././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5726602 slepc4py-3.24.2/0000755000076500000240000000000015133664271012566 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908575.0 slepc4py-3.24.2/CHANGES.rst0000644000076500000240000000446715133663437014406 0ustar00jromanstaffRelease 3.24 ------------ - Update to SLEPc 3.24. - Support (opt-in via setting the environment variable ``SLEPC4PY_BUILD_PYSABI=1``) for building with ``Py_LIMITED_API`` (Python Stable ABI) under Python 3.10+ (requires Cython 3.1+). - Add support for standard Python operators for `BV` and `FN` classes. - Add new `LME` class. Release 3.23 ------------ - Update to SLEPc 3.23. Release 3.22 ------------ - Update to SLEPc 3.22. - In slepc4py now `EPS.getEigenpair()` and `EPS.getEigenvalue()` will return a real value instead of a complex, if the problem is of Hermitian or generalized Hermitian type. Release 3.21 ------------ - Update to SLEPc 3.21. Release 3.20 ------------ - Update to SLEPc 3.20. Release 3.19 ------------ - Update to SLEPc 3.19. Release 3.18 ------------ - Update to SLEPc 3.18. Release 3.17 ------------ - Update to SLEPc 3.17. Release 3.16 ------------ - Update to SLEPc 3.16. Release 3.15 ------------ - Update to SLEPc 3.15. - Updates in installation scripts. Release 3.14 ------------ - Update to SLEPc 3.14. Release 3.13 ------------ - Update to SLEPc 3.13. Release 3.12 ------------ - Update to SLEPc 3.12. Release 3.11 ------------ - Update to SLEPc 3.11. Release 3.10 ------------ - Update to SLEPc 3.10. Release 3.9 ----------- - Update to SLEPc 3.9. Release 3.8 ----------- - Update to SLEPc 3.8. Release 3.7 ----------- - Update to SLEPc 3.7. Release 3.6 ----------- - Update to SLEPc 3.6. Release 3.5 ----------- - Update to SLEPc 3.5. - Add RG class introduced in SLEPc 3.5 release. - Add PySlepcXXX_New/Get C API functions. - Fix compilation problem with complex scalars on OS X. - Fix outdated SWIG interface file. Release 3.4 ----------- - Update to SLEPc 3.4. Release 3.3 ----------- - Update to SLEPc 3.3. - Regenerate the wrappers using Cython 0.18 and fix binary compatibility issues with petsc4py 3.3.1. Release 1.2 ----------- - Update to SLEPc 3.2. Release 1.1 ----------- - Support for new QEP quadratic eigenproblem solver in SLEPc. - Support for ``pip install slepc4py`` to download and install SLEPc. - Support for PETSc/SLEPc static library builds (Linux-only). - Preliminary support for Python 3. Release 1.0.0 ------------- - This is the fist release of the all-new, Cython-based, implementation of *SLEPc for Python*. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/DESCRIPTION.rst0000644000076500000240000000177315133663436015115 0ustar00jromanstaffSLEPc for Python ================ Python bindings for SLEPc_. .. _SLEPc: https://slepc.upv.es Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py slepc slepc4py Citations --------- If SLEPc for Python has been significant to a project that leads to an academic publication, please acknowledge that fact by citing the project. * L. Dalcin, P. Kler, R. Paz, and A. Cosimo, *Parallel Distributed Computing using Python*, Advances in Water Resources, 34(9):1124-1139, 2011. https://doi.org/10.1016/j.advwatres.2011.04.013 * V. Hernandez, J.E. Roman and V. Vidal. *SLEPc: A Scalable and Flexible Toolkit for the Solution of Eigenvalue Problems*, ACM Transactions on Mathematical Software, 31(3):351-362, 2005. https://doi.org/10.1145/1089014.1089019 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/LICENSE.rst0000644000076500000240000000265015133663436014407 0ustar00jromanstaff========================= LICENSE: SLEPc for Python ========================= :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Copyright (c) 2025, Lisandro Dalcin and Jose Roman. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/MANIFEST.in0000644000076500000240000000107015133663436014324 0ustar00jromanstaffinclude setup*.py *.toml *.cfg *.rst recursive-include demo [M,m]akefile* *.py recursive-include conf *.py *.sh *.cfg recursive-include src *.py *.pyx *.px[di] *.h *.c *.i *.cfg recursive-include test *.py recursive-include * [M,m]akefile exclude src/slepc4py/SLEPc.c exclude src/slepc4py/SLEPc.h exclude src/slepc4py/SLEPc_api.h include docs/*.html include docs/*.pdf include docs/*.info include docs/*.[137] include docs/*.rst include docs/*.bib graft docs/usrman graft docs/apiref graft docs/source prune docs/source/_build exclude docs/source/*.inv ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1768908984.572515 slepc4py-3.24.2/PKG-INFO0000644000076500000240000000476515133664271013677 0ustar00jromanstaffMetadata-Version: 2.4 Name: slepc4py Version: 3.24.2 Summary: SLEPc for Python Home-page: https://gitlab.com/slepc/slepc Download-URL: https://pypi.io/packages/source/s/slepc4py/slepc4py-3.24.2.tar.gz Author: Lisandro Dalcin Author-email: dalcinl@gmail.com Maintainer: SLEPc Team Maintainer-email: slepc-maint@upv.es License: BSD-2-Clause Keywords: scientific computing,parallel computing,MPI,SLEPc,PETSc Platform: POSIX Platform: Linux Platform: macOS Platform: FreeBSD Classifier: Operating System :: POSIX Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: Programming Language :: C Classifier: Programming Language :: C++ Classifier: Programming Language :: Cython Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Scientific/Engineering Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Development Status :: 5 - Production/Stable Requires: numpy Description-Content-Type: text/x-rst License-File: LICENSE.rst Requires-Dist: numpy Requires-Dist: petsc4py<3.25,>=3.24 Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: description-content-type Dynamic: download-url Dynamic: home-page Dynamic: keywords Dynamic: license Dynamic: license-file Dynamic: maintainer Dynamic: maintainer-email Dynamic: platform Dynamic: requires Dynamic: requires-dist Dynamic: summary SLEPc for Python ================ Python bindings for SLEPc_. .. _SLEPc: https://slepc.upv.es Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py slepc slepc4py Citations --------- If SLEPc for Python has been significant to a project that leads to an academic publication, please acknowledge that fact by citing the project. * L. Dalcin, P. Kler, R. Paz, and A. Cosimo, *Parallel Distributed Computing using Python*, Advances in Water Resources, 34(9):1124-1139, 2011. https://doi.org/10.1016/j.advwatres.2011.04.013 * V. Hernandez, J.E. Roman and V. Vidal. *SLEPc: A Scalable and Flexible Toolkit for the Solution of Eigenvalue Problems*, ACM Transactions on Mathematical Software, 31(3):351-362, 2005. https://doi.org/10.1145/1089014.1089019 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/README.rst0000644000076500000240000000146515133663436014265 0ustar00jromanstaff================ SLEPc for Python ================ Overview -------- Welcome to SLEPc for Python. This package provides Python bindings for SLEPc_, the *Scalable Library for Eigenvalue Problem Computations*. Dependencies ------------ * Python_ 3.6 or above. * A recent NumPy_ release. * A matching version of SLEPc_ built with *shared/dynamic libraries*. * A matching version of PETSc_ built with *shared/dynamic libraries*. * A matching version of petsc4py_. * To work with the in-development version, you need Cython_. .. _Python: https://www.python.org .. _NumPy: https://www.numpy.org .. _SLEPc: https://slepc.upv.es .. _PETSc: https://petsc.org .. _petsc4py: https://gitlab.com/petsc/petsc .. _Cython: https://cython.org Documentation ------------- * https://slepc.upv.es/release/slepc4py ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4735994 slepc4py-3.24.2/conf/0000755000076500000240000000000015133664270013512 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/__init__.py0000644000076500000240000000000015133663436015614 0ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/confpetsc.py0000644000076500000240000010230215133663436016051 0ustar00jromanstaff# -------------------------------------------------------------------- import re import os import sys import glob import copy import warnings from distutils import log from distutils import sysconfig from distutils.util import execute from distutils.util import split_quoted from distutils.errors import DistutilsError from distutils.text_file import TextFile try: from cStringIO import StringIO except ImportError: from io import StringIO try: import setuptools except ImportError: setuptools = None if setuptools: from setuptools import setup as _setup from setuptools import Extension as _Extension from setuptools import Command else: from distutils.core import setup as _setup from distutils.core import Extension as _Extension from distutils.core import Command def import_command(cmd): try: from importlib import import_module except ImportError: def import_module(n): return __import__(n, fromlist=[None]) try: if not setuptools: raise ImportError mod = import_module('setuptools.command.' + cmd) return getattr(mod, cmd) except ImportError: mod = import_module('distutils.command.' + cmd) return getattr(mod, cmd) _config = import_command('config') _build = import_command('build') _build_ext = import_command('build_ext') _install = import_command('install') try: from setuptools import modified except ImportError: try: from setuptools import dep_util as modified except ImportError: from distutils import dep_util as modified try: from packaging.version import Version except ImportError: try: from setuptools.extern.packaging.version import Version except ImportError: from distutils.version import StrictVersion as Version # -------------------------------------------------------------------- # Cython CYTHON = '3.0.0' def cython_req(): return CYTHON def cython_chk(VERSION, verbose=True): # def warn(message): if not verbose: return ruler, ws, nl = '*' * 80, ' ', '\n' pyexe = sys.executable advise = '$ %s -m pip install --upgrade cython' % pyexe def printer(*s): sys.stderr.write(' '.join(s) + '\n') printer(ruler, nl) printer(ws, message, nl) printer(ws, ws, advise, nl) printer(ruler) # try: import Cython except ImportError: warn('You need Cython to generate C source files.') return False # CYTHON_VERSION = Cython.__version__ m = re.match(r'(\d+\.\d+(?:\.\d+)?).*', CYTHON_VERSION) if not m: warn(f'Cannot parse Cython version string {CYTHON_VERSION!r}') return False REQUIRED = Version(VERSION) PROVIDED = Version(m.groups()[0]) if PROVIDED < REQUIRED: warn(f'You need Cython >= {VERSION} (you have version {CYTHON_VERSION})') return False # if verbose: log.info('using Cython %s' % CYTHON_VERSION) return True def cython_run( source, target=None, depends=(), includes=(), workdir=None, force=False, VERSION='0.0', ): if target is None: target = os.path.splitext(source)[0] + '.c' cwd = os.getcwd() try: if workdir: os.chdir(workdir) alldeps = [source] for dep in depends: alldeps += glob.glob(dep) if not (force or modified.newer_group(alldeps, target)): log.debug("skipping '%s' -> '%s' (up-to-date)", source, target) return finally: os.chdir(cwd) require = 'Cython >= %s' % VERSION if setuptools and not cython_chk(VERSION, verbose=False): if sys.modules.get('Cython'): removed = getattr(sys.modules['Cython'], '__version__', '') log.info('removing Cython %s from sys.modules' % removed) pkgname = re.compile(r'cython(\.|$)', re.IGNORECASE) for modname in list(sys.modules.keys()): if pkgname.match(modname): del sys.modules[modname] try: install_setup_requires = setuptools._install_setup_requires with warnings.catch_warnings(): if hasattr(setuptools, 'SetuptoolsDeprecationWarning'): category = setuptools.SetuptoolsDeprecationWarning warnings.simplefilter('ignore', category) log.info("fetching build requirement '%s'" % require) install_setup_requires({'setup_requires': [require]}) except Exception: log.info("failed to fetch build requirement '%s'" % require) if not cython_chk(VERSION): raise DistutilsError("unsatisfied build requirement '%s'" % require) # log.info("cythonizing '%s' -> '%s'", source, target) from cythonize import cythonize args = [] if workdir: args += ['--working', workdir] args += [source] if target: args += ['--output-file', target] err = cythonize(args) if err: raise DistutilsError(f"Cython failure: '{source}' -> '{target}'") # -------------------------------------------------------------------- def fix_config_vars(names, values): values = list(values) if 'CONDA_BUILD' in os.environ: return values if sys.platform == 'darwin': if 'ARCHFLAGS' in os.environ: ARCHFLAGS = os.environ['ARCHFLAGS'] for i, flag in enumerate(list(values)): flag, count = re.subn(r'-arch\s+\w+', ' ', str(flag)) if count and ARCHFLAGS: flag = flag + ' ' + ARCHFLAGS values[i] = flag if 'SDKROOT' in os.environ: SDKROOT = os.environ['SDKROOT'] for i, flag in enumerate(list(values)): flag, count = re.subn(r'-isysroot [^ \t]*', ' ', str(flag)) if count and SDKROOT: flag = flag + ' ' + '-isysroot ' + SDKROOT values[i] = flag return values def get_config_vars(*names): # Core Python configuration values = sysconfig.get_config_vars(*names) # Do any distutils flags fixup right now return fix_config_vars(names, values) # -------------------------------------------------------------------- class PetscConfig: def __init__(self, petsc_dir, petsc_arch, dest_dir=None): if dest_dir is None: dest_dir = os.environ.get('DESTDIR') self.configdict = {} if not petsc_dir: raise DistutilsError('PETSc not found') if not os.path.isdir(petsc_dir): raise DistutilsError('invalid PETSC_DIR: %s' % petsc_dir) self.version = self._get_petsc_version(petsc_dir) self.configdict = self._get_petsc_config(petsc_dir, petsc_arch) self.PETSC_DIR = self['PETSC_DIR'] self.PETSC_ARCH = self['PETSC_ARCH'] self.DESTDIR = dest_dir language_map = {'CONLY': 'c', 'CXXONLY': 'c++'} self.language = language_map[self['PETSC_LANGUAGE']] def __getitem__(self, item): return self.configdict[item] def get(self, item, default=None): return self.configdict.get(item, default) def configure(self, extension, compiler=None): self.configure_extension(extension) if compiler is not None: self.configure_compiler(compiler) def _get_petsc_version(self, petsc_dir): import re version_re = { 'major': re.compile(r'#define\s+PETSC_VERSION_MAJOR\s+(\d+)'), 'minor': re.compile(r'#define\s+PETSC_VERSION_MINOR\s+(\d+)'), 'micro': re.compile(r'#define\s+PETSC_VERSION_SUBMINOR\s+(\d+)'), 'release': re.compile(r'#define\s+PETSC_VERSION_RELEASE\s+(-*\d+)'), } petscversion_h = os.path.join(petsc_dir, 'include', 'petscversion.h') with open(petscversion_h, 'rt') as f: data = f.read() major = int(version_re['major'].search(data).groups()[0]) minor = int(version_re['minor'].search(data).groups()[0]) micro = int(version_re['micro'].search(data).groups()[0]) release = int(version_re['release'].search(data).groups()[0]) return (major, minor, micro), (release == 1) def _get_petsc_config(self, petsc_dir, petsc_arch): from os.path import join, isdir, exists PETSC_DIR = petsc_dir PETSC_ARCH = petsc_arch # confdir = join('lib', 'petsc', 'conf') if not (PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH))): petscvars = join(PETSC_DIR, confdir, 'petscvariables') PETSC_ARCH = makefile(open(petscvars, 'rt')).get('PETSC_ARCH') if not (PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH))): PETSC_ARCH = '' # variables = join(PETSC_DIR, confdir, 'variables') if not exists(variables): variables = join(PETSC_DIR, PETSC_ARCH, confdir, 'variables') petscvariables = join(PETSC_DIR, PETSC_ARCH, confdir, 'petscvariables') # with open(variables) as f: contents = f.read() with open(petscvariables) as f: contents += f.read() # confstr = 'PETSC_DIR = %s\n' % PETSC_DIR confstr += 'PETSC_ARCH = %s\n' % PETSC_ARCH confstr += contents return makefile(StringIO(confstr)) def _configure_ext(self, ext, dct, append=False): extdict = ext.__dict__ for key, values in dct.items(): if key in extdict: for value in values: if value not in extdict[key]: if not append: extdict[key].insert(0, value) else: extdict[key].append(value) def configure_extension(self, extension): # includes and libraries # paths in PETSc config files point to final installation location, but # we might be building against PETSc in staging location (DESTDIR) when # DESTDIR is set, so append DESTDIR (if nonempty) to those paths petsc_inc = flaglist(prepend_to_flags(self.DESTDIR, self['PETSC_CC_INCLUDES'])) lib_flags = prepend_to_flags( self.DESTDIR, '-L{} {}'.format(self['PETSC_LIB_DIR'], self['PETSC_LIB_BASIC']), ) petsc_lib = flaglist(lib_flags) # runtime_library_dirs is not supported on Windows if sys.platform != 'win32': # if DESTDIR is set, then we're building against PETSc in a staging # directory, but rpath needs to point to final install directory. rpath = [strip_prefix(self.DESTDIR, self['PETSC_LIB_DIR'])] if sys.modules.get('petsc') is not None: if sys.platform == 'darwin': rpath = ['@loader_path/../../petsc/lib'] else: rpath = ['$ORIGIN/../../petsc/lib'] petsc_lib['runtime_library_dirs'].extend(rpath) # Link in extra libraries on static builds if self['BUILDSHAREDLIB'] != 'yes': petsc_ext_lib = split_quoted(self['PETSC_EXTERNAL_LIB_BASIC']) petsc_lib['extra_link_args'].extend(petsc_ext_lib) self._configure_ext(extension, petsc_inc, append=True) self._configure_ext(extension, petsc_lib) def configure_compiler(self, compiler): if compiler.compiler_type != 'unix': return getenv = os.environ.get # distutils C/C++ compiler (cc, cflags, ccshared, cxx) = get_config_vars('CC', 'CFLAGS', 'CCSHARED', 'CXX') ccshared = getenv('CCSHARED', ccshared or '') cflags = getenv('CFLAGS', cflags or '') cflags = cflags.replace('-Wstrict-prototypes', '') # distutils linker (ldflags, ldshared, so_ext) = get_config_vars('LDFLAGS', 'LDSHARED', 'SO') ld = cc ldshared = getenv('LDSHARED', ldshared) ldflags = getenv('LDFLAGS', cflags + ' ' + (ldflags or '')) ldcmd = split_quoted(ld) + split_quoted(ldflags) ldshared = [ flg for flg in split_quoted(ldshared) if flg not in ldcmd and (flg.find('/lib/spack/env') < 0) and (flg.find('/libexec/spack/') < 0) ] ldshared = str.join(' ', ldshared) # def get_flags(cmd): if not cmd: return '' cmd = split_quoted(cmd) if os.path.basename(cmd[0]) == 'xcrun': del cmd[0] while True: if cmd[0] == '-sdk': del cmd[0:2] continue if cmd[0] == '-log': del cmd[0] continue break return ' '.join(cmd[1:]) # PETSc C compiler PCC = self['PCC'] PCC_FLAGS = get_flags(cc) + ' ' + self['PCC_FLAGS'] PCC_FLAGS = PCC_FLAGS.replace('-fvisibility=hidden', '') PCC_FLAGS = PCC_FLAGS.replace('-Wpedantic', '-Wno-pedantic') PCC_FLAGS = PCC_FLAGS.replace('-Wextra-semi-stmt', '-Wno-extra-semi-stmt') PCC = getenv('PCC', PCC) + ' ' + getenv('PCCFLAGS', PCC_FLAGS) PCC_SHARED = str.join(' ', (PCC, ccshared, cflags)) # PETSc C++ compiler PCXX = PCC if self.language == 'c++' else self.get('CXX', cxx) # PETSc linker PLD = self['PCC_LINKER'] PLD_FLAGS = get_flags(ld) + ' ' + self['PCC_LINKER_FLAGS'] PLD_FLAGS = PLD_FLAGS.replace('-fvisibility=hidden', '') PLD = getenv('PLD', PLD) + ' ' + getenv('PLDFLAGS', PLD_FLAGS) PLD_SHARED = str.join(' ', (PLD, ldshared, ldflags)) # compiler.set_executables( compiler=PCC, compiler_cxx=PCXX, linker_exe=PLD, compiler_so=PCC_SHARED, linker_so=PLD_SHARED, ) compiler.shared_lib_extension = so_ext def log_info(self): PETSC_DIR = self['PETSC_DIR'] PETSC_ARCH = self['PETSC_ARCH'] version = '.'.join([str(i) for i in self.version[0]]) release = ('development', 'release')[self.version[1]] version_info = version + ' ' + release integer_size = '%s-bit' % self['PETSC_INDEX_SIZE'] scalar_type = self['PETSC_SCALAR'] precision = self['PETSC_PRECISION'] language = self['PETSC_LANGUAGE'] compiler = self['PCC'] linker = self['PCC_LINKER'] log.info('PETSC_DIR: %s' % PETSC_DIR) log.info('PETSC_ARCH: %s' % PETSC_ARCH) log.info('version: %s' % version_info) log.info('integer-size: %s' % integer_size) log.info('scalar-type: %s' % scalar_type) log.info('precision: %s' % precision) log.info('language: %s' % language) log.info('compiler: %s' % compiler) log.info('linker: %s' % linker) # -------------------------------------------------------------------- class Extension(_Extension): pass # -------------------------------------------------------------------- cmd_petsc_opts = [ ('petsc-dir=', None, 'define PETSC_DIR, overriding environmental variables'), ('petsc-arch=', None, 'define PETSC_ARCH, overriding environmental variables'), ] class config(_config): Configure = PetscConfig user_options = _config.user_options + cmd_petsc_opts def initialize_options(self): _config.initialize_options(self) self.petsc_dir = None self.petsc_arch = None def get_config_arch(self, arch): return config.Configure(self.petsc_dir, arch) def run(self): _config.run(self) self.petsc_dir = config.get_petsc_dir(self.petsc_dir) if self.petsc_dir is None: return petsc_arch = config.get_petsc_arch(self.petsc_dir, self.petsc_arch) log.info('-' * 70) log.info('PETSC_DIR: %s' % self.petsc_dir) arch_list = petsc_arch if not arch_list: arch_list = [None] for arch in arch_list: conf = self.get_config_arch(arch) archname = conf.PETSC_ARCH or conf['PETSC_ARCH'] scalar_type = conf['PETSC_SCALAR'] precision = conf['PETSC_PRECISION'] language = conf['PETSC_LANGUAGE'] compiler = conf['PCC'] linker = conf['PCC_LINKER'] log.info('-' * 70) log.info('PETSC_ARCH: %s' % archname) log.info(' * scalar-type: %s' % scalar_type) log.info(' * precision: %s' % precision) log.info(' * language: %s' % language) log.info(' * compiler: %s' % compiler) log.info(' * linker: %s' % linker) log.info('-' * 70) # @staticmethod def get_petsc_dir(petsc_dir): if not petsc_dir: return None petsc_dir = os.path.expandvars(petsc_dir) if not petsc_dir or '$PETSC_DIR' in petsc_dir: try: import petsc petsc_dir = petsc.get_petsc_dir() except ImportError: log.warn('PETSC_DIR not specified') return None petsc_dir = os.path.expanduser(petsc_dir) petsc_dir = os.path.abspath(petsc_dir) return config.chk_petsc_dir(petsc_dir) get_petsc_dir = staticmethod(get_petsc_dir) # @staticmethod def chk_petsc_dir(petsc_dir): if not os.path.isdir(petsc_dir): log.error('invalid PETSC_DIR: %s (ignored)' % petsc_dir) return None return petsc_dir chk_petsc_dir = staticmethod(chk_petsc_dir) # @staticmethod def get_petsc_arch(petsc_dir, petsc_arch): if not petsc_dir: return None petsc_arch = os.path.expandvars(petsc_arch) if not petsc_arch or '$PETSC_ARCH' in petsc_arch: petsc_arch = '' petsc_conf = os.path.join(petsc_dir, 'lib', 'petsc', 'conf') if os.path.isdir(petsc_conf): petscvariables = os.path.join(petsc_conf, 'petscvariables') if os.path.exists(petscvariables): conf = makefile(open(petscvariables, 'rt')) petsc_arch = conf.get('PETSC_ARCH', '') petsc_arch = petsc_arch.split(os.pathsep) petsc_arch = unique(petsc_arch) petsc_arch = [arch for arch in petsc_arch if arch] return config.chk_petsc_arch(petsc_dir, petsc_arch) get_petsc_arch = staticmethod(get_petsc_arch) # @staticmethod def chk_petsc_arch(petsc_dir, petsc_arch): valid_archs = [] for arch in petsc_arch: arch_path = os.path.join(petsc_dir, arch) if os.path.isdir(arch_path): valid_archs.append(arch) else: log.warn('invalid PETSC_ARCH: %s (ignored)' % arch) return valid_archs chk_petsc_arch = staticmethod(chk_petsc_arch) class build(_build): user_options = _build.user_options user_options += [ ( 'inplace', 'i', 'ignore build-lib and put compiled extensions into the source ' 'directory alongside your pure Python modules', ) ] user_options += cmd_petsc_opts boolean_options = _build.boolean_options boolean_options += ['inplace'] def initialize_options(self): _build.initialize_options(self) self.inplace = None self.petsc_dir = None self.petsc_arch = None def finalize_options(self): _build.finalize_options(self) if self.inplace is None: self.inplace = False self.set_undefined_options( 'config', ('petsc_dir', 'petsc_dir'), ('petsc_arch', 'petsc_arch') ) self.petsc_dir = config.get_petsc_dir(self.petsc_dir) self.petsc_arch = config.get_petsc_arch(self.petsc_dir, self.petsc_arch) sub_commands = [('build_src', lambda *args: True)] + _build.sub_commands class build_src(Command): description = 'build C sources from Cython files' user_options = [ ('force', 'f', 'forcibly build everything (ignore file timestamps)'), ] boolean_options = ['force'] def initialize_options(self): self.force = False def finalize_options(self): self.set_undefined_options( 'build', ('force', 'force'), ) def run(self): sources = getattr(self, 'sources', []) for source in sources: cython_run(force=self.force, VERSION=cython_req(), **source) class build_ext(_build_ext): user_options = _build_ext.user_options + cmd_petsc_opts def initialize_options(self): _build_ext.initialize_options(self) self.inplace = None self.petsc_dir = None self.petsc_arch = None self._outputs = [] def finalize_options(self): _build_ext.finalize_options(self) self.set_undefined_options('build', ('inplace', 'inplace')) self.set_undefined_options( 'build', ('petsc_dir', 'petsc_dir'), ('petsc_arch', 'petsc_arch') ) def _copy_ext(self, ext): extclass = ext.__class__ fullname = self.get_ext_fullname(ext.name) modpath = str.split(fullname, '.') pkgpath = os.path.join('', *modpath[0:-1]) name = modpath[-1] sources = list(ext.sources) newext = extclass(name, sources) newext.__dict__.update(copy.deepcopy(ext.__dict__)) newext.name = name return pkgpath, newext def _build_ext_arch(self, ext, pkgpath, arch): build_temp = self.build_temp build_lib = self.build_lib try: self.build_temp = os.path.join(build_temp, arch) self.build_lib = os.path.join(build_lib, pkgpath, arch) _build_ext.build_extension(self, ext) finally: self.build_temp = build_temp self.build_lib = build_lib def get_config_arch(self, arch): return config.Configure(self.petsc_dir, arch) def build_extension(self, ext): if not isinstance(ext, Extension): return _build_ext.build_extension(self, ext) petsc_arch = self.petsc_arch if not petsc_arch: petsc_arch = [None] for arch in petsc_arch: config = self.get_config_arch(arch) ARCH = arch or config['PETSC_ARCH'] if ARCH not in self.PETSC_ARCH_LIST: self.PETSC_ARCH_LIST.append(ARCH) self.DESTDIR = config.DESTDIR ext.language = config.language config.log_info() pkgpath, newext = self._copy_ext(ext) config.configure(newext, self.compiler) self._build_ext_arch(newext, pkgpath, ARCH) return None def run(self): self.build_sources() _build_ext.run(self) def build_sources(self): if 'build_src' in self.distribution.cmdclass: self.run_command('build_src') def build_extensions(self, *args, **kargs): self.PETSC_ARCH_LIST = [] _build_ext.build_extensions(self, *args, **kargs) if not self.PETSC_ARCH_LIST: return self.build_configuration(self.PETSC_ARCH_LIST) def build_configuration(self, arch_list): # template, variables = self.get_config_data(arch_list) config_data = template % variables # build_lib = self.build_lib dist_name = self.distribution.get_name() config_file = os.path.join( build_lib, dist_name, 'lib', dist_name.replace('4py', '') + '.cfg' ) # def write_file(filename, data): with open(filename, 'w') as fh: fh.write(config_data) execute( write_file, (config_file, config_data), msg='writing %s' % config_file, verbose=self.verbose, dry_run=self.dry_run, ) def get_config_data(self, arch_list): DESTDIR = self.DESTDIR template = ( '\n'.join( [ 'PETSC_DIR = %(PETSC_DIR)s', 'PETSC_ARCH = %(PETSC_ARCH)s', ] ) + '\n' ) variables = { 'PETSC_DIR': strip_prefix(DESTDIR, self.petsc_dir), 'PETSC_ARCH': os.path.pathsep.join(arch_list), } return template, variables def copy_extensions_to_source(self): build_py = self.get_finalized_command('build_py') for ext in self.extensions: inp_file, reg_file = self._get_inplace_equivalent(build_py, ext) arch_list = [''] if isinstance(ext, Extension) and self.petsc_arch: arch_list = self.petsc_arch[:] file_pairs = [] inp_head, inp_tail = os.path.split(inp_file) reg_head, reg_tail = os.path.split(reg_file) for arch in arch_list: inp_file = os.path.join(inp_head, arch, inp_tail) reg_file = os.path.join(reg_head, arch, reg_tail) file_pairs.append((inp_file, reg_file)) for inp_file, reg_file in file_pairs: if os.path.exists(reg_file) or not ext.optional: dest_dir, _ = os.path.split(inp_file) self.mkpath(dest_dir) self.copy_file(reg_file, inp_file, level=self.verbose) def get_outputs(self): self.check_extensions_list(self.extensions) outputs = [] for ext in self.extensions: fullname = self.get_ext_fullname(ext.name) filename = self.get_ext_filename(fullname) if isinstance(ext, Extension) and self.petsc_arch: head, tail = os.path.split(filename) for arch in self.petsc_arch: outfile = os.path.join(self.build_lib, head, arch, tail) outputs.append(outfile) else: outfile = os.path.join(self.build_lib, filename) outputs.append(outfile) return list(set(outputs)) def get_source_files(self): orig = log.set_threshold(log.WARN) try: return super().get_source_files() finally: log.set_threshold(orig) class install(_install): def initialize_options(self): with warnings.catch_warnings(): if setuptools: if hasattr(setuptools, 'SetuptoolsDeprecationWarning'): category = setuptools.SetuptoolsDeprecationWarning warnings.simplefilter('ignore', category) _install.initialize_options(self) self.old_and_unmanageable = True cmdclass_list = [ config, build, build_src, build_ext, install, ] # -------------------------------------------------------------------- def setup(**attrs): cmdclass = attrs.setdefault('cmdclass', {}) for cmd in cmdclass_list: cmdclass.setdefault(cmd.__name__, cmd) build_src.sources = attrs.pop('cython_sources', None) use_setup_requires = False # handle Cython requirement ourselves if setuptools and build_src.sources and use_setup_requires: version = cython_req() if not cython_chk(version, verbose=False): reqs = attrs.setdefault('setup_requires', []) reqs += ['Cython>=' + version] return _setup(**attrs) # -------------------------------------------------------------------- if setuptools: try: from setuptools.command import egg_info as mod_egg_info _FileList = mod_egg_info.FileList class FileList(_FileList): def process_template_line(self, line): level = log.set_threshold(log.ERROR) try: _FileList.process_template_line(self, line) finally: log.set_threshold(level) mod_egg_info.FileList = FileList except (ImportError, AttributeError): pass # -------------------------------------------------------------------- def append(seq, item): if item not in seq: seq.append(item) def append_dict(conf, dct): for key, values in dct.items(): if key in conf: for value in values: if value not in conf[key]: conf[key].append(value) def unique(seq): res = [] for item in seq: if item not in res: res.append(item) return res def flaglist(flags): conf = { 'define_macros': [], 'undef_macros': [], 'include_dirs': [], 'libraries': [], 'library_dirs': [], 'runtime_library_dirs': [], 'extra_compile_args': [], 'extra_link_args': [], } if isinstance(flags, str): flags = flags.split() switch = '-Wl,' newflags = [] linkopts = [] for f in flags: if f.startswith(switch): if len(f) > 4: append(linkopts, f[4:]) else: append(newflags, f) if linkopts: newflags.append(switch + ','.join(linkopts)) flags = newflags append_next_word = None for word in flags: if append_next_word is not None: append(append_next_word, word) append_next_word = None continue switch, value = word[0:2], word[2:] if switch == '-I': append(conf['include_dirs'], value) elif switch == '-D': try: idx = value.index('=') macro = (value[:idx], value[idx + 1 :]) except ValueError: macro = (value, None) append(conf['define_macros'], macro) elif switch == '-U': append(conf['undef_macros'], value) elif switch == '-l': append(conf['libraries'], value) elif switch == '-L': append(conf['library_dirs'], value) elif switch == '-R': append(conf['runtime_library_dirs'], value) elif word.startswith('-Wl'): linkopts = word.split(',') append_dict(conf, flaglist(linkopts[1:])) elif word == '-rpath': append_next_word = conf['runtime_library_dirs'] elif word == '-Xlinker': append_next_word = conf['extra_link_args'] else: # log.warn("unrecognized flag '%s'" % word) pass return conf def prepend_to_flags(path, flags): """Prepend a path to compiler flags with absolute paths""" if not path: return flags def append_path(m): switch = m.group(1) open_quote = m.group(4) old_path = m.group(5) close_quote = m.group(6) if os.path.isabs(old_path): moded_path = os.path.normpath(path + os.path.sep + old_path) return switch + open_quote + moded_path + close_quote return m.group(0) return re.sub(r'((^|\s+)(-I|-L))(\s*["\']?)(\S+)(["\']?)', append_path, flags) def strip_prefix(prefix, string): if not prefix: return string return re.sub(r'^' + prefix, '', string) # -------------------------------------------------------------------- # Regexes needed for parsing Makefile-like syntaxes _variable_rx = re.compile(r'([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)') _findvar1_rx = re.compile(r'\$\(([A-Za-z][A-Za-z0-9_]*)\)') _findvar2_rx = re.compile(r'\${([A-Za-z][A-Za-z0-9_]*)}') def makefile(fileobj, dct=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ fp = TextFile(file=fileobj, strip_comments=1, skip_blanks=1, join_lines=1) if dct is None: dct = {} done = {} notdone = {} while 1: line = fp.readline() if line is None: # eof break m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = str.strip(v) if '$' in v: notdone[n] = v else: try: v = int(v) except ValueError: pass done[n] = v try: del notdone[n] except KeyError: pass fp.close() # do variable interpolation here while notdone: for name in list(notdone.keys()): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False else: done[n] = item = '' if found: after = value[m.end() :] value = value[: m.start()] + item + after if '$' in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = str.strip(value) else: done[name] = value del notdone[name] else: # bogus variable reference; # just drop it since we can't deal del notdone[name] # save the results in the global dictionary dct.update(done) return dct # -------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/confslepc.py0000644000076500000240000002241515133663436016047 0ustar00jromanstaffimport os import sys from confpetsc import setup as _setup from confpetsc import Extension from confpetsc import config as _config from confpetsc import build as _build from confpetsc import build_src as _build_src from confpetsc import build_ext as _build_ext from confpetsc import install as _install from confpetsc import log from confpetsc import makefile from confpetsc import strip_prefix from confpetsc import split_quoted from confpetsc import DistutilsError from confpetsc import PetscConfig # -------------------------------------------------------------------- class SlepcConfig(PetscConfig): def __init__(self, slepc_dir, petsc_dir, petsc_arch, dest_dir=None): PetscConfig.__init__(self, petsc_dir, petsc_arch, dest_dir='') if dest_dir is None: dest_dir = os.environ.get('DESTDIR') if not slepc_dir: raise DistutilsError("SLEPc not found") if not os.path.isdir(slepc_dir): raise DistutilsError("invalid SLEPC_DIR") self.sversion = self._get_slepc_version(slepc_dir) self._get_slepc_config(petsc_dir,slepc_dir) self.SLEPC_DIR = self['SLEPC_DIR'] self.SLEPC_DESTDIR = dest_dir self.SLEPC_LIB = self['SLEPC_LIB'] self.SLEPC_EXTERNAL_LIB_DIR = self['SLEPC_EXTERNAL_LIB_DIR'] def _get_slepc_version(self, slepc_dir): import re version_re = { 'major' : re.compile(r"#define\s+SLEPC_VERSION_MAJOR\s+(\d+)"), 'minor' : re.compile(r"#define\s+SLEPC_VERSION_MINOR\s+(\d+)"), 'micro' : re.compile(r"#define\s+SLEPC_VERSION_SUBMINOR\s+(\d+)"), 'release': re.compile(r"#define\s+SLEPC_VERSION_RELEASE\s+(-*\d+)"), } slepcversion_h = os.path.join(slepc_dir, 'include', 'slepcversion.h') with open(slepcversion_h, 'rt') as f: data = f.read() major = int(version_re['major'].search(data).groups()[0]) minor = int(version_re['minor'].search(data).groups()[0]) micro = int(version_re['micro'].search(data).groups()[0]) release = int(version_re['release'].search(data).groups()[0]) return (major, minor, micro), (release == 1) def _get_slepc_config(self, petsc_dir, slepc_dir): from os.path import join, isdir PETSC_DIR = petsc_dir SLEPC_DIR = slepc_dir PETSC_ARCH = self.PETSC_ARCH confdir = join('lib', 'slepc', 'conf') if not (PETSC_ARCH and isdir(join(SLEPC_DIR, PETSC_ARCH))): PETSC_ARCH = '' variables = join(SLEPC_DIR, confdir, 'slepc_variables') slepcvariables = join(SLEPC_DIR, PETSC_ARCH, confdir, 'slepcvariables') with open(variables) as f: contents = f.read() with open(slepcvariables) as f: contents += f.read() try: from cStringIO import StringIO except ImportError: from io import StringIO confstr = 'PETSC_DIR = %s\n' % PETSC_DIR confstr += 'PETSC_ARCH = %s\n' % PETSC_ARCH confstr = 'SLEPC_DIR = %s\n' % SLEPC_DIR confstr += contents slepc_confdict = makefile(StringIO(confstr)) self.configdict['SLEPC_DIR'] = SLEPC_DIR self.configdict['SLEPC_LIB'] = slepc_confdict['SLEPC_LIB'] dirlist = [] flags = split_quoted(slepc_confdict['SLEPC_EXTERNAL_LIB']) for entry in [lib[2:] for lib in flags if lib.startswith('-L')]: if entry not in dirlist: dirlist.append(entry) self.configdict['SLEPC_EXTERNAL_LIB_DIR'] = dirlist def configure_extension(self, extension): PetscConfig.configure_extension(self, extension) SLEPC_DIR = self.SLEPC_DIR PETSC_ARCH = self.PETSC_ARCH SLEPC_DESTDIR = self.SLEPC_DESTDIR # take into account the case of prefix PETSc with non-prefix SLEPc SLEPC_ARCH_DIR = PETSC_ARCH or os.environ.get('PETSC_ARCH', '') # includes and libraries SLEPC_INCLUDE = [ os.path.join(SLEPC_DIR, SLEPC_ARCH_DIR, 'include'), os.path.join(SLEPC_DIR, 'include'), ] SLEPC_LIB_DIR = [ os.path.join(SLEPC_DIR, SLEPC_ARCH_DIR, 'lib'), os.path.join(SLEPC_DIR, 'lib'), ] + self.SLEPC_EXTERNAL_LIB_DIR slepc_cfg = { } slepc_cfg['include_dirs'] = SLEPC_INCLUDE slepc_cfg['library_dirs'] = SLEPC_LIB_DIR slepc_cfg['libraries'] = [ lib[2:] for lib in split_quoted(self.SLEPC_LIB) if lib.startswith('-l') ] # runtime_library_dirs is not supported on Windows if sys.platform != 'win32': rpath = [strip_prefix(SLEPC_DESTDIR, d) for d in SLEPC_LIB_DIR] if sys.modules.get('slepc') is not None: if sys.platform == 'darwin': rpath = ['@loader_path/../../slepc/lib'] else: rpath = ['$ORIGIN/../../slepc/lib'] slepc_cfg['runtime_library_dirs'] = rpath self._configure_ext(extension, slepc_cfg) if self['BUILDSHAREDLIB'] == 'no': from petsc4py.lib import ImportPETSc PETSc = ImportPETSc(PETSC_ARCH) extension.extra_objects.append(PETSc.__file__) # extra configuration cflags = [] extension.extra_compile_args.extend(cflags) lflags = [] extension.extra_link_args.extend(lflags) def log_info(self): if not self.SLEPC_DIR: return version = ".".join([str(i) for i in self.sversion[0]]) release = ("development", "release")[self.sversion[1]] version_info = version + ' ' + release log.info('SLEPC_DIR: %s' % self.SLEPC_DIR) log.info('version: %s' % version_info) PetscConfig.log_info(self) # -------------------------------------------------------------------- cmd_slepc_opts = [ ('slepc-dir=', None, "define SLEPC_DIR, overriding environmental variable.") ] class config(_config): Configure = SlepcConfig user_options = _config.user_options + cmd_slepc_opts def initialize_options(self): _config.initialize_options(self) self.slepc_dir = None def get_config_arch(self, arch): return config.Configure(self.slepc_dir, self.petsc_dir, arch) def run(self): self.slepc_dir = config.get_slepc_dir(self.slepc_dir) if self.slepc_dir is None: return log.info('-' * 70) log.info('SLEPC_DIR: %s' % self.slepc_dir) _config.run(self) #@staticmethod def get_slepc_dir(slepc_dir): if not slepc_dir: return None slepc_dir = os.path.expandvars(slepc_dir) if not slepc_dir or '$SLEPC_DIR' in slepc_dir: try: import slepc slepc_dir = slepc.get_slepc_dir() except ImportError: log.warn("SLEPC_DIR not specified") return None slepc_dir = os.path.expanduser(slepc_dir) slepc_dir = os.path.abspath(slepc_dir) if not os.path.isdir(slepc_dir): log.warn('invalid SLEPC_DIR: %s' % slepc_dir) return None return slepc_dir get_slepc_dir = staticmethod(get_slepc_dir) class build(_build): user_options = _build.user_options + cmd_slepc_opts def initialize_options(self): _build.initialize_options(self) self.slepc_dir = None def finalize_options(self): _build.finalize_options(self) self.set_undefined_options('config', ('slepc_dir', 'slepc_dir'),) self.slepc_dir = config.get_slepc_dir(self.slepc_dir) class build_src(_build_src): pass class build_ext(_build_ext): user_options = _build_ext.user_options + cmd_slepc_opts def initialize_options(self): _build_ext.initialize_options(self) self.slepc_dir = None def finalize_options(self): _build_ext.finalize_options(self) self.set_undefined_options('build', ('slepc_dir', 'slepc_dir')) def get_config_arch(self, arch): return config.Configure(self.slepc_dir, self.petsc_dir, arch) def get_config_data(self, arch_list): DESTDIR = None for arch in arch_list: conf = self.get_config_arch(arch) DESTDIR = conf.SLEPC_DESTDIR # all archs will have same value template = "\n".join([ "SLEPC_DIR = %(SLEPC_DIR)s", "PETSC_DIR = %(PETSC_DIR)s", "PETSC_ARCH = %(PETSC_ARCH)s", ]) + "\n" variables = { 'SLEPC_DIR' : strip_prefix(DESTDIR, self.slepc_dir), 'PETSC_DIR' : self.petsc_dir, 'PETSC_ARCH' : os.path.pathsep.join(arch_list) } return template, variables def get_source_files(self): orig = log.set_threshold(log.WARN) try: return super().get_source_files() finally: log.set_threshold(orig) class install(_install): pass cmdclass_list = [ config, build, build_src, build_ext, install, ] # -------------------------------------------------------------------- def setup(**attrs): cmdclass = attrs.setdefault('cmdclass', {}) for cmd in cmdclass_list: cmdclass.setdefault(cmd.__name__, cmd) return _setup(**attrs) # -------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/cyautodoc.py0000644000076500000240000002467315133663436016075 0ustar00jromanstaff# ruff: noqa: UP008,UP031 from Cython.Compiler import Options from Cython.Compiler import PyrexTypes from Cython.Compiler.ExprNodes import TupleNode from Cython.Compiler.Visitor import CythonTransform from Cython.Compiler.StringEncoding import EncodedString from Cython.Compiler.AutoDocTransforms import ( ExpressionWriter as BaseExpressionWriter, AnnotationWriter as BaseAnnotationWriter, ) from Cython.Compiler.Errors import error class ExpressionWriter(BaseExpressionWriter): def visit_IndexNode(self, node): self.visit(node.base) self.put('[') if isinstance(node.index, TupleNode): if node.index.subexpr_nodes(): self.emit_sequence(node.index) else: self.put('()') else: self.visit(node.index) self.put(']') if hasattr(BaseExpressionWriter, 'emit_string'): def visit_UnicodeNode(self, node): self.emit_string(node, '') class AnnotationWriter(ExpressionWriter, BaseAnnotationWriter): pass class EmbedSignature(CythonTransform): def __init__(self, context): super(EmbedSignature, self).__init__(context) self.class_name = None self.class_node = None def _select_format(self, embed, clinic): return embed def _fmt_expr(self, node): writer = ExpressionWriter() return writer.write(node) def _fmt_annotation(self, node): writer = AnnotationWriter() return writer.write(node) def _fmt_arg(self, arg): annotation = None if arg.is_self_arg: doc = self._select_format(arg.name, '$self') elif arg.is_type_arg: doc = self._select_format(arg.name, '$type') else: doc = arg.name if arg.type is PyrexTypes.py_object_type: annotation = None else: annotation = arg.type.declaration_code('', for_display=1) if arg.default and arg.default.is_none: annotation += ' | None' if arg.annotation: annotation = self._fmt_annotation(arg.annotation) annotation = self._select_format(annotation, None) if annotation: doc = doc + (': %s' % annotation) if arg.default: default = self._fmt_expr(arg.default) doc = doc + (' = %s' % default) elif arg.default: default = self._fmt_expr(arg.default) doc = doc + ('=%s' % default) return doc def _fmt_star_arg(self, arg): arg_doc = arg.name if arg.annotation: annotation = self._fmt_annotation(arg.annotation) arg_doc = arg_doc + (': %s' % annotation) return arg_doc def _fmt_arglist( self, args, npoargs=0, npargs=0, pargs=None, nkargs=0, kargs=None, hide_self=False, ): arglist = [] for arg in args: if not hide_self or not arg.entry.is_self_arg: arg_doc = self._fmt_arg(arg) arglist.append(arg_doc) if pargs: arg_doc = self._fmt_star_arg(pargs) arglist.insert(npargs + npoargs, '*%s' % arg_doc) elif nkargs: arglist.insert(npargs + npoargs, '*') if npoargs: arglist.insert(npoargs, '/') if kargs: arg_doc = self._fmt_star_arg(kargs) arglist.append('**%s' % arg_doc) return arglist def _fmt_ret_type(self, ret): if ret is PyrexTypes.py_object_type: return None return ret.declaration_code('', for_display=1) def _fmt_signature( self, node, cls_name, func_name, args, npoargs=0, npargs=0, pargs=None, nkargs=0, kargs=None, return_expr=None, return_type=None, hide_self=False, ): arglist = self._fmt_arglist( args, npoargs, npargs, pargs, nkargs, kargs, hide_self=hide_self ) arglist_doc = ', '.join(arglist) func_doc = '%s(%s)' % (func_name, arglist_doc) if cls_name: namespace = self._select_format('%s.' % cls_name, '') func_doc = '%s%s' % (namespace, func_doc) ret_doc = None if return_expr: ret_doc = self._fmt_annotation(return_expr) elif return_type: ret_doc = self._fmt_ret_type(return_type) if ret_doc: docfmt = self._select_format('%s -> %s', '%s -> (%s)') func_doc = docfmt % (func_doc, ret_doc) else: if not func_doc.startswith('_') and not func_name.startswith('_'): error( node.pos, f'cyautodoc._fmt_signature: missing return type for {func_doc}', ) return func_doc def _fmt_relative_position(self, pos): return 'Source code at ' + ':'.join( (str(pos[0].get_filenametable_entry()), str(pos[1])) ) def _embed_signature(self, signature, pos, node_doc): pos = self._fmt_relative_position(pos) if node_doc: docfmt = self._select_format('%s\n%s\n%s', '%s\n--\n\n%s') return docfmt % (signature, node_doc, pos) docfmt = self._select_format('%s\n%s', '%s\n--\n\n%s') return docfmt % (signature, pos) def __call__(self, node): if not Options.docstrings: return node return super(EmbedSignature, self).__call__(node) def visit_ClassDefNode(self, node): oldname = self.class_name oldclass = self.class_node self.class_node = node try: # PyClassDefNode self.class_name = node.name except AttributeError: # CClassDefNode self.class_name = node.class_name self.visitchildren(node) self.class_name = oldname self.class_node = oldclass return node def visit_LambdaNode(self, node): # lambda expressions so not have signature or inner functions return node def visit_DefNode(self, node): if not self.current_directives['embedsignature']: return node hide_self = False if node.entry.is_special: return node class_name, func_name = self.class_name, node.name npoargs = getattr(node, 'num_posonly_args', 0) nkargs = getattr(node, 'num_kwonly_args', 0) npargs = len(node.args) - nkargs - npoargs signature = self._fmt_signature( node, class_name, func_name, node.args, npoargs, npargs, node.star_arg, nkargs, node.starstar_arg, return_expr=node.return_type_annotation, return_type=None, hide_self=hide_self, ) if signature: doc_holder = node.entry if doc_holder.doc is not None: old_doc = doc_holder.doc elif getattr(node, 'py_func', None) is not None: old_doc = node.py_func.entry.doc else: old_doc = None new_doc = self._embed_signature(signature, node.pos, old_doc) doc_holder.doc = EncodedString(new_doc) if getattr(node, 'py_func', None) is not None: node.py_func.entry.doc = EncodedString(new_doc) return node def visit_CFuncDefNode(self, node): if not self.current_directives['embedsignature']: return node if not node.overridable: # not cpdef FOO(...): return node signature = self._fmt_signature( node, self.class_name, node.declarator.base.name, node.declarator.args, return_type=node.return_type, ) if signature: if node.entry.doc is not None: old_doc = node.entry.doc elif getattr(node, 'py_func', None) is not None: old_doc = node.py_func.entry.doc else: old_doc = None new_doc = self._embed_signature(signature, node.pos, old_doc) node.entry.doc = EncodedString(new_doc) py_func = getattr(node, 'py_func', None) if py_func is not None: py_func.entry.doc = EncodedString(new_doc) return node def visit_PropertyNode(self, node): if not self.current_directives['embedsignature']: return node entry = node.entry body = node.body prop_name = entry.name type_name = None if entry.visibility == 'public': # property synthesised from a cdef public attribute type_name = entry.type.declaration_code('', for_display=1) if not entry.type.is_pyobject: type_name = "'%s'" % type_name elif entry.type.is_extension_type: type_name = entry.type.module_name + '.' + type_name if type_name is None: for stat in body.stats: if stat.name != '__get__': continue cls_name = self.class_name if cls_name: namespace = self._select_format('%s.' % cls_name, '') prop_name = '%s%s' % (namespace, prop_name) ret_annotation = stat.return_type_annotation if ret_annotation: type_name = self._fmt_annotation(ret_annotation) if type_name is not None: signature = '%s: %s' % (prop_name, type_name) new_doc = self._embed_signature(signature, node.pos, entry.doc) entry.doc = EncodedString(new_doc) return node # Monkeypatch AutoDocTransforms.EmbedSignature try: from Cython.Compiler import AutoDocTransforms AutoDocTransforms.EmbedSignature = EmbedSignature except Exception as exc: import logging logging.Logger(__name__).exception(exc) # Monkeypatch Nodes.raise_utility_code try: from Cython.Compiler.Nodes import raise_utility_code code = raise_utility_code.impl try: ipos = code.index('if (tb) {\n#if CYTHON_COMPILING_IN_PYPY\n') except ValueError: ipos = None else: raise_utility_code.impl = code[:ipos] + code[ipos:].replace( 'CYTHON_COMPILING_IN_PYPY', '!CYTHON_FAST_THREAD_STATE', 1 ) del raise_utility_code, code, ipos except Exception as exc: import logging logging.Logger(__name__).exception(exc) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/cythonize.py0000755000076500000240000000244415133663436016112 0ustar00jromanstaff#!/usr/bin/env python3 """Run Cython with custom options.""" import os import sys appdir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, appdir) import cyautodoc # noqa: F401,E402 from Cython.Compiler.Main import main as cython_main # noqa: E402 def cythonize(args=None): """Run `cython --3str --cleanup 3 ...`.""" if args is None: argv = sys.argv[:] else: argv = [os.path.abspath(__file__)] + list(args) if '--cleanup' not in argv: argv[1:1] = ['--cleanup', '3'] if '--3str' not in argv: argv[1:1] = ['--3str'] cwd = os.getcwd() sys_argv = sys.argv[:] try: sys.argv[:] = argv cython_main(command_line=1) return 0 except SystemExit as exc: return exc.code finally: os.chdir(cwd) sys.argv[:] = sys_argv def main(): """Entry-point to run Cython with custom options.""" args = sys.argv[1:] if not args: topdir = os.path.dirname(appdir) srcdir = os.path.join(topdir, 'src') source = os.path.join('slepc4py', 'SLEPc.pyx') target = os.path.join('slepc4py', 'SLEPc.c') args += ['--working', srcdir] args += [source, '--output-file', target] sys.exit(cythonize(args)) if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/conf/cythonize.sh0000755000076500000240000000022315133663436016065 0ustar00jromanstaff#!/bin/sh topdir=$(cd $(dirname "$0")/.. && pwd) python$py "$topdir/conf/cythonize.py" \ --working "$topdir/src" $@ \ "slepc4py/SLEPc.pyx" ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1768908984.481446 slepc4py-3.24.2/demo/0000755000076500000240000000000015133664270013511 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex1.py0000644000076500000240000001763615133663436014600 0ustar00jromanstaff# ex1.py: Standard symmetric eigenproblem for the 1-D Laplacian # ============================================================= # # This example computes eigenvalues and eigenvectors of the discrete Laplacian # on a one-dimensional domain with finite differences. # # The full source code for this demo can be `downloaded here # <../_static/ex1.py>`__. # The first thing to do is initialize the libraries. This is normally not # required, as it is done automatically at import time. However, if you want to # gain access to the facilities for setting command-line options, the # following lines must be executed by the main script prior to any petsc4py or # slepc4py calls: import sys, slepc4py slepc4py.init(sys.argv) # Next, we have to import the relevant modules. Normally, both PETSc and SLEPc # modules have to be imported in all slepc4py programs. It may be useful to # import NumPy as well: from petsc4py import PETSc from slepc4py import SLEPc import numpy # At this point, we can use any petsc4py and slepc4py operations. For instance, # the following lines allow the user to specify an integer command-line # argument ``n`` with a default value of 30 (see below for example usage # of command-line options): opts = PETSc.Options() n = opts.getInt('n', 30) # It is necessary to build a matrix to define an eigenproblem (or two in the # case of generalized eigenproblems). The following fragment of code creates # the matrix object and then fills the non-zero elements one by one. The matrix # of this particular example is tridiagonal, with value 2 in the diagonal, and # -1 in off-diagonal positions. See petsc4py documentation for details about # matrix objects: A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() # first row if rstart == 0: A[0, :2] = [2, -1] rstart += 1 # last row if rend == n: A[n-1, -2:] = [-1, 2] rend -= 1 # other rows for i in range(rstart, rend): A[i, i-1:i+2] = [-1, 2, -1] A.assemble() # The solver object is created in a similar way as other objects in petsc4py: E = SLEPc.EPS(); E.create() # Once the object is created, the eigenvalue problem must be specified. At # least one matrix must be provided. The problem type must be indicated as # well, in this case it is HEP (Hermitian eigenvalue problem). Apart from # these, other settings could be provided here (for instance, the tolerance for # the computation). After all options have been set, the user should call the # `setFromOptions() ` operation, so that any options # specified at run time in the command line are passed to the solver object: E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) history = [] def monitor(eps, its, nconv, eig, err): if nconv` method will run the selected # eigensolver, keeping the solution stored internally: E.solve() # Once the computation has finished, we are ready to print the results. First, # some informative data can be retrieved from the solver object: Print = PETSc.Sys.Print Print() Print("******************************") Print("*** SLEPc Solution Results ***") Print("******************************") Print() its = E.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) eps_type = E.getType() Print( "Solution method: %s" % eps_type ) nev, ncv, mpd = E.getDimensions() Print( "Number of requested eigenvalues: %d" % nev ) tol, maxit = E.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) # For retrieving the solution, it is necessary to find out how many eigenpairs # have converged to the requested precision: nconv = E.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) # For each of the ``nconv`` eigenpairs, we can retrieve the eigenvalue ``k``, # and the eigenvector, which is represented by means of two petsc4py vectors # ``vr`` and ``vi`` (the real and imaginary part of the eigenvector, since for # real matrices the eigenvalue and eigenvector may be complex). In this # example we know that both the eigenvalue and eigenvector are real, so only # one vector ``v`` is needed. We also compute the corresponding relative errors # in order to make sure that the computed solution is indeed correct: if nconv > 0: # Create the results vectors v, _ = A.createVecs() # Print() Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, v) error = E.computeError(i) Print( " %12f %12g" % (k, error) ) Print() # # Example of command-line usage # ----------------------------- # # Now we illustrate how to specify command-line options in order to extract the # full potential of slepc4py. # # A simple execution of the ``demo/ex1.py`` script will result in the following # output: # # .. code-block:: console # # $ python demo/ex1.py # # ****************************** # *** SLEPc Solution Results *** # ****************************** # # Number of iterations of the method: 4 # Solution method: krylovschur # Number of requested eigenvalues: 1 # Stopping condition: tol=1e-07, maxit=100 # Number of converged eigenpairs 4 # # k ||Ax-kx||/||kx|| # ----------------- ------------------ # 3.989739 5.76012e-09 # 3.959060 1.41957e-08 # 3.908279 6.74118e-08 # 3.837916 8.34269e-08 # # For specifying different setting for the solver parameters, we can use SLEPc # command-line options with the ``-eps`` prefix. For instance, to change the number # of requested eigenvalues and the tolerance: # # .. code-block:: console # # $ python demo/ex1.py -eps_nev 10 -eps_tol 1e-11 # # The method used by the solver object can also be set at run time: # # .. code-block:: console # # $ python demo/ex1.py -eps_type subspace # # All the above settings can also be changed within the source code by making # use of the appropriate slepc4py method. Since options can be set from within # the code and the command-line, it is often useful to view the particular # settings that are currently being used: # # .. code-block:: console # # $ python demo/ex1.py -eps_view # # EPS Object: 1 MPI process # type: krylovschur # 50% of basis vectors kept after restart # using the locking variant # problem type: symmetric eigenvalue problem # selected portion of the spectrum: largest eigenvalues in magnitude # number of eigenvalues (nev): 1 # number of column vectors (ncv): 16 # maximum dimension of projected problem (mpd): 16 # maximum number of iterations: 100 # tolerance: 1e-08 # convergence test: relative to the eigenvalue # BV Object: 1 MPI process # type: mat # 17 columns of global length 30 # orthogonalization method: classical Gram-Schmidt # orthogonalization refinement: if needed (eta: 0.7071) # block orthogonalization method: GS # doing matmult as a single matrix-matrix product # DS Object: 1 MPI process # type: hep # solving the problem with: Implicit QR method (_steqr) # ST Object: 1 MPI process # type: shift # shift: 0 # number of matrices: 1 # # Note that for computing eigenvalues of smallest magnitude we can use the # option ``-eps_smallest_magnitude``, but for interior eigenvalues things are # not so straightforward. One possibility is to try with harmonic extraction, # for instance to get the eigenvalues closest to 0.6: # # .. code-block:: console # # $ python demo/ex1.py -eps_harmonic -eps_target 0.6 # # Depending on the problem, harmonic extraction may fail to converge. In those # cases, it is necessary to specify a spectral transformation other than the # default. In the command-line, this is indicated with the ``-st_`` prefix. For # example, shift-and-invert with a value of the shift equal to 0.6 would be: # # .. code-block:: console # # $ python demo/ex1.py -st_type sinvert -eps_target 0.6 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex10.py0000644000076500000240000002170715133663436014652 0ustar00jromanstaff# ex10.py: Laplace problem using the Proper Orthogonal Decomposition # ================================================================== # # This example program solves the Laplace problem using the Proper Orthogonal # Decomposition (POD) reduced-order modeling technique. For a full description # of the technique the reader is referred to [1]_, [2]_. # # The method is split into an offline (computationally intensive) and an online # (computationally cheap) phase. This has many applications including real-time # simulation, uncertainty quantification and inverse problems, where similar # models must be evaluated quickly and many times. # # Offline phase: # # 1. A set of solution snapshots of the 1D Laplace problem in the full # problem space are constructed and assembled into the columns of a dense # matrix :math:`S`. # 2. A standard eigenvalue decomposition is performed on the # matrix :math:`S^T S`. # 3. The eigenvectors and eigenvalues are projected back to the # original eigenvalue problem :math:`S`. # 4. The leading eigenvectors then form the POD basis. # # Online phase: # # 1. The operator corresponding to the discrete Laplacian is # projected onto the POD basis. # 2. The operator corresponding to the right-hand side is # projected onto the POD basis. # 3. The reduced (dense) problem expressed in the POD basis is solved. # 4. The reduced solution is projected back to the full # problem space. # # Contributed by: Elisa Schenone, Jack S. Hale. # # The full source code for this demo can be `downloaded here # <../_static/ex10.py>`__. # Initialization is similar to previous examples, but importing some # additional modules. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy import random import math # This function builds the discrete Laplacian operator in 1 dimension # with homogeneous Dirichlet boundary conditions. def construct_operator(m): # Create matrix for 1D Laplacian operator A = PETSc.Mat().create(PETSc.COMM_SELF) A.setSizes([m, m]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = 2.0/hx offdx = -1.0/hx Istart, Iend = A.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): A[i, i] = diagv if i > 1: A[i, i - 1] = offdx if i < m - 2: A[i, i + 1] = offdx else: A[i, i] = 1. A.assemble() return A # Set bell-shape function as the solution of the Laplacian problem in # 1 dimension with homogeneous Dirichlet boundary conditions and # compute the associated discrete RHS. def set_problem_rhs(m): # Create 1D mass matrix operator M = PETSc.Mat().create(PETSc.COMM_SELF) M.setSizes([m, m]) M.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = hx/3 offdx = hx/6 Istart, Iend = M.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): M[i, i] = 2*diagv else: M[i, i] = diagv if i > 1: M[i, i - 1] = offdx if i < m - 2: M[i, i + 1] = offdx M.assemble() x_0 = 0.3 x_f = 0.7 mu = x_0 + (x_f - x_0)*random.random() sigma = 0.1**2 uex, f = M.createVecs() for j in range(Istart, Iend): value = 2/sigma * math.exp(-(hx*j - mu)**2/sigma) * (1 - 2/sigma * (hx*j - mu)**2 ) f.setValue(j, value) value = math.exp(-(hx*j - mu)**2/sigma) uex.setValue(j, value) f.assemble() uex.assemble() RHS = f.duplicate() M.mult(f, RHS) RHS.setValue(0, 0.) RHS.setValue(m-1, 0.) RHS.assemble() return RHS, uex # Solve 1D Laplace problem with FEM. def solve_laplace_problem(A, RHS): u = A.createVecs('right') r, c = A.getOrdering("natural") A.factorILU(r, c) A.solve(RHS, u) A.setUnfactored() return u # Solve 1D Laplace problem with POD (dense matrix). def solve_laplace_problem_pod(A, RHS, u): ksp = PETSc.KSP().create(PETSc.COMM_SELF) ksp.setOperators(A) ksp.setType('preonly') pc = ksp.getPC() pc.setType('none') ksp.setFromOptions() ksp.solve(RHS, u) return u # Set ``N`` solution of the 1D Laplace problem as columns of a matrix # (snapshot matrix). # # Note: For simplicity we do not perform a linear solve, but use # some analytical solution: # :math:`z(x) = \exp(-(x - \mu)^2 / \sigma)`. def construct_snapshot_matrix(A, N, m): snapshots = PETSc.Mat().create(PETSc.COMM_SELF) snapshots.setSizes([m, N]) snapshots.setType('seqdense') Istart, Iend = snapshots.getOwnershipRange() hx = 1.0/(m - 1) x_0 = 0.3 x_f = 0.7 sigma = 0.1**2 for i in range(N): mu = x_0 + (x_f - x_0)*random.random() for j in range(Istart, Iend): value = math.exp(-(hx*j - mu)**2/sigma) snapshots.setValue(j, i, value) snapshots.assemble() return snapshots # Solve the eigenvalue problem: the eigenvectors of this problem form the # POD basis. def solve_eigenproblem(snapshots, N): print('Solving POD basis eigenproblem using eigensolver...') Es = SLEPc.EPS() Es.create(PETSc.COMM_SELF) Es.setDimensions(N) Es.setProblemType(SLEPc.EPS.ProblemType.NHEP) Es.setTolerances(1.0e-8, 500); Es.setKrylovSchurRestart(0.6) Es.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_REAL) Es.setOperators(snapshots) Es.setFromOptions() Es.solve() print('Solved POD basis eigenproblem.') return Es # Function to project :math:`S^TS` eigenvectors to :math:`S` eigenvectors. def project_STS_eigenvectors_to_S_eigenvectors(bvEs, S): sizes = S.getSizes()[0] N = bvEs.getActiveColumns()[1] bv = SLEPc.BV().create(PETSc.COMM_SELF) bv.setSizes(sizes, N) bv.setActiveColumns(0, N) bv.setFromOptions() tmpvec2 = S.createVecs('left') for i in range(N): tmpvec = bvEs.getColumn(i) S.mult(tmpvec, tmpvec2) bv.insertVec(i, tmpvec2) bvEs.restoreColumn(i, tmpvec) return bv # Function to project the reduced space to the full space. def project_reduced_to_full_space(alpha, bv): uu = bv.getColumn(0) uPOD = uu.duplicate() bv.restoreColumn(0,uu) scatter, Wr = PETSc.Scatter.toAll(alpha) scatter.begin(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) scatter.end(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) PODcoeff = Wr.getArray(readonly=1) bv.multVec(1., 0., uPOD, PODcoeff) return uPOD # The main function realizes the full procedure. def main(): problem_dim = 200 num_snapshots = 30 num_pod_basis_functions = 8 assert(num_pod_basis_functions <= num_snapshots) A = construct_operator(problem_dim) S = construct_snapshot_matrix(A, num_snapshots, problem_dim) # Instead of solving the SVD of S, we solve the standard # eigenvalue problem on S.T*S STS = S.transposeMatMult(S) Es = solve_eigenproblem(STS, num_pod_basis_functions) nconv = Es.getConverged() print('Number of converged eigenvalues: %i' % nconv) Es.view() # get the EPS solution in a BV object bvEs = Es.getBV() bvEs.setActiveColumns(0, num_pod_basis_functions) # set the bv POD basis bv = project_STS_eigenvectors_to_S_eigenvectors(bvEs, S) # rescale the eigenvectors for i in range(num_pod_basis_functions): ll = Es.getEigenvalue(i) print('Eigenvalue '+str(i)+': '+str(ll.real)) bv.scaleColumn(i,1.0/math.sqrt(ll.real)) print('--------------------------------') # Verify that the active columns of bv form an orthonormal subspace, i.e. that X^H*X = Id print('Check that bv.dot(bv) is close to the identity matrix') XtX = bv.dot(bv) XtX.view() XtX_array = XtX.getDenseArray() n,m = XtX_array.shape assert numpy.allclose(XtX_array, numpy.eye(n, m)) print('--------------------------------') print('Solve the problem with POD') # Project the linear operator A Ared = bv.matProject(A,bv) # Set the RHS and the exact solution RHS, uex = set_problem_rhs(problem_dim) # Project the RHS on the POD basis RHSred = PETSc.Vec().createWithArray(bv.dotVec(RHS)) # Solve the problem with POD alpha = Ared.createVecs('right') alpha = solve_laplace_problem_pod(Ared,RHSred,alpha) # Project the POD solution back to the FE space uPOD = project_reduced_to_full_space(alpha, bv) # Compute the L2 and Linf norm of the error error = uex.copy() error.axpy(-1,uPOD) errorL2 = math.sqrt(error.dot(error).real) print('The L2-norm of the error is: '+str(errorL2)) print("NORMAL END") if __name__ == '__main__': main() # .. [1] K. Kunisch and S. Volkwein. Galerkin proper orthogonal decomposition methods # for a general equation in fluid dynamics. SIAM Journal on Numerical Analysis, # 40(2):492-515, 2003. # .. [2] S. Volkwein, Optimal control of a phase-field model using the proper orthogonal # decomposition, Z. Angew. Math. Mech., 81:83-97, 2001. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex11.py0000644000076500000240000000501215133663436014642 0ustar00jromanstaff# ex11.py: 2-D Laplacian eigenproblem solved with contour integral # ================================================================ # # This example is similar to ``ex2.py``, but employs a contour integral # solver. It illustrates how to define a region of the complex plane # using an `RG` object. # # The full source code for this demo can be `downloaded here # <../_static/ex11.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Build the finite-difference 2-D Laplacian matrix. def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # In the main function, first two command-line options are processed to # set the grid dimensions. Then the matrix is built and passed to the # solver object. In this case, the solver is configured to use the contour # integral method. Next, the region of interest is defined, in this case # an ellipse centered at the origin, with radius 0.2 and vertical scaling # of 0.1. Finally, the solver is run. In this example, we illustrate how to # print the solution using the solver method `errorView() `. def main(): opts = PETSc.Options() n = opts.getInt('n', 32) m = opts.getInt('m', 32) Print("2-D Laplacian Eigenproblem solved with contour integral, " "N=%d (%dx%d grid)\n" % (m*n, m, n)) A = construct_operator(m,n) E = SLEPc.EPS().create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setType(SLEPc.EPS.Type.CISS) R = E.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) R.setEllipseParameters(0.0,0.2,0.1) E.setFromOptions() E.solve() vw = PETSc.Viewer.STDOUT() vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) vw.popFormat() if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex12.py0000644000076500000240000000466115133663436014654 0ustar00jromanstaff# ex12.py: Illustrate the use of arbitrary selection # ================================================== # # This example solves a simple tridiagonal eigenproblem. It illustrates # how to set up the arbitrary selection of eigenvalues, where the # decision of which is the preferred eigenvalue is made based not only # on the value of the approximate eigenvalue but also on the approximate # eigenvector. # # In this example, the selection criterion is based on the projection # of the approximate eigenvector onto a precomputed eigenvector. That is # why we solve the problem twice. # # The full source code for this demo can be `downloaded here # <../_static/ex12.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy # The matrix size ``n`` can be specified at the command line. opts = PETSc.Options() n = opts.getInt('n', 30) # Create the matrix ``tridiag([-1 0 -1])``. A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i>0: A[i, i-1] = -1 if i0: sx, _ = A.createVecs() E.getEigenpair(0, sx) vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) def myArbitrarySel(evalue, xr, xi, sx): return abs(xr.dot(sx)) E.setArbitrarySelection(myArbitrarySel,sx) E.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_MAGNITUDE) E.solve() E.errorView(viewer=vw) vw.popFormat() else: Print( "No eigenpairs converged" ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex13.py0000644000076500000240000002142115133663436014646 0ustar00jromanstaff# ex13.py: Nonlinear eigenproblem with contour integral # ===================================================== # # This example solves a nonlinear eigenvalue problem with the `NEP # ` module configured to apply a contour integral # method. # # The problem arises from the PDE # # .. math:: # # u_{xx}(x) + n_c^2 \lambda^2 u(x) + g(\lambda) D_0 \lambda^2 u(x) = 0 # # where # # .. math:: # # g(\lambda) &= g_t/(\lambda-k_a + i g_t), \\ # k_a &= 8.0, \\ # g_t &= 0.5, \\ # D_0 &= 0.5, \\ # n_c &= 1.2, # # and the boundary conditions are # # .. math:: # # u(0) &= 0 \\ # u_x(1) &= i \lambda u(1). # # For the discretization, :math:`n` grid points are used, :math:`x_1=0,\dots,x_n=1`, # with step size :math:`h = 1/(n-1)`. Hence, # # .. math:: # # u_{xx}(x_i) &= \frac{1}{h^2} (u_{i-1} - 2 u_i + u_{i+1}) \\ # &= \frac{1}{h^2} [1, -2, 1] [u_{i-1}, u_i, u_{i+1}]^T. # # The boundary condition at :math:`x=0` is :math:`u_1=0`, and at :math:`x=1`: # # .. math:: # # u'(1) &= 1/2 ( u'(1+h/2) + u'(1-h/2) ) \\ # &= 1/2 ( (u_{n+1}-u_n)/h + (u_n-u_{n-1})/h ) \\ # &= 1/(2h) (u_{n+1} - u_{n-1}) = i\lambda u_n, # # and therefore # # .. math:: # # u_{n+1} = 2i h \lambda u_n + u_{n-1}. # # The Laplace term for :math:`u_n` is # # .. math:: # # &= \frac{1}{h^2} (u_{n-1} - 2u_n + u_{n+1}) \\ # &= \frac{1}{h^2} (u_{n-1} - 2u_n + 2ih\lambda u_n + u_{n-1}) \\ # &= \frac{1}{h^2} (2 u_{n-1} + (2ih\lambda - 2) u_n) \\ # &= \frac{1}{h^2} [2, 2ih\lambda -2] [u_{n-1}, u_n]^T. # # The above discretization allows us to write the nonlinear PDE in the # following split-operator form # # .. math:: # # \{A + \lambda^2 n_c^2 I_d + g(\lambda) \lambda^2 D_0 I_d + 2i\lambda/h D\} u = 0 # # so :math:`f_1 = 1`, :math:`f_2 = n_c^2 \lambda^2`, :math:`f_3 = g(\lambda) # \lambda^2D_0`, :math:`f_4 = 2i\lambda/h`, with coefficient matrices # # .. math:: # # A = \begin{bmatrix} # 1 & 0 & 0 & \dots & 0 \\ # 0 & * & * & \dots & 0 \\ # 0 & * & * & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & * # \end{bmatrix}, # I_d = \begin{bmatrix} # 0 & 0 & 0 & \dots & 0 \\ # 0 & 1 & 0 & \dots & 0 \\ # 0 & 0 & 1 & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & 0 # \end{bmatrix}, # D = \begin{bmatrix} # 0 & 0 & 0 & \dots & 0 \\ # 0 & 0 & 0 & \dots & 0 \\ # 0 & 0 & 0 & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & 1 # \end{bmatrix}. # # Contributed by: Thomas Hisch. # # The full source code for this demo can be `downloaded here # <../_static/ex13.py>`__. # Initialization by importing slepc4py, petsc4py, numpy and scipy. import sys import slepc4py slepc4py.init(sys.argv) # isort:skip import numpy as np try: import scipy import scipy.optimize except ImportError: scipy = None from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Check that the selected PETSc/SLEPc are built with complex scalars. if not np.issubdtype(PETSc.ScalarType, np.complexfloating): Print("Demo should only be executed with complex PETSc scalars") exit(0) # Long function that defines the nonlinear eigenproblem and solves it. def solve(n): L = 1.0 h = L / (n - 1) nc = 1.2 ka = 10.0 gt = 4.0 D0 = 0.5 A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() A.setOption(PETSc.Mat.Option.HERMITIAN, False) rstart, rend = A.getOwnershipRange() d0, d1, d2 = ( 1 / h**2, -2 / h**2, 1 / h**2, ) Print(f"dterms={(d0, d1, d2)}") if rstart == 0: # dirichlet boundary condition at the left lead A[0, 0] = 1.0 A[0, 1] = 0.0 A[1, 0] = 0.0 A[1, 1] = d1 A[1, 2] = d2 rstart += 2 if rend == n: # at x=1.0 neumann boundary condition (not handled here but in a # different matrix (D)) A[n - 1, n - 2] = 2.0 / h**2 A[n - 1, n - 1] = (-2) / h**2 # + 2j*k*h / h**2 (neumann) rend -= 1 for i in range(rstart, rend): A[i, i - 1 : i + 2] = [d0, d1, d2] A.assemble() Id = PETSc.Mat().create() Id.setSizes([n, n]) Id.setFromOptions() Id.setOption(PETSc.Mat.Option.HERMITIAN, True) rstart, rend = Id.getOwnershipRange() if rstart == 0: # due to dirichlet BC rstart += 1 for i in range(rstart, rend): Id[i, i] = 1.0 Id.assemble() D = PETSc.Mat().create() D.setSizes([n, n]) D.setFromOptions() D.setOption(PETSc.Mat.Option.HERMITIAN, True) _, rend = D.getOwnershipRange() if rend == n: D[n - 1, n - 1] = 1 D.assemble() Print(f"DOF: {A.getInfo()['nz_used']}, MEM: {A.getInfo()['memory']}") f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([1.0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([nc**2, 0.0, 0.0]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.RATIONAL) f3.setRationalNumerator([D0 * gt, 0.0, 0.0]) f3.setRationalDenominator([1.0, -ka + 1j * gt]) f4 = SLEPc.FN().create() f4.setType(SLEPc.FN.Type.RATIONAL) f4.setRationalNumerator([2j / h, 0]) # Setup the solver nep = SLEPc.NEP().create() nep.setSplitOperator( [A, Id, Id, D], [f1, f2, f3, f4], PETSc.Mat.Structure.SUBSET, ) # Customize options nep.setTolerances(tol=1e-7) nep.setDimensions(nev=24) nep.setType(SLEPc.NEP.Type.CISS) # the rg params are chosen s.t. the singularity at k = ka - 1j*gt is # outside of the contour. radius = 3 * gt vscale = 0.5 * gt / radius rg_params = (ka, 3 * gt, vscale) R = nep.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) Print(f"RG params: {rg_params}") R.setEllipseParameters(*rg_params) nep.setFromOptions() # Solve the problem nep.solve() its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print("Number of converged eigenpairs %d" % nconv) x = A.createVecs("right") evals = [] modes = [] if nconv > 0: Print() Print(" lam ||T(lam)x|| |lam-lam_exact|/|lam_exact| ") Print("--------------------- ------------- -----------------------------") for i in range(nconv): lam = nep.getEigenpair(i, x) error = nep.computeError(i) def eigenvalue_error_term(k): gkmu = gt / (k - ka + 1j * gt) nceff = np.sqrt(nc**2 + gkmu * D0) return -1j / np.tan(nceff * k * L) - 1 / nceff # compute the expected_eigenvalue # we assume that the numerically calculated eigenvalue is close to # the exact one, which we can determine using a Newton-Raphson # method. if scipy: expected_lam = scipy.optimize.newton( eigenvalue_error_term, np.complex128(lam), rtol=1e-11 ) rel_err = abs(lam - expected_lam) / abs(expected_lam) rel_err = "%6g" % rel_err else: rel_err = "scipy not installed" Print(" %9f%+9f j %12g %s" % (lam.real, lam.imag, error, rel_err)) evals.append(lam) modes.append(x.getArray().copy()) Print() return np.asarray(evals), rg_params, ka, gt # The main function reads the problem size ``n`` from the command line, # solves the problem with the above function, and then plots the computed # eigenvalues. def main(): opts = PETSc.Options() n = opts.getInt("n", 256) Print(f"n={n}") evals, rg_params, ka, gt = solve(n) if not opts.getBool("ploteigs", True) or PETSc.COMM_WORLD.getRank(): return try: import matplotlib.pyplot as plt from matplotlib.patches import Ellipse except ImportError: print("plot is not shown, because matplotlib is not installed") else: fig, ax = plt.subplots() ax.plot(evals.real, evals.imag, "x") height = 2 * rg_params[1] * rg_params[2] ellipse = Ellipse( xy=(rg_params[0], 0.0), width=rg_params[1] * 2, height=height, edgecolor="r", fc="None", lw=2, ) ax.add_patch(ellipse) ax.grid() ax.legend() plt.show() if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex14.py0000644000076500000240000000717415133663436014660 0ustar00jromanstaff# ex14.py: Lyapunov equation with the shifted 2-D Laplacian # ========================================================= # # This example illustrates the use of slepc4py linear matrix equations # solver object. In particular, a Lyapunov equation is solved, where # the coefficient matrix is the shifted 2-D Laplacian. # # The full source code for this demo can be `downloaded here # <../_static/ex14.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Once again, a function to build the discretized Laplacian operator # in two dimensions. In this case, we build the shifted negative # Laplacian because the Lyapunov equation requires the coefficient # matrix being stable. def Laplacian2D(m, n, sigma): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = -4.0-sigma i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = 1.0 if i< m-1: J = I+n; A[I,J] = 1.0 if j> 0 : J = I-1; A[I,J] = 1.0 if j< n-1: J = I+1; A[I,J] = 1.0 A.assemble() return A # The following function solves the continuous-time Lyapunov equation # # .. math:: # AX + XA^* = -C # # where :math:`C` is supposed to have low rank. The solution :math:`X` # also has low rank, which will be restricted to ``rk`` if it was # provided as an argument of the function. After solving the equation, # this function computes and prints a residual norm. def solve_lyap(A, C, rk=0): # Setup the solver L = SLEPc.LME().create() L.setProblemType(SLEPc.LME.ProblemType.LYAPUNOV) L.setCoefficients(A) L.setRHS(C) N = C.size[0] if rk>0: X1 = PETSc.Mat().createDense((N,rk)) X1.assemble() X = PETSc.Mat().createLRC(None, X1, None, None) L.setSolution(X) L.setTolerances(1e-7) L.setFromOptions() # Solve the problem L.solve() if rk==0: X = L.getSolution() its = L.getIterationNumber() Print(f'Number of iterations of the method: {its}') sol_type = L.getType() Print(f'Solution method: {sol_type}') tol, maxit = L.getTolerances() Print(f'Stopping condition: tol={tol}, maxit={maxit}') Print(f'Error estimate reported by the solver: {L.getErrorEstimate()}') if N<500: Print(f'Computed residual norm: {L.computeError()}') Print('') return X # The main function processes several command-line arguments such as # the grid dimension (``n``, ``m``), the shift ``sigma`` and the rank # of the solution, ``rank``. # # The coefficient matrix ``A`` is built with the function above, while # the right-hand side matrix ``C`` must be built as a low-rank matrix # using `Mat.createLRC() `. if __name__ == '__main__': opts = PETSc.Options() n = opts.getInt('n', 15) m = opts.getInt('m', n) N = m*n sigma = opts.getScalar('sigma', 0.0) rk = opts.getInt('rank', 0) # Coefficient matrix A A = Laplacian2D(m, n, sigma) # Create a low-rank Mat to store the right-hand side C = C1*C1' C1 = PETSc.Mat().createDense((N,2)) rstart, rend = C1.getOwnershipRange() v = C1.getDenseArray() for i in range(rstart,rend): if i`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # In this example we have organized the code in several functions. This # one builds the finite-difference Laplacian matrix by computing the # indices of each entry. An alternative would be to use the functionality # offered by `DMDA `. def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # This function receives the matrix and the problem type, then solves the # eigenvalue problem and prints information about the computed solution. # Although we know that eigenvalues and eigenvectors are real in this # example, the function is prepared to solve it as a non-symmetric problem, # by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles # possibly complex eigenvalues and eigenvectors. def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other two functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (sparse matrix), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex3.py0000644000076500000240000001072115133663436014566 0ustar00jromanstaff# ex3.py: Matrix-free eigenproblem for the 2-D Laplacian # ====================================================== # # This example solves the eigenproblem for the 2-D discrete Laplacian # without building the matrix explicitly. # # The full source code for this demo can be `downloaded here # <../_static/ex3.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy as np # In this case, the program cannot be run in parallel, so we check that # the number of MPI processes is 1. In order to enable parallelism, we # should implement a parallel matrix-vector operation ourselves, which # is not done in this example. assert PETSc.COMM_WORLD.getSize() == 1 Print = PETSc.Sys.Print # This function computes the matrix-vector product f = L*x where the # Laplacian L is not built explicitly, and the vectors x,f are viewed # as two-dimensional arrays associated to grid points. def laplace2d(U, x, f): U[:,:] = 0 U[1:-1, 1:-1] = x # Grid spacing m, n = x.shape hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing # Setup 5-points stencil u = U[1:-1, 1:-1] # center uN = U[1:-1, :-2] # north uS = U[1:-1, 2: ] # south uW = U[ :-2, 1:-1] # west uE = U[2:, 1:-1] # east # Apply Laplacian f[:,:] = \ (2*u - uE - uW) * (hy/hx) \ + (2*u - uN - uS) * (hx/hy) \ # For a matrix-free solution in slepc4py we have to create a class that # wraps the matrix-vector operation and optionally other operations of # the matrix. In this case, we provide the constructor and the ``mult`` # operation, that simply calls the ``laplace2d`` function above. class Laplacian2D(object): def __init__(self, m, n): self.m, self.n = m, n scalar = PETSc.ScalarType self.U = np.zeros([m+2, n+2], dtype=scalar) def mult(self, A, x, y): m, n = self.m, self.n xx = x.getArray(readonly=1).reshape(m,n) yy = y.getArray(readonly=0).reshape(m,n) laplace2d(self.U, xx, yy) # In this example, building the matrix amounts to creating an object of # the class defined above, and passing it to a special petsc4py matrix # with `createPython() `. def construct_operator(m, n): # Create shell matrix context = Laplacian2D(m,n) A = PETSc.Mat().createPython([m*n,m*n], context) return A # This function receives the matrix and the problem type, then solves the # eigenvalue problem and prints information about the computed solution. # Although we know that eigenvalues and eigenvectors are real in this # example, the function is prepared to solve it as a non-symmetric problem, # by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles # possibly complex eigenvalues and eigenvectors. def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other two functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (matrix-free), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex4.py0000644000076500000240000000472115133663436014572 0ustar00jromanstaff# ex4.py: Singular value decomposition of the Lauchli matrix # ========================================================== # # This example illustrates the use of the SVD solver in slepc4py. It # computes singular values and vectors of the Lauchli matrix, whose # condition number depends on a parameter ``mu``. # # The full source code for this demo can be `downloaded here # <../_static/ex4.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc # This example takes two command-line arguments, the matrix size ``n`` # and the ``mu`` parameter. opts = PETSc.Options() n = opts.getInt('n', 30) mu = opts.getReal('mu', 1e-6) PETSc.Sys.Print( "Lauchli singular value decomposition, (%d x %d) mu=%g\n" % (n+1,n,mu) ) # Create the matrix and fill its nonzero entries. Every MPI process will # insert its locally owned part only. A = PETSc.Mat(); A.create() A.setSizes([n+1, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i==0: for j in range(n): A[0,j] = 1.0 else: A[i,i-1] = mu A.assemble() # The singular value solver is similar to the eigensolver used in previous # examples. In this case, we select the thick-restart Lanczos # bidiagonalization method. S = SLEPc.SVD(); S.create() S.setOperator(A) S.setType(S.Type.TRLANCZOS) S.setFromOptions() S.solve() # After solve, we print some informative data and extract the computed # solution, showing the list of singular values and the corresponding # residual errors. Print = PETSc.Sys.Print Print( "******************************" ) Print( "*** SLEPc Solution Results ***" ) Print( "******************************\n" ) svd_type = S.getType() Print( "Solution method: %s" % svd_type ) its = S.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) nsv, ncv, mpd = S.getDimensions() Print( "Number of requested singular values: %d" % nsv ) tol, maxit = S.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) nconv = S.getConverged() Print( "Number of converged approximate singular triplets %d" % nconv ) if nconv > 0: v, u = A.createVecs() Print() Print(" sigma residual norm ") Print("------------- ---------------") for i in range(nconv): sigma = S.getSingularTriplet(i, u, v) error = S.computeError(i) Print( " %6f %12g" % (sigma, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex5.py0000644000076500000240000000705015133663436014571 0ustar00jromanstaff# ex5.py: Simple quadratic eigenvalue problem # =========================================== # # This example solves a polynomial eigenvalue problem of degree 2, # which is the most commonly found in applications. Larger degree # polynomials are handled similarly. The coefficient matrices in # this example do not come from an application, they are just simple # matrices that are easy to build, just to illustrate how it works. # The eigenvalues in this example are purely imaginary and come in # conjugate pairs. # # The full source code for this demo can be `downloaded here # <../_static/ex5.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # A function to build the matrices. The lowest degree coefficient is # the 2-D Laplacian, the highest degree one is the identity matrix, # and the other matrix is set to zero (which means that this problem # could have been solved as a linear eigenproblem). def construct_operators(m,n): Print("Quadratic Eigenproblem, N=%d (%dx%d grid)"% (m*n, m, n)) # K is the 2-D Laplacian K = PETSc.Mat().create() K.setSizes([n*m, n*m]) K.setFromOptions() Istart, Iend = K.getOwnershipRange() for I in range(Istart,Iend): v = -1.0; i = I//n; j = I-i*n; if i>0: J=I-n; K[I,J] = v if i0: J=I-1; K[I,J] = v if j 0: Print("") Print(" k ||(k^2M+Ck+K)x||/||kx|| ") Print("-------------------- -------------------------") for i in range(nconv): k = Q.getEigenpair(i, xr, xi) error = Q.computeError(i) if k.imag != 0.0: Print("%9f%+9f j %12g" % (k.real, k.imag, error)) else: Print("%12f %12g" % (k.real, error)) Print("") # The main program simply processes two user-defined command-line options # (the dimensions of the mesh) and calls the other two functions. if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 32) n = opts.getInt('n', m) M, C, K = construct_operators(m,n) solve_eigensystem(M, C, K) M = C = K = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex6.py0000644000076500000240000000764315133663436014602 0ustar00jromanstaff# ex6.py: Compute exp(t*A)*v for a matrix from a Markov model # =========================================================== # # This example illustrates the functionality in slepc4py for computing # matrix functions, or more precisely, the application of a matrix # function on a given vector. The example works with the exponential # function, which is most commonly found in applications. # # The main focus of slepc4py is eigenvalue and singular value problems, # but it has some codes to deal with matrix functions, which sometimes # are needed in the context of eigenproblems, but have interest on # their own. # # The full source code for this demo can be `downloaded here # <../_static/ex6.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # This function builds a matrix that implements a Markov model of a random # walk on a triangular grid. The entries of the matrix represent # probabilities of moving to neighboring cells in the grid. def build_matrix(m): N = m*(m+1)/2 Print("Markov y=exp(t*A)*e_1, N=%d (m=%d)"% (N, m)) A = PETSc.Mat().create() A.setSizes([N, N]) A.setFromOptions() Istart, Iend = A.getOwnershipRange() ix = 0 cst = 0.5/(m-1) for i in range(1,m+1): jmax = m-i+1 for j in range(1,jmax+1): ix = ix + 1 if ix-1Iend: continue # compute only owned rows if j!=jmax: pd = cst*(i+j-1) # north if i==1: A[ix-1,ix] = 2*pd else: A[ix-1,ix] = pd # east if j==1: A[ix-1,ix+jmax-1] = 2*pd else: A[ix-1,ix+jmax-1] = pd # south pu = 0.5 - cst*(i+j-3) if j>1: A[ix-1,ix-2] = pu # west if i>1: A[ix-1,ix-jmax-2] = pu A.assemble() return A # The following function solves the problem. This case is quite different # from eigenproblems, and is more similar to solving a linear system of # equations with `KSP `. To configure the problem we # must provide the matrix and the function (the exponential in this case). # Note how the internal `FN` object is extracted from the `MFN` solver. # Also, it is often necessary to specify a scale factor, which in this # case represents the time for which we want to obtain the evolved state. # Once the solver is set up, we call `solve() ` passing the # right-hand side vector ``b`` and the solution vector ``x``. def solve_exp(t, A, b, x): # Setup the solver M = SLEPc.MFN().create() M.setOperator(A) f = M.getFN() f.setType(SLEPc.FN.Type.EXP) f.setScale(t) M.setTolerances(1e-7) M.setFromOptions() # Solve the problem M.solve(b,x) its = M.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = M.getType() Print("Solution method: %s" % sol_type) ncv = M.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = M.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) Print("Computed vector at time t=%.4g has norm %g" % (t.real, x.norm())) Print("") # The main program processes the command-line option ``m`` (size of the # grid), builds the matrix and calls the solver. Note how the vectors are # created from the matrix. In this case, the right-hand side vector is # the first element of the canonical basis. if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 15) A = build_matrix(m) # transition probability matrix x, b = A.createVecs() x.set(0) b.set(0) b[0] = 1 b.assemble() t = 2 solve_exp(t, A, b, x) # compute x=exp(t*A)*b A = None b = x = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex7.py0000644000076500000240000001457115133663436014601 0ustar00jromanstaff# ex7.py: Nonlinear eigenproblem with callback functions # ====================================================== # # This example solves a nonlinear eigenvalue problem arising from the # the discretization of a PDE on a one-dimensional domain with finite # differences. The nonlinearity comes from the boundary conditions. # The PDE is # # .. math:: # # -u'' = \lambda u # # defined on the interval [0,1] and subject to the boundary conditions # # .. math:: # # u(0)=0, u'(1)=u(1)\lambda\frac{\kappa}{\kappa-\lambda}, # # where :math:`\lambda` is the eigenvalue and :math:`\kappa` is a parameter. # # The full source code for this demo can be `downloaded here # <../_static/ex7.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import sqrt, sin Print = PETSc.Sys.Print # When implementing a nonlinear eigenproblem with callback functions we # must provide code that builds the function matrix :math:`T(\lambda)` # for a given :math:`\lambda` and optionally the Jacobian matrix # :math:`T'(\lambda)`, i.e., the derivative with respect to the eigenvalue. # # In slepc4py the callbacks are integrated in a class. In this example, # apart from the constructor, we have three methods: # # + ``formFunction`` to fill the function matrix ``F``. Note that ``F`` # is received as an argument and we just need to fill its entries using # the value of the parameter ``mu``. Matrix ``B`` is used to build # the preconditioner, and is usually equal to ``F``. # + ``formJacobian`` to fill the Jacobian matrix ``J``. Some eigensolvers # do not need this, but it is recommended to implement it. # + ``checkSolution`` is just a convenience method to check that a given # solution satisfies the PDE. class MyPDE(object): def __init__(self, kappa, h): self.kappa = kappa self.h = h def formFunction(self, nep, mu, F, B): n, m = F.getSize() Istart, Iend = F.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) d = n # Interior grid points for i in range(i1,i2): val = -d-mu*h/6.0 F[i,i-1] = val F[i,i] = 2.0*(d-mu*h/3.0) F[i,i+1] = val # Boundary points if Istart==0: F[0,0] = 2.0*(d-mu*h/3.0) F[0,1] = -d-mu*h/6.0 if Iend==n: F[n-1,n-2] = -d-mu*h/6.0 F[n-1,n-1] = d-mu*h/3.0+mu*c F.assemble() if B != F: B.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def formJacobian(self, nep, mu, J): n, m = J.getSize() Istart, Iend = J.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) # Interior grid points for i in range(i1,i2): J[i,i-1] = -h/6.0 J[i,i] = -2.0*h/3.0 J[i,i+1] = -h/6.0 # Boundary points if Istart==0: J[0,0] = -2.0*h/3.0 J[0,1] = -h/6.0 if Iend==n: J[n-1,n-2] = -h/6.0 J[n-1,n-1] = -h/3.0-c*c J.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def checkSolution(self, mu, y): nu = sqrt(mu) u = y.duplicate() n = u.getSize() Istart, Iend = J.getOwnershipRange() h = self.h for i in range(Istart,Iend): x = (i+1)*h u[i] = sin(nu*x); u.assemble() u.normalize() u.axpy(-1.0,y) return u.norm() # We use an auxiliary function ``FixSign`` to force the computed # eigenfunction to be real and positive, since some eigensolvers may # return the eigenvector multiplied by a complex number of modulus one. def FixSign(x): comm = x.getComm() rank = comm.getRank() n = 1 if rank == 0 else 0 aux = PETSc.Vec().createMPI((n, PETSc.DECIDE), comm=comm) if rank == 0: aux[0] = x[0] aux.assemble() x0 = aux.sum() sign = x0/abs(x0) x.scale(1.0/sign) # The main program processes two command-line options, ``n`` (size of the # grid) and ``kappa`` (the parameter of the PDE), then creates an object # of the class we have defined previously. opts = PETSc.Options() n = opts.getInt('n', 128) kappa = opts.getReal('kappa', 1.0) pde = MyPDE(kappa, 1.0/n) # In order to set up the solver we have to pass the two callback functions # (methods of the class) together with the matrix objects that will be # used every time these methods are called. In this simple example we can # do a preallocation of the matrices, although this is not necessary. nep = SLEPc.NEP().create() F = PETSc.Mat().create() F.setSizes([n, n]) F.setType('aij') F.setPreallocationNNZ(3) nep.setFunction(pde.formFunction, F) J = PETSc.Mat().create() J.setSizes([n, n]) J.setType('aij') J.setPreallocationNNZ(3) nep.setJacobian(pde.formJacobian, J) # After setting some options, we can solve the problem. Here we also # illustrate how to pass an initial guess to the solver. nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() x = F.createVecs('right') x.set(1.0) nep.setInitialSpace(x) nep.solve() # Once the solver has finished, we print some information together with # the computed solution. For each computed eigenpair, we print the # residual norm and also the error estimated with the class method # ``checkSolution``. its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: Print() Print(" k ||T(k)x|| error ") Print("----------------- ------------------ ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) FixSign(x) res = nep.computeError(i) error = pde.checkSolution(k.real, x) if k.imag != 0.0: Print( " %9f%+9f j %12g %12g" % (k.real, k.imag, res, error) ) else: Print( " %12f %12g %12g" % (k.real, res, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex8.py0000644000076500000240000001010615133663436014570 0ustar00jromanstaff# ex8.py: Nonlinear eigenproblem with split form # ============================================== # # This example solves a nonlinear eigenvalue problem where the # nonlinear function is expressed in split form. # # We want to solve the following parabolic partial differential # equation with time delay :math:`\tau` # # .. math:: # # u_t &= u_{xx} + a u(t) + b u(t-\tau) \\ # u(0,t) &= u(\pi,t) = 0 # # with :math:`a = 20` and :math:`b(x) = -4.1+x (1-e^{x-\pi})`. # # Discretization leads to a DDE of dimension :math:`n` # # .. math:: # # -u' = A u(t) + B u(t-\tau) # # which results in the nonlinear eigenproblem # # .. math:: # # (-\lambda I + A + e^{-\tau\lambda}B)u = 0. # # The full source code for this demo can be `downloaded here # <../_static/ex8.py>`__. # Initialization is similar to previous examples. In this case we also # need to import some math symbols. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import exp from math import pi Print = PETSc.Sys.Print # This script has two command-line options: the discretization size ``n`` # and the time delay ``tau``. opts = PETSc.Options() n = opts.getInt('n', 128) tau = opts.getReal('tau', 0.001) a = 20 h = pi/(n+1) # Next we have to set up the solver. In this case, we are going to # represent the nonlinear problem in split form, i.e., as a sum of # terms made of a constant matrix multiplied by a scalar nonlinear # function. nep = SLEPc.NEP().create() # The first term involves the identity matrix. Id = PETSc.Mat().createConstantDiagonal([n, n], 1.0) # The second term has a tridiagonal matrix obtained from the # discretization, :math:`A = \frac{1}{h^2}\operatorname{tridiag}(1,-2,1) + a I`. A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() vd = -2.0/(h*h)+a vo = 1.0/(h*h) if rstart == 0: A[0, :2] = [vd, vo] rstart += 1 if rend == n: A[n-1, -2:] = [vo, vd] rend -= 1 for i in range(rstart, rend): A[i, i-1:i+2] = [vo, vd, vo] A.assemble() # The third term includes a diagonal matrix :math:`B = \operatorname{diag}(b(x_i))`. B = PETSc.Mat().create() B.setSizes([n, n]) B.setFromOptions() rstart, rend = B.getOwnershipRange() for i in range(rstart, rend): xi = (i+1)*h B[i, i] = -4.1+xi*(1.0-exp(xi-pi)); B.assemble() B.setOption(PETSc.Mat.Option.HERMITIAN, True) # Apart from the matrices, we have to create the functions, represented with # `FN` objects: :math:`f_1=-\lambda, f_2=1, f_3=\exp(-\tau\lambda)`. f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([-1, 0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([1]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.EXP) f3.setScale(-tau) # Put all the information together to define the split operator. Note that # ``A`` is passed first so that `SUBSET ` # nonzero_pattern can be used. nep.setSplitOperator([A, Id, B], [f2, f1, f3], PETSc.Mat.Structure.SUBSET) # Now we can set some options and call the solver. nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() nep.solve() # Once the solver has finished, we print some information together with # the computed solution. For each computed eigenpair, we print the # eigenvalue and the residual norm. its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: x = Id.createVecs('right') x.set(1.0) Print() Print(" k ||T(k)x||") Print("----------------- ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) res = nep.computeError(i) if k.imag != 0.0: Print( " %9f%+9f j %12g" % (k.real, k.imag, res) ) else: Print( " %12f %12g" % (k.real, res) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/ex9.py0000644000076500000240000001055715133663436014603 0ustar00jromanstaff# ex9.py: Generalized symmetric-definite eigenproblem # =================================================== # # This example computes eigenvalues and eigenvectors of a generalized # symmetric-definite eigenvalue problem, where the first matrix is the # discrete Laplacian in two dimensions and the second matrix is quasi # diagonal. # # The full source code for this demo can be `downloaded here # <../_static/ex9.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # This function builds the discretized Laplacian operator in 2 dimensions. def Laplacian2D(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # This function builds a quasi-diagonal matrix. It is two times the identity # matrix except for the 2x2 leading submatrix ``[6 -1; -1 1]``. def QuasiDiagonal(N): # Create matrix B = PETSc.Mat().create() B.setSizes([N, N]) B.setFromOptions() # Fill matrix Istart, Iend = B.getOwnershipRange() for I in range(Istart, Iend): B[I,I] = 2.0 if Istart==0: B[0,0] = 6.0 B[0,1] = -1.0 B[1,0] = -1.0 B[1,1] = 1.0 B.assemble() return B # The following function receives the two matrices and solves the # eigenproblem. In this example we illustrate how to pass objects # that have been created beforehand, instead of extracting the internal # objects. We are using a spectral transformation of type `ST.Type.PRECOND` # and a Block Jacobi preconditioner. We want to compute the leftmost # eigenvalues. The selected eigensolver is LOBPCG, which is appropriate # for this use case. After the solve, we print the computed solution. def solve_eigensystem(A, B, problem_type=SLEPc.EPS.ProblemType.GHEP): # Create the results vectors xr, xi = A.createVecs() pc = PETSc.PC().create() # pc.setType(pc.Type.HYPRE) pc.setType(pc.Type.BJACOBI) ksp = PETSc.KSP().create() ksp.setType(ksp.Type.PREONLY) ksp.setPC( pc ) F = SLEPc.ST().create() F.setType(F.Type.PRECOND) F.setKSP( ksp ) F.setShift(0) # Setup the eigensolver E = SLEPc.EPS().create() E.setST(F) E.setOperators(A,B) E.setType(E.Type.LOBPCG) E.setDimensions(10,PETSc.DECIDE) E.setWhichEigenpairs(E.Which.SMALLEST_REAL) E.setProblemType( problem_type ) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 10) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric-definite Eigenproblem, N=%d (%dx%d grid)" % (m*n, m, n)) A = Laplacian2D(m,n) B = QuasiDiagonal(m*n) solve_eigensystem(A,B) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/demo/makefile0000644000076500000240000000050515133663436015214 0ustar00jromanstaffPYTHON=python TESTFILES = $(filter-out ex13.py,$(wildcard ex*.py)) TESTS = $(TESTFILES:.py=) RUNRULES = $(addprefix run_,$(TESTS)) .PHONY:test run ${RUNRULES} test: run run: ${RUNRULES} run_ex13 ${RUNRULES}: ${PYTHON} $(subst run_,,$@).py ${SLEPC_OPTIONS} run_ex13: ${PYTHON} ex13.py -ploteigs 0 ${SLEPC_OPTIONS} ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4654093 slepc4py-3.24.2/docs/0000755000076500000240000000000015133664270013515 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4861557 slepc4py-3.24.2/docs/source/0000755000076500000240000000000015133664270015015 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/Makefile0000644000076500000240000000113615133663436016461 0ustar00jromanstaff# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = slepc4py SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4864595 slepc4py-3.24.2/docs/source/_templates/0000755000076500000240000000000015133664270017152 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1768908984.487087 slepc4py-3.24.2/docs/source/_templates/autosummary/0000755000076500000240000000000015133664270021540 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/_templates/autosummary/class.rst0000644000076500000240000000415715133663436023411 0ustar00jromanstaff{{ fullname | escape | underline}} {%- if autotype is defined %} {%- set objtype = autotype.get(name) or objtype %} {%- endif %} .. auto{{ objtype }}:: {{ module}}.{{ objname }} :show-inheritance: {%- for item in ['__new__', '__init__'] %} {%- if item in members and item not in inherited_members %} {%- endif %} {%- endfor %} {%- for item in ['__new__', '__init__'] %} {%- if item in methods %} {%- set dummy = methods.remove(item) %} {%- endif %} {%- endfor %} {%- for item in inherited_members %} {%- if item in methods %} {%- set dummy = methods.remove(item) %} {%- endif %} {%- if item in attributes %} {%- set dummy = attributes.remove(item) %} {%- endif %} {%- endfor %} {%- set enumerations = [] %} {%- for item in members %} {%- if item not in inherited_members and item not in all_methods and item not in all_attributes %} {%- set dummy = enumerations.append(item) %} {%- endif %} {%- endfor %} {% block enumerations_documentation %} {%- if enumerations %} .. rubric:: Enumerations .. autosummary:: :toctree: {%+ for item in enumerations %} ~{{ fullname }}.{{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block methods_summary %} {%- if methods %} .. rubric:: Methods Summary .. autosummary:: {%+ for item in methods %} ~{{ fullname }}.{{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block attributes_summary %} {%- if attributes %} .. rubric:: Attributes Summary .. autosummary:: {%+ for item in attributes %} ~{{ fullname }}.{{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block methods_documentation %} {%- if methods %} .. rubric:: Methods Documentation {%+ for item in methods %} .. automethod:: {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block attributes_documentation %} {%- if attributes %} .. rubric:: Attributes Documentation {%+ for item in attributes %} .. autoattribute:: {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {# #} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/_templates/autosummary/module.rst0000644000076500000240000000233515133663436023565 0ustar00jromanstaff{{ fullname | escape | underline}} .. automodule:: {{ fullname }} {%- if synopsis is defined %} :synopsis: {{ synopsis.get(fullname, '') }} {%- endif %} {% block classes %} {%- if classes %} .. rubric:: {{ _('Classes') }} .. autosummary:: :toctree: {% for item in classes %} {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block exceptions %} {%- if exceptions %} .. rubric:: {{ _('Exceptions') }} .. autosummary:: :toctree: {% for item in exceptions %} {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block functions %} {%- if functions %} .. rubric:: {{ _('Functions') }} .. autosummary:: :toctree: {% for item in functions %} {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block attributes %} {%- if attributes %} .. rubric:: {{ _('Attributes') }} .. autosummary:: :toctree: {% for item in attributes %} {{ item }} {%- endfor %} {%- endif %} {%- endblock %} {% block modules %} {%- if modules %} .. rubric:: {{ _('Modules') }} .. autosummary:: :toctree: :recursive: {% for item in modules %} {{ item }} {%- endfor %} {%- endif %} {%- endblock %} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/_templates/layout.html0000644000076500000240000000057315133663436021365 0ustar00jromanstaff{% extends "!layout.html" %} {% macro menu_genindex() -%} {%- endmacro %} {% block menu %} {{ super() }} {%- if builder == 'html' %} {{ menu_genindex() }} {%- endif %} {%- if builder == 'dirhtml' %} {{ menu_genindex() }} {%- endif %} {% endblock %} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/apidoc.py0000644000076500000240000003734415133663436016644 0ustar00jromanstaffimport os import sys import inspect import textwrap from sphinx.util import logging logger = logging.getLogger(__name__) def is_cyfunction(obj): return type(obj).__name__ == 'cython_function_or_method' def is_function(obj): return inspect.isbuiltin(obj) or is_cyfunction(obj) or type(obj) is type(ord) def is_method(obj): return ( inspect.ismethoddescriptor(obj) or inspect.ismethod(obj) or is_cyfunction(obj) or type(obj) in ( type(str.index), type(str.__add__), type(str.__new__), ) ) def is_classmethod(obj): return inspect.isbuiltin(obj) or type(obj).__name__ in ( 'classmethod', 'classmethod_descriptor', ) def is_staticmethod(obj): return type(obj).__name__ in ('staticmethod',) def is_constant(obj): return isinstance(obj, (int, float, str, dict)) def is_datadescr(obj): return inspect.isdatadescriptor(obj) and not hasattr(obj, 'fget') def is_property(obj): return inspect.isdatadescriptor(obj) and hasattr(obj, 'fget') def is_class(obj): return inspect.isclass(obj) or type(obj) is type(int) def is_hidden(obj): return obj.__qualname__.startswith('_') class Lines(list): INDENT = ' ' * 4 level = 0 @property def add(self): return self @add.setter def add(self, lines): if lines is None: return if isinstance(lines, str): lines = textwrap.dedent(lines).strip().split('\n') indent = self.INDENT * self.level for line in lines: self.append(indent + line) def signature(obj, fail=True): doc = obj.__doc__ if not doc: if fail and not is_hidden(obj): logger.warning(f'Missing signature for {obj}') doc = f'{obj.__name__}: Any' sig = doc.partition('\n')[0].split('.', 1)[-1] return sig or None def docstring(obj, fail=True): doc = obj.__doc__ if not doc: if fail and not is_hidden(obj): logger.warning(f'Missing docstring for {obj}') doc = '' link = None sig = None cl = is_class(obj) if not cl: sig, _, doc = doc.partition('\n') doc, _, link = doc.rpartition('\n') doc = doc.strip() summary, _, docbody = doc.partition('\n') summary = summary.strip() docbody = textwrap.dedent(docbody).strip() # raise warning if docstring is not provided for a method if not summary and not is_function(obj) and is_method(obj): logger.warning(f'docstring: Missing summary for {obj}') # warnings for docstrings that are not compliant if len(summary) > 79: logger.warning(f'Summary for {obj} too long.') if docbody: if not summary.endswith('.'): logger.warning(f'Summary for {obj} does not end with period.') # FIXME lines = docbody.split('\n') for i, line in enumerate(lines): if len(line) > 79: logger.warning(f'Line {i} for documentation of {obj} too long.') if not cl: init = ( 'Collective.', 'Not collective.', 'Logically collective.', 'Neighbor-wise collective.', 'Collective the first time it is called.', 'Collective on the subcommunicator.', 'Collective on the subcommunicator (if v is given).', ) if lines[0] not in init: logger.warning(f'Unexpected collectiveness for {sig}\nFound {lines[0]}') if link: linktxt, _, link = link.rpartition(' ') linkloc = link.replace(':', '#L') # FIXME do we want to use a special section? # section = f'References\n----------`' section = '\n' linkbody = f':sources:`{linktxt} {link} <{linkloc}>`' linkbody = f'{section}\n{linkbody}' if docbody: docbody = f'{docbody}\n\n{linkbody}' else: docbody = linkbody if docbody: doc = f'"""{summary}\n\n{docbody}\n\n"""' else: doc = f'"""{summary}"""' return textwrap.indent(doc, Lines.INDENT) def visit_data(constant): name, value = constant typename = type(value).__name__ kind = 'Constant' if isinstance(value, int) else 'Object' init = f"_def({typename}, '{name}')" doc = f'#: {kind} ``{name}`` of type :class:`{typename}`' return f'{name}: {typename} = {init} {doc}\n' def visit_function(function): sig = signature(function) doc = docstring(function) body = Lines.INDENT + '...' return f'def {sig}:\n{doc}\n{body}\n' def visit_method(method): sig = signature(method) doc = docstring(method) body = Lines.INDENT + '...' return f'def {sig}:\n{doc}\n{body}\n' def visit_datadescr(datadescr, name=None): sig = signature(datadescr) doc = docstring(datadescr) name = sig.partition(':')[0].strip() or datadescr.__name__ rtype = sig.partition(':')[2].strip() or 'Any' sig = f'{name}(self) -> {rtype}' body = Lines.INDENT + '...' return f'@property\ndef {sig}:\n{doc}\n{body}\n' def visit_property(prop, name=None): sig = signature(prop.fget) name = name or prop.fget.__name__ rtype = sig.rsplit('->', 1)[-1].strip() sig = f'{name}(self) -> {rtype}' doc = f'"""{prop.__doc__}"""' doc = textwrap.indent(doc, Lines.INDENT) body = Lines.INDENT + '...' return f'@property\ndef {sig}:\n{doc}\n{body}\n' def visit_constructor(cls, name='__init__', args=None): init = name == '__init__' argname = cls.__mro__[-2].__name__.lower() argtype = cls.__name__ initarg = args or f'{argname}: Optional[{argtype}] = None' selfarg = 'self' if init else 'cls' rettype = 'None' if init else argtype arglist = f'{selfarg}, {initarg}' sig = f'{name}({arglist}) -> {rettype}' ret = '...' if init else 'return super().__new__(cls)' body = Lines.INDENT + ret return f'def {sig}:\n{body}' def visit_class(cls, outer=None, done=None): skip = { '__doc__', '__dict__', '__module__', '__weakref__', '__pyx_vtable__', '__lt__', '__le__', '__ge__', '__gt__', '__enum2str', # FIXME refactor implementation '_traceback_', # FIXME maybe refactor? } special = { '__len__': '__len__(self) -> int', '__bool__': '__bool__(self) -> bool', '__hash__': '__hash__(self) -> int', '__int__': '__int__(self) -> int', '__index__': '__int__(self) -> int', '__str__': '__str__(self) -> str', '__repr__': '__repr__(self) -> str', '__eq__': '__eq__(self, other: object) -> bool', '__ne__': '__ne__(self, other: object) -> bool', } qualname = cls.__name__ cls_name = cls.__name__ if outer is not None and cls_name.startswith(outer): cls_name = cls_name[len(outer) :] qualname = f'{outer}.{cls_name}' override = OVERRIDE.get(qualname, {}) done = set() if done is None else done lines = Lines() base = cls.__base__ if base is object: lines.add = f'class {cls_name}:' else: lines.add = f'class {cls_name}({base.__name__}):' lines.level += 1 lines.add = docstring(cls) for name in ('__new__', '__init__', '__hash__'): if name in cls.__dict__: done.add(name) dct = cls.__dict__ keys = list(dct.keys()) def dunder(name): return name.startswith('__') and name.endswith('__') def members(seq): for name in seq: if name in skip: continue if name in done: continue if dunder(name): if name not in special and name not in override: done.add(name) continue yield name for name in members(keys): attr = getattr(cls, name) if is_class(attr): done.add(name) lines.add = visit_class(attr, outer=cls_name) continue for name in members(keys): if name in override: done.add(name) lines.add = override[name] continue if name in special: done.add(name) sig = special[name] lines.add = f'def {sig}: ...' continue attr = getattr(cls, name) if is_method(attr): done.add(name) if name == attr.__name__: obj = dct[name] if is_classmethod(obj): lines.add = '@classmethod' elif is_staticmethod(obj): lines.add = '@staticmethod' lines.add = visit_method(attr) continue if is_datadescr(attr): done.add(name) lines.add = visit_datadescr(attr) continue if is_property(attr): done.add(name) lines.add = visit_property(attr, name) continue if is_constant(attr): done.add(name) lines.add = visit_data((name, attr)) continue leftovers = [name for name in keys if name not in done and name not in skip] if leftovers: raise RuntimeError(f'leftovers: {leftovers}') lines.level -= 1 return lines def visit_module(module, done=None): skip = { '__doc__', '__name__', '__loader__', '__spec__', '__file__', '__package__', '__builtins__', '__pyx_capi__', '__pyx_unpickle_Enum', # FIXME review 'COMM_NULL', 'COMM_SELF', 'COMM_WORLD', } done = set() if done is None else done lines = Lines() keys = list(module.__dict__.keys()) keys.sort(key=lambda name: name.startswith('_')) constants = [ (name, getattr(module, name)) for name in keys if all( ( name not in done and name not in skip, is_constant(getattr(module, name)), ) ) ] for _, value in constants: cls = type(value) name = cls.__name__ if name in done or name in skip: continue if cls.__module__ == module.__name__: done.add(name) lines.add = visit_class(cls) lines.add = '' for attr in constants: name, value = attr done.add(name) if name in OVERRIDE: lines.add = OVERRIDE[name] else: lines.add = visit_data((name, value)) if constants: lines.add = '' for name in keys: if name in done or name in skip: continue value = getattr(module, name) if is_class(value): done.add(name) if value.__name__ != name: continue if value.__module__ != module.__name__: continue lines.add = visit_class(value) lines.add = '' instances = [ (k, getattr(module, k)) for k in keys if all( ( k not in done and k not in skip, type(getattr(module, k)) is value, ) ) ] for attrname, attrvalue in instances: done.add(attrname) lines.add = visit_data((attrname, attrvalue)) if instances: lines.add = '' continue if is_function(value): done.add(name) if name == value.__name__: lines.add = visit_function(value) else: lines.add = f'{name} = {value.__name__}' continue lines.add = '' for name in keys: if name in done or name in skip: continue value = getattr(module, name) done.add(name) if name in OVERRIDE: lines.add = OVERRIDE[name] else: lines.add = visit_data((name, value)) leftovers = [name for name in keys if name not in done and name not in skip] if leftovers: raise RuntimeError(f'leftovers: {leftovers}') return lines IMPORTS = """ from __future__ import annotations import sys from typing import ( Any, Union, Optional, Callable, Sequence, ) if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self import numpy from numpy import dtype, ndarray from mpi4py.MPI import ( Intracomm, Datatype, Op, ) # ----------------------------------------------------------------------------- from petsc4py.PETSc import ( Object, Comm, NormType, Random, Viewer, Vec, Mat, KSP, ) # ----------------------------------------------------------------------------- class _dtype: def __init__(self, name): self.name = name def __repr__(self): return self.name IntType: dtype = _dtype('IntType') RealType: dtype = _dtype('RealType') ComplexType: dtype = _dtype('ComplexType') ScalarType: dtype = _dtype('ScalarType') """ HELPERS = """ class _Int(int): pass class _Str(str): pass class _Float(float): pass class _Dict(dict): pass def _repr(obj): try: return obj._name except AttributeError: return super(obj).__repr__() def _def(cls, name): if cls is int: cls = _Int if cls is str: cls = _Str if cls is float: cls = _Float if cls is dict: cls = _Dict obj = cls() obj._name = name if '__repr__' not in cls.__dict__: cls.__repr__ = _repr return obj """ OVERRIDE = {} TYPING = """ from .typing import * """ def visit_slepc4py_SLEPc(done=None): from slepc4py import SLEPc lines = Lines() lines.add = f'"""{SLEPc.__doc__}"""' lines.add = IMPORTS lines.add = '' lines.add = HELPERS lines.add = '' lines.add = visit_module(SLEPc) lines.add = '' lines.add = TYPING return lines def generate(filename): dirname = os.path.dirname(filename) os.makedirs(dirname, exist_ok=True) with open(filename, 'w') as f: for line in visit_slepc4py_SLEPc(): print(line, file=f) def load_module(filename, name=None): if name is None: name, _ = os.path.splitext(os.path.basename(filename)) module = type(sys)(name) module.__file__ = filename module.__package__ = name.rsplit('.', 1)[0] old = replace_module(module) with open(filename) as f: exec(f.read(), module.__dict__) # noqa: S102 restore_module(old) return module _sys_modules = {} def replace_module(module): name = module.__name__ if name in _sys_modules: raise RuntimeError(f'{name} in modules') _sys_modules[name] = sys.modules[name] sys.modules[name] = module return _sys_modules[name] def restore_module(module): name = module.__name__ if name not in _sys_modules: raise RuntimeError(f'{name} not in modules') sys.modules[name] = _sys_modules[name] del _sys_modules[name] def annotate(dest, source): try: dest.__annotations__ = source.__annotations__ except AttributeError: pass if isinstance(dest, type): for name in dest.__dict__.keys(): if hasattr(source, name): obj = getattr(dest, name) annotate(obj, getattr(source, name)) if isinstance(dest, type(sys)): for name in dir(dest): if hasattr(source, name): obj = getattr(dest, name) mod = getattr(obj, '__module__', None) if dest.__name__ == mod: annotate(obj, getattr(source, name)) for name in dir(source): if not hasattr(dest, name): setattr(dest, name, getattr(source, name)) OUTDIR = 'reference' if __name__ == '__main__': generate(os.path.join(OUTDIR, 'slepc4py.SLEPc.py')) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/changes.rst0000644000076500000240000000011415133663436017156 0ustar00jromanstaff:tocdepth: 1 .. _changes: CHANGES ======= .. include:: ../../CHANGES.rst ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/citing.rst0000644000076500000240000000132315133663436017026 0ustar00jromanstaffCitations ========= If SLEPc for Python has been significant to a project that leads to an academic publication, please acknowledge that fact by citing the project. * L. Dalcin, P. Kler, R. Paz, and A. Cosimo, *Parallel Distributed Computing using Python*, Advances in Water Resources, 34(9):1124-1139, 2011. https://doi.org/10.1016/j.advwatres.2011.04.013 * V. Hernandez, J.E. Roman, and V. Vidal, *SLEPc: A scalable and flexible toolkit for the solution of eigenvalue problems*, ACM Transactions on Mathematical Software, 31(3):351-362, 2005. https://doi.org/10.1145/1089014.1089019 There is also a list of `SLEPc-related references`_. .. _SLEPc-related references: https://slepc.upv.es/release/material ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/conf.py0000644000076500000240000004330615133663436016325 0ustar00jromanstaff# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import re import os import shutil import sys import subprocess import typing import datetime import importlib import sphobjinv import functools import pylit from sphinx import __version__ as sphinx_version from sphinx.ext.napoleon.docstring import NumpyDocstring from packaging.version import Version # apidoc sys.path.insert(0, os.path.abspath('.')) _today = datetime.datetime.now() # FIXME: allow building from build? # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information package = 'slepc4py' project = 'slepc4py' docdir = os.path.abspath(os.path.dirname(__file__)) topdir = os.path.abspath(os.path.join(docdir, *[os.path.pardir] * 2)) def pkg_version(): with open(os.path.join(topdir, 'src', package, '__init__.py')) as f: m = re.search(r"__version__\s*=\s*'(.*)'", f.read()) return m.groups()[0] def get_doc_branch(): release = 1 if topdir.endswith(os.path.join(os.path.sep, 'src', 'binding', package)): rootdir = os.path.abspath(os.path.join(topdir, *[os.path.pardir] * 3)) rootname = package.replace('4py', '') version_h = os.path.join(rootdir, 'include', f'{rootname}version.h') if os.path.exists(version_h) and os.path.isfile(version_h): release_macro = f'{rootname.upper()}_VERSION_RELEASE' version_re = re.compile(rf'#define\s+{release_macro}\s+([-]*\d+)') with open(version_h, 'r') as f: release = int(version_re.search(f.read()).groups()[0]) return 'release' if release else 'main' __project__ = 'SLEPc for Python' __author__ = 'Lisandro Dalcin' __copyright__ = f'{_today.year}, {__author__}' release = pkg_version() version = release.rsplit('.', 1)[0] # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', 'sphinx.ext.extlinks', ] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] default_role = 'any' pygments_style = 'tango' nitpicky = True nitpick_ignore = [ ('envvar', 'NUMPY_INCLUDE'), ('envvar', 'SLEPC_DIR'), ('envvar', 'PETSC_DIR'), ('envvar', 'PETSC_ARCH'), ('envvar', 'MACOSX_DEPLOYMENT_TARGET'), ('envvar', 'SDKROOT'), ('envvar', 'ARCHFLAGS'), ('py:class', 'ndarray'), # FIXME ('py:class', 'typing_extensions.Self'), ] nitpick_ignore_regex = [ (r'c:.*', r'MPI_.*'), (r'c:.*', r'Slepc.*'), (r'envvar', r'(LD_LIBRARY_)?PATH'), (r'envvar', r'(MPICH|OMPI|MPIEXEC)_.*'), ] toc_object_entries = False toc_object_entries_show_parents = 'hide' # python_use_unqualified_type_names = True autodoc_class_signature = 'separated' autodoc_typehints = 'description' autodoc_typehints_format = 'short' autodoc_mock_imports = [] autodoc_type_aliases = {} autosummary_context = { 'synopsis': {}, 'autotype': {}, } suppress_warnings = [] if Version(sphinx_version) >= Version( '7.4' ): # https://github.com/sphinx-doc/sphinx/issues/12589 suppress_warnings.append('autosummary.import_cycle') # Links depends on the actual branch -> release or main www = f'https://gitlab.com/slepc/slepc/-/tree/{get_doc_branch()}' extlinks = {'sources': (f'{www}/src/binding/slepc4py/src/%s', '%s')} napoleon_preprocess_types = True try: import sphinx_rtd_theme if 'sphinx_rtd_theme' not in extensions: extensions.append('sphinx_rtd_theme') except ImportError: sphinx_rtd_theme = None intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'numpy': ('https://numpy.org/doc/stable/', None), 'numpydoc': ('https://numpydoc.readthedocs.io/en/latest/', None), 'mpi4py': ('https://mpi4py.readthedocs.io/en/stable/', None), 'pyopencl': ('https://documen.tician.de/pyopencl/', None), 'dlpack': ('https://dmlc.github.io/dlpack/latest/', None), 'petsc': ('https://petsc.org/release/', None), 'petsc4py': ('https://petsc.org/release/petsc4py/', None), 'slepc': ('https://slepc.upv.es/release/', None), } intersphinx_resolve_self = 'slepc' def _mangle_petsc_intersphinx(): """Preprocess the keys in PETSc's intersphinx inventory. PETSc have intersphinx keys of the form: manualpages/Vec/VecShift instead of: petsc.VecShift This function downloads their object inventory and strips the leading path elements so that references to PETSc names actually resolve.""" website = intersphinx_mapping['petsc'][0].partition('/release/')[0] branch = get_doc_branch() doc_url = f'{website}/{branch}/' inventory_url = f'{doc_url}objects.inv' print('Using PETSC inventory from ' + inventory_url) inventory = sphobjinv.Inventory(url=inventory_url) print(inventory) for obj in inventory.objects: if obj.name.startswith('manualpages'): obj.name = 'petsc.' + '/'.join(obj.name.split('/')[2:]) obj.role = 'class' obj.domain = 'py' new_inventory_filename = 'petsc_objects.inv' sphobjinv.writebytes( new_inventory_filename, sphobjinv.compress(inventory.data_file(contract=True)) ) intersphinx_mapping['petsc'] = (doc_url, new_inventory_filename) def _mangle_slepc_intersphinx(): """Preprocess the keys in SLEPc's intersphinx inventory. SLEPc have intersphinx keys of the form: manualpages/BV/BVGetSizes instead of: slepc.BVGetSizes This function downloads their object inventory and strips the leading path elements so that references to SLEPc names actually resolve.""" website = intersphinx_mapping['slepc'][0].partition('/release/')[0] branch = get_doc_branch() doc_url = f'{website}/{branch}/' inventory_url = None if 'LOC' in os.environ: inventory_file = os.path.join(os.environ['LOC'], 'objects.inv') inventory_url = 'file://' + inventory_file if not os.path.isfile(inventory_file): print('SLEPC inventory not found at ' + inventory_url) print('Check code for errors') inventory_url = None if inventory_url is None: inventory_url = f'{doc_url}objects.inv' print('Using SLEPC inventory from ' + inventory_url) inventory = sphobjinv.Inventory(url=inventory_url) print(inventory) for obj in inventory.objects: if obj.name.startswith('manualpages'): obj.name = 'slepc.' + '/'.join(obj.name.split('/')[2:]) obj.role = 'class' obj.domain = 'py' new_inventory_filename = 'slepc_objects.inv' sphobjinv.writebytes( new_inventory_filename, sphobjinv.compress(inventory.data_file(contract=True)) ) intersphinx_mapping['slepc'] = (doc_url, new_inventory_filename) _mangle_petsc_intersphinx() _mangle_slepc_intersphinx() def _setup_mpi4py_typing(): pkg = type(sys)('mpi4py') mod = type(sys)('mpi4py.MPI') mod.__package__ = pkg.__name__ sys.modules[pkg.__name__] = pkg sys.modules[mod.__name__] = mod for clsname in ( 'Intracomm', 'Datatype', 'Op', ): cls = type(clsname, (), {}) cls.__module__ = mod.__name__ setattr(mod, clsname, cls) def _patch_domain_python(): from sphinx.domains.python import PythonDomain PythonDomain.object_types['data'].roles += ('class',) def _setup_autodoc(app): from sphinx.ext import autodoc from sphinx.util import inspect from sphinx.util import typing # def stringify_annotation(annotation, *p, **kw): qualname = getattr(annotation, '__qualname__', '') module = getattr(annotation, '__module__', '') args = getattr(annotation, '__args__', None) if module == 'builtins' and qualname and args is not None: args = ', '.join(stringify_annotation(a, *p, **kw) for a in args) return f'{qualname}[{args}]' return stringify_annotation_orig(annotation, *p, **kw) try: stringify_annotation_orig = typing.stringify_annotation inspect.stringify_annotation = stringify_annotation typing.stringify_annotation = stringify_annotation autodoc.stringify_annotation = stringify_annotation autodoc.typehints.stringify_annotation = stringify_annotation except AttributeError: stringify_annotation_orig = typing.stringify inspect.stringify_annotation = stringify_annotation typing.stringify = stringify_annotation autodoc.stringify_typehint = stringify_annotation inspect.TypeAliasForwardRef.__repr__ = lambda self: self.name # class ClassDocumenterMixin: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.config.autodoc_class_signature == 'separated': members = self.options.members special_members = self.options.special_members if special_members is not None: for name in ('__new__', '__init__'): if name in members: members.remove(name) if name in special_members: special_members.remove(name) class ClassDocumenter( ClassDocumenterMixin, autodoc.ClassDocumenter, ): pass class ExceptionDocumenter( ClassDocumenterMixin, autodoc.ExceptionDocumenter, ): pass app.add_autodocumenter(ClassDocumenter, override=True) app.add_autodocumenter(ExceptionDocumenter, override=True) def _monkey_patch_returns(): """Rewrite the role of names in "Returns" sections. This is needed because Napoleon uses ``:class:`` for the return types and this does not work with type aliases like ``ArrayScalar``. To resolve this we swap ``:class:`` for ``:any:``. """ _parse_returns_section = NumpyDocstring._parse_returns_section @functools.wraps(NumpyDocstring._parse_returns_section) def wrapper(*args, **kwargs): out = _parse_returns_section(*args, **kwargs) for role in (':py:class:', ':class:'): out = [line.replace(role, ':any:') for line in out] return out NumpyDocstring._parse_returns_section = wrapper def _monkey_patch_see_also(): """Rewrite the role of names in "see also" sections. Napoleon uses :obj: for all names found in "see also" sections but we need :all: so that references to labels work.""" _parse_numpydoc_see_also_section = NumpyDocstring._parse_numpydoc_see_also_section @functools.wraps(NumpyDocstring._parse_numpydoc_see_also_section) def wrapper(*args, **kwargs): out = _parse_numpydoc_see_also_section(*args, **kwargs) for role in (':py:obj:', ':obj:'): out = [line.replace(role, ':any:') for line in out] return out NumpyDocstring._parse_numpydoc_see_also_section = wrapper def _apply_monkey_patches(): """Modify Napoleon types after parsing to make references work.""" _monkey_patch_returns() _monkey_patch_see_also() _apply_monkey_patches() def _process_demos(*demos): # Convert demo .py files to rst. Also copy the .py file so it can be # linked from the demo rst file. try: os.mkdir('demo') except FileExistsError: pass for demo in demos: demo_dir = os.path.join('demo', os.path.dirname(demo)) demo_src = os.path.join(os.pardir, os.pardir, 'demo', demo) try: os.mkdir(demo_dir) except FileExistsError: pass with open(demo_src, 'r') as infile: with open( os.path.join(os.path.join('demo', os.path.splitext(demo)[0] + '.rst')), 'w', ) as outfile: converter = pylit.Code2Text(infile) outfile.write(str(converter)) demo_copy_name = os.path.join(demo_dir, os.path.basename(demo)) shutil.copyfile(demo_src, demo_copy_name) html_static_path.append(demo_copy_name) with open(os.path.join('demo', 'demo.rst'), 'w') as demofile: demofile.write(""" .. _demos: slepc4py demos ============== .. toctree:: :maxdepth: 1 """) for demo in demos: demofile.write(' ' + os.path.splitext(demo)[0] + '\n') demofile.write('\n') html_static_path = ['_static'] html_css_files = [ # relative to the html_static_path 'css/slepc.css', ] _process_demos( 'ex1.py', 'ex2.py', 'ex3.py', 'ex4.py', 'ex5.py', 'ex6.py', 'ex7.py', 'ex8.py', 'ex9.py', 'ex10.py', 'ex11.py', 'ex12.py', 'ex13.py', 'ex14.py', ) def setup(app): if 'PETSC_DIR' not in os.environ: print('\nUnable to build the documentation, PETSC_DIR environment variable is not set') print('\nPlease configure PETSc and SLEPc before building the documentation') raise Exception('PETSC_DIR not set') if 'PETSC_ARCH' not in os.environ: print('\nUnable to build the documentation, PETSC_ARCH environment variable is not set') print('\nPlease configure PETSc and SLEPc before building the documentation') raise Exception('PETSC_ARCH not set') else: # We know where we are, don't we? app.slepc_dir = os.path.abspath('../../../') app.petsc_dir = os.path.abspath(os.environ['PETSC_DIR']) app.petsc_arch = os.environ['PETSC_ARCH'] sys.path.insert(0, os.path.abspath(app.petsc_dir +'/' +os.environ['PETSC_ARCH'] +'/lib')) sys.path.insert(0, os.path.abspath(app.slepc_dir +'/' +os.environ['PETSC_ARCH'] +'/lib')) print(sys.path) _setup_mpi4py_typing() _patch_domain_python() _monkey_patch_returns() _monkey_patch_see_also() _setup_autodoc(app) try: from slepc4py import SLEPc except ImportError as e: print('ImportError: slepc4py '+str(e)) autodoc_mock_imports.append('SLEPc') return sys_dwb = sys.dont_write_bytecode sys.dont_write_bytecode = True import apidoc sys.dont_write_bytecode = sys_dwb name = SLEPc.__name__ here = os.path.abspath(os.path.dirname(__file__)) outdir = os.path.join(here, apidoc.OUTDIR) source = os.path.join(outdir, f'{name}.py') print('source: {}'.format(source)) getmtime = os.path.getmtime generate = ( not os.path.exists(source) or getmtime(source) < getmtime(SLEPc.__file__) or getmtime(source) < getmtime(apidoc.__file__) ) if generate: apidoc.generate(source) module = apidoc.load_module(source) apidoc.replace_module(module) modules = [ 'slepc4py', ] typing_overload = typing.overload typing.overload = lambda arg: arg for name in modules: mod = importlib.import_module(name) ann = apidoc.load_module(f'{mod.__file__}i', name) apidoc.annotate(mod, ann) typing.overload = typing_overload from slepc4py import typing as tp for attr in tp.__all__: autodoc_type_aliases[attr] = f'~slepc4py.typing.{attr}' # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pydata_sphinx_theme' html_theme_options = { 'navigation_with_keys': True, 'footer_end': ['theme-version', 'last-updated'], 'header_links_before_dropdown': 10, # before "more" } git_describe_version = ( subprocess.check_output(['git', 'describe', '--always']).strip().decode('utf-8') # noqa: S603, S607 ) html_last_updated_fmt = r'%Y-%m-%dT%H:%M:%S%z (' + git_describe_version + ')' # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = f'{package}-man' # -- Options for LaTeX output --------------------------------------------- # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', f'{package}.tex', __project__, __author__, 'howto'), ] latex_elements = { 'papersize': 'a4', } # -- Options for manual page output --------------------------------------- # (source start file, name, description, authors, manual section). man_pages = [('index', package, __project__, [__author__], 3)] # -- Options for Texinfo output ------------------------------------------- # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( 'index', package, __project__, __author__, package, f'{__project__}.', 'Miscellaneous', ), ] # -- Options for Epub output ---------------------------------------------- # Output file base name for ePub builder. epub_basename = package ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4970214 slepc4py-3.24.2/docs/source/demo/0000755000076500000240000000000015133664270015741 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/demo.rst0000644000076500000240000000026215133664232017415 0ustar00jromanstaff .. _demos: slepc4py demos ============== .. toctree:: :maxdepth: 1 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 ex9 ex10 ex11 ex12 ex13 ex14 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex1.py0000644000076500000240000001763615133664232017023 0ustar00jromanstaff# ex1.py: Standard symmetric eigenproblem for the 1-D Laplacian # ============================================================= # # This example computes eigenvalues and eigenvectors of the discrete Laplacian # on a one-dimensional domain with finite differences. # # The full source code for this demo can be `downloaded here # <../_static/ex1.py>`__. # The first thing to do is initialize the libraries. This is normally not # required, as it is done automatically at import time. However, if you want to # gain access to the facilities for setting command-line options, the # following lines must be executed by the main script prior to any petsc4py or # slepc4py calls: import sys, slepc4py slepc4py.init(sys.argv) # Next, we have to import the relevant modules. Normally, both PETSc and SLEPc # modules have to be imported in all slepc4py programs. It may be useful to # import NumPy as well: from petsc4py import PETSc from slepc4py import SLEPc import numpy # At this point, we can use any petsc4py and slepc4py operations. For instance, # the following lines allow the user to specify an integer command-line # argument ``n`` with a default value of 30 (see below for example usage # of command-line options): opts = PETSc.Options() n = opts.getInt('n', 30) # It is necessary to build a matrix to define an eigenproblem (or two in the # case of generalized eigenproblems). The following fragment of code creates # the matrix object and then fills the non-zero elements one by one. The matrix # of this particular example is tridiagonal, with value 2 in the diagonal, and # -1 in off-diagonal positions. See petsc4py documentation for details about # matrix objects: A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() # first row if rstart == 0: A[0, :2] = [2, -1] rstart += 1 # last row if rend == n: A[n-1, -2:] = [-1, 2] rend -= 1 # other rows for i in range(rstart, rend): A[i, i-1:i+2] = [-1, 2, -1] A.assemble() # The solver object is created in a similar way as other objects in petsc4py: E = SLEPc.EPS(); E.create() # Once the object is created, the eigenvalue problem must be specified. At # least one matrix must be provided. The problem type must be indicated as # well, in this case it is HEP (Hermitian eigenvalue problem). Apart from # these, other settings could be provided here (for instance, the tolerance for # the computation). After all options have been set, the user should call the # `setFromOptions() ` operation, so that any options # specified at run time in the command line are passed to the solver object: E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) history = [] def monitor(eps, its, nconv, eig, err): if nconv` method will run the selected # eigensolver, keeping the solution stored internally: E.solve() # Once the computation has finished, we are ready to print the results. First, # some informative data can be retrieved from the solver object: Print = PETSc.Sys.Print Print() Print("******************************") Print("*** SLEPc Solution Results ***") Print("******************************") Print() its = E.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) eps_type = E.getType() Print( "Solution method: %s" % eps_type ) nev, ncv, mpd = E.getDimensions() Print( "Number of requested eigenvalues: %d" % nev ) tol, maxit = E.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) # For retrieving the solution, it is necessary to find out how many eigenpairs # have converged to the requested precision: nconv = E.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) # For each of the ``nconv`` eigenpairs, we can retrieve the eigenvalue ``k``, # and the eigenvector, which is represented by means of two petsc4py vectors # ``vr`` and ``vi`` (the real and imaginary part of the eigenvector, since for # real matrices the eigenvalue and eigenvector may be complex). In this # example we know that both the eigenvalue and eigenvector are real, so only # one vector ``v`` is needed. We also compute the corresponding relative errors # in order to make sure that the computed solution is indeed correct: if nconv > 0: # Create the results vectors v, _ = A.createVecs() # Print() Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, v) error = E.computeError(i) Print( " %12f %12g" % (k, error) ) Print() # # Example of command-line usage # ----------------------------- # # Now we illustrate how to specify command-line options in order to extract the # full potential of slepc4py. # # A simple execution of the ``demo/ex1.py`` script will result in the following # output: # # .. code-block:: console # # $ python demo/ex1.py # # ****************************** # *** SLEPc Solution Results *** # ****************************** # # Number of iterations of the method: 4 # Solution method: krylovschur # Number of requested eigenvalues: 1 # Stopping condition: tol=1e-07, maxit=100 # Number of converged eigenpairs 4 # # k ||Ax-kx||/||kx|| # ----------------- ------------------ # 3.989739 5.76012e-09 # 3.959060 1.41957e-08 # 3.908279 6.74118e-08 # 3.837916 8.34269e-08 # # For specifying different setting for the solver parameters, we can use SLEPc # command-line options with the ``-eps`` prefix. For instance, to change the number # of requested eigenvalues and the tolerance: # # .. code-block:: console # # $ python demo/ex1.py -eps_nev 10 -eps_tol 1e-11 # # The method used by the solver object can also be set at run time: # # .. code-block:: console # # $ python demo/ex1.py -eps_type subspace # # All the above settings can also be changed within the source code by making # use of the appropriate slepc4py method. Since options can be set from within # the code and the command-line, it is often useful to view the particular # settings that are currently being used: # # .. code-block:: console # # $ python demo/ex1.py -eps_view # # EPS Object: 1 MPI process # type: krylovschur # 50% of basis vectors kept after restart # using the locking variant # problem type: symmetric eigenvalue problem # selected portion of the spectrum: largest eigenvalues in magnitude # number of eigenvalues (nev): 1 # number of column vectors (ncv): 16 # maximum dimension of projected problem (mpd): 16 # maximum number of iterations: 100 # tolerance: 1e-08 # convergence test: relative to the eigenvalue # BV Object: 1 MPI process # type: mat # 17 columns of global length 30 # orthogonalization method: classical Gram-Schmidt # orthogonalization refinement: if needed (eta: 0.7071) # block orthogonalization method: GS # doing matmult as a single matrix-matrix product # DS Object: 1 MPI process # type: hep # solving the problem with: Implicit QR method (_steqr) # ST Object: 1 MPI process # type: shift # shift: 0 # number of matrices: 1 # # Note that for computing eigenvalues of smallest magnitude we can use the # option ``-eps_smallest_magnitude``, but for interior eigenvalues things are # not so straightforward. One possibility is to try with harmonic extraction, # for instance to get the eigenvalues closest to 0.6: # # .. code-block:: console # # $ python demo/ex1.py -eps_harmonic -eps_target 0.6 # # Depending on the problem, harmonic extraction may fail to converge. In those # cases, it is necessary to specify a spectral transformation other than the # default. In the command-line, this is indicated with the ``-st_`` prefix. For # example, shift-and-invert with a value of the shift equal to 0.6 would be: # # .. code-block:: console # # $ python demo/ex1.py -st_type sinvert -eps_target 0.6 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex1.rst0000644000076500000240000001746615133664232017204 0ustar00jromanstaffex1.py: Standard symmetric eigenproblem for the 1-D Laplacian ============================================================= This example computes eigenvalues and eigenvectors of the discrete Laplacian on a one-dimensional domain with finite differences. The full source code for this demo can be `downloaded here <../_static/ex1.py>`__. The first thing to do is initialize the libraries. This is normally not required, as it is done automatically at import time. However, if you want to gain access to the facilities for setting command-line options, the following lines must be executed by the main script prior to any petsc4py or slepc4py calls: :: import sys, slepc4py slepc4py.init(sys.argv) Next, we have to import the relevant modules. Normally, both PETSc and SLEPc modules have to be imported in all slepc4py programs. It may be useful to import NumPy as well: :: from petsc4py import PETSc from slepc4py import SLEPc import numpy At this point, we can use any petsc4py and slepc4py operations. For instance, the following lines allow the user to specify an integer command-line argument ``n`` with a default value of 30 (see below for example usage of command-line options): :: opts = PETSc.Options() n = opts.getInt('n', 30) It is necessary to build a matrix to define an eigenproblem (or two in the case of generalized eigenproblems). The following fragment of code creates the matrix object and then fills the non-zero elements one by one. The matrix of this particular example is tridiagonal, with value 2 in the diagonal, and -1 in off-diagonal positions. See petsc4py documentation for details about matrix objects: :: A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() # first row if rstart == 0: A[0, :2] = [2, -1] rstart += 1 # last row if rend == n: A[n-1, -2:] = [-1, 2] rend -= 1 # other rows for i in range(rstart, rend): A[i, i-1:i+2] = [-1, 2, -1] A.assemble() The solver object is created in a similar way as other objects in petsc4py: :: E = SLEPc.EPS(); E.create() Once the object is created, the eigenvalue problem must be specified. At least one matrix must be provided. The problem type must be indicated as well, in this case it is HEP (Hermitian eigenvalue problem). Apart from these, other settings could be provided here (for instance, the tolerance for the computation). After all options have been set, the user should call the `setFromOptions() ` operation, so that any options specified at run time in the command line are passed to the solver object: :: E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) history = [] def monitor(eps, its, nconv, eig, err): if nconv` method will run the selected eigensolver, keeping the solution stored internally: :: E.solve() Once the computation has finished, we are ready to print the results. First, some informative data can be retrieved from the solver object: :: Print = PETSc.Sys.Print Print() Print("******************************") Print("*** SLEPc Solution Results ***") Print("******************************") Print() its = E.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) eps_type = E.getType() Print( "Solution method: %s" % eps_type ) nev, ncv, mpd = E.getDimensions() Print( "Number of requested eigenvalues: %d" % nev ) tol, maxit = E.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) For retrieving the solution, it is necessary to find out how many eigenpairs have converged to the requested precision: :: nconv = E.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) For each of the ``nconv`` eigenpairs, we can retrieve the eigenvalue ``k``, and the eigenvector, which is represented by means of two petsc4py vectors ``vr`` and ``vi`` (the real and imaginary part of the eigenvector, since for real matrices the eigenvalue and eigenvector may be complex). In this example we know that both the eigenvalue and eigenvector are real, so only one vector ``v`` is needed. We also compute the corresponding relative errors in order to make sure that the computed solution is indeed correct: :: if nconv > 0: # Create the results vectors v, _ = A.createVecs() # Print() Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, v) error = E.computeError(i) Print( " %12f %12g" % (k, error) ) Print() Example of command-line usage ----------------------------- Now we illustrate how to specify command-line options in order to extract the full potential of slepc4py. A simple execution of the ``demo/ex1.py`` script will result in the following output: .. code-block:: console $ python demo/ex1.py ****************************** *** SLEPc Solution Results *** ****************************** Number of iterations of the method: 4 Solution method: krylovschur Number of requested eigenvalues: 1 Stopping condition: tol=1e-07, maxit=100 Number of converged eigenpairs 4 k ||Ax-kx||/||kx|| ----------------- ------------------ 3.989739 5.76012e-09 3.959060 1.41957e-08 3.908279 6.74118e-08 3.837916 8.34269e-08 For specifying different setting for the solver parameters, we can use SLEPc command-line options with the ``-eps`` prefix. For instance, to change the number of requested eigenvalues and the tolerance: .. code-block:: console $ python demo/ex1.py -eps_nev 10 -eps_tol 1e-11 The method used by the solver object can also be set at run time: .. code-block:: console $ python demo/ex1.py -eps_type subspace All the above settings can also be changed within the source code by making use of the appropriate slepc4py method. Since options can be set from within the code and the command-line, it is often useful to view the particular settings that are currently being used: .. code-block:: console $ python demo/ex1.py -eps_view EPS Object: 1 MPI process type: krylovschur 50% of basis vectors kept after restart using the locking variant problem type: symmetric eigenvalue problem selected portion of the spectrum: largest eigenvalues in magnitude number of eigenvalues (nev): 1 number of column vectors (ncv): 16 maximum dimension of projected problem (mpd): 16 maximum number of iterations: 100 tolerance: 1e-08 convergence test: relative to the eigenvalue BV Object: 1 MPI process type: mat 17 columns of global length 30 orthogonalization method: classical Gram-Schmidt orthogonalization refinement: if needed (eta: 0.7071) block orthogonalization method: GS doing matmult as a single matrix-matrix product DS Object: 1 MPI process type: hep solving the problem with: Implicit QR method (_steqr) ST Object: 1 MPI process type: shift shift: 0 number of matrices: 1 Note that for computing eigenvalues of smallest magnitude we can use the option ``-eps_smallest_magnitude``, but for interior eigenvalues things are not so straightforward. One possibility is to try with harmonic extraction, for instance to get the eigenvalues closest to 0.6: .. code-block:: console $ python demo/ex1.py -eps_harmonic -eps_target 0.6 Depending on the problem, harmonic extraction may fail to converge. In those cases, it is necessary to specify a spectral transformation other than the default. In the command-line, this is indicated with the ``-st_`` prefix. For example, shift-and-invert with a value of the shift equal to 0.6 would be: .. code-block:: console $ python demo/ex1.py -st_type sinvert -eps_target 0.6 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex10.py0000644000076500000240000002170715133664232017075 0ustar00jromanstaff# ex10.py: Laplace problem using the Proper Orthogonal Decomposition # ================================================================== # # This example program solves the Laplace problem using the Proper Orthogonal # Decomposition (POD) reduced-order modeling technique. For a full description # of the technique the reader is referred to [1]_, [2]_. # # The method is split into an offline (computationally intensive) and an online # (computationally cheap) phase. This has many applications including real-time # simulation, uncertainty quantification and inverse problems, where similar # models must be evaluated quickly and many times. # # Offline phase: # # 1. A set of solution snapshots of the 1D Laplace problem in the full # problem space are constructed and assembled into the columns of a dense # matrix :math:`S`. # 2. A standard eigenvalue decomposition is performed on the # matrix :math:`S^T S`. # 3. The eigenvectors and eigenvalues are projected back to the # original eigenvalue problem :math:`S`. # 4. The leading eigenvectors then form the POD basis. # # Online phase: # # 1. The operator corresponding to the discrete Laplacian is # projected onto the POD basis. # 2. The operator corresponding to the right-hand side is # projected onto the POD basis. # 3. The reduced (dense) problem expressed in the POD basis is solved. # 4. The reduced solution is projected back to the full # problem space. # # Contributed by: Elisa Schenone, Jack S. Hale. # # The full source code for this demo can be `downloaded here # <../_static/ex10.py>`__. # Initialization is similar to previous examples, but importing some # additional modules. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy import random import math # This function builds the discrete Laplacian operator in 1 dimension # with homogeneous Dirichlet boundary conditions. def construct_operator(m): # Create matrix for 1D Laplacian operator A = PETSc.Mat().create(PETSc.COMM_SELF) A.setSizes([m, m]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = 2.0/hx offdx = -1.0/hx Istart, Iend = A.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): A[i, i] = diagv if i > 1: A[i, i - 1] = offdx if i < m - 2: A[i, i + 1] = offdx else: A[i, i] = 1. A.assemble() return A # Set bell-shape function as the solution of the Laplacian problem in # 1 dimension with homogeneous Dirichlet boundary conditions and # compute the associated discrete RHS. def set_problem_rhs(m): # Create 1D mass matrix operator M = PETSc.Mat().create(PETSc.COMM_SELF) M.setSizes([m, m]) M.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = hx/3 offdx = hx/6 Istart, Iend = M.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): M[i, i] = 2*diagv else: M[i, i] = diagv if i > 1: M[i, i - 1] = offdx if i < m - 2: M[i, i + 1] = offdx M.assemble() x_0 = 0.3 x_f = 0.7 mu = x_0 + (x_f - x_0)*random.random() sigma = 0.1**2 uex, f = M.createVecs() for j in range(Istart, Iend): value = 2/sigma * math.exp(-(hx*j - mu)**2/sigma) * (1 - 2/sigma * (hx*j - mu)**2 ) f.setValue(j, value) value = math.exp(-(hx*j - mu)**2/sigma) uex.setValue(j, value) f.assemble() uex.assemble() RHS = f.duplicate() M.mult(f, RHS) RHS.setValue(0, 0.) RHS.setValue(m-1, 0.) RHS.assemble() return RHS, uex # Solve 1D Laplace problem with FEM. def solve_laplace_problem(A, RHS): u = A.createVecs('right') r, c = A.getOrdering("natural") A.factorILU(r, c) A.solve(RHS, u) A.setUnfactored() return u # Solve 1D Laplace problem with POD (dense matrix). def solve_laplace_problem_pod(A, RHS, u): ksp = PETSc.KSP().create(PETSc.COMM_SELF) ksp.setOperators(A) ksp.setType('preonly') pc = ksp.getPC() pc.setType('none') ksp.setFromOptions() ksp.solve(RHS, u) return u # Set ``N`` solution of the 1D Laplace problem as columns of a matrix # (snapshot matrix). # # Note: For simplicity we do not perform a linear solve, but use # some analytical solution: # :math:`z(x) = \exp(-(x - \mu)^2 / \sigma)`. def construct_snapshot_matrix(A, N, m): snapshots = PETSc.Mat().create(PETSc.COMM_SELF) snapshots.setSizes([m, N]) snapshots.setType('seqdense') Istart, Iend = snapshots.getOwnershipRange() hx = 1.0/(m - 1) x_0 = 0.3 x_f = 0.7 sigma = 0.1**2 for i in range(N): mu = x_0 + (x_f - x_0)*random.random() for j in range(Istart, Iend): value = math.exp(-(hx*j - mu)**2/sigma) snapshots.setValue(j, i, value) snapshots.assemble() return snapshots # Solve the eigenvalue problem: the eigenvectors of this problem form the # POD basis. def solve_eigenproblem(snapshots, N): print('Solving POD basis eigenproblem using eigensolver...') Es = SLEPc.EPS() Es.create(PETSc.COMM_SELF) Es.setDimensions(N) Es.setProblemType(SLEPc.EPS.ProblemType.NHEP) Es.setTolerances(1.0e-8, 500); Es.setKrylovSchurRestart(0.6) Es.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_REAL) Es.setOperators(snapshots) Es.setFromOptions() Es.solve() print('Solved POD basis eigenproblem.') return Es # Function to project :math:`S^TS` eigenvectors to :math:`S` eigenvectors. def project_STS_eigenvectors_to_S_eigenvectors(bvEs, S): sizes = S.getSizes()[0] N = bvEs.getActiveColumns()[1] bv = SLEPc.BV().create(PETSc.COMM_SELF) bv.setSizes(sizes, N) bv.setActiveColumns(0, N) bv.setFromOptions() tmpvec2 = S.createVecs('left') for i in range(N): tmpvec = bvEs.getColumn(i) S.mult(tmpvec, tmpvec2) bv.insertVec(i, tmpvec2) bvEs.restoreColumn(i, tmpvec) return bv # Function to project the reduced space to the full space. def project_reduced_to_full_space(alpha, bv): uu = bv.getColumn(0) uPOD = uu.duplicate() bv.restoreColumn(0,uu) scatter, Wr = PETSc.Scatter.toAll(alpha) scatter.begin(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) scatter.end(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) PODcoeff = Wr.getArray(readonly=1) bv.multVec(1., 0., uPOD, PODcoeff) return uPOD # The main function realizes the full procedure. def main(): problem_dim = 200 num_snapshots = 30 num_pod_basis_functions = 8 assert(num_pod_basis_functions <= num_snapshots) A = construct_operator(problem_dim) S = construct_snapshot_matrix(A, num_snapshots, problem_dim) # Instead of solving the SVD of S, we solve the standard # eigenvalue problem on S.T*S STS = S.transposeMatMult(S) Es = solve_eigenproblem(STS, num_pod_basis_functions) nconv = Es.getConverged() print('Number of converged eigenvalues: %i' % nconv) Es.view() # get the EPS solution in a BV object bvEs = Es.getBV() bvEs.setActiveColumns(0, num_pod_basis_functions) # set the bv POD basis bv = project_STS_eigenvectors_to_S_eigenvectors(bvEs, S) # rescale the eigenvectors for i in range(num_pod_basis_functions): ll = Es.getEigenvalue(i) print('Eigenvalue '+str(i)+': '+str(ll.real)) bv.scaleColumn(i,1.0/math.sqrt(ll.real)) print('--------------------------------') # Verify that the active columns of bv form an orthonormal subspace, i.e. that X^H*X = Id print('Check that bv.dot(bv) is close to the identity matrix') XtX = bv.dot(bv) XtX.view() XtX_array = XtX.getDenseArray() n,m = XtX_array.shape assert numpy.allclose(XtX_array, numpy.eye(n, m)) print('--------------------------------') print('Solve the problem with POD') # Project the linear operator A Ared = bv.matProject(A,bv) # Set the RHS and the exact solution RHS, uex = set_problem_rhs(problem_dim) # Project the RHS on the POD basis RHSred = PETSc.Vec().createWithArray(bv.dotVec(RHS)) # Solve the problem with POD alpha = Ared.createVecs('right') alpha = solve_laplace_problem_pod(Ared,RHSred,alpha) # Project the POD solution back to the FE space uPOD = project_reduced_to_full_space(alpha, bv) # Compute the L2 and Linf norm of the error error = uex.copy() error.axpy(-1,uPOD) errorL2 = math.sqrt(error.dot(error).real) print('The L2-norm of the error is: '+str(errorL2)) print("NORMAL END") if __name__ == '__main__': main() # .. [1] K. Kunisch and S. Volkwein. Galerkin proper orthogonal decomposition methods # for a general equation in fluid dynamics. SIAM Journal on Numerical Analysis, # 40(2):492-515, 2003. # .. [2] S. Volkwein, Optimal control of a phase-field model using the proper orthogonal # decomposition, Z. Angew. Math. Mech., 81:83-97, 2001. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex10.rst0000644000076500000240000002236215133664232017253 0ustar00jromanstaffex10.py: Laplace problem using the Proper Orthogonal Decomposition ================================================================== This example program solves the Laplace problem using the Proper Orthogonal Decomposition (POD) reduced-order modeling technique. For a full description of the technique the reader is referred to [1]_, [2]_. The method is split into an offline (computationally intensive) and an online (computationally cheap) phase. This has many applications including real-time simulation, uncertainty quantification and inverse problems, where similar models must be evaluated quickly and many times. Offline phase: 1. A set of solution snapshots of the 1D Laplace problem in the full problem space are constructed and assembled into the columns of a dense matrix :math:`S`. 2. A standard eigenvalue decomposition is performed on the matrix :math:`S^T S`. 3. The eigenvectors and eigenvalues are projected back to the original eigenvalue problem :math:`S`. 4. The leading eigenvectors then form the POD basis. Online phase: 1. The operator corresponding to the discrete Laplacian is projected onto the POD basis. 2. The operator corresponding to the right-hand side is projected onto the POD basis. 3. The reduced (dense) problem expressed in the POD basis is solved. 4. The reduced solution is projected back to the full problem space. Contributed by: Elisa Schenone, Jack S. Hale. The full source code for this demo can be `downloaded here <../_static/ex10.py>`__. Initialization is similar to previous examples, but importing some additional modules. :: try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy import random import math This function builds the discrete Laplacian operator in 1 dimension with homogeneous Dirichlet boundary conditions. :: def construct_operator(m): # Create matrix for 1D Laplacian operator A = PETSc.Mat().create(PETSc.COMM_SELF) A.setSizes([m, m]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = 2.0/hx offdx = -1.0/hx Istart, Iend = A.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): A[i, i] = diagv if i > 1: A[i, i - 1] = offdx if i < m - 2: A[i, i + 1] = offdx else: A[i, i] = 1. A.assemble() return A Set bell-shape function as the solution of the Laplacian problem in 1 dimension with homogeneous Dirichlet boundary conditions and compute the associated discrete RHS. :: def set_problem_rhs(m): # Create 1D mass matrix operator M = PETSc.Mat().create(PETSc.COMM_SELF) M.setSizes([m, m]) M.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing diagv = hx/3 offdx = hx/6 Istart, Iend = M.getOwnershipRange() for i in range(Istart, Iend): if i != 0 and i != (m - 1): M[i, i] = 2*diagv else: M[i, i] = diagv if i > 1: M[i, i - 1] = offdx if i < m - 2: M[i, i + 1] = offdx M.assemble() x_0 = 0.3 x_f = 0.7 mu = x_0 + (x_f - x_0)*random.random() sigma = 0.1**2 uex, f = M.createVecs() for j in range(Istart, Iend): value = 2/sigma * math.exp(-(hx*j - mu)**2/sigma) * (1 - 2/sigma * (hx*j - mu)**2 ) f.setValue(j, value) value = math.exp(-(hx*j - mu)**2/sigma) uex.setValue(j, value) f.assemble() uex.assemble() RHS = f.duplicate() M.mult(f, RHS) RHS.setValue(0, 0.) RHS.setValue(m-1, 0.) RHS.assemble() return RHS, uex Solve 1D Laplace problem with FEM. :: def solve_laplace_problem(A, RHS): u = A.createVecs('right') r, c = A.getOrdering("natural") A.factorILU(r, c) A.solve(RHS, u) A.setUnfactored() return u Solve 1D Laplace problem with POD (dense matrix). :: def solve_laplace_problem_pod(A, RHS, u): ksp = PETSc.KSP().create(PETSc.COMM_SELF) ksp.setOperators(A) ksp.setType('preonly') pc = ksp.getPC() pc.setType('none') ksp.setFromOptions() ksp.solve(RHS, u) return u Set ``N`` solution of the 1D Laplace problem as columns of a matrix (snapshot matrix). Note: For simplicity we do not perform a linear solve, but use some analytical solution: :math:`z(x) = \exp(-(x - \mu)^2 / \sigma)`. :: def construct_snapshot_matrix(A, N, m): snapshots = PETSc.Mat().create(PETSc.COMM_SELF) snapshots.setSizes([m, N]) snapshots.setType('seqdense') Istart, Iend = snapshots.getOwnershipRange() hx = 1.0/(m - 1) x_0 = 0.3 x_f = 0.7 sigma = 0.1**2 for i in range(N): mu = x_0 + (x_f - x_0)*random.random() for j in range(Istart, Iend): value = math.exp(-(hx*j - mu)**2/sigma) snapshots.setValue(j, i, value) snapshots.assemble() return snapshots Solve the eigenvalue problem: the eigenvectors of this problem form the POD basis. :: def solve_eigenproblem(snapshots, N): print('Solving POD basis eigenproblem using eigensolver...') Es = SLEPc.EPS() Es.create(PETSc.COMM_SELF) Es.setDimensions(N) Es.setProblemType(SLEPc.EPS.ProblemType.NHEP) Es.setTolerances(1.0e-8, 500); Es.setKrylovSchurRestart(0.6) Es.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_REAL) Es.setOperators(snapshots) Es.setFromOptions() Es.solve() print('Solved POD basis eigenproblem.') return Es Function to project :math:`S^TS` eigenvectors to :math:`S` eigenvectors. :: def project_STS_eigenvectors_to_S_eigenvectors(bvEs, S): sizes = S.getSizes()[0] N = bvEs.getActiveColumns()[1] bv = SLEPc.BV().create(PETSc.COMM_SELF) bv.setSizes(sizes, N) bv.setActiveColumns(0, N) bv.setFromOptions() tmpvec2 = S.createVecs('left') for i in range(N): tmpvec = bvEs.getColumn(i) S.mult(tmpvec, tmpvec2) bv.insertVec(i, tmpvec2) bvEs.restoreColumn(i, tmpvec) return bv Function to project the reduced space to the full space. :: def project_reduced_to_full_space(alpha, bv): uu = bv.getColumn(0) uPOD = uu.duplicate() bv.restoreColumn(0,uu) scatter, Wr = PETSc.Scatter.toAll(alpha) scatter.begin(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) scatter.end(alpha, Wr, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD) PODcoeff = Wr.getArray(readonly=1) bv.multVec(1., 0., uPOD, PODcoeff) return uPOD The main function realizes the full procedure. :: def main(): problem_dim = 200 num_snapshots = 30 num_pod_basis_functions = 8 assert(num_pod_basis_functions <= num_snapshots) A = construct_operator(problem_dim) S = construct_snapshot_matrix(A, num_snapshots, problem_dim) # Instead of solving the SVD of S, we solve the standard # eigenvalue problem on S.T*S STS = S.transposeMatMult(S) Es = solve_eigenproblem(STS, num_pod_basis_functions) nconv = Es.getConverged() print('Number of converged eigenvalues: %i' % nconv) Es.view() # get the EPS solution in a BV object bvEs = Es.getBV() bvEs.setActiveColumns(0, num_pod_basis_functions) # set the bv POD basis bv = project_STS_eigenvectors_to_S_eigenvectors(bvEs, S) # rescale the eigenvectors for i in range(num_pod_basis_functions): ll = Es.getEigenvalue(i) print('Eigenvalue '+str(i)+': '+str(ll.real)) bv.scaleColumn(i,1.0/math.sqrt(ll.real)) print('--------------------------------') # Verify that the active columns of bv form an orthonormal subspace, i.e. that X^H*X = Id print('Check that bv.dot(bv) is close to the identity matrix') XtX = bv.dot(bv) XtX.view() XtX_array = XtX.getDenseArray() n,m = XtX_array.shape assert numpy.allclose(XtX_array, numpy.eye(n, m)) print('--------------------------------') print('Solve the problem with POD') # Project the linear operator A Ared = bv.matProject(A,bv) # Set the RHS and the exact solution RHS, uex = set_problem_rhs(problem_dim) # Project the RHS on the POD basis RHSred = PETSc.Vec().createWithArray(bv.dotVec(RHS)) # Solve the problem with POD alpha = Ared.createVecs('right') alpha = solve_laplace_problem_pod(Ared,RHSred,alpha) # Project the POD solution back to the FE space uPOD = project_reduced_to_full_space(alpha, bv) # Compute the L2 and Linf norm of the error error = uex.copy() error.axpy(-1,uPOD) errorL2 = math.sqrt(error.dot(error).real) print('The L2-norm of the error is: '+str(errorL2)) print("NORMAL END") if __name__ == '__main__': main() .. [1] K. Kunisch and S. Volkwein. Galerkin proper orthogonal decomposition methods for a general equation in fluid dynamics. SIAM Journal on Numerical Analysis, 40(2):492-515, 2003. .. [2] S. Volkwein, Optimal control of a phase-field model using the proper orthogonal decomposition, Z. Angew. Math. Mech., 81:83-97, 2001. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex11.py0000644000076500000240000000501215133664232017065 0ustar00jromanstaff# ex11.py: 2-D Laplacian eigenproblem solved with contour integral # ================================================================ # # This example is similar to ``ex2.py``, but employs a contour integral # solver. It illustrates how to define a region of the complex plane # using an `RG` object. # # The full source code for this demo can be `downloaded here # <../_static/ex11.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Build the finite-difference 2-D Laplacian matrix. def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # In the main function, first two command-line options are processed to # set the grid dimensions. Then the matrix is built and passed to the # solver object. In this case, the solver is configured to use the contour # integral method. Next, the region of interest is defined, in this case # an ellipse centered at the origin, with radius 0.2 and vertical scaling # of 0.1. Finally, the solver is run. In this example, we illustrate how to # print the solution using the solver method `errorView() `. def main(): opts = PETSc.Options() n = opts.getInt('n', 32) m = opts.getInt('m', 32) Print("2-D Laplacian Eigenproblem solved with contour integral, " "N=%d (%dx%d grid)\n" % (m*n, m, n)) A = construct_operator(m,n) E = SLEPc.EPS().create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setType(SLEPc.EPS.Type.CISS) R = E.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) R.setEllipseParameters(0.0,0.2,0.1) E.setFromOptions() E.solve() vw = PETSc.Viewer.STDOUT() vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) vw.popFormat() if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex11.rst0000644000076500000240000000513215133664232017250 0ustar00jromanstaffex11.py: 2-D Laplacian eigenproblem solved with contour integral ================================================================ This example is similar to ``ex2.py``, but employs a contour integral solver. It illustrates how to define a region of the complex plane using an `RG` object. The full source code for this demo can be `downloaded here <../_static/ex11.py>`__. Initialization is similar to previous examples. :: try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print Build the finite-difference 2-D Laplacian matrix. :: def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A In the main function, first two command-line options are processed to set the grid dimensions. Then the matrix is built and passed to the solver object. In this case, the solver is configured to use the contour integral method. Next, the region of interest is defined, in this case an ellipse centered at the origin, with radius 0.2 and vertical scaling of 0.1. Finally, the solver is run. In this example, we illustrate how to print the solution using the solver method `errorView() `. :: def main(): opts = PETSc.Options() n = opts.getInt('n', 32) m = opts.getInt('m', 32) Print("2-D Laplacian Eigenproblem solved with contour integral, " "N=%d (%dx%d grid)\n" % (m*n, m, n)) A = construct_operator(m,n) E = SLEPc.EPS().create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setType(SLEPc.EPS.Type.CISS) R = E.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) R.setEllipseParameters(0.0,0.2,0.1) E.setFromOptions() E.solve() vw = PETSc.Viewer.STDOUT() vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) vw.popFormat() if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex12.py0000644000076500000240000000466115133664232017077 0ustar00jromanstaff# ex12.py: Illustrate the use of arbitrary selection # ================================================== # # This example solves a simple tridiagonal eigenproblem. It illustrates # how to set up the arbitrary selection of eigenvalues, where the # decision of which is the preferred eigenvalue is made based not only # on the value of the approximate eigenvalue but also on the approximate # eigenvector. # # In this example, the selection criterion is based on the projection # of the approximate eigenvector onto a precomputed eigenvector. That is # why we solve the problem twice. # # The full source code for this demo can be `downloaded here # <../_static/ex12.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy # The matrix size ``n`` can be specified at the command line. opts = PETSc.Options() n = opts.getInt('n', 30) # Create the matrix ``tridiag([-1 0 -1])``. A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i>0: A[i, i-1] = -1 if i0: sx, _ = A.createVecs() E.getEigenpair(0, sx) vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) def myArbitrarySel(evalue, xr, xi, sx): return abs(xr.dot(sx)) E.setArbitrarySelection(myArbitrarySel,sx) E.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_MAGNITUDE) E.solve() E.errorView(viewer=vw) vw.popFormat() else: Print( "No eigenpairs converged" ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex12.rst0000644000076500000240000000473415133664232017260 0ustar00jromanstaffex12.py: Illustrate the use of arbitrary selection ================================================== This example solves a simple tridiagonal eigenproblem. It illustrates how to set up the arbitrary selection of eigenvalues, where the decision of which is the preferred eigenvalue is made based not only on the value of the approximate eigenvalue but also on the approximate eigenvector. In this example, the selection criterion is based on the projection of the approximate eigenvector onto a precomputed eigenvector. That is why we solve the problem twice. The full source code for this demo can be `downloaded here <../_static/ex12.py>`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy The matrix size ``n`` can be specified at the command line. :: opts = PETSc.Options() n = opts.getInt('n', 30) Create the matrix ``tridiag([-1 0 -1])``. :: A = PETSc.Mat(); A.create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i>0: A[i, i-1] = -1 if i0: sx, _ = A.createVecs() E.getEigenpair(0, sx) vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) def myArbitrarySel(evalue, xr, xi, sx): return abs(xr.dot(sx)) E.setArbitrarySelection(myArbitrarySel,sx) E.setWhichEigenpairs(SLEPc.EPS.Which.LARGEST_MAGNITUDE) E.solve() E.errorView(viewer=vw) vw.popFormat() else: Print( "No eigenpairs converged" ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex13.py0000644000076500000240000002142115133664232017071 0ustar00jromanstaff# ex13.py: Nonlinear eigenproblem with contour integral # ===================================================== # # This example solves a nonlinear eigenvalue problem with the `NEP # ` module configured to apply a contour integral # method. # # The problem arises from the PDE # # .. math:: # # u_{xx}(x) + n_c^2 \lambda^2 u(x) + g(\lambda) D_0 \lambda^2 u(x) = 0 # # where # # .. math:: # # g(\lambda) &= g_t/(\lambda-k_a + i g_t), \\ # k_a &= 8.0, \\ # g_t &= 0.5, \\ # D_0 &= 0.5, \\ # n_c &= 1.2, # # and the boundary conditions are # # .. math:: # # u(0) &= 0 \\ # u_x(1) &= i \lambda u(1). # # For the discretization, :math:`n` grid points are used, :math:`x_1=0,\dots,x_n=1`, # with step size :math:`h = 1/(n-1)`. Hence, # # .. math:: # # u_{xx}(x_i) &= \frac{1}{h^2} (u_{i-1} - 2 u_i + u_{i+1}) \\ # &= \frac{1}{h^2} [1, -2, 1] [u_{i-1}, u_i, u_{i+1}]^T. # # The boundary condition at :math:`x=0` is :math:`u_1=0`, and at :math:`x=1`: # # .. math:: # # u'(1) &= 1/2 ( u'(1+h/2) + u'(1-h/2) ) \\ # &= 1/2 ( (u_{n+1}-u_n)/h + (u_n-u_{n-1})/h ) \\ # &= 1/(2h) (u_{n+1} - u_{n-1}) = i\lambda u_n, # # and therefore # # .. math:: # # u_{n+1} = 2i h \lambda u_n + u_{n-1}. # # The Laplace term for :math:`u_n` is # # .. math:: # # &= \frac{1}{h^2} (u_{n-1} - 2u_n + u_{n+1}) \\ # &= \frac{1}{h^2} (u_{n-1} - 2u_n + 2ih\lambda u_n + u_{n-1}) \\ # &= \frac{1}{h^2} (2 u_{n-1} + (2ih\lambda - 2) u_n) \\ # &= \frac{1}{h^2} [2, 2ih\lambda -2] [u_{n-1}, u_n]^T. # # The above discretization allows us to write the nonlinear PDE in the # following split-operator form # # .. math:: # # \{A + \lambda^2 n_c^2 I_d + g(\lambda) \lambda^2 D_0 I_d + 2i\lambda/h D\} u = 0 # # so :math:`f_1 = 1`, :math:`f_2 = n_c^2 \lambda^2`, :math:`f_3 = g(\lambda) # \lambda^2D_0`, :math:`f_4 = 2i\lambda/h`, with coefficient matrices # # .. math:: # # A = \begin{bmatrix} # 1 & 0 & 0 & \dots & 0 \\ # 0 & * & * & \dots & 0 \\ # 0 & * & * & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & * # \end{bmatrix}, # I_d = \begin{bmatrix} # 0 & 0 & 0 & \dots & 0 \\ # 0 & 1 & 0 & \dots & 0 \\ # 0 & 0 & 1 & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & 0 # \end{bmatrix}, # D = \begin{bmatrix} # 0 & 0 & 0 & \dots & 0 \\ # 0 & 0 & 0 & \dots & 0 \\ # 0 & 0 & 0 & \dots & 0 \\ # \vdots & \vdots & \vdots & \ddots & \vdots \\ # 0 & 0 & 0 & \dots & 1 # \end{bmatrix}. # # Contributed by: Thomas Hisch. # # The full source code for this demo can be `downloaded here # <../_static/ex13.py>`__. # Initialization by importing slepc4py, petsc4py, numpy and scipy. import sys import slepc4py slepc4py.init(sys.argv) # isort:skip import numpy as np try: import scipy import scipy.optimize except ImportError: scipy = None from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Check that the selected PETSc/SLEPc are built with complex scalars. if not np.issubdtype(PETSc.ScalarType, np.complexfloating): Print("Demo should only be executed with complex PETSc scalars") exit(0) # Long function that defines the nonlinear eigenproblem and solves it. def solve(n): L = 1.0 h = L / (n - 1) nc = 1.2 ka = 10.0 gt = 4.0 D0 = 0.5 A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() A.setOption(PETSc.Mat.Option.HERMITIAN, False) rstart, rend = A.getOwnershipRange() d0, d1, d2 = ( 1 / h**2, -2 / h**2, 1 / h**2, ) Print(f"dterms={(d0, d1, d2)}") if rstart == 0: # dirichlet boundary condition at the left lead A[0, 0] = 1.0 A[0, 1] = 0.0 A[1, 0] = 0.0 A[1, 1] = d1 A[1, 2] = d2 rstart += 2 if rend == n: # at x=1.0 neumann boundary condition (not handled here but in a # different matrix (D)) A[n - 1, n - 2] = 2.0 / h**2 A[n - 1, n - 1] = (-2) / h**2 # + 2j*k*h / h**2 (neumann) rend -= 1 for i in range(rstart, rend): A[i, i - 1 : i + 2] = [d0, d1, d2] A.assemble() Id = PETSc.Mat().create() Id.setSizes([n, n]) Id.setFromOptions() Id.setOption(PETSc.Mat.Option.HERMITIAN, True) rstart, rend = Id.getOwnershipRange() if rstart == 0: # due to dirichlet BC rstart += 1 for i in range(rstart, rend): Id[i, i] = 1.0 Id.assemble() D = PETSc.Mat().create() D.setSizes([n, n]) D.setFromOptions() D.setOption(PETSc.Mat.Option.HERMITIAN, True) _, rend = D.getOwnershipRange() if rend == n: D[n - 1, n - 1] = 1 D.assemble() Print(f"DOF: {A.getInfo()['nz_used']}, MEM: {A.getInfo()['memory']}") f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([1.0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([nc**2, 0.0, 0.0]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.RATIONAL) f3.setRationalNumerator([D0 * gt, 0.0, 0.0]) f3.setRationalDenominator([1.0, -ka + 1j * gt]) f4 = SLEPc.FN().create() f4.setType(SLEPc.FN.Type.RATIONAL) f4.setRationalNumerator([2j / h, 0]) # Setup the solver nep = SLEPc.NEP().create() nep.setSplitOperator( [A, Id, Id, D], [f1, f2, f3, f4], PETSc.Mat.Structure.SUBSET, ) # Customize options nep.setTolerances(tol=1e-7) nep.setDimensions(nev=24) nep.setType(SLEPc.NEP.Type.CISS) # the rg params are chosen s.t. the singularity at k = ka - 1j*gt is # outside of the contour. radius = 3 * gt vscale = 0.5 * gt / radius rg_params = (ka, 3 * gt, vscale) R = nep.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) Print(f"RG params: {rg_params}") R.setEllipseParameters(*rg_params) nep.setFromOptions() # Solve the problem nep.solve() its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print("Number of converged eigenpairs %d" % nconv) x = A.createVecs("right") evals = [] modes = [] if nconv > 0: Print() Print(" lam ||T(lam)x|| |lam-lam_exact|/|lam_exact| ") Print("--------------------- ------------- -----------------------------") for i in range(nconv): lam = nep.getEigenpair(i, x) error = nep.computeError(i) def eigenvalue_error_term(k): gkmu = gt / (k - ka + 1j * gt) nceff = np.sqrt(nc**2 + gkmu * D0) return -1j / np.tan(nceff * k * L) - 1 / nceff # compute the expected_eigenvalue # we assume that the numerically calculated eigenvalue is close to # the exact one, which we can determine using a Newton-Raphson # method. if scipy: expected_lam = scipy.optimize.newton( eigenvalue_error_term, np.complex128(lam), rtol=1e-11 ) rel_err = abs(lam - expected_lam) / abs(expected_lam) rel_err = "%6g" % rel_err else: rel_err = "scipy not installed" Print(" %9f%+9f j %12g %s" % (lam.real, lam.imag, error, rel_err)) evals.append(lam) modes.append(x.getArray().copy()) Print() return np.asarray(evals), rg_params, ka, gt # The main function reads the problem size ``n`` from the command line, # solves the problem with the above function, and then plots the computed # eigenvalues. def main(): opts = PETSc.Options() n = opts.getInt("n", 256) Print(f"n={n}") evals, rg_params, ka, gt = solve(n) if not opts.getBool("ploteigs", True) or PETSc.COMM_WORLD.getRank(): return try: import matplotlib.pyplot as plt from matplotlib.patches import Ellipse except ImportError: print("plot is not shown, because matplotlib is not installed") else: fig, ax = plt.subplots() ax.plot(evals.real, evals.imag, "x") height = 2 * rg_params[1] * rg_params[2] ellipse = Ellipse( xy=(rg_params[0], 0.0), width=rg_params[1] * 2, height=height, edgecolor="r", fc="None", lw=2, ) ax.add_patch(ellipse) ax.grid() ax.legend() plt.show() if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex13.rst0000644000076500000240000002172315133664232017256 0ustar00jromanstaffex13.py: Nonlinear eigenproblem with contour integral ===================================================== This example solves a nonlinear eigenvalue problem with the `NEP ` module configured to apply a contour integral method. The problem arises from the PDE .. math:: u_{xx}(x) + n_c^2 \lambda^2 u(x) + g(\lambda) D_0 \lambda^2 u(x) = 0 where .. math:: g(\lambda) &= g_t/(\lambda-k_a + i g_t), \\ k_a &= 8.0, \\ g_t &= 0.5, \\ D_0 &= 0.5, \\ n_c &= 1.2, and the boundary conditions are .. math:: u(0) &= 0 \\ u_x(1) &= i \lambda u(1). For the discretization, :math:`n` grid points are used, :math:`x_1=0,\dots,x_n=1`, with step size :math:`h = 1/(n-1)`. Hence, .. math:: u_{xx}(x_i) &= \frac{1}{h^2} (u_{i-1} - 2 u_i + u_{i+1}) \\ &= \frac{1}{h^2} [1, -2, 1] [u_{i-1}, u_i, u_{i+1}]^T. The boundary condition at :math:`x=0` is :math:`u_1=0`, and at :math:`x=1`: .. math:: u'(1) &= 1/2 ( u'(1+h/2) + u'(1-h/2) ) \\ &= 1/2 ( (u_{n+1}-u_n)/h + (u_n-u_{n-1})/h ) \\ &= 1/(2h) (u_{n+1} - u_{n-1}) = i\lambda u_n, and therefore .. math:: u_{n+1} = 2i h \lambda u_n + u_{n-1}. The Laplace term for :math:`u_n` is .. math:: &= \frac{1}{h^2} (u_{n-1} - 2u_n + u_{n+1}) \\ &= \frac{1}{h^2} (u_{n-1} - 2u_n + 2ih\lambda u_n + u_{n-1}) \\ &= \frac{1}{h^2} (2 u_{n-1} + (2ih\lambda - 2) u_n) \\ &= \frac{1}{h^2} [2, 2ih\lambda -2] [u_{n-1}, u_n]^T. The above discretization allows us to write the nonlinear PDE in the following split-operator form .. math:: \{A + \lambda^2 n_c^2 I_d + g(\lambda) \lambda^2 D_0 I_d + 2i\lambda/h D\} u = 0 so :math:`f_1 = 1`, :math:`f_2 = n_c^2 \lambda^2`, :math:`f_3 = g(\lambda) \lambda^2D_0`, :math:`f_4 = 2i\lambda/h`, with coefficient matrices .. math:: A = \begin{bmatrix} 1 & 0 & 0 & \dots & 0 \\ 0 & * & * & \dots & 0 \\ 0 & * & * & \dots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \dots & * \end{bmatrix}, I_d = \begin{bmatrix} 0 & 0 & 0 & \dots & 0 \\ 0 & 1 & 0 & \dots & 0 \\ 0 & 0 & 1 & \dots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \dots & 0 \end{bmatrix}, D = \begin{bmatrix} 0 & 0 & 0 & \dots & 0 \\ 0 & 0 & 0 & \dots & 0 \\ 0 & 0 & 0 & \dots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \dots & 1 \end{bmatrix}. Contributed by: Thomas Hisch. The full source code for this demo can be `downloaded here <../_static/ex13.py>`__. Initialization by importing slepc4py, petsc4py, numpy and scipy. :: import sys import slepc4py slepc4py.init(sys.argv) # isort:skip import numpy as np try: import scipy import scipy.optimize except ImportError: scipy = None from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print Check that the selected PETSc/SLEPc are built with complex scalars. :: if not np.issubdtype(PETSc.ScalarType, np.complexfloating): Print("Demo should only be executed with complex PETSc scalars") exit(0) Long function that defines the nonlinear eigenproblem and solves it. :: def solve(n): L = 1.0 h = L / (n - 1) nc = 1.2 ka = 10.0 gt = 4.0 D0 = 0.5 A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() A.setOption(PETSc.Mat.Option.HERMITIAN, False) rstart, rend = A.getOwnershipRange() d0, d1, d2 = ( 1 / h**2, -2 / h**2, 1 / h**2, ) Print(f"dterms={(d0, d1, d2)}") if rstart == 0: # dirichlet boundary condition at the left lead A[0, 0] = 1.0 A[0, 1] = 0.0 A[1, 0] = 0.0 A[1, 1] = d1 A[1, 2] = d2 rstart += 2 if rend == n: # at x=1.0 neumann boundary condition (not handled here but in a # different matrix (D)) A[n - 1, n - 2] = 2.0 / h**2 A[n - 1, n - 1] = (-2) / h**2 # + 2j*k*h / h**2 (neumann) rend -= 1 for i in range(rstart, rend): A[i, i - 1 : i + 2] = [d0, d1, d2] A.assemble() Id = PETSc.Mat().create() Id.setSizes([n, n]) Id.setFromOptions() Id.setOption(PETSc.Mat.Option.HERMITIAN, True) rstart, rend = Id.getOwnershipRange() if rstart == 0: # due to dirichlet BC rstart += 1 for i in range(rstart, rend): Id[i, i] = 1.0 Id.assemble() D = PETSc.Mat().create() D.setSizes([n, n]) D.setFromOptions() D.setOption(PETSc.Mat.Option.HERMITIAN, True) _, rend = D.getOwnershipRange() if rend == n: D[n - 1, n - 1] = 1 D.assemble() Print(f"DOF: {A.getInfo()['nz_used']}, MEM: {A.getInfo()['memory']}") f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([1.0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([nc**2, 0.0, 0.0]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.RATIONAL) f3.setRationalNumerator([D0 * gt, 0.0, 0.0]) f3.setRationalDenominator([1.0, -ka + 1j * gt]) f4 = SLEPc.FN().create() f4.setType(SLEPc.FN.Type.RATIONAL) f4.setRationalNumerator([2j / h, 0]) # Setup the solver nep = SLEPc.NEP().create() nep.setSplitOperator( [A, Id, Id, D], [f1, f2, f3, f4], PETSc.Mat.Structure.SUBSET, ) # Customize options nep.setTolerances(tol=1e-7) nep.setDimensions(nev=24) nep.setType(SLEPc.NEP.Type.CISS) # the rg params are chosen s.t. the singularity at k = ka - 1j*gt is # outside of the contour. radius = 3 * gt vscale = 0.5 * gt / radius rg_params = (ka, 3 * gt, vscale) R = nep.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) Print(f"RG params: {rg_params}") R.setEllipseParameters(*rg_params) nep.setFromOptions() # Solve the problem nep.solve() its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print("Number of converged eigenpairs %d" % nconv) x = A.createVecs("right") evals = [] modes = [] if nconv > 0: Print() Print(" lam ||T(lam)x|| |lam-lam_exact|/|lam_exact| ") Print("--------------------- ------------- -----------------------------") for i in range(nconv): lam = nep.getEigenpair(i, x) error = nep.computeError(i) def eigenvalue_error_term(k): gkmu = gt / (k - ka + 1j * gt) nceff = np.sqrt(nc**2 + gkmu * D0) return -1j / np.tan(nceff * k * L) - 1 / nceff # compute the expected_eigenvalue # we assume that the numerically calculated eigenvalue is close to # the exact one, which we can determine using a Newton-Raphson # method. if scipy: expected_lam = scipy.optimize.newton( eigenvalue_error_term, np.complex128(lam), rtol=1e-11 ) rel_err = abs(lam - expected_lam) / abs(expected_lam) rel_err = "%6g" % rel_err else: rel_err = "scipy not installed" Print(" %9f%+9f j %12g %s" % (lam.real, lam.imag, error, rel_err)) evals.append(lam) modes.append(x.getArray().copy()) Print() return np.asarray(evals), rg_params, ka, gt The main function reads the problem size ``n`` from the command line, solves the problem with the above function, and then plots the computed eigenvalues. :: def main(): opts = PETSc.Options() n = opts.getInt("n", 256) Print(f"n={n}") evals, rg_params, ka, gt = solve(n) if not opts.getBool("ploteigs", True) or PETSc.COMM_WORLD.getRank(): return try: import matplotlib.pyplot as plt from matplotlib.patches import Ellipse except ImportError: print("plot is not shown, because matplotlib is not installed") else: fig, ax = plt.subplots() ax.plot(evals.real, evals.imag, "x") height = 2 * rg_params[1] * rg_params[2] ellipse = Ellipse( xy=(rg_params[0], 0.0), width=rg_params[1] * 2, height=height, edgecolor="r", fc="None", lw=2, ) ax.add_patch(ellipse) ax.grid() ax.legend() plt.show() if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex14.py0000644000076500000240000000717415133664232017103 0ustar00jromanstaff# ex14.py: Lyapunov equation with the shifted 2-D Laplacian # ========================================================= # # This example illustrates the use of slepc4py linear matrix equations # solver object. In particular, a Lyapunov equation is solved, where # the coefficient matrix is the shifted 2-D Laplacian. # # The full source code for this demo can be `downloaded here # <../_static/ex14.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # Once again, a function to build the discretized Laplacian operator # in two dimensions. In this case, we build the shifted negative # Laplacian because the Lyapunov equation requires the coefficient # matrix being stable. def Laplacian2D(m, n, sigma): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = -4.0-sigma i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = 1.0 if i< m-1: J = I+n; A[I,J] = 1.0 if j> 0 : J = I-1; A[I,J] = 1.0 if j< n-1: J = I+1; A[I,J] = 1.0 A.assemble() return A # The following function solves the continuous-time Lyapunov equation # # .. math:: # AX + XA^* = -C # # where :math:`C` is supposed to have low rank. The solution :math:`X` # also has low rank, which will be restricted to ``rk`` if it was # provided as an argument of the function. After solving the equation, # this function computes and prints a residual norm. def solve_lyap(A, C, rk=0): # Setup the solver L = SLEPc.LME().create() L.setProblemType(SLEPc.LME.ProblemType.LYAPUNOV) L.setCoefficients(A) L.setRHS(C) N = C.size[0] if rk>0: X1 = PETSc.Mat().createDense((N,rk)) X1.assemble() X = PETSc.Mat().createLRC(None, X1, None, None) L.setSolution(X) L.setTolerances(1e-7) L.setFromOptions() # Solve the problem L.solve() if rk==0: X = L.getSolution() its = L.getIterationNumber() Print(f'Number of iterations of the method: {its}') sol_type = L.getType() Print(f'Solution method: {sol_type}') tol, maxit = L.getTolerances() Print(f'Stopping condition: tol={tol}, maxit={maxit}') Print(f'Error estimate reported by the solver: {L.getErrorEstimate()}') if N<500: Print(f'Computed residual norm: {L.computeError()}') Print('') return X # The main function processes several command-line arguments such as # the grid dimension (``n``, ``m``), the shift ``sigma`` and the rank # of the solution, ``rank``. # # The coefficient matrix ``A`` is built with the function above, while # the right-hand side matrix ``C`` must be built as a low-rank matrix # using `Mat.createLRC() `. if __name__ == '__main__': opts = PETSc.Options() n = opts.getInt('n', 15) m = opts.getInt('m', n) N = m*n sigma = opts.getScalar('sigma', 0.0) rk = opts.getInt('rank', 0) # Coefficient matrix A A = Laplacian2D(m, n, sigma) # Create a low-rank Mat to store the right-hand side C = C1*C1' C1 = PETSc.Mat().createDense((N,2)) rstart, rend = C1.getOwnershipRange() v = C1.getDenseArray() for i in range(rstart,rend): if i`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print Once again, a function to build the discretized Laplacian operator in two dimensions. In this case, we build the shifted negative Laplacian because the Lyapunov equation requires the coefficient matrix being stable. :: def Laplacian2D(m, n, sigma): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = -4.0-sigma i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = 1.0 if i< m-1: J = I+n; A[I,J] = 1.0 if j> 0 : J = I-1; A[I,J] = 1.0 if j< n-1: J = I+1; A[I,J] = 1.0 A.assemble() return A The following function solves the continuous-time Lyapunov equation .. math:: AX + XA^* = -C where :math:`C` is supposed to have low rank. The solution :math:`X` also has low rank, which will be restricted to ``rk`` if it was provided as an argument of the function. After solving the equation, this function computes and prints a residual norm. :: def solve_lyap(A, C, rk=0): # Setup the solver L = SLEPc.LME().create() L.setProblemType(SLEPc.LME.ProblemType.LYAPUNOV) L.setCoefficients(A) L.setRHS(C) N = C.size[0] if rk>0: X1 = PETSc.Mat().createDense((N,rk)) X1.assemble() X = PETSc.Mat().createLRC(None, X1, None, None) L.setSolution(X) L.setTolerances(1e-7) L.setFromOptions() # Solve the problem L.solve() if rk==0: X = L.getSolution() its = L.getIterationNumber() Print(f'Number of iterations of the method: {its}') sol_type = L.getType() Print(f'Solution method: {sol_type}') tol, maxit = L.getTolerances() Print(f'Stopping condition: tol={tol}, maxit={maxit}') Print(f'Error estimate reported by the solver: {L.getErrorEstimate()}') if N<500: Print(f'Computed residual norm: {L.computeError()}') Print('') return X The main function processes several command-line arguments such as the grid dimension (``n``, ``m``), the shift ``sigma`` and the rank of the solution, ``rank``. The coefficient matrix ``A`` is built with the function above, while the right-hand side matrix ``C`` must be built as a low-rank matrix using `Mat.createLRC() `. :: if __name__ == '__main__': opts = PETSc.Options() n = opts.getInt('n', 15) m = opts.getInt('m', n) N = m*n sigma = opts.getScalar('sigma', 0.0) rk = opts.getInt('rank', 0) # Coefficient matrix A A = Laplacian2D(m, n, sigma) # Create a low-rank Mat to store the right-hand side C = C1*C1' C1 = PETSc.Mat().createDense((N,2)) rstart, rend = C1.getOwnershipRange() v = C1.getDenseArray() for i in range(rstart,rend): if i`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # In this example we have organized the code in several functions. This # one builds the finite-difference Laplacian matrix by computing the # indices of each entry. An alternative would be to use the functionality # offered by `DMDA `. def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # This function receives the matrix and the problem type, then solves the # eigenvalue problem and prints information about the computed solution. # Although we know that eigenvalues and eigenvectors are real in this # example, the function is prepared to solve it as a non-symmetric problem, # by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles # possibly complex eigenvalues and eigenvectors. def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other two functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (sparse matrix), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex2.rst0000644000076500000240000000725015133664232017173 0ustar00jromanstaffex2.py: Standard symmetric eigenproblem for the 2-D Laplacian ============================================================= This example computes eigenvalues and eigenvectors of the discrete Laplacian on a two-dimensional domain with finite differences. The full source code for this demo can be `downloaded here <../_static/ex2.py>`__. Initialization is similar to previous examples. :: try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print In this example we have organized the code in several functions. This one builds the finite-difference Laplacian matrix by computing the indices of each entry. An alternative would be to use the functionality offered by `DMDA `. :: def construct_operator(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend) : A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A This function receives the matrix and the problem type, then solves the eigenvalue problem and prints information about the computed solution. Although we know that eigenvalues and eigenvectors are real in this example, the function is prepared to solve it as a non-symmetric problem, by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles possibly complex eigenvalues and eigenvectors. :: def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") The main program simply processes three user-defined command-line options and calls the other two functions. :: def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (sparse matrix), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex3.py0000644000076500000240000001072115133664232017011 0ustar00jromanstaff# ex3.py: Matrix-free eigenproblem for the 2-D Laplacian # ====================================================== # # This example solves the eigenproblem for the 2-D discrete Laplacian # without building the matrix explicitly. # # The full source code for this demo can be `downloaded here # <../_static/ex3.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy as np # In this case, the program cannot be run in parallel, so we check that # the number of MPI processes is 1. In order to enable parallelism, we # should implement a parallel matrix-vector operation ourselves, which # is not done in this example. assert PETSc.COMM_WORLD.getSize() == 1 Print = PETSc.Sys.Print # This function computes the matrix-vector product f = L*x where the # Laplacian L is not built explicitly, and the vectors x,f are viewed # as two-dimensional arrays associated to grid points. def laplace2d(U, x, f): U[:,:] = 0 U[1:-1, 1:-1] = x # Grid spacing m, n = x.shape hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing # Setup 5-points stencil u = U[1:-1, 1:-1] # center uN = U[1:-1, :-2] # north uS = U[1:-1, 2: ] # south uW = U[ :-2, 1:-1] # west uE = U[2:, 1:-1] # east # Apply Laplacian f[:,:] = \ (2*u - uE - uW) * (hy/hx) \ + (2*u - uN - uS) * (hx/hy) \ # For a matrix-free solution in slepc4py we have to create a class that # wraps the matrix-vector operation and optionally other operations of # the matrix. In this case, we provide the constructor and the ``mult`` # operation, that simply calls the ``laplace2d`` function above. class Laplacian2D(object): def __init__(self, m, n): self.m, self.n = m, n scalar = PETSc.ScalarType self.U = np.zeros([m+2, n+2], dtype=scalar) def mult(self, A, x, y): m, n = self.m, self.n xx = x.getArray(readonly=1).reshape(m,n) yy = y.getArray(readonly=0).reshape(m,n) laplace2d(self.U, xx, yy) # In this example, building the matrix amounts to creating an object of # the class defined above, and passing it to a special petsc4py matrix # with `createPython() `. def construct_operator(m, n): # Create shell matrix context = Laplacian2D(m,n) A = PETSc.Mat().createPython([m*n,m*n], context) return A # This function receives the matrix and the problem type, then solves the # eigenvalue problem and prints information about the computed solution. # Although we know that eigenvalues and eigenvectors are real in this # example, the function is prepared to solve it as a non-symmetric problem, # by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles # possibly complex eigenvalues and eigenvectors. def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other two functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (matrix-free), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex3.rst0000644000076500000240000001113115133664232017165 0ustar00jromanstaffex3.py: Matrix-free eigenproblem for the 2-D Laplacian ====================================================== This example solves the eigenproblem for the 2-D discrete Laplacian without building the matrix explicitly. The full source code for this demo can be `downloaded here <../_static/ex3.py>`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy as np In this case, the program cannot be run in parallel, so we check that the number of MPI processes is 1. In order to enable parallelism, we should implement a parallel matrix-vector operation ourselves, which is not done in this example. :: assert PETSc.COMM_WORLD.getSize() == 1 Print = PETSc.Sys.Print This function computes the matrix-vector product f = L*x where the Laplacian L is not built explicitly, and the vectors x,f are viewed as two-dimensional arrays associated to grid points. :: def laplace2d(U, x, f): U[:,:] = 0 U[1:-1, 1:-1] = x # Grid spacing m, n = x.shape hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing # Setup 5-points stencil u = U[1:-1, 1:-1] # center uN = U[1:-1, :-2] # north uS = U[1:-1, 2: ] # south uW = U[ :-2, 1:-1] # west uE = U[2:, 1:-1] # east # Apply Laplacian f[:,:] = \ (2*u - uE - uW) * (hy/hx) \ + (2*u - uN - uS) * (hx/hy) \ For a matrix-free solution in slepc4py we have to create a class that wraps the matrix-vector operation and optionally other operations of the matrix. In this case, we provide the constructor and the ``mult`` operation, that simply calls the ``laplace2d`` function above. :: class Laplacian2D(object): def __init__(self, m, n): self.m, self.n = m, n scalar = PETSc.ScalarType self.U = np.zeros([m+2, n+2], dtype=scalar) def mult(self, A, x, y): m, n = self.m, self.n xx = x.getArray(readonly=1).reshape(m,n) yy = y.getArray(readonly=0).reshape(m,n) laplace2d(self.U, xx, yy) In this example, building the matrix amounts to creating an object of the class defined above, and passing it to a special petsc4py matrix with `createPython() `. :: def construct_operator(m, n): # Create shell matrix context = Laplacian2D(m,n) A = PETSc.Mat().createPython([m*n,m*n], context) return A This function receives the matrix and the problem type, then solves the eigenvalue problem and prints information about the computed solution. Although we know that eigenvalues and eigenvectors are real in this example, the function is prepared to solve it as a non-symmetric problem, by passing `SLEPc.EPS.ProblemType.NHEP`, that is why the code handles possibly complex eigenvalues and eigenvectors. :: def solve_eigensystem(A, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = A.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A,None) E.setDimensions(3,PETSc.DECIDE) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") The main program simply processes three user-defined command-line options and calls the other two functions. :: def main(): opts = PETSc.Options() N = opts.getInt('N', 32) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric Eigenproblem (matrix-free), " "N=%d (%dx%d grid)" % (m*n, m, n)) A = construct_operator(m,n) solve_eigensystem(A) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex4.py0000644000076500000240000000472115133664232017015 0ustar00jromanstaff# ex4.py: Singular value decomposition of the Lauchli matrix # ========================================================== # # This example illustrates the use of the SVD solver in slepc4py. It # computes singular values and vectors of the Lauchli matrix, whose # condition number depends on a parameter ``mu``. # # The full source code for this demo can be `downloaded here # <../_static/ex4.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc # This example takes two command-line arguments, the matrix size ``n`` # and the ``mu`` parameter. opts = PETSc.Options() n = opts.getInt('n', 30) mu = opts.getReal('mu', 1e-6) PETSc.Sys.Print( "Lauchli singular value decomposition, (%d x %d) mu=%g\n" % (n+1,n,mu) ) # Create the matrix and fill its nonzero entries. Every MPI process will # insert its locally owned part only. A = PETSc.Mat(); A.create() A.setSizes([n+1, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i==0: for j in range(n): A[0,j] = 1.0 else: A[i,i-1] = mu A.assemble() # The singular value solver is similar to the eigensolver used in previous # examples. In this case, we select the thick-restart Lanczos # bidiagonalization method. S = SLEPc.SVD(); S.create() S.setOperator(A) S.setType(S.Type.TRLANCZOS) S.setFromOptions() S.solve() # After solve, we print some informative data and extract the computed # solution, showing the list of singular values and the corresponding # residual errors. Print = PETSc.Sys.Print Print( "******************************" ) Print( "*** SLEPc Solution Results ***" ) Print( "******************************\n" ) svd_type = S.getType() Print( "Solution method: %s" % svd_type ) its = S.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) nsv, ncv, mpd = S.getDimensions() Print( "Number of requested singular values: %d" % nsv ) tol, maxit = S.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) nconv = S.getConverged() Print( "Number of converged approximate singular triplets %d" % nconv ) if nconv > 0: v, u = A.createVecs() Print() Print(" sigma residual norm ") Print("------------- ---------------") for i in range(nconv): sigma = S.getSingularTriplet(i, u, v) error = S.computeError(i) Print( " %6f %12g" % (sigma, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex4.rst0000644000076500000240000000504315133664232017173 0ustar00jromanstaffex4.py: Singular value decomposition of the Lauchli matrix ========================================================== This example illustrates the use of the SVD solver in slepc4py. It computes singular values and vectors of the Lauchli matrix, whose condition number depends on a parameter ``mu``. The full source code for this demo can be `downloaded here <../_static/ex4.py>`__. Initialization is similar to previous examples. :: try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc This example takes two command-line arguments, the matrix size ``n`` and the ``mu`` parameter. :: opts = PETSc.Options() n = opts.getInt('n', 30) mu = opts.getReal('mu', 1e-6) PETSc.Sys.Print( "Lauchli singular value decomposition, (%d x %d) mu=%g\n" % (n+1,n,mu) ) Create the matrix and fill its nonzero entries. Every MPI process will insert its locally owned part only. :: A = PETSc.Mat(); A.create() A.setSizes([n+1, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() for i in range(rstart, rend): if i==0: for j in range(n): A[0,j] = 1.0 else: A[i,i-1] = mu A.assemble() The singular value solver is similar to the eigensolver used in previous examples. In this case, we select the thick-restart Lanczos bidiagonalization method. :: S = SLEPc.SVD(); S.create() S.setOperator(A) S.setType(S.Type.TRLANCZOS) S.setFromOptions() S.solve() After solve, we print some informative data and extract the computed solution, showing the list of singular values and the corresponding residual errors. :: Print = PETSc.Sys.Print Print( "******************************" ) Print( "*** SLEPc Solution Results ***" ) Print( "******************************\n" ) svd_type = S.getType() Print( "Solution method: %s" % svd_type ) its = S.getIterationNumber() Print( "Number of iterations of the method: %d" % its ) nsv, ncv, mpd = S.getDimensions() Print( "Number of requested singular values: %d" % nsv ) tol, maxit = S.getTolerances() Print( "Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit) ) nconv = S.getConverged() Print( "Number of converged approximate singular triplets %d" % nconv ) if nconv > 0: v, u = A.createVecs() Print() Print(" sigma residual norm ") Print("------------- ---------------") for i in range(nconv): sigma = S.getSingularTriplet(i, u, v) error = S.computeError(i) Print( " %6f %12g" % (sigma, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex5.py0000644000076500000240000000705015133664232017014 0ustar00jromanstaff# ex5.py: Simple quadratic eigenvalue problem # =========================================== # # This example solves a polynomial eigenvalue problem of degree 2, # which is the most commonly found in applications. Larger degree # polynomials are handled similarly. The coefficient matrices in # this example do not come from an application, they are just simple # matrices that are easy to build, just to illustrate how it works. # The eigenvalues in this example are purely imaginary and come in # conjugate pairs. # # The full source code for this demo can be `downloaded here # <../_static/ex5.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # A function to build the matrices. The lowest degree coefficient is # the 2-D Laplacian, the highest degree one is the identity matrix, # and the other matrix is set to zero (which means that this problem # could have been solved as a linear eigenproblem). def construct_operators(m,n): Print("Quadratic Eigenproblem, N=%d (%dx%d grid)"% (m*n, m, n)) # K is the 2-D Laplacian K = PETSc.Mat().create() K.setSizes([n*m, n*m]) K.setFromOptions() Istart, Iend = K.getOwnershipRange() for I in range(Istart,Iend): v = -1.0; i = I//n; j = I-i*n; if i>0: J=I-n; K[I,J] = v if i0: J=I-1; K[I,J] = v if j 0: Print("") Print(" k ||(k^2M+Ck+K)x||/||kx|| ") Print("-------------------- -------------------------") for i in range(nconv): k = Q.getEigenpair(i, xr, xi) error = Q.computeError(i) if k.imag != 0.0: Print("%9f%+9f j %12g" % (k.real, k.imag, error)) else: Print("%12f %12g" % (k.real, error)) Print("") # The main program simply processes two user-defined command-line options # (the dimensions of the mesh) and calls the other two functions. if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 32) n = opts.getInt('n', m) M, C, K = construct_operators(m,n) solve_eigensystem(M, C, K) M = C = K = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex5.rst0000644000076500000240000000723615133664232017202 0ustar00jromanstaffex5.py: Simple quadratic eigenvalue problem =========================================== This example solves a polynomial eigenvalue problem of degree 2, which is the most commonly found in applications. Larger degree polynomials are handled similarly. The coefficient matrices in this example do not come from an application, they are just simple matrices that are easy to build, just to illustrate how it works. The eigenvalues in this example are purely imaginary and come in conjugate pairs. The full source code for this demo can be `downloaded here <../_static/ex5.py>`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print A function to build the matrices. The lowest degree coefficient is the 2-D Laplacian, the highest degree one is the identity matrix, and the other matrix is set to zero (which means that this problem could have been solved as a linear eigenproblem). :: def construct_operators(m,n): Print("Quadratic Eigenproblem, N=%d (%dx%d grid)"% (m*n, m, n)) # K is the 2-D Laplacian K = PETSc.Mat().create() K.setSizes([n*m, n*m]) K.setFromOptions() Istart, Iend = K.getOwnershipRange() for I in range(Istart,Iend): v = -1.0; i = I//n; j = I-i*n; if i>0: J=I-n; K[I,J] = v if i0: J=I-1; K[I,J] = v if j 0: Print("") Print(" k ||(k^2M+Ck+K)x||/||kx|| ") Print("-------------------- -------------------------") for i in range(nconv): k = Q.getEigenpair(i, xr, xi) error = Q.computeError(i) if k.imag != 0.0: Print("%9f%+9f j %12g" % (k.real, k.imag, error)) else: Print("%12f %12g" % (k.real, error)) Print("") The main program simply processes two user-defined command-line options (the dimensions of the mesh) and calls the other two functions. :: if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 32) n = opts.getInt('n', m) M, C, K = construct_operators(m,n) solve_eigensystem(M, C, K) M = C = K = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex6.py0000644000076500000240000000764315133664232017025 0ustar00jromanstaff# ex6.py: Compute exp(t*A)*v for a matrix from a Markov model # =========================================================== # # This example illustrates the functionality in slepc4py for computing # matrix functions, or more precisely, the application of a matrix # function on a given vector. The example works with the exponential # function, which is most commonly found in applications. # # The main focus of slepc4py is eigenvalue and singular value problems, # but it has some codes to deal with matrix functions, which sometimes # are needed in the context of eigenproblems, but have interest on # their own. # # The full source code for this demo can be `downloaded here # <../_static/ex6.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # This function builds a matrix that implements a Markov model of a random # walk on a triangular grid. The entries of the matrix represent # probabilities of moving to neighboring cells in the grid. def build_matrix(m): N = m*(m+1)/2 Print("Markov y=exp(t*A)*e_1, N=%d (m=%d)"% (N, m)) A = PETSc.Mat().create() A.setSizes([N, N]) A.setFromOptions() Istart, Iend = A.getOwnershipRange() ix = 0 cst = 0.5/(m-1) for i in range(1,m+1): jmax = m-i+1 for j in range(1,jmax+1): ix = ix + 1 if ix-1Iend: continue # compute only owned rows if j!=jmax: pd = cst*(i+j-1) # north if i==1: A[ix-1,ix] = 2*pd else: A[ix-1,ix] = pd # east if j==1: A[ix-1,ix+jmax-1] = 2*pd else: A[ix-1,ix+jmax-1] = pd # south pu = 0.5 - cst*(i+j-3) if j>1: A[ix-1,ix-2] = pu # west if i>1: A[ix-1,ix-jmax-2] = pu A.assemble() return A # The following function solves the problem. This case is quite different # from eigenproblems, and is more similar to solving a linear system of # equations with `KSP `. To configure the problem we # must provide the matrix and the function (the exponential in this case). # Note how the internal `FN` object is extracted from the `MFN` solver. # Also, it is often necessary to specify a scale factor, which in this # case represents the time for which we want to obtain the evolved state. # Once the solver is set up, we call `solve() ` passing the # right-hand side vector ``b`` and the solution vector ``x``. def solve_exp(t, A, b, x): # Setup the solver M = SLEPc.MFN().create() M.setOperator(A) f = M.getFN() f.setType(SLEPc.FN.Type.EXP) f.setScale(t) M.setTolerances(1e-7) M.setFromOptions() # Solve the problem M.solve(b,x) its = M.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = M.getType() Print("Solution method: %s" % sol_type) ncv = M.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = M.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) Print("Computed vector at time t=%.4g has norm %g" % (t.real, x.norm())) Print("") # The main program processes the command-line option ``m`` (size of the # grid), builds the matrix and calls the solver. Note how the vectors are # created from the matrix. In this case, the right-hand side vector is # the first element of the canonical basis. if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 15) A = build_matrix(m) # transition probability matrix x, b = A.createVecs() x.set(0) b.set(0) b[0] = 1 b.assemble() t = 2 solve_exp(t, A, b, x) # compute x=exp(t*A)*b A = None b = x = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex6.rst0000644000076500000240000001001615133664232017171 0ustar00jromanstaffex6.py: Compute exp(t*A)*v for a matrix from a Markov model =========================================================== This example illustrates the functionality in slepc4py for computing matrix functions, or more precisely, the application of a matrix function on a given vector. The example works with the exponential function, which is most commonly found in applications. The main focus of slepc4py is eigenvalue and singular value problems, but it has some codes to deal with matrix functions, which sometimes are needed in the context of eigenproblems, but have interest on their own. The full source code for this demo can be `downloaded here <../_static/ex6.py>`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print This function builds a matrix that implements a Markov model of a random walk on a triangular grid. The entries of the matrix represent probabilities of moving to neighboring cells in the grid. :: def build_matrix(m): N = m*(m+1)/2 Print("Markov y=exp(t*A)*e_1, N=%d (m=%d)"% (N, m)) A = PETSc.Mat().create() A.setSizes([N, N]) A.setFromOptions() Istart, Iend = A.getOwnershipRange() ix = 0 cst = 0.5/(m-1) for i in range(1,m+1): jmax = m-i+1 for j in range(1,jmax+1): ix = ix + 1 if ix-1Iend: continue # compute only owned rows if j!=jmax: pd = cst*(i+j-1) # north if i==1: A[ix-1,ix] = 2*pd else: A[ix-1,ix] = pd # east if j==1: A[ix-1,ix+jmax-1] = 2*pd else: A[ix-1,ix+jmax-1] = pd # south pu = 0.5 - cst*(i+j-3) if j>1: A[ix-1,ix-2] = pu # west if i>1: A[ix-1,ix-jmax-2] = pu A.assemble() return A The following function solves the problem. This case is quite different from eigenproblems, and is more similar to solving a linear system of equations with `KSP `. To configure the problem we must provide the matrix and the function (the exponential in this case). Note how the internal `FN` object is extracted from the `MFN` solver. Also, it is often necessary to specify a scale factor, which in this case represents the time for which we want to obtain the evolved state. Once the solver is set up, we call `solve() ` passing the right-hand side vector ``b`` and the solution vector ``x``. :: def solve_exp(t, A, b, x): # Setup the solver M = SLEPc.MFN().create() M.setOperator(A) f = M.getFN() f.setType(SLEPc.FN.Type.EXP) f.setScale(t) M.setTolerances(1e-7) M.setFromOptions() # Solve the problem M.solve(b,x) its = M.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = M.getType() Print("Solution method: %s" % sol_type) ncv = M.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = M.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) Print("Computed vector at time t=%.4g has norm %g" % (t.real, x.norm())) Print("") The main program processes the command-line option ``m`` (size of the grid), builds the matrix and calls the solver. Note how the vectors are created from the matrix. In this case, the right-hand side vector is the first element of the canonical basis. :: if __name__ == '__main__': opts = PETSc.Options() m = opts.getInt('m', 15) A = build_matrix(m) # transition probability matrix x, b = A.createVecs() x.set(0) b.set(0) b[0] = 1 b.assemble() t = 2 solve_exp(t, A, b, x) # compute x=exp(t*A)*b A = None b = x = None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex7.py0000644000076500000240000001457115133664232017024 0ustar00jromanstaff# ex7.py: Nonlinear eigenproblem with callback functions # ====================================================== # # This example solves a nonlinear eigenvalue problem arising from the # the discretization of a PDE on a one-dimensional domain with finite # differences. The nonlinearity comes from the boundary conditions. # The PDE is # # .. math:: # # -u'' = \lambda u # # defined on the interval [0,1] and subject to the boundary conditions # # .. math:: # # u(0)=0, u'(1)=u(1)\lambda\frac{\kappa}{\kappa-\lambda}, # # where :math:`\lambda` is the eigenvalue and :math:`\kappa` is a parameter. # # The full source code for this demo can be `downloaded here # <../_static/ex7.py>`__. # Initialization is similar to previous examples. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import sqrt, sin Print = PETSc.Sys.Print # When implementing a nonlinear eigenproblem with callback functions we # must provide code that builds the function matrix :math:`T(\lambda)` # for a given :math:`\lambda` and optionally the Jacobian matrix # :math:`T'(\lambda)`, i.e., the derivative with respect to the eigenvalue. # # In slepc4py the callbacks are integrated in a class. In this example, # apart from the constructor, we have three methods: # # + ``formFunction`` to fill the function matrix ``F``. Note that ``F`` # is received as an argument and we just need to fill its entries using # the value of the parameter ``mu``. Matrix ``B`` is used to build # the preconditioner, and is usually equal to ``F``. # + ``formJacobian`` to fill the Jacobian matrix ``J``. Some eigensolvers # do not need this, but it is recommended to implement it. # + ``checkSolution`` is just a convenience method to check that a given # solution satisfies the PDE. class MyPDE(object): def __init__(self, kappa, h): self.kappa = kappa self.h = h def formFunction(self, nep, mu, F, B): n, m = F.getSize() Istart, Iend = F.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) d = n # Interior grid points for i in range(i1,i2): val = -d-mu*h/6.0 F[i,i-1] = val F[i,i] = 2.0*(d-mu*h/3.0) F[i,i+1] = val # Boundary points if Istart==0: F[0,0] = 2.0*(d-mu*h/3.0) F[0,1] = -d-mu*h/6.0 if Iend==n: F[n-1,n-2] = -d-mu*h/6.0 F[n-1,n-1] = d-mu*h/3.0+mu*c F.assemble() if B != F: B.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def formJacobian(self, nep, mu, J): n, m = J.getSize() Istart, Iend = J.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) # Interior grid points for i in range(i1,i2): J[i,i-1] = -h/6.0 J[i,i] = -2.0*h/3.0 J[i,i+1] = -h/6.0 # Boundary points if Istart==0: J[0,0] = -2.0*h/3.0 J[0,1] = -h/6.0 if Iend==n: J[n-1,n-2] = -h/6.0 J[n-1,n-1] = -h/3.0-c*c J.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def checkSolution(self, mu, y): nu = sqrt(mu) u = y.duplicate() n = u.getSize() Istart, Iend = J.getOwnershipRange() h = self.h for i in range(Istart,Iend): x = (i+1)*h u[i] = sin(nu*x); u.assemble() u.normalize() u.axpy(-1.0,y) return u.norm() # We use an auxiliary function ``FixSign`` to force the computed # eigenfunction to be real and positive, since some eigensolvers may # return the eigenvector multiplied by a complex number of modulus one. def FixSign(x): comm = x.getComm() rank = comm.getRank() n = 1 if rank == 0 else 0 aux = PETSc.Vec().createMPI((n, PETSc.DECIDE), comm=comm) if rank == 0: aux[0] = x[0] aux.assemble() x0 = aux.sum() sign = x0/abs(x0) x.scale(1.0/sign) # The main program processes two command-line options, ``n`` (size of the # grid) and ``kappa`` (the parameter of the PDE), then creates an object # of the class we have defined previously. opts = PETSc.Options() n = opts.getInt('n', 128) kappa = opts.getReal('kappa', 1.0) pde = MyPDE(kappa, 1.0/n) # In order to set up the solver we have to pass the two callback functions # (methods of the class) together with the matrix objects that will be # used every time these methods are called. In this simple example we can # do a preallocation of the matrices, although this is not necessary. nep = SLEPc.NEP().create() F = PETSc.Mat().create() F.setSizes([n, n]) F.setType('aij') F.setPreallocationNNZ(3) nep.setFunction(pde.formFunction, F) J = PETSc.Mat().create() J.setSizes([n, n]) J.setType('aij') J.setPreallocationNNZ(3) nep.setJacobian(pde.formJacobian, J) # After setting some options, we can solve the problem. Here we also # illustrate how to pass an initial guess to the solver. nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() x = F.createVecs('right') x.set(1.0) nep.setInitialSpace(x) nep.solve() # Once the solver has finished, we print some information together with # the computed solution. For each computed eigenpair, we print the # residual norm and also the error estimated with the class method # ``checkSolution``. its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: Print() Print(" k ||T(k)x|| error ") Print("----------------- ------------------ ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) FixSign(x) res = nep.computeError(i) error = pde.checkSolution(k.real, x) if k.imag != 0.0: Print( " %9f%+9f j %12g %12g" % (k.real, k.imag, res, error) ) else: Print( " %12f %12g %12g" % (k.real, res, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex7.rst0000644000076500000240000001506515133664232017203 0ustar00jromanstaffex7.py: Nonlinear eigenproblem with callback functions ====================================================== This example solves a nonlinear eigenvalue problem arising from the the discretization of a PDE on a one-dimensional domain with finite differences. The nonlinearity comes from the boundary conditions. The PDE is .. math:: -u'' = \lambda u defined on the interval [0,1] and subject to the boundary conditions .. math:: u(0)=0, u'(1)=u(1)\lambda\frac{\kappa}{\kappa-\lambda}, where :math:`\lambda` is the eigenvalue and :math:`\kappa` is a parameter. The full source code for this demo can be `downloaded here <../_static/ex7.py>`__. Initialization is similar to previous examples. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import sqrt, sin Print = PETSc.Sys.Print When implementing a nonlinear eigenproblem with callback functions we must provide code that builds the function matrix :math:`T(\lambda)` for a given :math:`\lambda` and optionally the Jacobian matrix :math:`T'(\lambda)`, i.e., the derivative with respect to the eigenvalue. In slepc4py the callbacks are integrated in a class. In this example, apart from the constructor, we have three methods: + ``formFunction`` to fill the function matrix ``F``. Note that ``F`` is received as an argument and we just need to fill its entries using the value of the parameter ``mu``. Matrix ``B`` is used to build the preconditioner, and is usually equal to ``F``. + ``formJacobian`` to fill the Jacobian matrix ``J``. Some eigensolvers do not need this, but it is recommended to implement it. + ``checkSolution`` is just a convenience method to check that a given solution satisfies the PDE. :: class MyPDE(object): def __init__(self, kappa, h): self.kappa = kappa self.h = h def formFunction(self, nep, mu, F, B): n, m = F.getSize() Istart, Iend = F.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) d = n # Interior grid points for i in range(i1,i2): val = -d-mu*h/6.0 F[i,i-1] = val F[i,i] = 2.0*(d-mu*h/3.0) F[i,i+1] = val # Boundary points if Istart==0: F[0,0] = 2.0*(d-mu*h/3.0) F[0,1] = -d-mu*h/6.0 if Iend==n: F[n-1,n-2] = -d-mu*h/6.0 F[n-1,n-1] = d-mu*h/3.0+mu*c F.assemble() if B != F: B.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def formJacobian(self, nep, mu, J): n, m = J.getSize() Istart, Iend = J.getOwnershipRange() i1 = Istart if Istart==0: i1 = i1 + 1 i2 = Iend if Iend==n: i2 = i2 - 1 h = self.h c = self.kappa/(mu-self.kappa) # Interior grid points for i in range(i1,i2): J[i,i-1] = -h/6.0 J[i,i] = -2.0*h/3.0 J[i,i+1] = -h/6.0 # Boundary points if Istart==0: J[0,0] = -2.0*h/3.0 J[0,1] = -h/6.0 if Iend==n: J[n-1,n-2] = -h/6.0 J[n-1,n-1] = -h/3.0-c*c J.assemble() return PETSc.Mat.Structure.SAME_NONZERO_PATTERN def checkSolution(self, mu, y): nu = sqrt(mu) u = y.duplicate() n = u.getSize() Istart, Iend = J.getOwnershipRange() h = self.h for i in range(Istart,Iend): x = (i+1)*h u[i] = sin(nu*x); u.assemble() u.normalize() u.axpy(-1.0,y) return u.norm() We use an auxiliary function ``FixSign`` to force the computed eigenfunction to be real and positive, since some eigensolvers may return the eigenvector multiplied by a complex number of modulus one. :: def FixSign(x): comm = x.getComm() rank = comm.getRank() n = 1 if rank == 0 else 0 aux = PETSc.Vec().createMPI((n, PETSc.DECIDE), comm=comm) if rank == 0: aux[0] = x[0] aux.assemble() x0 = aux.sum() sign = x0/abs(x0) x.scale(1.0/sign) The main program processes two command-line options, ``n`` (size of the grid) and ``kappa`` (the parameter of the PDE), then creates an object of the class we have defined previously. :: opts = PETSc.Options() n = opts.getInt('n', 128) kappa = opts.getReal('kappa', 1.0) pde = MyPDE(kappa, 1.0/n) In order to set up the solver we have to pass the two callback functions (methods of the class) together with the matrix objects that will be used every time these methods are called. In this simple example we can do a preallocation of the matrices, although this is not necessary. :: nep = SLEPc.NEP().create() F = PETSc.Mat().create() F.setSizes([n, n]) F.setType('aij') F.setPreallocationNNZ(3) nep.setFunction(pde.formFunction, F) J = PETSc.Mat().create() J.setSizes([n, n]) J.setType('aij') J.setPreallocationNNZ(3) nep.setJacobian(pde.formJacobian, J) After setting some options, we can solve the problem. Here we also illustrate how to pass an initial guess to the solver. :: nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() x = F.createVecs('right') x.set(1.0) nep.setInitialSpace(x) nep.solve() Once the solver has finished, we print some information together with the computed solution. For each computed eigenpair, we print the residual norm and also the error estimated with the class method ``checkSolution``. :: its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: Print() Print(" k ||T(k)x|| error ") Print("----------------- ------------------ ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) FixSign(x) res = nep.computeError(i) error = pde.checkSolution(k.real, x) if k.imag != 0.0: Print( " %9f%+9f j %12g %12g" % (k.real, k.imag, res, error) ) else: Print( " %12f %12g %12g" % (k.real, res, error) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex8.py0000644000076500000240000001010615133664232017013 0ustar00jromanstaff# ex8.py: Nonlinear eigenproblem with split form # ============================================== # # This example solves a nonlinear eigenvalue problem where the # nonlinear function is expressed in split form. # # We want to solve the following parabolic partial differential # equation with time delay :math:`\tau` # # .. math:: # # u_t &= u_{xx} + a u(t) + b u(t-\tau) \\ # u(0,t) &= u(\pi,t) = 0 # # with :math:`a = 20` and :math:`b(x) = -4.1+x (1-e^{x-\pi})`. # # Discretization leads to a DDE of dimension :math:`n` # # .. math:: # # -u' = A u(t) + B u(t-\tau) # # which results in the nonlinear eigenproblem # # .. math:: # # (-\lambda I + A + e^{-\tau\lambda}B)u = 0. # # The full source code for this demo can be `downloaded here # <../_static/ex8.py>`__. # Initialization is similar to previous examples. In this case we also # need to import some math symbols. import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import exp from math import pi Print = PETSc.Sys.Print # This script has two command-line options: the discretization size ``n`` # and the time delay ``tau``. opts = PETSc.Options() n = opts.getInt('n', 128) tau = opts.getReal('tau', 0.001) a = 20 h = pi/(n+1) # Next we have to set up the solver. In this case, we are going to # represent the nonlinear problem in split form, i.e., as a sum of # terms made of a constant matrix multiplied by a scalar nonlinear # function. nep = SLEPc.NEP().create() # The first term involves the identity matrix. Id = PETSc.Mat().createConstantDiagonal([n, n], 1.0) # The second term has a tridiagonal matrix obtained from the # discretization, :math:`A = \frac{1}{h^2}\operatorname{tridiag}(1,-2,1) + a I`. A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() vd = -2.0/(h*h)+a vo = 1.0/(h*h) if rstart == 0: A[0, :2] = [vd, vo] rstart += 1 if rend == n: A[n-1, -2:] = [vo, vd] rend -= 1 for i in range(rstart, rend): A[i, i-1:i+2] = [vo, vd, vo] A.assemble() # The third term includes a diagonal matrix :math:`B = \operatorname{diag}(b(x_i))`. B = PETSc.Mat().create() B.setSizes([n, n]) B.setFromOptions() rstart, rend = B.getOwnershipRange() for i in range(rstart, rend): xi = (i+1)*h B[i, i] = -4.1+xi*(1.0-exp(xi-pi)); B.assemble() B.setOption(PETSc.Mat.Option.HERMITIAN, True) # Apart from the matrices, we have to create the functions, represented with # `FN` objects: :math:`f_1=-\lambda, f_2=1, f_3=\exp(-\tau\lambda)`. f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([-1, 0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([1]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.EXP) f3.setScale(-tau) # Put all the information together to define the split operator. Note that # ``A`` is passed first so that `SUBSET ` # nonzero_pattern can be used. nep.setSplitOperator([A, Id, B], [f2, f1, f3], PETSc.Mat.Structure.SUBSET) # Now we can set some options and call the solver. nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() nep.solve() # Once the solver has finished, we print some information together with # the computed solution. For each computed eigenpair, we print the # eigenvalue and the residual norm. its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: x = Id.createVecs('right') x.set(1.0) Print() Print(" k ||T(k)x||") Print("----------------- ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) res = nep.computeError(i) if k.imag != 0.0: Print( " %9f%+9f j %12g" % (k.real, k.imag, res) ) else: Print( " %12f %12g" % (k.real, res) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex8.rst0000644000076500000240000001026015133664232017174 0ustar00jromanstaffex8.py: Nonlinear eigenproblem with split form ============================================== This example solves a nonlinear eigenvalue problem where the nonlinear function is expressed in split form. We want to solve the following parabolic partial differential equation with time delay :math:`\tau` .. math:: u_t &= u_{xx} + a u(t) + b u(t-\tau) \\ u(0,t) &= u(\pi,t) = 0 with :math:`a = 20` and :math:`b(x) = -4.1+x (1-e^{x-\pi})`. Discretization leads to a DDE of dimension :math:`n` .. math:: -u' = A u(t) + B u(t-\tau) which results in the nonlinear eigenproblem .. math:: (-\lambda I + A + e^{-\tau\lambda}B)u = 0. The full source code for this demo can be `downloaded here <../_static/ex8.py>`__. Initialization is similar to previous examples. In this case we also need to import some math symbols. :: import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import exp from math import pi Print = PETSc.Sys.Print This script has two command-line options: the discretization size ``n`` and the time delay ``tau``. :: opts = PETSc.Options() n = opts.getInt('n', 128) tau = opts.getReal('tau', 0.001) a = 20 h = pi/(n+1) Next we have to set up the solver. In this case, we are going to represent the nonlinear problem in split form, i.e., as a sum of terms made of a constant matrix multiplied by a scalar nonlinear function. :: nep = SLEPc.NEP().create() The first term involves the identity matrix. :: Id = PETSc.Mat().createConstantDiagonal([n, n], 1.0) The second term has a tridiagonal matrix obtained from the discretization, :math:`A = \frac{1}{h^2}\operatorname{tridiag}(1,-2,1) + a I`. :: A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() rstart, rend = A.getOwnershipRange() vd = -2.0/(h*h)+a vo = 1.0/(h*h) if rstart == 0: A[0, :2] = [vd, vo] rstart += 1 if rend == n: A[n-1, -2:] = [vo, vd] rend -= 1 for i in range(rstart, rend): A[i, i-1:i+2] = [vo, vd, vo] A.assemble() The third term includes a diagonal matrix :math:`B = \operatorname{diag}(b(x_i))`. :: B = PETSc.Mat().create() B.setSizes([n, n]) B.setFromOptions() rstart, rend = B.getOwnershipRange() for i in range(rstart, rend): xi = (i+1)*h B[i, i] = -4.1+xi*(1.0-exp(xi-pi)); B.assemble() B.setOption(PETSc.Mat.Option.HERMITIAN, True) Apart from the matrices, we have to create the functions, represented with `FN` objects: :math:`f_1=-\lambda, f_2=1, f_3=\exp(-\tau\lambda)`. :: f1 = SLEPc.FN().create() f1.setType(SLEPc.FN.Type.RATIONAL) f1.setRationalNumerator([-1, 0]) f2 = SLEPc.FN().create() f2.setType(SLEPc.FN.Type.RATIONAL) f2.setRationalNumerator([1]) f3 = SLEPc.FN().create() f3.setType(SLEPc.FN.Type.EXP) f3.setScale(-tau) Put all the information together to define the split operator. Note that ``A`` is passed first so that `SUBSET ` nonzero_pattern can be used. :: nep.setSplitOperator([A, Id, B], [f2, f1, f3], PETSc.Mat.Structure.SUBSET) Now we can set some options and call the solver. :: nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() nep.solve() Once the solver has finished, we print some information together with the computed solution. For each computed eigenpair, we print the eigenvalue and the residual norm. :: its = nep.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = nep.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = nep.getDimensions() Print("") Print("Subspace dimension: %i" % ncv) tol, maxit = nep.getTolerances() Print("Stopping condition: tol=%.4g" % tol) Print("") nconv = nep.getConverged() Print( "Number of converged eigenpairs %d" % nconv ) if nconv > 0: x = Id.createVecs('right') x.set(1.0) Print() Print(" k ||T(k)x||") Print("----------------- ------------------") for i in range(nconv): k = nep.getEigenpair(i, x) res = nep.computeError(i) if k.imag != 0.0: Print( " %9f%+9f j %12g" % (k.real, k.imag, res) ) else: Print( " %12f %12g" % (k.real, res) ) Print() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex9.py0000644000076500000240000001055715133664232017026 0ustar00jromanstaff# ex9.py: Generalized symmetric-definite eigenproblem # =================================================== # # This example computes eigenvalues and eigenvectors of a generalized # symmetric-definite eigenvalue problem, where the first matrix is the # discrete Laplacian in two dimensions and the second matrix is quasi # diagonal. # # The full source code for this demo can be `downloaded here # <../_static/ex9.py>`__. # Initialization is similar to previous examples. try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print # This function builds the discretized Laplacian operator in 2 dimensions. def Laplacian2D(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A # This function builds a quasi-diagonal matrix. It is two times the identity # matrix except for the 2x2 leading submatrix ``[6 -1; -1 1]``. def QuasiDiagonal(N): # Create matrix B = PETSc.Mat().create() B.setSizes([N, N]) B.setFromOptions() # Fill matrix Istart, Iend = B.getOwnershipRange() for I in range(Istart, Iend): B[I,I] = 2.0 if Istart==0: B[0,0] = 6.0 B[0,1] = -1.0 B[1,0] = -1.0 B[1,1] = 1.0 B.assemble() return B # The following function receives the two matrices and solves the # eigenproblem. In this example we illustrate how to pass objects # that have been created beforehand, instead of extracting the internal # objects. We are using a spectral transformation of type `ST.Type.PRECOND` # and a Block Jacobi preconditioner. We want to compute the leftmost # eigenvalues. The selected eigensolver is LOBPCG, which is appropriate # for this use case. After the solve, we print the computed solution. def solve_eigensystem(A, B, problem_type=SLEPc.EPS.ProblemType.GHEP): # Create the results vectors xr, xi = A.createVecs() pc = PETSc.PC().create() # pc.setType(pc.Type.HYPRE) pc.setType(pc.Type.BJACOBI) ksp = PETSc.KSP().create() ksp.setType(ksp.Type.PREONLY) ksp.setPC( pc ) F = SLEPc.ST().create() F.setType(F.Type.PRECOND) F.setKSP( ksp ) F.setShift(0) # Setup the eigensolver E = SLEPc.EPS().create() E.setST(F) E.setOperators(A,B) E.setType(E.Type.LOBPCG) E.setDimensions(10,PETSc.DECIDE) E.setWhichEigenpairs(E.Which.SMALLEST_REAL) E.setProblemType( problem_type ) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") # The main program simply processes three user-defined command-line options # and calls the other functions. def main(): opts = PETSc.Options() N = opts.getInt('N', 10) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric-definite Eigenproblem, N=%d (%dx%d grid)" % (m*n, m, n)) A = Laplacian2D(m,n) B = QuasiDiagonal(m*n) solve_eigensystem(A,B) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908954.0 slepc4py-3.24.2/docs/source/demo/ex9.rst0000644000076500000240000001104515133664232017177 0ustar00jromanstaffex9.py: Generalized symmetric-definite eigenproblem =================================================== This example computes eigenvalues and eigenvectors of a generalized symmetric-definite eigenvalue problem, where the first matrix is the discrete Laplacian in two dimensions and the second matrix is quasi diagonal. The full source code for this demo can be `downloaded here <../_static/ex9.py>`__. Initialization is similar to previous examples. :: try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print This function builds the discretized Laplacian operator in 2 dimensions. :: def Laplacian2D(m, n): # Create matrix for 2D Laplacian operator A = PETSc.Mat().create() A.setSizes([m*n, m*n]) A.setFromOptions() # Fill matrix hx = 1.0/(m-1) # x grid spacing hy = 1.0/(n-1) # y grid spacing diagv = 2.0*hy/hx + 2.0*hx/hy offdx = -1.0*hy/hx offdy = -1.0*hx/hy Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = diagv i = I//n # map row number to j = I - i*n # grid coordinates if i> 0 : J = I-n; A[I,J] = offdx if i< m-1: J = I+n; A[I,J] = offdx if j> 0 : J = I-1; A[I,J] = offdy if j< n-1: J = I+1; A[I,J] = offdy A.assemble() return A This function builds a quasi-diagonal matrix. It is two times the identity matrix except for the 2x2 leading submatrix ``[6 -1; -1 1]``. :: def QuasiDiagonal(N): # Create matrix B = PETSc.Mat().create() B.setSizes([N, N]) B.setFromOptions() # Fill matrix Istart, Iend = B.getOwnershipRange() for I in range(Istart, Iend): B[I,I] = 2.0 if Istart==0: B[0,0] = 6.0 B[0,1] = -1.0 B[1,0] = -1.0 B[1,1] = 1.0 B.assemble() return B The following function receives the two matrices and solves the eigenproblem. In this example we illustrate how to pass objects that have been created beforehand, instead of extracting the internal objects. We are using a spectral transformation of type `ST.Type.PRECOND` and a Block Jacobi preconditioner. We want to compute the leftmost eigenvalues. The selected eigensolver is LOBPCG, which is appropriate for this use case. After the solve, we print the computed solution. :: def solve_eigensystem(A, B, problem_type=SLEPc.EPS.ProblemType.GHEP): # Create the results vectors xr, xi = A.createVecs() pc = PETSc.PC().create() # pc.setType(pc.Type.HYPRE) pc.setType(pc.Type.BJACOBI) ksp = PETSc.KSP().create() ksp.setType(ksp.Type.PREONLY) ksp.setPC( pc ) F = SLEPc.ST().create() F.setType(F.Type.PRECOND) F.setKSP( ksp ) F.setShift(0) # Setup the eigensolver E = SLEPc.EPS().create() E.setST(F) E.setOperators(A,B) E.setType(E.Type.LOBPCG) E.setDimensions(10,PETSc.DECIDE) E.setWhichEigenpairs(E.Which.SMALLEST_REAL) E.setProblemType( problem_type ) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("") The main program simply processes three user-defined command-line options and calls the other functions. :: def main(): opts = PETSc.Options() N = opts.getInt('N', 10) m = opts.getInt('m', N) n = opts.getInt('n', m) Print("Symmetric-definite Eigenproblem, N=%d (%dx%d grid)" % (m*n, m, n)) A = Laplacian2D(m,n) B = QuasiDiagonal(m*n) solve_eigensystem(A,B) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/index.rst0000644000076500000240000000407715133663436016671 0ustar00jromanstaff================ SLEPc for Python ================ .. only:: html or man :Authors: Lisandro Dalcin, Jose E. Roman :Contact: dalcinl@gmail.com, jroman@dsic.upv.es :Web Site: https://gitlab.com/slepc/slepc :Date: |today| .. topic:: Abstract This document describes slepc4py_, a Python_ wrapper to the SLEPc_ libraries. SLEPc_ is a software package for the parallel solution of large-scale eigenvalue problems. It can be used for computing eigenvalues and eigenvectors of large, sparse matrices, or matrix pairs, and also for computing singular values and vectors of a rectangular matrix. It also provides more advanced functionality such as solvers for nonlinear eigenvalue problems (either polynomial or general) and matrix functions. SLEPc_ relies on PETSc_ for basic functionality such as the representation of matrices and vectors, and the solution of linear systems of equations. Thus, slepc4py_ must be used together with its companion petsc4py_. Discussion and Support ====================== + You can write to the `PETSc Users Mailing List `__ + See also the `contact information for SLEPc `__ + Issue Tracker: https://gitlab.com/slepc/slepc/-/issues + Git Repository: https://gitlab.com/slepc/slepc.git (the source code is in ``src/binding/slepc4py``) + Current release in PyPI: https://pypi.org/project/slepc4py/ Acknowledgments =============== L. Dalcin was partially supported by the Extreme Computing Research Center (ECRC), Division of Computer, Electrical, and Mathematical Sciences & Engineering (CEMSE), King Abdullah University of Science and Technology (KAUST). See additional acknowledgements related to `the SLEPc project `__. Contents ======== .. include:: links.txt .. toctree:: :maxdepth: 2 overview tutorial install citing changes .. toctree:: :caption: Python specifics :maxdepth: 2 reference demo/demo ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/install.rst0000644000076500000240000000432115133663436017220 0ustar00jromanstaffInstallation ============ Install from PyPI using **pip** ------------------------------- You can use :program:`pip` to install slepc4py_ and its dependencies. If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install mpi4py_ first:: $ python -m pip install mpi4py Ensure you have NumPy_ and petsc4py_ installed:: $ python -m pip install numpy petsc petsc4py Finally, install slepc4py_:: $ python -m pip install slepc slepc4py If you already have working PETSc and SLEPc installs, set environment variables :envvar:`SLEPC_DIR` and :envvar:`PETSC_DIR` (and perhaps :envvar:`PETSC_ARCH` for non-prefix installs) to appropriate values and next use :program:`pip`:: $ export SLEPC_DIR=/path/to/slepc $ export PETSC_DIR=/path/to/petsc $ export PETSC_ARCH=arch-linux2-c-opt $ python -m pip install petsc4py slepc4py Install from the SLEPc source tree ---------------------------------- If you also want to install petsc4py_ from the PETSc source tree, follow the instructions in the `petsc4py installation`_ page. Set the :envvar:`PETSC_DIR` and :envvar:`PETSC_ARCH` environment variables, as well as :envvar:`SLEPC_DIR`. Follow the instructions to `build SLEPc`_. Then :file:`cd` to the top of the SLEPc source tree and run:: $ python -m pip install src/binding/slepc4py The installation of slepc4py_ supports multiple :envvar:`PETSC_ARCH` in the form of a colon separated list:: $ PETSC_ARCH='arch-0:...:arch-N' python -m pip install src/binding/slepc4py If you are cross-compiling, and the :mod:`numpy` module cannot be loaded on your build host, then before invoking :program:`pip`, set the :envvar:`NUMPY_INCLUDE` environment variable to the path that would be returned by :samp:`import numpy; numpy.get_include()`:: $ export NUMPY_INCLUDE=/usr/lib/pythonX/site-packages/numpy/core/include .. _NumPy: https://www.numpy.org .. _mpi4py: https://mpi4py.readthedocs.io .. _petsc4py: https://petsc.org/release/petsc4py/reference.html .. _petsc4py installation: https://petsc.org/release/petsc4py/install.html .. _slepc4py: https://slepc.upv.es/release/slepc4py/reference.html .. _build SLEPc: https://slepc.upv.es/release/installation/index.html ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/links.txt0000644000076500000240000000074315133663436016705 0ustar00jromanstaff.. _MPI: https://www.mpi-forum.org .. _MPICH: https://www.mpich.org .. _Open MPI: https://www.open-mpi.org .. _PETSc: https://petsc.org .. _SLEPc: https://slepc.upv.es .. _Python: https://www.python.org .. _NumPy: https://www.numpy.org .. _mpi4py: https://github.com/mpi4py/mpi4py .. _petsc4py: https://gitlab.com/petsc/petsc .. _slepc4py: https://gitlab.com/slepc/slepc .. Local Variables: .. mode: rst .. End: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/overview.rst0000644000076500000240000002043415133663436017423 0ustar00jromanstaffOverview ======== *SLEPc for Python* (slepc4py) is a Python package that provides convenient access to the functionality of SLEPc. SLEPc [1]_, [2]_ implements algorithms and tools for the numerical solution of large, sparse eigenvalue problems on parallel computers. It can be used for linear eigenvalue problems in either standard or generalized form, with real or complex arithmetic. It can also be used for computing a partial SVD of a large, sparse, rectangular matrix, and to solve nonlinear eigenvalue problems (polynomial or general). Additionally, SLEPc provides solvers for the computation of the action of a matrix function on a vector. SLEPc is intended for computing a subset of the spectrum of a matrix (or matrix pair). One can for instance approximate the largest magnitude eigenvalues, or the smallest ones, or even those eigenvalues located near a given region of the complex plane. Interior eigenvalues are harder to compute, so SLEPc provides different methodologies. One such method is to use a spectral transformation. Cheaper alternatives are also available. .. [1] J. E. Roman, C. Campos, L. Dalcin, E. Romero, A. Tomas. SLEPc Users Manual. DSIC-II/24/02 - Revision 3.24. D. Sistemas Informaticos y Computacion, Universitat Politecnica de Valencia. 2025. .. [2] Vicente Hernandez, Jose E. Roman and Vicente Vidal. SLEPc: A Scalable and Flexible Toolkit for the Solution of Eigenvalue Problems, ACM Trans. Math. Softw. 31(3), pp. 351-362, 2005. https://doi.org/10.1145/1089014.1089019 .. include:: links.txt Features -------- Currently, the following types of eigenproblems can be addressed: * Standard eigenvalue problem, :math:`Ax = \lambda x`, either for Hermitian or non-Hermitian matrices. * Generalized eigenvalue problem, :math:`Ax = \lambda Bx`, either Hermitian positive-definite or not. * Partial singular value decomposition of a rectangular matrix, :math:`Au = \sigma v`. * Generalized singular values of a matrix pair, :math:`Ax = cu`, :math:`Bx = sv`. * Polynomial eigenvalue problem, :math:`P(\lambda)=0`. * Nonlinear eigenvalue problem, :math:`T(\lambda)=0`. * Computing the action of a matrix function on a vector, :math:`w=f(\alpha A)v`. For the linear eigenvalue problem, the following methods are available: * Krylov eigensolvers, particularly Krylov-Schur, Arnoldi, and Lanczos. * Davidson-type eigensolvers, including Generalized Davidson and Jacobi-Davidson. * Subspace iteration and single vector iterations (inverse iteration, RQI). * Conjugate gradient methods such as LOBPCG. * A contour integral solver using high-order moments. For singular value computations, the following alternatives can be used: * Use an eigensolver via the cross-product matrix :math:`A^*A` or the cyclic matrix :math:`\left[\begin{smallmatrix}0&A\\A^*&0\end{smallmatrix}\right]`. * Explicitly restarted Lanczos bidiagonalization. * Implicitly restarted Lanczos bidiagonalization (thick-restart Lanczos). * A basic randomized solver. For polynomial eigenvalue problems, the following methods are available: * Use an eigensolver to solve the generalized eigenvalue problem obtained after linearization. * TOAR and Q-Arnoldi, memory efficient variants of Arnoldi for polynomial eigenproblems. * Jacobi-Davidson for polynomial eigenproblems. * A contour integral solver using high-order moments. For general nonlinear eigenvalue problems, the following methods can be used: * Solve a polynomial eigenproblem obtained via polynomial interpolation. * Rational interpolation and linearization (NLEIGS). * Newton-type methods such as SLP or RII. * A subspace projection method (nonlinear Arnoldi). * A contour integral solver using high-order moments. Computation of interior eigenvalues is supported by means of the following methodologies: * Spectral transformations, such as shift-and-invert. This technique implicitly uses the inverse of the shifted matrix :math:`A-\sigma I` in order to compute eigenvalues closest to a given target value, :math:`\sigma`. * Harmonic extraction, a cheap alternative to shift-and-invert that also tries to approximate eigenvalues closest to a target, :math:`\sigma`, but without requiring a matrix inversion. Other remarkable features include: * High computational efficiency, by using NumPy and SLEPc under the hood. * Data-structure neutral implementation, by using efficient sparse matrix storage provided by PETSc. Implicit matrix representation is also available by providing basic operations such as matrix-vector products as user-defined Python functions. * Run-time flexibility, by specifying numerous setting at the command line. * Ability to do the computation in parallel and/or using GPUs. Components ---------- SLEPc provides the following components, which are mirrored by slepc4py for its use from Python. The first six components are solvers for different classes of problems, while the rest can be considered auxiliary object. :EPS: The Eigenvalue Problem Solver is the component that provides all the functionality necessary to define and solve an eigenproblem. It provides mechanisms for completely specifying the problem: the problem type (e.g. standard symmetric), number of eigenvalues to compute, part of the spectrum of interest. Once the problem has been defined, a collection of solvers can be used to compute the required solutions. The behavior of the solvers can be tuned by means of a few parameters, such as the maximum dimension of the subspace to be used during the computation. :SVD: This component is the analog of ``EPS`` for the case of Singular Value Decompositions. The user provides a rectangular matrix and specifies how many singular values and vectors are to be computed, whether the largest or smallest ones, as well as some other parameters for fine tuning the computation. Different solvers are available, as in the case of ``EPS``. :PEP: This component is the analog of ``EPS`` for the case of Polynomial Eigenvalue Problems. The user provides the coefficient matrices of the polynomial. Several parameters can be specified, as in the case of ``EPS``. It is also possible to indicate whether the problem belongs to a special type, e.g., symmetric or gyroscopic. :NEP: This component covers the case of general nonlinear eigenproblems, :math:`T(\lambda)=0`. The user provides the parameter-dependent matrix :math:`T` via the split form or by means of callback functions. :MFN: This component provides the functionality for computing the action of a matrix function on a vector. Given a matrix :math:`A` and a vector :math:`b`, the call ``MFNSolve(mfn,b,x)`` computes :math:`x=f(A)b`, where :math:`f` is a function such as the exponential. :LME: This component provides the functionality for solving linear matrix equations such as Lyapunov or Sylvester where the solution has low rank. :ST: The Spectral Transformation is a component that provides convenient implementations of common spectral transformations. These are simple transformations that map eigenvalues to different positions, in such a way that convergence to wanted eigenvalues is enhanced. The most common spectral transformation is shift-and-invert, that allows for the computation of eigenvalues closest to a given target value. :BV: This component encapsulates the concept of a set of Basis Vectors spanning a vector space. This component provides convenient access to common operations such as orthogonalization of vectors. The ``BV`` component is usually not required by end-users. :DS: The Dense System (or Direct Solver) component, used internally to solve dense eigenproblems of small size that appear in the course of iterative eigensolvers. :FN: A component used to define mathematical functions. This is required by the end-user for instance to define function :math:`T(\cdot)` when solving nonlinear eigenproblems with ``NEP`` in split form. :RG: A component used to define a region of the complex plane such as an ellipse or a rectangle. This is required by end-users in some cases such as contour-integral eigensolvers. In addition to the above components, some extra functionality is provided in the ``Sys`` and ``Util`` sections. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5383024 slepc4py-3.24.2/docs/source/reference/0000755000076500000240000000000015133664271016754 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.MatMultType.rst0000644000076500000240000000060715133664236024714 0ustar00jromanstaffslepc4py.SLEPc.BV.MatMultType ============================= .. autoclass:: slepc4py.SLEPc.BV.MatMultType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.MatMultType.MAT ~slepc4py.SLEPc.BV.MatMultType.VECS .. rubric:: Attributes Documentation .. autoattribute:: MAT .. autoattribute:: VECS ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.OrthogBlockType.rst0000644000076500000240000000117415133664236025546 0ustar00jromanstaffslepc4py.SLEPc.BV.OrthogBlockType ================================= .. autoclass:: slepc4py.SLEPc.BV.OrthogBlockType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.OrthogBlockType.CHOL ~slepc4py.SLEPc.BV.OrthogBlockType.GS ~slepc4py.SLEPc.BV.OrthogBlockType.SVQB ~slepc4py.SLEPc.BV.OrthogBlockType.TSQR ~slepc4py.SLEPc.BV.OrthogBlockType.TSQRCHOL .. rubric:: Attributes Documentation .. autoattribute:: CHOL .. autoattribute:: GS .. autoattribute:: SVQB .. autoattribute:: TSQR .. autoattribute:: TSQRCHOL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.OrthogRefineType.rst0000644000076500000240000000077215133664236025727 0ustar00jromanstaffslepc4py.SLEPc.BV.OrthogRefineType ================================== .. autoclass:: slepc4py.SLEPc.BV.OrthogRefineType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.OrthogRefineType.ALWAYS ~slepc4py.SLEPc.BV.OrthogRefineType.IFNEEDED ~slepc4py.SLEPc.BV.OrthogRefineType.NEVER .. rubric:: Attributes Documentation .. autoattribute:: ALWAYS .. autoattribute:: IFNEEDED .. autoattribute:: NEVER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.OrthogType.rst0000644000076500000240000000060015133664236024564 0ustar00jromanstaffslepc4py.SLEPc.BV.OrthogType ============================ .. autoclass:: slepc4py.SLEPc.BV.OrthogType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.OrthogType.CGS ~slepc4py.SLEPc.BV.OrthogType.MGS .. rubric:: Attributes Documentation .. autoattribute:: CGS .. autoattribute:: MGS ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.SVDMethod.rst0000644000076500000240000000070615133664236024264 0ustar00jromanstaffslepc4py.SLEPc.BV.SVDMethod =========================== .. autoclass:: slepc4py.SLEPc.BV.SVDMethod :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.SVDMethod.QR ~slepc4py.SLEPc.BV.SVDMethod.QR_CAA ~slepc4py.SLEPc.BV.SVDMethod.REFINE .. rubric:: Attributes Documentation .. autoattribute:: QR .. autoattribute:: QR_CAA .. autoattribute:: REFINE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.Type.rst0000644000076500000240000000105615133664236023407 0ustar00jromanstaffslepc4py.SLEPc.BV.Type ====================== .. autoclass:: slepc4py.SLEPc.BV.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.Type.CONTIGUOUS ~slepc4py.SLEPc.BV.Type.MAT ~slepc4py.SLEPc.BV.Type.SVEC ~slepc4py.SLEPc.BV.Type.TENSOR ~slepc4py.SLEPc.BV.Type.VECS .. rubric:: Attributes Documentation .. autoattribute:: CONTIGUOUS .. autoattribute:: MAT .. autoattribute:: SVEC .. autoattribute:: TENSOR .. autoattribute:: VECS ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.BV.rst0000644000076500000240000001402015133664234022460 0ustar00jromanstaffslepc4py.SLEPc.BV ================= .. autoclass:: slepc4py.SLEPc.BV :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.BV.MatMultType ~slepc4py.SLEPc.BV.OrthogBlockType ~slepc4py.SLEPc.BV.OrthogRefineType ~slepc4py.SLEPc.BV.OrthogType ~slepc4py.SLEPc.BV.SVDMethod ~slepc4py.SLEPc.BV.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.BV.appendOptionsPrefix ~slepc4py.SLEPc.BV.applyMatrix ~slepc4py.SLEPc.BV.copy ~slepc4py.SLEPc.BV.copyColumn ~slepc4py.SLEPc.BV.copyVec ~slepc4py.SLEPc.BV.create ~slepc4py.SLEPc.BV.createFromMat ~slepc4py.SLEPc.BV.createMat ~slepc4py.SLEPc.BV.createVec ~slepc4py.SLEPc.BV.destroy ~slepc4py.SLEPc.BV.dot ~slepc4py.SLEPc.BV.dotColumn ~slepc4py.SLEPc.BV.dotVec ~slepc4py.SLEPc.BV.duplicate ~slepc4py.SLEPc.BV.duplicateResize ~slepc4py.SLEPc.BV.getActiveColumns ~slepc4py.SLEPc.BV.getArray ~slepc4py.SLEPc.BV.getColumn ~slepc4py.SLEPc.BV.getDefiniteTolerance ~slepc4py.SLEPc.BV.getLeadingDimension ~slepc4py.SLEPc.BV.getMat ~slepc4py.SLEPc.BV.getMatMultMethod ~slepc4py.SLEPc.BV.getMatrix ~slepc4py.SLEPc.BV.getNumConstraints ~slepc4py.SLEPc.BV.getOptionsPrefix ~slepc4py.SLEPc.BV.getOrthogonalization ~slepc4py.SLEPc.BV.getRandomContext ~slepc4py.SLEPc.BV.getSizes ~slepc4py.SLEPc.BV.getType ~slepc4py.SLEPc.BV.getVecType ~slepc4py.SLEPc.BV.insertConstraints ~slepc4py.SLEPc.BV.insertVec ~slepc4py.SLEPc.BV.insertVecs ~slepc4py.SLEPc.BV.matMult ~slepc4py.SLEPc.BV.matMultColumn ~slepc4py.SLEPc.BV.matMultHermitianTranspose ~slepc4py.SLEPc.BV.matMultHermitianTransposeColumn ~slepc4py.SLEPc.BV.matMultTranspose ~slepc4py.SLEPc.BV.matMultTransposeColumn ~slepc4py.SLEPc.BV.matProject ~slepc4py.SLEPc.BV.mult ~slepc4py.SLEPc.BV.multColumn ~slepc4py.SLEPc.BV.multInPlace ~slepc4py.SLEPc.BV.multVec ~slepc4py.SLEPc.BV.norm ~slepc4py.SLEPc.BV.normColumn ~slepc4py.SLEPc.BV.orthogonalize ~slepc4py.SLEPc.BV.orthogonalizeColumn ~slepc4py.SLEPc.BV.orthogonalizeVec ~slepc4py.SLEPc.BV.orthonormalizeColumn ~slepc4py.SLEPc.BV.resize ~slepc4py.SLEPc.BV.restoreColumn ~slepc4py.SLEPc.BV.restoreMat ~slepc4py.SLEPc.BV.scale ~slepc4py.SLEPc.BV.scaleColumn ~slepc4py.SLEPc.BV.setActiveColumns ~slepc4py.SLEPc.BV.setDefiniteTolerance ~slepc4py.SLEPc.BV.setFromOptions ~slepc4py.SLEPc.BV.setLeadingDimension ~slepc4py.SLEPc.BV.setMatMultMethod ~slepc4py.SLEPc.BV.setMatrix ~slepc4py.SLEPc.BV.setNumConstraints ~slepc4py.SLEPc.BV.setOptionsPrefix ~slepc4py.SLEPc.BV.setOrthogonalization ~slepc4py.SLEPc.BV.setRandom ~slepc4py.SLEPc.BV.setRandomColumn ~slepc4py.SLEPc.BV.setRandomCond ~slepc4py.SLEPc.BV.setRandomContext ~slepc4py.SLEPc.BV.setRandomNormal ~slepc4py.SLEPc.BV.setRandomSign ~slepc4py.SLEPc.BV.setSizes ~slepc4py.SLEPc.BV.setSizesFromVec ~slepc4py.SLEPc.BV.setType ~slepc4py.SLEPc.BV.setVecType ~slepc4py.SLEPc.BV.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.BV.column_size ~slepc4py.SLEPc.BV.local_size ~slepc4py.SLEPc.BV.size ~slepc4py.SLEPc.BV.sizes .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: applyMatrix .. automethod:: copy .. automethod:: copyColumn .. automethod:: copyVec .. automethod:: create .. automethod:: createFromMat .. automethod:: createMat .. automethod:: createVec .. automethod:: destroy .. automethod:: dot .. automethod:: dotColumn .. automethod:: dotVec .. automethod:: duplicate .. automethod:: duplicateResize .. automethod:: getActiveColumns .. automethod:: getArray .. automethod:: getColumn .. automethod:: getDefiniteTolerance .. automethod:: getLeadingDimension .. automethod:: getMat .. automethod:: getMatMultMethod .. automethod:: getMatrix .. automethod:: getNumConstraints .. automethod:: getOptionsPrefix .. automethod:: getOrthogonalization .. automethod:: getRandomContext .. automethod:: getSizes .. automethod:: getType .. automethod:: getVecType .. automethod:: insertConstraints .. automethod:: insertVec .. automethod:: insertVecs .. automethod:: matMult .. automethod:: matMultColumn .. automethod:: matMultHermitianTranspose .. automethod:: matMultHermitianTransposeColumn .. automethod:: matMultTranspose .. automethod:: matMultTransposeColumn .. automethod:: matProject .. automethod:: mult .. automethod:: multColumn .. automethod:: multInPlace .. automethod:: multVec .. automethod:: norm .. automethod:: normColumn .. automethod:: orthogonalize .. automethod:: orthogonalizeColumn .. automethod:: orthogonalizeVec .. automethod:: orthonormalizeColumn .. automethod:: resize .. automethod:: restoreColumn .. automethod:: restoreMat .. automethod:: scale .. automethod:: scaleColumn .. automethod:: setActiveColumns .. automethod:: setDefiniteTolerance .. automethod:: setFromOptions .. automethod:: setLeadingDimension .. automethod:: setMatMultMethod .. automethod:: setMatrix .. automethod:: setNumConstraints .. automethod:: setOptionsPrefix .. automethod:: setOrthogonalization .. automethod:: setRandom .. automethod:: setRandomColumn .. automethod:: setRandomCond .. automethod:: setRandomContext .. automethod:: setRandomNormal .. automethod:: setRandomSign .. automethod:: setSizes .. automethod:: setSizesFromVec .. automethod:: setType .. automethod:: setVecType .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: column_size .. autoattribute:: local_size .. autoattribute:: size .. autoattribute:: sizes ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.CURRENT.rst0000644000076500000240000000014715133664234023300 0ustar00jromanstaffslepc4py.SLEPc.CURRENT ====================== .. currentmodule:: slepc4py.SLEPc .. autodata:: CURRENT././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DECIDE.rst0000644000076500000240000000014415133664234023070 0ustar00jromanstaffslepc4py.SLEPc.DECIDE ===================== .. currentmodule:: slepc4py.SLEPc .. autodata:: DECIDE././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DEFAULT.rst0000644000076500000240000000014715133664234023242 0ustar00jromanstaffslepc4py.SLEPc.DEFAULT ====================== .. currentmodule:: slepc4py.SLEPc .. autodata:: DEFAULT././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DETERMINE.rst0000644000076500000240000000015515133664234023471 0ustar00jromanstaffslepc4py.SLEPc.DETERMINE ======================== .. currentmodule:: slepc4py.SLEPc .. autodata:: DETERMINE././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DS.MatType.rst0000644000076500000240000000166715133664236024060 0ustar00jromanstaffslepc4py.SLEPc.DS.MatType ========================= .. autoclass:: slepc4py.SLEPc.DS.MatType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.DS.MatType.A ~slepc4py.SLEPc.DS.MatType.B ~slepc4py.SLEPc.DS.MatType.C ~slepc4py.SLEPc.DS.MatType.D ~slepc4py.SLEPc.DS.MatType.Q ~slepc4py.SLEPc.DS.MatType.T ~slepc4py.SLEPc.DS.MatType.U ~slepc4py.SLEPc.DS.MatType.V ~slepc4py.SLEPc.DS.MatType.W ~slepc4py.SLEPc.DS.MatType.X ~slepc4py.SLEPc.DS.MatType.Y ~slepc4py.SLEPc.DS.MatType.Z .. rubric:: Attributes Documentation .. autoattribute:: A .. autoattribute:: B .. autoattribute:: C .. autoattribute:: D .. autoattribute:: Q .. autoattribute:: T .. autoattribute:: U .. autoattribute:: V .. autoattribute:: W .. autoattribute:: X .. autoattribute:: Y .. autoattribute:: Z ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DS.ParallelType.rst0000644000076500000240000000077415133664236025071 0ustar00jromanstaffslepc4py.SLEPc.DS.ParallelType ============================== .. autoclass:: slepc4py.SLEPc.DS.ParallelType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.DS.ParallelType.DISTRIBUTED ~slepc4py.SLEPc.DS.ParallelType.REDUNDANT ~slepc4py.SLEPc.DS.ParallelType.SYNCHRONIZED .. rubric:: Attributes Documentation .. autoattribute:: DISTRIBUTED .. autoattribute:: REDUNDANT .. autoattribute:: SYNCHRONIZED ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DS.StateType.rst0000644000076500000240000000104715133664237024410 0ustar00jromanstaffslepc4py.SLEPc.DS.StateType =========================== .. autoclass:: slepc4py.SLEPc.DS.StateType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.DS.StateType.CONDENSED ~slepc4py.SLEPc.DS.StateType.INTERMEDIATE ~slepc4py.SLEPc.DS.StateType.RAW ~slepc4py.SLEPc.DS.StateType.TRUNCATED .. rubric:: Attributes Documentation .. autoattribute:: CONDENSED .. autoattribute:: INTERMEDIATE .. autoattribute:: RAW .. autoattribute:: TRUNCATED ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DS.Type.rst0000644000076500000240000000162415133664237023410 0ustar00jromanstaffslepc4py.SLEPc.DS.Type ====================== .. autoclass:: slepc4py.SLEPc.DS.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.DS.Type.GHEP ~slepc4py.SLEPc.DS.Type.GHIEP ~slepc4py.SLEPc.DS.Type.GNHEP ~slepc4py.SLEPc.DS.Type.GSVD ~slepc4py.SLEPc.DS.Type.HEP ~slepc4py.SLEPc.DS.Type.HSVD ~slepc4py.SLEPc.DS.Type.NEP ~slepc4py.SLEPc.DS.Type.NHEP ~slepc4py.SLEPc.DS.Type.NHEPTS ~slepc4py.SLEPc.DS.Type.PEP ~slepc4py.SLEPc.DS.Type.SVD .. rubric:: Attributes Documentation .. autoattribute:: GHEP .. autoattribute:: GHIEP .. autoattribute:: GNHEP .. autoattribute:: GSVD .. autoattribute:: HEP .. autoattribute:: HSVD .. autoattribute:: NEP .. autoattribute:: NHEP .. autoattribute:: NHEPTS .. autoattribute:: PEP .. autoattribute:: SVD ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.DS.rst0000644000076500000240000001023215133664234022460 0ustar00jromanstaffslepc4py.SLEPc.DS ================= .. autoclass:: slepc4py.SLEPc.DS :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.DS.MatType ~slepc4py.SLEPc.DS.ParallelType ~slepc4py.SLEPc.DS.StateType ~slepc4py.SLEPc.DS.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.DS.allocate ~slepc4py.SLEPc.DS.appendOptionsPrefix ~slepc4py.SLEPc.DS.cond ~slepc4py.SLEPc.DS.create ~slepc4py.SLEPc.DS.destroy ~slepc4py.SLEPc.DS.duplicate ~slepc4py.SLEPc.DS.getArray ~slepc4py.SLEPc.DS.getBlockSize ~slepc4py.SLEPc.DS.getCompact ~slepc4py.SLEPc.DS.getDimensions ~slepc4py.SLEPc.DS.getExtraRow ~slepc4py.SLEPc.DS.getGSVDDimensions ~slepc4py.SLEPc.DS.getHSVDDimensions ~slepc4py.SLEPc.DS.getLeadingDimension ~slepc4py.SLEPc.DS.getMat ~slepc4py.SLEPc.DS.getMethod ~slepc4py.SLEPc.DS.getOptionsPrefix ~slepc4py.SLEPc.DS.getPEPCoefficients ~slepc4py.SLEPc.DS.getPEPDegree ~slepc4py.SLEPc.DS.getParallel ~slepc4py.SLEPc.DS.getRefined ~slepc4py.SLEPc.DS.getSVDDimensions ~slepc4py.SLEPc.DS.getState ~slepc4py.SLEPc.DS.getType ~slepc4py.SLEPc.DS.reset ~slepc4py.SLEPc.DS.restoreMat ~slepc4py.SLEPc.DS.setBlockSize ~slepc4py.SLEPc.DS.setCompact ~slepc4py.SLEPc.DS.setDimensions ~slepc4py.SLEPc.DS.setExtraRow ~slepc4py.SLEPc.DS.setFromOptions ~slepc4py.SLEPc.DS.setGSVDDimensions ~slepc4py.SLEPc.DS.setHSVDDimensions ~slepc4py.SLEPc.DS.setIdentity ~slepc4py.SLEPc.DS.setMethod ~slepc4py.SLEPc.DS.setOptionsPrefix ~slepc4py.SLEPc.DS.setPEPCoefficients ~slepc4py.SLEPc.DS.setPEPDegree ~slepc4py.SLEPc.DS.setParallel ~slepc4py.SLEPc.DS.setRefined ~slepc4py.SLEPc.DS.setSVDDimensions ~slepc4py.SLEPc.DS.setState ~slepc4py.SLEPc.DS.setType ~slepc4py.SLEPc.DS.solve ~slepc4py.SLEPc.DS.truncate ~slepc4py.SLEPc.DS.updateExtraRow ~slepc4py.SLEPc.DS.vectors ~slepc4py.SLEPc.DS.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.DS.block_size ~slepc4py.SLEPc.DS.compact ~slepc4py.SLEPc.DS.extra_row ~slepc4py.SLEPc.DS.method ~slepc4py.SLEPc.DS.parallel ~slepc4py.SLEPc.DS.refined ~slepc4py.SLEPc.DS.state .. rubric:: Methods Documentation .. automethod:: allocate .. automethod:: appendOptionsPrefix .. automethod:: cond .. automethod:: create .. automethod:: destroy .. automethod:: duplicate .. automethod:: getArray .. automethod:: getBlockSize .. automethod:: getCompact .. automethod:: getDimensions .. automethod:: getExtraRow .. automethod:: getGSVDDimensions .. automethod:: getHSVDDimensions .. automethod:: getLeadingDimension .. automethod:: getMat .. automethod:: getMethod .. automethod:: getOptionsPrefix .. automethod:: getPEPCoefficients .. automethod:: getPEPDegree .. automethod:: getParallel .. automethod:: getRefined .. automethod:: getSVDDimensions .. automethod:: getState .. automethod:: getType .. automethod:: reset .. automethod:: restoreMat .. automethod:: setBlockSize .. automethod:: setCompact .. automethod:: setDimensions .. automethod:: setExtraRow .. automethod:: setFromOptions .. automethod:: setGSVDDimensions .. automethod:: setHSVDDimensions .. automethod:: setIdentity .. automethod:: setMethod .. automethod:: setOptionsPrefix .. automethod:: setPEPCoefficients .. automethod:: setPEPDegree .. automethod:: setParallel .. automethod:: setRefined .. automethod:: setSVDDimensions .. automethod:: setState .. automethod:: setType .. automethod:: solve .. automethod:: truncate .. automethod:: updateExtraRow .. automethod:: vectors .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: block_size .. autoattribute:: compact .. autoattribute:: extra_row .. autoattribute:: method .. autoattribute:: parallel .. autoattribute:: refined .. autoattribute:: state ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Balance.rst0000644000076500000240000000101215133664237024124 0ustar00jromanstaffslepc4py.SLEPc.EPS.Balance ========================== .. autoclass:: slepc4py.SLEPc.EPS.Balance :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Balance.NONE ~slepc4py.SLEPc.EPS.Balance.ONESIDE ~slepc4py.SLEPc.EPS.Balance.TWOSIDE ~slepc4py.SLEPc.EPS.Balance.USER .. rubric:: Attributes Documentation .. autoattribute:: NONE .. autoattribute:: ONESIDE .. autoattribute:: TWOSIDE .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.CISSExtraction.rst0000644000076500000240000000064115133664237025410 0ustar00jromanstaffslepc4py.SLEPc.EPS.CISSExtraction ================================= .. autoclass:: slepc4py.SLEPc.EPS.CISSExtraction :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.CISSExtraction.HANKEL ~slepc4py.SLEPc.EPS.CISSExtraction.RITZ .. rubric:: Attributes Documentation .. autoattribute:: HANKEL .. autoattribute:: RITZ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.CISSQuadRule.rst0000644000076500000240000000065315133664237025015 0ustar00jromanstaffslepc4py.SLEPc.EPS.CISSQuadRule =============================== .. autoclass:: slepc4py.SLEPc.EPS.CISSQuadRule :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.CISSQuadRule.CHEBYSHEV ~slepc4py.SLEPc.EPS.CISSQuadRule.TRAPEZOIDAL .. rubric:: Attributes Documentation .. autoattribute:: CHEBYSHEV .. autoattribute:: TRAPEZOIDAL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Conv.rst0000644000076500000240000000074515133664237023520 0ustar00jromanstaffslepc4py.SLEPc.EPS.Conv ======================= .. autoclass:: slepc4py.SLEPc.EPS.Conv :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Conv.ABS ~slepc4py.SLEPc.EPS.Conv.NORM ~slepc4py.SLEPc.EPS.Conv.REL ~slepc4py.SLEPc.EPS.Conv.USER .. rubric:: Attributes Documentation .. autoattribute:: ABS .. autoattribute:: NORM .. autoattribute:: REL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.ConvergedReason.rst0000644000076500000240000000166215133664237025676 0ustar00jromanstaffslepc4py.SLEPc.EPS.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.EPS.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.EPS.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.EPS.ConvergedReason.CONVERGED_USER ~slepc4py.SLEPc.EPS.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.EPS.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.EPS.ConvergedReason.DIVERGED_SYMMETRY_LOST ~slepc4py.SLEPc.EPS.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_TOL .. autoattribute:: CONVERGED_USER .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: DIVERGED_SYMMETRY_LOST .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.ErrorType.rst0000644000076500000240000000074015133664237024541 0ustar00jromanstaffslepc4py.SLEPc.EPS.ErrorType ============================ .. autoclass:: slepc4py.SLEPc.EPS.ErrorType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.ErrorType.ABSOLUTE ~slepc4py.SLEPc.EPS.ErrorType.BACKWARD ~slepc4py.SLEPc.EPS.ErrorType.RELATIVE .. rubric:: Attributes Documentation .. autoattribute:: ABSOLUTE .. autoattribute:: BACKWARD .. autoattribute:: RELATIVE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Extraction.rst0000644000076500000240000000151615133664237024730 0ustar00jromanstaffslepc4py.SLEPc.EPS.Extraction ============================= .. autoclass:: slepc4py.SLEPc.EPS.Extraction :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Extraction.HARMONIC ~slepc4py.SLEPc.EPS.Extraction.HARMONIC_LARGEST ~slepc4py.SLEPc.EPS.Extraction.HARMONIC_RELATIVE ~slepc4py.SLEPc.EPS.Extraction.HARMONIC_RIGHT ~slepc4py.SLEPc.EPS.Extraction.REFINED ~slepc4py.SLEPc.EPS.Extraction.REFINED_HARMONIC ~slepc4py.SLEPc.EPS.Extraction.RITZ .. rubric:: Attributes Documentation .. autoattribute:: HARMONIC .. autoattribute:: HARMONIC_LARGEST .. autoattribute:: HARMONIC_RELATIVE .. autoattribute:: HARMONIC_RIGHT .. autoattribute:: REFINED .. autoattribute:: REFINED_HARMONIC .. autoattribute:: RITZ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.KrylovSchurBSEType.rst0000644000076500000240000000102415133664237026271 0ustar00jromanstaffslepc4py.SLEPc.EPS.KrylovSchurBSEType ===================================== .. autoclass:: slepc4py.SLEPc.EPS.KrylovSchurBSEType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.KrylovSchurBSEType.GRUNING ~slepc4py.SLEPc.EPS.KrylovSchurBSEType.PROJECTEDBSE ~slepc4py.SLEPc.EPS.KrylovSchurBSEType.SHAO .. rubric:: Attributes Documentation .. autoattribute:: GRUNING .. autoattribute:: PROJECTEDBSE .. autoattribute:: SHAO ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.LanczosReorthogType.rst0000644000076500000240000000141615133664237026574 0ustar00jromanstaffslepc4py.SLEPc.EPS.LanczosReorthogType ====================================== .. autoclass:: slepc4py.SLEPc.EPS.LanczosReorthogType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.LanczosReorthogType.DELAYED ~slepc4py.SLEPc.EPS.LanczosReorthogType.FULL ~slepc4py.SLEPc.EPS.LanczosReorthogType.LOCAL ~slepc4py.SLEPc.EPS.LanczosReorthogType.PARTIAL ~slepc4py.SLEPc.EPS.LanczosReorthogType.PERIODIC ~slepc4py.SLEPc.EPS.LanczosReorthogType.SELECTIVE .. rubric:: Attributes Documentation .. autoattribute:: DELAYED .. autoattribute:: FULL .. autoattribute:: LOCAL .. autoattribute:: PARTIAL .. autoattribute:: PERIODIC .. autoattribute:: SELECTIVE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.PowerShiftType.rst0000644000076500000240000000100015133664237025530 0ustar00jromanstaffslepc4py.SLEPc.EPS.PowerShiftType ================================= .. autoclass:: slepc4py.SLEPc.EPS.PowerShiftType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.PowerShiftType.CONSTANT ~slepc4py.SLEPc.EPS.PowerShiftType.RAYLEIGH ~slepc4py.SLEPc.EPS.PowerShiftType.WILKINSON .. rubric:: Attributes Documentation .. autoattribute:: CONSTANT .. autoattribute:: RAYLEIGH .. autoattribute:: WILKINSON ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.ProblemType.rst0000644000076500000240000000147215133664237025053 0ustar00jromanstaffslepc4py.SLEPc.EPS.ProblemType ============================== .. autoclass:: slepc4py.SLEPc.EPS.ProblemType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.ProblemType.BSE ~slepc4py.SLEPc.EPS.ProblemType.GHEP ~slepc4py.SLEPc.EPS.ProblemType.GHIEP ~slepc4py.SLEPc.EPS.ProblemType.GNHEP ~slepc4py.SLEPc.EPS.ProblemType.HAMILT ~slepc4py.SLEPc.EPS.ProblemType.HEP ~slepc4py.SLEPc.EPS.ProblemType.NHEP ~slepc4py.SLEPc.EPS.ProblemType.PGNHEP .. rubric:: Attributes Documentation .. autoattribute:: BSE .. autoattribute:: GHEP .. autoattribute:: GHIEP .. autoattribute:: GNHEP .. autoattribute:: HAMILT .. autoattribute:: HEP .. autoattribute:: NHEP .. autoattribute:: PGNHEP ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Stop.rst0000644000076500000240000000066615133664237023542 0ustar00jromanstaffslepc4py.SLEPc.EPS.Stop ======================= .. autoclass:: slepc4py.SLEPc.EPS.Stop :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Stop.BASIC ~slepc4py.SLEPc.EPS.Stop.THRESHOLD ~slepc4py.SLEPc.EPS.Stop.USER .. rubric:: Attributes Documentation .. autoattribute:: BASIC .. autoattribute:: THRESHOLD .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Type.rst0000644000076500000240000000314415133664237023530 0ustar00jromanstaffslepc4py.SLEPc.EPS.Type ======================= .. autoclass:: slepc4py.SLEPc.EPS.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Type.ARNOLDI ~slepc4py.SLEPc.EPS.Type.ARPACK ~slepc4py.SLEPc.EPS.Type.BLOPEX ~slepc4py.SLEPc.EPS.Type.CHASE ~slepc4py.SLEPc.EPS.Type.CISS ~slepc4py.SLEPc.EPS.Type.ELEMENTAL ~slepc4py.SLEPc.EPS.Type.ELPA ~slepc4py.SLEPc.EPS.Type.EVSL ~slepc4py.SLEPc.EPS.Type.FEAST ~slepc4py.SLEPc.EPS.Type.GD ~slepc4py.SLEPc.EPS.Type.JD ~slepc4py.SLEPc.EPS.Type.KRYLOVSCHUR ~slepc4py.SLEPc.EPS.Type.LANCZOS ~slepc4py.SLEPc.EPS.Type.LAPACK ~slepc4py.SLEPc.EPS.Type.LOBPCG ~slepc4py.SLEPc.EPS.Type.LYAPII ~slepc4py.SLEPc.EPS.Type.POWER ~slepc4py.SLEPc.EPS.Type.PRIMME ~slepc4py.SLEPc.EPS.Type.RQCG ~slepc4py.SLEPc.EPS.Type.SCALAPACK ~slepc4py.SLEPc.EPS.Type.SUBSPACE .. rubric:: Attributes Documentation .. autoattribute:: ARNOLDI .. autoattribute:: ARPACK .. autoattribute:: BLOPEX .. autoattribute:: CHASE .. autoattribute:: CISS .. autoattribute:: ELEMENTAL .. autoattribute:: ELPA .. autoattribute:: EVSL .. autoattribute:: FEAST .. autoattribute:: GD .. autoattribute:: JD .. autoattribute:: KRYLOVSCHUR .. autoattribute:: LANCZOS .. autoattribute:: LAPACK .. autoattribute:: LOBPCG .. autoattribute:: LYAPII .. autoattribute:: POWER .. autoattribute:: PRIMME .. autoattribute:: RQCG .. autoattribute:: SCALAPACK .. autoattribute:: SUBSPACE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.Which.rst0000644000076500000240000000217215133664237023651 0ustar00jromanstaffslepc4py.SLEPc.EPS.Which ======================== .. autoclass:: slepc4py.SLEPc.EPS.Which :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.Which.ALL ~slepc4py.SLEPc.EPS.Which.LARGEST_IMAGINARY ~slepc4py.SLEPc.EPS.Which.LARGEST_MAGNITUDE ~slepc4py.SLEPc.EPS.Which.LARGEST_REAL ~slepc4py.SLEPc.EPS.Which.SMALLEST_IMAGINARY ~slepc4py.SLEPc.EPS.Which.SMALLEST_MAGNITUDE ~slepc4py.SLEPc.EPS.Which.SMALLEST_REAL ~slepc4py.SLEPc.EPS.Which.TARGET_IMAGINARY ~slepc4py.SLEPc.EPS.Which.TARGET_MAGNITUDE ~slepc4py.SLEPc.EPS.Which.TARGET_REAL ~slepc4py.SLEPc.EPS.Which.USER .. rubric:: Attributes Documentation .. autoattribute:: ALL .. autoattribute:: LARGEST_IMAGINARY .. autoattribute:: LARGEST_MAGNITUDE .. autoattribute:: LARGEST_REAL .. autoattribute:: SMALLEST_IMAGINARY .. autoattribute:: SMALLEST_MAGNITUDE .. autoattribute:: SMALLEST_REAL .. autoattribute:: TARGET_IMAGINARY .. autoattribute:: TARGET_MAGNITUDE .. autoattribute:: TARGET_REAL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.EPS.rst0000644000076500000240000003233215133664234022606 0ustar00jromanstaffslepc4py.SLEPc.EPS ================== .. autoclass:: slepc4py.SLEPc.EPS :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.EPS.Balance ~slepc4py.SLEPc.EPS.CISSExtraction ~slepc4py.SLEPc.EPS.CISSQuadRule ~slepc4py.SLEPc.EPS.Conv ~slepc4py.SLEPc.EPS.ConvergedReason ~slepc4py.SLEPc.EPS.ErrorType ~slepc4py.SLEPc.EPS.Extraction ~slepc4py.SLEPc.EPS.KrylovSchurBSEType ~slepc4py.SLEPc.EPS.LanczosReorthogType ~slepc4py.SLEPc.EPS.PowerShiftType ~slepc4py.SLEPc.EPS.ProblemType ~slepc4py.SLEPc.EPS.Stop ~slepc4py.SLEPc.EPS.Type ~slepc4py.SLEPc.EPS.Which .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.EPS.appendOptionsPrefix ~slepc4py.SLEPc.EPS.cancelMonitor ~slepc4py.SLEPc.EPS.computeError ~slepc4py.SLEPc.EPS.create ~slepc4py.SLEPc.EPS.destroy ~slepc4py.SLEPc.EPS.errorView ~slepc4py.SLEPc.EPS.getArbitrarySelection ~slepc4py.SLEPc.EPS.getArnoldiDelayed ~slepc4py.SLEPc.EPS.getBV ~slepc4py.SLEPc.EPS.getBalance ~slepc4py.SLEPc.EPS.getCISSExtraction ~slepc4py.SLEPc.EPS.getCISSKSPs ~slepc4py.SLEPc.EPS.getCISSQuadRule ~slepc4py.SLEPc.EPS.getCISSRefinement ~slepc4py.SLEPc.EPS.getCISSSizes ~slepc4py.SLEPc.EPS.getCISSThreshold ~slepc4py.SLEPc.EPS.getCISSUseST ~slepc4py.SLEPc.EPS.getConverged ~slepc4py.SLEPc.EPS.getConvergedReason ~slepc4py.SLEPc.EPS.getConvergenceTest ~slepc4py.SLEPc.EPS.getDS ~slepc4py.SLEPc.EPS.getDimensions ~slepc4py.SLEPc.EPS.getEigenpair ~slepc4py.SLEPc.EPS.getEigenvalue ~slepc4py.SLEPc.EPS.getEigenvalueComparison ~slepc4py.SLEPc.EPS.getEigenvector ~slepc4py.SLEPc.EPS.getErrorEstimate ~slepc4py.SLEPc.EPS.getExtraction ~slepc4py.SLEPc.EPS.getGDBOrth ~slepc4py.SLEPc.EPS.getGDBlockSize ~slepc4py.SLEPc.EPS.getGDDoubleExpansion ~slepc4py.SLEPc.EPS.getGDInitialSize ~slepc4py.SLEPc.EPS.getGDKrylovStart ~slepc4py.SLEPc.EPS.getGDRestart ~slepc4py.SLEPc.EPS.getInterval ~slepc4py.SLEPc.EPS.getInvariantSubspace ~slepc4py.SLEPc.EPS.getIterationNumber ~slepc4py.SLEPc.EPS.getJDBOrth ~slepc4py.SLEPc.EPS.getJDBlockSize ~slepc4py.SLEPc.EPS.getJDConstCorrectionTol ~slepc4py.SLEPc.EPS.getJDFix ~slepc4py.SLEPc.EPS.getJDInitialSize ~slepc4py.SLEPc.EPS.getJDKrylovStart ~slepc4py.SLEPc.EPS.getJDRestart ~slepc4py.SLEPc.EPS.getKrylovSchurBSEType ~slepc4py.SLEPc.EPS.getKrylovSchurDetectZeros ~slepc4py.SLEPc.EPS.getKrylovSchurDimensions ~slepc4py.SLEPc.EPS.getKrylovSchurInertias ~slepc4py.SLEPc.EPS.getKrylovSchurKSP ~slepc4py.SLEPc.EPS.getKrylovSchurLocking ~slepc4py.SLEPc.EPS.getKrylovSchurPartitions ~slepc4py.SLEPc.EPS.getKrylovSchurRestart ~slepc4py.SLEPc.EPS.getKrylovSchurSubcommInfo ~slepc4py.SLEPc.EPS.getKrylovSchurSubcommMats ~slepc4py.SLEPc.EPS.getKrylovSchurSubcommPairs ~slepc4py.SLEPc.EPS.getKrylovSchurSubintervals ~slepc4py.SLEPc.EPS.getLOBPCGBlockSize ~slepc4py.SLEPc.EPS.getLOBPCGLocking ~slepc4py.SLEPc.EPS.getLOBPCGRestart ~slepc4py.SLEPc.EPS.getLanczosReorthogType ~slepc4py.SLEPc.EPS.getLeftEigenvector ~slepc4py.SLEPc.EPS.getLyapIIRanks ~slepc4py.SLEPc.EPS.getMonitor ~slepc4py.SLEPc.EPS.getOperators ~slepc4py.SLEPc.EPS.getOptionsPrefix ~slepc4py.SLEPc.EPS.getPowerShiftType ~slepc4py.SLEPc.EPS.getProblemType ~slepc4py.SLEPc.EPS.getPurify ~slepc4py.SLEPc.EPS.getRG ~slepc4py.SLEPc.EPS.getRQCGReset ~slepc4py.SLEPc.EPS.getST ~slepc4py.SLEPc.EPS.getStoppingTest ~slepc4py.SLEPc.EPS.getTarget ~slepc4py.SLEPc.EPS.getThreshold ~slepc4py.SLEPc.EPS.getTolerances ~slepc4py.SLEPc.EPS.getTrackAll ~slepc4py.SLEPc.EPS.getTrueResidual ~slepc4py.SLEPc.EPS.getTwoSided ~slepc4py.SLEPc.EPS.getType ~slepc4py.SLEPc.EPS.getWhichEigenpairs ~slepc4py.SLEPc.EPS.isGeneralized ~slepc4py.SLEPc.EPS.isHermitian ~slepc4py.SLEPc.EPS.isPositive ~slepc4py.SLEPc.EPS.isStructured ~slepc4py.SLEPc.EPS.reset ~slepc4py.SLEPc.EPS.setArbitrarySelection ~slepc4py.SLEPc.EPS.setArnoldiDelayed ~slepc4py.SLEPc.EPS.setBV ~slepc4py.SLEPc.EPS.setBalance ~slepc4py.SLEPc.EPS.setCISSExtraction ~slepc4py.SLEPc.EPS.setCISSQuadRule ~slepc4py.SLEPc.EPS.setCISSRefinement ~slepc4py.SLEPc.EPS.setCISSSizes ~slepc4py.SLEPc.EPS.setCISSThreshold ~slepc4py.SLEPc.EPS.setCISSUseST ~slepc4py.SLEPc.EPS.setConvergenceTest ~slepc4py.SLEPc.EPS.setDS ~slepc4py.SLEPc.EPS.setDeflationSpace ~slepc4py.SLEPc.EPS.setDimensions ~slepc4py.SLEPc.EPS.setEigenvalueComparison ~slepc4py.SLEPc.EPS.setExtraction ~slepc4py.SLEPc.EPS.setFromOptions ~slepc4py.SLEPc.EPS.setGDBOrth ~slepc4py.SLEPc.EPS.setGDBlockSize ~slepc4py.SLEPc.EPS.setGDDoubleExpansion ~slepc4py.SLEPc.EPS.setGDInitialSize ~slepc4py.SLEPc.EPS.setGDKrylovStart ~slepc4py.SLEPc.EPS.setGDRestart ~slepc4py.SLEPc.EPS.setInitialSpace ~slepc4py.SLEPc.EPS.setInterval ~slepc4py.SLEPc.EPS.setJDBOrth ~slepc4py.SLEPc.EPS.setJDBlockSize ~slepc4py.SLEPc.EPS.setJDConstCorrectionTol ~slepc4py.SLEPc.EPS.setJDFix ~slepc4py.SLEPc.EPS.setJDInitialSize ~slepc4py.SLEPc.EPS.setJDKrylovStart ~slepc4py.SLEPc.EPS.setJDRestart ~slepc4py.SLEPc.EPS.setKrylovSchurBSEType ~slepc4py.SLEPc.EPS.setKrylovSchurDetectZeros ~slepc4py.SLEPc.EPS.setKrylovSchurDimensions ~slepc4py.SLEPc.EPS.setKrylovSchurLocking ~slepc4py.SLEPc.EPS.setKrylovSchurPartitions ~slepc4py.SLEPc.EPS.setKrylovSchurRestart ~slepc4py.SLEPc.EPS.setKrylovSchurSubintervals ~slepc4py.SLEPc.EPS.setLOBPCGBlockSize ~slepc4py.SLEPc.EPS.setLOBPCGLocking ~slepc4py.SLEPc.EPS.setLOBPCGRestart ~slepc4py.SLEPc.EPS.setLanczosReorthogType ~slepc4py.SLEPc.EPS.setLeftInitialSpace ~slepc4py.SLEPc.EPS.setLyapIIRanks ~slepc4py.SLEPc.EPS.setMonitor ~slepc4py.SLEPc.EPS.setOperators ~slepc4py.SLEPc.EPS.setOptionsPrefix ~slepc4py.SLEPc.EPS.setPowerShiftType ~slepc4py.SLEPc.EPS.setProblemType ~slepc4py.SLEPc.EPS.setPurify ~slepc4py.SLEPc.EPS.setRG ~slepc4py.SLEPc.EPS.setRQCGReset ~slepc4py.SLEPc.EPS.setST ~slepc4py.SLEPc.EPS.setStoppingTest ~slepc4py.SLEPc.EPS.setTarget ~slepc4py.SLEPc.EPS.setThreshold ~slepc4py.SLEPc.EPS.setTolerances ~slepc4py.SLEPc.EPS.setTrackAll ~slepc4py.SLEPc.EPS.setTrueResidual ~slepc4py.SLEPc.EPS.setTwoSided ~slepc4py.SLEPc.EPS.setType ~slepc4py.SLEPc.EPS.setUp ~slepc4py.SLEPc.EPS.setWhichEigenpairs ~slepc4py.SLEPc.EPS.solve ~slepc4py.SLEPc.EPS.updateKrylovSchurSubcommMats ~slepc4py.SLEPc.EPS.valuesView ~slepc4py.SLEPc.EPS.vectorsView ~slepc4py.SLEPc.EPS.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.EPS.bv ~slepc4py.SLEPc.EPS.ds ~slepc4py.SLEPc.EPS.extraction ~slepc4py.SLEPc.EPS.max_it ~slepc4py.SLEPc.EPS.problem_type ~slepc4py.SLEPc.EPS.purify ~slepc4py.SLEPc.EPS.rg ~slepc4py.SLEPc.EPS.st ~slepc4py.SLEPc.EPS.target ~slepc4py.SLEPc.EPS.tol ~slepc4py.SLEPc.EPS.track_all ~slepc4py.SLEPc.EPS.true_residual ~slepc4py.SLEPc.EPS.two_sided ~slepc4py.SLEPc.EPS.which .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: cancelMonitor .. automethod:: computeError .. automethod:: create .. automethod:: destroy .. automethod:: errorView .. automethod:: getArbitrarySelection .. automethod:: getArnoldiDelayed .. automethod:: getBV .. automethod:: getBalance .. automethod:: getCISSExtraction .. automethod:: getCISSKSPs .. automethod:: getCISSQuadRule .. automethod:: getCISSRefinement .. automethod:: getCISSSizes .. automethod:: getCISSThreshold .. automethod:: getCISSUseST .. automethod:: getConverged .. automethod:: getConvergedReason .. automethod:: getConvergenceTest .. automethod:: getDS .. automethod:: getDimensions .. automethod:: getEigenpair .. automethod:: getEigenvalue .. automethod:: getEigenvalueComparison .. automethod:: getEigenvector .. automethod:: getErrorEstimate .. automethod:: getExtraction .. automethod:: getGDBOrth .. automethod:: getGDBlockSize .. automethod:: getGDDoubleExpansion .. automethod:: getGDInitialSize .. automethod:: getGDKrylovStart .. automethod:: getGDRestart .. automethod:: getInterval .. automethod:: getInvariantSubspace .. automethod:: getIterationNumber .. automethod:: getJDBOrth .. automethod:: getJDBlockSize .. automethod:: getJDConstCorrectionTol .. automethod:: getJDFix .. automethod:: getJDInitialSize .. automethod:: getJDKrylovStart .. automethod:: getJDRestart .. automethod:: getKrylovSchurBSEType .. automethod:: getKrylovSchurDetectZeros .. automethod:: getKrylovSchurDimensions .. automethod:: getKrylovSchurInertias .. automethod:: getKrylovSchurKSP .. automethod:: getKrylovSchurLocking .. automethod:: getKrylovSchurPartitions .. automethod:: getKrylovSchurRestart .. automethod:: getKrylovSchurSubcommInfo .. automethod:: getKrylovSchurSubcommMats .. automethod:: getKrylovSchurSubcommPairs .. automethod:: getKrylovSchurSubintervals .. automethod:: getLOBPCGBlockSize .. automethod:: getLOBPCGLocking .. automethod:: getLOBPCGRestart .. automethod:: getLanczosReorthogType .. automethod:: getLeftEigenvector .. automethod:: getLyapIIRanks .. automethod:: getMonitor .. automethod:: getOperators .. automethod:: getOptionsPrefix .. automethod:: getPowerShiftType .. automethod:: getProblemType .. automethod:: getPurify .. automethod:: getRG .. automethod:: getRQCGReset .. automethod:: getST .. automethod:: getStoppingTest .. automethod:: getTarget .. automethod:: getThreshold .. automethod:: getTolerances .. automethod:: getTrackAll .. automethod:: getTrueResidual .. automethod:: getTwoSided .. automethod:: getType .. automethod:: getWhichEigenpairs .. automethod:: isGeneralized .. automethod:: isHermitian .. automethod:: isPositive .. automethod:: isStructured .. automethod:: reset .. automethod:: setArbitrarySelection .. automethod:: setArnoldiDelayed .. automethod:: setBV .. automethod:: setBalance .. automethod:: setCISSExtraction .. automethod:: setCISSQuadRule .. automethod:: setCISSRefinement .. automethod:: setCISSSizes .. automethod:: setCISSThreshold .. automethod:: setCISSUseST .. automethod:: setConvergenceTest .. automethod:: setDS .. automethod:: setDeflationSpace .. automethod:: setDimensions .. automethod:: setEigenvalueComparison .. automethod:: setExtraction .. automethod:: setFromOptions .. automethod:: setGDBOrth .. automethod:: setGDBlockSize .. automethod:: setGDDoubleExpansion .. automethod:: setGDInitialSize .. automethod:: setGDKrylovStart .. automethod:: setGDRestart .. automethod:: setInitialSpace .. automethod:: setInterval .. automethod:: setJDBOrth .. automethod:: setJDBlockSize .. automethod:: setJDConstCorrectionTol .. automethod:: setJDFix .. automethod:: setJDInitialSize .. automethod:: setJDKrylovStart .. automethod:: setJDRestart .. automethod:: setKrylovSchurBSEType .. automethod:: setKrylovSchurDetectZeros .. automethod:: setKrylovSchurDimensions .. automethod:: setKrylovSchurLocking .. automethod:: setKrylovSchurPartitions .. automethod:: setKrylovSchurRestart .. automethod:: setKrylovSchurSubintervals .. automethod:: setLOBPCGBlockSize .. automethod:: setLOBPCGLocking .. automethod:: setLOBPCGRestart .. automethod:: setLanczosReorthogType .. automethod:: setLeftInitialSpace .. automethod:: setLyapIIRanks .. automethod:: setMonitor .. automethod:: setOperators .. automethod:: setOptionsPrefix .. automethod:: setPowerShiftType .. automethod:: setProblemType .. automethod:: setPurify .. automethod:: setRG .. automethod:: setRQCGReset .. automethod:: setST .. automethod:: setStoppingTest .. automethod:: setTarget .. automethod:: setThreshold .. automethod:: setTolerances .. automethod:: setTrackAll .. automethod:: setTrueResidual .. automethod:: setTwoSided .. automethod:: setType .. automethod:: setUp .. automethod:: setWhichEigenpairs .. automethod:: solve .. automethod:: updateKrylovSchurSubcommMats .. automethod:: valuesView .. automethod:: vectorsView .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: bv .. autoattribute:: ds .. autoattribute:: extraction .. autoattribute:: max_it .. autoattribute:: problem_type .. autoattribute:: purify .. autoattribute:: rg .. autoattribute:: st .. autoattribute:: target .. autoattribute:: tol .. autoattribute:: track_all .. autoattribute:: true_residual .. autoattribute:: two_sided .. autoattribute:: which ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.FN.CombineType.rst0000644000076500000240000000104315133664237024675 0ustar00jromanstaffslepc4py.SLEPc.FN.CombineType ============================= .. autoclass:: slepc4py.SLEPc.FN.CombineType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.FN.CombineType.ADD ~slepc4py.SLEPc.FN.CombineType.COMPOSE ~slepc4py.SLEPc.FN.CombineType.DIVIDE ~slepc4py.SLEPc.FN.CombineType.MULTIPLY .. rubric:: Attributes Documentation .. autoattribute:: ADD .. autoattribute:: COMPOSE .. autoattribute:: DIVIDE .. autoattribute:: MULTIPLY ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.FN.ParallelType.rst0000644000076500000240000000065015133664237025060 0ustar00jromanstaffslepc4py.SLEPc.FN.ParallelType ============================== .. autoclass:: slepc4py.SLEPc.FN.ParallelType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.FN.ParallelType.REDUNDANT ~slepc4py.SLEPc.FN.ParallelType.SYNCHRONIZED .. rubric:: Attributes Documentation .. autoattribute:: REDUNDANT .. autoattribute:: SYNCHRONIZED ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908959.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.FN.Type.rst0000644000076500000240000000125215133664237023402 0ustar00jromanstaffslepc4py.SLEPc.FN.Type ====================== .. autoclass:: slepc4py.SLEPc.FN.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.FN.Type.COMBINE ~slepc4py.SLEPc.FN.Type.EXP ~slepc4py.SLEPc.FN.Type.INVSQRT ~slepc4py.SLEPc.FN.Type.LOG ~slepc4py.SLEPc.FN.Type.PHI ~slepc4py.SLEPc.FN.Type.RATIONAL ~slepc4py.SLEPc.FN.Type.SQRT .. rubric:: Attributes Documentation .. autoattribute:: COMBINE .. autoattribute:: EXP .. autoattribute:: INVSQRT .. autoattribute:: LOG .. autoattribute:: PHI .. autoattribute:: RATIONAL .. autoattribute:: SQRT ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908957.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.FN.rst0000644000076500000240000000514215133664235022462 0ustar00jromanstaffslepc4py.SLEPc.FN ================= .. autoclass:: slepc4py.SLEPc.FN :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.FN.CombineType ~slepc4py.SLEPc.FN.ParallelType ~slepc4py.SLEPc.FN.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.FN.appendOptionsPrefix ~slepc4py.SLEPc.FN.create ~slepc4py.SLEPc.FN.destroy ~slepc4py.SLEPc.FN.duplicate ~slepc4py.SLEPc.FN.evaluateDerivative ~slepc4py.SLEPc.FN.evaluateFunction ~slepc4py.SLEPc.FN.evaluateFunctionMat ~slepc4py.SLEPc.FN.evaluateFunctionMatVec ~slepc4py.SLEPc.FN.getCombineChildren ~slepc4py.SLEPc.FN.getMethod ~slepc4py.SLEPc.FN.getOptionsPrefix ~slepc4py.SLEPc.FN.getParallel ~slepc4py.SLEPc.FN.getPhiIndex ~slepc4py.SLEPc.FN.getRationalDenominator ~slepc4py.SLEPc.FN.getRationalNumerator ~slepc4py.SLEPc.FN.getScale ~slepc4py.SLEPc.FN.getType ~slepc4py.SLEPc.FN.setCombineChildren ~slepc4py.SLEPc.FN.setFromOptions ~slepc4py.SLEPc.FN.setMethod ~slepc4py.SLEPc.FN.setOptionsPrefix ~slepc4py.SLEPc.FN.setParallel ~slepc4py.SLEPc.FN.setPhiIndex ~slepc4py.SLEPc.FN.setRationalDenominator ~slepc4py.SLEPc.FN.setRationalNumerator ~slepc4py.SLEPc.FN.setScale ~slepc4py.SLEPc.FN.setType ~slepc4py.SLEPc.FN.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.FN.method ~slepc4py.SLEPc.FN.parallel .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: create .. automethod:: destroy .. automethod:: duplicate .. automethod:: evaluateDerivative .. automethod:: evaluateFunction .. automethod:: evaluateFunctionMat .. automethod:: evaluateFunctionMatVec .. automethod:: getCombineChildren .. automethod:: getMethod .. automethod:: getOptionsPrefix .. automethod:: getParallel .. automethod:: getPhiIndex .. automethod:: getRationalDenominator .. automethod:: getRationalNumerator .. automethod:: getScale .. automethod:: getType .. automethod:: setCombineChildren .. automethod:: setFromOptions .. automethod:: setMethod .. automethod:: setOptionsPrefix .. automethod:: setParallel .. automethod:: setPhiIndex .. automethod:: setRationalDenominator .. automethod:: setRationalNumerator .. automethod:: setScale .. automethod:: setType .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: method .. autoattribute:: parallel ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.LME.ConvergedReason.rst0000644000076500000240000000134615133664240025655 0ustar00jromanstaffslepc4py.SLEPc.LME.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.LME.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.LME.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.LME.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.LME.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.LME.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.LME.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_TOL .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.LME.ProblemType.rst0000644000076500000240000000135215133664240025030 0ustar00jromanstaffslepc4py.SLEPc.LME.ProblemType ============================== .. autoclass:: slepc4py.SLEPc.LME.ProblemType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.LME.ProblemType.DT_LYAPUNOV ~slepc4py.SLEPc.LME.ProblemType.GEN_LYAPUNOV ~slepc4py.SLEPc.LME.ProblemType.GEN_SYLVESTER ~slepc4py.SLEPc.LME.ProblemType.LYAPUNOV ~slepc4py.SLEPc.LME.ProblemType.STEIN ~slepc4py.SLEPc.LME.ProblemType.SYLVESTER .. rubric:: Attributes Documentation .. autoattribute:: DT_LYAPUNOV .. autoattribute:: GEN_LYAPUNOV .. autoattribute:: GEN_SYLVESTER .. autoattribute:: LYAPUNOV .. autoattribute:: STEIN .. autoattribute:: SYLVESTER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.LME.Type.rst0000644000076500000240000000046015133664240023506 0ustar00jromanstaffslepc4py.SLEPc.LME.Type ======================= .. autoclass:: slepc4py.SLEPc.LME.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.LME.Type.KRYLOV .. rubric:: Attributes Documentation .. autoattribute:: KRYLOV ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908957.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.LME.rst0000644000076500000240000000615415133664235022600 0ustar00jromanstaffslepc4py.SLEPc.LME ================== .. autoclass:: slepc4py.SLEPc.LME :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.LME.ConvergedReason ~slepc4py.SLEPc.LME.ProblemType ~slepc4py.SLEPc.LME.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.LME.appendOptionsPrefix ~slepc4py.SLEPc.LME.cancelMonitor ~slepc4py.SLEPc.LME.computeError ~slepc4py.SLEPc.LME.create ~slepc4py.SLEPc.LME.destroy ~slepc4py.SLEPc.LME.getBV ~slepc4py.SLEPc.LME.getCoefficients ~slepc4py.SLEPc.LME.getConvergedReason ~slepc4py.SLEPc.LME.getDimensions ~slepc4py.SLEPc.LME.getErrorEstimate ~slepc4py.SLEPc.LME.getErrorIfNotConverged ~slepc4py.SLEPc.LME.getIterationNumber ~slepc4py.SLEPc.LME.getMonitor ~slepc4py.SLEPc.LME.getOptionsPrefix ~slepc4py.SLEPc.LME.getProblemType ~slepc4py.SLEPc.LME.getRHS ~slepc4py.SLEPc.LME.getSolution ~slepc4py.SLEPc.LME.getTolerances ~slepc4py.SLEPc.LME.getType ~slepc4py.SLEPc.LME.reset ~slepc4py.SLEPc.LME.setBV ~slepc4py.SLEPc.LME.setCoefficients ~slepc4py.SLEPc.LME.setDimensions ~slepc4py.SLEPc.LME.setErrorIfNotConverged ~slepc4py.SLEPc.LME.setFromOptions ~slepc4py.SLEPc.LME.setMonitor ~slepc4py.SLEPc.LME.setOptionsPrefix ~slepc4py.SLEPc.LME.setProblemType ~slepc4py.SLEPc.LME.setRHS ~slepc4py.SLEPc.LME.setSolution ~slepc4py.SLEPc.LME.setTolerances ~slepc4py.SLEPc.LME.setType ~slepc4py.SLEPc.LME.setUp ~slepc4py.SLEPc.LME.solve ~slepc4py.SLEPc.LME.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.LME.bv ~slepc4py.SLEPc.LME.fn ~slepc4py.SLEPc.LME.max_it ~slepc4py.SLEPc.LME.tol .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: cancelMonitor .. automethod:: computeError .. automethod:: create .. automethod:: destroy .. automethod:: getBV .. automethod:: getCoefficients .. automethod:: getConvergedReason .. automethod:: getDimensions .. automethod:: getErrorEstimate .. automethod:: getErrorIfNotConverged .. automethod:: getIterationNumber .. automethod:: getMonitor .. automethod:: getOptionsPrefix .. automethod:: getProblemType .. automethod:: getRHS .. automethod:: getSolution .. automethod:: getTolerances .. automethod:: getType .. automethod:: reset .. automethod:: setBV .. automethod:: setCoefficients .. automethod:: setDimensions .. automethod:: setErrorIfNotConverged .. automethod:: setFromOptions .. automethod:: setMonitor .. automethod:: setOptionsPrefix .. automethod:: setProblemType .. automethod:: setRHS .. automethod:: setSolution .. automethod:: setTolerances .. automethod:: setType .. automethod:: setUp .. automethod:: solve .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: bv .. autoattribute:: fn .. autoattribute:: max_it .. autoattribute:: tol ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.MFN.ConvergedReason.rst0000644000076500000240000000150215133664240025652 0ustar00jromanstaffslepc4py.SLEPc.MFN.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.MFN.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.MFN.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.MFN.ConvergedReason.CONVERGED_ITS ~slepc4py.SLEPc.MFN.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.MFN.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.MFN.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.MFN.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_ITS .. autoattribute:: CONVERGED_TOL .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.MFN.Type.rst0000644000076500000240000000056515133664240023517 0ustar00jromanstaffslepc4py.SLEPc.MFN.Type ======================= .. autoclass:: slepc4py.SLEPc.MFN.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.MFN.Type.EXPOKIT ~slepc4py.SLEPc.MFN.Type.KRYLOV .. rubric:: Attributes Documentation .. autoattribute:: EXPOKIT .. autoattribute:: KRYLOV ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908957.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.MFN.rst0000644000076500000240000000530715133664235022602 0ustar00jromanstaffslepc4py.SLEPc.MFN ================== .. autoclass:: slepc4py.SLEPc.MFN :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.MFN.ConvergedReason ~slepc4py.SLEPc.MFN.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.MFN.appendOptionsPrefix ~slepc4py.SLEPc.MFN.cancelMonitor ~slepc4py.SLEPc.MFN.create ~slepc4py.SLEPc.MFN.destroy ~slepc4py.SLEPc.MFN.getBV ~slepc4py.SLEPc.MFN.getConvergedReason ~slepc4py.SLEPc.MFN.getDimensions ~slepc4py.SLEPc.MFN.getErrorIfNotConverged ~slepc4py.SLEPc.MFN.getFN ~slepc4py.SLEPc.MFN.getIterationNumber ~slepc4py.SLEPc.MFN.getMonitor ~slepc4py.SLEPc.MFN.getOperator ~slepc4py.SLEPc.MFN.getOptionsPrefix ~slepc4py.SLEPc.MFN.getTolerances ~slepc4py.SLEPc.MFN.getType ~slepc4py.SLEPc.MFN.reset ~slepc4py.SLEPc.MFN.setBV ~slepc4py.SLEPc.MFN.setDimensions ~slepc4py.SLEPc.MFN.setErrorIfNotConverged ~slepc4py.SLEPc.MFN.setFN ~slepc4py.SLEPc.MFN.setFromOptions ~slepc4py.SLEPc.MFN.setMonitor ~slepc4py.SLEPc.MFN.setOperator ~slepc4py.SLEPc.MFN.setOptionsPrefix ~slepc4py.SLEPc.MFN.setTolerances ~slepc4py.SLEPc.MFN.setType ~slepc4py.SLEPc.MFN.setUp ~slepc4py.SLEPc.MFN.solve ~slepc4py.SLEPc.MFN.solveTranspose ~slepc4py.SLEPc.MFN.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.MFN.bv ~slepc4py.SLEPc.MFN.fn ~slepc4py.SLEPc.MFN.max_it ~slepc4py.SLEPc.MFN.tol .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: cancelMonitor .. automethod:: create .. automethod:: destroy .. automethod:: getBV .. automethod:: getConvergedReason .. automethod:: getDimensions .. automethod:: getErrorIfNotConverged .. automethod:: getFN .. automethod:: getIterationNumber .. automethod:: getMonitor .. automethod:: getOperator .. automethod:: getOptionsPrefix .. automethod:: getTolerances .. automethod:: getType .. automethod:: reset .. automethod:: setBV .. automethod:: setDimensions .. automethod:: setErrorIfNotConverged .. automethod:: setFN .. automethod:: setFromOptions .. automethod:: setMonitor .. automethod:: setOperator .. automethod:: setOptionsPrefix .. automethod:: setTolerances .. automethod:: setType .. automethod:: setUp .. automethod:: solve .. automethod:: solveTranspose .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: bv .. autoattribute:: fn .. autoattribute:: max_it .. autoattribute:: tol ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.CISSExtraction.rst0000644000076500000240000000075015133664240025376 0ustar00jromanstaffslepc4py.SLEPc.NEP.CISSExtraction ================================= .. autoclass:: slepc4py.SLEPc.NEP.CISSExtraction :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.CISSExtraction.CAA ~slepc4py.SLEPc.NEP.CISSExtraction.HANKEL ~slepc4py.SLEPc.NEP.CISSExtraction.RITZ .. rubric:: Attributes Documentation .. autoattribute:: CAA .. autoattribute:: HANKEL .. autoattribute:: RITZ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.Conv.rst0000644000076500000240000000074515133664240023505 0ustar00jromanstaffslepc4py.SLEPc.NEP.Conv ======================= .. autoclass:: slepc4py.SLEPc.NEP.Conv :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.Conv.ABS ~slepc4py.SLEPc.NEP.Conv.NORM ~slepc4py.SLEPc.NEP.Conv.REL ~slepc4py.SLEPc.NEP.Conv.USER .. rubric:: Attributes Documentation .. autoattribute:: ABS .. autoattribute:: NORM .. autoattribute:: REL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.ConvergedReason.rst0000644000076500000240000000205015133664240025653 0ustar00jromanstaffslepc4py.SLEPc.NEP.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.NEP.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.NEP.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.NEP.ConvergedReason.CONVERGED_USER ~slepc4py.SLEPc.NEP.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.NEP.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.NEP.ConvergedReason.DIVERGED_LINEAR_SOLVE ~slepc4py.SLEPc.NEP.ConvergedReason.DIVERGED_SUBSPACE_EXHAUSTED ~slepc4py.SLEPc.NEP.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_TOL .. autoattribute:: CONVERGED_USER .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: DIVERGED_LINEAR_SOLVE .. autoattribute:: DIVERGED_SUBSPACE_EXHAUSTED .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.ErrorType.rst0000644000076500000240000000074015133664240024526 0ustar00jromanstaffslepc4py.SLEPc.NEP.ErrorType ============================ .. autoclass:: slepc4py.SLEPc.NEP.ErrorType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.ErrorType.ABSOLUTE ~slepc4py.SLEPc.NEP.ErrorType.BACKWARD ~slepc4py.SLEPc.NEP.ErrorType.RELATIVE .. rubric:: Attributes Documentation .. autoattribute:: ABSOLUTE .. autoattribute:: BACKWARD .. autoattribute:: RELATIVE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.ProblemType.rst0000644000076500000240000000063415133664240025037 0ustar00jromanstaffslepc4py.SLEPc.NEP.ProblemType ============================== .. autoclass:: slepc4py.SLEPc.NEP.ProblemType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.ProblemType.GENERAL ~slepc4py.SLEPc.NEP.ProblemType.RATIONAL .. rubric:: Attributes Documentation .. autoattribute:: GENERAL .. autoattribute:: RATIONAL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.Refine.rst0000644000076500000240000000070215133664240024001 0ustar00jromanstaffslepc4py.SLEPc.NEP.Refine ========================= .. autoclass:: slepc4py.SLEPc.NEP.Refine :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.Refine.MULTIPLE ~slepc4py.SLEPc.NEP.Refine.NONE ~slepc4py.SLEPc.NEP.Refine.SIMPLE .. rubric:: Attributes Documentation .. autoattribute:: MULTIPLE .. autoattribute:: NONE .. autoattribute:: SIMPLE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.RefineScheme.rst0000644000076500000240000000074215133664240025132 0ustar00jromanstaffslepc4py.SLEPc.NEP.RefineScheme =============================== .. autoclass:: slepc4py.SLEPc.NEP.RefineScheme :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.RefineScheme.EXPLICIT ~slepc4py.SLEPc.NEP.RefineScheme.MBE ~slepc4py.SLEPc.NEP.RefineScheme.SCHUR .. rubric:: Attributes Documentation .. autoattribute:: EXPLICIT .. autoattribute:: MBE .. autoattribute:: SCHUR ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.Stop.rst0000644000076500000240000000055515133664240023524 0ustar00jromanstaffslepc4py.SLEPc.NEP.Stop ======================= .. autoclass:: slepc4py.SLEPc.NEP.Stop :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.Stop.BASIC ~slepc4py.SLEPc.NEP.Stop.USER .. rubric:: Attributes Documentation .. autoattribute:: BASIC .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.Type.rst0000644000076500000240000000116715133664240023520 0ustar00jromanstaffslepc4py.SLEPc.NEP.Type ======================= .. autoclass:: slepc4py.SLEPc.NEP.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.Type.CISS ~slepc4py.SLEPc.NEP.Type.INTERPOL ~slepc4py.SLEPc.NEP.Type.NARNOLDI ~slepc4py.SLEPc.NEP.Type.NLEIGS ~slepc4py.SLEPc.NEP.Type.RII ~slepc4py.SLEPc.NEP.Type.SLP .. rubric:: Attributes Documentation .. autoattribute:: CISS .. autoattribute:: INTERPOL .. autoattribute:: NARNOLDI .. autoattribute:: NLEIGS .. autoattribute:: RII .. autoattribute:: SLP ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.Which.rst0000644000076500000240000000217215133664240023636 0ustar00jromanstaffslepc4py.SLEPc.NEP.Which ======================== .. autoclass:: slepc4py.SLEPc.NEP.Which :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.Which.ALL ~slepc4py.SLEPc.NEP.Which.LARGEST_IMAGINARY ~slepc4py.SLEPc.NEP.Which.LARGEST_MAGNITUDE ~slepc4py.SLEPc.NEP.Which.LARGEST_REAL ~slepc4py.SLEPc.NEP.Which.SMALLEST_IMAGINARY ~slepc4py.SLEPc.NEP.Which.SMALLEST_MAGNITUDE ~slepc4py.SLEPc.NEP.Which.SMALLEST_REAL ~slepc4py.SLEPc.NEP.Which.TARGET_IMAGINARY ~slepc4py.SLEPc.NEP.Which.TARGET_MAGNITUDE ~slepc4py.SLEPc.NEP.Which.TARGET_REAL ~slepc4py.SLEPc.NEP.Which.USER .. rubric:: Attributes Documentation .. autoattribute:: ALL .. autoattribute:: LARGEST_IMAGINARY .. autoattribute:: LARGEST_MAGNITUDE .. autoattribute:: LARGEST_REAL .. autoattribute:: SMALLEST_IMAGINARY .. autoattribute:: SMALLEST_MAGNITUDE .. autoattribute:: SMALLEST_REAL .. autoattribute:: TARGET_IMAGINARY .. autoattribute:: TARGET_MAGNITUDE .. autoattribute:: TARGET_REAL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908957.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.NEP.rst0000644000076500000240000002327015133664235022603 0ustar00jromanstaffslepc4py.SLEPc.NEP ================== .. autoclass:: slepc4py.SLEPc.NEP :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.NEP.CISSExtraction ~slepc4py.SLEPc.NEP.Conv ~slepc4py.SLEPc.NEP.ConvergedReason ~slepc4py.SLEPc.NEP.ErrorType ~slepc4py.SLEPc.NEP.ProblemType ~slepc4py.SLEPc.NEP.Refine ~slepc4py.SLEPc.NEP.RefineScheme ~slepc4py.SLEPc.NEP.Stop ~slepc4py.SLEPc.NEP.Type ~slepc4py.SLEPc.NEP.Which .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.NEP.appendOptionsPrefix ~slepc4py.SLEPc.NEP.applyResolvent ~slepc4py.SLEPc.NEP.cancelMonitor ~slepc4py.SLEPc.NEP.computeError ~slepc4py.SLEPc.NEP.create ~slepc4py.SLEPc.NEP.destroy ~slepc4py.SLEPc.NEP.errorView ~slepc4py.SLEPc.NEP.getBV ~slepc4py.SLEPc.NEP.getCISSExtraction ~slepc4py.SLEPc.NEP.getCISSKSPs ~slepc4py.SLEPc.NEP.getCISSRefinement ~slepc4py.SLEPc.NEP.getCISSSizes ~slepc4py.SLEPc.NEP.getCISSThreshold ~slepc4py.SLEPc.NEP.getConverged ~slepc4py.SLEPc.NEP.getConvergedReason ~slepc4py.SLEPc.NEP.getConvergenceTest ~slepc4py.SLEPc.NEP.getDS ~slepc4py.SLEPc.NEP.getDimensions ~slepc4py.SLEPc.NEP.getEigenpair ~slepc4py.SLEPc.NEP.getEigenvalueComparison ~slepc4py.SLEPc.NEP.getErrorEstimate ~slepc4py.SLEPc.NEP.getFunction ~slepc4py.SLEPc.NEP.getInterpolInterpolation ~slepc4py.SLEPc.NEP.getInterpolPEP ~slepc4py.SLEPc.NEP.getIterationNumber ~slepc4py.SLEPc.NEP.getJacobian ~slepc4py.SLEPc.NEP.getLeftEigenvector ~slepc4py.SLEPc.NEP.getMonitor ~slepc4py.SLEPc.NEP.getNArnoldiKSP ~slepc4py.SLEPc.NEP.getNArnoldiLagPreconditioner ~slepc4py.SLEPc.NEP.getNLEIGSEPS ~slepc4py.SLEPc.NEP.getNLEIGSFullBasis ~slepc4py.SLEPc.NEP.getNLEIGSInterpolation ~slepc4py.SLEPc.NEP.getNLEIGSKSPs ~slepc4py.SLEPc.NEP.getNLEIGSLocking ~slepc4py.SLEPc.NEP.getNLEIGSRKShifts ~slepc4py.SLEPc.NEP.getNLEIGSRestart ~slepc4py.SLEPc.NEP.getOptionsPrefix ~slepc4py.SLEPc.NEP.getProblemType ~slepc4py.SLEPc.NEP.getRG ~slepc4py.SLEPc.NEP.getRIIConstCorrectionTol ~slepc4py.SLEPc.NEP.getRIIDeflationThreshold ~slepc4py.SLEPc.NEP.getRIIHermitian ~slepc4py.SLEPc.NEP.getRIIKSP ~slepc4py.SLEPc.NEP.getRIILagPreconditioner ~slepc4py.SLEPc.NEP.getRIIMaximumIterations ~slepc4py.SLEPc.NEP.getRefine ~slepc4py.SLEPc.NEP.getRefineKSP ~slepc4py.SLEPc.NEP.getSLPDeflationThreshold ~slepc4py.SLEPc.NEP.getSLPEPS ~slepc4py.SLEPc.NEP.getSLPEPSLeft ~slepc4py.SLEPc.NEP.getSLPKSP ~slepc4py.SLEPc.NEP.getSplitOperator ~slepc4py.SLEPc.NEP.getSplitPreconditioner ~slepc4py.SLEPc.NEP.getStoppingTest ~slepc4py.SLEPc.NEP.getTarget ~slepc4py.SLEPc.NEP.getTolerances ~slepc4py.SLEPc.NEP.getTrackAll ~slepc4py.SLEPc.NEP.getTwoSided ~slepc4py.SLEPc.NEP.getType ~slepc4py.SLEPc.NEP.getWhichEigenpairs ~slepc4py.SLEPc.NEP.reset ~slepc4py.SLEPc.NEP.setBV ~slepc4py.SLEPc.NEP.setCISSExtraction ~slepc4py.SLEPc.NEP.setCISSRefinement ~slepc4py.SLEPc.NEP.setCISSSizes ~slepc4py.SLEPc.NEP.setCISSThreshold ~slepc4py.SLEPc.NEP.setConvergenceTest ~slepc4py.SLEPc.NEP.setDS ~slepc4py.SLEPc.NEP.setDimensions ~slepc4py.SLEPc.NEP.setEigenvalueComparison ~slepc4py.SLEPc.NEP.setFromOptions ~slepc4py.SLEPc.NEP.setFunction ~slepc4py.SLEPc.NEP.setInitialSpace ~slepc4py.SLEPc.NEP.setInterpolInterpolation ~slepc4py.SLEPc.NEP.setInterpolPEP ~slepc4py.SLEPc.NEP.setJacobian ~slepc4py.SLEPc.NEP.setMonitor ~slepc4py.SLEPc.NEP.setNArnoldiKSP ~slepc4py.SLEPc.NEP.setNArnoldiLagPreconditioner ~slepc4py.SLEPc.NEP.setNLEIGSEPS ~slepc4py.SLEPc.NEP.setNLEIGSFullBasis ~slepc4py.SLEPc.NEP.setNLEIGSInterpolation ~slepc4py.SLEPc.NEP.setNLEIGSLocking ~slepc4py.SLEPc.NEP.setNLEIGSRKShifts ~slepc4py.SLEPc.NEP.setNLEIGSRestart ~slepc4py.SLEPc.NEP.setOptionsPrefix ~slepc4py.SLEPc.NEP.setProblemType ~slepc4py.SLEPc.NEP.setRG ~slepc4py.SLEPc.NEP.setRIIConstCorrectionTol ~slepc4py.SLEPc.NEP.setRIIDeflationThreshold ~slepc4py.SLEPc.NEP.setRIIHermitian ~slepc4py.SLEPc.NEP.setRIIKSP ~slepc4py.SLEPc.NEP.setRIILagPreconditioner ~slepc4py.SLEPc.NEP.setRIIMaximumIterations ~slepc4py.SLEPc.NEP.setRefine ~slepc4py.SLEPc.NEP.setSLPDeflationThreshold ~slepc4py.SLEPc.NEP.setSLPEPS ~slepc4py.SLEPc.NEP.setSLPEPSLeft ~slepc4py.SLEPc.NEP.setSLPKSP ~slepc4py.SLEPc.NEP.setSplitOperator ~slepc4py.SLEPc.NEP.setSplitPreconditioner ~slepc4py.SLEPc.NEP.setStoppingTest ~slepc4py.SLEPc.NEP.setTarget ~slepc4py.SLEPc.NEP.setTolerances ~slepc4py.SLEPc.NEP.setTrackAll ~slepc4py.SLEPc.NEP.setTwoSided ~slepc4py.SLEPc.NEP.setType ~slepc4py.SLEPc.NEP.setUp ~slepc4py.SLEPc.NEP.setWhichEigenpairs ~slepc4py.SLEPc.NEP.solve ~slepc4py.SLEPc.NEP.valuesView ~slepc4py.SLEPc.NEP.vectorsView ~slepc4py.SLEPc.NEP.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.NEP.bv ~slepc4py.SLEPc.NEP.ds ~slepc4py.SLEPc.NEP.max_it ~slepc4py.SLEPc.NEP.problem_type ~slepc4py.SLEPc.NEP.rg ~slepc4py.SLEPc.NEP.target ~slepc4py.SLEPc.NEP.tol ~slepc4py.SLEPc.NEP.track_all ~slepc4py.SLEPc.NEP.which .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: applyResolvent .. automethod:: cancelMonitor .. automethod:: computeError .. automethod:: create .. automethod:: destroy .. automethod:: errorView .. automethod:: getBV .. automethod:: getCISSExtraction .. automethod:: getCISSKSPs .. automethod:: getCISSRefinement .. automethod:: getCISSSizes .. automethod:: getCISSThreshold .. automethod:: getConverged .. automethod:: getConvergedReason .. automethod:: getConvergenceTest .. automethod:: getDS .. automethod:: getDimensions .. automethod:: getEigenpair .. automethod:: getEigenvalueComparison .. automethod:: getErrorEstimate .. automethod:: getFunction .. automethod:: getInterpolInterpolation .. automethod:: getInterpolPEP .. automethod:: getIterationNumber .. automethod:: getJacobian .. automethod:: getLeftEigenvector .. automethod:: getMonitor .. automethod:: getNArnoldiKSP .. automethod:: getNArnoldiLagPreconditioner .. automethod:: getNLEIGSEPS .. automethod:: getNLEIGSFullBasis .. automethod:: getNLEIGSInterpolation .. automethod:: getNLEIGSKSPs .. automethod:: getNLEIGSLocking .. automethod:: getNLEIGSRKShifts .. automethod:: getNLEIGSRestart .. automethod:: getOptionsPrefix .. automethod:: getProblemType .. automethod:: getRG .. automethod:: getRIIConstCorrectionTol .. automethod:: getRIIDeflationThreshold .. automethod:: getRIIHermitian .. automethod:: getRIIKSP .. automethod:: getRIILagPreconditioner .. automethod:: getRIIMaximumIterations .. automethod:: getRefine .. automethod:: getRefineKSP .. automethod:: getSLPDeflationThreshold .. automethod:: getSLPEPS .. automethod:: getSLPEPSLeft .. automethod:: getSLPKSP .. automethod:: getSplitOperator .. automethod:: getSplitPreconditioner .. automethod:: getStoppingTest .. automethod:: getTarget .. automethod:: getTolerances .. automethod:: getTrackAll .. automethod:: getTwoSided .. automethod:: getType .. automethod:: getWhichEigenpairs .. automethod:: reset .. automethod:: setBV .. automethod:: setCISSExtraction .. automethod:: setCISSRefinement .. automethod:: setCISSSizes .. automethod:: setCISSThreshold .. automethod:: setConvergenceTest .. automethod:: setDS .. automethod:: setDimensions .. automethod:: setEigenvalueComparison .. automethod:: setFromOptions .. automethod:: setFunction .. automethod:: setInitialSpace .. automethod:: setInterpolInterpolation .. automethod:: setInterpolPEP .. automethod:: setJacobian .. automethod:: setMonitor .. automethod:: setNArnoldiKSP .. automethod:: setNArnoldiLagPreconditioner .. automethod:: setNLEIGSEPS .. automethod:: setNLEIGSFullBasis .. automethod:: setNLEIGSInterpolation .. automethod:: setNLEIGSLocking .. automethod:: setNLEIGSRKShifts .. automethod:: setNLEIGSRestart .. automethod:: setOptionsPrefix .. automethod:: setProblemType .. automethod:: setRG .. automethod:: setRIIConstCorrectionTol .. automethod:: setRIIDeflationThreshold .. automethod:: setRIIHermitian .. automethod:: setRIIKSP .. automethod:: setRIILagPreconditioner .. automethod:: setRIIMaximumIterations .. automethod:: setRefine .. automethod:: setSLPDeflationThreshold .. automethod:: setSLPEPS .. automethod:: setSLPEPSLeft .. automethod:: setSLPKSP .. automethod:: setSplitOperator .. automethod:: setSplitPreconditioner .. automethod:: setStoppingTest .. automethod:: setTarget .. automethod:: setTolerances .. automethod:: setTrackAll .. automethod:: setTwoSided .. automethod:: setType .. automethod:: setUp .. automethod:: setWhichEigenpairs .. automethod:: solve .. automethod:: valuesView .. automethod:: vectorsView .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: bv .. autoattribute:: ds .. autoattribute:: max_it .. autoattribute:: problem_type .. autoattribute:: rg .. autoattribute:: target .. autoattribute:: tol .. autoattribute:: track_all .. autoattribute:: which ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Basis.rst0000644000076500000240000000124615133664240023640 0ustar00jromanstaffslepc4py.SLEPc.PEP.Basis ======================== .. autoclass:: slepc4py.SLEPc.PEP.Basis :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Basis.CHEBYSHEV1 ~slepc4py.SLEPc.PEP.Basis.CHEBYSHEV2 ~slepc4py.SLEPc.PEP.Basis.HERMITE ~slepc4py.SLEPc.PEP.Basis.LAGUERRE ~slepc4py.SLEPc.PEP.Basis.LEGENDRE ~slepc4py.SLEPc.PEP.Basis.MONOMIAL .. rubric:: Attributes Documentation .. autoattribute:: CHEBYSHEV1 .. autoattribute:: CHEBYSHEV2 .. autoattribute:: HERMITE .. autoattribute:: LAGUERRE .. autoattribute:: LEGENDRE .. autoattribute:: MONOMIAL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.CISSExtraction.rst0000644000076500000240000000075015133664240025400 0ustar00jromanstaffslepc4py.SLEPc.PEP.CISSExtraction ================================= .. autoclass:: slepc4py.SLEPc.PEP.CISSExtraction :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.CISSExtraction.CAA ~slepc4py.SLEPc.PEP.CISSExtraction.HANKEL ~slepc4py.SLEPc.PEP.CISSExtraction.RITZ .. rubric:: Attributes Documentation .. autoattribute:: CAA .. autoattribute:: HANKEL .. autoattribute:: RITZ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Conv.rst0000644000076500000240000000074515133664240023507 0ustar00jromanstaffslepc4py.SLEPc.PEP.Conv ======================= .. autoclass:: slepc4py.SLEPc.PEP.Conv :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Conv.ABS ~slepc4py.SLEPc.PEP.Conv.NORM ~slepc4py.SLEPc.PEP.Conv.REL ~slepc4py.SLEPc.PEP.Conv.USER .. rubric:: Attributes Documentation .. autoattribute:: ABS .. autoattribute:: NORM .. autoattribute:: REL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.ConvergedReason.rst0000644000076500000240000000166215133664240025665 0ustar00jromanstaffslepc4py.SLEPc.PEP.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.PEP.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.PEP.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.PEP.ConvergedReason.CONVERGED_USER ~slepc4py.SLEPc.PEP.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.PEP.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.PEP.ConvergedReason.DIVERGED_SYMMETRY_LOST ~slepc4py.SLEPc.PEP.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_TOL .. autoattribute:: CONVERGED_USER .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: DIVERGED_SYMMETRY_LOST .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908960.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.ErrorType.rst0000644000076500000240000000074015133664240024530 0ustar00jromanstaffslepc4py.SLEPc.PEP.ErrorType ============================ .. autoclass:: slepc4py.SLEPc.PEP.ErrorType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.ErrorType.ABSOLUTE ~slepc4py.SLEPc.PEP.ErrorType.BACKWARD ~slepc4py.SLEPc.PEP.ErrorType.RELATIVE .. rubric:: Attributes Documentation .. autoattribute:: ABSOLUTE .. autoattribute:: BACKWARD .. autoattribute:: RELATIVE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Extract.rst0000644000076500000240000000102215133664241024202 0ustar00jromanstaffslepc4py.SLEPc.PEP.Extract ========================== .. autoclass:: slepc4py.SLEPc.PEP.Extract :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Extract.NONE ~slepc4py.SLEPc.PEP.Extract.NORM ~slepc4py.SLEPc.PEP.Extract.RESIDUAL ~slepc4py.SLEPc.PEP.Extract.STRUCTURED .. rubric:: Attributes Documentation .. autoattribute:: NONE .. autoattribute:: NORM .. autoattribute:: RESIDUAL .. autoattribute:: STRUCTURED ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.JDProjection.rst0000644000076500000240000000064715133664241025136 0ustar00jromanstaffslepc4py.SLEPc.PEP.JDProjection =============================== .. autoclass:: slepc4py.SLEPc.PEP.JDProjection :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.JDProjection.HARMONIC ~slepc4py.SLEPc.PEP.JDProjection.ORTHOGONAL .. rubric:: Attributes Documentation .. autoattribute:: HARMONIC .. autoattribute:: ORTHOGONAL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.ProblemType.rst0000644000076500000240000000110215133664241025031 0ustar00jromanstaffslepc4py.SLEPc.PEP.ProblemType ============================== .. autoclass:: slepc4py.SLEPc.PEP.ProblemType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.ProblemType.GENERAL ~slepc4py.SLEPc.PEP.ProblemType.GYROSCOPIC ~slepc4py.SLEPc.PEP.ProblemType.HERMITIAN ~slepc4py.SLEPc.PEP.ProblemType.HYPERBOLIC .. rubric:: Attributes Documentation .. autoattribute:: GENERAL .. autoattribute:: GYROSCOPIC .. autoattribute:: HERMITIAN .. autoattribute:: HYPERBOLIC ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Refine.rst0000644000076500000240000000070215133664241024004 0ustar00jromanstaffslepc4py.SLEPc.PEP.Refine ========================= .. autoclass:: slepc4py.SLEPc.PEP.Refine :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Refine.MULTIPLE ~slepc4py.SLEPc.PEP.Refine.NONE ~slepc4py.SLEPc.PEP.Refine.SIMPLE .. rubric:: Attributes Documentation .. autoattribute:: MULTIPLE .. autoattribute:: NONE .. autoattribute:: SIMPLE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.RefineScheme.rst0000644000076500000240000000074215133664241025135 0ustar00jromanstaffslepc4py.SLEPc.PEP.RefineScheme =============================== .. autoclass:: slepc4py.SLEPc.PEP.RefineScheme :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.RefineScheme.EXPLICIT ~slepc4py.SLEPc.PEP.RefineScheme.MBE ~slepc4py.SLEPc.PEP.RefineScheme.SCHUR .. rubric:: Attributes Documentation .. autoattribute:: EXPLICIT .. autoattribute:: MBE .. autoattribute:: SCHUR ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Scale.rst0000644000076500000240000000077415133664241023634 0ustar00jromanstaffslepc4py.SLEPc.PEP.Scale ======================== .. autoclass:: slepc4py.SLEPc.PEP.Scale :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Scale.BOTH ~slepc4py.SLEPc.PEP.Scale.DIAGONAL ~slepc4py.SLEPc.PEP.Scale.NONE ~slepc4py.SLEPc.PEP.Scale.SCALAR .. rubric:: Attributes Documentation .. autoattribute:: BOTH .. autoattribute:: DIAGONAL .. autoattribute:: NONE .. autoattribute:: SCALAR ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Stop.rst0000644000076500000240000000055515133664241023527 0ustar00jromanstaffslepc4py.SLEPc.PEP.Stop ======================= .. autoclass:: slepc4py.SLEPc.PEP.Stop :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Stop.BASIC ~slepc4py.SLEPc.PEP.Stop.USER .. rubric:: Attributes Documentation .. autoattribute:: BASIC .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Type.rst0000644000076500000240000000116115133664241023515 0ustar00jromanstaffslepc4py.SLEPc.PEP.Type ======================= .. autoclass:: slepc4py.SLEPc.PEP.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Type.CISS ~slepc4py.SLEPc.PEP.Type.JD ~slepc4py.SLEPc.PEP.Type.LINEAR ~slepc4py.SLEPc.PEP.Type.QARNOLDI ~slepc4py.SLEPc.PEP.Type.STOAR ~slepc4py.SLEPc.PEP.Type.TOAR .. rubric:: Attributes Documentation .. autoattribute:: CISS .. autoattribute:: JD .. autoattribute:: LINEAR .. autoattribute:: QARNOLDI .. autoattribute:: STOAR .. autoattribute:: TOAR ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.Which.rst0000644000076500000240000000217215133664241023641 0ustar00jromanstaffslepc4py.SLEPc.PEP.Which ======================== .. autoclass:: slepc4py.SLEPc.PEP.Which :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.Which.ALL ~slepc4py.SLEPc.PEP.Which.LARGEST_IMAGINARY ~slepc4py.SLEPc.PEP.Which.LARGEST_MAGNITUDE ~slepc4py.SLEPc.PEP.Which.LARGEST_REAL ~slepc4py.SLEPc.PEP.Which.SMALLEST_IMAGINARY ~slepc4py.SLEPc.PEP.Which.SMALLEST_MAGNITUDE ~slepc4py.SLEPc.PEP.Which.SMALLEST_REAL ~slepc4py.SLEPc.PEP.Which.TARGET_IMAGINARY ~slepc4py.SLEPc.PEP.Which.TARGET_MAGNITUDE ~slepc4py.SLEPc.PEP.Which.TARGET_REAL ~slepc4py.SLEPc.PEP.Which.USER .. rubric:: Attributes Documentation .. autoattribute:: ALL .. autoattribute:: LARGEST_IMAGINARY .. autoattribute:: LARGEST_MAGNITUDE .. autoattribute:: LARGEST_REAL .. autoattribute:: SMALLEST_IMAGINARY .. autoattribute:: SMALLEST_MAGNITUDE .. autoattribute:: SMALLEST_REAL .. autoattribute:: TARGET_IMAGINARY .. autoattribute:: TARGET_MAGNITUDE .. autoattribute:: TARGET_REAL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908957.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.PEP.rst0000644000076500000240000002250715133664235022607 0ustar00jromanstaffslepc4py.SLEPc.PEP ================== .. autoclass:: slepc4py.SLEPc.PEP :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.PEP.Basis ~slepc4py.SLEPc.PEP.CISSExtraction ~slepc4py.SLEPc.PEP.Conv ~slepc4py.SLEPc.PEP.ConvergedReason ~slepc4py.SLEPc.PEP.ErrorType ~slepc4py.SLEPc.PEP.Extract ~slepc4py.SLEPc.PEP.JDProjection ~slepc4py.SLEPc.PEP.ProblemType ~slepc4py.SLEPc.PEP.Refine ~slepc4py.SLEPc.PEP.RefineScheme ~slepc4py.SLEPc.PEP.Scale ~slepc4py.SLEPc.PEP.Stop ~slepc4py.SLEPc.PEP.Type ~slepc4py.SLEPc.PEP.Which .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.PEP.appendOptionsPrefix ~slepc4py.SLEPc.PEP.cancelMonitor ~slepc4py.SLEPc.PEP.computeError ~slepc4py.SLEPc.PEP.create ~slepc4py.SLEPc.PEP.destroy ~slepc4py.SLEPc.PEP.errorView ~slepc4py.SLEPc.PEP.getBV ~slepc4py.SLEPc.PEP.getBasis ~slepc4py.SLEPc.PEP.getCISSExtraction ~slepc4py.SLEPc.PEP.getCISSKSPs ~slepc4py.SLEPc.PEP.getCISSRefinement ~slepc4py.SLEPc.PEP.getCISSSizes ~slepc4py.SLEPc.PEP.getCISSThreshold ~slepc4py.SLEPc.PEP.getConverged ~slepc4py.SLEPc.PEP.getConvergedReason ~slepc4py.SLEPc.PEP.getConvergenceTest ~slepc4py.SLEPc.PEP.getDS ~slepc4py.SLEPc.PEP.getDimensions ~slepc4py.SLEPc.PEP.getEigenpair ~slepc4py.SLEPc.PEP.getEigenvalueComparison ~slepc4py.SLEPc.PEP.getErrorEstimate ~slepc4py.SLEPc.PEP.getExtract ~slepc4py.SLEPc.PEP.getInterval ~slepc4py.SLEPc.PEP.getIterationNumber ~slepc4py.SLEPc.PEP.getJDFix ~slepc4py.SLEPc.PEP.getJDMinimalityIndex ~slepc4py.SLEPc.PEP.getJDProjection ~slepc4py.SLEPc.PEP.getJDRestart ~slepc4py.SLEPc.PEP.getJDReusePreconditioner ~slepc4py.SLEPc.PEP.getLinearEPS ~slepc4py.SLEPc.PEP.getLinearExplicitMatrix ~slepc4py.SLEPc.PEP.getLinearLinearization ~slepc4py.SLEPc.PEP.getMonitor ~slepc4py.SLEPc.PEP.getOperators ~slepc4py.SLEPc.PEP.getOptionsPrefix ~slepc4py.SLEPc.PEP.getProblemType ~slepc4py.SLEPc.PEP.getQArnoldiLocking ~slepc4py.SLEPc.PEP.getQArnoldiRestart ~slepc4py.SLEPc.PEP.getRG ~slepc4py.SLEPc.PEP.getRefine ~slepc4py.SLEPc.PEP.getRefineKSP ~slepc4py.SLEPc.PEP.getST ~slepc4py.SLEPc.PEP.getSTOARCheckEigenvalueType ~slepc4py.SLEPc.PEP.getSTOARDetectZeros ~slepc4py.SLEPc.PEP.getSTOARDimensions ~slepc4py.SLEPc.PEP.getSTOARInertias ~slepc4py.SLEPc.PEP.getSTOARLinearization ~slepc4py.SLEPc.PEP.getSTOARLocking ~slepc4py.SLEPc.PEP.getScale ~slepc4py.SLEPc.PEP.getStoppingTest ~slepc4py.SLEPc.PEP.getTOARLocking ~slepc4py.SLEPc.PEP.getTOARRestart ~slepc4py.SLEPc.PEP.getTarget ~slepc4py.SLEPc.PEP.getTolerances ~slepc4py.SLEPc.PEP.getTrackAll ~slepc4py.SLEPc.PEP.getType ~slepc4py.SLEPc.PEP.getWhichEigenpairs ~slepc4py.SLEPc.PEP.reset ~slepc4py.SLEPc.PEP.setBV ~slepc4py.SLEPc.PEP.setBasis ~slepc4py.SLEPc.PEP.setCISSExtraction ~slepc4py.SLEPc.PEP.setCISSRefinement ~slepc4py.SLEPc.PEP.setCISSSizes ~slepc4py.SLEPc.PEP.setCISSThreshold ~slepc4py.SLEPc.PEP.setConvergenceTest ~slepc4py.SLEPc.PEP.setDS ~slepc4py.SLEPc.PEP.setDimensions ~slepc4py.SLEPc.PEP.setEigenvalueComparison ~slepc4py.SLEPc.PEP.setExtract ~slepc4py.SLEPc.PEP.setFromOptions ~slepc4py.SLEPc.PEP.setInitialSpace ~slepc4py.SLEPc.PEP.setInterval ~slepc4py.SLEPc.PEP.setJDFix ~slepc4py.SLEPc.PEP.setJDMinimalityIndex ~slepc4py.SLEPc.PEP.setJDProjection ~slepc4py.SLEPc.PEP.setJDRestart ~slepc4py.SLEPc.PEP.setJDReusePreconditioner ~slepc4py.SLEPc.PEP.setLinearEPS ~slepc4py.SLEPc.PEP.setLinearExplicitMatrix ~slepc4py.SLEPc.PEP.setLinearLinearization ~slepc4py.SLEPc.PEP.setMonitor ~slepc4py.SLEPc.PEP.setOperators ~slepc4py.SLEPc.PEP.setOptionsPrefix ~slepc4py.SLEPc.PEP.setProblemType ~slepc4py.SLEPc.PEP.setQArnoldiLocking ~slepc4py.SLEPc.PEP.setQArnoldiRestart ~slepc4py.SLEPc.PEP.setRG ~slepc4py.SLEPc.PEP.setRefine ~slepc4py.SLEPc.PEP.setST ~slepc4py.SLEPc.PEP.setSTOARCheckEigenvalueType ~slepc4py.SLEPc.PEP.setSTOARDetectZeros ~slepc4py.SLEPc.PEP.setSTOARDimensions ~slepc4py.SLEPc.PEP.setSTOARLinearization ~slepc4py.SLEPc.PEP.setSTOARLocking ~slepc4py.SLEPc.PEP.setScale ~slepc4py.SLEPc.PEP.setStoppingTest ~slepc4py.SLEPc.PEP.setTOARLocking ~slepc4py.SLEPc.PEP.setTOARRestart ~slepc4py.SLEPc.PEP.setTarget ~slepc4py.SLEPc.PEP.setTolerances ~slepc4py.SLEPc.PEP.setTrackAll ~slepc4py.SLEPc.PEP.setType ~slepc4py.SLEPc.PEP.setUp ~slepc4py.SLEPc.PEP.setWhichEigenpairs ~slepc4py.SLEPc.PEP.solve ~slepc4py.SLEPc.PEP.valuesView ~slepc4py.SLEPc.PEP.vectorsView ~slepc4py.SLEPc.PEP.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.PEP.bv ~slepc4py.SLEPc.PEP.ds ~slepc4py.SLEPc.PEP.extract ~slepc4py.SLEPc.PEP.max_it ~slepc4py.SLEPc.PEP.problem_type ~slepc4py.SLEPc.PEP.rg ~slepc4py.SLEPc.PEP.st ~slepc4py.SLEPc.PEP.target ~slepc4py.SLEPc.PEP.tol ~slepc4py.SLEPc.PEP.track_all ~slepc4py.SLEPc.PEP.which .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: cancelMonitor .. automethod:: computeError .. automethod:: create .. automethod:: destroy .. automethod:: errorView .. automethod:: getBV .. automethod:: getBasis .. automethod:: getCISSExtraction .. automethod:: getCISSKSPs .. automethod:: getCISSRefinement .. automethod:: getCISSSizes .. automethod:: getCISSThreshold .. automethod:: getConverged .. automethod:: getConvergedReason .. automethod:: getConvergenceTest .. automethod:: getDS .. automethod:: getDimensions .. automethod:: getEigenpair .. automethod:: getEigenvalueComparison .. automethod:: getErrorEstimate .. automethod:: getExtract .. automethod:: getInterval .. automethod:: getIterationNumber .. automethod:: getJDFix .. automethod:: getJDMinimalityIndex .. automethod:: getJDProjection .. automethod:: getJDRestart .. automethod:: getJDReusePreconditioner .. automethod:: getLinearEPS .. automethod:: getLinearExplicitMatrix .. automethod:: getLinearLinearization .. automethod:: getMonitor .. automethod:: getOperators .. automethod:: getOptionsPrefix .. automethod:: getProblemType .. automethod:: getQArnoldiLocking .. automethod:: getQArnoldiRestart .. automethod:: getRG .. automethod:: getRefine .. automethod:: getRefineKSP .. automethod:: getST .. automethod:: getSTOARCheckEigenvalueType .. automethod:: getSTOARDetectZeros .. automethod:: getSTOARDimensions .. automethod:: getSTOARInertias .. automethod:: getSTOARLinearization .. automethod:: getSTOARLocking .. automethod:: getScale .. automethod:: getStoppingTest .. automethod:: getTOARLocking .. automethod:: getTOARRestart .. automethod:: getTarget .. automethod:: getTolerances .. automethod:: getTrackAll .. automethod:: getType .. automethod:: getWhichEigenpairs .. automethod:: reset .. automethod:: setBV .. automethod:: setBasis .. automethod:: setCISSExtraction .. automethod:: setCISSRefinement .. automethod:: setCISSSizes .. automethod:: setCISSThreshold .. automethod:: setConvergenceTest .. automethod:: setDS .. automethod:: setDimensions .. automethod:: setEigenvalueComparison .. automethod:: setExtract .. automethod:: setFromOptions .. automethod:: setInitialSpace .. automethod:: setInterval .. automethod:: setJDFix .. automethod:: setJDMinimalityIndex .. automethod:: setJDProjection .. automethod:: setJDRestart .. automethod:: setJDReusePreconditioner .. automethod:: setLinearEPS .. automethod:: setLinearExplicitMatrix .. automethod:: setLinearLinearization .. automethod:: setMonitor .. automethod:: setOperators .. automethod:: setOptionsPrefix .. automethod:: setProblemType .. automethod:: setQArnoldiLocking .. automethod:: setQArnoldiRestart .. automethod:: setRG .. automethod:: setRefine .. automethod:: setST .. automethod:: setSTOARCheckEigenvalueType .. automethod:: setSTOARDetectZeros .. automethod:: setSTOARDimensions .. automethod:: setSTOARLinearization .. automethod:: setSTOARLocking .. automethod:: setScale .. automethod:: setStoppingTest .. automethod:: setTOARLocking .. automethod:: setTOARRestart .. automethod:: setTarget .. automethod:: setTolerances .. automethod:: setTrackAll .. automethod:: setType .. automethod:: setUp .. automethod:: setWhichEigenpairs .. automethod:: solve .. automethod:: valuesView .. automethod:: vectorsView .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: bv .. autoattribute:: ds .. autoattribute:: extract .. autoattribute:: max_it .. autoattribute:: problem_type .. autoattribute:: rg .. autoattribute:: st .. autoattribute:: target .. autoattribute:: tol .. autoattribute:: track_all .. autoattribute:: which ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.RG.QuadRule.rst0000644000076500000240000000062215133664241024203 0ustar00jromanstaffslepc4py.SLEPc.RG.QuadRule ========================== .. autoclass:: slepc4py.SLEPc.RG.QuadRule :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.RG.QuadRule.CHEBYSHEV ~slepc4py.SLEPc.RG.QuadRule.TRAPEZOIDAL .. rubric:: Attributes Documentation .. autoattribute:: CHEBYSHEV .. autoattribute:: TRAPEZOIDAL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.RG.Type.rst0000644000076500000240000000076615133664241023413 0ustar00jromanstaffslepc4py.SLEPc.RG.Type ====================== .. autoclass:: slepc4py.SLEPc.RG.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.RG.Type.ELLIPSE ~slepc4py.SLEPc.RG.Type.INTERVAL ~slepc4py.SLEPc.RG.Type.POLYGON ~slepc4py.SLEPc.RG.Type.RING .. rubric:: Attributes Documentation .. autoattribute:: ELLIPSE .. autoattribute:: INTERVAL .. autoattribute:: POLYGON .. autoattribute:: RING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.RG.rst0000644000076500000240000000511515133664236022470 0ustar00jromanstaffslepc4py.SLEPc.RG ================= .. autoclass:: slepc4py.SLEPc.RG :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.RG.QuadRule ~slepc4py.SLEPc.RG.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.RG.appendOptionsPrefix ~slepc4py.SLEPc.RG.canUseConjugates ~slepc4py.SLEPc.RG.checkInside ~slepc4py.SLEPc.RG.computeBoundingBox ~slepc4py.SLEPc.RG.computeContour ~slepc4py.SLEPc.RG.computeQuadrature ~slepc4py.SLEPc.RG.create ~slepc4py.SLEPc.RG.destroy ~slepc4py.SLEPc.RG.getComplement ~slepc4py.SLEPc.RG.getEllipseParameters ~slepc4py.SLEPc.RG.getIntervalEndpoints ~slepc4py.SLEPc.RG.getOptionsPrefix ~slepc4py.SLEPc.RG.getPolygonVertices ~slepc4py.SLEPc.RG.getRingParameters ~slepc4py.SLEPc.RG.getScale ~slepc4py.SLEPc.RG.getType ~slepc4py.SLEPc.RG.isAxisymmetric ~slepc4py.SLEPc.RG.isTrivial ~slepc4py.SLEPc.RG.setComplement ~slepc4py.SLEPc.RG.setEllipseParameters ~slepc4py.SLEPc.RG.setFromOptions ~slepc4py.SLEPc.RG.setIntervalEndpoints ~slepc4py.SLEPc.RG.setOptionsPrefix ~slepc4py.SLEPc.RG.setPolygonVertices ~slepc4py.SLEPc.RG.setRingParameters ~slepc4py.SLEPc.RG.setScale ~slepc4py.SLEPc.RG.setType ~slepc4py.SLEPc.RG.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.RG.complement ~slepc4py.SLEPc.RG.scale .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: canUseConjugates .. automethod:: checkInside .. automethod:: computeBoundingBox .. automethod:: computeContour .. automethod:: computeQuadrature .. automethod:: create .. automethod:: destroy .. automethod:: getComplement .. automethod:: getEllipseParameters .. automethod:: getIntervalEndpoints .. automethod:: getOptionsPrefix .. automethod:: getPolygonVertices .. automethod:: getRingParameters .. automethod:: getScale .. automethod:: getType .. automethod:: isAxisymmetric .. automethod:: isTrivial .. automethod:: setComplement .. automethod:: setEllipseParameters .. automethod:: setFromOptions .. automethod:: setIntervalEndpoints .. automethod:: setOptionsPrefix .. automethod:: setPolygonVertices .. automethod:: setRingParameters .. automethod:: setScale .. automethod:: setType .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: complement .. autoattribute:: scale ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.ST.FilterDamping.rst0000644000076500000240000000105715133664241025227 0ustar00jromanstaffslepc4py.SLEPc.ST.FilterDamping =============================== .. autoclass:: slepc4py.SLEPc.ST.FilterDamping :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.ST.FilterDamping.FEJER ~slepc4py.SLEPc.ST.FilterDamping.JACKSON ~slepc4py.SLEPc.ST.FilterDamping.LANCZOS ~slepc4py.SLEPc.ST.FilterDamping.NONE .. rubric:: Attributes Documentation .. autoattribute:: FEJER .. autoattribute:: JACKSON .. autoattribute:: LANCZOS .. autoattribute:: NONE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.ST.FilterType.rst0000644000076500000240000000062415133664241024570 0ustar00jromanstaffslepc4py.SLEPc.ST.FilterType ============================ .. autoclass:: slepc4py.SLEPc.ST.FilterType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.ST.FilterType.CHEBYSHEV ~slepc4py.SLEPc.ST.FilterType.FILTLAN .. rubric:: Attributes Documentation .. autoattribute:: CHEBYSHEV .. autoattribute:: FILTLAN ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.ST.MatMode.rst0000644000076500000240000000067615133664241024036 0ustar00jromanstaffslepc4py.SLEPc.ST.MatMode ========================= .. autoclass:: slepc4py.SLEPc.ST.MatMode :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.ST.MatMode.COPY ~slepc4py.SLEPc.ST.MatMode.INPLACE ~slepc4py.SLEPc.ST.MatMode.SHELL .. rubric:: Attributes Documentation .. autoattribute:: COPY .. autoattribute:: INPLACE .. autoattribute:: SHELL ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.ST.Type.rst0000644000076500000240000000116615133664241023424 0ustar00jromanstaffslepc4py.SLEPc.ST.Type ====================== .. autoclass:: slepc4py.SLEPc.ST.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.ST.Type.CAYLEY ~slepc4py.SLEPc.ST.Type.FILTER ~slepc4py.SLEPc.ST.Type.PRECOND ~slepc4py.SLEPc.ST.Type.SHELL ~slepc4py.SLEPc.ST.Type.SHIFT ~slepc4py.SLEPc.ST.Type.SINVERT .. rubric:: Attributes Documentation .. autoattribute:: CAYLEY .. autoattribute:: FILTER .. autoattribute:: PRECOND .. autoattribute:: SHELL .. autoattribute:: SHIFT .. autoattribute:: SINVERT ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.ST.rst0000644000076500000240000000774015133664236022514 0ustar00jromanstaffslepc4py.SLEPc.ST ================= .. autoclass:: slepc4py.SLEPc.ST :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.ST.FilterDamping ~slepc4py.SLEPc.ST.FilterType ~slepc4py.SLEPc.ST.MatMode ~slepc4py.SLEPc.ST.Type .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.ST.appendOptionsPrefix ~slepc4py.SLEPc.ST.apply ~slepc4py.SLEPc.ST.applyHermitianTranspose ~slepc4py.SLEPc.ST.applyMat ~slepc4py.SLEPc.ST.applyTranspose ~slepc4py.SLEPc.ST.create ~slepc4py.SLEPc.ST.destroy ~slepc4py.SLEPc.ST.getCayleyAntishift ~slepc4py.SLEPc.ST.getFilterDamping ~slepc4py.SLEPc.ST.getFilterDegree ~slepc4py.SLEPc.ST.getFilterInterval ~slepc4py.SLEPc.ST.getFilterRange ~slepc4py.SLEPc.ST.getFilterType ~slepc4py.SLEPc.ST.getKSP ~slepc4py.SLEPc.ST.getMatMode ~slepc4py.SLEPc.ST.getMatStructure ~slepc4py.SLEPc.ST.getMatrices ~slepc4py.SLEPc.ST.getOperator ~slepc4py.SLEPc.ST.getOptionsPrefix ~slepc4py.SLEPc.ST.getPreconditionerMat ~slepc4py.SLEPc.ST.getShift ~slepc4py.SLEPc.ST.getSplitPreconditioner ~slepc4py.SLEPc.ST.getTransform ~slepc4py.SLEPc.ST.getType ~slepc4py.SLEPc.ST.reset ~slepc4py.SLEPc.ST.restoreOperator ~slepc4py.SLEPc.ST.setCayleyAntishift ~slepc4py.SLEPc.ST.setFilterDamping ~slepc4py.SLEPc.ST.setFilterDegree ~slepc4py.SLEPc.ST.setFilterInterval ~slepc4py.SLEPc.ST.setFilterRange ~slepc4py.SLEPc.ST.setFilterType ~slepc4py.SLEPc.ST.setFromOptions ~slepc4py.SLEPc.ST.setKSP ~slepc4py.SLEPc.ST.setMatMode ~slepc4py.SLEPc.ST.setMatStructure ~slepc4py.SLEPc.ST.setMatrices ~slepc4py.SLEPc.ST.setOptionsPrefix ~slepc4py.SLEPc.ST.setPreconditionerMat ~slepc4py.SLEPc.ST.setShift ~slepc4py.SLEPc.ST.setSplitPreconditioner ~slepc4py.SLEPc.ST.setTransform ~slepc4py.SLEPc.ST.setType ~slepc4py.SLEPc.ST.setUp ~slepc4py.SLEPc.ST.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.ST.ksp ~slepc4py.SLEPc.ST.mat_mode ~slepc4py.SLEPc.ST.mat_structure ~slepc4py.SLEPc.ST.shift ~slepc4py.SLEPc.ST.transform .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: apply .. automethod:: applyHermitianTranspose .. automethod:: applyMat .. automethod:: applyTranspose .. automethod:: create .. automethod:: destroy .. automethod:: getCayleyAntishift .. automethod:: getFilterDamping .. automethod:: getFilterDegree .. automethod:: getFilterInterval .. automethod:: getFilterRange .. automethod:: getFilterType .. automethod:: getKSP .. automethod:: getMatMode .. automethod:: getMatStructure .. automethod:: getMatrices .. automethod:: getOperator .. automethod:: getOptionsPrefix .. automethod:: getPreconditionerMat .. automethod:: getShift .. automethod:: getSplitPreconditioner .. automethod:: getTransform .. automethod:: getType .. automethod:: reset .. automethod:: restoreOperator .. automethod:: setCayleyAntishift .. automethod:: setFilterDamping .. automethod:: setFilterDegree .. automethod:: setFilterInterval .. automethod:: setFilterRange .. automethod:: setFilterType .. automethod:: setFromOptions .. automethod:: setKSP .. automethod:: setMatMode .. automethod:: setMatStructure .. automethod:: setMatrices .. automethod:: setOptionsPrefix .. automethod:: setPreconditionerMat .. automethod:: setShift .. automethod:: setSplitPreconditioner .. automethod:: setTransform .. automethod:: setType .. automethod:: setUp .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: ksp .. autoattribute:: mat_mode .. autoattribute:: mat_structure .. autoattribute:: shift .. autoattribute:: transform ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.Conv.rst0000644000076500000240000000104615133664241023513 0ustar00jromanstaffslepc4py.SLEPc.SVD.Conv ======================= .. autoclass:: slepc4py.SLEPc.SVD.Conv :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.Conv.ABS ~slepc4py.SLEPc.SVD.Conv.MAXIT ~slepc4py.SLEPc.SVD.Conv.NORM ~slepc4py.SLEPc.SVD.Conv.REL ~slepc4py.SLEPc.SVD.Conv.USER .. rubric:: Attributes Documentation .. autoattribute:: ABS .. autoattribute:: MAXIT .. autoattribute:: NORM .. autoattribute:: REL .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.ConvergedReason.rst0000644000076500000240000000202215133664241025665 0ustar00jromanstaffslepc4py.SLEPc.SVD.ConvergedReason ================================== .. autoclass:: slepc4py.SLEPc.SVD.ConvergedReason :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.ConvergedReason.CONVERGED_ITERATING ~slepc4py.SLEPc.SVD.ConvergedReason.CONVERGED_MAXIT ~slepc4py.SLEPc.SVD.ConvergedReason.CONVERGED_TOL ~slepc4py.SLEPc.SVD.ConvergedReason.CONVERGED_USER ~slepc4py.SLEPc.SVD.ConvergedReason.DIVERGED_BREAKDOWN ~slepc4py.SLEPc.SVD.ConvergedReason.DIVERGED_ITS ~slepc4py.SLEPc.SVD.ConvergedReason.DIVERGED_SYMMETRY_LOST ~slepc4py.SLEPc.SVD.ConvergedReason.ITERATING .. rubric:: Attributes Documentation .. autoattribute:: CONVERGED_ITERATING .. autoattribute:: CONVERGED_MAXIT .. autoattribute:: CONVERGED_TOL .. autoattribute:: CONVERGED_USER .. autoattribute:: DIVERGED_BREAKDOWN .. autoattribute:: DIVERGED_ITS .. autoattribute:: DIVERGED_SYMMETRY_LOST .. autoattribute:: ITERATING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.ErrorType.rst0000644000076500000240000000073015133664241024540 0ustar00jromanstaffslepc4py.SLEPc.SVD.ErrorType ============================ .. autoclass:: slepc4py.SLEPc.SVD.ErrorType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.ErrorType.ABSOLUTE ~slepc4py.SLEPc.SVD.ErrorType.NORM ~slepc4py.SLEPc.SVD.ErrorType.RELATIVE .. rubric:: Attributes Documentation .. autoattribute:: ABSOLUTE .. autoattribute:: NORM .. autoattribute:: RELATIVE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908961.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.ProblemType.rst0000644000076500000240000000076615133664241025060 0ustar00jromanstaffslepc4py.SLEPc.SVD.ProblemType ============================== .. autoclass:: slepc4py.SLEPc.SVD.ProblemType :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.ProblemType.GENERALIZED ~slepc4py.SLEPc.SVD.ProblemType.HYPERBOLIC ~slepc4py.SLEPc.SVD.ProblemType.STANDARD .. rubric:: Attributes Documentation .. autoattribute:: GENERALIZED .. autoattribute:: HYPERBOLIC .. autoattribute:: STANDARD ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908962.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.Stop.rst0000644000076500000240000000066615133664242023543 0ustar00jromanstaffslepc4py.SLEPc.SVD.Stop ======================= .. autoclass:: slepc4py.SLEPc.SVD.Stop :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.Stop.BASIC ~slepc4py.SLEPc.SVD.Stop.THRESHOLD ~slepc4py.SLEPc.SVD.Stop.USER .. rubric:: Attributes Documentation .. autoattribute:: BASIC .. autoattribute:: THRESHOLD .. autoattribute:: USER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908962.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.TRLanczosGBidiag.rst0000644000076500000240000000077215133664242025702 0ustar00jromanstaffslepc4py.SLEPc.SVD.TRLanczosGBidiag =================================== .. autoclass:: slepc4py.SLEPc.SVD.TRLanczosGBidiag :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.TRLanczosGBidiag.LOWER ~slepc4py.SLEPc.SVD.TRLanczosGBidiag.SINGLE ~slepc4py.SLEPc.SVD.TRLanczosGBidiag.UPPER .. rubric:: Attributes Documentation .. autoattribute:: LOWER .. autoattribute:: SINGLE .. autoattribute:: UPPER ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908962.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.Type.rst0000644000076500000240000000164115133664242023531 0ustar00jromanstaffslepc4py.SLEPc.SVD.Type ======================= .. autoclass:: slepc4py.SLEPc.SVD.Type :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.Type.CROSS ~slepc4py.SLEPc.SVD.Type.CYCLIC ~slepc4py.SLEPc.SVD.Type.ELEMENTAL ~slepc4py.SLEPc.SVD.Type.KSVD ~slepc4py.SLEPc.SVD.Type.LANCZOS ~slepc4py.SLEPc.SVD.Type.LAPACK ~slepc4py.SLEPc.SVD.Type.PRIMME ~slepc4py.SLEPc.SVD.Type.RANDOMIZED ~slepc4py.SLEPc.SVD.Type.SCALAPACK ~slepc4py.SLEPc.SVD.Type.TRLANCZOS .. rubric:: Attributes Documentation .. autoattribute:: CROSS .. autoattribute:: CYCLIC .. autoattribute:: ELEMENTAL .. autoattribute:: KSVD .. autoattribute:: LANCZOS .. autoattribute:: LAPACK .. autoattribute:: PRIMME .. autoattribute:: RANDOMIZED .. autoattribute:: SCALAPACK .. autoattribute:: TRLANCZOS ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908962.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.Which.rst0000644000076500000240000000057615133664242023660 0ustar00jromanstaffslepc4py.SLEPc.SVD.Which ======================== .. autoclass:: slepc4py.SLEPc.SVD.Which :show-inheritance: .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.Which.LARGEST ~slepc4py.SLEPc.SVD.Which.SMALLEST .. rubric:: Attributes Documentation .. autoattribute:: LARGEST .. autoattribute:: SMALLEST ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.SVD.rst0000644000076500000240000001524215133664236022616 0ustar00jromanstaffslepc4py.SLEPc.SVD ================== .. autoclass:: slepc4py.SLEPc.SVD :show-inheritance: .. rubric:: Enumerations .. autosummary:: :toctree: ~slepc4py.SLEPc.SVD.Conv ~slepc4py.SLEPc.SVD.ConvergedReason ~slepc4py.SLEPc.SVD.ErrorType ~slepc4py.SLEPc.SVD.ProblemType ~slepc4py.SLEPc.SVD.Stop ~slepc4py.SLEPc.SVD.TRLanczosGBidiag ~slepc4py.SLEPc.SVD.Type ~slepc4py.SLEPc.SVD.Which .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.SVD.appendOptionsPrefix ~slepc4py.SLEPc.SVD.cancelMonitor ~slepc4py.SLEPc.SVD.computeError ~slepc4py.SLEPc.SVD.create ~slepc4py.SLEPc.SVD.destroy ~slepc4py.SLEPc.SVD.errorView ~slepc4py.SLEPc.SVD.getBV ~slepc4py.SLEPc.SVD.getConverged ~slepc4py.SLEPc.SVD.getConvergedReason ~slepc4py.SLEPc.SVD.getConvergenceTest ~slepc4py.SLEPc.SVD.getCrossEPS ~slepc4py.SLEPc.SVD.getCrossExplicitMatrix ~slepc4py.SLEPc.SVD.getCyclicEPS ~slepc4py.SLEPc.SVD.getCyclicExplicitMatrix ~slepc4py.SLEPc.SVD.getDS ~slepc4py.SLEPc.SVD.getDimensions ~slepc4py.SLEPc.SVD.getImplicitTranspose ~slepc4py.SLEPc.SVD.getIterationNumber ~slepc4py.SLEPc.SVD.getLanczosOneSide ~slepc4py.SLEPc.SVD.getMonitor ~slepc4py.SLEPc.SVD.getOperators ~slepc4py.SLEPc.SVD.getOptionsPrefix ~slepc4py.SLEPc.SVD.getProblemType ~slepc4py.SLEPc.SVD.getSignature ~slepc4py.SLEPc.SVD.getSingularTriplet ~slepc4py.SLEPc.SVD.getStoppingTest ~slepc4py.SLEPc.SVD.getTRLanczosExplicitMatrix ~slepc4py.SLEPc.SVD.getTRLanczosGBidiag ~slepc4py.SLEPc.SVD.getTRLanczosKSP ~slepc4py.SLEPc.SVD.getTRLanczosLocking ~slepc4py.SLEPc.SVD.getTRLanczosOneSide ~slepc4py.SLEPc.SVD.getTRLanczosRestart ~slepc4py.SLEPc.SVD.getThreshold ~slepc4py.SLEPc.SVD.getTolerances ~slepc4py.SLEPc.SVD.getTrackAll ~slepc4py.SLEPc.SVD.getType ~slepc4py.SLEPc.SVD.getValue ~slepc4py.SLEPc.SVD.getVectors ~slepc4py.SLEPc.SVD.getWhichSingularTriplets ~slepc4py.SLEPc.SVD.isGeneralized ~slepc4py.SLEPc.SVD.isHyperbolic ~slepc4py.SLEPc.SVD.reset ~slepc4py.SLEPc.SVD.setBV ~slepc4py.SLEPc.SVD.setConvergenceTest ~slepc4py.SLEPc.SVD.setCrossEPS ~slepc4py.SLEPc.SVD.setCrossExplicitMatrix ~slepc4py.SLEPc.SVD.setCyclicEPS ~slepc4py.SLEPc.SVD.setCyclicExplicitMatrix ~slepc4py.SLEPc.SVD.setDS ~slepc4py.SLEPc.SVD.setDimensions ~slepc4py.SLEPc.SVD.setFromOptions ~slepc4py.SLEPc.SVD.setImplicitTranspose ~slepc4py.SLEPc.SVD.setInitialSpace ~slepc4py.SLEPc.SVD.setLanczosOneSide ~slepc4py.SLEPc.SVD.setMonitor ~slepc4py.SLEPc.SVD.setOperators ~slepc4py.SLEPc.SVD.setOptionsPrefix ~slepc4py.SLEPc.SVD.setProblemType ~slepc4py.SLEPc.SVD.setSignature ~slepc4py.SLEPc.SVD.setStoppingTest ~slepc4py.SLEPc.SVD.setTRLanczosExplicitMatrix ~slepc4py.SLEPc.SVD.setTRLanczosGBidiag ~slepc4py.SLEPc.SVD.setTRLanczosKSP ~slepc4py.SLEPc.SVD.setTRLanczosLocking ~slepc4py.SLEPc.SVD.setTRLanczosOneSide ~slepc4py.SLEPc.SVD.setTRLanczosRestart ~slepc4py.SLEPc.SVD.setThreshold ~slepc4py.SLEPc.SVD.setTolerances ~slepc4py.SLEPc.SVD.setTrackAll ~slepc4py.SLEPc.SVD.setType ~slepc4py.SLEPc.SVD.setUp ~slepc4py.SLEPc.SVD.setWhichSingularTriplets ~slepc4py.SLEPc.SVD.solve ~slepc4py.SLEPc.SVD.valuesView ~slepc4py.SLEPc.SVD.vectorsView ~slepc4py.SLEPc.SVD.view .. rubric:: Attributes Summary .. autosummary:: ~slepc4py.SLEPc.SVD.ds ~slepc4py.SLEPc.SVD.max_it ~slepc4py.SLEPc.SVD.problem_type ~slepc4py.SLEPc.SVD.tol ~slepc4py.SLEPc.SVD.track_all ~slepc4py.SLEPc.SVD.transpose_mode ~slepc4py.SLEPc.SVD.which .. rubric:: Methods Documentation .. automethod:: appendOptionsPrefix .. automethod:: cancelMonitor .. automethod:: computeError .. automethod:: create .. automethod:: destroy .. automethod:: errorView .. automethod:: getBV .. automethod:: getConverged .. automethod:: getConvergedReason .. automethod:: getConvergenceTest .. automethod:: getCrossEPS .. automethod:: getCrossExplicitMatrix .. automethod:: getCyclicEPS .. automethod:: getCyclicExplicitMatrix .. automethod:: getDS .. automethod:: getDimensions .. automethod:: getImplicitTranspose .. automethod:: getIterationNumber .. automethod:: getLanczosOneSide .. automethod:: getMonitor .. automethod:: getOperators .. automethod:: getOptionsPrefix .. automethod:: getProblemType .. automethod:: getSignature .. automethod:: getSingularTriplet .. automethod:: getStoppingTest .. automethod:: getTRLanczosExplicitMatrix .. automethod:: getTRLanczosGBidiag .. automethod:: getTRLanczosKSP .. automethod:: getTRLanczosLocking .. automethod:: getTRLanczosOneSide .. automethod:: getTRLanczosRestart .. automethod:: getThreshold .. automethod:: getTolerances .. automethod:: getTrackAll .. automethod:: getType .. automethod:: getValue .. automethod:: getVectors .. automethod:: getWhichSingularTriplets .. automethod:: isGeneralized .. automethod:: isHyperbolic .. automethod:: reset .. automethod:: setBV .. automethod:: setConvergenceTest .. automethod:: setCrossEPS .. automethod:: setCrossExplicitMatrix .. automethod:: setCyclicEPS .. automethod:: setCyclicExplicitMatrix .. automethod:: setDS .. automethod:: setDimensions .. automethod:: setFromOptions .. automethod:: setImplicitTranspose .. automethod:: setInitialSpace .. automethod:: setLanczosOneSide .. automethod:: setMonitor .. automethod:: setOperators .. automethod:: setOptionsPrefix .. automethod:: setProblemType .. automethod:: setSignature .. automethod:: setStoppingTest .. automethod:: setTRLanczosExplicitMatrix .. automethod:: setTRLanczosGBidiag .. automethod:: setTRLanczosKSP .. automethod:: setTRLanczosLocking .. automethod:: setTRLanczosOneSide .. automethod:: setTRLanczosRestart .. automethod:: setThreshold .. automethod:: setTolerances .. automethod:: setTrackAll .. automethod:: setType .. automethod:: setUp .. automethod:: setWhichSingularTriplets .. automethod:: solve .. automethod:: valuesView .. automethod:: vectorsView .. automethod:: view .. rubric:: Attributes Documentation .. autoattribute:: ds .. autoattribute:: max_it .. autoattribute:: problem_type .. autoattribute:: tol .. autoattribute:: track_all .. autoattribute:: transpose_mode .. autoattribute:: which ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.Sys.rst0000644000076500000240000000110715133664236022733 0ustar00jromanstaffslepc4py.SLEPc.Sys ================== .. autoclass:: slepc4py.SLEPc.Sys :show-inheritance: .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.Sys.getVersion ~slepc4py.SLEPc.Sys.getVersionInfo ~slepc4py.SLEPc.Sys.hasExternalPackage ~slepc4py.SLEPc.Sys.isFinalized ~slepc4py.SLEPc.Sys.isInitialized .. rubric:: Methods Documentation .. automethod:: getVersion .. automethod:: getVersionInfo .. automethod:: hasExternalPackage .. automethod:: isFinalized .. automethod:: isInitialized ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.Util.rst0000644000076500000240000000057315133664236023100 0ustar00jromanstaffslepc4py.SLEPc.Util =================== .. autoclass:: slepc4py.SLEPc.Util :show-inheritance: .. rubric:: Methods Summary .. autosummary:: ~slepc4py.SLEPc.Util.createMatBSE ~slepc4py.SLEPc.Util.createMatHamiltonian .. rubric:: Methods Documentation .. automethod:: createMatBSE .. automethod:: createMatHamiltonian ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908955.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.py0000644000076500000240000215036715133664233022012 0ustar00jromanstaff""" Scalable Library for Eigenvalue Problem Computations """ from __future__ import annotations import sys from typing import ( Any, Union, Optional, Callable, Sequence, ) if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self import numpy from numpy import dtype, ndarray from mpi4py.MPI import ( Intracomm, Datatype, Op, ) # ----------------------------------------------------------------------------- from petsc4py.PETSc import ( Object, Comm, NormType, Random, Viewer, Vec, Mat, KSP, ) # ----------------------------------------------------------------------------- class _dtype: def __init__(self, name): self.name = name def __repr__(self): return self.name IntType: dtype = _dtype('IntType') RealType: dtype = _dtype('RealType') ComplexType: dtype = _dtype('ComplexType') ScalarType: dtype = _dtype('ScalarType') class _Int(int): pass class _Str(str): pass class _Float(float): pass class _Dict(dict): pass def _repr(obj): try: return obj._name except AttributeError: return super(obj).__repr__() def _def(cls, name): if cls is int: cls = _Int if cls is str: cls = _Str if cls is float: cls = _Float if cls is dict: cls = _Dict obj = cls() obj._name = name if '__repr__' not in cls.__dict__: cls.__repr__ = _repr return obj DECIDE: int = _def(int, 'DECIDE') #: Constant ``DECIDE`` of type :class:`int` DEFAULT: int = _def(int, 'DEFAULT') #: Constant ``DEFAULT`` of type :class:`int` DETERMINE: int = _def(int, 'DETERMINE') #: Constant ``DETERMINE`` of type :class:`int` CURRENT: int = _def(int, 'CURRENT') #: Constant ``CURRENT`` of type :class:`int` __arch__: str = _def(str, '__arch__') #: Object ``__arch__`` of type :class:`str` class ST(Object): """Spectral Transformation. The Spectral Transformation (`ST`) class encapsulates the functionality required for acceleration techniques based on the transformation of the spectrum. The eigensolvers implemented in `EPS` work by applying an operator to a set of vectors and this operator can adopt different forms. The `ST` object handles all the different possibilities in a uniform way, so that the solver can proceed without knowing which transformation has been selected. Polynomial eigensolvers in `PEP` also support spectral transformation. """ class Type: """ST type. - `SHIFT`: Shift from origin. - `SINVERT`: Shift-and-invert. - `CAYLEY`: Cayley transform. - `PRECOND`: Preconditioner. - `FILTER`: Polynomial filter. - `SHELL`: User-defined. See Also -------- slepc.STType """ SHIFT: str = _def(str, 'SHIFT') #: Object ``SHIFT`` of type :class:`str` SINVERT: str = _def(str, 'SINVERT') #: Object ``SINVERT`` of type :class:`str` CAYLEY: str = _def(str, 'CAYLEY') #: Object ``CAYLEY`` of type :class:`str` PRECOND: str = _def(str, 'PRECOND') #: Object ``PRECOND`` of type :class:`str` FILTER: str = _def(str, 'FILTER') #: Object ``FILTER`` of type :class:`str` SHELL: str = _def(str, 'SHELL') #: Object ``SHELL`` of type :class:`str` class MatMode: """ST matrix mode. - `COPY`: A working copy of the matrix is created. - `INPLACE`: The operation is computed in-place. - `SHELL`: The matrix :math:`A - \sigma B` is handled as an implicit matrix. See Also -------- slepc.STMatMode """ COPY: int = _def(int, 'COPY') #: Constant ``COPY`` of type :class:`int` INPLACE: int = _def(int, 'INPLACE') #: Constant ``INPLACE`` of type :class:`int` SHELL: int = _def(int, 'SHELL') #: Constant ``SHELL`` of type :class:`int` class FilterType: """ST filter type. - ``FILTLAN``: An adapted implementation of the Filtered Lanczos Package. - ``CHEBYSEV``: A polynomial filter based on a truncated Chebyshev series. See Also -------- slepc.STFilterType """ FILTLAN: int = _def(int, 'FILTLAN') #: Constant ``FILTLAN`` of type :class:`int` CHEBYSHEV: int = _def(int, 'CHEBYSHEV') #: Constant ``CHEBYSHEV`` of type :class:`int` class FilterDamping: """ST filter damping. - `NONE`: No damping - `JACKSON`: Jackson damping - `LANCZOS`: Lanczos damping - `FEJER`: Fejer damping See Also -------- slepc.STFilterDamping """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` JACKSON: int = _def(int, 'JACKSON') #: Constant ``JACKSON`` of type :class:`int` LANCZOS: int = _def(int, 'LANCZOS') #: Constant ``LANCZOS`` of type :class:`int` FEJER: int = _def(int, 'FEJER') #: Constant ``FEJER`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the ST data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.STView :sources:`Source code at slepc4py/SLEPc/ST.pyx:100 ` """ ... def destroy(self) -> Self: """Destroy the ST object. Collective. See Also -------- slepc.STDestroy :sources:`Source code at slepc4py/SLEPc/ST.pyx:119 ` """ ... def reset(self) -> None: """Reset the ST object. Collective. See Also -------- slepc.STReset :sources:`Source code at slepc4py/SLEPc/ST.pyx:133 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the ST object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.STCreate :sources:`Source code at slepc4py/SLEPc/ST.pyx:145 ` """ ... def setType(self, st_type: Type | str) -> None: """Set the particular spectral transformation to be used. Logically collective. Parameters ---------- st_type The spectral transformation to be used. Notes ----- The default is `SHIFT` with a zero shift. Normally, it is best to use `setFromOptions()` and then set the ST type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.STSetType :sources:`Source code at slepc4py/SLEPc/ST.pyx:166 ` """ ... def getType(self) -> str: """Get the ST type of this object. Not collective. Returns ------- str The spectral transformation currently being used. See Also -------- setType, slepc.STGetType :sources:`Source code at slepc4py/SLEPc/ST.pyx:193 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all ST options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all ST option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.STGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/ST.pyx:212 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all ST options in the database. Not collective. Returns ------- str The prefix string set for this ST object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.STGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/ST.pyx:237 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all ST options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all ST option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.STAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/ST.pyx:256 ` """ ... def setFromOptions(self) -> None: """Set ST options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.STSetFromOptions :sources:`Source code at slepc4py/SLEPc/ST.pyx:275 ` """ ... def setShift(self, shift: Scalar) -> None: """Set the shift associated with the spectral transformation. Collective. Parameters ---------- shift The value of the shift. Notes ----- In some spectral transformations, changing the shift may have associated a lot of work, for example recomputing a factorization. This function is normally not directly called by users, since the shift is indirectly set by `EPS.setTarget()`. See Also -------- getShift, slepc.STSetShift :sources:`Source code at slepc4py/SLEPc/ST.pyx:296 ` """ ... def getShift(self) -> Scalar: """Get the shift associated with the spectral transformation. Not collective. Returns ------- Scalar The value of the shift. See Also -------- setShift, slepc.STGetShift :sources:`Source code at slepc4py/SLEPc/ST.pyx:323 ` """ ... def setTransform(self, flag: bool = True) -> None: """Set a flag to indicate whether the transformed matrices are computed or not. Logically collective. Parameters ---------- flag This flag is intended for the case of polynomial eigenproblems solved via linearization. If this flag is ``False`` (default) the spectral transformation is applied to the linearization (handled by the eigensolver), otherwise it is applied to the original problem. See Also -------- getTransform, slepc.STSetTransform :sources:`Source code at slepc4py/SLEPc/ST.pyx:342 ` """ ... def getTransform(self) -> bool: """Get the flag indicating whether the transformed matrices are computed or not. Not collective. Returns ------- bool This flag is intended for the case of polynomial eigenproblems solved via linearization. If this flag is ``False`` (default) the spectral transformation is applied to the linearization (handled by the eigensolver), otherwise it is applied to the original problem. See Also -------- setTransform, slepc.STGetTransform :sources:`Source code at slepc4py/SLEPc/ST.pyx:364 ` """ ... def setMatMode(self, mode: MatMode) -> None: """Set a flag related to management of transformed matrices. Logically collective. The flag indicates how the transformed matrices are being stored in the spectral transformation. Parameters ---------- mode The mode flag. Notes ----- By default (`ST.MatMode.COPY`), a copy of matrix :math:`A` is made and then this copy is modified explicitly, e.g., :math:`A \leftarrow (A - \sigma B)`. With `ST.MatMode.INPLACE`, the original matrix :math:`A` is modified at `setUp()` and reverted at the end of the computations. With respect to the previous one, this mode avoids a copy of matrix :math:`A`. However, a backdraw is that the recovered matrix might be slightly different from the original one (due to roundoff). With `ST.MatMode.SHELL`, the solver works with an implicit shell matrix that represents the shifted matrix. This mode is the most efficient in creating the transformed matrix but it places serious limitations to the linear solves performed in each iteration of the eigensolver (typically, only iterative solvers with Jacobi preconditioning can be used). In the two first modes the efficiency of this computation can be controlled with `setMatStructure()`. See Also -------- setMatrices, setMatStructure, getMatMode, slepc.STSetMatMode :sources:`Source code at slepc4py/SLEPc/ST.pyx:387 ` """ ... def getMatMode(self) -> MatMode: """Get a flag that indicates how the matrix is being shifted. Not collective. Get a flag that indicates how the matrix is being shifted in the shift-and-invert and Cayley spectral transformations. Returns ------- MatMode The mode flag. See Also -------- setMatMode, slepc.STGetMatMode :sources:`Source code at slepc4py/SLEPc/ST.pyx:430 ` """ ... def setMatrices(self, operators: list[Mat]) -> None: """Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- operators The matrices associated with the eigensystem. Notes ----- It must be called before `setUp()`. If it is called again after `setUp()` then the `ST` object is reset. In standard eigenproblems only one matrix is passed, while in generalized problems two matrices are provided. The number of matrices is larger in polynomial eigenproblems. In normal usage, matrices are provided via the corresponding `EPS` of `PEP` interface function. See Also -------- getMatrices, setUp, reset, slepc.STSetMatrices :sources:`Source code at slepc4py/SLEPc/ST.pyx:452 ` """ ... def getMatrices(self) -> list[Mat]: """Get the matrices associated with the eigenvalue problem. Collective. Returns ------- list of petsc4py.PETSc.Mat The matrices associated with the eigensystem. See Also -------- setMatrices, slepc.STGetNumMatrices, slepc.STGetMatrix :sources:`Source code at slepc4py/SLEPc/ST.pyx:486 ` """ ... def setMatStructure(self, structure: petsc4py.PETSc.Mat.Structure) -> None: """Set the matrix structure attribute. Logically collective. Set an internal `petsc4py.PETSc.Mat.Structure` attribute to indicate which is the relation of the sparsity pattern of all the `ST` matrices. Parameters ---------- structure The matrix structure specification. Notes ----- By default, the sparsity patterns are assumed to be different. If the patterns are equal or a subset then it is recommended to set this attribute for efficiency reasons (in particular, for internal ``Mat.axpy()`` operations). This function has no effect in the case of standard eigenproblems. In case of polynomial eigenproblems, the flag applies to all matrices relative to the first one. See Also -------- getMatStructure, setMatrices, slepc.STSetMatStructure :sources:`Source code at slepc4py/SLEPc/ST.pyx:512 ` """ ... def getMatStructure(self) -> petsc4py.PETSc.Mat.Structure: """Get the internal matrix structure attribute. Not collective. Get the internal `petsc4py.PETSc.Mat.Structure` attribute to indicate which is the relation of the sparsity pattern of the matrices. Returns ------- petsc4py.PETSc.Mat.Structure The structure flag. See Also -------- setMatStructure, slepc.STGetMatStructure :sources:`Source code at slepc4py/SLEPc/ST.pyx:545 ` """ ... def setKSP(self, ksp: KSP) -> None: """Set the ``KSP`` object associated with the spectral transformation. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getKSP, slepc.STSetKSP :sources:`Source code at slepc4py/SLEPc/ST.pyx:568 ` """ ... def getKSP(self) -> KSP: """Get the ``KSP`` object associated with the spectral transformation. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setKSP, slepc.STGetKSP :sources:`Source code at slepc4py/SLEPc/ST.pyx:585 ` """ ... def setPreconditionerMat(self, P: Mat | None = None) -> None: """Set the matrix to be used to build the preconditioner. Collective. Parameters ---------- P The matrix that will be used in constructing the preconditioner. Notes ----- This matrix will be passed to the internal ``KSP`` object (via the last argument of ``KSP.setOperators()``) as the matrix to be used when constructing the preconditioner. If no matrix is set then :math:`A-\sigma B` will be used to build the preconditioner, being :math:`\sigma` the value set by `setShift()`. More precisely, this is relevant for spectral transformations that represent a rational matrix function, and use a ``KSP`` object for the denominator. It includes also the `PRECOND` case. If the user has a good approximation to matrix that can be used to build a cheap preconditioner, it can be passed with this function. Note that it affects only the ``Pmat`` argument of ``KSP.setOperators()``, not the ``Amat`` argument. If a preconditioner matrix is set, the default is to use an iterative ``KSP`` rather than a direct method. An alternative to pass an approximation of :math:`A-\sigma B` with this function is to provide approximations of :math:`A` and :math:`B` via `setSplitPreconditioner()`. The difference is that when :math:`\sigma` changes the preconditioner is recomputed. A call with no matrix argument will remove a previously set matrix. See Also -------- getPreconditionerMat, slepc.STSetPreconditionerMat :sources:`Source code at slepc4py/SLEPc/ST.pyx:605 ` """ ... def getPreconditionerMat(self) -> Mat: """Get the matrix previously set by `setPreconditionerMat()`. Not collective. Returns ------- petsc4py.PETSc.Mat The matrix that will be used in constructing the preconditioner. See Also -------- setPreconditionerMat, slepc.STGetPreconditionerMat :sources:`Source code at slepc4py/SLEPc/ST.pyx:649 ` """ ... def setSplitPreconditioner(self, operators: list[petsc4py.PETSc.Mat], structure: petsc4py.PETSc.Mat.Structure | None = None) -> None: """Set the matrices to be used to build the preconditioner. Collective. Parameters ---------- operators The matrices associated with the preconditioner. structure The matrix structure specification. Notes ----- The number of matrices passed here must be the same as in `setMatrices()`. For linear eigenproblems, the preconditioner matrix is computed as :math:`P(\sigma) = A_0-\sigma B_0`, where :math:`A_0,B_0` are approximations of :math:`A,B` (the eigenproblem matrices) provided via the ``operators`` argument in this function. Compared to `setPreconditionerMat()`, this function allows setting a preconditioner in a way that is independent of the shift :math:`\sigma`. Whenever the value of :math:`\sigma` changes the preconditioner is recomputed. Similarly, for polynomial eigenproblems the matrix for the preconditioner is expressed as :math:`P(\sigma) = \sum_i P_i \phi_i(\sigma)`, for :math:`i=1,\dots,n`, where :math:`P_i` are given in ``operators`` and the :math:`\phi_i`'s are the polynomial basis functions. The ``structure`` flag provides information about the relative nonzero pattern of the ``operators`` matrices, in the same way as in `setMatStructure()`. See Also -------- getSplitPreconditioner, setPreconditionerMat, slepc.STSetSplitPreconditioner :sources:`Source code at slepc4py/SLEPc/ST.pyx:669 ` """ ... def getSplitPreconditioner(self) -> tuple[list[petsc4py.PETSc.Mat], petsc4py.PETSc.Mat.Structure]: """Get the matrices to be used to build the preconditioner. Not collective. Returns ------- list of petsc4py.PETSc.Mat The list of matrices associated with the preconditioner. petsc4py.PETSc.Mat.Structure The structure flag. See Also -------- slepc.STGetSplitPreconditionerInfo, slepc.STGetSplitPreconditionerTerm :sources:`Source code at slepc4py/SLEPc/ST.pyx:716 ` """ ... def setUp(self) -> None: """Prepare for the use of a spectral transformation. Collective. See Also -------- apply, slepc.STSetUp :sources:`Source code at slepc4py/SLEPc/ST.pyx:746 ` """ ... def apply(self, x: Vec, y: Vec) -> None: """Apply the spectral transformation operator to a vector. Collective. Apply the spectral transformation operator to a vector, for instance :math:`y=(A-\sigma B)^{-1}Bx` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- applyTranspose, applyHermitianTranspose, applyMat, slepc.STApply :sources:`Source code at slepc4py/SLEPc/ST.pyx:758 ` """ ... def applyTranspose(self, x: Vec, y: Vec) -> None: """Apply the transpose of the operator to a vector. Collective. Apply the transpose of the operator to a vector, for instance :math:`y=B^T(A-\sigma B)^{-T}x` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- apply, applyHermitianTranspose, slepc.STApplyTranspose :sources:`Source code at slepc4py/SLEPc/ST.pyx:781 ` """ ... def applyHermitianTranspose(self, x: Vec, y: Vec) -> None: """Apply the Hermitian-transpose of the operator to a vector. Collective. Apply the Hermitian-transpose of the operator to a vector, for instance :math:`y=B^*(A - \sigma B)^{-*}x` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- apply, applyTranspose, slepc.STApplyHermitianTranspose :sources:`Source code at slepc4py/SLEPc/ST.pyx:804 ` """ ... def applyMat(self, X: Mat, Y: Mat) -> None: """Apply the spectral transformation operator to a matrix. Collective. Apply the spectral transformation operator to a matrix, for instance :math:`Y=(A-\sigma B)^{-1}BX` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- X The input matrix. Y The result matrix. See Also -------- apply, slepc.STApplyMat :sources:`Source code at slepc4py/SLEPc/ST.pyx:827 ` """ ... def getOperator(self) -> Mat: """Get a shell matrix that represents the operator of the spectral transformation. Collective. Returns ------- petsc4py.PETSc.Mat Operator matrix. Notes ----- The operator is defined in linear eigenproblems only, not in polynomial ones, so the call will fail if more than 2 matrices were passed in `setMatrices()`. The returned shell matrix is essentially a wrapper to the `apply()` and `applyTranspose()` operations. The operator can often be expressed as .. math:: Op = D K^{-1} M D^{-1} where :math:`D` is the balancing matrix, and :math:`M` and :math:`K` are two matrices corresponding to the numerator and denominator for spectral transformations that represent a rational matrix function. The preconditioner matrix :math:`K` typically depends on the value of the shift, and its inverse is handled via an internal ``KSP`` object. Normal usage does not require explicitly calling `getOperator()`, but it can be used to force the creation of :math:`K` and :math:`M`, and then :math:`K` is passed to the ``KSP``. This is useful for setting options associated with the ``PCFactor`` (to set MUMPS options, for instance). The returned matrix must NOT be destroyed by the user. Instead, when no longer needed it must be returned with `restoreOperator()`. In particular, this is required before modifying the `ST` matrices or the shift. See Also -------- apply, setMatrices, setShift, restoreOperator, slepc.STGetOperator :sources:`Source code at slepc4py/SLEPc/ST.pyx:850 ` """ ... def restoreOperator(self, op: Mat) -> None: """Restore the previously seized operator matrix. Logically collective. Parameters ---------- op Operator matrix previously obtained with `getOperator()`. See Also -------- getOperator, slepc.STRestoreOperator :sources:`Source code at slepc4py/SLEPc/ST.pyx:898 ` """ ... def setCayleyAntishift(self, mu: Scalar) -> None: """Set the value of the anti-shift for the Cayley spectral transformation. Logically collective. Parameters ---------- mu The anti-shift. Notes ----- In the generalized Cayley transform, the operator can be expressed as :math:`(A - \sigma B)^{-1}(A + \mu B)`. This function sets the value of :math:`mu`. Use `setShift()` for setting :math:`\sigma`. See Also -------- setShift, getCayleyAntishift, slepc.STCayleySetAntishift :sources:`Source code at slepc4py/SLEPc/ST.pyx:918 ` """ ... def getCayleyAntishift(self) -> Scalar: """Get the value of the anti-shift for the Cayley spectral transformation. Not collective. Returns ------- Scalar The anti-shift. See Also -------- setCayleyAntishift, slepc.STCayleyGetAntishift :sources:`Source code at slepc4py/SLEPc/ST.pyx:942 ` """ ... def setFilterType(self, filter_type: FilterType) -> None: """Set the method to be used to build the polynomial filter. Logically collective. Parameter --------- filter_type The type of filter. See Also -------- getFilterType, slepc.STFilterSetType :sources:`Source code at slepc4py/SLEPc/ST.pyx:961 ` """ ... def getFilterType(self) -> FilterType: """Get the method to be used to build the polynomial filter. Not collective. Returns ------- FilterType The type of filter. See Also -------- setFilterType, slepc.STFilterGetType :sources:`Source code at slepc4py/SLEPc/ST.pyx:979 ` """ ... def setFilterInterval(self, inta: float, intb: float) -> None: """Set the interval containing the desired eigenvalues. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- The filter will be configured to emphasize eigenvalues contained in the given interval, and damp out eigenvalues outside it. If the interval is open, then the filter is low- or high-pass, otherwise it is mid-pass. Common usage is to set the interval in `EPS` with `EPS.setInterval()`. The interval must be contained within the numerical range of the matrix, see `setFilterRange()`. See Also -------- getFilterInterval, setFilterRange, slepc.STFilterSetInterval :sources:`Source code at slepc4py/SLEPc/ST.pyx:998 ` """ ... def getFilterInterval(self) -> tuple[float, float]: """Get the interval containing the desired eigenvalues. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. See Also -------- setFilterInterval, slepc.STFilterGetInterval :sources:`Source code at slepc4py/SLEPc/ST.pyx:1031 ` """ ... def setFilterRange(self, left: float, right: float) -> None: """Set the numerical range (or field of values) of the matrix. Logically collective. Set the numerical range (or field of values) of the matrix, that is, the interval containing all eigenvalues. Parameters ---------- left The left end of the spectral range. right The right end of the spectral range. Notes ----- The filter will be most effective if the numerical range is tight, that is, ``left`` and ``right`` are good approximations to the leftmost and rightmost eigenvalues, respectively. See Also -------- setFilterInterval, getFilterRange, slepc.STFilterSetRange :sources:`Source code at slepc4py/SLEPc/ST.pyx:1053 ` """ ... def getFilterRange(self) -> tuple[float, float]: """Get the interval containing all eigenvalues. Not collective. Returns ------- left: float The left end of the spectral range. right: float The right end of the spectral range. See Also -------- getFilterInterval, slepc.STFilterGetRange :sources:`Source code at slepc4py/SLEPc/ST.pyx:1083 ` """ ... def setFilterDegree(self, deg: int) -> None: """Set the degree of the filter polynomial. Logically collective. Parameters ---------- deg The polynomial degree. See Also -------- getFilterDegree, slepc.STFilterSetDegree :sources:`Source code at slepc4py/SLEPc/ST.pyx:1105 ` """ ... def getFilterDegree(self) -> int: """Get the degree of the filter polynomial. Not collective. Returns ------- int The polynomial degree. See Also -------- setFilterDegree, slepc.STFilterGetDegree :sources:`Source code at slepc4py/SLEPc/ST.pyx:1123 ` """ ... def setFilterDamping(self, damping: FilterDamping) -> None: """Set the type of damping to be used in the polynomial filter. Logically collective. Parameter --------- damping The type of damping. Notes ----- Only used in `FilterType.CHEBYSHEV` filters. See Also -------- getFilterDamping, slepc.STFilterSetDamping :sources:`Source code at slepc4py/SLEPc/ST.pyx:1142 ` """ ... def getFilterDamping(self) -> FilterDamping: """Get the type of damping used in the polynomial filter. Not collective. Returns ------- FilterDamping The type of damping. See Also -------- setFilterDamping, slepc.STFilterGetDamping :sources:`Source code at slepc4py/SLEPc/ST.pyx:1164 ` """ ... @property def shift(self) -> float: """Value of the shift. :sources:`Source code at slepc4py/SLEPc/ST.pyx:1185 ` """ ... @property def transform(self) -> bool: """If the transformed matrices are computed. :sources:`Source code at slepc4py/SLEPc/ST.pyx:1192 ` """ ... @property def mat_mode(self) -> STMatMode: """How the transformed matrices are being stored in the ST. :sources:`Source code at slepc4py/SLEPc/ST.pyx:1199 ` """ ... @property def mat_structure(self) -> MatStructure: """Relation of the sparsity pattern of all ST matrices. :sources:`Source code at slepc4py/SLEPc/ST.pyx:1206 ` """ ... @property def ksp(self) -> KSP: """KSP object associated with the spectral transformation. :sources:`Source code at slepc4py/SLEPc/ST.pyx:1213 ` """ ... class BV(Object): """Basis Vectors. The `BV` package provides the concept of a block of vectors that represent the basis of a subspace. It is a convenient way of handling a collection of vectors that often operate together, rather than working with an array of `petsc4py.PETSc.Vec`. """ class Type: """BV type. - `MAT`: A `BV` stored as a dense `petsc.Mat`. - `SVEC`: A `BV` stored as a single `petsc.Vec`. - `VECS`: A `BV` stored as an array of independent `petsc.Vec`. - `CONTIGUOUS`: A `BV` stored as an array of `petsc.Vec` sharing a contiguous array of scalars. - `TENSOR`: A special `BV` represented in compact form as :math:`V = (I \otimes U) S`. See Also -------- slepc.BVType """ MAT: str = _def(str, 'MAT') #: Object ``MAT`` of type :class:`str` SVEC: str = _def(str, 'SVEC') #: Object ``SVEC`` of type :class:`str` VECS: str = _def(str, 'VECS') #: Object ``VECS`` of type :class:`str` CONTIGUOUS: str = _def(str, 'CONTIGUOUS') #: Object ``CONTIGUOUS`` of type :class:`str` TENSOR: str = _def(str, 'TENSOR') #: Object ``TENSOR`` of type :class:`str` class OrthogType: """BV orthogonalization types. - `CGS`: Classical Gram-Schmidt. - `MGS`: Modified Gram-Schmidt. See Also -------- slepc.BVOrthogType """ CGS: int = _def(int, 'CGS') #: Constant ``CGS`` of type :class:`int` MGS: int = _def(int, 'MGS') #: Constant ``MGS`` of type :class:`int` class OrthogRefineType: """BV orthogonalization refinement types. - `IFNEEDED`: Reorthogonalize if a criterion is satisfied. - `NEVER`: Never reorthogonalize. - `ALWAYS`: Always reorthogonalize. See Also -------- slepc.BVOrthogRefineType """ IFNEEDED: int = _def(int, 'IFNEEDED') #: Constant ``IFNEEDED`` of type :class:`int` NEVER: int = _def(int, 'NEVER') #: Constant ``NEVER`` of type :class:`int` ALWAYS: int = _def(int, 'ALWAYS') #: Constant ``ALWAYS`` of type :class:`int` class OrthogRefineType: """BV orthogonalization refinement types. - `IFNEEDED`: Reorthogonalize if a criterion is satisfied. - `NEVER`: Never reorthogonalize. - `ALWAYS`: Always reorthogonalize. See Also -------- slepc.BVOrthogRefineType """ IFNEEDED: int = _def(int, 'IFNEEDED') #: Constant ``IFNEEDED`` of type :class:`int` NEVER: int = _def(int, 'NEVER') #: Constant ``NEVER`` of type :class:`int` ALWAYS: int = _def(int, 'ALWAYS') #: Constant ``ALWAYS`` of type :class:`int` class OrthogBlockType: """BV block-orthogonalization types. - `GS`: Gram-Schmidt, column by column. - `CHOL`: Cholesky QR method. - `TSQR`: Tall-skinny QR method. - `TSQRCHOL`: Tall-skinny QR, but computing the triangular factor only. - `SVQB`: SVQB method. See Also -------- slepc.BVOrthogBlockType """ GS: int = _def(int, 'GS') #: Constant ``GS`` of type :class:`int` CHOL: int = _def(int, 'CHOL') #: Constant ``CHOL`` of type :class:`int` TSQR: int = _def(int, 'TSQR') #: Constant ``TSQR`` of type :class:`int` TSQRCHOL: int = _def(int, 'TSQRCHOL') #: Constant ``TSQRCHOL`` of type :class:`int` SVQB: int = _def(int, 'SVQB') #: Constant ``SVQB`` of type :class:`int` class OrthogBlockType: """BV block-orthogonalization types. - `GS`: Gram-Schmidt, column by column. - `CHOL`: Cholesky QR method. - `TSQR`: Tall-skinny QR method. - `TSQRCHOL`: Tall-skinny QR, but computing the triangular factor only. - `SVQB`: SVQB method. See Also -------- slepc.BVOrthogBlockType """ GS: int = _def(int, 'GS') #: Constant ``GS`` of type :class:`int` CHOL: int = _def(int, 'CHOL') #: Constant ``CHOL`` of type :class:`int` TSQR: int = _def(int, 'TSQR') #: Constant ``TSQR`` of type :class:`int` TSQRCHOL: int = _def(int, 'TSQRCHOL') #: Constant ``TSQRCHOL`` of type :class:`int` SVQB: int = _def(int, 'SVQB') #: Constant ``SVQB`` of type :class:`int` class MatMultType: """BV mat-mult types. - `VECS`: Perform a matrix-vector multiply per each column. - `MAT`: Carry out a Mat-Mat product with a dense matrix. See Also -------- slepc.BVMatMultType """ VECS: int = _def(int, 'VECS') #: Constant ``VECS`` of type :class:`int` MAT: int = _def(int, 'MAT') #: Constant ``MAT`` of type :class:`int` class SVDMethod: """BV methods for computing the SVD. - `REFINE`: Based on the SVD of the cross product matrix :math:`S^* S`, with refinement. - `QR`: Based on the SVD of the triangular factor of qr(S). - `QR_CAA`: Variant of QR intended for use in communication-avoiding. Arnoldi. See Also -------- slepc.BVSVDMethod """ REFINE: int = _def(int, 'REFINE') #: Constant ``REFINE`` of type :class:`int` QR: int = _def(int, 'QR') #: Constant ``QR`` of type :class:`int` QR_CAA: int = _def(int, 'QR_CAA') #: Constant ``QR_CAA`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the BV data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.BVView :sources:`Source code at slepc4py/SLEPc/BV.pyx:192 ` """ ... def destroy(self) -> Self: """Destroy the BV object. Collective. See Also -------- slepc.BVDestroy :sources:`Source code at slepc4py/SLEPc/BV.pyx:211 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the BV object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- createFromMat, slepc.BVCreate :sources:`Source code at slepc4py/SLEPc/BV.pyx:225 ` """ ... def createFromMat(self, A: Mat) -> Self: """Create a basis vectors object from a dense matrix. Collective. Parameters ---------- A A dense tall-skinny matrix. Notes ----- The matrix values are copied to the `BV` data storage, memory is not shared. The communicator of the `BV` object will be the same as `A`, and so will be the dimensions. See Also -------- create, createMat, slepc.BVCreateFromMat :sources:`Source code at slepc4py/SLEPc/BV.pyx:247 ` """ ... def createMat(self) -> Mat: """Create a new dense matrix and copy the contents of the BV. Collective. Returns ------- petsc4py.PETSc.Mat The new matrix. Notes ----- The matrix contains all columns of the `BV`, not just the active columns. See Also -------- createFromMat, createVec, getMat, slepc.BVCreateMat :sources:`Source code at slepc4py/SLEPc/BV.pyx:275 ` """ ... def duplicate(self) -> BV: """Duplicate the BV object with the same type and dimensions. Collective. Returns ------- BV The new object. Notes ----- This function does not copy the entries, it just allocates the storage for the new `BV`. Use `copy()` to copy the content. See Also -------- duplicateResize, slepc.BVDuplicate :sources:`Source code at slepc4py/SLEPc/BV.pyx:299 ` """ ... def duplicateResize(self, m: int) -> BV: """Create a BV object of the same type and dimensions as an existing one. Collective. Parameters ---------- m The number of columns. Returns ------- BV The new object. Notes ----- This is equivalent to a call to `duplicate()` followed by `resize()` with possibly different number of columns. The contents of this `BV` are not copied to the new one. See Also -------- duplicate, resize, slepc.BVDuplicateResize :sources:`Source code at slepc4py/SLEPc/BV.pyx:323 ` """ ... def copy(self, result: BV | None = None) -> BV: """Copy a basis vector object into another one. Logically collective. Returns ------- BV The copy. Parameters ---------- result The copy. Notes ----- Both objects must be distributed in the same manner; local copies are done. Only active columns (excluding the leading ones) are copied. In the destination BV, columns are overwritten starting from the leading ones. Constraints are not copied. See Also -------- slepc.BVCopy :sources:`Source code at slepc4py/SLEPc/BV.pyx:354 ` """ ... def setType(self, bv_type: Type | str) -> None: """Set the type for the BV object. Logically collective. Parameters ---------- bv_type The basis vectors type to be used. See Also -------- getType, slepc.BVSetType :sources:`Source code at slepc4py/SLEPc/BV.pyx:388 ` """ ... def getType(self) -> str: """Get the BV type of this object. Not collective. Returns ------- str The basis vectors type currently being used. See Also -------- setType, slepc.BVGetType :sources:`Source code at slepc4py/SLEPc/BV.pyx:407 ` """ ... def setSizes(self, sizes: LayoutSizeSpec, m: int) -> None: """Set the local and global sizes, and the number of columns. Collective. Parameters ---------- sizes The global size ``N`` or a two-tuple ``(n, N)`` with the local and global sizes. m The number of columns. Notes ----- Either ``n`` or ``N`` (but not both) can be `DETERMINE` or ``None`` to have it automatically set. See Also -------- setSizesFromVec, getSizes, slepc.BVSetSizes :sources:`Source code at slepc4py/SLEPc/BV.pyx:426 ` """ ... def setSizesFromVec(self, w: Vec, m: int) -> None: """Set the local and global sizes, and the number of columns. Collective. Local and global sizes are specified indirectly by passing a template vector. Parameters ---------- w The template vector. m The number of columns. See Also -------- setSizes, getSizes, slepc.BVSetSizesFromVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:454 ` """ ... def getSizes(self) -> tuple[LayoutSizeSpec, int]: """Get the local and global sizes, and the number of columns. Not collective. Returns ------- (n, N): tuple of int The local and global sizes. m: int The number of columns. See Also -------- setSizes, setSizesFromVec, slepc.BVGetSizes :sources:`Source code at slepc4py/SLEPc/BV.pyx:477 ` """ ... def setLeadingDimension(self, ld: int) -> None: """Set the leading dimension. Not collective. Parameters ---------- ld The leading dimension. Notes ----- This parameter is relevant for a BV of `BV.Type.MAT`. See Also -------- getLeadingDimension, slepc.BVSetLeadingDimension :sources:`Source code at slepc4py/SLEPc/BV.pyx:498 ` """ ... def getLeadingDimension(self) -> int: """Get the leading dimension. Not collective. Returns ------- int The leading dimension. Notes ----- The returned value may be different in different processes. The leading dimension must be used when accessing the internal array via `getArray()`. See Also -------- setLeadingDimension, slepc.BVGetLeadingDimension :sources:`Source code at slepc4py/SLEPc/BV.pyx:520 ` """ ... def getArray(self, readonly: bool = False) -> ArrayScalar: """Return the array where the data is stored. Not collective. Parameters ---------- readonly Enable to obtain a read only array. Returns ------- ArrayScalar The array. See Also -------- slepc.BVGetArray, slepc.BVGetArrayRead :sources:`Source code at slepc4py/SLEPc/BV.pyx:546 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all BV options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all BV option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.BVGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/BV.pyx:593 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all BV options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all BV option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.BVAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/BV.pyx:618 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all BV options in the database. Not collective. Returns ------- str The prefix string set for this BV object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.BVGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/BV.pyx:637 ` """ ... def setFromOptions(self) -> None: """Set BV options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.BVSetFromOptions :sources:`Source code at slepc4py/SLEPc/BV.pyx:656 ` """ ... def getOrthogonalization(self) -> tuple[OrthogType, OrthogRefineType, float, OrthogBlockType]: """Get the orthogonalization settings from the BV object. Not collective. Returns ------- type: OrthogType The type of orthogonalization technique. refine: OrthogRefineType The type of refinement. eta: float Parameter for selective refinement (used when the refinement type is `IFNEEDED`). block: OrthogBlockType The type of block orthogonalization. See Also -------- setOrthogonalization, slepc.BVGetOrthogonalization :sources:`Source code at slepc4py/SLEPc/BV.pyx:675 ` """ ... def setOrthogonalization(self, otype: OrthogType | None = None, refine: OrthogRefineType | None = None, eta: float | None = None, block: OrthogBlockType | None = None) -> None: """Set the method used for the (block-)orthogonalization of vectors. Logically collective. Ortogonalization of vectors (classical or modified Gram-Schmidt with or without refinement), and for the block-orthogonalization (simultaneous orthogonalization of a set of vectors). Parameters ---------- otype The type of orthogonalization technique. refine The type of refinement. eta Parameter for selective refinement. block The type of block orthogonalization. Notes ----- The default settings work well for most problems. The parameter ``eta`` should be a real value between ``0`` and ``1`` (or `DETERMINE`). The value of ``eta`` is used only when the refinement type is `IFNEEDED`. When using several processes, `MGS` is likely to result in bad scalability. If the method set for block orthogonalization is `GS`, then the computation is done column by column with the vector orthogonalization. See Also -------- getOrthogonalization, slepc.BVSetOrthogonalization :sources:`Source code at slepc4py/SLEPc/BV.pyx:704 ` """ ... def getMatMultMethod(self) -> MatMultType: """Get the method used for the `matMult()` operation. Not collective. Returns ------- MatMultType The method for the `matMult()` operation. See Also -------- matMult, setMatMultMethod, slepc.BVGetMatMultMethod :sources:`Source code at slepc4py/SLEPc/BV.pyx:760 ` """ ... def setMatMultMethod(self, method: MatMultType) -> None: """Set the method used for the `matMult()` operation. Logically collective. Parameters ---------- method The method for the `matMult()` operation. See Also -------- matMult, getMatMultMethod, slepc.BVSetMatMultMethod :sources:`Source code at slepc4py/SLEPc/BV.pyx:779 ` """ ... def getMatrix(self) -> tuple[Mat, bool] | tuple[None, bool]: """Get the matrix representation of the inner product. Not collective. Returns ------- B: petsc4py.PETSc.Mat The matrix of the inner product. indef: bool Whether the matrix is indefinite. See Also -------- setMatrix, slepc.BVGetMatrix :sources:`Source code at slepc4py/SLEPc/BV.pyx:799 ` """ ... def setMatrix(self, B: Mat | None, indef: bool = False) -> None: """Set the bilinear form to be used for inner products. Collective. Parameters ---------- B The matrix of the inner product. indef Whether the matrix is indefinite. Notes ----- This is used to specify a non-standard inner product, whose matrix representation is given by ``B``. Then, all inner products required during orthogonalization are computed as :math:`(x,y)_B=y^*Bx` rather than the standard form :math:`(x,y)=y^*x`. Matrix ``B`` must be real symmetric (or complex Hermitian). A genuine inner product requires that ``B`` is also positive (semi-)definite. However, we also allow for an indefinite ``B`` (setting ``indef=True``), in which case the orthogonalization uses an indefinite inner product. This affects operations `dot()`, `norm()`, `orthogonalize()`, and variants. Omitting ``B`` has the same effect as if the identity matrix was passed. See Also -------- getMatrix, slepc.BVSetMatrix :sources:`Source code at slepc4py/SLEPc/BV.pyx:825 ` """ ... def applyMatrix(self, x: Vec, y: Vec) -> None: """Multiply a vector with the matrix associated to the bilinear form. Neighbor-wise collective. Parameters ---------- x The input vector. y The result vector. Notes ----- If the bilinear form has no associated matrix this function copies the vector. See Also -------- setMatrix, slepc.BVApplyMatrix :sources:`Source code at slepc4py/SLEPc/BV.pyx:863 ` """ ... def setActiveColumns(self, l: int, k: int) -> None: """Set the columns that will be involved in operations. Logically collective. Parameters ---------- l The leading number of columns. k The active number of columns. Notes ----- In operations such as `mult()` or `dot()`, only the first ``k`` columns are considered. This is useful when the BV is filled from left to right, so the last ``m-k`` columns do not have relevant information. Also in operations such as `mult()` or `dot()`, the first ``l`` columns are normally not included in the computation. In orthogonalization operations, the first ``l`` columns are treated differently, they participate in the orthogonalization but the computed coefficients are not stored. Use `CURRENT` to leave any of the values unchanged. Use `DETERMINE` to set ``l`` to the minimum value (``0``) and ``k`` to the maximum (``m``). See Also -------- getActiveColumns, setSizes, slepc.BVSetActiveColumns :sources:`Source code at slepc4py/SLEPc/BV.pyx:887 ` """ ... def getActiveColumns(self) -> tuple[int, int]: """Get the current active dimensions. Not collective. Returns ------- l: int The leading number of columns. k: int The active number of columns. See Also -------- setActiveColumns, slepc.BVGetActiveColumns :sources:`Source code at slepc4py/SLEPc/BV.pyx:924 ` """ ... def scaleColumn(self, j: int, alpha: Scalar) -> None: """Scale a column of a BV. Logically collective. Parameters ---------- j column index to be scaled. alpha scaling factor. See Also -------- scale, slepc.BVScaleColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:945 ` """ ... def scale(self, alpha: Scalar) -> None: """Multiply the entries by a scalar value. Logically collective. Parameters ---------- alpha scaling factor. Notes ----- All active columns (except the leading ones) are scaled. See Also -------- scaleColumn, setActiveColumns, slepc.BVScale :sources:`Source code at slepc4py/SLEPc/BV.pyx:966 ` """ ... def insertVec(self, j: int, w: Vec) -> None: """Insert a vector into the specified column. Logically collective. Parameters ---------- j The column to be overwritten. w The vector to be copied. See Also -------- insertVecs, slepc.BVInsertVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:988 ` """ ... def insertVecs(self, s: int, W: Vec | list[Vec], orth: bool = False) -> int: """Insert a set of vectors into the specified columns. Collective. Parameters ---------- s The first column to be overwritten. W Set of vectors to be copied. orth Flag indicating if the vectors must be orthogonalized. Returns ------- int Number of linearly independent vectors. Notes ----- Copies the contents of vectors ``W`` into the BV columns ``s:s+n``, where ``n`` is the length of ``W``. If ``orth`` is set, then the vectors are copied one by one and then orthogonalized against the previous one. If any of them is linearly dependent then it is discarded and the not counted in the return value. See Also -------- insertVec, orthogonalizeColumn, slepc.BVInsertVecs :sources:`Source code at slepc4py/SLEPc/BV.pyx:1008 ` """ ... def insertConstraints(self, C: Vec | list[Vec]) -> int: """Insert a set of vectors as constraints. Collective. Parameters ---------- C Set of vectors to be inserted as constraints. Returns ------- int Number of linearly independent constraints. Notes ----- The constraints are relevant only during orthogonalization. Constraint vectors span a subspace that is deflated in every orthogonalization operation, so they are intended for removing those directions from the orthogonal basis computed in regular BV columns. Constraints are not stored in regular columns, but in a special part of the storage. They can be accessed with negative indices in `getColumn()`. This operation is DESTRUCTIVE, meaning that all data contained in the columns of the BV is lost. This is typically invoked just after creating the BV. Once a set of constraints has been set, it is not allowed to call this function again. The vectors are copied one by one and then orthogonalized against the previous ones. If any of them is linearly dependent then it is discarded and not counted in the return value. The behavior is similar to `insertVecs()`. See Also -------- insertVecs, setNumConstraints, slepc.BVInsertConstraints :sources:`Source code at slepc4py/SLEPc/BV.pyx:1051 ` """ ... def setNumConstraints(self, nc: int) -> None: """Set the number of constraints. Logically collective. Parameters ---------- nc The number of constraints. Notes ----- This function sets the number of constraints to ``nc`` and marks all remaining columns as regular. Normal usage would be to call `insertConstraints()` instead. If ``nc`` is smaller than the previously set value, then some of the constraints are discarded. In particular, using ``nc=0`` removes all constraints preserving the content of regular columns. See Also -------- insertConstraints, getNumConstraints, slepc.BVSetNumConstraints :sources:`Source code at slepc4py/SLEPc/BV.pyx:1101 ` """ ... def getNumConstraints(self) -> int: """Get the number of constraints. Not collective. Returns ------- int The number of constraints. See Also -------- insertConstraints, setNumConstraints, slepc.BVGetNumConstraints :sources:`Source code at slepc4py/SLEPc/BV.pyx:1128 ` """ ... def createVec(self) -> Vec: """Create a vector with the type and dimensions of the columns of the BV. Collective. Returns ------- petsc4py.PETSc.Vec New vector. See Also -------- createMat, setVecType, slepc.BVCreateVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:1147 ` """ ... def setVecType(self, vec_type: petsc4py.PETSc.Vec.Type | str) -> None: """Set the vector type to be used when creating vectors via `createVec()`. Collective. Parameters ---------- vec_type Vector type used when creating vectors with `createVec`. Notes ----- This is not needed if the BV object is set up with `setSizesFromVec()`, but may be required in the case of `setSizes()` if one wants to work with non-standard vectors. See Also -------- createVec, getVecType, setSizes, setSizesFromVec, slepc.BVSetVecType :sources:`Source code at slepc4py/SLEPc/BV.pyx:1166 ` """ ... def getVecType(self) -> str: """Get the vector type used when creating vectors via `createVec()`. Not collective. Returns ------- str The vector type. See Also -------- createVec, setVecType, slepc.BVGetVecType :sources:`Source code at slepc4py/SLEPc/BV.pyx:1191 ` """ ... def copyVec(self, j: int, v: Vec) -> None: """Copy one of the columns of a basis vectors object into a vector. Logically collective. Parameters ---------- j The column index to be copied. v A vector. Notes ----- The BV and ``v`` must be distributed in the same manner; local copies are done. See Also -------- copy, copyColumn, slepc.BVCopyVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:1210 ` """ ... def copyColumn(self, j: int, i: int) -> None: """Copy the values from one of the columns to another one. Logically collective. Parameters ---------- j The index of the source column. i The index of the destination column. See Also -------- copy, copyVec, slepc.BVCopyColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1235 ` """ ... def setDefiniteTolerance(self, deftol: float) -> None: """Set the tolerance to be used when checking a definite inner product. Logically collective. Parameters ---------- deftol The tolerance. Notes ----- When using a non-standard inner product, see `setMatrix()`, the solver needs to compute :math:`\sqrt{z^*B z}` for various vectors :math:`z`. If the inner product has not been declared indefinite, the value :math:`z^*B z` must be positive, but due to rounding error a tiny value may become negative. A tolerance is used to detect this situation. Likewise, in complex arithmetic :math:`z^*B z` should be real, and we use the same tolerance to check whether a nonzero imaginary part can be considered negligible. See Also -------- setMatrix, getDefiniteTolerance, slepc.BVSetDefiniteTolerance :sources:`Source code at slepc4py/SLEPc/BV.pyx:1256 ` """ ... def getDefiniteTolerance(self) -> float: """Get the tolerance to be used when checking a definite inner product. Not collective. Returns ------- float The tolerance. See Also -------- setDefiniteTolerance, slepc.BVGetDefiniteTolerance :sources:`Source code at slepc4py/SLEPc/BV.pyx:1285 ` """ ... def dotVec(self, v: Vec) -> ArrayScalar: """Dot products of a vector against all the column vectors of the BV. Collective. Parameters ---------- v A vector. Returns ------- ArrayScalar The computed values. Notes ----- This is analogue to ``Vec.mDot()``, but using `BV` to represent a collection of vectors ``X``. The result is :math:`m = X^* v`, so :math:`m_i` is equal to :math:`x_j^* v`. Note that here :math:`X` is transposed as opposed to `dot()`. If a non-standard inner product has been specified with `setMatrix()`, then the result is :math:`m = X^* B v`. See Also -------- dot, dotColumn, setMatrix, slepc.BVDotVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:1304 ` """ ... def dotColumn(self, j: int) -> ArrayScalar: """Dot products of a column against all the column vectors of a BV. Collective. Parameters ---------- j The index of the column. Returns ------- ArrayScalar The computed values. Notes ----- This operation is equivalent to `dotVec()` but it uses column ``j`` of the BV rather than taking a vector as an argument. The number of active columns of the BV is set to ``j`` before the computation, and restored afterwards. If the BV has leading columns specified, then these columns do not participate in the computation. Therefore, the length of the returned array will be ``j`` minus the number of leading columns. See Also -------- dot, dotVec, slepc.BVDotColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1344 ` """ ... def getColumn(self, j: int) -> Vec: """Get a vector with the entries of the column of the BV object. Logically collective. Parameters ---------- j The index of the requested column. Returns ------- petsc4py.PETSc.Vec The vector containing the ``j``-th column. Notes ----- Modifying the returned vector will change the BV entries as well. The returned vector must not be destroyed, `restoreColumn()` must be called when it is no longer needed. At most, two columns can be fetched, that is, this function can only be called twice before the corresponding `restoreColumn()` is invoked. A negative index ``j`` selects the ``i``-th constraint, where ``i=-j``. Constraints should not be modified. See Also -------- restoreColumn, insertConstraints, slepc.BVGetColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1384 ` """ ... def restoreColumn(self, j: int, v: Vec) -> None: """Restore a column obtained with `getColumn()`. Logically collective. Parameters ---------- j The index of the requested column. v The vector obtained with `getColumn()`. Notes ----- The arguments must match the corresponding call to `getColumn()`. See Also -------- getColumn, slepc.BVRestoreColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1422 ` """ ... def getMat(self) -> Mat: """Get a matrix of dense type that shares the memory of the BV object. Collective. Returns ------- petsc4py.PETSc.Mat The matrix. Notes ----- The returned matrix contains only the active columns. If the content of the matrix is modified, these changes are also done in the BV object. The user must call `restoreMat()` when no longer needed. This operation implies a call to `getArray()`, which may result in data copies. See Also -------- restoreMat, createMat, getArray, slepc.BVGetMat :sources:`Source code at slepc4py/SLEPc/BV.pyx:1447 ` """ ... def restoreMat(self, A: Mat) -> None: """Restore the matrix obtained with `getMat()`. Logically collective. Parameters ---------- A The matrix obtained with `getMat()`. Notes ----- A call to this function must match a previous call of `getMat()`. The effect is that the contents of the matrix are copied back to the BV internal data structures. See Also -------- getMat, slepc.BVRestoreMat :sources:`Source code at slepc4py/SLEPc/BV.pyx:1476 ` """ ... def dot(self, Y: BV) -> Mat: """Compute the 'block-dot' product of two basis vectors objects. Collective. :math:`M = Y^* X` :math:`(m_{ij} = y_i^* x_j)` or :math:`M = Y^* B X` Parameters ---------- Y Left basis vectors, can be the same as self, giving :math:`M = X^* X`. Returns ------- petsc4py.PETSc.Mat The resulting matrix. Notes ----- This is the generalization of ``Vec.dot()`` for a collection of vectors, :math:`M = Y^* X`. The result is a matrix :math:`M` whose entry :math:`m_{ij}` is equal to :math:`y_i^* x_j` (where :math:`y_i^*` denotes the conjugate transpose of :math:`y_i`). :math:`X` and :math:`Y` can be the same object. If a non-standard inner product has been specified with `setMatrix()`, then the result is :math:`M = Y^* B X`. In this case, both :math:`X` and :math:`Y` must have the same associated matrix. Only rows (resp. columns) of :math:`M` starting from :math:`l_y` (resp. :math:`l_x`) are computed, where :math:`l_y` (resp. :math:`l_x`) is the number of leading columns of :math:`Y` (resp. :math:`X`). See Also -------- dotVec, dotColumn, setActiveColumns, setMatrix, slepc.BVDot :sources:`Source code at slepc4py/SLEPc/BV.pyx:1500 ` """ ... def matProject(self, A: Mat | None, Y: BV) -> Mat: """Compute the projection of a matrix onto a subspace. Collective. :math:`M = Y^* A X` Parameters ---------- A Matrix to be projected. Y Left basis vectors, can be the same as self, giving :math:`M = X^* A X`. Returns ------- petsc4py.PETSc.Mat Projection of the matrix ``A`` onto the subspace. Notes ----- If ``A`` is ``None``, then it is assumed that the BV already contains :math:`AX`. This operation is similar to `dot()`, with important differences. The goal is to compute the matrix resulting from the orthogonal projection of ``A`` onto the subspace spanned by the columns of the BV, :math:`M = X^*AX`, or the oblique projection onto the BV along the second one ``Y``, :math:`M = Y^*AX`. A difference with respect to `dot()` is that the standard inner product is always used, regardless of a non-standard inner product being specified with `setMatrix()`. See Also -------- dot, setActiveColumns, setMatrix, slepc.BVMatProject :sources:`Source code at slepc4py/SLEPc/BV.pyx:1549 ` """ ... def matMult(self, A: Mat, Y: BV | None = None) -> BV: """Compute the matrix-vector product for each column, :math:`Y = A V`. Neighbor-wise collective. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. It is possible to choose whether the computation is done column by column or as a dense matrix-matrix product with `setMatMultMethod()`. See Also -------- copy, matMultColumn, matMultTranspose, setMatMultMethod, slepc.BVMatMult :sources:`Source code at slepc4py/SLEPc/BV.pyx:1598 ` """ ... def matMultTranspose(self, A: Mat, Y: BV | None = None) -> BV: """Pre-multiplication with the transpose of a matrix. Neighbor-wise collective. :math:`Y = A^T V`. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. See Also -------- matMult, matMultTransposeColumn, slepc.BVMatMultTranspose :sources:`Source code at slepc4py/SLEPc/BV.pyx:1647 ` """ ... def matMultHermitianTranspose(self, A: Mat, Y: BV | None = None) -> BV: """Pre-multiplication with the conjugate transpose of a matrix. Neighbor-wise collective. :math:`Y = A^* V`. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. See Also -------- matMult, matMultHermitianTransposeColumn, slepc.BVMatMultHermitianTranspose :sources:`Source code at slepc4py/SLEPc/BV.pyx:1695 ` """ ... def matMultColumn(self, A: Mat, j: int) -> None: """Mat-vec product for a column, storing the result in the next column. Neighbor-wise collective. :math:`v_{j+1} = A v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMult, slepc.BVMatMultColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1743 ` """ ... def matMultTransposeColumn(self, A: Mat, j: int) -> None: """Transpose matrix-vector product for a specified column. Neighbor-wise collective. Store the result in the next column: :math:`v_{j+1} = A^T v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMultColumn, slepc.BVMatMultTransposeColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1765 ` """ ... def matMultHermitianTransposeColumn(self, A: Mat, j: int) -> None: """Conjugate-transpose matrix-vector product for a specified column. Neighbor-wise collective. Store the result in the next column: :math:`v_{j+1} = A^* v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMultColumn, slepc.BVMatMultHermitianTransposeColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1787 ` """ ... def mult(self, delta: Scalar, gamma: Scalar, X: BV, Q: Mat | None) -> None: """Compute :math:`Y = \gamma Y + \delta X Q`. Logically collective. Parameters ---------- delta Coefficient that multiplies ``X``. gamma Coefficient that multiplies self (``Y``). X Input basis vectors. Q Input matrix, if not given the identity matrix is assumed. Notes ----- ``X`` must be different from self (``Y``). The case ``X=Y`` can be addressed with `multInPlace()`. See Also -------- multVec, multColumn, multInPlace, slepc.BVMult :sources:`Source code at slepc4py/SLEPc/BV.pyx:1809 ` """ ... def multInPlace(self, Q: Mat, s: int, e: int) -> None: """Update a set of vectors as :math:`V(:,s:e-1) = V Q(:,s:e-1)`. Logically collective. Parameters ---------- Q A sequential dense matrix. s First column to be overwritten. e Last column to be overwritten. See Also -------- mult, multVec, slepc.BVMultInPlace :sources:`Source code at slepc4py/SLEPc/BV.pyx:1840 ` """ ... def multColumn(self, delta: Scalar, gamma: Scalar, j: int, q: Sequence[Scalar]) -> None: """Compute :math:`y = \gamma y + \delta X q`. Logically collective. Compute :math:`y = \gamma y + \delta X q`, where :math:`y` is the ``j``-th column. Parameters ---------- delta Coefficient that multiplies self (``X``). gamma Coefficient that multiplies :math:`y`. j The column index. q Input coefficients. See Also -------- mult, multVec, multInPlace, slepc.BVMultColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1863 ` """ ... def multVec(self, delta: Scalar, gamma: Scalar, y: Vec, q: Sequence[Scalar]) -> None: """Compute :math:`y = \gamma y + \delta X q`. Logically collective. Parameters ---------- delta Coefficient that multiplies self (``X``). gamma Coefficient that multiplies ``y``. y Input/output vector. q Input coefficients. See Also -------- mult, multColumn, multInPlace, slepc.BVMultVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:1898 ` """ ... def normColumn(self, j: int, norm_type: NormType | None = None) -> float: """Compute the vector norm of a selected column. Collective. Parameters ---------- j Index of column. norm_type The norm type. Returns ------- float The norm. Notes ----- The norm of :math:`v_j` is computed (``NORM_1``, ``NORM_2``, or ``NORM_INFINITY``). If a non-standard inner product has been specified with `setMatrix()`, then the returned value is :math:`\sqrt{v_j^* B v_j}`, where :math:`B` is the inner product matrix (argument 'norm_type' is ignored). See Also -------- norm, setMatrix, slepc.BVNormColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:1929 ` """ ... def norm(self, norm_type: NormType | None = None) -> float: """Compute the matrix norm of the BV. Collective. Parameters ---------- norm_type The norm type. Returns ------- float The norm. Notes ----- All active columns (except the leading ones) are considered as a matrix. The allowed norms are ``NORM_1``, ``NORM_FROBENIUS``, and ``NORM_INFINITY``. This operation fails if a non-standard inner product has been specified with `setMatrix()`. See Also -------- normColumn, setMatrix, slepc.BVNorm :sources:`Source code at slepc4py/SLEPc/BV.pyx:1967 ` """ ... def resize(self, m: int, copy: bool = True) -> None: """Change the number of columns. Collective. Parameters ---------- m The new number of columns. copy A flag indicating whether current values should be kept. Notes ----- Internal storage is reallocated. If ``copy`` is ``True``, then the contents are copied to the leading part of the new space. See Also -------- setSizes, setSizesFromVec, slepc.BVResize :sources:`Source code at slepc4py/SLEPc/BV.pyx:2002 ` """ ... def setRandom(self) -> None: """Set the active columns of the BV to random numbers. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandomColumn, setRandomNormal, slepc.BVSetRandom :sources:`Source code at slepc4py/SLEPc/BV.pyx:2028 ` """ ... def setRandomNormal(self) -> None: """Set the active columns of the BV to normal random numbers. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandom, setRandomSign, slepc.BVSetRandomNormal :sources:`Source code at slepc4py/SLEPc/BV.pyx:2044 ` """ ... def setRandomSign(self) -> None: """Set the entries of a BV to values 1 or -1 with equal probability. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandom, setRandomNormal, slepc.BVSetRandomSign :sources:`Source code at slepc4py/SLEPc/BV.pyx:2060 ` """ ... def setRandomColumn(self, j: int) -> None: """Set one column of the BV to random numbers. Logically collective. Parameters ---------- j Column index to be set. See Also -------- setRandomContext, setRandom, setRandomNormal, slepc.BVSetRandomColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:2076 ` """ ... def setRandomCond(self, condn: float) -> None: """Set the columns of a BV to random numbers. Logically collective. The generated matrix has a prescribed condition number. Parameters ---------- condn Condition number. See Also -------- setRandomContext, setRandomSign, setRandomNormal, slepc.BVSetRandomCond :sources:`Source code at slepc4py/SLEPc/BV.pyx:2094 ` """ ... def setRandomContext(self, rnd: Random) -> None: """Set the `petsc4py.PETSc.Random` object associated with the BV. Collective. To be used in operations that need random numbers. Parameters ---------- rnd The random number generator context. See Also -------- getRandomContext, setRandom, setRandomColumn, slepc.BVSetRandomContext :sources:`Source code at slepc4py/SLEPc/BV.pyx:2114 ` """ ... def getRandomContext(self) -> Random: """Get the `petsc4py.PETSc.Random` object associated with the BV. Collective. Returns ------- petsc4py.PETSc.Random The random number generator context. See Also -------- setRandomContext, slepc.BVGetRandomContext :sources:`Source code at slepc4py/SLEPc/BV.pyx:2133 ` """ ... def orthogonalizeVec(self, v: Vec) -> tuple[float, bool]: """Orthogonalize a vector with respect to all active columns. Collective. Parameters ---------- v Vector to be orthogonalized, modified on return. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. Notes ----- This function applies an orthogonal projector to project vector :math:`v` onto the orthogonal complement of the span of the columns of the BV. This routine does not normalize the resulting vector. See Also -------- orthogonalizeColumn, setOrthogonalization slepc.BVOrthogonalizeVec :sources:`Source code at slepc4py/SLEPc/BV.pyx:2153 ` """ ... def orthogonalizeColumn(self, j: int) -> tuple[float, bool]: """Orthogonalize a column vector with respect to the previous ones. Collective. Parameters ---------- j Index of the column to be orthogonalized. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. Notes ----- This function applies an orthogonal projector to project vector :math:`v_j` onto the orthogonal complement of the span of the columns :math:`V[0..j-1]`, where :math:`V[.]` are the vectors of the BV. The columns :math:`V[0..j-1]` are assumed to be mutually orthonormal. This routine does not normalize the resulting vector. See Also -------- orthogonalizeVec, setOrthogonalization slepc.BVOrthogonalizeColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:2189 ` """ ... def orthonormalizeColumn(self, j: int, replace: bool = False) -> tuple[float, bool]: """Orthonormalize a column vector with respect to the previous ones. Collective. This is equivalent to a call to `orthogonalizeColumn()` followed by a call to `scaleColumn()` with the reciprocal of the norm. Parameters ---------- j Index of the column to be orthonormalized. replace Whether it is allowed to set the vector randomly. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. See Also -------- orthogonalizeColumn, setOrthogonalization slepc.BVOrthonormalizeColumn :sources:`Source code at slepc4py/SLEPc/BV.pyx:2227 ` """ ... def orthogonalize(self, R: Mat | None = None, **kargs: Any) -> None: """Orthogonalize all columns (except leading ones) (QR decomposition). Collective. Parameters ---------- R A sequential dense matrix. Notes ----- The output satisfies :math:`V_0 = V R` (where :math:`V_0` represent the input :math:`V`) and :math:`V^* V = I` (or :math:`V^*BV=I` if an inner product matrix :math:`B` has been specified with `setMatrix()`). See Also -------- orthogonalizeColumn, setMatrix, setOrthogonalization, slepc.BVOrthogonalize :sources:`Source code at slepc4py/SLEPc/BV.pyx:2263 ` """ ... @property def sizes(self) -> tuple[LayoutSizeSpec, int]: """Basis vectors local and global sizes, and the number of columns. :sources:`Source code at slepc4py/SLEPc/BV.pyx:2290 ` """ ... @property def size(self) -> tuple[int, int]: """Basis vectors global size. :sources:`Source code at slepc4py/SLEPc/BV.pyx:2295 ` """ ... @property def local_size(self) -> int: """Basis vectors local size. :sources:`Source code at slepc4py/SLEPc/BV.pyx:2300 ` """ ... @property def column_size(self) -> int: """Basis vectors column size. :sources:`Source code at slepc4py/SLEPc/BV.pyx:2305 ` """ ... class DS(Object): """Direct Solver (or Dense System). The `DS` package provides auxiliary routines that are internally used by the different slepc4py solvers. It is used to represent low-dimensional eigenproblems that must be solved within iterative solvers with direct methods. It can be seen as a structured wrapper to LAPACK functionality. """ class Type: """DS type. - `HEP`: Dense Hermitian Eigenvalue Problem. - `NHEP`: Dense Non-Hermitian Eigenvalue Problem. - `GHEP`: Dense Generalized Hermitian Eigenvalue Problem. - `GHIEP`: Dense Generalized Hermitian Indefinite Eigenvalue Problem. - `GNHEP`: Dense Generalized Non-Hermitian Eigenvalue Problem. - `NHEPTS`: Dense Non-Hermitian Eigenvalue Problem (special variant intended for two-sided Krylov solvers). - `SVD`: Dense Singular Value Decomposition. - `HSVD`: Dense Hyperbolic Singular Value Decomposition. - `GSVD`: Dense Generalized Singular Value Decomposition. - `PEP`: Dense Polynomial Eigenvalue Problem. - `NEP`: Dense Nonlinear Eigenvalue Problem. See Also -------- slepc.DSType """ HEP: str = _def(str, 'HEP') #: Object ``HEP`` of type :class:`str` NHEP: str = _def(str, 'NHEP') #: Object ``NHEP`` of type :class:`str` GHEP: str = _def(str, 'GHEP') #: Object ``GHEP`` of type :class:`str` GHIEP: str = _def(str, 'GHIEP') #: Object ``GHIEP`` of type :class:`str` GNHEP: str = _def(str, 'GNHEP') #: Object ``GNHEP`` of type :class:`str` NHEPTS: str = _def(str, 'NHEPTS') #: Object ``NHEPTS`` of type :class:`str` SVD: str = _def(str, 'SVD') #: Object ``SVD`` of type :class:`str` HSVD: str = _def(str, 'HSVD') #: Object ``HSVD`` of type :class:`str` GSVD: str = _def(str, 'GSVD') #: Object ``GSVD`` of type :class:`str` PEP: str = _def(str, 'PEP') #: Object ``PEP`` of type :class:`str` NEP: str = _def(str, 'NEP') #: Object ``NEP`` of type :class:`str` class StateType: """DS state types. - `RAW`: Not processed yet. - `INTERMEDIATE`: Reduced to Hessenberg or tridiagonal form (or equivalent). - `CONDENSED`: Reduced to Schur or diagonal form (or equivalent). - `TRUNCATED`: Condensed form truncated to a smaller size. See Also -------- slepc.DSStateType """ RAW: int = _def(int, 'RAW') #: Constant ``RAW`` of type :class:`int` INTERMEDIATE: int = _def(int, 'INTERMEDIATE') #: Constant ``INTERMEDIATE`` of type :class:`int` CONDENSED: int = _def(int, 'CONDENSED') #: Constant ``CONDENSED`` of type :class:`int` TRUNCATED: int = _def(int, 'TRUNCATED') #: Constant ``TRUNCATED`` of type :class:`int` class MatType: """To refer to one of the matrices stored internally in DS. - `A`: first matrix of eigenproblem/singular value problem. - `B`: second matrix of a generalized eigenproblem. - `C`: third matrix of a quadratic eigenproblem. - `T`: tridiagonal matrix. - `D`: diagonal matrix. - `Q`: orthogonal matrix of (right) Schur vectors. - `Z`: orthogonal matrix of left Schur vectors. - `X`: right eigenvectors. - `Y`: left eigenvectors. - `U`: left singular vectors. - `V`: right singular vectors. - `W`: workspace matrix. See Also -------- slepc.DSMatType """ A: int = _def(int, 'A') #: Constant ``A`` of type :class:`int` B: int = _def(int, 'B') #: Constant ``B`` of type :class:`int` C: int = _def(int, 'C') #: Constant ``C`` of type :class:`int` T: int = _def(int, 'T') #: Constant ``T`` of type :class:`int` D: int = _def(int, 'D') #: Constant ``D`` of type :class:`int` Q: int = _def(int, 'Q') #: Constant ``Q`` of type :class:`int` Z: int = _def(int, 'Z') #: Constant ``Z`` of type :class:`int` X: int = _def(int, 'X') #: Constant ``X`` of type :class:`int` Y: int = _def(int, 'Y') #: Constant ``Y`` of type :class:`int` U: int = _def(int, 'U') #: Constant ``U`` of type :class:`int` V: int = _def(int, 'V') #: Constant ``V`` of type :class:`int` W: int = _def(int, 'W') #: Constant ``W`` of type :class:`int` class ParallelType: """Indicates the parallel mode that the direct solver will use. - `REDUNDANT`: Every process performs the computation redundantly. - `SYNCHRONIZED`: The first process sends the result to the rest. - `DISTRIBUTED`: Used in some cases to distribute the computation among processes. See Also -------- slepc.DSParallelType """ REDUNDANT: int = _def(int, 'REDUNDANT') #: Constant ``REDUNDANT`` of type :class:`int` SYNCHRONIZED: int = _def(int, 'SYNCHRONIZED') #: Constant ``SYNCHRONIZED`` of type :class:`int` DISTRIBUTED: int = _def(int, 'DISTRIBUTED') #: Constant ``DISTRIBUTED`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the DS data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.DSView :sources:`Source code at slepc4py/SLEPc/DS.pyx:127 ` """ ... def destroy(self) -> Self: """Destroy the DS object. Collective. See Also -------- slepc.DSDestroy :sources:`Source code at slepc4py/SLEPc/DS.pyx:146 ` """ ... def reset(self) -> None: """Reset the DS object. Collective. See Also -------- allocate, slepc.DSReset :sources:`Source code at slepc4py/SLEPc/DS.pyx:160 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the DS object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- duplicate, slepc.DSCreate :sources:`Source code at slepc4py/SLEPc/DS.pyx:172 ` """ ... def setType(self, ds_type: Type | str) -> None: """Set the type for the DS object. Logically collective. Parameters ---------- ds_type The direct solver type to be used. See Also -------- getType, slepc.DSSetType :sources:`Source code at slepc4py/SLEPc/DS.pyx:193 ` """ ... def getType(self) -> str: """Get the DS type of this object. Not collective. Returns ------- str The direct solver type currently being used. See Also -------- setType, slepc.DSGetType :sources:`Source code at slepc4py/SLEPc/DS.pyx:212 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all DS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all DS option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.DSSetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/DS.pyx:231 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all DS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all DS option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.DSSetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/DS.pyx:256 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all DS options in the database. Not collective. Returns ------- str The prefix string set for this DS object. See Also -------- appendOptionsPrefix, setOptionsPrefix, slepc.DSSetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/DS.pyx:275 ` """ ... def setFromOptions(self) -> None: """Set DS options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.DSSetFromOptions :sources:`Source code at slepc4py/SLEPc/DS.pyx:294 ` """ ... def duplicate(self) -> DS: """Duplicate the DS object with the same type and dimensions. Collective. Returns ------- DS The new object. Notes ----- This method does not copy the matrices, and the new object does not even have internal arrays allocated. Use `allocate()` to use the new `DS`. See Also -------- create, allocate, slepc.DSDuplicate :sources:`Source code at slepc4py/SLEPc/DS.pyx:311 ` """ ... def allocate(self, ld: int) -> None: """Allocate memory for internal storage or matrices in DS. Logically collective. Parameters ---------- ld Leading dimension (maximum allowed dimension for the matrices, including the extra row if present). Notes ----- If the leading dimension is different from a previously set value, then all matrices are destroyed with `reset()`. See Also -------- getLeadingDimension, setDimensions, setExtraRow, reset, slepc.DSAllocate :sources:`Source code at slepc4py/SLEPc/DS.pyx:338 ` """ ... def getLeadingDimension(self) -> int: """Get the leading dimension of the allocated matrices. Not collective. Returns ------- int Leading dimension (maximum allowed dimension for the matrices). See Also -------- allocate, setDimensions, slepc.DSGetLeadingDimension :sources:`Source code at slepc4py/SLEPc/DS.pyx:362 ` """ ... def setState(self, state: StateType) -> None: """Set the state of the DS object. Logically collective. Parameters ---------- state The new state. Notes ----- The state indicates that the dense system is in an initial state (raw), in an intermediate state (such as tridiagonal, Hessenberg or Hessenberg-triangular), in a condensed state (such as diagonal, Schur or generalized Schur), or in a truncated state. The state is automatically changed in functions such as `solve()` or `truncate()`. This function is normally used to return to the raw state when the condensed structure is destroyed, or to indicate that `solve()` must start with a problem that already has an intermediate form. See Also -------- getState, solve, truncate, slepc.DSSetState :sources:`Source code at slepc4py/SLEPc/DS.pyx:381 ` """ ... def getState(self) -> StateType: """Get the current state. Not collective. Returns ------- StateType The current state. See Also -------- setState, slepc.DSGetState :sources:`Source code at slepc4py/SLEPc/DS.pyx:413 ` """ ... def setParallel(self, pmode: ParallelType) -> None: """Set the mode of operation in parallel runs. Logically collective. Parameters ---------- pmode The parallel mode. See Also -------- getParallel, slepc.DSSetParallel :sources:`Source code at slepc4py/SLEPc/DS.pyx:432 ` """ ... def getParallel(self) -> ParallelType: """Get the mode of operation in parallel runs. Not collective. Returns ------- ParallelType The parallel mode. See Also -------- setParallel, slepc.DSGetParallel :sources:`Source code at slepc4py/SLEPc/DS.pyx:450 ` """ ... def setDimensions(self, n: int | None = None, l: int | None = None, k: int | None = None) -> None: """Set the matrix sizes in the DS object. Logically collective. Parameters ---------- n The new size. l Number of locked (inactive) leading columns. k Intermediate dimension (e.g., position of arrow). Notes ----- The internal arrays are not reallocated. Some `DS` types have additional dimensions, e.g., the number of columns in `DS.Type.SVD`. For these, you should call a specific interface function. See Also -------- getDimensions, allocate, slepc.DSSetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:469 ` """ ... def getDimensions(self) -> tuple[int, int, int, int]: """Get the current dimensions. Not collective. Returns ------- n: int The new size. l: int Number of locked (inactive) leading columns. k: int Intermediate dimension (e.g., position of arrow). t: int Truncated length. Notes ----- The ``t`` value makes sense only if `truncate()` has been called. Otherwise it is equal to ``n``. See Also -------- setDimensions, truncate, getLeadingDimension, slepc.DSGetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:504 ` """ ... def setBlockSize(self, bs: int) -> None: """Set the block size. Logically collective. Parameters ---------- bs The block size. See Also -------- getBlockSize, slepc.DSSetBlockSize :sources:`Source code at slepc4py/SLEPc/DS.pyx:537 ` """ ... def getBlockSize(self) -> int: """Get the block size. Not collective. Returns ------- int The block size. See Also -------- setBlockSize, slepc.DSGetBlockSize :sources:`Source code at slepc4py/SLEPc/DS.pyx:555 ` """ ... def setMethod(self, meth: int) -> None: """Set the method to be used to solve the problem. Logically collective. Parameters ---------- meth An index identifying the method. See Also -------- getMethod, slepc.DSSetMethod :sources:`Source code at slepc4py/SLEPc/DS.pyx:574 ` """ ... def getMethod(self) -> int: """Get the method currently used in the DS. Not collective. Returns ------- int Identifier of the method. See Also -------- setMethod, slepc.DSGetMethod :sources:`Source code at slepc4py/SLEPc/DS.pyx:592 ` """ ... def setCompact(self, comp: bool) -> None: """Set the compact flag for storage of matrices. Logically collective. Parameters ---------- comp ``True`` means compact storage. Notes ----- Compact storage is used in some `DS` types such as `DS.Type.HEP` when the matrix is tridiagonal. This flag can be used to indicate whether the user provides the matrix entries via the compact form (the tridiagonal `DS.MatType.T`) or the non-compact one (`DS.MatType.A`). The default is ``False``. See Also -------- getCompact, slepc.DSSetCompact :sources:`Source code at slepc4py/SLEPc/DS.pyx:611 ` """ ... def getCompact(self) -> bool: """Get the compact storage flag. Not collective. Returns ------- bool The flag. See Also -------- setCompact, slepc.DSGetCompact :sources:`Source code at slepc4py/SLEPc/DS.pyx:639 ` """ ... def setExtraRow(self, ext: bool) -> None: """Set a flag to indicate that the matrix has one extra row. Logically collective. Parameters ---------- ext ``True`` if the matrix has extra row. Notes ----- In Krylov methods it is useful that the matrix representing the direct solver has one extra row, i.e., has :math:`(n+1)` rows and :math:`(n+1)` columns. If this flag is activated, all transformations applied to the right of the matrix also affect this additional row. In that case, :math:`(n+1)` must be less or equal than the leading dimension. The default is ``False``. See Also -------- getExtraRow, solve, allocate, slepc.DSSetExtraRow :sources:`Source code at slepc4py/SLEPc/DS.pyx:658 ` """ ... def getExtraRow(self) -> bool: """Get the extra row flag. Not collective. Returns ------- bool The flag. See Also -------- setExtraRow, slepc.DSGetExtraRow :sources:`Source code at slepc4py/SLEPc/DS.pyx:686 ` """ ... def setRefined(self, ref: bool) -> None: """Set a flag to indicate that refined vectors must be computed. Logically collective. Parameters ---------- ref ``True`` if refined vectors must be used. Notes ----- Normally the vectors returned in `DS.MatType.X` are eigenvectors of the projected matrix. With this flag activated, `vectors()` will return the right singular vector of the smallest singular value of matrix :math:`\hat A - \eta I`, where :math:`\hat A` is the extended matrix (with extra row) and :math:`\eta` is the Ritz value. This is used in the refined Ritz approximation. The default is ``False``. See Also -------- getRefined, vectors, setExtraRow, slepc.DSSetRefined :sources:`Source code at slepc4py/SLEPc/DS.pyx:705 ` """ ... def getRefined(self) -> bool: """Get the refined vectors flag. Not collective. Returns ------- bool The flag. See Also -------- setRefined, slepc.DSGetRefined :sources:`Source code at slepc4py/SLEPc/DS.pyx:734 ` """ ... def truncate(self, n: int, trim: bool = False) -> None: """Truncate the system represented in the DS object. Logically collective. Parameters ---------- n The new size. trim A flag to indicate if the factorization must be trimmed. See Also -------- setDimensions, setExtraRow, slepc.DSTruncate :sources:`Source code at slepc4py/SLEPc/DS.pyx:753 ` """ ... def updateExtraRow(self) -> None: """Ensure that the extra row gets up-to-date after a call to `DS.solve()`. Logically collective. Perform all necessary operations so that the extra row gets up-to-date after a call to `DS.solve()`. See Also -------- slepc.DSUpdateExtraRow :sources:`Source code at slepc4py/SLEPc/DS.pyx:774 ` """ ... def getMat(self, matname: MatType) -> Mat: """Get the requested matrix as a sequential dense ``Mat`` object. Not collective. Parameters ---------- matname The requested matrix. Returns ------- petsc4py.PETSc.Mat The matrix. Notes ----- The returned matrix has sizes equal to the current `DS` dimensions (see `setDimensions()`), and contains the values that would be obtained with `getArray()`. If the `DS` was truncated, then the number of rows is equal to the dimension prior to truncation, see `truncate()`. When no longer needed the user must call `restoreMat()`. See Also -------- restoreMat, setDimensions, getArray, truncate, slepc.DSGetMat :sources:`Source code at slepc4py/SLEPc/DS.pyx:789 ` """ ... def restoreMat(self, matname: MatType, mat: petsc4py.PETSc.Mat) -> None: """Restore the previously seized matrix. Not collective. Parameters ---------- matname The selected matrix. mat The matrix previously obtained with `getMat()`. See Also -------- getMat, slepc.DSRestoreMat :sources:`Source code at slepc4py/SLEPc/DS.pyx:824 ` """ ... def getArray(self, matname: MatType) -> ArrayScalar: """Return the array where the data is stored. Not collective. Parameters ---------- matname The selected matrix. Returns ------- ArrayScalar The array. See Also -------- slepc.DSGetArray :sources:`Source code at slepc4py/SLEPc/DS.pyx:845 ` """ ... def setIdentity(self, matname: MatType) -> None: """Set the identity on the active part of a matrix. Logically collective. Parameters ---------- matname The matrix to be changed. See Also -------- slepc.DSSetIdentity :sources:`Source code at slepc4py/SLEPc/DS.pyx:885 ` """ ... def cond(self) -> float: """Compute the inf-norm condition number of the first matrix. Logically collective. Returns ------- float Condition number. See Also -------- slepc.DSCond :sources:`Source code at slepc4py/SLEPc/DS.pyx:905 ` """ ... def solve(self) -> ArrayScalar: """Solve the problem. Logically collective. Returns ------- ArrayScalar Eigenvalues or singular values. See Also -------- slepc.DSSolve :sources:`Source code at slepc4py/SLEPc/DS.pyx:924 ` """ ... def vectors(self, matname=MatType.X) -> None: """Compute vectors associated to the dense system such as eigenvectors. Logically collective. Parameters ---------- matname The matrix, used to indicate which vectors are required. See Also -------- slepc.DSVectors :sources:`Source code at slepc4py/SLEPc/DS.pyx:952 ` """ ... def setSVDDimensions(self, m: int) -> None: """Set the number of columns of a `DS` of type `SVD`. Logically collective. Parameters ---------- m The number of columns. Notes ----- This call is complementary to `setDimensions()`, to provide a dimension that is specific to this `DS.Type`. See Also -------- setDimensions, getSVDDimensions, slepc.DSSVDSetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:972 ` """ ... def getSVDDimensions(self) -> int: """Get the number of columns of a `DS` of type `SVD`. Not collective. Returns ------- int The number of columns. See Also -------- setSVDDimensions, slepc.DSSVDGetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:995 ` """ ... def setHSVDDimensions(self, m: int) -> None: """Set the number of columns of a `DS` of type `HSVD`. Logically collective. Parameters ---------- m The number of columns. Notes ----- This call is complementary to `setDimensions()`, to provide a dimension that is specific to this `DS.Type`. See Also -------- setDimensions, getHSVDDimensions, slepc.DSHSVDSetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:1014 ` """ ... def getHSVDDimensions(self) -> int: """Get the number of columns of a `DS` of type `HSVD`. Not collective. Returns ------- int The number of columns. See Also -------- setHSVDDimensions, slepc.DSHSVDGetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:1037 ` """ ... def setGSVDDimensions(self, m: int, p: int) -> None: """Set the number of columns and rows of a `DS` of type `GSVD`. Logically collective. Parameters ---------- m The number of columns. p The number of rows for the second matrix. Notes ----- This call is complementary to `setDimensions()`, to provide dimensions that are specific to this `DS.Type`. See Also -------- setDimensions, getGSVDDimensions, slepc.DSGSVDSetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:1056 ` """ ... def getGSVDDimensions(self) -> tuple[int, int]: """Get the number of columns and rows of a `DS` of type `GSVD`. Not collective. Returns ------- m: int The number of columns. p: int The number of rows for the second matrix. See Also -------- setGSVDDimensions, slepc.DSGSVDGetDimensions :sources:`Source code at slepc4py/SLEPc/DS.pyx:1082 ` """ ... def setPEPDegree(self, deg: int) -> None: """Set the polynomial degree of a `DS` of type `PEP`. Logically collective. Parameters ---------- deg The polynomial degree. See Also -------- getPEPDegree, slepc.DSPEPSetDegree :sources:`Source code at slepc4py/SLEPc/DS.pyx:1104 ` """ ... def getPEPDegree(self) -> int: """Get the polynomial degree of a `DS` of type `PEP`. Not collective. Returns ------- int The polynomial degree. See Also -------- setPEPDegree, slepc.DSPEPGetDegree :sources:`Source code at slepc4py/SLEPc/DS.pyx:1122 ` """ ... def setPEPCoefficients(self, pbc: Sequence[float]) -> None: """Set the polynomial basis coefficients of a `DS` of type `PEP`. Logically collective. Parameters ---------- pbc Coefficients. Notes ----- This function is required only in the case of a polynomial specified in a non-monomial basis, to provide the coefficients that will be used during the linearization, multiplying the identity blocks on the three main diagonal blocks. Depending on the polynomial basis (Chebyshev, Legendre, ...) the coefficients must be different. There must be a total of :math:`3(d+1)` coefficients, where :math:`d` is the degree of the polynomial. The coefficients are arranged in three groups, :math:`a_i, b_i, c_i`, according to the definition of the three-term recurrence. In the case of the monomial basis, :math:`a_i=1` and :math:`b_i=c_i=0`, in which case it is not necessary to invoke this function. See Also -------- getPEPCoefficients, slepc.DSPEPSetCoefficients :sources:`Source code at slepc4py/SLEPc/DS.pyx:1141 ` """ ... def getPEPCoefficients(self) -> ArrayReal: """Get the polynomial basis coefficients of a `DS` of type `PEP`. Not collective. Returns ------- ArrayReal Coefficients. See Also -------- setPEPCoefficients, slepc.DSPEPGetCoefficients :sources:`Source code at slepc4py/SLEPc/DS.pyx:1176 ` """ ... @property def state(self) -> DSStateType: """The state of the DS object. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1204 ` """ ... @property def parallel(self) -> DSParallelType: """The mode of operation in parallel runs. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1211 ` """ ... @property def block_size(self) -> int: """The block size. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1218 ` """ ... @property def method(self) -> int: """The method to be used to solve the problem. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1225 ` """ ... @property def compact(self) -> bool: """Compact storage of matrices. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1232 ` """ ... @property def extra_row(self) -> bool: """If the matrix has one extra row. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1239 ` """ ... @property def refined(self) -> bool: """If refined vectors must be computed. :sources:`Source code at slepc4py/SLEPc/DS.pyx:1246 ` """ ... class FN(Object): """Mathematical Function. The `FN` package provides the functionality to represent a simple mathematical function such as an exponential, a polynomial or a rational function. This is used as a building block for defining the function associated to the nonlinear eigenproblem, as well as for specifying which function to use when computing the action of a matrix function on a vector. """ class Type: """FN type. - `COMBINE`: A math function defined by combining two functions. - `RATIONAL`: A rational function :math:`f(x)=p(x)/q(x)`. - `EXP`: The exponential function :math:`f(x)=e^x`. - `LOG`: The logarithm function :math:`f(x)=\log{x}`. - `PHI`: One of the Phi_k functions with index k. - `SQRT`: The square root function :math:`f(x)=\sqrt{x}`. - `INVSQRT`: The inverse square root function. See Also -------- slepc.FNType """ COMBINE: str = _def(str, 'COMBINE') #: Object ``COMBINE`` of type :class:`str` RATIONAL: str = _def(str, 'RATIONAL') #: Object ``RATIONAL`` of type :class:`str` EXP: str = _def(str, 'EXP') #: Object ``EXP`` of type :class:`str` LOG: str = _def(str, 'LOG') #: Object ``LOG`` of type :class:`str` PHI: str = _def(str, 'PHI') #: Object ``PHI`` of type :class:`str` SQRT: str = _def(str, 'SQRT') #: Object ``SQRT`` of type :class:`str` INVSQRT: str = _def(str, 'INVSQRT') #: Object ``INVSQRT`` of type :class:`str` class CombineType: """FN type of combination of child functions. - `ADD`: Addition :math:`f(x) = f_1(x)+f_2(x)` - `MULTIPLY`: Multiplication :math:`f(x) = f_1(x)f_2(x)` - `DIVIDE`: Division :math:`f(x) = f_1(x)/f_2(x)` - `COMPOSE`: Composition :math:`f(x) = f_2(f_1(x))` See Also -------- slepc.FNCombineType """ ADD: int = _def(int, 'ADD') #: Constant ``ADD`` of type :class:`int` MULTIPLY: int = _def(int, 'MULTIPLY') #: Constant ``MULTIPLY`` of type :class:`int` DIVIDE: int = _def(int, 'DIVIDE') #: Constant ``DIVIDE`` of type :class:`int` COMPOSE: int = _def(int, 'COMPOSE') #: Constant ``COMPOSE`` of type :class:`int` class ParallelType: """FN parallel types. - `REDUNDANT`: Every process performs the computation redundantly. - `SYNCHRONIZED`: The first process sends the result to the rest. See Also -------- slepc.FNParallelType """ REDUNDANT: int = _def(int, 'REDUNDANT') #: Constant ``REDUNDANT`` of type :class:`int` SYNCHRONIZED: int = _def(int, 'SYNCHRONIZED') #: Constant ``SYNCHRONIZED`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the FN data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.FNView :sources:`Source code at slepc4py/SLEPc/FN.pyx:149 ` """ ... def destroy(self) -> Self: """Destroy the FN object. Collective. See Also -------- slepc.FNDestroy :sources:`Source code at slepc4py/SLEPc/FN.pyx:168 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the FN object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.FNCreate :sources:`Source code at slepc4py/SLEPc/FN.pyx:182 ` """ ... def setType(self, fn_type: Type | str) -> None: """Set the type for the FN object. Logically collective. Parameters ---------- fn_type The math function type to be used. See Also -------- getType, slepc.FNSetType :sources:`Source code at slepc4py/SLEPc/FN.pyx:203 ` """ ... def getType(self) -> str: """Get the FN type of this object. Not collective. Returns ------- str The math function type currently being used. See Also -------- setType, slepc.FNGetType :sources:`Source code at slepc4py/SLEPc/FN.pyx:222 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all FN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all FN option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.FNGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/FN.pyx:241 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all FN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all FN option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.FNAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/FN.pyx:266 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all FN options in the database. Not collective. Returns ------- str The prefix string set for this FN object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.FNGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/FN.pyx:285 ` """ ... def setFromOptions(self) -> None: """Set FN options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.FNSetFromOptions :sources:`Source code at slepc4py/SLEPc/FN.pyx:304 ` """ ... def duplicate(self, comm: Comm | None = None) -> FN: """Duplicate the FN object copying all parameters. Collective. Duplicate the FN object copying all parameters, possibly with a different communicator. Parameters ---------- comm MPI communicator; if not provided, it defaults to the object's communicator. Returns ------- FN The new object. See Also -------- create, slepc.FNDuplicate :sources:`Source code at slepc4py/SLEPc/FN.pyx:321 ` """ ... def evaluateFunction(self, x: Scalar) -> Scalar: """Compute the value of the function :math:`f(x)` for a given x. Not collective. Parameters ---------- x Value where the function must be evaluated. Returns ------- Scalar The result of :math:`f(x)`. Notes ----- Scaling factors are taken into account, so the actual function evaluation will return :math:`b f(a x)`. See Also -------- evaluateDerivative, evaluateFunctionMat, setScale, slepc.FNEvaluateFunction :sources:`Source code at slepc4py/SLEPc/FN.pyx:352 ` """ ... def evaluateDerivative(self, x: Scalar) -> Scalar: """Compute the value of the derivative :math:`f'(x)` for a given x. Not collective. Parameters ---------- x Value where the derivative must be evaluated. Returns ------- Scalar The result of :math:`f'(x)`. Notes ----- Scaling factors are taken into account, so the actual derivative evaluation will return :math:`ab f'(a x)`. See Also -------- evaluateFunction, setScale, slepc.FNEvaluateDerivative :sources:`Source code at slepc4py/SLEPc/FN.pyx:382 ` """ ... def evaluateFunctionMat(self, A: Mat, B: Mat | None = None) -> Mat: """Compute the value of the function :math:`f(A)` for a given matrix A. Logically collective. Parameters ---------- A Matrix on which the function must be evaluated. B Placeholder for the result. Returns ------- petsc4py.PETSc.Mat The result of :math:`f(A)`. Notes ----- Scaling factors are taken into account, so the actual function evaluation will return :math:`b f(a A)`. See Also -------- evaluateFunction, evaluateFunctionMatVec, slepc.FNEvaluateFunctionMat :sources:`Source code at slepc4py/SLEPc/FN.pyx:412 ` """ ... def evaluateFunctionMatVec(self, A: Mat, v: Vec | None = None) -> Vec: """Compute the first column of the matrix :math:`f(A)`. Logically collective. Parameters ---------- A Matrix on which the function must be evaluated. Returns ------- petsc4py.PETSc.Vec The first column of the result :math:`f(A)`. Notes ----- This operation is similar to `evaluateFunctionMat()` but returns only the first column of :math:`f(A)`, hence saving computations in most cases. See Also -------- evaluateFunctionMat, slepc.FNEvaluateFunctionMatVec :sources:`Source code at slepc4py/SLEPc/FN.pyx:443 ` """ ... def setScale(self, alpha: Scalar | None = None, beta: Scalar | None = None) -> None: """Set the scaling parameters that define the matematical function. Logically collective. Parameters ---------- alpha Inner scaling (argument), default is 1.0. beta Outer scaling (result), default is 1.0. See Also -------- getScale, evaluateFunction, slepc.FNSetScale :sources:`Source code at slepc4py/SLEPc/FN.pyx:473 ` """ ... def getScale(self) -> tuple[Scalar, Scalar]: """Get the scaling parameters that define the matematical function. Not collective. Returns ------- alpha: Scalar Inner scaling (argument). beta: Scalar Outer scaling (result). See Also -------- setScale, slepc.FNGetScale :sources:`Source code at slepc4py/SLEPc/FN.pyx:496 ` """ ... def setMethod(self, meth: int) -> None: """Set the method to be used to evaluate functions of matrices. Logically collective. Parameters ---------- meth An index identifying the method. Notes ----- In some `FN` types there are more than one algorithms available for computing matrix functions. In that case, this function allows choosing the wanted method. If ``meth`` is currently set to 0 and the input argument of `FN.evaluateFunctionMat()` is a symmetric/Hermitian matrix, then the computation is done via the eigendecomposition, rather than with the general algorithm. See Also -------- getMethod, slepc.FNSetMethod :sources:`Source code at slepc4py/SLEPc/FN.pyx:517 ` """ ... def getMethod(self) -> int: """Get the method currently used for matrix functions. Not collective. Returns ------- int An index identifying the method. See Also -------- setMethod, slepc.FNGetMethod :sources:`Source code at slepc4py/SLEPc/FN.pyx:546 ` """ ... def setParallel(self, pmode: ParallelType) -> None: """Set the mode of operation in parallel runs. Logically collective. Parameters ---------- pmode The parallel mode. Notes ----- This is relevant only when the function is evaluated on a matrix, with either `evaluateFunctionMat()` or `evaluateFunctionMatVec()`. See Also -------- evaluateFunctionMat, getParallel, slepc.FNSetParallel :sources:`Source code at slepc4py/SLEPc/FN.pyx:565 ` """ ... def getParallel(self) -> ParallelType: """Get the mode of operation in parallel runs. Not collective. Returns ------- ParallelType The parallel mode. See Also -------- setParallel, slepc.FNGetParallel :sources:`Source code at slepc4py/SLEPc/FN.pyx:588 ` """ ... def setRationalNumerator(self, alpha: Sequence[Scalar]) -> None: """Set the coefficients of the numerator of the rational function. Logically collective. Parameters ---------- alpha Coefficients. See Also -------- setRationalDenominator, slepc.FNRationalSetNumerator :sources:`Source code at slepc4py/SLEPc/FN.pyx:609 ` """ ... def getRationalNumerator(self) -> ArrayScalar: """Get the coefficients of the numerator of the rational function. Not collective. Returns ------- ArrayScalar Coefficients. See Also -------- setRationalNumerator, slepc.FNRationalGetNumerator :sources:`Source code at slepc4py/SLEPc/FN.pyx:629 ` """ ... def setRationalDenominator(self, alpha: Sequence[Scalar]) -> None: """Set the coefficients of the denominator of the rational function. Logically collective. Parameters ---------- alpha Coefficients. See Also -------- setRationalNumerator, slepc.FNRationalSetDenominator :sources:`Source code at slepc4py/SLEPc/FN.pyx:654 ` """ ... def getRationalDenominator(self) -> ArrayScalar: """Get the coefficients of the denominator of the rational function. Not collective. Returns ------- ArrayScalar Coefficients. See Also -------- setRationalDenominator, slepc.FNRationalGetDenominator :sources:`Source code at slepc4py/SLEPc/FN.pyx:674 ` """ ... def setCombineChildren(self, comb: CombineType, f1: FN, f2: FN) -> None: """Set the two child functions that constitute this combined function. Logically collective. Set the two child functions that constitute this combined function, and the way they must be combined. Parameters ---------- comb How to combine the functions (addition, multiplication, division, composition). f1 First function. f2 Second function. See Also -------- getCombineChildren, slepc.FNCombineSetChildren :sources:`Source code at slepc4py/SLEPc/FN.pyx:699 ` """ ... def getCombineChildren(self) -> tuple[CombineType, FN, FN]: """Get the two child functions that constitute this combined function. Not collective. Get the two child functions that constitute this combined function, and the way they must be combined. Returns ------- comb: CombineType How to combine the functions (addition, multiplication, division, composition). f1: FN First function. f2: FN Second function. See Also -------- setCombineChildren, slepc.FNCombineGetChildren :sources:`Source code at slepc4py/SLEPc/FN.pyx:725 ` """ ... def setPhiIndex(self, k: int) -> None: """Set the index of the phi-function. Logically collective. Parameters ---------- k The index. Notes ----- If not set, the default index is 1. See Also -------- getPhiIndex, slepc.FNPhiSetIndex :sources:`Source code at slepc4py/SLEPc/FN.pyx:756 ` """ ... def getPhiIndex(self) -> int: """Get the index of the phi-function. Not collective. Returns ------- int The index. See Also -------- setPhiIndex, slepc.FNPhiGetIndex :sources:`Source code at slepc4py/SLEPc/FN.pyx:778 ` """ ... @property def method(self) -> int: """The method to be used to evaluate functions of matrices. :sources:`Source code at slepc4py/SLEPc/FN.pyx:799 ` """ ... @property def parallel(self) -> FNParallelType: """The mode of operation in parallel runs. :sources:`Source code at slepc4py/SLEPc/FN.pyx:806 ` """ ... class RG(Object): """Region. The `RG` package provides a way to define a region of the complex plane. This is used in various eigensolvers to specify where the wanted eigenvalues are located. """ class Type: """RG type. - `INTERVAL`: A (generalized) interval. - `POLYGON`: A polygonal region defined by its vertices. - `ELLIPSE`: An ellipse defined by its center, radius and vertical scale. - `RING`: A ring region. See Also -------- slepc.RGType """ INTERVAL: str = _def(str, 'INTERVAL') #: Object ``INTERVAL`` of type :class:`str` POLYGON: str = _def(str, 'POLYGON') #: Object ``POLYGON`` of type :class:`str` ELLIPSE: str = _def(str, 'ELLIPSE') #: Object ``ELLIPSE`` of type :class:`str` RING: str = _def(str, 'RING') #: Object ``RING`` of type :class:`str` class QuadRule: """RG quadrature rule for contour integral methods. - `TRAPEZOIDAL`: Trapezoidal rule. - `CHEBYSHEV`: Chebyshev points. See Also -------- slepc.RGQuadRule """ TRAPEZOIDAL: int = _def(int, 'TRAPEZOIDAL') #: Constant ``TRAPEZOIDAL`` of type :class:`int` CHEBYSHEV: int = _def(int, 'CHEBYSHEV') #: Constant ``CHEBYSHEV`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the RG data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.RGView :sources:`Source code at slepc4py/SLEPc/RG.pyx:54 ` """ ... def destroy(self) -> Self: """Destroy the RG object. Collective. See Also -------- slepc.RGDestroy :sources:`Source code at slepc4py/SLEPc/RG.pyx:73 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the RG object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.RGCreate :sources:`Source code at slepc4py/SLEPc/RG.pyx:87 ` """ ... def setType(self, rg_type: Type | str) -> None: """Set the type for the RG object. Logically collective. Parameters ---------- rg_type The region type to be used. See Also -------- getType, slepc.RGSetType :sources:`Source code at slepc4py/SLEPc/RG.pyx:108 ` """ ... def getType(self) -> str: """Get the RG type of this object. Not collective. Returns ------- str The region type currently being used. See Also -------- setType, slepc.RGGetType :sources:`Source code at slepc4py/SLEPc/RG.pyx:127 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all RG options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all RG option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.RGGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/RG.pyx:146 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all RG options in the database. Not collective. Returns ------- str The prefix string set for this RG object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.RGGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/RG.pyx:171 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all RG options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all RG option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.RGAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/RG.pyx:190 ` """ ... def setFromOptions(self) -> None: """Set RG options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.RGSetFromOptions :sources:`Source code at slepc4py/SLEPc/RG.pyx:209 ` """ ... def isTrivial(self) -> bool: """Tell whether it is the trivial region (whole complex plane). Not collective. Returns ------- bool ``True`` if the region is equal to the whole complex plane, e.g., an interval region with all four endpoints unbounded or an ellipse with infinite radius. See Also -------- checkInside, slepc.RGIsTrivial :sources:`Source code at slepc4py/SLEPc/RG.pyx:228 ` """ ... def isAxisymmetric(self, vertical: bool = False) -> bool: """Determine if the region is axisymmetric. Not collective. Determine if the region is symmetric with respect to the real or imaginary axis. Parameters ---------- vertical ``True`` if symmetry must be checked against the vertical axis. Returns ------- bool ``True`` if the region is axisymmetric. See Also -------- canUseConjugates, slepc.RGIsAxisymmetric :sources:`Source code at slepc4py/SLEPc/RG.pyx:249 ` """ ... def getComplement(self) -> bool: """Get the flag indicating whether the region is complemented or not. Not collective. Returns ------- bool Whether the region is complemented or not. See Also -------- setComplement, slepc.RGGetComplement :sources:`Source code at slepc4py/SLEPc/RG.pyx:277 ` """ ... def setComplement(self, comp: bool = True) -> None: """Set a flag to indicate that the region is the complement of the specified one. Logically collective. Parameters ---------- comp Activate/deactivate the complementation of the region. See Also -------- getComplement, slepc.RGSetComplement :sources:`Source code at slepc4py/SLEPc/RG.pyx:296 ` """ ... def setScale(self, sfactor: float = None) -> None: """Set the scaling factor to be used. Logically collective. Set the scaling factor to be used when checking that a point is inside the region and when computing the contour. Parameters ---------- sfactor The scaling factor (default=1). See Also -------- getScale, checkInside, computeContour, slepc.RGSetScale :sources:`Source code at slepc4py/SLEPc/RG.pyx:314 ` """ ... def getScale(self) -> float: """Get the scaling factor. Not collective. Returns ------- float The scaling factor. See Also -------- setScale, slepc.RGGetScale :sources:`Source code at slepc4py/SLEPc/RG.pyx:336 ` """ ... def checkInside(self, a: Sequence[complex]) -> ArrayInt: """Determine if a set of given points are inside the region or not. Not collective. Parameters ---------- a The coordinates of the points. Returns ------- ArrayInt Computed result for each point (1=inside, 0=on the contour, -1=outside). Notes ----- If a scaling factor was set, the points are scaled before checking. See Also -------- setScale, setComplement, slepc.RGCheckInside :sources:`Source code at slepc4py/SLEPc/RG.pyx:355 ` """ ... def computeContour(self, n: int) -> list[complex]: """Compute points on the contour of the region. Not collective. Compute the coordinates of several points lying on the contour of the region. Parameters ---------- n The number of points to compute. Returns ------- list of complex Computed points. See Also -------- computeBoundingBox, setScale, slepc.RGComputeContour :sources:`Source code at slepc4py/SLEPc/RG.pyx:395 ` """ ... def computeBoundingBox(self) -> tuple[float, float, float, float]: """Compute box containing the region. Not collective. Determine the endpoints of a rectangle in the complex plane that contains the region. Returns ------- a: float The left endpoint of the bounding box in the real axis. b: float The right endpoint of the bounding box in the real axis. c: float The bottom endpoint of the bounding box in the imaginary axis. d: float The top endpoint of the bounding box in the imaginary axis. See Also -------- computeContour, setScale, slepc.RGComputeBoundingBox :sources:`Source code at slepc4py/SLEPc/RG.pyx:430 ` """ ... def canUseConjugates(self, realmats: bool = True) -> bool: """Half of integration points can be avoided (use their conjugates). Not collective. Used in contour integral methods to determine whether half of integration points can be avoided (use their conjugates). Parameters ---------- realmats ``True`` if the problem matrices are real. Returns ------- bool Whether it is possible to use conjugates. Notes ----- If some integration points are the conjugates of other points, then the associated computational cost can be saved. This depends on the problem matrices being real and also the region being symmetric with respect to the horizontal axis. The result is ``false`` if using real arithmetic or in the case of a flat region (height equal to zero). See Also -------- isAxisymmetric, slepc.RGCanUseConjugates :sources:`Source code at slepc4py/SLEPc/RG.pyx:458 ` """ ... def computeQuadrature(self, quad: QuadRule, n: int) -> tuple[ArrayScalar, ArrayScalar, ArrayScalar]: """Compute the values of the parameters used in a quadrature rule. Not collective. Compute the values of the parameters used in a quadrature rule for a contour integral around the boundary of the region. Parameters ---------- quad The type of quadrature. n The number of quadrature points to compute. Returns ------- z: ArrayScalar Quadrature points. zn: ArrayScalar Normalized quadrature points. w: ArrayScalar Quadrature weights. Notes ----- In complex scalars, the values returned in ``z`` are often the same as those computed by `computeContour()`, but this is not the case in real scalars where all output arguments are real. The computed values change for different quadrature rules. See Also -------- computeContour, slepc.RGComputeQuadrature :sources:`Source code at slepc4py/SLEPc/RG.pyx:494 ` """ ... def setEllipseParameters(self, center: Scalar, radius: float, vscale: float | None = None) -> None: """Set the parameters defining the ellipse region. Logically collective. Parameters ---------- center The center. radius The radius. vscale The vertical scale. Notes ----- When PETSc is built with real scalars, the center is restricted to a real value. See Also -------- getEllipseParameters, slepc.RGEllipseSetParameters :sources:`Source code at slepc4py/SLEPc/RG.pyx:542 ` """ ... def getEllipseParameters(self) -> tuple[Scalar, float, float]: """Get the parameters that define the ellipse region. Not collective. Returns ------- center: Scalar The center. radius: float The radius. vscale: float The vertical scale. See Also -------- setEllipseParameters, slepc.RGEllipseGetParameters :sources:`Source code at slepc4py/SLEPc/RG.pyx:572 ` """ ... def setIntervalEndpoints(self, a: float, b: float, c: float, d: float) -> None: """Set the parameters defining the interval region. Logically collective. Parameters ---------- a The left endpoint in the real axis. b The right endpoint in the real axis. c The bottom endpoint in the imaginary axis. d The top endpoint in the imaginary axis. Notes ----- The region is defined as :math:`[a,b] x [c,d]`. Particular cases are an interval on the real axis (:math:`c=d=0`), similarly for the imaginary axis (:math:`a=b=0`), the whole complex plane (:math:`a=-\infty,b=\infty,c=-\infty,d=\infty`), and so on. When PETSc is built with real scalars, the region must be symmetric with respect to the real axis. See Also -------- getIntervalEndpoints, slepc.RGIntervalSetEndpoints :sources:`Source code at slepc4py/SLEPc/RG.pyx:597 ` """ ... def getIntervalEndpoints(self) -> tuple[float, float, float, float]: """Get the parameters that define the interval region. Not collective. Returns ------- a: float The left endpoint in the real axis. b: float The right endpoint in the real axis. c: float The bottom endpoint in the imaginary axis. d: float The top endpoint in the imaginary axis. See Also -------- setIntervalEndpoints, slepc.RGIntervalGetEndpoints :sources:`Source code at slepc4py/SLEPc/RG.pyx:634 ` """ ... def setPolygonVertices(self, v: Sequence[float] | Sequence[Scalar]) -> None: """Set the vertices that define the polygon region. Logically collective. Parameters ---------- v The vertices. See Also -------- getPolygonVertices, slepc.RGPolygonSetVertices :sources:`Source code at slepc4py/SLEPc/RG.pyx:662 ` """ ... def getPolygonVertices(self) -> ArrayComplex: """Get the parameters that define the interval region. Not collective. Returns ------- ArrayComplex The vertices. See Also -------- setPolygonVertices, slepc.RGPolygonGetVertices :sources:`Source code at slepc4py/SLEPc/RG.pyx:690 ` """ ... def setRingParameters(self, center: Scalar, radius: float, vscale: float, start_ang: float, end_ang: float, width: float) -> None: """Set the parameters defining the ring region. Logically collective. Parameters ---------- center The center. radius The radius. vscale The vertical scale. start_ang The right-hand side angle. end_ang The left-hand side angle. width The width of the ring. Notes ----- The values of ``center``, ``radius`` and ``vscale`` have the same meaning as in the ellipse region. The ``start_ang`` and ``end_ang`` define the span of the ring (by default it is the whole ring), while the ``width`` is the separation between the two concentric ellipses (above and below the radius by ``width/2``). The start and end angles are expressed as a fraction of the circumference. The allowed range is :math:`[0,\dots,1]`, with ``0`` corresponding to 0 radians, ``0.25`` to :math:`\pi/2` radians, and so on. It is allowed to have ``start_ang`` > ``end_ang``, in which case the ring region crosses over the zero angle. When PETSc is built with real scalars, the center is restricted to a real value, and the start and end angles must be such that the region is symmetric with respect to the real axis. See Also -------- getRingParameters, slepc.RGRingSetParameters :sources:`Source code at slepc4py/SLEPc/RG.pyx:716 ` """ ... def getRingParameters(self) -> tuple[Scalar, float, float, float, float, float]: """Get the parameters that define the ring region. Not collective. Returns ------- center: Scalar The center. radius: float The radius. vscale: float The vertical scale. start_ang: float The right-hand side angle. end_ang: float The left-hand side angle. width: float The width of the ring. See Also -------- setRingParameters, slepc.RGRingGetParameters :sources:`Source code at slepc4py/SLEPc/RG.pyx:775 ` """ ... @property def complement(self) -> bool: """If the region is the complement of the specified one. :sources:`Source code at slepc4py/SLEPc/RG.pyx:811 ` """ ... @property def scale(self) -> float: """The scaling factor to be used. :sources:`Source code at slepc4py/SLEPc/RG.pyx:818 ` """ ... class EPS(Object): """Eigenvalue Problem Solver. The Eigenvalue Problem Solver (`EPS`) is the object provided by slepc4py for specifying a linear eigenvalue problem, either in standard or generalized form. It provides uniform and efficient access to all of the linear eigensolvers included in the package. """ class Type: """EPS type. Native eigenvalue solvers. - `POWER`: Power Iteration, Inverse Iteration, RQI. - `SUBSPACE`: Subspace Iteration. - `ARNOLDI`: Arnoldi. - `LANCZOS`: Lanczos. - `KRYLOVSCHUR`: Krylov-Schur (default). - `GD`: Generalized Davidson. - `JD`: Jacobi-Davidson. - `RQCG`: Rayleigh Quotient Conjugate Gradient. - `LOBPCG`: Locally Optimal Block Preconditioned Conjugate Gradient. - `CISS`: Contour Integral Spectrum Slicing. - `LYAPII`: Lyapunov inverse iteration. Wrappers to external eigensolvers (should be enabled during installation of SLEPc). - `LAPACK`: Sequential dense eigensolver. - `ARPACK`: Iterative Krylov-based eigensolver. - `BLOPEX`: Implementation of LOBPCG. - `PRIMME`: Iterative eigensolvers of Davidson type. - `FEAST`: Contour integral eigensolver. - `SCALAPACK`: Parallel dense eigensolver for symmetric problems. - `ELPA`: Parallel dense eigensolver for symmetric problems. - `ELEMENTAL`: Parallel dense eigensolver for symmetric problems. - `EVSL`: Iterative eigensolver based on polynomial filters. - `CHASE`: Subspace iteration accelerated with polynomials. See Also -------- slepc.EPSType """ POWER: str = _def(str, 'POWER') #: Object ``POWER`` of type :class:`str` SUBSPACE: str = _def(str, 'SUBSPACE') #: Object ``SUBSPACE`` of type :class:`str` ARNOLDI: str = _def(str, 'ARNOLDI') #: Object ``ARNOLDI`` of type :class:`str` LANCZOS: str = _def(str, 'LANCZOS') #: Object ``LANCZOS`` of type :class:`str` KRYLOVSCHUR: str = _def(str, 'KRYLOVSCHUR') #: Object ``KRYLOVSCHUR`` of type :class:`str` GD: str = _def(str, 'GD') #: Object ``GD`` of type :class:`str` JD: str = _def(str, 'JD') #: Object ``JD`` of type :class:`str` RQCG: str = _def(str, 'RQCG') #: Object ``RQCG`` of type :class:`str` LOBPCG: str = _def(str, 'LOBPCG') #: Object ``LOBPCG`` of type :class:`str` CISS: str = _def(str, 'CISS') #: Object ``CISS`` of type :class:`str` LYAPII: str = _def(str, 'LYAPII') #: Object ``LYAPII`` of type :class:`str` LAPACK: str = _def(str, 'LAPACK') #: Object ``LAPACK`` of type :class:`str` ARPACK: str = _def(str, 'ARPACK') #: Object ``ARPACK`` of type :class:`str` BLOPEX: str = _def(str, 'BLOPEX') #: Object ``BLOPEX`` of type :class:`str` PRIMME: str = _def(str, 'PRIMME') #: Object ``PRIMME`` of type :class:`str` FEAST: str = _def(str, 'FEAST') #: Object ``FEAST`` of type :class:`str` SCALAPACK: str = _def(str, 'SCALAPACK') #: Object ``SCALAPACK`` of type :class:`str` ELPA: str = _def(str, 'ELPA') #: Object ``ELPA`` of type :class:`str` ELEMENTAL: str = _def(str, 'ELEMENTAL') #: Object ``ELEMENTAL`` of type :class:`str` EVSL: str = _def(str, 'EVSL') #: Object ``EVSL`` of type :class:`str` CHASE: str = _def(str, 'CHASE') #: Object ``CHASE`` of type :class:`str` class ProblemType: """EPS problem type. - `HEP`: Hermitian eigenproblem. - `NHEP`: Non-Hermitian eigenproblem. - `GHEP`: Generalized Hermitian eigenproblem. - `GNHEP`: Generalized Non-Hermitian eigenproblem. - `PGNHEP`: Generalized Non-Hermitian eigenproblem with positive definite :math:`B`. - `GHIEP`: Generalized Hermitian-indefinite eigenproblem. - `BSE`: Structured Bethe-Salpeter eigenproblem. - `HAMILT`: Hamiltonian eigenproblem. See Also -------- slepc.EPSProblemType """ HEP: int = _def(int, 'HEP') #: Constant ``HEP`` of type :class:`int` NHEP: int = _def(int, 'NHEP') #: Constant ``NHEP`` of type :class:`int` GHEP: int = _def(int, 'GHEP') #: Constant ``GHEP`` of type :class:`int` GNHEP: int = _def(int, 'GNHEP') #: Constant ``GNHEP`` of type :class:`int` PGNHEP: int = _def(int, 'PGNHEP') #: Constant ``PGNHEP`` of type :class:`int` GHIEP: int = _def(int, 'GHIEP') #: Constant ``GHIEP`` of type :class:`int` BSE: int = _def(int, 'BSE') #: Constant ``BSE`` of type :class:`int` HAMILT: int = _def(int, 'HAMILT') #: Constant ``HAMILT`` of type :class:`int` class Extraction: """EPS extraction technique. - `RITZ`: Standard Rayleigh-Ritz extraction. - `HARMONIC`: Harmonic extraction. - `HARMONIC_RELATIVE`: Harmonic extraction relative to the eigenvalue. - `HARMONIC_RIGHT`: Harmonic extraction for rightmost eigenvalues. - `HARMONIC_LARGEST`: Harmonic extraction for largest magnitude (without target). - `REFINED`: Refined extraction. - `REFINED_HARMONIC`: Refined harmonic extraction. See Also -------- slepc.EPSExtraction """ RITZ: int = _def(int, 'RITZ') #: Constant ``RITZ`` of type :class:`int` HARMONIC: int = _def(int, 'HARMONIC') #: Constant ``HARMONIC`` of type :class:`int` HARMONIC_RELATIVE: int = _def(int, 'HARMONIC_RELATIVE') #: Constant ``HARMONIC_RELATIVE`` of type :class:`int` HARMONIC_RIGHT: int = _def(int, 'HARMONIC_RIGHT') #: Constant ``HARMONIC_RIGHT`` of type :class:`int` HARMONIC_LARGEST: int = _def(int, 'HARMONIC_LARGEST') #: Constant ``HARMONIC_LARGEST`` of type :class:`int` REFINED: int = _def(int, 'REFINED') #: Constant ``REFINED`` of type :class:`int` REFINED_HARMONIC: int = _def(int, 'REFINED_HARMONIC') #: Constant ``REFINED_HARMONIC`` of type :class:`int` class Balance: """EPS type of balancing used for non-Hermitian problems. - `NONE`: None. - `ONESIDE`: One-sided balancing. - `TWOSIDE`: Two-sided balancing. - `USER`: User-provided balancing matrices. See Also -------- slepc.EPSBalance """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` ONESIDE: int = _def(int, 'ONESIDE') #: Constant ``ONESIDE`` of type :class:`int` TWOSIDE: int = _def(int, 'TWOSIDE') #: Constant ``TWOSIDE`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class ErrorType: """EPS error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.EPSErrorType """ ABSOLUTE: int = _def(int, 'ABSOLUTE') #: Constant ``ABSOLUTE`` of type :class:`int` RELATIVE: int = _def(int, 'RELATIVE') #: Constant ``RELATIVE`` of type :class:`int` BACKWARD: int = _def(int, 'BACKWARD') #: Constant ``BACKWARD`` of type :class:`int` class Which: """EPS desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in an interval. - `USER`: User defined selection. See Also -------- slepc.EPSWhich """ LARGEST_MAGNITUDE: int = _def(int, 'LARGEST_MAGNITUDE') #: Constant ``LARGEST_MAGNITUDE`` of type :class:`int` SMALLEST_MAGNITUDE: int = _def(int, 'SMALLEST_MAGNITUDE') #: Constant ``SMALLEST_MAGNITUDE`` of type :class:`int` LARGEST_REAL: int = _def(int, 'LARGEST_REAL') #: Constant ``LARGEST_REAL`` of type :class:`int` SMALLEST_REAL: int = _def(int, 'SMALLEST_REAL') #: Constant ``SMALLEST_REAL`` of type :class:`int` LARGEST_IMAGINARY: int = _def(int, 'LARGEST_IMAGINARY') #: Constant ``LARGEST_IMAGINARY`` of type :class:`int` SMALLEST_IMAGINARY: int = _def(int, 'SMALLEST_IMAGINARY') #: Constant ``SMALLEST_IMAGINARY`` of type :class:`int` TARGET_MAGNITUDE: int = _def(int, 'TARGET_MAGNITUDE') #: Constant ``TARGET_MAGNITUDE`` of type :class:`int` TARGET_REAL: int = _def(int, 'TARGET_REAL') #: Constant ``TARGET_REAL`` of type :class:`int` TARGET_IMAGINARY: int = _def(int, 'TARGET_IMAGINARY') #: Constant ``TARGET_IMAGINARY`` of type :class:`int` ALL: int = _def(int, 'ALL') #: Constant ``ALL`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Conv: """EPS convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.EPSConv """ ABS: int = _def(int, 'ABS') #: Constant ``ABS`` of type :class:`int` REL: int = _def(int, 'REL') #: Constant ``REL`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Stop: """EPS stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. - `THRESHOLD`: Threshold stopping test. See Also -------- slepc.EPSStop """ BASIC: int = _def(int, 'BASIC') #: Constant ``BASIC`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` THRESHOLD: int = _def(int, 'THRESHOLD') #: Constant ``THRESHOLD`` of type :class:`int` class ConvergedReason: """EPS convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Lanczos-type method could not preserve symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.EPSConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` CONVERGED_USER: int = _def(int, 'CONVERGED_USER') #: Constant ``CONVERGED_USER`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` DIVERGED_SYMMETRY_LOST: int = _def(int, 'DIVERGED_SYMMETRY_LOST') #: Constant ``DIVERGED_SYMMETRY_LOST`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` class PowerShiftType: """EPS Power shift type. - `CONSTANT`: Constant shift. - `RAYLEIGH`: Rayleigh quotient. - `WILKINSON`: Wilkinson shift. See Also -------- slepc.EPSPowerShiftType """ CONSTANT: int = _def(int, 'CONSTANT') #: Constant ``CONSTANT`` of type :class:`int` RAYLEIGH: int = _def(int, 'RAYLEIGH') #: Constant ``RAYLEIGH`` of type :class:`int` WILKINSON: int = _def(int, 'WILKINSON') #: Constant ``WILKINSON`` of type :class:`int` class KrylovSchurBSEType: """EPS Krylov-Schur method for BSE problems. - `SHAO`: Lanczos recurrence for H square. - `GRUNING`: Lanczos recurrence for H. - `PROJECTEDBSE`: Lanczos where the projected problem has BSE structure. See Also -------- slepc.EPSKrylovSchurBSEType """ SHAO: int = _def(int, 'SHAO') #: Constant ``SHAO`` of type :class:`int` GRUNING: int = _def(int, 'GRUNING') #: Constant ``GRUNING`` of type :class:`int` PROJECTEDBSE: int = _def(int, 'PROJECTEDBSE') #: Constant ``PROJECTEDBSE`` of type :class:`int` class LanczosReorthogType: """EPS Lanczos reorthogonalization type. - `LOCAL`: Local reorthogonalization only. - `FULL`: Full reorthogonalization. - `SELECTIVE`: Selective reorthogonalization. - `PERIODIC`: Periodic reorthogonalization. - `PARTIAL`: Partial reorthogonalization. - `DELAYED`: Delayed reorthogonalization. See Also -------- slepc.EPSLanczosReorthogType """ LOCAL: int = _def(int, 'LOCAL') #: Constant ``LOCAL`` of type :class:`int` FULL: int = _def(int, 'FULL') #: Constant ``FULL`` of type :class:`int` SELECTIVE: int = _def(int, 'SELECTIVE') #: Constant ``SELECTIVE`` of type :class:`int` PERIODIC: int = _def(int, 'PERIODIC') #: Constant ``PERIODIC`` of type :class:`int` PARTIAL: int = _def(int, 'PARTIAL') #: Constant ``PARTIAL`` of type :class:`int` DELAYED: int = _def(int, 'DELAYED') #: Constant ``DELAYED`` of type :class:`int` class CISSQuadRule: """EPS CISS quadrature rule. - `TRAPEZOIDAL`: Trapezoidal rule. - `CHEBYSHEV`: Chebyshev points. See Also -------- slepc.EPSCISSQuadRule """ TRAPEZOIDAL: int = _def(int, 'TRAPEZOIDAL') #: Constant ``TRAPEZOIDAL`` of type :class:`int` CHEBYSHEV: int = _def(int, 'CHEBYSHEV') #: Constant ``CHEBYSHEV`` of type :class:`int` class CISSExtraction: """EPS CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. See Also -------- slepc.EPSCISSExtraction """ RITZ: int = _def(int, 'RITZ') #: Constant ``RITZ`` of type :class:`int` HANKEL: int = _def(int, 'HANKEL') #: Constant ``HANKEL`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the EPS data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.EPSView :sources:`Source code at slepc4py/SLEPc/EPS.pyx:351 ` """ ... def destroy(self) -> Self: """Destroy the EPS object. Collective. See Also -------- slepc.EPSDestroy :sources:`Source code at slepc4py/SLEPc/EPS.pyx:370 ` """ ... def reset(self) -> None: """Reset the EPS object. Collective. See Also -------- slepc.EPSReset :sources:`Source code at slepc4py/SLEPc/EPS.pyx:384 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the EPS object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.EPSCreate :sources:`Source code at slepc4py/SLEPc/EPS.pyx:396 ` """ ... def setType(self, eps_type: Type | str) -> None: """Set the particular solver to be used in the EPS object. Logically collective. Parameters ---------- eps_type The solver to be used. Notes ----- The default is `KRYLOVSCHUR`. Normally, it is best to use `setFromOptions()` and then set the EPS type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.EPSSetType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:417 ` """ ... def getType(self) -> str: """Get the EPS type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.EPSGetType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:444 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all EPS options in the database. Not collective. Returns ------- str The prefix string set for this EPS object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.EPSGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/EPS.pyx:463 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all EPS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all EPS option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different EPS contexts, one could call:: E1.setOptionsPrefix("eig1_") E2.setOptionsPrefix("eig2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.EPSGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/EPS.pyx:482 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all EPS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all EPS option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.EPSAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/EPS.pyx:513 ` """ ... def setFromOptions(self) -> None: """Set EPS options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.EPSSetFromOptions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:532 ` """ ... def getProblemType(self) -> ProblemType: """Get the problem type from the EPS object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.EPSGetProblemType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:553 ` """ ... def setProblemType(self, problem_type: ProblemType) -> None: """Set the type of the eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function must be used to instruct SLEPc to exploit symmetry or other kind of structure. If no problem type is specified, by default a non-Hermitian problem is assumed (either standard or generalized). If the user knows that the problem is Hermitian (i.e., :math:`A=A^*`) or generalized Hermitian (i.e., :math:`A=A^*`, :math:`B=B^*`, and :math:`B` positive definite) then it is recommended to set the problem type so that eigensolver can exploit these properties. If the user does not call this function, the solver will use a reasonable guess. For structured problem types such as `BSE`, the matrices passed in via `setOperators()` must have been created with the corresponding helper function, i.e., `createMatBSE()`. See Also -------- setOperators, createMatBSE, getProblemType, slepc.EPSSetProblemType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:572 ` """ ... def isGeneralized(self) -> bool: """Tell if the EPS object corresponds to a generalized eigenproblem. Not collective. Returns ------- bool ``True`` if the problem is generalized. See Also -------- isHermitian, isPositive, isStructured, slepc.EPSIsGeneralized :sources:`Source code at slepc4py/SLEPc/EPS.pyx:608 ` """ ... def isHermitian(self) -> bool: """Tell if the EPS object corresponds to a Hermitian eigenproblem. Not collective. Returns ------- bool ``True`` if the problem is Hermitian. See Also -------- isGeneralized, isPositive, isStructured, slepc.EPSIsHermitian :sources:`Source code at slepc4py/SLEPc/EPS.pyx:627 ` """ ... def isPositive(self) -> bool: """Eigenproblem requiring a positive (semi-) definite matrix :math:`B`. Not collective. Tell if the EPS corresponds to an eigenproblem requiring a positive (semi-) definite matrix :math:`B`. Returns ------- bool ``True`` if the problem is positive (semi-) definite. See Also -------- isGeneralized, isHermitian, isStructured, slepc.EPSIsPositive :sources:`Source code at slepc4py/SLEPc/EPS.pyx:646 ` """ ... def isStructured(self) -> bool: """Tell if the EPS object corresponds to a structured eigenvalue problem. Not collective. Returns ------- bool ``True`` if the problem is structured. Notes ----- The result will be ``True`` if the problem type has been set to some structured type such as `BSE`. This is independent of whether the input matrix has been built with a certain structure with a helper function. See Also -------- isGeneralized, isHermitian, isPositive, slepc.EPSIsStructured :sources:`Source code at slepc4py/SLEPc/EPS.pyx:668 ` """ ... def getBalance(self) -> tuple[Balance, int, float]: """Get the balancing type used by the EPS, and the associated parameters. Not collective. Returns ------- balance: Balance The balancing method. iterations: int Number of iterations of the balancing algorithm. cutoff: float Cutoff value. See Also -------- setBalance, slepc.EPSGetBalance :sources:`Source code at slepc4py/SLEPc/EPS.pyx:693 ` """ ... def setBalance(self, balance: Balance | None = None, iterations: int | None = None, cutoff: float | None = None) -> None: """Set the balancing technique to be used by the eigensolver. Logically collective. Parameters ---------- balance The balancing method. iterations Number of iterations of the balancing algorithm. cutoff Cutoff value. Notes ----- When balancing is enabled, the solver works implicitly with matrix :math:`DAD^{-1}`, where :math:`D` is an appropriate diagonal matrix. This improves the accuracy of the computed results in some cases. Balancing makes sense only for non-Hermitian problems when the required precision is high (i.e., with a small tolerance). By default, balancing is disabled. The two-sided method is much more effective than the one-sided counterpart, but it requires the system matrices to have the ``Mat.multTranspose()`` operation defined. The parameter ``iterations`` is the number of iterations performed by the method. The ``cutoff`` value is used only in the two-side variant. See Also -------- setBalance, slepc.EPSGetBalance :sources:`Source code at slepc4py/SLEPc/EPS.pyx:718 ` """ ... def getExtraction(self) -> Extraction: """Get the extraction type used by the EPS object. Not collective. Returns ------- Extraction The method of extraction. See Also -------- setExtraction, slepc.EPSGetExtraction :sources:`Source code at slepc4py/SLEPc/EPS.pyx:768 ` """ ... def setExtraction(self, extraction: Extraction) -> None: """Set the extraction type used by the eigensolver. Logically collective. Parameters ---------- extraction The extraction method to be used by the solver. Notes ----- Not all eigensolvers support all types of extraction. By default, a standard Rayleigh-Ritz extraction is used. Other extractions may be useful when computing interior eigenvalues. Harmonic-type extractions are used in combination with a *target*, see `setTarget()`. See Also -------- getExtraction, setTarget, slepc.EPSSetExtraction :sources:`Source code at slepc4py/SLEPc/EPS.pyx:787 ` """ ... def getWhichEigenpairs(self) -> Which: """Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.EPSGetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/EPS.pyx:815 ` """ ... def setWhichEigenpairs(self, which: Which) -> None: """Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in EPS account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `EPS.Which.LARGEST_IMAGINARY` and `EPS.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `EPS.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `EPS.Which.ALL` is intended for use in combination with an interval (see `setInterval()`), when all eigenvalues within the interval are requested, or in the context of the `EPS.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- setTarget, setInterval, getWhichEigenpairs, slepc.EPSSetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/EPS.pyx:834 ` """ ... def getThreshold(self) -> tuple[float, bool]: """Get the threshold used in the threshold stopping test. Not collective. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. See Also -------- setThreshold, slepc.EPSGetThreshold :sources:`Source code at slepc4py/SLEPc/EPS.pyx:871 ` """ ... def setThreshold(self, thres: float, rel: bool = False) -> None: """Set the threshold used in the threshold stopping test. Logically collective. Parameters ---------- thres The threshold. rel Whether the threshold is relative or not. Notes ----- This function internally sets a special stopping test based on the threshold, where eigenvalues are computed in sequence until one of the computed eigenvalues is below/above the threshold (depending on whether largest or smallest eigenvalues are computed). The details are given in `slepc.EPSSetThreshold`. See Also -------- setStoppingTest, getThreshold, slepc.EPSSetThreshold :sources:`Source code at slepc4py/SLEPc/EPS.pyx:893 ` """ ... def getTarget(self) -> Scalar: """Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.EPSGetTarget :sources:`Source code at slepc4py/SLEPc/EPS.pyx:922 ` """ ... def setTarget(self, target: Scalar) -> None: """Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, slepc.EPSSetTarget :sources:`Source code at slepc4py/SLEPc/EPS.pyx:945 ` """ ... def getInterval(self) -> tuple[float, float]: """Get the computational interval for spectrum slicing. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. Notes ----- If the interval was not set by the user, then zeros are returned. See Also -------- setInterval, slepc.EPSGetInterval :sources:`Source code at slepc4py/SLEPc/EPS.pyx:972 ` """ ... def setInterval(self, inta: float, intb: float) -> None: """Set the computational interval for spectrum slicing. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- Spectrum slicing is a technique employed for computing all eigenvalues of symmetric eigenproblems in a given interval. This function provides the interval to be considered. It must be used in combination with `EPS.Which.ALL`, see `setWhichEigenpairs()`. A computational interval is also needed when using polynomial filters, see `slepc.STFILTER`. See Also -------- getInterval, setWhichEigenpairs, slepc.EPSSetInterval, slepc.STFILTER :sources:`Source code at slepc4py/SLEPc/EPS.pyx:998 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and max. iter. count used for convergence tests. Not collective. Get the tolerance and iteration limit used by the default EPS convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.EPSGetTolerances :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1032 ` """ ... def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """Set the tolerance and max. iter. used by the default EPS convergence tests. Logically collective. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.EPSSetTolerances :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1057 ` """ ... def getTwoSided(self) -> bool: """Get the flag indicating if a two-sided variant of the algorithm is being used. Not collective. Returns ------- bool Whether the two-sided variant is to be used or not. See Also -------- setTwoSided, slepc.EPSGetTwoSided :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1085 ` """ ... def setTwoSided(self, twosided: bool) -> None: """Set to use a two-sided variant that also computes left eigenvectors. Logically collective. Parameters ---------- twosided Whether the two-sided variant is to be used or not. Notes ----- If the user sets ``twosided`` to ``True`` then the solver uses a variant of the algorithm that computes both right and left eigenvectors. This is usually much more costly. This option is not available in all solvers. When using two-sided solvers, the problem matrices must have both the ``Mat.mult`` and ``Mat.multTranspose`` operations defined. See Also -------- getTwoSided, getLeftEigenvector, slepc.EPSSetTwoSided :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1104 ` """ ... def getPurify(self) -> bool: """Get the flag indicating whether purification is activated or not. Not collective. Returns ------- bool Whether purification is activated or not. See Also -------- setPurify, slepc.EPSGetPurify :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1132 ` """ ... def setPurify(self, purify: bool = True) -> None: """Set (toggle) eigenvector purification. Logically collective. Parameters ---------- purify ``True`` to activate purification (default). Notes ----- By default, eigenvectors of generalized symmetric eigenproblems are purified in order to purge directions in the nullspace of matrix :math:`B`. If the user knows that :math:`B` is non-singular, then purification can be safely deactivated and some computational cost is avoided (this is particularly important in interval computations). See Also -------- getPurify, setInterval, slepc.EPSSetPurify :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1151 ` """ ... def getConvergenceTest(self) -> Conv: """Get how to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.EPSGetConvergenceTest :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1177 ` """ ... def setConvergenceTest(self, conv: Conv) -> None: """Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.EPSSetConvergenceTest :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1197 ` """ ... def getTrueResidual(self) -> bool: """Get the flag indicating if true residual must be computed explicitly. Not collective. Returns ------- bool Whether the solver computes true residuals or not. See Also -------- setTrueResidual, slepc.EPSGetTrueResidual :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1216 ` """ ... def setTrueResidual(self, trueres: bool) -> None: """Set if the solver must compute the true residual explicitly or not. Logically collective. Parameters ---------- trueres Whether the solver computes true residuals or not. See Also -------- getTrueResidual, slepc.EPSSetTrueResidual :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1235 ` """ ... def getTrackAll(self) -> bool: """Get the flag indicating if all residual norms must be computed or not. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.EPSGetTrackAll :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1253 ` """ ... def setTrackAll(self, trackall: bool) -> None: """Set if the solver must compute the residual of all approximate eigenpairs. Logically collective. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.EPSSetTrackAll :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1272 ` """ ... def getDimensions(self) -> tuple[int, int, int]: """Get number of eigenvalues to compute and the dimension of the subspace. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.EPSGetDimensions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1290 ` """ ... def setDimensions(self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set number of eigenvalues to compute and the dimension of the subspace. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. When computing all eigenvalues in an interval, see `setInterval()`, these parameters lose relevance, and tuning must be done with `setKrylovSchurDimensions()`. See Also -------- getDimensions, setKrylovSchurDimensions, slepc.EPSSetDimensions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1315 ` """ ... def getST(self) -> ST: """Get the spectral transformation object associated to the eigensolver. Not collective. Returns ------- ST The spectral transformation. See Also -------- setST, slepc.EPSGetST :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1370 ` """ ... def setST(self, st: ST) -> None: """Set a spectral transformation object associated to the eigensolver. Collective. Parameters ---------- st The spectral transformation. See Also -------- getST, slepc.EPSSetST :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1390 ` """ ... def getBV(self) -> BV: """Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.EPSGetBV :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1407 ` """ ... def setBV(self, bv: BV) -> None: """Set a basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.EPSSetBV :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1427 ` """ ... def getDS(self) -> DS: """Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.EPSGetDS :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1444 ` """ ... def setDS(self, ds: DS) -> None: """Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.EPSSetDS :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1464 ` """ ... def getRG(self) -> RG: """Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.EPSGetRG :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1481 ` """ ... def setRG(self, rg: RG) -> None: """Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.EPSSetRG :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1501 ` """ ... def getOperators(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """Get the matrices associated with the eigenvalue problem. Collective. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the eigensystem. B: petsc4py.PETSc.Mat The second matrix in the case of generalized eigenproblems. See Also -------- setOperators, slepc.EPSGetOperators :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1518 ` """ ... def setOperators(self, A: Mat, B: Mat | None = None) -> None: """Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- A The matrix associated with the eigensystem. B The second matrix in the case of generalized eigenproblems; if not provided, a standard eigenproblem is assumed. Notes ----- It must be called before `setUp()`. If it is called again after `setUp()` and the matrix sizes have changed then the `EPS` object is reset. For structured eigenproblem types such as `BSE`, see `setProblemType()`, the provided matrices must have been created with the corresponding helper function, i.e., `createMatBSE()`. See Also -------- getOperators, solve, setUp, reset, setProblemType, slepc.EPSSetOperators :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1545 ` """ ... def setDeflationSpace(self, space: Vec | list[Vec]) -> None: """Set vectors to form a basis of the deflation space. Collective. Parameters ---------- space Set of basis vectors of the deflation space. Notes ----- When a deflation space is given, the eigensolver seeks the eigensolution in the restriction of the problem to the orthogonal complement of this space. This can be used for instance in the case that an invariant subspace is known beforehand (such as the nullspace of the matrix). These vectors do not persist from one `solve()` call to the other, so the deflation space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. See Also -------- setInitialSpace, slepc.EPSSetDeflationSpace :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1576 ` """ ... def setInitialSpace(self, space: Vec | list[Vec]) -> None: """Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space Set of basis vectors of the initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. But other solvers such as `SUBSPACE` are able to make use of the whole initial subspace as an initial guess. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setDeflationSpace, setLeftInitialSpace, slepc.EPSSetInitialSpace :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1614 ` """ ... def setLeftInitialSpace(self, space: Vec | list[Vec]) -> None: """Set a left initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space Set of basis vectors of the left initial space. Notes ----- Left initial vectors are used to initiate the left search space in two-sided eigensolvers. Users should pass here an approximation of the left eigenspace, if available. The same comments in `setInitialSpace()` are applicable here. See Also -------- setInitialSpace, setTwoSided, slepc.EPSSetLeftInitialSpace :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1652 ` """ ... def setStoppingTest(self, stopping: EPSStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.EPSSetStoppingTestFunction :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1684 ` """ ... def getStoppingTest(self) -> EPSStoppingFunction: """Get the stopping test function. Not collective. Returns ------- EPSStoppingFunction The stopping test function. See Also -------- setStoppingTest :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1708 ` """ ... def setArbitrarySelection(self, arbitrary: EPSArbitraryFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set an arbitrary selection criterion function. Logically collective. Set a function to look for eigenvalues according to an arbitrary selection criterion. This criterion can be based on a computation involving the current eigenvector approximation. See Also -------- getArbitrarySelection, slepc.EPSSetArbitrarySelection :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1725 ` """ ... def getArbitrarySelection(self) -> EPSArbitraryFunction: """Get the arbitrary selection function. Not collective. Returns ------- EPSArbitraryFunction The arbitrary selection function. See Also -------- setArbitrarySelection :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1754 ` """ ... def setEigenvalueComparison(self, comparison: EPSEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `EPS.Which.USER`. See Also -------- getEigenvalueComparison, slepc.EPSSetEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1771 ` """ ... def getEigenvalueComparison(self) -> EPSEigenvalueComparison: """Get the eigenvalue comparison function. Not collective. Returns ------- EPSEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1801 ` """ ... def setMonitor(self, monitor: EPSMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.EPSMonitorSet :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1818 ` """ ... def getMonitor(self) -> EPSMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- EPSMonitorFunction The list of monitor functions. See Also -------- setMonitor :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1843 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for an `EPS` object. Logically collective. See Also -------- slepc.EPSMonitorCancel :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1860 ` """ ... def setUp(self) -> None: """Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This includes the setup of the internal `ST` object. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, setInitialSpace, setDeflationSpace, slepc.EPSSetUp :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1875 ` """ ... def solve(self) -> None: """Solve the eigensystem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.EPSSolve :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1897 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.EPSGetIterationNumber :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1919 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.EPSGetConvergedReason :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1941 ` """ ... def getConverged(self) -> int: """Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.EPSGetConverged :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1960 ` """ ... def getEigenvalue(self, i: int) -> Scalar: """Get the i-th eigenvalue as computed by `solve()`. Not collective. Parameters ---------- i Index of the solution to be obtained. Returns ------- Scalar The computed eigenvalue. It will be a real variable in case of a Hermitian or generalized Hermitian eigenproblem. Otherwise it will be a complex variable (possibly with zero imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetEigenvalue :sources:`Source code at slepc4py/SLEPc/EPS.pyx:1986 ` """ ... def getEigenvector(self, i: int, Vr: Vec | None = None, Vi: Vec | None = None) -> None: """Get the i-th right eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The 2-norm of the eigenvector is one unless the problem is generalized Hermitian. In this case the eigenvector is normalized with respect to the norm defined by the B matrix. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetEigenvector :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2024 ` """ ... def getLeftEigenvector(self, i: int, Wr: Vec | None = None, Wi: Vec | None = None) -> None: """Get the i-th left eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Wr Placeholder for the returned left eigenvector (real part). Wi Placeholder for the returned left eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigensolutions are indexed according to the ordering criterion established with `setWhichEigenpairs()`. Left eigenvectors are available only if the twosided flag was set with `setTwoSided()`. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetLeftEigenvector :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2058 ` """ ... def getEigenpair(self, i: int, Vr: Vec | None = None, Vi: Vec | None = None) -> Scalar: """Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- e: Scalar The computed eigenvalue. It will be a real variable in case of a Hermitian or generalized Hermitian eigenproblem. Otherwise it will be a complex variable (possibly with zero imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The 2-norm of the eigenvector is one unless the problem is generalized Hermitian. In this case the eigenvector is normalized with respect to the norm defined by the B matrix. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.EPSGetEigenpair :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2090 ` """ ... def getInvariantSubspace(self) -> list[Vec]: """Get an orthonormal basis of the computed invariant subspace. Collective. Returns ------- list of petsc4py.PETSc.Vec Basis of the invariant subspace. Notes ----- This function should be called after `solve()` has finished. The returned vectors span an invariant subspace associated with the computed eigenvalues. An invariant subspace :math:`X` of :math:`A` satisfies :math:`A x \in X`, for all :math:`x \in X` (a similar definition applies for generalized eigenproblems). See Also -------- getEigenpair, getConverged, solve, slepc.EPSGetInvariantSubspace :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2140 ` """ ... def getErrorEstimate(self, i: int) -> float: """Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.EPSGetErrorEstimate :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2184 ` """ ... def computeError(self, i: int, etype: ErrorType | None = None) -> float: """Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|Ax-\lambda Bx\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). If the computation of left eigenvectors was enabled with `setTwoSided()`, then the error will be computed using the maximum of the value above and the left residual norm :math:`\|y^*A-\lambda y^*B\|_2`, where :math:`y` is the approximate left eigenvector. See Also -------- getErrorEstimate, setTwoSided, slepc.EPSComputeError :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2213 ` """ ... def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.EPSErrorView :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2256 ` """ ... def valuesView(self, viewer: Viewer | None = None) -> None: """Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.EPSValuesView :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2288 ` """ ... def vectorsView(self, viewer: Viewer | None = None) -> None: """Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.EPSVectorsView :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2307 ` """ ... def setPowerShiftType(self, shift: PowerShiftType) -> None: """Set the type of shifts used during the power iteration. Logically collective. This can be used to emulate the Rayleigh Quotient Iteration (RQI) method. Parameters ---------- shift The type of shift. Notes ----- This call is only relevant if the type was set to `EPS.Type.POWER` with `setType()`. By default, shifts are constant (`EPS.PowerShiftType.CONSTANT`) and the iteration is the simple power method (or inverse iteration if a shift-and-invert transformation is being used). A variable shift can be specified (`EPS.PowerShiftType.RAYLEIGH` or `EPS.PowerShiftType.WILKINSON`). In this case, the iteration behaves rather like a cubic converging method as RQI. See Also -------- getPowerShiftType, slepc.EPSPowerSetShiftType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2328 ` """ ... def getPowerShiftType(self) -> PowerShiftType: """Get the type of shifts used during the power iteration. Not collective. Returns ------- PowerShiftType The type of shift. See Also -------- setPowerShiftType, slepc.EPSPowerGetShiftType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2364 ` """ ... def setArnoldiDelayed(self, delayed: bool) -> None: """Set (toggle) delayed reorthogonalization in the Arnoldi iteration. Logically collective. Parameters ---------- delayed ``True`` if delayed reorthogonalization is to be used. Notes ----- This call is only relevant if the type was set to `EPS.Type.ARNOLDI` with `setType()`. Delayed reorthogonalization is an aggressive optimization for the Arnoldi eigensolver than may provide better scalability, but sometimes makes the solver converge more slowly compared to the default algorithm. See Also -------- getArnoldiDelayed, slepc.EPSArnoldiSetDelayed :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2383 ` """ ... def getArnoldiDelayed(self) -> bool: """Get the type of reorthogonalization used during the Arnoldi iteration. Not collective. Returns ------- bool ``True`` if delayed reorthogonalization is to be used. See Also -------- setArnoldiDelayed, slepc.EPSArnoldiGetDelayed :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2411 ` """ ... def setLanczosReorthogType(self, reorthog: LanczosReorthogType) -> None: """Set the type of reorthogonalization used during the Lanczos iteration. Logically collective. Parameters ---------- reorthog The type of reorthogonalization. Notes ----- This call is only relevant if the type was set to `EPS.Type.LANCZOS` with `setType()`. See Also -------- getLanczosReorthogType, slepc.EPSLanczosSetReorthog :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2430 ` """ ... def getLanczosReorthogType(self) -> LanczosReorthogType: """Get the type of reorthogonalization used during the Lanczos iteration. Not collective. Returns ------- LanczosReorthogType The type of reorthogonalization. See Also -------- setLanczosReorthogType, slepc.EPSLanczosGetReorthog :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2453 ` """ ... def setKrylovSchurBSEType(self, bse: KrylovSchurBSEType) -> None: """Set the Krylov-Schur variant used for BSE structured eigenproblems. Logically collective. Parameters ---------- bse The BSE method. Notes ----- This call is only relevant if the type was set to `EPS.Type.KRYLOVSCHUR` with `setType()` and the problem type to `EPS.ProblemType.BSE` with `setProblemType()`. See Also -------- createMatBSE, getKrylovSchurBSEType, slepc.EPSKrylovSchurSetBSEType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2475 ` """ ... def getKrylovSchurBSEType(self) -> KrylovSchurBSEType: """Get the method used for BSE structured eigenproblems (Krylov-Schur). Not collective. Returns ------- KrylovSchurBSEType The BSE method. See Also -------- setKrylovSchurBSEType, slepc.EPSKrylovSchurGetBSEType :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2499 ` """ ... def setKrylovSchurRestart(self, keep: float) -> None: """Set the restart parameter for the Krylov-Schur method. Logically collective. It is the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getKrylovSchurRestart, slepc.EPSKrylovSchurSetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2518 ` """ ... def getKrylovSchurRestart(self) -> float: """Get the restart parameter used in the Krylov-Schur method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setKrylovSchurRestart, slepc.EPSKrylovSchurGetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2542 ` """ ... def setKrylovSchurLocking(self, lock: bool) -> None: """Set (toggle) locking/non-locking variants of the Krylov-Schur method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getKrylovSchurLocking, slepc.EPSKrylovSchurSetLocking :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2561 ` """ ... def getKrylovSchurLocking(self) -> bool: """Get the locking flag used in the Krylov-Schur method. Not collective. Returns ------- bool The locking flag. See Also -------- setKrylovSchurLocking, slepc.EPSKrylovSchurGetLocking :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2586 ` """ ... def setKrylovSchurPartitions(self, npart: int) -> None: """Set the number of partitions of the communicator (spectrum slicing). Logically collective. Set the number of partitions for the case of doing spectrum slicing for a computational interval with the communicator split in several sub-communicators. Parameters ---------- npart The number of partitions. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. By default, ``npart=1`` so all processes in the communicator participate in the processing of the whole interval. If ``npart>1`` then the interval is divided into ``npart`` subintervals, each of them being processed by a subset of processes. The interval is split proportionally unless the separation points are specified with `setKrylovSchurSubintervals()`. See Also -------- setInterval, getKrylovSchurPartitions, slepc.EPSKrylovSchurSetPartitions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2605 ` """ ... def getKrylovSchurPartitions(self) -> int: """Get the number of partitions of the communicator (spectrum slicing). Not collective. Returns ------- int The number of partitions. See Also -------- setKrylovSchurPartitions, slepc.EPSKrylovSchurGetPartitions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2640 ` """ ... def setKrylovSchurDetectZeros(self, detect: bool) -> None: """Set the flag that enforces zero detection in spectrum slicing. Logically collective. Set a flag to enforce the detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect ``True`` if zeros must checked for. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. A zero in the factorization indicates that a shift coincides with an eigenvalue. This flag is turned off by default, and may be necessary in some cases, especially when several partitions are being used. This feature currently requires an external package for factorizations with support for zero detection, e.g., MUMPS. See Also -------- setInterval, getKrylovSchurDetectZeros, slepc.EPSKrylovSchurSetDetectZeros :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2659 ` """ ... def getKrylovSchurDetectZeros(self) -> bool: """Get the flag that enforces zero detection in spectrum slicing. Not collective. Returns ------- bool The zero detection flag. See Also -------- setKrylovSchurDetectZeros, slepc.EPSKrylovSchurGetDetectZeros :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2693 ` """ ... def setKrylovSchurDimensions(self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set the dimensions used for each subsolve step (spectrum slicing). Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. The meaning of the parameters is the same as in `setDimensions()`, but the ones here apply to every subsolve done by the child `EPS` object. See Also -------- setInterval, getKrylovSchurDimensions, slepc.EPSKrylovSchurSetDimensions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2712 ` """ ... def getKrylovSchurDimensions(self) -> tuple[int, int, int]: """Get the dimensions used for each subsolve step (spectrum slicing). Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setKrylovSchurDimensions, slepc.EPSKrylovSchurGetDimensions :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2752 ` """ ... def getKrylovSchurSubcommInfo(self) -> tuple[int, int, Vec]: """Get information related to the case of doing spectrum slicing. Collective on the subcommunicator. Get information related to the case of doing spectrum slicing for a computational interval with multiple communicators. Returns ------- k: int Index of the subinterval for the calling process. n: int Number of eigenvalues found in the ``k``-th subinterval. v: petsc4py.PETSc.Vec A vector owned by processes in the subcommunicator with dimensions compatible for locally computed eigenvectors. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. See Also -------- getKrylovSchurSubcommPairs, slepc.EPSKrylovSchurGetSubcommInfo :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2777 ` """ ... def getKrylovSchurSubcommPairs(self, i: int, v: Vec | None = None) -> Scalar: """Get the i-th eigenpair stored in the multi-communicator of the process. Collective on the subcommunicator (if v is given). Get the i-th eigenpair stored internally in the multi-communicator to which the calling process belongs. Parameters ---------- i Index of the solution to be obtained. v Placeholder for the returned eigenvector. Returns ------- Scalar The computed eigenvalue. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. Argument ``v`` must be a valid ``Vec`` object, created by calling `getKrylovSchurSubcommInfo()`. The index ``i`` should be a value between ``0`` and ``n-1``, where ``n`` is the number of vectors in the local subinterval, see `getKrylovSchurSubcommInfo()`. See Also -------- getKrylovSchurSubcommMats, slepc.EPSKrylovSchurGetSubcommPairs :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2811 ` """ ... def getKrylovSchurSubcommMats(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """Get the eigenproblem matrices stored in the subcommunicator. Collective on the subcommunicator. Get the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the eigensystem. B: petsc4py.PETSc.Mat The second matrix in the case of generalized eigenproblems. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. This is the analog of `getOperators()`, but returns the matrices distributed differently (in the subcommunicator rather than in the parent communicator). These matrices should not be modified by the user. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurGetSubcommMats :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2855 ` """ ... def updateKrylovSchurSubcommMats(self, s: Scalar = 1.0, a: Scalar = 1.0, Au: petsc4py.PETSc.Mat | None = None, t: Scalar = 1.0, b: Scalar = 1.0, Bu: petsc4py.PETSc.Mat | None = None, structure: petsc4py.PETSc.Mat.Structure | None = None, globalup: bool = False) -> None: """Update the eigenproblem matrices stored internally in the communicator. Collective. Update the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Parameters ---------- s Scalar that multiplies the existing A matrix. a Scalar used in the axpy operation on A. Au The matrix used in the axpy operation on A. t Scalar that multiplies the existing B matrix. b Scalar used in the axpy operation on B. Bu The matrix used in the axpy operation on B. structure Either same, different, or a subset of the non-zero sparsity pattern. globalup Whether global matrices must be updated or not. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. This function modifies the eigenproblem matrices at subcommunicator level, and optionally updates the global matrices in the parent communicator. The updates are expressed as :math:`A \leftarrow s A + a Au`, :math:`B \leftarrow t B + b Bu`. It is possible to update one of the matrices, or both. The matrices ``Au`` and ``Bu`` must be equal in all subcommunicators. The ``structure`` flag is passed to the `petsc4py.PETSc.Mat.axpy` operations to perform the updates. If ``globalup`` is ``True``, communication is carried out to reconstruct the updated matrices in the parent communicator. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurUpdateSubcommMats :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2897 ` """ ... def setKrylovSchurSubintervals(self, subint: Sequence[float]) -> None: """Set the subinterval boundaries. Logically collective. Set the subinterval boundaries for spectrum slicing with a computational interval with several partitions. Parameters ---------- subint Real values specifying subintervals. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. This function must be called after `setKrylovSchurPartitions()`. For ``npart`` partitions, the argument ``subint`` must contain ``npart+1`` real values sorted in ascending order: ``subint_0``, ``subint_1``, ..., ``subint_npart``, where the first and last values must coincide with the interval endpoints set with `setInterval()`. The subintervals are then defined by two consecutive points: ``[subint_0,subint_1]``, ``[subint_1,subint_2]``, and so on. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurSetSubintervals :sources:`Source code at slepc4py/SLEPc/EPS.pyx:2968 ` """ ... def getKrylovSchurSubintervals(self) -> ArrayReal: """Get the points that delimit the subintervals. Not collective. Get the points that delimit the subintervals used in spectrum slicing with several partitions. Returns ------- ArrayReal Real values specifying subintervals. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If the user passed values with `setKrylovSchurSubintervals()`, then the same values are returned here. Otherwise, the values computed internally are obtained. See Also -------- setKrylovSchurSubintervals, slepc.EPSKrylovSchurGetSubintervals :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3012 ` """ ... def getKrylovSchurInertias(self) -> tuple[ArrayReal, ArrayInt]: """Get the values of the shifts and their corresponding inertias. Not collective. Get the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: ArrayReal The values of the shifts used internally in the solver. inertias: ArrayInt The values of the inertia in each shift. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If called after `solve()`, all shifts used internally by the solver are returned (including both endpoints and any intermediate ones). If called before `solve()` and after `setUp()` then only the information of the endpoints of subintervals is available. See Also -------- setInterval, setKrylovSchurSubintervals, slepc.EPSKrylovSchurGetInertias :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3050 ` """ ... def getKrylovSchurKSP(self) -> KSP: """Get the linear solver object associated with the internal `EPS` object. Collective. Get the linear solver object associated with the internal `EPS` object in case of doing spectrum slicing for a computational interval. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. When invoked to compute all eigenvalues in an interval with spectrum slicing, `KRYLOVSCHUR` creates another `EPS` object internally that is used to compute eigenvalues by chunks near selected shifts. This function allows access to the ``KSP`` object associated to this internal `EPS` object. In case of having more than one partition, the returned ``KSP`` will be different in MPI processes belonging to different partitions. Hence, if required, `setKrylovSchurPartitions()` must be called BEFORE this function. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurGetKSP :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3094 ` """ ... def setGDKrylovStart(self, krylovstart: bool = True) -> None: """Set (toggle) starting the search subspace with a Krylov basis. Logically collective. Parameters ---------- krylovstart ``True`` if starting the search subspace with a Krylov basis. See Also -------- setGDInitialSize, getGDKrylovStart, slepc.EPSGDSetKrylovStart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3135 ` """ ... def getGDKrylovStart(self) -> bool: """Get a flag indicating if the search subspace is started with a Krylov basis. Not collective. Returns ------- bool ``True`` if starting the search subspace with a Krylov basis. See Also -------- setGDKrylovStart, slepc.EPSGDGetKrylovStart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3153 ` """ ... def setGDBlockSize(self, bs: int) -> None: """Set the number of vectors to be added to the searching space. Logically collective. Set the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs The number of vectors added to the search space in every iteration. See Also -------- getGDBlockSize, slepc.EPSGDSetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3172 ` """ ... def getGDBlockSize(self) -> int: """Get the number of vectors to be added to the searching space. Not collective. Get the number of vectors to be added to the searching space in every iteration. Returns ------- int The number of vectors added to the search space in every iteration. See Also -------- setGDBlockSize, slepc.EPSGDGetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3193 ` """ ... def setGDRestart(self, minv: int = None, plusk: int = None) -> None: """Set the number of vectors of the search space after restart. Logically collective. Set the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv The number of vectors of the search subspace after restart. plusk The number of vectors saved from the previous iteration. See Also -------- getGDRestart, slepc.EPSGDSetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3215 ` """ ... def getGDRestart(self) -> tuple[int, int]: """Get the number of vectors of the search space after restart. Not collective. Get the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Returns ------- minv: int The number of vectors of the search subspace after restart. plusk: int The number of vectors saved from the previous iteration. See Also -------- setGDRestart, slepc.EPSGDGetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3241 ` """ ... def setGDInitialSize(self, initialsize: int) -> None: """Set the initial size of the searching space. Logically collective. Parameters ---------- initialsize The number of vectors of the initial searching subspace. Notes ----- If the flag in `setGDKrylovStart()` is set to ``False`` and the user provides vectors with `setInitialSpace()`, up to ``initialsize`` vectors will be used; and if the provided vectors are not enough, the solver completes the subspace with random vectors. In case the `setGDKrylovStart()` flag is ``True``, the solver gets the first vector provided by the user or, if not available, a random vector, and expands the Krylov basis up to ``initialsize`` vectors. See Also -------- setGDKrylovStart, getGDInitialSize, slepc.EPSGDSetInitialSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3266 ` """ ... def getGDInitialSize(self) -> int: """Get the initial size of the searching space. Not collective. Returns ------- int The number of vectors of the initial searching subspace. See Also -------- setGDInitialSize, slepc.EPSGDGetInitialSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3294 ` """ ... def setGDBOrth(self, borth: bool) -> None: """Set the orthogonalization that will be used in the search subspace. Logically collective. Set the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth Whether to B-orthogonalize the search subspace. See Also -------- getGDBOrth, slepc.EPSGDSetBOrth :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3313 ` """ ... def getGDBOrth(self) -> bool: """Get the orthogonalization used in the search subspace. Not collective. Get the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- bool Whether to B-orthogonalize the search subspace. See Also -------- setGDBOrth, slepc.EPSGDGetBOrth :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3334 ` """ ... def setGDDoubleExpansion(self, doubleexp: bool) -> None: """Set that the search subspace is expanded with double expansion. Logically collective. Parameters ---------- doubleexp ``True`` if using double expansion. Notes ----- In the double expansion variant the search subspace is expanded with :math:`K [A x, B x]` (double expansion) instead of the classic :math:`K r`, where :math:`K` is the preconditioner, :math:`x` the selected approximate eigenvector and :math:`r` its associated residual vector. See Also -------- getGDDoubleExpansion, slepc.EPSGDSetDoubleExpansion :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3356 ` """ ... def getGDDoubleExpansion(self) -> bool: """Get a flag indicating whether the double expansion variant is active. Not collective. Get a flag indicating whether the double expansion variant has been activated or not. Returns ------- bool ``True`` if using double expansion. See Also -------- setGDDoubleExpansion, slepc.EPSGDGetDoubleExpansion :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3382 ` """ ... def setJDKrylovStart(self, krylovstart: bool = True) -> None: """Set (toggle) starting the search subspace with a Krylov basis. Logically collective. Parameters ---------- krylovstart ``True`` if starting the search subspace with a Krylov basis. See Also -------- setJDInitialSize, getJDKrylovStart, slepc.EPSJDSetKrylovStart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3406 ` """ ... def getJDKrylovStart(self) -> bool: """Get a flag indicating if the search subspace is started with a Krylov basis. Not collective. Returns ------- bool ``True`` if starting the search subspace with a Krylov basis. See Also -------- setJDKrylovStart, slepc.EPSJDGetKrylovStart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3424 ` """ ... def setJDBlockSize(self, bs: int) -> None: """Set the number of vectors to be added to the searching space. Logically collective. Set the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs The number of vectors added to the search space in every iteration. See Also -------- getJDBlockSize, slepc.EPSJDSetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3443 ` """ ... def getJDBlockSize(self) -> int: """Get the number of vectors to be added to the searching space. Not collective. Get the number of vectors to be added to the searching space in every iteration. Returns ------- int The number of vectors added to the search space in every iteration. See Also -------- setJDBlockSize, slepc.EPSJDGetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3464 ` """ ... def setJDRestart(self, minv: int | None = None, plusk: int | None = None) -> None: """Set the number of vectors of the search space after restart. Logically collective. Set the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv The number of vectors of the search subspace after restart. plusk The number of vectors saved from the previous iteration. See Also -------- getJDRestart, slepc.EPSJDSetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3486 ` """ ... def getJDRestart(self) -> tuple[int, int]: """Get the number of vectors of the search space after restart. Not collective. Get the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Returns ------- minv: int The number of vectors of the search subspace after restart. plusk: int The number of vectors saved from the previous iteration. See Also -------- setJDRestart, slepc.EPSJDGetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3512 ` """ ... def setJDInitialSize(self, initialsize: int) -> None: """Set the initial size of the searching space. Logically collective. Parameters ---------- initialsize The number of vectors of the initial searching subspace. Notes ----- If the flag in `setJDKrylovStart()` is set to ``False`` and the user provides vectors with `setInitialSpace()`, up to ``initialsize`` vectors will be used; and if the provided vectors are not enough, the solver completes the subspace with random vectors. In case the `setJDKrylovStart()` flag is ``True``, the solver gets the first vector provided by the user or, if not available, a random vector, and expands the Krylov basis up to ``initialsize`` vectors. See Also -------- setJDKrylovStart, getJDInitialSize, slepc.EPSJDSetInitialSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3537 ` """ ... def getJDInitialSize(self) -> int: """Get the initial size of the searching space. Not collective. Returns ------- int The number of vectors of the initial searching subspace. See Also -------- setJDInitialSize, slepc.EPSJDGetInitialSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3565 ` """ ... def setJDFix(self, fix: float) -> None: """Set the threshold for changing the target in the correction equation. Logically collective. Parameters ---------- fix The threshold for changing the target. Notes ----- The target in the correction equation is fixed at the first iterations. When the norm of the residual vector is lower than the ``fix`` value, the target is set to the corresponding eigenvalue. See Also -------- getJDFix, slepc.EPSJDSetFix :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3584 ` """ ... def getJDFix(self) -> float: """Get the threshold for changing the target in the correction equation. Not collective. Returns ------- float The threshold for changing the target. See Also -------- setJDFix, slepc.EPSJDGetFix :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3608 ` """ ... def setJDConstCorrectionTol(self, constant: bool) -> None: """Deactivate the dynamic stopping criterion. Logically collective. Parameters ---------- constant If ``False``, the `petsc4py.PETSc.KSP` relative tolerance is set to ``0.5**i``. Notes ----- If this flag is set to ``False``, then the `petsc4py.PETSc.KSP` relative tolerance is dynamically set to ``0.5**i``, where ``i`` is the number of `EPS` iterations since the last converged value. By the default, a constant tolerance is used. See Also -------- getJDConstCorrectionTol, slepc.EPSJDSetConstCorrectionTol :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3627 ` """ ... def getJDConstCorrectionTol(self) -> bool: """Get the flag indicating if the dynamic stopping is being used. Not collective. Returns ------- bool ``True`` if the dynamic stopping criterion is not being used. See Also -------- setJDConstCorrectionTol, slepc.EPSJDGetConstCorrectionTol :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3653 ` """ ... def setJDBOrth(self, borth: bool) -> None: """Set the orthogonalization that will be used in the search subspace. Logically collective. Set the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth Whether to B-orthogonalize the search subspace. See Also -------- getJDBOrth, slepc.EPSJDSetBOrth :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3672 ` """ ... def getJDBOrth(self) -> bool: """Get the orthogonalization used in the search subspace. Not collective. Get the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- bool Whether to B-orthogonalize the search subspace. See Also -------- setJDBOrth, slepc.EPSJDGetBOrth :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3693 ` """ ... def setRQCGReset(self, nrest: int) -> None: """Set the reset parameter of the RQCG iteration. Logically collective. Parameters ---------- nrest The number of iterations between resets. Notes ----- Every ``nrest`` iterations the solver performs a Rayleigh-Ritz projection step. See Also -------- getRQCGReset, slepc.EPSRQCGSetReset :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3717 ` """ ... def getRQCGReset(self) -> int: """Get the reset parameter used in the RQCG method. Not collective. Returns ------- int The number of iterations between resets. See Also -------- setRQCGReset, slepc.EPSRQCGGetReset :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3740 ` """ ... def setLOBPCGBlockSize(self, bs: int) -> None: """Set the block size of the LOBPCG method. Logically collective. Parameters ---------- bs The block size. See Also -------- getLOBPCGBlockSize, slepc.EPSLOBPCGSetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3759 ` """ ... def getLOBPCGBlockSize(self) -> int: """Get the block size used in the LOBPCG method. Not collective. Returns ------- int The block size. See Also -------- setLOBPCGBlockSize, slepc.EPSLOBPCGGetBlockSize :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3777 ` """ ... def setLOBPCGRestart(self, restart: float) -> None: """Set the restart parameter for the LOBPCG method. Logically collective. Parameters ---------- restart The percentage of the block of vectors to force a restart. Notes ----- The meaning of this parameter is the proportion of vectors within the current block iterate that must have converged in order to force a restart with hard locking. Allowed values are in the range [0.1,1.0]. The default is 0.9. See Also -------- getLOBPCGRestart, slepc.EPSLOBPCGSetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3796 ` """ ... def getLOBPCGRestart(self) -> float: """Get the restart parameter used in the LOBPCG method. Not collective. Returns ------- float The restart parameter. See Also -------- setLOBPCGRestart, slepc.EPSLOBPCGGetRestart :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3821 ` """ ... def setLOBPCGLocking(self, lock: bool) -> None: """Toggle between locking and non-locking (LOBPCG method). Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- This flag refers to soft locking (converged vectors within the current block iterate), since hard locking is always used (when ``nev`` is larger than the block size). See Also -------- getLOBPCGLocking, slepc.EPSLOBPCGSetLocking :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3840 ` """ ... def getLOBPCGLocking(self) -> bool: """Get the locking flag used in the LOBPCG method. Not collective. Returns ------- bool The locking flag. See Also -------- setLOBPCGLocking, slepc.EPSLOBPCGGetLocking :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3864 ` """ ... def setLyapIIRanks(self, rkc: int | None = None, rkl: int | None = None) -> None: """Set the ranks used in the solution of the Lyapunov equation. Logically collective. Parameters ---------- rkc The compressed rank. rkl The Lyapunov rank. Notes ----- Lyapunov inverse iteration needs to solve a large-scale Lyapunov equation at each iteration of the eigensolver. For this, an iterative solver (`LME`) is used, which requires to prescribe the rank of the solution matrix :math:`X`. This is the meaning of parameter ``rkl``. Later, this matrix is compressed into another matrix of rank ``rkc``. If not provided, ``rkl`` is a small multiple of ``rkc``. See Also -------- getLyapIIRanks, slepc.EPSLyapIISetRanks :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3883 ` """ ... def getLyapIIRanks(self) -> tuple[int, int]: """Get the rank values used for the Lyapunov step. Not collective. Returns ------- rkc: int The compressed rank. rkl: int The Lyapunov rank. See Also -------- setLyapIIRanks, slepc.EPSLyapIIGetRanks :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3915 ` """ ... def setCISSExtraction(self, extraction: CISSExtraction) -> None: """Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.EPSCISSSetExtraction :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3939 ` """ ... def getCISSExtraction(self) -> CISSExtraction: """Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.EPSCISSGetExtraction :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3957 ` """ ... def setCISSQuadRule(self, quad: CISSQuadRule) -> None: """Set the quadrature rule used in the CISS solver. Logically collective. Parameters ---------- quad The quadrature rule. See Also -------- getCISSQuadRule, slepc.EPSCISSSetQuadRule :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3976 ` """ ... def getCISSQuadRule(self) -> CISSQuadRule: """Get the quadrature rule used in the CISS solver. Not collective. Returns ------- CISSQuadRule The quadrature rule. See Also -------- setCISSQuadRule, slepc.EPSCISSGetQuadRule :sources:`Source code at slepc4py/SLEPc/EPS.pyx:3994 ` """ ... def setCISSSizes(self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False) -> None: """Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `EPS` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.EPSCISSSetSizes :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4013 ` """ ... def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.EPSCISSGetSizes :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4067 ` """ ... def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.EPSCISSSetThreshold :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4101 ` """ ... def getCISSThreshold(self) -> tuple[float, float]: """Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.EPSCISSGetThreshold :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4124 ` """ ... def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.EPSCISSSetRefinement :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4146 ` """ ... def getCISSRefinement(self) -> tuple[int, int]: """Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.EPSCISSGetRefinement :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4169 ` """ ... def setCISSUseST(self, usest: bool) -> None: """Set a flag indicating that the CISS solver will use the `ST` object. Logically collective. Parameters ---------- usest Whether to use the `ST` object or not. Notes ----- When this option is set, the linear solves can be configured by setting options for the `petsc4py.PETSc.KSP` object obtained with `ST.getKSP()`. Otherwise, several `petsc4py.PETSc.KSP` objects are created, which can be accessed with `getCISSKSPs()`. The default is to use the `ST`, unless several partitions have been specified, see `setCISSSizes()`. See Also -------- getCISSUseST, getCISSKSPs, setCISSSizes, slepc.EPSCISSSetUseST :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4191 ` """ ... def getCISSUseST(self) -> bool: """Get the flag indicating the use of the `ST` object in the CISS solver. Not collective. Returns ------- bool Whether to use the `ST` object or not. See Also -------- setCISSUseST, slepc.EPSCISSGetUseST :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4219 ` """ ... def getCISSKSPs(self) -> list[KSP]: """Get the array of linear solver objects associated with the CISS solver. Not collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.EPSCISSGetKSPs :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4238 ` """ ... @property def problem_type(self) -> EPSProblemType: """The type of the eigenvalue problem. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4266 ` """ ... @property def extraction(self) -> EPSExtraction: """The type of extraction technique to be employed. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4273 ` """ ... @property def which(self) -> EPSWhich: """The portion of the spectrum to be sought. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4280 ` """ ... @property def target(self) -> float: """The value of the target. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4287 ` """ ... @property def tol(self) -> float: """The tolerance. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4294 ` """ ... @property def max_it(self) -> int: """The maximum iteration count. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4301 ` """ ... @property def two_sided(self) -> bool: """Two-sided that also computes left eigenvectors. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4308 ` """ ... @property def true_residual(self) -> bool: """Compute the true residual explicitly. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4315 ` """ ... @property def purify(self) -> bool: """Eigenvector purification. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4322 ` """ ... @property def track_all(self) -> bool: """Compute the residual norm of all approximate eigenpairs. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4329 ` """ ... @property def st(self) -> ST: """The spectral transformation (`ST`) object associated. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4336 ` """ ... @property def bv(self) -> BV: """The basis vectors (`BV`) object associated. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4343 ` """ ... @property def rg(self) -> RG: """The region (`RG`) object associated. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4350 ` """ ... @property def ds(self) -> DS: """The direct solver (`DS`) object associated. :sources:`Source code at slepc4py/SLEPc/EPS.pyx:4357 ` """ ... class SVD(Object): """Singular Value Decomposition Solver. The Singular Value Decomposition Solver (`SVD`) is very similar to the `EPS` object, but intended for the computation of the partial SVD of a rectangular matrix. With this type of object, the user can specify an SVD problem and solve it with any of the different solvers encapsulated by the package. Some of these solvers are actually implemented through calls to `EPS` eigensolvers. """ class Type: """SVD type. Native singular value solvers. - `CROSS`: Eigenproblem with the cross-product matrix. - `CYCLIC`: Eigenproblem with the cyclic matrix. - `LANCZOS`: Explicitly restarted Lanczos. - `TRLANCZOS`: Thick-restart Lanczos. - `RANDOMIZED`: Iterative RSVD for low-rank matrices. Wrappers to external SVD solvers (should be enabled during installation of SLEPc). - `LAPACK`: Sequential dense SVD solver. - `SCALAPACK`: Parallel dense SVD solver. - `KSVD`: Parallel dense SVD solver. - `ELEMENTAL`: Parallel dense SVD solver. - `PRIMME`: Iterative SVD solvers of Davidson type. See Also -------- slepc.SVDType """ CROSS: str = _def(str, 'CROSS') #: Object ``CROSS`` of type :class:`str` CYCLIC: str = _def(str, 'CYCLIC') #: Object ``CYCLIC`` of type :class:`str` LAPACK: str = _def(str, 'LAPACK') #: Object ``LAPACK`` of type :class:`str` LANCZOS: str = _def(str, 'LANCZOS') #: Object ``LANCZOS`` of type :class:`str` TRLANCZOS: str = _def(str, 'TRLANCZOS') #: Object ``TRLANCZOS`` of type :class:`str` RANDOMIZED: str = _def(str, 'RANDOMIZED') #: Object ``RANDOMIZED`` of type :class:`str` SCALAPACK: str = _def(str, 'SCALAPACK') #: Object ``SCALAPACK`` of type :class:`str` KSVD: str = _def(str, 'KSVD') #: Object ``KSVD`` of type :class:`str` ELEMENTAL: str = _def(str, 'ELEMENTAL') #: Object ``ELEMENTAL`` of type :class:`str` PRIMME: str = _def(str, 'PRIMME') #: Object ``PRIMME`` of type :class:`str` class ProblemType: """SVD problem type. - `STANDARD`: Standard SVD. - `GENERALIZED`: Generalized singular value decomposition (GSVD). - `HYPERBOLIC` : Hyperbolic singular value decomposition (HSVD). See Also -------- slepc.SVDProblemType """ STANDARD: int = _def(int, 'STANDARD') #: Constant ``STANDARD`` of type :class:`int` GENERALIZED: int = _def(int, 'GENERALIZED') #: Constant ``GENERALIZED`` of type :class:`int` HYPERBOLIC: int = _def(int, 'HYPERBOLIC') #: Constant ``HYPERBOLIC`` of type :class:`int` class ErrorType: """SVD error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `NORM`: Error relative to the matrix norm. See Also -------- slepc.SVDErrorType """ ABSOLUTE: int = _def(int, 'ABSOLUTE') #: Constant ``ABSOLUTE`` of type :class:`int` RELATIVE: int = _def(int, 'RELATIVE') #: Constant ``RELATIVE`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` class Which: """SVD desired part of spectrum. - `LARGEST`: Largest singular values. - `SMALLEST`: Smallest singular values. See Also -------- slepc.SVDWhich """ LARGEST: int = _def(int, 'LARGEST') #: Constant ``LARGEST`` of type :class:`int` SMALLEST: int = _def(int, 'SMALLEST') #: Constant ``SMALLEST`` of type :class:`int` class Conv: """SVD convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the singular value. - `NORM`: Convergence test relative to the matrix norms. - `MAXIT`: No convergence until maximum number of iterations has been reached. - `USER`: User-defined convergence test. See Also -------- slepc.SVDConv """ ABS: int = _def(int, 'ABS') #: Constant ``ABS`` of type :class:`int` REL: int = _def(int, 'REL') #: Constant ``REL`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` MAXIT: int = _def(int, 'MAXIT') #: Constant ``MAXIT`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Stop: """SVD stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. - `THRESHOLD`: Threshold stopping test. See Also -------- slepc.SVDStop """ BASIC: int = _def(int, 'BASIC') #: Constant ``BASIC`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` THRESHOLD: int = _def(int, 'THRESHOLD') #: Constant ``THRESHOLD`` of type :class:`int` class ConvergedReason: """SVD convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `CONVERGED_MAXIT`: Maximum iterations completed in case MAXIT convergence criterion. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Underlying indefinite eigensolver was not able to keep symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.SVDConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` CONVERGED_USER: int = _def(int, 'CONVERGED_USER') #: Constant ``CONVERGED_USER`` of type :class:`int` CONVERGED_MAXIT: int = _def(int, 'CONVERGED_MAXIT') #: Constant ``CONVERGED_MAXIT`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` DIVERGED_SYMMETRY_LOST: int = _def(int, 'DIVERGED_SYMMETRY_LOST') #: Constant ``DIVERGED_SYMMETRY_LOST`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` class TRLanczosGBidiag: """SVD TRLanczos bidiagonalization choices for the GSVD case. - `SINGLE`: Single bidiagonalization (:math:`Q_A`). - `UPPER`: Joint bidiagonalization, both :math:`Q_A` and :math:`Q_B` in upper bidiagonal form. - `LOWER`: Joint bidiagonalization, :math:`Q_A` lower bidiagonal, :math:`Q_B` upper bidiagonal. See Also -------- slepc.SVDTRLanczosGBidiag """ SINGLE: int = _def(int, 'SINGLE') #: Constant ``SINGLE`` of type :class:`int` UPPER: int = _def(int, 'UPPER') #: Constant ``UPPER`` of type :class:`int` LOWER: int = _def(int, 'LOWER') #: Constant ``LOWER`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the SVD data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.SVDView :sources:`Source code at slepc4py/SLEPc/SVD.pyx:195 ` """ ... def destroy(self) -> Self: """Destroy the SVD object. Collective. See Also -------- slepc.SVDDestroy :sources:`Source code at slepc4py/SLEPc/SVD.pyx:214 ` """ ... def reset(self) -> None: """Reset the SVD object. Collective. See Also -------- slepc.SVDReset :sources:`Source code at slepc4py/SLEPc/SVD.pyx:228 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the SVD object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.SVDCreate :sources:`Source code at slepc4py/SLEPc/SVD.pyx:240 ` """ ... def setType(self, svd_type: Type | str) -> None: """Set the particular solver to be used in the SVD object. Logically collective. Parameters ---------- svd_type The solver to be used. Notes ----- The default is `CROSS`. Normally, it is best to use `setFromOptions()` and then set the SVD type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.SVDSetType :sources:`Source code at slepc4py/SLEPc/SVD.pyx:261 ` """ ... def getType(self) -> str: """Get the SVD type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.SVDGetType :sources:`Source code at slepc4py/SLEPc/SVD.pyx:288 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all SVD options in the database. Not collective. Returns ------- str The prefix string set for this SVD object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.SVDGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:307 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all SVD options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all SVD option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different SVD contexts, one could call:: S1.setOptionsPrefix("svd1_") S2.setOptionsPrefix("svd2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.SVDGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:326 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all SVD options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all SVD option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.SVDAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:357 ` """ ... def setFromOptions(self) -> None: """Set SVD options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.SVDSetFromOptions :sources:`Source code at slepc4py/SLEPc/SVD.pyx:376 ` """ ... def getProblemType(self) -> ProblemType: """Get the problem type from the SVD object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.SVDGetProblemType :sources:`Source code at slepc4py/SLEPc/SVD.pyx:395 ` """ ... def setProblemType(self, problem_type: ProblemType) -> None: """Set the type of the singular value problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- The GSVD requires that two matrices have been passed via `setOperators()`. The HSVD requires that a signature matrix has been passed via `setSignature()`. See Also -------- setOperators, setSignature, getProblemType, slepc.SVDSetProblemType :sources:`Source code at slepc4py/SLEPc/SVD.pyx:414 ` """ ... def isGeneralized(self) -> bool: """Tell if the SVD corresponds to a generalized singular value problem. Not collective. Returns ------- bool ``True`` if two matrices were set with `setOperators()`. See Also -------- setProblemType, isHyperbolic, slepc.SVDIsGeneralized :sources:`Source code at slepc4py/SLEPc/SVD.pyx:438 ` """ ... def isHyperbolic(self) -> bool: """Tell whether the SVD object corresponds to a hyperbolic singular value problem. Not collective. Returns ------- bool ``True`` if the problem was specified as hyperbolic. See Also -------- setProblemType, isGeneralized, slepc.SVDIsHyperbolic :sources:`Source code at slepc4py/SLEPc/SVD.pyx:457 ` """ ... def getImplicitTranspose(self) -> bool: """Get the mode used to handle the transpose of the associated matrix. Not collective. Returns ------- bool How to handle the transpose (implicitly or not). See Also -------- setImplicitTranspose, slepc.SVDGetImplicitTranspose :sources:`Source code at slepc4py/SLEPc/SVD.pyx:478 ` """ ... def setImplicitTranspose(self, mode: bool) -> None: """Set how to handle the transpose of the associated matrix. Logically collective. Parameters ---------- impl How to handle the transpose (implicitly or not). Notes ----- By default, the transpose of the matrix is explicitly built (if the matrix has defined the ``Mat.transpose()`` operation). If this flag is set to ``True``, the solver does not build the transpose, but handles it implicitly via ``Mat.multTranspose()`` (or ``Mat.multHermitianTranspose()`` in the complex case). See Also -------- getImplicitTranspose, slepc.SVDSetImplicitTranspose :sources:`Source code at slepc4py/SLEPc/SVD.pyx:497 ` """ ... def getWhichSingularTriplets(self) -> Which: """Get which singular triplets are to be sought. Not collective. Returns ------- Which The singular values to be sought (either largest or smallest). See Also -------- setWhichSingularTriplets, slepc.SVDGetWhichSingularTriplets :sources:`Source code at slepc4py/SLEPc/SVD.pyx:524 ` """ ... def setWhichSingularTriplets(self, which: Which) -> None: """Set which singular triplets are to be sought. Logically collective. Parameters ---------- which The singular values to be sought (either largest or smallest). See Also -------- getWhichSingularTriplets, slepc.SVDSetWhichSingularTriplets :sources:`Source code at slepc4py/SLEPc/SVD.pyx:543 ` """ ... def getThreshold(self) -> tuple[float, bool]: """Get the threshold used in the threshold stopping test. Not collective. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. See Also -------- setThreshold, slepc.SVDGetThreshold :sources:`Source code at slepc4py/SLEPc/SVD.pyx:561 ` """ ... def setThreshold(self, thres: float, rel: bool = False) -> None: """Set the threshold used in the threshold stopping test. Logically collective. Parameters ---------- thres The threshold. rel Whether the threshold is relative or not. Notes ----- This function internally sets a special stopping test based on the threshold, where singular values are computed in sequence until one of the computed singular values is below/above the threshold (depending on whether largest or smallest singular values are computed). In the case of largest singular values, the threshold can be made relative with respect to the largest singular value (i.e., the matrix norm). The details are given in `slepc.SVDSetThreshold`. See Also -------- setStoppingTest, getThreshold, slepc.SVDSetThreshold :sources:`Source code at slepc4py/SLEPc/SVD.pyx:583 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default SVD convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.SVDGetTolerances :sources:`Source code at slepc4py/SLEPc/SVD.pyx:618 ` """ ... def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """Set the tolerance and maximum iteration count used. Logically collective. Set the tolerance and maximum iteration count used by the default SVD convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.SVDSetTolerances :sources:`Source code at slepc4py/SLEPc/SVD.pyx:643 ` """ ... def getConvergenceTest(self) -> Conv: """Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.SVDGetConvergenceTest :sources:`Source code at slepc4py/SLEPc/SVD.pyx:674 ` """ ... def setConvergenceTest(self, conv: Conv) -> None: """Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.SVDSetConvergenceTest :sources:`Source code at slepc4py/SLEPc/SVD.pyx:694 ` """ ... def getTrackAll(self) -> bool: """Get the flag indicating if all residual norms must be computed or not. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.SVDGetTrackAll :sources:`Source code at slepc4py/SLEPc/SVD.pyx:713 ` """ ... def setTrackAll(self, trackall: bool) -> None: """Set flag to compute the residual of all singular triplets. Logically collective. Set if the solver must compute the residual of all approximate singular triplets or not. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.SVDSetTrackAll :sources:`Source code at slepc4py/SLEPc/SVD.pyx:732 ` """ ... def getDimensions(self) -> tuple[int, int, int]: """Get the number of singular values to compute and the dimension of the subspace. Not collective. Returns ------- nsv: int Number of singular values to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.SVDGetDimensions :sources:`Source code at slepc4py/SLEPc/SVD.pyx:753 ` """ ... def setDimensions(self, nsv: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set the number of singular values to compute and the dimension of the subspace. Logically collective. Parameters ---------- nsv Number of singular values to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nsv`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nsv``). + In cases where ``nsv`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nsv`` and (``nsv`` + ``mpd``), typically ``ncv`` = ``nsv`` + ``mpd``. If ``nsv`` is not too large, ``mpd`` = ``nsv`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.SVDSetDimensions :sources:`Source code at slepc4py/SLEPc/SVD.pyx:778 ` """ ... def getBV(self) -> tuple[BV, BV]: """Get the basis vectors objects associated to the SVD object. Not collective. Returns ------- V: BV The basis vectors context for right singular vectors. U: BV The basis vectors context for left singular vectors. See Also -------- setBV, slepc.SVDGetBV :sources:`Source code at slepc4py/SLEPc/SVD.pyx:829 ` """ ... def setBV(self, V: BV, U: BV | None = None) -> None: """Set basis vectors objects associated to the SVD solver. Collective. Parameters ---------- V The basis vectors context for right singular vectors. U The basis vectors context for left singular vectors. See Also -------- getBV, slepc.SVDSetBV :sources:`Source code at slepc4py/SLEPc/SVD.pyx:853 ` """ ... def getDS(self) -> DS: """Get the direct solver associated to the singular value solver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.SVDGetDS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:874 ` """ ... def setDS(self, ds: DS) -> None: """Set a direct solver object associated to the singular value solver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.SVDSetDS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:894 ` """ ... def getOperators(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """Get the matrices associated with the singular value problem. Collective. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the singular value problem. B: petsc4py.PETSc.Mat The second matrix in the case of GSVD. See Also -------- setOperators, slepc.SVDGetOperators :sources:`Source code at slepc4py/SLEPc/SVD.pyx:911 ` """ ... def setOperators(self, A: Mat, B: Mat | None = None) -> None: """Set the matrices associated with the singular value problem. Collective. Parameters ---------- A The matrix associated with the singular value problem. B The second matrix in the case of GSVD. See Also -------- getOperators, slepc.SVDSetOperators :sources:`Source code at slepc4py/SLEPc/SVD.pyx:938 ` """ ... def getSignature(self, omega: Vec | None = None) -> Vec: """Get the signature matrix defining a hyperbolic singular value problem. Collective. Parameters ---------- omega Optional vector to store the diagonal elements of the signature matrix. Returns ------- petsc4py.PETSc.Vec A vector containing the diagonal elements of the signature matrix. See Also -------- setSignature, slepc.SVDGetSignature :sources:`Source code at slepc4py/SLEPc/SVD.pyx:958 ` """ ... def setSignature(self, omega: Vec | None = None) -> None: """Set the signature matrix defining a hyperbolic singular value problem. Collective. Parameters ---------- omega A vector containing the diagonal elements of the signature matrix. See Also -------- getSignature, slepc.SVDSetSignature :sources:`Source code at slepc4py/SLEPc/SVD.pyx:987 ` """ ... def setInitialSpace(self, spaceright: list[Vec] | None = None, spaceleft: list[Vec] | None = None) -> None: """Set the initial spaces from which the SVD solver starts to iterate. Collective. Parameters ---------- spaceright The right initial space. spaceleft The left initial space. Notes ----- The initial right and left spaces are rough approximations to the right and/or left singular subspaces from which the solver starts to iterate. It is not necessary to provide both sets of vectors. Some solvers start to iterate on a single vector (initial vector). In that case, the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial spaces should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted singular spaces. Then, convergence may be faster. See Also -------- slepc.SVDSetInitialSpaces :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1007 ` """ ... def setStoppingTest(self, stopping: SVDStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.SVDSetStoppingTestFunction :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1064 ` """ ... def getStoppingTest(self) -> SVDStoppingFunction: """Get the stopping test function. Not collective. Returns ------- SVDStoppingFunction The stopping test function. See Also -------- setStoppingTest :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1088 ` """ ... def setMonitor(self, monitor: SVDMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.SVDMonitorSet :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1107 ` """ ... def getMonitor(self) -> SVDMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- SVDMonitorFunction The list of monitor functions. See Also -------- setMonitor :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1132 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for an `SVD` object. Logically collective. See Also -------- slepc.SVDMonitorCancel :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1149 ` """ ... def setUp(self) -> None: """Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the singular value solver. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.SVDSetUp :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1164 ` """ ... def solve(self) -> None: """Solve the singular value problem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.SVDSolve :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1185 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.SVDGetIterationNumber :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1207 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.SVDGetConvergedReason :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1229 ` """ ... def getConverged(self) -> int: """Get the number of converged singular triplets. Not collective. Returns ------- nconv: int Number of converged singular triplets. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nsv``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getValue, slepc.SVDGetConverged :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1248 ` """ ... def getValue(self, i: int) -> float: """Get the i-th singular value as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Returns ------- float The computed singular value. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1274 ` """ ... def getVectors(self, i: int, U: Vec, V: Vec) -> None: """Get the i-th left and right singular vectors as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. U Placeholder for the returned left singular vector. V Placeholder for the returned right singular vector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1305 ` """ ... def getSingularTriplet(self, i: int, U: Vec | None = None, V: Vec | None = None) -> float: """Get the i-th triplet of the singular value decomposition. Collective. Get the i-th triplet of the singular value decomposition as computed by `solve()`. The solution consists of the singular value and its left and right singular vectors. Parameters ---------- i Index of the solution to be obtained. U Placeholder for the returned left singular vector. V Placeholder for the returned right singular vector. Returns ------- float The computed singular value. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1334 ` """ ... def computeError(self, i: int, etype: ErrorType | None = None) -> float: """Compute the error associated with the i-th singular triplet. Collective. Compute the error (based on the residual norm) associated with the i-th singular triplet. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\sqrt{\eta_1^2+\eta_2^2}` where :math:`\eta_1 = \|A v - \sigma u\|_2`, :math:`\eta_2 = \|A^* u - \sigma v\|_2`, :math:`\sigma` is the approximate singular value, :math:`u` and :math:`v` are the left and right singular vectors. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). In the case of the GSVD, the two components of the residual norm are :math:`\eta_1 = \|s^2 A^*u-cB^*Bx\|_2` and :math:`\eta_2 = ||c^2 B^*v-sA^*Ax||_2`, where :math:`(\sigma,u,v,x)` is the approximate generalized singular quadruple, with :math:`\sigma=c/s`. See Also -------- solve, slepc.SVDComputeError :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1377 ` """ ... def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """Display the errors associated with the computed solution. Collective. Display the errors and the singular values. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all singular triplets and prints the singular values if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with singular values and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.SVDErrorView :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1424 ` """ ... def valuesView(self, viewer: Viewer | None = None) -> None: """Display the computed singular values in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.SVDValuesView :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1456 ` """ ... def vectorsView(self, viewer: Viewer | None = None) -> None: """Output computed singular vectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.SVDVectorsView :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1475 ` """ ... def setCrossEPS(self, eps: EPS) -> None: """Set an eigensolver object associated to the singular value solver. Collective. Parameters ---------- eps The eigensolver object. See Also -------- getCrossEPS, slepc.SVDCrossSetEPS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1496 ` """ ... def getCrossEPS(self) -> EPS: """Get the eigensolver object associated to the singular value solver. Collective. Returns ------- EPS The eigensolver object. See Also -------- setCrossEPS, slepc.SVDCrossGetEPS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1513 ` """ ... def setCrossExplicitMatrix(self, flag: bool = True) -> None: """Set if the eigensolver operator :math:`A^*A` must be computed. Logically collective. Parameters ---------- flag ``True`` to build :math:`A^*A` explicitly. Notes ----- In GSVD there are two cross product matrices, :math:`A^*A` and :math:`B^*B`. In HSVD the expression for the cross product matrix is different, :math:`A^*\Omega A`. By default the matrices are not built explicitly, but handled as shell matrices See Also -------- getCrossExplicitMatrix, slepc.SVDCrossSetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1533 ` """ ... def getCrossExplicitMatrix(self) -> bool: """Get the flag indicating if :math:`A^*A` is built explicitly. Not collective. Returns ------- bool ``True`` if :math:`A^*A` is built explicitly. See Also -------- setCrossExplicitMatrix, slepc.SVDCrossGetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1560 ` """ ... def setCyclicEPS(self, eps: EPS) -> None: """Set an eigensolver object associated to the singular value solver. Collective. Parameters ---------- eps The eigensolver object. See Also -------- getCyclicEPS, slepc.SVDCyclicSetEPS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1579 ` """ ... def getCyclicEPS(self) -> EPS: """Get the eigensolver object associated to the singular value solver. Collective. Returns ------- EPS The eigensolver object. See Also -------- setCyclicEPS, slepc.SVDCyclicGetEPS :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1596 ` """ ... def setCyclicExplicitMatrix(self, flag: bool = True) -> None: """Set if the eigensolver operator :math:`H(A)` must be computed explicitly. Logically collective. Set if the eigensolver operator :math:`H(A) = [ 0\; A ; A^T\; 0 ]` must be computed explicitly. Parameters ---------- flag ``True`` if :math:`H(A)` must be built explicitly. Notes ----- In GSVD and HSVD the equivalent eigenvalue problem has generalized form, and hence two matrices are built. By default the matrices are not built explicitly, but handled as shell matrices. See Also -------- getCyclicExplicitMatrix, slepc.SVDCyclicSetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1616 ` """ ... def getCyclicExplicitMatrix(self) -> bool: """Get the flag indicating if :math:`H(A)` is built explicitly. Not collective. Get the flag indicating if :math:`H(A) = [ 0\; A ; A^T\; 0 ]` is built explicitly. Returns ------- bool ``True`` if :math:`H(A)` is built explicitly. See Also -------- setCyclicExplicitMatrix, slepc.SVDCyclicGetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1645 ` """ ... def setLanczosOneSide(self, flag: bool = True) -> None: """Set if the variant of the Lanczos method to be used is one-sided or two-sided. Logically collective. Parameters ---------- flag ``True`` if the method is one-sided. Notes ----- By default, a two-sided variant is selected, which is sometimes slightly more robust. However, the one-sided variant is faster because it avoids the orthogonalization associated to left singular vectors. It also saves the memory required for storing such vectors. See Also -------- getLanczosOneSide, slepc.SVDLanczosSetOneSide :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1667 ` """ ... def getLanczosOneSide(self) -> bool: """Get if the variant of the Lanczos method to be used is one-sided or two-sided. Not collective. Returns ------- bool ``True`` if the method is one-sided. See Also -------- setLanczosOneSide, slepc.SVDLanczosGetOneSide :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1693 ` """ ... def setTRLanczosOneSide(self, flag: bool = True) -> None: """Set if the variant of the method to be used is one-sided or two-sided. Logically collective. Set if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Parameters ---------- flag ``True`` if the method is one-sided. Notes ----- By default, a two-sided variant is selected, which is sometimes slightly more robust. However, the one-sided variant is faster because it avoids the orthogonalization associated to left singular vectors. See Also -------- getTRLanczosOneSide, slepc.SVDLanczosSetOneSide :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1712 ` """ ... def getTRLanczosOneSide(self) -> bool: """Get if the variant of the method to be used is one-sided or two-sided. Not collective. Get if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Returns ------- bool ``True`` if the method is one-sided. See Also -------- setTRLanczosOneSide, slepc.SVDLanczosGetOneSide :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1740 ` """ ... def setTRLanczosGBidiag(self, bidiag: TRLanczosGBidiag) -> None: """Set the bidiagonalization choice to use in the GSVD TRLanczos solver. Logically collective. Parameters ---------- bidiag The bidiagonalization choice. See Also -------- getTRLanczosGBidiag, slepc.SVDTRLanczosSetGBidiag :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1762 ` """ ... def getTRLanczosGBidiag(self) -> TRLanczosGBidiag: """Get bidiagonalization choice used in the GSVD TRLanczos solver. Not collective. Returns ------- TRLanczosGBidiag The bidiagonalization choice. See Also -------- setTRLanczosGBidiag, slepc.SVDTRLanczosGetGBidiag :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1780 ` """ ... def setTRLanczosRestart(self, keep: float) -> None: """Set the restart parameter for the thick-restart Lanczos method. Logically collective. Set the restart parameter for the thick-restart Lanczos method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getTRLanczosRestart, slepc.SVDTRLanczosSetRestart :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1799 ` """ ... def getTRLanczosRestart(self) -> float: """Get the restart parameter used in the thick-restart Lanczos method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setTRLanczosRestart, slepc.SVDTRLanczosGetRestart :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1825 ` """ ... def setTRLanczosLocking(self, lock: bool) -> None: """Toggle between locking and non-locking variants of TRLanczos. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged singular triplets when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getTRLanczosLocking, slepc.SVDTRLanczosSetLocking :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1844 ` """ ... def getTRLanczosLocking(self) -> bool: """Get the locking flag used in the thick-restart Lanczos method. Not collective. Returns ------- bool The locking flag. See Also -------- setTRLanczosLocking, slepc.SVDTRLanczosGetLocking :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1869 ` """ ... def setTRLanczosKSP(self, ksp: KSP) -> None: """Set a linear solver object associated to the SVD solver. Collective. Parameters ---------- ``ksp`` The linear solver object. See Also -------- getTRLanczosKSP, slepc.SVDTRLanczosSetKSP :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1888 ` """ ... def getTRLanczosKSP(self) -> KSP: """Get the linear solver object associated with the SVD solver. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setTRLanczosKSP, slepc.SVDTRLanczosGetKSP :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1905 ` """ ... def setTRLanczosExplicitMatrix(self, flag: bool = True) -> None: """Set if the matrix :math:`Z=[A^*,B^*]^*` must be built explicitly. Logically collective. Parameters ---------- flag ``True`` if :math:`Z=[A^*,B^*]^*` is built explicitly. Notes ----- This option is relevant for the GSVD case only. :math:`Z` is the coefficient matrix of the least-squares solver used internally. See Also -------- getTRLanczosExplicitMatrix, slepc.SVDTRLanczosSetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1925 ` """ ... def getTRLanczosExplicitMatrix(self) -> bool: """Get the flag indicating if :math:`Z=[A^*,B^*]^*` is built explicitly. Not collective. Returns ------- bool ``True`` if :math:`Z=[A^*,B^*]^*` is built explicitly. See Also -------- setTRLanczosExplicitMatrix, slepc.SVDTRLanczosGetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1948 ` """ ... @property def problem_type(self) -> SVDProblemType: """The type of the eigenvalue problem. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1971 ` """ ... @property def transpose_mode(self) -> bool: """How to handle the transpose of the matrix. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1978 ` """ ... @property def which(self) -> SVDWhich: """The portion of the spectrum to be sought. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1985 ` """ ... @property def tol(self) -> float: """The tolerance. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1992 ` """ ... @property def max_it(self) -> int: """The maximum iteration count. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:1999 ` """ ... @property def track_all(self) -> bool: """Compute the residual norm of all approximate eigenpairs. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:2006 ` """ ... @property def ds(self) -> DS: """The direct solver (`DS`) object associated. :sources:`Source code at slepc4py/SLEPc/SVD.pyx:2013 ` """ ... class PEP(Object): """Polynomial Eigenvalue Problem Solver. The Polynomial Eigenvalue Problem (`PEP`) solver is the object provided by slepc4py for specifying a polynomial eigenvalue problem. Apart from the specific solvers for this type of problems, there is an `EPS`-based solver, i.e., it uses a solver from `EPS` to solve a generalized eigenproblem obtained after linearization. """ class Type: """PEP type. - `TOAR`: Two-level orthogonal Arnoldi. - `STOAR`: Symmetric TOAR. - `QARNOLDI`: Q-Arnoldi for quadratic problems. - `LINEAR`: Linearization via EPS. - `JD`: Polynomial Jacobi-Davidson. - `CISS`: Contour integral spectrum slice. See Also -------- slepc.PEPType """ TOAR: str = _def(str, 'TOAR') #: Object ``TOAR`` of type :class:`str` STOAR: str = _def(str, 'STOAR') #: Object ``STOAR`` of type :class:`str` QARNOLDI: str = _def(str, 'QARNOLDI') #: Object ``QARNOLDI`` of type :class:`str` LINEAR: str = _def(str, 'LINEAR') #: Object ``LINEAR`` of type :class:`str` JD: str = _def(str, 'JD') #: Object ``JD`` of type :class:`str` CISS: str = _def(str, 'CISS') #: Object ``CISS`` of type :class:`str` class ProblemType: """PEP problem type. - `GENERAL`: No structure. - `HERMITIAN`: Hermitian structure. - `HYPERBOLIC`: QEP with Hermitian matrices, :math:`M>0`, :math:`(x^TCx)^2 > 4(x^TMx)(x^TKx)`. - `GYROSCOPIC`: QEP with :math:`M`, :math:`K` Hermitian, :math:`M>0`, :math:`C` skew-Hermitian. See Also -------- slepc.PEPProblemType """ GENERAL: int = _def(int, 'GENERAL') #: Constant ``GENERAL`` of type :class:`int` HERMITIAN: int = _def(int, 'HERMITIAN') #: Constant ``HERMITIAN`` of type :class:`int` HYPERBOLIC: int = _def(int, 'HYPERBOLIC') #: Constant ``HYPERBOLIC`` of type :class:`int` GYROSCOPIC: int = _def(int, 'GYROSCOPIC') #: Constant ``GYROSCOPIC`` of type :class:`int` class Which: """PEP desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in an interval. - `USER`: User-defined criterion. See Also -------- slepc.PEPWhich """ LARGEST_MAGNITUDE: int = _def(int, 'LARGEST_MAGNITUDE') #: Constant ``LARGEST_MAGNITUDE`` of type :class:`int` SMALLEST_MAGNITUDE: int = _def(int, 'SMALLEST_MAGNITUDE') #: Constant ``SMALLEST_MAGNITUDE`` of type :class:`int` LARGEST_REAL: int = _def(int, 'LARGEST_REAL') #: Constant ``LARGEST_REAL`` of type :class:`int` SMALLEST_REAL: int = _def(int, 'SMALLEST_REAL') #: Constant ``SMALLEST_REAL`` of type :class:`int` LARGEST_IMAGINARY: int = _def(int, 'LARGEST_IMAGINARY') #: Constant ``LARGEST_IMAGINARY`` of type :class:`int` SMALLEST_IMAGINARY: int = _def(int, 'SMALLEST_IMAGINARY') #: Constant ``SMALLEST_IMAGINARY`` of type :class:`int` TARGET_MAGNITUDE: int = _def(int, 'TARGET_MAGNITUDE') #: Constant ``TARGET_MAGNITUDE`` of type :class:`int` TARGET_REAL: int = _def(int, 'TARGET_REAL') #: Constant ``TARGET_REAL`` of type :class:`int` TARGET_IMAGINARY: int = _def(int, 'TARGET_IMAGINARY') #: Constant ``TARGET_IMAGINARY`` of type :class:`int` ALL: int = _def(int, 'ALL') #: Constant ``ALL`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Basis: """PEP basis type for the representation of the polynomial. - `MONOMIAL`: Monomials (default). - `CHEBYSHEV1`: Chebyshev polynomials of the 1st kind. - `CHEBYSHEV2`: Chebyshev polynomials of the 2nd kind. - `LEGENDRE`: Legendre polynomials. - `LAGUERRE`: Laguerre polynomials. - `HERMITE`: Hermite polynomials. See Also -------- slepc.PEPBasis """ MONOMIAL: int = _def(int, 'MONOMIAL') #: Constant ``MONOMIAL`` of type :class:`int` CHEBYSHEV1: int = _def(int, 'CHEBYSHEV1') #: Constant ``CHEBYSHEV1`` of type :class:`int` CHEBYSHEV2: int = _def(int, 'CHEBYSHEV2') #: Constant ``CHEBYSHEV2`` of type :class:`int` LEGENDRE: int = _def(int, 'LEGENDRE') #: Constant ``LEGENDRE`` of type :class:`int` LAGUERRE: int = _def(int, 'LAGUERRE') #: Constant ``LAGUERRE`` of type :class:`int` HERMITE: int = _def(int, 'HERMITE') #: Constant ``HERMITE`` of type :class:`int` class Scale: """PEP scaling strategy. - `NONE`: No scaling. - `SCALAR`: Parameter scaling. - `DIAGONAL`: Diagonal scaling. - `BOTH`: Both parameter and diagonal scaling. See Also -------- slepc.PEPScale """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` SCALAR: int = _def(int, 'SCALAR') #: Constant ``SCALAR`` of type :class:`int` DIAGONAL: int = _def(int, 'DIAGONAL') #: Constant ``DIAGONAL`` of type :class:`int` BOTH: int = _def(int, 'BOTH') #: Constant ``BOTH`` of type :class:`int` class Refine: """PEP refinement strategy. - `NONE`: No refinement. - `SIMPLE`: Refine eigenpairs one by one. - `MULTIPLE`: Refine all eigenpairs simultaneously (invariant pair). See Also -------- slepc.PEPRefine """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` SIMPLE: int = _def(int, 'SIMPLE') #: Constant ``SIMPLE`` of type :class:`int` MULTIPLE: int = _def(int, 'MULTIPLE') #: Constant ``MULTIPLE`` of type :class:`int` class RefineScheme: """PEP scheme for solving linear systems during iterative refinement. - `SCHUR`: Schur complement. - `MBE`: Mixed block elimination. - `EXPLICIT`: Build the explicit matrix. See Also -------- slepc.PEPRefineScheme """ SCHUR: int = _def(int, 'SCHUR') #: Constant ``SCHUR`` of type :class:`int` MBE: int = _def(int, 'MBE') #: Constant ``MBE`` of type :class:`int` EXPLICIT: int = _def(int, 'EXPLICIT') #: Constant ``EXPLICIT`` of type :class:`int` class Extract: """PEP extraction strategy used. PEP extraction strategy used to obtain eigenvectors of the PEP from the eigenvectors of the linearization. - `NONE`: Use the first block. - `NORM`: Use the first or last block depending on norm of H. - `RESIDUAL`: Use the block with smallest residual. - `STRUCTURED`: Combine all blocks in a certain way. See Also -------- slepc.PEPExtract """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` RESIDUAL: int = _def(int, 'RESIDUAL') #: Constant ``RESIDUAL`` of type :class:`int` STRUCTURED: int = _def(int, 'STRUCTURED') #: Constant ``STRUCTURED`` of type :class:`int` class ErrorType: """PEP error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.PEPErrorType """ ABSOLUTE: int = _def(int, 'ABSOLUTE') #: Constant ``ABSOLUTE`` of type :class:`int` RELATIVE: int = _def(int, 'RELATIVE') #: Constant ``RELATIVE`` of type :class:`int` BACKWARD: int = _def(int, 'BACKWARD') #: Constant ``BACKWARD`` of type :class:`int` class Conv: """PEP convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.PEPConv """ ABS: int = _def(int, 'ABS') #: Constant ``ABS`` of type :class:`int` REL: int = _def(int, 'REL') #: Constant ``REL`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Stop: """PEP stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. See Also -------- slepc.PEPStop """ BASIC: int = _def(int, 'BASIC') #: Constant ``BASIC`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class ConvergedReason: """PEP convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Lanczos-type method could not preserve symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.PEPConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` CONVERGED_USER: int = _def(int, 'CONVERGED_USER') #: Constant ``CONVERGED_USER`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` DIVERGED_SYMMETRY_LOST: int = _def(int, 'DIVERGED_SYMMETRY_LOST') #: Constant ``DIVERGED_SYMMETRY_LOST`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` class JDProjection: """PEP type of projection to be used in the Jacobi-Davidson solver. - `HARMONIC`: Harmonic projection. - `ORTHOGONAL`: Orthogonal projection. See Also -------- slepc.PEPJDProjection """ HARMONIC: int = _def(int, 'HARMONIC') #: Constant ``HARMONIC`` of type :class:`int` ORTHOGONAL: int = _def(int, 'ORTHOGONAL') #: Constant ``ORTHOGONAL`` of type :class:`int` class CISSExtraction: """PEP CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. - `CAA`: Communication-avoiding Arnoldi. See Also -------- slepc.PEPCISSExtraction """ RITZ: int = _def(int, 'RITZ') #: Constant ``RITZ`` of type :class:`int` HANKEL: int = _def(int, 'HANKEL') #: Constant ``HANKEL`` of type :class:`int` CAA: int = _def(int, 'CAA') #: Constant ``CAA`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the PEP data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.PEPView :sources:`Source code at slepc4py/SLEPc/PEP.pyx:305 ` """ ... def destroy(self) -> Self: """Destroy the PEP object. Collective. See Also -------- slepc.PEPDestroy :sources:`Source code at slepc4py/SLEPc/PEP.pyx:324 ` """ ... def reset(self) -> None: """Reset the PEP object. Collective. See Also -------- slepc.PEPReset :sources:`Source code at slepc4py/SLEPc/PEP.pyx:338 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the PEP object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.PEPCreate :sources:`Source code at slepc4py/SLEPc/PEP.pyx:350 ` """ ... def setType(self, pep_type: Type | str) -> None: """Set the particular solver to be used in the PEP object. Logically collective. Parameters ---------- pep_type The solver to be used. Notes ----- The default is `TOAR`. Normally, it is best to use `setFromOptions()` and then set the PEP type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.PEPSetType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:371 ` """ ... def getType(self) -> str: """Get the PEP type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.PEPGetType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:398 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all PEP options in the database. Not collective. Returns ------- str The prefix string set for this PEP object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.PEPGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:417 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all PEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all PEP option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different PEP contexts, one could call:: P1.setOptionsPrefix("pep1_") P2.setOptionsPrefix("pep2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.PEPGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:436 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all PEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all PEP option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.PEPAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:467 ` """ ... def setFromOptions(self) -> None: """Set PEP options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.PEPSetFromOptions :sources:`Source code at slepc4py/SLEPc/PEP.pyx:486 ` """ ... def getBasis(self) -> Basis: """Get the type of polynomial basis used. Not collective. Returns ------- Basis The basis that was previously set. See Also -------- setBasis, slepc.PEPGetBasis :sources:`Source code at slepc4py/SLEPc/PEP.pyx:505 ` """ ... def setBasis(self, basis: Basis) -> None: """Set the type of polynomial basis used. Logically collective. Set the type of polynomial basis used to describe the polynomial eigenvalue problem. Parameters ---------- basis The basis to be set. Notes ----- By default, the coefficient matrices passed via `setOperators()` are expressed in the monomial basis, i.e. :math:`P(\lambda)=A_0+\lambda A_1+\lambda^2 A_2+\dots+\lambda^d A_d`. Other polynomial bases may have better numerical behavior, but the user must then pass the coefficient matrices accordingly. See Also -------- getBasis, setOperators, slepc.PEPSetBasis :sources:`Source code at slepc4py/SLEPc/PEP.pyx:524 ` """ ... def getProblemType(self) -> ProblemType: """Get the problem type from the PEP object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.PEPGetProblemType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:553 ` """ ... def setProblemType(self, problem_type: ProblemType) -> None: """Set the type of the polynomial eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function is used to instruct SLEPc to exploit certain structure in the polynomial eigenproblem. By default, no particular structure is assumed. If the problem matrices are Hermitian (symmetric in the real case) or Hermitian/skew-Hermitian then the solver can exploit this fact to perform less operations or provide better stability. Hyperbolic problems are a particular case of Hermitian problems, some solvers may treat them simply as Hermitian. See Also -------- setOperators, setType, getProblemType, slepc.PEPSetProblemType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:572 ` """ ... def getWhichEigenpairs(self) -> Which: """Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.PEPGetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/PEP.pyx:602 ` """ ... def setWhichEigenpairs(self, which: Which) -> None: """Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in PEP account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `PEP.Which.LARGEST_IMAGINARY` and `PEP.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `PEP.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `PEP.Which.ALL` is intended for use in combination with an interval (see `setInterval()`), when all eigenvalues within the interval are requested, or in the context of the `PEP.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- getWhichEigenpairs, setTarget, setInterval, slepc.PEPSetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/PEP.pyx:621 ` """ ... def getTarget(self) -> Scalar: """Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.PEPGetTarget :sources:`Source code at slepc4py/SLEPc/PEP.pyx:658 ` """ ... def setTarget(self, target: Scalar) -> None: """Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, setWhichEigenpairs, slepc.PEPSetTarget :sources:`Source code at slepc4py/SLEPc/PEP.pyx:681 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default PEP convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.PEPGetTolerances :sources:`Source code at slepc4py/SLEPc/PEP.pyx:708 ` """ ... def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default PEP convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.PEPSetTolerances :sources:`Source code at slepc4py/SLEPc/PEP.pyx:733 ` """ ... def getInterval(self) -> tuple[float, float]: """Get the computational interval for spectrum slicing. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. Notes ----- If the interval was not set by the user, then zeros are returned. See Also -------- setInterval, slepc.PEPGetInterval :sources:`Source code at slepc4py/SLEPc/PEP.pyx:764 ` """ ... def setInterval(self, inta: float, intb: float) -> None: """Set the computational interval for spectrum slicing. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- Spectrum slicing is a technique employed for computing all eigenvalues of symmetric quadratic eigenproblems in a given interval. This function provides the interval to be considered. It must be used in combination with `PEP.Which.ALL`, see `setWhichEigenpairs()`. Note that in polynomial eigenproblems spectrum slicing is implemented in `STOAR` only. See Also -------- getInterval, slepc.PEPSetInterval :sources:`Source code at slepc4py/SLEPc/PEP.pyx:790 ` """ ... def getConvergenceTest(self) -> Conv: """Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.PEPGetConvergenceTest :sources:`Source code at slepc4py/SLEPc/PEP.pyx:820 ` """ ... def setConvergenceTest(self, conv: Conv) -> None: """Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.PEPSetConvergenceTest :sources:`Source code at slepc4py/SLEPc/PEP.pyx:840 ` """ ... def getRefine(self) -> tuple[Refine, int, float, int, RefineScheme]: """Get the refinement strategy used by the PEP object. Not collective. Returns ------- ref: Refine The refinement type. npart: int The number of partitions of the communicator. tol: float The convergence tolerance. its: int The maximum number of refinement iterations. scheme: RefineScheme Scheme for solving linear systems. See Also -------- setRefine, slepc.PEPGetRefine :sources:`Source code at slepc4py/SLEPc/PEP.pyx:859 ` """ ... def setRefine(self, ref: Refine, npart: int | None = None, tol: float | None = None, its: int | None = None, scheme: RefineScheme | None = None) -> None: """Set the refinement strategy used by the PEP object. Logically collective. Set the refinement strategy used by the PEP object, and the associated parameters. Parameters ---------- ref The refinement type. npart The number of partitions of the communicator. tol The convergence tolerance. its The maximum number of refinement iterations. scheme Scheme for solving linear systems. See Also -------- getRefine, slepc.PEPSetRefine :sources:`Source code at slepc4py/SLEPc/PEP.pyx:890 ` """ ... def getRefineKSP(self) -> KSP: """Get the ``KSP`` object used by the eigensolver in the refinement phase. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setRefine, slepc.PEPRefineGetKSP :sources:`Source code at slepc4py/SLEPc/PEP.pyx:934 ` """ ... def setExtract(self, extract: Extract) -> None: """Set the extraction strategy to be used. Logically collective. Parameters ---------- extract The extraction strategy. Notes ----- This is relevant for solvers based on linearization. Once the solver has converged, the polynomial eigenvectors can be extracted from the eigenvectors of the linearized problem in different ways. See Also -------- getExtract, slepc.PEPSetExtract :sources:`Source code at slepc4py/SLEPc/PEP.pyx:954 ` """ ... def getExtract(self) -> Extract: """Get the extraction technique used by the `PEP` object. Not collective. Returns ------- Extract The extraction strategy. See Also -------- setExtract, slepc.PEPGetExtract :sources:`Source code at slepc4py/SLEPc/PEP.pyx:979 ` """ ... def getTrackAll(self) -> bool: """Get the flag indicating whether all residual norms must be computed. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.PEPGetTrackAll :sources:`Source code at slepc4py/SLEPc/PEP.pyx:998 ` """ ... def setTrackAll(self, trackall: bool) -> None: """Set flag to compute the residual of all approximate eigenpairs. Logically collective. Set if the solver must compute the residual of all approximate eigenpairs or not. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.PEPSetTrackAll :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1017 ` """ ... def getDimensions(self) -> tuple[int, int, int]: """Get the number of eigenvalues to compute and the dimension of the subspace. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.PEPGetDimensions :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1038 ` """ ... def setDimensions(self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set the number of eigenvalues to compute and the dimension of the subspace. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.PEPSetDimensions :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1063 ` """ ... def getST(self) -> ST: """Get the spectral transformation object associated to the eigensolver. Not collective. Returns ------- ST The spectral transformation. See Also -------- setST, slepc.PEPGetST :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1114 ` """ ... def setST(self, st: ST) -> None: """Set a spectral transformation object associated to the eigensolver. Collective. Parameters ---------- st The spectral transformation. See Also -------- getST, slepc.PEPSetST :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1134 ` """ ... def getScale(self, Dl: petsc4py.PETSc.Vec | None = None, Dr: petsc4py.PETSc.Vec | None = None) -> tuple[Scale, float, int, float]: """Get the strategy used for scaling the polynomial eigenproblem. Not collective. Parameters ---------- Dl Placeholder for the returned left diagonal matrix. Dr Placeholder for the returned right diagonal matrix. Returns ------- scale: Scale The scaling strategy. alpha: float The scaling factor. its: int The number of iterations of diagonal scaling. lbda: float Approximation of the wanted eigenvalues (modulus). See Also -------- setScale, slepc.PEPGetScale :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1151 ` """ ... def setScale(self, scale: Scale, alpha: float | None = None, Dl: petsc4py.PETSc.Vec | None = None, Dr: petsc4py.PETSc.Vec | None = None, its: int | None = None, lbda: float | None = None) -> None: """Set the scaling strategy to be used. Collective. Parameters ---------- scale The scaling strategy. alpha The scaling factor. Dl The left diagonal matrix. Dr The right diagonal matrix. its The number of iterations of diagonal scaling. lbda Approximation of the wanted eigenvalues (modulus). See Also -------- getScale, slepc.PEPSetScale :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1204 ` """ ... def getBV(self) -> BV: """Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.PEPGetBV :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1250 ` """ ... def setBV(self, bv: BV) -> None: """Set a basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.PEPSetBV :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1270 ` """ ... def getRG(self) -> RG: """Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.PEPGetRG :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1287 ` """ ... def setRG(self, rg: RG) -> None: """Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.PEPSetRG :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1307 ` """ ... def getDS(self) -> DS: """Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.PEPGetDS :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1324 ` """ ... def setDS(self, ds: DS) -> None: """Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.PEPSetDS :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1344 ` """ ... def getOperators(self) -> list[Mat]: """Get the matrices associated with the eigenvalue problem. Collective. Returns ------- list of petsc4py.PETSc.Mat The matrices associated with the eigensystem. See Also -------- setOperators, slepc.PEPGetOperators :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1361 ` """ ... def setOperators(self, operators: list[Mat]) -> None: """Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- operators The matrices associated with the eigensystem. Notes ----- The polynomial eigenproblem is defined as :math:`P(\lambda)x=0`, where :math:`\lambda` is the eigenvalue, :math:`x` is the eigenvector, and :math:`P` is defined as :math:`P(\lambda) = A_0 + \lambda A_1 + \dots + \lambda^d A_d`, with :math:`d` = ``nmat``-1 (the degree of :math:`P`). For non-monomial bases, this expression is different. See Also -------- getOperators, slepc.PEPSetOperators :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1387 ` """ ... def setInitialSpace(self, space: Vec | list[Vec]) -> None: """Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space The initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setUp, slepc.PEPSetInitialSpace :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1420 ` """ ... def setStoppingTest(self, stopping: PEPStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.PEPSetStoppingTestFunction :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1459 ` """ ... def getStoppingTest(self) -> PEPStoppingFunction: """Get the stopping test function. Not collective. Returns ------- PEPStoppingFunction The stopping test function. See Also -------- setStoppingTest :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1483 ` """ ... def setEigenvalueComparison(self, comparison: PEPEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `PEP.Which.USER`. See Also -------- getEigenvalueComparison, slepc.PEPSetEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1500 ` """ ... def getEigenvalueComparison(self) -> PEPEigenvalueComparison: """Get the eigenvalue comparison function. Not collective. Returns ------- PEPEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1530 ` """ ... def setMonitor(self, monitor: PEPMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.PEPMonitorSet :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1547 ` """ ... def getMonitor(self) -> PEPMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- PEPMonitorFunction The list of monitor functions. See Also -------- setMonitor :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1572 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for a `PEP` object. Logically collective. See Also -------- slepc.PEPMonitorCancel :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1589 ` """ ... def setUp(self) -> None: """Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This includes the setup of the internal `ST` object. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.PEPSetUp :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1604 ` """ ... def solve(self) -> None: """Solve the polynomial eigenproblem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.PEPSolve :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1626 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.PEPGetIterationNumber :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1648 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.PEPGetConvergedReason :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1670 ` """ ... def getConverged(self) -> int: """Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.PEPGetConverged :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1689 ` """ ... def getEigenpair(self, i: int, Vr: Vec | None = None, Vi: Vec | None = None) -> complex: """Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- complex The computed eigenvalue. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The eigenvector is normalized to have unit norm. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.PEPGetEigenpair :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1715 ` """ ... def getErrorEstimate(self, i: int) -> float: """Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.PEPGetErrorEstimate :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1756 ` """ ... def computeError(self, i: int, etype: ErrorType | None = None) -> float: """Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|P(\lambda)x\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). See Also -------- getErrorEstimate, slepc.PEPComputeError :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1785 ` """ ... def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.PEPErrorView :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1823 ` """ ... def valuesView(self, viewer: Viewer | None = None) -> None: """Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.PEPValuesView :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1855 ` """ ... def vectorsView(self, viewer: Viewer | None = None) -> None: """Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.PEPVectorsView :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1874 ` """ ... def setLinearEPS(self, eps: EPS) -> None: """Set an eigensolver object associated to the polynomial eigenvalue solver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getLinearEPS, slepc.PEPLinearSetEPS :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1895 ` """ ... def getLinearEPS(self) -> EPS: """Get the eigensolver object associated to the polynomial eigenvalue solver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setLinearEPS, slepc.PEPLinearGetEPS :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1912 ` """ ... def setLinearLinearization(self, alpha: float = 1.0, beta: float = 0.0) -> None: """Set the coefficients that define the linearization of a quadratic eigenproblem. Logically collective. Parameters ---------- alpha First parameter of the linearization. beta Second parameter of the linearization. See Also -------- getLinearLinearization, slepc.PEPLinearSetLinearization :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1932 ` """ ... def getLinearLinearization(self) -> tuple[float, float]: """Get the coeffs. defining the linearization of a quadratic eigenproblem. Not collective. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. See Also -------- setLinearLinearization, slepc.PEPLinearGetLinearization :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1953 ` """ ... def setLinearExplicitMatrix(self, flag: bool) -> None: """Set flag to explicitly build the matrices for the linearization. Logically collective. Parameters ---------- flag Boolean flag indicating if the matrices are built explicitly. See Also -------- getLinearExplicitMatrix, slepc.PEPLinearSetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1975 ` """ ... def getLinearExplicitMatrix(self) -> bool: """Get if the matrices for the linearization are built explicitly. Not collective. Returns ------- bool Boolean flag indicating if the matrices are built explicitly. See Also -------- getLinearExplicitMatrix, slepc.PEPLinearSetExplicitMatrix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:1993 ` """ ... def setQArnoldiRestart(self, keep: float) -> None: """Set the restart parameter for the Q-Arnoldi method. Logically collective. Set the restart parameter for the Q-Arnoldi method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getQArnoldiRestart, slepc.PEPQArnoldiSetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2014 ` """ ... def getQArnoldiRestart(self) -> float: """Get the restart parameter used in the Q-Arnoldi method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setQArnoldiRestart, slepc.PEPQArnoldiGetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2040 ` """ ... def setQArnoldiLocking(self, lock: bool) -> None: """Toggle between locking and non-locking variants of the Q-Arnoldi method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getQArnoldiLocking, slepc.PEPQArnoldiSetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2059 ` """ ... def getQArnoldiLocking(self) -> bool: """Get the locking flag used in the Q-Arnoldi method. Not collective. Returns ------- bool The locking flag. See Also -------- setQArnoldiLocking, slepc.PEPQArnoldiGetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2084 ` """ ... def setTOARRestart(self, keep: float) -> None: """Set the restart parameter for the TOAR method. Logically collective. Set the restart parameter for the TOAR method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getTOARRestart, slepc.PEPTOARSetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2105 ` """ ... def getTOARRestart(self) -> float: """Get the restart parameter used in the TOAR method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setTOARRestart, slepc.PEPTOARGetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2131 ` """ ... def setTOARLocking(self, lock: bool) -> None: """Toggle between locking and non-locking variants of the TOAR method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getTOARLocking, slepc.PEPTOARSetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2150 ` """ ... def getTOARLocking(self) -> bool: """Get the locking flag used in the TOAR method. Not collective. Returns ------- bool The locking flag. See Also -------- setTOARLocking, slepc.PEPTOARGetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2175 ` """ ... def setSTOARLinearization(self, alpha: float = 1.0, beta: float = 0.0) -> None: """Set the coefficients that define the linearization of a quadratic eigenproblem. Logically collective. Parameters ---------- alpha First parameter of the linearization. beta Second parameter of the linearization. See Also -------- getSTOARLinearization, slepc.PEPSTOARSetLinearization :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2196 ` """ ... def getSTOARLinearization(self) -> tuple[float, float]: """Get the coefficients that define the linearization of a quadratic eigenproblem. Not collective. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. See Also -------- setSTOARLinearization, slepc.PEPSTOARGetLinearization :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2217 ` """ ... def setSTOARLocking(self, lock: bool) -> None: """Toggle between locking and non-locking variants of the STOAR method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getSTOARLocking, slepc.PEPSTOARSetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2239 ` """ ... def getSTOARLocking(self) -> bool: """Get the locking flag used in the STOAR method. Not collective. Returns ------- bool The locking flag. See Also -------- setSTOARLocking, slepc.PEPSTOARGetLocking :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2264 ` """ ... def setSTOARDetectZeros(self, detect: bool) -> None: """Set flag to enforce detection of zeros during the factorizations. Logically collective. Set a flag to enforce detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect ``True`` if zeros must checked for. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. A zero in the factorization indicates that a shift coincides with an eigenvalue. This flag is turned off by default, and may be necessary in some cases. This feature currently requires an external package for factorizations with support for zero detection, e.g. MUMPS. See Also -------- setInterval, getSTOARDetectZeros, slepc.PEPSTOARSetDetectZeros :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2283 ` """ ... def getSTOARDetectZeros(self) -> bool: """Get the flag that enforces zero detection in spectrum slicing. Not collective. Returns ------- bool The zero detection flag. See Also -------- setSTOARDetectZeros, slepc.PEPSTOARGetDetectZeros :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2316 ` """ ... def setSTOARDimensions(self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set the dimensions used for each subsolve step. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. The meaning of the parameters is the same as in `setDimensions()`, but the ones here apply to every subsolve done by the child `PEP` object. See Also -------- setInterval, setDimensions, getSTOARDimensions, slepc.PEPSTOARSetDimensions :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2335 ` """ ... def getSTOARDimensions(self) -> tuple[int, int, int]: """Get the dimensions used for each subsolve step. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setSTOARDimensions, slepc.PEPSTOARGetDimensions :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2375 ` """ ... def getSTOARInertias(self) -> tuple[ArrayReal, ArrayInt]: """Get the values of the shifts and their corresponding inertias. Not collective. Get the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: ArrayReal The values of the shifts used internally in the solver. inertias: ArrayInt The values of the inertia in each shift. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If called after `solve()`, all shifts used internally by the solver are returned (including both endpoints and any intermediate ones). If called before `solve()` and after `setUp()` then only the information of the endpoints of subintervals is available. See Also -------- setInterval, slepc.PEPSTOARGetInertias :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2400 ` """ ... def setSTOARCheckEigenvalueType(self, flag: bool) -> None: """Set flag to check if all eigenvalues have the same definite type. Logically collective. Set a flag to check that all the eigenvalues obtained throughout the spectrum slicing computation have the same definite type. Parameters ---------- flag Whether the eigenvalue type is checked or not. Notes ----- This option is relevant only for spectrum slicing computations, but is ignored in `slepc4py.SLEPc.PEP.ProblemType.HYPERBOLIC` problems. This flag is turned on by default, to guarantee that the computed eigenvalues have the same type (otherwise the computed solution might be wrong). But since the check is computationally quite expensive, the check may be turned off if the user knows for sure that all eigenvalues in the requested interval have the same type. See Also -------- getSTOARCheckEigenvalueType, slepc.PEPSTOARSetCheckEigenvalueType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2444 ` """ ... def getSTOARCheckEigenvalueType(self) -> bool: """Get the flag for the eigenvalue type check in spectrum slicing. Not collective. Returns ------- bool Whether the eigenvalue type is checked or not. See Also -------- setSTOARCheckEigenvalueType, slepc.PEPSTOARGetCheckEigenvalueType :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2476 ` """ ... def setJDRestart(self, keep: float) -> None: """Set the restart parameter for the Jacobi-Davidson method. Logically collective. Set the restart parameter for the Jacobi-Davidson method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getJDRestart, slepc.PEPJDSetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2497 ` """ ... def getJDRestart(self) -> float: """Get the restart parameter used in the Jacobi-Davidson method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setJDRestart, slepc.PEPJDGetRestart :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2523 ` """ ... def setJDFix(self, fix: float) -> None: """Set the threshold for changing the target in the correction equation. Logically collective. Parameters ---------- fix Threshold for changing the target. Notes ----- The target in the correction equation is fixed at the first iterations. When the norm of the residual vector is lower than the fix value, the target is set to the corresponding eigenvalue. See Also -------- getJDFix, slepc.PEPJDSetFix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2542 ` """ ... def getJDFix(self) -> float: """Get threshold for changing the target in the correction equation. Not collective. Returns ------- float The threshold for changing the target. See Also -------- setJDFix, slepc.PEPJDGetFix :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2566 ` """ ... def setJDReusePreconditioner(self, flag: bool) -> None: """Set a flag indicating whether the preconditioner must be reused or not. Logically collective. Parameters ---------- flag The reuse flag. Notes ----- The default value is ``False``. If set to ``True``, the preconditioner is built only at the beginning, using the target value. Otherwise, it may be rebuilt (depending on the ``fix`` parameter) at each iteration from the Ritz value. See Also -------- setJDFix, getJDReusePreconditioner, slepc.PEPJDSetReusePreconditioner :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2585 ` """ ... def getJDReusePreconditioner(self) -> bool: """Get the flag for reusing the preconditioner. Not collective. Returns ------- bool The reuse flag. See Also -------- setJDReusePreconditioner, slepc.PEPJDGetReusePreconditioner :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2610 ` """ ... def setJDMinimalityIndex(self, flag: int) -> None: """Set the maximum allowed value for the minimality index. Logically collective. Parameters ---------- flag The maximum minimality index. Notes ----- The default value is equal to the degree of the polynomial. A smaller value can be used if the wanted eigenvectors are known to be linearly independent. See Also -------- getJDMinimalityIndex, slepc.PEPJDSetMinimalityIndex :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2629 ` """ ... def getJDMinimalityIndex(self) -> int: """Get the maximum allowed value of the minimality index. Not collective. Returns ------- int The maximum minimality index. See Also -------- setJDMinimalityIndex, slepc.PEPJDGetMinimalityIndex :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2653 ` """ ... def setJDProjection(self, proj: JDProjection) -> None: """Set the type of projection to be used in the Jacobi-Davidson solver. Logically collective. Parameters ---------- proj The type of projection. See Also -------- getJDProjection, slepc.PEPJDSetProjection :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2672 ` """ ... def getJDProjection(self) -> JDProjection: """Get the type of projection to be used in the Jacobi-Davidson solver. Not collective. Returns ------- JDProjection The type of projection. See Also -------- setJDProjection, slepc.PEPJDGetProjection :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2690 ` """ ... def setCISSExtraction(self, extraction: CISSExtraction) -> None: """Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.PEPCISSSetExtraction :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2711 ` """ ... def getCISSExtraction(self) -> CISSExtraction: """Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.PEPCISSGetExtraction :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2729 ` """ ... def setCISSSizes(self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False) -> None: """Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `PEP` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.PEPCISSSetSizes :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2748 ` """ ... def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.PEPCISSGetSizes :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2802 ` """ ... def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.PEPCISSSetThreshold :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2836 ` """ ... def getCISSThreshold(self) -> tuple[float, float]: """Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.PEPCISSGetThreshold :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2859 ` """ ... def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.PEPCISSSetRefinement :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2881 ` """ ... def getCISSRefinement(self) -> tuple[int, int]: """Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.PEPCISSGetRefinement :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2904 ` """ ... def getCISSKSPs(self) -> list[KSP]: """Get the array of linear solver objects associated with the CISS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.PEPCISSGetKSPs :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2926 ` """ ... @property def problem_type(self) -> PEPProblemType: """The type of the eigenvalue problem. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2955 ` """ ... @property def which(self) -> PEPWhich: """The portion of the spectrum to be sought. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2962 ` """ ... @property def target(self) -> float: """The value of the target. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2969 ` """ ... @property def extract(self) -> PEPExtract: """The type of extraction technique to be employed. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2976 ` """ ... @property def tol(self) -> float: """The tolerance. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2983 ` """ ... @property def max_it(self) -> int: """The maximum iteration count. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2990 ` """ ... @property def track_all(self) -> bool: """Compute the residual norm of all approximate eigenpairs. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:2997 ` """ ... @property def st(self) -> ST: """The spectral transformation (`ST`) object associated. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:3004 ` """ ... @property def bv(self) -> BV: """The basis vectors (`BV`) object associated. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:3011 ` """ ... @property def rg(self) -> RG: """The region (`RG`) object associated. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:3018 ` """ ... @property def ds(self) -> DS: """The direct solver (`DS`) object associated. :sources:`Source code at slepc4py/SLEPc/PEP.pyx:3025 ` """ ... class NEP(Object): """Nonlinear Eigenvalue Problem Solver. The Nonlinear Eigenvalue Problem (`NEP`) solver is the object provided by slepc4py for specifying an eigenvalue problem that is nonlinear with respect to the eigenvalue (not the eigenvector). This is intended for general nonlinear problems (rather than polynomial eigenproblems) described as :math:`T(\lambda) x=0`. """ class Type: """NEP type. - `RII`: Residual inverse iteration. - `SLP`: Successive linear problems. - `NARNOLDI`: Nonlinear Arnoldi. - `NLEIGS`: Fully rational Krylov method for nonlinear eigenproblems. - `CISS`: Contour integral spectrum slice. - `INTERPOL`: Polynomial interpolation. See Also -------- slepc.NEPType """ RII: str = _def(str, 'RII') #: Object ``RII`` of type :class:`str` SLP: str = _def(str, 'SLP') #: Object ``SLP`` of type :class:`str` NARNOLDI: str = _def(str, 'NARNOLDI') #: Object ``NARNOLDI`` of type :class:`str` NLEIGS: str = _def(str, 'NLEIGS') #: Object ``NLEIGS`` of type :class:`str` CISS: str = _def(str, 'CISS') #: Object ``CISS`` of type :class:`str` INTERPOL: str = _def(str, 'INTERPOL') #: Object ``INTERPOL`` of type :class:`str` class ProblemType: """NEP problem type. - `GENERAL`: General nonlinear eigenproblem. - `RATIONAL`: NEP defined in split form with all :math:`f_i` rational. See Also -------- slepc.NEPProblemType """ GENERAL: int = _def(int, 'GENERAL') #: Constant ``GENERAL`` of type :class:`int` RATIONAL: int = _def(int, 'RATIONAL') #: Constant ``RATIONAL`` of type :class:`int` class ErrorType: """NEP error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.NEPErrorType """ ABSOLUTE: int = _def(int, 'ABSOLUTE') #: Constant ``ABSOLUTE`` of type :class:`int` RELATIVE: int = _def(int, 'RELATIVE') #: Constant ``RELATIVE`` of type :class:`int` BACKWARD: int = _def(int, 'BACKWARD') #: Constant ``BACKWARD`` of type :class:`int` class Which: """NEP desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in a region. - `USER`: User defined selection. See Also -------- slepc.NEPWhich """ LARGEST_MAGNITUDE: int = _def(int, 'LARGEST_MAGNITUDE') #: Constant ``LARGEST_MAGNITUDE`` of type :class:`int` SMALLEST_MAGNITUDE: int = _def(int, 'SMALLEST_MAGNITUDE') #: Constant ``SMALLEST_MAGNITUDE`` of type :class:`int` LARGEST_REAL: int = _def(int, 'LARGEST_REAL') #: Constant ``LARGEST_REAL`` of type :class:`int` SMALLEST_REAL: int = _def(int, 'SMALLEST_REAL') #: Constant ``SMALLEST_REAL`` of type :class:`int` LARGEST_IMAGINARY: int = _def(int, 'LARGEST_IMAGINARY') #: Constant ``LARGEST_IMAGINARY`` of type :class:`int` SMALLEST_IMAGINARY: int = _def(int, 'SMALLEST_IMAGINARY') #: Constant ``SMALLEST_IMAGINARY`` of type :class:`int` TARGET_MAGNITUDE: int = _def(int, 'TARGET_MAGNITUDE') #: Constant ``TARGET_MAGNITUDE`` of type :class:`int` TARGET_REAL: int = _def(int, 'TARGET_REAL') #: Constant ``TARGET_REAL`` of type :class:`int` TARGET_IMAGINARY: int = _def(int, 'TARGET_IMAGINARY') #: Constant ``TARGET_IMAGINARY`` of type :class:`int` ALL: int = _def(int, 'ALL') #: Constant ``ALL`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class ConvergedReason: """NEP convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_LINEAR_SOLVE`: Inner linear solve failed. - `DIVERGED_SUBSPACE_EXHAUSTED`: Run out of space for the basis in an unrestarted solver. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.NEPConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` CONVERGED_USER: int = _def(int, 'CONVERGED_USER') #: Constant ``CONVERGED_USER`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` DIVERGED_LINEAR_SOLVE: int = _def(int, 'DIVERGED_LINEAR_SOLVE') #: Constant ``DIVERGED_LINEAR_SOLVE`` of type :class:`int` DIVERGED_SUBSPACE_EXHAUSTED: int = _def(int, 'DIVERGED_SUBSPACE_EXHAUSTED') #: Constant ``DIVERGED_SUBSPACE_EXHAUSTED`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` class Refine: """NEP refinement strategy. - `NONE`: No refinement. - `SIMPLE`: Refine eigenpairs one by one. - `MULTIPLE`: Refine all eigenpairs simultaneously (invariant pair). See Also -------- slepc.NEPRefine """ NONE: int = _def(int, 'NONE') #: Constant ``NONE`` of type :class:`int` SIMPLE: int = _def(int, 'SIMPLE') #: Constant ``SIMPLE`` of type :class:`int` MULTIPLE: int = _def(int, 'MULTIPLE') #: Constant ``MULTIPLE`` of type :class:`int` class RefineScheme: """NEP scheme for solving linear systems during iterative refinement. - `SCHUR`: Schur complement. - `MBE`: Mixed block elimination. - `EXPLICIT`: Build the explicit matrix. See Also -------- slepc.NEPRefineScheme """ SCHUR: int = _def(int, 'SCHUR') #: Constant ``SCHUR`` of type :class:`int` MBE: int = _def(int, 'MBE') #: Constant ``MBE`` of type :class:`int` EXPLICIT: int = _def(int, 'EXPLICIT') #: Constant ``EXPLICIT`` of type :class:`int` class Conv: """NEP convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.NEPConv """ ABS: int = _def(int, 'ABS') #: Constant ``ABS`` of type :class:`int` REL: int = _def(int, 'REL') #: Constant ``REL`` of type :class:`int` NORM: int = _def(int, 'NORM') #: Constant ``NORM`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class Stop: """NEP stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. See Also -------- slepc.NEPStop """ BASIC: int = _def(int, 'BASIC') #: Constant ``BASIC`` of type :class:`int` USER: int = _def(int, 'USER') #: Constant ``USER`` of type :class:`int` class CISSExtraction: """NEP CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. - `CAA`: Communication-avoiding Arnoldi. See Also -------- slepc.NEPCISSExtraction """ RITZ: int = _def(int, 'RITZ') #: Constant ``RITZ`` of type :class:`int` HANKEL: int = _def(int, 'HANKEL') #: Constant ``HANKEL`` of type :class:`int` CAA: int = _def(int, 'CAA') #: Constant ``CAA`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the NEP data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.NEPView :sources:`Source code at slepc4py/SLEPc/NEP.pyx:223 ` """ ... def destroy(self) -> Self: """Destroy the NEP object. Collective. See Also -------- slepc.NEPDestroy :sources:`Source code at slepc4py/SLEPc/NEP.pyx:242 ` """ ... def reset(self) -> None: """Reset the NEP object. Collective. See Also -------- slepc.NEPReset :sources:`Source code at slepc4py/SLEPc/NEP.pyx:256 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the NEP object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.NEPCreate :sources:`Source code at slepc4py/SLEPc/NEP.pyx:268 ` """ ... def setType(self, nep_type: Type | str) -> None: """Set the particular solver to be used in the NEP object. Logically collective. Parameters ---------- nep_type The solver to be used. Notes ----- The default is `RII`. Normally, it is best to use `setFromOptions()` and then set the NEP type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.NEPSetType :sources:`Source code at slepc4py/SLEPc/NEP.pyx:289 ` """ ... def getType(self) -> str: """Get the NEP type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.NEPGetType :sources:`Source code at slepc4py/SLEPc/NEP.pyx:316 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all NEP options in the database. Not collective. Returns ------- str The prefix string set for this NEP object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.NEPGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/NEP.pyx:335 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all NEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all NEP option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different NEP contexts, one could call:: N1.setOptionsPrefix("nep1_") N2.setOptionsPrefix("nep2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.NEPGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/NEP.pyx:354 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all NEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all NEP option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.NEPAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/NEP.pyx:385 ` """ ... def setFromOptions(self) -> None: """Set NEP options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.NEPSetFromOptions :sources:`Source code at slepc4py/SLEPc/NEP.pyx:404 ` """ ... def getProblemType(self) -> ProblemType: """Get the problem type from the `NEP` object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.NEPGetProblemType :sources:`Source code at slepc4py/SLEPc/NEP.pyx:423 ` """ ... def setProblemType(self, problem_type: ProblemType) -> None: """Set the type of the eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function is used to provide a hint to the `NEP` solver to exploit certain properties of the nonlinear eigenproblem. This hint may be used or not, depending on the solver. By default, no particular structure is assumed. See Also -------- getProblemType, slepc.NEPSetProblemType :sources:`Source code at slepc4py/SLEPc/NEP.pyx:442 ` """ ... def getWhichEigenpairs(self) -> Which: """Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.NEPGetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/NEP.pyx:467 ` """ ... def setWhichEigenpairs(self, which: Which) -> None: """Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in NEP account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `NEP.Which.LARGEST_IMAGINARY` and `NEP.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `NEP.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `NEP.Which.ALL` is intended for use in the context of the `PEP.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- getWhichEigenpairs, setTarget, slepc.PEPSetWhichEigenpairs :sources:`Source code at slepc4py/SLEPc/NEP.pyx:486 ` """ ... def getTarget(self) -> Scalar: """Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.NEPGetTarget :sources:`Source code at slepc4py/SLEPc/NEP.pyx:521 ` """ ... def setTarget(self, target: Scalar) -> None: """Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, setWhichEigenpairs, slepc.NEPSetTarget :sources:`Source code at slepc4py/SLEPc/NEP.pyx:544 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default NEP convergence tests. Returns ------- tol: float The convergence tolerance. maxit: int The maximum number of iterations. See Also -------- setTolerances, slepc.NEPGetTolerances :sources:`Source code at slepc4py/SLEPc/NEP.pyx:571 ` """ ... def setTolerances(self, tol: float | None = None, maxit: int | None = None) -> None: """Set the tolerance and max. iteration count used in convergence tests. Logically collective. Parameters ---------- tol The convergence tolerance. maxit The maximum number of iterations. Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.NEPSetTolerances :sources:`Source code at slepc4py/SLEPc/NEP.pyx:596 ` """ ... def getConvergenceTest(self) -> Conv: """Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.NEPGetConvergenceTest :sources:`Source code at slepc4py/SLEPc/NEP.pyx:624 ` """ ... def setConvergenceTest(self, conv: Conv) -> None: """Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.NEPSetConvergenceTest :sources:`Source code at slepc4py/SLEPc/NEP.pyx:644 ` """ ... def getRefine(self) -> tuple[Refine, int, float, int, RefineScheme]: """Get the refinement strategy used by the NEP object. Not collective. Returns ------- ref: Refine The refinement type. npart: int The number of partitions of the communicator. tol: float The convergence tolerance. its: int The maximum number of refinement iterations. scheme: RefineScheme Scheme for solving linear systems. See Also -------- setRefine, slepc.NEPGetRefine :sources:`Source code at slepc4py/SLEPc/NEP.pyx:663 ` """ ... def setRefine(self, ref: Refine, npart: int | None = None, tol: float | None = None, its: int | None = None, scheme: RefineScheme | None = None) -> None: """Set the refinement strategy used by the NEP object. Logically collective. Set the refinement strategy used by the NEP object and the associated parameters. Parameters ---------- ref The refinement type. npart The number of partitions of the communicator. tol The convergence tolerance. its The maximum number of refinement iterations. scheme Scheme for solving linear systems. See Also -------- getRefine, slepc.NEPSetRefine :sources:`Source code at slepc4py/SLEPc/NEP.pyx:694 ` """ ... def getRefineKSP(self) -> KSP: """Get the ``KSP`` object used by the eigensolver in the refinement phase. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setRefine, slepc.NEPRefineGetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:738 ` """ ... def getTrackAll(self) -> bool: """Get the flag indicating whether all residual norms must be computed. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.NEPGetTrackAll :sources:`Source code at slepc4py/SLEPc/NEP.pyx:758 ` """ ... def setTrackAll(self, trackall: bool) -> None: """Set if the solver must compute the residual of all approximate eigenpairs. Logically collective. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.NEPSetTrackAll :sources:`Source code at slepc4py/SLEPc/NEP.pyx:777 ` """ ... def getDimensions(self) -> tuple[int, int, int]: """Get the number of eigenvalues to compute. Not collective. Get the number of eigenvalues to compute, and the dimension of the subspace. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.NEPGetDimensions :sources:`Source code at slepc4py/SLEPc/NEP.pyx:795 ` """ ... def setDimensions(self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None) -> None: """Set the number of eigenvalues to compute. Logically collective. Set the number of eigenvalues to compute and the dimension of the subspace. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.NEPSetDimensions :sources:`Source code at slepc4py/SLEPc/NEP.pyx:823 ` """ ... def getBV(self) -> BV: """Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.NEPGetBV :sources:`Source code at slepc4py/SLEPc/NEP.pyx:877 ` """ ... def setBV(self, bv: BV) -> None: """Set the basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.NEPSetBV :sources:`Source code at slepc4py/SLEPc/NEP.pyx:897 ` """ ... def getRG(self) -> RG: """Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.NEPGetRG :sources:`Source code at slepc4py/SLEPc/NEP.pyx:914 ` """ ... def setRG(self, rg: RG) -> None: """Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.NEPSetRG :sources:`Source code at slepc4py/SLEPc/NEP.pyx:934 ` """ ... def getDS(self) -> DS: """Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.NEPGetDS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:951 ` """ ... def setDS(self, ds: DS) -> None: """Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.NEPSetDS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:971 ` """ ... def setInitialSpace(self, space: Vec or list[Vec]) -> None: """Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space The initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setUp, slepc.NEPSetInitialSpace :sources:`Source code at slepc4py/SLEPc/NEP.pyx:990 ` """ ... def setStoppingTest(self, stopping: NEPStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.NEPSetStoppingTestFunction :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1029 ` """ ... def getStoppingTest(self) -> NEPStoppingFunction: """Get the stopping test function. Not collective. Returns ------- NEPStoppingFunction The stopping test function. See Also -------- setStoppingTest :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1053 ` """ ... def setEigenvalueComparison(self, comparison: NEPEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `NEP.Which.USER`. See Also -------- getEigenvalueComparison, slepc.NEPSetEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1070 ` """ ... def getEigenvalueComparison(self) -> NEPEigenvalueComparison: """Get the eigenvalue comparison function. Not collective. Returns ------- NEPEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1100 ` """ ... def setMonitor(self, monitor: NEPMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.NEPMonitorSet :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1117 ` """ ... def getMonitor(self) -> NEPMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- NEPMonitorFunction The list of monitor functions. See Also -------- setMonitor :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1142 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for a `NEP` object. Logically collective. See Also -------- slepc.NEPMonitorCancel :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1159 ` """ ... def setUp(self) -> None: """Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.NEPSetUp :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1174 ` """ ... def solve(self) -> None: """Solve the nonlinear eigenproblem. Collective. Notes ----- `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, getConverged, getConvergedReason, slepc.NEPSolve :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1195 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.NEPGetIterationNumber :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1215 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.NEPGetConvergedReason :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1237 ` """ ... def getConverged(self) -> int: """Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.NEPGetConverged :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1256 ` """ ... def getEigenpair(self, i: int, Vr: Vec | None = None, Vi: Vec | None = None) -> None: """Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- complex The computed eigenvalue. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The eigenvector is normalized to have unit norm. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.NEPGetEigenpair :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1282 ` """ ... def getLeftEigenvector(self, i: int, Wr: Vec, Wi: Vec | None = None) -> None: """Get the i-th left eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Wr Placeholder for the returned eigenvector (real part). Wi Placeholder for the returned eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigensolutions are indexed according to the ordering criterion established with `setWhichEigenpairs()`. Left eigenvectors are available only if the ``twosided`` flag was set with `setTwoSided()`. See Also -------- getEigenpair, getConverged, setTwoSided, slepc.NEPGetLeftEigenvector :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1323 ` """ ... def getErrorEstimate(self, i: int) -> float: """Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.NEPGetErrorEstimate :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1356 ` """ ... def computeError(self, i: int, etype: ErrorType | None = None) -> float: """Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|T(\lambda)x\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). If the computation of left eigenvectors was enabled with `setTwoSided()`, then the error will be computed using the maximum of the value above and the left residual norm :math:`\|y^*T(\lambda)\|_2`, where :math:`y` is the approximate left eigenvector. See Also -------- getErrorEstimate, setTwoSided, slepc.NEPComputeError :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1385 ` """ ... def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.NEPErrorView :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1428 ` """ ... def valuesView(self, viewer: Viewer | None = None) -> None: """Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.NEPValuesView :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1460 ` """ ... def vectorsView(self, viewer: Viewer | None = None) -> None: """Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.NEPVectorsView :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1479 ` """ ... def setFunction(self, function: NEPFunction, F: petsc4py.PETSc.Mat | None = None, P: petsc4py.PETSc.Mat | None = None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set the function to compute the nonlinear Function :math:`T(\lambda)`. Collective. Set the function to compute the nonlinear Function :math:`T(\lambda)` as well as the location to store the matrix. Parameters ---------- function Function evaluation routine. F Function matrix. P Preconditioner matrix (usually the same as ``F``). See Also -------- setJacobian, getFunction, slepc.NEPSetFunction :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1500 ` """ ... def getFunction(self) -> tuple[petsc4py.PETSc.Mat, petsc4py.PETSc.Mat, NEPFunction]: """Get the function to compute the nonlinear Function :math:`T(\lambda)`. Collective. Get the function to compute the nonlinear Function :math:`T(\lambda)` and the matrix. Returns ------- F: petsc4py.PETSc.Mat Function matrix. P: petsc4py.PETSc.Mat Preconditioner matrix (usually the same as the F). function: NEPFunction Function evaluation routine. See Also -------- setFunction, slepc.NEPGetFunction :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1540 ` """ ... def setJacobian(self, jacobian: NEPJacobian, J: petsc4py.PETSc.Mat | None = None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Set the function to compute the Jacobian :math:`T'(\lambda)`. Collective. Set the function to compute the Jacobian :math:`T'(\lambda)` as well as the location to store the matrix. Parameters ---------- jacobian Jacobian evaluation routine. J Jacobian matrix. See Also -------- setFunction, getJacobian, slepc.NEPSetJacobian :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1570 ` """ ... def getJacobian(self) -> tuple[petsc4py.PETSc.Mat, NEPJacobian]: """Get the function to compute the Jacobian :math:`T'(\lambda)` and J. Collective. Get the function to compute the Jacobian :math:`T'(\lambda)` and the matrix. Returns ------- J: petsc4py.PETSc.Mat Jacobian matrix. jacobian: NEPJacobian Jacobian evaluation routine. See Also -------- setJacobian, slepc.NEPGetJacobian :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1606 ` """ ... def setSplitOperator(self, A: petsc4py.PETSc.Mat | list[petsc4py.PETSc.Mat], f: FN | list[FN], structure: petsc4py.PETSc.Mat.Structure | None = None) -> None: """Set the operator of the nonlinear eigenvalue problem in split form. Collective. Parameters ---------- A Coefficient matrices of the split form. f Scalar functions of the split form. structure Structure flag for matrices. Notes ----- The nonlinear operator is written as :math:`T(\lambda) = \sum_i A_i f_i(\lambda)`, for :math:`i=1,\dots,n`. The derivative :math:`T'(\lambda)` can be obtained using the derivatives of :math:`f_i`. The ``structure`` flag provides information about :math:`A_i`'s nonzero pattern. This function must be called before `setUp()`. If it is called again after `setUp()` then the `NEP` object is reset. See Also -------- getSplitOperator, slepc.NEPSetSplitOperator :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1632 ` """ ... def getSplitOperator(self) -> tuple[list[petsc4py.PETSc.Mat], list[FN], petsc4py.PETSc.Mat.Structure]: """Get the operator of the nonlinear eigenvalue problem in split form. Collective. Returns ------- A: list of petsc4py.PETSc.Mat Coefficient matrices of the split form. f: list of FN Scalar functions of the split form. structure: petsc4py.PETSc.Mat.Structure Structure flag for matrices. See Also -------- setSplitOperator, slepc.NEPGetSplitOperatorInfo, slepc.NEPGetSplitOperatorTerm :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1683 ` """ ... def setSplitPreconditioner(self, P: petsc4py.PETSc.Mat | list[petsc4py.PETSc.Mat], structure: petsc4py.PETSc.Mat.Structure | None = None) -> None: """Set the operator in split form. Collective. Set the operator in split form from which to build the preconditioner to be used when solving the nonlinear eigenvalue problem in split form. Parameters ---------- P Coefficient matrices of the split preconditioner. structure Structure flag for matrices. See Also -------- getSplitPreconditioner, slepc.NEPSetSplitPreconditioner :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1719 ` """ ... def getSplitPreconditioner(self) -> tuple[list[petsc4py.PETSc.Mat], petsc4py.PETSc.Mat.Structure]: """Get the operator of the split preconditioner. Not collective. Returns ------- P: list of petsc4py.PETSc.Mat Coefficient matrices of the split preconditioner. structure: petsc4py.PETSc.Mat.Structure Structure flag for matrices. See Also -------- setSplitPreconditioner, slepc.NEPGetSplitPreconditionerTerm :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1752 ` """ ... def getTwoSided(self) -> bool: """Get the flag indicating if a two-sided variant is being used. Not collective. Get the flag indicating whether a two-sided variant of the algorithm is being used or not. Returns ------- bool Whether the two-sided variant is to be used or not. See Also -------- setTwoSided, slepc.NEPGetTwoSided :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1781 ` """ ... def setTwoSided(self, twosided: bool) -> None: """Set the solver to use a two-sided variant. Logically collective. Set the solver to use a two-sided variant so that left eigenvectors are also computed. Parameters ---------- twosided Whether the two-sided variant is to be used or not. Notes ----- If the user sets ``twosided`` to ``True`` then the solver uses a variant of the algorithm that computes both right and left eigenvectors. This is usually much more costly. This option is not available in all solvers. When using two-sided solvers, the problem matrices must have both the ``Mat.mult`` and ``Mat.multTranspose`` operations defined. See Also -------- getTwoSided, getLeftEigenvector, slepc.NEPSetTwoSided :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1803 ` """ ... def applyResolvent(self, omega: Scalar, v: Vec, r: Vec, rg: RG | None = None) -> None: """Apply the resolvent :math:`T^{-1}(z)` to a given vector. Collective. Parameters ---------- omega Value where the resolvent must be evaluated. v Input vector. r Placeholder for the result vector. rg Region. Notes ----- The resolvent :math:`T^{-1}(z)=\sum_i(z-\lambda_i)^{-1}x_iy_i^*` is evaluated at :math:`z=\omega` and the matrix-vector product :math:`r = T^{-1}(\omega) v` is computed. Vectors :math:`x_i,y_i` are right and left eigenvectors, respectively, normalized so that :math:`y_i^*T'(\lambda_i)x_i=1`. The sum contains only eigenvectors that have been previously computed with `solve()`, and if a region ``rg`` is given then only those corresponding to eigenvalues inside the region are considered. See Also -------- solve, getLeftEigenvector, slepc.NEPApplyResolvent :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1834 ` """ ... def setRIILagPreconditioner(self, lag: int) -> None: """Set when the preconditioner is rebuilt in the nonlinear solve. Logically collective. Parameters ---------- lag 0 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within the nonlinear iteration, 2 means every second time the Jacobian is built, etc. See Also -------- getRIILagPreconditioner, slepc.NEPRIISetLagPreconditioner :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1878 ` """ ... def getRIILagPreconditioner(self) -> int: """Get how often the preconditioner is rebuilt. Not collective. Returns ------- int The lag parameter. See Also -------- setRIILagPreconditioner, slepc.NEPRIIGetLagPreconditioner :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1898 ` """ ... def setRIIConstCorrectionTol(self, cct: bool) -> None: """Set a flag to keep the tolerance used in the linear solver constant. Logically collective. Parameters ---------- cct If ``True``, the `petsc4py.PETSc.KSP` relative tolerance is constant. Notes ----- By default, an exponentially decreasing tolerance is set in the ``KSP`` used within the nonlinear iteration, so that each Newton iteration requests better accuracy than the previous one. The constant correction tolerance flag stops this behavior. See Also -------- getRIIConstCorrectionTol, slepc.NEPRIISetConstCorrectionTol :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1917 ` """ ... def getRIIConstCorrectionTol(self) -> bool: """Get the constant tolerance flag. Not collective. Returns ------- bool If ``True``, the `petsc4py.PETSc.KSP` relative tolerance is constant. See Also -------- setRIIConstCorrectionTol, slepc.NEPRIIGetConstCorrectionTol :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1942 ` """ ... def setRIIMaximumIterations(self, its: int) -> None: """Set the max. number of inner iterations to be used in the RII solver. Logically collective. These are the Newton iterations related to the computation of the nonlinear Rayleigh functional. Parameters ---------- its Maximum inner iterations. See Also -------- getRIIMaximumIterations, slepc.NEPRIISetMaximumIterations :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1962 ` """ ... def getRIIMaximumIterations(self) -> int: """Get the maximum number of inner iterations of RII. Not collective. Returns ------- int Maximum inner iterations. See Also -------- setRIIMaximumIterations, slepc.NEPRIIGetMaximumIterations :sources:`Source code at slepc4py/SLEPc/NEP.pyx:1983 ` """ ... def setRIIHermitian(self, herm: bool) -> None: """Set a flag to use the Hermitian version of the solver. Logically collective. Set a flag to indicate if the Hermitian version of the scalar nonlinear equation must be used by the solver. Parameters ---------- herm If ``True``, the Hermitian version is used. Notes ----- By default, the scalar nonlinear equation :math:`x^*T(\sigma)^{-1}T(z)x=0` is solved at each step of the nonlinear iteration. When this flag is set the simpler form :math:`x^*T(z)x=0` is used, which is supposed to be valid only for Hermitian problems. See Also -------- getRIIHermitian, slepc.NEPRIISetHermitian :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2002 ` """ ... def getRIIHermitian(self) -> bool: """Get if the Hermitian version must be used by the solver. Not collective. Returns ------- bool If ``True``, the Hermitian version is used. See Also -------- setRIIHermitian, slepc.NEPRIIGetHermitian :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2031 ` """ ... def setRIIDeflationThreshold(self, deftol: float) -> None: """Set the threshold used to switch between deflated and non-deflated. Logically collective. Set the threshold value used to switch between deflated and non-deflated iteration. Parameters ---------- deftol The threshold value. Notes ----- Normally, the solver iterates on the extended problem in order to deflate previously converged eigenpairs. If this threshold is set to a nonzero value, then once the residual error is below this threshold the solver will continue the iteration without deflation. The intention is to be able to improve the current eigenpair further, despite having previous eigenpairs with somewhat bad precision. See Also -------- getRIIDeflationThreshold, slepc.NEPRIISetDeflationThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2050 ` """ ... def getRIIDeflationThreshold(self) -> float: """Get the threshold value that controls deflation. Not collective. Returns ------- float The threshold value. See Also -------- setRIIDeflationThreshold, slepc.NEPRIIGetDeflationThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2081 ` """ ... def setRIIKSP(self, ksp: KSP) -> None: """Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getRIIKSP, slepc.NEPRIISetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2100 ` """ ... def getRIIKSP(self) -> KSP: """Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setRIIKSP, slepc.NEPRIIGetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2117 ` """ ... def setSLPDeflationThreshold(self, deftol: float) -> None: """Set the threshold used to switch between deflated and non-deflated. Logically collective. Parameters ---------- deftol The threshold value. Notes ----- Normally, the solver iterates on the extended problem in order to deflate previously converged eigenpairs. If this threshold is set to a nonzero value, then once the residual error is below this threshold the solver will continue the iteration without deflation. The intention is to be able to improve the current eigenpair further, despite having previous eigenpairs with somewhat bad precision. See Also -------- getSLPDeflationThreshold, slepc.NEPSLPSetDeflationThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2139 ` """ ... def getSLPDeflationThreshold(self) -> float: """Get the threshold value that controls deflation. Not collective. Returns ------- float The threshold value. See Also -------- setSLPDeflationThreshold, slepc.NEPSLPGetDeflationThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2167 ` """ ... def setSLPEPS(self, eps: EPS) -> None: """Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getSLPEPS, slepc.NEPSLPSetEPS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2186 ` """ ... def getSLPEPS(self) -> EPS: """Get the linear eigensolver object associated with the nonlinear eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setSLPEPS, slepc.NEPSLPGetEPS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2203 ` """ ... def setSLPEPSLeft(self, eps: EPS) -> None: """Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Used to compute left eigenvectors in the two-sided variant of SLP. Parameters ---------- eps The linear eigensolver. See Also -------- setTwoSided, setSLPEPS, getSLPEPSLeft, slepc.NEPSLPSetEPSLeft :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2223 ` """ ... def getSLPEPSLeft(self) -> EPS: """Get the left eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setSLPEPSLeft, slepc.NEPSLPGetEPSLeft :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2242 ` """ ... def setSLPKSP(self, ksp: KSP) -> None: """Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getSLPKSP, slepc.NEPSLPSetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2262 ` """ ... def getSLPKSP(self) -> KSP: """Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setSLPKSP, slepc.NEPSLPGetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2279 ` """ ... def setNArnoldiKSP(self, ksp: KSP) -> None: """Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getNArnoldiKSP, slepc.NEPNArnoldiSetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2301 ` """ ... def getNArnoldiKSP(self) -> KSP: """Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setNArnoldiKSP, slepc.NEPNArnoldiGetKSP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2318 ` """ ... def setNArnoldiLagPreconditioner(self, lag: int) -> None: """Set when the preconditioner is rebuilt in the nonlinear solve. Logically collective. Parameters ---------- lag 0 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within the nonlinear iteration, 2 means every second time the Jacobian is built, etc. Notes ----- The default is 1. The preconditioner is ALWAYS built in the first iteration of a nonlinear solve. See Also -------- getNArnoldiLagPreconditioner, slepc.NEPNArnoldiSetLagPreconditioner :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2338 ` """ ... def getNArnoldiLagPreconditioner(self) -> int: """Get how often the preconditioner is rebuilt. Not collective. Returns ------- int The lag parameter. See Also -------- setNArnoldiLagPreconditioner, slepc.NEPNArnoldiGetLagPreconditioner :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2363 ` """ ... def setInterpolPEP(self, pep: PEP) -> None: """Set a polynomial eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- pep The polynomial eigensolver. See Also -------- getInterpolPEP, slepc.NEPInterpolSetPEP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2384 ` """ ... def getInterpolPEP(self) -> PEP: """Get the associated polynomial eigensolver object. Collective. Returns ------- PEP The polynomial eigensolver. See Also -------- setInterpolPEP, slepc.NEPInterpolGetPEP :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2401 ` """ ... def setInterpolInterpolation(self, tol: float | None = None, deg: int | None = None) -> None: """Set the tolerance and maximum degree for the interpolation polynomial. Collective. Parameters ---------- tol The tolerance to stop computing polynomial coefficients. deg The maximum degree of interpolation. See Also -------- getInterpolInterpolation, slepc.NEPInterpolSetInterpolation :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2421 ` """ ... def getInterpolInterpolation(self) -> tuple[float, int]: """Get the tolerance and maximum degree for the interpolation polynomial. Not collective. Returns ------- tol: float The tolerance to stop computing polynomial coefficients. deg: int The maximum degree of interpolation. See Also -------- setInterpolInterpolation, slepc.NEPInterpolGetInterpolation :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2444 ` """ ... def setNLEIGSRestart(self, keep: float) -> None: """Set the restart parameter for the NLEIGS method. Logically collective. The proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getNLEIGSRestart, slepc.NEPNLEIGSSetRestart :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2468 ` """ ... def getNLEIGSRestart(self) -> float: """Get the restart parameter used in the NLEIGS method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setNLEIGSRestart, slepc.NEPNLEIGSGetRestart :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2492 ` """ ... def setNLEIGSLocking(self, lock: bool) -> None: """Toggle between locking and non-locking variants of the NLEIGS method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getNLEIGSLocking, slepc.NEPNLEIGSSetLocking :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2511 ` """ ... def getNLEIGSLocking(self) -> bool: """Get the locking flag used in the NLEIGS method. Not collective. Returns ------- bool The locking flag. See Also -------- setNLEIGSLocking, slepc.NEPNLEIGSGetLocking :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2536 ` """ ... def setNLEIGSInterpolation(self, tol: float | None = None, deg: int | None = None) -> None: """Set the tolerance and maximum degree for the interpolation polynomial. Collective. Set the tolerance and maximum degree when building the interpolation via divided differences. Parameters ---------- tol The tolerance to stop computing divided differences. deg The maximum degree of interpolation. See Also -------- getNLEIGSInterpolation, slepc.NEPNLEIGSSetInterpolation :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2555 ` """ ... def getNLEIGSInterpolation(self) -> tuple[float, int]: """Get the tolerance and maximum degree for the interpolation polynomial. Not collective. Get the tolerance and maximum degree when building the interpolation via divided differences. Returns ------- tol: float The tolerance to stop computing divided differences. deg: int The maximum degree of interpolation. See Also -------- setNLEIGSInterpolation, slepc.NEPNLEIGSGetInterpolation :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2581 ` """ ... def setNLEIGSFullBasis(self, fullbasis: bool = True) -> None: """Set TOAR-basis (default) or full-basis variants of the NLEIGS method. Logically collective. Toggle between TOAR-basis (default) and full-basis variants of the NLEIGS method. Parameters ---------- fullbasis ``True`` if the full-basis variant must be selected. Notes ----- The default is to use a compact representation of the Krylov basis, that is, :math:`V = (I \otimes U) S`, with a `BV` of type `TENSOR`. This behavior can be changed so that the full basis :math:`V` is explicitly stored and operated with. This variant is more expensive in terms of memory and computation, but is necessary in some cases, particularly for two-sided computations, see `setTwoSided()`. In the full-basis variant, the NLEIGS solver uses an `EPS` object to explicitly solve the linearized eigenproblem, see `getNLEIGSEPS()`. See Also -------- setTwoSided, getNLEIGSFullBasis, getNLEIGSEPS, slepc.NEPNLEIGSSetFullBasis :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2606 ` """ ... def getNLEIGSFullBasis(self) -> bool: """Get the flag that indicates if NLEIGS is using the full-basis variant. Not collective. Returns ------- bool ``True`` if the full-basis variant is selected. See Also -------- setNLEIGSFullBasis, slepc.NEPNLEIGSGetFullBasis :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2639 ` """ ... def setNLEIGSEPS(self, eps: EPS) -> None: """Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getNLEIGSEPS, slepc.NEPNLEIGSSetEPS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2658 ` """ ... def getNLEIGSEPS(self) -> EPS: """Get the linear eigensolver object associated with the nonlinear eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setNLEIGSEPS, slepc.NEPNLEIGSGetEPS :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2675 ` """ ... def setNLEIGSRKShifts(self, shifts: Sequence[Scalar]) -> None: """Set a list of shifts to be used in the Rational Krylov method. Collective. Parameters ---------- shifts Values specifying the shifts. Notes ----- If only one shift is provided, the built subspace is equivalent to shift-and-invert Krylov-Schur (provided that the absolute convergence criterion is used). Otherwise, the rational Krylov variant is run. See Also -------- getNLEIGSRKShifts, getNLEIGSKSPs, slepc.NEPNLEIGSSetRKShifts :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2695 ` """ ... def getNLEIGSRKShifts(self) -> ArrayScalar: """Get the list of shifts used in the Rational Krylov method. Not collective. Returns ------- ArrayScalar The shift values. See Also -------- setNLEIGSRKShifts, slepc.NEPNLEIGSGetRKShifts :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2722 ` """ ... def getNLEIGSKSPs(self) -> list[KSP]: """Get the list of linear solver objects associated with the NLEIGS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of shifts provided by the user, or 1 if the user did not provide shifts. See Also -------- setNLEIGSRKShifts, slepc.NEPNLEIGSGetKSPs :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2747 ` """ ... def setCISSExtraction(self, extraction: CISSExtraction) -> None: """Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.NEPCISSSetExtraction :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2774 ` """ ... def getCISSExtraction(self) -> CISSExtraction: """Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.NEPCISSGetExtraction :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2792 ` """ ... def setCISSSizes(self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False) -> None: """Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `NEP` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.NEPCISSSetSizes :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2811 ` """ ... def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.NEPCISSGetSizes :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2865 ` """ ... def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.NEPCISSSetThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2899 ` """ ... def getCISSThreshold(self) -> tuple[float, float]: """Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.NEPCISSGetThreshold :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2922 ` """ ... def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.NEPCISSSetRefinement :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2944 ` """ ... def getCISSRefinement(self) -> tuple[int, int]: """Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.NEPCISSGetRefinement :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2967 ` """ ... def getCISSKSPs(self) -> list[KSP]: """Get the list of linear solver objects associated with the CISS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.NEPCISSGetKSPs :sources:`Source code at slepc4py/SLEPc/NEP.pyx:2989 ` """ ... @property def problem_type(self) -> NEPProblemType: """The problem type from the NEP object. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3016 ` """ ... @property def which(self) -> NEPWhich: """The portion of the spectrum to be sought. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3023 ` """ ... @property def target(self) -> float: """The value of the target. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3030 ` """ ... @property def tol(self) -> float: """The tolerance used by the NEP convergence tests. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3037 ` """ ... @property def max_it(self) -> int: """The maximum iteration count used by the NEP convergence tests. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3044 ` """ ... @property def track_all(self) -> bool: """Compute the residual of all approximate eigenpairs. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3051 ` """ ... @property def bv(self) -> BV: """The basis vectors (`BV`) object associated. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3058 ` """ ... @property def rg(self) -> RG: """The region (`RG`) object associated. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3065 ` """ ... @property def ds(self) -> DS: """The direct solver (`DS`) object associated. :sources:`Source code at slepc4py/SLEPc/NEP.pyx:3072 ` """ ... class MFN(Object): """Matrix Function. Matrix Function (`MFN`) is the object provided by slepc4py for computing the action of a matrix function on a vector. Given a matrix :math:`A` and a vector :math:`b`, the call ``mfn.solve(b,x)`` computes :math:`x=f(A)b`, where :math:`f` is a function such as the exponential. """ class Type: """MFN type. - `KRYLOV`: Restarted Krylov solver. - `EXPOKIT`: Implementation of the method in Expokit. See Also -------- slepc.MFNType """ KRYLOV: str = _def(str, 'KRYLOV') #: Object ``KRYLOV`` of type :class:`str` EXPOKIT: str = _def(str, 'EXPOKIT') #: Object ``EXPOKIT`` of type :class:`str` class ConvergedReason: """MFN convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_ITS`: Solver completed the requested number of steps. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Generic breakdown in method. See Also -------- slepc.MFNConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` CONVERGED_ITS: int = _def(int, 'CONVERGED_ITS') #: Constant ``CONVERGED_ITS`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the MFN data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.MFNView :sources:`Source code at slepc4py/SLEPc/MFN.pyx:57 ` """ ... def destroy(self) -> Self: """Destroy the MFN object. Logically collective. See Also -------- slepc.MFNDestroy :sources:`Source code at slepc4py/SLEPc/MFN.pyx:76 ` """ ... def reset(self) -> None: """Reset the MFN object. Collective. See Also -------- slepc.MFNReset :sources:`Source code at slepc4py/SLEPc/MFN.pyx:90 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the MFN object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.MFNCreate :sources:`Source code at slepc4py/SLEPc/MFN.pyx:102 ` """ ... def setType(self, mfn_type: Type | str) -> None: """Set the particular solver to be used in the MFN object. Logically collective. Parameters ---------- mfn_type The solver to be used. Notes ----- The default is ``KRYLOV``. Normally, it is best to use `setFromOptions()` and then set the MFN type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.MFNSetType :sources:`Source code at slepc4py/SLEPc/MFN.pyx:123 ` """ ... def getType(self) -> str: """Get the MFN type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.MFNGetType :sources:`Source code at slepc4py/SLEPc/MFN.pyx:150 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all MFN options in the database. Not collective. Returns ------- str The prefix string set for this MFN object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.MFNGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/MFN.pyx:169 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all MFN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all MFN option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different MFN contexts, one could call:: M1.setOptionsPrefix("mfn1_") M2.setOptionsPrefix("mfn2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.MFNGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/MFN.pyx:188 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching for all MFN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all MFN option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.MFNAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/MFN.pyx:219 ` """ ... def setFromOptions(self) -> None: """Set MFN options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.MFNSetFromOptions :sources:`Source code at slepc4py/SLEPc/MFN.pyx:238 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and maximum iteration count. Not collective. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.MFNGetTolerances :sources:`Source code at slepc4py/SLEPc/MFN.pyx:257 ` """ ... def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default MFN convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. See Also -------- getTolerances, slepc.MFNSetTolerances :sources:`Source code at slepc4py/SLEPc/MFN.pyx:279 ` """ ... def getDimensions(self) -> int: """Get the dimension of the subspace used by the solver. Not collective. Returns ------- int Maximum dimension of the subspace to be used by the solver. See Also -------- setDimensions, slepc.MFNGetDimensions :sources:`Source code at slepc4py/SLEPc/MFN.pyx:305 ` """ ... def setDimensions(self, ncv: int) -> None: """Set the dimension of the subspace to be used by the solver. Logically collective. Parameters ---------- ncv Maximum dimension of the subspace to be used by the solver. See Also -------- getDimensions, slepc.MFNSetDimensions :sources:`Source code at slepc4py/SLEPc/MFN.pyx:324 ` """ ... def getFN(self) -> FN: """Get the math function object associated to the MFN object. Not collective. Returns ------- FN The math function context. See Also -------- setFN, slepc.MFNGetFN :sources:`Source code at slepc4py/SLEPc/MFN.pyx:342 ` """ ... def setFN(self, fn: FN) -> None: """Set a math function object associated to the MFN object. Collective. Parameters ---------- fn The math function context. See Also -------- getFN, slepc.MFNSetFN :sources:`Source code at slepc4py/SLEPc/MFN.pyx:362 ` """ ... def getBV(self) -> BV: """Get the basis vector object associated to the MFN object. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.MFNGetBV :sources:`Source code at slepc4py/SLEPc/MFN.pyx:379 ` """ ... def setBV(self, bv: BV) -> None: """Set a basis vector object associated to the MFN object. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.MFNSetBV :sources:`Source code at slepc4py/SLEPc/MFN.pyx:399 ` """ ... def getOperator(self) -> Mat: """Get the matrix associated with the MFN object. Collective. Returns ------- petsc4py.PETSc.Mat The matrix for which the matrix function is to be computed. See Also -------- setOperator, slepc.MFNGetOperator :sources:`Source code at slepc4py/SLEPc/MFN.pyx:416 ` """ ... def setOperator(self, A: Mat) -> None: """Set the matrix associated with the MFN object. Collective. Parameters ---------- A The problem matrix. Notes ----- This must be called before `setUp()`. If called again after `setUp()` then the `MFN` object is reset. See Also -------- getOperator, slepc.MFNSetOperator :sources:`Source code at slepc4py/SLEPc/MFN.pyx:436 ` """ ... def setMonitor(self, monitor: MFNMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.MFNMonitorSet :sources:`Source code at slepc4py/SLEPc/MFN.pyx:460 ` """ ... def getMonitor(self) -> MFNMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- MFNMonitorFunction The list of monitor functions. :sources:`Source code at slepc4py/SLEPc/MFN.pyx:485 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for an `MFN` object. Logically collective. See Also -------- slepc.MFNMonitorCancel :sources:`Source code at slepc4py/SLEPc/MFN.pyx:498 ` """ ... def setUp(self) -> None: """Set up all the necessary internal data structures. Collective. Set up all the internal data structures necessary for the execution of the eigensolver. See Also -------- solve, slepc.MFNSetUp :sources:`Source code at slepc4py/SLEPc/MFN.pyx:513 ` """ ... def solve(self, b: Vec, x: Vec) -> None: """Solve the matrix function problem. Collective. Given a vector :math:`b`, the vector :math:`x = f(A) b` is returned. Parameters ---------- b The right hand side vector. x The solution. Notes ----- The matrix :math:`A` is specified with `setOperator()`. The function :math:`f` is specified via the `FN` object obtained with `getFN()` or set with `setFN()`. See Also -------- setOperator, getFN, solveTranspose, slepc.MFNSolve :sources:`Source code at slepc4py/SLEPc/MFN.pyx:528 ` """ ... def solveTranspose(self, b: Vec, x: Vec) -> None: """Solve the transpose matrix function problem. Collective. Given a vector :math:`b`, the vector :math:`x = f(A^T) b` is returned. Parameters ---------- b The right hand side vector. x The solution. Notes ----- The matrix :math:`A` is specified with `setOperator()`. The function :math:`f` is specified via the `FN` object obtained with `getFN()` or set with `setFN()`. See Also -------- setOperator, getFN, solve, slepc.MFNSolveTranspose :sources:`Source code at slepc4py/SLEPc/MFN.pyx:556 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. Get the current iteration number. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, slepc.MFNGetIterationNumber :sources:`Source code at slepc4py/SLEPc/MFN.pyx:584 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, setErrorIfNotConverged, slepc.MFNGetConvergedReason :sources:`Source code at slepc4py/SLEPc/MFN.pyx:607 ` """ ... def setErrorIfNotConverged(self, flg: bool = True) -> None: """Set `solve()` to generate an error if the solver does not converge. Logically collective. Parameters ---------- flg ``True`` indicates you want the error generated. Notes ----- Normally SLEPc continues if the solver fails to converge, you can call `getConvergedReason()` after a `solve()` to determine if it has converged. See Also -------- getConvergedReason, solve, slepc.MFNSetErrorIfNotConverged :sources:`Source code at slepc4py/SLEPc/MFN.pyx:626 ` """ ... def getErrorIfNotConverged(self) -> bool: """Get if `solve()` generates an error if the solver does not converge. Not collective. Get a flag indicating whether `solve()` will generate an error if the solver does not converge. Returns ------- bool ``True`` indicates you want the error generated. See Also -------- setErrorIfNotConverged, slepc.MFNGetErrorIfNotConverged :sources:`Source code at slepc4py/SLEPc/MFN.pyx:650 ` """ ... @property def tol(self) -> float: """The tolerance count used by the MFN convergence tests. :sources:`Source code at slepc4py/SLEPc/MFN.pyx:674 ` """ ... @property def max_it(self) -> int: """The maximum iteration count used by the MFN convergence tests. :sources:`Source code at slepc4py/SLEPc/MFN.pyx:681 ` """ ... @property def fn(self) -> FN: """The math function (`FN`) object associated to the MFN object. :sources:`Source code at slepc4py/SLEPc/MFN.pyx:688 ` """ ... @property def bv(self) -> BV: """The basis vectors (`BV`) object associated to the MFN object. :sources:`Source code at slepc4py/SLEPc/MFN.pyx:695 ` """ ... class LME(Object): """Linear Matrix Equation. Linear Matrix Equation (`LME`) is the object provided by slepc4py for solving linear matrix equations such as Lyapunov or Sylvester where the solution has low rank. """ class Type: """LME type. - `KRYLOV`: Restarted Krylov solver. See Also -------- slepc.LMEType """ KRYLOV: str = _def(str, 'KRYLOV') #: Object ``KRYLOV`` of type :class:`str` class ConvergedReason: """LME convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.LMEConvergedReason """ CONVERGED_TOL: int = _def(int, 'CONVERGED_TOL') #: Constant ``CONVERGED_TOL`` of type :class:`int` DIVERGED_ITS: int = _def(int, 'DIVERGED_ITS') #: Constant ``DIVERGED_ITS`` of type :class:`int` DIVERGED_BREAKDOWN: int = _def(int, 'DIVERGED_BREAKDOWN') #: Constant ``DIVERGED_BREAKDOWN`` of type :class:`int` CONVERGED_ITERATING: int = _def(int, 'CONVERGED_ITERATING') #: Constant ``CONVERGED_ITERATING`` of type :class:`int` ITERATING: int = _def(int, 'ITERATING') #: Constant ``ITERATING`` of type :class:`int` class ProblemType: """LME problem type. - `LYAPUNOV`: Continuous-time Lyapunov. - `SYLVESTER`: Continuous-time Sylvester. - `GEN_LYAPUNOV`: Generalized Lyapunov. - `GEN_SYLVESTER`: Generalized Sylvester. - `DT_LYAPUNOV`: Discrete-time Lyapunov. - `STEIN`: Stein. See Also -------- slepc.LMEProblemType """ LYAPUNOV: int = _def(int, 'LYAPUNOV') #: Constant ``LYAPUNOV`` of type :class:`int` SYLVESTER: int = _def(int, 'SYLVESTER') #: Constant ``SYLVESTER`` of type :class:`int` GEN_LYAPUNOV: int = _def(int, 'GEN_LYAPUNOV') #: Constant ``GEN_LYAPUNOV`` of type :class:`int` GEN_SYLVESTER: int = _def(int, 'GEN_SYLVESTER') #: Constant ``GEN_SYLVESTER`` of type :class:`int` DT_LYAPUNOV: int = _def(int, 'DT_LYAPUNOV') #: Constant ``DT_LYAPUNOV`` of type :class:`int` STEIN: int = _def(int, 'STEIN') #: Constant ``STEIN`` of type :class:`int` def view(self, viewer: Viewer | None = None) -> None: """Print the LME data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.LMEView :sources:`Source code at slepc4py/SLEPc/LME.pyx:76 ` """ ... def destroy(self) -> Self: """Destroy the LME object. Collective. See Also -------- slepc.LMEDestroy :sources:`Source code at slepc4py/SLEPc/LME.pyx:95 ` """ ... def reset(self) -> None: """Reset the LME object. Collective. See Also -------- slepc.LMEReset :sources:`Source code at slepc4py/SLEPc/LME.pyx:109 ` """ ... def create(self, comm: Comm | None = None) -> Self: """Create the LME object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.LMECreate :sources:`Source code at slepc4py/SLEPc/LME.pyx:121 ` """ ... def setType(self, lme_type: Type | str) -> None: """Set the particular solver to be used in the LME object. Logically collective. Parameters ---------- lme_type The solver to be used. Notes ----- The default is ``KRYLOV``. Normally, it is best to use `setFromOptions()` and then set the LME type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.LMESetType :sources:`Source code at slepc4py/SLEPc/LME.pyx:142 ` """ ... def getType(self) -> str: """Get the LME type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.LMEGetType :sources:`Source code at slepc4py/SLEPc/LME.pyx:169 ` """ ... def setProblemType(self, lme_problem_type: ProblemType | str) -> None: """Set the LME problem type of this object. Logically collective. Parameters ---------- lme_problem_type The problem type to be used. See Also -------- getProblemType, slepc.LMESetProblemType :sources:`Source code at slepc4py/SLEPc/LME.pyx:188 ` """ ... def getProblemType(self) -> ProblemType: """Get the LME problem type of this object. Not collective. Returns ------- ProblemType The problem type currently being used. See Also -------- setProblemType, slepc.LMEGetProblemType :sources:`Source code at slepc4py/SLEPc/LME.pyx:206 ` """ ... def setCoefficients(self, A: Mat, B: Mat | None = None, D: Mat | None = None, E: Mat | None = None) -> None: """Set the coefficient matrices. Collective. Set the coefficient matrices that define the linear matrix equation to be solved. Parameters ---------- A First coefficient matrix B Second coefficient matrix, optional D Third coefficient matrix, optional E Fourth coefficient matrix, optional Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where matrix :math:`C` is not provided here but with `setRHS()`. Not all four matrices must be passed. This must be called before `setUp()`. If called again after `setUp()` then the `LME` object is reset. See Also -------- getCoefficients, solve, setRHS, setUp, slepc.LMESetCoefficients :sources:`Source code at slepc4py/SLEPc/LME.pyx:225 ` """ ... def getCoefficients(self) -> tuple[Mat, Mat | None, Mat | None, Mat | None]: """Get the coefficient matrices of the matrix equation. Collective. Returns ------- A: petsc4py.PETSc.Mat First coefficient matrix. B: petsc4py.PETSc.Mat Second coefficient matrix, if available. D: petsc4py.PETSc.Mat Third coefficient matrix, if available. E: petsc4py.PETSc.Mat Fourth coefficient matrix, if available. See Also -------- setCoefficients, slepc.LMEGetCoefficients :sources:`Source code at slepc4py/SLEPc/LME.pyx:264 ` """ ... def setRHS(self, C: Mat) -> None: """Set the right-hand side of the matrix equation. Collective. Parameters ---------- C The right-hand side matrix Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where matrix :math:`C` is given with this function. It must be a low-rank matrix of type `petsc4py.PETSc.Mat.Type.LRC`, that is, :math:`C = UDV^*` where :math:`D` is diagonal of order :math:`k`, and :math:`U,V` are dense tall-skinny matrices with :math:`k` columns. No sparse matrix must be provided when creating the ``LRC`` matrix. In equation types that require :math:`C` to be symmetric, such as Lyapunov, ``C`` must be created with :math:`V=U`. See Also -------- getRHS, setSolution, slepc.LMESetRHS :sources:`Source code at slepc4py/SLEPc/LME.pyx:298 ` """ ... def getRHS(self) -> Mat: """Get the right-hand side of the matrix equation. Collective. Returns ------- C: petsc4py.PETSc.Mat The low-rank matrix. See Also -------- setRHS, slepc.LMEGetRHS :sources:`Source code at slepc4py/SLEPc/LME.pyx:327 ` """ ... def setSolution(self, X: Mat | None = None) -> None: """Set the placeholder for the solution of the matrix equation. Collective. Parameters ---------- X The solution matrix Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where the solution matrix is of low rank and is written in factored form :math:`X = UDV^*`. This function provides a matrix object of type `petsc4py.PETSc.Mat.Type.LRC` that stores :math:`U,V` and (optionally) :math:`D`. These factors will be computed during `solve()`. In equation types whose solution :math:`X` is symmetric, such as Lyapunov, ``X`` must be created with :math:`V=U`. If the user provides ``X`` with this function, then the solver will return a solution with rank at most the number of columns of :math:`U`. Alternatively, it is possible to let the solver choose the rank of the solution, by passing ``None`` and then calling `getSolution()` after `solve()`. See Also -------- solve, setRHS, getSolution, slepc.LMESetSolution :sources:`Source code at slepc4py/SLEPc/LME.pyx:347 ` """ ... def getSolution(self) -> Mat: """Get the solution of the matrix equation. Collective. Returns ------- X: petsc4py.PETSc.Mat The low-rank matrix. Notes ----- If called after `solve()`, ``X`` will contain the solution of the equation. The matrix ``X`` may have been passed by the user via `setSolution()`, although this is not required. See Also -------- solve, setSolution, slepc.LMEGetSolution :sources:`Source code at slepc4py/SLEPc/LME.pyx:382 ` """ ... def getErrorEstimate(self) -> float: """Get the error estimate obtained during the solve. Not collective. Returns ------- float The error estimate. Notes ----- This is the error estimated internally by the solver. The actual error bound can be computed with `computeError()`. Note that some solvers may not be able to provide an error estimate. See Also -------- computeError, slepc.LMEGetErrorEstimate :sources:`Source code at slepc4py/SLEPc/LME.pyx:410 ` """ ... def computeError(self) -> float: """Compute the error associated with the last equation solved. Collective. Returns ------- float The error. Notes ----- The error is based on the residual norm. This function is not scalable (in terms of memory or parallel communication), so it should not be called except in the case of small problem size. For large equations, use `getErrorEstimate()`. See Also -------- getErrorEstimate, slepc.LMEComputeError :sources:`Source code at slepc4py/SLEPc/LME.pyx:435 ` """ ... def getOptionsPrefix(self) -> str: """Get the prefix used for searching for all LME options in the database. Not collective. Returns ------- str The prefix string set for this LME object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.LMEGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/LME.pyx:462 ` """ ... def setOptionsPrefix(self, prefix: str | None = None) -> None: """Set the prefix used for searching for all LME options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all LME option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different LME contexts, one could call:: L1.setOptionsPrefix("lme1_") L2.setOptionsPrefix("lme2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.LMEGetOptionsPrefix :sources:`Source code at slepc4py/SLEPc/LME.pyx:481 ` """ ... def appendOptionsPrefix(self, prefix: str | None = None) -> None: """Append to the prefix used for searching in the database. Logically collective. Append to the prefix used for searching for all LME options in the database. Parameters ---------- prefix The prefix string to prepend to all LME option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.LMEAppendOptionsPrefix :sources:`Source code at slepc4py/SLEPc/LME.pyx:512 ` """ ... def setFromOptions(self) -> None: """Set LME options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.LMESetFromOptions :sources:`Source code at slepc4py/SLEPc/LME.pyx:534 ` """ ... def getTolerances(self) -> tuple[float, int]: """Get the tolerance and maximum iteration count. Not collective. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.LMEGetTolerances :sources:`Source code at slepc4py/SLEPc/LME.pyx:553 ` """ ... def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default LME convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. See Also -------- getTolerances, slepc.LMESetTolerances :sources:`Source code at slepc4py/SLEPc/LME.pyx:575 ` """ ... def getDimensions(self) -> int: """Get the dimension of the subspace used by the solver. Not collective. Returns ------- int Maximum dimension of the subspace to be used by the solver. See Also -------- setDimensions, slepc.LMEGetDimensions :sources:`Source code at slepc4py/SLEPc/LME.pyx:601 ` """ ... def setDimensions(self, ncv: int) -> None: """Set the dimension of the subspace to be used by the solver. Logically collective. Parameters ---------- ncv Maximum dimension of the subspace to be used by the solver. See Also -------- getDimensions, slepc.LMESetDimensions :sources:`Source code at slepc4py/SLEPc/LME.pyx:620 ` """ ... def getBV(self) -> BV: """Get the basis vector object associated to the LME object. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.LMEGetBV :sources:`Source code at slepc4py/SLEPc/LME.pyx:638 ` """ ... def setBV(self, bv: BV) -> None: """Set a basis vector object to the LME object. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.LMESetBV :sources:`Source code at slepc4py/SLEPc/LME.pyx:658 ` """ ... def setMonitor(self, monitor: LMEMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None) -> None: """Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.LMEMonitorSet :sources:`Source code at slepc4py/SLEPc/LME.pyx:675 ` """ ... def getMonitor(self) -> LMEMonitorFunction: """Get the list of monitor functions. Not collective. Returns ------- LMEMonitorFunction The list of monitor functions. :sources:`Source code at slepc4py/SLEPc/LME.pyx:700 ` """ ... def cancelMonitor(self) -> None: """Clear all monitors for an `LME` object. Logically collective. See Also -------- slepc.LMEMonitorCancel :sources:`Source code at slepc4py/SLEPc/LME.pyx:713 ` """ ... def setUp(self) -> None: """Set up all the internal necessary data structures. Collective. Set up all the internal data structures necessary for the execution of the eigensolver. See Also -------- solve, slepc.LMESetUp :sources:`Source code at slepc4py/SLEPc/LME.pyx:726 ` """ ... def solve(self) -> None: """Solve the linear matrix equation. Collective. Notes ----- The matrix coefficients are specified with `setCoefficients()`. The right-hand side is specified with `setRHS()`. The placeholder for the solution is specified with `setSolution()`. See Also -------- setCoefficients, setRHS, setSolution, slepc.LMESolve :sources:`Source code at slepc4py/SLEPc/LME.pyx:741 ` """ ... def getIterationNumber(self) -> int: """Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, slepc.LMEGetIterationNumber :sources:`Source code at slepc4py/SLEPc/LME.pyx:758 ` """ ... def getConvergedReason(self) -> ConvergedReason: """Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, setErrorIfNotConverged, slepc.LMEGetConvergedReason :sources:`Source code at slepc4py/SLEPc/LME.pyx:780 ` """ ... def setErrorIfNotConverged(self, flg: bool = True) -> None: """Set `solve()` to generate an error if the solver has not converged. Logically collective. Parameters ---------- flg ``True`` indicates you want the error generated. Notes ----- Normally SLEPc continues if the solver fails to converge, you can call `getConvergedReason()` after a `solve()` to determine if it has converged. See Also -------- getConvergedReason, solve, slepc.LMESetErrorIfNotConverged :sources:`Source code at slepc4py/SLEPc/LME.pyx:799 ` """ ... def getErrorIfNotConverged(self) -> bool: """Get if `solve()` generates an error if the solver does not converge. Not collective. Get a flag indicating whether `solve()` will generate an error if the solver does not converge. Returns ------- bool ``True`` indicates you want the error generated. See Also -------- setErrorIfNotConverged, slepc.LMEGetErrorIfNotConverged :sources:`Source code at slepc4py/SLEPc/LME.pyx:823 ` """ ... @property def tol(self) -> float: """The tolerance value used by the LME convergence tests. :sources:`Source code at slepc4py/SLEPc/LME.pyx:847 ` """ ... @property def max_it(self) -> int: """The maximum iteration count used by the LME convergence tests. :sources:`Source code at slepc4py/SLEPc/LME.pyx:854 ` """ ... @property def fn(self) -> FN: """The math function (`FN`) object associated to the LME object. :sources:`Source code at slepc4py/SLEPc/LME.pyx:861 ` """ ... @property def bv(self) -> BV: """The basis vectors (`BV`) object associated to the LME object. :sources:`Source code at slepc4py/SLEPc/LME.pyx:868 ` """ ... class Sys: """System utilities.""" @classmethod def getVersion(cls, devel: bool = False, date: bool = False, author: bool = False) -> tuple[int, int, int]: """Return SLEPc version information. Not collective. Parameters ---------- devel Additionally, return whether using an in-development version. date Additionally, return date information. author Additionally, return author information. Returns ------- major: int Major version number. minor: int Minor version number. micro: int Micro (or patch) version number. See Also -------- slepc.SlepcGetVersion, slepc.SlepcGetVersionNumber :sources:`Source code at slepc4py/SLEPc/Sys.pyx:8 ` """ ... @classmethod def getVersionInfo(cls) -> dict[str, bool | int | str]: """Return SLEPc version information. Not collective. Returns ------- info: dict Dictionary with version information. See Also -------- slepc.SlepcGetVersion, slepc.SlepcGetVersionNumber :sources:`Source code at slepc4py/SLEPc/Sys.pyx:64 ` """ ... @classmethod def isInitialized(cls) -> bool: """Return whether SLEPc has been initialized. Not collective. See Also -------- isFinalized :sources:`Source code at slepc4py/SLEPc/Sys.pyx:90 ` """ ... @classmethod def isFinalized(cls) -> bool: """Return whether SLEPc has been finalized. Not collective. See Also -------- isInitialized :sources:`Source code at slepc4py/SLEPc/Sys.pyx:103 ` """ ... @classmethod def hasExternalPackage(cls, package: str) -> bool: """Return whether SLEPc has support for external package. Not collective. Parameters ---------- package The external package name. See Also -------- slepc.SlepcHasExternalPackage :sources:`Source code at slepc4py/SLEPc/Sys.pyx:118 ` """ ... class Util: """Other utilities such as the creation of structured matrices.""" @classmethod def createMatBSE(cls, R: petsc4py.PETSc.Mat, C: petsc4py.PETSc.Mat) -> petsc4py.PETSc.Mat: """Create a matrix that can be used to define a BSE type problem. Collective. Create a matrix that can be used to define a structured eigenvalue problem of type BSE (Bethe-Salpeter Equation). Parameters ---------- R The matrix for the diagonal block (resonant). C The matrix for the off-diagonal block (coupling). Returns ------- petsc4py.PETSc.Mat The matrix with the block form :math:`H = [ R\; C; {-C}^*\; {-R}^T ]`. See Also -------- slepc.MatCreateBSE :sources:`Source code at slepc4py/SLEPc/Util.pyx:8 ` """ ... @classmethod def createMatHamiltonian(cls, A: petsc4py.PETSc.Mat, B: petsc4py.PETSc.Mat, C: petsc4py.PETSc.Mat) -> petsc4py.PETSc.Mat: """Create matrix to be used for a structured Hamiltonian eigenproblem. Collective. Parameters ---------- A The matrix for (0,0) block. B The matrix for (0,1) block, must be real symmetric or Hermitian. C The matrix for (1,0) block, must be real symmetric or Hermitian. Returns ------- petsc4py.PETSc.Mat The matrix with the block form :math:`H = [ A\; B; C\; -A^* ]`. See Also -------- slepc.MatCreateHamiltonian :sources:`Source code at slepc4py/SLEPc/Util.pyx:38 ` """ ... class _p_mem: """""" def _initialize(args=None): """ :sources:`Source code at slepc4py/SLEPc/SLEPc.pyx:262 ` """ ... def _finalize(): """ :sources:`Source code at slepc4py/SLEPc/SLEPc.pyx:266 ` """ ... from .typing import * ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.SLEPc.rst0000644000076500000240000000063515133664234022161 0ustar00jromanstaffslepc4py.SLEPc ============== .. automodule:: slepc4py.SLEPc :synopsis: .. rubric:: Classes .. autosummary:: :toctree: BV DS EPS FN LME MFN NEP PEP RG ST SVD Sys Util .. rubric:: Attributes .. autosummary:: :toctree: DECIDE DEFAULT DETERMINE CURRENT ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.get_config.rst0000644000076500000240000000014415133664236023354 0ustar00jromanstaffslepc4py.get\_config ==================== .. currentmodule:: slepc4py .. autofunction:: get_config././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.get_include.rst0000644000076500000240000000014715133664236023535 0ustar00jromanstaffslepc4py.get\_include ===================== .. currentmodule:: slepc4py .. autofunction:: get_include././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.init.rst0000644000076500000240000000012015133664236022205 0ustar00jromanstaffslepc4py.init ============= .. currentmodule:: slepc4py .. autofunction:: init././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908955.0 slepc4py-3.24.2/docs/source/reference/slepc4py.rst0000644000076500000240000000030215133664233021242 0ustar00jromanstaffslepc4py ======== .. automodule:: slepc4py :synopsis: .. rubric:: Functions .. autosummary:: :toctree: get_config get_include init ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.ArrayComplex.rst0000644000076500000240000000017115133664236025167 0ustar00jromanstaffslepc4py.typing.ArrayComplex ============================ .. currentmodule:: slepc4py.typing .. autodata:: ArrayComplex././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.ArrayInt.rst0000644000076500000240000000015515133664236024314 0ustar00jromanstaffslepc4py.typing.ArrayInt ======================== .. currentmodule:: slepc4py.typing .. autodata:: ArrayInt././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.ArrayReal.rst0000644000076500000240000000016015133664236024441 0ustar00jromanstaffslepc4py.typing.ArrayReal ========================= .. currentmodule:: slepc4py.typing .. autodata:: ArrayReal././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.ArrayScalar.rst0000644000076500000240000000016615133664236024771 0ustar00jromanstaffslepc4py.typing.ArrayScalar =========================== .. currentmodule:: slepc4py.typing .. autodata:: ArrayScalar././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.EPSArbitraryFunction.rst0000644000076500000240000000022115133664236026572 0ustar00jromanstaffslepc4py.typing.EPSArbitraryFunction ==================================== .. currentmodule:: slepc4py.typing .. autodata:: EPSArbitraryFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.EPSEigenvalueComparison.rst0000644000076500000240000000023215133664236027246 0ustar00jromanstaffslepc4py.typing.EPSEigenvalueComparison ======================================= .. currentmodule:: slepc4py.typing .. autodata:: EPSEigenvalueComparison././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.EPSMonitorFunction.rst0000644000076500000240000000021315133664236026263 0ustar00jromanstaffslepc4py.typing.EPSMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: EPSMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.EPSStoppingFunction.rst0000644000076500000240000000021615133664236026442 0ustar00jromanstaffslepc4py.typing.EPSStoppingFunction =================================== .. currentmodule:: slepc4py.typing .. autodata:: EPSStoppingFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.LMEMonitorFunction.rst0000644000076500000240000000021315133664236026251 0ustar00jromanstaffslepc4py.typing.LMEMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: LMEMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.LayoutSizeSpec.rst0000644000076500000240000000017715133664236025512 0ustar00jromanstaffslepc4py.typing.LayoutSizeSpec ============================== .. currentmodule:: slepc4py.typing .. autodata:: LayoutSizeSpec././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.MFNMonitorFunction.rst0000644000076500000240000000021315133664236026254 0ustar00jromanstaffslepc4py.typing.MFNMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: MFNMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.NEPEigenvalueComparison.rst0000644000076500000240000000023215133664236027241 0ustar00jromanstaffslepc4py.typing.NEPEigenvalueComparison ======================================= .. currentmodule:: slepc4py.typing .. autodata:: NEPEigenvalueComparison././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.NEPFunction.rst0000644000076500000240000000016615133664236024715 0ustar00jromanstaffslepc4py.typing.NEPFunction =========================== .. currentmodule:: slepc4py.typing .. autodata:: NEPFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.NEPJacobian.rst0000644000076500000240000000016615133664236024636 0ustar00jromanstaffslepc4py.typing.NEPJacobian =========================== .. currentmodule:: slepc4py.typing .. autodata:: NEPJacobian././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.NEPMonitorFunction.rst0000644000076500000240000000021315133664236026256 0ustar00jromanstaffslepc4py.typing.NEPMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: NEPMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.NEPStoppingFunction.rst0000644000076500000240000000021615133664236026435 0ustar00jromanstaffslepc4py.typing.NEPStoppingFunction =================================== .. currentmodule:: slepc4py.typing .. autodata:: NEPStoppingFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.PEPEigenvalueComparison.rst0000644000076500000240000000023215133664236027243 0ustar00jromanstaffslepc4py.typing.PEPEigenvalueComparison ======================================= .. currentmodule:: slepc4py.typing .. autodata:: PEPEigenvalueComparison././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.PEPMonitorFunction.rst0000644000076500000240000000021315133664236026260 0ustar00jromanstaffslepc4py.typing.PEPMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: PEPMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.PEPStoppingFunction.rst0000644000076500000240000000021615133664236026437 0ustar00jromanstaffslepc4py.typing.PEPStoppingFunction =================================== .. currentmodule:: slepc4py.typing .. autodata:: PEPStoppingFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.SVDMonitorFunction.rst0000644000076500000240000000021315133664236026270 0ustar00jromanstaffslepc4py.typing.SVDMonitorFunction ================================== .. currentmodule:: slepc4py.typing .. autodata:: SVDMonitorFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.SVDStoppingFunction.rst0000644000076500000240000000021615133664236026447 0ustar00jromanstaffslepc4py.typing.SVDStoppingFunction =================================== .. currentmodule:: slepc4py.typing .. autodata:: SVDStoppingFunction././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908958.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.Scalar.rst0000644000076500000240000000014715133664236023771 0ustar00jromanstaffslepc4py.typing.Scalar ====================== .. currentmodule:: slepc4py.typing .. autodata:: Scalar././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908956.0 slepc4py-3.24.2/docs/source/reference/slepc4py.typing.rst0000644000076500000240000000124715133664234022565 0ustar00jromanstaffslepc4py.typing =============== .. automodule:: slepc4py.typing :synopsis: .. rubric:: Attributes .. autosummary:: :toctree: Scalar ArrayInt ArrayReal ArrayComplex ArrayScalar LayoutSizeSpec EPSStoppingFunction EPSArbitraryFunction EPSEigenvalueComparison EPSMonitorFunction PEPStoppingFunction PEPEigenvalueComparison PEPMonitorFunction NEPStoppingFunction NEPEigenvalueComparison NEPMonitorFunction NEPFunction NEPJacobian SVDStoppingFunction SVDMonitorFunction MFNMonitorFunction LMEMonitorFunction ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/reference.rst0000644000076500000240000000020015133663436017500 0ustar00jromanstaff.. _reference: Reference ========= .. autosummary:: :toctree: reference/ slepc4py slepc4py.typing slepc4py.SLEPc ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/docs/source/tutorial.rst0000644000076500000240000000164215133663436017420 0ustar00jromanstaffTutorial ======== Below we provide links to tutorial examples intended for learning the basics of slepc4py. For additional information, the reader is referred to: + slepc4py :ref:`reference` (manual pages for all slepc4py classes and methods). + `SLEPc documentation`_. + `petsc4py documentation`_. .. _SLEPc documentation: https://slepc.upv.es/release/documentation .. _petsc4py documentation: https://petsc.org/release/petsc4py Commented source of demo examples --------------------------------- + To get started, we recommend having a look at the source code of example ``demo/ex1.py``, that has comments inserted inline. It is also `available online here <../slepc4py/demo/ex1.html>`__. This example solves a standard symmetric eigenvalue problem. * Demo examples for other problems, including linear and nonlinear eigenvalue problems and singular value problems, are available in the section :ref:`demos`. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/pyproject.toml0000644000076500000240000000016215133663436015503 0ustar00jromanstaff[build-system] requires = [ "cython >= 3", "numpy", "setuptools", ] build-backend = "setuptools.build_meta" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5732546 slepc4py-3.24.2/setup.cfg0000644000076500000240000000030015133664271014400 0ustar00jromanstaff[config] slepc_dir = $SLEPC_DIR petsc_dir = $PETSC_DIR petsc_arch = $PETSC_ARCH [build] debug = 0 [sdist] force_manifest = 1 [nosetests] where = test [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/setup.py0000755000076500000240000002262615133663436014315 0ustar00jromanstaff#!/usr/bin/env python3 # Author: Lisandro Dalcin # Contact: dalcinl@gmail.com import re import os import sys import warnings try: import setuptools except ImportError: setuptools = None topdir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(topdir, 'conf')) pyver = sys.version_info[:2] if pyver < (3, 6): raise RuntimeError("Python version 3.6 or higher is required") PNAME = 'SLEPc' EMAIL = 'slepc-maint@upv.es' PLIST = [PNAME, 'PETSc'] # -------------------------------------------------------------------- # Metadata # -------------------------------------------------------------------- py_limited_api = (3, 10) def F(string): return string.format( Name=PNAME, name=PNAME.lower(), pyname=PNAME.lower()+'4py', ) def get_name(): return F('{pyname}') def get_version(): try: return get_version.result except AttributeError: pass pkg_init_py = os.path.join(F('{pyname}'), '__init__.py') with open(os.path.join(topdir, 'src', pkg_init_py)) as f: m = re.search(r"__version__\s*=\s*'(.*)'", f.read()) version = m.groups()[0] get_version.result = version return version def description(): return F('{Name} for Python') def long_description(): with open(os.path.join(topdir, 'DESCRIPTION.rst')) as f: return f.read() url = F('https://gitlab.com/{name}/{name}') pypiroot = F('https://pypi.io/packages/source') pypislug = F('{pyname}')[0] + F('/{pyname}') tarball = F('{pyname}-%s.tar.gz' % get_version()) download = '/'.join([pypiroot, pypislug, tarball]) classifiers = """ Operating System :: POSIX Intended Audience :: Developers Intended Audience :: Science/Research Programming Language :: C Programming Language :: C++ Programming Language :: Cython Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: Implementation :: CPython Topic :: Scientific/Engineering Topic :: Software Development :: Libraries :: Python Modules Development Status :: 5 - Production/Stable """.strip().split('\n') keywords = """ scientific computing parallel computing MPI """.strip().split('\n') platforms = """ POSIX Linux macOS FreeBSD """.strip().split('\n') metadata = { 'name' : get_name(), 'version' : get_version(), 'description' : description(), 'long_description' : long_description(), 'url' : url, 'download_url' : download, 'classifiers' : classifiers, 'keywords' : keywords + PLIST, 'license' : 'BSD-2-Clause', 'platforms' : platforms, 'author' : 'Lisandro Dalcin', 'author_email' : 'dalcinl@gmail.com', 'maintainer' : F('{Name} Team'), 'maintainer_email' : EMAIL, } metadata.update( { 'requires': ['numpy'], } ) metadata_extra = { 'long_description_content_type': 'text/x-rst', } def get_build_pysabi(): abi = os.environ.get("SLEPC4PY_BUILD_PYSABI", "").lower() if abi and sys.implementation.name == "cpython": if abi in {"false", "no", "off", "n", "0"}: return None if abi in {"true", "yes", "on", "y", "1"} | {"abi3"}: return py_limited_api if abi.startswith("cp"): abi = abi[2:] if "." in abi: x, y = abi.split(".") else: x, y = abi[0], abi[1:] return (int(x), int(y)) return None # -------------------------------------------------------------------- # Extension modules # -------------------------------------------------------------------- def sources(): src = { 'source': F('{pyname}/{Name}.pyx'), 'depends': [ F('{pyname}/*.pyx'), F('{pyname}/*.pxd'), F('{pyname}/{Name}/*.pyx'), F('{pyname}/{Name}/*.pxd'), F('{pyname}/{Name}/*.pxi'), ], 'workdir': 'src', } return [src] def extensions(): from os import walk from glob import glob from os.path import join # depends = [] glob_join = lambda *args: glob(join(*args)) for pth, dirs, files in walk('src'): depends += glob_join(pth, '*.h') depends += glob_join(pth, '*.c') for pkg in map(str.lower, reversed(PLIST)): if (pkg.upper()+'_DIR') in os.environ: pd = os.environ[pkg.upper()+'_DIR'] pa = os.environ.get('PETSC_ARCH', '') depends += glob_join(pd, 'include', '*.h') depends += glob_join(pd, 'include', pkg, 'private', '*.h') depends += glob_join(pd, pa, 'include', '%sconf.h' % pkg) # include_dirs = [] numpy_include = os.environ.get('NUMPY_INCLUDE') if numpy_include is not None: numpy_includes = [numpy_include] else: try: import numpy numpy_includes = [numpy.get_include()] except ImportError: numpy_includes = [] include_dirs.extend(numpy_includes) if F('{pyname}') != 'petsc4py': try: import petsc4py petsc4py_includes = [petsc4py.get_include()] except ImportError: petsc4py_includes = [] include_dirs.extend(petsc4py_includes) # ext = { 'name': F('{pyname}.lib.{Name}'), 'sources': [F('src/{pyname}/{Name}.c')], 'depends': depends, 'include_dirs': [ 'src', F('src/{pyname}/include'), ] + include_dirs, 'define_macros': [ ('MPICH_SKIP_MPICXX', 1), ('OMPI_SKIP_MPICXX', 1), ('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION'), ], } return [ext] # -------------------------------------------------------------------- # Setup # -------------------------------------------------------------------- def get_release(): suffix = os.path.join('src', 'binding', F('{pyname}')) if not topdir.endswith(os.path.join(os.path.sep, suffix)): return True release = 1 rootdir = os.path.abspath(os.path.join(topdir, *[os.path.pardir]*3)) version_h = os.path.join(rootdir, 'include', F('{name}version.h')) release_macro = '%s_VERSION_RELEASE' % F('{name}').upper() version_re = re.compile(r'#define\s+%s\s+([-]*\d+)' % release_macro) if os.path.exists(version_h) and os.path.isfile(version_h): with open(version_h, 'r') as f: release = int(version_re.search(f.read()).groups()[0]) return bool(release) def requires(pkgname, major, minor, release=True): minor = minor + int(not release) devel = '' if release else '.dev0' vmin = f'{major}.{minor}{devel}' vmax = f'{major}.{minor+1}' return f'{pkgname}>={vmin},<{vmax}' def run_setup(): is_sdist = 'sdist' in sys.argv setup_args = metadata.copy() vstr = setup_args['version'].split('.')[:2] x, y = tuple(map(int, vstr)) release = get_release() if not release: setup_args['version'] = '%d.%d.0.dev0' % (x, y + 1) if setuptools: warnings.filterwarnings( 'ignore', message=r'.*fetch_build_eggs', module='setuptools' ) setup_args['zip_safe'] = False numpy_pin = 'numpy' if not is_sdist: try: import numpy major = int(numpy.__version__.partition('.')[0]) numpy_pin = 'numpy>=1.19' if major >= 2 else 'numpy<2' except ImportError: pass setup_args['setup_requires'] = ['numpy'] setup_args['install_requires'] = [numpy_pin] for pkg in map(str.lower, PLIST): PKG_DIR = os.environ.get(pkg.upper() + '_DIR') if not (PKG_DIR and os.path.isdir(PKG_DIR)): package = requires(pkg, x, y, release) setup_args['setup_requires'] += [package] setup_args['install_requires'] += [package] if F('{pyname}') != 'petsc4py': package = requires('petsc4py', x, y, release) setup_args['setup_requires'] += [package] setup_args['install_requires'] += [package] setup_args.update(metadata_extra) # conf = __import__(F('conf{name}')) cython_sources = [src for src in sources()] # noqa: C416 ext_modules = [conf.Extension(**ext) for ext in extensions()] # sabi = get_build_pysabi() if sabi and setuptools: api_tag = "cp{}{}".format(*sabi) options = {"bdist_wheel": {"py_limited_api": api_tag}} setup_args["options"] = options api_ver = "0x{:02X}{:02X}0000".format(*sabi) defines = [("Py_LIMITED_API", api_ver)] for ext in ext_modules: ext.define_macros.extend(defines) ext.py_limited_api = True # conf.setup( packages=[ F('{pyname}'), F('{pyname}.lib'), ], package_dir={'' : 'src'}, package_data={ F('{pyname}'): [ F('{Name}.pxd'), F('{Name}*.h'), F('include/{pyname}/*.h'), F('include/{pyname}/*.i'), 'py.typed', '*.pyi', '*/*.pyi', ], F('{pyname}.lib'): [ F('{name}.cfg'), ], }, cython_sources=cython_sources, ext_modules=ext_modules, **setup_args, ) # -------------------------------------------------------------------- def main(): run_setup() if __name__ == '__main__': main() # -------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5386217 slepc4py-3.24.2/src/0000755000076500000240000000000015133664271013355 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5398262 slepc4py-3.24.2/src/lib-slepc/0000755000076500000240000000000015133664271015227 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/lib-slepc/compat.h0000644000076500000240000000022115133663436016660 0ustar00jromanstaff#ifndef SLEPC4PY_COMPAT_H #define SLEPC4PY_COMPAT_H #if !defined(PETSC_USE_COMPLEX) #endif /*PETSC_USE_COMPLEX*/ #endif /*SLEPC4PY_COMPAT_H*/ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/lib-slepc/custom.h0000644000076500000240000000142015133663436016711 0ustar00jromanstaff#ifndef SLEPC4PY_CUSTOM_H #define SLEPC4PY_CUSTOM_H #ifndef PETSC_ERR_PYTHON #define PETSC_ERR_PYTHON ((PetscErrorCode)(-1)) #endif #undef __FUNCT__ #define __FUNCT__ "SlepcInitializePackageAll" static PetscErrorCode SlepcInitializePackageAll(void) { PetscFunctionBegin; PetscCall(EPSInitializePackage()); PetscCall(SVDInitializePackage()); PetscCall(PEPInitializePackage()); PetscCall(NEPInitializePackage()); PetscCall(LMEInitializePackage()); PetscCall(MFNInitializePackage()); PetscCall(LMEInitializePackage()); PetscCall(STInitializePackage()); PetscCall(BVInitializePackage()); PetscCall(DSInitializePackage()); PetscCall(FNInitializePackage()); PetscCall(RGInitializePackage()); PetscFunctionReturn(PETSC_SUCCESS); } #endif/*SLEPC4PY_CUSTOM_H*/ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/pyapicompat.h0000644000076500000240000000455315133663436016065 0ustar00jromanstaff/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ /* -------------------------------------------------------------------------- */ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < 0x030B0000 #define Py_bf_getbuffer 1 #define Py_bf_releasebuffer 2 typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE) #define PyBUF_CONTIG_RO (PyBUF_ND) #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE) #define PyBUF_STRIDED_RO (PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT) #define PyBUF_READ 0x100 #define PyBUF_WRITE 0x200 PyAPI_FUNC(int) PyObject_CheckBuffer(PyObject *); PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *, Py_buffer *, int); PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *); PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *, PyObject *, void *, Py_ssize_t, int, int); #endif /* -------------------------------------------------------------------------- */ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < 0x030D0000 /* https://github.com/cython/cython/pull/6914 */ #define PyDict_GetItemStringRef PyDict_GetItemStringRef_313 static inline int PyDict_GetItemStringRef(PyObject *d, const char *key, PyObject **result) { PyObject *key_obj = PyUnicode_FromString(key); if (key_obj == NULL) return -1; *result = PyDict_GetItemWithError(d, key_obj); Py_DECREF(key_obj); if (*result == NULL) return PyErr_Occurred() ? -1 : 0; Py_INCREF(*result); return 1; } #endif /* -------------------------------------------------------------------------- */ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5435963 slepc4py-3.24.2/src/slepc4py/0000755000076500000240000000000015133664271015120 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1768908984.567757 slepc4py-3.24.2/src/slepc4py/SLEPc/0000755000076500000240000000000015133664271016026 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/BV.pyx0000644000076500000240000020120415133663436017100 0ustar00jromanstaff# ----------------------------------------------------------------------------- class BVType(object): """ BV type. - `MAT`: A `BV` stored as a dense `petsc.Mat`. - `SVEC`: A `BV` stored as a single `petsc.Vec`. - `VECS`: A `BV` stored as an array of independent `petsc.Vec`. - `CONTIGUOUS`: A `BV` stored as an array of `petsc.Vec` sharing a contiguous array of scalars. - `TENSOR`: A special `BV` represented in compact form as :math:`V = (I \otimes U) S`. See Also -------- slepc.BVType """ MAT = S_(BVMAT) SVEC = S_(BVSVEC) VECS = S_(BVVECS) CONTIGUOUS = S_(BVCONTIGUOUS) TENSOR = S_(BVTENSOR) class BVOrthogType(object): """ BV orthogonalization types. - `CGS`: Classical Gram-Schmidt. - `MGS`: Modified Gram-Schmidt. See Also -------- slepc.BVOrthogType """ CGS = BV_ORTHOG_CGS MGS = BV_ORTHOG_MGS class BVOrthogRefineType(object): """ BV orthogonalization refinement types. - `IFNEEDED`: Reorthogonalize if a criterion is satisfied. - `NEVER`: Never reorthogonalize. - `ALWAYS`: Always reorthogonalize. See Also -------- slepc.BVOrthogRefineType """ IFNEEDED = BV_ORTHOG_REFINE_IFNEEDED NEVER = BV_ORTHOG_REFINE_NEVER ALWAYS = BV_ORTHOG_REFINE_ALWAYS class BVOrthogBlockType(object): """ BV block-orthogonalization types. - `GS`: Gram-Schmidt, column by column. - `CHOL`: Cholesky QR method. - `TSQR`: Tall-skinny QR method. - `TSQRCHOL`: Tall-skinny QR, but computing the triangular factor only. - `SVQB`: SVQB method. See Also -------- slepc.BVOrthogBlockType """ GS = BV_ORTHOG_BLOCK_GS CHOL = BV_ORTHOG_BLOCK_CHOL TSQR = BV_ORTHOG_BLOCK_TSQR TSQRCHOL = BV_ORTHOG_BLOCK_TSQRCHOL SVQB = BV_ORTHOG_BLOCK_SVQB class BVMatMultType(object): """ BV mat-mult types. - `VECS`: Perform a matrix-vector multiply per each column. - `MAT`: Carry out a Mat-Mat product with a dense matrix. See Also -------- slepc.BVMatMultType """ VECS = BV_MATMULT_VECS MAT = BV_MATMULT_MAT class BVSVDMethod(object): """ BV methods for computing the SVD. - `REFINE`: Based on the SVD of the cross product matrix :math:`S^* S`, with refinement. - `QR`: Based on the SVD of the triangular factor of qr(S). - `QR_CAA`: Variant of QR intended for use in communication-avoiding. Arnoldi. See Also -------- slepc.BVSVDMethod """ REFINE = BV_SVD_METHOD_REFINE QR = BV_SVD_METHOD_QR QR_CAA = BV_SVD_METHOD_QR_CAA # ----------------------------------------------------------------------------- cdef class BV(Object): """ Basis Vectors. The `BV` package provides the concept of a block of vectors that represent the basis of a subspace. It is a convenient way of handling a collection of vectors that often operate together, rather than working with an array of `petsc4py.PETSc.Vec`. """ Type = BVType OrthogType = BVOrthogType OrthogRefineType = BVOrthogRefineType RefineType = BVOrthogRefineType OrthogBlockType = BVOrthogBlockType BlockType = BVOrthogBlockType MatMultType = BVMatMultType SVDMethod = BVSVDMethod def __cinit__(self): self.obj = &self.bv self.bv = NULL # unary operations def __pos__(self): return bv_pos(self) def __neg__(self): return bv_neg(self) # inplace binary operations def __iadd__(self, other): return bv_iadd(self, other) def __isub__(self, other): return bv_isub(self, other) def __imul__(self, other): return bv_imul(self, other) def __idiv__(self, other): return bv_idiv(self, other) def __itruediv__(self, other): return bv_idiv(self, other) # binary operations def __add__(self, other): return bv_add(self, other) def __radd__(self, other): return bv_radd(self, other) def __sub__(self, other): return bv_sub(self, other) def __rsub__(self, other): return bv_rsub(self, other) def __mul__(self, other): return bv_mul(self, other) def __rmul__(self, other): return bv_rmul(self, other) def __div__(self, other): return bv_div(self, other) def __rdiv__(self, other): return bv_rdiv(self, other) def __truediv__(self, other): return bv_div(self, other) def __rtruediv__(self, other): return bv_rdiv(self, other) # def view(self, Viewer viewer=None) -> None: """ Print the BV data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.BVView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( BVView(self.bv, vwr) ) def destroy(self) -> Self: """ Destroy the BV object. Collective. See Also -------- slepc.BVDestroy """ CHKERR( BVDestroy(&self.bv) ) self.bv = NULL return self def create(self, comm: Comm | None = None) -> Self: """ Create the BV object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- createFromMat, slepc.BVCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcBV newbv = NULL CHKERR( BVCreate(ccomm, &newbv) ) CHKERR( SlepcCLEAR(self.obj) ); self.bv = newbv return self def createFromMat(self, Mat A) -> Self: """ Create a basis vectors object from a dense matrix. Collective. Parameters ---------- A A dense tall-skinny matrix. Notes ----- The matrix values are copied to the `BV` data storage, memory is not shared. The communicator of the `BV` object will be the same as `A`, and so will be the dimensions. See Also -------- create, createMat, slepc.BVCreateFromMat """ cdef SlepcBV newbv = NULL CHKERR( BVCreateFromMat(A.mat, &newbv) ) CHKERR( SlepcCLEAR(self.obj) ); self.bv = newbv return self def createMat(self) -> Mat: """ Create a new dense matrix and copy the contents of the BV. Collective. Returns ------- petsc4py.PETSc.Mat The new matrix. Notes ----- The matrix contains all columns of the `BV`, not just the active columns. See Also -------- createFromMat, createVec, getMat, slepc.BVCreateMat """ cdef Mat mat = Mat() CHKERR( BVCreateMat(self.bv, &mat.mat) ) return mat def duplicate(self) -> BV: """ Duplicate the BV object with the same type and dimensions. Collective. Returns ------- BV The new object. Notes ----- This function does not copy the entries, it just allocates the storage for the new `BV`. Use `copy()` to copy the content. See Also -------- duplicateResize, slepc.BVDuplicate """ cdef BV bv = type(self)() CHKERR( BVDuplicate(self.bv, &bv.bv) ) return bv def duplicateResize(self, m: int) -> BV: """ Create a BV object of the same type and dimensions as an existing one. Collective. Parameters ---------- m The number of columns. Returns ------- BV The new object. Notes ----- This is equivalent to a call to `duplicate()` followed by `resize()` with possibly different number of columns. The contents of this `BV` are not copied to the new one. See Also -------- duplicate, resize, slepc.BVDuplicateResize """ cdef BV bv = type(self)() cdef PetscInt ival = asInt(m) CHKERR( BVDuplicateResize(self.bv, ival, &bv.bv) ) return bv def copy(self, BV result=None) -> BV: """ Copy a basis vector object into another one. Logically collective. Returns ------- BV The copy. Parameters ---------- result The copy. Notes ----- Both objects must be distributed in the same manner; local copies are done. Only active columns (excluding the leading ones) are copied. In the destination BV, columns are overwritten starting from the leading ones. Constraints are not copied. See Also -------- slepc.BVCopy """ if result is None: result = type(self)() if result.bv == NULL: CHKERR( BVDuplicate(self.bv, &result.bv) ) CHKERR( BVCopy(self.bv, result.bv) ) return result def setType(self, bv_type: Type | str) -> None: """ Set the type for the BV object. Logically collective. Parameters ---------- bv_type The basis vectors type to be used. See Also -------- getType, slepc.BVSetType """ cdef SlepcBVType cval = NULL bv_type = str2bytes(bv_type, &cval) CHKERR( BVSetType(self.bv, cval) ) def getType(self) -> str: """ Get the BV type of this object. Not collective. Returns ------- str The basis vectors type currently being used. See Also -------- setType, slepc.BVGetType """ cdef SlepcBVType bv_type = NULL CHKERR( BVGetType(self.bv, &bv_type) ) return bytes2str(bv_type) def setSizes(self, sizes: LayoutSizeSpec, m: int) -> None: """ Set the local and global sizes, and the number of columns. Collective. Parameters ---------- sizes The global size ``N`` or a two-tuple ``(n, N)`` with the local and global sizes. m The number of columns. Notes ----- Either ``n`` or ``N`` (but not both) can be `DETERMINE` or ``None`` to have it automatically set. See Also -------- setSizesFromVec, getSizes, slepc.BVSetSizes """ cdef PetscInt n=0, N=0 cdef PetscInt ival = asInt(m) BV_Sizes(sizes, &n, &N) CHKERR( BVSetSizes(self.bv, n, N, ival) ) def setSizesFromVec(self, Vec w, m: int) -> None: """ Set the local and global sizes, and the number of columns. Collective. Local and global sizes are specified indirectly by passing a template vector. Parameters ---------- w The template vector. m The number of columns. See Also -------- setSizes, getSizes, slepc.BVSetSizesFromVec """ cdef PetscInt ival = asInt(m) CHKERR( BVSetSizesFromVec(self.bv, w.vec, ival) ) def getSizes(self) -> tuple[LayoutSizeSpec, int]: """ Get the local and global sizes, and the number of columns. Not collective. Returns ------- (n, N): tuple of int The local and global sizes. m: int The number of columns. See Also -------- setSizes, setSizesFromVec, slepc.BVGetSizes """ cdef PetscInt n=0, N=0, m=0 CHKERR( BVGetSizes(self.bv, &n, &N, &m) ) return ((toInt(n), toInt(N)), toInt(m)) def setLeadingDimension(self, ld: int) -> None: """ Set the leading dimension. Not collective. Parameters ---------- ld The leading dimension. Notes ----- This parameter is relevant for a BV of `BV.Type.MAT`. See Also -------- getLeadingDimension, slepc.BVSetLeadingDimension """ cdef PetscInt val = asInt(ld) CHKERR( BVSetLeadingDimension(self.bv, val) ) def getLeadingDimension(self) -> int: """ Get the leading dimension. Not collective. Returns ------- int The leading dimension. Notes ----- The returned value may be different in different processes. The leading dimension must be used when accessing the internal array via `getArray()`. See Also -------- setLeadingDimension, slepc.BVGetLeadingDimension """ cdef PetscInt val = 0 CHKERR( BVGetLeadingDimension(self.bv, &val) ) return toInt(val) def getArray(self, readonly: bool = False) -> ArrayScalar: """ Return the array where the data is stored. Not collective. Parameters ---------- readonly Enable to obtain a read only array. Returns ------- ArrayScalar The array. See Also -------- slepc.BVGetArray, slepc.BVGetArrayRead """ cdef PetscInt m=0, N=0, lda=0, k=0, l=0 cdef PetscScalar *data = NULL CHKERR(BVGetSizes(self.bv, NULL, &N, NULL)) CHKERR(BVGetLeadingDimension(self.bv, &lda)) CHKERR(BVGetActiveColumns(self.bv, &l, &k)) m = k-l if readonly: CHKERR(BVGetArrayRead(self.bv, &data)) else: CHKERR(BVGetArray(self.bv, &data)) cdef int typenum = NPY_PETSC_SCALAR cdef int itemsize = sizeof(PetscScalar) cdef int flags = NPY_ARRAY_FARRAY_RO if readonly else NPY_ARRAY_FARRAY cdef npy_intp dims[2], strides[2] dims[0] = N; strides[0] = sizeof(PetscScalar) dims[1] = m; strides[1] = (lda*sizeof(PetscScalar)) cdef ndarray array = PyArray_New(ndarray, 2, dims, typenum, strides, data, itemsize, flags, NULL) Py_INCREF(self) PyArray_SetBaseObject(array, self) if readonly: CHKERR(BVRestoreArrayRead(self.bv, &data)) else: CHKERR(BVRestoreArray(self.bv, &data)) return array def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all BV options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all BV option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.BVGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( BVSetOptionsPrefix(self.bv, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all BV options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all BV option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.BVAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( BVAppendOptionsPrefix(self.bv, cval) ) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all BV options in the database. Not collective. Returns ------- str The prefix string set for this BV object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.BVGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( BVGetOptionsPrefix(self.bv, &prefix) ) return bytes2str(prefix) def setFromOptions(self) -> None: """ Set BV options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.BVSetFromOptions """ CHKERR( BVSetFromOptions(self.bv) ) # def getOrthogonalization(self) -> tuple[OrthogType, OrthogRefineType, float, OrthogBlockType]: """ Get the orthogonalization settings from the BV object. Not collective. Returns ------- type: OrthogType The type of orthogonalization technique. refine: OrthogRefineType The type of refinement. eta: float Parameter for selective refinement (used when the refinement type is `IFNEEDED`). block: OrthogBlockType The type of block orthogonalization. See Also -------- setOrthogonalization, slepc.BVGetOrthogonalization """ cdef SlepcBVOrthogType val1 = BV_ORTHOG_CGS cdef SlepcBVOrthogRefineType val2 = BV_ORTHOG_REFINE_IFNEEDED cdef SlepcBVOrthogBlockType val3 = BV_ORTHOG_BLOCK_GS cdef PetscReal rval = PETSC_DEFAULT CHKERR( BVGetOrthogonalization(self.bv, &val1, &val2, &rval, &val3) ) return (val1, val2, toReal(rval), val3) def setOrthogonalization( self, otype: OrthogType | None = None, refine: OrthogRefineType | None = None, eta: float | None = None, block: OrthogBlockType | None = None, ) -> None: """ Set the method used for the (block-)orthogonalization of vectors. Logically collective. Ortogonalization of vectors (classical or modified Gram-Schmidt with or without refinement), and for the block-orthogonalization (simultaneous orthogonalization of a set of vectors). Parameters ---------- otype The type of orthogonalization technique. refine The type of refinement. eta Parameter for selective refinement. block The type of block orthogonalization. Notes ----- The default settings work well for most problems. The parameter ``eta`` should be a real value between ``0`` and ``1`` (or `DETERMINE`). The value of ``eta`` is used only when the refinement type is `IFNEEDED`. When using several processes, `MGS` is likely to result in bad scalability. If the method set for block orthogonalization is `GS`, then the computation is done column by column with the vector orthogonalization. See Also -------- getOrthogonalization, slepc.BVSetOrthogonalization """ cdef SlepcBVOrthogType val1 = BV_ORTHOG_CGS cdef SlepcBVOrthogRefineType val2 = BV_ORTHOG_REFINE_IFNEEDED cdef SlepcBVOrthogBlockType val3 = BV_ORTHOG_BLOCK_GS cdef PetscReal rval = PETSC_CURRENT CHKERR( BVGetOrthogonalization(self.bv, &val1, &val2, NULL, &val3) ) if otype is not None: val1 = otype if refine is not None: val2 = refine if block is not None: val3 = block if eta is not None: rval = asReal(eta) CHKERR( BVSetOrthogonalization(self.bv, val1, val2, rval, val3) ) def getMatMultMethod(self) -> MatMultType: """ Get the method used for the `matMult()` operation. Not collective. Returns ------- MatMultType The method for the `matMult()` operation. See Also -------- matMult, setMatMultMethod, slepc.BVGetMatMultMethod """ cdef SlepcBVMatMultType val = BV_MATMULT_MAT CHKERR( BVGetMatMultMethod(self.bv, &val) ) return val def setMatMultMethod(self, method: MatMultType) -> None: """ Set the method used for the `matMult()` operation. Logically collective. Parameters ---------- method The method for the `matMult()` operation. See Also -------- matMult, getMatMultMethod, slepc.BVSetMatMultMethod """ cdef SlepcBVMatMultType val = method CHKERR( BVSetMatMultMethod(self.bv, val) ) # def getMatrix(self) -> tuple[Mat, bool] | tuple[None, bool]: """ Get the matrix representation of the inner product. Not collective. Returns ------- B: petsc4py.PETSc.Mat The matrix of the inner product. indef: bool Whether the matrix is indefinite. See Also -------- setMatrix, slepc.BVGetMatrix """ cdef Mat B = Mat() cdef PetscBool indef = PETSC_FALSE CHKERR( BVGetMatrix(self.bv, &B.mat, &indef) ) if B.mat: CHKERR( PetscINCREF(B.obj) ) return (B, toBool(indef)) else: return (None, False) def setMatrix(self, Mat B or None: Mat | None, indef: bool = False) -> None: """ Set the bilinear form to be used for inner products. Collective. Parameters ---------- B The matrix of the inner product. indef Whether the matrix is indefinite. Notes ----- This is used to specify a non-standard inner product, whose matrix representation is given by ``B``. Then, all inner products required during orthogonalization are computed as :math:`(x,y)_B=y^*Bx` rather than the standard form :math:`(x,y)=y^*x`. Matrix ``B`` must be real symmetric (or complex Hermitian). A genuine inner product requires that ``B`` is also positive (semi-)definite. However, we also allow for an indefinite ``B`` (setting ``indef=True``), in which case the orthogonalization uses an indefinite inner product. This affects operations `dot()`, `norm()`, `orthogonalize()`, and variants. Omitting ``B`` has the same effect as if the identity matrix was passed. See Also -------- getMatrix, slepc.BVSetMatrix """ cdef PetscMat m = NULL if B is None else B.mat cdef PetscBool tval = PETSC_TRUE if indef else PETSC_FALSE CHKERR( BVSetMatrix(self.bv, m, tval) ) def applyMatrix(self, Vec x, Vec y) -> None: """ Multiply a vector with the matrix associated to the bilinear form. Neighbor-wise collective. Parameters ---------- x The input vector. y The result vector. Notes ----- If the bilinear form has no associated matrix this function copies the vector. See Also -------- setMatrix, slepc.BVApplyMatrix """ CHKERR( BVApplyMatrix(self.bv, x.vec, y.vec) ) def setActiveColumns(self, l: int, k: int) -> None: """ Set the columns that will be involved in operations. Logically collective. Parameters ---------- l The leading number of columns. k The active number of columns. Notes ----- In operations such as `mult()` or `dot()`, only the first ``k`` columns are considered. This is useful when the BV is filled from left to right, so the last ``m-k`` columns do not have relevant information. Also in operations such as `mult()` or `dot()`, the first ``l`` columns are normally not included in the computation. In orthogonalization operations, the first ``l`` columns are treated differently, they participate in the orthogonalization but the computed coefficients are not stored. Use `CURRENT` to leave any of the values unchanged. Use `DETERMINE` to set ``l`` to the minimum value (``0``) and ``k`` to the maximum (``m``). See Also -------- getActiveColumns, setSizes, slepc.BVSetActiveColumns """ cdef PetscInt ival1 = asInt(l) cdef PetscInt ival2 = asInt(k) CHKERR( BVSetActiveColumns(self.bv, ival1, ival2) ) def getActiveColumns(self) -> tuple[int, int]: """ Get the current active dimensions. Not collective. Returns ------- l: int The leading number of columns. k: int The active number of columns. See Also -------- setActiveColumns, slepc.BVGetActiveColumns """ cdef PetscInt l=0, k=0 CHKERR( BVGetActiveColumns(self.bv, &l, &k) ) return (toInt(l), toInt(k)) def scaleColumn(self, j: int, alpha: Scalar) -> None: """ Scale a column of a BV. Logically collective. Parameters ---------- j column index to be scaled. alpha scaling factor. See Also -------- scale, slepc.BVScaleColumn """ cdef PetscInt ival = asInt(j) cdef PetscScalar sval = asScalar(alpha) CHKERR( BVScaleColumn(self.bv, ival, sval) ) def scale(self, alpha: Scalar) -> None: """ Multiply the entries by a scalar value. Logically collective. Parameters ---------- alpha scaling factor. Notes ----- All active columns (except the leading ones) are scaled. See Also -------- scaleColumn, setActiveColumns, slepc.BVScale """ cdef PetscScalar sval = asScalar(alpha) CHKERR( BVScale(self.bv, sval) ) def insertVec(self, j: int, Vec w) -> None: """ Insert a vector into the specified column. Logically collective. Parameters ---------- j The column to be overwritten. w The vector to be copied. See Also -------- insertVecs, slepc.BVInsertVec """ cdef PetscInt ival = asInt(j) CHKERR( BVInsertVec(self.bv, ival, w.vec) ) def insertVecs(self, s: int, W: Vec | list[Vec], orth: bool = False) -> int: """ Insert a set of vectors into the specified columns. Collective. Parameters ---------- s The first column to be overwritten. W Set of vectors to be copied. orth Flag indicating if the vectors must be orthogonalized. Returns ------- int Number of linearly independent vectors. Notes ----- Copies the contents of vectors ``W`` into the BV columns ``s:s+n``, where ``n`` is the length of ``W``. If ``orth`` is set, then the vectors are copied one by one and then orthogonalized against the previous one. If any of them is linearly dependent then it is discarded and the not counted in the return value. See Also -------- insertVec, orthogonalizeColumn, slepc.BVInsertVecs """ if isinstance(W, Vec): W = [W] cdef PetscInt ival = asInt(s) cdef PetscVec *ws = NULL cdef Py_ssize_t i = 0, ns = len(W) cdef tmp = allocate(ns*sizeof(PetscVec),&ws) for i in range(ns): ws[i] = (W[i]).vec cdef PetscInt m = ns cdef PetscBool tval = PETSC_TRUE if orth else PETSC_FALSE CHKERR( BVInsertVecs(self.bv, ival, &m, ws, tval) ) return toInt(m) def insertConstraints(self, C: Vec | list[Vec]) -> int: """ Insert a set of vectors as constraints. Collective. Parameters ---------- C Set of vectors to be inserted as constraints. Returns ------- int Number of linearly independent constraints. Notes ----- The constraints are relevant only during orthogonalization. Constraint vectors span a subspace that is deflated in every orthogonalization operation, so they are intended for removing those directions from the orthogonal basis computed in regular BV columns. Constraints are not stored in regular columns, but in a special part of the storage. They can be accessed with negative indices in `getColumn()`. This operation is DESTRUCTIVE, meaning that all data contained in the columns of the BV is lost. This is typically invoked just after creating the BV. Once a set of constraints has been set, it is not allowed to call this function again. The vectors are copied one by one and then orthogonalized against the previous ones. If any of them is linearly dependent then it is discarded and not counted in the return value. The behavior is similar to `insertVecs()`. See Also -------- insertVecs, setNumConstraints, slepc.BVInsertConstraints """ if isinstance(C, Vec): C = [C] cdef PetscVec *cs = NULL cdef Py_ssize_t i = 0, nc = len(C) cdef tmp = allocate(nc*sizeof(PetscVec),&cs) for i in range(nc): cs[i] = (C[i]).vec cdef PetscInt m = nc CHKERR( BVInsertConstraints(self.bv, &m, cs) ) return toInt(m) def setNumConstraints(self, nc: int) -> None: """ Set the number of constraints. Logically collective. Parameters ---------- nc The number of constraints. Notes ----- This function sets the number of constraints to ``nc`` and marks all remaining columns as regular. Normal usage would be to call `insertConstraints()` instead. If ``nc`` is smaller than the previously set value, then some of the constraints are discarded. In particular, using ``nc=0`` removes all constraints preserving the content of regular columns. See Also -------- insertConstraints, getNumConstraints, slepc.BVSetNumConstraints """ cdef PetscInt val = asInt(nc) CHKERR( BVSetNumConstraints(self.bv, val) ) def getNumConstraints(self) -> int: """ Get the number of constraints. Not collective. Returns ------- int The number of constraints. See Also -------- insertConstraints, setNumConstraints, slepc.BVGetNumConstraints """ cdef PetscInt val = 0 CHKERR( BVGetNumConstraints(self.bv, &val) ) return toInt(val) def createVec(self) -> Vec: """ Create a vector with the type and dimensions of the columns of the BV. Collective. Returns ------- petsc4py.PETSc.Vec New vector. See Also -------- createMat, setVecType, slepc.BVCreateVec """ cdef Vec v = Vec() CHKERR( BVCreateVec(self.bv, &v.vec) ) return v def setVecType(self, vec_type: petsc4py.PETSc.Vec.Type | str) -> None: """ Set the vector type to be used when creating vectors via `createVec()`. Collective. Parameters ---------- vec_type Vector type used when creating vectors with `createVec`. Notes ----- This is not needed if the BV object is set up with `setSizesFromVec()`, but may be required in the case of `setSizes()` if one wants to work with non-standard vectors. See Also -------- createVec, getVecType, setSizes, setSizesFromVec, slepc.BVSetVecType """ cdef PetscVecType cval = NULL vec_type = str2bytes(vec_type, &cval) CHKERR( BVSetVecType(self.bv, cval) ) def getVecType(self) -> str: """ Get the vector type used when creating vectors via `createVec()`. Not collective. Returns ------- str The vector type. See Also -------- createVec, setVecType, slepc.BVGetVecType """ cdef PetscVecType cval = NULL CHKERR( BVGetVecType(self.bv, &cval) ) return bytes2str(cval) def copyVec(self, j: int, Vec v) -> None: """ Copy one of the columns of a basis vectors object into a vector. Logically collective. Parameters ---------- j The column index to be copied. v A vector. Notes ----- The BV and ``v`` must be distributed in the same manner; local copies are done. See Also -------- copy, copyColumn, slepc.BVCopyVec """ cdef PetscInt ival = asInt(j) CHKERR( BVCopyVec(self.bv, ival, v.vec) ) def copyColumn(self, j: int, i: int) -> None: """ Copy the values from one of the columns to another one. Logically collective. Parameters ---------- j The index of the source column. i The index of the destination column. See Also -------- copy, copyVec, slepc.BVCopyColumn """ cdef PetscInt ival1 = asInt(j) cdef PetscInt ival2 = asInt(i) CHKERR( BVCopyColumn(self.bv, ival1, ival2) ) def setDefiniteTolerance(self, deftol: float) -> None: """ Set the tolerance to be used when checking a definite inner product. Logically collective. Parameters ---------- deftol The tolerance. Notes ----- When using a non-standard inner product, see `setMatrix()`, the solver needs to compute :math:`\sqrt{z^*B z}` for various vectors :math:`z`. If the inner product has not been declared indefinite, the value :math:`z^*B z` must be positive, but due to rounding error a tiny value may become negative. A tolerance is used to detect this situation. Likewise, in complex arithmetic :math:`z^*B z` should be real, and we use the same tolerance to check whether a nonzero imaginary part can be considered negligible. See Also -------- setMatrix, getDefiniteTolerance, slepc.BVSetDefiniteTolerance """ cdef PetscReal val = asReal(deftol) CHKERR( BVSetDefiniteTolerance(self.bv, val) ) def getDefiniteTolerance(self) -> float: """ Get the tolerance to be used when checking a definite inner product. Not collective. Returns ------- float The tolerance. See Also -------- setDefiniteTolerance, slepc.BVGetDefiniteTolerance """ cdef PetscReal val = 0 CHKERR( BVGetDefiniteTolerance(self.bv, &val) ) return toReal(val) def dotVec(self, Vec v) -> ArrayScalar: """ Dot products of a vector against all the column vectors of the BV. Collective. Parameters ---------- v A vector. Returns ------- ArrayScalar The computed values. Notes ----- This is analogue to ``Vec.mDot()``, but using `BV` to represent a collection of vectors ``X``. The result is :math:`m = X^* v`, so :math:`m_i` is equal to :math:`x_j^* v`. Note that here :math:`X` is transposed as opposed to `dot()`. If a non-standard inner product has been specified with `setMatrix()`, then the result is :math:`m = X^* B v`. See Also -------- dot, dotColumn, setMatrix, slepc.BVDotVec """ l, k = self.getActiveColumns() cdef PetscScalar* mval = NULL cdef tmp = allocate((k - l)*sizeof(PetscScalar), &mval) CHKERR( BVDotVec(self.bv, v.vec, mval) ) cdef object m = None m = array_s(k - l, mval) return m def dotColumn(self, j: int) -> ArrayScalar: """ Dot products of a column against all the column vectors of a BV. Collective. Parameters ---------- j The index of the column. Returns ------- ArrayScalar The computed values. Notes ----- This operation is equivalent to `dotVec()` but it uses column ``j`` of the BV rather than taking a vector as an argument. The number of active columns of the BV is set to ``j`` before the computation, and restored afterwards. If the BV has leading columns specified, then these columns do not participate in the computation. Therefore, the length of the returned array will be ``j`` minus the number of leading columns. See Also -------- dot, dotVec, slepc.BVDotColumn """ cdef PetscInt ival = asInt(j) l, k = self.getActiveColumns() cdef PetscScalar* mval = NULL cdef tmp = allocate((k - l)*sizeof(PetscScalar), &mval) CHKERR( BVDotColumn(self.bv, ival, mval) ) cdef object m = None m = array_s(k - l, mval) return m def getColumn(self, j: int) -> Vec: """ Get a vector with the entries of the column of the BV object. Logically collective. Parameters ---------- j The index of the requested column. Returns ------- petsc4py.PETSc.Vec The vector containing the ``j``-th column. Notes ----- Modifying the returned vector will change the BV entries as well. The returned vector must not be destroyed, `restoreColumn()` must be called when it is no longer needed. At most, two columns can be fetched, that is, this function can only be called twice before the corresponding `restoreColumn()` is invoked. A negative index ``j`` selects the ``i``-th constraint, where ``i=-j``. Constraints should not be modified. See Also -------- restoreColumn, insertConstraints, slepc.BVGetColumn """ cdef Vec v = Vec() cdef PetscInt ival = asInt(j) CHKERR( BVGetColumn(self.bv, j, &v.vec) ) CHKERR( PetscINCREF(v.obj) ) return v def restoreColumn(self, j: int, Vec v) -> None: """ Restore a column obtained with `getColumn()`. Logically collective. Parameters ---------- j The index of the requested column. v The vector obtained with `getColumn()`. Notes ----- The arguments must match the corresponding call to `getColumn()`. See Also -------- getColumn, slepc.BVRestoreColumn """ cdef PetscInt ival = asInt(j) CHKERR( PetscObjectDereference(v.vec) ) CHKERR( BVRestoreColumn(self.bv, ival, &v.vec) ) def getMat(self) -> Mat: """ Get a matrix of dense type that shares the memory of the BV object. Collective. Returns ------- petsc4py.PETSc.Mat The matrix. Notes ----- The returned matrix contains only the active columns. If the content of the matrix is modified, these changes are also done in the BV object. The user must call `restoreMat()` when no longer needed. This operation implies a call to `getArray()`, which may result in data copies. See Also -------- restoreMat, createMat, getArray, slepc.BVGetMat """ cdef Mat A = Mat() CHKERR( BVGetMat(self.bv, &A.mat) ) CHKERR( PetscINCREF(A.obj) ) return A def restoreMat(self, Mat A) -> None: """ Restore the matrix obtained with `getMat()`. Logically collective. Parameters ---------- A The matrix obtained with `getMat()`. Notes ----- A call to this function must match a previous call of `getMat()`. The effect is that the contents of the matrix are copied back to the BV internal data structures. See Also -------- getMat, slepc.BVRestoreMat """ CHKERR( PetscObjectDereference(A.mat) ) CHKERR( BVRestoreMat(self.bv, &A.mat) ) def dot(self, BV Y) -> Mat: """ Compute the 'block-dot' product of two basis vectors objects. Collective. :math:`M = Y^* X` :math:`(m_{ij} = y_i^* x_j)` or :math:`M = Y^* B X` Parameters ---------- Y Left basis vectors, can be the same as self, giving :math:`M = X^* X`. Returns ------- petsc4py.PETSc.Mat The resulting matrix. Notes ----- This is the generalization of ``Vec.dot()`` for a collection of vectors, :math:`M = Y^* X`. The result is a matrix :math:`M` whose entry :math:`m_{ij}` is equal to :math:`y_i^* x_j` (where :math:`y_i^*` denotes the conjugate transpose of :math:`y_i`). :math:`X` and :math:`Y` can be the same object. If a non-standard inner product has been specified with `setMatrix()`, then the result is :math:`M = Y^* B X`. In this case, both :math:`X` and :math:`Y` must have the same associated matrix. Only rows (resp. columns) of :math:`M` starting from :math:`l_y` (resp. :math:`l_x`) are computed, where :math:`l_y` (resp. :math:`l_x`) is the number of leading columns of :math:`Y` (resp. :math:`X`). See Also -------- dotVec, dotColumn, setActiveColumns, setMatrix, slepc.BVDot """ cdef BV X = self cdef PetscInt ky=0, kx=0 CHKERR( BVGetActiveColumns(Y.bv, NULL, &ky) ) CHKERR( BVGetActiveColumns(X.bv, NULL, &kx) ) cdef Mat M = Mat().createDense((ky, kx), comm=COMM_SELF).setUp() CHKERR( BVDot(X.bv, Y.bv, M.mat) ) return M def matProject(self, Mat A: Mat | None, BV Y) -> Mat: """ Compute the projection of a matrix onto a subspace. Collective. :math:`M = Y^* A X` Parameters ---------- A Matrix to be projected. Y Left basis vectors, can be the same as self, giving :math:`M = X^* A X`. Returns ------- petsc4py.PETSc.Mat Projection of the matrix ``A`` onto the subspace. Notes ----- If ``A`` is ``None``, then it is assumed that the BV already contains :math:`AX`. This operation is similar to `dot()`, with important differences. The goal is to compute the matrix resulting from the orthogonal projection of ``A`` onto the subspace spanned by the columns of the BV, :math:`M = X^*AX`, or the oblique projection onto the BV along the second one ``Y``, :math:`M = Y^*AX`. A difference with respect to `dot()` is that the standard inner product is always used, regardless of a non-standard inner product being specified with `setMatrix()`. See Also -------- dot, setActiveColumns, setMatrix, slepc.BVMatProject """ cdef BV X = self cdef PetscInt kx=0, ky=0 CHKERR( BVGetActiveColumns(X.bv, NULL, &kx) ) CHKERR( BVGetActiveColumns(Y.bv, NULL, &ky) ) cdef PetscMat Amat = NULL if A is None else A.mat cdef Mat M = Mat().createDense((ky, kx), comm=COMM_SELF).setUp() CHKERR( BVMatProject(X.bv, Amat, Y.bv, M.mat) ) return M def matMult(self, Mat A, BV Y=None) -> BV: """ Compute the matrix-vector product for each column, :math:`Y = A V`. Neighbor-wise collective. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. It is possible to choose whether the computation is done column by column or as a dense matrix-matrix product with `setMatMultMethod()`. See Also -------- copy, matMultColumn, matMultTranspose, setMatMultMethod, slepc.BVMatMult """ cdef MPI_Comm comm = PetscObjectComm(self.bv) cdef SlepcBVType bv_type = NULL cdef PetscInt n=0, N=0, m=0 cdef SlepcBVOrthogType val1 = BV_ORTHOG_CGS cdef SlepcBVOrthogRefineType val2 = BV_ORTHOG_REFINE_IFNEEDED cdef SlepcBVOrthogBlockType val3 = BV_ORTHOG_BLOCK_GS cdef PetscReal rval = PETSC_DEFAULT if Y is None: Y = BV() if Y.bv == NULL: CHKERR( BVGetType(self.bv, &bv_type) ) CHKERR( MatGetLocalSize(A.mat, &n, NULL) ) CHKERR( MatGetSize(A.mat, &N, NULL) ) CHKERR( BVGetSizes(self.bv, NULL, NULL, &m) ) CHKERR( BVGetOrthogonalization(self.bv, &val1, &val2, &rval, &val3) ) CHKERR( BVCreate(comm, &Y.bv) ) CHKERR( BVSetType(Y.bv, bv_type) ) CHKERR( BVSetSizes(Y.bv, n, N, m) ) CHKERR( BVSetOrthogonalization(Y.bv, val1, val2, rval, val3) ) CHKERR( BVMatMult(self.bv, A.mat, Y.bv) ) return Y def matMultTranspose(self, Mat A, BV Y=None) -> BV: """ Pre-multiplication with the transpose of a matrix. Neighbor-wise collective. :math:`Y = A^T V`. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. See Also -------- matMult, matMultTransposeColumn, slepc.BVMatMultTranspose """ cdef MPI_Comm comm = PetscObjectComm(self.bv) cdef SlepcBVType bv_type = NULL cdef PetscInt n=0, N=0, m=0 cdef SlepcBVOrthogType val1 = BV_ORTHOG_CGS cdef SlepcBVOrthogRefineType val2 = BV_ORTHOG_REFINE_IFNEEDED cdef SlepcBVOrthogBlockType val3 = BV_ORTHOG_BLOCK_GS cdef PetscReal rval = PETSC_DEFAULT if Y is None: Y = BV() if Y.bv == NULL: CHKERR( BVGetType(self.bv, &bv_type) ) CHKERR( MatGetLocalSize(A.mat, NULL, &n) ) CHKERR( MatGetSize(A.mat, NULL, &N) ) CHKERR( BVGetSizes(self.bv, NULL, NULL, &m) ) CHKERR( BVGetOrthogonalization(self.bv, &val1, &val2, &rval, &val3) ) CHKERR( BVCreate(comm, &Y.bv) ) CHKERR( BVSetType(Y.bv, bv_type) ) CHKERR( BVSetSizes(Y.bv, n, N, m) ) CHKERR( BVSetOrthogonalization(Y.bv, val1, val2, rval, val3) ) CHKERR( BVMatMultTranspose(self.bv, A.mat, Y.bv) ) return Y def matMultHermitianTranspose(self, Mat A, BV Y=None) -> BV: """ Pre-multiplication with the conjugate transpose of a matrix. Neighbor-wise collective. :math:`Y = A^* V`. Parameters ---------- A The matrix. Returns ------- BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. If ``Y`` is ``None`` a new BV is created. See Also -------- matMult, matMultHermitianTransposeColumn, slepc.BVMatMultHermitianTranspose """ cdef MPI_Comm comm = PetscObjectComm(self.bv) cdef SlepcBVType bv_type = NULL cdef PetscInt n=0, N=0, m=0 cdef SlepcBVOrthogType val1 = BV_ORTHOG_CGS cdef SlepcBVOrthogRefineType val2 = BV_ORTHOG_REFINE_IFNEEDED cdef SlepcBVOrthogBlockType val3 = BV_ORTHOG_BLOCK_GS cdef PetscReal rval = PETSC_DEFAULT if Y is None: Y = BV() if Y.bv == NULL: CHKERR( BVGetType(self.bv, &bv_type) ) CHKERR( MatGetLocalSize(A.mat, NULL, &n) ) CHKERR( MatGetSize(A.mat, NULL, &N) ) CHKERR( BVGetSizes(self.bv, NULL, NULL, &m) ) CHKERR( BVGetOrthogonalization(self.bv, &val1, &val2, &rval, &val3) ) CHKERR( BVCreate(comm, &Y.bv) ) CHKERR( BVSetType(Y.bv, bv_type) ) CHKERR( BVSetSizes(Y.bv, n, N, m) ) CHKERR( BVSetOrthogonalization(Y.bv, val1, val2, rval, val3) ) CHKERR( BVMatMultHermitianTranspose(self.bv, A.mat, Y.bv) ) return Y def matMultColumn(self, Mat A, j: int) -> None: """ Mat-vec product for a column, storing the result in the next column. Neighbor-wise collective. :math:`v_{j+1} = A v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMult, slepc.BVMatMultColumn """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultColumn(self.bv, A.mat, ival) ) def matMultTransposeColumn(self, Mat A, j: int) -> None: """ Transpose matrix-vector product for a specified column. Neighbor-wise collective. Store the result in the next column: :math:`v_{j+1} = A^T v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMultColumn, slepc.BVMatMultTransposeColumn """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultTransposeColumn(self.bv, A.mat, ival) ) def matMultHermitianTransposeColumn(self, Mat A, j: int) -> None: """ Conjugate-transpose matrix-vector product for a specified column. Neighbor-wise collective. Store the result in the next column: :math:`v_{j+1} = A^* v_j`. Parameters ---------- A The matrix. j Index of column. See Also -------- matMultColumn, slepc.BVMatMultHermitianTransposeColumn """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultHermitianTransposeColumn(self.bv, A.mat, ival) ) def mult(self, delta: Scalar, gamma: Scalar, BV X, Mat Q or None: Mat | None) -> None: """ Compute :math:`Y = \gamma Y + \delta X Q`. Logically collective. Parameters ---------- delta Coefficient that multiplies ``X``. gamma Coefficient that multiplies self (``Y``). X Input basis vectors. Q Input matrix, if not given the identity matrix is assumed. Notes ----- ``X`` must be different from self (``Y``). The case ``X=Y`` can be addressed with `multInPlace()`. See Also -------- multVec, multColumn, multInPlace, slepc.BVMult """ cdef PetscScalar sval1 = asScalar(delta) cdef PetscScalar sval2 = asScalar(gamma) cdef PetscMat Qmat = NULL if Q is None else Q.mat CHKERR( BVMult(self.bv, sval1, sval2, X.bv, Qmat) ) def multInPlace(self, Mat Q, s: int, e: int) -> None: """ Update a set of vectors as :math:`V(:,s:e-1) = V Q(:,s:e-1)`. Logically collective. Parameters ---------- Q A sequential dense matrix. s First column to be overwritten. e Last column to be overwritten. See Also -------- mult, multVec, slepc.BVMultInPlace """ cdef PetscInt ival1 = asInt(s) cdef PetscInt ival2 = asInt(e) CHKERR( BVMultInPlace(self.bv, Q.mat, ival1, ival2) ) def multColumn(self, delta: Scalar, gamma: Scalar, j: int, q: Sequence[Scalar]) -> None: """ Compute :math:`y = \gamma y + \delta X q`. Logically collective. Compute :math:`y = \gamma y + \delta X q`, where :math:`y` is the ``j``-th column. Parameters ---------- delta Coefficient that multiplies self (``X``). gamma Coefficient that multiplies :math:`y`. j The column index. q Input coefficients. See Also -------- mult, multVec, multInPlace, slepc.BVMultColumn """ cdef PetscScalar sval1 = asScalar(delta) cdef PetscScalar sval2 = asScalar(gamma) cdef PetscInt ival = asInt(j) cdef PetscInt nq = 0 cdef PetscScalar* qval = NULL cdef tmp = iarray_s(q, &nq, &qval) cdef PetscInt l=0, k=0 CHKERR( BVGetActiveColumns(self.bv, &l, &k) ) assert nq == k-l CHKERR( BVMultColumn(self.bv, sval1, sval2, ival, qval) ) def multVec(self, delta: Scalar, gamma: Scalar, Vec y, q: Sequence[Scalar]) -> None: """ Compute :math:`y = \gamma y + \delta X q`. Logically collective. Parameters ---------- delta Coefficient that multiplies self (``X``). gamma Coefficient that multiplies ``y``. y Input/output vector. q Input coefficients. See Also -------- mult, multColumn, multInPlace, slepc.BVMultVec """ cdef PetscScalar sval1 = asScalar(delta) cdef PetscScalar sval2 = asScalar(gamma) cdef PetscInt nq = 0 cdef PetscScalar* qval = NULL cdef tmp = iarray_s(q, &nq, &qval) cdef PetscInt l=0, k=0 CHKERR( BVGetActiveColumns(self.bv, &l, &k) ) assert nq == k-l CHKERR( BVMultVec(self.bv, sval1, sval2, y.vec, qval) ) def normColumn(self, j: int, norm_type: NormType | None = None) -> float: """ Compute the vector norm of a selected column. Collective. Parameters ---------- j Index of column. norm_type The norm type. Returns ------- float The norm. Notes ----- The norm of :math:`v_j` is computed (``NORM_1``, ``NORM_2``, or ``NORM_INFINITY``). If a non-standard inner product has been specified with `setMatrix()`, then the returned value is :math:`\sqrt{v_j^* B v_j}`, where :math:`B` is the inner product matrix (argument 'norm_type' is ignored). See Also -------- norm, setMatrix, slepc.BVNormColumn """ cdef PetscNormType ntype = PETSC_NORM_2 if norm_type is not None: ntype = norm_type cdef PetscReal norm = 0 CHKERR( BVNormColumn(self.bv, j, ntype, &norm) ) return toReal(norm) def norm(self, norm_type: NormType | None = None) -> float: """ Compute the matrix norm of the BV. Collective. Parameters ---------- norm_type The norm type. Returns ------- float The norm. Notes ----- All active columns (except the leading ones) are considered as a matrix. The allowed norms are ``NORM_1``, ``NORM_FROBENIUS``, and ``NORM_INFINITY``. This operation fails if a non-standard inner product has been specified with `setMatrix()`. See Also -------- normColumn, setMatrix, slepc.BVNorm """ cdef PetscNormType ntype = PETSC_NORM_FROBENIUS if norm_type is not None: ntype = norm_type cdef PetscReal norm = 0 CHKERR( BVNorm(self.bv, ntype, &norm) ) return toReal(norm) def resize(self, m: int, copy: bool = True) -> None: """ Change the number of columns. Collective. Parameters ---------- m The new number of columns. copy A flag indicating whether current values should be kept. Notes ----- Internal storage is reallocated. If ``copy`` is ``True``, then the contents are copied to the leading part of the new space. See Also -------- setSizes, setSizesFromVec, slepc.BVResize """ cdef PetscInt ival = asInt(m) cdef PetscBool tval = PETSC_TRUE if copy else PETSC_FALSE CHKERR( BVResize(self.bv, ival, tval) ) def setRandom(self) -> None: """ Set the active columns of the BV to random numbers. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandomColumn, setRandomNormal, slepc.BVSetRandom """ CHKERR( BVSetRandom(self.bv) ) def setRandomNormal(self) -> None: """ Set the active columns of the BV to normal random numbers. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandom, setRandomSign, slepc.BVSetRandomNormal """ CHKERR( BVSetRandomNormal(self.bv) ) def setRandomSign(self) -> None: """ Set the entries of a BV to values 1 or -1 with equal probability. Logically collective. Notes ----- All active columns (except the leading ones) are modified. See Also -------- setRandomContext, setRandom, setRandomNormal, slepc.BVSetRandomSign """ CHKERR( BVSetRandomSign(self.bv) ) def setRandomColumn(self, j: int) -> None: """ Set one column of the BV to random numbers. Logically collective. Parameters ---------- j Column index to be set. See Also -------- setRandomContext, setRandom, setRandomNormal, slepc.BVSetRandomColumn """ cdef PetscInt ival = asInt(j) CHKERR( BVSetRandomColumn(self.bv, ival) ) def setRandomCond(self, condn: float) -> None: """ Set the columns of a BV to random numbers. Logically collective. The generated matrix has a prescribed condition number. Parameters ---------- condn Condition number. See Also -------- setRandomContext, setRandomSign, setRandomNormal, slepc.BVSetRandomCond """ cdef PetscReal rval = asReal(condn) CHKERR( BVSetRandomCond(self.bv, rval) ) def setRandomContext(self, Random rnd) -> None: """ Set the `petsc4py.PETSc.Random` object associated with the BV. Collective. To be used in operations that need random numbers. Parameters ---------- rnd The random number generator context. See Also -------- getRandomContext, setRandom, setRandomColumn, slepc.BVSetRandomContext """ CHKERR( BVSetRandomContext(self.bv, rnd.rnd) ) def getRandomContext(self) -> Random: """ Get the `petsc4py.PETSc.Random` object associated with the BV. Collective. Returns ------- petsc4py.PETSc.Random The random number generator context. See Also -------- setRandomContext, slepc.BVGetRandomContext """ cdef Random rnd = Random() CHKERR( BVGetRandomContext(self.bv, &rnd.rnd) ) CHKERR( PetscINCREF(rnd.obj) ) return rnd def orthogonalizeVec(self, Vec v) -> tuple[float, bool]: """ Orthogonalize a vector with respect to all active columns. Collective. Parameters ---------- v Vector to be orthogonalized, modified on return. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. Notes ----- This function applies an orthogonal projector to project vector :math:`v` onto the orthogonal complement of the span of the columns of the BV. This routine does not normalize the resulting vector. See Also -------- orthogonalizeColumn, setOrthogonalization slepc.BVOrthogonalizeVec """ cdef PetscReal norm = 0 cdef PetscBool ldep = PETSC_FALSE CHKERR( BVOrthogonalizeVec(self.bv, v.vec, NULL, &norm, &ldep) ) return (toReal(norm), toBool(ldep)) def orthogonalizeColumn(self, j: int) -> tuple[float, bool]: """ Orthogonalize a column vector with respect to the previous ones. Collective. Parameters ---------- j Index of the column to be orthogonalized. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. Notes ----- This function applies an orthogonal projector to project vector :math:`v_j` onto the orthogonal complement of the span of the columns :math:`V[0..j-1]`, where :math:`V[.]` are the vectors of the BV. The columns :math:`V[0..j-1]` are assumed to be mutually orthonormal. This routine does not normalize the resulting vector. See Also -------- orthogonalizeVec, setOrthogonalization slepc.BVOrthogonalizeColumn """ cdef PetscInt ival = asInt(j) cdef PetscReal norm = 0 cdef PetscBool ldep = PETSC_FALSE CHKERR( BVOrthogonalizeColumn(self.bv, ival, NULL, &norm, &ldep) ) return (toReal(norm), toBool(ldep)) def orthonormalizeColumn(self, j: int, replace: bool = False) -> tuple[float, bool]: """ Orthonormalize a column vector with respect to the previous ones. Collective. This is equivalent to a call to `orthogonalizeColumn()` followed by a call to `scaleColumn()` with the reciprocal of the norm. Parameters ---------- j Index of the column to be orthonormalized. replace Whether it is allowed to set the vector randomly. Returns ------- norm: float The norm of the resulting vector. lindep: bool Flag indicating that refinement did not improve the quality of orthogonalization. See Also -------- orthogonalizeColumn, setOrthogonalization slepc.BVOrthonormalizeColumn """ cdef PetscInt ival = asInt(j) cdef PetscBool bval = PETSC_FALSE if replace is not None: bval = asBool(replace) cdef PetscReal norm = 0 cdef PetscBool ldep = PETSC_FALSE CHKERR( BVOrthonormalizeColumn(self.bv, ival, bval, &norm, &ldep) ) return (toReal(norm), toBool(ldep)) def orthogonalize(self, Mat R=None, **kargs: Any) -> None: """ Orthogonalize all columns (except leading ones) (QR decomposition). Collective. Parameters ---------- R A sequential dense matrix. Notes ----- The output satisfies :math:`V_0 = V R` (where :math:`V_0` represent the input :math:`V`) and :math:`V^* V = I` (or :math:`V^*BV=I` if an inner product matrix :math:`B` has been specified with `setMatrix()`). See Also -------- orthogonalizeColumn, setMatrix, setOrthogonalization, slepc.BVOrthogonalize """ if kargs: self.setOrthogonalization(**kargs) cdef PetscMat Rmat = NULL if R is None else R.mat CHKERR( BVOrthogonalize(self.bv, Rmat) ) # property sizes: """Basis vectors local and global sizes, and the number of columns.""" def __get__(self) -> tuple[LayoutSizeSpec, int]: return self.getSizes() property size: """Basis vectors global size.""" def __get__(self) -> tuple[int, int]: return self.getSizes()[0][0] property local_size: """Basis vectors local size.""" def __get__(self) -> int: return self.getSizes()[0][1] property column_size: """Basis vectors column size.""" def __get__(self) -> int: return self.getSizes()[1] # ----------------------------------------------------------------------------- del BVType del BVOrthogType del BVOrthogRefineType del BVOrthogBlockType del BVMatMultType del BVSVDMethod # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/CAPI.pyx0000644000076500000240000001034115133663436017305 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef inline int setref(void *d, void *s) except -1: cdef PetscObject *dest = d cdef PetscObject source = s CHKERR( PetscINCREF(&source) ) dest[0] = source return 0 # ----------------------------------------------------------------------------- # -- ST -- cdef api object PySlepcST_New(SlepcST arg): cdef ST retv = ST() setref(&retv.st, arg) return retv cdef api SlepcST PySlepcST_Get(object arg) except ? NULL: cdef SlepcST retv = NULL cdef ST ob = arg retv = ob.st return retv # ----------------------------------------------------------------------------- # -- BV -- cdef api object PySlepcBV_New(SlepcBV arg): cdef BV retv = BV() setref(&retv.bv, arg) return retv cdef api SlepcBV PySlepcBV_Get(object arg) except ? NULL: cdef SlepcBV retv = NULL cdef BV ob = arg retv = ob.bv return retv # ----------------------------------------------------------------------------- # -- DS -- cdef api object PySlepcDS_New(SlepcDS arg): cdef DS retv = DS() setref(&retv.ds, arg) return retv cdef api SlepcDS PySlepcDS_Get(object arg) except ? NULL: cdef SlepcDS retv = NULL cdef DS ob = arg retv = ob.ds return retv # ----------------------------------------------------------------------------- # -- FN -- cdef api object PySlepcFN_New(SlepcFN arg): cdef FN retv = FN() setref(&retv.fn, arg) return retv cdef api SlepcFN PySlepcFN_Get(object arg) except ? NULL: cdef SlepcFN retv = NULL cdef FN ob = arg retv = ob.fn return retv # ----------------------------------------------------------------------------- # -- RG -- cdef api object PySlepcRG_New(SlepcRG arg): cdef RG retv = RG() setref(&retv.rg, arg) return retv cdef api SlepcRG PySlepcRG_Get(object arg) except ? NULL: cdef SlepcRG retv = NULL cdef RG ob = arg retv = ob.rg return retv # ----------------------------------------------------------------------------- # -- EPS -- cdef api object PySlepcEPS_New(SlepcEPS arg): cdef EPS retv = EPS() setref(&retv.eps, arg) return retv cdef api SlepcEPS PySlepcEPS_Get(object arg) except ? NULL: cdef SlepcEPS retv = NULL cdef EPS ob = arg retv = ob.eps return retv # ----------------------------------------------------------------------------- # -- SVD -- cdef api object PySlepcSVD_New(SlepcSVD arg): cdef SVD retv = SVD() setref(&retv.svd, arg) return retv cdef api SlepcSVD PySlepcSVD_Get(object arg) except ? NULL: cdef SlepcSVD retv = NULL cdef SVD ob = arg retv = ob.svd return retv # ----------------------------------------------------------------------------- # -- PEP -- cdef api object PySlepcPEP_New(SlepcPEP arg): cdef PEP retv = PEP() setref(&retv.pep, arg) return retv cdef api SlepcPEP PySlepcPEP_Get(object arg) except ? NULL: cdef SlepcPEP retv = NULL cdef PEP ob = arg retv = ob.pep return retv # ----------------------------------------------------------------------------- # -- NEP -- cdef api object PySlepcNEP_New(SlepcNEP arg): cdef NEP retv = NEP() setref(&retv.nep, arg) return retv cdef api SlepcNEP PySlepcNEP_Get(object arg) except ? NULL: cdef SlepcNEP retv = NULL cdef NEP ob = arg retv = ob.nep return retv # ----------------------------------------------------------------------------- # -- MFN -- cdef api object PySlepcMFN_New(SlepcMFN arg): cdef MFN retv = MFN() setref(&retv.mfn, arg) return retv cdef api SlepcMFN PySlepcMFN_Get(object arg) except ? NULL: cdef SlepcMFN retv = NULL cdef MFN ob = arg retv = ob.mfn return retv # ----------------------------------------------------------------------------- # -- LME -- cdef api object PySlepcLME_New(SlepcLME arg): cdef LME retv = LME() setref(&retv.lme, arg) return retv cdef api SlepcLME PySlepcLME_Get(object arg) except ? NULL: cdef SlepcLME retv = NULL cdef LME ob = arg retv = ob.lme return retv # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/DS.pyx0000644000076500000240000010120315133663436017075 0ustar00jromanstaff# ----------------------------------------------------------------------------- class DSType(object): """ DS type. - `HEP`: Dense Hermitian Eigenvalue Problem. - `NHEP`: Dense Non-Hermitian Eigenvalue Problem. - `GHEP`: Dense Generalized Hermitian Eigenvalue Problem. - `GHIEP`: Dense Generalized Hermitian Indefinite Eigenvalue Problem. - `GNHEP`: Dense Generalized Non-Hermitian Eigenvalue Problem. - `NHEPTS`: Dense Non-Hermitian Eigenvalue Problem (special variant intended for two-sided Krylov solvers). - `SVD`: Dense Singular Value Decomposition. - `HSVD`: Dense Hyperbolic Singular Value Decomposition. - `GSVD`: Dense Generalized Singular Value Decomposition. - `PEP`: Dense Polynomial Eigenvalue Problem. - `NEP`: Dense Nonlinear Eigenvalue Problem. See Also -------- slepc.DSType """ HEP = S_(DSHEP) NHEP = S_(DSNHEP) GHEP = S_(DSGHEP) GHIEP = S_(DSGHIEP) GNHEP = S_(DSGNHEP) NHEPTS = S_(DSNHEPTS) SVD = S_(DSSVD) HSVD = S_(DSHSVD) GSVD = S_(DSGSVD) PEP = S_(DSPEP) NEP = S_(DSNEP) class DSStateType(object): """ DS state types. - `RAW`: Not processed yet. - `INTERMEDIATE`: Reduced to Hessenberg or tridiagonal form (or equivalent). - `CONDENSED`: Reduced to Schur or diagonal form (or equivalent). - `TRUNCATED`: Condensed form truncated to a smaller size. See Also -------- slepc.DSStateType """ RAW = DS_STATE_RAW INTERMEDIATE = DS_STATE_INTERMEDIATE CONDENSED = DS_STATE_CONDENSED TRUNCATED = DS_STATE_TRUNCATED class DSMatType(object): """ To refer to one of the matrices stored internally in DS. - `A`: first matrix of eigenproblem/singular value problem. - `B`: second matrix of a generalized eigenproblem. - `C`: third matrix of a quadratic eigenproblem. - `T`: tridiagonal matrix. - `D`: diagonal matrix. - `Q`: orthogonal matrix of (right) Schur vectors. - `Z`: orthogonal matrix of left Schur vectors. - `X`: right eigenvectors. - `Y`: left eigenvectors. - `U`: left singular vectors. - `V`: right singular vectors. - `W`: workspace matrix. See Also -------- slepc.DSMatType """ A = DS_MAT_A B = DS_MAT_B C = DS_MAT_C T = DS_MAT_T D = DS_MAT_D Q = DS_MAT_Q Z = DS_MAT_Z X = DS_MAT_X Y = DS_MAT_Y U = DS_MAT_U V = DS_MAT_V W = DS_MAT_W class DSParallelType(object): """ Indicates the parallel mode that the direct solver will use. - `REDUNDANT`: Every process performs the computation redundantly. - `SYNCHRONIZED`: The first process sends the result to the rest. - `DISTRIBUTED`: Used in some cases to distribute the computation among processes. See Also -------- slepc.DSParallelType """ REDUNDANT = DS_PARALLEL_REDUNDANT SYNCHRONIZED = DS_PARALLEL_SYNCHRONIZED DISTRIBUTED = DS_PARALLEL_DISTRIBUTED # ----------------------------------------------------------------------------- cdef class DS(Object): """ Direct Solver (or Dense System). The `DS` package provides auxiliary routines that are internally used by the different slepc4py solvers. It is used to represent low-dimensional eigenproblems that must be solved within iterative solvers with direct methods. It can be seen as a structured wrapper to LAPACK functionality. """ Type = DSType StateType = DSStateType MatType = DSMatType ParallelType = DSParallelType def __cinit__(self): self.obj = &self.ds self.ds = NULL def view(self, Viewer viewer=None) -> None: """ Print the DS data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.DSView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( DSView(self.ds, vwr) ) def destroy(self) -> Self: """ Destroy the DS object. Collective. See Also -------- slepc.DSDestroy """ CHKERR( DSDestroy(&self.ds) ) self.ds = NULL return self def reset(self) -> None: """ Reset the DS object. Collective. See Also -------- allocate, slepc.DSReset """ CHKERR( DSReset(self.ds) ) def create(self, comm: Comm | None = None) -> Self: """ Create the DS object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- duplicate, slepc.DSCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcDS newds = NULL CHKERR( DSCreate(ccomm, &newds) ) CHKERR( SlepcCLEAR(self.obj) ); self.ds = newds return self def setType(self, ds_type: Type | str) -> None: """ Set the type for the DS object. Logically collective. Parameters ---------- ds_type The direct solver type to be used. See Also -------- getType, slepc.DSSetType """ cdef SlepcDSType cval = NULL ds_type = str2bytes(ds_type, &cval) CHKERR( DSSetType(self.ds, cval) ) def getType(self) -> str: """ Get the DS type of this object. Not collective. Returns ------- str The direct solver type currently being used. See Also -------- setType, slepc.DSGetType """ cdef SlepcDSType ds_type = NULL CHKERR( DSGetType(self.ds, &ds_type) ) return bytes2str(ds_type) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all DS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all DS option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.DSSetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( DSSetOptionsPrefix(self.ds, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all DS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all DS option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.DSSetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( DSAppendOptionsPrefix(self.ds, cval) ) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all DS options in the database. Not collective. Returns ------- str The prefix string set for this DS object. See Also -------- appendOptionsPrefix, setOptionsPrefix, slepc.DSSetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( DSGetOptionsPrefix(self.ds, &prefix) ) return bytes2str(prefix) def setFromOptions(self) -> None: """ Set DS options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.DSSetFromOptions """ CHKERR( DSSetFromOptions(self.ds) ) def duplicate(self) -> DS: """ Duplicate the DS object with the same type and dimensions. Collective. Returns ------- DS The new object. Notes ----- This method does not copy the matrices, and the new object does not even have internal arrays allocated. Use `allocate()` to use the new `DS`. See Also -------- create, allocate, slepc.DSDuplicate """ cdef DS ds = type(self)() CHKERR( DSDuplicate(self.ds, &ds.ds) ) return ds # def allocate(self, ld: int) -> None: """ Allocate memory for internal storage or matrices in DS. Logically collective. Parameters ---------- ld Leading dimension (maximum allowed dimension for the matrices, including the extra row if present). Notes ----- If the leading dimension is different from a previously set value, then all matrices are destroyed with `reset()`. See Also -------- getLeadingDimension, setDimensions, setExtraRow, reset, slepc.DSAllocate """ cdef PetscInt val = asInt(ld) CHKERR( DSAllocate(self.ds, val) ) def getLeadingDimension(self) -> int: """ Get the leading dimension of the allocated matrices. Not collective. Returns ------- int Leading dimension (maximum allowed dimension for the matrices). See Also -------- allocate, setDimensions, slepc.DSGetLeadingDimension """ cdef PetscInt val = 0 CHKERR( DSGetLeadingDimension(self.ds, &val) ) return toInt(val) def setState(self, state: StateType) -> None: """ Set the state of the DS object. Logically collective. Parameters ---------- state The new state. Notes ----- The state indicates that the dense system is in an initial state (raw), in an intermediate state (such as tridiagonal, Hessenberg or Hessenberg-triangular), in a condensed state (such as diagonal, Schur or generalized Schur), or in a truncated state. The state is automatically changed in functions such as `solve()` or `truncate()`. This function is normally used to return to the raw state when the condensed structure is destroyed, or to indicate that `solve()` must start with a problem that already has an intermediate form. See Also -------- getState, solve, truncate, slepc.DSSetState """ cdef SlepcDSStateType val = state CHKERR( DSSetState(self.ds, val) ) def getState(self) -> StateType: """ Get the current state. Not collective. Returns ------- StateType The current state. See Also -------- setState, slepc.DSGetState """ cdef SlepcDSStateType val = DS_STATE_RAW CHKERR( DSGetState(self.ds, &val) ) return val def setParallel(self, pmode: ParallelType) -> None: """ Set the mode of operation in parallel runs. Logically collective. Parameters ---------- pmode The parallel mode. See Also -------- getParallel, slepc.DSSetParallel """ cdef SlepcDSParallelType val = pmode CHKERR( DSSetParallel(self.ds, val) ) def getParallel(self) -> ParallelType: """ Get the mode of operation in parallel runs. Not collective. Returns ------- ParallelType The parallel mode. See Also -------- setParallel, slepc.DSGetParallel """ cdef SlepcDSParallelType val = DS_PARALLEL_REDUNDANT CHKERR( DSGetParallel(self.ds, &val) ) return val def setDimensions(self, n: int | None = None, l: int | None = None, k: int | None = None) -> None: """ Set the matrix sizes in the DS object. Logically collective. Parameters ---------- n The new size. l Number of locked (inactive) leading columns. k Intermediate dimension (e.g., position of arrow). Notes ----- The internal arrays are not reallocated. Some `DS` types have additional dimensions, e.g., the number of columns in `DS.Type.SVD`. For these, you should call a specific interface function. See Also -------- getDimensions, allocate, slepc.DSSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if n is not None: ival1 = asInt(n) if l is not None: ival2 = asInt(l) if k is not None: ival3 = asInt(k) CHKERR( DSSetDimensions(self.ds, ival1, ival2, ival3) ) def getDimensions(self) -> tuple[int, int, int, int]: """ Get the current dimensions. Not collective. Returns ------- n: int The new size. l: int Number of locked (inactive) leading columns. k: int Intermediate dimension (e.g., position of arrow). t: int Truncated length. Notes ----- The ``t`` value makes sense only if `truncate()` has been called. Otherwise it is equal to ``n``. See Also -------- setDimensions, truncate, getLeadingDimension, slepc.DSGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 cdef PetscInt ival4 = 0 CHKERR( DSGetDimensions(self.ds, &ival1, &ival2, &ival3, &ival4) ) return (toInt(ival1), toInt(ival2), toInt(ival3), toInt(ival4)) def setBlockSize(self, bs: int) -> None: """ Set the block size. Logically collective. Parameters ---------- bs The block size. See Also -------- getBlockSize, slepc.DSSetBlockSize """ cdef PetscInt val = bs CHKERR( DSSetBlockSize(self.ds, val) ) def getBlockSize(self) -> int: """ Get the block size. Not collective. Returns ------- int The block size. See Also -------- setBlockSize, slepc.DSGetBlockSize """ cdef PetscInt val = 0 CHKERR( DSGetBlockSize(self.ds, &val) ) return val def setMethod(self, meth: int) -> None: """ Set the method to be used to solve the problem. Logically collective. Parameters ---------- meth An index identifying the method. See Also -------- getMethod, slepc.DSSetMethod """ cdef PetscInt val = meth CHKERR( DSSetMethod(self.ds, val) ) def getMethod(self) -> int: """ Get the method currently used in the DS. Not collective. Returns ------- int Identifier of the method. See Also -------- setMethod, slepc.DSGetMethod """ cdef PetscInt val = 0 CHKERR( DSGetMethod(self.ds, &val) ) return val def setCompact(self, comp: bool) -> None: """ Set the compact flag for storage of matrices. Logically collective. Parameters ---------- comp ``True`` means compact storage. Notes ----- Compact storage is used in some `DS` types such as `DS.Type.HEP` when the matrix is tridiagonal. This flag can be used to indicate whether the user provides the matrix entries via the compact form (the tridiagonal `DS.MatType.T`) or the non-compact one (`DS.MatType.A`). The default is ``False``. See Also -------- getCompact, slepc.DSSetCompact """ cdef PetscBool val = asBool(comp) CHKERR( DSSetCompact(self.ds, val) ) def getCompact(self) -> bool: """ Get the compact storage flag. Not collective. Returns ------- bool The flag. See Also -------- setCompact, slepc.DSGetCompact """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetCompact(self.ds, &val) ) return toBool(val) def setExtraRow(self, ext: bool) -> None: """ Set a flag to indicate that the matrix has one extra row. Logically collective. Parameters ---------- ext ``True`` if the matrix has extra row. Notes ----- In Krylov methods it is useful that the matrix representing the direct solver has one extra row, i.e., has :math:`(n+1)` rows and :math:`(n+1)` columns. If this flag is activated, all transformations applied to the right of the matrix also affect this additional row. In that case, :math:`(n+1)` must be less or equal than the leading dimension. The default is ``False``. See Also -------- getExtraRow, solve, allocate, slepc.DSSetExtraRow """ cdef PetscBool val = asBool(ext) CHKERR( DSSetExtraRow(self.ds, val) ) def getExtraRow(self) -> bool: """ Get the extra row flag. Not collective. Returns ------- bool The flag. See Also -------- setExtraRow, slepc.DSGetExtraRow """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetExtraRow(self.ds, &val) ) return toBool(val) def setRefined(self, ref: bool) -> None: """ Set a flag to indicate that refined vectors must be computed. Logically collective. Parameters ---------- ref ``True`` if refined vectors must be used. Notes ----- Normally the vectors returned in `DS.MatType.X` are eigenvectors of the projected matrix. With this flag activated, `vectors()` will return the right singular vector of the smallest singular value of matrix :math:`\hat A - \eta I`, where :math:`\hat A` is the extended matrix (with extra row) and :math:`\eta` is the Ritz value. This is used in the refined Ritz approximation. The default is ``False``. See Also -------- getRefined, vectors, setExtraRow, slepc.DSSetRefined """ cdef PetscBool val = asBool(ref) CHKERR( DSSetRefined(self.ds, val) ) def getRefined(self) -> bool: """ Get the refined vectors flag. Not collective. Returns ------- bool The flag. See Also -------- setRefined, slepc.DSGetRefined """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetRefined(self.ds, &val) ) return toBool(val) def truncate(self, n: int, trim: bool = False) -> None: """ Truncate the system represented in the DS object. Logically collective. Parameters ---------- n The new size. trim A flag to indicate if the factorization must be trimmed. See Also -------- setDimensions, setExtraRow, slepc.DSTruncate """ cdef PetscInt val = asInt(n) cdef PetscBool flg = asBool(trim) CHKERR( DSTruncate(self.ds, val, flg) ) def updateExtraRow(self) -> None: """ Ensure that the extra row gets up-to-date after a call to `DS.solve()`. Logically collective. Perform all necessary operations so that the extra row gets up-to-date after a call to `DS.solve()`. See Also -------- slepc.DSUpdateExtraRow """ CHKERR( DSUpdateExtraRow(self.ds) ) def getMat(self, matname: MatType) -> Mat: """ Get the requested matrix as a sequential dense ``Mat`` object. Not collective. Parameters ---------- matname The requested matrix. Returns ------- petsc4py.PETSc.Mat The matrix. Notes ----- The returned matrix has sizes equal to the current `DS` dimensions (see `setDimensions()`), and contains the values that would be obtained with `getArray()`. If the `DS` was truncated, then the number of rows is equal to the dimension prior to truncation, see `truncate()`. When no longer needed the user must call `restoreMat()`. See Also -------- restoreMat, setDimensions, getArray, truncate, slepc.DSGetMat """ cdef SlepcDSMatType mname = matname cdef Mat mat = Mat() CHKERR( DSGetMat(self.ds, mname, &mat.mat) ) CHKERR( PetscINCREF(mat.obj) ) return mat def restoreMat(self, matname: MatType, Mat mat: petsc4py.PETSc.Mat) -> None: """ Restore the previously seized matrix. Not collective. Parameters ---------- matname The selected matrix. mat The matrix previously obtained with `getMat()`. See Also -------- getMat, slepc.DSRestoreMat """ cdef SlepcDSMatType mname = matname CHKERR( PetscObjectDereference(mat.mat) ) CHKERR( DSRestoreMat(self.ds, mname, &mat.mat) ) def getArray(self, matname: MatType) -> ArrayScalar: """ Return the array where the data is stored. Not collective. Parameters ---------- matname The selected matrix. Returns ------- ArrayScalar The array. See Also -------- slepc.DSGetArray """ cdef PetscInt m=0, n=0, lda=0, k=0, l=0 cdef PetscScalar *data = NULL CHKERR(DSMatGetSize(self.ds, matname, &m, &n)) CHKERR(DSGetLeadingDimension(self.ds, &lda)) CHKERR(DSGetArray(self.ds, matname, &data)) cdef int typenum = NPY_PETSC_SCALAR cdef int itemsize = sizeof(PetscScalar) cdef int flags = NPY_ARRAY_FARRAY cdef npy_intp dims[2], strides[2] dims[0] = m; strides[0] = sizeof(PetscScalar) dims[1] = n; strides[1] = (lda*sizeof(PetscScalar)) cdef ndarray array = PyArray_New(ndarray, 2, dims, typenum, strides, data, itemsize, flags, NULL) Py_INCREF(self) PyArray_SetBaseObject(array, self) CHKERR(DSRestoreArray(self.ds, matname, &data)) return array def setIdentity(self, matname: MatType) -> None: """ Set the identity on the active part of a matrix. Logically collective. Parameters ---------- matname The matrix to be changed. See Also -------- slepc.DSSetIdentity """ cdef SlepcDSMatType mname = matname CHKERR( DSSetIdentity(self.ds, mname) ) # def cond(self) -> float: """ Compute the inf-norm condition number of the first matrix. Logically collective. Returns ------- float Condition number. See Also -------- slepc.DSCond """ cdef PetscReal rval = 0 CHKERR( DSCond(self.ds, &rval) ) return toReal(rval) def solve(self) -> ArrayScalar: """ Solve the problem. Logically collective. Returns ------- ArrayScalar Eigenvalues or singular values. See Also -------- slepc.DSSolve """ n = self.getDimensions()[0] cdef PetscScalar *eigr = NULL cdef PetscScalar *eigi = NULL cdef tmpr = allocate(n*sizeof(PetscScalar), &eigr) cdef tmpi = allocate(n*sizeof(PetscScalar), &eigi) CHKERR( DSSolve(self.ds, eigr, eigi) ) cdef object kr = array_s(n, eigr) cdef object ki = array_s(n, eigi) if self.getType().upper() in ['HEP','GHEP','BSE','SVD','HSVD','GSVD']: return kr.real.copy() else: return kr+1j*ki def vectors(self, matname = MatType.X) -> None: """ Compute vectors associated to the dense system such as eigenvectors. Logically collective. Parameters ---------- matname The matrix, used to indicate which vectors are required. See Also -------- slepc.DSVectors """ cdef SlepcDSMatType mname = matname CHKERR( DSVectors(self.ds, mname, NULL, NULL) ) # def setSVDDimensions(self, m: int) -> None: """ Set the number of columns of a `DS` of type `SVD`. Logically collective. Parameters ---------- m The number of columns. Notes ----- This call is complementary to `setDimensions()`, to provide a dimension that is specific to this `DS.Type`. See Also -------- setDimensions, getSVDDimensions, slepc.DSSVDSetDimensions """ cdef PetscInt val = asInt(m) CHKERR( DSSVDSetDimensions(self.ds, val) ) def getSVDDimensions(self) -> int: """ Get the number of columns of a `DS` of type `SVD`. Not collective. Returns ------- int The number of columns. See Also -------- setSVDDimensions, slepc.DSSVDGetDimensions """ cdef PetscInt val = 0 CHKERR( DSSVDGetDimensions(self.ds, &val) ) return toInt(val) def setHSVDDimensions(self, m: int) -> None: """ Set the number of columns of a `DS` of type `HSVD`. Logically collective. Parameters ---------- m The number of columns. Notes ----- This call is complementary to `setDimensions()`, to provide a dimension that is specific to this `DS.Type`. See Also -------- setDimensions, getHSVDDimensions, slepc.DSHSVDSetDimensions """ cdef PetscInt val = asInt(m) CHKERR( DSHSVDSetDimensions(self.ds, val) ) def getHSVDDimensions(self) -> int: """ Get the number of columns of a `DS` of type `HSVD`. Not collective. Returns ------- int The number of columns. See Also -------- setHSVDDimensions, slepc.DSHSVDGetDimensions """ cdef PetscInt val = 0 CHKERR( DSHSVDGetDimensions(self.ds, &val) ) return toInt(val) def setGSVDDimensions(self, m: int, p: int) -> None: """ Set the number of columns and rows of a `DS` of type `GSVD`. Logically collective. Parameters ---------- m The number of columns. p The number of rows for the second matrix. Notes ----- This call is complementary to `setDimensions()`, to provide dimensions that are specific to this `DS.Type`. See Also -------- setDimensions, getGSVDDimensions, slepc.DSGSVDSetDimensions """ cdef PetscInt val1 = asInt(m) cdef PetscInt val2 = asInt(p) CHKERR( DSGSVDSetDimensions(self.ds, val1, val2) ) def getGSVDDimensions(self) -> tuple[int, int]: """ Get the number of columns and rows of a `DS` of type `GSVD`. Not collective. Returns ------- m: int The number of columns. p: int The number of rows for the second matrix. See Also -------- setGSVDDimensions, slepc.DSGSVDGetDimensions """ cdef PetscInt val1 = 0 cdef PetscInt val2 = 0 CHKERR( DSGSVDGetDimensions(self.ds, &val1, &val2) ) return (toInt(val1), toInt(val2)) def setPEPDegree(self, deg: int) -> None: """ Set the polynomial degree of a `DS` of type `PEP`. Logically collective. Parameters ---------- deg The polynomial degree. See Also -------- getPEPDegree, slepc.DSPEPSetDegree """ cdef PetscInt val = asInt(deg) CHKERR( DSPEPSetDegree(self.ds, val) ) def getPEPDegree(self) -> int: """ Get the polynomial degree of a `DS` of type `PEP`. Not collective. Returns ------- int The polynomial degree. See Also -------- setPEPDegree, slepc.DSPEPGetDegree """ cdef PetscInt val = 0 CHKERR( DSPEPGetDegree(self.ds, &val) ) return toInt(val) def setPEPCoefficients(self, pbc: Sequence[float]) -> None: """ Set the polynomial basis coefficients of a `DS` of type `PEP`. Logically collective. Parameters ---------- pbc Coefficients. Notes ----- This function is required only in the case of a polynomial specified in a non-monomial basis, to provide the coefficients that will be used during the linearization, multiplying the identity blocks on the three main diagonal blocks. Depending on the polynomial basis (Chebyshev, Legendre, ...) the coefficients must be different. There must be a total of :math:`3(d+1)` coefficients, where :math:`d` is the degree of the polynomial. The coefficients are arranged in three groups, :math:`a_i, b_i, c_i`, according to the definition of the three-term recurrence. In the case of the monomial basis, :math:`a_i=1` and :math:`b_i=c_i=0`, in which case it is not necessary to invoke this function. See Also -------- getPEPCoefficients, slepc.DSPEPSetCoefficients """ cdef PetscInt na = 0 cdef PetscReal *a = NULL cdef object tmp1 = iarray_r(pbc, &na, &a) CHKERR( DSPEPSetCoefficients(self.ds, a) ) def getPEPCoefficients(self) -> ArrayReal: """ Get the polynomial basis coefficients of a `DS` of type `PEP`. Not collective. Returns ------- ArrayReal Coefficients. See Also -------- setPEPCoefficients, slepc.DSPEPGetCoefficients """ cdef PetscInt np = 0 cdef PetscReal *coeff = NULL CHKERR( DSPEPGetDegree(self.ds, &np) ) CHKERR( DSPEPGetCoefficients(self.ds, &coeff) ) cdef object ocoeff = None try: ocoeff = array_r(3*(np+1), coeff) finally: CHKERR( PetscFree(coeff) ) return ocoeff # property state: """The state of the DS object.""" def __get__(self) -> DSStateType: return self.getState() def __set__(self, value): self.setState(value) property parallel: """The mode of operation in parallel runs.""" def __get__(self) -> DSParallelType: return self.getParallel() def __set__(self, value): self.setParallel(value) property block_size: """The block size.""" def __get__(self) -> int: return self.getBlockSize() def __set__(self, value): self.setBlockSize(value) property method: """The method to be used to solve the problem.""" def __get__(self) -> int: return self.getMethod() def __set__(self, value): self.setMethod(value) property compact: """Compact storage of matrices.""" def __get__(self) -> bool: return self.getCompact() def __set__(self, value): self.setCompact(value) property extra_row: """If the matrix has one extra row.""" def __get__(self) -> bool: return self.getExtraRow() def __set__(self, value): self.setExtraRow(value) property refined: """If refined vectors must be computed.""" def __get__(self) -> bool: return self.getRefined() def __set__(self, value): self.setRefined(value) # ----------------------------------------------------------------------------- del DSType del DSStateType del DSMatType del DSParallelType # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/EPS.pyx0000644000076500000240000037744615133663436017246 0ustar00jromanstaff# ----------------------------------------------------------------------------- class EPSType(object): """ EPS type. Native eigenvalue solvers. - `POWER`: Power Iteration, Inverse Iteration, RQI. - `SUBSPACE`: Subspace Iteration. - `ARNOLDI`: Arnoldi. - `LANCZOS`: Lanczos. - `KRYLOVSCHUR`: Krylov-Schur (default). - `GD`: Generalized Davidson. - `JD`: Jacobi-Davidson. - `RQCG`: Rayleigh Quotient Conjugate Gradient. - `LOBPCG`: Locally Optimal Block Preconditioned Conjugate Gradient. - `CISS`: Contour Integral Spectrum Slicing. - `LYAPII`: Lyapunov inverse iteration. Wrappers to external eigensolvers (should be enabled during installation of SLEPc). - `LAPACK`: Sequential dense eigensolver. - `ARPACK`: Iterative Krylov-based eigensolver. - `BLOPEX`: Implementation of LOBPCG. - `PRIMME`: Iterative eigensolvers of Davidson type. - `FEAST`: Contour integral eigensolver. - `SCALAPACK`: Parallel dense eigensolver for symmetric problems. - `ELPA`: Parallel dense eigensolver for symmetric problems. - `ELEMENTAL`: Parallel dense eigensolver for symmetric problems. - `EVSL`: Iterative eigensolver based on polynomial filters. - `CHASE`: Subspace iteration accelerated with polynomials. See Also -------- slepc.EPSType """ POWER = S_(EPSPOWER) SUBSPACE = S_(EPSSUBSPACE) ARNOLDI = S_(EPSARNOLDI) LANCZOS = S_(EPSLANCZOS) KRYLOVSCHUR = S_(EPSKRYLOVSCHUR) GD = S_(EPSGD) JD = S_(EPSJD) RQCG = S_(EPSRQCG) LOBPCG = S_(EPSLOBPCG) CISS = S_(EPSCISS) LYAPII = S_(EPSLYAPII) LAPACK = S_(EPSLAPACK) ARPACK = S_(EPSARPACK) BLOPEX = S_(EPSBLOPEX) PRIMME = S_(EPSPRIMME) FEAST = S_(EPSFEAST) SCALAPACK = S_(EPSSCALAPACK) ELPA = S_(EPSELPA) ELEMENTAL = S_(EPSELEMENTAL) EVSL = S_(EPSEVSL) CHASE = S_(EPSCHASE) class EPSProblemType(object): """ EPS problem type. - `HEP`: Hermitian eigenproblem. - `NHEP`: Non-Hermitian eigenproblem. - `GHEP`: Generalized Hermitian eigenproblem. - `GNHEP`: Generalized Non-Hermitian eigenproblem. - `PGNHEP`: Generalized Non-Hermitian eigenproblem with positive definite :math:`B`. - `GHIEP`: Generalized Hermitian-indefinite eigenproblem. - `BSE`: Structured Bethe-Salpeter eigenproblem. - `HAMILT`: Hamiltonian eigenproblem. See Also -------- slepc.EPSProblemType """ HEP = EPS_HEP NHEP = EPS_NHEP GHEP = EPS_GHEP GNHEP = EPS_GNHEP PGNHEP = EPS_PGNHEP GHIEP = EPS_GHIEP BSE = EPS_BSE HAMILT = EPS_HAMILT class EPSExtraction(object): """ EPS extraction technique. - `RITZ`: Standard Rayleigh-Ritz extraction. - `HARMONIC`: Harmonic extraction. - `HARMONIC_RELATIVE`: Harmonic extraction relative to the eigenvalue. - `HARMONIC_RIGHT`: Harmonic extraction for rightmost eigenvalues. - `HARMONIC_LARGEST`: Harmonic extraction for largest magnitude (without target). - `REFINED`: Refined extraction. - `REFINED_HARMONIC`: Refined harmonic extraction. See Also -------- slepc.EPSExtraction """ RITZ = EPS_RITZ HARMONIC = EPS_HARMONIC HARMONIC_RELATIVE = EPS_HARMONIC_RELATIVE HARMONIC_RIGHT = EPS_HARMONIC_RIGHT HARMONIC_LARGEST = EPS_HARMONIC_LARGEST REFINED = EPS_REFINED REFINED_HARMONIC = EPS_REFINED_HARMONIC class EPSBalance(object): """ EPS type of balancing used for non-Hermitian problems. - `NONE`: None. - `ONESIDE`: One-sided balancing. - `TWOSIDE`: Two-sided balancing. - `USER`: User-provided balancing matrices. See Also -------- slepc.EPSBalance """ NONE = EPS_BALANCE_NONE ONESIDE = EPS_BALANCE_ONESIDE TWOSIDE = EPS_BALANCE_TWOSIDE USER = EPS_BALANCE_USER class EPSErrorType(object): """ EPS error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.EPSErrorType """ ABSOLUTE = EPS_ERROR_ABSOLUTE RELATIVE = EPS_ERROR_RELATIVE BACKWARD = EPS_ERROR_BACKWARD class EPSWhich(object): """ EPS desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in an interval. - `USER`: User defined selection. See Also -------- slepc.EPSWhich """ LARGEST_MAGNITUDE = EPS_LARGEST_MAGNITUDE SMALLEST_MAGNITUDE = EPS_SMALLEST_MAGNITUDE LARGEST_REAL = EPS_LARGEST_REAL SMALLEST_REAL = EPS_SMALLEST_REAL LARGEST_IMAGINARY = EPS_LARGEST_IMAGINARY SMALLEST_IMAGINARY = EPS_SMALLEST_IMAGINARY TARGET_MAGNITUDE = EPS_TARGET_MAGNITUDE TARGET_REAL = EPS_TARGET_REAL TARGET_IMAGINARY = EPS_TARGET_IMAGINARY ALL = EPS_ALL USER = EPS_WHICH_USER class EPSConv(object): """ EPS convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.EPSConv """ ABS = EPS_CONV_ABS REL = EPS_CONV_REL NORM = EPS_CONV_NORM USER = EPS_CONV_USER class EPSStop(object): """ EPS stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. - `THRESHOLD`: Threshold stopping test. See Also -------- slepc.EPSStop """ BASIC = EPS_STOP_BASIC USER = EPS_STOP_USER THRESHOLD = EPS_STOP_THRESHOLD class EPSConvergedReason(object): """ EPS convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Lanczos-type method could not preserve symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.EPSConvergedReason """ CONVERGED_TOL = EPS_CONVERGED_TOL CONVERGED_USER = EPS_CONVERGED_USER DIVERGED_ITS = EPS_DIVERGED_ITS DIVERGED_BREAKDOWN = EPS_DIVERGED_BREAKDOWN DIVERGED_SYMMETRY_LOST = EPS_DIVERGED_SYMMETRY_LOST CONVERGED_ITERATING = EPS_CONVERGED_ITERATING ITERATING = EPS_CONVERGED_ITERATING class EPSPowerShiftType(object): """ EPS Power shift type. - `CONSTANT`: Constant shift. - `RAYLEIGH`: Rayleigh quotient. - `WILKINSON`: Wilkinson shift. See Also -------- slepc.EPSPowerShiftType """ CONSTANT = EPS_POWER_SHIFT_CONSTANT RAYLEIGH = EPS_POWER_SHIFT_RAYLEIGH WILKINSON = EPS_POWER_SHIFT_WILKINSON class EPSKrylovSchurBSEType(object): """ EPS Krylov-Schur method for BSE problems. - `SHAO`: Lanczos recurrence for H square. - `GRUNING`: Lanczos recurrence for H. - `PROJECTEDBSE`: Lanczos where the projected problem has BSE structure. See Also -------- slepc.EPSKrylovSchurBSEType """ SHAO = EPS_KRYLOVSCHUR_BSE_SHAO GRUNING = EPS_KRYLOVSCHUR_BSE_GRUNING PROJECTEDBSE = EPS_KRYLOVSCHUR_BSE_PROJECTEDBSE class EPSLanczosReorthogType(object): """ EPS Lanczos reorthogonalization type. - `LOCAL`: Local reorthogonalization only. - `FULL`: Full reorthogonalization. - `SELECTIVE`: Selective reorthogonalization. - `PERIODIC`: Periodic reorthogonalization. - `PARTIAL`: Partial reorthogonalization. - `DELAYED`: Delayed reorthogonalization. See Also -------- slepc.EPSLanczosReorthogType """ LOCAL = EPS_LANCZOS_REORTHOG_LOCAL FULL = EPS_LANCZOS_REORTHOG_FULL SELECTIVE = EPS_LANCZOS_REORTHOG_SELECTIVE PERIODIC = EPS_LANCZOS_REORTHOG_PERIODIC PARTIAL = EPS_LANCZOS_REORTHOG_PARTIAL DELAYED = EPS_LANCZOS_REORTHOG_DELAYED class EPSCISSQuadRule(object): """ EPS CISS quadrature rule. - `TRAPEZOIDAL`: Trapezoidal rule. - `CHEBYSHEV`: Chebyshev points. See Also -------- slepc.EPSCISSQuadRule """ TRAPEZOIDAL = EPS_CISS_QUADRULE_TRAPEZOIDAL CHEBYSHEV = EPS_CISS_QUADRULE_CHEBYSHEV class EPSCISSExtraction(object): """ EPS CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. See Also -------- slepc.EPSCISSExtraction """ RITZ = EPS_CISS_EXTRACTION_RITZ HANKEL = EPS_CISS_EXTRACTION_HANKEL # ----------------------------------------------------------------------------- cdef class EPS(Object): """ Eigenvalue Problem Solver. The Eigenvalue Problem Solver (`EPS`) is the object provided by slepc4py for specifying a linear eigenvalue problem, either in standard or generalized form. It provides uniform and efficient access to all of the linear eigensolvers included in the package. """ Type = EPSType ProblemType = EPSProblemType Extraction = EPSExtraction Balance = EPSBalance ErrorType = EPSErrorType Which = EPSWhich Conv = EPSConv Stop = EPSStop ConvergedReason = EPSConvergedReason PowerShiftType = EPSPowerShiftType KrylovSchurBSEType = EPSKrylovSchurBSEType LanczosReorthogType = EPSLanczosReorthogType CISSQuadRule = EPSCISSQuadRule CISSExtraction = EPSCISSExtraction def __cinit__(self): self.obj = &self.eps self.eps = NULL def view(self, Viewer viewer=None) -> None: """ Print the EPS data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.EPSView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSView(self.eps, vwr) ) def destroy(self) -> Self: """ Destroy the EPS object. Collective. See Also -------- slepc.EPSDestroy """ CHKERR( EPSDestroy(&self.eps) ) self.eps = NULL return self def reset(self) -> None: """ Reset the EPS object. Collective. See Also -------- slepc.EPSReset """ CHKERR( EPSReset(self.eps) ) def create(self, comm: Comm | None = None) -> Self: """ Create the EPS object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.EPSCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcEPS neweps = NULL CHKERR( EPSCreate(ccomm, &neweps) ) CHKERR( SlepcCLEAR(self.obj) ); self.eps = neweps return self def setType(self, eps_type: Type | str) -> None: """ Set the particular solver to be used in the EPS object. Logically collective. Parameters ---------- eps_type The solver to be used. Notes ----- The default is `KRYLOVSCHUR`. Normally, it is best to use `setFromOptions()` and then set the EPS type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.EPSSetType """ cdef SlepcEPSType cval = NULL eps_type = str2bytes(eps_type, &cval) CHKERR( EPSSetType(self.eps, cval) ) def getType(self) -> str: """ Get the EPS type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.EPSGetType """ cdef SlepcEPSType eps_type = NULL CHKERR( EPSGetType(self.eps, &eps_type) ) return bytes2str(eps_type) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all EPS options in the database. Not collective. Returns ------- str The prefix string set for this EPS object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.EPSGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( EPSGetOptionsPrefix(self.eps, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all EPS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all EPS option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different EPS contexts, one could call:: E1.setOptionsPrefix("eig1_") E2.setOptionsPrefix("eig2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.EPSGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( EPSSetOptionsPrefix(self.eps, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all EPS options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all EPS option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.EPSAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( EPSAppendOptionsPrefix(self.eps, cval) ) def setFromOptions(self) -> None: """ Set EPS options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.EPSSetFromOptions """ CHKERR( EPSSetFromOptions(self.eps) ) # def getProblemType(self) -> ProblemType: """ Get the problem type from the EPS object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.EPSGetProblemType """ cdef SlepcEPSProblemType val = EPS_NHEP CHKERR( EPSGetProblemType(self.eps, &val) ) return val def setProblemType(self, problem_type: ProblemType) -> None: """ Set the type of the eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function must be used to instruct SLEPc to exploit symmetry or other kind of structure. If no problem type is specified, by default a non-Hermitian problem is assumed (either standard or generalized). If the user knows that the problem is Hermitian (i.e., :math:`A=A^*`) or generalized Hermitian (i.e., :math:`A=A^*`, :math:`B=B^*`, and :math:`B` positive definite) then it is recommended to set the problem type so that eigensolver can exploit these properties. If the user does not call this function, the solver will use a reasonable guess. For structured problem types such as `BSE`, the matrices passed in via `setOperators()` must have been created with the corresponding helper function, i.e., `createMatBSE()`. See Also -------- setOperators, createMatBSE, getProblemType, slepc.EPSSetProblemType """ cdef SlepcEPSProblemType val = problem_type CHKERR( EPSSetProblemType(self.eps, val) ) def isGeneralized(self) -> bool: """ Tell if the EPS object corresponds to a generalized eigenproblem. Not collective. Returns ------- bool ``True`` if the problem is generalized. See Also -------- isHermitian, isPositive, isStructured, slepc.EPSIsGeneralized """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsGeneralized(self.eps, &tval) ) return toBool(tval) def isHermitian(self) -> bool: """ Tell if the EPS object corresponds to a Hermitian eigenproblem. Not collective. Returns ------- bool ``True`` if the problem is Hermitian. See Also -------- isGeneralized, isPositive, isStructured, slepc.EPSIsHermitian """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsHermitian(self.eps, &tval) ) return toBool(tval) def isPositive(self) -> bool: """ Eigenproblem requiring a positive (semi-) definite matrix :math:`B`. Not collective. Tell if the EPS corresponds to an eigenproblem requiring a positive (semi-) definite matrix :math:`B`. Returns ------- bool ``True`` if the problem is positive (semi-) definite. See Also -------- isGeneralized, isHermitian, isStructured, slepc.EPSIsPositive """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsPositive(self.eps, &tval) ) return toBool(tval) def isStructured(self) -> bool: """ Tell if the EPS object corresponds to a structured eigenvalue problem. Not collective. Returns ------- bool ``True`` if the problem is structured. Notes ----- The result will be ``True`` if the problem type has been set to some structured type such as `BSE`. This is independent of whether the input matrix has been built with a certain structure with a helper function. See Also -------- isGeneralized, isHermitian, isPositive, slepc.EPSIsStructured """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsStructured(self.eps, &tval) ) return toBool(tval) def getBalance(self) -> tuple[Balance, int, float]: """ Get the balancing type used by the EPS, and the associated parameters. Not collective. Returns ------- balance: Balance The balancing method. iterations: int Number of iterations of the balancing algorithm. cutoff: float Cutoff value. See Also -------- setBalance, slepc.EPSGetBalance """ cdef SlepcEPSBalance val = EPS_BALANCE_ONESIDE cdef PetscInt ival = 0 cdef PetscReal rval = 0 CHKERR( EPSGetBalance(self.eps, &val, &ival, &rval) ) return (val, toInt(ival), toReal(rval)) def setBalance( self, balance: Balance | None = None, iterations: int | None = None, cutoff: float | None = None, ) -> None: """ Set the balancing technique to be used by the eigensolver. Logically collective. Parameters ---------- balance The balancing method. iterations Number of iterations of the balancing algorithm. cutoff Cutoff value. Notes ----- When balancing is enabled, the solver works implicitly with matrix :math:`DAD^{-1}`, where :math:`D` is an appropriate diagonal matrix. This improves the accuracy of the computed results in some cases. Balancing makes sense only for non-Hermitian problems when the required precision is high (i.e., with a small tolerance). By default, balancing is disabled. The two-sided method is much more effective than the one-sided counterpart, but it requires the system matrices to have the ``Mat.multTranspose()`` operation defined. The parameter ``iterations`` is the number of iterations performed by the method. The ``cutoff`` value is used only in the two-side variant. See Also -------- setBalance, slepc.EPSGetBalance """ cdef SlepcEPSBalance val = EPS_BALANCE_NONE cdef PetscInt ival = PETSC_CURRENT cdef PetscReal rval = PETSC_CURRENT if balance is not None: val = balance else: CHKERR( EPSGetBalance(self.eps, &val, NULL, NULL) ) if iterations is not None: ival = asInt(iterations) if cutoff is not None: rval = asReal(cutoff) CHKERR( EPSSetBalance(self.eps, val, ival, rval) ) def getExtraction(self) -> Extraction: """ Get the extraction type used by the EPS object. Not collective. Returns ------- Extraction The method of extraction. See Also -------- setExtraction, slepc.EPSGetExtraction """ cdef SlepcEPSExtraction val = EPS_RITZ CHKERR( EPSGetExtraction(self.eps, &val) ) return val def setExtraction(self, extraction: Extraction) -> None: """ Set the extraction type used by the eigensolver. Logically collective. Parameters ---------- extraction The extraction method to be used by the solver. Notes ----- Not all eigensolvers support all types of extraction. By default, a standard Rayleigh-Ritz extraction is used. Other extractions may be useful when computing interior eigenvalues. Harmonic-type extractions are used in combination with a *target*, see `setTarget()`. See Also -------- getExtraction, setTarget, slepc.EPSSetExtraction """ cdef SlepcEPSExtraction val = extraction CHKERR( EPSSetExtraction(self.eps, val) ) def getWhichEigenpairs(self) -> Which: """ Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.EPSGetWhichEigenpairs """ cdef SlepcEPSWhich val = EPS_LARGEST_MAGNITUDE CHKERR( EPSGetWhichEigenpairs(self.eps, &val) ) return val def setWhichEigenpairs(self, which: Which) -> None: """ Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in EPS account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `EPS.Which.LARGEST_IMAGINARY` and `EPS.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `EPS.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `EPS.Which.ALL` is intended for use in combination with an interval (see `setInterval()`), when all eigenvalues within the interval are requested, or in the context of the `EPS.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- setTarget, setInterval, getWhichEigenpairs, slepc.EPSSetWhichEigenpairs """ cdef SlepcEPSWhich val = which CHKERR( EPSSetWhichEigenpairs(self.eps, val) ) def getThreshold(self) -> tuple[float, bool]: """ Get the threshold used in the threshold stopping test. Not collective. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. See Also -------- setThreshold, slepc.EPSGetThreshold """ cdef PetscReal rval = 0 cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetThreshold(self.eps, &rval, &tval) ) return (toReal(rval), toBool(tval)) def setThreshold(self, thres: float, rel: bool = False) -> None: """ Set the threshold used in the threshold stopping test. Logically collective. Parameters ---------- thres The threshold. rel Whether the threshold is relative or not. Notes ----- This function internally sets a special stopping test based on the threshold, where eigenvalues are computed in sequence until one of the computed eigenvalues is below/above the threshold (depending on whether largest or smallest eigenvalues are computed). The details are given in `slepc.EPSSetThreshold`. See Also -------- setStoppingTest, getThreshold, slepc.EPSSetThreshold """ cdef PetscReal rval = asReal(thres) cdef PetscBool tval = asBool(rel) CHKERR( EPSSetThreshold(self.eps, rval, tval) ) def getTarget(self) -> Scalar: """ Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.EPSGetTarget """ cdef PetscScalar sval = 0 CHKERR( EPSGetTarget(self.eps, &sval) ) return toScalar(sval) def setTarget(self, target: Scalar) -> None: """ Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, slepc.EPSSetTarget """ cdef PetscScalar sval = asScalar(target) CHKERR( EPSSetTarget(self.eps, sval) ) def getInterval(self) -> tuple[float, float]: """ Get the computational interval for spectrum slicing. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. Notes ----- If the interval was not set by the user, then zeros are returned. See Also -------- setInterval, slepc.EPSGetInterval """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( EPSGetInterval(self.eps, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setInterval(self, inta: float, intb: float) -> None: """ Set the computational interval for spectrum slicing. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- Spectrum slicing is a technique employed for computing all eigenvalues of symmetric eigenproblems in a given interval. This function provides the interval to be considered. It must be used in combination with `EPS.Which.ALL`, see `setWhichEigenpairs()`. A computational interval is also needed when using polynomial filters, see `slepc.STFILTER`. See Also -------- getInterval, setWhichEigenpairs, slepc.EPSSetInterval, slepc.STFILTER """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( EPSSetInterval(self.eps, rval1, rval2) ) # def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and max. iter. count used for convergence tests. Not collective. Get the tolerance and iteration limit used by the default EPS convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.EPSGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( EPSGetTolerances(self.eps, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """ Set the tolerance and max. iter. used by the default EPS convergence tests. Logically collective. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.EPSSetTolerances """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if max_it is not None: ival = asInt(max_it) CHKERR( EPSSetTolerances(self.eps, rval, ival) ) def getTwoSided(self) -> bool: """ Get the flag indicating if a two-sided variant of the algorithm is being used. Not collective. Returns ------- bool Whether the two-sided variant is to be used or not. See Also -------- setTwoSided, slepc.EPSGetTwoSided """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTwoSided(self.eps, &tval) ) return toBool(tval) def setTwoSided(self, twosided: bool) -> None: """ Set to use a two-sided variant that also computes left eigenvectors. Logically collective. Parameters ---------- twosided Whether the two-sided variant is to be used or not. Notes ----- If the user sets ``twosided`` to ``True`` then the solver uses a variant of the algorithm that computes both right and left eigenvectors. This is usually much more costly. This option is not available in all solvers. When using two-sided solvers, the problem matrices must have both the ``Mat.mult`` and ``Mat.multTranspose`` operations defined. See Also -------- getTwoSided, getLeftEigenvector, slepc.EPSSetTwoSided """ cdef PetscBool tval = asBool(twosided) CHKERR( EPSSetTwoSided(self.eps, tval) ) def getPurify(self) -> bool: """ Get the flag indicating whether purification is activated or not. Not collective. Returns ------- bool Whether purification is activated or not. See Also -------- setPurify, slepc.EPSGetPurify """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetPurify(self.eps, &tval) ) return toBool(tval) def setPurify(self, purify: bool = True) -> None: """ Set (toggle) eigenvector purification. Logically collective. Parameters ---------- purify ``True`` to activate purification (default). Notes ----- By default, eigenvectors of generalized symmetric eigenproblems are purified in order to purge directions in the nullspace of matrix :math:`B`. If the user knows that :math:`B` is non-singular, then purification can be safely deactivated and some computational cost is avoided (this is particularly important in interval computations). See Also -------- getPurify, setInterval, slepc.EPSSetPurify """ cdef PetscBool tval = asBool(purify) CHKERR( EPSSetPurify(self.eps, tval) ) def getConvergenceTest(self) -> Conv: """ Get how to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.EPSGetConvergenceTest """ cdef SlepcEPSConv conv = EPS_CONV_REL CHKERR( EPSGetConvergenceTest(self.eps, &conv) ) return conv def setConvergenceTest(self, conv: Conv) -> None: """ Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.EPSSetConvergenceTest """ cdef SlepcEPSConv tconv = conv CHKERR( EPSSetConvergenceTest(self.eps, tconv) ) def getTrueResidual(self) -> bool: """ Get the flag indicating if true residual must be computed explicitly. Not collective. Returns ------- bool Whether the solver computes true residuals or not. See Also -------- setTrueResidual, slepc.EPSGetTrueResidual """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTrueResidual(self.eps, &tval) ) return toBool(tval) def setTrueResidual(self, trueres: bool) -> None: """ Set if the solver must compute the true residual explicitly or not. Logically collective. Parameters ---------- trueres Whether the solver computes true residuals or not. See Also -------- getTrueResidual, slepc.EPSSetTrueResidual """ cdef PetscBool tval = asBool(trueres) CHKERR( EPSSetTrueResidual(self.eps, tval) ) def getTrackAll(self) -> bool: """ Get the flag indicating if all residual norms must be computed or not. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.EPSGetTrackAll """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTrackAll(self.eps, &tval) ) return toBool(tval) def setTrackAll(self, trackall: bool) -> None: """ Set if the solver must compute the residual of all approximate eigenpairs. Logically collective. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.EPSSetTrackAll """ cdef PetscBool tval = asBool(trackall) CHKERR( EPSSetTrackAll(self.eps, tval) ) def getDimensions(self) -> tuple[int, int, int]: """ Get number of eigenvalues to compute and the dimension of the subspace. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.EPSGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( EPSGetDimensions(self.eps, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def setDimensions( self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set number of eigenvalues to compute and the dimension of the subspace. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. When computing all eigenvalues in an interval, see `setInterval()`, these parameters lose relevance, and tuning must be done with `setKrylovSchurDimensions()`. See Also -------- getDimensions, setKrylovSchurDimensions, slepc.EPSSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nev is not None: ival1 = asInt(nev) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( EPSSetDimensions(self.eps, ival1, ival2, ival3) ) def getST(self) -> ST: """ Get the spectral transformation object associated to the eigensolver. Not collective. Returns ------- ST The spectral transformation. See Also -------- setST, slepc.EPSGetST """ cdef ST st = ST() CHKERR( EPSGetST(self.eps, &st.st) ) CHKERR( PetscINCREF(st.obj) ) return st def setST(self, ST st) -> None: """ Set a spectral transformation object associated to the eigensolver. Collective. Parameters ---------- st The spectral transformation. See Also -------- getST, slepc.EPSSetST """ CHKERR( EPSSetST(self.eps, st.st) ) def getBV(self) -> BV: """ Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.EPSGetBV """ cdef BV bv = BV() CHKERR( EPSGetBV(self.eps, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv) -> None: """ Set a basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.EPSSetBV """ CHKERR( EPSSetBV(self.eps, bv.bv) ) def getDS(self) -> DS: """ Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.EPSGetDS """ cdef DS ds = DS() CHKERR( EPSGetDS(self.eps, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds) -> None: """ Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.EPSSetDS """ CHKERR( EPSSetDS(self.eps, ds.ds) ) def getRG(self) -> RG: """ Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.EPSGetRG """ cdef RG rg = RG() CHKERR( EPSGetRG(self.eps, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg) -> None: """ Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.EPSSetRG """ CHKERR( EPSSetRG(self.eps, rg.rg) ) def getOperators(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """ Get the matrices associated with the eigenvalue problem. Collective. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the eigensystem. B: petsc4py.PETSc.Mat The second matrix in the case of generalized eigenproblems. See Also -------- setOperators, slepc.EPSGetOperators """ cdef Mat A = Mat() cdef Mat B = Mat() CHKERR( EPSGetOperators(self.eps, &A.mat, &B.mat) ) CHKERR( PetscINCREF(A.obj) ) if B.mat: CHKERR( PetscINCREF(B.obj) ) return (A, B) else: return (A, None) def setOperators(self, Mat A, Mat B=None) -> None: """ Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- A The matrix associated with the eigensystem. B The second matrix in the case of generalized eigenproblems; if not provided, a standard eigenproblem is assumed. Notes ----- It must be called before `setUp()`. If it is called again after `setUp()` and the matrix sizes have changed then the `EPS` object is reset. For structured eigenproblem types such as `BSE`, see `setProblemType()`, the provided matrices must have been created with the corresponding helper function, i.e., `createMatBSE()`. See Also -------- getOperators, solve, setUp, reset, setProblemType, slepc.EPSSetOperators """ cdef PetscMat Bmat = B.mat if B is not None else NULL CHKERR( EPSSetOperators(self.eps, A.mat, Bmat) ) def setDeflationSpace(self, space: Vec | list[Vec]) -> None: """ Set vectors to form a basis of the deflation space. Collective. Parameters ---------- space Set of basis vectors of the deflation space. Notes ----- When a deflation space is given, the eigensolver seeks the eigensolution in the restriction of the problem to the orthogonal complement of this space. This can be used for instance in the case that an invariant subspace is known beforehand (such as the nullspace of the matrix). These vectors do not persist from one `solve()` call to the other, so the deflation space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. See Also -------- setInitialSpace, slepc.EPSSetDeflationSpace """ if isinstance(space, Vec): space = [space] cdef PetscVec* vs = NULL cdef Py_ssize_t i = 0, ns = len(space) cdef tmp = allocate(ns*sizeof(PetscVec),&vs) for i in range(ns): vs[i] = (space[i]).vec CHKERR( EPSSetDeflationSpace(self.eps, ns, vs) ) # def setInitialSpace(self, space: Vec | list[Vec]) -> None: """ Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space Set of basis vectors of the initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. But other solvers such as `SUBSPACE` are able to make use of the whole initial subspace as an initial guess. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setDeflationSpace, setLeftInitialSpace, slepc.EPSSetInitialSpace """ if isinstance(space, Vec): space = [space] cdef PetscVec *vs = NULL cdef Py_ssize_t i = 0, ns = len(space) cdef tmp = allocate(ns*sizeof(PetscVec),&vs) for i in range(ns): vs[i] = (space[i]).vec CHKERR( EPSSetInitialSpace(self.eps, ns, vs) ) def setLeftInitialSpace(self, space: Vec | list[Vec]) -> None: """ Set a left initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space Set of basis vectors of the left initial space. Notes ----- Left initial vectors are used to initiate the left search space in two-sided eigensolvers. Users should pass here an approximation of the left eigenspace, if available. The same comments in `setInitialSpace()` are applicable here. See Also -------- setInitialSpace, setTwoSided, slepc.EPSSetLeftInitialSpace """ if isinstance(space, Vec): space = [space] cdef PetscVec *vs = NULL cdef Py_ssize_t i = 0, ns = len(space) cdef tmp = allocate(ns*sizeof(PetscVec),&vs) for i in range(ns): vs[i] = (space[i]).vec CHKERR( EPSSetLeftInitialSpace(self.eps, ns, vs) ) # def setStoppingTest( self, stopping: EPSStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.EPSSetStoppingTestFunction """ if stopping is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__stopping__', (stopping, args, kargs)) CHKERR( EPSSetStoppingTestFunction(self.eps, EPS_Stopping, NULL, NULL) ) else: self.set_attr('__stopping__', None) CHKERR( EPSSetStoppingTestFunction(self.eps, EPSStoppingBasic, NULL, NULL) ) def getStoppingTest(self) -> EPSStoppingFunction: """ Get the stopping test function. Not collective. Returns ------- EPSStoppingFunction The stopping test function. See Also -------- setStoppingTest """ return self.get_attr('__stopping__') def setArbitrarySelection( self, arbitrary: EPSArbitraryFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set an arbitrary selection criterion function. Logically collective. Set a function to look for eigenvalues according to an arbitrary selection criterion. This criterion can be based on a computation involving the current eigenvector approximation. See Also -------- getArbitrarySelection, slepc.EPSSetArbitrarySelection """ if arbitrary is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__arbitrary__', (arbitrary, args, kargs)) ctx = self.get_attr('__arbitrary__') CHKERR( EPSSetArbitrarySelection(self.eps, EPS_Arbitrary, ctx) ) else: self.set_attr('__arbitrary__', None) CHKERR( EPSSetArbitrarySelection(self.eps, NULL, NULL) ) def getArbitrarySelection(self) -> EPSArbitraryFunction: """ Get the arbitrary selection function. Not collective. Returns ------- EPSArbitraryFunction The arbitrary selection function. See Also -------- setArbitrarySelection """ return self.get_attr('__arbitrary__') def setEigenvalueComparison( self, comparison: EPSEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `EPS.Which.USER`. See Also -------- getEigenvalueComparison, slepc.EPSSetEigenvalueComparison """ if comparison is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__comparison__', (comparison, args, kargs)) ctx = self.get_attr('__comparison__') CHKERR( EPSSetEigenvalueComparison(self.eps, EPS_Comparison, ctx) ) else: self.set_attr('__comparison__', None) CHKERR( EPSSetEigenvalueComparison(self.eps, NULL, NULL) ) def getEigenvalueComparison(self) -> EPSEigenvalueComparison: """ Get the eigenvalue comparison function. Not collective. Returns ------- EPSEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison """ return self.get_attr('__comparison__') def setMonitor( self, monitor: EPSMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.EPSMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( EPSMonitorSet(self.eps, EPS_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> EPSMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- EPSMonitorFunction The list of monitor functions. See Also -------- setMonitor """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for an `EPS` object. Logically collective. See Also -------- slepc.EPSMonitorCancel """ CHKERR( EPSMonitorCancel(self.eps) ) self.set_attr('__monitor__', None) # def setUp(self) -> None: """ Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This includes the setup of the internal `ST` object. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, setInitialSpace, setDeflationSpace, slepc.EPSSetUp """ CHKERR( EPSSetUp(self.eps) ) def solve(self) -> None: """ Solve the eigensystem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.EPSSolve """ CHKERR( EPSSolve(self.eps) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.EPSGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( EPSGetIterationNumber(self.eps, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.EPSGetConvergedReason """ cdef SlepcEPSConvergedReason val = EPS_CONVERGED_ITERATING CHKERR( EPSGetConvergedReason(self.eps, &val) ) return val def getConverged(self) -> int: """ Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.EPSGetConverged """ cdef PetscInt ival = 0 CHKERR( EPSGetConverged(self.eps, &ival) ) return toInt(ival) def getEigenvalue(self, i: int) -> Scalar: """ Get the i-th eigenvalue as computed by `solve()`. Not collective. Parameters ---------- i Index of the solution to be obtained. Returns ------- Scalar The computed eigenvalue. It will be a real variable in case of a Hermitian or generalized Hermitian eigenproblem. Otherwise it will be a complex variable (possibly with zero imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetEigenvalue """ cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 0 cdef SlepcEPSProblemType ptype CHKERR( EPSGetEigenvalue(self.eps, i, &sval1, &sval2) ) CHKERR( EPSGetProblemType(self.eps, &ptype) ) if ptype == EPS_HEP or ptype == EPS_GHEP or ptype == EPS_BSE: return toReal(PetscRealPart(sval1)) else: return toComplex(sval1, sval2) def getEigenvector(self, i: int, Vec Vr = None, Vec Vi = None) -> None: """ Get the i-th right eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The 2-norm of the eigenvector is one unless the problem is generalized Hermitian. In this case the eigenvector is normalized with respect to the norm defined by the B matrix. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetEigenvector """ cdef PetscVec vecr = Vr.vec if Vr is not None else NULL cdef PetscVec veci = Vi.vec if Vi is not None else NULL CHKERR( EPSGetEigenvector(self.eps, i, vecr, veci) ) def getLeftEigenvector(self, i: int, Vec Wr = None, Vec Wi = None) -> None: """ Get the i-th left eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Wr Placeholder for the returned left eigenvector (real part). Wi Placeholder for the returned left eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigensolutions are indexed according to the ordering criterion established with `setWhichEigenpairs()`. Left eigenvectors are available only if the twosided flag was set with `setTwoSided()`. See Also -------- getConverged, setWhichEigenpairs, getEigenpair, slepc.EPSGetLeftEigenvector """ cdef PetscVec vecr = Wr.vec if Wr is not None else NULL cdef PetscVec veci = Wi.vec if Wi is not None else NULL CHKERR( EPSGetLeftEigenvector(self.eps, i, vecr, veci) ) def getEigenpair(self, i: int, Vec Vr = None, Vec Vi = None) -> Scalar: """ Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- e: Scalar The computed eigenvalue. It will be a real variable in case of a Hermitian or generalized Hermitian eigenproblem. Otherwise it will be a complex variable (possibly with zero imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The 2-norm of the eigenvector is one unless the problem is generalized Hermitian. In this case the eigenvector is normalized with respect to the norm defined by the B matrix. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.EPSGetEigenpair """ cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 0 cdef PetscVec vecr = Vr.vec if Vr is not None else NULL cdef PetscVec veci = Vi.vec if Vi is not None else NULL cdef SlepcEPSProblemType ptype CHKERR( EPSGetEigenpair(self.eps, i, &sval1, &sval2, vecr, veci) ) CHKERR( EPSGetProblemType(self.eps, &ptype) ) if ptype == EPS_HEP or ptype == EPS_GHEP or ptype == EPS_BSE: return toReal(PetscRealPart(sval1)) else: return toComplex(sval1, sval2) def getInvariantSubspace(self) -> list[Vec]: """ Get an orthonormal basis of the computed invariant subspace. Collective. Returns ------- list of petsc4py.PETSc.Vec Basis of the invariant subspace. Notes ----- This function should be called after `solve()` has finished. The returned vectors span an invariant subspace associated with the computed eigenvalues. An invariant subspace :math:`X` of :math:`A` satisfies :math:`A x \in X`, for all :math:`x \in X` (a similar definition applies for generalized eigenproblems). See Also -------- getEigenpair, getConverged, solve, slepc.EPSGetInvariantSubspace """ cdef PetscInt i = 0, ncv = 0 cdef PetscVec v = NULL, *isp = NULL cdef list subspace = [] CHKERR( EPSGetConverged(self.eps, &ncv) ) if ncv == 0: return subspace cdef PetscMat A = NULL CHKERR( EPSGetOperators(self.eps, &A, NULL) ) CHKERR( MatCreateVecs(A, &v, NULL) ) cdef Vec V = None cdef object tmp = allocate(ncv*sizeof(PetscVec),&isp) for i in range(ncv): if i == 0: isp[0] = v if i >= 1: CHKERR( VecDuplicate(v, &isp[i]) ) V = Vec(); V.vec = isp[i]; subspace.append(V) CHKERR( EPSGetInvariantSubspace(self.eps, isp) ) return subspace # def getErrorEstimate(self, i: int) -> float: """ Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.EPSGetErrorEstimate """ cdef PetscReal rval = 0 CHKERR( EPSGetErrorEstimate(self.eps, i, &rval) ) return toReal(rval) def computeError(self, i: int, etype: ErrorType | None = None) -> float: """ Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|Ax-\lambda Bx\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). If the computation of left eigenvectors was enabled with `setTwoSided()`, then the error will be computed using the maximum of the value above and the left residual norm :math:`\|y^*A-\lambda y^*B\|_2`, where :math:`y` is the approximate left eigenvector. See Also -------- getErrorEstimate, setTwoSided, slepc.EPSComputeError """ cdef SlepcEPSErrorType et = EPS_ERROR_RELATIVE cdef PetscReal rval = 0 if etype is not None: et = etype CHKERR( EPSComputeError(self.eps, i, et, &rval) ) return toReal(rval) def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """ Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.EPSErrorView """ cdef SlepcEPSErrorType et = EPS_ERROR_RELATIVE if etype is not None: et = etype cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSErrorView(self.eps, et, vwr) ) def valuesView(self, viewer: Viewer | None = None) -> None: """ Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.EPSValuesView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSValuesView(self.eps, vwr) ) def vectorsView(self, viewer: Viewer | None = None) -> None: """ Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.EPSVectorsView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSVectorsView(self.eps, vwr) ) # def setPowerShiftType(self, shift: PowerShiftType) -> None: """ Set the type of shifts used during the power iteration. Logically collective. This can be used to emulate the Rayleigh Quotient Iteration (RQI) method. Parameters ---------- shift The type of shift. Notes ----- This call is only relevant if the type was set to `EPS.Type.POWER` with `setType()`. By default, shifts are constant (`EPS.PowerShiftType.CONSTANT`) and the iteration is the simple power method (or inverse iteration if a shift-and-invert transformation is being used). A variable shift can be specified (`EPS.PowerShiftType.RAYLEIGH` or `EPS.PowerShiftType.WILKINSON`). In this case, the iteration behaves rather like a cubic converging method as RQI. See Also -------- getPowerShiftType, slepc.EPSPowerSetShiftType """ cdef SlepcEPSPowerShiftType val = shift CHKERR( EPSPowerSetShiftType(self.eps, val) ) def getPowerShiftType(self) -> PowerShiftType: """ Get the type of shifts used during the power iteration. Not collective. Returns ------- PowerShiftType The type of shift. See Also -------- setPowerShiftType, slepc.EPSPowerGetShiftType """ cdef SlepcEPSPowerShiftType val = EPS_POWER_SHIFT_CONSTANT CHKERR( EPSPowerGetShiftType(self.eps, &val) ) return val def setArnoldiDelayed(self, delayed: bool) -> None: """ Set (toggle) delayed reorthogonalization in the Arnoldi iteration. Logically collective. Parameters ---------- delayed ``True`` if delayed reorthogonalization is to be used. Notes ----- This call is only relevant if the type was set to `EPS.Type.ARNOLDI` with `setType()`. Delayed reorthogonalization is an aggressive optimization for the Arnoldi eigensolver than may provide better scalability, but sometimes makes the solver converge more slowly compared to the default algorithm. See Also -------- getArnoldiDelayed, slepc.EPSArnoldiSetDelayed """ cdef PetscBool val = asBool(delayed) CHKERR( EPSArnoldiSetDelayed(self.eps, val) ) def getArnoldiDelayed(self) -> bool: """ Get the type of reorthogonalization used during the Arnoldi iteration. Not collective. Returns ------- bool ``True`` if delayed reorthogonalization is to be used. See Also -------- setArnoldiDelayed, slepc.EPSArnoldiGetDelayed """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSArnoldiGetDelayed(self.eps, &tval) ) return toBool(tval) def setLanczosReorthogType(self, reorthog: LanczosReorthogType) -> None: """ Set the type of reorthogonalization used during the Lanczos iteration. Logically collective. Parameters ---------- reorthog The type of reorthogonalization. Notes ----- This call is only relevant if the type was set to `EPS.Type.LANCZOS` with `setType()`. See Also -------- getLanczosReorthogType, slepc.EPSLanczosSetReorthog """ cdef SlepcEPSLanczosReorthogType val = reorthog CHKERR( EPSLanczosSetReorthog(self.eps, val) ) def getLanczosReorthogType(self) -> LanczosReorthogType: """ Get the type of reorthogonalization used during the Lanczos iteration. Not collective. Returns ------- LanczosReorthogType The type of reorthogonalization. See Also -------- setLanczosReorthogType, slepc.EPSLanczosGetReorthog """ cdef SlepcEPSLanczosReorthogType val = \ EPS_LANCZOS_REORTHOG_LOCAL CHKERR( EPSLanczosGetReorthog(self.eps, &val) ) return val # def setKrylovSchurBSEType(self, bse: KrylovSchurBSEType) -> None: """ Set the Krylov-Schur variant used for BSE structured eigenproblems. Logically collective. Parameters ---------- bse The BSE method. Notes ----- This call is only relevant if the type was set to `EPS.Type.KRYLOVSCHUR` with `setType()` and the problem type to `EPS.ProblemType.BSE` with `setProblemType()`. See Also -------- createMatBSE, getKrylovSchurBSEType, slepc.EPSKrylovSchurSetBSEType """ cdef SlepcEPSKrylovSchurBSEType val = bse CHKERR( EPSKrylovSchurSetBSEType(self.eps, val) ) def getKrylovSchurBSEType(self) -> KrylovSchurBSEType: """ Get the method used for BSE structured eigenproblems (Krylov-Schur). Not collective. Returns ------- KrylovSchurBSEType The BSE method. See Also -------- setKrylovSchurBSEType, slepc.EPSKrylovSchurGetBSEType """ cdef SlepcEPSKrylovSchurBSEType val = EPS_KRYLOVSCHUR_BSE_SHAO CHKERR( EPSKrylovSchurGetBSEType(self.eps, &val) ) return val def setKrylovSchurRestart(self, keep: float) -> None: """ Set the restart parameter for the Krylov-Schur method. Logically collective. It is the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getKrylovSchurRestart, slepc.EPSKrylovSchurSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( EPSKrylovSchurSetRestart(self.eps, val) ) def getKrylovSchurRestart(self) -> float: """ Get the restart parameter used in the Krylov-Schur method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setKrylovSchurRestart, slepc.EPSKrylovSchurGetRestart """ cdef PetscReal val = 0 CHKERR( EPSKrylovSchurGetRestart(self.eps, &val) ) return toReal(val) def setKrylovSchurLocking(self, lock: bool) -> None: """ Set (toggle) locking/non-locking variants of the Krylov-Schur method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getKrylovSchurLocking, slepc.EPSKrylovSchurSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( EPSKrylovSchurSetLocking(self.eps, val) ) def getKrylovSchurLocking(self) -> bool: """ Get the locking flag used in the Krylov-Schur method. Not collective. Returns ------- bool The locking flag. See Also -------- setKrylovSchurLocking, slepc.EPSKrylovSchurGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSKrylovSchurGetLocking(self.eps, &tval) ) return toBool(tval) def setKrylovSchurPartitions(self, npart: int) -> None: """ Set the number of partitions of the communicator (spectrum slicing). Logically collective. Set the number of partitions for the case of doing spectrum slicing for a computational interval with the communicator split in several sub-communicators. Parameters ---------- npart The number of partitions. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. By default, ``npart=1`` so all processes in the communicator participate in the processing of the whole interval. If ``npart>1`` then the interval is divided into ``npart`` subintervals, each of them being processed by a subset of processes. The interval is split proportionally unless the separation points are specified with `setKrylovSchurSubintervals()`. See Also -------- setInterval, getKrylovSchurPartitions, slepc.EPSKrylovSchurSetPartitions """ cdef PetscInt val = asInt(npart) CHKERR( EPSKrylovSchurSetPartitions(self.eps, val) ) def getKrylovSchurPartitions(self) -> int: """ Get the number of partitions of the communicator (spectrum slicing). Not collective. Returns ------- int The number of partitions. See Also -------- setKrylovSchurPartitions, slepc.EPSKrylovSchurGetPartitions """ cdef PetscInt val = 0 CHKERR( EPSKrylovSchurGetPartitions(self.eps, &val) ) return toInt(val) def setKrylovSchurDetectZeros(self, detect: bool) -> None: """ Set the flag that enforces zero detection in spectrum slicing. Logically collective. Set a flag to enforce the detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect ``True`` if zeros must checked for. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. A zero in the factorization indicates that a shift coincides with an eigenvalue. This flag is turned off by default, and may be necessary in some cases, especially when several partitions are being used. This feature currently requires an external package for factorizations with support for zero detection, e.g., MUMPS. See Also -------- setInterval, getKrylovSchurDetectZeros, slepc.EPSKrylovSchurSetDetectZeros """ cdef PetscBool val = asBool(detect) CHKERR( EPSKrylovSchurSetDetectZeros(self.eps, val) ) def getKrylovSchurDetectZeros(self) -> bool: """ Get the flag that enforces zero detection in spectrum slicing. Not collective. Returns ------- bool The zero detection flag. See Also -------- setKrylovSchurDetectZeros, slepc.EPSKrylovSchurGetDetectZeros """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSKrylovSchurGetDetectZeros(self.eps, &tval) ) return toBool(tval) def setKrylovSchurDimensions( self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set the dimensions used for each subsolve step (spectrum slicing). Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. The meaning of the parameters is the same as in `setDimensions()`, but the ones here apply to every subsolve done by the child `EPS` object. See Also -------- setInterval, getKrylovSchurDimensions, slepc.EPSKrylovSchurSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nev is not None: ival1 = asInt(nev) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( EPSKrylovSchurSetDimensions(self.eps, ival1, ival2, ival3) ) def getKrylovSchurDimensions(self) -> tuple[int, int, int]: """ Get the dimensions used for each subsolve step (spectrum slicing). Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setKrylovSchurDimensions, slepc.EPSKrylovSchurGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( EPSKrylovSchurGetDimensions(self.eps, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def getKrylovSchurSubcommInfo(self) -> tuple[int, int, Vec]: """ Get information related to the case of doing spectrum slicing. Collective on the subcommunicator. Get information related to the case of doing spectrum slicing for a computational interval with multiple communicators. Returns ------- k: int Index of the subinterval for the calling process. n: int Number of eigenvalues found in the ``k``-th subinterval. v: petsc4py.PETSc.Vec A vector owned by processes in the subcommunicator with dimensions compatible for locally computed eigenvectors. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. See Also -------- getKrylovSchurSubcommPairs, slepc.EPSKrylovSchurGetSubcommInfo """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef Vec vec = Vec() CHKERR( EPSKrylovSchurGetSubcommInfo(self.eps, &ival1, &ival2, &vec.vec) ) return (toInt(ival1), toInt(ival2), vec) def getKrylovSchurSubcommPairs(self, i: int, Vec v = None) -> Scalar: """ Get the i-th eigenpair stored in the multi-communicator of the process. Collective on the subcommunicator (if v is given). Get the i-th eigenpair stored internally in the multi-communicator to which the calling process belongs. Parameters ---------- i Index of the solution to be obtained. v Placeholder for the returned eigenvector. Returns ------- Scalar The computed eigenvalue. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. Argument ``v`` must be a valid ``Vec`` object, created by calling `getKrylovSchurSubcommInfo()`. The index ``i`` should be a value between ``0`` and ``n-1``, where ``n`` is the number of vectors in the local subinterval, see `getKrylovSchurSubcommInfo()`. See Also -------- getKrylovSchurSubcommMats, slepc.EPSKrylovSchurGetSubcommPairs """ cdef PetscScalar sval = 0 cdef PetscVec vec = v.vec if v is not None else NULL CHKERR( EPSKrylovSchurGetSubcommPairs(self.eps, i, &sval, vec) ) return toScalar(sval) def getKrylovSchurSubcommMats(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """ Get the eigenproblem matrices stored in the subcommunicator. Collective on the subcommunicator. Get the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the eigensystem. B: petsc4py.PETSc.Mat The second matrix in the case of generalized eigenproblems. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. This is the analog of `getOperators()`, but returns the matrices distributed differently (in the subcommunicator rather than in the parent communicator). These matrices should not be modified by the user. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurGetSubcommMats """ cdef Mat A = Mat() cdef Mat B = Mat() CHKERR( EPSKrylovSchurGetSubcommMats(self.eps, &A.mat, &B.mat) ) CHKERR( PetscINCREF(A.obj) ) if B.mat: CHKERR( PetscINCREF(B.obj) ) return (A, B) else: return (A, None) def updateKrylovSchurSubcommMats( self, s: Scalar = 1.0, a: Scalar = 1.0, Mat Au: petsc4py.PETSc.Mat | None = None, t: Scalar = 1.0, b: Scalar = 1.0, Mat Bu: petsc4py.PETSc.Mat | None = None, structure: petsc4py.PETSc.Mat.Structure | None = None, globalup: bool = False, ) -> None: """ Update the eigenproblem matrices stored internally in the communicator. Collective. Update the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Parameters ---------- s Scalar that multiplies the existing A matrix. a Scalar used in the axpy operation on A. Au The matrix used in the axpy operation on A. t Scalar that multiplies the existing B matrix. b Scalar used in the axpy operation on B. Bu The matrix used in the axpy operation on B. structure Either same, different, or a subset of the non-zero sparsity pattern. globalup Whether global matrices must be updated or not. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. And is relevant only when the number of partitions (`setKrylovSchurPartitions()`) is larger than one. This function modifies the eigenproblem matrices at subcommunicator level, and optionally updates the global matrices in the parent communicator. The updates are expressed as :math:`A \leftarrow s A + a Au`, :math:`B \leftarrow t B + b Bu`. It is possible to update one of the matrices, or both. The matrices ``Au`` and ``Bu`` must be equal in all subcommunicators. The ``structure`` flag is passed to the `petsc4py.PETSc.Mat.axpy` operations to perform the updates. If ``globalup`` is ``True``, communication is carried out to reconstruct the updated matrices in the parent communicator. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurUpdateSubcommMats """ cdef PetscMat Amat = Au.mat if Au is not None else NULL cdef PetscMat Bmat = Bu.mat if Bu is not None else NULL cdef PetscMatStructure vstr = matstructure(structure) cdef PetscBool tval = globalup CHKERR( EPSKrylovSchurUpdateSubcommMats(self.eps, s, a, Amat, t, b, Bmat, vstr, tval) ) def setKrylovSchurSubintervals(self, subint: Sequence[float]) -> None: """ Set the subinterval boundaries. Logically collective. Set the subinterval boundaries for spectrum slicing with a computational interval with several partitions. Parameters ---------- subint Real values specifying subintervals. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. This function must be called after `setKrylovSchurPartitions()`. For ``npart`` partitions, the argument ``subint`` must contain ``npart+1`` real values sorted in ascending order: ``subint_0``, ``subint_1``, ..., ``subint_npart``, where the first and last values must coincide with the interval endpoints set with `setInterval()`. The subintervals are then defined by two consecutive points: ``[subint_0,subint_1]``, ``[subint_1,subint_2]``, and so on. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurSetSubintervals """ cdef PetscBool match = PETSC_FALSE CHKERR( PetscObjectTypeCompare(self.eps, EPSKRYLOVSCHUR, &match) ) if match == PETSC_FALSE: return cdef PetscReal *subintarray = NULL cdef Py_ssize_t i = 0, n = len(subint) cdef PetscInt nparts = 0 CHKERR( EPSKrylovSchurGetPartitions(self.eps, &nparts) ) assert n >= nparts cdef tmp = allocate(n*sizeof(PetscReal),&subintarray) for i in range(n): subintarray[i] = asReal(subint[i]) CHKERR( EPSKrylovSchurSetSubintervals(self.eps, subintarray) ) def getKrylovSchurSubintervals(self) -> ArrayReal: """ Get the points that delimit the subintervals. Not collective. Get the points that delimit the subintervals used in spectrum slicing with several partitions. Returns ------- ArrayReal Real values specifying subintervals. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If the user passed values with `setKrylovSchurSubintervals()`, then the same values are returned here. Otherwise, the values computed internally are obtained. See Also -------- setKrylovSchurSubintervals, slepc.EPSKrylovSchurGetSubintervals """ cdef PetscReal *subintarray = NULL cdef PetscInt nparts = 0 CHKERR( EPSKrylovSchurGetPartitions(self.eps, &nparts) ) CHKERR( EPSKrylovSchurGetSubintervals(self.eps, &subintarray) ) cdef object subint = None try: subint = array_r(nparts+1, subintarray) finally: CHKERR( PetscFree(subintarray) ) return subint def getKrylovSchurInertias(self) -> tuple[ArrayReal, ArrayInt]: """ Get the values of the shifts and their corresponding inertias. Not collective. Get the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: ArrayReal The values of the shifts used internally in the solver. inertias: ArrayInt The values of the inertia in each shift. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If called after `solve()`, all shifts used internally by the solver are returned (including both endpoints and any intermediate ones). If called before `solve()` and after `setUp()` then only the information of the endpoints of subintervals is available. See Also -------- setInterval, setKrylovSchurSubintervals, slepc.EPSKrylovSchurGetInertias """ cdef PetscReal *shiftsarray = NULL cdef PetscInt *inertiasarray = NULL cdef PetscInt n = 0 CHKERR(EPSKrylovSchurGetInertias(self.eps, &n, &shiftsarray, &inertiasarray)) cdef object shifts = None cdef object inertias = None try: shifts = array_r(n, shiftsarray) inertias = array_i(n, inertiasarray) finally: CHKERR( PetscFree(shiftsarray) ) CHKERR( PetscFree(inertiasarray) ) return (shifts, inertias) def getKrylovSchurKSP(self) -> KSP: """ Get the linear solver object associated with the internal `EPS` object. Collective. Get the linear solver object associated with the internal `EPS` object in case of doing spectrum slicing for a computational interval. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. When invoked to compute all eigenvalues in an interval with spectrum slicing, `KRYLOVSCHUR` creates another `EPS` object internally that is used to compute eigenvalues by chunks near selected shifts. This function allows access to the ``KSP`` object associated to this internal `EPS` object. In case of having more than one partition, the returned ``KSP`` will be different in MPI processes belonging to different partitions. Hence, if required, `setKrylovSchurPartitions()` must be called BEFORE this function. See Also -------- setInterval, setKrylovSchurPartitions, slepc.EPSKrylovSchurGetKSP """ cdef KSP ksp = KSP() CHKERR( EPSKrylovSchurGetKSP(self.eps, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setGDKrylovStart(self, krylovstart: bool = True) -> None: """ Set (toggle) starting the search subspace with a Krylov basis. Logically collective. Parameters ---------- krylovstart ``True`` if starting the search subspace with a Krylov basis. See Also -------- setGDInitialSize, getGDKrylovStart, slepc.EPSGDSetKrylovStart """ cdef PetscBool val = asBool(krylovstart) CHKERR( EPSGDSetKrylovStart(self.eps, val) ) def getGDKrylovStart(self) -> bool: """ Get a flag indicating if the search subspace is started with a Krylov basis. Not collective. Returns ------- bool ``True`` if starting the search subspace with a Krylov basis. See Also -------- setGDKrylovStart, slepc.EPSGDGetKrylovStart """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetKrylovStart(self.eps, &tval) ) return toBool(tval) def setGDBlockSize(self, bs: int) -> None: """ Set the number of vectors to be added to the searching space. Logically collective. Set the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs The number of vectors added to the search space in every iteration. See Also -------- getGDBlockSize, slepc.EPSGDSetBlockSize """ cdef PetscInt ival = asInt(bs) CHKERR( EPSGDSetBlockSize(self.eps, ival) ) def getGDBlockSize(self) -> int: """ Get the number of vectors to be added to the searching space. Not collective. Get the number of vectors to be added to the searching space in every iteration. Returns ------- int The number of vectors added to the search space in every iteration. See Also -------- setGDBlockSize, slepc.EPSGDGetBlockSize """ cdef PetscInt ival = 0 CHKERR( EPSGDGetBlockSize(self.eps, &ival) ) return toInt(ival) def setGDRestart(self, minv: int = None, plusk: int = None) -> None: """ Set the number of vectors of the search space after restart. Logically collective. Set the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv The number of vectors of the search subspace after restart. plusk The number of vectors saved from the previous iteration. See Also -------- getGDRestart, slepc.EPSGDSetRestart """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if minv is not None: ival1 = asInt(minv) if plusk is not None: ival2 = asInt(plusk) CHKERR( EPSGDSetRestart(self.eps, ival1, ival2) ) def getGDRestart(self) -> tuple[int, int]: """ Get the number of vectors of the search space after restart. Not collective. Get the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Returns ------- minv: int The number of vectors of the search subspace after restart. plusk: int The number of vectors saved from the previous iteration. See Also -------- setGDRestart, slepc.EPSGDGetRestart """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSGDGetRestart(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setGDInitialSize(self, initialsize: int) -> None: """ Set the initial size of the searching space. Logically collective. Parameters ---------- initialsize The number of vectors of the initial searching subspace. Notes ----- If the flag in `setGDKrylovStart()` is set to ``False`` and the user provides vectors with `setInitialSpace()`, up to ``initialsize`` vectors will be used; and if the provided vectors are not enough, the solver completes the subspace with random vectors. In case the `setGDKrylovStart()` flag is ``True``, the solver gets the first vector provided by the user or, if not available, a random vector, and expands the Krylov basis up to ``initialsize`` vectors. See Also -------- setGDKrylovStart, getGDInitialSize, slepc.EPSGDSetInitialSize """ cdef PetscInt ival = asInt(initialsize) CHKERR( EPSGDSetInitialSize(self.eps, ival) ) def getGDInitialSize(self) -> int: """ Get the initial size of the searching space. Not collective. Returns ------- int The number of vectors of the initial searching subspace. See Also -------- setGDInitialSize, slepc.EPSGDGetInitialSize """ cdef PetscInt ival = 0 CHKERR( EPSGDGetInitialSize(self.eps, &ival) ) return toInt(ival) def setGDBOrth(self, borth: bool) -> None: """ Set the orthogonalization that will be used in the search subspace. Logically collective. Set the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth Whether to B-orthogonalize the search subspace. See Also -------- getGDBOrth, slepc.EPSGDSetBOrth """ cdef PetscBool tval = asBool(borth) CHKERR( EPSGDSetBOrth(self.eps, tval) ) def getGDBOrth(self) -> bool: """ Get the orthogonalization used in the search subspace. Not collective. Get the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- bool Whether to B-orthogonalize the search subspace. See Also -------- setGDBOrth, slepc.EPSGDGetBOrth """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetBOrth(self.eps, &tval) ) return toBool(tval) def setGDDoubleExpansion(self, doubleexp: bool) -> None: """ Set that the search subspace is expanded with double expansion. Logically collective. Parameters ---------- doubleexp ``True`` if using double expansion. Notes ----- In the double expansion variant the search subspace is expanded with :math:`K [A x, B x]` (double expansion) instead of the classic :math:`K r`, where :math:`K` is the preconditioner, :math:`x` the selected approximate eigenvector and :math:`r` its associated residual vector. See Also -------- getGDDoubleExpansion, slepc.EPSGDSetDoubleExpansion """ cdef PetscBool val = asBool(doubleexp) CHKERR( EPSGDSetDoubleExpansion(self.eps, val) ) def getGDDoubleExpansion(self) -> bool: """ Get a flag indicating whether the double expansion variant is active. Not collective. Get a flag indicating whether the double expansion variant has been activated or not. Returns ------- bool ``True`` if using double expansion. See Also -------- setGDDoubleExpansion, slepc.EPSGDGetDoubleExpansion """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetDoubleExpansion(self.eps, &tval) ) return toBool(tval) # def setJDKrylovStart(self, krylovstart: bool = True) -> None: """ Set (toggle) starting the search subspace with a Krylov basis. Logically collective. Parameters ---------- krylovstart ``True`` if starting the search subspace with a Krylov basis. See Also -------- setJDInitialSize, getJDKrylovStart, slepc.EPSJDSetKrylovStart """ cdef PetscBool val = asBool(krylovstart) CHKERR( EPSJDSetKrylovStart(self.eps, val) ) def getJDKrylovStart(self) -> bool: """ Get a flag indicating if the search subspace is started with a Krylov basis. Not collective. Returns ------- bool ``True`` if starting the search subspace with a Krylov basis. See Also -------- setJDKrylovStart, slepc.EPSJDGetKrylovStart """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetKrylovStart(self.eps, &tval) ) return toBool(tval) def setJDBlockSize(self, bs: int) -> None: """ Set the number of vectors to be added to the searching space. Logically collective. Set the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs The number of vectors added to the search space in every iteration. See Also -------- getJDBlockSize, slepc.EPSJDSetBlockSize """ cdef PetscInt ival = asInt(bs) CHKERR( EPSJDSetBlockSize(self.eps, ival) ) def getJDBlockSize(self) -> int: """ Get the number of vectors to be added to the searching space. Not collective. Get the number of vectors to be added to the searching space in every iteration. Returns ------- int The number of vectors added to the search space in every iteration. See Also -------- setJDBlockSize, slepc.EPSJDGetBlockSize """ cdef PetscInt ival = 0 CHKERR( EPSJDGetBlockSize(self.eps, &ival) ) return toInt(ival) def setJDRestart(self, minv: int | None = None, plusk: int | None = None) -> None: """ Set the number of vectors of the search space after restart. Logically collective. Set the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv The number of vectors of the search subspace after restart. plusk The number of vectors saved from the previous iteration. See Also -------- getJDRestart, slepc.EPSJDSetRestart """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if minv is not None: ival1 = asInt(minv) if plusk is not None: ival2 = asInt(plusk) CHKERR( EPSJDSetRestart(self.eps, ival1, ival2) ) def getJDRestart(self) -> tuple[int, int]: """ Get the number of vectors of the search space after restart. Not collective. Get the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Returns ------- minv: int The number of vectors of the search subspace after restart. plusk: int The number of vectors saved from the previous iteration. See Also -------- setJDRestart, slepc.EPSJDGetRestart """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSJDGetRestart(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setJDInitialSize(self, initialsize: int) -> None: """ Set the initial size of the searching space. Logically collective. Parameters ---------- initialsize The number of vectors of the initial searching subspace. Notes ----- If the flag in `setJDKrylovStart()` is set to ``False`` and the user provides vectors with `setInitialSpace()`, up to ``initialsize`` vectors will be used; and if the provided vectors are not enough, the solver completes the subspace with random vectors. In case the `setJDKrylovStart()` flag is ``True``, the solver gets the first vector provided by the user or, if not available, a random vector, and expands the Krylov basis up to ``initialsize`` vectors. See Also -------- setJDKrylovStart, getJDInitialSize, slepc.EPSJDSetInitialSize """ cdef PetscInt ival = asInt(initialsize) CHKERR( EPSJDSetInitialSize(self.eps, ival) ) def getJDInitialSize(self) -> int: """ Get the initial size of the searching space. Not collective. Returns ------- int The number of vectors of the initial searching subspace. See Also -------- setJDInitialSize, slepc.EPSJDGetInitialSize """ cdef PetscInt ival = 0 CHKERR( EPSJDGetInitialSize(self.eps, &ival) ) return toInt(ival) def setJDFix(self, fix: float) -> None: """ Set the threshold for changing the target in the correction equation. Logically collective. Parameters ---------- fix The threshold for changing the target. Notes ----- The target in the correction equation is fixed at the first iterations. When the norm of the residual vector is lower than the ``fix`` value, the target is set to the corresponding eigenvalue. See Also -------- getJDFix, slepc.EPSJDSetFix """ cdef PetscReal val = asReal(fix) CHKERR( EPSJDSetFix(self.eps, val) ) def getJDFix(self) -> float: """ Get the threshold for changing the target in the correction equation. Not collective. Returns ------- float The threshold for changing the target. See Also -------- setJDFix, slepc.EPSJDGetFix """ cdef PetscReal val = 0 CHKERR( EPSJDGetFix(self.eps, &val) ) return toReal(val) def setJDConstCorrectionTol(self, constant: bool) -> None: """ Deactivate the dynamic stopping criterion. Logically collective. Parameters ---------- constant If ``False``, the `petsc4py.PETSc.KSP` relative tolerance is set to ``0.5**i``. Notes ----- If this flag is set to ``False``, then the `petsc4py.PETSc.KSP` relative tolerance is dynamically set to ``0.5**i``, where ``i`` is the number of `EPS` iterations since the last converged value. By the default, a constant tolerance is used. See Also -------- getJDConstCorrectionTol, slepc.EPSJDSetConstCorrectionTol """ cdef PetscBool tval = asBool(constant) CHKERR( EPSJDSetConstCorrectionTol(self.eps, tval) ) def getJDConstCorrectionTol(self) -> bool: """ Get the flag indicating if the dynamic stopping is being used. Not collective. Returns ------- bool ``True`` if the dynamic stopping criterion is not being used. See Also -------- setJDConstCorrectionTol, slepc.EPSJDGetConstCorrectionTol """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetConstCorrectionTol(self.eps, &tval) ) return toBool(tval) def setJDBOrth(self, borth: bool) -> None: """ Set the orthogonalization that will be used in the search subspace. Logically collective. Set the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth Whether to B-orthogonalize the search subspace. See Also -------- getJDBOrth, slepc.EPSJDSetBOrth """ cdef PetscBool tval = asBool(borth) CHKERR( EPSJDSetBOrth(self.eps, tval) ) def getJDBOrth(self) -> bool: """ Get the orthogonalization used in the search subspace. Not collective. Get the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- bool Whether to B-orthogonalize the search subspace. See Also -------- setJDBOrth, slepc.EPSJDGetBOrth """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetBOrth(self.eps, &tval) ) return toBool(tval) # def setRQCGReset(self, nrest: int) -> None: """ Set the reset parameter of the RQCG iteration. Logically collective. Parameters ---------- nrest The number of iterations between resets. Notes ----- Every ``nrest`` iterations the solver performs a Rayleigh-Ritz projection step. See Also -------- getRQCGReset, slepc.EPSRQCGSetReset """ cdef PetscInt val = asInt(nrest) CHKERR( EPSRQCGSetReset(self.eps, val) ) def getRQCGReset(self) -> int: """ Get the reset parameter used in the RQCG method. Not collective. Returns ------- int The number of iterations between resets. See Also -------- setRQCGReset, slepc.EPSRQCGGetReset """ cdef PetscInt val = 0 CHKERR( EPSRQCGGetReset(self.eps, &val) ) return toInt(val) def setLOBPCGBlockSize(self, bs: int) -> None: """ Set the block size of the LOBPCG method. Logically collective. Parameters ---------- bs The block size. See Also -------- getLOBPCGBlockSize, slepc.EPSLOBPCGSetBlockSize """ cdef PetscInt ival = asInt(bs) CHKERR( EPSLOBPCGSetBlockSize(self.eps, ival) ) def getLOBPCGBlockSize(self) -> int: """ Get the block size used in the LOBPCG method. Not collective. Returns ------- int The block size. See Also -------- setLOBPCGBlockSize, slepc.EPSLOBPCGGetBlockSize """ cdef PetscInt ival = 0 CHKERR( EPSLOBPCGGetBlockSize(self.eps, &ival) ) return toInt(ival) def setLOBPCGRestart(self, restart: float) -> None: """ Set the restart parameter for the LOBPCG method. Logically collective. Parameters ---------- restart The percentage of the block of vectors to force a restart. Notes ----- The meaning of this parameter is the proportion of vectors within the current block iterate that must have converged in order to force a restart with hard locking. Allowed values are in the range [0.1,1.0]. The default is 0.9. See Also -------- getLOBPCGRestart, slepc.EPSLOBPCGSetRestart """ cdef PetscReal val = asReal(restart) CHKERR( EPSLOBPCGSetRestart(self.eps, val) ) def getLOBPCGRestart(self) -> float: """ Get the restart parameter used in the LOBPCG method. Not collective. Returns ------- float The restart parameter. See Also -------- setLOBPCGRestart, slepc.EPSLOBPCGGetRestart """ cdef PetscReal val = 0 CHKERR( EPSLOBPCGGetRestart(self.eps, &val) ) return toReal(val) def setLOBPCGLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking (LOBPCG method). Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- This flag refers to soft locking (converged vectors within the current block iterate), since hard locking is always used (when ``nev`` is larger than the block size). See Also -------- getLOBPCGLocking, slepc.EPSLOBPCGSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( EPSLOBPCGSetLocking(self.eps, val) ) def getLOBPCGLocking(self) -> bool: """ Get the locking flag used in the LOBPCG method. Not collective. Returns ------- bool The locking flag. See Also -------- setLOBPCGLocking, slepc.EPSLOBPCGGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSLOBPCGGetLocking(self.eps, &tval) ) return toBool(tval) def setLyapIIRanks(self, rkc: int | None = None, rkl: int | None = None) -> None: """ Set the ranks used in the solution of the Lyapunov equation. Logically collective. Parameters ---------- rkc The compressed rank. rkl The Lyapunov rank. Notes ----- Lyapunov inverse iteration needs to solve a large-scale Lyapunov equation at each iteration of the eigensolver. For this, an iterative solver (`LME`) is used, which requires to prescribe the rank of the solution matrix :math:`X`. This is the meaning of parameter ``rkl``. Later, this matrix is compressed into another matrix of rank ``rkc``. If not provided, ``rkl`` is a small multiple of ``rkc``. See Also -------- getLyapIIRanks, slepc.EPSLyapIISetRanks """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if rkc is not None: ival1 = asInt(rkc) if rkl is not None: ival2 = asInt(rkl) CHKERR( EPSLyapIISetRanks(self.eps, ival1, ival2) ) def getLyapIIRanks(self) -> tuple[int, int]: """ Get the rank values used for the Lyapunov step. Not collective. Returns ------- rkc: int The compressed rank. rkl: int The Lyapunov rank. See Also -------- setLyapIIRanks, slepc.EPSLyapIIGetRanks """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSLyapIIGetRanks(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) # def setCISSExtraction(self, extraction: CISSExtraction) -> None: """ Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.EPSCISSSetExtraction """ cdef SlepcEPSCISSExtraction val = extraction CHKERR( EPSCISSSetExtraction(self.eps, val) ) def getCISSExtraction(self) -> CISSExtraction: """ Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.EPSCISSGetExtraction """ cdef SlepcEPSCISSExtraction val = EPS_CISS_EXTRACTION_RITZ CHKERR( EPSCISSGetExtraction(self.eps, &val) ) return val def setCISSQuadRule(self, quad: CISSQuadRule) -> None: """ Set the quadrature rule used in the CISS solver. Logically collective. Parameters ---------- quad The quadrature rule. See Also -------- getCISSQuadRule, slepc.EPSCISSSetQuadRule """ cdef SlepcEPSCISSQuadRule val = quad CHKERR( EPSCISSSetQuadRule(self.eps, val) ) def getCISSQuadRule(self) -> CISSQuadRule: """ Get the quadrature rule used in the CISS solver. Not collective. Returns ------- CISSQuadRule The quadrature rule. See Also -------- setCISSQuadRule, slepc.EPSCISSGetQuadRule """ cdef SlepcEPSCISSQuadRule val = EPS_CISS_QUADRULE_TRAPEZOIDAL CHKERR( EPSCISSGetQuadRule(self.eps, &val) ) return val def setCISSSizes( self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False, ) -> None: """ Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `EPS` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.EPSCISSSetSizes """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT cdef PetscInt ival4 = PETSC_CURRENT cdef PetscInt ival5 = PETSC_CURRENT cdef PetscBool bval = asBool(realmats) if ip is not None: ival1 = asInt(ip) if bs is not None: ival2 = asInt(bs) if ms is not None: ival3 = asInt(ms) if npart is not None: ival4 = asInt(npart) if bsmax is not None: ival5 = asInt(bsmax) CHKERR( EPSCISSSetSizes(self.eps, ival1, ival2, ival3, ival4, ival5, bval) ) def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """ Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.EPSCISSGetSizes """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 cdef PetscInt ival4 = 0 cdef PetscInt ival5 = 0 cdef PetscBool bval = PETSC_FALSE CHKERR( EPSCISSGetSizes(self.eps, &ival1, &ival2, &ival3, &ival4, &ival5, &bval) ) return (toInt(ival1), toInt(ival2), toInt(ival3), toInt(ival4), toInt(ival5), toBool(bval)) def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """ Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.EPSCISSSetThreshold """ cdef PetscReal rval1 = PETSC_CURRENT cdef PetscReal rval2 = PETSC_CURRENT if delta is not None: rval1 = asReal(delta) if spur is not None: rval2 = asReal(spur) CHKERR( EPSCISSSetThreshold(self.eps, rval1, rval2) ) def getCISSThreshold(self) -> tuple[float, float]: """ Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.EPSCISSGetThreshold """ cdef PetscReal delta = 0 cdef PetscReal spur = 0 CHKERR( EPSCISSGetThreshold(self.eps, &delta, &spur) ) return (toReal(delta), toReal(spur)) def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """ Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.EPSCISSSetRefinement """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if inner is not None: ival1 = asInt(inner) if blsize is not None: ival2 = asInt(blsize) CHKERR( EPSCISSSetRefinement(self.eps, ival1, ival2) ) def getCISSRefinement(self) -> tuple[int, int]: """ Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.EPSCISSGetRefinement """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSCISSGetRefinement(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setCISSUseST(self, usest: bool) -> None: """ Set a flag indicating that the CISS solver will use the `ST` object. Logically collective. Parameters ---------- usest Whether to use the `ST` object or not. Notes ----- When this option is set, the linear solves can be configured by setting options for the `petsc4py.PETSc.KSP` object obtained with `ST.getKSP()`. Otherwise, several `petsc4py.PETSc.KSP` objects are created, which can be accessed with `getCISSKSPs()`. The default is to use the `ST`, unless several partitions have been specified, see `setCISSSizes()`. See Also -------- getCISSUseST, getCISSKSPs, setCISSSizes, slepc.EPSCISSSetUseST """ cdef PetscBool tval = asBool(usest) CHKERR( EPSCISSSetUseST(self.eps, tval) ) def getCISSUseST(self) -> bool: """ Get the flag indicating the use of the `ST` object in the CISS solver. Not collective. Returns ------- bool Whether to use the `ST` object or not. See Also -------- setCISSUseST, slepc.EPSCISSGetUseST """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSCISSGetUseST(self.eps, &tval) ) return toBool(tval) def getCISSKSPs(self) -> list[KSP]: """ Get the array of linear solver objects associated with the CISS solver. Not collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.EPSCISSGetKSPs """ cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL CHKERR( EPSCISSGetKSPs(self.eps, &n, &p) ) return [ref_KSP(p[i]) for i from 0 <= i EPSProblemType: return self.getProblemType() def __set__(self, value): self.setProblemType(value) property extraction: """The type of extraction technique to be employed.""" def __get__(self) -> EPSExtraction: return self.getExtraction() def __set__(self, value): self.setExtraction(value) property which: """The portion of the spectrum to be sought.""" def __get__(self) -> EPSWhich: return self.getWhichEigenpairs() def __set__(self, value): self.setWhichEigenpairs(value) property target: """The value of the target.""" def __get__(self) -> float: return self.getTarget() def __set__(self, value): self.setTarget(value) property tol: """The tolerance.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property two_sided: """Two-sided that also computes left eigenvectors.""" def __get__(self) -> bool: return self.getTwoSided() def __set__(self, value): self.setTwoSided(value) property true_residual: """Compute the true residual explicitly.""" def __get__(self) -> bool: return self.getTrueResidual() def __set__(self, value): self.setTrueResidual(value) property purify: """Eigenvector purification.""" def __get__(self) -> bool: return self.getPurify() def __set__(self, value): self.setPurify(value) property track_all: """Compute the residual norm of all approximate eigenpairs.""" def __get__(self) -> bool: return self.getTrackAll() def __set__(self, value): self.setTrackAll(value) property st: """The spectral transformation (`ST`) object associated.""" def __get__(self) -> ST: return self.getST() def __set__(self, value): self.setST(value) property bv: """The basis vectors (`BV`) object associated.""" def __get__(self) -> BV: return self.getBV() def __set__(self, value): self.setBV(value) property rg: """The region (`RG`) object associated.""" def __get__(self) -> RG: return self.getRG() def __set__(self, value): self.setRG(value) property ds: """The direct solver (`DS`) object associated.""" def __get__(self) -> DS: return self.getDS() def __set__(self, value): self.setDS(value) # ----------------------------------------------------------------------------- del EPSType del EPSProblemType del EPSExtraction del EPSBalance del EPSErrorType del EPSWhich del EPSConv del EPSStop del EPSConvergedReason del EPSPowerShiftType del EPSKrylovSchurBSEType del EPSLanczosReorthogType del EPSCISSQuadRule del EPSCISSExtraction # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/FN.pyx0000644000076500000240000005145115133663436017103 0ustar00jromanstaff# ----------------------------------------------------------------------------- class FNType(object): """ FN type. - `COMBINE`: A math function defined by combining two functions. - `RATIONAL`: A rational function :math:`f(x)=p(x)/q(x)`. - `EXP`: The exponential function :math:`f(x)=e^x`. - `LOG`: The logarithm function :math:`f(x)=\log{x}`. - `PHI`: One of the Phi_k functions with index k. - `SQRT`: The square root function :math:`f(x)=\sqrt{x}`. - `INVSQRT`: The inverse square root function. See Also -------- slepc.FNType """ COMBINE = S_(FNCOMBINE) RATIONAL = S_(FNRATIONAL) EXP = S_(FNEXP) LOG = S_(FNLOG) PHI = S_(FNPHI) SQRT = S_(FNSQRT) INVSQRT = S_(FNINVSQRT) class FNCombineType(object): """ FN type of combination of child functions. - `ADD`: Addition :math:`f(x) = f_1(x)+f_2(x)` - `MULTIPLY`: Multiplication :math:`f(x) = f_1(x)f_2(x)` - `DIVIDE`: Division :math:`f(x) = f_1(x)/f_2(x)` - `COMPOSE`: Composition :math:`f(x) = f_2(f_1(x))` See Also -------- slepc.FNCombineType """ ADD = FN_COMBINE_ADD MULTIPLY = FN_COMBINE_MULTIPLY DIVIDE = FN_COMBINE_DIVIDE COMPOSE = FN_COMBINE_COMPOSE class FNParallelType(object): """ FN parallel types. - `REDUNDANT`: Every process performs the computation redundantly. - `SYNCHRONIZED`: The first process sends the result to the rest. See Also -------- slepc.FNParallelType """ REDUNDANT = FN_PARALLEL_REDUNDANT SYNCHRONIZED = FN_PARALLEL_SYNCHRONIZED # ----------------------------------------------------------------------------- cdef class FN(Object): """ Mathematical Function. The `FN` package provides the functionality to represent a simple mathematical function such as an exponential, a polynomial or a rational function. This is used as a building block for defining the function associated to the nonlinear eigenproblem, as well as for specifying which function to use when computing the action of a matrix function on a vector. """ Type = FNType CombineType = FNCombineType ParallelType = FNParallelType def __cinit__(self): self.obj = &self.fn self.fn = NULL # unary operations def __pos__(self): return fn_pos(self) def __neg__(self): return fn_neg(self) # inplace binary operations def __iadd__(self, other): return fn_iadd(self, other) def __isub__(self, other): return fn_isub(self, other) def __imul__(self, other): return fn_imul(self, other) def __idiv__(self, other): return fn_idiv(self, other) def __itruediv__(self, other): return fn_idiv(self, other) # binary operations def __add__(self, other): return fn_add(self, other) def __radd__(self, other): return fn_radd(self, other) def __sub__(self, other): return fn_sub(self, other) def __rsub__(self, other): return fn_rsub(self, other) def __mul__(self, other): return fn_mul(self, other) def __rmul__(self, other): return fn_rmul(self, other) def __div__(self, other): return fn_div(self, other) def __rdiv__(self, other): return fn_rdiv(self, other) def __truediv__(self, other): return fn_div(self, other) def __rtruediv__(self, other): return fn_rdiv(self, other) def __matmul__(self, other): return fn_matmul(self, other) def __call__(self, arg): if isinstance(arg, Mat): return self.evaluateFunctionMat(arg) else: return self.evaluateFunction(arg) # def view(self, Viewer viewer=None) -> None: """ Print the FN data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.FNView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( FNView(self.fn, vwr) ) def destroy(self) -> Self: """ Destroy the FN object. Collective. See Also -------- slepc.FNDestroy """ CHKERR( FNDestroy(&self.fn) ) self.fn = NULL return self def create(self, comm: Comm | None = None) -> Self: """ Create the FN object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.FNCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcFN newfn = NULL CHKERR( FNCreate(ccomm, &newfn) ) CHKERR( SlepcCLEAR(self.obj) ); self.fn = newfn return self def setType(self, fn_type: Type | str) -> None: """ Set the type for the FN object. Logically collective. Parameters ---------- fn_type The math function type to be used. See Also -------- getType, slepc.FNSetType """ cdef SlepcFNType cval = NULL fn_type = str2bytes(fn_type, &cval) CHKERR( FNSetType(self.fn, cval) ) def getType(self) -> str: """ Get the FN type of this object. Not collective. Returns ------- str The math function type currently being used. See Also -------- setType, slepc.FNGetType """ cdef SlepcFNType fn_type = NULL CHKERR( FNGetType(self.fn, &fn_type) ) return bytes2str(fn_type) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all FN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all FN option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.FNGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( FNSetOptionsPrefix(self.fn, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all FN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all FN option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.FNAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( FNAppendOptionsPrefix(self.fn, cval) ) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all FN options in the database. Not collective. Returns ------- str The prefix string set for this FN object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.FNGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( FNGetOptionsPrefix(self.fn, &prefix) ) return bytes2str(prefix) def setFromOptions(self) -> None: """ Set FN options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.FNSetFromOptions """ CHKERR( FNSetFromOptions(self.fn) ) def duplicate(self, comm: Comm | None = None) -> FN: """ Duplicate the FN object copying all parameters. Collective. Duplicate the FN object copying all parameters, possibly with a different communicator. Parameters ---------- comm MPI communicator; if not provided, it defaults to the object's communicator. Returns ------- FN The new object. See Also -------- create, slepc.FNDuplicate """ cdef MPI_Comm ccomm = def_Comm(comm, PetscObjectComm(self.fn)) cdef FN fn = type(self)() CHKERR( FNDuplicate(self.fn, ccomm, &fn.fn) ) return fn # def evaluateFunction(self, x: Scalar) -> Scalar: """ Compute the value of the function :math:`f(x)` for a given x. Not collective. Parameters ---------- x Value where the function must be evaluated. Returns ------- Scalar The result of :math:`f(x)`. Notes ----- Scaling factors are taken into account, so the actual function evaluation will return :math:`b f(a x)`. See Also -------- evaluateDerivative, evaluateFunctionMat, setScale, slepc.FNEvaluateFunction """ cdef PetscScalar sval = 0 cdef PetscScalar sarg = asScalar(x) CHKERR( FNEvaluateFunction(self.fn, sarg, &sval) ) return toScalar(sval) def evaluateDerivative(self, x: Scalar) -> Scalar: """ Compute the value of the derivative :math:`f'(x)` for a given x. Not collective. Parameters ---------- x Value where the derivative must be evaluated. Returns ------- Scalar The result of :math:`f'(x)`. Notes ----- Scaling factors are taken into account, so the actual derivative evaluation will return :math:`ab f'(a x)`. See Also -------- evaluateFunction, setScale, slepc.FNEvaluateDerivative """ cdef PetscScalar sval = 0 cdef PetscScalar sarg = asScalar(x) CHKERR( FNEvaluateDerivative(self.fn, sarg, &sval) ) return toScalar(sval) def evaluateFunctionMat(self, Mat A, Mat B: Mat | None = None) -> Mat: """ Compute the value of the function :math:`f(A)` for a given matrix A. Logically collective. Parameters ---------- A Matrix on which the function must be evaluated. B Placeholder for the result. Returns ------- petsc4py.PETSc.Mat The result of :math:`f(A)`. Notes ----- Scaling factors are taken into account, so the actual function evaluation will return :math:`b f(a A)`. See Also -------- evaluateFunction, evaluateFunctionMatVec, slepc.FNEvaluateFunctionMat """ if B is None: B = A.duplicate() CHKERR( FNEvaluateFunctionMat(self.fn, A.mat, B.mat) ) return B def evaluateFunctionMatVec(self, Mat A, Vec v: Vec | None = None) -> Vec: """ Compute the first column of the matrix :math:`f(A)`. Logically collective. Parameters ---------- A Matrix on which the function must be evaluated. Returns ------- petsc4py.PETSc.Vec The first column of the result :math:`f(A)`. Notes ----- This operation is similar to `evaluateFunctionMat()` but returns only the first column of :math:`f(A)`, hence saving computations in most cases. See Also -------- evaluateFunctionMat, slepc.FNEvaluateFunctionMatVec """ if v is None: v = A.createVecs('left') CHKERR( FNEvaluateFunctionMatVec(self.fn, A.mat, v.vec) ) return v def setScale(self, alpha: Scalar | None = None, beta: Scalar | None = None) -> None: """ Set the scaling parameters that define the matematical function. Logically collective. Parameters ---------- alpha Inner scaling (argument), default is 1.0. beta Outer scaling (result), default is 1.0. See Also -------- getScale, evaluateFunction, slepc.FNSetScale """ cdef PetscScalar aval = 1.0 cdef PetscScalar bval = 1.0 if alpha is not None: aval = asScalar(alpha) if beta is not None: bval = asScalar(beta) CHKERR( FNSetScale(self.fn, aval, bval) ) def getScale(self) -> tuple[Scalar, Scalar]: """ Get the scaling parameters that define the matematical function. Not collective. Returns ------- alpha: Scalar Inner scaling (argument). beta: Scalar Outer scaling (result). See Also -------- setScale, slepc.FNGetScale """ cdef PetscScalar aval = 0, bval = 0 CHKERR( FNGetScale(self.fn, &aval, &bval) ) return (toScalar(aval), toScalar(bval)) def setMethod(self, meth: int) -> None: """ Set the method to be used to evaluate functions of matrices. Logically collective. Parameters ---------- meth An index identifying the method. Notes ----- In some `FN` types there are more than one algorithms available for computing matrix functions. In that case, this function allows choosing the wanted method. If ``meth`` is currently set to 0 and the input argument of `FN.evaluateFunctionMat()` is a symmetric/Hermitian matrix, then the computation is done via the eigendecomposition, rather than with the general algorithm. See Also -------- getMethod, slepc.FNSetMethod """ cdef PetscInt val = asInt(meth) CHKERR( FNSetMethod(self.fn, val) ) def getMethod(self) -> int: """ Get the method currently used for matrix functions. Not collective. Returns ------- int An index identifying the method. See Also -------- setMethod, slepc.FNGetMethod """ cdef PetscInt val = 0 CHKERR( FNGetMethod(self.fn, &val) ) return toInt(val) def setParallel(self, pmode: ParallelType) -> None: """ Set the mode of operation in parallel runs. Logically collective. Parameters ---------- pmode The parallel mode. Notes ----- This is relevant only when the function is evaluated on a matrix, with either `evaluateFunctionMat()` or `evaluateFunctionMatVec()`. See Also -------- evaluateFunctionMat, getParallel, slepc.FNSetParallel """ cdef SlepcFNParallelType val = pmode CHKERR( FNSetParallel(self.fn, val) ) def getParallel(self) -> ParallelType: """ Get the mode of operation in parallel runs. Not collective. Returns ------- ParallelType The parallel mode. See Also -------- setParallel, slepc.FNGetParallel """ cdef SlepcFNParallelType val = FN_PARALLEL_REDUNDANT CHKERR( FNGetParallel(self.fn, &val) ) return val # def setRationalNumerator(self, alpha: Sequence[Scalar]) -> None: """ Set the coefficients of the numerator of the rational function. Logically collective. Parameters ---------- alpha Coefficients. See Also -------- setRationalDenominator, slepc.FNRationalSetNumerator """ cdef PetscInt na = 0 cdef PetscScalar *a = NULL cdef object tmp1 = iarray_s(alpha, &na, &a) CHKERR( FNRationalSetNumerator(self.fn, na, a) ) def getRationalNumerator(self) -> ArrayScalar: """ Get the coefficients of the numerator of the rational function. Not collective. Returns ------- ArrayScalar Coefficients. See Also -------- setRationalNumerator, slepc.FNRationalGetNumerator """ cdef PetscInt np = 0 cdef PetscScalar *coeff = NULL CHKERR( FNRationalGetNumerator(self.fn, &np, &coeff) ) cdef object ocoeff = None try: ocoeff = array_s(np, coeff) finally: CHKERR( PetscFree(coeff) ) return ocoeff def setRationalDenominator(self, alpha: Sequence[Scalar]) -> None: """ Set the coefficients of the denominator of the rational function. Logically collective. Parameters ---------- alpha Coefficients. See Also -------- setRationalNumerator, slepc.FNRationalSetDenominator """ cdef PetscInt na = 0 cdef PetscScalar *a = NULL cdef object tmp1 = iarray_s(alpha, &na, &a) CHKERR( FNRationalSetDenominator(self.fn, na, a) ) def getRationalDenominator(self) -> ArrayScalar: """ Get the coefficients of the denominator of the rational function. Not collective. Returns ------- ArrayScalar Coefficients. See Also -------- setRationalDenominator, slepc.FNRationalGetDenominator """ cdef PetscInt np = 0 cdef PetscScalar *coeff = NULL CHKERR( FNRationalGetDenominator(self.fn, &np, &coeff) ) cdef object ocoeff = None try: ocoeff = array_s(np, coeff) finally: CHKERR( PetscFree(coeff) ) return ocoeff def setCombineChildren(self, comb: CombineType, FN f1, FN f2) -> None: """ Set the two child functions that constitute this combined function. Logically collective. Set the two child functions that constitute this combined function, and the way they must be combined. Parameters ---------- comb How to combine the functions (addition, multiplication, division, composition). f1 First function. f2 Second function. See Also -------- getCombineChildren, slepc.FNCombineSetChildren """ cdef SlepcFNCombineType val = comb CHKERR( FNCombineSetChildren(self.fn, val, f1.fn, f2.fn) ) def getCombineChildren(self) -> tuple[CombineType, FN, FN]: """ Get the two child functions that constitute this combined function. Not collective. Get the two child functions that constitute this combined function, and the way they must be combined. Returns ------- comb: CombineType How to combine the functions (addition, multiplication, division, composition). f1: FN First function. f2: FN Second function. See Also -------- setCombineChildren, slepc.FNCombineGetChildren """ cdef SlepcFNCombineType comb cdef FN f1 = FN() cdef FN f2 = FN() CHKERR( FNCombineGetChildren(self.fn, &comb, &f1.fn, &f2.fn) ) CHKERR( PetscINCREF(f1.obj) ) CHKERR( PetscINCREF(f2.obj) ) return (comb, f1, f2) def setPhiIndex(self, k: int) -> None: """ Set the index of the phi-function. Logically collective. Parameters ---------- k The index. Notes ----- If not set, the default index is 1. See Also -------- getPhiIndex, slepc.FNPhiSetIndex """ cdef PetscInt val = asInt(k) CHKERR( FNPhiSetIndex(self.fn, val) ) def getPhiIndex(self) -> int: """ Get the index of the phi-function. Not collective. Returns ------- int The index. See Also -------- setPhiIndex, slepc.FNPhiGetIndex """ cdef PetscInt val = 0 CHKERR( FNPhiGetIndex(self.fn, &val) ) return toInt(val) # property method: """The method to be used to evaluate functions of matrices.""" def __get__(self) -> int: return self.getMethod() def __set__(self, value): self.setMethod(value) property parallel: """The mode of operation in parallel runs.""" def __get__(self) -> FNParallelType: return self.getParallel() def __set__(self, value): self.setParallel(value) # ----------------------------------------------------------------------------- del FNType del FNCombineType del FNParallelType # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/LME.pyx0000644000076500000240000005722615133663436017223 0ustar00jromanstaff# ----------------------------------------------------------------------------- class LMEType(object): """ LME type. - `KRYLOV`: Restarted Krylov solver. See Also -------- slepc.LMEType """ KRYLOV = S_(LMEKRYLOV) class LMEConvergedReason(object): """ LME convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.LMEConvergedReason """ CONVERGED_TOL = LME_CONVERGED_TOL DIVERGED_ITS = LME_DIVERGED_ITS DIVERGED_BREAKDOWN = LME_DIVERGED_BREAKDOWN CONVERGED_ITERATING = LME_CONVERGED_ITERATING ITERATING = LME_CONVERGED_ITERATING class LMEProblemType(object): """ LME problem type. - `LYAPUNOV`: Continuous-time Lyapunov. - `SYLVESTER`: Continuous-time Sylvester. - `GEN_LYAPUNOV`: Generalized Lyapunov. - `GEN_SYLVESTER`: Generalized Sylvester. - `DT_LYAPUNOV`: Discrete-time Lyapunov. - `STEIN`: Stein. See Also -------- slepc.LMEProblemType """ LYAPUNOV = LME_LYAPUNOV SYLVESTER = LME_SYLVESTER GEN_LYAPUNOV = LME_GEN_LYAPUNOV GEN_SYLVESTER = LME_GEN_SYLVESTER DT_LYAPUNOV = LME_DT_LYAPUNOV STEIN = LME_STEIN # ----------------------------------------------------------------------------- cdef class LME(Object): """ Linear Matrix Equation. Linear Matrix Equation (`LME`) is the object provided by slepc4py for solving linear matrix equations such as Lyapunov or Sylvester where the solution has low rank. """ Type = LMEType ConvergedReason = LMEConvergedReason ProblemType = LMEProblemType def __cinit__(self): self.obj = &self.lme self.lme = NULL def view(self, Viewer viewer=None) -> None: """ Print the LME data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.LMEView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( LMEView(self.lme, vwr) ) def destroy(self) -> Self: """ Destroy the LME object. Collective. See Also -------- slepc.LMEDestroy """ CHKERR( LMEDestroy(&self.lme) ) self.lme = NULL return self def reset(self) -> None: """ Reset the LME object. Collective. See Also -------- slepc.LMEReset """ CHKERR( LMEReset(self.lme) ) def create(self, comm: Comm | None = None) -> Self: """ Create the LME object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.LMECreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcLME newlme = NULL CHKERR( LMECreate(ccomm, &newlme) ) CHKERR( SlepcCLEAR(self.obj) ); self.lme = newlme return self def setType(self, lme_type: Type | str) -> None: """ Set the particular solver to be used in the LME object. Logically collective. Parameters ---------- lme_type The solver to be used. Notes ----- The default is ``KRYLOV``. Normally, it is best to use `setFromOptions()` and then set the LME type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.LMESetType """ cdef SlepcLMEType cval = NULL lme_type = str2bytes(lme_type, &cval) CHKERR( LMESetType(self.lme, cval) ) def getType(self) -> str: """ Get the LME type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.LMEGetType """ cdef SlepcLMEType lme_type = NULL CHKERR( LMEGetType(self.lme, &lme_type) ) return bytes2str(lme_type) def setProblemType(self, lme_problem_type: ProblemType | str) -> None: """ Set the LME problem type of this object. Logically collective. Parameters ---------- lme_problem_type The problem type to be used. See Also -------- getProblemType, slepc.LMESetProblemType """ cdef SlepcLMEProblemType val = lme_problem_type CHKERR( LMESetProblemType(self.lme, val) ) def getProblemType(self) -> ProblemType: """ Get the LME problem type of this object. Not collective. Returns ------- ProblemType The problem type currently being used. See Also -------- setProblemType, slepc.LMEGetProblemType """ cdef SlepcLMEProblemType val = LME_LYAPUNOV CHKERR( LMEGetProblemType(self.lme, &val)) return val def setCoefficients(self, Mat A, Mat B = None, Mat D = None, Mat E = None) -> None: """ Set the coefficient matrices. Collective. Set the coefficient matrices that define the linear matrix equation to be solved. Parameters ---------- A First coefficient matrix B Second coefficient matrix, optional D Third coefficient matrix, optional E Fourth coefficient matrix, optional Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where matrix :math:`C` is not provided here but with `setRHS()`. Not all four matrices must be passed. This must be called before `setUp()`. If called again after `setUp()` then the `LME` object is reset. See Also -------- getCoefficients, solve, setRHS, setUp, slepc.LMESetCoefficients """ cdef PetscMat Amat = A.mat cdef PetscMat Bmat = B.mat if B is not None else NULL cdef PetscMat Dmat = D.mat if D is not None else NULL cdef PetscMat Emat = E.mat if E is not None else NULL CHKERR( LMESetCoefficients(self.lme, Amat, Bmat, Dmat, Emat)) def getCoefficients(self) -> tuple[Mat, Mat | None, Mat | None, Mat | None]: """ Get the coefficient matrices of the matrix equation. Collective. Returns ------- A: petsc4py.PETSc.Mat First coefficient matrix. B: petsc4py.PETSc.Mat Second coefficient matrix, if available. D: petsc4py.PETSc.Mat Third coefficient matrix, if available. E: petsc4py.PETSc.Mat Fourth coefficient matrix, if available. See Also -------- setCoefficients, slepc.LMEGetCoefficients """ cdef PetscMat Amat, Bmat, Dmat, Emat cdef Mat A = Mat(), B = None, D = None, E = None CHKERR( LMEGetCoefficients(self.lme, &Amat, &Bmat, &Dmat, &Emat) ) A.mat = Amat CHKERR( PetscINCREF(A.obj) ) if Bmat: B = Mat(); B.mat = Bmat; CHKERR( PetscINCREF(B.obj) ) if Dmat: D = Mat(); D.mat = Dmat; CHKERR( PetscINCREF(D.obj) ) if Emat: E = Mat(); E.mat = Emat; CHKERR( PetscINCREF(E.obj) ) return (A, B, D, E) def setRHS(self, Mat C) -> None: """ Set the right-hand side of the matrix equation. Collective. Parameters ---------- C The right-hand side matrix Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where matrix :math:`C` is given with this function. It must be a low-rank matrix of type `petsc4py.PETSc.Mat.Type.LRC`, that is, :math:`C = UDV^*` where :math:`D` is diagonal of order :math:`k`, and :math:`U,V` are dense tall-skinny matrices with :math:`k` columns. No sparse matrix must be provided when creating the ``LRC`` matrix. In equation types that require :math:`C` to be symmetric, such as Lyapunov, ``C`` must be created with :math:`V=U`. See Also -------- getRHS, setSolution, slepc.LMESetRHS """ CHKERR( LMESetRHS(self.lme, C.mat) ) def getRHS(self) -> Mat: """ Get the right-hand side of the matrix equation. Collective. Returns ------- C: petsc4py.PETSc.Mat The low-rank matrix. See Also -------- setRHS, slepc.LMEGetRHS """ cdef Mat C = Mat() CHKERR( LMEGetRHS(self.lme, &C.mat) ) CHKERR( PetscINCREF(C.obj) ) return C def setSolution(self, Mat X = None) -> None: """ Set the placeholder for the solution of the matrix equation. Collective. Parameters ---------- X The solution matrix Notes ----- The matrix equation takes the general form :math:`AXE+DXB=C`, where the solution matrix is of low rank and is written in factored form :math:`X = UDV^*`. This function provides a matrix object of type `petsc4py.PETSc.Mat.Type.LRC` that stores :math:`U,V` and (optionally) :math:`D`. These factors will be computed during `solve()`. In equation types whose solution :math:`X` is symmetric, such as Lyapunov, ``X`` must be created with :math:`V=U`. If the user provides ``X`` with this function, then the solver will return a solution with rank at most the number of columns of :math:`U`. Alternatively, it is possible to let the solver choose the rank of the solution, by passing ``None`` and then calling `getSolution()` after `solve()`. See Also -------- solve, setRHS, getSolution, slepc.LMESetSolution """ cdef PetscMat Xmat = X.mat if X is not None else NULL CHKERR( LMESetSolution(self.lme, Xmat) ) def getSolution(self) -> Mat: """ Get the solution of the matrix equation. Collective. Returns ------- X: petsc4py.PETSc.Mat The low-rank matrix. Notes ----- If called after `solve()`, ``X`` will contain the solution of the equation. The matrix ``X`` may have been passed by the user via `setSolution()`, although this is not required. See Also -------- solve, setSolution, slepc.LMEGetSolution """ cdef Mat X = Mat() CHKERR( LMEGetSolution(self.lme, &X.mat) ) CHKERR( PetscINCREF(X.obj) ) return X def getErrorEstimate(self) -> float: """ Get the error estimate obtained during the solve. Not collective. Returns ------- float The error estimate. Notes ----- This is the error estimated internally by the solver. The actual error bound can be computed with `computeError()`. Note that some solvers may not be able to provide an error estimate. See Also -------- computeError, slepc.LMEGetErrorEstimate """ cdef PetscReal rval = 0 CHKERR( LMEGetErrorEstimate(self.lme, &rval) ) return toReal(rval) def computeError(self) -> float: """ Compute the error associated with the last equation solved. Collective. Returns ------- float The error. Notes ----- The error is based on the residual norm. This function is not scalable (in terms of memory or parallel communication), so it should not be called except in the case of small problem size. For large equations, use `getErrorEstimate()`. See Also -------- getErrorEstimate, slepc.LMEComputeError """ cdef PetscReal rval = 0 CHKERR( LMEComputeError(self.lme, &rval) ) return toReal(rval) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all LME options in the database. Not collective. Returns ------- str The prefix string set for this LME object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.LMEGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( LMEGetOptionsPrefix(self.lme, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all LME options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all LME option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different LME contexts, one could call:: L1.setOptionsPrefix("lme1_") L2.setOptionsPrefix("lme2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.LMEGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( LMESetOptionsPrefix(self.lme, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching in the database. Logically collective. Append to the prefix used for searching for all LME options in the database. Parameters ---------- prefix The prefix string to prepend to all LME option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.LMEAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( LMEAppendOptionsPrefix(self.lme, cval) ) def setFromOptions(self) -> None: """ Set LME options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.LMESetFromOptions """ CHKERR( LMESetFromOptions(self.lme) ) def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and maximum iteration count. Not collective. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.LMEGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( LMEGetTolerances(self.lme, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """ Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default LME convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. See Also -------- getTolerances, slepc.LMESetTolerances """ cdef PetscReal rval = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT if tol is not None: rval = asReal(tol) if max_it is not None: ival = asInt(max_it) CHKERR( LMESetTolerances(self.lme, rval, ival) ) def getDimensions(self) -> int: """ Get the dimension of the subspace used by the solver. Not collective. Returns ------- int Maximum dimension of the subspace to be used by the solver. See Also -------- setDimensions, slepc.LMEGetDimensions """ cdef PetscInt ival = 0 CHKERR( LMEGetDimensions(self.lme, &ival) ) return toInt(ival) def setDimensions(self, ncv: int) -> None: """ Set the dimension of the subspace to be used by the solver. Logically collective. Parameters ---------- ncv Maximum dimension of the subspace to be used by the solver. See Also -------- getDimensions, slepc.LMESetDimensions """ cdef PetscInt ival = asInt(ncv) CHKERR( LMESetDimensions(self.lme, ival) ) def getBV(self) -> BV: """ Get the basis vector object associated to the LME object. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.LMEGetBV """ cdef BV bv = BV() CHKERR( LMEGetBV(self.lme, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv) -> None: """ Set a basis vector object to the LME object. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.LMESetBV """ CHKERR( LMESetBV(self.lme, bv.bv) ) def setMonitor( self, monitor: LMEMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.LMEMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( LMEMonitorSet(self.lme, LME_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> LMEMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- LMEMonitorFunction The list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for an `LME` object. Logically collective. See Also -------- slepc.LMEMonitorCancel """ CHKERR( LMEMonitorCancel(self.lme) ) self.set_attr('__monitor__', None) def setUp(self) -> None: """ Set up all the internal necessary data structures. Collective. Set up all the internal data structures necessary for the execution of the eigensolver. See Also -------- solve, slepc.LMESetUp """ CHKERR( LMESetUp(self.lme) ) def solve(self) -> None: """ Solve the linear matrix equation. Collective. Notes ----- The matrix coefficients are specified with `setCoefficients()`. The right-hand side is specified with `setRHS()`. The placeholder for the solution is specified with `setSolution()`. See Also -------- setCoefficients, setRHS, setSolution, slepc.LMESolve """ CHKERR( LMESolve(self.lme) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, slepc.LMEGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( LMEGetIterationNumber(self.lme, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, setErrorIfNotConverged, slepc.LMEGetConvergedReason """ cdef SlepcLMEConvergedReason val = LME_CONVERGED_ITERATING CHKERR( LMEGetConvergedReason(self.lme, &val) ) return val def setErrorIfNotConverged(self, flg: bool = True) -> None: """ Set `solve()` to generate an error if the solver has not converged. Logically collective. Parameters ---------- flg ``True`` indicates you want the error generated. Notes ----- Normally SLEPc continues if the solver fails to converge, you can call `getConvergedReason()` after a `solve()` to determine if it has converged. See Also -------- getConvergedReason, solve, slepc.LMESetErrorIfNotConverged """ cdef PetscBool tval = flg CHKERR( LMESetErrorIfNotConverged(self.lme, tval) ) def getErrorIfNotConverged(self) -> bool: """ Get if `solve()` generates an error if the solver does not converge. Not collective. Get a flag indicating whether `solve()` will generate an error if the solver does not converge. Returns ------- bool ``True`` indicates you want the error generated. See Also -------- setErrorIfNotConverged, slepc.LMEGetErrorIfNotConverged """ cdef PetscBool tval = PETSC_FALSE CHKERR( LMEGetErrorIfNotConverged(self.lme, &tval) ) return toBool(tval) # property tol: """The tolerance value used by the LME convergence tests.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count used by the LME convergence tests.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property fn: """The math function (`FN`) object associated to the LME object.""" def __get__(self) -> FN: return self.getFN() def __set__(self, value): self.setFN(value) property bv: """The basis vectors (`BV`) object associated to the LME object.""" def __get__(self) -> BV: return self.getBV() def __set__(self, value): self.setBV(value) # ----------------------------------------------------------------------------- del LMEType del LMEConvergedReason del LMEProblemType # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/MFN.pyx0000644000076500000240000004365715133663436017231 0ustar00jromanstaff# ----------------------------------------------------------------------------- class MFNType(object): """ MFN type. - `KRYLOV`: Restarted Krylov solver. - `EXPOKIT`: Implementation of the method in Expokit. See Also -------- slepc.MFNType """ KRYLOV = S_(MFNKRYLOV) EXPOKIT = S_(MFNEXPOKIT) class MFNConvergedReason(object): """ MFN convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_ITS`: Solver completed the requested number of steps. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Generic breakdown in method. See Also -------- slepc.MFNConvergedReason """ CONVERGED_TOL = MFN_CONVERGED_TOL CONVERGED_ITS = MFN_CONVERGED_ITS DIVERGED_ITS = MFN_DIVERGED_ITS DIVERGED_BREAKDOWN = MFN_DIVERGED_BREAKDOWN CONVERGED_ITERATING = MFN_CONVERGED_ITERATING ITERATING = MFN_CONVERGED_ITERATING # ----------------------------------------------------------------------------- cdef class MFN(Object): """ Matrix Function. Matrix Function (`MFN`) is the object provided by slepc4py for computing the action of a matrix function on a vector. Given a matrix :math:`A` and a vector :math:`b`, the call ``mfn.solve(b,x)`` computes :math:`x=f(A)b`, where :math:`f` is a function such as the exponential. """ Type = MFNType ConvergedReason = MFNConvergedReason def __cinit__(self): self.obj = &self.mfn self.mfn = NULL def view(self, Viewer viewer=None) -> None: """ Print the MFN data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.MFNView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( MFNView(self.mfn, vwr) ) def destroy(self) -> Self: """ Destroy the MFN object. Logically collective. See Also -------- slepc.MFNDestroy """ CHKERR( MFNDestroy(&self.mfn) ) self.mfn = NULL return self def reset(self) -> None: """ Reset the MFN object. Collective. See Also -------- slepc.MFNReset """ CHKERR( MFNReset(self.mfn) ) def create(self, comm: Comm | None = None) -> Self: """ Create the MFN object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.MFNCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcMFN newmfn = NULL CHKERR( MFNCreate(ccomm, &newmfn) ) CHKERR( SlepcCLEAR(self.obj) ); self.mfn = newmfn return self def setType(self, mfn_type: Type | str) -> None: """ Set the particular solver to be used in the MFN object. Logically collective. Parameters ---------- mfn_type The solver to be used. Notes ----- The default is ``KRYLOV``. Normally, it is best to use `setFromOptions()` and then set the MFN type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.MFNSetType """ cdef SlepcMFNType cval = NULL mfn_type = str2bytes(mfn_type, &cval) CHKERR( MFNSetType(self.mfn, cval) ) def getType(self) -> str: """ Get the MFN type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.MFNGetType """ cdef SlepcMFNType mfn_type = NULL CHKERR( MFNGetType(self.mfn, &mfn_type) ) return bytes2str(mfn_type) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all MFN options in the database. Not collective. Returns ------- str The prefix string set for this MFN object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.MFNGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( MFNGetOptionsPrefix(self.mfn, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all MFN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all MFN option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different MFN contexts, one could call:: M1.setOptionsPrefix("mfn1_") M2.setOptionsPrefix("mfn2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.MFNGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MFNSetOptionsPrefix(self.mfn, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all MFN options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all MFN option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.MFNAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MFNAppendOptionsPrefix(self.mfn, cval) ) def setFromOptions(self) -> None: """ Set MFN options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.MFNSetFromOptions """ CHKERR( MFNSetFromOptions(self.mfn) ) def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and maximum iteration count. Not collective. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.MFNGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( MFNGetTolerances(self.mfn, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """ Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default MFN convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations. See Also -------- getTolerances, slepc.MFNSetTolerances """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if max_it is not None: ival = asInt(max_it) CHKERR( MFNSetTolerances(self.mfn, rval, ival) ) def getDimensions(self) -> int: """ Get the dimension of the subspace used by the solver. Not collective. Returns ------- int Maximum dimension of the subspace to be used by the solver. See Also -------- setDimensions, slepc.MFNGetDimensions """ cdef PetscInt ival = 0 CHKERR( MFNGetDimensions(self.mfn, &ival) ) return toInt(ival) def setDimensions(self, ncv: int) -> None: """ Set the dimension of the subspace to be used by the solver. Logically collective. Parameters ---------- ncv Maximum dimension of the subspace to be used by the solver. See Also -------- getDimensions, slepc.MFNSetDimensions """ cdef PetscInt ival = asInt(ncv) CHKERR( MFNSetDimensions(self.mfn, ival) ) def getFN(self) -> FN: """ Get the math function object associated to the MFN object. Not collective. Returns ------- FN The math function context. See Also -------- setFN, slepc.MFNGetFN """ cdef FN fn = FN() CHKERR( MFNGetFN(self.mfn, &fn.fn) ) CHKERR( PetscINCREF(fn.obj) ) return fn def setFN(self, FN fn) -> None: """ Set a math function object associated to the MFN object. Collective. Parameters ---------- fn The math function context. See Also -------- getFN, slepc.MFNSetFN """ CHKERR( MFNSetFN(self.mfn, fn.fn) ) def getBV(self) -> BV: """ Get the basis vector object associated to the MFN object. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.MFNGetBV """ cdef BV bv = BV() CHKERR( MFNGetBV(self.mfn, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv) -> None: """ Set a basis vector object associated to the MFN object. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.MFNSetBV """ CHKERR( MFNSetBV(self.mfn, bv.bv) ) def getOperator(self) -> Mat: """ Get the matrix associated with the MFN object. Collective. Returns ------- petsc4py.PETSc.Mat The matrix for which the matrix function is to be computed. See Also -------- setOperator, slepc.MFNGetOperator """ cdef Mat A = Mat() CHKERR( MFNGetOperator(self.mfn, &A.mat) ) CHKERR( PetscINCREF(A.obj) ) return A def setOperator(self, Mat A) -> None: """ Set the matrix associated with the MFN object. Collective. Parameters ---------- A The problem matrix. Notes ----- This must be called before `setUp()`. If called again after `setUp()` then the `MFN` object is reset. See Also -------- getOperator, slepc.MFNSetOperator """ CHKERR( MFNSetOperator(self.mfn, A.mat) ) # def setMonitor( self, monitor: MFNMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.MFNMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( MFNMonitorSet(self.mfn, MFN_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> MFNMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- MFNMonitorFunction The list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for an `MFN` object. Logically collective. See Also -------- slepc.MFNMonitorCancel """ CHKERR( MFNMonitorCancel(self.mfn) ) self.set_attr('__monitor__', None) # def setUp(self) -> None: """ Set up all the necessary internal data structures. Collective. Set up all the internal data structures necessary for the execution of the eigensolver. See Also -------- solve, slepc.MFNSetUp """ CHKERR( MFNSetUp(self.mfn) ) def solve(self, Vec b, Vec x) -> None: """ Solve the matrix function problem. Collective. Given a vector :math:`b`, the vector :math:`x = f(A) b` is returned. Parameters ---------- b The right hand side vector. x The solution. Notes ----- The matrix :math:`A` is specified with `setOperator()`. The function :math:`f` is specified via the `FN` object obtained with `getFN()` or set with `setFN()`. See Also -------- setOperator, getFN, solveTranspose, slepc.MFNSolve """ CHKERR( MFNSolve(self.mfn, b.vec, x.vec) ) def solveTranspose(self, Vec b, Vec x) -> None: """ Solve the transpose matrix function problem. Collective. Given a vector :math:`b`, the vector :math:`x = f(A^T) b` is returned. Parameters ---------- b The right hand side vector. x The solution. Notes ----- The matrix :math:`A` is specified with `setOperator()`. The function :math:`f` is specified via the `FN` object obtained with `getFN()` or set with `setFN()`. See Also -------- setOperator, getFN, solve, slepc.MFNSolveTranspose """ CHKERR( MFNSolveTranspose(self.mfn, b.vec, x.vec) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. Get the current iteration number. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, slepc.MFNGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( MFNGetIterationNumber(self.mfn, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, setErrorIfNotConverged, slepc.MFNGetConvergedReason """ cdef SlepcMFNConvergedReason val = MFN_CONVERGED_ITERATING CHKERR( MFNGetConvergedReason(self.mfn, &val) ) return val def setErrorIfNotConverged(self, flg: bool = True) -> None: """ Set `solve()` to generate an error if the solver does not converge. Logically collective. Parameters ---------- flg ``True`` indicates you want the error generated. Notes ----- Normally SLEPc continues if the solver fails to converge, you can call `getConvergedReason()` after a `solve()` to determine if it has converged. See Also -------- getConvergedReason, solve, slepc.MFNSetErrorIfNotConverged """ cdef PetscBool tval = flg CHKERR( MFNSetErrorIfNotConverged(self.mfn, tval) ) def getErrorIfNotConverged(self) -> bool: """ Get if `solve()` generates an error if the solver does not converge. Not collective. Get a flag indicating whether `solve()` will generate an error if the solver does not converge. Returns ------- bool ``True`` indicates you want the error generated. See Also -------- setErrorIfNotConverged, slepc.MFNGetErrorIfNotConverged """ cdef PetscBool tval = PETSC_FALSE CHKERR( MFNGetErrorIfNotConverged(self.mfn, &tval) ) return toBool(tval) # property tol: """The tolerance count used by the MFN convergence tests.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count used by the MFN convergence tests.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property fn: """The math function (`FN`) object associated to the MFN object.""" def __get__(self) -> FN: return self.getFN() def __set__(self, value): self.setBV(value) property bv: """The basis vectors (`BV`) object associated to the MFN object.""" def __get__(self) -> BV: return self.getFN() def __set__(self, value): self.setBV(value) # ----------------------------------------------------------------------------- del MFNType del MFNConvergedReason # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/NEP.pyx0000644000076500000240000025414515133663436017227 0ustar00jromanstaff# ----------------------------------------------------------------------------- class NEPType(object): """ NEP type. - `RII`: Residual inverse iteration. - `SLP`: Successive linear problems. - `NARNOLDI`: Nonlinear Arnoldi. - `NLEIGS`: Fully rational Krylov method for nonlinear eigenproblems. - `CISS`: Contour integral spectrum slice. - `INTERPOL`: Polynomial interpolation. See Also -------- slepc.NEPType """ RII = S_(NEPRII) SLP = S_(NEPSLP) NARNOLDI = S_(NEPNARNOLDI) NLEIGS = S_(NEPNLEIGS) CISS = S_(NEPCISS) INTERPOL = S_(NEPINTERPOL) class NEPProblemType(object): """ NEP problem type. - `GENERAL`: General nonlinear eigenproblem. - `RATIONAL`: NEP defined in split form with all :math:`f_i` rational. See Also -------- slepc.NEPProblemType """ GENERAL = NEP_GENERAL RATIONAL = NEP_RATIONAL class NEPErrorType(object): """ NEP error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.NEPErrorType """ ABSOLUTE = NEP_ERROR_ABSOLUTE RELATIVE = NEP_ERROR_RELATIVE BACKWARD = NEP_ERROR_BACKWARD class NEPWhich(object): """ NEP desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in a region. - `USER`: User defined selection. See Also -------- slepc.NEPWhich """ LARGEST_MAGNITUDE = NEP_LARGEST_MAGNITUDE SMALLEST_MAGNITUDE = NEP_SMALLEST_MAGNITUDE LARGEST_REAL = NEP_LARGEST_REAL SMALLEST_REAL = NEP_SMALLEST_REAL LARGEST_IMAGINARY = NEP_LARGEST_IMAGINARY SMALLEST_IMAGINARY = NEP_SMALLEST_IMAGINARY TARGET_MAGNITUDE = NEP_TARGET_MAGNITUDE TARGET_REAL = NEP_TARGET_REAL TARGET_IMAGINARY = NEP_TARGET_IMAGINARY ALL = NEP_ALL USER = NEP_WHICH_USER class NEPConvergedReason(object): """ NEP convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_LINEAR_SOLVE`: Inner linear solve failed. - `DIVERGED_SUBSPACE_EXHAUSTED`: Run out of space for the basis in an unrestarted solver. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.NEPConvergedReason """ CONVERGED_TOL = NEP_CONVERGED_TOL CONVERGED_USER = NEP_CONVERGED_USER DIVERGED_ITS = NEP_DIVERGED_ITS DIVERGED_BREAKDOWN = NEP_DIVERGED_BREAKDOWN DIVERGED_LINEAR_SOLVE = NEP_DIVERGED_LINEAR_SOLVE DIVERGED_SUBSPACE_EXHAUSTED = NEP_DIVERGED_SUBSPACE_EXHAUSTED CONVERGED_ITERATING = NEP_CONVERGED_ITERATING ITERATING = NEP_CONVERGED_ITERATING class NEPRefine(object): """ NEP refinement strategy. - `NONE`: No refinement. - `SIMPLE`: Refine eigenpairs one by one. - `MULTIPLE`: Refine all eigenpairs simultaneously (invariant pair). See Also -------- slepc.NEPRefine """ NONE = NEP_REFINE_NONE SIMPLE = NEP_REFINE_SIMPLE MULTIPLE = NEP_REFINE_MULTIPLE class NEPRefineScheme(object): """ NEP scheme for solving linear systems during iterative refinement. - `SCHUR`: Schur complement. - `MBE`: Mixed block elimination. - `EXPLICIT`: Build the explicit matrix. See Also -------- slepc.NEPRefineScheme """ SCHUR = NEP_REFINE_SCHEME_SCHUR MBE = NEP_REFINE_SCHEME_MBE EXPLICIT = NEP_REFINE_SCHEME_EXPLICIT class NEPConv(object): """ NEP convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.NEPConv """ ABS = NEP_CONV_ABS REL = NEP_CONV_REL NORM = NEP_CONV_NORM USER = NEP_CONV_USER class NEPStop(object): """ NEP stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. See Also -------- slepc.NEPStop """ BASIC = NEP_STOP_BASIC USER = NEP_STOP_USER class NEPCISSExtraction(object): """ NEP CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. - `CAA`: Communication-avoiding Arnoldi. See Also -------- slepc.NEPCISSExtraction """ RITZ = NEP_CISS_EXTRACTION_RITZ HANKEL = NEP_CISS_EXTRACTION_HANKEL CAA = NEP_CISS_EXTRACTION_CAA # ----------------------------------------------------------------------------- cdef class NEP(Object): """ Nonlinear Eigenvalue Problem Solver. The Nonlinear Eigenvalue Problem (`NEP`) solver is the object provided by slepc4py for specifying an eigenvalue problem that is nonlinear with respect to the eigenvalue (not the eigenvector). This is intended for general nonlinear problems (rather than polynomial eigenproblems) described as :math:`T(\lambda) x=0`. """ Type = NEPType ProblemType = NEPProblemType ErrorType = NEPErrorType Which = NEPWhich ConvergedReason = NEPConvergedReason Refine = NEPRefine RefineScheme = NEPRefineScheme Conv = NEPConv Stop = NEPStop CISSExtraction = NEPCISSExtraction def __cinit__(self): self.obj = &self.nep self.nep = NULL def view(self, Viewer viewer=None) -> None: """ Print the NEP data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.NEPView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPView(self.nep, vwr) ) def destroy(self) -> Self: """ Destroy the NEP object. Collective. See Also -------- slepc.NEPDestroy """ CHKERR( NEPDestroy(&self.nep) ) self.nep = NULL return self def reset(self) -> None: """ Reset the NEP object. Collective. See Also -------- slepc.NEPReset """ CHKERR( NEPReset(self.nep) ) def create(self, comm: Comm | None = None) -> Self: """ Create the NEP object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.NEPCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcNEP newnep = NULL CHKERR( NEPCreate(ccomm, &newnep) ) CHKERR( SlepcCLEAR(self.obj) ); self.nep = newnep return self def setType(self, nep_type: Type | str) -> None: """ Set the particular solver to be used in the NEP object. Logically collective. Parameters ---------- nep_type The solver to be used. Notes ----- The default is `RII`. Normally, it is best to use `setFromOptions()` and then set the NEP type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.NEPSetType """ cdef SlepcNEPType cval = NULL nep_type = str2bytes(nep_type, &cval) CHKERR( NEPSetType(self.nep, cval) ) def getType(self) -> str: """ Get the NEP type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.NEPGetType """ cdef SlepcNEPType nep_type = NULL CHKERR( NEPGetType(self.nep, &nep_type) ) return bytes2str(nep_type) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all NEP options in the database. Not collective. Returns ------- str The prefix string set for this NEP object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.NEPGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( NEPGetOptionsPrefix(self.nep, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all NEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all NEP option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different NEP contexts, one could call:: N1.setOptionsPrefix("nep1_") N2.setOptionsPrefix("nep2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.NEPGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( NEPSetOptionsPrefix(self.nep, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all NEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all NEP option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.NEPAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( NEPAppendOptionsPrefix(self.nep, cval) ) def setFromOptions(self) -> None: """ Set NEP options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.NEPSetFromOptions """ CHKERR( NEPSetFromOptions(self.nep) ) def getProblemType(self) -> ProblemType: """ Get the problem type from the `NEP` object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.NEPGetProblemType """ cdef SlepcNEPProblemType val = NEP_GENERAL CHKERR( NEPGetProblemType(self.nep, &val) ) return val def setProblemType(self, problem_type: ProblemType) -> None: """ Set the type of the eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function is used to provide a hint to the `NEP` solver to exploit certain properties of the nonlinear eigenproblem. This hint may be used or not, depending on the solver. By default, no particular structure is assumed. See Also -------- getProblemType, slepc.NEPSetProblemType """ cdef SlepcNEPProblemType val = problem_type CHKERR( NEPSetProblemType(self.nep, val) ) def getWhichEigenpairs(self) -> Which: """ Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.NEPGetWhichEigenpairs """ cdef SlepcNEPWhich val = NEP_LARGEST_MAGNITUDE CHKERR( NEPGetWhichEigenpairs(self.nep, &val) ) return val def setWhichEigenpairs(self, which: Which) -> None: """ Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in NEP account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `NEP.Which.LARGEST_IMAGINARY` and `NEP.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `NEP.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `NEP.Which.ALL` is intended for use in the context of the `PEP.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- getWhichEigenpairs, setTarget, slepc.PEPSetWhichEigenpairs """ cdef SlepcNEPWhich val = which CHKERR( NEPSetWhichEigenpairs(self.nep, val) ) def getTarget(self) -> Scalar: """ Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.NEPGetTarget """ cdef PetscScalar sval = 0 CHKERR( NEPGetTarget(self.nep, &sval) ) return toScalar(sval) def setTarget(self, target: Scalar) -> None: """ Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, setWhichEigenpairs, slepc.NEPSetTarget """ cdef PetscScalar sval = asScalar(target) CHKERR( NEPSetTarget(self.nep, sval) ) def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default NEP convergence tests. Returns ------- tol: float The convergence tolerance. maxit: int The maximum number of iterations. See Also -------- setTolerances, slepc.NEPGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPGetTolerances(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, maxit: int | None = None) -> None: """ Set the tolerance and max. iteration count used in convergence tests. Logically collective. Parameters ---------- tol The convergence tolerance. maxit The maximum number of iterations. Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.NEPSetTolerances """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if maxit is not None: ival = asInt(maxit) CHKERR( NEPSetTolerances(self.nep, rval, ival) ) def getConvergenceTest(self) -> Conv: """ Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.NEPGetConvergenceTest """ cdef SlepcNEPConv conv = NEP_CONV_REL CHKERR( NEPGetConvergenceTest(self.nep, &conv) ) return conv def setConvergenceTest(self, conv: Conv) -> None: """ Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.NEPSetConvergenceTest """ cdef SlepcNEPConv tconv = conv CHKERR( NEPSetConvergenceTest(self.nep, tconv) ) def getRefine(self) -> tuple[Refine, int, float, int, RefineScheme]: """ Get the refinement strategy used by the NEP object. Not collective. Returns ------- ref: Refine The refinement type. npart: int The number of partitions of the communicator. tol: float The convergence tolerance. its: int The maximum number of refinement iterations. scheme: RefineScheme Scheme for solving linear systems. See Also -------- setRefine, slepc.NEPGetRefine """ cdef SlepcNEPRefine ref = NEP_REFINE_NONE cdef PetscInt npart = 1 cdef PetscReal tol = PETSC_DEFAULT cdef PetscInt its = PETSC_DEFAULT cdef SlepcNEPRefineScheme scheme = NEP_REFINE_SCHEME_MBE CHKERR( NEPGetRefine(self.nep, &ref, &npart, &tol, &its, &scheme) ) return (ref, toInt(npart), toReal(tol), toInt(its), scheme) def setRefine( self, ref: Refine, npart: int | None = None, tol: float | None = None, its: int | None = None, scheme: RefineScheme | None = None, ) -> None: """ Set the refinement strategy used by the NEP object. Logically collective. Set the refinement strategy used by the NEP object and the associated parameters. Parameters ---------- ref The refinement type. npart The number of partitions of the communicator. tol The convergence tolerance. its The maximum number of refinement iterations. scheme Scheme for solving linear systems. See Also -------- getRefine, slepc.NEPSetRefine """ cdef SlepcNEPRefine tref = ref cdef PetscInt tnpart = PETSC_CURRENT cdef PetscReal ttol = PETSC_CURRENT cdef PetscInt tits = PETSC_CURRENT cdef SlepcNEPRefineScheme tscheme = NEP_REFINE_SCHEME_MBE if npart is not None: tnpart = asInt(npart) if tol is not None: ttol = asReal(tol) if its is not None: tits = asInt(its) if scheme is not None: tscheme = scheme CHKERR( NEPSetRefine(self.nep, tref, tnpart, ttol, tits, tscheme) ) def getRefineKSP(self) -> KSP: """ Get the ``KSP`` object used by the eigensolver in the refinement phase. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setRefine, slepc.NEPRefineGetKSP """ cdef KSP ksp = KSP() CHKERR( NEPRefineGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def getTrackAll(self) -> bool: """ Get the flag indicating whether all residual norms must be computed. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.NEPGetTrackAll """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPGetTrackAll(self.nep, &tval) ) return toBool(tval) def setTrackAll(self, trackall: bool) -> None: """ Set if the solver must compute the residual of all approximate eigenpairs. Logically collective. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.NEPSetTrackAll """ cdef PetscBool tval = trackall CHKERR( NEPSetTrackAll(self.nep, tval) ) def getDimensions(self) -> tuple[int, int, int]: """ Get the number of eigenvalues to compute. Not collective. Get the number of eigenvalues to compute, and the dimension of the subspace. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.NEPGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( NEPGetDimensions(self.nep, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def setDimensions( self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set the number of eigenvalues to compute. Logically collective. Set the number of eigenvalues to compute and the dimension of the subspace. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.NEPSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nev is not None: ival1 = asInt(nev) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( NEPSetDimensions(self.nep, ival1, ival2, ival3) ) def getBV(self) -> BV: """ Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.NEPGetBV """ cdef BV bv = BV() CHKERR( NEPGetBV(self.nep, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv) -> None: """ Set the basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.NEPSetBV """ CHKERR( NEPSetBV(self.nep, bv.bv) ) def getRG(self) -> RG: """ Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.NEPGetRG """ cdef RG rg = RG() CHKERR( NEPGetRG(self.nep, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg) -> None: """ Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.NEPSetRG """ CHKERR( NEPSetRG(self.nep, rg.rg) ) def getDS(self) -> DS: """ Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.NEPGetDS """ cdef DS ds = DS() CHKERR( NEPGetDS(self.nep, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds) -> None: """ Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.NEPSetDS """ CHKERR( NEPSetDS(self.nep, ds.ds) ) # def setInitialSpace(self, space: Vec or list[Vec]) -> None: """ Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space The initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setUp, slepc.NEPSetInitialSpace """ if isinstance(space, Vec): space = [space] cdef PetscVec *vs = NULL cdef Py_ssize_t i = 0, ns = len(space) cdef tmp = allocate(ns*sizeof(PetscVec),&vs) for i in range(ns): vs[i] = (space[i]).vec CHKERR( NEPSetInitialSpace(self.nep, ns, vs) ) # def setStoppingTest( self, stopping: NEPStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.NEPSetStoppingTestFunction """ if stopping is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__stopping__', (stopping, args, kargs)) CHKERR( NEPSetStoppingTestFunction(self.nep, NEP_Stopping, NULL, NULL) ) else: self.set_attr('__stopping__', None) CHKERR( NEPSetStoppingTestFunction(self.nep, NEPStoppingBasic, NULL, NULL) ) def getStoppingTest(self) -> NEPStoppingFunction: """ Get the stopping test function. Not collective. Returns ------- NEPStoppingFunction The stopping test function. See Also -------- setStoppingTest """ return self.get_attr('__stopping__') def setEigenvalueComparison( self, comparison: NEPEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `NEP.Which.USER`. See Also -------- getEigenvalueComparison, slepc.NEPSetEigenvalueComparison """ if comparison is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__comparison__', (comparison, args, kargs)) ctx = self.get_attr('__comparison__') CHKERR( NEPSetEigenvalueComparison(self.nep, NEP_Comparison, ctx) ) else: self.set_attr('__comparison__', None) CHKERR( NEPSetEigenvalueComparison(self.nep, NULL, NULL) ) def getEigenvalueComparison(self) -> NEPEigenvalueComparison: """ Get the eigenvalue comparison function. Not collective. Returns ------- NEPEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison """ return self.get_attr('__comparison__') def setMonitor( self, monitor: NEPMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.NEPMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( NEPMonitorSet(self.nep, NEP_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> NEPMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- NEPMonitorFunction The list of monitor functions. See Also -------- setMonitor """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for a `NEP` object. Logically collective. See Also -------- slepc.NEPMonitorCancel """ CHKERR( NEPMonitorCancel(self.nep) ) self.set_attr('__monitor__', None) # def setUp(self) -> None: """ Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.NEPSetUp """ CHKERR( NEPSetUp(self.nep) ) def solve(self) -> None: """ Solve the nonlinear eigenproblem. Collective. Notes ----- `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, getConverged, getConvergedReason, slepc.NEPSolve """ CHKERR( NEPSolve(self.nep) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.NEPGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( NEPGetIterationNumber(self.nep, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.NEPGetConvergedReason """ cdef SlepcNEPConvergedReason val = NEP_CONVERGED_ITERATING CHKERR( NEPGetConvergedReason(self.nep, &val) ) return val def getConverged(self) -> int: """ Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.NEPGetConverged """ cdef PetscInt ival = 0 CHKERR( NEPGetConverged(self.nep, &ival) ) return toInt(ival) def getEigenpair(self, i: int, Vec Vr = None, Vec Vi = None) -> None: """ Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- complex The computed eigenvalue. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The eigenvector is normalized to have unit norm. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.NEPGetEigenpair """ cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 0 cdef PetscVec vecr = Vr.vec if Vr is not None else NULL cdef PetscVec veci = Vi.vec if Vi is not None else NULL CHKERR( NEPGetEigenpair(self.nep, i, &sval1, &sval2, vecr, veci) ) return toComplex(sval1, sval2) def getLeftEigenvector(self, i: int, Vec Wr, Vec Wi=None) -> None: """ Get the i-th left eigenvector as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Wr Placeholder for the returned eigenvector (real part). Wi Placeholder for the returned eigenvector (imaginary part). Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigensolutions are indexed according to the ordering criterion established with `setWhichEigenpairs()`. Left eigenvectors are available only if the ``twosided`` flag was set with `setTwoSided()`. See Also -------- getEigenpair, getConverged, setTwoSided, slepc.NEPGetLeftEigenvector """ cdef PetscVec vecr = Wr.vec if Wr is not None else NULL cdef PetscVec veci = Wi.vec if Wi is not None else NULL CHKERR( NEPGetLeftEigenvector(self.nep, i, vecr, veci) ) def getErrorEstimate(self, i: int) -> float: """ Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.NEPGetErrorEstimate """ cdef PetscReal rval = 0 CHKERR( NEPGetErrorEstimate(self.nep, i, &rval) ) return toReal(rval) def computeError(self, i: int, etype: ErrorType | None = None) -> float: """ Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|T(\lambda)x\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). If the computation of left eigenvectors was enabled with `setTwoSided()`, then the error will be computed using the maximum of the value above and the left residual norm :math:`\|y^*T(\lambda)\|_2`, where :math:`y` is the approximate left eigenvector. See Also -------- getErrorEstimate, setTwoSided, slepc.NEPComputeError """ cdef SlepcNEPErrorType et = NEP_ERROR_RELATIVE cdef PetscReal rval = 0 if etype is not None: et = etype CHKERR( NEPComputeError(self.nep, i, et, &rval) ) return toReal(rval) def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """ Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.NEPErrorView """ cdef SlepcNEPErrorType et = NEP_ERROR_RELATIVE if etype is not None: et = etype cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPErrorView(self.nep, et, vwr) ) def valuesView(self, viewer: Viewer | None = None) -> None: """ Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.NEPValuesView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPValuesView(self.nep, vwr) ) def vectorsView(self, viewer: Viewer | None = None) -> None: """ Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.NEPVectorsView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPVectorsView(self.nep, vwr) ) # def setFunction( self, function: NEPFunction, Mat F: petsc4py.PETSc.Mat | None = None, Mat P: petsc4py.PETSc.Mat | None = None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set the function to compute the nonlinear Function :math:`T(\lambda)`. Collective. Set the function to compute the nonlinear Function :math:`T(\lambda)` as well as the location to store the matrix. Parameters ---------- function Function evaluation routine. F Function matrix. P Preconditioner matrix (usually the same as ``F``). See Also -------- setJacobian, getFunction, slepc.NEPSetFunction """ cdef PetscMat Fmat = F.mat if F is not None else NULL cdef PetscMat Pmat = P.mat if P is not None else Fmat if function is not None: if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr('__function__', context) CHKERR( NEPSetFunction(self.nep, Fmat, Pmat, NEP_Function, context) ) else: CHKERR( NEPSetFunction(self.nep, Fmat, Pmat, NULL, NULL) ) def getFunction(self) -> tuple[petsc4py.PETSc.Mat, petsc4py.PETSc.Mat, NEPFunction]: """ Get the function to compute the nonlinear Function :math:`T(\lambda)`. Collective. Get the function to compute the nonlinear Function :math:`T(\lambda)` and the matrix. Returns ------- F: petsc4py.PETSc.Mat Function matrix. P: petsc4py.PETSc.Mat Preconditioner matrix (usually the same as the F). function: NEPFunction Function evaluation routine. See Also -------- setFunction, slepc.NEPGetFunction """ cdef Mat F = Mat() cdef Mat P = Mat() CHKERR( NEPGetFunction(self.nep, &F.mat, &P.mat, NULL, NULL) ) CHKERR( PetscINCREF(F.obj) ) CHKERR( PetscINCREF(P.obj) ) cdef object function = self.get_attr('__function__') return (F, P, function) def setJacobian( self, jacobian: NEPJacobian, Mat J: petsc4py.PETSc.Mat | None = None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set the function to compute the Jacobian :math:`T'(\lambda)`. Collective. Set the function to compute the Jacobian :math:`T'(\lambda)` as well as the location to store the matrix. Parameters ---------- jacobian Jacobian evaluation routine. J Jacobian matrix. See Also -------- setFunction, getJacobian, slepc.NEPSetJacobian """ cdef PetscMat Jmat = J.mat if J is not None else NULL if jacobian is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr('__jacobian__', context) CHKERR( NEPSetJacobian(self.nep, Jmat, NEP_Jacobian, context) ) else: CHKERR( NEPSetJacobian(self.nep, Jmat, NULL, NULL) ) def getJacobian(self) -> tuple[petsc4py.PETSc.Mat, NEPJacobian]: """ Get the function to compute the Jacobian :math:`T'(\lambda)` and J. Collective. Get the function to compute the Jacobian :math:`T'(\lambda)` and the matrix. Returns ------- J: petsc4py.PETSc.Mat Jacobian matrix. jacobian: NEPJacobian Jacobian evaluation routine. See Also -------- setJacobian, slepc.NEPGetJacobian """ cdef Mat J = Mat() CHKERR( NEPGetJacobian(self.nep, &J.mat, NULL, NULL) ) CHKERR( PetscINCREF(J.obj) ) cdef object jacobian = self.get_attr('__jacobian__') return (J, jacobian) def setSplitOperator( self, A: petsc4py.PETSc.Mat | list[petsc4py.PETSc.Mat], f: FN | list[FN], structure: petsc4py.PETSc.Mat.Structure | None = None, ) -> None: """ Set the operator of the nonlinear eigenvalue problem in split form. Collective. Parameters ---------- A Coefficient matrices of the split form. f Scalar functions of the split form. structure Structure flag for matrices. Notes ----- The nonlinear operator is written as :math:`T(\lambda) = \sum_i A_i f_i(\lambda)`, for :math:`i=1,\dots,n`. The derivative :math:`T'(\lambda)` can be obtained using the derivatives of :math:`f_i`. The ``structure`` flag provides information about :math:`A_i`'s nonzero pattern. This function must be called before `setUp()`. If it is called again after `setUp()` then the `NEP` object is reset. See Also -------- getSplitOperator, slepc.NEPSetSplitOperator """ if isinstance(A, Mat): A = [A] if isinstance(f, FN): f = [f] cdef PetscMat *As = NULL cdef SlepcFN *Fs = NULL cdef Py_ssize_t i = 0, n = len(A) cdef PetscMatStructure mstr = matstructure(structure) assert n == len(f) cdef tmp1 = allocate(n*sizeof(PetscMat),&As) cdef tmp2 = allocate(n*sizeof(SlepcFN),&Fs) for i in range(n): As[i] = (A[i]).mat Fs[i] = (f[i]).fn CHKERR( NEPSetSplitOperator(self.nep, n, As, Fs, mstr) ) def getSplitOperator(self) -> tuple[list[petsc4py.PETSc.Mat], list[FN], petsc4py.PETSc.Mat.Structure]: """ Get the operator of the nonlinear eigenvalue problem in split form. Collective. Returns ------- A: list of petsc4py.PETSc.Mat Coefficient matrices of the split form. f: list of FN Scalar functions of the split form. structure: petsc4py.PETSc.Mat.Structure Structure flag for matrices. See Also -------- setSplitOperator, slepc.NEPGetSplitOperatorInfo, slepc.NEPGetSplitOperatorTerm """ cdef Mat A cdef FN f cdef PetscMat mat = NULL cdef SlepcFN fn = NULL cdef PetscInt i=0, n=0 cdef PetscMatStructure mstr CHKERR( NEPGetSplitOperatorInfo(self.nep, &n, &mstr) ) cdef object matrices = [] cdef object functions = [] for i in range(n): CHKERR( NEPGetSplitOperatorTerm(self.nep, i, &mat, &fn) ) A = Mat(); A.mat = mat; CHKERR( PetscINCREF(A.obj) ) f = FN(); f.fn = fn; CHKERR( PetscINCREF(f.obj) ) matrices.append(A) functions.append(f) return (matrices, functions, mstr) def setSplitPreconditioner( self, P: petsc4py.PETSc.Mat | list[petsc4py.PETSc.Mat], structure: petsc4py.PETSc.Mat.Structure | None = None, ) -> None: """ Set the operator in split form. Collective. Set the operator in split form from which to build the preconditioner to be used when solving the nonlinear eigenvalue problem in split form. Parameters ---------- P Coefficient matrices of the split preconditioner. structure Structure flag for matrices. See Also -------- getSplitPreconditioner, slepc.NEPSetSplitPreconditioner """ if isinstance(P, Mat): P = [P] cdef PetscMat *Ps = NULL cdef Py_ssize_t i = 0, n = len(P) cdef PetscMatStructure mstr = matstructure(structure) cdef tmp1 = allocate(n*sizeof(PetscMat),&Ps) for i in range(n): Ps[i] = (P[i]).mat CHKERR( NEPSetSplitPreconditioner(self.nep, n, Ps, mstr) ) def getSplitPreconditioner(self) -> tuple[list[petsc4py.PETSc.Mat], petsc4py.PETSc.Mat.Structure]: """ Get the operator of the split preconditioner. Not collective. Returns ------- P: list of petsc4py.PETSc.Mat Coefficient matrices of the split preconditioner. structure: petsc4py.PETSc.Mat.Structure Structure flag for matrices. See Also -------- setSplitPreconditioner, slepc.NEPGetSplitPreconditionerTerm """ cdef Mat P cdef PetscMat mat = NULL cdef PetscInt i=0, n=0 cdef PetscMatStructure mstr CHKERR( NEPGetSplitPreconditionerInfo(self.nep, &n, &mstr) ) cdef object matrices = [] for i in range(n): CHKERR( NEPGetSplitPreconditionerTerm(self.nep, i, &mat) ) P = Mat(); P.mat = mat; CHKERR( PetscINCREF(P.obj) ) matrices.append(P) return (matrices, mstr) def getTwoSided(self) -> bool: """ Get the flag indicating if a two-sided variant is being used. Not collective. Get the flag indicating whether a two-sided variant of the algorithm is being used or not. Returns ------- bool Whether the two-sided variant is to be used or not. See Also -------- setTwoSided, slepc.NEPGetTwoSided """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPGetTwoSided(self.nep, &tval) ) return toBool(tval) def setTwoSided(self, twosided: bool) -> None: """ Set the solver to use a two-sided variant. Logically collective. Set the solver to use a two-sided variant so that left eigenvectors are also computed. Parameters ---------- twosided Whether the two-sided variant is to be used or not. Notes ----- If the user sets ``twosided`` to ``True`` then the solver uses a variant of the algorithm that computes both right and left eigenvectors. This is usually much more costly. This option is not available in all solvers. When using two-sided solvers, the problem matrices must have both the ``Mat.mult`` and ``Mat.multTranspose`` operations defined. See Also -------- getTwoSided, getLeftEigenvector, slepc.NEPSetTwoSided """ cdef PetscBool tval = asBool(twosided) CHKERR( NEPSetTwoSided(self.nep, tval) ) def applyResolvent( self, omega: Scalar, Vec v, Vec r, RG rg = None, ) -> None: """ Apply the resolvent :math:`T^{-1}(z)` to a given vector. Collective. Parameters ---------- omega Value where the resolvent must be evaluated. v Input vector. r Placeholder for the result vector. rg Region. Notes ----- The resolvent :math:`T^{-1}(z)=\sum_i(z-\lambda_i)^{-1}x_iy_i^*` is evaluated at :math:`z=\omega` and the matrix-vector product :math:`r = T^{-1}(\omega) v` is computed. Vectors :math:`x_i,y_i` are right and left eigenvectors, respectively, normalized so that :math:`y_i^*T'(\lambda_i)x_i=1`. The sum contains only eigenvectors that have been previously computed with `solve()`, and if a region ``rg`` is given then only those corresponding to eigenvalues inside the region are considered. See Also -------- solve, getLeftEigenvector, slepc.NEPApplyResolvent """ cdef PetscScalar sval = asScalar(omega) cdef SlepcRG region = rg.rg if rg is not None else NULL CHKERR( NEPApplyResolvent(self.nep, region, sval, v.vec, r.vec) ) # def setRIILagPreconditioner(self, lag: int) -> None: """ Set when the preconditioner is rebuilt in the nonlinear solve. Logically collective. Parameters ---------- lag 0 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within the nonlinear iteration, 2 means every second time the Jacobian is built, etc. See Also -------- getRIILagPreconditioner, slepc.NEPRIISetLagPreconditioner """ cdef PetscInt ival = asInt(lag) CHKERR( NEPRIISetLagPreconditioner(self.nep, ival) ) def getRIILagPreconditioner(self) -> int: """ Get how often the preconditioner is rebuilt. Not collective. Returns ------- int The lag parameter. See Also -------- setRIILagPreconditioner, slepc.NEPRIIGetLagPreconditioner """ cdef PetscInt ival = 0 CHKERR( NEPRIIGetLagPreconditioner(self.nep, &ival) ) return toInt(ival) def setRIIConstCorrectionTol(self, cct: bool) -> None: """ Set a flag to keep the tolerance used in the linear solver constant. Logically collective. Parameters ---------- cct If ``True``, the `petsc4py.PETSc.KSP` relative tolerance is constant. Notes ----- By default, an exponentially decreasing tolerance is set in the ``KSP`` used within the nonlinear iteration, so that each Newton iteration requests better accuracy than the previous one. The constant correction tolerance flag stops this behavior. See Also -------- getRIIConstCorrectionTol, slepc.NEPRIISetConstCorrectionTol """ cdef PetscBool val = asBool(cct) CHKERR( NEPRIISetConstCorrectionTol(self.nep, val) ) def getRIIConstCorrectionTol(self) -> bool: """ Get the constant tolerance flag. Not collective. Returns ------- bool If ``True``, the `petsc4py.PETSc.KSP` relative tolerance is constant. See Also -------- setRIIConstCorrectionTol, slepc.NEPRIIGetConstCorrectionTol """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPRIIGetConstCorrectionTol(self.nep, &tval) ) return toBool(tval) def setRIIMaximumIterations(self, its: int) -> None: """ Set the max. number of inner iterations to be used in the RII solver. Logically collective. These are the Newton iterations related to the computation of the nonlinear Rayleigh functional. Parameters ---------- its Maximum inner iterations. See Also -------- getRIIMaximumIterations, slepc.NEPRIISetMaximumIterations """ cdef PetscInt ival = asInt(its) CHKERR( NEPRIISetMaximumIterations(self.nep, ival) ) def getRIIMaximumIterations(self) -> int: """ Get the maximum number of inner iterations of RII. Not collective. Returns ------- int Maximum inner iterations. See Also -------- setRIIMaximumIterations, slepc.NEPRIIGetMaximumIterations """ cdef PetscInt ival = 0 CHKERR( NEPRIIGetMaximumIterations(self.nep, &ival) ) return toInt(ival) def setRIIHermitian(self, herm: bool) -> None: """ Set a flag to use the Hermitian version of the solver. Logically collective. Set a flag to indicate if the Hermitian version of the scalar nonlinear equation must be used by the solver. Parameters ---------- herm If ``True``, the Hermitian version is used. Notes ----- By default, the scalar nonlinear equation :math:`x^*T(\sigma)^{-1}T(z)x=0` is solved at each step of the nonlinear iteration. When this flag is set the simpler form :math:`x^*T(z)x=0` is used, which is supposed to be valid only for Hermitian problems. See Also -------- getRIIHermitian, slepc.NEPRIISetHermitian """ cdef PetscBool val = asBool(herm) CHKERR( NEPRIISetHermitian(self.nep, val) ) def getRIIHermitian(self) -> bool: """ Get if the Hermitian version must be used by the solver. Not collective. Returns ------- bool If ``True``, the Hermitian version is used. See Also -------- setRIIHermitian, slepc.NEPRIIGetHermitian """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPRIIGetHermitian(self.nep, &tval) ) return toBool(tval) def setRIIDeflationThreshold(self, deftol: float) -> None: """ Set the threshold used to switch between deflated and non-deflated. Logically collective. Set the threshold value used to switch between deflated and non-deflated iteration. Parameters ---------- deftol The threshold value. Notes ----- Normally, the solver iterates on the extended problem in order to deflate previously converged eigenpairs. If this threshold is set to a nonzero value, then once the residual error is below this threshold the solver will continue the iteration without deflation. The intention is to be able to improve the current eigenpair further, despite having previous eigenpairs with somewhat bad precision. See Also -------- getRIIDeflationThreshold, slepc.NEPRIISetDeflationThreshold """ cdef PetscReal val = asReal(deftol) CHKERR( NEPRIISetDeflationThreshold(self.nep, val) ) def getRIIDeflationThreshold(self) -> float: """ Get the threshold value that controls deflation. Not collective. Returns ------- float The threshold value. See Also -------- setRIIDeflationThreshold, slepc.NEPRIIGetDeflationThreshold """ cdef PetscReal rval = 0.0 CHKERR( NEPRIIGetDeflationThreshold(self.nep, &rval) ) return toReal(rval) def setRIIKSP(self, KSP ksp) -> None: """ Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getRIIKSP, slepc.NEPRIISetKSP """ CHKERR( NEPRIISetKSP(self.nep, ksp.ksp) ) def getRIIKSP(self) -> KSP: """ Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setRIIKSP, slepc.NEPRIIGetKSP """ cdef KSP ksp = KSP() CHKERR( NEPRIIGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setSLPDeflationThreshold(self, deftol: float) -> None: """ Set the threshold used to switch between deflated and non-deflated. Logically collective. Parameters ---------- deftol The threshold value. Notes ----- Normally, the solver iterates on the extended problem in order to deflate previously converged eigenpairs. If this threshold is set to a nonzero value, then once the residual error is below this threshold the solver will continue the iteration without deflation. The intention is to be able to improve the current eigenpair further, despite having previous eigenpairs with somewhat bad precision. See Also -------- getSLPDeflationThreshold, slepc.NEPSLPSetDeflationThreshold """ cdef PetscReal val = asReal(deftol) CHKERR( NEPSLPSetDeflationThreshold(self.nep, val) ) def getSLPDeflationThreshold(self) -> float: """ Get the threshold value that controls deflation. Not collective. Returns ------- float The threshold value. See Also -------- setSLPDeflationThreshold, slepc.NEPSLPGetDeflationThreshold """ cdef PetscReal rval = 0.0 CHKERR( NEPSLPGetDeflationThreshold(self.nep, &rval) ) return toReal(rval) def setSLPEPS(self, EPS eps) -> None: """ Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getSLPEPS, slepc.NEPSLPSetEPS """ CHKERR( NEPSLPSetEPS(self.nep, eps.eps) ) def getSLPEPS(self) -> EPS: """ Get the linear eigensolver object associated with the nonlinear eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setSLPEPS, slepc.NEPSLPGetEPS """ cdef EPS eps = EPS() CHKERR( NEPSLPGetEPS(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setSLPEPSLeft(self, EPS eps) -> None: """ Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Used to compute left eigenvectors in the two-sided variant of SLP. Parameters ---------- eps The linear eigensolver. See Also -------- setTwoSided, setSLPEPS, getSLPEPSLeft, slepc.NEPSLPSetEPSLeft """ CHKERR( NEPSLPSetEPSLeft(self.nep, eps.eps) ) def getSLPEPSLeft(self) -> EPS: """ Get the left eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setSLPEPSLeft, slepc.NEPSLPGetEPSLeft """ cdef EPS eps = EPS() CHKERR( NEPSLPGetEPSLeft(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setSLPKSP(self, KSP ksp) -> None: """ Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getSLPKSP, slepc.NEPSLPSetKSP """ CHKERR( NEPSLPSetKSP(self.nep, ksp.ksp) ) def getSLPKSP(self) -> KSP: """ Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setSLPKSP, slepc.NEPSLPGetKSP """ cdef KSP ksp = KSP() CHKERR( NEPSLPGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setNArnoldiKSP(self, KSP ksp) -> None: """ Set a linear solver object associated to the nonlinear eigensolver. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getNArnoldiKSP, slepc.NEPNArnoldiSetKSP """ CHKERR( NEPNArnoldiSetKSP(self.nep, ksp.ksp) ) def getNArnoldiKSP(self) -> KSP: """ Get the linear solver object associated with the nonlinear eigensolver. Collective. Returns ------- petsc4py.PETSc.KSP The linear solver object. See Also -------- setNArnoldiKSP, slepc.NEPNArnoldiGetKSP """ cdef KSP ksp = KSP() CHKERR( NEPNArnoldiGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setNArnoldiLagPreconditioner(self, lag: int) -> None: """ Set when the preconditioner is rebuilt in the nonlinear solve. Logically collective. Parameters ---------- lag 0 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within the nonlinear iteration, 2 means every second time the Jacobian is built, etc. Notes ----- The default is 1. The preconditioner is ALWAYS built in the first iteration of a nonlinear solve. See Also -------- getNArnoldiLagPreconditioner, slepc.NEPNArnoldiSetLagPreconditioner """ cdef PetscInt ival = asInt(lag) CHKERR( NEPNArnoldiSetLagPreconditioner(self.nep, ival) ) def getNArnoldiLagPreconditioner(self) -> int: """ Get how often the preconditioner is rebuilt. Not collective. Returns ------- int The lag parameter. See Also -------- setNArnoldiLagPreconditioner, slepc.NEPNArnoldiGetLagPreconditioner """ cdef PetscInt ival = 0 CHKERR( NEPNArnoldiGetLagPreconditioner(self.nep, &ival) ) return toInt(ival) # def setInterpolPEP(self, PEP pep) -> None: """ Set a polynomial eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- pep The polynomial eigensolver. See Also -------- getInterpolPEP, slepc.NEPInterpolSetPEP """ CHKERR( NEPInterpolSetPEP(self.nep, pep.pep) ) def getInterpolPEP(self) -> PEP: """ Get the associated polynomial eigensolver object. Collective. Returns ------- PEP The polynomial eigensolver. See Also -------- setInterpolPEP, slepc.NEPInterpolGetPEP """ cdef PEP pep = PEP() CHKERR( NEPInterpolGetPEP(self.nep, &pep.pep) ) CHKERR( PetscINCREF(pep.obj) ) return pep def setInterpolInterpolation(self, tol: float | None = None, deg: int | None = None) -> None: """ Set the tolerance and maximum degree for the interpolation polynomial. Collective. Parameters ---------- tol The tolerance to stop computing polynomial coefficients. deg The maximum degree of interpolation. See Also -------- getInterpolInterpolation, slepc.NEPInterpolSetInterpolation """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if deg is not None: ival = asInt(deg) CHKERR( NEPInterpolSetInterpolation(self.nep, rval, ival) ) def getInterpolInterpolation(self) -> tuple[float, int]: """ Get the tolerance and maximum degree for the interpolation polynomial. Not collective. Returns ------- tol: float The tolerance to stop computing polynomial coefficients. deg: int The maximum degree of interpolation. See Also -------- setInterpolInterpolation, slepc.NEPInterpolGetInterpolation """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPInterpolGetInterpolation(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) # def setNLEIGSRestart(self, keep: float) -> None: """ Set the restart parameter for the NLEIGS method. Logically collective. The proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getNLEIGSRestart, slepc.NEPNLEIGSSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( NEPNLEIGSSetRestart(self.nep, val) ) def getNLEIGSRestart(self) -> float: """ Get the restart parameter used in the NLEIGS method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setNLEIGSRestart, slepc.NEPNLEIGSGetRestart """ cdef PetscReal val = 0 CHKERR( NEPNLEIGSGetRestart(self.nep, &val) ) return toReal(val) def setNLEIGSLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking variants of the NLEIGS method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getNLEIGSLocking, slepc.NEPNLEIGSSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( NEPNLEIGSSetLocking(self.nep, val) ) def getNLEIGSLocking(self) -> bool: """ Get the locking flag used in the NLEIGS method. Not collective. Returns ------- bool The locking flag. See Also -------- setNLEIGSLocking, slepc.NEPNLEIGSGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPNLEIGSGetLocking(self.nep, &tval) ) return toBool(tval) def setNLEIGSInterpolation(self, tol: float | None = None, deg: int | None = None) -> None: """ Set the tolerance and maximum degree for the interpolation polynomial. Collective. Set the tolerance and maximum degree when building the interpolation via divided differences. Parameters ---------- tol The tolerance to stop computing divided differences. deg The maximum degree of interpolation. See Also -------- getNLEIGSInterpolation, slepc.NEPNLEIGSSetInterpolation """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if deg is not None: ival = asInt(deg) CHKERR( NEPNLEIGSSetInterpolation(self.nep, rval, ival) ) def getNLEIGSInterpolation(self) -> tuple[float, int]: """ Get the tolerance and maximum degree for the interpolation polynomial. Not collective. Get the tolerance and maximum degree when building the interpolation via divided differences. Returns ------- tol: float The tolerance to stop computing divided differences. deg: int The maximum degree of interpolation. See Also -------- setNLEIGSInterpolation, slepc.NEPNLEIGSGetInterpolation """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPNLEIGSGetInterpolation(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setNLEIGSFullBasis(self, fullbasis: bool = True) -> None: """ Set TOAR-basis (default) or full-basis variants of the NLEIGS method. Logically collective. Toggle between TOAR-basis (default) and full-basis variants of the NLEIGS method. Parameters ---------- fullbasis ``True`` if the full-basis variant must be selected. Notes ----- The default is to use a compact representation of the Krylov basis, that is, :math:`V = (I \otimes U) S`, with a `BV` of type `TENSOR`. This behavior can be changed so that the full basis :math:`V` is explicitly stored and operated with. This variant is more expensive in terms of memory and computation, but is necessary in some cases, particularly for two-sided computations, see `setTwoSided()`. In the full-basis variant, the NLEIGS solver uses an `EPS` object to explicitly solve the linearized eigenproblem, see `getNLEIGSEPS()`. See Also -------- setTwoSided, getNLEIGSFullBasis, getNLEIGSEPS, slepc.NEPNLEIGSSetFullBasis """ cdef PetscBool val = asBool(fullbasis) CHKERR( NEPNLEIGSSetFullBasis(self.nep, val) ) def getNLEIGSFullBasis(self) -> bool: """ Get the flag that indicates if NLEIGS is using the full-basis variant. Not collective. Returns ------- bool ``True`` if the full-basis variant is selected. See Also -------- setNLEIGSFullBasis, slepc.NEPNLEIGSGetFullBasis """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPNLEIGSGetFullBasis(self.nep, &tval) ) return toBool(tval) def setNLEIGSEPS(self, EPS eps) -> None: """ Set a linear eigensolver object associated to the nonlinear eigensolver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getNLEIGSEPS, slepc.NEPNLEIGSSetEPS """ CHKERR( NEPNLEIGSSetEPS(self.nep, eps.eps) ) def getNLEIGSEPS(self) -> EPS: """ Get the linear eigensolver object associated with the nonlinear eigensolver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setNLEIGSEPS, slepc.NEPNLEIGSGetEPS """ cdef EPS eps = EPS() CHKERR( NEPNLEIGSGetEPS(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setNLEIGSRKShifts(self, shifts: Sequence[Scalar]) -> None: """ Set a list of shifts to be used in the Rational Krylov method. Collective. Parameters ---------- shifts Values specifying the shifts. Notes ----- If only one shift is provided, the built subspace is equivalent to shift-and-invert Krylov-Schur (provided that the absolute convergence criterion is used). Otherwise, the rational Krylov variant is run. See Also -------- getNLEIGSRKShifts, getNLEIGSKSPs, slepc.NEPNLEIGSSetRKShifts """ cdef PetscInt na = 0 cdef PetscScalar *a = NULL cdef object tmp1 = iarray_s(shifts, &na, &a) CHKERR( NEPNLEIGSSetRKShifts(self.nep, na, a) ) def getNLEIGSRKShifts(self) -> ArrayScalar: """ Get the list of shifts used in the Rational Krylov method. Not collective. Returns ------- ArrayScalar The shift values. See Also -------- setNLEIGSRKShifts, slepc.NEPNLEIGSGetRKShifts """ cdef PetscInt np = 0 cdef PetscScalar *coeff = NULL CHKERR( NEPNLEIGSGetRKShifts(self.nep, &np, &coeff) ) cdef object ocoeff = None try: ocoeff = array_s(np, coeff) finally: CHKERR( PetscFree(coeff) ) return ocoeff def getNLEIGSKSPs(self) -> list[KSP]: """ Get the list of linear solver objects associated with the NLEIGS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of shifts provided by the user, or 1 if the user did not provide shifts. See Also -------- setNLEIGSRKShifts, slepc.NEPNLEIGSGetKSPs """ cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL CHKERR( NEPNLEIGSGetKSPs(self.nep, &n, &p) ) return [ref_KSP(p[i]) for i from 0 <= i None: """ Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.NEPCISSSetExtraction """ cdef SlepcNEPCISSExtraction val = extraction CHKERR( NEPCISSSetExtraction(self.nep, val) ) def getCISSExtraction(self) -> CISSExtraction: """ Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.NEPCISSGetExtraction """ cdef SlepcNEPCISSExtraction val = NEP_CISS_EXTRACTION_RITZ CHKERR( NEPCISSGetExtraction(self.nep, &val) ) return val def setCISSSizes( self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False, ) -> None: """ Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `NEP` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.NEPCISSSetSizes """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT cdef PetscInt ival4 = PETSC_CURRENT cdef PetscInt ival5 = PETSC_CURRENT cdef PetscBool bval = asBool(realmats) if ip is not None: ival1 = asInt(ip) if bs is not None: ival2 = asInt(bs) if ms is not None: ival3 = asInt(ms) if npart is not None: ival4 = asInt(npart) if bsmax is not None: ival5 = asInt(bsmax) CHKERR( NEPCISSSetSizes(self.nep, ival1, ival2, ival3, ival4, ival5, bval) ) def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """ Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.NEPCISSGetSizes """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 cdef PetscInt ival4 = 0 cdef PetscInt ival5 = 0 cdef PetscBool bval = PETSC_FALSE CHKERR( NEPCISSGetSizes(self.nep, &ival1, &ival2, &ival3, &ival4, &ival5, &bval) ) return (toInt(ival1), toInt(ival2), toInt(ival3), toInt(ival4), toInt(ival5), toBool(bval)) def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """ Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.NEPCISSSetThreshold """ cdef PetscReal rval1 = PETSC_CURRENT cdef PetscReal rval2 = PETSC_CURRENT if delta is not None: rval1 = asReal(delta) if spur is not None: rval2 = asReal(spur) CHKERR( NEPCISSSetThreshold(self.nep, rval1, rval2) ) def getCISSThreshold(self) -> tuple[float, float]: """ Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.NEPCISSGetThreshold """ cdef PetscReal delta = 0 cdef PetscReal spur = 0 CHKERR( NEPCISSGetThreshold(self.nep, &delta, &spur) ) return (toReal(delta), toReal(spur)) def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """ Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.NEPCISSSetRefinement """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if inner is not None: ival1 = asInt(inner) if blsize is not None: ival2 = asInt(blsize) CHKERR( NEPCISSSetRefinement(self.nep, ival1, ival2) ) def getCISSRefinement(self) -> tuple[int, int]: """ Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.NEPCISSGetRefinement """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( NEPCISSGetRefinement(self.nep, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def getCISSKSPs(self) -> list[KSP]: """ Get the list of linear solver objects associated with the CISS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.NEPCISSGetKSPs """ cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL CHKERR( NEPCISSGetKSPs(self.nep, &n, &p) ) return [ref_KSP(p[i]) for i from 0 <= i NEPProblemType: return self.getProblemType() def __set__(self, value): self.setProblemType(value) property which: """The portion of the spectrum to be sought.""" def __get__(self) -> NEPWhich: return self.getWhichEigenpairs() def __set__(self, value): self.setWhichEigenpairs(value) property target: """The value of the target.""" def __get__(self) -> float: return self.getTarget() def __set__(self, value): self.setTarget(value) property tol: """The tolerance used by the NEP convergence tests.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count used by the NEP convergence tests.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property track_all: """Compute the residual of all approximate eigenpairs.""" def __get__(self) -> bool: return self.getTrackAll() def __set__(self, value): self.setTrackAll(value) property bv: """The basis vectors (`BV`) object associated.""" def __get__(self) -> BV: return self.getBV() def __set__(self, value): self.setBV(value) property rg: """The region (`RG`) object associated.""" def __get__(self) -> RG: return self.getRG() def __set__(self, value): self.setRG(value) property ds: """The direct solver (`DS`) object associated.""" def __get__(self) -> DS: return self.getDS() def __set__(self, value): self.setDS(value) # ----------------------------------------------------------------------------- del NEPType del NEPProblemType del NEPErrorType del NEPWhich del NEPConvergedReason del NEPRefine del NEPRefineScheme del NEPConv del NEPStop del NEPCISSExtraction # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/PEP.pyx0000644000076500000240000025017215133663436017225 0ustar00jromanstaff# ----------------------------------------------------------------------------- class PEPType(object): """ PEP type. - `TOAR`: Two-level orthogonal Arnoldi. - `STOAR`: Symmetric TOAR. - `QARNOLDI`: Q-Arnoldi for quadratic problems. - `LINEAR`: Linearization via EPS. - `JD`: Polynomial Jacobi-Davidson. - `CISS`: Contour integral spectrum slice. See Also -------- slepc.PEPType """ TOAR = S_(PEPTOAR) STOAR = S_(PEPSTOAR) QARNOLDI = S_(PEPQARNOLDI) LINEAR = S_(PEPLINEAR) JD = S_(PEPJD) CISS = S_(PEPCISS) class PEPProblemType(object): """ PEP problem type. - `GENERAL`: No structure. - `HERMITIAN`: Hermitian structure. - `HYPERBOLIC`: QEP with Hermitian matrices, :math:`M>0`, :math:`(x^TCx)^2 > 4(x^TMx)(x^TKx)`. - `GYROSCOPIC`: QEP with :math:`M`, :math:`K` Hermitian, :math:`M>0`, :math:`C` skew-Hermitian. See Also -------- slepc.PEPProblemType """ GENERAL = PEP_GENERAL HERMITIAN = PEP_HERMITIAN HYPERBOLIC = PEP_HYPERBOLIC GYROSCOPIC = PEP_GYROSCOPIC class PEPWhich(object): """ PEP desired part of spectrum. - `LARGEST_MAGNITUDE`: Largest magnitude (default). - `SMALLEST_MAGNITUDE`: Smallest magnitude. - `LARGEST_REAL`: Largest real parts. - `SMALLEST_REAL`: Smallest real parts. - `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude. - `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude. - `TARGET_MAGNITUDE`: Closest to target (in magnitude). - `TARGET_REAL`: Real part closest to target. - `TARGET_IMAGINARY`: Imaginary part closest to target. - `ALL`: All eigenvalues in an interval. - `USER`: User-defined criterion. See Also -------- slepc.PEPWhich """ LARGEST_MAGNITUDE = PEP_LARGEST_MAGNITUDE SMALLEST_MAGNITUDE = PEP_SMALLEST_MAGNITUDE LARGEST_REAL = PEP_LARGEST_REAL SMALLEST_REAL = PEP_SMALLEST_REAL LARGEST_IMAGINARY = PEP_LARGEST_IMAGINARY SMALLEST_IMAGINARY = PEP_SMALLEST_IMAGINARY TARGET_MAGNITUDE = PEP_TARGET_MAGNITUDE TARGET_REAL = PEP_TARGET_REAL TARGET_IMAGINARY = PEP_TARGET_IMAGINARY ALL = PEP_ALL USER = PEP_WHICH_USER class PEPBasis(object): """ PEP basis type for the representation of the polynomial. - `MONOMIAL`: Monomials (default). - `CHEBYSHEV1`: Chebyshev polynomials of the 1st kind. - `CHEBYSHEV2`: Chebyshev polynomials of the 2nd kind. - `LEGENDRE`: Legendre polynomials. - `LAGUERRE`: Laguerre polynomials. - `HERMITE`: Hermite polynomials. See Also -------- slepc.PEPBasis """ MONOMIAL = PEP_BASIS_MONOMIAL CHEBYSHEV1 = PEP_BASIS_CHEBYSHEV1 CHEBYSHEV2 = PEP_BASIS_CHEBYSHEV2 LEGENDRE = PEP_BASIS_LEGENDRE LAGUERRE = PEP_BASIS_LAGUERRE HERMITE = PEP_BASIS_HERMITE class PEPScale(object): """ PEP scaling strategy. - `NONE`: No scaling. - `SCALAR`: Parameter scaling. - `DIAGONAL`: Diagonal scaling. - `BOTH`: Both parameter and diagonal scaling. See Also -------- slepc.PEPScale """ NONE = PEP_SCALE_NONE SCALAR = PEP_SCALE_SCALAR DIAGONAL = PEP_SCALE_DIAGONAL BOTH = PEP_SCALE_BOTH class PEPRefine(object): """ PEP refinement strategy. - `NONE`: No refinement. - `SIMPLE`: Refine eigenpairs one by one. - `MULTIPLE`: Refine all eigenpairs simultaneously (invariant pair). See Also -------- slepc.PEPRefine """ NONE = PEP_REFINE_NONE SIMPLE = PEP_REFINE_SIMPLE MULTIPLE = PEP_REFINE_MULTIPLE class PEPRefineScheme(object): """ PEP scheme for solving linear systems during iterative refinement. - `SCHUR`: Schur complement. - `MBE`: Mixed block elimination. - `EXPLICIT`: Build the explicit matrix. See Also -------- slepc.PEPRefineScheme """ SCHUR = PEP_REFINE_SCHEME_SCHUR MBE = PEP_REFINE_SCHEME_MBE EXPLICIT = PEP_REFINE_SCHEME_EXPLICIT class PEPExtract(object): """ PEP extraction strategy used. PEP extraction strategy used to obtain eigenvectors of the PEP from the eigenvectors of the linearization. - `NONE`: Use the first block. - `NORM`: Use the first or last block depending on norm of H. - `RESIDUAL`: Use the block with smallest residual. - `STRUCTURED`: Combine all blocks in a certain way. See Also -------- slepc.PEPExtract """ NONE = PEP_EXTRACT_NONE NORM = PEP_EXTRACT_NORM RESIDUAL = PEP_EXTRACT_RESIDUAL STRUCTURED = PEP_EXTRACT_STRUCTURED class PEPErrorType(object): """ PEP error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `BACKWARD`: Backward error. See Also -------- slepc.PEPErrorType """ ABSOLUTE = PEP_ERROR_ABSOLUTE RELATIVE = PEP_ERROR_RELATIVE BACKWARD = PEP_ERROR_BACKWARD class PEPConv(object): """ PEP convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the eigenvalue. - `NORM`: Convergence test relative to the matrix norms. - `USER`: User-defined convergence test. See Also -------- slepc.PEPConv """ ABS = PEP_CONV_ABS REL = PEP_CONV_REL NORM = PEP_CONV_NORM USER = PEP_CONV_USER class PEPStop(object): """ PEP stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. See Also -------- slepc.PEPStop """ BASIC = PEP_STOP_BASIC USER = PEP_STOP_USER class PEPConvergedReason(object): """ PEP convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Lanczos-type method could not preserve symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.PEPConvergedReason """ CONVERGED_TOL = PEP_CONVERGED_TOL CONVERGED_USER = PEP_CONVERGED_USER DIVERGED_ITS = PEP_DIVERGED_ITS DIVERGED_BREAKDOWN = PEP_DIVERGED_BREAKDOWN DIVERGED_SYMMETRY_LOST = PEP_DIVERGED_SYMMETRY_LOST CONVERGED_ITERATING = PEP_CONVERGED_ITERATING ITERATING = PEP_CONVERGED_ITERATING class PEPJDProjection(object): """ PEP type of projection to be used in the Jacobi-Davidson solver. - `HARMONIC`: Harmonic projection. - `ORTHOGONAL`: Orthogonal projection. See Also -------- slepc.PEPJDProjection """ HARMONIC = PEP_JD_PROJECTION_HARMONIC ORTHOGONAL = PEP_JD_PROJECTION_ORTHOGONAL class PEPCISSExtraction(object): """ PEP CISS extraction technique. - `RITZ`: Ritz extraction. - `HANKEL`: Extraction via Hankel eigenproblem. - `CAA`: Communication-avoiding Arnoldi. See Also -------- slepc.PEPCISSExtraction """ RITZ = PEP_CISS_EXTRACTION_RITZ HANKEL = PEP_CISS_EXTRACTION_HANKEL CAA = PEP_CISS_EXTRACTION_CAA # ----------------------------------------------------------------------------- cdef class PEP(Object): """ Polynomial Eigenvalue Problem Solver. The Polynomial Eigenvalue Problem (`PEP`) solver is the object provided by slepc4py for specifying a polynomial eigenvalue problem. Apart from the specific solvers for this type of problems, there is an `EPS`-based solver, i.e., it uses a solver from `EPS` to solve a generalized eigenproblem obtained after linearization. """ Type = PEPType ProblemType = PEPProblemType Which = PEPWhich Basis = PEPBasis Scale = PEPScale Refine = PEPRefine RefineScheme = PEPRefineScheme Extract = PEPExtract ErrorType = PEPErrorType Conv = PEPConv Stop = PEPStop ConvergedReason = PEPConvergedReason JDProjection = PEPJDProjection CISSExtraction = PEPCISSExtraction def __cinit__(self): self.obj = &self.pep self.pep = NULL def view(self, Viewer viewer=None) -> None: """ Print the PEP data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.PEPView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPView(self.pep, vwr) ) def destroy(self) -> Self: """ Destroy the PEP object. Collective. See Also -------- slepc.PEPDestroy """ CHKERR( PEPDestroy(&self.pep) ) self.pep = NULL return self def reset(self) -> None: """ Reset the PEP object. Collective. See Also -------- slepc.PEPReset """ CHKERR( PEPReset(self.pep) ) def create(self, comm: Comm | None = None) -> Self: """ Create the PEP object. Collective. Parameters ---------- comm MPI communicator. If not provided, it defaults to all processes. See Also -------- slepc.PEPCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcPEP newpep = NULL CHKERR( PEPCreate(ccomm, &newpep) ) CHKERR( SlepcCLEAR(self.obj) ); self.pep = newpep return self def setType(self, pep_type: Type | str) -> None: """ Set the particular solver to be used in the PEP object. Logically collective. Parameters ---------- pep_type The solver to be used. Notes ----- The default is `TOAR`. Normally, it is best to use `setFromOptions()` and then set the PEP type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.PEPSetType """ cdef SlepcPEPType cval = NULL pep_type = str2bytes(pep_type, &cval) CHKERR( PEPSetType(self.pep, cval) ) def getType(self) -> str: """ Get the PEP type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.PEPGetType """ cdef SlepcPEPType pep_type = NULL CHKERR( PEPGetType(self.pep, &pep_type) ) return bytes2str(pep_type) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all PEP options in the database. Not collective. Returns ------- str The prefix string set for this PEP object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.PEPGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( PEPGetOptionsPrefix(self.pep, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all PEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all PEP option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different PEP contexts, one could call:: P1.setOptionsPrefix("pep1_") P2.setOptionsPrefix("pep2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.PEPGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PEPSetOptionsPrefix(self.pep, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all PEP options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all PEP option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.PEPAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PEPAppendOptionsPrefix(self.pep, cval) ) def setFromOptions(self) -> None: """ Set PEP options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.PEPSetFromOptions """ CHKERR( PEPSetFromOptions(self.pep) ) def getBasis(self) -> Basis: """ Get the type of polynomial basis used. Not collective. Returns ------- Basis The basis that was previously set. See Also -------- setBasis, slepc.PEPGetBasis """ cdef SlepcPEPBasis val = PEP_BASIS_MONOMIAL CHKERR( PEPGetBasis(self.pep, &val) ) return val def setBasis(self, basis: Basis) -> None: """ Set the type of polynomial basis used. Logically collective. Set the type of polynomial basis used to describe the polynomial eigenvalue problem. Parameters ---------- basis The basis to be set. Notes ----- By default, the coefficient matrices passed via `setOperators()` are expressed in the monomial basis, i.e. :math:`P(\lambda)=A_0+\lambda A_1+\lambda^2 A_2+\dots+\lambda^d A_d`. Other polynomial bases may have better numerical behavior, but the user must then pass the coefficient matrices accordingly. See Also -------- getBasis, setOperators, slepc.PEPSetBasis """ cdef SlepcPEPBasis val = basis CHKERR( PEPSetBasis(self.pep, val) ) def getProblemType(self) -> ProblemType: """ Get the problem type from the PEP object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.PEPGetProblemType """ cdef SlepcPEPProblemType val = PEP_GENERAL CHKERR( PEPGetProblemType(self.pep, &val) ) return val def setProblemType(self, problem_type: ProblemType) -> None: """ Set the type of the polynomial eigenvalue problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- This function is used to instruct SLEPc to exploit certain structure in the polynomial eigenproblem. By default, no particular structure is assumed. If the problem matrices are Hermitian (symmetric in the real case) or Hermitian/skew-Hermitian then the solver can exploit this fact to perform less operations or provide better stability. Hyperbolic problems are a particular case of Hermitian problems, some solvers may treat them simply as Hermitian. See Also -------- setOperators, setType, getProblemType, slepc.PEPSetProblemType """ cdef SlepcPEPProblemType val = problem_type CHKERR( PEPSetProblemType(self.pep, val) ) def getWhichEigenpairs(self) -> Which: """ Get which portion of the spectrum is to be sought. Not collective. Returns ------- Which The portion of the spectrum to be sought by the solver. See Also -------- setWhichEigenpairs, slepc.PEPGetWhichEigenpairs """ cdef SlepcPEPWhich val = PEP_LARGEST_MAGNITUDE CHKERR( PEPGetWhichEigenpairs(self.pep, &val) ) return val def setWhichEigenpairs(self, which: Which) -> None: """ Set which portion of the spectrum is to be sought. Logically collective. Parameters ---------- which The portion of the spectrum to be sought by the solver. Notes ----- Not all eigensolvers implemented in PEP account for all the possible values. Also, some values make sense only for certain types of problems. If SLEPc is compiled for real numbers `PEP.Which.LARGEST_IMAGINARY` and `PEP.Which.SMALLEST_IMAGINARY` use the absolute value of the imaginary part for eigenvalue selection. The target is a scalar value provided with `setTarget()`. The criterion `PEP.Which.TARGET_IMAGINARY` is available only in case PETSc and SLEPc have been built with complex scalars. `PEP.Which.ALL` is intended for use in combination with an interval (see `setInterval()`), when all eigenvalues within the interval are requested, or in the context of the `PEP.Type.CISS` solver for computing all eigenvalues in a region. See Also -------- getWhichEigenpairs, setTarget, setInterval, slepc.PEPSetWhichEigenpairs """ cdef SlepcPEPWhich val = which CHKERR( PEPSetWhichEigenpairs(self.pep, val) ) def getTarget(self) -> Scalar: """ Get the value of the target. Not collective. Returns ------- Scalar The value of the target. Notes ----- If the target was not set by the user, then zero is returned. See Also -------- setTarget, slepc.PEPGetTarget """ cdef PetscScalar sval = 0 CHKERR( PEPGetTarget(self.pep, &sval) ) return toScalar(sval) def setTarget(self, target: Scalar) -> None: """ Set the value of the target. Logically collective. Parameters ---------- target The value of the target. Notes ----- The target is a scalar value used to determine the portion of the spectrum of interest. It is used in combination with `setWhichEigenpairs()`. When PETSc is built with real scalars, it is not possible to specify a complex target. See Also -------- getTarget, setWhichEigenpairs, slepc.PEPSetTarget """ cdef PetscScalar sval = asScalar(target) CHKERR( PEPSetTarget(self.pep, sval) ) def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default PEP convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.PEPGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( PEPGetTolerances(self.pep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """ Set the tolerance and maximum iteration count. Logically collective. Set the tolerance and maximum iteration count used by the default PEP convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.PEPSetTolerances """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if max_it is not None: ival = asInt(max_it) CHKERR( PEPSetTolerances(self.pep, rval, ival) ) def getInterval(self) -> tuple[float, float]: """ Get the computational interval for spectrum slicing. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. Notes ----- If the interval was not set by the user, then zeros are returned. See Also -------- setInterval, slepc.PEPGetInterval """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( PEPGetInterval(self.pep, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setInterval(self, inta: float, intb: float) -> None: """ Set the computational interval for spectrum slicing. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- Spectrum slicing is a technique employed for computing all eigenvalues of symmetric quadratic eigenproblems in a given interval. This function provides the interval to be considered. It must be used in combination with `PEP.Which.ALL`, see `setWhichEigenpairs()`. Note that in polynomial eigenproblems spectrum slicing is implemented in `STOAR` only. See Also -------- getInterval, slepc.PEPSetInterval """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( PEPSetInterval(self.pep, rval1, rval2) ) def getConvergenceTest(self) -> Conv: """ Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.PEPGetConvergenceTest """ cdef SlepcPEPConv conv = PEP_CONV_REL CHKERR( PEPGetConvergenceTest(self.pep, &conv) ) return conv def setConvergenceTest(self, conv: Conv) -> None: """ Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.PEPSetConvergenceTest """ cdef SlepcPEPConv tconv = conv CHKERR( PEPSetConvergenceTest(self.pep, tconv) ) def getRefine(self) -> tuple[Refine, int, float, int, RefineScheme]: """ Get the refinement strategy used by the PEP object. Not collective. Returns ------- ref: Refine The refinement type. npart: int The number of partitions of the communicator. tol: float The convergence tolerance. its: int The maximum number of refinement iterations. scheme: RefineScheme Scheme for solving linear systems. See Also -------- setRefine, slepc.PEPGetRefine """ cdef SlepcPEPRefine ref = PEP_REFINE_NONE cdef PetscInt npart = 1 cdef PetscReal tol = PETSC_DEFAULT cdef PetscInt its = PETSC_DEFAULT cdef SlepcPEPRefineScheme scheme = PEP_REFINE_SCHEME_MBE CHKERR( PEPGetRefine(self.pep, &ref, &npart, &tol, &its, &scheme) ) return (ref, toInt(npart), toReal(tol), toInt(its), scheme) def setRefine( self, ref: Refine, npart: int | None = None, tol: float | None = None, its: int | None = None, scheme: RefineScheme | None = None, ) -> None: """ Set the refinement strategy used by the PEP object. Logically collective. Set the refinement strategy used by the PEP object, and the associated parameters. Parameters ---------- ref The refinement type. npart The number of partitions of the communicator. tol The convergence tolerance. its The maximum number of refinement iterations. scheme Scheme for solving linear systems. See Also -------- getRefine, slepc.PEPSetRefine """ cdef SlepcPEPRefine tref = ref cdef PetscInt tnpart = PETSC_CURRENT cdef PetscReal ttol = PETSC_CURRENT cdef PetscInt tits = PETSC_CURRENT cdef SlepcPEPRefineScheme tscheme = PEP_REFINE_SCHEME_MBE if npart is not None: tnpart = asInt(npart) if tol is not None: ttol = asReal(tol) if its is not None: tits = asInt(its) if scheme is not None: tscheme = scheme CHKERR( PEPSetRefine(self.pep, tref, tnpart, ttol, tits, tscheme) ) def getRefineKSP(self) -> KSP: """ Get the ``KSP`` object used by the eigensolver in the refinement phase. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setRefine, slepc.PEPRefineGetKSP """ cdef KSP ksp = KSP() CHKERR( PEPRefineGetKSP(self.pep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setExtract(self, extract: Extract) -> None: """ Set the extraction strategy to be used. Logically collective. Parameters ---------- extract The extraction strategy. Notes ----- This is relevant for solvers based on linearization. Once the solver has converged, the polynomial eigenvectors can be extracted from the eigenvectors of the linearized problem in different ways. See Also -------- getExtract, slepc.PEPSetExtract """ cdef SlepcPEPExtract val = extract CHKERR( PEPSetExtract(self.pep, val) ) def getExtract(self) -> Extract: """ Get the extraction technique used by the `PEP` object. Not collective. Returns ------- Extract The extraction strategy. See Also -------- setExtract, slepc.PEPGetExtract """ cdef SlepcPEPExtract val = PEP_EXTRACT_NONE CHKERR( PEPGetExtract(self.pep, &val) ) return val def getTrackAll(self) -> bool: """ Get the flag indicating whether all residual norms must be computed. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.PEPGetTrackAll """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPGetTrackAll(self.pep, &tval) ) return toBool(tval) def setTrackAll(self, trackall: bool) -> None: """ Set flag to compute the residual of all approximate eigenpairs. Logically collective. Set if the solver must compute the residual of all approximate eigenpairs or not. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.PEPSetTrackAll """ cdef PetscBool tval = trackall CHKERR( PEPSetTrackAll(self.pep, tval) ) def getDimensions(self) -> tuple[int, int, int]: """ Get the number of eigenvalues to compute and the dimension of the subspace. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.PEPGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( PEPGetDimensions(self.pep, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def setDimensions( self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set the number of eigenvalues to compute and the dimension of the subspace. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nev`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nev``). + In cases where ``nev`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nev`` and (``nev`` + ``mpd``), typically ``ncv`` = ``nev`` + ``mpd``. If ``nev`` is not too large, ``mpd`` = ``nev`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.PEPSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nev is not None: ival1 = asInt(nev) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( PEPSetDimensions(self.pep, ival1, ival2, ival3) ) def getST(self) -> ST: """ Get the spectral transformation object associated to the eigensolver. Not collective. Returns ------- ST The spectral transformation. See Also -------- setST, slepc.PEPGetST """ cdef ST st = ST() CHKERR( PEPGetST(self.pep, &st.st) ) CHKERR( PetscINCREF(st.obj) ) return st def setST(self, ST st) -> None: """ Set a spectral transformation object associated to the eigensolver. Collective. Parameters ---------- st The spectral transformation. See Also -------- getST, slepc.PEPSetST """ CHKERR( PEPSetST(self.pep, st.st) ) def getScale( self, Vec Dl: petsc4py.PETSc.Vec | None = None, Vec Dr: petsc4py.PETSc.Vec | None = None ) -> tuple[Scale, float, int, float]: """ Get the strategy used for scaling the polynomial eigenproblem. Not collective. Parameters ---------- Dl Placeholder for the returned left diagonal matrix. Dr Placeholder for the returned right diagonal matrix. Returns ------- scale: Scale The scaling strategy. alpha: float The scaling factor. its: int The number of iterations of diagonal scaling. lbda: float Approximation of the wanted eigenvalues (modulus). See Also -------- setScale, slepc.PEPGetScale """ cdef SlepcPEPScale scale = PEP_SCALE_NONE cdef PetscReal alpha = 0 cdef PetscInt its = 0 cdef PetscReal lbda = 0 cdef PetscVec vecl = NULL cdef PetscVec vecr = NULL CHKERR( PEPGetScale(self.pep, &scale, &alpha, &vecl, &vecr, &its, &lbda) ) if Dl.vec != NULL: if vecl != NULL: CHKERR( VecCopy(vecl, Dl.vec) ) else: CHKERR( VecSet(Dl.vec, 1.0) ) if Dr.vec != NULL: if vecr != NULL: CHKERR( VecCopy(vecr, Dr.vec) ) else: CHKERR( VecSet(Dr.vec, 1.0) ) CHKERR( VecDestroy(&vecl) ) CHKERR( VecDestroy(&vecr) ) return (scale, toReal(alpha), toInt(its), toReal(lbda)) def setScale( self, scale: Scale, alpha: float | None = None, Vec Dl: petsc4py.PETSc.Vec | None = None, Vec Dr: petsc4py.PETSc.Vec | None = None, its: int | None = None, lbda: float | None = None, ) -> None: """ Set the scaling strategy to be used. Collective. Parameters ---------- scale The scaling strategy. alpha The scaling factor. Dl The left diagonal matrix. Dr The right diagonal matrix. its The number of iterations of diagonal scaling. lbda Approximation of the wanted eigenvalues (modulus). See Also -------- getScale, slepc.PEPSetScale """ cdef SlepcPEPScale senum = scale cdef PetscReal rval1 = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT cdef PetscReal rval2 = PETSC_CURRENT cdef PetscVec vecl = NULL cdef PetscVec vecr = NULL if alpha is not None: rval1 = asReal(alpha) if Dl is not None: vecl = Dl.vec if Dr is not None: vecr = Dr.vec if its is not None: ival = asInt(its) if lbda is not None: rval2 = asReal(lbda) CHKERR( PEPSetScale(self.pep, senum, rval1, vecl, vecr, ival, rval2) ) def getBV(self) -> BV: """ Get the basis vectors object associated to the eigensolver. Not collective. Returns ------- BV The basis vectors context. See Also -------- setBV, slepc.PEPGetBV """ cdef BV bv = BV() CHKERR( PEPGetBV(self.pep, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv) -> None: """ Set a basis vectors object associated to the eigensolver. Collective. Parameters ---------- bv The basis vectors context. See Also -------- getBV, slepc.PEPSetBV """ CHKERR( PEPSetBV(self.pep, bv.bv) ) def getRG(self) -> RG: """ Get the region object associated to the eigensolver. Not collective. Returns ------- RG The region context. See Also -------- setRG, slepc.PEPGetRG """ cdef RG rg = RG() CHKERR( PEPGetRG(self.pep, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg) -> None: """ Set a region object associated to the eigensolver. Collective. Parameters ---------- rg The region context. See Also -------- getRG, slepc.PEPSetRG """ CHKERR( PEPSetRG(self.pep, rg.rg) ) def getDS(self) -> DS: """ Get the direct solver associated to the eigensolver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.PEPGetDS """ cdef DS ds = DS() CHKERR( PEPGetDS(self.pep, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds) -> None: """ Set a direct solver object associated to the eigensolver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.PEPSetDS """ CHKERR( PEPSetDS(self.pep, ds.ds) ) def getOperators(self) -> list[Mat]: """ Get the matrices associated with the eigenvalue problem. Collective. Returns ------- list of petsc4py.PETSc.Mat The matrices associated with the eigensystem. See Also -------- setOperators, slepc.PEPGetOperators """ cdef Mat A cdef PetscMat mat = NULL cdef PetscInt k=0, n=0 CHKERR( PEPGetNumMatrices(self.pep, &n) ) cdef object operators = [] for k from 0 <= k < n: CHKERR( PEPGetOperators(self.pep, k, &mat) ) A = Mat(); A.mat = mat; CHKERR( PetscINCREF(A.obj) ) operators.append(A) return tuple(operators) def setOperators(self, operators: list[Mat]) -> None: """ Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- operators The matrices associated with the eigensystem. Notes ----- The polynomial eigenproblem is defined as :math:`P(\lambda)x=0`, where :math:`\lambda` is the eigenvalue, :math:`x` is the eigenvector, and :math:`P` is defined as :math:`P(\lambda) = A_0 + \lambda A_1 + \dots + \lambda^d A_d`, with :math:`d` = ``nmat``-1 (the degree of :math:`P`). For non-monomial bases, this expression is different. See Also -------- getOperators, slepc.PEPSetOperators """ operators = tuple(operators) cdef PetscMat *mats = NULL cdef Py_ssize_t k=0, n = len(operators) cdef tmp = allocate(n*sizeof(PetscMat),&mats) for k from 0 <= k < n: mats[k] = (operators[k]).mat CHKERR( PEPSetOperators(self.pep, n, mats) ) # def setInitialSpace(self, space: Vec | list[Vec]) -> None: """ Set the initial space from which the eigensolver starts to iterate. Collective. Parameters ---------- space The initial space. Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, only the first vector is taken into account and the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial space should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted eigenspace. Then, convergence may be faster. See Also -------- setUp, slepc.PEPSetInitialSpace """ if isinstance(space, Vec): space = [space] cdef PetscVec *vs = NULL cdef Py_ssize_t i = 0, ns = len(space) cdef tmp = allocate(ns*sizeof(PetscVec),&vs) for i in range(ns): vs[i] = (space[i]).vec CHKERR( PEPSetInitialSpace(self.pep, ns, vs) ) # def setStoppingTest( self, stopping: PEPStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.PEPSetStoppingTestFunction """ if stopping is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__stopping__', (stopping, args, kargs)) CHKERR( PEPSetStoppingTestFunction(self.pep, PEP_Stopping, NULL, NULL) ) else: self.set_attr('__stopping__', None) CHKERR( PEPSetStoppingTestFunction(self.pep, PEPStoppingBasic, NULL, NULL) ) def getStoppingTest(self) -> PEPStoppingFunction: """ Get the stopping test function. Not collective. Returns ------- PEPStoppingFunction The stopping test function. See Also -------- setStoppingTest """ return self.get_attr('__stopping__') def setEigenvalueComparison( self, comparison: PEPEigenvalueComparison | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set an eigenvalue comparison function. Logically collective. Notes ----- This eigenvalue comparison function is used when `setWhichEigenpairs()` is set to `PEP.Which.USER`. See Also -------- getEigenvalueComparison, slepc.PEPSetEigenvalueComparison """ if comparison is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__comparison__', (comparison, args, kargs)) ctx = self.get_attr('__comparison__') CHKERR( PEPSetEigenvalueComparison(self.pep, PEP_Comparison, ctx) ) else: self.set_attr('__comparison__', None) CHKERR( PEPSetEigenvalueComparison(self.pep, NULL, NULL) ) def getEigenvalueComparison(self) -> PEPEigenvalueComparison: """ Get the eigenvalue comparison function. Not collective. Returns ------- PEPEigenvalueComparison The eigenvalue comparison function. See Also -------- setEigenvalueComparison """ return self.get_attr('__comparison__') def setMonitor( self, monitor: PEPMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.PEPMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( PEPMonitorSet(self.pep, PEP_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> PEPMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- PEPMonitorFunction The list of monitor functions. See Also -------- setMonitor """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for a `PEP` object. Logically collective. See Also -------- slepc.PEPMonitorCancel """ CHKERR( PEPMonitorCancel(self.pep) ) self.set_attr('__monitor__', None) # def setUp(self) -> None: """ Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the eigensolver. This includes the setup of the internal `ST` object. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.PEPSetUp """ CHKERR( PEPSetUp(self.pep) ) def solve(self) -> None: """ Solve the polynomial eigenproblem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.PEPSolve """ CHKERR( PEPSolve(self.pep) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.PEPGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( PEPGetIterationNumber(self.pep, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.PEPGetConvergedReason """ cdef SlepcPEPConvergedReason val = PEP_CONVERGED_ITERATING CHKERR( PEPGetConvergedReason(self.pep, &val) ) return val def getConverged(self) -> int: """ Get the number of converged eigenpairs. Not collective. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nev``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getEigenpair, slepc.PEPGetConverged """ cdef PetscInt ival = 0 CHKERR( PEPGetConverged(self.pep, &ival) ) return toInt(ival) def getEigenpair(self, i: int, Vec Vr = None, Vec Vi = None) -> complex: """ Get the i-th solution of the eigenproblem as computed by `solve()`. Collective. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i Index of the solution to be obtained. Vr Placeholder for the returned eigenvector (real part). Vi Placeholder for the returned eigenvector (imaginary part). Returns ------- complex The computed eigenvalue. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). Eigenpairs are indexed according to the ordering criterion established with `setWhichEigenpairs()`. The eigenvector is normalized to have unit norm. See Also -------- solve, getConverged, setWhichEigenpairs, slepc.PEPGetEigenpair """ cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 0 cdef PetscVec vecr = Vr.vec if Vr is not None else NULL cdef PetscVec veci = Vi.vec if Vi is not None else NULL CHKERR( PEPGetEigenpair(self.pep, i, &sval1, &sval2, vecr, veci) ) return toComplex(sval1, sval2) def getErrorEstimate(self, i: int) -> float: """ Get the error estimate associated to the i-th computed eigenpair. Not collective. Parameters ---------- i Index of the solution to be considered. Returns ------- float Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. See Also -------- computeError, slepc.PEPGetErrorEstimate """ cdef PetscReal rval = 0 CHKERR( PEPGetErrorEstimate(self.pep, i, &rval) ) return toReal(rval) def computeError(self, i: int, etype: ErrorType | None = None) -> float: """ Compute the error associated with the i-th computed eigenpair. Collective. Compute the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\|P(\lambda)x\|_2` where :math:`\lambda` is the eigenvalue and :math:`x` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). See Also -------- getErrorEstimate, slepc.PEPComputeError """ cdef SlepcPEPErrorType et = PEP_ERROR_BACKWARD cdef PetscReal rval = 0 if etype is not None: et = etype CHKERR( PEPComputeError(self.pep, i, et, &rval) ) return toReal(rval) def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """ Display the errors associated with the computed solution. Collective. Display the errors and the eigenvalues. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all eigenpairs and prints the eigenvalues if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with eigenvalues and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.PEPErrorView """ cdef SlepcPEPErrorType et = PEP_ERROR_RELATIVE if etype is not None: et = etype cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPErrorView(self.pep, et, vwr) ) def valuesView(self, viewer: Viewer | None = None) -> None: """ Display the computed eigenvalues in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.PEPValuesView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPValuesView(self.pep, vwr) ) def vectorsView(self, viewer: Viewer | None = None) -> None: """ Output computed eigenvectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.PEPVectorsView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPVectorsView(self.pep, vwr) ) # def setLinearEPS(self, EPS eps) -> None: """ Set an eigensolver object associated to the polynomial eigenvalue solver. Collective. Parameters ---------- eps The linear eigensolver. See Also -------- getLinearEPS, slepc.PEPLinearSetEPS """ CHKERR( PEPLinearSetEPS(self.pep, eps.eps) ) def getLinearEPS(self) -> EPS: """ Get the eigensolver object associated to the polynomial eigenvalue solver. Collective. Returns ------- EPS The linear eigensolver. See Also -------- setLinearEPS, slepc.PEPLinearGetEPS """ cdef EPS eps = EPS() CHKERR( PEPLinearGetEPS(self.pep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setLinearLinearization(self, alpha: float = 1.0, beta: float = 0.0) -> None: """ Set the coefficients that define the linearization of a quadratic eigenproblem. Logically collective. Parameters ---------- alpha First parameter of the linearization. beta Second parameter of the linearization. See Also -------- getLinearLinearization, slepc.PEPLinearSetLinearization """ cdef PetscReal a = asReal(alpha) cdef PetscReal b = asReal(beta) CHKERR( PEPLinearSetLinearization(self.pep, a, b) ) def getLinearLinearization(self) -> tuple[float, float]: """ Get the coeffs. defining the linearization of a quadratic eigenproblem. Not collective. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. See Also -------- setLinearLinearization, slepc.PEPLinearGetLinearization """ cdef PetscReal a = 0.0 cdef PetscReal b = 0.0 CHKERR( PEPLinearGetLinearization(self.pep, &a, &b) ) return (asReal(a), asReal(b)) def setLinearExplicitMatrix(self, flag: bool) -> None: """ Set flag to explicitly build the matrices for the linearization. Logically collective. Parameters ---------- flag Boolean flag indicating if the matrices are built explicitly. See Also -------- getLinearExplicitMatrix, slepc.PEPLinearSetExplicitMatrix """ cdef PetscBool sval = asBool(flag) CHKERR( PEPLinearSetExplicitMatrix(self.pep, sval) ) def getLinearExplicitMatrix(self) -> bool: """ Get if the matrices for the linearization are built explicitly. Not collective. Returns ------- bool Boolean flag indicating if the matrices are built explicitly. See Also -------- getLinearExplicitMatrix, slepc.PEPLinearSetExplicitMatrix """ cdef PetscBool sval = PETSC_FALSE CHKERR( PEPLinearGetExplicitMatrix(self.pep, &sval) ) return toBool(sval) # def setQArnoldiRestart(self, keep: float) -> None: """ Set the restart parameter for the Q-Arnoldi method. Logically collective. Set the restart parameter for the Q-Arnoldi method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getQArnoldiRestart, slepc.PEPQArnoldiSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( PEPQArnoldiSetRestart(self.pep, val) ) def getQArnoldiRestart(self) -> float: """ Get the restart parameter used in the Q-Arnoldi method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setQArnoldiRestart, slepc.PEPQArnoldiGetRestart """ cdef PetscReal val = 0 CHKERR( PEPQArnoldiGetRestart(self.pep, &val) ) return toReal(val) def setQArnoldiLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking variants of the Q-Arnoldi method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getQArnoldiLocking, slepc.PEPQArnoldiSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( PEPQArnoldiSetLocking(self.pep, val) ) def getQArnoldiLocking(self) -> bool: """ Get the locking flag used in the Q-Arnoldi method. Not collective. Returns ------- bool The locking flag. See Also -------- setQArnoldiLocking, slepc.PEPQArnoldiGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPQArnoldiGetLocking(self.pep, &tval) ) return toBool(tval) # def setTOARRestart(self, keep: float) -> None: """ Set the restart parameter for the TOAR method. Logically collective. Set the restart parameter for the TOAR method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getTOARRestart, slepc.PEPTOARSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( PEPTOARSetRestart(self.pep, val) ) def getTOARRestart(self) -> float: """ Get the restart parameter used in the TOAR method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setTOARRestart, slepc.PEPTOARGetRestart """ cdef PetscReal val = 0 CHKERR( PEPTOARGetRestart(self.pep, &val) ) return toReal(val) def setTOARLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking variants of the TOAR method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getTOARLocking, slepc.PEPTOARSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( PEPTOARSetLocking(self.pep, val) ) def getTOARLocking(self) -> bool: """ Get the locking flag used in the TOAR method. Not collective. Returns ------- bool The locking flag. See Also -------- setTOARLocking, slepc.PEPTOARGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPTOARGetLocking(self.pep, &tval) ) return toBool(tval) # def setSTOARLinearization(self, alpha: float = 1.0, beta: float = 0.0) -> None: """ Set the coefficients that define the linearization of a quadratic eigenproblem. Logically collective. Parameters ---------- alpha First parameter of the linearization. beta Second parameter of the linearization. See Also -------- getSTOARLinearization, slepc.PEPSTOARSetLinearization """ cdef PetscReal a = asReal(alpha) cdef PetscReal b = asReal(beta) CHKERR( PEPSTOARSetLinearization(self.pep, a, b) ) def getSTOARLinearization(self) -> tuple[float, float]: """ Get the coefficients that define the linearization of a quadratic eigenproblem. Not collective. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. See Also -------- setSTOARLinearization, slepc.PEPSTOARGetLinearization """ cdef PetscReal a = 0.0 cdef PetscReal b = 0.0 CHKERR( PEPSTOARGetLinearization(self.pep, &a, &b) ) return (asReal(a), asReal(b)) def setSTOARLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking variants of the STOAR method. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getSTOARLocking, slepc.PEPSTOARSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( PEPSTOARSetLocking(self.pep, val) ) def getSTOARLocking(self) -> bool: """ Get the locking flag used in the STOAR method. Not collective. Returns ------- bool The locking flag. See Also -------- setSTOARLocking, slepc.PEPSTOARGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPSTOARGetLocking(self.pep, &tval) ) return toBool(tval) def setSTOARDetectZeros(self, detect: bool) -> None: """ Set flag to enforce detection of zeros during the factorizations. Logically collective. Set a flag to enforce detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect ``True`` if zeros must checked for. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. A zero in the factorization indicates that a shift coincides with an eigenvalue. This flag is turned off by default, and may be necessary in some cases. This feature currently requires an external package for factorizations with support for zero detection, e.g. MUMPS. See Also -------- setInterval, getSTOARDetectZeros, slepc.PEPSTOARSetDetectZeros """ cdef PetscBool val = asBool(detect) CHKERR( PEPSTOARSetDetectZeros(self.pep, val) ) def getSTOARDetectZeros(self) -> bool: """ Get the flag that enforces zero detection in spectrum slicing. Not collective. Returns ------- bool The zero detection flag. See Also -------- setSTOARDetectZeros, slepc.PEPSTOARGetDetectZeros """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPSTOARGetDetectZeros(self.pep, &tval) ) return toBool(tval) def setSTOARDimensions( self, nev: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set the dimensions used for each subsolve step. Logically collective. Parameters ---------- nev Number of eigenvalues to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. The meaning of the parameters is the same as in `setDimensions()`, but the ones here apply to every subsolve done by the child `PEP` object. See Also -------- setInterval, setDimensions, getSTOARDimensions, slepc.PEPSTOARSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nev is not None: ival1 = asInt(nev) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( PEPSTOARSetDimensions(self.pep, ival1, ival2, ival3) ) def getSTOARDimensions(self) -> tuple[int, int, int]: """ Get the dimensions used for each subsolve step. Not collective. Returns ------- nev: int Number of eigenvalues to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setSTOARDimensions, slepc.PEPSTOARGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( PEPSTOARGetDimensions(self.pep, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def getSTOARInertias(self) -> tuple[ArrayReal, ArrayInt]: """ Get the values of the shifts and their corresponding inertias. Not collective. Get the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: ArrayReal The values of the shifts used internally in the solver. inertias: ArrayInt The values of the inertia in each shift. Notes ----- This call makes sense only for spectrum slicing runs, that is, when an interval has been given with `setInterval()` and `SINVERT` is set. If called after `solve()`, all shifts used internally by the solver are returned (including both endpoints and any intermediate ones). If called before `solve()` and after `setUp()` then only the information of the endpoints of subintervals is available. See Also -------- setInterval, slepc.PEPSTOARGetInertias """ cdef PetscReal *shiftsarray = NULL cdef PetscInt *inertiasarray = NULL cdef PetscInt n = 0 CHKERR(PEPSTOARGetInertias(self.pep, &n, &shiftsarray, &inertiasarray)) cdef object shifts = None cdef object inertias = None try: shifts = array_r(n, shiftsarray) inertias = array_i(n, inertiasarray) finally: CHKERR( PetscFree(shiftsarray) ) CHKERR( PetscFree(inertiasarray) ) return (shifts, inertias) def setSTOARCheckEigenvalueType(self, flag: bool) -> None: """ Set flag to check if all eigenvalues have the same definite type. Logically collective. Set a flag to check that all the eigenvalues obtained throughout the spectrum slicing computation have the same definite type. Parameters ---------- flag Whether the eigenvalue type is checked or not. Notes ----- This option is relevant only for spectrum slicing computations, but is ignored in `slepc4py.SLEPc.PEP.ProblemType.HYPERBOLIC` problems. This flag is turned on by default, to guarantee that the computed eigenvalues have the same type (otherwise the computed solution might be wrong). But since the check is computationally quite expensive, the check may be turned off if the user knows for sure that all eigenvalues in the requested interval have the same type. See Also -------- getSTOARCheckEigenvalueType, slepc.PEPSTOARSetCheckEigenvalueType """ cdef PetscBool sval = asBool(flag) CHKERR( PEPSTOARSetCheckEigenvalueType(self.pep, sval) ) def getSTOARCheckEigenvalueType(self) -> bool: """ Get the flag for the eigenvalue type check in spectrum slicing. Not collective. Returns ------- bool Whether the eigenvalue type is checked or not. See Also -------- setSTOARCheckEigenvalueType, slepc.PEPSTOARGetCheckEigenvalueType """ cdef PetscBool sval = PETSC_FALSE CHKERR( PEPSTOARGetCheckEigenvalueType(self.pep, &sval) ) return toBool(sval) # def setJDRestart(self, keep: float) -> None: """ Set the restart parameter for the Jacobi-Davidson method. Logically collective. Set the restart parameter for the Jacobi-Davidson method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getJDRestart, slepc.PEPJDSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( PEPJDSetRestart(self.pep, val) ) def getJDRestart(self) -> float: """ Get the restart parameter used in the Jacobi-Davidson method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setJDRestart, slepc.PEPJDGetRestart """ cdef PetscReal val = 0 CHKERR( PEPJDGetRestart(self.pep, &val) ) return toReal(val) def setJDFix(self, fix: float) -> None: """ Set the threshold for changing the target in the correction equation. Logically collective. Parameters ---------- fix Threshold for changing the target. Notes ----- The target in the correction equation is fixed at the first iterations. When the norm of the residual vector is lower than the fix value, the target is set to the corresponding eigenvalue. See Also -------- getJDFix, slepc.PEPJDSetFix """ cdef PetscReal val = asReal(fix) CHKERR( PEPJDSetFix(self.pep, val) ) def getJDFix(self) -> float: """ Get threshold for changing the target in the correction equation. Not collective. Returns ------- float The threshold for changing the target. See Also -------- setJDFix, slepc.PEPJDGetFix """ cdef PetscReal val = 0 CHKERR( PEPJDGetFix(self.pep, &val) ) return toReal(val) def setJDReusePreconditioner(self, flag: bool) -> None: """ Set a flag indicating whether the preconditioner must be reused or not. Logically collective. Parameters ---------- flag The reuse flag. Notes ----- The default value is ``False``. If set to ``True``, the preconditioner is built only at the beginning, using the target value. Otherwise, it may be rebuilt (depending on the ``fix`` parameter) at each iteration from the Ritz value. See Also -------- setJDFix, getJDReusePreconditioner, slepc.PEPJDSetReusePreconditioner """ cdef PetscBool bval = asBool(flag) CHKERR( PEPJDSetReusePreconditioner(self.pep, bval) ) def getJDReusePreconditioner(self) -> bool: """ Get the flag for reusing the preconditioner. Not collective. Returns ------- bool The reuse flag. See Also -------- setJDReusePreconditioner, slepc.PEPJDGetReusePreconditioner """ cdef PetscBool bval = PETSC_FALSE CHKERR( PEPJDGetReusePreconditioner(self.pep, &bval) ) return toBool(bval) def setJDMinimalityIndex(self, flag: int) -> None: """ Set the maximum allowed value for the minimality index. Logically collective. Parameters ---------- flag The maximum minimality index. Notes ----- The default value is equal to the degree of the polynomial. A smaller value can be used if the wanted eigenvectors are known to be linearly independent. See Also -------- getJDMinimalityIndex, slepc.PEPJDSetMinimalityIndex """ cdef PetscInt ival = asInt(flag) CHKERR( PEPJDSetMinimalityIndex(self.pep, ival) ) def getJDMinimalityIndex(self) -> int: """ Get the maximum allowed value of the minimality index. Not collective. Returns ------- int The maximum minimality index. See Also -------- setJDMinimalityIndex, slepc.PEPJDGetMinimalityIndex """ cdef PetscInt ival = 1 CHKERR( PEPJDGetMinimalityIndex(self.pep, &ival) ) return toInt(ival) def setJDProjection(self, proj: JDProjection) -> None: """ Set the type of projection to be used in the Jacobi-Davidson solver. Logically collective. Parameters ---------- proj The type of projection. See Also -------- getJDProjection, slepc.PEPJDSetProjection """ cdef SlepcPEPJDProjection val = proj CHKERR( PEPJDSetProjection(self.pep, val) ) def getJDProjection(self) -> JDProjection: """ Get the type of projection to be used in the Jacobi-Davidson solver. Not collective. Returns ------- JDProjection The type of projection. See Also -------- setJDProjection, slepc.PEPJDGetProjection """ cdef SlepcPEPJDProjection val = PEP_JD_PROJECTION_HARMONIC CHKERR( PEPJDGetProjection(self.pep, &val) ) return val # def setCISSExtraction(self, extraction: CISSExtraction) -> None: """ Set the extraction technique used in the CISS solver. Logically collective. Parameters ---------- extraction The extraction technique. See Also -------- getCISSExtraction, slepc.PEPCISSSetExtraction """ cdef SlepcPEPCISSExtraction val = extraction CHKERR( PEPCISSSetExtraction(self.pep, val) ) def getCISSExtraction(self) -> CISSExtraction: """ Get the extraction technique used in the CISS solver. Not collective. Returns ------- CISSExtraction The extraction technique. See Also -------- setCISSExtraction, slepc.PEPCISSGetExtraction """ cdef SlepcPEPCISSExtraction val = PEP_CISS_EXTRACTION_RITZ CHKERR( PEPCISSGetExtraction(self.pep, &val) ) return val def setCISSSizes( self, ip: int | None = None, bs: int | None = None, ms: int | None = None, npart: int | None = None, bsmax: int | None = None, realmats: bool = False, ) -> None: """ Set the values of various size parameters in the CISS solver. Logically collective. Parameters ---------- ip Number of integration points. bs Block size. ms Moment size. npart Number of partitions when splitting the communicator. bsmax Maximum block size. realmats ``True`` if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `petsc4py.PETSc.KSP` object is shared among all processes of the `PEP` communicator. Otherwise, the communicator is split into ``npart`` communicators, so that ``npart`` `petsc4py.PETSc.KSP` solves proceed simultaneously. See Also -------- getCISSSizes, setCISSThreshold, setCISSRefinement, slepc.PEPCISSSetSizes """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT cdef PetscInt ival4 = PETSC_CURRENT cdef PetscInt ival5 = PETSC_CURRENT cdef PetscBool bval = asBool(realmats) if ip is not None: ival1 = asInt(ip) if bs is not None: ival2 = asInt(bs) if ms is not None: ival3 = asInt(ms) if npart is not None: ival4 = asInt(npart) if bsmax is not None: ival5 = asInt(bsmax) CHKERR( PEPCISSSetSizes(self.pep, ival1, ival2, ival3, ival4, ival5, bval) ) def getCISSSizes(self) -> tuple[int, int, int, int, int, bool]: """ Get the values of various size parameters in the CISS solver. Not collective. Returns ------- ip: int Number of integration points. bs: int Block size. ms: int Moment size. npart: int Number of partitions when splitting the communicator. bsmax: int Maximum block size. realmats: bool ``True`` if A and B are real. See Also -------- setCISSSizes, slepc.PEPCISSGetSizes """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 cdef PetscInt ival4 = 0 cdef PetscInt ival5 = 0 cdef PetscBool bval = PETSC_FALSE CHKERR( PEPCISSGetSizes(self.pep, &ival1, &ival2, &ival3, &ival4, &ival5, &bval) ) return (toInt(ival1), toInt(ival2), toInt(ival3), toInt(ival4), toInt(ival5), toBool(bval)) def setCISSThreshold(self, delta: float | None = None, spur: float | None = None) -> None: """ Set the values of various threshold parameters in the CISS solver. Logically collective. Parameters ---------- delta Threshold for numerical rank. spur Spurious threshold (to discard spurious eigenpairs). See Also -------- getCISSThreshold, slepc.PEPCISSSetThreshold """ cdef PetscReal rval1 = PETSC_CURRENT cdef PetscReal rval2 = PETSC_CURRENT if delta is not None: rval1 = asReal(delta) if spur is not None: rval2 = asReal(spur) CHKERR( PEPCISSSetThreshold(self.pep, rval1, rval2) ) def getCISSThreshold(self) -> tuple[float, float]: """ Get the values of various threshold parameters in the CISS solver. Not collective. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. See Also -------- setCISSThreshold, slepc.PEPCISSGetThreshold """ cdef PetscReal delta = 0 cdef PetscReal spur = 0 CHKERR( PEPCISSGetThreshold(self.pep, &delta, &spur) ) return (toReal(delta), toReal(spur)) def setCISSRefinement(self, inner: int | None = None, blsize: int | None = None) -> None: """ Set the values of various refinement parameters in the CISS solver. Logically collective. Parameters ---------- inner Number of iterative refinement iterations (inner loop). blsize Number of iterative refinement iterations (blocksize loop). See Also -------- getCISSRefinement, slepc.PEPCISSSetRefinement """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT if inner is not None: ival1 = asInt(inner) if blsize is not None: ival2 = asInt(blsize) CHKERR( PEPCISSSetRefinement(self.pep, ival1, ival2) ) def getCISSRefinement(self) -> tuple[int, int]: """ Get the values of various refinement parameters in the CISS solver. Not collective. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). See Also -------- setCISSRefinement, slepc.PEPCISSGetRefinement """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( PEPCISSGetRefinement(self.pep, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def getCISSKSPs(self) -> list[KSP]: """ Get the array of linear solver objects associated with the CISS solver. Collective. Returns ------- list of `petsc4py.PETSc.KSP` The linear solver objects. Notes ----- The number of `petsc4py.PETSc.KSP` solvers is equal to the number of integration points divided by the number of partitions. This value is halved in the case of real matrices with a region centered at the real axis. See Also -------- setCISSSizes, slepc.PEPCISSGetKSPs """ cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL CHKERR( PEPCISSGetKSPs(self.pep, &n, &p) ) return [ref_KSP(p[i]) for i from 0 <= i PEPProblemType: return self.getProblemType() def __set__(self, value): self.setProblemType(value) property which: """The portion of the spectrum to be sought.""" def __get__(self) -> PEPWhich: return self.getWhichEigenpairs() def __set__(self, value): self.setWhichEigenpairs(value) property target: """The value of the target.""" def __get__(self) -> float: return self.getTarget() def __set__(self, value): self.setTarget(value) property extract: """The type of extraction technique to be employed.""" def __get__(self) -> PEPExtract: return self.getExtract() def __set__(self, value): self.setExtract(value) property tol: """The tolerance.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property track_all: """Compute the residual norm of all approximate eigenpairs.""" def __get__(self) -> bool: return self.getTrackAll() def __set__(self, value): self.setTrackAll(value) property st: """The spectral transformation (`ST`) object associated.""" def __get__(self) -> ST: return self.getST() def __set__(self, value): self.setST(value) property bv: """The basis vectors (`BV`) object associated.""" def __get__(self) -> BV: return self.getBV() def __set__(self, value): self.setBV(value) property rg: """The region (`RG`) object associated.""" def __get__(self) -> RG: return self.getRG() def __set__(self, value): self.setRG(value) property ds: """The direct solver (`DS`) object associated.""" def __get__(self) -> DS: return self.getDS() def __set__(self, value): self.setDS(value) # ----------------------------------------------------------------------------- del PEPType del PEPProblemType del PEPWhich del PEPBasis del PEPScale del PEPRefine del PEPRefineScheme del PEPExtract del PEPErrorType del PEPConv del PEPStop del PEPConvergedReason del PEPJDProjection del PEPCISSExtraction # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/RG.pyx0000644000076500000240000005646515133663436017122 0ustar00jromanstaff# ----------------------------------------------------------------------------- class RGType(object): """ RG type. - `INTERVAL`: A (generalized) interval. - `POLYGON`: A polygonal region defined by its vertices. - `ELLIPSE`: An ellipse defined by its center, radius and vertical scale. - `RING`: A ring region. See Also -------- slepc.RGType """ INTERVAL = S_(RGINTERVAL) POLYGON = S_(RGPOLYGON) ELLIPSE = S_(RGELLIPSE) RING = S_(RGRING) class RGQuadRule(object): """ RG quadrature rule for contour integral methods. - `TRAPEZOIDAL`: Trapezoidal rule. - `CHEBYSHEV`: Chebyshev points. See Also -------- slepc.RGQuadRule """ TRAPEZOIDAL = EPS_CISS_QUADRULE_TRAPEZOIDAL CHEBYSHEV = EPS_CISS_QUADRULE_CHEBYSHEV # ----------------------------------------------------------------------------- cdef class RG(Object): """ Region. The `RG` package provides a way to define a region of the complex plane. This is used in various eigensolvers to specify where the wanted eigenvalues are located. """ Type = RGType QuadRule = RGQuadRule def __cinit__(self): self.obj = &self.rg self.rg = NULL def view(self, Viewer viewer=None) -> None: """ Print the RG data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.RGView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( RGView(self.rg, vwr) ) def destroy(self) -> Self: """ Destroy the RG object. Collective. See Also -------- slepc.RGDestroy """ CHKERR( RGDestroy(&self.rg) ) self.rg = NULL return self def create(self, comm: Comm | None = None) -> Self: """ Create the RG object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.RGCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcRG newrg = NULL CHKERR( RGCreate(ccomm, &newrg) ) CHKERR( SlepcCLEAR(self.obj) ); self.rg = newrg return self def setType(self, rg_type: Type | str) -> None: """ Set the type for the RG object. Logically collective. Parameters ---------- rg_type The region type to be used. See Also -------- getType, slepc.RGSetType """ cdef SlepcRGType cval = NULL rg_type = str2bytes(rg_type, &cval) CHKERR( RGSetType(self.rg, cval) ) def getType(self) -> str: """ Get the RG type of this object. Not collective. Returns ------- str The region type currently being used. See Also -------- setType, slepc.RGGetType """ cdef SlepcRGType rg_type = NULL CHKERR( RGGetType(self.rg, &rg_type) ) return bytes2str(rg_type) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all RG options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all RG option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.RGGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( RGSetOptionsPrefix(self.rg, cval) ) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all RG options in the database. Not collective. Returns ------- str The prefix string set for this RG object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.RGGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( RGGetOptionsPrefix(self.rg, &prefix) ) return bytes2str(prefix) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all RG options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all RG option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.RGAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( RGAppendOptionsPrefix(self.rg, cval) ) def setFromOptions(self) -> None: """ Set RG options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. See Also -------- setOptionsPrefix, slepc.RGSetFromOptions """ CHKERR( RGSetFromOptions(self.rg) ) # def isTrivial(self) -> bool: """ Tell whether it is the trivial region (whole complex plane). Not collective. Returns ------- bool ``True`` if the region is equal to the whole complex plane, e.g., an interval region with all four endpoints unbounded or an ellipse with infinite radius. See Also -------- checkInside, slepc.RGIsTrivial """ cdef PetscBool tval = PETSC_FALSE CHKERR( RGIsTrivial(self.rg, &tval) ) return toBool(tval) def isAxisymmetric(self, vertical: bool = False) -> bool: """ Determine if the region is axisymmetric. Not collective. Determine if the region is symmetric with respect to the real or imaginary axis. Parameters ---------- vertical ``True`` if symmetry must be checked against the vertical axis. Returns ------- bool ``True`` if the region is axisymmetric. See Also -------- canUseConjugates, slepc.RGIsAxisymmetric """ cdef PetscBool val = asBool(vertical) cdef PetscBool tval = PETSC_FALSE CHKERR( RGIsAxisymmetric(self.rg, val, &tval) ) return toBool(tval) def getComplement(self) -> bool: """ Get the flag indicating whether the region is complemented or not. Not collective. Returns ------- bool Whether the region is complemented or not. See Also -------- setComplement, slepc.RGGetComplement """ cdef PetscBool tval = PETSC_FALSE CHKERR( RGGetComplement(self.rg, &tval) ) return toBool(tval) def setComplement(self, comp: bool = True) -> None: """ Set a flag to indicate that the region is the complement of the specified one. Logically collective. Parameters ---------- comp Activate/deactivate the complementation of the region. See Also -------- getComplement, slepc.RGSetComplement """ cdef PetscBool tval = asBool(comp) CHKERR( RGSetComplement(self.rg, tval) ) def setScale(self, sfactor: float = None) -> None: """ Set the scaling factor to be used. Logically collective. Set the scaling factor to be used when checking that a point is inside the region and when computing the contour. Parameters ---------- sfactor The scaling factor (default=1). See Also -------- getScale, checkInside, computeContour, slepc.RGSetScale """ cdef PetscReal rval = 1.0 if sfactor is not None: rval = asReal(sfactor) CHKERR( RGSetScale(self.rg, rval) ) def getScale(self) -> float: """ Get the scaling factor. Not collective. Returns ------- float The scaling factor. See Also -------- setScale, slepc.RGGetScale """ cdef PetscReal rval = 0 CHKERR( RGGetScale(self.rg, &rval) ) return toReal(rval) def checkInside(self, a: Sequence[complex]) -> ArrayInt: """ Determine if a set of given points are inside the region or not. Not collective. Parameters ---------- a The coordinates of the points. Returns ------- ArrayInt Computed result for each point (1=inside, 0=on the contour, -1=outside). Notes ----- If a scaling factor was set, the points are scaled before checking. See Also -------- setScale, setComplement, slepc.RGCheckInside """ cdef Py_ssize_t i = 0, n = len(a) cdef PetscScalar *ar = NULL, *ai = NULL cdef PetscInt *inside = NULL cdef tmp1 = allocate(n*sizeof(PetscScalar),&ar) cdef tmp2 if sizeof(PetscScalar) == sizeof(PetscReal): tmp2 = allocate(n*sizeof(PetscScalar),&ai) for i in range(n): ar[i] = asComplexReal(a[i]) ai[i] = asComplexImag(a[i]) else: for i in range(n): ar[i] = asScalar(a[i]) cdef tmp3 = allocate(n*sizeof(PetscInt),&inside) CHKERR( RGCheckInside(self.rg, n, ar, ai, inside) ) return array_i(n, inside) def computeContour(self, n: int) -> list[complex]: """ Compute points on the contour of the region. Not collective. Compute the coordinates of several points lying on the contour of the region. Parameters ---------- n The number of points to compute. Returns ------- list of complex Computed points. See Also -------- computeBoundingBox, setScale, slepc.RGComputeContour """ cdef PetscInt k = asInt(n), i = 0 cdef PetscScalar *cr = NULL, *ci = NULL cdef tmp1 = allocate(k*sizeof(PetscScalar),&cr) cdef tmp2 if sizeof(PetscScalar) == sizeof(PetscReal): tmp2 = allocate(k*sizeof(PetscScalar),&ci) CHKERR( RGComputeContour(self.rg, k, cr, ci) ) if sizeof(PetscScalar) == sizeof(PetscReal): return [toComplex(cr[i],ci[i]) for i from 0 <= i tuple[float, float, float, float]: """ Compute box containing the region. Not collective. Determine the endpoints of a rectangle in the complex plane that contains the region. Returns ------- a: float The left endpoint of the bounding box in the real axis. b: float The right endpoint of the bounding box in the real axis. c: float The bottom endpoint of the bounding box in the imaginary axis. d: float The top endpoint of the bounding box in the imaginary axis. See Also -------- computeContour, setScale, slepc.RGComputeBoundingBox """ cdef PetscReal a = 0, b = 0, c = 0, d = 0 CHKERR( RGComputeBoundingBox(self.rg, &a, &b, &c, &d) ) return (toReal(a), toReal(b), toReal(c), toReal(d)) def canUseConjugates(self, realmats: bool = True) -> bool: """ Half of integration points can be avoided (use their conjugates). Not collective. Used in contour integral methods to determine whether half of integration points can be avoided (use their conjugates). Parameters ---------- realmats ``True`` if the problem matrices are real. Returns ------- bool Whether it is possible to use conjugates. Notes ----- If some integration points are the conjugates of other points, then the associated computational cost can be saved. This depends on the problem matrices being real and also the region being symmetric with respect to the horizontal axis. The result is ``false`` if using real arithmetic or in the case of a flat region (height equal to zero). See Also -------- isAxisymmetric, slepc.RGCanUseConjugates """ cdef PetscBool bval = asBool(realmats) cdef PetscBool tval = PETSC_FALSE CHKERR( RGCanUseConjugates(self.rg, bval, &tval) ) return toBool(tval) def computeQuadrature(self, quad: QuadRule, n: int) -> tuple[ArrayScalar, ArrayScalar, ArrayScalar]: """ Compute the values of the parameters used in a quadrature rule. Not collective. Compute the values of the parameters used in a quadrature rule for a contour integral around the boundary of the region. Parameters ---------- quad The type of quadrature. n The number of quadrature points to compute. Returns ------- z: ArrayScalar Quadrature points. zn: ArrayScalar Normalized quadrature points. w: ArrayScalar Quadrature weights. Notes ----- In complex scalars, the values returned in ``z`` are often the same as those computed by `computeContour()`, but this is not the case in real scalars where all output arguments are real. The computed values change for different quadrature rules. See Also -------- computeContour, slepc.RGComputeQuadrature """ cdef SlepcRGQuadRule val = quad cdef PetscInt k = asInt(n), i = 0 cdef PetscScalar *z = NULL, *zn = NULL, *w = NULL cdef tmp1 = allocate(k*sizeof(PetscScalar),&z) cdef tmp2 = allocate(k*sizeof(PetscScalar),&zn) cdef tmp3 = allocate(k*sizeof(PetscScalar),&w) CHKERR( RGComputeQuadrature(self.rg, val, k, z, zn, w) ) return (array_s(k, z), array_s(k, zn), array_s(k, w)) # def setEllipseParameters(self, center: Scalar, radius: float, vscale: float | None = None) -> None: """ Set the parameters defining the ellipse region. Logically collective. Parameters ---------- center The center. radius The radius. vscale The vertical scale. Notes ----- When PETSc is built with real scalars, the center is restricted to a real value. See Also -------- getEllipseParameters, slepc.RGEllipseSetParameters """ cdef PetscScalar sval = asScalar(center) cdef PetscReal val1 = asReal(radius) cdef PetscReal val2 = 1.0 if vscale is not None: val2 = asReal(vscale) CHKERR( RGEllipseSetParameters(self.rg, sval, val1, val2) ) def getEllipseParameters(self) -> tuple[Scalar, float, float]: """ Get the parameters that define the ellipse region. Not collective. Returns ------- center: Scalar The center. radius: float The radius. vscale: float The vertical scale. See Also -------- setEllipseParameters, slepc.RGEllipseGetParameters """ cdef PetscScalar sval = 0 cdef PetscReal val1 = 0 cdef PetscReal val2 = 0 CHKERR( RGEllipseGetParameters(self.rg, &sval, &val1, &val2) ) return (toScalar(sval), toReal(val1), toReal(val2)) def setIntervalEndpoints(self, a: float, b: float, c: float, d: float) -> None: """ Set the parameters defining the interval region. Logically collective. Parameters ---------- a The left endpoint in the real axis. b The right endpoint in the real axis. c The bottom endpoint in the imaginary axis. d The top endpoint in the imaginary axis. Notes ----- The region is defined as :math:`[a,b] x [c,d]`. Particular cases are an interval on the real axis (:math:`c=d=0`), similarly for the imaginary axis (:math:`a=b=0`), the whole complex plane (:math:`a=-\infty,b=\infty,c=-\infty,d=\infty`), and so on. When PETSc is built with real scalars, the region must be symmetric with respect to the real axis. See Also -------- getIntervalEndpoints, slepc.RGIntervalSetEndpoints """ cdef PetscReal va = asReal(a) cdef PetscReal vb = asReal(b) cdef PetscReal vc = asReal(c) cdef PetscReal vd = asReal(d) CHKERR( RGIntervalSetEndpoints(self.rg, va, vb, vc, vd) ) def getIntervalEndpoints(self) -> tuple[float, float, float, float]: """ Get the parameters that define the interval region. Not collective. Returns ------- a: float The left endpoint in the real axis. b: float The right endpoint in the real axis. c: float The bottom endpoint in the imaginary axis. d: float The top endpoint in the imaginary axis. See Also -------- setIntervalEndpoints, slepc.RGIntervalGetEndpoints """ cdef PetscReal va = 0 cdef PetscReal vb = 0 cdef PetscReal vc = 0 cdef PetscReal vd = 0 CHKERR( RGIntervalGetEndpoints(self.rg, &va, &vb, &vc, &vd) ) return (toReal(va), toReal(vb), toReal(vc), toReal(vd)) def setPolygonVertices(self, v: Sequence[float] | Sequence[Scalar]) -> None: """ Set the vertices that define the polygon region. Logically collective. Parameters ---------- v The vertices. See Also -------- getPolygonVertices, slepc.RGPolygonSetVertices """ cdef Py_ssize_t i = 0, n = len(v) cdef PetscScalar *vr = NULL, *vi = NULL cdef tmp1 = allocate(n*sizeof(PetscScalar),&vr) cdef tmp2 if sizeof(PetscScalar) == sizeof(PetscReal): tmp2 = allocate(n*sizeof(PetscScalar),&vi) for i in range(n): vr[i] = asComplexReal(v[i]) vi[i] = asComplexImag(v[i]) else: for i in range(n): vr[i] = asScalar(v[i]) CHKERR( RGPolygonSetVertices(self.rg, n, vr, vi) ) def getPolygonVertices(self) -> ArrayComplex: """ Get the parameters that define the interval region. Not collective. Returns ------- ArrayComplex The vertices. See Also -------- setPolygonVertices, slepc.RGPolygonGetVertices """ cdef PetscInt n = 0 cdef PetscScalar *vr = NULL, *vi = NULL CHKERR( RGPolygonGetVertices(self.rg, &n, &vr, &vi) ) if sizeof(PetscScalar) == sizeof(PetscReal): v = [toComplex(vr[i],vi[i]) for i from 0 <= i None: """ Set the parameters defining the ring region. Logically collective. Parameters ---------- center The center. radius The radius. vscale The vertical scale. start_ang The right-hand side angle. end_ang The left-hand side angle. width The width of the ring. Notes ----- The values of ``center``, ``radius`` and ``vscale`` have the same meaning as in the ellipse region. The ``start_ang`` and ``end_ang`` define the span of the ring (by default it is the whole ring), while the ``width`` is the separation between the two concentric ellipses (above and below the radius by ``width/2``). The start and end angles are expressed as a fraction of the circumference. The allowed range is :math:`[0,\dots,1]`, with ``0`` corresponding to 0 radians, ``0.25`` to :math:`\pi/2` radians, and so on. It is allowed to have ``start_ang`` > ``end_ang``, in which case the ring region crosses over the zero angle. When PETSc is built with real scalars, the center is restricted to a real value, and the start and end angles must be such that the region is symmetric with respect to the real axis. See Also -------- getRingParameters, slepc.RGRingSetParameters """ cdef PetscScalar sval = asScalar(center) cdef PetscReal val1 = asReal(radius) cdef PetscReal val2 = asReal(vscale) cdef PetscReal val3 = asReal(start_ang) cdef PetscReal val4 = asReal(end_ang) cdef PetscReal val5 = asReal(width) CHKERR( RGRingSetParameters(self.rg, sval, val1, val2, val3, val4, val5) ) def getRingParameters(self) -> tuple[Scalar, float, float, float, float, float]: """ Get the parameters that define the ring region. Not collective. Returns ------- center: Scalar The center. radius: float The radius. vscale: float The vertical scale. start_ang: float The right-hand side angle. end_ang: float The left-hand side angle. width: float The width of the ring. See Also -------- setRingParameters, slepc.RGRingGetParameters """ cdef PetscScalar sval = 0 cdef PetscReal val1 = 0 cdef PetscReal val2 = 0 cdef PetscReal val3 = 0 cdef PetscReal val4 = 0 cdef PetscReal val5 = 0 CHKERR( RGRingGetParameters(self.rg, &sval, &val1, &val2, &val3, &val4, &val5) ) return (toScalar(sval), toReal(val1), toReal(val2), toReal(val3), toReal(val4), toReal(val5)) # property complement: """If the region is the complement of the specified one.""" def __get__(self) -> bool: return self.getComplement() def __set__(self, value): self.setComplement(value) property scale: """The scaling factor to be used.""" def __get__(self) -> float: return self.getScale() def __set__(self, value): self.setScale(value) # ----------------------------------------------------------------------------- del RGType del RGQuadRule # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/SLEPc.pyx0000644000076500000240000002073215133663436017504 0ustar00jromanstaff# -------------------------------------------------------------------- cdef extern from * nogil: """ #include "pyapicompat.h" #include "lib-slepc/compat.h" #include "lib-slepc/custom.h" /* Silence Clang warnings in Cython-generated C code */ #if defined(__clang__) #pragma clang diagnostic ignored "-Wextra-semi-stmt" #pragma clang diagnostic ignored "-Wparentheses-equality" #pragma clang diagnostic ignored "-Wunreachable-code-fallthrough" #pragma clang diagnostic ignored "-Woverlength-strings" #pragma clang diagnostic ignored "-Wunreachable-code" #pragma clang diagnostic ignored "-Wundef" #elif defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic ignored "-Wstrict-aliasing" #pragma GCC diagnostic ignored "-Wtype-limits" #endif """ # ----------------------------------------------------------------------------- from petsc4py.PETSc import COMM_NULL from petsc4py.PETSc import COMM_SELF from petsc4py.PETSc import COMM_WORLD # ----------------------------------------------------------------------------- from petsc4py.PETSc cimport MPI_Comm from petsc4py.PETSc cimport PetscErrorCode, PetscErrorType from petsc4py.PETSc cimport PETSC_SUCCESS, PETSC_ERR_PYTHON from petsc4py.PETSc cimport CHKERR from petsc4py.PETSc cimport PetscObject, PetscViewer from petsc4py.PETSc cimport PetscRandom from petsc4py.PETSc cimport PetscVec, PetscMat from petsc4py.PETSc cimport PetscKSP, PetscPC from petsc4py.PETSc cimport Comm from petsc4py.PETSc cimport Object, Viewer from petsc4py.PETSc cimport Random from petsc4py.PETSc cimport Vec, Mat from petsc4py.PETSc cimport KSP, PC # ----------------------------------------------------------------------------- cdef inline object bytes2str(const char p[]): if p == NULL: return None cdef bytes s = p if isinstance(s, str): return s else: return s.decode() cdef inline object str2bytes(object s, const char *p[]): if s is None: p[0] = NULL return None if not isinstance(s, bytes): s = s.encode() p[0] = (s) return s cdef inline object S_(const char p[]): if p == NULL: return None cdef object s = p return s if isinstance(s, str) else s.decode() include "allocate.pxi" # ----------------------------------------------------------------------------- cdef extern from * nogil: ctypedef bint PetscBool const PetscBool PETSC_TRUE const PetscBool PETSC_FALSE ctypedef long PetscInt ctypedef double PetscReal ctypedef double PetscScalar cdef inline object toBool(PetscBool value): return True if value == PETSC_TRUE else False cdef inline PetscBool asBool(object value) except? 0: return PETSC_TRUE if value else PETSC_FALSE cdef inline object toInt(PetscInt value): return value cdef inline PetscInt asInt(object value) except? -1: return value cdef inline object toReal(PetscReal value): return value cdef inline PetscReal asReal(object value) except? -1: return value cdef extern from "": object PyPetscScalar_FromPetscScalar(PetscScalar) PetscScalar PyPetscScalar_AsPetscScalar(object) except? -1.0 cdef inline object toScalar(PetscScalar value): return PyPetscScalar_FromPetscScalar(value) cdef inline PetscScalar asScalar(object value) except? -1.0: return PyPetscScalar_AsPetscScalar(value) cdef extern from "Python.h": double PyComplex_RealAsDouble(object) double PyComplex_ImagAsDouble(object) void Py_INCREF(object) cdef inline object toComplex(PetscScalar rvalue, PetscScalar ivalue): return complex(toScalar(rvalue), toScalar(ivalue)) cdef inline PetscReal asComplexReal(object value) except? -1.0: return PyComplex_RealAsDouble(value) cdef inline PetscReal asComplexImag(object value) except? -1.0: return PyComplex_ImagAsDouble(value) cdef extern from * nogil: PetscReal PetscRealPart(PetscScalar v) PetscReal PetscImaginaryPart(PetscScalar v) # -------------------------------------------------------------------- # NumPy support # ------------- include "arraynpy.pxi" import_array() IntType = PyArray_TypeObjectFromType(NPY_PETSC_INT) RealType = PyArray_TypeObjectFromType(NPY_PETSC_REAL) ScalarType = PyArray_TypeObjectFromType(NPY_PETSC_SCALAR) ComplexType = PyArray_TypeObjectFromType(NPY_PETSC_COMPLEX) # ----------------------------------------------------------------------------- cdef extern from "" nogil: void* memset(void*,int,size_t) void* memcpy(void*,void*,size_t) char* strdup(char*) # ----------------------------------------------------------------------------- include "slepcmpi.pxi" include "slepcsys.pxi" include "slepcutil.pxi" include "slepcst.pxi" include "slepcbv.pxi" include "slepcds.pxi" include "slepcfn.pxi" include "slepcrg.pxi" include "slepceps.pxi" include "slepcsvd.pxi" include "slepcpep.pxi" include "slepcnep.pxi" include "slepcmfn.pxi" include "slepclme.pxi" # ----------------------------------------------------------------------------- __doc__ = u""" Scalable Library for Eigenvalue Problem Computations """ DECIDE = PETSC_DECIDE DEFAULT = PETSC_DEFAULT DETERMINE = PETSC_DETERMINE CURRENT = PETSC_CURRENT include "Sys.pyx" include "Util.pyx" include "ST.pyx" include "BV.pyx" include "DS.pyx" include "FN.pyx" include "RG.pyx" include "EPS.pyx" include "SVD.pyx" include "PEP.pyx" include "NEP.pyx" include "MFN.pyx" include "LME.pyx" # ----------------------------------------------------------------------------- include "CAPI.pyx" # ----------------------------------------------------------------------------- cdef extern from "Python.h": int Py_AtExit(void (*)() noexcept nogil) void PySys_WriteStderr(char*,...) cdef extern from "" nogil: ctypedef struct FILE FILE *stderr int fprintf(FILE *, char *, ...) cdef int initialize(object args) except PETSC_ERR_PYTHON: if (SlepcInitializeCalled): return 1 if (SlepcFinalizeCalled): return 0 # initialize SLEPC CHKERR( SlepcInitialize(NULL, NULL, NULL, NULL) ) # register finalization function if Py_AtExit(finalize) < 0: PySys_WriteStderr(b"warning: could not register %s with Py_AtExit()", b"SlepcFinalize()") return 1 # and we are done, enjoy !! from petsc4py.PETSc cimport PyPetscType_Register cdef extern from * nogil: PetscErrorCode SlepcInitializePackageAll() ctypedef int PetscClassId PetscClassId SLEPC_ST_CLASSID "ST_CLASSID" PetscClassId SLEPC_BV_CLASSID "BV_CLASSID" PetscClassId SLEPC_DS_CLASSID "DS_CLASSID" PetscClassId SLEPC_FN_CLASSID "FN_CLASSID" PetscClassId SLEPC_RG_CLASSID "RG_CLASSID" PetscClassId SLEPC_EPS_CLASSID "EPS_CLASSID" PetscClassId SLEPC_SVD_CLASSID "SVD_CLASSID" PetscClassId SLEPC_PEP_CLASSID "PEP_CLASSID" PetscClassId SLEPC_NEP_CLASSID "NEP_CLASSID" PetscClassId SLEPC_MFN_CLASSID "MFN_CLASSID" PetscClassId SLEPC_LME_CLASSID "LME_CLASSID" cdef PetscErrorCode register() except PETSC_ERR_PYTHON: # make sure all SLEPc packages are initialized CHKERR( SlepcInitializePackageAll() ) # register Python types PyPetscType_Register(SLEPC_ST_CLASSID, ST) PyPetscType_Register(SLEPC_BV_CLASSID, BV) PyPetscType_Register(SLEPC_DS_CLASSID, DS) PyPetscType_Register(SLEPC_FN_CLASSID, FN) PyPetscType_Register(SLEPC_RG_CLASSID, RG) PyPetscType_Register(SLEPC_EPS_CLASSID, EPS) PyPetscType_Register(SLEPC_SVD_CLASSID, SVD) PyPetscType_Register(SLEPC_PEP_CLASSID, PEP) PyPetscType_Register(SLEPC_NEP_CLASSID, NEP) PyPetscType_Register(SLEPC_MFN_CLASSID, MFN) PyPetscType_Register(SLEPC_LME_CLASSID, LME) return PETSC_SUCCESS cdef void finalize() noexcept nogil: cdef PetscErrorCode ierr = PETSC_SUCCESS # manage SLEPc finalization if not (SlepcInitializeCalled): return if (SlepcFinalizeCalled): return # finalize SLEPc ierr = SlepcFinalize() if ierr != PETSC_SUCCESS: fprintf(stderr, "SlepcFinalize() failed " "[error code: %d]\n", ierr) # and we are done, see you later !! # ----------------------------------------------------------------------------- def _initialize(args=None): cdef int ready = initialize(args) if ready: register() def _finalize(): finalize() # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/ST.pyx0000644000076500000240000010607415133663436017130 0ustar00jromanstaff# ----------------------------------------------------------------------------- class STType(object): """ ST type. - `SHIFT`: Shift from origin. - `SINVERT`: Shift-and-invert. - `CAYLEY`: Cayley transform. - `PRECOND`: Preconditioner. - `FILTER`: Polynomial filter. - `SHELL`: User-defined. See Also -------- slepc.STType """ SHIFT = S_(STSHIFT) SINVERT = S_(STSINVERT) CAYLEY = S_(STCAYLEY) PRECOND = S_(STPRECOND) FILTER = S_(STFILTER) SHELL = S_(STSHELL) class STMatMode(object): """ ST matrix mode. - `COPY`: A working copy of the matrix is created. - `INPLACE`: The operation is computed in-place. - `SHELL`: The matrix :math:`A - \sigma B` is handled as an implicit matrix. See Also -------- slepc.STMatMode """ COPY = ST_MATMODE_COPY INPLACE = ST_MATMODE_INPLACE SHELL = ST_MATMODE_SHELL class STFilterType(object): """ ST filter type. - ``FILTLAN``: An adapted implementation of the Filtered Lanczos Package. - ``CHEBYSEV``: A polynomial filter based on a truncated Chebyshev series. See Also -------- slepc.STFilterType """ FILTLAN = ST_FILTER_FILTLAN CHEBYSHEV = ST_FILTER_CHEBYSHEV class STFilterDamping(object): """ ST filter damping. - `NONE`: No damping - `JACKSON`: Jackson damping - `LANCZOS`: Lanczos damping - `FEJER`: Fejer damping See Also -------- slepc.STFilterDamping """ NONE = ST_FILTER_DAMPING_NONE JACKSON = ST_FILTER_DAMPING_JACKSON LANCZOS = ST_FILTER_DAMPING_LANCZOS FEJER = ST_FILTER_DAMPING_FEJER # ----------------------------------------------------------------------------- cdef class ST(Object): """ Spectral Transformation. The Spectral Transformation (`ST`) class encapsulates the functionality required for acceleration techniques based on the transformation of the spectrum. The eigensolvers implemented in `EPS` work by applying an operator to a set of vectors and this operator can adopt different forms. The `ST` object handles all the different possibilities in a uniform way, so that the solver can proceed without knowing which transformation has been selected. Polynomial eigensolvers in `PEP` also support spectral transformation. """ Type = STType MatMode = STMatMode FilterType = STFilterType FilterDamping = STFilterDamping def __cinit__(self): self.obj = &self.st self.st = NULL def view(self, Viewer viewer=None) -> None: """ Print the ST data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.STView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( STView(self.st, vwr) ) def destroy(self) -> Self: """ Destroy the ST object. Collective. See Also -------- slepc.STDestroy """ CHKERR( STDestroy(&self.st) ) self.st = NULL return self def reset(self) -> None: """ Reset the ST object. Collective. See Also -------- slepc.STReset """ CHKERR( STReset(self.st) ) def create(self, comm: Comm | None = None) -> Self: """ Create the ST object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.STCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcST newst = NULL CHKERR( STCreate(ccomm, &newst) ) CHKERR( SlepcCLEAR(self.obj) ); self.st = newst return self def setType(self, st_type: Type | str) -> None: """ Set the particular spectral transformation to be used. Logically collective. Parameters ---------- st_type The spectral transformation to be used. Notes ----- The default is `SHIFT` with a zero shift. Normally, it is best to use `setFromOptions()` and then set the ST type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.STSetType """ cdef SlepcSTType cval = NULL st_type = str2bytes(st_type, &cval) CHKERR( STSetType(self.st, cval) ) def getType(self) -> str: """ Get the ST type of this object. Not collective. Returns ------- str The spectral transformation currently being used. See Also -------- setType, slepc.STGetType """ cdef SlepcSTType st_type = NULL CHKERR( STGetType(self.st, &st_type) ) return bytes2str(st_type) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all ST options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all ST option requests. Notes ----- A hyphen (``-``) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.STGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( STSetOptionsPrefix(self.st, cval) ) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all ST options in the database. Not collective. Returns ------- str The prefix string set for this ST object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.STGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( STGetOptionsPrefix(self.st, &prefix) ) return bytes2str(prefix) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all ST options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all ST option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.STAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( STAppendOptionsPrefix(self.st, cval) ) def setFromOptions(self) -> None: """ Set ST options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.STSetFromOptions """ CHKERR( STSetFromOptions(self.st) ) # def setShift(self, shift: Scalar) -> None: """ Set the shift associated with the spectral transformation. Collective. Parameters ---------- shift The value of the shift. Notes ----- In some spectral transformations, changing the shift may have associated a lot of work, for example recomputing a factorization. This function is normally not directly called by users, since the shift is indirectly set by `EPS.setTarget()`. See Also -------- getShift, slepc.STSetShift """ cdef PetscScalar sval = asScalar(shift) CHKERR( STSetShift(self.st, sval) ) def getShift(self) -> Scalar: """ Get the shift associated with the spectral transformation. Not collective. Returns ------- Scalar The value of the shift. See Also -------- setShift, slepc.STGetShift """ cdef PetscScalar sval = 0 CHKERR( STGetShift(self.st, &sval) ) return toScalar(sval) def setTransform(self, flag: bool = True) -> None: """ Set a flag to indicate whether the transformed matrices are computed or not. Logically collective. Parameters ---------- flag This flag is intended for the case of polynomial eigenproblems solved via linearization. If this flag is ``False`` (default) the spectral transformation is applied to the linearization (handled by the eigensolver), otherwise it is applied to the original problem. See Also -------- getTransform, slepc.STSetTransform """ cdef PetscBool sval = asBool(flag) CHKERR( STSetTransform(self.st, sval) ) def getTransform(self) -> bool: """ Get the flag indicating whether the transformed matrices are computed or not. Not collective. Returns ------- bool This flag is intended for the case of polynomial eigenproblems solved via linearization. If this flag is ``False`` (default) the spectral transformation is applied to the linearization (handled by the eigensolver), otherwise it is applied to the original problem. See Also -------- setTransform, slepc.STGetTransform """ cdef PetscBool sval = PETSC_FALSE CHKERR( STGetTransform(self.st, &sval) ) return toBool(sval) def setMatMode(self, mode: MatMode) -> None: """ Set a flag related to management of transformed matrices. Logically collective. The flag indicates how the transformed matrices are being stored in the spectral transformation. Parameters ---------- mode The mode flag. Notes ----- By default (`ST.MatMode.COPY`), a copy of matrix :math:`A` is made and then this copy is modified explicitly, e.g., :math:`A \leftarrow (A - \sigma B)`. With `ST.MatMode.INPLACE`, the original matrix :math:`A` is modified at `setUp()` and reverted at the end of the computations. With respect to the previous one, this mode avoids a copy of matrix :math:`A`. However, a backdraw is that the recovered matrix might be slightly different from the original one (due to roundoff). With `ST.MatMode.SHELL`, the solver works with an implicit shell matrix that represents the shifted matrix. This mode is the most efficient in creating the transformed matrix but it places serious limitations to the linear solves performed in each iteration of the eigensolver (typically, only iterative solvers with Jacobi preconditioning can be used). In the two first modes the efficiency of this computation can be controlled with `setMatStructure()`. See Also -------- setMatrices, setMatStructure, getMatMode, slepc.STSetMatMode """ cdef SlepcSTMatMode val = mode CHKERR( STSetMatMode(self.st, val) ) def getMatMode(self) -> MatMode: """ Get a flag that indicates how the matrix is being shifted. Not collective. Get a flag that indicates how the matrix is being shifted in the shift-and-invert and Cayley spectral transformations. Returns ------- MatMode The mode flag. See Also -------- setMatMode, slepc.STGetMatMode """ cdef SlepcSTMatMode val = ST_MATMODE_INPLACE CHKERR( STGetMatMode(self.st, &val) ) return val def setMatrices(self, operators: list[Mat]) -> None: """ Set the matrices associated with the eigenvalue problem. Collective. Parameters ---------- operators The matrices associated with the eigensystem. Notes ----- It must be called before `setUp()`. If it is called again after `setUp()` then the `ST` object is reset. In standard eigenproblems only one matrix is passed, while in generalized problems two matrices are provided. The number of matrices is larger in polynomial eigenproblems. In normal usage, matrices are provided via the corresponding `EPS` of `PEP` interface function. See Also -------- getMatrices, setUp, reset, slepc.STSetMatrices """ operators = tuple(operators) cdef PetscMat *mats = NULL cdef Py_ssize_t k=0, n = len(operators) cdef tmp = allocate(n*sizeof(PetscMat),&mats) for k from 0 <= k < n: mats[k] = (operators[k]).mat CHKERR( STSetMatrices(self.st, n, mats) ) def getMatrices(self) -> list[Mat]: """ Get the matrices associated with the eigenvalue problem. Collective. Returns ------- list of petsc4py.PETSc.Mat The matrices associated with the eigensystem. See Also -------- setMatrices, slepc.STGetNumMatrices, slepc.STGetMatrix """ cdef Mat A cdef PetscMat mat = NULL cdef PetscInt k=0, n=0 CHKERR( STGetNumMatrices(self.st, &n) ) cdef object operators = [] for k from 0 <= k < n: CHKERR( STGetMatrix(self.st, k, &mat) ) A = Mat(); A.mat = mat; CHKERR( PetscINCREF(A.obj) ) operators.append(A) return tuple(operators) def setMatStructure(self, structure: petsc4py.PETSc.Mat.Structure) -> None: """ Set the matrix structure attribute. Logically collective. Set an internal `petsc4py.PETSc.Mat.Structure` attribute to indicate which is the relation of the sparsity pattern of all the `ST` matrices. Parameters ---------- structure The matrix structure specification. Notes ----- By default, the sparsity patterns are assumed to be different. If the patterns are equal or a subset then it is recommended to set this attribute for efficiency reasons (in particular, for internal ``Mat.axpy()`` operations). This function has no effect in the case of standard eigenproblems. In case of polynomial eigenproblems, the flag applies to all matrices relative to the first one. See Also -------- getMatStructure, setMatrices, slepc.STSetMatStructure """ cdef PetscMatStructure val = matstructure(structure) CHKERR( STSetMatStructure(self.st, val) ) def getMatStructure(self) -> petsc4py.PETSc.Mat.Structure: """ Get the internal matrix structure attribute. Not collective. Get the internal `petsc4py.PETSc.Mat.Structure` attribute to indicate which is the relation of the sparsity pattern of the matrices. Returns ------- petsc4py.PETSc.Mat.Structure The structure flag. See Also -------- setMatStructure, slepc.STGetMatStructure """ cdef PetscMatStructure val CHKERR( STGetMatStructure(self.st, &val) ) return val def setKSP(self, KSP ksp) -> None: """ Set the ``KSP`` object associated with the spectral transformation. Collective. Parameters ---------- ksp The linear solver object. See Also -------- getKSP, slepc.STSetKSP """ CHKERR( STSetKSP(self.st, ksp.ksp) ) def getKSP(self) -> KSP: """ Get the ``KSP`` object associated with the spectral transformation. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setKSP, slepc.STGetKSP """ cdef KSP ksp = KSP() CHKERR( STGetKSP(self.st, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setPreconditionerMat(self, Mat P = None) -> None: """ Set the matrix to be used to build the preconditioner. Collective. Parameters ---------- P The matrix that will be used in constructing the preconditioner. Notes ----- This matrix will be passed to the internal ``KSP`` object (via the last argument of ``KSP.setOperators()``) as the matrix to be used when constructing the preconditioner. If no matrix is set then :math:`A-\sigma B` will be used to build the preconditioner, being :math:`\sigma` the value set by `setShift()`. More precisely, this is relevant for spectral transformations that represent a rational matrix function, and use a ``KSP`` object for the denominator. It includes also the `PRECOND` case. If the user has a good approximation to matrix that can be used to build a cheap preconditioner, it can be passed with this function. Note that it affects only the ``Pmat`` argument of ``KSP.setOperators()``, not the ``Amat`` argument. If a preconditioner matrix is set, the default is to use an iterative ``KSP`` rather than a direct method. An alternative to pass an approximation of :math:`A-\sigma B` with this function is to provide approximations of :math:`A` and :math:`B` via `setSplitPreconditioner()`. The difference is that when :math:`\sigma` changes the preconditioner is recomputed. A call with no matrix argument will remove a previously set matrix. See Also -------- getPreconditionerMat, slepc.STSetPreconditionerMat """ cdef PetscMat Pmat = P.mat if P is not None else NULL CHKERR( STSetPreconditionerMat(self.st, Pmat) ) def getPreconditionerMat(self) -> Mat: """ Get the matrix previously set by `setPreconditionerMat()`. Not collective. Returns ------- petsc4py.PETSc.Mat The matrix that will be used in constructing the preconditioner. See Also -------- setPreconditionerMat, slepc.STGetPreconditionerMat """ cdef Mat P = Mat() CHKERR( STGetPreconditionerMat(self.st, &P.mat) ) CHKERR( PetscINCREF(P.obj) ) return P def setSplitPreconditioner(self, operators: list[petsc4py.PETSc.Mat], structure: petsc4py.PETSc.Mat. Structure | None = None) -> None: """ Set the matrices to be used to build the preconditioner. Collective. Parameters ---------- operators The matrices associated with the preconditioner. structure The matrix structure specification. Notes ----- The number of matrices passed here must be the same as in `setMatrices()`. For linear eigenproblems, the preconditioner matrix is computed as :math:`P(\sigma) = A_0-\sigma B_0`, where :math:`A_0,B_0` are approximations of :math:`A,B` (the eigenproblem matrices) provided via the ``operators`` argument in this function. Compared to `setPreconditionerMat()`, this function allows setting a preconditioner in a way that is independent of the shift :math:`\sigma`. Whenever the value of :math:`\sigma` changes the preconditioner is recomputed. Similarly, for polynomial eigenproblems the matrix for the preconditioner is expressed as :math:`P(\sigma) = \sum_i P_i \phi_i(\sigma)`, for :math:`i=1,\dots,n`, where :math:`P_i` are given in ``operators`` and the :math:`\phi_i`'s are the polynomial basis functions. The ``structure`` flag provides information about the relative nonzero pattern of the ``operators`` matrices, in the same way as in `setMatStructure()`. See Also -------- getSplitPreconditioner, setPreconditionerMat, slepc.STSetSplitPreconditioner """ operators = tuple(operators) cdef PetscMatStructure cstructure = matstructure(structure) cdef PetscMat *mats = NULL cdef Py_ssize_t k=0, n = len(operators) cdef tmp = allocate(n*sizeof(PetscMat),&mats) for k from 0 <= k < n: mats[k] = (operators[k]).mat CHKERR( STSetSplitPreconditioner(self.st, n, mats, cstructure) ) def getSplitPreconditioner(self) -> tuple[list[petsc4py.PETSc.Mat], petsc4py.PETSc.Mat.Structure]: """ Get the matrices to be used to build the preconditioner. Not collective. Returns ------- list of petsc4py.PETSc.Mat The list of matrices associated with the preconditioner. petsc4py.PETSc.Mat.Structure The structure flag. See Also -------- slepc.STGetSplitPreconditionerInfo, slepc.STGetSplitPreconditionerTerm """ cdef PetscInt k=0,n=0 cdef PetscMatStructure cstructure cdef PetscMat mat = NULL CHKERR( STGetSplitPreconditionerInfo(self.st, &n, &cstructure) ) cdef object operators = [] for k from 0 <= k < n: CHKERR( STGetSplitPreconditionerTerm(self.st, k, &mat) ) A = Mat(); A.mat = mat; CHKERR( PetscINCREF(A.obj) ) operators.append(A) return tuple(operators, cstructure) # def setUp(self) -> None: """ Prepare for the use of a spectral transformation. Collective. See Also -------- apply, slepc.STSetUp """ CHKERR( STSetUp(self.st) ) def apply(self, Vec x, Vec y) -> None: """ Apply the spectral transformation operator to a vector. Collective. Apply the spectral transformation operator to a vector, for instance :math:`y=(A-\sigma B)^{-1}Bx` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- applyTranspose, applyHermitianTranspose, applyMat, slepc.STApply """ CHKERR( STApply(self.st, x.vec, y.vec) ) def applyTranspose(self, Vec x, Vec y) -> None: """ Apply the transpose of the operator to a vector. Collective. Apply the transpose of the operator to a vector, for instance :math:`y=B^T(A-\sigma B)^{-T}x` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- apply, applyHermitianTranspose, slepc.STApplyTranspose """ CHKERR( STApplyTranspose(self.st, x.vec, y.vec) ) def applyHermitianTranspose(self, Vec x, Vec y) -> None: """ Apply the Hermitian-transpose of the operator to a vector. Collective. Apply the Hermitian-transpose of the operator to a vector, for instance :math:`y=B^*(A - \sigma B)^{-*}x` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x The input vector. y The result vector. See Also -------- apply, applyTranspose, slepc.STApplyHermitianTranspose """ CHKERR( STApplyHermitianTranspose(self.st, x.vec, y.vec) ) def applyMat(self, Mat X, Mat Y) -> None: """ Apply the spectral transformation operator to a matrix. Collective. Apply the spectral transformation operator to a matrix, for instance :math:`Y=(A-\sigma B)^{-1}BX` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- X The input matrix. Y The result matrix. See Also -------- apply, slepc.STApplyMat """ CHKERR( STApplyMat(self.st, X.mat, Y.mat) ) def getOperator(self) -> Mat: """ Get a shell matrix that represents the operator of the spectral transformation. Collective. Returns ------- petsc4py.PETSc.Mat Operator matrix. Notes ----- The operator is defined in linear eigenproblems only, not in polynomial ones, so the call will fail if more than 2 matrices were passed in `setMatrices()`. The returned shell matrix is essentially a wrapper to the `apply()` and `applyTranspose()` operations. The operator can often be expressed as .. math:: Op = D K^{-1} M D^{-1} where :math:`D` is the balancing matrix, and :math:`M` and :math:`K` are two matrices corresponding to the numerator and denominator for spectral transformations that represent a rational matrix function. The preconditioner matrix :math:`K` typically depends on the value of the shift, and its inverse is handled via an internal ``KSP`` object. Normal usage does not require explicitly calling `getOperator()`, but it can be used to force the creation of :math:`K` and :math:`M`, and then :math:`K` is passed to the ``KSP``. This is useful for setting options associated with the ``PCFactor`` (to set MUMPS options, for instance). The returned matrix must NOT be destroyed by the user. Instead, when no longer needed it must be returned with `restoreOperator()`. In particular, this is required before modifying the `ST` matrices or the shift. See Also -------- apply, setMatrices, setShift, restoreOperator, slepc.STGetOperator """ cdef Mat op = Mat() CHKERR( STGetOperator(self.st, &op.mat) ) CHKERR( PetscINCREF(op.obj) ) return op def restoreOperator(self, Mat op) -> None: """ Restore the previously seized operator matrix. Logically collective. Parameters ---------- op Operator matrix previously obtained with `getOperator()`. See Also -------- getOperator, slepc.STRestoreOperator """ CHKERR( PetscObjectDereference(op.mat) ) CHKERR( STRestoreOperator(self.st, &op.mat) ) # def setCayleyAntishift(self, mu: Scalar) -> None: """ Set the value of the anti-shift for the Cayley spectral transformation. Logically collective. Parameters ---------- mu The anti-shift. Notes ----- In the generalized Cayley transform, the operator can be expressed as :math:`(A - \sigma B)^{-1}(A + \mu B)`. This function sets the value of :math:`mu`. Use `setShift()` for setting :math:`\sigma`. See Also -------- setShift, getCayleyAntishift, slepc.STCayleySetAntishift """ cdef PetscScalar sval = asScalar(mu) CHKERR( STCayleySetAntishift(self.st, sval) ) def getCayleyAntishift(self) -> Scalar: """ Get the value of the anti-shift for the Cayley spectral transformation. Not collective. Returns ------- Scalar The anti-shift. See Also -------- setCayleyAntishift, slepc.STCayleyGetAntishift """ cdef PetscScalar sval = 0 CHKERR( STCayleyGetAntishift(self.st, &sval) ) return toScalar(sval) def setFilterType(self, filter_type: FilterType) -> None: """ Set the method to be used to build the polynomial filter. Logically collective. Parameter --------- filter_type The type of filter. See Also -------- getFilterType, slepc.STFilterSetType """ cdef SlepcSTFilterType val = filter_type CHKERR( STFilterSetType(self.st, val) ) def getFilterType(self) -> FilterType: """ Get the method to be used to build the polynomial filter. Not collective. Returns ------- FilterType The type of filter. See Also -------- setFilterType, slepc.STFilterGetType """ cdef SlepcSTFilterType val = ST_FILTER_FILTLAN CHKERR( STFilterGetType(self.st, &val) ) return val def setFilterInterval(self, inta: float, intb: float) -> None: """ Set the interval containing the desired eigenvalues. Logically collective. Parameters ---------- inta The left end of the interval. intb The right end of the interval. Notes ----- The filter will be configured to emphasize eigenvalues contained in the given interval, and damp out eigenvalues outside it. If the interval is open, then the filter is low- or high-pass, otherwise it is mid-pass. Common usage is to set the interval in `EPS` with `EPS.setInterval()`. The interval must be contained within the numerical range of the matrix, see `setFilterRange()`. See Also -------- getFilterInterval, setFilterRange, slepc.STFilterSetInterval """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( STFilterSetInterval(self.st, rval1, rval2) ) def getFilterInterval(self) -> tuple[float, float]: """ Get the interval containing the desired eigenvalues. Not collective. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. See Also -------- setFilterInterval, slepc.STFilterGetInterval """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( STFilterGetInterval(self.st, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setFilterRange(self, left: float, right: float) -> None: """ Set the numerical range (or field of values) of the matrix. Logically collective. Set the numerical range (or field of values) of the matrix, that is, the interval containing all eigenvalues. Parameters ---------- left The left end of the spectral range. right The right end of the spectral range. Notes ----- The filter will be most effective if the numerical range is tight, that is, ``left`` and ``right`` are good approximations to the leftmost and rightmost eigenvalues, respectively. See Also -------- setFilterInterval, getFilterRange, slepc.STFilterSetRange """ cdef PetscReal rval1 = asReal(left) cdef PetscReal rval2 = asReal(right) CHKERR( STFilterSetRange(self.st, rval1, rval2) ) def getFilterRange(self) -> tuple[float, float]: """ Get the interval containing all eigenvalues. Not collective. Returns ------- left: float The left end of the spectral range. right: float The right end of the spectral range. See Also -------- getFilterInterval, slepc.STFilterGetRange """ cdef PetscReal left = 0 cdef PetscReal right = 0 CHKERR( STFilterGetRange(self.st, &left, &right) ) return (toReal(left), toReal(right)) def setFilterDegree(self, deg: int) -> None: """ Set the degree of the filter polynomial. Logically collective. Parameters ---------- deg The polynomial degree. See Also -------- getFilterDegree, slepc.STFilterSetDegree """ cdef PetscInt val = asInt(deg) CHKERR( STFilterSetDegree(self.st, val) ) def getFilterDegree(self) -> int: """ Get the degree of the filter polynomial. Not collective. Returns ------- int The polynomial degree. See Also -------- setFilterDegree, slepc.STFilterGetDegree """ cdef PetscInt val = 0 CHKERR( STFilterGetDegree(self.st, &val) ) return toInt(val) def setFilterDamping(self, damping: FilterDamping) -> None: """ Set the type of damping to be used in the polynomial filter. Logically collective. Parameter --------- damping The type of damping. Notes ----- Only used in `FilterType.CHEBYSHEV` filters. See Also -------- getFilterDamping, slepc.STFilterSetDamping """ cdef SlepcSTFilterDamping val = damping CHKERR( STFilterSetDamping(self.st, val) ) def getFilterDamping(self) -> FilterDamping: """ Get the type of damping used in the polynomial filter. Not collective. Returns ------- FilterDamping The type of damping. See Also -------- setFilterDamping, slepc.STFilterGetDamping """ cdef SlepcSTFilterDamping val = ST_FILTER_DAMPING_NONE CHKERR( STFilterGetDamping(self.st, &val) ) return val # property shift: """Value of the shift.""" def __get__(self) -> float: return self.getShift() def __set__(self, value): self.setShift(value) property transform: """If the transformed matrices are computed.""" def __get__(self) -> bool: return self.getTransform() def __set__(self, value): self.setTransform(value) property mat_mode: """How the transformed matrices are being stored in the ST.""" def __get__(self) -> STMatMode: return self.getMatMode() def __set__(self, value): self.setMatMode(value) property mat_structure: """Relation of the sparsity pattern of all ST matrices.""" def __get__(self) -> MatStructure: return self.getMatStructure() def __set__(self, value): self.setMatStructure(value) property ksp: """KSP object associated with the spectral transformation.""" def __get__(self) -> KSP: return self.getKSP() def __set__(self, value): self.setKSP(value) # ----------------------------------------------------------------------------- del STType del STMatMode del STFilterType del STFilterDamping # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/SVD.pyx0000644000076500000240000015765615133663436017252 0ustar00jromanstaff# ----------------------------------------------------------------------------- class SVDType(object): """ SVD type. Native singular value solvers. - `CROSS`: Eigenproblem with the cross-product matrix. - `CYCLIC`: Eigenproblem with the cyclic matrix. - `LANCZOS`: Explicitly restarted Lanczos. - `TRLANCZOS`: Thick-restart Lanczos. - `RANDOMIZED`: Iterative RSVD for low-rank matrices. Wrappers to external SVD solvers (should be enabled during installation of SLEPc). - `LAPACK`: Sequential dense SVD solver. - `SCALAPACK`: Parallel dense SVD solver. - `KSVD`: Parallel dense SVD solver. - `ELEMENTAL`: Parallel dense SVD solver. - `PRIMME`: Iterative SVD solvers of Davidson type. See Also -------- slepc.SVDType """ CROSS = S_(SVDCROSS) CYCLIC = S_(SVDCYCLIC) LAPACK = S_(SVDLAPACK) LANCZOS = S_(SVDLANCZOS) TRLANCZOS = S_(SVDTRLANCZOS) RANDOMIZED = S_(SVDRANDOMIZED) SCALAPACK = S_(SVDSCALAPACK) KSVD = S_(SVDKSVD) ELEMENTAL = S_(SVDELEMENTAL) PRIMME = S_(SVDPRIMME) class SVDProblemType(object): """ SVD problem type. - `STANDARD`: Standard SVD. - `GENERALIZED`: Generalized singular value decomposition (GSVD). - `HYPERBOLIC` : Hyperbolic singular value decomposition (HSVD). See Also -------- slepc.SVDProblemType """ STANDARD = SVD_STANDARD GENERALIZED = SVD_GENERALIZED HYPERBOLIC = SVD_HYPERBOLIC class SVDErrorType(object): """ SVD error type to assess accuracy of computed solutions. - `ABSOLUTE`: Absolute error. - `RELATIVE`: Relative error. - `NORM`: Error relative to the matrix norm. See Also -------- slepc.SVDErrorType """ ABSOLUTE = SVD_ERROR_ABSOLUTE RELATIVE = SVD_ERROR_RELATIVE NORM = SVD_ERROR_NORM class SVDWhich(object): """ SVD desired part of spectrum. - `LARGEST`: Largest singular values. - `SMALLEST`: Smallest singular values. See Also -------- slepc.SVDWhich """ LARGEST = SVD_LARGEST SMALLEST = SVD_SMALLEST class SVDConv(object): """ SVD convergence test. - `ABS`: Absolute convergence test. - `REL`: Convergence test relative to the singular value. - `NORM`: Convergence test relative to the matrix norms. - `MAXIT`: No convergence until maximum number of iterations has been reached. - `USER`: User-defined convergence test. See Also -------- slepc.SVDConv """ ABS = SVD_CONV_ABS REL = SVD_CONV_REL NORM = SVD_CONV_NORM MAXIT = SVD_CONV_MAXIT USER = SVD_CONV_USER class SVDStop(object): """ SVD stopping test. - `BASIC`: Default stopping test. - `USER`: User-defined stopping test. - `THRESHOLD`: Threshold stopping test. See Also -------- slepc.SVDStop """ BASIC = SVD_STOP_BASIC USER = SVD_STOP_USER THRESHOLD = SVD_STOP_THRESHOLD class SVDConvergedReason(object): """ SVD convergence reasons. - `CONVERGED_TOL`: All eigenpairs converged to requested tolerance. - `CONVERGED_USER`: User-defined convergence criterion satisfied. - `CONVERGED_MAXIT`: Maximum iterations completed in case MAXIT convergence criterion. - `DIVERGED_ITS`: Maximum number of iterations exceeded. - `DIVERGED_BREAKDOWN`: Solver failed due to breakdown. - `DIVERGED_SYMMETRY_LOST`: Underlying indefinite eigensolver was not able to keep symmetry. - `CONVERGED_ITERATING`: Iteration not finished yet. See Also -------- slepc.SVDConvergedReason """ CONVERGED_TOL = SVD_CONVERGED_TOL CONVERGED_USER = SVD_CONVERGED_USER CONVERGED_MAXIT = SVD_CONVERGED_MAXIT DIVERGED_ITS = SVD_DIVERGED_ITS DIVERGED_BREAKDOWN = SVD_DIVERGED_BREAKDOWN DIVERGED_SYMMETRY_LOST = SVD_DIVERGED_SYMMETRY_LOST CONVERGED_ITERATING = SVD_CONVERGED_ITERATING ITERATING = SVD_CONVERGED_ITERATING class SVDTRLanczosGBidiag(object): """ SVD TRLanczos bidiagonalization choices for the GSVD case. - `SINGLE`: Single bidiagonalization (:math:`Q_A`). - `UPPER`: Joint bidiagonalization, both :math:`Q_A` and :math:`Q_B` in upper bidiagonal form. - `LOWER`: Joint bidiagonalization, :math:`Q_A` lower bidiagonal, :math:`Q_B` upper bidiagonal. See Also -------- slepc.SVDTRLanczosGBidiag """ SINGLE = SVD_TRLANCZOS_GBIDIAG_SINGLE UPPER = SVD_TRLANCZOS_GBIDIAG_UPPER LOWER = SVD_TRLANCZOS_GBIDIAG_LOWER # ----------------------------------------------------------------------------- cdef class SVD(Object): """ Singular Value Decomposition Solver. The Singular Value Decomposition Solver (`SVD`) is very similar to the `EPS` object, but intended for the computation of the partial SVD of a rectangular matrix. With this type of object, the user can specify an SVD problem and solve it with any of the different solvers encapsulated by the package. Some of these solvers are actually implemented through calls to `EPS` eigensolvers. """ Type = SVDType ProblemType = SVDProblemType ErrorType = SVDErrorType Which = SVDWhich Conv = SVDConv Stop = SVDStop ConvergedReason = SVDConvergedReason TRLanczosGBidiag = SVDTRLanczosGBidiag def __cinit__(self): self.obj = &self.svd self.svd = NULL def view(self, Viewer viewer=None) -> None: """ Print the SVD data structure. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- slepc.SVDView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDView(self.svd, vwr) ) def destroy(self) -> Self: """ Destroy the SVD object. Collective. See Also -------- slepc.SVDDestroy """ CHKERR( SVDDestroy(&self.svd) ) self.svd = NULL return self def reset(self) -> None: """ Reset the SVD object. Collective. See Also -------- slepc.SVDReset """ CHKERR( SVDReset(self.svd) ) def create(self, comm: Comm | None = None) -> Self: """ Create the SVD object. Collective. Parameters ---------- comm MPI communicator; if not provided, it defaults to all processes. See Also -------- slepc.SVDCreate """ cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT()) cdef SlepcSVD newsvd = NULL CHKERR( SVDCreate(ccomm, &newsvd) ) CHKERR( SlepcCLEAR(self.obj) ); self.svd = newsvd return self def setType(self, svd_type: Type | str) -> None: """ Set the particular solver to be used in the SVD object. Logically collective. Parameters ---------- svd_type The solver to be used. Notes ----- The default is `CROSS`. Normally, it is best to use `setFromOptions()` and then set the SVD type from the options database rather than by using this routine. Using the options database provides the user with maximum flexibility in evaluating the different available methods. See Also -------- getType, slepc.SVDSetType """ cdef SlepcSVDType cval = NULL svd_type = str2bytes(svd_type, &cval) CHKERR( SVDSetType(self.svd, cval) ) def getType(self) -> str: """ Get the SVD type of this object. Not collective. Returns ------- str The solver currently being used. See Also -------- setType, slepc.SVDGetType """ cdef SlepcSVDType svd_type = NULL CHKERR( SVDGetType(self.svd, &svd_type) ) return bytes2str(svd_type) def getOptionsPrefix(self) -> str: """ Get the prefix used for searching for all SVD options in the database. Not collective. Returns ------- str The prefix string set for this SVD object. See Also -------- setOptionsPrefix, appendOptionsPrefix, slepc.SVDGetOptionsPrefix """ cdef const char *prefix = NULL CHKERR( SVDGetOptionsPrefix(self.svd, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix: str | None = None) -> None: """ Set the prefix used for searching for all SVD options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all SVD option requests. Notes ----- A hyphen (-) must NOT be given at the beginning of the prefix name. The first character of all runtime options is AUTOMATICALLY the hyphen. For example, to distinguish between the runtime options for two different SVD contexts, one could call:: S1.setOptionsPrefix("svd1_") S2.setOptionsPrefix("svd2_") See Also -------- appendOptionsPrefix, getOptionsPrefix, slepc.SVDGetOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SVDSetOptionsPrefix(self.svd, cval) ) def appendOptionsPrefix(self, prefix: str | None = None) -> None: """ Append to the prefix used for searching for all SVD options in the database. Logically collective. Parameters ---------- prefix The prefix string to prepend to all SVD option requests. See Also -------- setOptionsPrefix, getOptionsPrefix, slepc.SVDAppendOptionsPrefix """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SVDAppendOptionsPrefix(self.svd, cval) ) def setFromOptions(self) -> None: """ Set SVD options from the options database. Collective. Notes ----- To see all options, run your program with the ``-help`` option. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. See Also -------- setOptionsPrefix, slepc.SVDSetFromOptions """ CHKERR( SVDSetFromOptions(self.svd) ) def getProblemType(self) -> ProblemType: """ Get the problem type from the SVD object. Not collective. Returns ------- ProblemType The problem type that was previously set. See Also -------- setProblemType, slepc.SVDGetProblemType """ cdef SlepcSVDProblemType val = SVD_STANDARD CHKERR( SVDGetProblemType(self.svd, &val) ) return val def setProblemType(self, problem_type: ProblemType) -> None: """ Set the type of the singular value problem. Logically collective. Parameters ---------- problem_type The problem type to be set. Notes ----- The GSVD requires that two matrices have been passed via `setOperators()`. The HSVD requires that a signature matrix has been passed via `setSignature()`. See Also -------- setOperators, setSignature, getProblemType, slepc.SVDSetProblemType """ cdef SlepcSVDProblemType val = problem_type CHKERR( SVDSetProblemType(self.svd, val) ) def isGeneralized(self) -> bool: """ Tell if the SVD corresponds to a generalized singular value problem. Not collective. Returns ------- bool ``True`` if two matrices were set with `setOperators()`. See Also -------- setProblemType, isHyperbolic, slepc.SVDIsGeneralized """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDIsGeneralized(self.svd, &tval) ) return toBool(tval) def isHyperbolic(self) -> bool: """ Tell whether the SVD object corresponds to a hyperbolic singular value problem. Not collective. Returns ------- bool ``True`` if the problem was specified as hyperbolic. See Also -------- setProblemType, isGeneralized, slepc.SVDIsHyperbolic """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDIsHyperbolic(self.svd, &tval) ) return toBool(tval) # def getImplicitTranspose(self) -> bool: """ Get the mode used to handle the transpose of the associated matrix. Not collective. Returns ------- bool How to handle the transpose (implicitly or not). See Also -------- setImplicitTranspose, slepc.SVDGetImplicitTranspose """ cdef PetscBool val = PETSC_FALSE CHKERR( SVDGetImplicitTranspose(self.svd, &val) ) return toBool(val) def setImplicitTranspose(self, mode: bool) -> None: """ Set how to handle the transpose of the associated matrix. Logically collective. Parameters ---------- impl How to handle the transpose (implicitly or not). Notes ----- By default, the transpose of the matrix is explicitly built (if the matrix has defined the ``Mat.transpose()`` operation). If this flag is set to ``True``, the solver does not build the transpose, but handles it implicitly via ``Mat.multTranspose()`` (or ``Mat.multHermitianTranspose()`` in the complex case). See Also -------- getImplicitTranspose, slepc.SVDSetImplicitTranspose """ cdef PetscBool val = asBool(mode) CHKERR( SVDSetImplicitTranspose(self.svd, val) ) def getWhichSingularTriplets(self) -> Which: """ Get which singular triplets are to be sought. Not collective. Returns ------- Which The singular values to be sought (either largest or smallest). See Also -------- setWhichSingularTriplets, slepc.SVDGetWhichSingularTriplets """ cdef SlepcSVDWhich val = SVD_LARGEST CHKERR( SVDGetWhichSingularTriplets(self.svd, &val) ) return val def setWhichSingularTriplets(self, which: Which) -> None: """ Set which singular triplets are to be sought. Logically collective. Parameters ---------- which The singular values to be sought (either largest or smallest). See Also -------- getWhichSingularTriplets, slepc.SVDSetWhichSingularTriplets """ cdef SlepcSVDWhich val = which CHKERR( SVDSetWhichSingularTriplets(self.svd, val) ) def getThreshold(self) -> tuple[float, bool]: """ Get the threshold used in the threshold stopping test. Not collective. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. See Also -------- setThreshold, slepc.SVDGetThreshold """ cdef PetscReal rval = 0 cdef PetscBool tval = PETSC_FALSE CHKERR( SVDGetThreshold(self.svd, &rval, &tval) ) return (toReal(rval), toBool(tval)) def setThreshold(self, thres: float, rel: bool = False) -> None: """ Set the threshold used in the threshold stopping test. Logically collective. Parameters ---------- thres The threshold. rel Whether the threshold is relative or not. Notes ----- This function internally sets a special stopping test based on the threshold, where singular values are computed in sequence until one of the computed singular values is below/above the threshold (depending on whether largest or smallest singular values are computed). In the case of largest singular values, the threshold can be made relative with respect to the largest singular value (i.e., the matrix norm). The details are given in `slepc.SVDSetThreshold`. See Also -------- setStoppingTest, getThreshold, slepc.SVDSetThreshold """ cdef PetscReal rval = asReal(thres) cdef PetscBool tval = asBool(rel) CHKERR( SVDSetThreshold(self.svd, rval, tval) ) def getTolerances(self) -> tuple[float, int]: """ Get the tolerance and maximum iteration count. Not collective. Get the tolerance and maximum iteration count used by the default SVD convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations. See Also -------- setTolerances, slepc.SVDGetTolerances """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( SVDGetTolerances(self.svd, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol: float | None = None, max_it: int | None = None) -> None: """ Set the tolerance and maximum iteration count used. Logically collective. Set the tolerance and maximum iteration count used by the default SVD convergence tests. Parameters ---------- tol The convergence tolerance. max_it The maximum number of iterations Notes ----- Use `DETERMINE` for ``max_it`` to assign a reasonably good value, which is dependent on the solution method. See Also -------- getTolerances, slepc.SVDSetTolerances """ cdef PetscReal rval = PETSC_CURRENT cdef PetscInt ival = PETSC_CURRENT if tol is not None: rval = asReal(tol) if max_it is not None: ival = asInt(max_it) CHKERR( SVDSetTolerances(self.svd, rval, ival) ) def getConvergenceTest(self) -> Conv: """ Get the method used to compute the error estimate used in the convergence test. Not collective. Returns ------- Conv The method used to compute the error estimate used in the convergence test. See Also -------- setConvergenceTest, slepc.SVDGetConvergenceTest """ cdef SlepcSVDConv conv = SVD_CONV_REL CHKERR( SVDGetConvergenceTest(self.svd, &conv) ) return conv def setConvergenceTest(self, conv: Conv) -> None: """ Set how to compute the error estimate used in the convergence test. Logically collective. Parameters ---------- conv The method used to compute the error estimate used in the convergence test. See Also -------- getConvergenceTest, slepc.SVDSetConvergenceTest """ cdef SlepcSVDConv tconv = conv CHKERR( SVDSetConvergenceTest(self.svd, tconv) ) def getTrackAll(self) -> bool: """ Get the flag indicating if all residual norms must be computed or not. Not collective. Returns ------- bool Whether the solver computes all residuals or not. See Also -------- setTrackAll, slepc.SVDGetTrackAll """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDGetTrackAll(self.svd, &tval) ) return toBool(tval) def setTrackAll(self, trackall: bool) -> None: """ Set flag to compute the residual of all singular triplets. Logically collective. Set if the solver must compute the residual of all approximate singular triplets or not. Parameters ---------- trackall Whether to compute all residuals or not. See Also -------- getTrackAll, slepc.SVDSetTrackAll """ cdef PetscBool tval = asBool(trackall) CHKERR( SVDSetTrackAll(self.svd, tval) ) def getDimensions(self) -> tuple[int, int, int]: """ Get the number of singular values to compute and the dimension of the subspace. Not collective. Returns ------- nsv: int Number of singular values to compute. ncv: int Maximum dimension of the subspace to be used by the solver. mpd: int Maximum dimension allowed for the projected problem. See Also -------- setDimensions, slepc.SVDGetDimensions """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 CHKERR( SVDGetDimensions(self.svd, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def setDimensions( self, nsv: int | None = None, ncv: int | None = None, mpd: int | None = None, ) -> None: """ Set the number of singular values to compute and the dimension of the subspace. Logically collective. Parameters ---------- nsv Number of singular values to compute. ncv Maximum dimension of the subspace to be used by the solver. mpd Maximum dimension allowed for the projected problem. Notes ----- Use `DETERMINE` for ``ncv`` and ``mpd`` to assign a reasonably good value, which is dependent on the solution method. The parameters ``ncv`` and ``mpd`` are intimately related, so that the user is advised to set one of them at most. Normal usage is the following: + In cases where ``nsv`` is small, the user sets ``ncv`` (a reasonable default is 2 * ``nsv``). + In cases where ``nsv`` is large, the user sets ``mpd``. The value of ``ncv`` should always be between ``nsv`` and (``nsv`` + ``mpd``), typically ``ncv`` = ``nsv`` + ``mpd``. If ``nsv`` is not too large, ``mpd`` = ``nsv`` is a reasonable choice, otherwise a smaller value should be used. See Also -------- getDimensions, slepc.SVDSetDimensions """ cdef PetscInt ival1 = PETSC_CURRENT cdef PetscInt ival2 = PETSC_CURRENT cdef PetscInt ival3 = PETSC_CURRENT if nsv is not None: ival1 = asInt(nsv) if ncv is not None: ival2 = asInt(ncv) if mpd is not None: ival3 = asInt(mpd) CHKERR( SVDSetDimensions(self.svd, ival1, ival2, ival3) ) def getBV(self) -> tuple[BV, BV]: """ Get the basis vectors objects associated to the SVD object. Not collective. Returns ------- V: BV The basis vectors context for right singular vectors. U: BV The basis vectors context for left singular vectors. See Also -------- setBV, slepc.SVDGetBV """ cdef BV V = BV() cdef BV U = BV() CHKERR( SVDGetBV(self.svd, &V.bv, &U.bv) ) CHKERR( PetscINCREF(V.obj) ) CHKERR( PetscINCREF(U.obj) ) return (V,U) def setBV(self, BV V,BV U=None) -> None: """ Set basis vectors objects associated to the SVD solver. Collective. Parameters ---------- V The basis vectors context for right singular vectors. U The basis vectors context for left singular vectors. See Also -------- getBV, slepc.SVDSetBV """ cdef SlepcBV VBV = V.bv cdef SlepcBV UBV = U.bv if U is not None else NULL CHKERR( SVDSetBV(self.svd, VBV, UBV) ) def getDS(self) -> DS: """ Get the direct solver associated to the singular value solver. Not collective. Returns ------- DS The direct solver context. See Also -------- setDS, slepc.SVDGetDS """ cdef DS ds = DS() CHKERR( SVDGetDS(self.svd, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds) -> None: """ Set a direct solver object associated to the singular value solver. Collective. Parameters ---------- ds The direct solver context. See Also -------- getDS, slepc.SVDSetDS """ CHKERR( SVDSetDS(self.svd, ds.ds) ) def getOperators(self) -> tuple[Mat, Mat] | tuple[Mat, None]: """ Get the matrices associated with the singular value problem. Collective. Returns ------- A: petsc4py.PETSc.Mat The matrix associated with the singular value problem. B: petsc4py.PETSc.Mat The second matrix in the case of GSVD. See Also -------- setOperators, slepc.SVDGetOperators """ cdef Mat A = Mat() cdef Mat B = Mat() CHKERR( SVDGetOperators(self.svd, &A.mat, &B.mat) ) CHKERR( PetscINCREF(A.obj) ) if B.mat: CHKERR( PetscINCREF(B.obj) ) return (A, B) else: return (A, None) def setOperators(self, Mat A, Mat B=None) -> None: """ Set the matrices associated with the singular value problem. Collective. Parameters ---------- A The matrix associated with the singular value problem. B The second matrix in the case of GSVD. See Also -------- getOperators, slepc.SVDSetOperators """ cdef PetscMat Bmat = B.mat if B is not None else NULL CHKERR( SVDSetOperators(self.svd, A.mat, Bmat) ) def getSignature(self, Vec omega = None) -> Vec: """ Get the signature matrix defining a hyperbolic singular value problem. Collective. Parameters ---------- omega Optional vector to store the diagonal elements of the signature matrix. Returns ------- petsc4py.PETSc.Vec A vector containing the diagonal elements of the signature matrix. See Also -------- setSignature, slepc.SVDGetSignature """ cdef PetscMat A = NULL if omega is None: omega = Vec() if omega.vec == NULL: CHKERR( SVDGetOperators(self.svd, &A, NULL) ) CHKERR( MatCreateVecs(A, NULL, &omega.vec) ) CHKERR( SVDGetSignature(self.svd, omega.vec) ) return omega def setSignature(self, Vec omega=None) -> None: """ Set the signature matrix defining a hyperbolic singular value problem. Collective. Parameters ---------- omega A vector containing the diagonal elements of the signature matrix. See Also -------- getSignature, slepc.SVDSetSignature """ cdef PetscVec Ovec = omega.vec if omega is not None else NULL CHKERR( SVDSetSignature(self.svd, Ovec) ) # def setInitialSpace( self, spaceright: list[Vec] | None = None, spaceleft: list[Vec] | None = None, ) -> None: """ Set the initial spaces from which the SVD solver starts to iterate. Collective. Parameters ---------- spaceright The right initial space. spaceleft The left initial space. Notes ----- The initial right and left spaces are rough approximations to the right and/or left singular subspaces from which the solver starts to iterate. It is not necessary to provide both sets of vectors. Some solvers start to iterate on a single vector (initial vector). In that case, the other vectors are ignored. These vectors do not persist from one `solve()` call to the other, so the initial spaces should be set every time. The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. Common usage of this function is when the user can provide a rough approximation of the wanted singular spaces. Then, convergence may be faster. See Also -------- slepc.SVDSetInitialSpaces """ cdef Py_ssize_t i = 0 if spaceright is None: spaceright = [] elif isinstance(spaceright, Vec): spaceright = [spaceright] cdef PetscVec *isr = NULL cdef Py_ssize_t nr = len(spaceright) cdef tmp1 = allocate(nr*sizeof(PetscVec),&isr) for i in range(nr): isr[i] = (spaceright[i]).vec if spaceleft is None: spaceright = [] elif isinstance(spaceleft, Vec): spaceleft = [spaceleft] cdef PetscVec *isl = NULL cdef Py_ssize_t nl = len(spaceleft) cdef tmp2 = allocate(nl*sizeof(PetscVec),&isl) for i in range(nl): isl[i] = (spaceleft[i]).vec CHKERR( SVDSetInitialSpaces(self.svd, nr, isr, nl, isl) ) # def setStoppingTest( self, stopping: SVDStoppingFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Set a function to decide when to stop the outer iteration of the eigensolver. Logically collective. See Also -------- getStoppingTest, slepc.SVDSetStoppingTestFunction """ if stopping is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__stopping__', (stopping, args, kargs)) CHKERR( SVDSetStoppingTestFunction(self.svd, SVD_Stopping, NULL, NULL) ) else: self.set_attr('__stopping__', None) CHKERR( SVDSetStoppingTestFunction(self.svd, SVDStoppingBasic, NULL, NULL) ) def getStoppingTest(self) -> SVDStoppingFunction: """ Get the stopping test function. Not collective. Returns ------- SVDStoppingFunction The stopping test function. See Also -------- setStoppingTest """ return self.get_attr('__stopping__') # def setMonitor( self, monitor: SVDMonitorFunction | None, args: tuple[Any, ...] | None = None, kargs: dict[str, Any] | None = None, ) -> None: """ Append a monitor function to the list of monitors. Logically collective. See Also -------- getMonitor, cancelMonitor, slepc.SVDMonitorSet """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( SVDMonitorSet(self.svd, SVD_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self) -> SVDMonitorFunction: """ Get the list of monitor functions. Not collective. Returns ------- SVDMonitorFunction The list of monitor functions. See Also -------- setMonitor """ return self.get_attr('__monitor__') def cancelMonitor(self) -> None: """ Clear all monitors for an `SVD` object. Logically collective. See Also -------- slepc.SVDMonitorCancel """ CHKERR( SVDMonitorCancel(self.svd) ) self.set_attr('__monitor__', None) # def setUp(self) -> None: """ Set up all the internal data structures. Collective. Notes ----- Sets up all the internal data structures necessary for the execution of the singular value solver. This function need not be called explicitly in most cases, since `solve()` calls it. It can be useful when one wants to measure the set-up time separately from the solve time. See Also -------- solve, slepc.SVDSetUp """ CHKERR( SVDSetUp(self.svd) ) def solve(self) -> None: """ Solve the singular value problem. Collective. Notes ----- The problem matrices are specified with `setOperators()`. `solve()` will return without generating an error regardless of whether all requested solutions were computed or not. Call `getConverged()` to get the actual number of computed solutions, and `getConvergedReason()` to determine if the solver converged or failed and why. See Also -------- setUp, setOperators, getConverged, getConvergedReason, slepc.SVDSolve """ CHKERR( SVDSolve(self.svd) ) def getIterationNumber(self) -> int: """ Get the current iteration number. Not collective. If the call to `solve()` is complete, then it returns the number of iterations carried out by the solution method. Returns ------- int Iteration number. See Also -------- getConvergedReason, setTolerances, slepc.SVDGetIterationNumber """ cdef PetscInt ival = 0 CHKERR( SVDGetIterationNumber(self.svd, &ival) ) return toInt(ival) def getConvergedReason(self) -> ConvergedReason: """ Get the reason why the `solve()` iteration was stopped. Not collective. Returns ------- ConvergedReason Negative value indicates diverged, positive value converged. See Also -------- setTolerances, solve, slepc.SVDGetConvergedReason """ cdef SlepcSVDConvergedReason val = SVD_CONVERGED_ITERATING CHKERR( SVDGetConvergedReason(self.svd, &val) ) return val def getConverged(self) -> int: """ Get the number of converged singular triplets. Not collective. Returns ------- nconv: int Number of converged singular triplets. Notes ----- This function should be called after `solve()` has finished. The value ``nconv`` may be different from the number of requested solutions ``nsv``, but not larger than ``ncv``, see `setDimensions()`. See Also -------- setDimensions, solve, getValue, slepc.SVDGetConverged """ cdef PetscInt ival = 0 CHKERR( SVDGetConverged(self.svd, &ival) ) return toInt(ival) def getValue(self, i: int) -> float: """ Get the i-th singular value as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. Returns ------- float The computed singular value. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet """ cdef PetscReal rval = 0 CHKERR( SVDGetSingularTriplet(self.svd, i, &rval, NULL, NULL) ) return toReal(rval) def getVectors(self, i: int, Vec U, Vec V) -> None: """ Get the i-th left and right singular vectors as computed by `solve()`. Collective. Parameters ---------- i Index of the solution to be obtained. U Placeholder for the returned left singular vector. V Placeholder for the returned right singular vector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet """ cdef PetscReal dummy = 0 CHKERR( SVDGetSingularTriplet(self.svd, i, &dummy, U.vec, V.vec) ) def getSingularTriplet(self, i: int, Vec U=None, Vec V=None) -> float: """ Get the i-th triplet of the singular value decomposition. Collective. Get the i-th triplet of the singular value decomposition as computed by `solve()`. The solution consists of the singular value and its left and right singular vectors. Parameters ---------- i Index of the solution to be obtained. U Placeholder for the returned left singular vector. V Placeholder for the returned right singular vector. Returns ------- float The computed singular value. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`. Singular triplets are indexed according to the ordering criterion established with `setWhichSingularTriplets()`. See Also -------- getConverged, setWhichSingularTriplets, slepc.SVDGetSingularTriplet """ cdef PetscReal rval = 0 cdef PetscVec Uvec = U.vec if U is not None else NULL cdef PetscVec Vvec = V.vec if V is not None else NULL CHKERR( SVDGetSingularTriplet(self.svd, i, &rval, Uvec, Vvec) ) return toReal(rval) # def computeError(self, i: int, etype: ErrorType | None = None) -> float: """ Compute the error associated with the i-th singular triplet. Collective. Compute the error (based on the residual norm) associated with the i-th singular triplet. Parameters ---------- i Index of the solution to be considered. etype The error type to compute. Returns ------- float The error bound, computed in various ways from the residual norm :math:`\sqrt{\eta_1^2+\eta_2^2}` where :math:`\eta_1 = \|A v - \sigma u\|_2`, :math:`\eta_2 = \|A^* u - \sigma v\|_2`, :math:`\sigma` is the approximate singular value, :math:`u` and :math:`v` are the left and right singular vectors. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). In the case of the GSVD, the two components of the residual norm are :math:`\eta_1 = \|s^2 A^*u-cB^*Bx\|_2` and :math:`\eta_2 = ||c^2 B^*v-sA^*Ax||_2`, where :math:`(\sigma,u,v,x)` is the approximate generalized singular quadruple, with :math:`\sigma=c/s`. See Also -------- solve, slepc.SVDComputeError """ cdef SlepcSVDErrorType et = SVD_ERROR_RELATIVE cdef PetscReal rval = 0 if etype is not None: et = etype CHKERR( SVDComputeError(self.svd, i, et, &rval) ) return toReal(rval) def errorView(self, etype: ErrorType | None = None, viewer: petsc4py.PETSc.Viewer | None = None) -> None: """ Display the errors associated with the computed solution. Collective. Display the errors and the singular values. Parameters ---------- etype The error type to compute. viewer Visualization context; if not provided, the standard output is used. Notes ----- By default, this function checks the error of all singular triplets and prints the singular values if all of them are below the requested tolerance. If the viewer has format ``ASCII_INFO_DETAIL`` then a table with singular values and corresponding errors is printed. See Also -------- solve, valuesView, vectorsView, slepc.SVDErrorView """ cdef SlepcSVDErrorType et = SVD_ERROR_RELATIVE if etype is not None: et = etype cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDErrorView(self.svd, et, vwr) ) def valuesView(self, viewer: Viewer | None = None) -> None: """ Display the computed singular values in a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, vectorsView, errorView, slepc.SVDValuesView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDValuesView(self.svd, vwr) ) def vectorsView(self, viewer: Viewer | None = None) -> None: """ Output computed singular vectors to a viewer. Collective. Parameters ---------- viewer Visualization context; if not provided, the standard output is used. See Also -------- solve, valuesView, errorView, slepc.SVDVectorsView """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDVectorsView(self.svd, vwr) ) # def setCrossEPS(self, EPS eps) -> None: """ Set an eigensolver object associated to the singular value solver. Collective. Parameters ---------- eps The eigensolver object. See Also -------- getCrossEPS, slepc.SVDCrossSetEPS """ CHKERR( SVDCrossSetEPS(self.svd, eps.eps) ) def getCrossEPS(self) -> EPS: """ Get the eigensolver object associated to the singular value solver. Collective. Returns ------- EPS The eigensolver object. See Also -------- setCrossEPS, slepc.SVDCrossGetEPS """ cdef EPS eps = EPS() CHKERR( SVDCrossGetEPS(self.svd, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setCrossExplicitMatrix(self, flag: bool = True) -> None: """ Set if the eigensolver operator :math:`A^*A` must be computed. Logically collective. Parameters ---------- flag ``True`` to build :math:`A^*A` explicitly. Notes ----- In GSVD there are two cross product matrices, :math:`A^*A` and :math:`B^*B`. In HSVD the expression for the cross product matrix is different, :math:`A^*\Omega A`. By default the matrices are not built explicitly, but handled as shell matrices See Also -------- getCrossExplicitMatrix, slepc.SVDCrossSetExplicitMatrix """ cdef PetscBool tval = asBool(flag) CHKERR( SVDCrossSetExplicitMatrix(self.svd, tval) ) def getCrossExplicitMatrix(self) -> bool: """ Get the flag indicating if :math:`A^*A` is built explicitly. Not collective. Returns ------- bool ``True`` if :math:`A^*A` is built explicitly. See Also -------- setCrossExplicitMatrix, slepc.SVDCrossGetExplicitMatrix """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDCrossGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) def setCyclicEPS(self, EPS eps) -> None: """ Set an eigensolver object associated to the singular value solver. Collective. Parameters ---------- eps The eigensolver object. See Also -------- getCyclicEPS, slepc.SVDCyclicSetEPS """ CHKERR( SVDCyclicSetEPS(self.svd, eps.eps) ) def getCyclicEPS(self) -> EPS: """ Get the eigensolver object associated to the singular value solver. Collective. Returns ------- EPS The eigensolver object. See Also -------- setCyclicEPS, slepc.SVDCyclicGetEPS """ cdef EPS eps = EPS() CHKERR( SVDCyclicGetEPS(self.svd, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setCyclicExplicitMatrix(self, flag: bool = True) -> None: """ Set if the eigensolver operator :math:`H(A)` must be computed explicitly. Logically collective. Set if the eigensolver operator :math:`H(A) = [ 0\; A ; A^T\; 0 ]` must be computed explicitly. Parameters ---------- flag ``True`` if :math:`H(A)` must be built explicitly. Notes ----- In GSVD and HSVD the equivalent eigenvalue problem has generalized form, and hence two matrices are built. By default the matrices are not built explicitly, but handled as shell matrices. See Also -------- getCyclicExplicitMatrix, slepc.SVDCyclicSetExplicitMatrix """ cdef PetscBool tval = asBool(flag) CHKERR( SVDCyclicSetExplicitMatrix(self.svd, tval) ) def getCyclicExplicitMatrix(self) -> bool: """ Get the flag indicating if :math:`H(A)` is built explicitly. Not collective. Get the flag indicating if :math:`H(A) = [ 0\; A ; A^T\; 0 ]` is built explicitly. Returns ------- bool ``True`` if :math:`H(A)` is built explicitly. See Also -------- setCyclicExplicitMatrix, slepc.SVDCyclicGetExplicitMatrix """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDCyclicGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) def setLanczosOneSide(self, flag: bool = True) -> None: """ Set if the variant of the Lanczos method to be used is one-sided or two-sided. Logically collective. Parameters ---------- flag ``True`` if the method is one-sided. Notes ----- By default, a two-sided variant is selected, which is sometimes slightly more robust. However, the one-sided variant is faster because it avoids the orthogonalization associated to left singular vectors. It also saves the memory required for storing such vectors. See Also -------- getLanczosOneSide, slepc.SVDLanczosSetOneSide """ cdef PetscBool tval = asBool(flag) CHKERR( SVDLanczosSetOneSide(self.svd, tval) ) def getLanczosOneSide(self) -> bool: """ Get if the variant of the Lanczos method to be used is one-sided or two-sided. Not collective. Returns ------- bool ``True`` if the method is one-sided. See Also -------- setLanczosOneSide, slepc.SVDLanczosGetOneSide """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDLanczosGetOneSide(self.svd, &tval) ) return toBool(tval) def setTRLanczosOneSide(self, flag: bool = True) -> None: """ Set if the variant of the method to be used is one-sided or two-sided. Logically collective. Set if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Parameters ---------- flag ``True`` if the method is one-sided. Notes ----- By default, a two-sided variant is selected, which is sometimes slightly more robust. However, the one-sided variant is faster because it avoids the orthogonalization associated to left singular vectors. See Also -------- getTRLanczosOneSide, slepc.SVDLanczosSetOneSide """ cdef PetscBool tval = asBool(flag) CHKERR( SVDLanczosSetOneSide(self.svd, tval) ) def getTRLanczosOneSide(self) -> bool: """ Get if the variant of the method to be used is one-sided or two-sided. Not collective. Get if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Returns ------- bool ``True`` if the method is one-sided. See Also -------- setTRLanczosOneSide, slepc.SVDLanczosGetOneSide """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetOneSide(self.svd, &tval) ) return toBool(tval) def setTRLanczosGBidiag(self, bidiag: TRLanczosGBidiag) -> None: """ Set the bidiagonalization choice to use in the GSVD TRLanczos solver. Logically collective. Parameters ---------- bidiag The bidiagonalization choice. See Also -------- getTRLanczosGBidiag, slepc.SVDTRLanczosSetGBidiag """ cdef SlepcSVDTRLanczosGBidiag val = bidiag CHKERR( SVDTRLanczosSetGBidiag(self.svd, val) ) def getTRLanczosGBidiag(self) -> TRLanczosGBidiag: """ Get bidiagonalization choice used in the GSVD TRLanczos solver. Not collective. Returns ------- TRLanczosGBidiag The bidiagonalization choice. See Also -------- setTRLanczosGBidiag, slepc.SVDTRLanczosGetGBidiag """ cdef SlepcSVDTRLanczosGBidiag val = SVD_TRLANCZOS_GBIDIAG_LOWER CHKERR( SVDTRLanczosGetGBidiag(self.svd, &val) ) return val def setTRLanczosRestart(self, keep: float) -> None: """ Set the restart parameter for the thick-restart Lanczos method. Logically collective. Set the restart parameter for the thick-restart Lanczos method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep The number of vectors to be kept at restart. Notes ----- Allowed values are in the range [0.1,0.9]. The default is 0.5. See Also -------- getTRLanczosRestart, slepc.SVDTRLanczosSetRestart """ cdef PetscReal val = asReal(keep) CHKERR( SVDTRLanczosSetRestart(self.svd, val) ) def getTRLanczosRestart(self) -> float: """ Get the restart parameter used in the thick-restart Lanczos method. Not collective. Returns ------- float The number of vectors to be kept at restart. See Also -------- setTRLanczosRestart, slepc.SVDTRLanczosGetRestart """ cdef PetscReal val = 0 CHKERR( SVDTRLanczosGetRestart(self.svd, &val) ) return toReal(val) def setTRLanczosLocking(self, lock: bool) -> None: """ Toggle between locking and non-locking variants of TRLanczos. Logically collective. Parameters ---------- lock ``True`` if the locking variant must be selected. Notes ----- The default is to lock converged singular triplets when the method restarts. This behavior can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). See Also -------- getTRLanczosLocking, slepc.SVDTRLanczosSetLocking """ cdef PetscBool val = asBool(lock) CHKERR( SVDTRLanczosSetLocking(self.svd, val) ) def getTRLanczosLocking(self) -> bool: """ Get the locking flag used in the thick-restart Lanczos method. Not collective. Returns ------- bool The locking flag. See Also -------- setTRLanczosLocking, slepc.SVDTRLanczosGetLocking """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetLocking(self.svd, &tval) ) return toBool(tval) def setTRLanczosKSP(self, KSP ksp) -> None: """ Set a linear solver object associated to the SVD solver. Collective. Parameters ---------- ``ksp`` The linear solver object. See Also -------- getTRLanczosKSP, slepc.SVDTRLanczosSetKSP """ CHKERR( SVDTRLanczosSetKSP(self.svd, ksp.ksp) ) def getTRLanczosKSP(self) -> KSP: """ Get the linear solver object associated with the SVD solver. Collective. Returns ------- `petsc4py.PETSc.KSP` The linear solver object. See Also -------- setTRLanczosKSP, slepc.SVDTRLanczosGetKSP """ cdef KSP ksp = KSP() CHKERR( SVDTRLanczosGetKSP(self.svd, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setTRLanczosExplicitMatrix(self, flag: bool = True) -> None: """ Set if the matrix :math:`Z=[A^*,B^*]^*` must be built explicitly. Logically collective. Parameters ---------- flag ``True`` if :math:`Z=[A^*,B^*]^*` is built explicitly. Notes ----- This option is relevant for the GSVD case only. :math:`Z` is the coefficient matrix of the least-squares solver used internally. See Also -------- getTRLanczosExplicitMatrix, slepc.SVDTRLanczosSetExplicitMatrix """ cdef PetscBool tval = asBool(flag) CHKERR( SVDTRLanczosSetExplicitMatrix(self.svd, tval) ) def getTRLanczosExplicitMatrix(self) -> bool: """ Get the flag indicating if :math:`Z=[A^*,B^*]^*` is built explicitly. Not collective. Returns ------- bool ``True`` if :math:`Z=[A^*,B^*]^*` is built explicitly. See Also -------- setTRLanczosExplicitMatrix, slepc.SVDTRLanczosGetExplicitMatrix """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) setOperator = setOperators # backward compatibility # property problem_type: """The type of the eigenvalue problem.""" def __get__(self) -> SVDProblemType: return self.getProblemType() def __set__(self, value): self.setProblemType(value) property transpose_mode: """How to handle the transpose of the matrix.""" def __get__(self) -> bool: return self.getTransposeMode() def __set__(self, value): self.setTransposeMode(value) property which: """The portion of the spectrum to be sought.""" def __get__(self) -> SVDWhich: return self.getWhichSingularTriplets() def __set__(self, value): self.setWhichSingularTriplets(value) property tol: """The tolerance.""" def __get__(self) -> float: return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: """The maximum iteration count.""" def __get__(self) -> int: return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property track_all: """Compute the residual norm of all approximate eigenpairs.""" def __get__(self) -> bool: return self.getTrackAll() def __set__(self, value): self.setTrackAll(value) property ds: """The direct solver (`DS`) object associated.""" def __get__(self) -> DS: return self.getDS() def __set__(self, value): self.setDS(value) # ----------------------------------------------------------------------------- del SVDType del SVDProblemType del SVDErrorType del SVDWhich del SVDConv del SVDStop del SVDConvergedReason del SVDTRLanczosGBidiag # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/Sys.pyx0000644000076500000240000000717215133663436017357 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef class Sys: """ System utilities. """ @classmethod def getVersion( cls, devel: bool = False, date: bool = False, author: bool = False, ) -> tuple[int, int, int]: """Return SLEPc version information. Not collective. Parameters ---------- devel Additionally, return whether using an in-development version. date Additionally, return date information. author Additionally, return author information. Returns ------- major: int Major version number. minor: int Minor version number. micro: int Micro (or patch) version number. See Also -------- slepc.SlepcGetVersion, slepc.SlepcGetVersionNumber """ cdef char cversion[256] cdef PetscInt major=0, minor=0, micro=0, release=0 CHKERR( SlepcGetVersion(cversion, sizeof(cversion)) ) CHKERR( SlepcGetVersionNumber(&major, &minor, µ, &release) ) out = version = (toInt(major), toInt(minor), toInt(micro)) if devel or date or author: out = [version] if devel: out.append(not release) if date: vstr = bytes2str(cversion) if release != 0: date = vstr.split(",", 1)[-1].strip() else: date = vstr.split("Git Date:")[-1].strip() out.append(date) if author: author = bytes2str(SLEPC_AUTHOR_INFO).split('\n') author = tuple([s.strip() for s in author if s]) out.append(author) return tuple(out) @classmethod def getVersionInfo(cls) -> dict[str, bool | int | str]: """Return SLEPc version information. Not collective. Returns ------- info: dict Dictionary with version information. See Also -------- slepc.SlepcGetVersion, slepc.SlepcGetVersionNumber """ version, dev, date, author = cls.getVersion(True, True, True) return dict(major = version[0], minor = version[1], subminor = version[2], release = not dev, date = date, authorinfo = author) # --- xxx --- @classmethod def isInitialized(cls) -> bool: """Return whether SLEPc has been initialized. Not collective. See Also -------- isFinalized """ return toBool(SlepcInitializeCalled) @classmethod def isFinalized(cls) -> bool: """Return whether SLEPc has been finalized. Not collective. See Also -------- isInitialized """ return toBool(SlepcFinalizeCalled) # --- xxx --- @classmethod def hasExternalPackage(cls, package: str) -> bool: """Return whether SLEPc has support for external package. Not collective. Parameters ---------- package The external package name. See Also -------- slepc.SlepcHasExternalPackage """ cdef const char *cpackage = NULL package = str2bytes(package, &cpackage) cdef PetscBool has = PETSC_FALSE CHKERR( SlepcHasExternalPackage(cpackage, &has) ) return toBool(has) # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/Util.pyx0000644000076500000240000000365715133663436017522 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef class Util: """ Other utilities such as the creation of structured matrices. """ @classmethod def createMatBSE(cls, Mat R: petsc4py.PETSc.Mat, Mat C: petsc4py.PETSc.Mat) -> petsc4py.PETSc.Mat: """ Create a matrix that can be used to define a BSE type problem. Collective. Create a matrix that can be used to define a structured eigenvalue problem of type BSE (Bethe-Salpeter Equation). Parameters ---------- R The matrix for the diagonal block (resonant). C The matrix for the off-diagonal block (coupling). Returns ------- petsc4py.PETSc.Mat The matrix with the block form :math:`H = [ R\; C; {-C}^*\; {-R}^T ]`. See Also -------- slepc.MatCreateBSE """ cdef Mat H = Mat() CHKERR( MatCreateBSE(R.mat, C.mat, &H.mat) ) return H @classmethod def createMatHamiltonian(cls, Mat A: petsc4py.PETSc.Mat, Mat B: petsc4py.PETSc.Mat, Mat C: petsc4py.PETSc.Mat) -> petsc4py.PETSc.Mat: """ Create matrix to be used for a structured Hamiltonian eigenproblem. Collective. Parameters ---------- A The matrix for (0,0) block. B The matrix for (0,1) block, must be real symmetric or Hermitian. C The matrix for (1,0) block, must be real symmetric or Hermitian. Returns ------- petsc4py.PETSc.Mat The matrix with the block form :math:`H = [ A\; B; C\; -A^* ]`. See Also -------- slepc.MatCreateHamiltonian """ cdef Mat H = Mat() CHKERR( MatCreateHamiltonian(A.mat, B.mat, C.mat, &H.mat) ) return H # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/allocate.pxi0000644000076500000240000000132215133663436020334 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef extern from "Python.h": enum: PY_SSIZE_T_MAX void *PyMem_Malloc(size_t) void *PyMem_Realloc(void*, size_t) void PyMem_Free(void*) #@cython.final #@cython.internal cdef class _p_mem: cdef void *buf def __cinit__(self): self.buf = NULL def __dealloc__(self): PyMem_Free(self.buf) cdef inline object allocate(size_t n, void **buf): cdef _p_mem ob = <_p_mem>_p_mem.__new__(_p_mem) ob.buf = PyMem_Malloc(n) if ob.buf == NULL: raise MemoryError if buf != NULL: buf[0] = ob.buf return ob # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/arraynpy.pxi0000644000076500000240000001706115133663436020424 0ustar00jromanstaff# -------------------------------------------------------------------- cdef extern from "": int import_array "_import_array" () except -1 ctypedef long npy_intp ctypedef extern class numpy.dtype [object PyArray_Descr]: pass ctypedef extern class numpy.ndarray [object PyArrayObject]: pass void* PyArray_DATA(ndarray) npy_intp PyArray_SIZE(ndarray) int PyArray_NDIM(ndarray) npy_intp* PyArray_DIMS(ndarray) npy_intp PyArray_DIM(ndarray, int) enum: NPY_INTP dtype PyArray_DescrFromType(int) object PyArray_TypeObjectFromType(int) enum: NPY_ARRAY_ALIGNED enum: NPY_ARRAY_WRITEABLE enum: NPY_ARRAY_NOTSWAPPED enum: NPY_ARRAY_CARRAY enum: NPY_ARRAY_CARRAY_RO enum: NPY_ARRAY_FARRAY enum: NPY_ARRAY_FARRAY_RO ndarray PyArray_FROM_O(object) ndarray PyArray_FROM_OT(object,int) ndarray PyArray_FROM_OTF(object,int,int) ndarray PyArray_Copy(ndarray) ndarray PyArray_ArangeObj(object,object,object,dtype) ndarray PyArray_EMPTY(int,npy_intp[],int,int) ndarray PyArray_ZEROS(int,npy_intp[],int,int) bint PyArray_ISCONTIGUOUS(ndarray) bint PyArray_ISFORTRAN(ndarray) ctypedef enum NPY_ORDER: NPY_ANYORDER NPY_CORDER NPY_FORTRANORDER ndarray PyArray_NewCopy(ndarray,NPY_ORDER) ctypedef struct PyObject ctypedef struct PyTypeObject ndarray PyArray_New(PyTypeObject*,int,npy_intp[],int,npy_intp[],void*,int,int,PyObject*) ndarray PyArray_SimpleNewFromData(int,npy_intp[],int,void*) int PyArray_SetBaseObject(ndarray,object) except -1 cdef extern from "": enum: NPY_INT enum: NPY_DOUBLE enum: NPY_PETSC_BOOL enum: NPY_PETSC_INT enum: NPY_PETSC_REAL enum: NPY_PETSC_SCALAR enum: NPY_PETSC_COMPLEX # -------------------------------------------------------------------- cdef inline ndarray asarray(object ob): return PyArray_FROM_O(ob) cdef inline ndarray arange(start, stop, stride): cdef dtype descr = PyArray_DescrFromType(NPY_PETSC_INT) return PyArray_ArangeObj(start, stop, stride, descr) # -------------------------------------------------------------------- cdef inline ndarray empty_i(PetscInt size): cdef npy_intp s = size return PyArray_EMPTY(1, &s, NPY_PETSC_INT, 0) cdef inline ndarray empty_r(PetscInt size): cdef npy_intp s = size return PyArray_EMPTY(1, &s, NPY_PETSC_REAL, 0) cdef inline ndarray empty_s(PetscInt size): cdef npy_intp s = size return PyArray_EMPTY(1, &s, NPY_PETSC_SCALAR, 0) cdef inline ndarray empty_c(PetscInt size): cdef npy_intp s = size return PyArray_EMPTY(1, &s, NPY_PETSC_COMPLEX, 0) cdef inline ndarray empty_p(PetscInt size): cdef npy_intp s = size return PyArray_EMPTY(1, &s, NPY_INTP, 0) # -------------------------------------------------------------------- cdef inline ndarray array_i(PetscInt size, const PetscInt* data): cdef npy_intp s = size cdef ndarray ary = PyArray_EMPTY(1, &s, NPY_PETSC_INT, 0) if data != NULL: memcpy(PyArray_DATA(ary), data, size*sizeof(PetscInt)) return ary cdef inline ndarray array_r(PetscInt size, const PetscReal* data): cdef npy_intp s = size cdef ndarray ary = PyArray_EMPTY(1, &s, NPY_PETSC_REAL, 0) if data != NULL: memcpy(PyArray_DATA(ary), data, size*sizeof(PetscReal)) return ary cdef inline ndarray array_b(PetscInt size, const PetscBool* data): cdef npy_intp s = size cdef ndarray ary = PyArray_EMPTY(1, &s, NPY_PETSC_BOOL, 0) if data != NULL: memcpy(PyArray_DATA(ary), data, size*sizeof(PetscBool)) return ary cdef inline ndarray array_s(PetscInt size, const PetscScalar* data): cdef npy_intp s = size cdef ndarray ary = PyArray_EMPTY(1, &s, NPY_PETSC_SCALAR, 0) if data != NULL: memcpy(PyArray_DATA(ary), data, size*sizeof(PetscScalar)) return ary # -------------------------------------------------------------------- cdef inline ndarray iarray(object ob, int typenum): cdef ndarray ary = PyArray_FROM_OTF( ob, typenum, NPY_ARRAY_ALIGNED|NPY_ARRAY_NOTSWAPPED) if PyArray_ISCONTIGUOUS(ary): return ary if PyArray_ISFORTRAN(ary): return ary return PyArray_Copy(ary) cdef inline ndarray iarray_i(object ob, PetscInt* size, PetscInt** data): cdef ndarray ary = iarray(ob, NPY_PETSC_INT) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray iarray_r(object ob, PetscInt* size, PetscReal** data): cdef ndarray ary = iarray(ob, NPY_PETSC_REAL) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray iarray_b(object ob, PetscInt* size, PetscBool** data): cdef ndarray ary = iarray(ob, NPY_PETSC_BOOL) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray iarray_s(object ob, PetscInt* size, PetscScalar** data): cdef ndarray ary = iarray(ob, NPY_PETSC_SCALAR) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary # -------------------------------------------------------------------- cdef inline ndarray oarray(object ob, int typenum): cdef ndarray ary = PyArray_FROM_OTF( ob, typenum, NPY_ARRAY_ALIGNED|NPY_ARRAY_WRITEABLE|NPY_ARRAY_NOTSWAPPED) if PyArray_ISCONTIGUOUS(ary): return ary if PyArray_ISFORTRAN(ary): return ary return PyArray_Copy(ary) cdef inline ndarray oarray_i(object ob, PetscInt* size, PetscInt** data): cdef ndarray ary = oarray(ob, NPY_PETSC_INT) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray oarray_r(object ob, PetscInt* size, PetscReal** data): cdef ndarray ary = oarray(ob, NPY_PETSC_REAL) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray oarray_s(object ob, PetscInt* size, PetscScalar** data): cdef ndarray ary = oarray(ob, NPY_PETSC_SCALAR) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray oarray_p(object ob, PetscInt* size, void** data): cdef ndarray ary = oarray(ob, NPY_INTP) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary # -------------------------------------------------------------------- cdef inline ndarray ocarray_s(object ob, PetscInt* size, PetscScalar** data): cdef ndarray ary = PyArray_FROM_OTF( ob, NPY_PETSC_SCALAR, NPY_ARRAY_CARRAY|NPY_ARRAY_NOTSWAPPED) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary cdef inline ndarray ofarray_s(object ob, PetscInt* size, PetscScalar** data): cdef ndarray ary = PyArray_FROM_OTF( ob, NPY_PETSC_SCALAR, NPY_ARRAY_FARRAY|NPY_ARRAY_NOTSWAPPED) if size != NULL: size[0] = PyArray_SIZE(ary) if data != NULL: data[0] = PyArray_DATA(ary) return ary # -------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcbv.pxi0000644000076500000240000002047415133663436020217 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcBVType "const char*" SlepcBVType BVMAT SlepcBVType BVSVEC SlepcBVType BVVECS SlepcBVType BVCONTIGUOUS SlepcBVType BVTENSOR ctypedef enum SlepcBVOrthogType "BVOrthogType": BV_ORTHOG_CGS BV_ORTHOG_MGS ctypedef enum SlepcBVOrthogRefineType "BVOrthogRefineType": BV_ORTHOG_REFINE_IFNEEDED BV_ORTHOG_REFINE_NEVER BV_ORTHOG_REFINE_ALWAYS ctypedef enum SlepcBVOrthogBlockType "BVOrthogBlockType": BV_ORTHOG_BLOCK_GS BV_ORTHOG_BLOCK_CHOL BV_ORTHOG_BLOCK_TSQR BV_ORTHOG_BLOCK_TSQRCHOL BV_ORTHOG_BLOCK_SVQB ctypedef enum SlepcBVMatMultType "BVMatMultType": BV_MATMULT_VECS BV_MATMULT_MAT ctypedef enum SlepcBVSVDMethod "BVSVDMethod": BV_SVD_METHOD_REFINE BV_SVD_METHOD_QR BV_SVD_METHOD_QR_CAA PetscErrorCode BVCreate(MPI_Comm,SlepcBV*) PetscErrorCode BVCreateMat(SlepcBV,PetscMat*) PetscErrorCode BVDuplicate(SlepcBV,SlepcBV*) PetscErrorCode BVDuplicateResize(SlepcBV,PetscInt,SlepcBV*) PetscErrorCode BVCopy(SlepcBV,SlepcBV) PetscErrorCode BVView(SlepcBV,PetscViewer) PetscErrorCode BVDestroy(SlepcBV*) PetscErrorCode BVSetType(SlepcBV,SlepcBVType) PetscErrorCode BVGetType(SlepcBV,SlepcBVType*) PetscErrorCode BVSetSizes(SlepcBV,PetscInt,PetscInt,PetscInt) PetscErrorCode BVSetSizesFromVec(SlepcBV,PetscVec,PetscInt) PetscErrorCode BVGetSizes(SlepcBV,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode BVResize(SlepcBV,PetscInt,PetscBool) PetscErrorCode BVSetLeadingDimension(SlepcBV,PetscInt) PetscErrorCode BVGetLeadingDimension(SlepcBV,PetscInt*) PetscErrorCode BVGetArray(SlepcBV,PetscScalar**) PetscErrorCode BVGetArrayRead(SlepcBV,const PetscScalar**) PetscErrorCode BVRestoreArray(SlepcBV,PetscScalar**) PetscErrorCode BVRestoreArrayRead(SlepcBV,const PetscScalar**) PetscErrorCode BVSetOptionsPrefix(SlepcBV,char[]) PetscErrorCode BVGetOptionsPrefix(SlepcBV,char*[]) PetscErrorCode BVAppendOptionsPrefix(SlepcBV,char[]) PetscErrorCode BVSetFromOptions(SlepcBV) PetscErrorCode BVSetOrthogonalization(SlepcBV,SlepcBVOrthogType,SlepcBVOrthogRefineType,PetscReal,SlepcBVOrthogBlockType) PetscErrorCode BVGetOrthogonalization(SlepcBV,SlepcBVOrthogType*,SlepcBVOrthogRefineType*,PetscReal*,SlepcBVOrthogBlockType*) PetscErrorCode BVSetMatMultMethod(SlepcBV,SlepcBVMatMultType) PetscErrorCode BVGetMatMultMethod(SlepcBV,SlepcBVMatMultType*) PetscErrorCode BVSetRandom(SlepcBV) PetscErrorCode BVSetRandomNormal(SlepcBV) PetscErrorCode BVSetRandomSign(SlepcBV) PetscErrorCode BVSetRandomColumn(SlepcBV,PetscInt) PetscErrorCode BVSetRandomCond(SlepcBV,PetscReal) PetscErrorCode BVSetRandomContext(SlepcBV,PetscRandom) PetscErrorCode BVGetRandomContext(SlepcBV,PetscRandom*) PetscErrorCode BVSetMatrix(SlepcBV,PetscMat,PetscBool) PetscErrorCode BVGetMatrix(SlepcBV,PetscMat*,PetscBool*) PetscErrorCode BVApplyMatrix(SlepcBV,PetscVec,PetscVec) PetscErrorCode BVSetActiveColumns(SlepcBV,PetscInt,PetscInt) PetscErrorCode BVGetActiveColumns(SlepcBV,PetscInt*,PetscInt*) PetscErrorCode BVSetDefiniteTolerance(SlepcBV,PetscReal) PetscErrorCode BVGetDefiniteTolerance(SlepcBV,PetscReal*) PetscErrorCode BVCreateVec(SlepcBV,PetscVec*) PetscErrorCode BVSetVecType(SlepcBV,PetscVecType) PetscErrorCode BVGetVecType(SlepcBV,PetscVecType*) PetscErrorCode BVInsertVec(SlepcBV,PetscInt,PetscVec) PetscErrorCode BVInsertVecs(SlepcBV,PetscInt,PetscInt*,PetscVec*,PetscBool) PetscErrorCode BVInsertConstraints(SlepcBV,PetscInt*,PetscVec*) PetscErrorCode BVSetNumConstraints(SlepcBV,PetscInt) PetscErrorCode BVGetNumConstraints(SlepcBV,PetscInt*) PetscErrorCode BVGetColumn(SlepcBV,PetscInt,PetscVec*) PetscErrorCode BVRestoreColumn(SlepcBV,PetscInt,PetscVec*) PetscErrorCode BVCopyVec(SlepcBV,PetscInt,PetscVec) PetscErrorCode BVCopyColumn(SlepcBV,PetscInt,PetscInt) PetscErrorCode BVDot(SlepcBV,SlepcBV,PetscMat) PetscErrorCode BVDotVec(SlepcBV,PetscVec,PetscScalar*) PetscErrorCode BVDotColumn(SlepcBV,PetscInt,PetscScalar*) PetscErrorCode BVMatProject(SlepcBV,PetscMat,SlepcBV,PetscMat) PetscErrorCode BVMatMult(SlepcBV,PetscMat,SlepcBV) PetscErrorCode BVMatMultTranspose(SlepcBV,PetscMat,SlepcBV) PetscErrorCode BVMatMultHermitianTranspose(SlepcBV,PetscMat,SlepcBV) PetscErrorCode BVMatMultColumn(SlepcBV,PetscMat,PetscInt) PetscErrorCode BVMatMultTransposeColumn(SlepcBV,PetscMat,PetscInt) PetscErrorCode BVMatMultHermitianTransposeColumn(SlepcBV,PetscMat,PetscInt) PetscErrorCode BVMult(SlepcBV,PetscScalar,PetscScalar,SlepcBV,PetscMat) PetscErrorCode BVMultColumn(SlepcBV,PetscScalar,PetscScalar,PetscInt,PetscScalar*) PetscErrorCode BVMultInPlace(SlepcBV,PetscMat,PetscInt,PetscInt) PetscErrorCode BVMultVec(SlepcBV,PetscScalar,PetscScalar,PetscVec,PetscScalar*) PetscErrorCode BVScaleColumn(SlepcBV,PetscInt,PetscScalar) PetscErrorCode BVScale(SlepcBV,PetscScalar) PetscErrorCode BVNormColumn(SlepcBV,PetscInt,PetscNormType,PetscReal*) PetscErrorCode BVNorm(SlepcBV,PetscNormType,PetscReal*) PetscErrorCode BVOrthogonalizeVec(SlepcBV,PetscVec,PetscScalar*,PetscReal*,PetscBool*) PetscErrorCode BVOrthogonalizeColumn(SlepcBV,PetscInt,PetscScalar*,PetscReal*,PetscBool*) PetscErrorCode BVOrthonormalizeColumn(SlepcBV,PetscInt,PetscBool,PetscReal*,PetscBool*) PetscErrorCode BVOrthogonalize(SlepcBV,PetscMat) PetscErrorCode BVCreateFromMat(PetscMat,SlepcBV*) PetscErrorCode BVGetMat(SlepcBV,PetscMat*) PetscErrorCode BVRestoreMat(SlepcBV,PetscMat*) cdef inline PetscErrorCode BV_Sizes( object size, PetscInt *_n, PetscInt *_N, ) except PETSC_ERR_PYTHON: # unpack and get local and global sizes cdef PetscInt n=PETSC_DECIDE, N=PETSC_DECIDE cdef object on, oN try: on, oN = size except (TypeError, ValueError): on = None; oN = size if on is not None: n = asInt(on) if oN is not None: N = asInt(oN) if n==PETSC_DECIDE and N==PETSC_DECIDE: raise ValueError( "local and global sizes cannot be both 'DECIDE'") # return result to the caller if _n != NULL: _n[0] = n if _N != NULL: _N[0] = N return PETSC_SUCCESS # -------------------------------------------------------------------- # unary operations cdef BV bv_pos(BV self): cdef BV bv = type(self)() CHKERR(BVDuplicate(self.bv, &bv.bv)) CHKERR(BVCopy(self.bv, bv.bv)) return bv cdef BV bv_neg(BV self): cdef BV bv = bv_pos(self) CHKERR(BVScale(bv.bv, -1)) return bv # inplace binary operations cdef BV bv_iadd(BV self, other): cdef PetscScalar alpha = 1, beta = 1 cdef BV bv if isinstance(other, BV): alpha = 1; bv = other CHKERR(BVMult(self.bv, alpha, beta, bv.bv, NULL)) return self elif isinstance(other, (tuple, list)): other, bv = other alpha = asScalar(other) CHKERR(BVMult(self.bv, alpha, beta, bv.bv, NULL)) return self return NotImplemented cdef BV bv_isub(BV self, other): cdef PetscScalar alpha = 1, beta = 1 cdef BV bv if isinstance(other, BV): alpha = 1; bv = other CHKERR(BVMult(self.bv, -alpha, beta, bv.bv, NULL)) return self elif isinstance(other, (tuple, list)): other, bv = other alpha = asScalar(other) CHKERR(BVMult(self.bv, -alpha, beta, bv.bv, NULL)) return self return NotImplemented cdef BV bv_imul(BV self, other): self.scale(other) return self cdef BV bv_idiv(BV self, other): other = 1/other self.scale(other) return self # binary operations cdef BV bv_add(BV self, other): return bv_iadd(bv_pos(self), other) cdef BV bv_sub(BV self, other): return bv_isub(bv_pos(self), other) cdef BV bv_mul(BV self, other): return bv_imul(bv_pos(self), other) cdef BV bv_div(BV self, other): return bv_idiv(bv_pos(self), other) # reflected binary operations cdef BV bv_radd(BV self, other): return bv_add(self, other) cdef BV bv_rsub(BV self, other): cdef BV bv = bv_sub(self, other) CHKERR(BVScale(bv.bv, -1)) return bv cdef BV bv_rmul(BV self, other): return bv_mul(self, other) cdef BV bv_rdiv(BV self, other): self; other # unused return NotImplemented ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcds.pxi0000644000076500000240000000777715133663436020231 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcDSType "const char*" SlepcDSType DSHEP SlepcDSType DSNHEP SlepcDSType DSGHEP SlepcDSType DSGHIEP SlepcDSType DSGNHEP SlepcDSType DSNHEPTS SlepcDSType DSSVD SlepcDSType DSHSVD SlepcDSType DSGSVD SlepcDSType DSPEP SlepcDSType DSNEP ctypedef enum SlepcDSStateType "DSStateType": DS_STATE_RAW DS_STATE_INTERMEDIATE DS_STATE_CONDENSED DS_STATE_TRUNCATED ctypedef enum SlepcDSMatType "DSMatType": DS_MAT_A DS_MAT_B DS_MAT_C DS_MAT_T DS_MAT_D DS_MAT_Q DS_MAT_Z DS_MAT_X DS_MAT_Y DS_MAT_U DS_MAT_V DS_MAT_W DS_NUM_MAT ctypedef enum SlepcDSParallelType "DSParallelType": DS_PARALLEL_REDUNDANT DS_PARALLEL_SYNCHRONIZED DS_PARALLEL_DISTRIBUTED PetscErrorCode DSCreate(MPI_Comm,SlepcDS*) PetscErrorCode DSView(SlepcDS,PetscViewer) PetscErrorCode DSDestroy(SlepcDS*) PetscErrorCode DSReset(SlepcDS) PetscErrorCode DSSetType(SlepcDS,SlepcDSType) PetscErrorCode DSGetType(SlepcDS,SlepcDSType*) PetscErrorCode DSSetOptionsPrefix(SlepcDS,char[]) PetscErrorCode DSGetOptionsPrefix(SlepcDS,char*[]) PetscErrorCode DSAppendOptionsPrefix(SlepcDS,char[]) PetscErrorCode DSSetFromOptions(SlepcDS) PetscErrorCode DSDuplicate(SlepcDS,SlepcDS*) PetscErrorCode DSAllocate(SlepcDS,PetscInt) PetscErrorCode DSGetLeadingDimension(SlepcDS,PetscInt*) PetscErrorCode DSSetState(SlepcDS,SlepcDSStateType) PetscErrorCode DSGetState(SlepcDS,SlepcDSStateType*) PetscErrorCode DSSetDimensions(SlepcDS,PetscInt,PetscInt,PetscInt) PetscErrorCode DSGetDimensions(SlepcDS,PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DSTruncate(SlepcDS,PetscInt,PetscBool) PetscErrorCode DSSetBlockSize(SlepcDS,PetscInt) PetscErrorCode DSGetBlockSize(SlepcDS,PetscInt*) PetscErrorCode DSSetMethod(SlepcDS,PetscInt) PetscErrorCode DSGetMethod(SlepcDS,PetscInt*) PetscErrorCode DSSetParallel(SlepcDS,SlepcDSParallelType) PetscErrorCode DSGetParallel(SlepcDS,SlepcDSParallelType*) PetscErrorCode DSSetCompact(SlepcDS,PetscBool) PetscErrorCode DSGetCompact(SlepcDS,PetscBool*) PetscErrorCode DSSetExtraRow(SlepcDS,PetscBool) PetscErrorCode DSGetExtraRow(SlepcDS,PetscBool*) PetscErrorCode DSSetRefined(SlepcDS,PetscBool) PetscErrorCode DSGetRefined(SlepcDS,PetscBool*) PetscErrorCode DSGetMat(SlepcDS,SlepcDSMatType,PetscMat*) PetscErrorCode DSRestoreMat(SlepcDS,SlepcDSMatType,PetscMat*) PetscErrorCode DSGetArray(SlepcDS,SlepcDSMatType,PetscScalar**) PetscErrorCode DSRestoreArray(SlepcDS,SlepcDSMatType,PetscScalar**) PetscErrorCode DSMatGetSize(SlepcDS,SlepcDSMatType,PetscInt*,PetscInt*) PetscErrorCode DSSetIdentity(SlepcDS,SlepcDSMatType) PetscErrorCode DSVectors(SlepcDS,SlepcDSMatType,PetscInt*,PetscReal*) PetscErrorCode DSSolve(SlepcDS,PetscScalar*,PetscScalar*) PetscErrorCode DSSort(SlepcDS,PetscScalar*,PetscScalar*,PetscScalar*,PetscScalar*,PetscInt*) PetscErrorCode DSUpdateExtraRow(SlepcDS) PetscErrorCode DSCond(SlepcDS,PetscReal*) PetscErrorCode DSTranslateHarmonic(SlepcDS,PetscScalar,PetscReal,PetscBool,PetscScalar*,PetscReal*) PetscErrorCode DSTranslateRKS(SlepcDS,PetscScalar) PetscErrorCode DSCond(SlepcDS,PetscReal*) PetscErrorCode DSNormalize(SlepcDS,SlepcDSMatType,PetscInt) PetscErrorCode DSSVDSetDimensions(SlepcDS,PetscInt) PetscErrorCode DSSVDGetDimensions(SlepcDS,PetscInt*) PetscErrorCode DSHSVDSetDimensions(SlepcDS,PetscInt) PetscErrorCode DSHSVDGetDimensions(SlepcDS,PetscInt*) PetscErrorCode DSGSVDSetDimensions(SlepcDS,PetscInt,PetscInt) PetscErrorCode DSGSVDGetDimensions(SlepcDS,PetscInt*,PetscInt*) PetscErrorCode DSPEPSetDegree(SlepcDS,PetscInt) PetscErrorCode DSPEPGetDegree(SlepcDS,PetscInt*) PetscErrorCode DSPEPSetCoefficients(SlepcDS,PetscReal*) PetscErrorCode DSPEPGetCoefficients(SlepcDS,PetscReal**) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepceps.pxi0000644000076500000240000004263515133663436020402 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcEPSType "const char*" SlepcEPSType EPSPOWER SlepcEPSType EPSSUBSPACE SlepcEPSType EPSARNOLDI SlepcEPSType EPSLANCZOS SlepcEPSType EPSKRYLOVSCHUR SlepcEPSType EPSGD SlepcEPSType EPSJD SlepcEPSType EPSRQCG SlepcEPSType EPSLOBPCG SlepcEPSType EPSCISS SlepcEPSType EPSLYAPII SlepcEPSType EPSLAPACK SlepcEPSType EPSARPACK SlepcEPSType EPSBLOPEX SlepcEPSType EPSPRIMME SlepcEPSType EPSFEAST SlepcEPSType EPSSCALAPACK SlepcEPSType EPSELPA SlepcEPSType EPSELEMENTAL SlepcEPSType EPSEVSL SlepcEPSType EPSCHASE ctypedef enum SlepcEPSProblemType "EPSProblemType": EPS_HEP EPS_GHEP EPS_NHEP EPS_GNHEP EPS_PGNHEP EPS_GHIEP EPS_BSE EPS_HAMILT ctypedef enum SlepcEPSExtraction "EPSExtraction": EPS_RITZ EPS_HARMONIC EPS_HARMONIC_RELATIVE EPS_HARMONIC_RIGHT EPS_HARMONIC_LARGEST EPS_REFINED EPS_REFINED_HARMONIC ctypedef enum SlepcEPSWhich "EPSWhich": EPS_LARGEST_MAGNITUDE EPS_LARGEST_REAL EPS_LARGEST_IMAGINARY EPS_SMALLEST_MAGNITUDE EPS_SMALLEST_REAL EPS_SMALLEST_IMAGINARY EPS_TARGET_MAGNITUDE EPS_TARGET_REAL EPS_TARGET_IMAGINARY EPS_ALL EPS_WHICH_USER ctypedef enum SlepcEPSBalance "EPSBalance": EPS_BALANCE_NONE EPS_BALANCE_ONESIDE EPS_BALANCE_TWOSIDE EPS_BALANCE_USER ctypedef enum SlepcEPSErrorType "EPSErrorType": EPS_ERROR_ABSOLUTE EPS_ERROR_RELATIVE EPS_ERROR_BACKWARD ctypedef enum SlepcEPSConv "EPSConv": EPS_CONV_ABS EPS_CONV_REL EPS_CONV_NORM EPS_CONV_USER ctypedef enum SlepcEPSStop "EPSStop": EPS_STOP_BASIC EPS_STOP_USER EPS_STOP_THRESHOLD ctypedef enum SlepcEPSConvergedReason "EPSConvergedReason": EPS_CONVERGED_TOL EPS_CONVERGED_USER EPS_DIVERGED_ITS EPS_DIVERGED_BREAKDOWN EPS_DIVERGED_SYMMETRY_LOST EPS_CONVERGED_ITERATING ctypedef PetscErrorCode (*SlepcEPSCtxDel)(void*) ctypedef PetscErrorCode (*SlepcEPSStoppingFunction)(SlepcEPS, PetscInt, PetscInt, PetscInt, PetscInt, SlepcEPSConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcEPSMonitorFunction)(SlepcEPS, PetscInt, PetscInt, PetscScalar*, PetscScalar*, PetscReal*, PetscInt, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcEPSArbitraryFunction)(PetscScalar, PetscScalar, PetscVec, PetscVec, PetscScalar*, PetscScalar*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcEPSComparisonFunction)(PetscScalar, PetscScalar, PetscScalar, PetscScalar, PetscInt*, void*) except PETSC_ERR_PYTHON PetscErrorCode EPSView(SlepcEPS,PetscViewer) PetscErrorCode EPSDestroy(SlepcEPS*) PetscErrorCode EPSReset(SlepcEPS) PetscErrorCode EPSCreate(MPI_Comm,SlepcEPS*) PetscErrorCode EPSSetType(SlepcEPS,SlepcEPSType) PetscErrorCode EPSGetType(SlepcEPS,SlepcEPSType*) PetscErrorCode EPSSetOptionsPrefix(SlepcEPS,char[]) PetscErrorCode EPSAppendOptionsPrefix(SlepcEPS,char []) PetscErrorCode EPSGetOptionsPrefix(SlepcEPS,char*[]) PetscErrorCode EPSSetFromOptions(SlepcEPS) PetscErrorCode EPSSetProblemType(SlepcEPS,SlepcEPSProblemType) PetscErrorCode EPSGetProblemType(SlepcEPS,SlepcEPSProblemType*) PetscErrorCode EPSIsGeneralized(SlepcEPS,PetscBool*) PetscErrorCode EPSIsHermitian(SlepcEPS,PetscBool*) PetscErrorCode EPSIsPositive(SlepcEPS,PetscBool*) PetscErrorCode EPSIsStructured(SlepcEPS,PetscBool*) PetscErrorCode EPSSetExtraction(SlepcEPS,SlepcEPSExtraction) PetscErrorCode EPSGetExtraction(SlepcEPS,SlepcEPSExtraction*) PetscErrorCode EPSSetBalance(SlepcEPS,SlepcEPSBalance,PetscInt,PetscReal) PetscErrorCode EPSGetBalance(SlepcEPS,SlepcEPSBalance*,PetscInt*,PetscReal*) PetscErrorCode EPSSetWhichEigenpairs(SlepcEPS,SlepcEPSWhich) PetscErrorCode EPSGetWhichEigenpairs(SlepcEPS,SlepcEPSWhich*) PetscErrorCode EPSSetThreshold(SlepcEPS,PetscReal,PetscBool) PetscErrorCode EPSGetThreshold(SlepcEPS,PetscReal*,PetscBool*) PetscErrorCode EPSSetTarget(SlepcEPS,PetscScalar) PetscErrorCode EPSGetTarget(SlepcEPS,PetscScalar*) PetscErrorCode EPSSetInterval(SlepcEPS,PetscReal,PetscReal) PetscErrorCode EPSGetInterval(SlepcEPS,PetscReal*,PetscReal*) PetscErrorCode EPSSetTolerances(SlepcEPS,PetscReal,PetscInt) PetscErrorCode EPSGetTolerances(SlepcEPS,PetscReal*,PetscInt*) PetscErrorCode EPSSetDimensions(SlepcEPS,PetscInt,PetscInt,PetscInt) PetscErrorCode EPSGetDimensions(SlepcEPS,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode EPSSetBV(SlepcEPS,SlepcBV) PetscErrorCode EPSGetBV(SlepcEPS,SlepcBV*) PetscErrorCode EPSSetDS(SlepcEPS,SlepcDS) PetscErrorCode EPSGetDS(SlepcEPS,SlepcDS*) PetscErrorCode EPSSetST(SlepcEPS,SlepcST) PetscErrorCode EPSGetST(SlepcEPS,SlepcST*) PetscErrorCode EPSSetRG(SlepcEPS,SlepcRG) PetscErrorCode EPSGetRG(SlepcEPS,SlepcRG*) PetscErrorCode EPSSetOperators(SlepcEPS,PetscMat,PetscMat) PetscErrorCode EPSGetOperators(SlepcEPS,PetscMat*,PetscMat*) PetscErrorCode EPSSetTwoSided(SlepcEPS,PetscBool) PetscErrorCode EPSGetTwoSided(SlepcEPS,PetscBool*) PetscErrorCode EPSSetPurify(SlepcEPS,PetscBool) PetscErrorCode EPSGetPurify(SlepcEPS,PetscBool*) PetscErrorCode EPSSetConvergenceTest(SlepcEPS,SlepcEPSConv) PetscErrorCode EPSGetConvergenceTest(SlepcEPS,SlepcEPSConv*) PetscErrorCode EPSSetTrueResidual(SlepcEPS,PetscBool) PetscErrorCode EPSGetTrueResidual(SlepcEPS,PetscBool*) PetscErrorCode EPSSetTrackAll(SlepcEPS,PetscBool) PetscErrorCode EPSGetTrackAll(SlepcEPS,PetscBool*) PetscErrorCode EPSSetDeflationSpace(SlepcEPS,PetscInt,PetscVec*) PetscErrorCode EPSSetInitialSpace(SlepcEPS,PetscInt,PetscVec*) PetscErrorCode EPSSetLeftInitialSpace(SlepcEPS,PetscInt,PetscVec*) PetscErrorCode EPSSetUp(SlepcEPS) PetscErrorCode EPSSolve(SlepcEPS) PetscErrorCode EPSGetIterationNumber(SlepcEPS,PetscInt*) PetscErrorCode EPSGetConvergedReason(SlepcEPS,SlepcEPSConvergedReason*) PetscErrorCode EPSGetConverged(SlepcEPS,PetscInt*) PetscErrorCode EPSGetEigenvalue(SlepcEPS,PetscInt,PetscScalar*,PetscScalar*) PetscErrorCode EPSGetEigenvector(SlepcEPS,PetscInt,PetscVec,PetscVec) PetscErrorCode EPSGetLeftEigenvector(SlepcEPS,PetscInt,PetscVec,PetscVec) PetscErrorCode EPSGetEigenpair(SlepcEPS,PetscInt,PetscScalar*,PetscScalar*,PetscVec,PetscVec) PetscErrorCode EPSGetInvariantSubspace(SlepcEPS,PetscVec*) PetscErrorCode EPSSetStoppingTestFunction(SlepcEPS,SlepcEPSStoppingFunction,void*,SlepcEPSCtxDel) PetscErrorCode EPSStoppingBasic(SlepcEPS,PetscInt,PetscInt,PetscInt,PetscInt,SlepcEPSConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode EPSSetArbitrarySelection(SlepcEPS,SlepcEPSArbitraryFunction,void*); PetscErrorCode EPSSetEigenvalueComparison(SlepcEPS,SlepcEPSComparisonFunction,void*); PetscErrorCode EPSGetErrorEstimate(SlepcEPS,PetscInt,PetscReal*) PetscErrorCode EPSComputeError(SlepcEPS,PetscInt,SlepcEPSErrorType,PetscReal*) PetscErrorCode EPSErrorView(SlepcEPS,SlepcEPSErrorType,PetscViewer) PetscErrorCode EPSValuesView(SlepcEPS,PetscViewer) PetscErrorCode EPSVectorsView(SlepcEPS,PetscViewer) PetscErrorCode EPSMonitorSet(SlepcEPS,SlepcEPSMonitorFunction,void*,SlepcEPSCtxDel) PetscErrorCode EPSMonitorCancel(SlepcEPS) ctypedef enum SlepcEPSPowerShiftType "EPSPowerShiftType": EPS_POWER_SHIFT_CONSTANT EPS_POWER_SHIFT_RAYLEIGH EPS_POWER_SHIFT_WILKINSON PetscErrorCode EPSPowerSetShiftType(SlepcEPS,SlepcEPSPowerShiftType) PetscErrorCode EPSPowerGetShiftType(SlepcEPS,SlepcEPSPowerShiftType*) PetscErrorCode EPSArnoldiSetDelayed(SlepcEPS,PetscBool) PetscErrorCode EPSArnoldiGetDelayed(SlepcEPS,PetscBool*) ctypedef enum SlepcEPSKrylovSchurBSEType "EPSKrylovSchurBSEType": EPS_KRYLOVSCHUR_BSE_SHAO EPS_KRYLOVSCHUR_BSE_GRUNING EPS_KRYLOVSCHUR_BSE_PROJECTEDBSE PetscErrorCode EPSKrylovSchurSetBSEType(SlepcEPS,SlepcEPSKrylovSchurBSEType) PetscErrorCode EPSKrylovSchurGetBSEType(SlepcEPS,SlepcEPSKrylovSchurBSEType*) PetscErrorCode EPSKrylovSchurSetRestart(SlepcEPS,PetscReal) PetscErrorCode EPSKrylovSchurGetRestart(SlepcEPS,PetscReal*) PetscErrorCode EPSKrylovSchurSetLocking(SlepcEPS,PetscBool) PetscErrorCode EPSKrylovSchurGetLocking(SlepcEPS,PetscBool*) PetscErrorCode EPSKrylovSchurSetPartitions(SlepcEPS,PetscInt) PetscErrorCode EPSKrylovSchurGetPartitions(SlepcEPS,PetscInt*) PetscErrorCode EPSKrylovSchurSetDetectZeros(SlepcEPS,PetscBool) PetscErrorCode EPSKrylovSchurGetDetectZeros(SlepcEPS,PetscBool*) PetscErrorCode EPSKrylovSchurSetDimensions(SlepcEPS,PetscInt,PetscInt,PetscInt) PetscErrorCode EPSKrylovSchurGetDimensions(SlepcEPS,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode EPSKrylovSchurGetSubcommInfo(SlepcEPS,PetscInt*,PetscInt*,PetscVec*) PetscErrorCode EPSKrylovSchurGetSubcommPairs(SlepcEPS,PetscInt,PetscScalar*,PetscVec) PetscErrorCode EPSKrylovSchurGetSubcommMats(SlepcEPS,PetscMat*,PetscMat*) PetscErrorCode EPSKrylovSchurUpdateSubcommMats(SlepcEPS,PetscScalar,PetscScalar,PetscMat,PetscScalar,PetscScalar,PetscMat,PetscMatStructure,PetscBool) PetscErrorCode EPSKrylovSchurSetSubintervals(SlepcEPS,PetscReal*) PetscErrorCode EPSKrylovSchurGetSubintervals(SlepcEPS,PetscReal**) PetscErrorCode EPSKrylovSchurGetInertias(SlepcEPS,PetscInt*,PetscReal**,PetscInt**) PetscErrorCode EPSKrylovSchurGetKSP(SlepcEPS,PetscKSP*) ctypedef enum SlepcEPSLanczosReorthogType "EPSLanczosReorthogType": EPS_LANCZOS_REORTHOG_LOCAL EPS_LANCZOS_REORTHOG_FULL EPS_LANCZOS_REORTHOG_SELECTIVE EPS_LANCZOS_REORTHOG_PERIODIC EPS_LANCZOS_REORTHOG_PARTIAL EPS_LANCZOS_REORTHOG_DELAYED PetscErrorCode EPSLanczosSetReorthog(SlepcEPS,SlepcEPSLanczosReorthogType) PetscErrorCode EPSLanczosGetReorthog(SlepcEPS,SlepcEPSLanczosReorthogType*) PetscErrorCode EPSGDSetKrylovStart(SlepcEPS,PetscBool) PetscErrorCode EPSGDGetKrylovStart(SlepcEPS,PetscBool*) PetscErrorCode EPSGDSetBlockSize(SlepcEPS,PetscInt) PetscErrorCode EPSGDGetBlockSize(SlepcEPS,PetscInt*) PetscErrorCode EPSGDSetRestart(SlepcEPS,PetscInt,PetscInt) PetscErrorCode EPSGDGetRestart(SlepcEPS,PetscInt*,PetscInt*) PetscErrorCode EPSGDSetInitialSize(SlepcEPS,PetscInt) PetscErrorCode EPSGDGetInitialSize(SlepcEPS,PetscInt*) PetscErrorCode EPSGDSetBOrth(SlepcEPS,PetscBool) PetscErrorCode EPSGDGetBOrth(SlepcEPS,PetscBool*) PetscErrorCode EPSGDSetDoubleExpansion(SlepcEPS,PetscBool) PetscErrorCode EPSGDGetDoubleExpansion(SlepcEPS,PetscBool*) PetscErrorCode EPSJDSetKrylovStart(SlepcEPS,PetscBool) PetscErrorCode EPSJDGetKrylovStart(SlepcEPS,PetscBool*) PetscErrorCode EPSJDSetBlockSize(SlepcEPS,PetscInt) PetscErrorCode EPSJDGetBlockSize(SlepcEPS,PetscInt*) PetscErrorCode EPSJDSetRestart(SlepcEPS,PetscInt,PetscInt) PetscErrorCode EPSJDGetRestart(SlepcEPS,PetscInt*,PetscInt*) PetscErrorCode EPSJDSetInitialSize(SlepcEPS,PetscInt) PetscErrorCode EPSJDGetInitialSize(SlepcEPS,PetscInt*) PetscErrorCode EPSJDSetFix(SlepcEPS,PetscReal) PetscErrorCode EPSJDGetFix(SlepcEPS,PetscReal*) PetscErrorCode EPSJDSetConstCorrectionTol(SlepcEPS,PetscBool) PetscErrorCode EPSJDGetConstCorrectionTol(SlepcEPS,PetscBool*) PetscErrorCode EPSJDSetBOrth(SlepcEPS,PetscBool) PetscErrorCode EPSJDGetBOrth(SlepcEPS,PetscBool*) PetscErrorCode EPSRQCGSetReset(SlepcEPS,PetscInt) PetscErrorCode EPSRQCGGetReset(SlepcEPS,PetscInt*) PetscErrorCode EPSLOBPCGSetBlockSize(SlepcEPS,PetscInt) PetscErrorCode EPSLOBPCGGetBlockSize(SlepcEPS,PetscInt*) PetscErrorCode EPSLOBPCGSetRestart(SlepcEPS,PetscReal) PetscErrorCode EPSLOBPCGGetRestart(SlepcEPS,PetscReal*) PetscErrorCode EPSLOBPCGSetLocking(SlepcEPS,PetscBool) PetscErrorCode EPSLOBPCGGetLocking(SlepcEPS,PetscBool*) PetscErrorCode EPSLyapIISetRanks(SlepcEPS,PetscInt,PetscInt) PetscErrorCode EPSLyapIIGetRanks(SlepcEPS,PetscInt*,PetscInt*) ctypedef enum SlepcEPSCISSQuadRule "EPSCISSQuadRule": EPS_CISS_QUADRULE_TRAPEZOIDAL EPS_CISS_QUADRULE_CHEBYSHEV ctypedef enum SlepcEPSCISSExtraction "EPSCISSExtraction": EPS_CISS_EXTRACTION_RITZ EPS_CISS_EXTRACTION_HANKEL PetscErrorCode EPSCISSSetExtraction(SlepcEPS,SlepcEPSCISSExtraction) PetscErrorCode EPSCISSGetExtraction(SlepcEPS,SlepcEPSCISSExtraction*) PetscErrorCode EPSCISSSetQuadRule(SlepcEPS,SlepcEPSCISSQuadRule) PetscErrorCode EPSCISSGetQuadRule(SlepcEPS,SlepcEPSCISSQuadRule*) PetscErrorCode EPSCISSSetSizes(SlepcEPS,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscBool) PetscErrorCode EPSCISSGetSizes(SlepcEPS,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscBool*) PetscErrorCode EPSCISSSetThreshold(SlepcEPS,PetscReal,PetscReal) PetscErrorCode EPSCISSGetThreshold(SlepcEPS,PetscReal*,PetscReal*) PetscErrorCode EPSCISSSetRefinement(SlepcEPS,PetscInt,PetscInt) PetscErrorCode EPSCISSGetRefinement(SlepcEPS,PetscInt*,PetscInt*) PetscErrorCode EPSCISSSetUseST(SlepcEPS,PetscBool) PetscErrorCode EPSCISSGetUseST(SlepcEPS,PetscBool*) PetscErrorCode EPSCISSGetKSPs(SlepcEPS,PetscInt*,PetscKSP**) cdef extern from * nogil: PetscErrorCode VecDuplicate(PetscVec,PetscVec*) PetscErrorCode MatCreateVecs(PetscMat,PetscVec*,PetscVec*) # ----------------------------------------------------------------------------- cdef inline EPS ref_EPS(SlepcEPS eps): cdef EPS ob = EPS() ob.eps = eps CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode EPS_Stopping( SlepcEPS eps, PetscInt its, PetscInt max_it, PetscInt nconv, PetscInt nev, SlepcEPSConvergedReason *r, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef EPS Eps = ref_EPS(eps) (stopping, args, kargs) = Eps.get_attr('__stopping__') reason = stopping(Eps, toInt(its), toInt(max_it), toInt(nconv), toInt(nev), *args, **kargs) if reason is None: r[0] = EPS_CONVERGED_ITERATING elif reason is False: r[0] = EPS_CONVERGED_ITERATING elif reason is True: r[0] = EPS_CONVERGED_USER else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode EPS_Arbitrary( PetscScalar er, PetscScalar ei, PetscVec xr, PetscVec xi, PetscScalar* rr, PetscScalar* ri, void *ctx, ) except PETSC_ERR_PYTHON with gil: (arbitrary, args, kargs) = ctx cdef Vec Vr = ref_Vec(xr) cdef Vec Vi = ref_Vec(xi) r = arbitrary(toComplex(er, ei), Vr, Vi, args, **kargs) if sizeof(PetscScalar) == sizeof(PetscReal): rr[0] = asComplexReal(r) ri[0] = asComplexImag(r) else: rr[0] = asScalar(r) ri[0] = 0.0 return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode EPS_Comparison( PetscScalar ar, PetscScalar ai, PetscScalar br, PetscScalar bi, PetscInt* res, void *ctx, ) except PETSC_ERR_PYTHON with gil: (comparison, args, kargs) = ctx r = comparison(toComplex(ar, ai), toComplex(br, bi), args, **kargs) res[0] = asInt(r) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode EPS_Monitor( SlepcEPS eps, PetscInt its, PetscInt nconv, PetscScalar *eigr, PetscScalar *eigi, PetscReal *errest, PetscInt nest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef EPS Eps = ref_EPS(eps) cdef object monitorlist = Eps.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS cdef object eig = [toComplex(eigr[i], eigi[i]) for i in range(nest)] cdef object err = [toReal(errest[i]) for i in range(nest)] for (monitor, args, kargs) in monitorlist: monitor(Eps, toInt(its), toInt(nconv), eig, err, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcfn.pxi0000644000076500000240000001533415133663436020212 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcFNType "const char*" SlepcFNType FNCOMBINE SlepcFNType FNRATIONAL SlepcFNType FNEXP SlepcFNType FNLOG SlepcFNType FNPHI SlepcFNType FNSQRT SlepcFNType FNINVSQRT ctypedef enum SlepcFNCombineType "FNCombineType": FN_COMBINE_ADD FN_COMBINE_MULTIPLY FN_COMBINE_DIVIDE FN_COMBINE_COMPOSE ctypedef enum SlepcFNParallelType "FNParallelType": FN_PARALLEL_REDUNDANT FN_PARALLEL_SYNCHRONIZED PetscErrorCode FNCreate(MPI_Comm,SlepcFN*) PetscErrorCode FNView(SlepcFN,PetscViewer) PetscErrorCode FNDestroy(SlepcFN*) PetscErrorCode FNReset(SlepcFN) PetscErrorCode FNSetType(SlepcFN,SlepcFNType) PetscErrorCode FNGetType(SlepcFN,SlepcFNType*) PetscErrorCode FNSetOptionsPrefix(SlepcFN,char[]) PetscErrorCode FNGetOptionsPrefix(SlepcFN,char*[]) PetscErrorCode FNAppendOptionsPrefix(SlepcFN,char[]) PetscErrorCode FNSetFromOptions(SlepcFN) PetscErrorCode FNDuplicate(SlepcFN,MPI_Comm,SlepcFN*) PetscErrorCode FNSetScale(SlepcFN,PetscScalar,PetscScalar) PetscErrorCode FNGetScale(SlepcFN,PetscScalar*,PetscScalar*) PetscErrorCode FNSetMethod(SlepcFN,PetscInt) PetscErrorCode FNGetMethod(SlepcFN,PetscInt*) PetscErrorCode FNSetParallel(SlepcFN,SlepcFNParallelType) PetscErrorCode FNGetParallel(SlepcFN,SlepcFNParallelType*) PetscErrorCode FNEvaluateFunction(SlepcFN,PetscScalar,PetscScalar*) PetscErrorCode FNEvaluateDerivative(SlepcFN,PetscScalar,PetscScalar*) PetscErrorCode FNEvaluateFunctionMat(SlepcFN,PetscMat,PetscMat) PetscErrorCode FNEvaluateFunctionMatVec(SlepcFN,PetscMat,PetscVec) PetscErrorCode FNRationalSetNumerator(SlepcFN,PetscInt,PetscScalar[]) PetscErrorCode FNRationalGetNumerator(SlepcFN,PetscInt*,PetscScalar*[]) PetscErrorCode FNRationalSetDenominator(SlepcFN,PetscInt,PetscScalar[]) PetscErrorCode FNRationalGetDenominator(SlepcFN,PetscInt*,PetscScalar*[]) PetscErrorCode FNCombineSetChildren(SlepcFN,SlepcFNCombineType,SlepcFN,SlepcFN) PetscErrorCode FNCombineGetChildren(SlepcFN,SlepcFNCombineType*,SlepcFN*,SlepcFN*) PetscErrorCode FNPhiSetIndex(SlepcFN,PetscInt) PetscErrorCode FNPhiGetIndex(SlepcFN,PetscInt*) # -------------------------------------------------------------------- # unary operations cdef FN fn_pos(FN self): cdef FN fn = type(self)() cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) CHKERR(FNDuplicate(self.fn, comm, &fn.fn)) return fn cdef FN fn_neg(FN self): cdef PetscScalar alpha = 1, beta = 1 cdef FN fn = fn_pos(self) CHKERR(FNGetScale(fn.fn, &alpha, &beta)) CHKERR(FNSetScale(fn.fn, alpha, -beta)) return fn # inplace binary operations cdef FN fn_iadd(FN self, other): cdef PetscScalar alpha = 1 cdef FN comb = type(self)() cdef SlepcFN fn = NULL cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) CHKERR(FNCreate(comm, &comb.fn)) CHKERR(FNSetType(comb.fn, FNCOMBINE)) CHKERR(FNSetFromOptions(comb.fn)) if isinstance(other, FN): fn = (other).fn CHKERR(PetscObjectReference(fn)) else: alpha = asScalar(other) CHKERR(FNCreate(comm, &fn)) CHKERR(FNSetType(fn, FNRATIONAL)) CHKERR(FNSetFromOptions(fn)) CHKERR(FNRationalSetNumerator(fn, 1, &alpha)); CHKERR(FNCombineSetChildren(comb.fn, FN_COMBINE_ADD, self.fn, fn)) CHKERR(FNDestroy(&fn)) return comb cdef FN fn_isub(FN self, other): cdef PetscScalar alpha = 1, beta = 1 cdef FN comb = type(self)() cdef SlepcFN fn = NULL cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) CHKERR(FNCreate(comm, &comb.fn)) CHKERR(FNSetType(comb.fn, FNCOMBINE)) CHKERR(FNSetFromOptions(comb.fn)) if isinstance(other, FN): CHKERR(FNDuplicate((other).fn, comm, &fn)) CHKERR(FNGetScale(fn, &alpha, &beta)) CHKERR(FNSetScale(fn, alpha, -beta)) else: alpha = -asScalar(other) CHKERR(FNCreate(comm, &fn)) CHKERR(FNSetType(fn, FNRATIONAL)) CHKERR(FNSetFromOptions(fn)) CHKERR(FNRationalSetNumerator(fn, 1, &alpha)); CHKERR(FNCombineSetChildren(comb.fn, FN_COMBINE_ADD, self.fn, fn)) CHKERR(FNDestroy(&fn)) return comb cdef FN fn_imul(FN self, other): cdef PetscScalar alpha = 1, beta = 1, gamma = 1 cdef FN comb cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) if isinstance(other, FN): comb = type(self)() CHKERR(FNCreate(comm, &comb.fn)) CHKERR(FNSetType(comb.fn, FNCOMBINE)) CHKERR(FNSetFromOptions(comb.fn)) CHKERR(FNCombineSetChildren(comb.fn, FN_COMBINE_MULTIPLY, self.fn, (other).fn)) return comb else: gamma = asScalar(other) CHKERR(FNGetScale(self.fn, &alpha, &beta)) CHKERR(FNSetScale(self.fn, alpha, beta*gamma)) return self cdef FN fn_idiv(FN self, other): cdef PetscScalar alpha = 1, beta = 1, gamma = 1 cdef FN comb cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) if isinstance(other, FN): comb = type(self)() CHKERR(FNCreate(comm, &comb.fn)) CHKERR(FNSetType(comb.fn, FNCOMBINE)) CHKERR(FNSetFromOptions(comb.fn)) CHKERR(FNCombineSetChildren(comb.fn, FN_COMBINE_DIVIDE, self.fn, (other).fn)) return comb else: gamma = asScalar(other) CHKERR(FNGetScale(self.fn, &alpha, &beta)) CHKERR(FNSetScale(self.fn, alpha, beta/gamma)) return self # binary operations cdef FN fn_add(FN self, other): return fn_iadd(fn_pos(self), other) cdef FN fn_sub(FN self, other): return fn_isub(fn_pos(self), other) cdef FN fn_mul(FN self, other): return fn_imul(fn_pos(self), other) cdef FN fn_div(FN self, other): return fn_idiv(fn_pos(self), other) # reflected binary operations cdef FN fn_radd(FN self, other): return fn_add(self, other) cdef FN fn_rsub(FN self, other): cdef FN fn = fn_sub(self, other) CHKERR(FNSetScale(fn.fn, 1, -1)) return fn cdef FN fn_rmul(FN self, other): return fn_mul(self, other) cdef FN fn_rdiv(FN self, other): self; other # unused return NotImplemented # composition cdef FN fn_matmul(FN self, other): cdef FN fn, comb cdef MPI_Comm comm = def_Comm(None, PetscObjectComm(self.fn)) if isinstance(other, FN): comb = type(self)() CHKERR(FNCreate(comm, &comb.fn)) CHKERR(FNSetType(comb.fn, FNCOMBINE)) CHKERR(FNSetFromOptions(comb.fn)) CHKERR(FNCombineSetChildren(comb.fn, FN_COMBINE_COMPOSE, (other).fn, self.fn)) return comb else: return NotImplemented ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepclme.pxi0000644000076500000240000000706015133663436020361 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcLMEType "const char*" SlepcLMEType LMEKRYLOV ctypedef enum SlepcLMEConvergedReason "LMEConvergedReason": LME_CONVERGED_TOL LME_DIVERGED_ITS LME_DIVERGED_BREAKDOWN LME_CONVERGED_ITERATING ctypedef enum SlepcLMEProblemType "LMEProblemType": LME_LYAPUNOV LME_SYLVESTER LME_GEN_LYAPUNOV LME_GEN_SYLVESTER LME_DT_LYAPUNOV LME_STEIN ctypedef PetscErrorCode (*SlepcLMECtxDel)(void*) ctypedef PetscErrorCode (*SlepcLMEMonitorFunction)(SlepcLME, PetscInt, PetscReal, void*) except PETSC_ERR_PYTHON PetscErrorCode LMECreate(MPI_Comm,SlepcLME*) PetscErrorCode LMEDestroy(SlepcLME*) PetscErrorCode LMEReset(SlepcLME) PetscErrorCode LMEView(SlepcLME,PetscViewer) PetscErrorCode LMESetType(SlepcLME,SlepcLMEType) PetscErrorCode LMEGetType(SlepcLME,SlepcLMEType*) PetscErrorCode LMESetProblemType(SlepcLME,SlepcLMEProblemType) PetscErrorCode LMEGetProblemType(SlepcLME,SlepcLMEProblemType*) PetscErrorCode LMESetCoefficients(SlepcLME,PetscMat,PetscMat,PetscMat,PetscMat) PetscErrorCode LMEGetCoefficients(SlepcLME,PetscMat*,PetscMat*,PetscMat*,PetscMat*) PetscErrorCode LMESetRHS(SlepcLME,PetscMat) PetscErrorCode LMEGetRHS(SlepcLME,PetscMat*) PetscErrorCode LMESetSolution(SlepcLME,PetscMat) PetscErrorCode LMEGetSolution(SlepcLME,PetscMat*) PetscErrorCode LMEGetErrorEstimate(SlepcLME,PetscReal*) PetscErrorCode LMEComputeError(SlepcLME,PetscReal*) PetscErrorCode LMESetOptionsPrefix(SlepcLME,char*) PetscErrorCode LMEGetOptionsPrefix(SlepcLME,char*[]) PetscErrorCode LMESetFromOptions(SlepcLME) PetscErrorCode LMEAppendOptionsPrefix(SlepcLME,char*) PetscErrorCode LMESetUp(SlepcLME) PetscErrorCode LMESolve(SlepcLME) PetscErrorCode LMESetBV(SlepcLME,SlepcBV) PetscErrorCode LMEGetBV(SlepcLME,SlepcBV*) PetscErrorCode LMESetFN(SlepcLME,SlepcFN) PetscErrorCode LMEGetFN(SlepcLME,SlepcFN*) PetscErrorCode LMESetTolerances(SlepcLME,PetscReal,PetscInt) PetscErrorCode LMEGetTolerances(SlepcLME,PetscReal*,PetscInt*) PetscErrorCode LMESetDimensions(SlepcLME,PetscInt) PetscErrorCode LMEGetDimensions(SlepcLME,PetscInt*) PetscErrorCode LMESetErrorIfNotConverged(SlepcLME,PetscBool) PetscErrorCode LMEGetErrorIfNotConverged(SlepcLME,PetscBool*) PetscErrorCode LMEMonitorSet(SlepcLME,SlepcLMEMonitorFunction,void*,SlepcLMECtxDel) PetscErrorCode LMEMonitorCancel(SlepcLME) PetscErrorCode LMEGetIterationNumber(SlepcLME,PetscInt*) PetscErrorCode LMEGetConvergedReason(SlepcLME,SlepcLMEConvergedReason*) # ----------------------------------------------------------------------------- cdef inline LME ref_LME(SlepcLME lme): cdef LME ob = LME() ob.lme = lme CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode LME_Monitor( SlepcLME lme, PetscInt it, PetscReal errest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef LME Lme = ref_LME(lme) cdef object monitorlist = Lme.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS for (monitor, args, kargs) in monitorlist: monitor(Lme, toInt(it), toReal(errest), *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcmfn.pxi0000644000076500000240000000575615133663436020376 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcMFNType "const char*" SlepcMFNType MFNKRYLOV SlepcMFNType MFNEXPOKIT ctypedef enum SlepcMFNConvergedReason "MFNConvergedReason": MFN_CONVERGED_TOL MFN_CONVERGED_ITS MFN_DIVERGED_ITS MFN_DIVERGED_BREAKDOWN MFN_CONVERGED_ITERATING ctypedef PetscErrorCode (*SlepcMFNCtxDel)(void*) ctypedef PetscErrorCode (*SlepcMFNMonitorFunction)(SlepcMFN, PetscInt, PetscReal, void*) except PETSC_ERR_PYTHON PetscErrorCode MFNCreate(MPI_Comm,SlepcMFN*) PetscErrorCode MFNDestroy(SlepcMFN*) PetscErrorCode MFNReset(SlepcMFN) PetscErrorCode MFNView(SlepcMFN,PetscViewer) PetscErrorCode MFNSetType(SlepcMFN,SlepcMFNType) PetscErrorCode MFNGetType(SlepcMFN,SlepcMFNType*) PetscErrorCode MFNSetOperator(SlepcMFN,PetscMat) PetscErrorCode MFNGetOperator(SlepcMFN,PetscMat*) PetscErrorCode MFNSetOptionsPrefix(SlepcMFN,char*) PetscErrorCode MFNGetOptionsPrefix(SlepcMFN,char*[]) PetscErrorCode MFNSetFromOptions(SlepcMFN) PetscErrorCode MFNAppendOptionsPrefix(SlepcMFN,char*) PetscErrorCode MFNSetUp(SlepcMFN) PetscErrorCode MFNSolve(SlepcMFN,PetscVec,PetscVec) PetscErrorCode MFNSolveTranspose(SlepcMFN,PetscVec,PetscVec) PetscErrorCode MFNSetBV(SlepcMFN,SlepcBV) PetscErrorCode MFNGetBV(SlepcMFN,SlepcBV*) PetscErrorCode MFNSetFN(SlepcMFN,SlepcFN) PetscErrorCode MFNGetFN(SlepcMFN,SlepcFN*) PetscErrorCode MFNSetTolerances(SlepcMFN,PetscReal,PetscInt) PetscErrorCode MFNGetTolerances(SlepcMFN,PetscReal*,PetscInt*) PetscErrorCode MFNSetDimensions(SlepcMFN,PetscInt) PetscErrorCode MFNGetDimensions(SlepcMFN,PetscInt*) PetscErrorCode MFNSetErrorIfNotConverged(SlepcMFN,PetscBool) PetscErrorCode MFNGetErrorIfNotConverged(SlepcMFN,PetscBool*) PetscErrorCode MFNMonitorSet(SlepcMFN,SlepcMFNMonitorFunction,void*,SlepcMFNCtxDel) PetscErrorCode MFNMonitorCancel(SlepcMFN) PetscErrorCode MFNGetIterationNumber(SlepcMFN,PetscInt*) PetscErrorCode MFNGetConvergedReason(SlepcMFN,SlepcMFNConvergedReason*) # ----------------------------------------------------------------------------- cdef inline MFN ref_MFN(SlepcMFN mfn): cdef MFN ob = MFN() ob.mfn = mfn CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode MFN_Monitor( SlepcMFN mfn, PetscInt it, PetscReal errest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef MFN Mfn = ref_MFN(mfn) cdef object monitorlist = Mfn.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS for (monitor, args, kargs) in monitorlist: monitor(Mfn, toInt(it), toReal(errest), *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcmpi.pxi0000644000076500000240000000136015133663436020366 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef extern from * nogil: const MPI_Comm MPI_COMM_NULL const MPI_Comm MPI_COMM_SELF const MPI_Comm MPI_COMM_WORLD cdef extern from * nogil: MPI_Comm PETSC_COMM_SELF MPI_Comm PETSC_COMM_WORLD # ----------------------------------------------------------------------------- from petsc4py.PETSc cimport GetComm cdef inline MPI_Comm def_Comm( object comm, MPI_Comm defv, ) except? MPI_COMM_NULL: return GetComm(comm, defv) from petsc4py.PETSc cimport GetCommDefault cdef inline MPI_Comm SLEPC_COMM_DEFAULT() except? MPI_COMM_NULL: return GetCommDefault() # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcnep.pxi0000644000076500000240000003443715133663436020376 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcNEPType "const char*" SlepcNEPType NEPRII SlepcNEPType NEPSLP SlepcNEPType NEPNARNOLDI SlepcNEPType NEPCISS SlepcNEPType NEPINTERPOL SlepcNEPType NEPNLEIGS ctypedef enum SlepcNEPProblemType "NEPProblemType": NEP_GENERAL NEP_RATIONAL ctypedef enum SlepcNEPWhich "NEPWhich": NEP_LARGEST_MAGNITUDE NEP_SMALLEST_MAGNITUDE NEP_LARGEST_REAL NEP_SMALLEST_REAL NEP_LARGEST_IMAGINARY NEP_SMALLEST_IMAGINARY NEP_TARGET_MAGNITUDE NEP_TARGET_REAL NEP_TARGET_IMAGINARY NEP_ALL NEP_WHICH_USER ctypedef enum SlepcNEPErrorType "NEPErrorType": NEP_ERROR_ABSOLUTE NEP_ERROR_RELATIVE NEP_ERROR_BACKWARD ctypedef enum SlepcNEPRefine "NEPRefine": NEP_REFINE_NONE NEP_REFINE_SIMPLE NEP_REFINE_MULTIPLE ctypedef enum SlepcNEPRefineScheme "NEPRefineScheme": NEP_REFINE_SCHEME_SCHUR NEP_REFINE_SCHEME_MBE NEP_REFINE_SCHEME_EXPLICIT ctypedef enum SlepcNEPConv "NEPConv": NEP_CONV_ABS NEP_CONV_REL NEP_CONV_NORM NEP_CONV_USER ctypedef enum SlepcNEPStop "NEPStop": NEP_STOP_BASIC NEP_STOP_USER ctypedef enum SlepcNEPConvergedReason "NEPConvergedReason": NEP_CONVERGED_TOL NEP_CONVERGED_USER NEP_DIVERGED_ITS NEP_DIVERGED_BREAKDOWN NEP_DIVERGED_LINEAR_SOLVE NEP_DIVERGED_SUBSPACE_EXHAUSTED NEP_CONVERGED_ITERATING ctypedef PetscErrorCode (*SlepcNEPFunction)(SlepcNEP, PetscScalar, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcNEPJacobian)(SlepcNEP, PetscScalar, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcNEPCtxDel)(void*) ctypedef PetscErrorCode (*SlepcNEPStoppingFunction)(SlepcNEP, PetscInt, PetscInt, PetscInt, PetscInt, SlepcNEPConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcNEPMonitorFunction)(SlepcNEP, PetscInt, PetscInt, PetscScalar*, PetscScalar*, PetscReal*, PetscInt, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcNEPComparisonFunction)(PetscScalar, PetscScalar, PetscScalar, PetscScalar, PetscInt*, void*) except PETSC_ERR_PYTHON PetscErrorCode NEPCreate(MPI_Comm,SlepcNEP*) PetscErrorCode NEPDestroy(SlepcNEP*) PetscErrorCode NEPReset(SlepcNEP) PetscErrorCode NEPView(SlepcNEP,PetscViewer) PetscErrorCode NEPSetType(SlepcNEP,SlepcNEPType) PetscErrorCode NEPGetType(SlepcNEP,SlepcNEPType*) PetscErrorCode NEPSetTarget(SlepcNEP,PetscScalar) PetscErrorCode NEPGetTarget(SlepcNEP,PetscScalar*) PetscErrorCode NEPSetOptionsPrefix(SlepcNEP,char*) PetscErrorCode NEPGetOptionsPrefix(SlepcNEP,char*[]) PetscErrorCode NEPSetFromOptions(SlepcNEP) PetscErrorCode NEPAppendOptionsPrefix(SlepcNEP,char*) PetscErrorCode NEPSetUp(SlepcNEP) PetscErrorCode NEPSolve(SlepcNEP) PetscErrorCode NEPSetFunction(SlepcNEP,PetscMat,PetscMat,SlepcNEPFunction,void*) PetscErrorCode NEPGetFunction(SlepcNEP,PetscMat*,PetscMat*,SlepcNEPFunction*,void**) PetscErrorCode NEPSetJacobian(SlepcNEP,PetscMat,SlepcNEPJacobian,void*) PetscErrorCode NEPGetJacobian(SlepcNEP,PetscMat*,SlepcNEPJacobian*,void**) PetscErrorCode NEPSetSplitOperator(SlepcNEP,PetscInt,PetscMat[],SlepcFN[],PetscMatStructure) PetscErrorCode NEPGetSplitOperatorTerm(SlepcNEP,PetscInt,PetscMat*,SlepcFN*) PetscErrorCode NEPGetSplitOperatorInfo(SlepcNEP,PetscInt*,PetscMatStructure*) PetscErrorCode NEPSetSplitPreconditioner(SlepcNEP,PetscInt,PetscMat[],PetscMatStructure) PetscErrorCode NEPGetSplitPreconditionerTerm(SlepcNEP,PetscInt,PetscMat*) PetscErrorCode NEPGetSplitPreconditionerInfo(SlepcNEP,PetscInt*,PetscMatStructure*) PetscErrorCode NEPSetBV(SlepcNEP,SlepcBV) PetscErrorCode NEPGetBV(SlepcNEP,SlepcBV*) PetscErrorCode NEPSetRG(SlepcNEP,SlepcRG) PetscErrorCode NEPGetRG(SlepcNEP,SlepcRG*) PetscErrorCode NEPSetDS(SlepcNEP,SlepcDS) PetscErrorCode NEPGetDS(SlepcNEP,SlepcDS*) PetscErrorCode NEPSetTolerances(SlepcNEP,PetscReal,PetscInt) PetscErrorCode NEPGetTolerances(SlepcNEP,PetscReal*,PetscInt*) PetscErrorCode NEPSetTwoSided(SlepcNEP,PetscBool) PetscErrorCode NEPGetTwoSided(SlepcNEP,PetscBool*) PetscErrorCode NEPApplyResolvent(SlepcNEP,SlepcRG,PetscScalar,PetscVec,PetscVec) PetscErrorCode NEPSetTrackAll(SlepcNEP,PetscBool) PetscErrorCode NEPGetTrackAll(SlepcNEP,PetscBool*) PetscErrorCode NEPSetDimensions(SlepcNEP,PetscInt,PetscInt,PetscInt) PetscErrorCode NEPGetDimensions(SlepcNEP,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode NEPGetConverged(SlepcNEP,PetscInt*) PetscErrorCode NEPGetEigenpair(SlepcNEP,PetscInt,PetscScalar*,PetscScalar*,PetscVec,PetscVec) PetscErrorCode NEPGetLeftEigenvector(SlepcNEP,PetscInt,PetscVec,PetscVec) PetscErrorCode NEPComputeError(SlepcNEP,PetscInt,SlepcNEPErrorType,PetscReal*) PetscErrorCode NEPErrorView(SlepcNEP,SlepcNEPErrorType,PetscViewer) PetscErrorCode NEPValuesView(SlepcNEP,PetscViewer) PetscErrorCode NEPVectorsView(SlepcNEP,PetscViewer) PetscErrorCode NEPGetErrorEstimate(SlepcNEP,PetscInt,PetscReal*) PetscErrorCode NEPMonitorSet(SlepcNEP,SlepcNEPMonitorFunction,void*,SlepcNEPCtxDel) PetscErrorCode NEPMonitorCancel(SlepcNEP) PetscErrorCode NEPGetIterationNumber(SlepcNEP,PetscInt*) PetscErrorCode NEPSetInitialSpace(SlepcNEP,PetscInt,PetscVec*) PetscErrorCode NEPSetProblemType(SlepcNEP,SlepcNEPProblemType) PetscErrorCode NEPGetProblemType(SlepcNEP,SlepcNEPProblemType*) PetscErrorCode NEPSetWhichEigenpairs(SlepcNEP,SlepcNEPWhich) PetscErrorCode NEPGetWhichEigenpairs(SlepcNEP,SlepcNEPWhich*) PetscErrorCode NEPSetRefine(SlepcNEP,SlepcNEPRefine,PetscInt,PetscReal,PetscInt,SlepcNEPRefineScheme) PetscErrorCode NEPGetRefine(SlepcNEP,SlepcNEPRefine*,PetscInt*,PetscReal*,PetscInt*,SlepcNEPRefineScheme*) PetscErrorCode NEPRefineGetKSP(SlepcNEP,PetscKSP*) PetscErrorCode NEPGetConvergedReason(SlepcNEP,SlepcNEPConvergedReason*) PetscErrorCode NEPSetConvergenceTest(SlepcNEP,SlepcNEPConv) PetscErrorCode NEPGetConvergenceTest(SlepcNEP,SlepcNEPConv*) PetscErrorCode NEPSetStoppingTestFunction(SlepcNEP,SlepcNEPStoppingFunction,void*,SlepcNEPCtxDel) PetscErrorCode NEPStoppingBasic(SlepcNEP,PetscInt,PetscInt,PetscInt,PetscInt,SlepcNEPConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode NEPSetEigenvalueComparison(SlepcNEP,SlepcNEPComparisonFunction,void*); PetscErrorCode NEPRIISetLagPreconditioner(SlepcNEP,PetscInt) PetscErrorCode NEPRIIGetLagPreconditioner(SlepcNEP,PetscInt*) PetscErrorCode NEPRIISetConstCorrectionTol(SlepcNEP,PetscBool) PetscErrorCode NEPRIIGetConstCorrectionTol(SlepcNEP,PetscBool*) PetscErrorCode NEPRIISetMaximumIterations(SlepcNEP,PetscInt) PetscErrorCode NEPRIIGetMaximumIterations(SlepcNEP,PetscInt*) PetscErrorCode NEPRIISetHermitian(SlepcNEP,PetscBool) PetscErrorCode NEPRIIGetHermitian(SlepcNEP,PetscBool*) PetscErrorCode NEPRIISetDeflationThreshold(SlepcNEP,PetscReal) PetscErrorCode NEPRIIGetDeflationThreshold(SlepcNEP,PetscReal*) PetscErrorCode NEPRIISetKSP(SlepcNEP,PetscKSP) PetscErrorCode NEPRIIGetKSP(SlepcNEP,PetscKSP*) PetscErrorCode NEPSLPSetDeflationThreshold(SlepcNEP,PetscReal) PetscErrorCode NEPSLPGetDeflationThreshold(SlepcNEP,PetscReal*) PetscErrorCode NEPSLPSetEPS(SlepcNEP,SlepcEPS) PetscErrorCode NEPSLPGetEPS(SlepcNEP,SlepcEPS*) PetscErrorCode NEPSLPSetEPSLeft(SlepcNEP,SlepcEPS) PetscErrorCode NEPSLPGetEPSLeft(SlepcNEP,SlepcEPS*) PetscErrorCode NEPSLPSetKSP(SlepcNEP,PetscKSP) PetscErrorCode NEPSLPGetKSP(SlepcNEP,PetscKSP*) PetscErrorCode NEPNArnoldiSetKSP(SlepcNEP,PetscKSP) PetscErrorCode NEPNArnoldiGetKSP(SlepcNEP,PetscKSP*) PetscErrorCode NEPNArnoldiSetLagPreconditioner(SlepcNEP,PetscInt) PetscErrorCode NEPNArnoldiGetLagPreconditioner(SlepcNEP,PetscInt*) PetscErrorCode NEPInterpolSetPEP(SlepcNEP,SlepcPEP) PetscErrorCode NEPInterpolGetPEP(SlepcNEP,SlepcPEP*) PetscErrorCode NEPInterpolSetInterpolation(SlepcNEP,PetscReal,PetscInt) PetscErrorCode NEPInterpolGetInterpolation(SlepcNEP,PetscReal*,PetscInt*) PetscErrorCode NEPNLEIGSSetRestart(SlepcNEP,PetscReal) PetscErrorCode NEPNLEIGSGetRestart(SlepcNEP,PetscReal*) PetscErrorCode NEPNLEIGSSetLocking(SlepcNEP,PetscBool) PetscErrorCode NEPNLEIGSGetLocking(SlepcNEP,PetscBool*) PetscErrorCode NEPNLEIGSSetInterpolation(SlepcNEP,PetscReal,PetscInt) PetscErrorCode NEPNLEIGSGetInterpolation(SlepcNEP,PetscReal*,PetscInt*) PetscErrorCode NEPNLEIGSSetRKShifts(SlepcNEP,PetscInt,PetscScalar[]) PetscErrorCode NEPNLEIGSGetRKShifts(SlepcNEP,PetscInt*,PetscScalar*[]) PetscErrorCode NEPNLEIGSGetKSPs(SlepcNEP,PetscInt*,PetscKSP**) PetscErrorCode NEPNLEIGSSetFullBasis(SlepcNEP,PetscBool) PetscErrorCode NEPNLEIGSGetFullBasis(SlepcNEP,PetscBool*) PetscErrorCode NEPNLEIGSSetEPS(SlepcNEP,SlepcEPS) PetscErrorCode NEPNLEIGSGetEPS(SlepcNEP,SlepcEPS*) ctypedef enum SlepcNEPCISSExtraction "NEPCISSExtraction": NEP_CISS_EXTRACTION_RITZ NEP_CISS_EXTRACTION_HANKEL NEP_CISS_EXTRACTION_CAA PetscErrorCode NEPCISSSetExtraction(SlepcNEP,SlepcNEPCISSExtraction) PetscErrorCode NEPCISSGetExtraction(SlepcNEP,SlepcNEPCISSExtraction*) PetscErrorCode NEPCISSSetSizes(SlepcNEP,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscBool) PetscErrorCode NEPCISSGetSizes(SlepcNEP,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscBool*) PetscErrorCode NEPCISSSetThreshold(SlepcNEP,PetscReal,PetscReal) PetscErrorCode NEPCISSGetThreshold(SlepcNEP,PetscReal*,PetscReal*) PetscErrorCode NEPCISSSetRefinement(SlepcNEP,PetscInt,PetscInt) PetscErrorCode NEPCISSGetRefinement(SlepcNEP,PetscInt*,PetscInt*) PetscErrorCode NEPCISSGetKSPs(SlepcNEP,PetscInt*,PetscKSP**) # ----------------------------------------------------------------------------- cdef inline NEP ref_NEP(SlepcNEP nep): cdef NEP ob = NEP() ob.nep = nep CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode NEP_Function( SlepcNEP nep, PetscScalar mu, PetscMat A, PetscMat B, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef NEP Nep = ref_NEP(nep) cdef Mat Amat = ref_Mat(A) cdef Mat Bmat = ref_Mat(B) (function, args, kargs) = Nep.get_attr('__function__') retv = function(Nep, toScalar(mu), Amat, Bmat, *args, **kargs) cdef PetscMat Atmp = NULL, Btmp = NULL Atmp = A; A = Amat.mat; Amat.mat = Atmp Btmp = B; B = Bmat.mat; Bmat.mat = Btmp return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode NEP_Jacobian( SlepcNEP nep, PetscScalar mu, PetscMat J, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef NEP Nep = ref_NEP(nep) cdef Mat Jmat = ref_Mat(J) (jacobian, args, kargs) = Nep.get_attr('__jacobian__') retv = jacobian(Nep, toScalar(mu), Jmat, *args, **kargs) cdef PetscMat Jtmp = NULL Jtmp = J; J = Jmat.mat; Jmat.mat = Jtmp return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode NEP_Stopping( SlepcNEP nep, PetscInt its, PetscInt max_it, PetscInt nconv, PetscInt nev, SlepcNEPConvergedReason *r, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef NEP Nep = ref_NEP(nep) (stopping, args, kargs) = Nep.get_attr('__stopping__') reason = stopping(Nep, toInt(its), toInt(max_it), toInt(nconv), toInt(nev), *args, **kargs) if reason is None: r[0] = NEP_CONVERGED_ITERATING elif reason is False: r[0] = NEP_CONVERGED_ITERATING elif reason is True: r[0] = NEP_CONVERGED_USER else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode NEP_Comparison( PetscScalar ar, PetscScalar ai, PetscScalar br, PetscScalar bi, PetscInt* res, void *ctx, ) except PETSC_ERR_PYTHON with gil: (comparison, args, kargs) = ctx r = comparison(toComplex(ar, ai), toComplex(br, bi), args, **kargs) res[0] = asInt(r) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode NEP_Monitor( SlepcNEP nep, PetscInt its, PetscInt nconv, PetscScalar *eigr, PetscScalar *eigi, PetscReal *errest, PetscInt nest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef NEP Nep = ref_NEP(nep) cdef object monitorlist = Nep.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS cdef object eig = [toComplex(eigr[i], eigi[i]) for i in range(nest)] cdef object err = [toReal(errest[i]) for i in range(nest)] for (monitor, args, kargs) in monitorlist: monitor(Nep, toInt(its), toInt(nconv), eig, err, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcpep.pxi0000644000076500000240000003136615133663436020376 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcPEPType "const char*" SlepcPEPType PEPLINEAR SlepcPEPType PEPQARNOLDI SlepcPEPType PEPTOAR SlepcPEPType PEPSTOAR SlepcPEPType PEPJD SlepcPEPType PEPCISS ctypedef enum SlepcPEPProblemType "PEPProblemType": PEP_GENERAL PEP_HERMITIAN PEP_HYPERBOLIC PEP_GYROSCOPIC ctypedef enum SlepcPEPRefine "PEPRefine": PEP_REFINE_NONE PEP_REFINE_SIMPLE PEP_REFINE_MULTIPLE ctypedef enum SlepcPEPExtract "PEPExtract": PEP_EXTRACT_NONE PEP_EXTRACT_NORM PEP_EXTRACT_RESIDUAL PEP_EXTRACT_STRUCTURED ctypedef enum SlepcPEPRefineScheme "PEPRefineScheme": PEP_REFINE_SCHEME_EXPLICIT PEP_REFINE_SCHEME_MBE PEP_REFINE_SCHEME_SCHUR ctypedef enum SlepcPEPErrorType "PEPErrorType": PEP_ERROR_ABSOLUTE PEP_ERROR_RELATIVE PEP_ERROR_BACKWARD ctypedef enum SlepcPEPWhich "PEPWhich": PEP_LARGEST_MAGNITUDE PEP_SMALLEST_MAGNITUDE PEP_LARGEST_REAL PEP_SMALLEST_REAL PEP_LARGEST_IMAGINARY PEP_SMALLEST_IMAGINARY PEP_TARGET_MAGNITUDE PEP_TARGET_REAL PEP_TARGET_IMAGINARY PEP_ALL PEP_WHICH_USER ctypedef enum SlepcPEPBasis "PEPBasis": PEP_BASIS_MONOMIAL PEP_BASIS_CHEBYSHEV1 PEP_BASIS_CHEBYSHEV2 PEP_BASIS_LEGENDRE PEP_BASIS_LAGUERRE PEP_BASIS_HERMITE ctypedef enum SlepcPEPScale "PEPScale": PEP_SCALE_NONE PEP_SCALE_SCALAR PEP_SCALE_DIAGONAL PEP_SCALE_BOTH ctypedef enum SlepcPEPConv "PEPConv": PEP_CONV_ABS PEP_CONV_REL PEP_CONV_NORM PEP_CONV_USER ctypedef enum SlepcPEPStop "PEPStop": PEP_STOP_BASIC PEP_STOP_USER ctypedef enum SlepcPEPConvergedReason "PEPConvergedReason": PEP_CONVERGED_TOL PEP_CONVERGED_USER PEP_DIVERGED_ITS PEP_DIVERGED_BREAKDOWN PEP_DIVERGED_SYMMETRY_LOST PEP_CONVERGED_ITERATING ctypedef PetscErrorCode (*SlepcPEPCtxDel)(void*) ctypedef PetscErrorCode (*SlepcPEPStoppingFunction)(SlepcPEP, PetscInt, PetscInt, PetscInt, PetscInt, SlepcPEPConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcPEPMonitorFunction)(SlepcPEP, PetscInt, PetscInt, PetscScalar*, PetscScalar*, PetscReal*, PetscInt, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcPEPComparisonFunction)(PetscScalar, PetscScalar, PetscScalar, PetscScalar, PetscInt*, void*) except PETSC_ERR_PYTHON PetscErrorCode PEPCreate(MPI_Comm,SlepcPEP*) PetscErrorCode PEPDestroy(SlepcPEP*) PetscErrorCode PEPReset(SlepcPEP) PetscErrorCode PEPView(SlepcPEP,PetscViewer) PetscErrorCode PEPSetType(SlepcPEP,SlepcPEPType) PetscErrorCode PEPGetType(SlepcPEP,SlepcPEPType*) PetscErrorCode PEPSetBasis(SlepcPEP,SlepcPEPBasis) PetscErrorCode PEPGetBasis(SlepcPEP,SlepcPEPBasis*) PetscErrorCode PEPSetProblemType(SlepcPEP,SlepcPEPProblemType) PetscErrorCode PEPGetProblemType(SlepcPEP,SlepcPEPProblemType*) PetscErrorCode PEPSetOperators(SlepcPEP,PetscInt,PetscMat*) PetscErrorCode PEPGetOperators(SlepcPEP,PetscInt,PetscMat*) PetscErrorCode PEPGetNumMatrices(SlepcPEP,PetscInt*) PetscErrorCode PEPSetOptionsPrefix(SlepcPEP,char*) PetscErrorCode PEPGetOptionsPrefix(SlepcPEP,char*[]) PetscErrorCode PEPSetFromOptions(SlepcPEP) PetscErrorCode PEPAppendOptionsPrefix(SlepcPEP,char*) PetscErrorCode PEPSetUp(SlepcPEP) PetscErrorCode PEPSolve(SlepcPEP) PetscErrorCode PEPSetBV(SlepcPEP,SlepcBV) PetscErrorCode PEPGetBV(SlepcPEP,SlepcBV*) PetscErrorCode PEPSetDS(SlepcPEP,SlepcDS) PetscErrorCode PEPGetDS(SlepcPEP,SlepcDS*) PetscErrorCode PEPSetST(SlepcPEP,SlepcST) PetscErrorCode PEPGetST(SlepcPEP,SlepcST*) PetscErrorCode PEPSetRG(SlepcPEP,SlepcRG) PetscErrorCode PEPGetRG(SlepcPEP,SlepcRG*) PetscErrorCode PEPSetTrackAll(SlepcPEP,PetscBool) PetscErrorCode PEPGetTrackAll(SlepcPEP,PetscBool*) PetscErrorCode PEPSetTolerances(SlepcPEP,PetscReal,PetscInt) PetscErrorCode PEPGetTolerances(SlepcPEP,PetscReal*,PetscInt*) PetscErrorCode PEPSetDimensions(SlepcPEP,PetscInt,PetscInt,PetscInt) PetscErrorCode PEPGetDimensions(SlepcPEP,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode PEPSetScale(SlepcPEP,SlepcPEPScale,PetscReal,PetscVec,PetscVec,PetscInt,PetscReal) PetscErrorCode PEPGetScale(SlepcPEP,SlepcPEPScale*,PetscReal*,PetscVec*,PetscVec*,PetscInt*,PetscReal*) PetscErrorCode PEPGetConverged(SlepcPEP,PetscInt*) PetscErrorCode PEPGetEigenpair(SlepcPEP,PetscInt,PetscScalar*,PetscScalar*,PetscVec,PetscVec) PetscErrorCode PEPComputeError(SlepcPEP,PetscInt,SlepcPEPErrorType,PetscReal*) PetscErrorCode PEPErrorView(SlepcPEP,SlepcPEPErrorType,PetscViewer) PetscErrorCode PEPValuesView(SlepcPEP,PetscViewer) PetscErrorCode PEPVectorsView(SlepcPEP,PetscViewer) PetscErrorCode PEPGetErrorEstimate(SlepcPEP,PetscInt,PetscReal*) PetscErrorCode PEPSetStoppingTestFunction(SlepcPEP,SlepcPEPStoppingFunction,void*,SlepcPEPCtxDel) PetscErrorCode PEPStoppingBasic(SlepcPEP,PetscInt,PetscInt,PetscInt,PetscInt,SlepcPEPConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode PEPSetEigenvalueComparison(SlepcPEP,SlepcPEPComparisonFunction,void*); PetscErrorCode PEPSetConvergenceTest(SlepcPEP,SlepcPEPConv) PetscErrorCode PEPGetConvergenceTest(SlepcPEP,SlepcPEPConv*) PetscErrorCode PEPSetRefine(SlepcPEP,SlepcPEPRefine,PetscInt,PetscReal,PetscInt,SlepcPEPRefineScheme) PetscErrorCode PEPGetRefine(SlepcPEP,SlepcPEPRefine*,PetscInt*,PetscReal*,PetscInt*,SlepcPEPRefineScheme*) PetscErrorCode PEPRefineGetKSP(SlepcPEP,PetscKSP*) PetscErrorCode PEPSetExtract(SlepcPEP,SlepcPEPExtract); PetscErrorCode PEPGetExtract(SlepcPEP,SlepcPEPExtract*) PetscErrorCode PEPMonitorSet(SlepcPEP,SlepcPEPMonitorFunction,void*,SlepcPEPCtxDel) PetscErrorCode PEPMonitorCancel(SlepcPEP) PetscErrorCode PEPGetIterationNumber(SlepcPEP,PetscInt*) PetscErrorCode PEPSetInitialSpace(SlepcPEP,PetscInt,PetscVec*) PetscErrorCode PEPSetWhichEigenpairs(SlepcPEP,SlepcPEPWhich) PetscErrorCode PEPGetWhichEigenpairs(SlepcPEP,SlepcPEPWhich*) PetscErrorCode PEPSetTarget(SlepcPEP,PetscScalar) PetscErrorCode PEPGetTarget(SlepcPEP,PetscScalar*) PetscErrorCode PEPSetInterval(SlepcPEP,PetscReal,PetscReal) PetscErrorCode PEPGetInterval(SlepcPEP,PetscReal*,PetscReal*) PetscErrorCode PEPGetConvergedReason(SlepcPEP,SlepcPEPConvergedReason*) PetscErrorCode PEPLinearSetLinearization(SlepcPEP,PetscReal,PetscReal) PetscErrorCode PEPLinearGetLinearization(SlepcPEP,PetscReal*,PetscReal*) PetscErrorCode PEPLinearSetExplicitMatrix(SlepcPEP,PetscBool) PetscErrorCode PEPLinearGetExplicitMatrix(SlepcPEP,PetscBool*) PetscErrorCode PEPLinearSetEPS(SlepcPEP,SlepcEPS) PetscErrorCode PEPLinearGetEPS(SlepcPEP,SlepcEPS*) PetscErrorCode PEPQArnoldiSetRestart(SlepcPEP,PetscReal) PetscErrorCode PEPQArnoldiGetRestart(SlepcPEP,PetscReal*) PetscErrorCode PEPQArnoldiSetLocking(SlepcPEP,PetscBool) PetscErrorCode PEPQArnoldiGetLocking(SlepcPEP,PetscBool*) PetscErrorCode PEPTOARSetRestart(SlepcPEP,PetscReal) PetscErrorCode PEPTOARGetRestart(SlepcPEP,PetscReal*) PetscErrorCode PEPTOARSetLocking(SlepcPEP,PetscBool) PetscErrorCode PEPTOARGetLocking(SlepcPEP,PetscBool*) PetscErrorCode PEPSTOARSetLinearization(SlepcPEP,PetscReal,PetscReal) PetscErrorCode PEPSTOARGetLinearization(SlepcPEP,PetscReal*,PetscReal*) PetscErrorCode PEPSTOARSetLocking(SlepcPEP,PetscBool) PetscErrorCode PEPSTOARGetLocking(SlepcPEP,PetscBool*) PetscErrorCode PEPSTOARSetDetectZeros(SlepcPEP,PetscBool) PetscErrorCode PEPSTOARGetDetectZeros(SlepcPEP,PetscBool*) PetscErrorCode PEPSTOARSetDimensions(SlepcPEP,PetscInt,PetscInt,PetscInt) PetscErrorCode PEPSTOARGetDimensions(SlepcPEP,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode PEPSTOARGetInertias(SlepcPEP,PetscInt*,PetscReal**,PetscInt**) PetscErrorCode PEPSTOARSetCheckEigenvalueType(SlepcPEP,PetscBool) PetscErrorCode PEPSTOARGetCheckEigenvalueType(SlepcPEP,PetscBool*) ctypedef enum SlepcPEPJDProjection "PEPJDProjection": PEP_JD_PROJECTION_HARMONIC PEP_JD_PROJECTION_ORTHOGONAL PetscErrorCode PEPJDSetRestart(SlepcPEP,PetscReal) PetscErrorCode PEPJDGetRestart(SlepcPEP,PetscReal*) PetscErrorCode PEPJDSetFix(SlepcPEP,PetscReal) PetscErrorCode PEPJDGetFix(SlepcPEP,PetscReal*) PetscErrorCode PEPJDSetReusePreconditioner(SlepcPEP,PetscBool) PetscErrorCode PEPJDGetReusePreconditioner(SlepcPEP,PetscBool*) PetscErrorCode PEPJDSetMinimalityIndex(SlepcPEP,PetscInt) PetscErrorCode PEPJDGetMinimalityIndex(SlepcPEP,PetscInt*) PetscErrorCode PEPJDSetProjection(SlepcPEP,SlepcPEPJDProjection) PetscErrorCode PEPJDGetProjection(SlepcPEP,SlepcPEPJDProjection*) ctypedef enum SlepcPEPCISSExtraction "PEPCISSExtraction": PEP_CISS_EXTRACTION_RITZ PEP_CISS_EXTRACTION_HANKEL PEP_CISS_EXTRACTION_CAA PetscErrorCode PEPCISSSetExtraction(SlepcPEP,SlepcPEPCISSExtraction) PetscErrorCode PEPCISSGetExtraction(SlepcPEP,SlepcPEPCISSExtraction*) PetscErrorCode PEPCISSSetSizes(SlepcPEP,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscBool) PetscErrorCode PEPCISSGetSizes(SlepcPEP,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscBool*) PetscErrorCode PEPCISSSetThreshold(SlepcPEP,PetscReal,PetscReal) PetscErrorCode PEPCISSGetThreshold(SlepcPEP,PetscReal*,PetscReal*) PetscErrorCode PEPCISSSetRefinement(SlepcPEP,PetscInt,PetscInt) PetscErrorCode PEPCISSGetRefinement(SlepcPEP,PetscInt*,PetscInt*) PetscErrorCode PEPCISSGetKSPs(SlepcPEP,PetscInt*,PetscKSP**) # ----------------------------------------------------------------------------- cdef inline PEP ref_PEP(SlepcPEP pep): cdef PEP ob = PEP() ob.pep = pep CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode PEP_Stopping( SlepcPEP pep, PetscInt its, PetscInt max_it, PetscInt nconv, PetscInt nev, SlepcPEPConvergedReason *r, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef PEP Pep = ref_PEP(pep) (stopping, args, kargs) = Pep.get_attr('__stopping__') reason = stopping(Pep, toInt(its), toInt(max_it), toInt(nconv), toInt(nev), *args, **kargs) if reason is None: r[0] = PEP_CONVERGED_ITERATING elif reason is False: r[0] = PEP_CONVERGED_ITERATING elif reason is True: r[0] = PEP_CONVERGED_USER else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode PEP_Comparison( PetscScalar ar, PetscScalar ai, PetscScalar br, PetscScalar bi, PetscInt* res, void *ctx, ) except PETSC_ERR_PYTHON with gil: (comparison, args, kargs) = ctx r = comparison(toComplex(ar, ai), toComplex(br, bi), args, **kargs) res[0] = asInt(r) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode PEP_Monitor( SlepcPEP pep, PetscInt its, PetscInt nconv, PetscScalar *eigr, PetscScalar *eigi, PetscReal *errest, PetscInt nest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef PEP Pep = ref_PEP(pep) cdef object monitorlist = Pep.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS cdef object eig = [toComplex(eigr[i], eigi[i]) for i in range(nest)] cdef object err = [toReal(errest[i]) for i in range(nest)] for (monitor, args, kargs) in monitorlist: monitor(Pep, toInt(its), toInt(nconv), eig, err, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcrg.pxi0000644000076500000240000000444715133663436020222 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcRGType "const char*" SlepcRGType RGINTERVAL SlepcRGType RGPOLYGON SlepcRGType RGELLIPSE SlepcRGType RGRING ctypedef enum SlepcRGQuadRule "RGQuadRule": RG_QUADRULE_TRAPEZOIDAL RG_QUADRULE_CHEBYSHEV PetscErrorCode RGCreate(MPI_Comm,SlepcRG*) PetscErrorCode RGView(SlepcRG,PetscViewer) PetscErrorCode RGDestroy(SlepcRG*) PetscErrorCode RGSetType(SlepcRG,SlepcRGType) PetscErrorCode RGGetType(SlepcRG,SlepcRGType*) PetscErrorCode RGSetOptionsPrefix(SlepcRG,char[]) PetscErrorCode RGGetOptionsPrefix(SlepcRG,char*[]) PetscErrorCode RGAppendOptionsPrefix(SlepcRG,char[]) PetscErrorCode RGSetFromOptions(SlepcRG) PetscErrorCode RGIsTrivial(SlepcRG,PetscBool*) PetscErrorCode RGIsAxisymmetric(SlepcRG,PetscBool,PetscBool*) PetscErrorCode RGSetComplement(SlepcRG,PetscBool) PetscErrorCode RGGetComplement(SlepcRG,PetscBool*) PetscErrorCode RGSetScale(SlepcRG,PetscReal) PetscErrorCode RGGetScale(SlepcRG,PetscReal*) PetscErrorCode RGPushScale(SlepcRG,PetscReal) PetscErrorCode RGPopScale(SlepcRG) PetscErrorCode RGCheckInside(SlepcRG,PetscInt,PetscScalar*,PetscScalar*,PetscInt*) PetscErrorCode RGComputeContour(SlepcRG,PetscInt,PetscScalar*,PetscScalar*) PetscErrorCode RGComputeBoundingBox(SlepcRG,PetscReal*,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode RGCanUseConjugates(SlepcRG,PetscBool,PetscBool*) PetscErrorCode RGComputeQuadrature(SlepcRG,SlepcRGQuadRule,PetscInt,PetscScalar*,PetscScalar*,PetscScalar*) PetscErrorCode RGEllipseSetParameters(SlepcRG,PetscScalar,PetscReal,PetscReal) PetscErrorCode RGEllipseGetParameters(SlepcRG,PetscScalar*,PetscReal*,PetscReal*) PetscErrorCode RGIntervalSetEndpoints(SlepcRG,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode RGIntervalGetEndpoints(SlepcRG,PetscReal*,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode RGPolygonSetVertices(SlepcRG,PetscInt,PetscScalar*,PetscScalar*) PetscErrorCode RGPolygonGetVertices(SlepcRG,PetscInt*,PetscScalar**,PetscScalar**) PetscErrorCode RGRingSetParameters(SlepcRG,PetscScalar,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode RGRingGetParameters(SlepcRG,PetscScalar*,PetscReal*,PetscReal*,PetscReal*,PetscReal*,PetscReal*) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcst.pxi0000644000076500000240000000647315133663436020241 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcSTType "const char*" SlepcSTType STSHELL SlepcSTType STSHIFT SlepcSTType STSINVERT SlepcSTType STCAYLEY SlepcSTType STPRECOND SlepcSTType STFILTER ctypedef enum SlepcSTMatMode "STMatMode": ST_MATMODE_COPY ST_MATMODE_INPLACE ST_MATMODE_SHELL PetscErrorCode STView(SlepcST,PetscViewer) PetscErrorCode STDestroy(SlepcST*) PetscErrorCode STReset(SlepcST) PetscErrorCode STCreate(MPI_Comm,SlepcST*) PetscErrorCode STGetType(SlepcST,SlepcSTType*) PetscErrorCode STSetType(SlepcST,SlepcSTType) PetscErrorCode STGetOptionsPrefix(SlepcST,char*[]) PetscErrorCode STSetOptionsPrefix(SlepcST,char[]) PetscErrorCode STAppendOptionsPrefix(SlepcST,char[]) PetscErrorCode STSetFromOptions(SlepcST) PetscErrorCode STGetShift(SlepcST,PetscScalar*) PetscErrorCode STSetShift(SlepcST,PetscScalar) PetscErrorCode STGetKSP(SlepcST,PetscKSP*) PetscErrorCode STSetKSP(SlepcST,PetscKSP) PetscErrorCode STGetOperator(SlepcST,PetscMat*) PetscErrorCode STRestoreOperator(SlepcST,PetscMat*) PetscErrorCode STGetNumMatrices(SlepcST,PetscInt*) PetscErrorCode STGetMatrix(SlepcST,PetscInt,PetscMat*) PetscErrorCode STSetMatrices(SlepcST,PetscInt,PetscMat*) PetscErrorCode STSetMatStructure(SlepcST,PetscMatStructure) PetscErrorCode STGetMatStructure(SlepcST,PetscMatStructure*) PetscErrorCode STSetPreconditionerMat(SlepcST,PetscMat) PetscErrorCode STGetPreconditionerMat(SlepcST,PetscMat*) PetscErrorCode STSetSplitPreconditioner(SlepcST,PetscInt,PetscMat*,PetscMatStructure) PetscErrorCode STGetSplitPreconditionerTerm(SlepcST,PetscInt,PetscMat*) PetscErrorCode STGetSplitPreconditionerInfo(SlepcST,PetscInt*,PetscMatStructure*) PetscErrorCode STSetTransform(SlepcST,PetscBool) PetscErrorCode STGetTransform(SlepcST,PetscBool*) PetscErrorCode STGetMatMode(SlepcST,SlepcSTMatMode*) PetscErrorCode STSetMatMode(SlepcST,SlepcSTMatMode) PetscErrorCode STSetUp(SlepcST) PetscErrorCode STApply(SlepcST,PetscVec,PetscVec) PetscErrorCode STApplyMat(SlepcST,PetscMat,PetscMat) PetscErrorCode STApplyTranspose(SlepcST,PetscVec,PetscVec) PetscErrorCode STApplyHermitianTranspose(SlepcST,PetscVec,PetscVec) PetscErrorCode STCayleySetAntishift(SlepcST,PetscScalar) PetscErrorCode STCayleyGetAntishift(SlepcST,PetscScalar*) ctypedef enum SlepcSTFilterType "STFilterType": ST_FILTER_FILTLAN ST_FILTER_CHEBYSHEV ctypedef enum SlepcSTFilterDamping "STFilterDamping": ST_FILTER_DAMPING_NONE ST_FILTER_DAMPING_JACKSON ST_FILTER_DAMPING_LANCZOS ST_FILTER_DAMPING_FEJER PetscErrorCode STFilterSetType(SlepcST,SlepcSTFilterType); PetscErrorCode STFilterGetType(SlepcST,SlepcSTFilterType*); PetscErrorCode STFilterSetInterval(SlepcST,PetscReal,PetscReal) PetscErrorCode STFilterGetInterval(SlepcST,PetscReal*,PetscReal*) PetscErrorCode STFilterSetRange(SlepcST,PetscReal,PetscReal) PetscErrorCode STFilterGetRange(SlepcST,PetscReal*,PetscReal*) PetscErrorCode STFilterSetDegree(SlepcST,PetscInt) PetscErrorCode STFilterGetDegree(SlepcST,PetscInt*) PetscErrorCode STFilterSetDamping(SlepcST,SlepcSTFilterDamping); PetscErrorCode STFilterGetDamping(SlepcST,SlepcSTFilterDamping*); ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcsvd.pxi0000644000076500000240000002103115133663436020372 0ustar00jromanstaffcdef extern from * nogil: ctypedef char* SlepcSVDType "const char*" SlepcSVDType SVDCROSS SlepcSVDType SVDCYCLIC SlepcSVDType SVDLAPACK SlepcSVDType SVDLANCZOS SlepcSVDType SVDTRLANCZOS SlepcSVDType SVDRANDOMIZED SlepcSVDType SVDSCALAPACK SlepcSVDType SVDKSVD SlepcSVDType SVDELEMENTAL SlepcSVDType SVDPRIMME ctypedef enum SlepcSVDProblemType "SVDProblemType": SVD_STANDARD SVD_GENERALIZED SVD_HYPERBOLIC ctypedef enum SlepcSVDWhich "SVDWhich": SVD_LARGEST SVD_SMALLEST ctypedef enum SlepcSVDErrorType "SVDErrorType": SVD_ERROR_ABSOLUTE SVD_ERROR_RELATIVE SVD_ERROR_NORM ctypedef enum SlepcSVDConv "SVDConv": SVD_CONV_ABS SVD_CONV_REL SVD_CONV_NORM SVD_CONV_MAXIT SVD_CONV_USER ctypedef enum SlepcSVDStop "SVDStop": SVD_STOP_BASIC SVD_STOP_USER SVD_STOP_THRESHOLD ctypedef enum SlepcSVDConvergedReason "SVDConvergedReason": SVD_CONVERGED_TOL SVD_CONVERGED_USER SVD_CONVERGED_MAXIT SVD_DIVERGED_ITS SVD_DIVERGED_BREAKDOWN SVD_DIVERGED_SYMMETRY_LOST SVD_CONVERGED_ITERATING ctypedef PetscErrorCode (*SlepcSVDCtxDel)(void*) ctypedef PetscErrorCode (*SlepcSVDStoppingFunction)(SlepcSVD, PetscInt, PetscInt, PetscInt, PetscInt, SlepcSVDConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*SlepcSVDMonitorFunction)(SlepcSVD, PetscInt, PetscInt, PetscReal*, PetscReal*, PetscInt, void*) except PETSC_ERR_PYTHON PetscErrorCode SVDCreate(MPI_Comm,SlepcSVD*) PetscErrorCode SVDView(SlepcSVD,PetscViewer) PetscErrorCode SVDDestroy(SlepcSVD*) PetscErrorCode SVDReset(SlepcSVD) PetscErrorCode SVDSetType(SlepcSVD,SlepcSVDType) PetscErrorCode SVDGetType(SlepcSVD,SlepcSVDType*) PetscErrorCode SVDSetOptionsPrefix(SlepcSVD,char[]) PetscErrorCode SVDAppendOptionsPrefix(SlepcSVD,char[]) PetscErrorCode SVDGetOptionsPrefix(SlepcSVD,char*[]) PetscErrorCode SVDSetFromOptions(SlepcSVD) PetscErrorCode SVDSetProblemType(SlepcSVD,SlepcSVDProblemType) PetscErrorCode SVDGetProblemType(SlepcSVD,SlepcSVDProblemType*) PetscErrorCode SVDIsGeneralized(SlepcSVD,PetscBool*) PetscErrorCode SVDIsHyperbolic(SlepcSVD,PetscBool*) PetscErrorCode SVDSetBV(SlepcSVD,SlepcBV,SlepcBV) PetscErrorCode SVDGetBV(SlepcSVD,SlepcBV*,SlepcBV*) PetscErrorCode SVDSetDS(SlepcSVD,SlepcDS) PetscErrorCode SVDGetDS(SlepcSVD,SlepcDS*) PetscErrorCode SVDSetOperators(SlepcSVD,PetscMat,PetscMat) PetscErrorCode SVDGetOperators(SlepcSVD,PetscMat*,PetscMat*) PetscErrorCode SVDSetSignature(SlepcSVD,PetscVec) PetscErrorCode SVDGetSignature(SlepcSVD,PetscVec) PetscErrorCode SVDSetInitialSpaces(SlepcSVD,PetscInt,PetscVec*,PetscInt,PetscVec*) PetscErrorCode SVDSetImplicitTranspose(SlepcSVD,PetscBool) PetscErrorCode SVDGetImplicitTranspose(SlepcSVD,PetscBool*) PetscErrorCode SVDSetDimensions(SlepcSVD,PetscInt,PetscInt,PetscInt) PetscErrorCode SVDGetDimensions(SlepcSVD,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode SVDSetTolerances(SlepcSVD,PetscReal,PetscInt) PetscErrorCode SVDGetTolerances(SlepcSVD,PetscReal*,PetscInt*) PetscErrorCode SVDSetWhichSingularTriplets(SlepcSVD,SlepcSVDWhich) PetscErrorCode SVDGetWhichSingularTriplets(SlepcSVD,SlepcSVDWhich*) PetscErrorCode SVDSetThreshold(SlepcSVD,PetscReal,PetscBool) PetscErrorCode SVDGetThreshold(SlepcSVD,PetscReal*,PetscBool*) PetscErrorCode SVDSetConvergenceTest(SlepcSVD,SlepcSVDConv) PetscErrorCode SVDGetConvergenceTest(SlepcSVD,SlepcSVDConv*) PetscErrorCode SVDMonitorSet(SlepcSVD,SlepcSVDMonitorFunction,void*,SlepcSVDCtxDel) PetscErrorCode SVDMonitorCancel(SlepcSVD) PetscErrorCode SVDSetStoppingTestFunction(SlepcSVD,SlepcSVDStoppingFunction,void*,SlepcSVDCtxDel) PetscErrorCode SVDStoppingBasic(SlepcSVD,PetscInt,PetscInt,PetscInt,PetscInt,SlepcSVDConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode SVDSetTrackAll(SlepcSVD,PetscBool) PetscErrorCode SVDGetTrackAll(SlepcSVD,PetscBool*) PetscErrorCode SVDSetUp(SlepcSVD) PetscErrorCode SVDSolve(SlepcSVD) PetscErrorCode SVDGetIterationNumber(SlepcSVD,PetscInt*) PetscErrorCode SVDGetConvergedReason(SlepcSVD,SlepcSVDConvergedReason*) PetscErrorCode SVDGetConverged(SlepcSVD,PetscInt*) PetscErrorCode SVDGetSingularTriplet(SlepcSVD,PetscInt,PetscReal*,PetscVec,PetscVec) PetscErrorCode SVDComputeError(SlepcSVD,PetscInt,SlepcSVDErrorType,PetscReal*) PetscErrorCode SVDErrorView(SlepcSVD,SlepcSVDErrorType,PetscViewer) PetscErrorCode SVDValuesView(SlepcSVD,PetscViewer) PetscErrorCode SVDVectorsView(SlepcSVD,PetscViewer) PetscErrorCode SVDCrossSetExplicitMatrix(SlepcSVD,PetscBool) PetscErrorCode SVDCrossGetExplicitMatrix(SlepcSVD,PetscBool*) PetscErrorCode SVDCrossSetEPS(SlepcSVD,SlepcEPS) PetscErrorCode SVDCrossGetEPS(SlepcSVD,SlepcEPS*) PetscErrorCode SVDCyclicSetExplicitMatrix(SlepcSVD,PetscBool) PetscErrorCode SVDCyclicGetExplicitMatrix(SlepcSVD,PetscBool*) PetscErrorCode SVDCyclicSetEPS(SlepcSVD,SlepcEPS) PetscErrorCode SVDCyclicGetEPS(SlepcSVD,SlepcEPS*) PetscErrorCode SVDLanczosSetOneSide(SlepcSVD,PetscBool) PetscErrorCode SVDLanczosGetOneSide(SlepcSVD,PetscBool*) PetscErrorCode SVDTRLanczosSetOneSide(SlepcSVD,PetscBool) PetscErrorCode SVDTRLanczosGetOneSide(SlepcSVD,PetscBool*) PetscErrorCode SVDTRLanczosSetGBidiag(SlepcSVD,SlepcSVDTRLanczosGBidiag) PetscErrorCode SVDTRLanczosGetGBidiag(SlepcSVD,SlepcSVDTRLanczosGBidiag*) PetscErrorCode SVDTRLanczosSetKSP(SlepcSVD,PetscKSP) PetscErrorCode SVDTRLanczosGetKSP(SlepcSVD,PetscKSP*) PetscErrorCode SVDTRLanczosSetRestart(SlepcSVD,PetscReal) PetscErrorCode SVDTRLanczosGetRestart(SlepcSVD,PetscReal*) PetscErrorCode SVDTRLanczosSetLocking(SlepcSVD,PetscBool) PetscErrorCode SVDTRLanczosGetLocking(SlepcSVD,PetscBool*) PetscErrorCode SVDTRLanczosSetExplicitMatrix(SlepcSVD,PetscBool) PetscErrorCode SVDTRLanczosGetExplicitMatrix(SlepcSVD,PetscBool*) ctypedef enum SlepcSVDTRLanczosGBidiag "SVDTRLanczosGBidiag": SVD_TRLANCZOS_GBIDIAG_SINGLE SVD_TRLANCZOS_GBIDIAG_UPPER SVD_TRLANCZOS_GBIDIAG_LOWER # ----------------------------------------------------------------------------- cdef inline SVD ref_SVD(SlepcSVD svd): cdef SVD ob = SVD() ob.svd = svd CHKERR( PetscINCREF(ob.obj) ) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode SVD_Stopping( SlepcSVD svd, PetscInt its, PetscInt max_it, PetscInt nconv, PetscInt nev, SlepcSVDConvergedReason *r, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef SVD Svd = ref_SVD(svd) (stopping, args, kargs) = Svd.get_attr('__stopping__') reason = stopping(Svd, toInt(its), toInt(max_it), toInt(nconv), toInt(nev), *args, **kargs) if reason is None: r[0] = SVD_CONVERGED_ITERATING elif reason is False: r[0] = SVD_CONVERGED_ITERATING elif reason is True: r[0] = SVD_CONVERGED_USER else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SVD_Monitor( SlepcSVD svd, PetscInt its, PetscInt nconv, PetscReal *sigma, PetscReal *errest, PetscInt nest, void *ctx, ) except PETSC_ERR_PYTHON with gil: cdef SVD Svd = ref_SVD(svd) cdef object monitorlist = Svd.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS cdef object eig = [toReal(sigma[i]) for i in range(nest)] cdef object err = [toReal(errest[i]) for i in range(nest)] for (monitor, args, kargs) in monitorlist: monitor(Svd, toInt(its), toInt(nconv), eig, err, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcsys.pxi0000644000076500000240000000627615133663436020432 0ustar00jromanstaffcdef extern from * nogil: enum: PETSC_DECIDE enum: PETSC_DEFAULT enum: PETSC_DETERMINE enum: PETSC_CURRENT ctypedef const char* PetscVecType "VecType" ctypedef enum PetscNormType "NormType": PETSC_NORM_1 "NORM_1" PETSC_NORM_2 "NORM_2" PETSC_NORM_1_AND_2 "NORM_1_AND_2" PETSC_NORM_FROBENIUS "NORM_FROBENIUS" PETSC_NORM_INFINITY "NORM_INFINITY" PETSC_NORM_MAX "NORM_MAX" ctypedef enum PetscMatStructure "MatStructure": MAT_SAME_NONZERO_PATTERN "SAME_NONZERO_PATTERN" MAT_DIFFERENT_NONZERO_PATTERN "DIFFERENT_NONZERO_PATTERN" MAT_SUBSET_NONZERO_PATTERN "SUBSET_NONZERO_PATTERN" cdef extern from * nogil: PetscErrorCode PetscMalloc(size_t,void*) PetscErrorCode PetscFree(void*) PetscErrorCode PetscMemcpy(void*,void*,size_t) PetscErrorCode PetscMemzero(void*,size_t) cdef extern from * nogil: MPI_Comm PetscObjectComm(PetscObject) PetscErrorCode PetscObjectReference(PetscObject) PetscErrorCode PetscObjectDereference(PetscObject) PetscErrorCode PetscObjectDestroy(PetscObject*) PetscErrorCode PetscObjectTypeCompare(PetscObject,char[],PetscBool*) cdef extern from * nogil: PetscErrorCode VecCopy(PetscVec,PetscVec) PetscErrorCode VecSet(PetscVec,PetscScalar) PetscErrorCode VecDestroy(PetscVec*) cdef extern from * nogil: PetscErrorCode MatGetSize(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetLocalSize(PetscMat,PetscInt*,PetscInt*) cdef extern from * nogil: const char SLEPC_AUTHOR_INFO[] PetscErrorCode SlepcGetVersion(char[],size_t) PetscErrorCode SlepcGetVersionNumber(PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode SlepcInitialize(int*,char***,char[],char[]) PetscErrorCode SlepcFinalize() PetscBool SlepcInitializeCalled PetscBool SlepcFinalizeCalled PetscErrorCode SlepcHasExternalPackage(const char[],PetscBool*) cdef inline PetscMatStructure matstructure(object structure) \ except (-1): if structure is None: return MAT_DIFFERENT_NONZERO_PATTERN elif structure is False: return MAT_DIFFERENT_NONZERO_PATTERN elif structure is True: return MAT_SAME_NONZERO_PATTERN else: return structure cdef inline PetscErrorCode PetscINCREF(PetscObject *obj): if obj == NULL: return PETSC_SUCCESS if obj[0] == NULL: return PETSC_SUCCESS return PetscObjectReference(obj[0]) cdef inline PetscErrorCode SlepcCLEAR(PetscObject* obj): if obj == NULL: return PETSC_SUCCESS if obj[0] == NULL: return PETSC_SUCCESS cdef PetscObject tmp tmp = obj[0]; obj[0] = NULL return PetscObjectDestroy(&tmp) cdef inline PetscViewer def_Viewer(Viewer viewer): return viewer.vwr if viewer is not None else NULL cdef inline KSP ref_KSP(PetscKSP ksp): cdef KSP ob = KSP() ob.ksp = ksp CHKERR( PetscINCREF(ob.obj) ) return ob cdef inline Mat ref_Mat(PetscMat mat): cdef Mat ob = Mat() ob.mat = mat CHKERR( PetscINCREF(ob.obj) ) return ob cdef inline Vec ref_Vec(PetscVec vec): cdef Vec ob = Vec() ob.vec = vec CHKERR( PetscINCREF(ob.obj) ) return ob ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/slepcutil.pxi0000644000076500000240000000024615133663436020560 0ustar00jromanstaffcdef extern from * nogil: PetscErrorCode MatCreateBSE(PetscMat,PetscMat,PetscMat*) PetscErrorCode MatCreateHamiltonian(PetscMat,PetscMat,PetscMat,PetscMat*) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc/typing.pxi0000644000076500000240000000117215133663436020065 0ustar00jromanstaffcdef Callable cdef Sequence cdef Literal cdef NDArray, cdef Vec cdef Mat cdef KSP cdef BV cdef DS cdef FN cdef RG cdef ST cdef EPS cdef PEP cdef NEP cdef SVD cdef MFN cdef LME cdef Scalar cdef ArrayInt cdef ArrayReal cdef ArrayComplex cdef ArrayScalar cdef LayoutSizeSpec cdef EPSStoppingFunction cdef EPSArbitraryFunction cdef EPSEigenvalueComparison cdef EPSMonitorFunction cdef PEPStoppingFunction cdef PEPEigenvalueComparison cdef PEPMonitorFunction cdef NEPStoppingFunction cdef NEPEigenvalueComparison cdef NEPMonitorFunction cdef SVDStoppingFunction cdef SVDMonitorFunction cdef MFNMonitorFunction cdef LMEMonitorFunction ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc.pxd0000644000076500000240000000433015133663436016545 0ustar00jromanstaff# ----------------------------------------------------------------------------- cdef extern from "": struct _p_ST ctypedef _p_ST* SlepcST "ST" struct _p_BV ctypedef _p_BV* SlepcBV "BV" struct _p_DS ctypedef _p_DS* SlepcDS "DS" struct _p_FN ctypedef _p_FN* SlepcFN "FN" struct _p_RG ctypedef _p_RG* SlepcRG "RG" struct _p_EPS ctypedef _p_EPS* SlepcEPS "EPS" struct _p_SVD ctypedef _p_SVD* SlepcSVD "SVD" struct _p_PEP ctypedef _p_PEP* SlepcPEP "PEP" struct _p_NEP ctypedef _p_NEP* SlepcNEP "NEP" struct _p_MFN ctypedef _p_MFN* SlepcMFN "MFN" struct _p_LME ctypedef _p_LME* SlepcLME "LME" # ----------------------------------------------------------------------------- from petsc4py.PETSc cimport Object ctypedef public api class ST(Object) [ type PySlepcST_Type, object PySlepcSTObject, ]: cdef SlepcST st ctypedef public api class BV(Object) [ type PySlepcBV_Type, object PySlepcBVObject, ]: cdef SlepcBV bv ctypedef public api class DS(Object) [ type PySlepcDS_Type, object PySlepcDSObject, ]: cdef SlepcDS ds ctypedef public api class FN(Object) [ type PySlepcFN_Type, object PySlepcFNObject, ]: cdef SlepcFN fn ctypedef public api class RG(Object) [ type PySlepcRG_Type, object PySlepcRGObject, ]: cdef SlepcRG rg ctypedef public api class EPS(Object) [ type PySlepcEPS_Type, object PySlepcEPSObject, ]: cdef SlepcEPS eps ctypedef public api class SVD(Object) [ type PySlepcSVD_Type, object PySlepcSVDObject, ]: cdef SlepcSVD svd ctypedef public api class PEP(Object) [ type PySlepcPEP_Type, object PySlepcPEPObject, ]: cdef SlepcPEP pep ctypedef public api class NEP(Object) [ type PySlepcNEP_Type, object PySlepcNEPObject, ]: cdef SlepcNEP nep ctypedef public api class MFN(Object) [ type PySlepcMFN_Type, object PySlepcMFNObject, ]: cdef SlepcMFN mfn ctypedef public api class LME(Object) [ type PySlepcLME_Type, object PySlepcLMEObject, ]: cdef SlepcLME lme # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc.py0000644000076500000240000000040515133663436016401 0ustar00jromanstaffARCH = None from slepc4py.lib import ImportSLEPc # noqa: E402 from slepc4py.lib import ImportPETSc # noqa: E402 SLEPc = ImportSLEPc(ARCH) PETSc = ImportPETSc(ARCH) PETSc._initialize() SLEPc._initialize() del SLEPc, PETSc del ImportSLEPc, ImportPETSc del ARCH ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/SLEPc.pyx0000644000076500000240000000072115133663436016572 0ustar00jromanstaff#cython: language_level=3str #cython: embedsignature=True #cython: embedsignature.format=python #cython: annotation_typing=False #cython: cdivision=True #cython: auto_pickle=False #cython: always_allow_keywords=True #cython: allow_none_for_extension_args=False #cython: autotestdict=False #cython: warn.multiple_declarators=False #cython: optimize.use_switch=False #cython: binding=True from __future__ import annotations cimport cython include "SLEPc/SLEPc.pyx" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/__init__.pxd0000644000076500000240000000000015133663436017364 0ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908575.0 slepc4py-3.24.2/src/slepc4py/__init__.py0000644000076500000240000000545415133663437017244 0ustar00jromanstaff# ----------------------------------------------------------------------------- """ SLEPc for Python ================ This package is an interface to SLEPc_ libraries. SLEPc_ (the Scalable Library for Eigenvalue Problem Computations) is a software library for the solution of large scale sparse eigenvalue problems on parallel computers. It is an extension of PETSc_ and can be used for either standard or generalized eigenproblems, with real or complex arithmetic. It can also be used for computing a partial SVD of a large, sparse, rectangular matrix, and to solve nonlinear eigenvalue problems (polynomial or general). Additionally, SLEPc provides solvers for the computation of the action of a matrix function on a vector. .. _SLEPc: https://slepc.upv.es .. _PETSc: https://petsc.org """ __author__ = 'Lisandro Dalcin' __version__ = '3.24.2' __credits__ = 'SLEPc Team ' # ----------------------------------------------------------------------------- def init(args=None, arch=None, comm=None): """ Initialize SLEPc. Parameters ---------- args Command-line arguments, usually the `sys.argv` list. arch Specific configuration to use. comm MPI commmunicator. Notes ----- This function should be called only once, typically at the very beginning of the bootstrap script of an application. """ import slepc4py.lib SLEPc = slepc4py.lib.ImportSLEPc(arch) PETSc = slepc4py.lib.ImportPETSc(arch) args = slepc4py.lib.getInitArgs(args) PETSc._initialize(args, comm) SLEPc._initialize(args) # ----------------------------------------------------------------------------- def get_include(): """ Return the directory in the package that contains header files. Extension modules that need to compile against slepc4py should use this function to locate the appropriate include directory. Example ------- Using Python distutils or NumPy distutils:: import petscc4py, slepc4py Extension('extension_name', ... include_dirs=[..., petsc4py.get_include(), slepc4py.get_include(),]) """ from os.path import dirname, join return join(dirname(__file__), 'include') # ----------------------------------------------------------------------------- def get_config(): """Return a dictionary with information about SLEPc.""" import os from io import StringIO from configparser import ConfigParser pgkdir = os.path.dirname(__file__) filename = os.path.join(pgkdir, 'lib', 'slepc.cfg') with open(filename) as fp: stream = StringIO('[slepc]\n' + fp.read()) parser = ConfigParser() parser.optionxform = str parser.read_file(stream, filename) return dict(parser.items('slepc')) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/__init__.pyi0000644000076500000240000000041615133663436017405 0ustar00jromanstafffrom typing import Union from mpi4py.MPI import Intracomm __version__: str = ... def init(args: Union[str, list[str]] | None = ..., arch: str | None = ..., comm: Intracomm | None = ...) -> None: ... def get_include() -> str: ... def get_config() -> dict[str, str]: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/__main__.py0000644000076500000240000000445315133663436017222 0ustar00jromanstaff""" Command line access to the SLEPc Options Database. This module provides command line access to SLEPc Options Database. It outputs a listing of the many SLEPc options indicating option names, default values and descriptions. Usage:: $ python -m slepc4py [eps|svd|pep|nep|mfn|st|bv|rg|fn|ds] [] """ def help(args=None): import sys # program name try: prog = sys.argv[0] except Exception: prog = getattr(sys, 'executable', 'python') # arguments if args is None: args = sys.argv[1:] elif isinstance(args, str): args = args.split() else: args = [str(a) for a in args] if '-help' not in args: args.append('-help') # initialization import slepc4py slepc4py.init([prog] + args) from slepc4py import SLEPc # and finally ... COMM = SLEPc.COMM_SELF if 'eps' in args: eps = SLEPc.EPS().create(comm=COMM) eps.setFromOptions() eps.destroy() del eps if 'svd' in args: svd = SLEPc.SVD().create(comm=COMM) svd.setFromOptions() svd.destroy() del svd if 'pep' in args: pep = SLEPc.PEP().create(comm=COMM) pep.setFromOptions() pep.destroy() del pep if 'nep' in args: nep = SLEPc.NEP().create(comm=COMM) nep.setFromOptions() nep.destroy() del nep if 'mfn' in args: mfn = SLEPc.MFN().create(comm=COMM) mfn.setFromOptions() mfn.destroy() del mfn if 'lme' in args: lme = SLEPc.LME().create(comm=COMM) lme.setFromOptions() lme.destroy() del lme if 'st' in args: st = SLEPc.ST().create(comm=COMM) st.setFromOptions() st.destroy() del st if 'bv' in args: bv = SLEPc.BV().create(comm=COMM) bv.setFromOptions() bv.destroy() del bv if 'rg' in args: rg = SLEPc.RG().create(comm=COMM) rg.setFromOptions() rg.destroy() del rg if 'fn' in args: fn = SLEPc.FN().create(comm=COMM) fn.setFromOptions() fn.destroy() del fn if 'ds' in args: ds = SLEPc.DS().create(comm=COMM) ds.setFromOptions() ds.destroy() del ds if __name__ == '__main__': help() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.4676821 slepc4py-3.24.2/src/slepc4py/include/0000755000076500000240000000000015133664270016542 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1768908984.568874 slepc4py-3.24.2/src/slepc4py/include/slepc4py/0000755000076500000240000000000015133664271020306 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/include/slepc4py/slepc4py.h0000644000076500000240000000037115133663436022225 0ustar00jromanstaff#ifndef SLEPC4PY_H #define SLEPC4PY_H #include #include #include "../../SLEPc_api.h" static int import_slepc4py(void) { if (import_slepc4py__SLEPc() < 0) goto bad; return 0; bad: return -1; } #endif /* !SLEPC4PY_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/include/slepc4py/slepc4py.i0000644000076500000240000000305615133663436022231 0ustar00jromanstaff/* ---------------------------------------------------------------- */ %include petsc4py/petsc4py.i /* ---------------------------------------------------------------- */ %header %{#include "slepc4py/slepc4py.h"%} %init %{import_slepc4py();%} %define SWIG_TYPECHECK_SLEPC_ST 650 %enddef %define SWIG_TYPECHECK_SLEPC_BV 651 %enddef %define SWIG_TYPECHECK_SLEPC_DS 652 %enddef %define SWIG_TYPECHECK_SLEPC_FN 653 %enddef %define SWIG_TYPECHECK_SLEPC_RG 654 %enddef %define SWIG_TYPECHECK_SLEPC_EPS 655 %enddef %define SWIG_TYPECHECK_SLEPC_SVD 656 %enddef %define SWIG_TYPECHECK_SLEPC_PEP 657 %enddef %define SWIG_TYPECHECK_SLEPC_NEP 658 %enddef %define SWIG_TYPECHECK_SLEPC_MFN 659 %enddef %define SWIG_TYPECHECK_SLEPC_LME 660 %enddef %define %slepc4py_objt(Pkg, PyType, Type, CODE) %petsc4py_objt(Pkg, PyType, Type, CODE) %enddef /* %slepc4py_objt */ /* ---------------------------------------------------------------- */ %slepc4py_objt( Slepc , ST , ST , SLEPC_ST ) %slepc4py_objt( Slepc , BV , BV , SLEPC_BV ) %slepc4py_objt( Slepc , DS , DS , SLEPC_DS ) %slepc4py_objt( Slepc , FN , FN , SLEPC_FN ) %slepc4py_objt( Slepc , RG , RG , SLEPC_RG ) %slepc4py_objt( Slepc , EPS , EPS , SLEPC_EPS ) %slepc4py_objt( Slepc , SVD , SVD , SLEPC_SVD ) %slepc4py_objt( Slepc , PEP , PEP , SLEPC_PEP ) %slepc4py_objt( Slepc , NEP , NEP , SLEPC_NEP ) %slepc4py_objt( Slepc , MFN , MFN , SLEPC_MFN ) %slepc4py_objt( Slepc , LME , LME , SLEPC_LME ) /* ---------------------------------------------------------------- */ /* * Local Variables: * mode: C * End: */ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5703828 slepc4py-3.24.2/src/slepc4py/lib/0000755000076500000240000000000015133664271015666 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/lib/__init__.py0000644000076500000240000000320515133663436020001 0ustar00jromanstaff# ----------------------------------------------------------------------------- """ Extension modules for different SLEPc configurations. SLEPc can be configured with different options (eg. debug/optimized, single/double precisionm, C/C++ compilers, external packages). Each configuration variant is associated to a name, frequently available as an environmental variable named ``PETSC_ARCH``. This package is a holds all the available variants of the SLEPc extension module built against specific SLEPc configurations. It also provides a convenience function using of the builtin ``imp`` module for easily importing any of the available extension modules depending on the value of a user-provided configuration name, the ``PETSC_ARCH`` environmental variable, or a configuration file. """ # ----------------------------------------------------------------------------- from petsc4py.lib import ImportPETSc from petsc4py.lib import Import, getPathArch, getInitArgs # noqa: F401 def ImportSLEPc(arch=None): """ Import the SLEPc extension module for a given configuration name. """ path, arch = getPathArchSLEPc(arch) PETSc = ImportPETSc(arch) # noqa: F841 return Import('slepc4py', 'SLEPc', path, arch) def getPathArchSLEPc(arch=None): """ Undocumented. """ import os import sys PETSc = sys.modules.get('petsc4py.PETSc') arch = getattr(PETSc, '__arch__', arch) path = os.path.dirname(__file__) rcvar, rcfile = 'PETSC_ARCH', 'slepc.cfg' path, arch = getPathArch(path, arch, rcvar, rcfile) return (path, arch) # ----------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/lib/__init__.pyi0000644000076500000240000000061515133663436020154 0ustar00jromanstafffrom types import ModuleType def ImportSLEPc(arch: str | None = ...) -> ModuleType: ... def getPathArchSLEPc(arch: str | None = ...) -> tuple[str, str]: ... def Import(pkg: str, name: str, path: str, arch: str) -> ModuleType: ... def getPathArch(path: str, arch: str, rcvar: str = ..., rcfile: str = ...) -> tuple[str, str]: ... def getInitArgs(args: str | list[str] | None) -> list[str]: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/lib/slepc.cfg0000644000076500000240000000012215133663436017452 0ustar00jromanstaffSLEPC_DIR = %(SLEPC_DIR)s PETSC_DIR = %(PETSC_DIR)s PETSC_ARCH = %(PETSC_ARCH)s ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/src/slepc4py/typing.py0000644000076500000240000000717015133663436017013 0ustar00jromanstaff"""Typing support.""" from __future__ import annotations # novermin from typing import ( # novermin Callable, Sequence, Literal, ) from numpy.typing import ( NDArray, ) from petsc4py.PETSc import ( Vec, Mat, KSP, ) from .SLEPc import ( BV, DS, FN, RG, ST, EPS, PEP, NEP, SVD, MFN, LME, ) __all__ = [ 'Scalar', 'ArrayInt', 'ArrayReal', 'ArrayComplex', 'ArrayScalar', 'LayoutSizeSpec', 'EPSStoppingFunction', 'EPSArbitraryFunction', 'EPSEigenvalueComparison', 'EPSMonitorFunction', 'PEPStoppingFunction', 'PEPEigenvalueComparison', 'PEPMonitorFunction', 'NEPStoppingFunction', 'NEPEigenvalueComparison', 'NEPMonitorFunction', 'SVDStoppingFunction', 'SVDMonitorFunction', 'MFNMonitorFunction', 'LMEMonitorFunction', ] # --- PETSc Sys --- Scalar = float | complex """Scalar type. Scalars can be either `float` or `complex` (but not both) depending on how PETSc was configured (``./configure --with-scalar-type=real|complex``). """ ArrayInt = NDArray[int] """Array of `int`.""" ArrayReal = NDArray[float] """Array of `float`.""" ArrayComplex = NDArray[complex] """Array of `complex`.""" ArrayScalar = NDArray[Scalar] """Array of `Scalar` numbers.""" LayoutSizeSpec = int | tuple[int, int] """`int` or 2-`tuple` of `int` describing the layout sizes. A single `int` indicates global size. A `tuple` of `int` indicates ``(local_size, global_size)``. """ # --- EPS --- EPSStoppingFunction = Callable[[EPS, int, int, int, int], EPS.ConvergedReason] """`EPS` stopping test callback.""" EPSArbitraryFunction = Callable[[Scalar, Scalar, Vec, Vec, Scalar, Scalar], [Scalar, Scalar]] """`EPS` arbitrary selection callback.""" EPSEigenvalueComparison = Callable[[Scalar, Scalar, Scalar, Scalar], int] """`EPS` eigenvalue comparison callback.""" EPSMonitorFunction = Callable[[EPS, int, int, ArrayScalar, ArrayScalar, ArrayReal, int], None] """`EPS` monitor callback.""" # --- PEP --- PEPStoppingFunction = Callable[[PEP, int, int, int, int], PEP.ConvergedReason] """:py:class:`PEP ` stopping test callback.""" PEPEigenvalueComparison = Callable[[Scalar, Scalar, Scalar, Scalar], int] """:py:class:`PEP ` eigenvalue comparison callback.""" PEPMonitorFunction = Callable[[PEP, int, int, ArrayScalar, ArrayScalar, ArrayReal, int], None] """:py:class:`PEP ` monitor callback.""" # --- NEP --- NEPStoppingFunction = Callable[[NEP, int, int, int, int], NEP.ConvergedReason] """:py:class:`NEP ` stopping test callback.""" NEPEigenvalueComparison = Callable[[Scalar, Scalar, Scalar, Scalar], int] """:py:class:`NEP ` eigenvalue comparison callback.""" NEPMonitorFunction = Callable[[NEP, int, int, ArrayScalar, ArrayScalar, ArrayReal, int], None] """:py:class:`NEP ` monitor callback.""" NEPFunction = Callable[[NEP, Scalar, Mat, Mat], None] """:py:class:`NEP ` Function callback.""" NEPJacobian = Callable[[NEP, Scalar, Mat], None] """:py:class:`NEP ` Jacobian callback.""" # --- SVD --- SVDStoppingFunction = Callable[[SVD, int, int, int, int], SVD.ConvergedReason] """:py:class:`SVD ` stopping test callback.""" SVDMonitorFunction = Callable[[SVD, int, int, ArrayReal, ArrayReal, int], None] """:py:class:`SVD ` monitor callback.""" # --- MFN --- MFNMonitorFunction = Callable[[MFN, int, float], None] """`MFN` monitor callback.""" # --- LME --- LMEMonitorFunction = Callable[[LME, int, float], None] """`LME` monitor callback.""" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5720298 slepc4py-3.24.2/src/slepc4py.egg-info/0000755000076500000240000000000015133664271016612 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908984.0 slepc4py-3.24.2/src/slepc4py.egg-info/PKG-INFO0000644000076500000240000000476515133664270017722 0ustar00jromanstaffMetadata-Version: 2.4 Name: slepc4py Version: 3.24.2 Summary: SLEPc for Python Home-page: https://gitlab.com/slepc/slepc Download-URL: https://pypi.io/packages/source/s/slepc4py/slepc4py-3.24.2.tar.gz Author: Lisandro Dalcin Author-email: dalcinl@gmail.com Maintainer: SLEPc Team Maintainer-email: slepc-maint@upv.es License: BSD-2-Clause Keywords: scientific computing,parallel computing,MPI,SLEPc,PETSc Platform: POSIX Platform: Linux Platform: macOS Platform: FreeBSD Classifier: Operating System :: POSIX Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: Programming Language :: C Classifier: Programming Language :: C++ Classifier: Programming Language :: Cython Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Scientific/Engineering Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Development Status :: 5 - Production/Stable Requires: numpy Description-Content-Type: text/x-rst License-File: LICENSE.rst Requires-Dist: numpy Requires-Dist: petsc4py<3.25,>=3.24 Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: description-content-type Dynamic: download-url Dynamic: home-page Dynamic: keywords Dynamic: license Dynamic: license-file Dynamic: maintainer Dynamic: maintainer-email Dynamic: platform Dynamic: requires Dynamic: requires-dist Dynamic: summary SLEPc for Python ================ Python bindings for SLEPc_. .. _SLEPc: https://slepc.upv.es Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py slepc slepc4py Citations --------- If SLEPc for Python has been significant to a project that leads to an academic publication, please acknowledge that fact by citing the project. * L. Dalcin, P. Kler, R. Paz, and A. Cosimo, *Parallel Distributed Computing using Python*, Advances in Water Resources, 34(9):1124-1139, 2011. https://doi.org/10.1016/j.advwatres.2011.04.013 * V. Hernandez, J.E. Roman and V. Vidal. *SLEPc: A Scalable and Flexible Toolkit for the Solution of Eigenvalue Problems*, ACM Transactions on Mathematical Software, 31(3):351-362, 2005. https://doi.org/10.1145/1089014.1089019 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908984.0 slepc4py-3.24.2/src/slepc4py.egg-info/SOURCES.txt0000644000076500000240000002213715133664270020502 0ustar00jromanstaffCHANGES.rst DESCRIPTION.rst LICENSE.rst MANIFEST.in README.rst pyproject.toml setup.cfg setup.py conf/__init__.py conf/confpetsc.py conf/confslepc.py conf/cyautodoc.py conf/cythonize.py conf/cythonize.sh demo/ex1.py demo/ex10.py demo/ex11.py demo/ex12.py demo/ex13.py demo/ex14.py demo/ex2.py demo/ex3.py demo/ex4.py demo/ex5.py demo/ex6.py demo/ex7.py demo/ex8.py demo/ex9.py demo/makefile docs/source/Makefile docs/source/apidoc.py docs/source/changes.rst docs/source/citing.rst docs/source/conf.py docs/source/index.rst docs/source/install.rst docs/source/links.txt docs/source/overview.rst docs/source/reference.rst docs/source/tutorial.rst docs/source/_templates/layout.html docs/source/_templates/autosummary/class.rst docs/source/_templates/autosummary/module.rst docs/source/demo/demo.rst docs/source/demo/ex1.py docs/source/demo/ex1.rst docs/source/demo/ex10.py docs/source/demo/ex10.rst docs/source/demo/ex11.py docs/source/demo/ex11.rst docs/source/demo/ex12.py docs/source/demo/ex12.rst docs/source/demo/ex13.py docs/source/demo/ex13.rst docs/source/demo/ex14.py docs/source/demo/ex14.rst docs/source/demo/ex2.py docs/source/demo/ex2.rst docs/source/demo/ex3.py docs/source/demo/ex3.rst docs/source/demo/ex4.py docs/source/demo/ex4.rst docs/source/demo/ex5.py docs/source/demo/ex5.rst docs/source/demo/ex6.py docs/source/demo/ex6.rst docs/source/demo/ex7.py docs/source/demo/ex7.rst docs/source/demo/ex8.py docs/source/demo/ex8.rst docs/source/demo/ex9.py docs/source/demo/ex9.rst docs/source/reference/slepc4py.SLEPc.BV.MatMultType.rst docs/source/reference/slepc4py.SLEPc.BV.OrthogBlockType.rst docs/source/reference/slepc4py.SLEPc.BV.OrthogRefineType.rst docs/source/reference/slepc4py.SLEPc.BV.OrthogType.rst docs/source/reference/slepc4py.SLEPc.BV.SVDMethod.rst docs/source/reference/slepc4py.SLEPc.BV.Type.rst docs/source/reference/slepc4py.SLEPc.BV.rst docs/source/reference/slepc4py.SLEPc.CURRENT.rst docs/source/reference/slepc4py.SLEPc.DECIDE.rst docs/source/reference/slepc4py.SLEPc.DEFAULT.rst docs/source/reference/slepc4py.SLEPc.DETERMINE.rst docs/source/reference/slepc4py.SLEPc.DS.MatType.rst docs/source/reference/slepc4py.SLEPc.DS.ParallelType.rst docs/source/reference/slepc4py.SLEPc.DS.StateType.rst docs/source/reference/slepc4py.SLEPc.DS.Type.rst docs/source/reference/slepc4py.SLEPc.DS.rst docs/source/reference/slepc4py.SLEPc.EPS.Balance.rst docs/source/reference/slepc4py.SLEPc.EPS.CISSExtraction.rst docs/source/reference/slepc4py.SLEPc.EPS.CISSQuadRule.rst docs/source/reference/slepc4py.SLEPc.EPS.Conv.rst docs/source/reference/slepc4py.SLEPc.EPS.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.EPS.ErrorType.rst docs/source/reference/slepc4py.SLEPc.EPS.Extraction.rst docs/source/reference/slepc4py.SLEPc.EPS.KrylovSchurBSEType.rst docs/source/reference/slepc4py.SLEPc.EPS.LanczosReorthogType.rst docs/source/reference/slepc4py.SLEPc.EPS.PowerShiftType.rst docs/source/reference/slepc4py.SLEPc.EPS.ProblemType.rst docs/source/reference/slepc4py.SLEPc.EPS.Stop.rst docs/source/reference/slepc4py.SLEPc.EPS.Type.rst docs/source/reference/slepc4py.SLEPc.EPS.Which.rst docs/source/reference/slepc4py.SLEPc.EPS.rst docs/source/reference/slepc4py.SLEPc.FN.CombineType.rst docs/source/reference/slepc4py.SLEPc.FN.ParallelType.rst docs/source/reference/slepc4py.SLEPc.FN.Type.rst docs/source/reference/slepc4py.SLEPc.FN.rst docs/source/reference/slepc4py.SLEPc.LME.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.LME.ProblemType.rst docs/source/reference/slepc4py.SLEPc.LME.Type.rst docs/source/reference/slepc4py.SLEPc.LME.rst docs/source/reference/slepc4py.SLEPc.MFN.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.MFN.Type.rst docs/source/reference/slepc4py.SLEPc.MFN.rst docs/source/reference/slepc4py.SLEPc.NEP.CISSExtraction.rst docs/source/reference/slepc4py.SLEPc.NEP.Conv.rst docs/source/reference/slepc4py.SLEPc.NEP.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.NEP.ErrorType.rst docs/source/reference/slepc4py.SLEPc.NEP.ProblemType.rst docs/source/reference/slepc4py.SLEPc.NEP.Refine.rst docs/source/reference/slepc4py.SLEPc.NEP.RefineScheme.rst docs/source/reference/slepc4py.SLEPc.NEP.Stop.rst docs/source/reference/slepc4py.SLEPc.NEP.Type.rst docs/source/reference/slepc4py.SLEPc.NEP.Which.rst docs/source/reference/slepc4py.SLEPc.NEP.rst docs/source/reference/slepc4py.SLEPc.PEP.Basis.rst docs/source/reference/slepc4py.SLEPc.PEP.CISSExtraction.rst docs/source/reference/slepc4py.SLEPc.PEP.Conv.rst docs/source/reference/slepc4py.SLEPc.PEP.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.PEP.ErrorType.rst docs/source/reference/slepc4py.SLEPc.PEP.Extract.rst docs/source/reference/slepc4py.SLEPc.PEP.JDProjection.rst docs/source/reference/slepc4py.SLEPc.PEP.ProblemType.rst docs/source/reference/slepc4py.SLEPc.PEP.Refine.rst docs/source/reference/slepc4py.SLEPc.PEP.RefineScheme.rst docs/source/reference/slepc4py.SLEPc.PEP.Scale.rst docs/source/reference/slepc4py.SLEPc.PEP.Stop.rst docs/source/reference/slepc4py.SLEPc.PEP.Type.rst docs/source/reference/slepc4py.SLEPc.PEP.Which.rst docs/source/reference/slepc4py.SLEPc.PEP.rst docs/source/reference/slepc4py.SLEPc.RG.QuadRule.rst docs/source/reference/slepc4py.SLEPc.RG.Type.rst docs/source/reference/slepc4py.SLEPc.RG.rst docs/source/reference/slepc4py.SLEPc.ST.FilterDamping.rst docs/source/reference/slepc4py.SLEPc.ST.FilterType.rst docs/source/reference/slepc4py.SLEPc.ST.MatMode.rst docs/source/reference/slepc4py.SLEPc.ST.Type.rst docs/source/reference/slepc4py.SLEPc.ST.rst docs/source/reference/slepc4py.SLEPc.SVD.Conv.rst docs/source/reference/slepc4py.SLEPc.SVD.ConvergedReason.rst docs/source/reference/slepc4py.SLEPc.SVD.ErrorType.rst docs/source/reference/slepc4py.SLEPc.SVD.ProblemType.rst docs/source/reference/slepc4py.SLEPc.SVD.Stop.rst docs/source/reference/slepc4py.SLEPc.SVD.TRLanczosGBidiag.rst docs/source/reference/slepc4py.SLEPc.SVD.Type.rst docs/source/reference/slepc4py.SLEPc.SVD.Which.rst docs/source/reference/slepc4py.SLEPc.SVD.rst docs/source/reference/slepc4py.SLEPc.Sys.rst docs/source/reference/slepc4py.SLEPc.Util.rst docs/source/reference/slepc4py.SLEPc.py docs/source/reference/slepc4py.SLEPc.rst docs/source/reference/slepc4py.get_config.rst docs/source/reference/slepc4py.get_include.rst docs/source/reference/slepc4py.init.rst docs/source/reference/slepc4py.rst docs/source/reference/slepc4py.typing.ArrayComplex.rst docs/source/reference/slepc4py.typing.ArrayInt.rst docs/source/reference/slepc4py.typing.ArrayReal.rst docs/source/reference/slepc4py.typing.ArrayScalar.rst docs/source/reference/slepc4py.typing.EPSArbitraryFunction.rst docs/source/reference/slepc4py.typing.EPSEigenvalueComparison.rst docs/source/reference/slepc4py.typing.EPSMonitorFunction.rst docs/source/reference/slepc4py.typing.EPSStoppingFunction.rst docs/source/reference/slepc4py.typing.LMEMonitorFunction.rst docs/source/reference/slepc4py.typing.LayoutSizeSpec.rst docs/source/reference/slepc4py.typing.MFNMonitorFunction.rst docs/source/reference/slepc4py.typing.NEPEigenvalueComparison.rst docs/source/reference/slepc4py.typing.NEPFunction.rst docs/source/reference/slepc4py.typing.NEPJacobian.rst docs/source/reference/slepc4py.typing.NEPMonitorFunction.rst docs/source/reference/slepc4py.typing.NEPStoppingFunction.rst docs/source/reference/slepc4py.typing.PEPEigenvalueComparison.rst docs/source/reference/slepc4py.typing.PEPMonitorFunction.rst docs/source/reference/slepc4py.typing.PEPStoppingFunction.rst docs/source/reference/slepc4py.typing.SVDMonitorFunction.rst docs/source/reference/slepc4py.typing.SVDStoppingFunction.rst docs/source/reference/slepc4py.typing.Scalar.rst docs/source/reference/slepc4py.typing.rst src/pyapicompat.h src/lib-slepc/compat.h src/lib-slepc/custom.h src/slepc4py/SLEPc.pxd src/slepc4py/SLEPc.py src/slepc4py/SLEPc.pyx src/slepc4py/__init__.pxd src/slepc4py/__init__.py src/slepc4py/__init__.pyi src/slepc4py/__main__.py src/slepc4py/typing.py src/slepc4py.egg-info/PKG-INFO src/slepc4py.egg-info/SOURCES.txt src/slepc4py.egg-info/dependency_links.txt src/slepc4py.egg-info/not-zip-safe src/slepc4py.egg-info/requires.txt src/slepc4py.egg-info/top_level.txt src/slepc4py/SLEPc/BV.pyx src/slepc4py/SLEPc/CAPI.pyx src/slepc4py/SLEPc/DS.pyx src/slepc4py/SLEPc/EPS.pyx src/slepc4py/SLEPc/FN.pyx src/slepc4py/SLEPc/LME.pyx src/slepc4py/SLEPc/MFN.pyx src/slepc4py/SLEPc/NEP.pyx src/slepc4py/SLEPc/PEP.pyx src/slepc4py/SLEPc/RG.pyx src/slepc4py/SLEPc/SLEPc.pyx src/slepc4py/SLEPc/ST.pyx src/slepc4py/SLEPc/SVD.pyx src/slepc4py/SLEPc/Sys.pyx src/slepc4py/SLEPc/Util.pyx src/slepc4py/SLEPc/allocate.pxi src/slepc4py/SLEPc/arraynpy.pxi src/slepc4py/SLEPc/slepcbv.pxi src/slepc4py/SLEPc/slepcds.pxi src/slepc4py/SLEPc/slepceps.pxi src/slepc4py/SLEPc/slepcfn.pxi src/slepc4py/SLEPc/slepclme.pxi src/slepc4py/SLEPc/slepcmfn.pxi src/slepc4py/SLEPc/slepcmpi.pxi src/slepc4py/SLEPc/slepcnep.pxi src/slepc4py/SLEPc/slepcpep.pxi src/slepc4py/SLEPc/slepcrg.pxi src/slepc4py/SLEPc/slepcst.pxi src/slepc4py/SLEPc/slepcsvd.pxi src/slepc4py/SLEPc/slepcsys.pxi src/slepc4py/SLEPc/slepcutil.pxi src/slepc4py/SLEPc/typing.pxi src/slepc4py/include/slepc4py/slepc4py.h src/slepc4py/include/slepc4py/slepc4py.i src/slepc4py/lib/__init__.py src/slepc4py/lib/__init__.pyi src/slepc4py/lib/slepc.cfg test/runtests.py test/test_object.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908984.0 slepc4py-3.24.2/src/slepc4py.egg-info/dependency_links.txt0000644000076500000240000000000115133664270022657 0ustar00jromanstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908759.0 slepc4py-3.24.2/src/slepc4py.egg-info/not-zip-safe0000644000076500000240000000000115133663727021045 0ustar00jromanstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908984.0 slepc4py-3.24.2/src/slepc4py.egg-info/requires.txt0000644000076500000240000000003315133664270021205 0ustar00jromanstaffnumpy petsc4py<3.25,>=3.24 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908984.0 slepc4py-3.24.2/src/slepc4py.egg-info/top_level.txt0000644000076500000240000000001115133664270021333 0ustar00jromanstaffslepc4py ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768908984.5713956 slepc4py-3.24.2/test/0000755000076500000240000000000015133664271013545 5ustar00jromanstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/test/runtests.py0000644000076500000240000001675215133663436016023 0ustar00jromanstaffimport os import sys import optparse import unittest __unittest = True components = [ 'PETSc', 'SLEPc', ] def getoptionparser(): parser = optparse.OptionParser() parser.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", default=1, help="do not print status messages to stdout") parser.add_option("-v", "--verbose", action="store_const", const=2, dest="verbose", default=1, help="print status messages to stdout") parser.add_option("-i", "--include", type="string", action="append", dest="include", default=[], help="include tests matching PATTERN", metavar="PATTERN") parser.add_option("-e", "--exclude", type="string", action="append", dest="exclude", default=[], help="exclude tests matching PATTERN", metavar="PATTERN") parser.add_option("-k", "--pattern", type="string", action="append", dest="patterns", default=[], help="only run tests which match the given substring") parser.add_option("-f", "--failfast", action="store_true", dest="failfast", default=False, help="Stop on first failure") parser.add_option("--no-builddir", action="store_false", dest="builddir", default=True, help="disable testing from build directory") parser.add_option("--path", type="string", action="append", dest="path", default=[], help="prepend PATH to sys.path", metavar="PATH") parser.add_option("--arch", type="string", action="store", dest="arch", default=None, help="use PETSC_ARCH", metavar="PETSC_ARCH") parser.add_option("-s","--summary", action="store_true", dest="summary", default=0, help="print PETSc log summary") parser.add_option("--no-memdebug", action="store_false", dest="memdebug", default=True, help="Do not use PETSc memory debugging") return parser def getbuilddir(): try: try: from setuptools.dist import Distribution except ImportError: from distutils.dist import Distribution try: from setuptools.command.build import build except ImportError: from distutils.command.build import build cmd_obj = build(Distribution()) cmd_obj.finalize_options() return cmd_obj.build_platlib except Exception: return None def getprocessorinfo(): try: name = os.uname()[1] except: import platform name = platform.uname()[1] from petsc4py.PETSc import COMM_WORLD rank = COMM_WORLD.getRank() return (rank, name) def getlibraryinfo(name): modname = "%s4py.%s" % (name.lower(), name) module = __import__(modname, fromlist=[name]) (major, minor, micro), devel = module.Sys.getVersion(devel=True) r = not devel if r: release = 'release' else: release = 'development' arch = module.__arch__ return ( "%s %d.%d.%d %s (conf: '%s')" % (name, major, minor, micro, release, arch) ) def getpythoninfo(): x, y, z = sys.version_info[:3] return ("Python %d.%d.%d (%s)" % (x, y, z, sys.executable)) def getpackageinfo(pkg): try: pkg = __import__(pkg) except ImportError: return None name = pkg.__name__ version = pkg.__version__ path = pkg.__path__[0] return ("%s %s (%s)" % (name, version, path)) def setup_python(options): rootdir = os.path.dirname(os.path.dirname(__file__)) builddir = os.path.join(rootdir, getbuilddir()) if options.builddir and os.path.exists(builddir): sys.path.insert(0, builddir) if options.path: path = options.path[:] path.reverse() for p in path: sys.path.insert(0, p) def setup_unittest(options): from unittest import TestSuite try: from unittest.runner import _WritelnDecorator except ImportError: from unittest import _WritelnDecorator # writeln_orig = _WritelnDecorator.writeln def writeln(self, message=''): try: self.stream.flush() except: pass writeln_orig(self, message) try: self.stream.flush() except: pass _WritelnDecorator.writeln = writeln def import_package(options, pkgname): args = [sys.argv[0]] if options.memdebug: args.append('-malloc_debug') args.append('-malloc_dump') if options.summary: args.append('-log_view') package = __import__(pkgname) package.init(args, arch=options.arch) def print_banner(options): r, n = getprocessorinfo() prefix = "[%d@%s]" % (r, n) def writeln(message='', endl='\n'): if message is None: return from petsc4py.PETSc import Sys message = "%s %s" % (prefix, message) Sys.syncPrint(message, endl=endl, flush=True) if options.verbose: writeln(getpythoninfo()) writeln(getpackageinfo('numpy')) for entry in components: writeln(getlibraryinfo(entry)) writeln(getpackageinfo('%s4py' % entry.lower())) def load_tests(options, args): from glob import glob import re testsuitedir = os.path.dirname(__file__) sys.path.insert(0, testsuitedir) pattern = 'test_*.py' wildcard = os.path.join(testsuitedir, pattern) testfiles = glob(wildcard) testfiles.sort() testsuite = unittest.TestSuite() testloader = unittest.TestLoader() if options.patterns: testloader.testNamePatterns = [ # novermin ('*%s*' % p) if ('*' not in p) else p for p in options.patterns ] include = exclude = None if options.include: include = re.compile('|'.join(options.include)).search if options.exclude: exclude = re.compile('|'.join(options.exclude)).search for testfile in testfiles: filename = os.path.basename(testfile) testname = os.path.splitext(filename)[0] if ((exclude and exclude(testname)) or (include and not include(testname))): continue module = __import__(testname) for arg in args: try: cases = testloader.loadTestsFromNames((arg,), module) testsuite.addTests(cases) except AttributeError: pass if not args: cases = testloader.loadTestsFromModule(module) testsuite.addTests(cases) return testsuite def run_tests(options, testsuite, runner=None): if runner is None: runner = unittest.TextTestRunner(verbosity=options.verbose) runner.failfast = options.failfast result = runner.run(testsuite) return result.wasSuccessful() def abort(code=1): os.abort() def shutdown(success): pass def main(args=None): pkgname = '%s4py' % components[-1].lower() parser = getoptionparser() (options, args) = parser.parse_args(args) setup_python(options) setup_unittest(options) import_package(options, pkgname) print_banner(options) testsuite = load_tests(options, args) success = run_tests(options, testsuite) if not success and options.failfast: abort() shutdown(success) return not success if __name__ == '__main__': import sys sys.dont_write_bytecode = True sys.exit(main()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1768908574.0 slepc4py-3.24.2/test/test_object.py0000644000076500000240000001356415133663436016437 0ustar00jromanstafffrom slepc4py import SLEPc from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestObject(object): CLASS, FACTORY = None, 'create' TARGS, KARGS = (), {} BUILD = None def setUp(self): self.obj = self.CLASS() getattr(self.obj,self.FACTORY)(*self.TARGS, **self.KARGS) if not self.obj: self.obj.create() def tearDown(self): self.obj = None def testTypeRegistry(self): type_reg = PETSc.__type_registry__ classid = self.obj.getClassId() typeobj = self.CLASS if isinstance(self.obj, PETSc.DMDA): typeobj = PETSc.DM self.assertTrue(type_reg[classid] is typeobj ) def testLogClass(self): name = self.CLASS.__name__ logcls = PETSc.Log.Class(name) classid = self.obj.getClassId() self.assertEqual(logcls.id, classid) def testClass(self): self.assertTrue(isinstance(self.obj, self.CLASS)) self.assertTrue(type(self.obj) is self.CLASS) def testNonZero(self): self.assertTrue(bool(self.obj)) def testDestroy(self): self.assertTrue(bool(self.obj)) self.obj.destroy() self.assertFalse(bool(self.obj)) ## self.assertRaises(PETSc.Error, self.obj.destroy) ## self.assertTrue(self.obj.this is this) def testOptions(self): self.assertFalse(self.obj.getOptionsPrefix()) prefix1 = 'my_' self.obj.setOptionsPrefix(prefix1) self.assertEqual(self.obj.getOptionsPrefix(), prefix1) prefix2 = 'opt_' self.obj.setOptionsPrefix(prefix2) self.assertEqual(self.obj.getOptionsPrefix(), prefix2) ## self.obj.appendOptionsPrefix(prefix1) ## self.assertEqual(self.obj.getOptionsPrefix(), ## prefix2 + prefix1) ## self.obj.prependOptionsPrefix(prefix1) ## self.assertEqual(self.obj.getOptionsPrefix(), ## prefix1 + prefix2 + prefix1) self.obj.setFromOptions() def testName(self): oldname = self.obj.getName() newname = '%s-%s' %(oldname, oldname) self.obj.setName(newname) self.assertEqual(self.obj.getName(), newname) self.obj.setName(oldname) self.assertEqual(self.obj.getName(), oldname) def testComm(self): comm = self.obj.getComm() self.assertTrue(isinstance(comm, PETSc.Comm)) self.assertTrue(comm in [PETSc.COMM_SELF, PETSc.COMM_WORLD]) def testRefCount(self): self.assertEqual(self.obj.getRefCount(), 1) self.obj.incRef() self.assertEqual(self.obj.getRefCount(), 2) self.obj.incRef() self.assertEqual(self.obj.getRefCount(), 3) self.obj.decRef() self.assertEqual(self.obj.getRefCount(), 2) self.obj.decRef() self.assertEqual(self.obj.getRefCount(), 1) self.obj.decRef() self.assertFalse(bool(self.obj)) def testHandle(self): self.assertTrue(self.obj.handle) self.assertTrue(self.obj.fortran) h, f = self.obj.handle, self.obj.fortran if (h>0 and f>0) or (h<0 and f<0): self.assertEqual(h, f) self.obj.destroy() self.assertFalse(self.obj.handle) self.assertFalse(self.obj.fortran) def testComposeQuery(self): myobj = type(self.obj)().create() self.assertEqual(myobj.getRefCount(), 1) self.obj.compose('myobj', myobj) self.assertTrue(type(self.obj.query('myobj')) is self.CLASS) self.assertEqual(self.obj.query('myobj'), myobj) self.assertEqual(myobj.getRefCount(), 2) self.obj.compose('myobj', None) self.assertEqual(myobj.getRefCount(), 1) self.assertEqual(self.obj.query('myobj'), None) myobj.destroy() def testProperties(self): self.assertEqual(self.obj.getClassId(), self.obj.classid) self.assertEqual(self.obj.getClassName(), self.obj.klass) self.assertEqual(self.obj.getType(), self.obj.type) self.assertEqual(self.obj.getName(), self.obj.name) self.assertEqual(self.obj.getComm(), self.obj.comm) self.assertEqual(self.obj.getRefCount(), self.obj.refcount) def testShallowCopy(self): import copy rc = self.obj.getRefCount() obj = copy.copy(self.obj) self.assertTrue(obj is not self.obj) self.assertTrue(obj == self.obj) self.assertTrue(type(obj) is type(self.obj)) self.assertEqual(obj.getRefCount(), rc+1) del obj self.assertEqual(self.obj.getRefCount(), rc) def testDeepCopy(self): self.obj.setFromOptions() import copy rc = self.obj.getRefCount() try: obj = copy.deepcopy(self.obj) except NotImplementedError: return self.assertTrue(obj is not self.obj) self.assertTrue(obj != self.obj) self.assertTrue(type(obj) is type(self.obj)) self.assertEqual(self.obj.getRefCount(), rc) self.assertEqual(obj.getRefCount(), 1) del obj # -------------------------------------------------------------------- class TestObjectST(BaseTestObject, unittest.TestCase): CLASS = SLEPc.ST class TestObjectBV(BaseTestObject, unittest.TestCase): CLASS = SLEPc.BV def testDeepCopy(self): pass class TestObjectEPS(BaseTestObject, unittest.TestCase): CLASS = SLEPc.EPS class TestObjectSVD(BaseTestObject, unittest.TestCase): CLASS = SLEPc.SVD class TestObjectPEP(BaseTestObject, unittest.TestCase): CLASS = SLEPc.PEP class TestObjectNEP(BaseTestObject, unittest.TestCase): CLASS = SLEPc.NEP class TestObjectMFN(BaseTestObject, unittest.TestCase): CLASS = SLEPc.MFN class TestObjectLME(BaseTestObject, unittest.TestCase): CLASS = SLEPc.LME # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main()