pax_global_header00006660000000000000000000000064150053412000014500gustar00rootroot0000000000000052 comment=8806759289b0ef11cde17922ef2e042e6c081e3c slepc4py-3.23.1/000077500000000000000000000000001500534120000133315ustar00rootroot00000000000000slepc4py-3.23.1/CHANGES.rst000066400000000000000000000066151500534120000151430ustar00rootroot00000000000000========================= CHANGES: SLEPc for Python ========================= :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Release 3.23.1 ============== - Update to SLEPc 3.23.1. Release 3.23.0 ============== - Update to SLEPc 3.23.0. Release 3.22.2 ============== - Update to SLEPc 3.22.2. Release 3.22.1 ============== - Update to SLEPc 3.22.1. Release 3.22.0 ============== - Update to SLEPc 3.22.0. - 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.2 ============== - Update to SLEPc 3.21.2. Release 3.21.1 ============== - Update to SLEPc 3.21.1. Release 3.21.0 ============== - Update to SLEPc 3.21.0. Release 3.20.2 ============== - Update to SLEPc 3.20.2. Release 3.20.1 ============== - Update to SLEPc 3.20.1. Release 3.20.0 ============== - Update to SLEPc 3.20.0. Release 3.19.2 ============== - Update to SLEPc 3.19.2. Release 3.19.1 ============== - Update to SLEPc 3.19.1. Release 3.19.0 ============== - Update to SLEPc 3.19.0. Release 3.18.3 ============== - Update to SLEPc 3.18.3. Release 3.18.2 ============== - Update to SLEPc 3.18.2. Release 3.18.1 ============== - Update to SLEPc 3.18.1. Release 3.18.0 ============== - Update to SLEPc 3.18 release. Release 3.17.2 ============== - Update to SLEPc 3.17.2. Release 3.17.1 ============== - Update to SLEPc 3.17.1. Release 3.17.0 ============== - Update to SLEPc 3.17 release. Release 3.16.2 ============== - Update to SLEPc 3.16.2. Release 3.16.1 ============== - Update to SLEPc 3.16.1. Release 3.16.0 ============== - Update to SLEPc 3.16 release. Release 3.15.2 ============== - Update to SLEPc 3.15.2. Release 3.15.1 ============== - Updates in installation scripts. Release 3.15.0 ============== - Update to SLEPc 3.15 release. Release 3.14.0 ============== - Update to SLEPc 3.14 release. Release 3.13.0 ============== - Update to SLEPc 3.13 release. Release 3.12.0 ============== - Update to SLEPc 3.12 release. Release 3.11.0 ============== - Update to SLEPc 3.11 release. Release 3.10.0 ============== - Update to SLEPc 3.10 release. Release 3.9.0 ============= - Update to SLEPc 3.9 release. Release 3.8.0 ============= - Update to SLEPc 3.8 release. Release 3.7.0 ============= - Update to SLEPc 3.7 release. Release 3.6.0 ============= - Update to SLEPc 3.6 release. Release 3.5.1 ============= - 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.5 =========== - Update to SLEPc 3.5 release. Release 3.4 =========== - Update to SLEPc 3.4 release. Release 3.3.1 ============= - Regenerate the wrappers using Cython 0.18 and fix binary compatibility issues with petsc4py 3.3.1 . Release 3.3 =========== - Update to SLEPc 3.3 release. Release 1.2 =========== - Update to SLEPc 3.2 release. 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). * Preliminar support for Python 3. Release 1.0.0 ============= This is the fist release of the all-new, Cython-based, implementation of *SLEPc for Python*. slepc4py-3.23.1/DESCRIPTION.rst000066400000000000000000000017171500534120000156540ustar00rootroot00000000000000SLEPc for Python ================ Python bindings for SLEPc. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it 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 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 slepc4py-3.23.1/LICENSE.rst000066400000000000000000000026501500534120000151500ustar00rootroot00000000000000========================= LICENSE: SLEPc for Python ========================= :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Copyright (c) 2024, 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. slepc4py-3.23.1/MANIFEST.in000066400000000000000000000010361500534120000150670ustar00rootroot00000000000000include 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 slepc4py-3.23.1/PKG-INFO000066400000000000000000000047111500534120000144310ustar00rootroot00000000000000Metadata-Version: 2.4 Name: slepc4py Version: 3.23.1 Summary: SLEPc for Python Home-page: https://gitlab.com/slepc/slepc Download-URL: https://pypi.io/packages/source/s/slepc4py/slepc4py-3.23.1.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.24,>=3.23 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. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it 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 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 slepc4py-3.23.1/README.rst000066400000000000000000000017401500534120000150220ustar00rootroot00000000000000================ 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_ 2.7, 3.3 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://slepc4py.readthedocs.org/, This does not contain the epydoc-generated API reference. * https://slepc.upv.es/slepc4py-current/docs/, This is for the last release, not the in-development version. slepc4py-3.23.1/conf/000077500000000000000000000000001500534120000142565ustar00rootroot00000000000000slepc4py-3.23.1/conf/__init__.py000066400000000000000000000000001500534120000163550ustar00rootroot00000000000000slepc4py-3.23.1/conf/confpetsc.py000066400000000000000000001023121500534120000166130ustar00rootroot00000000000000# -------------------------------------------------------------------- import re import os import sys import glob import copy import warnings 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') from distutils import log from distutils import sysconfig from distutils.util import execute from distutils.util import split_quoted from distutils.errors import DistutilsError 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("Cannot parse Cython version string {0!r}" .format(CYTHON_VERSION)) return False REQUIRED = Version(VERSION) PROVIDED = Version(m.groups()[0]) if PROVIDED < REQUIRED: warn("You need Cython >= {0} (you have version {1})" .format(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(dict(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( "Cython failure: '%s' -> '%s'" % (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 values = fix_config_vars(names, values) return 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 confdict = makefile(StringIO(confstr)) return confdict 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%s %s' % \ (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) 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) outputs = list(set(outputs)) return outputs 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 type(flags) is 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) # -------------------------------------------------------------------- from distutils.text_file import TextFile # Regexes needed for parsing Makefile-like syntaxes import re as _re _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 # -------------------------------------------------------------------- slepc4py-3.23.1/conf/confslepc.py000066400000000000000000000221211500534120000166020ustar00rootroot00000000000000import 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 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) # -------------------------------------------------------------------- slepc4py-3.23.1/conf/cythonize.py000077500000000000000000000024461500534120000166550ustar00rootroot00000000000000#!/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() slepc4py-3.23.1/conf/cythonize.sh000077500000000000000000000002231500534120000166260ustar00rootroot00000000000000#!/bin/sh topdir=$(cd $(dirname "$0")/.. && pwd) python$py "$topdir/conf/cythonize.py" \ --working "$topdir/src" $@ \ "slepc4py/SLEPc.pyx" slepc4py-3.23.1/conf/epydoc.cfg000066400000000000000000000105511500534120000162240ustar00rootroot00000000000000[epydoc] # Epydoc section marker (required by ConfigParser) # The list of objects to document. Objects can be named using # dotted names, module filenames, or package directory names. # Alases for this option include "objects" and "values". modules: slepc4py # The type of output that should be generated. Should be one # of: html, text, latex, dvi, ps, pdf. #output: html # The path to the output directory. May be relative or absolute. #target: docs/html/ # An integer indicating how verbose epydoc should be. The default # value is 0; negative values will suppress warnings and errors; # positive values will give more verbose output. verbosity: 0 # A boolean value indicating that Epydoc should show a tracaback # in case of unexpected error. By default don't show tracebacks #debug: 0 # If True, don't try to use colors or cursor control when doing # textual output. The default False assumes a rich text prompt #simple-term: 0 ### Generation options # The default markup language for docstrings, for modules that do # not define __docformat__. Defaults to epytext. docformat: reStructuredText # Whether or not parsing should be used to examine objects. parse: yes # Whether or not introspection should be used to examine objects. introspect: yes # Don't examine in any way the modules whose dotted name match this # regular expression pattern. exclude: slepc4py.__main__ # Don't perform introspection on the modules whose dotted name match this # regular expression pattern. #exclude-introspect # Don't perform parsing on the modules whose dotted name match this # regular expression pattern. #exclude-parse: # The format for showing inheritance objects. # It should be one of: 'grouped', 'listed', 'included'. inheritance: listed # Whether or not to include private variables. (Even if included, # private variables will be hidden by default.) private: yes # Whether or not to list each module's imports. imports: no # Whether or not to include syntax highlighted source code in # the output (HTML only). sourcecode: no # Whether or not to include a page with Epydoc log, containing # effective option at the time of generation and the reported logs. include-log: no ### Output options # The documented project's name. name: SLEPc for Python # The documented project's URL. url: https://gitlab.com/slepc/slepc # The CSS stylesheet for HTML output. Can be the name of a builtin # stylesheet, or the name of a file. css: white # HTML code for the project link in the navigation bar. If left # unspecified, the project link will be generated based on the # project's name and URL. #link: My Cool Project # The "top" page for the documentation. Can be a URL, the name # of a module or class, or one of the special names "trees.html", # "indices.html", or "help.html" #top: os.path # An alternative help file. The named file should contain the # body of an HTML file; navigation bars will be added to it. #help: my_helpfile.html # Whether or not to include a frames-based table of contents. frames: yes # Whether each class should be listed in its own section when # generating LaTeX or PDF output. separate-classes: no ### API linking options # Define a new API document. A new interpreted text role # will be created #external-api: epydoc # Use the records in this file to resolve objects in the API named NAME. #external-api-file: epydoc:api-objects.txt # Use this URL prefix to configure the string returned for external API. #external-api-root: epydoc:http://epydoc.sourceforge.net/api ### Graph options # The list of graph types that should be automatically included # in the output. Graphs are generated using the Graphviz "dot" # executable. Graph types include: "classtree", "callgraph", # "umlclasstree". Use "all" to include all graph types graph: classtree # The path to the Graphviz "dot" executable, used to generate # graphs. #dotpath: /usr/local/bin/dot # The name of one or more pstat files (generated by the profile # or hotshot module). These are used to generate call graphs. #pstat: profile.out # Specify the font used to generate Graphviz graphs. # (e.g., helvetica or times). graph-font: Helvetica # Specify the font size used to generate Graphviz graphs. graph-font-size: 10 ### Return value options # The condition upon which Epydoc should exit with a non-zero # exit status. Possible values are error, warning, docstring_warning #fail-on: error slepc4py-3.23.1/conf/epydocify.py000077500000000000000000000055051500534120000166330ustar00rootroot00000000000000#!/usr/bin/env python # -------------------------------------------------------------------- from slepc4py import SLEPc # -------------------------------------------------------------------- try: from docutils.nodes import NodeVisitor NodeVisitor.unknown_visit = lambda self, node: None NodeVisitor.unknown_departure = lambda self, node: None except ImportError: pass try: # epydoc 3.0.1 + docutils 0.6 from docutils.nodes import Text from UserString import UserString if not isinstance(Text, UserString): def Text_get_data(s): try: return s._data except AttributeError: return s.astext() def Text_set_data(s, d): s.astext = lambda: d s._data = d Text.data = property(Text_get_data, Text_set_data) except ImportError: pass # -------------------------------------------------------------------- from epydoc.docwriter import dotgraph import re dotgraph._DOT_VERSION_RE = \ re.compile(r'dot (?:- Graphviz )version ([\d\.]+)') try: dotgraph.DotGraph.DEFAULT_HTML_IMAGE_FORMAT dotgraph.DotGraph.DEFAULT_HTML_IMAGE_FORMAT = 'png' except AttributeError: DotGraph_to_html = dotgraph.DotGraph.to_html DotGraph_run_dot = dotgraph.DotGraph._run_dot def to_html(self, image_file, image_url, center=True): if image_file[-4:] == '.gif': image_file = image_file[:-4] + '.png' if image_url[-4:] == '.gif': image_url = image_url[:-4] + '.png' return DotGraph_to_html(self, image_file, image_url) def _run_dot(self, *options): if '-Tgif' in options: opts = list(options) for i, o in enumerate(opts): if o == '-Tgif': opts[i] = '-Tpng' options = type(options)(opts) return DotGraph_run_dot(self, *options) dotgraph.DotGraph.to_html = to_html dotgraph.DotGraph._run_dot = _run_dot # -------------------------------------------------------------------- import re _SIGNATURE_RE = re.compile( # Class name (for builtin methods) r'^\s*((?P\w+)\.)?' + # The function name r'(?P\w+)' + # The parameters r'\(((?P(?:self|cls|mcs)),?)?(?P.*)\)' + # The return value (optional) r'(\s*(->)\s*(?P\S.*?))?'+ # The end marker r'\s*(\n|\s+(--|<=+>)\s+|$|\.\s+|\.\n)') from epydoc import docstringparser as dsp dsp._SIGNATURE_RE = _SIGNATURE_RE # -------------------------------------------------------------------- import sys, os import epydoc.cli def epydocify(): dirname = os.path.dirname(__file__) config = os.path.join(dirname, 'epydoc.cfg') sys.argv.append('--config=' + config) epydoc.cli.cli() if __name__ == '__main__': epydocify() # -------------------------------------------------------------------- slepc4py-3.23.1/demo/000077500000000000000000000000001500534120000142555ustar00rootroot00000000000000slepc4py-3.23.1/demo/ex1.py000066400000000000000000000034651500534120000153340ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Standard symmetric eigenproblem for the Laplacian operator in 1-D # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy opts = PETSc.Options() n = opts.getInt('n', 30) 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() E = SLEPc.EPS(); E.create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) history = [] def monitor(eps, its, nconv, eig, err): 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() slepc4py-3.23.1/demo/ex10.py000066400000000000000000000212071500534120000154060ustar00rootroot00000000000000""" 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 the papers: [1] K. Kunisch and S. Volkwein. Galerkin proper orthogonal decomposition methods for a general equation in fluid dynamics. SIAM Journal on Numerical Analusis, 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(2001):83-97 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 S. 2. A standard eigenvalue decomposition is performed on the matrix S.T*S. 3. The eigenvectors and eigenvalues are projected back to the original eigenvalue problem 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. Authors: Elisa Schenone Jack S. Hale """ 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 def construct_operator(m): """ Standard symmetric eigenproblem corresponding to the Laplacian operator in 1 dimension with homogeneous Dirichlet boundary conditions. """ # 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 def set_problem_rhs(m): """ 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. """ # 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 def solve_laplace_problem(A, RHS): """ Solve 1D Laplace problem with FEM. """ u = A.createVecs('right') r, c = A.getOrdering("natural") A.factorILU(r, c) A.solve(RHS, u) A.setUnfactored() return u def solve_laplace_problem_pod(A, RHS, u): """ Solve 1D Laplace problem with POD (dense matrix). """ 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 def construct_snapshot_matrix(A, N, m): """ 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: z(x) = exp(-(x - mu)**2 / sigma) """ 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 def solve_eigenproblem(snapshots, N): """ Solve the eigenvalue problem: the eigenvectors of this problem form the POD basis. """ 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 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 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 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() slepc4py-3.23.1/demo/ex11.py000066400000000000000000000036671500534120000154210ustar00rootroot00000000000000# ------------------------------------------------------------------------ # 2-D Laplacian Eigenproblem solved with contour integral # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print def construct_operator(m, n): """ Standard symmetric eigenproblem corresponding to the Laplacian operator in 2 dimensions. """ # 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 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) # Solver object E = SLEPc.EPS().create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setType(SLEPc.EPS.Type.CISS) # Define region of interest R = E.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) R.setEllipseParameters(0.0,0.2,0.1) E.setFromOptions() # Compute solution E.solve() # Print solution vw = PETSc.Viewer.STDOUT() vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) vw.popFormat() if __name__ == '__main__': main() slepc4py-3.23.1/demo/ex12.py000066400000000000000000000025661500534120000154170ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Tests use of setArbitrarySelection() # - selection criterion is the projection onto a precomputed eigenvector # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy opts = PETSc.Options() n = opts.getInt('n', 30) # Create 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" ) slepc4py-3.23.1/demo/ex13.py000066400000000000000000000171121500534120000154110ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Solve nonlinear (in eigenvalue k) EVP using the NEP module # # u_xx(x) + nc^2*k^2*u(x) + g(k)*D0*k^2*u(x) = 0 # # where g(k) = gt/(k-ka + i*gt) # ka=8.0, gt=0.5 # D0 = 0.5 # nc = 1.2 # # u(0) = 0 # u_x(1) = i*k*u(1) ## ## # # Discretization: # # n grid points: x1=0.0 .. xn=1.0 # # u1 is at x=0.0 # un is at x=1.0 # # step size h = 1/(n-1) # # u_xx(x_i) = 1/h**2 * (u_im1 - 2 u_i + u_ip1) # = 1/h**2 dot((1, -2, 1), (u_im1, u_i, u_ip1)) # # BC x=0: u1 = 0.0 # BC x=1: u'(1) ~ 1/2*( u'(1+h/2) + u'(1-h/2) ) # = 1/2*( (u_np1-u_n)/h + (u_n-u_nm1)/h ) # = 1/(2h)*(u_np1 - u_nm1) = ik * u_n # => u_np1 = 2i*h*k u_n + u_nm1 # # laplace term for un: # 1/h**2 (u_nm1 - 2u_n + u_np1) # = 1/h**2 (u_nm1 - 2u_n + 2ihk u_n + u_nm1) # = 1/h**2 (2 u_nm1 + (2ihk - 2) u_n) # = 1/h**2 dot((2, 2ihk -2), (u_nm1, u_n)) # # The above discretization allows us to write the nonlinear PDE # in the following split-operator form # # {A + k^2 nc^2 Id + g(k)*k^2*D0 Id + 2ik/h D} u = 0 # # f1 = 1, f2 = nc^2 k^2, f3 = g(k)k^2D0, f4 = 2ik/h # # A = (1 0 0 ... ) # (0 ....... ) # (0 ....... ) # (0 ....... ) # (......... ) # # Id = (0 0 0 ... ) # (0 1 0 ... ) # (0 0 1 ... ) # (0 0 0 ... ) # (......... ) # # D = (0 0 0 ... ) # (0 ....... ) # (0 ....... ) # (0 ....... ) # (......... ) # # ------------------------------------------------------------------------ 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 if not np.issubdtype(PETSc.ScalarType, np.complexfloating): Print("Demo should only be executed with complex PETSc scalars") exit(0) 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 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() slepc4py-3.23.1/demo/ex2.py000066400000000000000000000053211500534120000153260ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Standard symmetric eigenproblem for the Laplacian operator in 2-D # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print def construct_operator(m, n): """ Standard symmetric eigenproblem corresponding to the Laplacian operator in 2 dimensions. """ # 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 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("") 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() slepc4py-3.23.1/demo/ex3.py000066400000000000000000000060531500534120000153320ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Matrix-free eigenproblem for the Laplacian operator in 2-D # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy as np # this a sequential example assert PETSc.COMM_WORLD.getSize() == 1 Print = PETSc.Sys.Print 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) \ 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) def construct_operator(m, n): """ Standard symmetric eigenproblem corresponding to the Laplacian operator in 2 dimensions. Uses *shell* matrix. """ # Create shell matrix context = Laplacian2D(m,n) A = PETSc.Mat().createPython([m*n,m*n], context) return A 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("") 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() slepc4py-3.23.1/demo/ex4.py000066400000000000000000000033001500534120000153230ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Singular value decomposition of the Lauchli matrix # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc 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) ) 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() S = SLEPc.SVD(); S.create() S.setOperator(A) S.setType(S.Type.TRLANCZOS) S.setFromOptions() S.solve() 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() slepc4py-3.23.1/demo/ex5.py000066400000000000000000000051701500534120000153330ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Simple quadratic eigenvalue problem # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print def construct_operators(m,n): """ Standard symmetric eigenproblem corresponding to the Laplacian operator in 2 dimensions. """ 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("") 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 slepc4py-3.23.1/demo/ex6.py000066400000000000000000000045731500534120000153420ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Computes exp(t*A)*v for a matrix associated with a Markov model # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print def build_matrix(m): """ Markov model of a random walk on a triangular grid """ 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 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("") 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 slepc4py-3.23.1/demo/ex7.py000066400000000000000000000103101500534120000153250ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Solve 1-D PDE # -u'' = lambda*u # on [0,1] subject to # u(0)=0, u'(1)=u(1)*lambda*kappa/(kappa-lambda) # ------------------------------------------------------------------------ import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc from numpy import sqrt, sin Print = PETSc.Sys.Print 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, F): 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() def FixSign(x): # Force the eigenfunction to be real and positive, since # some eigensolvers may return the eigenvector multiplied # by a complex number of modulus one. 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) opts = PETSc.Options() n = opts.getInt('n', 128) kappa = opts.getReal('kappa', 1.0) pde = MyPDE(kappa, 1.0/n) # Setup the solver 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) nep.setTolerances(tol=1e-9) nep.setDimensions(1) nep.setFromOptions() # Solve the problem x = F.createVecs('right') x.set(1.0) nep.setInitialSpace(x) 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 ) 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() slepc4py-3.23.1/demo/ex8.py000066400000000000000000000056571500534120000153500ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Solve parabolic partial differential equation with time delay tau # # u_t = u_xx + a*u(t) + b*u(t-tau) # u(0,t) = u(pi,t) = 0 # # with a = 20 and b(x) = -4.1+x*(1-exp(x-pi)). # # Discretization leads to a DDE of dimension n # # -u' = A*u(t) + B*u(t-tau) # # which results in the nonlinear eigenproblem # # (-lambda*I + A + exp(-tau*lambda)*B)*u = 0 # ------------------------------------------------------------------------ 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 opts = PETSc.Options() n = opts.getInt('n', 128) tau = opts.getReal('tau', 0.001) a = 20 h = pi/(n+1) # Setup the solver nep = SLEPc.NEP().create() # Create problem matrices # Identity matrix Id = PETSc.Mat().createConstantDiagonal([n, n], 1.0) # A = 1/h^2*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() # B = diag(b(xi)) 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) # Functions: f1=-lambda, f2=1.0, f3=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) # Set 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) # Customize options nep.setTolerances(tol=1e-9) nep.setDimensions(1) 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 ) 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() slepc4py-3.23.1/demo/ex9.py000066400000000000000000000066671500534120000153530ustar00rootroot00000000000000# ------------------------------------------------------------------------ # Generalized symmetric-definite eigenproblem # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc Print = PETSc.Sys.Print def Laplacian2D(m, n): """ Builds discretized Laplacian operator in 2 dimensions. """ # 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 def QuasiDiagonal(N): """ Builds matrix diag(2)+[6 -1; -1 1] """ # 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 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("") 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() slepc4py-3.23.1/demo/makefile000066400000000000000000000005051500534120000157550ustar00rootroot00000000000000PYTHON=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} slepc4py-3.23.1/docs/000077500000000000000000000000001500534120000142615ustar00rootroot00000000000000slepc4py-3.23.1/docs/index.rst000066400000000000000000000033611500534120000161250ustar00rootroot00000000000000================ SLEPc for Python ================ :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Online Documentation -------------------- + `User Manual (HTML)`_ (generated with Sphinx_). + `User Manual (PDF)`_ (generated with Sphinx_). + `API Reference`_ (generated with Epydoc_). .. _User Manual (HTML): usrman/index.html .. _User Manual (PDF): slepc4py.pdf .. _API Reference: apiref/index.html .. _Sphinx: https://www.sphinx-doc.org/ .. _Epydoc: https://epydoc.sourceforge.net/ Discussion and Support ---------------------- + Mailing Lists: petsc-users@mcs.anl.gov, slepc-maint@upv.es Downloads and Development ------------------------- + Issue Tracker: https://gitlab.com/slepc/slepc/-/issues + Git Repository: https://gitlab.com/slepc/slepc.git + The source code is in ``src/binding/slepc4py`` + Previous source releases: https://pypi.org/project/slepc4py/ Citations --------- If SLEPc for Python 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. http://dx.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. http://dx.doi.org/10.1145/1089014.1089019 Acknowledgments --------------- This project 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). slepc4py-3.23.1/docs/source/000077500000000000000000000000001500534120000155615ustar00rootroot00000000000000slepc4py-3.23.1/docs/source/Makefile000066400000000000000000000011411500534120000172160ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = petsc4py 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) slepc4py-3.23.1/docs/source/abstract.txt000066400000000000000000000012231500534120000201230ustar00rootroot00000000000000.. topic:: Abstract This document describes slepc4py_, a Python_ port 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. 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_. .. Local Variables: .. mode: rst .. End: slepc4py-3.23.1/docs/source/citing.rst000066400000000000000000000011301500534120000175630ustar00rootroot00000000000000Citations ========= If SLEPc for Python 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. http://dx.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. http://dx.doi.org/10.1145/1089014.1089019 slepc4py-3.23.1/docs/source/conf.py000066400000000000000000000143421500534120000170640ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # SLEPc for Python documentation build configuration file, created by # sphinx-quickstart on Sun Oct 1 15:52:05 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # 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 os # import sys # sys.path.insert(0, os.path.abspath('.')) def get_version(): import sys, os, re here = os.path.dirname(__file__) pardir = [os.path.pardir] * 2 topdir = os.path.join(here, *pardir) srcdir = os.path.join(topdir, 'src') with open(os.path.join(srcdir, 'slepc4py', '__init__.py')) as f: m = re.search(r"__version__\s*=\s*'(.*)'", f.read()) return m.groups()[0] pkg_version = get_version() # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] templates_path = [] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The main toctree document. main_doc = 'index' # General information about the project. project = u'SLEPc for Python' copyright = u'2024, Lisandro Dalcin and Jose Roman' author = u'Lisandro Dalcin' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = pkg_version[:3] # The full version, including alpha/beta/rc tags. release = pkg_version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- 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 = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] html_static_path = [] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars # html_sidebars = { # '**': [ # 'about.html', # 'navigation.html', # 'relations.html', # needs 'show_related': True theme option to display # 'searchbox.html', # 'donate.html', # ] # } # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'slepc4py-man' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', 'papersize': 'a4', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', #'printmodindex': '', #'printindex': '', #'preamble' : '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('manual', 'slepc4py.tex', project, author, 'howto'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (main_doc, 'slepc4py', project, [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (main_doc, 'slepc4py', project, author, 'slepc4py', project+u'.', 'Miscellaneous'), ] # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] slepc4py-3.23.1/docs/source/contents.rst000066400000000000000000000000001500534120000201360ustar00rootroot00000000000000slepc4py-3.23.1/docs/source/index.rst000066400000000000000000000004741500534120000174270ustar00rootroot00000000000000================ SLEPc for Python ================ :Authors: Lisandro Dalcin, Jose E. Roman :Contact: dalcinl@gmail.com, jroman@dsic.upv.es :Web Site: https://gitlab.com/slepc/slepc :Date: |today| .. include:: abstract.txt Contents ======== .. include:: toctree.txt .. include:: links.txt slepc4py-3.23.1/docs/source/install.rst000066400000000000000000000077011500534120000177660ustar00rootroot00000000000000Installation ============ Using **pip** or **easy_install** --------------------------------- You can use :program:`pip` to install :mod:`slepc4py` and its dependencies (:mod:`mpi4py` is optional but highly recommended):: $ pip install [--user] numpy mpi4py $ pip install [--user] petsc petsc4py $ pip install [--user] slepc slepc4py Alternatively, you can use :program:`easy_install` (deprecated):: $ easy_install [--user] 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 $ pip install [--user] petsc4py slepc4py Using **distutils** ------------------- Requirements ^^^^^^^^^^^^ You need to have the following software properly installed in order to build *SLEPc for Python*: * Any MPI_ implementation [#]_ (e.g., MPICH_ or `Open MPI`_), built with shared libraries. * A matching version of PETSc_ built with shared libraries. * A matching version of SLEPc_ built with shared libraries. * NumPy_ package. * petsc4py_ package. .. [#] Unless you have appropriately configured and built SLEPc and PETSc without MPI (configure option ``--with-mpi=0``). .. [#] You may need to use a parallelized version of the Python interpreter with some MPI-1 implementations (e.g. MPICH1). .. include:: links.txt Downloading ^^^^^^^^^^^ The *SLEPc for Python* package is available for download at the Python Package Index. You can use :program:`curl` or :program:`wget` to get a release tarball. * Using :program:`curl`:: $ curl -LO https://pypi.io/packages/source/s/slepc4py/slepc4py-X.Y.Z.tar.gz * Using :program:`wget`:: $ wget https://pypi.io/packages/source/s/slepc4py/slepc4py-X.Y.Z.tar.gz Building ^^^^^^^^ After unpacking the release tarball:: $ tar -zxf slepc4py-X.Y.tar.gz $ cd slepc4py-X.Y the distribution is ready for building. .. note:: **Mac OS X** users employing a Python distribution built with **universal binaries** may need to set the environment variables :envvar:`MACOSX_DEPLOYMENT_TARGET`, :envvar:`SDKROOT`, and :envvar:`ARCHFLAGS` to appropriate values. As an example, assume your Mac is running **Snow Leopard** on a **64-bit Intel** processor and you want to override the hard-wired cross-development SDK in Python configuration, your environment should be modified like this:: $ export MACOSX_DEPLOYMENT_TARGET=10.6 $ export SDKROOT=/ $ export ARCHFLAGS='-arch x86_64' Some environment configuration is needed to inform the location of PETSc and SLEPc. You can set (using :command:`setenv`, :command:`export` or what applies to you shell or system) the environment variables :envvar:`SLEPC_DIR``, :envvar:`PETSC_DIR`, and :envvar:`PETSC_ARCH` indicating where you have built/installed SLEPc and PETSc:: $ export SLEPC_DIR=/usr/local/slepc $ export PETSC_DIR=/usr/local/petsc $ export PETSC_ARCH=arch-linux2-c-opt Alternatively, you can edit the file :file:`setup.cfg` and provide the required information below the ``[config]`` section:: [config] slepc_dir = /usr/local/slepc petsc_dir = /usr/local/petsc petsc_arch = arch-linux2-c-opt ... Finally, you can build the distribution by typing:: $ python setup.py build Installing ^^^^^^^^^^ After building, the distribution is ready for installation. If you have root privileges (either by log-in as the root user of by using :command:`sudo`) and you want to install *SLEPc for Python* in your system for all users, just do:: $ python setup.py install The previous steps will install the :mod:`slepc4py` package at standard location :file:`{prefix}/lib/python{X}.{X}/site-packages`. If you do not have root privileges or you want to install *SLEPc for Python* for your private use, just do:: $ python setup.py install --user slepc4py-3.23.1/docs/source/links.txt000066400000000000000000000007431500534120000174460ustar00rootroot00000000000000.. _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: slepc4py-3.23.1/docs/source/make.bat000066400000000000000000000014461500534120000171730ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=petsc4py if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd slepc4py-3.23.1/docs/source/manual.rst000066400000000000000000000002001500534120000175600ustar00rootroot00000000000000================ SLEPc for Python ================ .. include:: abstract.txt .. include:: toctree.txt .. include:: links.txt slepc4py-3.23.1/docs/source/overview.rst000066400000000000000000000167711500534120000201750ustar00rootroot00000000000000Overview ======== *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.23. 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. .. include:: links.txt Features -------- Currently, the following types of eigenproblems can be addressed: * Standard eigenvalue problem, *Ax=kx*, either for Hermitian or non-Hermitian matrices. * Generalized eigenvalue problem, *Ax=kBx*, either Hermitian positive-definite or not. * Partial singular value decomposition of a rectangular matrix, *Au=sv*. * Polynomial eigenvalue problem, *P(k)x=0*. * Nonlinear eigenvalue problem, *T(k)x=0*. * Computing the action of a matrix function on a vector, *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 for the minimization of the Rayleigh quotient. * A contour integral solver. For singular value computations, the following alternatives can be used: * Use an eigensolver via the cross-product matrix *A'A* or the cyclic matrix *[0 A; A' 0]*. * Explicitly restarted Lanczos bidiagonalization. * Implicitly restarted Lanczos bidiagonalization (thick-restart Lanczos). 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. 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. 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 *(A-tI)* in order to compute eigenvalues closest to a given target value, *t*. * Harmonic extraction, a cheap alternative to shift-and-invert that also tries to approximate eigenvalues closest to a target, *t*, 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. Components ---------- SLEPc provides the following components, which are mirrored by slepc4py for its use from Python. The first five 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 behaviour 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, T(lambda)x=0. The user provides the parameter-dependent matrix 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 A and a vector b, the call MFNSolve(mfn,b,x) computes x=f(A)b, where f is a function such as the exponential. :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 T(.) 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. slepc4py-3.23.1/docs/source/toctree.txt000066400000000000000000000001651500534120000177710ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 overview tutorial install citing .. Local Variables: .. mode: rst .. End: slepc4py-3.23.1/docs/source/tutorial.rst000066400000000000000000000175131500534120000201650ustar00rootroot00000000000000Tutorial ======== This tutorial is intended for basic use of slepc4py. For more advanced use, the reader is referred to SLEPc tutorials as well as to slepc4py reference documentation. Commented source of a simple example ------------------------------------ In this section, we include the source code of example ``demo/ex1.py`` available in the slepc4py distribution, with comments inserted inline. 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 accessing 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 the next section 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().create() A.setSizes([n, n]) A.setFromOptions() A.setUp() 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) E.setFromOptions() After that, the ``solve()`` 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). 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 vr, wr = A.getVecs() vi, wi = A.getVecs() # Print() Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, vr, vi) 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() 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:: $ 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:: $ 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:: $ 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:: $ 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:: $ 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:: $ python demo/ex1.py -st_type sinvert -eps_target 0.6 slepc4py-3.23.1/pyproject.toml000066400000000000000000000001621500534120000162440ustar00rootroot00000000000000[build-system] requires = [ "cython >= 3", "numpy", "setuptools", ] build-backend = "setuptools.build_meta" slepc4py-3.23.1/setup.cfg000066400000000000000000000003001500534120000151430ustar00rootroot00000000000000[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 slepc4py-3.23.1/setup.py000077500000000000000000000202661500534120000150540ustar00rootroot00000000000000#!/usr/bin/env python3 # Author: Lisandro Dalcin # Contact: dalcinl@gmail.com import re import os import sys 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 # -------------------------------------------------------------------- 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', } # -------------------------------------------------------------------- # Extension modules # -------------------------------------------------------------------- def sources(): src = dict( 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 = dict( 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 = "%s.%s%s" % (major, minor, devel) vmax = "%s.%s" % (major, minor + 1) return "%s>=%s,<%s" % (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: 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}')) 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'), ], F('{pyname}.lib'): [ F('{name}.cfg'), ], }, cython_sources=[ src for src in sources() ], ext_modules=[ conf.Extension(**ext) for ext in extensions() ], **setup_args ) # -------------------------------------------------------------------- def main(): run_setup() if __name__ == '__main__': main() # -------------------------------------------------------------------- slepc4py-3.23.1/src/000077500000000000000000000000001500534120000141205ustar00rootroot00000000000000slepc4py-3.23.1/src/lib-slepc/000077500000000000000000000000001500534120000157725ustar00rootroot00000000000000slepc4py-3.23.1/src/lib-slepc/compat.h000066400000000000000000000002211500534120000174210ustar00rootroot00000000000000#ifndef SLEPC4PY_COMPAT_H #define SLEPC4PY_COMPAT_H #if !defined(PETSC_USE_COMPLEX) #endif /*PETSC_USE_COMPLEX*/ #endif /*SLEPC4PY_COMPAT_H*/ slepc4py-3.23.1/src/lib-slepc/custom.h000066400000000000000000000013531500534120000174570ustar00rootroot00000000000000#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(STInitializePackage()); PetscCall(BVInitializePackage()); PetscCall(DSInitializePackage()); PetscCall(FNInitializePackage()); PetscCall(RGInitializePackage()); PetscFunctionReturn(PETSC_SUCCESS); } #endif/*SLEPC4PY_CUSTOM_H*/ slepc4py-3.23.1/src/slepc4py.egg-info/000077500000000000000000000000001500534120000173555ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py.egg-info/PKG-INFO000066400000000000000000000047111500534120000204550ustar00rootroot00000000000000Metadata-Version: 2.4 Name: slepc4py Version: 3.23.1 Summary: SLEPc for Python Home-page: https://gitlab.com/slepc/slepc Download-URL: https://pypi.io/packages/source/s/slepc4py/slepc4py-3.23.1.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.24,>=3.23 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. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it 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 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 slepc4py-3.23.1/src/slepc4py.egg-info/SOURCES.txt000066400000000000000000000041341500534120000212430ustar00rootroot00000000000000CHANGES.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/cythonize.py conf/cythonize.sh conf/epydoc.cfg conf/epydocify.py demo/ex1.py demo/ex10.py demo/ex11.py demo/ex12.py demo/ex13.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/index.rst docs/source/Makefile docs/source/abstract.txt docs/source/citing.rst docs/source/conf.py docs/source/contents.rst docs/source/index.rst docs/source/install.rst docs/source/links.txt docs/source/make.bat docs/source/manual.rst docs/source/overview.rst docs/source/toctree.txt docs/source/tutorial.rst 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/__main__.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/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/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/include/slepc4py/slepc4py.h src/slepc4py/include/slepc4py/slepc4py.i src/slepc4py/lib/__init__.py src/slepc4py/lib/slepc.cfg test/runtests.py test/test_object.pyslepc4py-3.23.1/src/slepc4py.egg-info/dependency_links.txt000066400000000000000000000000011500534120000234230ustar00rootroot00000000000000 slepc4py-3.23.1/src/slepc4py.egg-info/not-zip-safe000066400000000000000000000000011500534120000216030ustar00rootroot00000000000000 slepc4py-3.23.1/src/slepc4py.egg-info/requires.txt000066400000000000000000000000331500534120000217510ustar00rootroot00000000000000numpy petsc4py<3.24,>=3.23 slepc4py-3.23.1/src/slepc4py.egg-info/top_level.txt000066400000000000000000000000111500534120000220770ustar00rootroot00000000000000slepc4py slepc4py-3.23.1/src/slepc4py/000077500000000000000000000000001500534120000156635ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py/SLEPc.pxd000066400000000000000000000041331500534120000173070ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # ----------------------------------------------------------------------------- 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" # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc.py000066400000000000000000000004051500534120000171420ustar00rootroot00000000000000ARCH = 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 slepc4py-3.23.1/src/slepc4py/SLEPc.pyx000066400000000000000000000007231500534120000173350ustar00rootroot00000000000000#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=False #from __future__ import annotations cimport cython include "SLEPc/SLEPc.pyx" slepc4py-3.23.1/src/slepc4py/SLEPc/000077500000000000000000000000001500534120000165715ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py/SLEPc/BV.pyx000066400000000000000000001241561500534120000176530ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class BVType(object): """ BV type """ 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. """ 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. """ 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. - `CHOL`: Cholesky. - `TSQR`: Tall-skinny QR. - `TSQRCHOL`: Tall-skinny QR with Cholesky. - `SVQB`: SVQB. """ 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. """ 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 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 cammunication-avoiding Arnoldi. """ REFINE = BV_SVD_METHOD_REFINE QR = BV_SVD_METHOD_QR QR_CAA = BV_SVD_METHOD_QR_CAA # ----------------------------------------------------------------------------- cdef class BV(Object): """ BV """ Type = BVType OrthogType = BVOrthogType OrthogRefineType = BVOrthogRefineType RefineType = BVOrthogRefineType OrthogBlockType = BVOrthogBlockType BlockType = BVOrthogBlockType MatMultType = BVMatMultType def __cinit__(self): self.obj = &self.bv self.bv = NULL def view(self, Viewer viewer=None): """ Prints the BV data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( BVView(self.bv, vwr) ) def destroy(self): """ Destroys the BV object. """ CHKERR( BVDestroy(&self.bv) ) self.bv = NULL return self def create(self, comm=None): """ Creates the BV object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Creates a basis vectors object from a dense Mat object. Parameters ---------- A: Mat A dense tall-skinny matrix. """ cdef SlepcBV newbv = NULL CHKERR( BVCreateFromMat(A.mat, &newbv) ) CHKERR( SlepcCLEAR(self.obj) ); self.bv = newbv return self def createMat(self): """ Creates a new Mat object of dense type and copies the contents of the BV object. Returns ------- mat: the new matrix. """ cdef Mat mat = Mat() CHKERR( BVCreateMat(self.bv, &mat.mat) ) return mat def duplicate(self): """ Duplicate the BV object with the same type and dimensions. """ cdef BV bv = type(self)() CHKERR( BVDuplicate(self.bv, &bv.bv) ) return bv def duplicateResize(self, m): """ Creates a new BV object of the same type and dimensions as an existing one, but with possibly different number of columns. Parameters ---------- m: int The number of columns. """ 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): """ Copies a basis vector object into another one. Parameters ---------- result: `BV`, optional The copy. """ 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): """ Selects the type for the BV object. Parameters ---------- bv_type: `BV.Type` enumerate The inner product type to be used. """ cdef SlepcBVType cval = NULL bv_type = str2bytes(bv_type, &cval) CHKERR( BVSetType(self.bv, cval) ) def getType(self): """ Gets the BV type of this object. Returns ------- type: `BV.Type` enumerate The inner product type currently being used. """ cdef SlepcBVType bv_type = NULL CHKERR( BVGetType(self.bv, &bv_type) ) return bytes2str(bv_type) def setSizes(self, sizes, m): """ Sets the local and global sizes, and the number of columns. Parameters ---------- sizes: int or two-tuple of int The global size ``N`` or a two-tuple ``(n, N)`` with the local and global sizes. m: int The number of columns. Notes ----- Either ``n`` or ``N`` (but not both) can be ``PETSc.DECIDE`` or ``None`` to have it automatically set. """ 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): """ Sets the local and global sizes, and the number of columns. Local and global sizes are specified indirectly by passing a template vector. Parameters ---------- w: Vec The template vector. m: int The number of columns. """ cdef PetscInt ival = asInt(m) CHKERR( BVSetSizesFromVec(self.bv, w.vec, ival) ) def getSizes(self): """ Returns the local and global sizes, and the number of columns. Returns ------- sizes: two-tuple of int The local and global sizes ``(n, N)``. m: int The number of columns. """ 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): """ Sets the leading dimension. Parameters ---------- ld: int The leading dimension. """ cdef PetscInt val = asInt(ld) CHKERR( BVSetLeadingDimension(self.bv, val) ) def getLeadingDimension(self): """ Gets the leading dimension. Returns ------- ld: int The leading dimension. """ cdef PetscInt val = 0 CHKERR( BVGetLeadingDimension(self.bv, &val) ) return toInt(val) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all BV options in the database. Parameters ---------- prefix: string 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. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( BVSetOptionsPrefix(self.bv, cval) ) def getOptionsPrefix(self): """ Gets the prefix used for searching for all BV options in the database. Returns ------- prefix: string The prefix string set for this BV object. """ cdef const char *prefix = NULL CHKERR( BVGetOptionsPrefix(self.bv, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ Sets BV options from the options database. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( BVSetFromOptions(self.bv) ) # def getOrthogonalization(self): """ Gets the orthogonalization settings from the BV object. Returns ------- type: `BV.OrthogType` enumerate The type of orthogonalization technique. refine: `BV.OrthogRefineType` enumerate The type of refinement. eta: float Parameter for selective refinement (used when the refinement type is `BV.OrthogRefineType.IFNEEDED`). block: `BV.OrthogBlockType` enumerate The type of block orthogonalization . """ 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=None, refine=None, eta=None, block=None): """ Specifies the method used for the orthogonalization 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: `BV.OrthogType` enumerate, optional The type of orthogonalization technique. refine: `BV.OrthogRefineType` enumerate, optional The type of refinement. eta: float, optional Parameter for selective refinement. block: `BV.OrthogBlockType` enumerate, optional 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 `DEFAULT`). The value of `eta` is used only when the refinement type is `BV.OrthogRefineType.IFNEEDED`. When using several processors, `BV.OrthogType.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. """ 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) ) 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): """ Gets the method used for the `matMult()` operation. Returns ------- method: `BV.MatMultType` enumerate The method for the `matMult()` operation. """ cdef SlepcBVMatMultType val = BV_MATMULT_MAT CHKERR( BVGetMatMultMethod(self.bv, &val) ) return val def setMatMultMethod(self, method): """ Specifies the method used for the `matMult()` operation. Parameters ---------- method: `BV.MatMultType` enumerate The method for the `matMult()` operation. """ cdef SlepcBVMatMultType val = method CHKERR( BVSetMatMultMethod(self.bv, val) ) # def getMatrix(self): """ Retrieves the matrix representation of the inner product. Returns ------- mat: the matrix of the inner product """ cdef Mat mat = Mat() cdef PetscBool indef = PETSC_FALSE CHKERR( BVGetMatrix(self.bv, &mat.mat, &indef) ) CHKERR( PetscINCREF(mat.obj) ) return (mat, toBool(indef)) def setMatrix(self, Mat mat or None, bint indef): """ Sets the bilinear form to be used for inner products. Parameters ---------- mat: Mat or None The matrix of the inner product. indef: bool, optional Whether the matrix is indefinite """ cdef PetscMat m = NULL if mat is None else mat.mat cdef PetscBool tval = PETSC_TRUE if indef else PETSC_FALSE CHKERR( BVSetMatrix(self.bv, m, tval) ) def applyMatrix(self, Vec x, Vec y): """ Multiplies a vector with the matrix associated to the bilinear form. Parameters ---------- x: Vec The input vector. y: Vec The result vector. Notes ----- If the bilinear form has no associated matrix this function copies the vector. """ CHKERR( BVApplyMatrix(self.bv, x.vec, y.vec) ) def setActiveColumns(self, l, k): """ Specify the columns that will be involved in operations. Parameters ---------- l: int The leading number of columns. k: int The active number of columns. """ cdef PetscInt ival1 = asInt(l) cdef PetscInt ival2 = asInt(k) CHKERR( BVSetActiveColumns(self.bv, ival1, ival2) ) def getActiveColumns(self): """ Returns the current active dimensions. Returns ------- l: int The leading number of columns. k: int The active number of columns. """ cdef PetscInt l=0, k=0 CHKERR( BVGetActiveColumns(self.bv, &l, &k) ) return (toInt(l), toInt(k)) def scaleColumn(self, j, alpha): """ Scale column j by alpha Parameters ---------- j: int column number to be scaled. alpha: float scaling factor. """ cdef PetscInt ival = asInt(j) cdef PetscScalar sval = asScalar(alpha) CHKERR( BVScaleColumn(self.bv, ival, sval) ) def scale(self, alpha): """ Multiply the entries by a scalar value. Parameters ---------- alpha: float scaling factor. Notes ----- All active columns (except the leading ones) are scaled. """ cdef PetscScalar sval = asScalar(alpha) CHKERR( BVScale(self.bv, sval) ) def insertVec(self, j, Vec w): """ Insert a vector into the specified column. Parameters ---------- j: int The column to be overwritten. w: Vec The vector to be copied. """ cdef PetscInt ival = asInt(j) CHKERR( BVInsertVec(self.bv, ival, w.vec) ) def insertVecs(self, s, W, bint orth): """ Insert a set of vectors into specified columns. Parameters ---------- s: int The first column to be overwritten. W: Vec or sequence of Vec. Set of vectors to be copied. orth: Flag indicating if the vectors must be orthogonalized. Returns ------- m: int Number of linearly independent vectors. Notes ----- Copies the contents of vectors W into self(:,s:s+n), where n is the length of W. If orthogonalization flag is set then the vectors are copied one by one then orthogonalized against the previous one. If any are linearly dependent then it is discared and the value of m is decreased. """ 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): """ Insert a set of vectors as constraints. Parameters ---------- C: Vec or sequence of Vec. Set of vectors to be inserted as constraints. Returns ------- nc: int Number of linearly independent vectors. 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. """ 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): """ Sets the number of constraints. Parameters ---------- nc: int The number of constraints. """ cdef PetscInt val = asInt(nc) CHKERR( BVSetNumConstraints(self.bv, val) ) def getNumConstraints(self): """ Gets the number of constraints. Returns ------- nc: int The number of constraints. """ cdef PetscInt val = 0 CHKERR( BVGetNumConstraints(self.bv, &val) ) return toInt(val) def createVec(self): """ Creates a new Vec object with the same type and dimensions as the columns of the basis vectors object. Returns ------- v: Vec New vector. """ cdef Vec v = Vec() CHKERR( BVCreateVec(self.bv, &v.vec) ) return v def setVecType(self, vec_type): """ Set the vector type. Parameters ---------- vec_type Vector type used when creating vectors with `createVec`. """ cdef PetscVecType cval = NULL vec_type = str2bytes(vec_type, &cval) CHKERR( BVSetVecType(self.bv, cval) ) def getVecType(self): """ Return the vector type used by the basis vectors object. """ cdef PetscVecType cval = NULL CHKERR( BVGetVecType(self.bv, &cval) ) return bytes2str(cval) def copyVec(self, j, Vec v): """ Copies one of the columns of a basis vectors object into a Vec. Parameters ---------- j: int The column number to be copied. v: Vec A vector. """ cdef PetscInt ival = asInt(j) CHKERR( BVCopyVec(self.bv, ival, v.vec) ) def copyColumn(self, j, i): """ Copies the values from one of the columns to another one. Parameters ---------- j: int The number of the source column. i: int The number of the destination column. """ cdef PetscInt ival1 = asInt(j) cdef PetscInt ival2 = asInt(i) CHKERR( BVCopyColumn(self.bv, ival1, ival2) ) def setDefiniteTolerance(self, deftol): """ Sets the tolerance to be used when checking a definite inner product. Parameters ---------- deftol: float The tolerance. """ cdef PetscReal val = asReal(deftol) CHKERR( BVSetDefiniteTolerance(self.bv, val) ) def getDefiniteTolerance(self): """ Gets the tolerance to be used when checking a definite inner product. Returns ------- deftol: float The tolerance. """ cdef PetscReal val = 0 CHKERR( BVGetDefiniteTolerance(self.bv, &val) ) return toReal(val) def dotVec(self, Vec v): """ Computes multiple dot products of a vector against all the column vectors of a BV. Parameters ---------- v: Vec A vector. Returns ------- m: array of scalars The computed values. Notes ----- This is analogue to VecMDot(), but using BV to represent a collection of vectors. The result is m = X^H*y, so m_i is equal to x_j^H y. Note that here X is transposed as opposed to BVDot(). If a non-standard inner product has been specified with BVSetMatrix(), then the result is m = X^H*B*y. """ 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): """ Computes multiple dot products of a column against all the column vectors of a BV. Parameters ---------- j: int The index of the column. Returns ------- m: array of scalars The computed values. """ 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): """ Returns a Vec object that contains the entries of the requested column of the basis vectors object. Parameters ---------- j: int The index of the requested column. Returns ------- v: Vec The vector containing the jth column. Notes ----- Modifying the returned Vec will change the BV entries as well. """ 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, Vec v): """ Restore a column obtained with `getColumn()`. Parameters ---------- j: int The index of the requested column. v: Vec The vector obtained with `getColumn()`. Notes ----- The arguments must match the corresponding call to `getColumn()`. """ cdef PetscInt ival = asInt(j) CHKERR( PetscObjectDereference(v.vec) ) CHKERR( BVRestoreColumn(self.bv, ival, &v.vec) ) def getMat(self): """ Returns a Mat object of dense type that shares the memory of the basis vectors object. Returns ------- A: Mat The matrix Notes ----- The returned matrix contains only the active columns. If the content of the Mat is modified, these changes are also done in the BV object. The user must call `restoreMat()` when no longer needed. """ cdef Mat A = Mat() CHKERR( BVGetMat(self.bv, &A.mat) ) CHKERR( PetscINCREF(A.obj) ) return A def restoreMat(self, Mat A): """ Restores the Mat obtained with `getMat()`. Parameters ---------- A: Mat 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 Mat are copied back to the BV internal data structures. """ CHKERR( PetscObjectDereference(A.mat) ) CHKERR( BVRestoreMat(self.bv, &A.mat) ) def dot(self, BV Y): """ Computes the 'block-dot' product of two basis vectors objects. M = Y^H*X (m_ij = y_i^H x_j) or M = Y^H*B*X Parameters ---------- Y: BV Left basis vectors, can be the same as self, giving M = X^H X. Returns ------- M: Mat The resulting matrix. Notes ----- This is the generalization of VecDot() for a collection of vectors, M = Y^H*X. The result is a matrix M whose entry m_ij is equal to y_i^H x_j (where y_i^H denotes the conjugate transpose of y_i). X and Y can be the same object. If a non-standard inner product has been specified with setMatrix(), then the result is M = Y^H*B*X. In this case, both X and Y must have the same associated matrix. Only rows (resp. columns) of M starting from ly (resp. lx) are computed, where ly (resp. lx) is the number of leading columns of Y (resp. X). """ 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 or None, BV Y): """ Computes the projection of a matrix onto a subspace. M = Y^H A X Parameters ---------- A: Mat or None Matrix to be projected. Y: BV Left basis vectors, can be the same as self, giving M = X^H A X. Returns ------- M: Mat Projection of the matrix A onto the subspace. """ 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): """ Computes the matrix-vector product for each column, Y = A*V. Parameters ---------- A: Mat The matrix. Returns ------- Y: BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. It is possible to choose whether the computation is done column by column or using dense matrices using the options database keys: -bv_matmult_vecs -bv_matmult_mat The default is bv_matmult_mat. """ 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 matMultHermitianTranspose(self, Mat A, BV Y=None): """ Computes the matrix-vector product with the conjugate transpose of a matrix for each column, Y=A^H*V. Parameters ---------- A: Mat The matrix. Returns ------- Y: BV The result. Notes ----- Only active columns (excluding the leading ones) are processed. As opoosed to matMult(), this operation is always done by column by column, with a sequence of calls to MatMultHermitianTranspose(). """ 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): """ Computes the matrix-vector product for a specified column, storing the result in the next column: v_{j+1}=A*v_j. Parameters ---------- A: Mat The matrix. j: int Index of column. """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultColumn(self.bv, A.mat, ival) ) def matMultTransposeColumn(self, Mat A, j): """ Computes the transpose matrix-vector product for a specified column, storing the result in the next column: v_{j+1}=A^T*v_j. Parameters ---------- A: Mat The matrix. j: int Index of column. """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultTransposeColumn(self.bv, A.mat, ival) ) def matMultHermitianTransposeColumn(self, Mat A, j): """ Computes the conjugate-transpose matrix-vector product for a specified column, storing the result in the next column: v_{j+1}=A^H*v_j. Parameters ---------- A: Mat The matrix. j: int Index of column. """ cdef PetscInt ival = asInt(j) CHKERR( BVMatMultHermitianTransposeColumn(self.bv, A.mat, ival) ) def mult(self, alpha, beta, BV X, Mat Q): """ Computes Y = beta*Y + alpha*X*Q. Parameters ---------- alpha: scalar Coefficient that multiplies X. beta: scalar Coefficient that multiplies Y. X: BV Input basis vectors. Q: Mat, optional Input matrix, if not given the identity matrix is assumed. """ cdef PetscScalar sval1 = asScalar(alpha) cdef PetscScalar sval2 = asScalar(beta) 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, e): """ Update a set of vectors as V(:,s:e-1) = V*Q(:,s:e-1). Parameters ---------- Q: Mat A sequential dense matrix. s: int First column to be overwritten. e: int Last column to be overwritten. """ cdef PetscInt ival1 = asInt(s) cdef PetscInt ival2 = asInt(e) CHKERR( BVMultInPlace(self.bv, Q.mat, ival1, ival2) ) def multColumn(self, alpha, beta, j, q): """ Computes y = beta*y + alpha*X*q, where y is the j-th column. Parameters ---------- alpha: scalar Coefficient that multiplies X. beta: scalar Coefficient that multiplies y. j: int The column index. q: Array of scalar Input coefficients. """ cdef PetscScalar sval1 = asScalar(alpha) cdef PetscScalar sval2 = asScalar(beta) 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, alpha, beta, Vec y, q): """ Computes y = beta*y + alpha*X*q. Parameters ---------- alpha: scalar Coefficient that multiplies X. beta: scalar Coefficient that multiplies y. y: Vec Input/output vector. q: Array of scalar Input coefficients. """ cdef PetscScalar sval1 = asScalar(alpha) cdef PetscScalar sval2 = asScalar(beta) 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, int j, norm_type=None): """ Computes the matrix norm of the BV. Parameters ---------- j: int Index of column. norm_type: `PETSc.NormType` enumerate The norm type. Returns ------- norm: float Notes ----- The norm of V[j] is computed (NORM_1, NORM_2, or NORM_INFINITY). If a non-standard inner product has been specified with BVSetMatrix(), then the returned value is ``sqrt(V[j]'* B*V[j])``, where B is the inner product matrix (argument 'type' is ignored). """ 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=None): """ Computes the matrix norm of the BV. Parameters ---------- norm_type: `PETSC.NormType` enumerate The norm type. Returns ------- norm: float 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 BVSetMatrix(). """ 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, copy=True): """ Change the number of columns. Parameters ---------- m: int The new number of columns. copy: bool 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. """ cdef PetscInt ival = asInt(m) cdef PetscBool tval = PETSC_TRUE if copy else PETSC_FALSE CHKERR( BVResize(self.bv, ival, tval) ) def setRandom(self): """ Set the active columns of the BV to random numbers. Notes ----- All active columns (except the leading ones) are modified. """ CHKERR( BVSetRandom(self.bv) ) def setRandomNormal(self): """ Set the active columns of the BV to random numbers (with normal distribution). Notes ----- All active columns (except the leading ones) are modified. """ CHKERR( BVSetRandomNormal(self.bv) ) def setRandomSign(self): """ Set the entries of a BV to values 1 or -1 with equal probability. Notes ----- All active columns (except the leading ones) are modified. """ CHKERR( BVSetRandomSign(self.bv) ) def setRandomColumn(self, j): """ Set one column of the BV to random numbers. Parameters ---------- j: int Column number to be set. """ cdef PetscInt ival = asInt(j) CHKERR( BVSetRandomColumn(self.bv, ival) ) def setRandomCond(self, condn): """ Set the columns of a BV to random numbers, in a way that the generated matrix has a given condition number. Parameters ---------- condn: float Condition number. """ cdef PetscReal rval = asReal(condn) CHKERR( BVSetRandomCond(self.bv, rval) ) def setRandomContext(self, Random rnd): """ Sets the `PETSc.Random` object associated with the BV, to be used in operations that need random numbers. Parameters ---------- rnd: `PETSc.Random` The random number generator context. """ CHKERR( BVSetRandomContext(self.bv, rnd.rnd) ) def getRandomContext(self): """ Gets the `PETSc.Random` object associated with the BV. Returns ------- rnd: `PETSc.Random` The random number generator context. """ cdef Random rnd = Random() CHKERR( BVGetRandomContext(self.bv, &rnd.rnd) ) CHKERR( PetscINCREF(rnd.obj) ) return rnd def orthogonalizeVec(self, Vec v): """ Orthogonalize a vector with respect to a set of vectors. Parameters ---------- v: Vec 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 ``v`` onto the orthogonal complement of the span of the columns of the BV. This routine does not normalize the resulting vector. """ 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): """ Orthogonalize one of the column vectors with respect to the previous ones. Parameters ---------- j: int 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 ``V[j]`` onto the orthogonal complement of the span of the columns ``V[0..j-1]``, where ``V[.]`` are the vectors of the BV. The columns ``V[0..j-1]`` are assumed to be mutually orthonormal. This routine does not normalize the resulting vector. """ 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, replace=False): """ Orthonormalize one of the column vectors with respect to the previous ones. This is equivalent to a call to `orthogonalizeColumn()` followed by a call to `scaleColumn()` with the reciprocal of the norm. Parameters ---------- j: int Index of the column to be orthonormalized. replace: bool, optional 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. """ 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): """ Orthogonalize all columns (except leading ones), that is, compute the QR decomposition. Parameters ---------- R: Mat, optional A sequential dense matrix. Notes ----- The output satisfies ``V0 = V*R`` (where V0 represent the input V) and ``V'*V = I``. """ if kargs: self.setOrthogonalization(**kargs) cdef PetscMat Rmat = NULL if R is None else R.mat CHKERR( BVOrthogonalize(self.bv, Rmat) ) # ----------------------------------------------------------------------------- del BVType del BVOrthogType del BVOrthogRefineType del BVOrthogBlockType del BVMatMultType # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/CAPI.pyx000066400000000000000000000075651500534120000200640ustar00rootroot00000000000000# ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/DS.pyx000066400000000000000000000505301500534120000176440ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class DSType(object): """ DS type """ 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. """ 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. """ 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): """ DS parallel types - `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. """ REDUNDANT = DS_PARALLEL_REDUNDANT SYNCHRONIZED = DS_PARALLEL_SYNCHRONIZED DISTRIBUTED = DS_PARALLEL_DISTRIBUTED # ----------------------------------------------------------------------------- cdef class DS(Object): """ DS """ Type = DSType StateType = DSStateType MatType = DSMatType ParallelType = DSParallelType def __cinit__(self): self.obj = &self.ds self.ds = NULL def view(self, Viewer viewer=None): """ Prints the DS data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( DSView(self.ds, vwr) ) def destroy(self): """ Destroys the DS object. """ CHKERR( DSDestroy(&self.ds) ) self.ds = NULL return self def reset(self): """ Resets the DS object. """ CHKERR( DSReset(self.ds) ) def create(self, comm=None): """ Creates the DS object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Selects the type for the DS object. Parameters ---------- ds_type: `DS.Type` enumerate The direct solver type to be used. """ cdef SlepcDSType cval = NULL ds_type = str2bytes(ds_type, &cval) CHKERR( DSSetType(self.ds, cval) ) def getType(self): """ Gets the DS type of this object. Returns ------- type: `DS.Type` enumerate The direct solver type currently being used. """ cdef SlepcDSType ds_type = NULL CHKERR( DSGetType(self.ds, &ds_type) ) return bytes2str(ds_type) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all DS options in the database. Parameters ---------- prefix: string 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. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( DSSetOptionsPrefix(self.ds, cval) ) def getOptionsPrefix(self): """ Gets the prefix used for searching for all DS options in the database. Returns ------- prefix: string The prefix string set for this DS object. """ cdef const char *prefix = NULL CHKERR( DSGetOptionsPrefix(self.ds, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ Sets DS options from the options database. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( DSSetFromOptions(self.ds) ) def duplicate(self): """ Duplicate the DS object with the same type and dimensions. """ cdef DS ds = type(self)() CHKERR( DSDuplicate(self.ds, &ds.ds) ) return ds # def allocate(self, ld): """ Allocates memory for internal storage or matrices in DS. Parameters ---------- ld: int Leading dimension (maximum allowed dimension for the matrices, including the extra row if present). """ cdef PetscInt val = asInt(ld) CHKERR( DSAllocate(self.ds, val) ) def getLeadingDimension(self): """ Returns the leading dimension of the allocated matrices. Returns ------- ld: int Leading dimension (maximum allowed dimension for the matrices). """ cdef PetscInt val = 0 CHKERR( DSGetLeadingDimension(self.ds, &val) ) return toInt(val) def setState(self, state): """ Change the state of the DS object. Parameters ---------- state: `DS.StateType` enumerate 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. This function is normally used to return to the raw state when the condensed structure is destroyed. """ cdef SlepcDSStateType val = state CHKERR( DSSetState(self.ds, val) ) def getState(self): """ Returns the current state. Returns ------- state: `DS.StateType` enumerate The current state. """ cdef SlepcDSStateType val = DS_STATE_RAW CHKERR( DSGetState(self.ds, &val) ) return val def setParallel(self, pmode): """ Selects the mode of operation in parallel runs. Parameters ---------- pmode: `DS.ParallelType` enumerate The parallel mode. """ cdef SlepcDSParallelType val = pmode CHKERR( DSSetParallel(self.ds, val) ) def getParallel(self): """ Gets the mode of operation in parallel runs. Returns ------- pmode: `DS.ParallelType` enumerate The parallel mode. """ cdef SlepcDSParallelType val = DS_PARALLEL_REDUNDANT CHKERR( DSGetParallel(self.ds, &val) ) return val def setDimensions(self, n=None, l=None, k=None): """ Resize the matrices in the DS object. Parameters ---------- n: int, optional The new size. l: int, optional Number of locked (inactive) leading columns. k: int, optional Intermediate dimension (e.g., position of arrow). Notes ----- The internal arrays are not reallocated. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = 0 cdef PetscInt ival3 = 0 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): """ Returns the current dimensions. 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. """ 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): """ Selects the block size. Parameters ---------- bs: int The block size. """ cdef PetscInt val = bs CHKERR( DSSetBlockSize(self.ds, val) ) def getBlockSize(self): """ Gets the block size. Returns ------- bs: int The block size. """ cdef PetscInt val = 0 CHKERR( DSGetBlockSize(self.ds, &val) ) return val def setMethod(self, meth): """ Selects the method to be used to solve the problem. Parameters ---------- meth: int An index identifying the method. """ cdef PetscInt val = meth CHKERR( DSSetMethod(self.ds, val) ) def getMethod(self): """ Gets the method currently used in the DS. Returns ------- meth: int Identifier of the method. """ cdef PetscInt val = 0 CHKERR( DSGetMethod(self.ds, &val) ) return val def setCompact(self, comp): """ Switch to compact storage of matrices. Parameters ---------- comp: bool 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``. """ cdef PetscBool val = asBool(comp) CHKERR( DSSetCompact(self.ds, val) ) def getCompact(self): """ Gets the compact storage flag. Returns ------- comp: bool The flag. """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetCompact(self.ds, &val) ) return toBool(val) def setExtraRow(self, ext): """ Sets a flag to indicate that the matrix has one extra row. Parameters ---------- ext: bool 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 dimension (n+1)*n . If this flag is activated, all transformations applied to the right of the matrix also affect this additional row. In that case, (n+1) must be less or equal than the leading dimension. The default is ``False``. """ cdef PetscBool val = asBool(ext) CHKERR( DSSetExtraRow(self.ds, val) ) def getExtraRow(self): """ Gets the extra row flag. Returns ------- comp: bool The flag. """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetExtraRow(self.ds, &val) ) return toBool(val) def setRefined(self, ref): """ Sets a flag to indicate that refined vectors must be computed. Parameters ---------- ref: bool 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 At-theta*I, where At is the extended (n+1)xn matrix and theta is the Ritz value. This is used in the refined Ritz approximation. The default is ``False``. """ cdef PetscBool val = asBool(ref) CHKERR( DSSetRefined(self.ds, val) ) def getRefined(self): """ Gets the refined vectors flag. Returns ------- comp: bool The flag. """ cdef PetscBool val = PETSC_FALSE CHKERR( DSGetRefined(self.ds, &val) ) return toBool(val) def truncate(self, n, trim=False): """ Truncates the system represented in the DS object. Parameters ---------- n: int The new size. trim: bool, optional A flag to indicate if the factorization must be trimmed. """ cdef PetscInt val = asInt(n) cdef PetscBool flg = asBool(trim) CHKERR( DSTruncate(self.ds, val, flg) ) def updateExtraRow(self): """ Performs all necessary operations so that the extra row gets up-to-date after a call to `solve()`. """ CHKERR( DSUpdateExtraRow(self.ds) ) def getMat(self, matname): """ Returns the requested matrix as a sequential dense Mat object. Parameters ---------- matname: `DS.MatType` enumerate The requested matrix. """ 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, Mat mat): """ Restore the previously seized matrix. Parameters ---------- matname: `DS.MatType` enumerate The selected matrix. mat: Mat The matrix previously obtained with `getMat()`. """ cdef SlepcDSMatType mname = matname CHKERR( PetscObjectDereference(mat.mat) ) CHKERR( DSRestoreMat(self.ds, mname, &mat.mat) ) def setIdentity(self, matname): """ Copy the identity on the active part of a matrix. Parameters ---------- matname: `DS.MatType` enumerate The requested matrix. """ cdef SlepcDSMatType mname = matname CHKERR( DSSetIdentity(self.ds, mname) ) # def cond(self): """ Compute the inf-norm condition number of the first matrix. Returns ------- cond: real Condition number. """ cdef PetscReal rval = 0 CHKERR( DSCond(self.ds, &rval) ) return toReal(rval) # def setSVDDimensions(self, m): """ Sets the number of columns of a `DS` of type `SVD`. Parameters ---------- m: int The number of columns. """ cdef PetscInt val = asInt(m) CHKERR( DSSVDSetDimensions(self.ds, val) ) def getSVDDimensions(self): """ Gets the number of columns of a `DS` of type `SVD`. Returns ------- m: int The number of columns. """ cdef PetscInt val = 0 CHKERR( DSSVDGetDimensions(self.ds, &val) ) return toInt(val) def setHSVDDimensions(self, m): """ Sets the number of columns of a `DS` of type `HSVD`. Parameters ---------- m: int The number of columns. """ cdef PetscInt val = asInt(m) CHKERR( DSHSVDSetDimensions(self.ds, val) ) def getHSVDDimensions(self): """ Gets the number of columns of a `DS` of type `HSVD`. Returns ------- m: int The number of columns. """ cdef PetscInt val = 0 CHKERR( DSHSVDGetDimensions(self.ds, &val) ) return toInt(val) def setGSVDDimensions(self, m, p): """ Sets the number of columns and rows of a `DS` of type `GSVD`. Parameters ---------- m: int The number of columns. p: int The number of rows for the second matrix. """ cdef PetscInt val1 = asInt(m) cdef PetscInt val2 = asInt(p) CHKERR( DSGSVDSetDimensions(self.ds, val1, val2) ) def getGSVDDimensions(self): """ Gets the number of columns and rows of a `DS` of type `GSVD`. Returns ------- m: int The number of columns. p: int The number of rows for the second matrix. """ cdef PetscInt val1 = 0 cdef PetscInt val2 = 0 CHKERR( DSGSVDGetDimensions(self.ds, &val1, &val2) ) return (toInt(val1), toInt(val2)) def setPEPDegree(self, deg): """ Sets the polynomial degree of a `DS` of type `PEP`. Parameters ---------- deg: int The polynomial degree. """ cdef PetscInt val = asInt(deg) CHKERR( DSPEPSetDegree(self.ds, val) ) def getPEPDegree(self): """ Gets the polynomial degree of a `DS` of type `PEP`. Returns ------- deg: int The polynomial degree. """ cdef PetscInt val = 0 CHKERR( DSPEPGetDegree(self.ds, &val) ) return toInt(val) def setPEPCoefficients(self, pbc): """ Sets the polynomial basis coefficients of a `DS` of type `PEP`. Parameters ---------- pbc: array of float Coefficients. """ cdef PetscInt na = 0 cdef PetscReal *a = NULL cdef object tmp1 = iarray_r(pbc, &na, &a) CHKERR( DSPEPSetCoefficients(self.ds, a) ) def getPEPCoefficients(self): """ Gets the polynomial basis coefficients of a `DS` of type `PEP`. Returns ------- pbc: array of float Coefficients. """ 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: def __get__(self): return self.getState() def __set__(self, value): self.setState(value) property parallel: def __get__(self): return self.getParallel() def __set__(self, value): self.setParallel(value) property block_size: def __get__(self): return self.getBlockSize() def __set__(self, value): self.setBlockSize(value) property method: def __get__(self): return self.getMethod() def __set__(self, value): self.setMethod(value) property compact: def __get__(self): return self.getCompact() def __set__(self, value): self.setCompact(value) property extra_row: def __get__(self): return self.getExtraRow() def __set__(self, value): self.setExtraRow(value) property refined: def __get__(self): return self.getRefined() def __set__(self, value): self.setRefined(value) # ----------------------------------------------------------------------------- del DSType del DSStateType del DSMatType del DSParallelType # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/EPS.pyx000066400000000000000000002747561500534120000200070ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class EPSType(object): """ EPS type Native sparse eigensolvers. - `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. - `LAPACK`: Wrappers to dense eigensolvers in Lapack. Wrappers to external eigensolvers (should be enabled during installation of SLEPc) - `ARPACK`: - `TRLAN`: - `BLOPEX`: - `PRIMME`: - `FEAST`: - `SCALAPACK`: - `ELPA`: - `ELEMENTAL`: - `EVSL`: - `CHASE`: """ # provided implementations 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) # with external libraries ARPACK = S_(EPSARPACK) TRLAN = S_(EPSTRLAN) 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 ``B``. - `GHIEP`: Generalized Hermitian-indefinite eigenproblem. - `BSE`: Structured Bethe-Salpeter eigenproblem. """ HEP = EPS_HEP NHEP = EPS_NHEP GHEP = EPS_GHEP GNHEP = EPS_GNHEP PGNHEP = EPS_PGNHEP GHIEP = EPS_GHIEP BSE = EPS_BSE 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ RITZ = EPS_CISS_EXTRACTION_RITZ HANKEL = EPS_CISS_EXTRACTION_HANKEL # ----------------------------------------------------------------------------- cdef class EPS(Object): """ EPS """ Type = EPSType ProblemType = EPSProblemType Extraction = EPSExtraction Balance = EPSBalance ErrorType = EPSErrorType Which = EPSWhich Conv = EPSConv Stop = EPSStop ConvergedReason = EPSConvergedReason PowerShiftType = EPSPowerShiftType LanczosReorthogType = EPSLanczosReorthogType CISSQuadRule = EPSCISSQuadRule CISSExtraction = EPSCISSExtraction def __cinit__(self): self.obj = &self.eps self.eps = NULL def view(self, Viewer viewer=None): """ Prints the EPS data structure. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSView(self.eps, vwr) ) def destroy(self): """ Destroys the EPS object. """ CHKERR( EPSDestroy(&self.eps) ) self.eps = NULL return self def reset(self): """ Resets the EPS object. """ CHKERR( EPSReset(self.eps) ) def create(self, comm=None): """ Creates the EPS object. Parameters ---------- comm: MPI_Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Selects the particular solver to be used in the EPS object. Parameters ---------- eps_type: `EPS.Type` enumerate The solver to be used. Notes ----- See `EPS.Type` for available methods. The default is `EPS.Type.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. """ cdef SlepcEPSType cval = NULL eps_type = str2bytes(eps_type, &cval) CHKERR( EPSSetType(self.eps, cval) ) def getType(self): """ Gets the EPS type of this object. Returns ------- type: `EPS.Type` enumerate The solver currently being used. """ cdef SlepcEPSType eps_type = NULL CHKERR( EPSGetType(self.eps, &eps_type) ) return bytes2str(eps_type) def getOptionsPrefix(self): """ Gets the prefix used for searching for all EPS options in the database. Returns ------- prefix: string The prefix string set for this EPS object. """ cdef const char *prefix = NULL CHKERR( EPSGetOptionsPrefix(self.eps, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all EPS options in the database. Parameters ---------- prefix: string 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_") """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( EPSSetOptionsPrefix(self.eps, cval) ) def appendOptionsPrefix(self, prefix): """ Appends to the prefix used for searching for all EPS options in the database. Parameters ---------- prefix: string The prefix string to prepend to all EPS option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( EPSAppendOptionsPrefix(self.eps, cval) ) def setFromOptions(self): """ Sets EPS options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( EPSSetFromOptions(self.eps) ) # def getProblemType(self): """ Gets the problem type from the EPS object. Returns ------- problem_type: `EPS.ProblemType` enumerate The problem type that was previously set. """ cdef SlepcEPSProblemType val = EPS_NHEP CHKERR( EPSGetProblemType(self.eps, &val) ) return val def setProblemType(self, problem_type): """ Specifies the type of the eigenvalue problem. Parameters ---------- problem_type: `EPS.ProblemType` enumerate The problem type to be set. Notes ----- Allowed values are: Hermitian (HEP), non-Hermitian (NHEP), generalized Hermitian (GHEP), generalized non-Hermitian (GNHEP), and generalized non-Hermitian with positive semi-definite B (PGNHEP). This function must be used to instruct SLEPc to exploit symmetry. 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. ``A=A^H``) or generalized Hermitian (i.e. ``A=A^H``, ``B=B^H``, and ``B`` positive definite) then it is recommended to set the problem type so that eigensolver can exploit these properties. """ cdef SlepcEPSProblemType val = problem_type CHKERR( EPSSetProblemType(self.eps, val) ) def isGeneralized(self): """ Tells whether the EPS object corresponds to a generalized eigenvalue problem. Returns ------- flag: bool True if two matrices were set with `setOperators()`. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsGeneralized(self.eps, &tval) ) return toBool(tval) def isHermitian(self): """ Tells whether the EPS object corresponds to a Hermitian eigenvalue problem. Returns ------- flag: bool True if the problem type set with `setProblemType()` was Hermitian. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsHermitian(self.eps, &tval) ) return toBool(tval) def isPositive(self): """ Tells whether the EPS object corresponds to an eigenvalue problem type that requires a positive (semi-) definite matrix B. Returns ------- flag: bool True if the problem type set with `setProblemType()` was positive. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsPositive(self.eps, &tval) ) return toBool(tval) def isStructured(self): """ Tells whether the EPS object corresponds to a structured eigenvalue problem. Returns ------- flag: bool True if the problem type set with `setProblemType()` was structured. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSIsStructured(self.eps, &tval) ) return toBool(tval) def getBalance(self): """ Gets the balancing type used by the EPS object, and the associated parameters. Returns ------- balance: `EPS.Balance` enumerate The balancing method iterations: int Number of iterations of the balancing algorithm cutoff: real Cutoff value """ 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=None, iterations=None, cutoff=None): """ Specifies the balancing technique to be employed by the eigensolver, and some parameters associated to it. Parameters ---------- balance: `EPS.Balance` enumerate The balancing method iterations: int Number of iterations of the balancing algorithm cutoff: real Cutoff value """ cdef SlepcEPSBalance val = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT cdef PetscReal rval = PETSC_DEFAULT if balance is not None: val = balance 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): """ Gets the extraction type used by the EPS object. Returns ------- extraction: `EPS.Extraction` enumerate The method of extraction. """ cdef SlepcEPSExtraction val = EPS_RITZ CHKERR( EPSGetExtraction(self.eps, &val) ) return val def setExtraction(self, extraction): """ Sets the extraction type used by the EPS object. Parameters ---------- extraction: `EPS.Extraction` enumerate The extraction method to be used by the solver. Notes ----- Not all eigensolvers support all types of extraction. See the SLEPc documentation for details. 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()`. """ cdef SlepcEPSExtraction val = extraction CHKERR( EPSSetExtraction(self.eps, val) ) def getWhichEigenpairs(self): """ Returns which portion of the spectrum is to be sought. Returns ------- which: `EPS.Which` enumerate The portion of the spectrum to be sought by the solver. """ cdef SlepcEPSWhich val = EPS_LARGEST_MAGNITUDE CHKERR( EPSGetWhichEigenpairs(self.eps, &val) ) return val def setWhichEigenpairs(self, which): """ Specifies which portion of the spectrum is to be sought. Parameters ---------- which: `EPS.Which` enumerate 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. """ cdef SlepcEPSWhich val = which CHKERR( EPSSetWhichEigenpairs(self.eps, val) ) def getThreshold(self): """ Gets the threshold used in the threshold stopping test. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. """ cdef PetscReal rval = 0 cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetThreshold(self.eps, &rval, &tval) ) return (toReal(rval), toBool(tval)) def setThreshold(self, thres, rel=False): """ Sets the threshold used in the threshold stopping test. Parameters ---------- thres: float The threshold. rel: bool, optional 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). """ cdef PetscReal rval = asReal(thres) cdef PetscBool tval = asBool(rel) CHKERR( EPSSetThreshold(self.eps, rval, tval) ) def getTarget(self): """ Gets the value of the target. Returns ------- target: float (real or complex) The value of the target. Notes ----- If the target was not set by the user, then zero is returned. """ cdef PetscScalar sval = 0 CHKERR( EPSGetTarget(self.eps, &sval) ) return toScalar(sval) def setTarget(self, target): """ Sets the value of the target. Parameters ---------- target: float (real or complex) 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()`. """ cdef PetscScalar sval = asScalar(target) CHKERR( EPSSetTarget(self.eps, sval) ) def getInterval(self): """ Gets the computational interval for spectrum slicing. 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. """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( EPSGetInterval(self.eps, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setInterval(self, inta, intb): """ Defines the computational interval for spectrum slicing. Parameters ---------- inta: float The left end of the interval. intb: float 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()`. """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( EPSSetInterval(self.eps, rval1, rval2) ) # def getTolerances(self): """ Gets the tolerance and maximum iteration count used by the default EPS convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( EPSGetTolerances(self.eps, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol=None, max_it=None): """ Sets the tolerance and maximum iteration count used by the default EPS convergence tests. Parameters ---------- tol: float, optional The convergence tolerance. max_it: int, optional The maximum number of iterations Notes ----- Use `DECIDE` for maxits to assign a reasonably good value, which is dependent on the solution method. """ 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( EPSSetTolerances(self.eps, rval, ival) ) def getTwoSided(self): """ Returns the flag indicating whether a two-sided variant of the algorithm is being used or not. Returns ------- twosided: bool Whether the two-sided variant is to be used or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTwoSided(self.eps, &tval) ) return toBool(tval) def setTwoSided(self, twosided): """ Sets the solver to use a two-sided variant so that left eigenvectors are also computed. Parameters ---------- twosided: bool Whether the two-sided variant is to be used or not. """ cdef PetscBool tval = asBool(twosided) CHKERR( EPSSetTwoSided(self.eps, tval) ) def getPurify(self): """ Returns the flag indicating whether purification is activated or not. Returns ------- purify: bool Whether purification is activated or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetPurify(self.eps, &tval) ) return toBool(tval) def setPurify(self, purify=True): """ Activate or deactivate eigenvector purification. Parameters ---------- purify: bool, optional True to activate purification (default). """ cdef PetscBool tval = asBool(purify) CHKERR( EPSSetPurify(self.eps, tval) ) def getConvergenceTest(self): """ Return the method used to compute the error estimate used in the convergence test. Returns ------- conv: EPS.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcEPSConv conv = EPS_CONV_REL CHKERR( EPSGetConvergenceTest(self.eps, &conv) ) return conv def setConvergenceTest(self, conv): """ Specifies how to compute the error estimate used in the convergence test. Parameters ---------- conv: EPS.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcEPSConv tconv = conv CHKERR( EPSSetConvergenceTest(self.eps, tconv) ) def getTrueResidual(self): """ Returns the flag indicating whether true residual must be computed explicitly or not. Returns ------- trueres: bool Whether the solver compute all residuals or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTrueResidual(self.eps, &tval) ) return toBool(tval) def setTrueResidual(self, trueres): """ Specifies if the solver must compute the true residual explicitly or not. Parameters ---------- trueres: bool Whether compute the true residual or not. """ cdef PetscBool tval = asBool(trueres) CHKERR( EPSSetTrueResidual(self.eps, tval) ) def getTrackAll(self): """ Returns the flag indicating whether all residual norms must be computed or not. Returns ------- trackall: bool Whether the solver compute all residuals or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGetTrackAll(self.eps, &tval) ) return toBool(tval) def setTrackAll(self, trackall): """ Specifies if the solver must compute the residual of all approximate eigenpairs or not. Parameters ---------- trackall: bool Whether compute all residuals or not. """ cdef PetscBool tval = asBool(trackall) CHKERR( EPSSetTrackAll(self.eps, tval) ) def getDimensions(self): """ Gets 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. """ 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=None, ncv=None, mpd=None): """ Sets the number of eigenvalues to compute and the dimension of the subspace. Parameters ---------- nev: int, optional Number of eigenvalues to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. Notes ----- Use `DECIDE` 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. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Obtain the spectral transformation (`ST`) object associated to the eigensolver object. Returns ------- st: ST The spectral transformation. """ cdef ST st = ST() CHKERR( EPSGetST(self.eps, &st.st) ) CHKERR( PetscINCREF(st.obj) ) return st def setST(self, ST st): """ Associates a spectral transformation object to the eigensolver. Parameters ---------- st: ST The spectral transformation. """ CHKERR( EPSSetST(self.eps, st.st) ) def getBV(self): """ Obtain the basis vector objects associated to the eigensolver. Returns ------- bv: BV The basis vectors context. """ cdef BV bv = BV() CHKERR( EPSGetBV(self.eps, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv): """ Associates a basis vectors object to the eigensolver. Parameters ---------- bv: BV The basis vectors context. """ CHKERR( EPSSetBV(self.eps, bv.bv) ) def getDS(self): """ Obtain the direct solver associated to the eigensolver. Returns ------- ds: DS The direct solver context. """ cdef DS ds = DS() CHKERR( EPSGetDS(self.eps, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds): """ Associates a direct solver object to the eigensolver. Parameters ---------- ds: DS The direct solver context. """ CHKERR( EPSSetDS(self.eps, ds.ds) ) def getRG(self): """ Obtain the region object associated to the eigensolver. Returns ------- rg: RG The region context. """ cdef RG rg = RG() CHKERR( EPSGetRG(self.eps, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg): """ Associates a region object to the eigensolver. Parameters ---------- rg: RG The region context. """ CHKERR( EPSSetRG(self.eps, rg.rg) ) def getOperators(self): """ Gets the matrices associated with the eigenvalue problem. Returns ------- A: Mat The matrix associated with the eigensystem. B: Mat The second matrix in the case of generalized eigenproblems. """ 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): """ Sets the matrices associated with the eigenvalue problem. Parameters ---------- A: Mat The matrix associated with the eigensystem. B: Mat, optional The second matrix in the case of generalized eigenproblems; if not provided, a standard eigenproblem is assumed. """ cdef PetscMat Bmat = B.mat if B is not None else NULL CHKERR( EPSSetOperators(self.eps, A.mat, Bmat) ) def setDeflationSpace(self, space): """ Add vectors to the basis of the deflation space. Parameters ---------- space: a Vec or an array of Vec Set of basis vectors to be added to 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). The vectors do not need to be mutually orthonormal, since they are explicitly orthonormalized internally. These vectors do not persist from one `solve()` call to the other, so the deflation space should be set every time. """ 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): """ Sets the initial space from which the eigensolver starts to iterate. Parameters ---------- space: Vec or sequence of Vec The initial space Notes ----- Some solvers start to iterate on a single vector (initial vector). In that case, the other vectors are ignored. In contrast to `setDeflationSpace()`, 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. """ 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): """ Sets the left initial space from which the eigensolver starts to iterate. Parameters ---------- space: Vec or sequence of Vec 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. """ 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, args=None, kargs=None): """ Sets a function to decide when to stop the outer iteration of the eigensolver. """ 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): """ Gets the stopping function. """ return self.get_attr('__stopping__') # def setArbitrarySelection(self, arbitrary, args=None, kargs=None): """ Sets 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. """ 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 setEigenvalueComparison(self, comparison, args=None, kargs=None): """ Specifies the eigenvalue comparison function when `setWhichEigenpairs()` is set to `EPS.Which.USER`. """ 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 setMonitor(self, monitor, args=None, kargs=None): """ Appends a monitor function to the list of monitors. """ 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): """ Gets the list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self): """ Clears all monitors for an `EPS` object. """ CHKERR( EPSMonitorCancel(self.eps) ) self.set_attr('__monitor__', None) # def setUp(self): """ Sets up all the internal data structures necessary for the execution of the eigensolver. Notes ----- 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. """ CHKERR( EPSSetUp(self.eps) ) def solve(self): """ Solves the eigensystem. """ CHKERR( EPSSolve(self.eps) ) def getIterationNumber(self): """ Gets 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 ------- its: int Iteration number. """ cdef PetscInt ival = 0 CHKERR( EPSGetIterationNumber(self.eps, &ival) ) return toInt(ival) def getConvergedReason(self): """ Gets the reason why the `solve()` iteration was stopped. Returns ------- reason: `EPS.ConvergedReason` enumerate Negative value indicates diverged, positive value converged. """ cdef SlepcEPSConvergedReason val = EPS_CONVERGED_ITERATING CHKERR( EPSGetConvergedReason(self.eps, &val) ) return val def getConverged(self): """ Gets the number of converged eigenpairs. Returns ------- nconv: int Number of converged eigenpairs. Notes ----- This function should be called after `solve()` has finished. """ cdef PetscInt ival = 0 CHKERR( EPSGetConverged(self.eps, &ival) ) return toInt(ival) def getEigenvalue(self, int i): """ Gets the i-th eigenvalue as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. Returns ------- e: float | complex 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()`. """ 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, int i, Vec Vr, Vec Vi=None): """ Gets the i-th eigenvector as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. Vr: Vec Placeholder for the returned eigenvector (real part). Vi: Vec, optional 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()`. """ cdef PetscVec vecr = Vr.vec cdef PetscVec veci = Vi.vec if Vi is not None else NULL CHKERR( EPSGetEigenvector(self.eps, i, vecr, veci) ) def getLeftEigenvector(self, int i, Vec Wr, Vec Wi=None): """ Gets the i-th left eigenvector as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. Wr: Vec Placeholder for the returned eigenvector (real part). Wi: Vec, optional 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()`. """ cdef PetscVec vecr = Wr.vec cdef PetscVec veci = Wi.vec if Wi is not None else NULL CHKERR( EPSGetLeftEigenvector(self.eps, i, vecr, veci) ) def getEigenpair(self, int i, Vec Vr=None, Vec Vi=None): """ Gets the i-th solution of the eigenproblem as computed by `solve()`. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i: int Index of the solution to be obtained. Vr: Vec, optional Placeholder for the returned eigenvector (real part). Vi: Vec, optional Placeholder for the returned eigenvector (imaginary part). Returns ------- e: float | complex 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()`. """ 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): """ Gets an orthonormal basis of the computed invariant subspace. Returns ------- subspace: list of 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 ``X`` of ``A` satisfies ``A x`` in ``X`` for all ``x`` in ``X`` (a similar definition applies for generalized eigenproblems). """ 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, int i): """ Returns the error estimate associated to the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. Returns ------- e: real Error estimate. Notes ----- This is the error estimate used internally by the eigensolver. The actual error bound can be computed with `computeError()`. """ cdef PetscReal rval = 0 CHKERR( EPSGetErrorEstimate(self.eps, i, &rval) ) return toReal(rval) def computeError(self, int i, etype=None): """ Computes the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. etype: `EPS.ErrorType` enumerate The error type to compute. Returns ------- e: real The error bound, computed in various ways from the residual norm ``||Ax-kBx||_2`` where ``k`` is the eigenvalue and ``x`` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). """ 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=None, Viewer viewer=None): """ Displays the errors associated with the computed solution (as well as the eigenvalues). Parameters ---------- etype: `EPS.ErrorType` enumerate, optional The error type to compute. viewer: Viewer, optional. 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. """ 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): """ Displays the computed eigenvalues in a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSValuesView(self.eps, vwr) ) def vectorsView(self, Viewer viewer=None): """ Outputs computed eigenvectors to a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( EPSVectorsView(self.eps, vwr) ) # def setPowerShiftType(self, shift): """ Sets the type of shifts used during the power iteration. This can be used to emulate the Rayleigh Quotient Iteration (RQI) method. Parameters ---------- shift: `EPS.PowerShiftType` enumerate 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. """ cdef SlepcEPSPowerShiftType val = shift CHKERR( EPSPowerSetShiftType(self.eps, val) ) def getPowerShiftType(self): """ Gets the type of shifts used during the power iteration. Returns ------- shift: `EPS.PowerShiftType` enumerate The type of shift. """ cdef SlepcEPSPowerShiftType val = EPS_POWER_SHIFT_CONSTANT CHKERR( EPSPowerGetShiftType(self.eps, &val) ) return val def setArnoldiDelayed(self, delayed): """ Activates or deactivates delayed reorthogonalization in the Arnoldi iteration. Parameters ---------- delayed: bool 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 less than the default algorithm. """ cdef PetscBool val = asBool(delayed) CHKERR( EPSArnoldiSetDelayed(self.eps, val) ) def getArnoldiDelayed(self): """ Gets the type of reorthogonalization used during the Arnoldi iteration. Returns ------- delayed: bool True if delayed reorthogonalization is to be used. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSArnoldiGetDelayed(self.eps, &tval) ) return toBool(tval) def setLanczosReorthogType(self, reorthog): """ Sets the type of reorthogonalization used during the Lanczos iteration. Parameters ---------- reorthog: `EPS.LanczosReorthogType` enumerate The type of reorthogonalization. Notes ----- This call is only relevant if the type was set to `EPS.Type.LANCZOS` with `setType()`. """ cdef SlepcEPSLanczosReorthogType val = reorthog CHKERR( EPSLanczosSetReorthog(self.eps, val) ) def getLanczosReorthogType(self): """ Gets the type of reorthogonalization used during the Lanczos iteration. Returns ------- reorthog: `EPS.LanczosReorthogType` enumerate The type of reorthogonalization. """ cdef SlepcEPSLanczosReorthogType val = \ EPS_LANCZOS_REORTHOG_LOCAL CHKERR( EPSLanczosGetReorthog(self.eps, &val) ) return val # def setKrylovSchurBSEType(self, bse): """ Sets the method to be used for BSE structured eigenproblems in the Krylov-Schur solver. Parameters ---------- bse: `EPS.KrylovSchurBSEType` enumerate 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()`. """ cdef SlepcEPSKrylovSchurBSEType val = bse CHKERR( EPSKrylovSchurSetBSEType(self.eps, val) ) def getKrylovSchurBSEType(self): """ Gets the method used for BSE structured eigenproblems in the Krylov-Schur solver. Returns ------- bse: `EPS.KrylovSchurBSEType` enumerate The BSE method. """ cdef SlepcEPSKrylovSchurBSEType val = EPS_KRYLOVSCHUR_BSE_SHAO CHKERR( EPSKrylovSchurGetBSEType(self.eps, &val) ) return val def setKrylovSchurRestart(self, keep): """ Sets the restart parameter for the Krylov-Schur method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( EPSKrylovSchurSetRestart(self.eps, val) ) def getKrylovSchurRestart(self): """ Gets the restart parameter used in the Krylov-Schur method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( EPSKrylovSchurGetRestart(self.eps, &val) ) return toReal(val) def setKrylovSchurLocking(self, lock): """ Choose between locking and non-locking variants of the Krylov-Schur method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( EPSKrylovSchurSetLocking(self.eps, val) ) def getKrylovSchurLocking(self): """ Gets the locking flag used in the Krylov-Schur method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSKrylovSchurGetLocking(self.eps, &tval) ) return toBool(tval) def setKrylovSchurPartitions(self, npart): """ Sets 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: int The number of partitions. Notes ----- 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. """ cdef PetscInt val = asInt(npart) CHKERR( EPSKrylovSchurSetPartitions(self.eps, val) ) def getKrylovSchurPartitions(self): """ Gets the number of partitions of the communicator in case of spectrum slicing. Returns ------- npart: int The number of partitions. """ cdef PetscInt val = 0 CHKERR( EPSKrylovSchurGetPartitions(self.eps, &val) ) return toInt(val) def setKrylovSchurDetectZeros(self, detect): """ Sets a flag to enforce detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect: bool True if zeros must checked for. Notes ----- 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. """ cdef PetscBool val = asBool(detect) CHKERR( EPSKrylovSchurSetDetectZeros(self.eps, val) ) def getKrylovSchurDetectZeros(self): """ Gets the flag that enforces zero detection in spectrum slicing. Returns ------- detect: bool The zero detection flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSKrylovSchurGetDetectZeros(self.eps, &tval) ) return toBool(tval) def setKrylovSchurDimensions(self, nev=None, ncv=None, mpd=None): """ Sets the dimensions used for each subsolve step in case of doing spectrum slicing for a computational interval. The meaning of the parameters is the same as in `setDimensions()`. Parameters ---------- nev: int, optional Number of eigenvalues to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Gets the dimensions used for each subsolve step in case of doing spectrum slicing for a computational interval. 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. """ 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): """ Gets information related to the case of doing spectrum slicing for a computational interval with multiple communicators. Returns ------- k: int Number of the subinterval for the calling process. n: int Number of eigenvalues found in the k-th subinterval. v: Vec A vector owned by processes in the subcommunicator with dimensions compatible for locally computed eigenvectors. Notes ----- This function is only available for spectrum slicing runs. The returned Vec should be destroyed by the user. """ 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, int i, Vec V): """ Gets the i-th eigenpair stored internally in the multi-communicator to which the calling process belongs. Parameters ---------- i: int Index of the solution to be obtained. V: Vec Placeholder for the returned eigenvector. Returns ------- e: scalar The computed eigenvalue. Notes ----- 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()`. """ 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): """ Gets the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Returns ------- A: Mat The matrix associated with the eigensystem. B: Mat The second matrix in the case of generalized eigenproblems. Notes ----- 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. """ cdef Mat A = Mat() cdef Mat B = Mat() CHKERR( EPSKrylovSchurGetSubcommMats(self.eps, &A.mat, &B.mat) ) CHKERR( PetscINCREF(A.obj) ) CHKERR( PetscINCREF(B.obj) ) return (A, B) def updateKrylovSchurSubcommMats(self, s=1.0, a=1.0, Mat Au=None, t=1.0, b=1.0, Mat Bu=None, structure=None, globalup=False): """ Update the eigenproblem matrices stored internally in the subcommunicator to which the calling process belongs. Parameters ---------- s: float (real or complex) Scalar that multiplies the existing A matrix. a: float (real or complex) Scalar used in the axpy operation on A. Au: Mat, optional The matrix used in the axpy operation on A. t: float (real or complex) Scalar that multiplies the existing B matrix. b: float (real or complex) Scalar used in the axpy operation on B. Bu: Mat, optional The matrix used in the axpy operation on B. structure: `PETSc.Mat.Structure` enumerate Either same, different, or a subset of the non-zero sparsity pattern. globalup: bool Whether global matrices must be updated or not. Notes ----- This function modifies the eigenproblem matrices at subcommunicator level, and optionally updates the global matrices in the parent communicator. The updates are expressed as ``A <-- s*A + a*Au``, ``B <-- 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 `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. """ 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): """ Sets the subinterval boundaries for spectrum slicing with a computational interval. Parameters ---------- subint: list of float Real values specifying subintervals Notes ----- 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 EPSSetInterval(). The subintervals are then defined by two consecutive points: [subint_0,subint_1], [subint_1,subint_2], and so on. """ 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): """ Returns the points that delimit the subintervals used in spectrum slicing with several partitions. Returns ------- subint: list of float Real values specifying subintervals """ 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): """ Gets the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: list of float The values of the shifts used internally in the solver. inertias: list of int The values of the inertia in each shift. """ 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): """ Retrieve the linear solver object associated with the internal `EPS` object in case of doing spectrum slicing for a computational interval. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( EPSKrylovSchurGetKSP(self.eps, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setGDKrylovStart(self, krylovstart=True): """ Activates or deactivates starting the search subspace with a Krylov basis. Parameters ---------- krylovstart: bool True if starting the search subspace with a Krylov basis. """ cdef PetscBool val = asBool(krylovstart) CHKERR( EPSGDSetKrylovStart(self.eps, val) ) def getGDKrylovStart(self): """ Gets a flag indicating if the search subspace is started with a Krylov basis. Returns ------- krylovstart: bool True if starting the search subspace with a Krylov basis. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetKrylovStart(self.eps, &tval) ) return toBool(tval) def setGDBlockSize(self, bs): """ Sets the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs: int The number of vectors added to the search space in every iteration. """ cdef PetscInt ival = asInt(bs) CHKERR( EPSGDSetBlockSize(self.eps, ival) ) def getGDBlockSize(self): """ Gets the number of vectors to be added to the searching space in every iteration. Returns ------- bs: int The number of vectors added to the search space in every iteration. """ cdef PetscInt ival = 0 CHKERR( EPSGDGetBlockSize(self.eps, &ival) ) return toInt(ival) def setGDRestart(self, minv=None, plusk=None): """ Sets the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv: int, optional The number of vectors of the search subspace after restart. plusk: int, optional The number of vectors saved from the previous iteration. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT 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): """ Gets 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. """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSGDGetRestart(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setGDInitialSize(self, initialsize): """ Sets the initial size of the searching space. Parameters ---------- initialsize: int The number of vectors of the initial searching subspace. """ cdef PetscInt ival = asInt(initialsize) CHKERR( EPSGDSetInitialSize(self.eps, ival) ) def getGDInitialSize(self): """ Gets the initial size of the searching space. Returns ------- initialsize: int The number of vectors of the initial searching subspace. """ cdef PetscInt ival = 0 CHKERR( EPSGDGetInitialSize(self.eps, &ival) ) return toInt(ival) def setGDBOrth(self, borth): """ Selects the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth: bool Whether to B-orthogonalize the search subspace. """ cdef PetscBool tval = asBool(borth) CHKERR( EPSGDSetBOrth(self.eps, tval) ) def getGDBOrth(self): """ Returns the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- borth: bool Whether to B-orthogonalize the search subspace. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetBOrth(self.eps, &tval) ) return toBool(tval) def setGDDoubleExpansion(self, doubleexp): """ Activate a variant where the search subspace is expanded with K*[A*x B*x] (double expansion) instead of the classic K*r, where K is the preconditioner, x the selected approximate eigenvector and r its associated residual vector. Parameters ---------- doubleexp: bool True if using double expansion. """ cdef PetscBool val = asBool(doubleexp) CHKERR( EPSGDSetDoubleExpansion(self.eps, val) ) def getGDDoubleExpansion(self): """ Gets a flag indicating whether the double expansion variant has been activated or not. Returns ------- doubleexp: bool True if using double expansion. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSGDGetDoubleExpansion(self.eps, &tval) ) return toBool(tval) # def setJDKrylovStart(self, krylovstart=True): """ Activates or deactivates starting the search subspace with a Krylov basis. Parameters ---------- krylovstart: bool True if starting the search subspace with a Krylov basis. """ cdef PetscBool val = asBool(krylovstart) CHKERR( EPSJDSetKrylovStart(self.eps, val) ) def getJDKrylovStart(self): """ Gets a flag indicating if the search subspace is started with a Krylov basis. Returns ------- krylovstart: bool True if starting the search subspace with a Krylov basis. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetKrylovStart(self.eps, &tval) ) return toBool(tval) def setJDBlockSize(self, bs): """ Sets the number of vectors to be added to the searching space in every iteration. Parameters ---------- bs: int The number of vectors added to the search space in every iteration. """ cdef PetscInt ival = asInt(bs) CHKERR( EPSJDSetBlockSize(self.eps, ival) ) def getJDBlockSize(self): """ Gets the number of vectors to be added to the searching space in every iteration. Returns ------- bs: int The number of vectors added to the search space in every iteration. """ cdef PetscInt ival = 0 CHKERR( EPSJDGetBlockSize(self.eps, &ival) ) return toInt(ival) def setJDRestart(self, minv=None, plusk=None): """ Sets the number of vectors of the search space after restart and the number of vectors saved from the previous iteration. Parameters ---------- minv: int, optional The number of vectors of the search subspace after restart. plusk: int, optional The number of vectors saved from the previous iteration. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT 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): """ Gets 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. """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSJDGetRestart(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setJDInitialSize(self, initialsize): """ Sets the initial size of the searching space. Parameters ---------- initialsize: int The number of vectors of the initial searching subspace. """ cdef PetscInt ival = asInt(initialsize) CHKERR( EPSJDSetInitialSize(self.eps, ival) ) def getJDInitialSize(self): """ Gets the initial size of the searching space. Returns ------- initialsize: int The number of vectors of the initial searching subspace. """ cdef PetscInt ival = 0 CHKERR( EPSJDGetInitialSize(self.eps, &ival) ) return toInt(ival) def setJDFix(self, fix): """ Sets the threshold for changing the target in the correction equation. Parameters ---------- fix: float 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. """ cdef PetscReal val = asReal(fix) CHKERR( EPSJDSetFix(self.eps, val) ) def getJDFix(self): """ Gets the threshold for changing the target in the correction equation. Returns ------- fix: float The threshold for changing the target. """ cdef PetscReal val = 0 CHKERR( EPSJDGetFix(self.eps, &val) ) return toReal(val) def setJDConstCorrectionTol(self, constant): """ Deactivates the dynamic stopping criterion that sets the `KSP` relative tolerance to `0.5**i`, where `i` is the number of `EPS` iterations from the last converged value. Parameters ---------- constant: bool If False, the `KSP` relative tolerance is set to `0.5**i`. """ cdef PetscBool tval = asBool(constant) CHKERR( EPSJDSetConstCorrectionTol(self.eps, tval) ) def getJDConstCorrectionTol(self): """ Returns the flag indicating if the dynamic stopping is being used for solving the correction equation. Returns ------- constant: bool Flag indicating if the dynamic stopping criterion is not being used. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetConstCorrectionTol(self.eps, &tval) ) return toBool(tval) def setJDBOrth(self, borth): """ Selects the orthogonalization that will be used in the search subspace in case of generalized Hermitian problems. Parameters ---------- borth: bool Whether to B-orthogonalize the search subspace. """ cdef PetscBool tval = asBool(borth) CHKERR( EPSJDSetBOrth(self.eps, tval) ) def getJDBOrth(self): """ Returns the orthogonalization used in the search subspace in case of generalized Hermitian problems. Returns ------- borth: bool Whether to B-orthogonalize the search subspace. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSJDGetBOrth(self.eps, &tval) ) return toBool(tval) # def setRQCGReset(self, nrest): """ Sets the reset parameter of the RQCG iteration. Every nrest iterations, the solver performs a Rayleigh-Ritz projection step. Parameters ---------- nrest: int The number of iterations between resets. """ cdef PetscInt val = asInt(nrest) CHKERR( EPSRQCGSetReset(self.eps, val) ) def getRQCGReset(self): """ Gets the reset parameter used in the RQCG method. Returns ------- nrest: int The number of iterations between resets. """ cdef PetscInt val = 0 CHKERR( EPSRQCGGetReset(self.eps, &val) ) return toInt(val) def setLOBPCGBlockSize(self, bs): """ Sets the block size of the LOBPCG method. Parameters ---------- bs: int The block size. """ cdef PetscInt ival = asInt(bs) CHKERR( EPSLOBPCGSetBlockSize(self.eps, ival) ) def getLOBPCGBlockSize(self): """ Gets the block size used in the LOBPCG method. Returns ------- bs: int The block size. """ cdef PetscInt ival = 0 CHKERR( EPSLOBPCGGetBlockSize(self.eps, &ival) ) return toInt(ival) def setLOBPCGRestart(self, restart): """ Sets the restart parameter for the LOBPCG method. 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. Parameters ---------- restart: float The percentage of the block of vectors to force a restart. Notes ----- Allowed values are in the range [0.1,1.0]. The default is 0.9. """ cdef PetscReal val = asReal(restart) CHKERR( EPSLOBPCGSetRestart(self.eps, val) ) def getLOBPCGRestart(self): """ Gets the restart parameter used in the LOBPCG method. Returns ------- restart: float The restart parameter. """ cdef PetscReal val = 0 CHKERR( EPSLOBPCGGetRestart(self.eps, &val) ) return toReal(val) def setLOBPCGLocking(self, lock): """ Choose between locking and non-locking variants of the LOBPCG method. Parameters ---------- lock: bool 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). """ cdef PetscBool val = asBool(lock) CHKERR( EPSLOBPCGSetLocking(self.eps, val) ) def getLOBPCGLocking(self): """ Gets the locking flag used in the LOBPCG method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSLOBPCGGetLocking(self.eps, &tval) ) return toBool(tval) def setLyapIIRanks(self, rkc=None, rkl=None): """ Set the ranks used in the solution of the Lyapunov equation. Parameters ---------- rkc: int, optional The compressed rank. rkl: int, optional The Lyapunov rank. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT 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): """ Return the rank values used for the Lyapunov step. Returns ------- rkc: int The compressed rank. rkl: int The Lyapunov rank. """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSLyapIIGetRanks(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) # def setCISSExtraction(self, extraction): """ Sets the extraction technique used in the CISS solver. Parameters ---------- extraction: `EPS.CISSExtraction` enumerate The extraction technique. """ cdef SlepcEPSCISSExtraction val = extraction CHKERR( EPSCISSSetExtraction(self.eps, val) ) def getCISSExtraction(self): """ Gets the extraction technique used in the CISS solver. Returns ------- extraction: `EPS.CISSExtraction` enumerate The extraction technique. """ cdef SlepcEPSCISSExtraction val = EPS_CISS_EXTRACTION_RITZ CHKERR( EPSCISSGetExtraction(self.eps, &val) ) return val def setCISSQuadRule(self, quad): """ Sets the quadrature rule used in the CISS solver. Parameters ---------- quad: `EPS.CISSQuadRule` enumerate The quadrature rule. """ cdef SlepcEPSCISSQuadRule val = quad CHKERR( EPSCISSSetQuadRule(self.eps, val) ) def getCISSQuadRule(self): """ Gets the quadrature rule used in the CISS solver. Returns ------- quad: `EPS.CISSQuadRule` enumerate The quadrature rule. """ cdef SlepcEPSCISSQuadRule val = EPS_CISS_QUADRULE_TRAPEZOIDAL CHKERR( EPSCISSGetQuadRule(self.eps, &val) ) return val def setCISSSizes(self, ip=None, bs=None, ms=None, npart=None, bsmax=None, realmats=False): """ Sets the values of various size parameters in the CISS solver. Parameters ---------- ip: int, optional Number of integration points. bs: int, optional Block size. ms: int, optional Moment size. npart: int, optional Number of partitions when splitting the communicator. bsmax: int, optional Maximum block size. realmats: bool, optional True if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `KSP` object is shared among all processes of the `EPS` communicator. Otherwise, the communicator is split into npart communicators, so that `npart` `KSP` solves proceed simultaneously. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT cdef PetscInt ival4 = PETSC_DEFAULT cdef PetscInt ival5 = PETSC_DEFAULT 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): """ Gets the values of various size parameters in the CISS solver. 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. """ 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=None, spur=None): """ Sets the values of various threshold parameters in the CISS solver. Parameters ---------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs). """ cdef PetscReal rval1 = PETSC_DEFAULT cdef PetscReal rval2 = PETSC_DEFAULT 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): """ Gets the values of various threshold parameters in the CISS solver. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. """ cdef PetscReal delta = 0 cdef PetscReal spur = 0 CHKERR( EPSCISSGetThreshold(self.eps, &delta, &spur) ) return (toReal(delta), toReal(spur)) def setCISSRefinement(self, inner=None, blsize=None): """ Sets the values of various refinement parameters in the CISS solver. Parameters ---------- inner: int, optional Number of iterative refinement iterations (inner loop). blsize: int, optional Number of iterative refinement iterations (blocksize loop). """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT 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): """ Gets the values of various refinement parameters in the CISS solver. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( EPSCISSGetRefinement(self.eps, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def setCISSUseST(self, usest): """ Sets a flag indicating that the CISS solver will use the `ST` object for the linear solves. Parameters ---------- usest: bool Whether to use the `ST` object or not. """ cdef PetscBool tval = asBool(usest) CHKERR( EPSCISSSetUseST(self.eps, tval) ) def getCISSUseST(self): """ Gets the flag for using the `ST` object in the CISS solver. Returns ------- usest: bool Whether to use the `ST` object or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( EPSCISSGetUseST(self.eps, &tval) ) return toBool(tval) def getCISSKSPs(self): """ Retrieve the array of linear solver objects associated with the CISS solver. Returns ------- ksp: list of `KSP` The linear solver objects. Notes ----- The number of `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. """ 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 &self.fn self.fn = NULL def view(self, Viewer viewer=None): """ Prints the FN data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( FNView(self.fn, vwr) ) def destroy(self): """ Destroys the FN object. """ CHKERR( FNDestroy(&self.fn) ) self.fn = NULL return self def create(self, comm=None): """ Creates the FN object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Selects the type for the FN object. Parameters ---------- fn_type: `FN.Type` enumerate The inner product type to be used. """ cdef SlepcFNType cval = NULL fn_type = str2bytes(fn_type, &cval) CHKERR( FNSetType(self.fn, cval) ) def getType(self): """ Gets the FN type of this object. Returns ------- type: `FN.Type` enumerate The inner product type currently being used. """ cdef SlepcFNType fn_type = NULL CHKERR( FNGetType(self.fn, &fn_type) ) return bytes2str(fn_type) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all FN options in the database. Parameters ---------- prefix: string 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. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( FNSetOptionsPrefix(self.fn, cval) ) def getOptionsPrefix(self): """ Gets the prefix used for searching for all FN options in the database. Returns ------- prefix: string The prefix string set for this FN object. """ cdef const char *prefix = NULL CHKERR( FNGetOptionsPrefix(self.fn, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ Sets FN options from the options database. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( FNSetFromOptions(self.fn) ) def duplicate(self, comm=None): """ Duplicate the FN object copying all parameters, possibly with a different communicator. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to the object's communicator. """ 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): """ Computes the value of the function f(x) for a given x. Parameters ---------- x: scalar Value where the function must be evaluated. Returns ------- y: scalar The result of f(x). """ cdef PetscScalar sval = 0 CHKERR( FNEvaluateFunction(self.fn, x, &sval) ) return toScalar(sval) def evaluateDerivative(self, x): """ Computes the value of the derivative f'(x) for a given x. Parameters ---------- x: scalar Value where the derivative must be evaluated. Returns ------- y: scalar The result of f'(x). """ cdef PetscScalar sval = 0 CHKERR( FNEvaluateDerivative(self.fn, x, &sval) ) return toScalar(sval) def evaluateFunctionMat(self, Mat A, Mat B=None): """ Computes the value of the function f(A) for a given matrix A. Parameters ---------- A: Mat Matrix on which the function must be evaluated. B: Mat, optional Placeholder for the result. Returns ------- B: Mat The result of f(A). """ if B is None: B = A.duplicate() CHKERR( FNEvaluateFunctionMat(self.fn, A.mat, B.mat) ) return B def evaluateFunctionMatVec(self, Mat A, Vec v=None): """ Computes the first column of the matrix f(A) for a given matrix A. Parameters ---------- A: Mat Matrix on which the function must be evaluated. Returns ------- v: Vec The first column of the result f(A). """ if v is None: v = A.createVecs('left') CHKERR( FNEvaluateFunctionMatVec(self.fn, A.mat, v.vec) ) return v def setScale(self, alpha=None, beta=None): """ Sets the scaling parameters that define the matematical function. Parameters ---------- alpha: scalar (possibly complex), optional Inner scaling (argument), default is 1.0. beta: scalar (possibly complex), optional Outer scaling (result), default is 1.0. """ 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): """ Gets the scaling parameters that define the matematical function. Returns ------- alpha: scalar (possibly complex) Inner scaling (argument). beta: scalar (possibly complex) Outer scaling (result). """ cdef PetscScalar aval = 0, bval = 0 CHKERR( FNGetScale(self.fn, &aval, &bval) ) return (toScalar(aval), toScalar(bval)) def setMethod(self, meth): """ Selects the method to be used to evaluate functions of matrices. Parameters ---------- meth: int 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. """ cdef PetscInt val = asInt(meth) CHKERR( FNSetMethod(self.fn, val) ) def getMethod(self): """ Gets the method currently used for matrix functions. Returns ------- meth: int An index identifying the method. """ cdef PetscInt val = 0 CHKERR( FNGetMethod(self.fn, &val) ) return toInt(val) def setParallel(self, pmode): """ Selects the mode of operation in parallel runs. Parameters ---------- pmode: `FN.ParallelType` enumerate The parallel mode. """ cdef SlepcFNParallelType val = pmode CHKERR( FNSetParallel(self.fn, val) ) def getParallel(self): """ Gets the mode of operation in parallel runs. Returns ------- pmode: `FN.ParallelType` enumerate The parallel mode. """ cdef SlepcFNParallelType val = FN_PARALLEL_REDUNDANT CHKERR( FNGetParallel(self.fn, &val) ) return val # def setRationalNumerator(self, alpha): """ Sets the coefficients of the numerator of the rational function. Parameters ---------- alpha: array of scalars Coefficients. """ 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): """ Gets the coefficients of the numerator of the rational function. Returns ------- alpha: array of scalars Coefficients. """ 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): """ Sets the coefficients of the denominator of the rational function. Parameters ---------- alpha: array of scalars Coefficients. """ 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): """ Gets the coefficients of the denominator of the rational function. Returns ------- alpha: array of scalars Coefficients. """ 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, FN f1, FN f2): """ Sets the two child functions that constitute this combined function, and the way they must be combined. Parameters ---------- comb: `FN.CombineType` enumerate How to combine the functions (addition, multiplication, division, composition). f1: FN First function. f2: FN Second function. """ cdef SlepcFNCombineType val = comb CHKERR( FNCombineSetChildren(self.fn, val, f1.fn, f2.fn) ) def getCombineChildren(self): """ Gets the two child functions that constitute this combined function, and the way they must be combined. Returns ------- comb: `FN.CombineType` enumerate How to combine the functions (addition, multiplication, division, composition). f1: FN First function. f2: FN Second function. """ 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): """ Sets the index of the phi-function. Parameters ---------- k: int The index. """ cdef PetscInt val = asInt(k) CHKERR( FNPhiSetIndex(self.fn, val) ) def getPhiIndex(self): """ Gets the index of the phi-function. Returns ------- k: int The index. """ cdef PetscInt val = 0 CHKERR( FNPhiGetIndex(self.fn, &val) ) return toInt(val) # property method: def __get__(self): return self.getMethod() def __set__(self, value): self.setMethod(value) property parallel: def __get__(self): return self.getParallel() def __set__(self, value): self.setParallel(value) # ----------------------------------------------------------------------------- del FNType del FNCombineType del FNParallelType # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/MFN.pyx000066400000000000000000000275141500534120000177640ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class MFNType(object): """ MFN type Action of a matrix function on a vector. - `KRYLOV`: Restarted Krylov solver. - `EXPOKIT`: Implementation of the method in Expokit. """ KRYLOV = S_(MFNKRYLOV) EXPOKIT = S_(MFNEXPOKIT) class MFNConvergedReason(object): 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): """ MFN """ Type = MFNType ConvergedReason = MFNConvergedReason def __cinit__(self): self.obj = &self.mfn self.mfn = NULL def view(self, Viewer viewer=None): """ Prints the MFN data structure. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( MFNView(self.mfn, vwr) ) def destroy(self): """ Destroys the MFN object. """ CHKERR( MFNDestroy(&self.mfn) ) self.mfn = NULL return self def reset(self): """ Resets the MFN object. """ CHKERR( MFNReset(self.mfn) ) def create(self, comm=None): """ Creates the MFN object. Parameters ---------- comm: Comm, optional. MPI communicator. If not provided, it defaults to all processes. """ 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): """ Selects the particular solver to be used in the MFN object. Parameters ---------- mfn_type: `MFN.Type` enumerate The solver to be used. """ cdef SlepcMFNType cval = NULL mfn_type = str2bytes(mfn_type, &cval) CHKERR( MFNSetType(self.mfn, cval) ) def getType(self): """ Gets the MFN type of this object. Returns ------- type: `MFN.Type` enumerate The solver currently being used. """ cdef SlepcMFNType mfn_type = NULL CHKERR( MFNGetType(self.mfn, &mfn_type) ) return bytes2str(mfn_type) def getOptionsPrefix(self): """ Gets the prefix used for searching for all MFN options in the database. Returns ------- prefix: string The prefix string set for this MFN object. """ cdef const char *prefix = NULL CHKERR( MFNGetOptionsPrefix(self.mfn, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all MFN options in the database. Parameters ---------- prefix: string The prefix string to prepend to all MFN option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MFNSetOptionsPrefix(self.mfn, cval) ) def appendOptionsPrefix(self, prefix): """ Appends to the prefix used for searching for all MFN options in the database. Parameters ---------- prefix: string The prefix string to prepend to all MFN option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MFNAppendOptionsPrefix(self.mfn, cval) ) def setFromOptions(self): """ Sets MFN options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. """ CHKERR( MFNSetFromOptions(self.mfn) ) def getTolerances(self): """ Gets the tolerance and maximum iteration count used by the default MFN convergence tests. Returns ------- tol: float The convergence tolerance. max_it: int The maximum number of iterations """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( MFNGetTolerances(self.mfn, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol=None, max_it=None): """ Sets the tolerance and maximum iteration count used by the default MFN convergence tests. Parameters ---------- tol: float, optional The convergence tolerance. max_it: int, optional The maximum number of iterations """ 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( MFNSetTolerances(self.mfn, rval, ival) ) def getDimensions(self): """ Gets the dimension of the subspace used by the solver. Returns ------- ncv: int Maximum dimension of the subspace to be used by the solver. """ cdef PetscInt ival = 0 CHKERR( MFNGetDimensions(self.mfn, &ival) ) return toInt(ival) def setDimensions(self, ncv): """ Sets the dimension of the subspace to be used by the solver. Parameters ---------- ncv: int Maximum dimension of the subspace to be used by the solver. """ cdef PetscInt ival = asInt(ncv) CHKERR( MFNSetDimensions(self.mfn, ival) ) def getFN(self): """ Obtain the math function object associated to the MFN object. Returns ------- fn: FN The math function context. """ cdef FN fn = FN() CHKERR( MFNGetFN(self.mfn, &fn.fn) ) CHKERR( PetscINCREF(fn.obj) ) return fn def setFN(self, FN fn): """ Associates a math function object to the MFN object. Parameters ---------- fn: FN The math function context. """ CHKERR( MFNSetFN(self.mfn, fn.fn) ) def getBV(self): """ Obtain the basis vector object associated to the MFN object. Returns ------- bv: BV The basis vectors context. """ cdef BV bv = BV() CHKERR( MFNGetBV(self.mfn, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv): """ Associates a basis vector object to the MFN object. Parameters ---------- bv: BV The basis vectors context. """ CHKERR( MFNSetBV(self.mfn, bv.bv) ) def getOperator(self): """ Gets the matrix associated with the MFN object. Returns ------- A: Mat The matrix for which the matrix function is to be computed. """ cdef Mat A = Mat() CHKERR( MFNGetOperator(self.mfn, &A.mat) ) CHKERR( PetscINCREF(A.obj) ) return A def setOperator(self, Mat A): """ Sets the matrix associated with the MFN object. Parameters ---------- A: Mat The problem matrix. """ CHKERR( MFNSetOperator(self.mfn, A.mat) ) # def setMonitor(self, monitor, args=None, kargs=None): """ Appends a monitor function to the list of monitors. """ 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): """ Gets the list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self): """ Clears all monitors for an `MFN` object. """ CHKERR( MFNMonitorCancel(self.mfn) ) self.set_attr('__monitor__', None) # def setUp(self): """ Sets up all the internal data structures necessary for the execution of the eigensolver. """ CHKERR( MFNSetUp(self.mfn) ) def solve(self, Vec b, Vec x): """ Solves the matrix function problem. Given a vector b, the vector x = f(A)*b is returned. Parameters ---------- b: Vec The right hand side vector. x: Vec The solution. """ CHKERR( MFNSolve(self.mfn, b.vec, x.vec) ) def solveTranspose(self, Vec b, Vec x): """ Solves the transpose matrix function problem. Given a vector b, the vector x = f(A^T)*b is returned. Parameters ---------- b: Vec The right hand side vector. x: Vec The solution. """ CHKERR( MFNSolveTranspose(self.mfn, b.vec, x.vec) ) def getIterationNumber(self): """ Gets 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 ------- its: int Iteration number. """ cdef PetscInt ival = 0 CHKERR( MFNGetIterationNumber(self.mfn, &ival) ) return toInt(ival) def getConvergedReason(self): """ Gets the reason why the `solve()` iteration was stopped. Returns ------- reason: `MFN.ConvergedReason` enumerate Negative value indicates diverged, positive value converged. """ cdef SlepcMFNConvergedReason val = MFN_CONVERGED_ITERATING CHKERR( MFNGetConvergedReason(self.mfn, &val) ) return val def setErrorIfNotConverged(self, flg=True): """ Causes `solve()` to generate an error if the solver has not converged. Parameters ---------- flg: bool True indicates you want the error generated. """ cdef PetscBool tval = flg CHKERR( MFNSetErrorIfNotConverged(self.mfn, tval) ) def getErrorIfNotConverged(self): """ Return a flag indicating whether `solve()` will generate an error if the solver does not converge. Returns ------- flg: bool True indicates you want the error generated. """ cdef PetscBool tval = PETSC_FALSE CHKERR( MFNGetErrorIfNotConverged(self.mfn, &tval) ) return toBool(tval) # property tol: def __get__(self): return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: def __get__(self): return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property fn: def __get__(self): return self.getFN() def __set__(self, value): self.setBV(value) property bv: def __get__(self): return self.getFN() def __set__(self, value): self.setBV(value) # ----------------------------------------------------------------------------- del MFNType del MFNConvergedReason # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/NEP.pyx000066400000000000000000001667501500534120000177740ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class NEPType(object): """ NEP type Nonlinear eigensolvers. - `RII`: Residual inverse iteration. - `SLP`: Successive linear problems. - `NARNOLDI`: Nonlinear Arnoldi. - `CISS`: Contour integral spectrum slice. - `INTERPOL`: Polynomial interpolation. - `NLEIGS`: Fully rational Krylov method for nonlinear eigenproblems. """ RII = S_(NEPRII) SLP = S_(NEPSLP) NARNOLDI = S_(NEPNARNOLDI) CISS = S_(NEPCISS) INTERPOL = S_(NEPINTERPOL) NLEIGS = S_(NEPNLEIGS) class NEPProblemType(object): """ NEP problem type - `GENERAL`: General nonlinear eigenproblem. - `RATIONAL`: NEP defined in split form with all f_i rational. """ 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. """ 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. """ 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. """ 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). """ 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. """ 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. """ 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. """ 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. """ RITZ = NEP_CISS_EXTRACTION_RITZ HANKEL = NEP_CISS_EXTRACTION_HANKEL CAA = NEP_CISS_EXTRACTION_CAA # ----------------------------------------------------------------------------- cdef class NEP(Object): """ NEP """ 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): """ Prints the NEP data structure. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPView(self.nep, vwr) ) def destroy(self): """ Destroys the NEP object. """ CHKERR( NEPDestroy(&self.nep) ) self.nep = NULL return self def reset(self): """ Resets the NEP object. """ CHKERR( NEPReset(self.nep) ) def create(self, comm=None): """ Creates the NEP object. Parameters ---------- comm: Comm, optional. MPI communicator. If not provided, it defaults to all processes. """ 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): """ Selects the particular solver to be used in the NEP object. Parameters ---------- nep_type: `NEP.Type` enumerate The solver to be used. """ cdef SlepcNEPType cval = NULL nep_type = str2bytes(nep_type, &cval) CHKERR( NEPSetType(self.nep, cval) ) def getType(self): """ Gets the NEP type of this object. Returns ------- type: `NEP.Type` enumerate The solver currently being used. """ cdef SlepcNEPType nep_type = NULL CHKERR( NEPGetType(self.nep, &nep_type) ) return bytes2str(nep_type) def getOptionsPrefix(self): """ Gets the prefix used for searching for all NEP options in the database. Returns ------- prefix: string The prefix string set for this NEP object. """ cdef const char *prefix = NULL CHKERR( NEPGetOptionsPrefix(self.nep, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all NEP options in the database. Parameters ---------- prefix: string The prefix string to prepend to all NEP option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( NEPSetOptionsPrefix(self.nep, cval) ) def appendOptionsPrefix(self, prefix): """ Appends to the prefix used for searching for all NEP options in the database. Parameters ---------- prefix: string The prefix string to prepend to all NEP option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( NEPAppendOptionsPrefix(self.nep, cval) ) def setFromOptions(self): """ Sets NEP options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. """ CHKERR( NEPSetFromOptions(self.nep) ) def getProblemType(self): """ Gets the problem type from the `NEP` object. Returns ------- problem_type: `NEP.ProblemType` enumerate The problem type that was previously set. """ cdef SlepcNEPProblemType val = NEP_GENERAL CHKERR( NEPGetProblemType(self.nep, &val) ) return val def setProblemType(self, problem_type): """ Specifies the type of the eigenvalue problem. Parameters ---------- problem_type: `NEP.ProblemType` enumerate The problem type to be set. """ cdef SlepcNEPProblemType val = problem_type CHKERR( NEPSetProblemType(self.nep, val) ) def getWhichEigenpairs(self): """ Returns which portion of the spectrum is to be sought. Returns ------- which: `NEP.Which` enumerate The portion of the spectrum to be sought by the solver. """ cdef SlepcNEPWhich val = NEP_LARGEST_MAGNITUDE CHKERR( NEPGetWhichEigenpairs(self.nep, &val) ) return val def setWhichEigenpairs(self, which): """ Specifies which portion of the spectrum is to be sought. Parameters ---------- which: `NEP.Which` enumerate The portion of the spectrum to be sought by the solver. """ cdef SlepcNEPWhich val = which CHKERR( NEPSetWhichEigenpairs(self.nep, val) ) def getTarget(self): """ Gets the value of the target. Returns ------- target: float (real or complex) The value of the target. Notes ----- If the target was not set by the user, then zero is returned. """ cdef PetscScalar sval = 0 CHKERR( NEPGetTarget(self.nep, &sval) ) return toScalar(sval) def setTarget(self, target): """ Sets the value of the target. Parameters ---------- target: float (real or complex) 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()`. """ cdef PetscScalar sval = asScalar(target) CHKERR( NEPSetTarget(self.nep, sval) ) def getTolerances(self): """ Gets 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. """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPGetTolerances(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol=None, maxit=None): """ Sets the tolerance and maximum iteration count used in convergence tests. Parameters ---------- tol: float, optional The convergence tolerance. maxit: int, optional The maximum number of iterations. """ cdef PetscReal rval = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT 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): """ Return the method used to compute the error estimate used in the convergence test. Returns ------- conv: NEP.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcNEPConv conv = NEP_CONV_REL CHKERR( NEPGetConvergenceTest(self.nep, &conv) ) return conv def setConvergenceTest(self, conv): """ Specifies how to compute the error estimate used in the convergence test. Parameters ---------- conv: NEP.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcNEPConv tconv = conv CHKERR( NEPSetConvergenceTest(self.nep, tconv) ) def getRefine(self): """ Gets the refinement strategy used by the NEP object, and the associated parameters. Returns ------- ref: NEP.Refine The refinement type. npart: int The number of partitions of the communicator. tol: real The convergence tolerance. its: int The maximum number of refinement iterations. scheme: NEP.RefineScheme Scheme for solving linear systems """ 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, npart=None, tol=None, its=None, scheme=None): """ Sets the refinement strategy used by the NEP object, and the associated parameters. Parameters ---------- ref: NEP.Refine The refinement type. npart: int, optional The number of partitions of the communicator. tol: real, optional The convergence tolerance. its: int, optional The maximum number of refinement iterations. scheme: NEP.RefineScheme, optional Scheme for linear system solves """ cdef SlepcNEPRefine tref = ref cdef PetscInt tnpart = 1 cdef PetscReal ttol = PETSC_DEFAULT cdef PetscInt tits = PETSC_DEFAULT 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): """ Obtain the `KSP` object used by the eigensolver in the refinement phase. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( NEPRefineGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def getTrackAll(self): """ Returns the flag indicating whether all residual norms must be computed or not. Returns ------- trackall: bool Whether the solver compute all residuals or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPGetTrackAll(self.nep, &tval) ) return toBool(tval) def setTrackAll(self, trackall): """ Specifies if the solver must compute the residual of all approximate eigenpairs or not. Parameters ---------- trackall: bool Whether compute all residuals or not. """ cdef PetscBool tval = trackall CHKERR( NEPSetTrackAll(self.nep, tval) ) def getDimensions(self): """ Gets 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. """ 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=None, ncv=None, mpd=None): """ Sets the number of eigenvalues to compute and the dimension of the subspace. Parameters ---------- nev: int, optional Number of eigenvalues to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Obtain the basis vectors object associated to the eigensolver. Returns ------- bv: BV The basis vectors context. """ cdef BV bv = BV() CHKERR( NEPGetBV(self.nep, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv): """ Associates a basis vectors object to the eigensolver. Parameters ---------- bv: BV The basis vectors context. """ CHKERR( NEPSetBV(self.nep, bv.bv) ) def getRG(self): """ Obtain the region object associated to the eigensolver. Returns ------- rg: RG The region context. """ cdef RG rg = RG() CHKERR( NEPGetRG(self.nep, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg): """ Associates a region object to the eigensolver. Parameters ---------- rg: RG The region context. """ CHKERR( NEPSetRG(self.nep, rg.rg) ) def getDS(self): """ Obtain the direct solver associated to the eigensolver. Returns ------- ds: DS The direct solver context. """ cdef DS ds = DS() CHKERR( NEPGetDS(self.nep, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds): """ Associates a direct solver object to the eigensolver. Parameters ---------- ds: DS The direct solver context. """ CHKERR( NEPSetDS(self.nep, ds.ds) ) # def setInitialSpace(self, space): """ Sets the initial space from which the eigensolver starts to iterate. Parameters ---------- space: Vec or sequence of Vec The initial space """ 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, args=None, kargs=None): """ Sets a function to decide when to stop the outer iteration of the eigensolver. """ 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): """ Gets the stopping function. """ return self.get_attr('__stopping__') # def setMonitor(self, monitor, args=None, kargs=None): """ Appends a monitor function to the list of monitors. """ 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): """ Gets the list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self): """ Clears all monitors for a `NEP` object. """ CHKERR( NEPMonitorCancel(self.nep) ) self.set_attr('__monitor__', None) # def setUp(self): """ Sets up all the internal data structures necessary for the execution of the eigensolver. """ CHKERR( NEPSetUp(self.nep) ) def solve(self): """ Solves the eigensystem. """ CHKERR( NEPSolve(self.nep) ) def getIterationNumber(self): """ Gets 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 ------- its: int Iteration number. """ cdef PetscInt ival = 0 CHKERR( NEPGetIterationNumber(self.nep, &ival) ) return toInt(ival) def getConvergedReason(self): """ Gets the reason why the `solve()` iteration was stopped. Returns ------- reason: `NEP.ConvergedReason` enumerate Negative value indicates diverged, positive value converged. """ cdef SlepcNEPConvergedReason val = NEP_CONVERGED_ITERATING CHKERR( NEPGetConvergedReason(self.nep, &val) ) return val def getConverged(self): """ Gets the number of converged eigenpairs. Returns ------- nconv: int Number of converged eigenpairs. """ cdef PetscInt ival = 0 CHKERR( NEPGetConverged(self.nep, &ival) ) return toInt(ival) def getEigenpair(self, int i, Vec Vr=None, Vec Vi=None): """ Gets the i-th solution of the eigenproblem as computed by `solve()`. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i: int Index of the solution to be obtained. Vr: Vec, optional Placeholder for the returned eigenvector (real part). Vi: Vec, optional Placeholder for the returned eigenvector (imaginary part). Returns ------- e: complex The computed eigenvalue. """ 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, int i, Vec Wr, Vec Wi=None): """ Gets the i-th left eigenvector as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. Wr: Vec Placeholder for the returned eigenvector (real part). Wi: Vec, optional 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()`. """ cdef PetscVec vecr = Wr.vec cdef PetscVec veci = Wi.vec if Wi is not None else NULL CHKERR( NEPGetLeftEigenvector(self.nep, i, vecr, veci) ) def getErrorEstimate(self, int i): """ Returns the error estimate associated to the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. Returns ------- error: real Error estimate. """ cdef PetscReal rval = 0 CHKERR( NEPGetErrorEstimate(self.nep, i, &rval) ) return toReal(rval) def computeError(self, int i, etype=None): """ Computes the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. etype: `NEP.ErrorType` enumerate The error type to compute. Returns ------- error: real The error bound, computed in various ways from the residual norm ``||T(lambda)x||_2`` where ``lambda`` is the eigenvalue and ``x`` is the eigenvector. """ 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=None, Viewer viewer=None): """ Displays the errors associated with the computed solution (as well as the eigenvalues). Parameters ---------- etype: `NEP.ErrorType` enumerate, optional The error type to compute. viewer: Viewer, optional. 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. """ 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): """ Displays the computed eigenvalues in a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPValuesView(self.nep, vwr) ) def vectorsView(self, Viewer viewer=None): """ Outputs computed eigenvectors to a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( NEPVectorsView(self.nep, vwr) ) # def setFunction(self, function, Mat F=None, Mat P=None, args=None, kargs=None): """ Sets the function to compute the nonlinear Function T(lambda) as well as the location to store the matrix. Parameters ---------- function: Function evaluation routine F: Mat Function matrix P: Mat preconditioner matrix (usually the same as F) """ 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): """ Returns the function to compute the nonlinear Function T(lambda) and the matrix. Parameters ---------- F: Mat Function matrix P: Mat preconditioner matrix (usually the same as the F) function: Function evaluation routine """ 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, Mat J=None, args=None, kargs=None): """ Sets the function to compute the Jacobian T'(lambda) as well as the location to store the matrix. Parameters ---------- jacobian: Jacobian evaluation routine J: Mat Jacobian matrix """ 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): """ Returns the function to compute the Jacobian T'(lambda) and the matrix. Parameters ---------- J: Mat Jacobian matrix jacobian: Jacobian evaluation routine """ 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, f, structure=None): """ Sets the operator of the nonlinear eigenvalue problem in split form. Parameters ---------- A: Mat or sequence of Mat Coefficient matrices of the split form. f: sequence of FN Scalar functions of the split form. structure: `PETSc.Mat.Structure` enumerate, optional Structure flag for matrices. """ 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): """ Returns the operator of the nonlinear eigenvalue problem in split form. Returns ------- A: sequence of Mat Coefficient matrices of the split form. f: sequence of FN Scalar functions of the split form. structure: `PETSc.Mat.Structure` enumerate Structure flag for matrices. """ 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, structure=None): """ Sets 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: Mat or sequence of Mat Coefficient matrices of the split preconditioner. structure: `PETSc.Mat.Structure` enumerate, optional Structure flag for matrices. """ 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): """ Returns the operator of the split preconditioner. Returns ------- P: sequence of Mat Coefficient matrices of the split preconditioner. structure: `PETSc.Mat.Structure` enumerate Structure flag for matrices. """ 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): """ Returns the flag indicating whether a two-sided variant of the algorithm is being used or not. Returns ------- twosided: bool Whether the two-sided variant is to be used or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPGetTwoSided(self.nep, &tval) ) return toBool(tval) def setTwoSided(self, twosided): """ Sets the solver to use a two-sided variant so that left eigenvectors are also computed. Parameters ---------- twosided: bool Whether the two-sided variant is to be used or not. """ cdef PetscBool tval = asBool(twosided) CHKERR( NEPSetTwoSided(self.nep, tval) ) def applyResolvent(self, omega, Vec v, Vec r, RG rg=None): """ Applies the resolvent T^{-1}(z) to a given vector. Parameters ---------- omega: scalar Value where the resolvent must be evaluated. v: Vec Input vector. r: Vec Placeholder for the result vector. rg: `RG` object, optional Region. """ 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): """ Determines when the preconditioner is rebuilt in the nonlinear solve. Parameters ---------- lag: int 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. """ cdef PetscInt ival = asInt(lag) CHKERR( NEPRIISetLagPreconditioner(self.nep, ival) ) def getRIILagPreconditioner(self): """ Indicates how often the preconditioner is rebuilt. Returns ------- lag: int The lag parameter. """ cdef PetscInt ival = 0 CHKERR( NEPRIIGetLagPreconditioner(self.nep, &ival) ) return toInt(ival) def setRIIConstCorrectionTol(self, cct): """ Sets a flag to keep the tolerance used in the linear solver constant. Parameters ---------- cct: bool If True, the `KSP` relative tolerance is constant. """ cdef PetscBool val = asBool(cct) CHKERR( NEPRIISetConstCorrectionTol(self.nep, val) ) def getRIIConstCorrectionTol(self): """ Returns the constant tolerance flag. Returns ------- cct: bool If True, the `KSP` relative tolerance is constant. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPRIIGetConstCorrectionTol(self.nep, &tval) ) return toBool(tval) def setRIIMaximumIterations(self, its): """ Sets the maximum number of inner iterations to be used in the RII solver. These are the Newton iterations related to the computation of the nonlinear Rayleigh functional. Parameters ---------- its: int Maximum inner iterations. """ cdef PetscInt ival = asInt(its) CHKERR( NEPRIISetMaximumIterations(self.nep, ival) ) def getRIIMaximumIterations(self): """ Gets the maximum number of inner iterations of RII. Returns ------- its: int Maximum inner iterations. """ cdef PetscInt ival = 0 CHKERR( NEPRIIGetMaximumIterations(self.nep, &ival) ) return toInt(ival) def setRIIHermitian(self, herm): """ Sets a flag to indicate if the Hermitian version of the scalar nonlinear equation must be used by the solver. Parameters ---------- herm: bool If True, the Hermitian version is used. """ cdef PetscBool val = asBool(herm) CHKERR( NEPRIISetHermitian(self.nep, val) ) def getRIIHermitian(self): """ Returns the flag about using the Hermitian version of the scalar nonlinear equation. Returns ------- herm: bool If True, the Hermitian version is used. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPRIIGetHermitian(self.nep, &tval) ) return toBool(tval) def setRIIDeflationThreshold(self, deftol): """ Sets the threshold value used to switch between deflated and non-deflated iteration. Parameters ---------- deftol: float The threshold value. """ cdef PetscReal val = asReal(deftol) CHKERR( NEPRIISetDeflationThreshold(self.nep, val) ) def getRIIDeflationThreshold(self): """ Returns the threshold value that controls deflation. Returns ------- deftol: float The threshold value. """ cdef PetscReal rval = 0.0 CHKERR( NEPRIIGetDeflationThreshold(self.nep, &rval) ) return toReal(rval) def setRIIKSP(self, KSP ksp): """ Associate a linear solver object to the nonlinear eigensolver. Parameters ---------- ksp: `KSP` The linear solver object. """ CHKERR( NEPRIISetKSP(self.nep, ksp.ksp) ) def getRIIKSP(self): """ Retrieve the linear solver object associated with the nonlinear eigensolver. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( NEPRIIGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setSLPDeflationThreshold(self, deftol): """ Sets the threshold value used to switch between deflated and non-deflated iteration. Parameters ---------- deftol: float The threshold value. """ cdef PetscReal val = asReal(deftol) CHKERR( NEPSLPSetDeflationThreshold(self.nep, val) ) def getSLPDeflationThreshold(self): """ Returns the threshold value that controls deflation. Returns ------- deftol: float The threshold value. """ cdef PetscReal rval = 0.0 CHKERR( NEPSLPGetDeflationThreshold(self.nep, &rval) ) return toReal(rval) def setSLPEPS(self, EPS eps): """ Associate a linear eigensolver object to the nonlinear eigensolver. Parameters ---------- eps: `EPS` The linear eigensolver. """ CHKERR( NEPSLPSetEPS(self.nep, eps.eps) ) def getSLPEPS(self): """ Retrieve the linear eigensolver object associated with the nonlinear eigensolver. Returns ------- eps: `EPS` The linear eigensolver. """ cdef EPS eps = EPS() CHKERR( NEPSLPGetEPS(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setSLPEPSLeft(self, EPS eps): """ Associate a linear eigensolver object to the nonlinear eigensolver, used to compute left eigenvectors in the two-sided variant of SLP. Parameters ---------- eps: `EPS` The linear eigensolver. """ CHKERR( NEPSLPSetEPSLeft(self.nep, eps.eps) ) def getSLPEPSLeft(self): """ Retrieve the left eigensolver. Returns ------- eps: `EPS` The linear eigensolver. """ cdef EPS eps = EPS() CHKERR( NEPSLPGetEPSLeft(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setSLPKSP(self, KSP ksp): """ Associate a linear solver object to the nonlinear eigensolver. Parameters ---------- ksp: `KSP` The linear solver object. """ CHKERR( NEPSLPSetKSP(self.nep, ksp.ksp) ) def getSLPKSP(self): """ Retrieve the linear solver object associated with the nonlinear eigensolver. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( NEPSLPGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp # def setNArnoldiKSP(self, KSP ksp): """ Associate a linear solver object to the nonlinear eigensolver. Parameters ---------- ksp: `KSP` The linear solver object. """ CHKERR( NEPNArnoldiSetKSP(self.nep, ksp.ksp) ) def getNArnoldiKSP(self): """ Retrieve the linear solver object associated with the nonlinear eigensolver. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( NEPNArnoldiGetKSP(self.nep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setNArnoldiLagPreconditioner(self, lag): """ Determines when the preconditioner is rebuilt in the nonlinear solve. Parameters ---------- lag: int 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. """ cdef PetscInt ival = asInt(lag) CHKERR( NEPNArnoldiSetLagPreconditioner(self.nep, ival) ) def getNArnoldiLagPreconditioner(self): """ Indicates how often the preconditioner is rebuilt. Returns ------- lag: int The lag parameter. """ cdef PetscInt ival = 0 CHKERR( NEPNArnoldiGetLagPreconditioner(self.nep, &ival) ) return toInt(ival) # def setInterpolPEP(self, PEP pep): """ Associate a polynomial eigensolver object to the nonlinear eigensolver. Parameters ---------- pep: `PEP` The polynomial eigensolver. """ CHKERR( NEPInterpolSetPEP(self.nep, pep.pep) ) def getInterpolPEP(self): """ Retrieve the polynomial eigensolver object associated with the nonlinear eigensolver. Returns ------- pep: `PEP` The polynomial eigensolver. """ cdef PEP pep = PEP() CHKERR( NEPInterpolGetPEP(self.nep, &pep.pep) ) CHKERR( PetscINCREF(pep.obj) ) return pep def setInterpolInterpolation(self, tol=None, deg=None): """ Sets the tolerance and maximum degree when building the interpolation polynomial. Parameters ---------- tol: float, optional The tolerance to stop computing polynomial coefficients. deg: int, optional The maximum degree of interpolation. """ cdef PetscReal rval = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT 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): """ Gets the tolerance and maximum degree when building the interpolation polynomial. Returns ------- tol: float The tolerance to stop computing polynomial coefficients. deg: int The maximum degree of interpolation. """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPInterpolGetInterpolation(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) # def setNLEIGSRestart(self, keep): """ Sets the restart parameter for the NLEIGS method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( NEPNLEIGSSetRestart(self.nep, val) ) def getNLEIGSRestart(self): """ Gets the restart parameter used in the NLEIGS method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( NEPNLEIGSGetRestart(self.nep, &val) ) return toReal(val) def setNLEIGSLocking(self, lock): """ Choose between locking and non-locking variants of the NLEIGS method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( NEPNLEIGSSetLocking(self.nep, val) ) def getNLEIGSLocking(self): """ Gets the locking flag used in the NLEIGS method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPNLEIGSGetLocking(self.nep, &tval) ) return toBool(tval) def setNLEIGSInterpolation(self, tol=None, deg=None): """ Sets the tolerance and maximum degree when building the interpolation via divided differences. Parameters ---------- tol: float, optional The tolerance to stop computing divided differences. deg: int, optional The maximum degree of interpolation. """ cdef PetscReal rval = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT 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): """ Gets 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. """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( NEPNLEIGSGetInterpolation(self.nep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setNLEIGSFullBasis(self, fullbasis=True): """ Choose between TOAR-basis (default) and full-basis variants of the NLEIGS method. Parameters ---------- fullbasis: bool True if the full-basis variant must be selected. """ cdef PetscBool val = asBool(fullbasis) CHKERR( NEPNLEIGSSetFullBasis(self.nep, val) ) def getNLEIGSFullBasis(self): """ Gets the flag that indicates if NLEIGS is using the full-basis variant. Returns ------- fullbasis: bool True if the full-basis variant must be selected. """ cdef PetscBool tval = PETSC_FALSE CHKERR( NEPNLEIGSGetFullBasis(self.nep, &tval) ) return toBool(tval) def setNLEIGSEPS(self, EPS eps): """ Associate a linear eigensolver object to the nonlinear eigensolver. Parameters ---------- eps: `EPS` The linear eigensolver. """ CHKERR( NEPNLEIGSSetEPS(self.nep, eps.eps) ) def getNLEIGSEPS(self): """ Retrieve the linear eigensolver object associated with the nonlinear eigensolver. Returns ------- eps: `EPS` The linear eigensolver. """ cdef EPS eps = EPS() CHKERR( NEPNLEIGSGetEPS(self.nep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setNLEIGSRKShifts(self, shifts): """ Sets a list of shifts to be used in the Rational Krylov method. Parameters ---------- shifts: array of scalars Values specifying the shifts. """ 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): """ Gets the list of shifts used in the Rational Krylov method. Returns ------- shifts: array of scalars The shift values. """ 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): """ Retrieve the array of linear solver objects associated with the NLEIGS solver. Returns ------- ksp: list of `KSP` The linear solver objects. Notes ----- The number of `KSP` solvers is equal to the number of shifts provided by the user, or 1 if the user did not provide shifts. """ 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 0, (x'Cx)^2 > 4(x'Mx)(x'Kx). - `GYROSCOPIC`: QEP with M, K Hermitian, M>0, C skew-Hermitian. """ 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. """ 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. """ 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. """ 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). """ 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. """ SCHUR = PEP_REFINE_SCHEME_SCHUR MBE = PEP_REFINE_SCHEME_MBE EXPLICIT = PEP_REFINE_SCHEME_EXPLICIT class PEPExtract(object): """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ 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. """ RITZ = PEP_CISS_EXTRACTION_RITZ HANKEL = PEP_CISS_EXTRACTION_HANKEL CAA = PEP_CISS_EXTRACTION_CAA # ----------------------------------------------------------------------------- cdef class PEP(Object): """ PEP """ 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): """ Prints the PEP data structure. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPView(self.pep, vwr) ) def destroy(self): """ Destroys the PEP object. """ CHKERR( PEPDestroy(&self.pep) ) self.pep = NULL return self def reset(self): """ Resets the PEP object. """ CHKERR( PEPReset(self.pep) ) def create(self, comm=None): """ Creates the PEP object. Parameters ---------- comm: Comm, optional. MPI communicator. If not provided, it defaults to all processes. """ 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): """ Selects the particular solver to be used in the PEP object. Parameters ---------- pep_type: `PEP.Type` enumerate The solver to be used. """ cdef SlepcPEPType cval = NULL pep_type = str2bytes(pep_type, &cval) CHKERR( PEPSetType(self.pep, cval) ) def getType(self): """ Gets the PEP type of this object. Returns ------- type: `PEP.Type` enumerate The solver currently being used. """ cdef SlepcPEPType pep_type = NULL CHKERR( PEPGetType(self.pep, &pep_type) ) return bytes2str(pep_type) def getOptionsPrefix(self): """ Gets the prefix used for searching for all PEP options in the database. Returns ------- prefix: string The prefix string set for this PEP object. """ cdef const char *prefix = NULL CHKERR( PEPGetOptionsPrefix(self.pep, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all PEP options in the database. Parameters ---------- prefix: string The prefix string to prepend to all PEP option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PEPSetOptionsPrefix(self.pep, cval) ) def appendOptionsPrefix(self, prefix): """ Appends to the prefix used for searching for all PEP options in the database. Parameters ---------- prefix: string The prefix string to prepend to all PEP option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PEPAppendOptionsPrefix(self.pep, cval) ) def setFromOptions(self): """ Sets PEP options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. """ CHKERR( PEPSetFromOptions(self.pep) ) def getBasis(self): """ Gets the type of polynomial basis used to describe the polynomial eigenvalue problem. Returns ------- basis: `PEP.Basis` enumerate the basis that was previously set. """ cdef SlepcPEPBasis val = PEP_BASIS_MONOMIAL CHKERR( PEPGetBasis(self.pep, &val) ) return val def setBasis(self, basis): """ Specifies the type of polynomial basis used to describe the polynomial eigenvalue problem. Parameters ---------- basis: `PEP.Basis` enumerate the basis to be set. """ cdef SlepcPEPBasis val = basis CHKERR( PEPSetBasis(self.pep, val) ) def getProblemType(self): """ Gets the problem type from the PEP object. Returns ------- problem_type: `PEP.ProblemType` enumerate The problem type that was previously set. """ cdef SlepcPEPProblemType val = PEP_GENERAL CHKERR( PEPGetProblemType(self.pep, &val) ) return val def setProblemType(self, problem_type): """ Specifies the type of the eigenvalue problem. Parameters ---------- problem_type: `PEP.ProblemType` enumerate The problem type to be set. """ cdef SlepcPEPProblemType val = problem_type CHKERR( PEPSetProblemType(self.pep, val) ) def getWhichEigenpairs(self): """ Returns which portion of the spectrum is to be sought. Returns ------- which: `PEP.Which` enumerate The portion of the spectrum to be sought by the solver. """ cdef SlepcPEPWhich val = PEP_LARGEST_MAGNITUDE CHKERR( PEPGetWhichEigenpairs(self.pep, &val) ) return val def setWhichEigenpairs(self, which): """ Specifies which portion of the spectrum is to be sought. Parameters ---------- which: `PEP.Which` enumerate The portion of the spectrum to be sought by the solver. """ cdef SlepcPEPWhich val = which CHKERR( PEPSetWhichEigenpairs(self.pep, val) ) def getTarget(self): """ Gets the value of the target. Returns ------- target: float (real or complex) The value of the target. Notes ----- If the target was not set by the user, then zero is returned. """ cdef PetscScalar sval = 0 CHKERR( PEPGetTarget(self.pep, &sval) ) return toScalar(sval) def setTarget(self, target): """ Sets the value of the target. Parameters ---------- target: float (real or complex) 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()`. """ cdef PetscScalar sval = asScalar(target) CHKERR( PEPSetTarget(self.pep, sval) ) def getTolerances(self): """ Gets 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 """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( PEPGetTolerances(self.pep, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol=None, max_it=None): """ Sets the tolerance and maximum iteration count used by the default PEP convergence tests. Parameters ---------- tol: float, optional The convergence tolerance. max_it: int, optional The maximum number of iterations """ 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( PEPSetTolerances(self.pep, rval, ival) ) def getInterval(self): """ Gets the computational interval for spectrum slicing. 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. """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( PEPGetInterval(self.pep, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setInterval(self, inta, intb): """ Defines the computational interval for spectrum slicing. Parameters ---------- inta: float The left end of the interval. intb: float 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()`. """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( PEPSetInterval(self.pep, rval1, rval2) ) def getConvergenceTest(self): """ Return the method used to compute the error estimate used in the convergence test. Returns ------- conv: PEP.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcPEPConv conv = PEP_CONV_REL CHKERR( PEPGetConvergenceTest(self.pep, &conv) ) return conv def setConvergenceTest(self, conv): """ Specifies how to compute the error estimate used in the convergence test. Parameters ---------- conv: PEP.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcPEPConv tconv = conv CHKERR( PEPSetConvergenceTest(self.pep, tconv) ) def getRefine(self): """ Gets the refinement strategy used by the PEP object, and the associated parameters. Returns ------- ref: PEP.Refine The refinement type. npart: int The number of partitions of the communicator. tol: real The convergence tolerance. its: int The maximum number of refinement iterations. scheme: PEP.RefineScheme Scheme for solving linear systems """ 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, npart=None, tol=None, its=None, scheme=None): """ Sets the refinement strategy used by the PEP object, and the associated parameters. Parameters ---------- ref: PEP.Refine The refinement type. npart: int, optional The number of partitions of the communicator. tol: real, optional The convergence tolerance. its: int, optional The maximum number of refinement iterations. scheme: PEP.RefineScheme, optional Scheme for linear system solves """ cdef SlepcPEPRefine tref = ref cdef PetscInt tnpart = 1 cdef PetscReal ttol = PETSC_DEFAULT cdef PetscInt tits = PETSC_DEFAULT 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): """ Obtain the `KSP` object used by the eigensolver in the refinement phase. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( PEPRefineGetKSP(self.pep, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setExtract(self, extract): """ Specifies the extraction strategy to be used. Parameters ---------- extract: `PEP.Extract` enumerate The extraction strategy. """ cdef SlepcPEPExtract val = extract CHKERR( PEPSetExtract(self.pep, val) ) def getExtract(self): """ Gets the extraction technique used by the `PEP` object. Returns ------- extract: `PEP.Extract` enumerate The extraction strategy. """ cdef SlepcPEPExtract val = PEP_EXTRACT_NONE CHKERR( PEPGetExtract(self.pep, &val) ) return val def getTrackAll(self): """ Returns the flag indicating whether all residual norms must be computed or not. Returns ------- trackall: bool Whether the solver compute all residuals or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPGetTrackAll(self.pep, &tval) ) return toBool(tval) def setTrackAll(self, trackall): """ Specifies if the solver must compute the residual of all approximate eigenpairs or not. Parameters ---------- trackall: bool Whether compute all residuals or not. """ cdef PetscBool tval = trackall CHKERR( PEPSetTrackAll(self.pep, tval) ) def getDimensions(self): """ Gets 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. """ 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=None, ncv=None, mpd=None): """ Sets the number of eigenvalues to compute and the dimension of the subspace. Parameters ---------- nev: int, optional Number of eigenvalues to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Obtain the spectral transformation (`ST`) object associated to the eigensolver object. Returns ------- st: ST The spectral transformation. """ cdef ST st = ST() CHKERR( PEPGetST(self.pep, &st.st) ) CHKERR( PetscINCREF(st.obj) ) return st def setST(self, ST st): """ Associates a spectral transformation object to the eigensolver. Parameters ---------- st: ST The spectral transformation. """ CHKERR( PEPSetST(self.pep, st.st) ) def getScale(self, Vec Dl=None, Vec Dr=None): """ Gets the strategy used for scaling the polynomial eigenproblem. Parameters ---------- Dl: Vec, optional Placeholder for the returned left diagonal matrix. Dr: Vec, optional Placeholder for the returned right diagonal matrix. Returns ------- scale: `PEP.Scale` enumerate The scaling strategy. alpha: real The scaling factor. its: int The number of iteration of diagonal scaling. lbda: real Approximation of the wanted eigenvalues (modulus). """ 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, alpha=None, Vec Dl=None, Vec Dr=None, its=None, lbda=None): """ Sets the scaling strategy to be used for scaling the polynomial problem before attempting to solve. Parameters ---------- scale: `PEP.Scale` enumerate The scaling strategy. alpha: real, optional The scaling factor. Dl: Vec, optional The left diagonal matrix. Dr: Vec, optional The right diagonal matrix. its: int, optional The number of iteration of diagonal scaling. lbda: real, optional Approximation of the wanted eigenvalues (modulus). """ cdef SlepcPEPScale senum = scale cdef PetscReal rval1 = PETSC_DEFAULT cdef PetscInt ival = PETSC_DEFAULT cdef PetscReal rval2 = PETSC_DEFAULT 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): """ Obtain the basis vectors object associated to the eigensolver. Returns ------- bv: BV The basis vectors context. """ cdef BV bv = BV() CHKERR( PEPGetBV(self.pep, &bv.bv) ) CHKERR( PetscINCREF(bv.obj) ) return bv def setBV(self, BV bv): """ Associates a basis vectors object to the eigensolver. Parameters ---------- bv: BV The basis vectors context. """ CHKERR( PEPSetBV(self.pep, bv.bv) ) def getRG(self): """ Obtain the region object associated to the eigensolver. Returns ------- rg: RG The region context. """ cdef RG rg = RG() CHKERR( PEPGetRG(self.pep, &rg.rg) ) CHKERR( PetscINCREF(rg.obj) ) return rg def setRG(self, RG rg): """ Associates a region object to the eigensolver. Parameters ---------- rg: RG The region context. """ CHKERR( PEPSetRG(self.pep, rg.rg) ) def getDS(self): """ Obtain the direct solver associated to the eigensolver. Returns ------- ds: DS The direct solver context. """ cdef DS ds = DS() CHKERR( PEPGetDS(self.pep, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds): """ Associates a direct solver object to the eigensolver. Parameters ---------- ds: DS The direct solver context. """ CHKERR( PEPSetDS(self.pep, ds.ds) ) def getOperators(self): """ Gets the matrices associated with the eigenvalue problem. Returns ------- operators: tuple of Mat The matrices associated with the eigensystem. """ 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): """ Sets the matrices associated with the eigenvalue problem. Parameters ---------- operators: sequence of Mat The matrices associated with the eigensystem. """ 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): """ Sets the initial space from which the eigensolver starts to iterate. Parameters ---------- space: Vec or sequence of Vec The initial space """ 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, args=None, kargs=None): """ Sets a function to decide when to stop the outer iteration of the eigensolver. """ 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): """ Gets the stopping function. """ return self.get_attr('__stopping__') # def setMonitor(self, monitor, args=None, kargs=None): """ Appends a monitor function to the list of monitors. """ 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): """ Gets the list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self): """ Clears all monitors for a `PEP` object. """ CHKERR( PEPMonitorCancel(self.pep) ) self.set_attr('__monitor__', None) # def setUp(self): """ Sets up all the internal data structures necessary for the execution of the eigensolver. """ CHKERR( PEPSetUp(self.pep) ) def solve(self): """ Solves the eigensystem. """ CHKERR( PEPSolve(self.pep) ) def getIterationNumber(self): """ Gets 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 ------- its: int Iteration number. """ cdef PetscInt ival = 0 CHKERR( PEPGetIterationNumber(self.pep, &ival) ) return toInt(ival) def getConvergedReason(self): """ Gets the reason why the `solve()` iteration was stopped. Returns ------- reason: `PEP.ConvergedReason` enumerate Negative value indicates diverged, positive value converged. """ cdef SlepcPEPConvergedReason val = PEP_CONVERGED_ITERATING CHKERR( PEPGetConvergedReason(self.pep, &val) ) return val def getConverged(self): """ Gets the number of converged eigenpairs. Returns ------- nconv: int Number of converged eigenpairs. """ cdef PetscInt ival = 0 CHKERR( PEPGetConverged(self.pep, &ival) ) return toInt(ival) def getEigenpair(self, int i, Vec Vr=None, Vec Vi=None): """ Gets the i-th solution of the eigenproblem as computed by `solve()`. The solution consists of both the eigenvalue and the eigenvector. Parameters ---------- i: int Index of the solution to be obtained. Vr: Vec, optional Placeholder for the returned eigenvector (real part). Vi: Vec, optional Placeholder for the returned eigenvector (imaginary part). Returns ------- e: complex The computed eigenvalue. """ 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, int i): """ Returns the error estimate associated to the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. Returns ------- error: real Error estimate. """ cdef PetscReal rval = 0 CHKERR( PEPGetErrorEstimate(self.pep, i, &rval) ) return toReal(rval) def computeError(self, int i, etype=None): """ Computes the error (based on the residual norm) associated with the i-th computed eigenpair. Parameters ---------- i: int Index of the solution to be considered. etype: `PEP.ErrorType` enumerate The error type to compute. Returns ------- error: real The error bound, computed in various ways from the residual norm ``||P(l)x||_2`` where ``l`` is the eigenvalue and ``x`` is the eigenvector. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). """ 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=None, Viewer viewer=None): """ Displays the errors associated with the computed solution (as well as the eigenvalues). Parameters ---------- etype: `PEP.ErrorType` enumerate, optional The error type to compute. viewer: Viewer, optional. 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. """ 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): """ Displays the computed eigenvalues in a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPValuesView(self.pep, vwr) ) def vectorsView(self, Viewer viewer=None): """ Outputs computed eigenvectors to a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( PEPVectorsView(self.pep, vwr) ) # def setLinearEPS(self, EPS eps): """ Associate an eigensolver object to the polynomial eigenvalue solver. Parameters ---------- eps: `EPS` The linear eigensolver. """ CHKERR( PEPLinearSetEPS(self.pep, eps.eps) ) def getLinearEPS(self): """ Retrieve the eigensolver object associated to the polynomial eigenvalue solver. Returns ------- eps: `EPS` The linear eigensolver. """ cdef EPS eps = EPS() CHKERR( PEPLinearGetEPS(self.pep, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setLinearLinearization(self, alpha=1.0, beta=0.0): """ Set the coefficients that define the linearization of a quadratic eigenproblem. Parameters ---------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. """ cdef PetscReal a = asReal(alpha) cdef PetscReal b = asReal(beta) CHKERR( PEPLinearSetLinearization(self.pep, a, b) ) def getLinearLinearization(self): """ Returns the coefficients that define the linearization of a quadratic eigenproblem. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. """ 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): """ Indicate if the matrices A and B for the linearization of the problem must be built explicitly. Parameters ---------- flag: bool Boolean flag indicating if the matrices are built explicitly. """ cdef PetscBool sval = asBool(flag) CHKERR( PEPLinearSetExplicitMatrix(self.pep, sval) ) def getLinearExplicitMatrix(self): """ Returns the flag indicating if the matrices A and B for the linearization are built explicitly. Returns ------- flag: bool Boolean flag indicating if the matrices are built explicitly. """ cdef PetscBool sval = PETSC_FALSE CHKERR( PEPLinearGetExplicitMatrix(self.pep, &sval) ) return toBool(sval) # def setQArnoldiRestart(self, keep): """ Sets the restart parameter for the Q-Arnoldi method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( PEPQArnoldiSetRestart(self.pep, val) ) def getQArnoldiRestart(self): """ Gets the restart parameter used in the Q-Arnoldi method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( PEPQArnoldiGetRestart(self.pep, &val) ) return toReal(val) def setQArnoldiLocking(self, lock): """ Choose between locking and non-locking variants of the Q-Arnoldi method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( PEPQArnoldiSetLocking(self.pep, val) ) def getQArnoldiLocking(self): """ Gets the locking flag used in the Q-Arnoldi method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPQArnoldiGetLocking(self.pep, &tval) ) return toBool(tval) # def setTOARRestart(self, keep): """ Sets the restart parameter for the TOAR method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( PEPTOARSetRestart(self.pep, val) ) def getTOARRestart(self): """ Gets the restart parameter used in the TOAR method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( PEPTOARGetRestart(self.pep, &val) ) return toReal(val) def setTOARLocking(self, lock): """ Choose between locking and non-locking variants of the TOAR method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( PEPTOARSetLocking(self.pep, val) ) def getTOARLocking(self): """ Gets the locking flag used in the TOAR method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPTOARGetLocking(self.pep, &tval) ) return toBool(tval) # def setSTOARLinearization(self, alpha=1.0, beta=0.0): """ Set the coefficients that define the linearization of a quadratic eigenproblem. Parameters ---------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. """ cdef PetscReal a = asReal(alpha) cdef PetscReal b = asReal(beta) CHKERR( PEPSTOARSetLinearization(self.pep, a, b) ) def getSTOARLinearization(self): """ Returns the coefficients that define the linearization of a quadratic eigenproblem. Returns ------- alpha: float First parameter of the linearization. beta: float Second parameter of the linearization. """ 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): """ Choose between locking and non-locking variants of the STOAR method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged eigenpairs when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( PEPSTOARSetLocking(self.pep, val) ) def getSTOARLocking(self): """ Gets the locking flag used in the STOAR method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPSTOARGetLocking(self.pep, &tval) ) return toBool(tval) def setSTOARDetectZeros(self, detect): """ Sets a flag to enforce detection of zeros during the factorizations throughout the spectrum slicing computation. Parameters ---------- detect: bool True if zeros must checked for. Notes ----- 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. """ cdef PetscBool val = asBool(detect) CHKERR( PEPSTOARSetDetectZeros(self.pep, val) ) def getSTOARDetectZeros(self): """ Gets the flag that enforces zero detection in spectrum slicing. Returns ------- detect: bool The zero detection flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( PEPSTOARGetDetectZeros(self.pep, &tval) ) return toBool(tval) def setSTOARDimensions(self, nev=None, ncv=None, mpd=None): """ Sets the dimensions used for each subsolve step in case of doing spectrum slicing for a computational interval. The meaning of the parameters is the same as in `setDimensions()`. Parameters ---------- nev: int, optional Number of eigenvalues to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Gets the dimensions used for each subsolve step in case of doing spectrum slicing for a computational interval. 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. """ 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): """ Gets the values of the shifts and their corresponding inertias in case of doing spectrum slicing for a computational interval. Returns ------- shifts: list of float The values of the shifts used internally in the solver. inertias: list of int The values of the inertia in each shift. """ 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): """ Sets a flag to check that all the eigenvalues obtained throughout the spectrum slicing computation have the same definite type. Parameters ---------- flag: bool Whether the eigenvalue type is checked or not. """ cdef PetscBool sval = asBool(flag) CHKERR( PEPSTOARSetCheckEigenvalueType(self.pep, sval) ) def getSTOARCheckEigenvalueType(self): """ Gets the flag for the eigenvalue type check in spectrum slicing. Returns ------- flag: bool Whether the eigenvalue type is checked or not. """ cdef PetscBool sval = PETSC_FALSE CHKERR( PEPSTOARGetCheckEigenvalueType(self.pep, &sval) ) return toBool(sval) # def setJDRestart(self, keep): """ Sets the restart parameter for the Jacobi-Davidson method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( PEPJDSetRestart(self.pep, val) ) def getJDRestart(self): """ Gets the restart parameter used in the Jacobi-Davidson method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( PEPJDGetRestart(self.pep, &val) ) return toReal(val) def setJDFix(self, fix): """ Sets the threshold for changing the target in the correction equation. Parameters ---------- fix: float 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. """ cdef PetscReal val = asReal(fix) CHKERR( PEPJDSetFix(self.pep, val) ) def getJDFix(self): """ Gets threshold for changing the target in the correction equation. Returns ------- fix: float The threshold for changing the target. """ cdef PetscReal val = 0 CHKERR( PEPJDGetFix(self.pep, &val) ) return toReal(val) def setJDReusePreconditioner(self, flag): """ Sets a flag indicating whether the preconditioner must be reused or not. Parameters ---------- flag: bool The reuse flag. """ cdef PetscBool bval = asBool(flag) CHKERR( PEPJDSetReusePreconditioner(self.pep, bval) ) def getJDReusePreconditioner(self): """ Returns the flag for reusing the preconditioner. Returns ------- flag: bool The reuse flag. """ cdef PetscBool bval = PETSC_FALSE CHKERR( PEPJDGetReusePreconditioner(self.pep, &bval) ) return toBool(bval) def setJDMinimalityIndex(self, flag): """ Sets the maximum allowed value for the minimality index. Parameters ---------- flag: int The maximum minimality index. """ cdef PetscInt ival = asInt(flag) CHKERR( PEPJDSetMinimalityIndex(self.pep, ival) ) def getJDMinimalityIndex(self): """ Returns the maximum allowed value of the minimality index. Returns ------- flag: int The maximum minimality index. """ cdef PetscInt ival = 1 CHKERR( PEPJDGetMinimalityIndex(self.pep, &ival) ) return toInt(ival) def setJDProjection(self, proj): """ Sets the type of projection to be used in the Jacobi-Davidson solver. Parameters ---------- proj: `PEP.JDProjection` enumerate The type of projection. """ cdef SlepcPEPJDProjection val = proj CHKERR( PEPJDSetProjection(self.pep, val) ) def getJDProjection(self): """ Gets the type of projection to be used in the Jacobi-Davidson solver. Returns ------- proj: `PEP.JDProjection` enumerate The type of projection. """ cdef SlepcPEPJDProjection val = PEP_JD_PROJECTION_HARMONIC CHKERR( PEPJDGetProjection(self.pep, &val) ) return val # def setCISSExtraction(self, extraction): """ Sets the extraction technique used in the CISS solver. Parameters ---------- extraction: `PEP.CISSExtraction` enumerate The extraction technique. """ cdef SlepcPEPCISSExtraction val = extraction CHKERR( PEPCISSSetExtraction(self.pep, val) ) def getCISSExtraction(self): """ Gets the extraction technique used in the CISS solver. Returns ------- extraction: `PEP.CISSExtraction` enumerate The extraction technique. """ cdef SlepcPEPCISSExtraction val = PEP_CISS_EXTRACTION_RITZ CHKERR( PEPCISSGetExtraction(self.pep, &val) ) return val def setCISSSizes(self, ip=None, bs=None, ms=None, npart=None, bsmax=None, realmats=False): """ Sets the values of various size parameters in the CISS solver. Parameters ---------- ip: int, optional Number of integration points. bs: int, optional Block size. ms: int, optional Moment size. npart: int, optional Number of partitions when splitting the communicator. bsmax: int, optional Maximum block size. realmats: bool, optional True if A and B are real. Notes ----- The default number of partitions is 1. This means the internal `KSP` object is shared among all processes of the `PEP` communicator. Otherwise, the communicator is split into npart communicators, so that `npart` `KSP` solves proceed simultaneously. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT cdef PetscInt ival4 = PETSC_DEFAULT cdef PetscInt ival5 = PETSC_DEFAULT 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): """ Gets the values of various size parameters in the CISS solver. 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. """ 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=None, spur=None): """ Sets the values of various threshold parameters in the CISS solver. Parameters ---------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs). """ cdef PetscReal rval1 = PETSC_DEFAULT cdef PetscReal rval2 = PETSC_DEFAULT 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): """ Gets the values of various threshold parameters in the CISS solver. Returns ------- delta: float Threshold for numerical rank. spur: float Spurious threshold (to discard spurious eigenpairs. """ cdef PetscReal delta = 0 cdef PetscReal spur = 0 CHKERR( PEPCISSGetThreshold(self.pep, &delta, &spur) ) return (toReal(delta), toReal(spur)) def setCISSRefinement(self, inner=None, blsize=None): """ Sets the values of various refinement parameters in the CISS solver. Parameters ---------- inner: int, optional Number of iterative refinement iterations (inner loop). blsize: int, optional Number of iterative refinement iterations (blocksize loop). """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT 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): """ Gets the values of various refinement parameters in the CISS solver. Returns ------- inner: int Number of iterative refinement iterations (inner loop). blsize: int Number of iterative refinement iterations (blocksize loop). """ cdef PetscInt ival1 = 0 cdef PetscInt ival2 = 0 CHKERR( PEPCISSGetRefinement(self.pep, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def getCISSKSPs(self): """ Retrieve the array of linear solver objects associated with the CISS solver. Returns ------- ksp: list of `KSP` The linear solver objects. Notes ----- The number of `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. """ 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 &self.rg self.rg = NULL def view(self, Viewer viewer=None): """ Prints the RG data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( RGView(self.rg, vwr) ) def destroy(self): """ Destroys the RG object. """ CHKERR( RGDestroy(&self.rg) ) self.rg = NULL return self def create(self, comm=None): """ Creates the RG object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Selects the type for the RG object. Parameters ---------- rg_type: `RG.Type` enumerate The inner product type to be used. """ cdef SlepcRGType cval = NULL rg_type = str2bytes(rg_type, &cval) CHKERR( RGSetType(self.rg, cval) ) def getType(self): """ Gets the RG type of this object. Returns ------- type: `RG.Type` enumerate The inner product type currently being used. """ cdef SlepcRGType rg_type = NULL CHKERR( RGGetType(self.rg, &rg_type) ) return bytes2str(rg_type) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all RG options in the database. Parameters ---------- prefix: string 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. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( RGSetOptionsPrefix(self.rg, cval) ) def getOptionsPrefix(self): """ Gets the prefix used for searching for all RG options in the database. Returns ------- prefix: string The prefix string set for this RG object. """ cdef const char *prefix = NULL CHKERR( RGGetOptionsPrefix(self.rg, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ Sets RG options from the options database. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( RGSetFromOptions(self.rg) ) # def isTrivial(self): """ Tells whether it is the trivial region (whole complex plane). Returns ------- flag: 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. """ cdef PetscBool tval = PETSC_FALSE CHKERR( RGIsTrivial(self.rg, &tval) ) return toBool(tval) def isAxisymmetric(self, vertical=False): """ Determines if the region is symmetric with respect to the real or imaginary axis. Parameters ---------- vertical: bool, optional True if symmetry must be checked against the vertical axis. Returns ------- symm: bool True if the region is axisymmetric. """ cdef PetscBool val = asBool(vertical) cdef PetscBool tval = PETSC_FALSE CHKERR( RGIsAxisymmetric(self.rg, val, &tval) ) return toBool(tval) def getComplement(self): """ Returns the flag indicating whether the region is complemented or not. Returns ------- flg: bool Whether the region is complemented or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( RGGetComplement(self.rg, &tval) ) return toBool(tval) def setComplement(self, comp=True): """ Sets a flag to indicate that the region is the complement of the specified one. Parameters ---------- comp: bool, optional Activate/deactivate the complementation of the region. """ cdef PetscBool tval = asBool(comp) CHKERR( RGSetComplement(self.rg, tval) ) def setScale(self, sfactor=None): """ Sets the scaling factor to be used when checking that a point is inside the region and when computing the contour. Parameters ---------- sfactor: float, optional The scaling factor (default=1). """ cdef PetscReal rval = 1.0 if sfactor is not None: rval = asReal(sfactor) CHKERR( RGSetScale(self.rg, rval) ) def getScale(self): """ Gets the scaling factor. Returns ------- sfactor: float The scaling factor. """ cdef PetscReal rval = 0 CHKERR( RGGetScale(self.rg, &rval) ) return toReal(rval) def checkInside(self, a): """ Determines if a set of given points are inside the region or not. Parameters ---------- a: list of float (complex) The coordinates of the points. Returns ------- inside: list of int Computed result for each point (1=inside, 0=on the contour, -1=outside). """ 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): """ Computes the coordinates of several points lying on the contour of the region. Parameters ---------- n: int The number of points to compute. Returns ------- x: list of float (complex) Computed points. """ 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 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, radius, vscale=None): """ Sets the parameters defining the ellipse region. Parameters ---------- center: float (real or complex) The center. radius: float The radius. vscale: float, optional The vertical scale. """ 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): """ Gets the parameters that define the ellipse region. Returns ------- center: float (real or complex) The center. radius: float The radius. vscale: float The vertical scale. """ 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, b, c, d): """ Sets the parameters defining the interval region. Parameters ---------- a: float The left endpoint in the real axis. b: float The right endpoint in the real axis. c: float The upper endpoint in the imaginary axis. d: float The lower endpoint in the imaginary axis. """ 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): """ Gets the parameters that define the interval region. Returns ------- a: float The left endpoint in the real axis. b: float The right endpoint in the real axis. c: float The upper endpoint in the imaginary axis. d: float The lower endpoint in the imaginary axis. """ 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): """ Sets the vertices that define the polygon region. Parameters ---------- v: list of float (complex) The vertices. """ 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): """ Gets the parameters that define the interval region. Returns ------- v: list of float (complex) The vertices. """ 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 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 long PetscInt ctypedef double PetscReal ctypedef double PetscScalar cdef inline object toBool(PetscBool value): return True if value 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": PyObject *PyErr_Occurred() ctypedef struct Py_complex: double real double imag Py_complex PyComplex_AsCComplex(object) cdef inline object toComplex(PetscScalar rvalue, PetscScalar ivalue): return complex(toScalar(rvalue), toScalar(ivalue)) cdef inline PetscReal asComplexReal(object value) except? -1.0: cdef Py_complex cval = PyComplex_AsCComplex(value) return cval.real cdef inline PetscReal asComplexImag(object value) except? -1.0: cdef Py_complex cval = PyComplex_AsCComplex(value) if cval.real == -1.0 and PyErr_Occurred() != NULL: cval.imag = -1.0 return cval.imag 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" # ----------------------------------------------------------------------------- __doc__ = u""" Scalable Library for Eigenvalue Problem Computations """ DECIDE = PETSC_DECIDE DEFAULT = PETSC_DEFAULT DETERMINE = PETSC_DETERMINE 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 "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" 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) 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() # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/ST.pyx000066400000000000000000000505511500534120000176670ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class STType(object): """ ST types - `SHELL`: User-defined. - `SHIFT`: Shift from origin. - `SINVERT`: Shift-and-invert. - `CAYLEY`: Cayley transform. - `PRECOND`: Preconditioner. - `FILTER`: Polynomial filter. """ SHELL = S_(STSHELL) SHIFT = S_(STSHIFT) SINVERT = S_(STSINVERT) CAYLEY = S_(STCAYLEY) PRECOND = S_(STPRECOND) FILTER = S_(STFILTER) 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 ``A-sigma*B`` is handled as an implicit matrix. """ COPY = ST_MATMODE_COPY INPLACE = ST_MATMODE_INPLACE SHELL = ST_MATMODE_SHELL # ----------------------------------------------------------------------------- cdef class ST(Object): """ ST """ Type = STType MatMode = STMatMode def __cinit__(self): self.obj = &self.st self.st = NULL def view(self, Viewer viewer=None): """ Prints the ST data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( STView(self.st, vwr) ) def destroy(self): """ Destroys the ST object. """ CHKERR( STDestroy(&self.st) ) self.st = NULL return self def reset(self): """ Resets the ST object. """ CHKERR( STReset(self.st) ) def create(self, comm=None): """ Creates the ST object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Builds ST for a particular spectral transformation. Parameters ---------- st_type: `ST.Type` enumerate The spectral transformation to be used. Notes ----- See `ST.Type` for available methods. The default is `ST.Type.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. """ cdef SlepcSTType cval = NULL st_type = str2bytes(st_type, &cval) CHKERR( STSetType(self.st, cval) ) def getType(self): """ Gets the ST type of this object. Returns ------- type: `ST.Type` enumerate The spectral transformation currently being used. """ cdef SlepcSTType st_type = NULL CHKERR( STGetType(self.st, &st_type) ) return bytes2str(st_type) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all ST options in the database. Parameters ---------- prefix: string 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. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( STSetOptionsPrefix(self.st, cval) ) def getOptionsPrefix(self): """ Gets the prefix used for searching for all ST options in the database. Returns ------- prefix: string The prefix string set for this ST object. """ cdef const char *prefix = NULL CHKERR( STGetOptionsPrefix(self.st, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ Sets ST options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. Notes ----- To see all options, run your program with the -help option. """ CHKERR( STSetFromOptions(self.st) ) # def setShift(self, shift): """ Sets the shift associated with the spectral transformation. Parameters ---------- shift: scalar (possibly complex) 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. """ cdef PetscScalar sval = asScalar(shift) CHKERR( STSetShift(self.st, sval) ) def getShift(self): """ Gets the shift associated with the spectral transformation. Returns ------- shift: scalar (possibly complex) The value of the shift. """ cdef PetscScalar sval = 0 CHKERR( STGetShift(self.st, &sval) ) return toScalar(sval) def setTransform(self, flag=True): """ Sets a flag to indicate whether the transformed matrices are computed or not. Parameters ---------- flag: bool, optional 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. """ cdef PetscBool sval = asBool(flag) CHKERR( STSetTransform(self.st, sval) ) def getTransform(self): """ Gets the flag indicating whether the transformed matrices are computed or not. Returns ------- flag: 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. """ cdef PetscBool sval = PETSC_FALSE CHKERR( STGetTransform(self.st, &sval) ) return toBool(sval) def setMatMode(self, mode): """ Sets a flag to indicate how the matrix is being shifted in the shift-and-invert and Cayley spectral transformations. Parameters ---------- mode: `ST.MatMode` enumerate The mode flag. Notes ----- By default (`ST.MatMode.COPY`), a copy of matrix ``A`` is made and then this copy is shifted explicitly, e.g. ``A <- (A - s B)``. With `ST.MatMode.INPLACE`, the original matrix ``A`` is shifted at `setUp()` and unshifted at the end of the computations. With respect to the previous one, this mode avoids a copy of matrix ``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 shifted 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 case of generalized problems, in the two first modes the matrix ``A - s B`` has to be computed explicitly. The efficiency of this computation can be controlled with `setMatStructure()`. """ cdef SlepcSTMatMode val = mode CHKERR( STSetMatMode(self.st, val) ) def getMatMode(self): """ Gets a flag that indicates how the matrix is being shifted in the shift-and-invert and Cayley spectral transformations. Returns ------- mode: `ST.MatMode` enumerate The mode flag. """ cdef SlepcSTMatMode val = ST_MATMODE_INPLACE CHKERR( STGetMatMode(self.st, &val) ) return val def setMatrices(self, operators): """ Sets the matrices associated with the eigenvalue problem. Parameters ---------- operators: sequence of Mat The matrices associated with the eigensystem. """ 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): """ Gets the matrices associated with the eigenvalue problem. Returns ------- operators: tuple of Mat The matrices associated with the eigensystem. """ 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): """ Sets an internal Mat.Structure attribute to indicate which is the relation of the sparsity pattern of the two matrices ``A`` and ``B`` constituting the generalized eigenvalue problem. This function has no effect in the case of standard eigenproblems. Parameters ---------- structure: `PETSc.Mat.Structure` enumerate Either same, different, or a subset of the non-zero sparsity pattern. 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 *AXPY()* matrix operations). """ cdef PetscMatStructure val = matstructure(structure) CHKERR( STSetMatStructure(self.st, val) ) def getMatStructure(self): """ Gets the internal Mat.Structure attribute to indicate which is the relation of the sparsity pattern of the matrices. Returns ------- structure: `PETSc.Mat.Structure` enumerate The structure flag. """ cdef PetscMatStructure val CHKERR( STGetMatStructure(self.st, &val) ) return val def setKSP(self, KSP ksp): """ Sets the KSP object associated with the spectral transformation. Parameters ---------- ksp: KSP The linear solver object. """ CHKERR( STSetKSP(self.st, ksp.ksp) ) def getKSP(self): """ Gets the KSP object associated with the spectral transformation. Returns ------- ksp: KSP The linear solver object. Notes ----- On output, the internal value of KSP can be ``NULL`` if the combination of eigenproblem type and selected transformation does not require to solve a linear system of equations. """ cdef KSP ksp = KSP() CHKERR( STGetKSP(self.st, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setPreconditionerMat(self, Mat P=None): """ Sets the matrix to be used to build the preconditioner. Parameters ---------- P: Mat, optional The matrix that will be used in constructing the preconditioner. """ cdef PetscMat Pmat = P.mat if P is not None else NULL CHKERR( STSetPreconditionerMat(self.st, Pmat) ) def getPreconditionerMat(self): """ Gets the matrix previously set by setPreconditionerMat(). Returns ------- P: Mat The matrix that will be used in constructing the preconditioner. """ cdef Mat P = Mat() CHKERR( STGetPreconditionerMat(self.st, &P.mat) ) CHKERR( PetscINCREF(P.obj) ) return P # def setUp(self): """ Prepares for the use of a spectral transformation. """ CHKERR( STSetUp(self.st) ) def apply(self, Vec x, Vec y): """ Applies the spectral transformation operator to a vector, for instance ``(A - sB)^-1 B`` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x: Vec The input vector. y: Vec The result vector. """ CHKERR( STApply(self.st, x.vec, y.vec) ) def applyTranspose(self, Vec x, Vec y): """ Applies the transpose of the operator to a vector, for instance ``B^T(A - sB)^-T`` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x: Vec The input vector. y: Vec The result vector. """ CHKERR( STApplyTranspose(self.st, x.vec, y.vec) ) def applyHermitianTranspose(self, Vec x, Vec y): """ Applies the hermitian-transpose of the operator to a vector, for instance ``B^H(A - sB)^-H`` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x: Vec The input vector. y: Vec The result vector. """ CHKERR( STApplyHermitianTranspose(self.st, x.vec, y.vec) ) def applyMat(self, Mat x, Mat y): """ Applies the spectral transformation operator to a matrix, for instance ``(A - sB)^-1 B`` in the case of the shift-and-invert transformation and generalized eigenproblem. Parameters ---------- x: Mat The input matrix. y: Mat The result matrix. """ CHKERR( STApplyMat(self.st, x.mat, y.mat) ) def getOperator(self): """ Returns a shell matrix that represents the operator of the spectral transformation. Returns ------- op: Mat Operator matrix. """ cdef Mat op = Mat() CHKERR( STGetOperator(self.st, &op.mat) ) CHKERR( PetscINCREF(op.obj) ) return op def restoreOperator(self, Mat op): """ Restore the previously seized operator matrix. Parameters ---------- op: Mat Operator matrix previously obtained with getOperator(). """ CHKERR( PetscObjectDereference(op.mat) ) CHKERR( STRestoreOperator(self.st, &op.mat) ) # def setCayleyAntishift(self, tau): """ Sets the value of the anti-shift for the Cayley spectral transformation. Parameters ---------- tau: scalar (possibly complex) The anti-shift. Notes ----- In the generalized Cayley transform, the operator can be expressed as ``OP = inv(A - sigma B)*(A + tau B)``. This function sets the value of `tau`. Use `setShift()` for setting ``sigma``. """ cdef PetscScalar sval = asScalar(tau) CHKERR( STCayleySetAntishift(self.st, sval) ) def getCayleyAntishift(self): """ Gets the value of the anti-shift for the Cayley spectral transformation. Returns ------- tau: scalar (possibly complex) The anti-shift. """ cdef PetscScalar sval = 0 CHKERR( STCayleyGetAntishift(self.st, &sval) ) return toScalar(sval) def setFilterInterval(self, inta, intb): """ Defines the interval containing the desired eigenvalues. Parameters ---------- inta: float The left end of the interval. intb: float 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 `ST.setFilterRange()`. """ cdef PetscReal rval1 = asReal(inta) cdef PetscReal rval2 = asReal(intb) CHKERR( STFilterSetInterval(self.st, rval1, rval2) ) def getFilterInterval(self): """ Gets the interval containing the desired eigenvalues. Returns ------- inta: float The left end of the interval. intb: float The right end of the interval. """ cdef PetscReal inta = 0 cdef PetscReal intb = 0 CHKERR( STFilterGetInterval(self.st, &inta, &intb) ) return (toReal(inta), toReal(intb)) def setFilterRange(self, left, right): """ Defines the numerical range (or field of values) of the matrix, that is, the interval containing all eigenvalues. Parameters ---------- left: float The left end of the interval. right: float The right end of the interval. 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. """ cdef PetscReal rval1 = asReal(left) cdef PetscReal rval2 = asReal(right) CHKERR( STFilterSetRange(self.st, rval1, rval2) ) def getFilterRange(self): """ Gets the interval containing all eigenvalues. Returns ------- left: float The left end of the interval. right: float The right end of the interval. """ cdef PetscReal left = 0 cdef PetscReal right = 0 CHKERR( STFilterGetRange(self.st, &left, &right) ) return (toReal(left), toReal(right)) def setFilterDegree(self, deg): """ Sets the degree of the filter polynomial. Parameters ---------- deg: int The polynomial degree. """ cdef PetscInt val = asInt(deg) CHKERR( STFilterSetDegree(self.st, val) ) def getFilterDegree(self): """ Gets the degree of the filter polynomial. Returns ------- deg: int The polynomial degree. """ cdef PetscInt val = 0 CHKERR( STFilterGetDegree(self.st, &val) ) return toInt(val) # property shift: def __get__(self): return self.getShift() def __set__(self, value): self.setShift(value) property transform: def __get__(self): return self.getTransform() def __set__(self, value): self.setTransform(value) property mat_mode: def __get__(self): return self.getMatMode() def __set__(self, value): self.setMatMode(value) property mat_structure: def __get__(self): return self.getMatStructure() def __set__(self, value): self.setMatStructure(value) property ksp: def __get__(self): return self.getKSP() def __set__(self, value): self.setKSP(value) # ----------------------------------------------------------------------------- del STType del STMatMode # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/SVD.pyx000066400000000000000000001245371500534120000200030ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class SVDType(object): """ SVD types - `CROSS`: Eigenproblem with the cross-product matrix. - `CYCLIC`: Eigenproblem with the cyclic matrix. - `LAPACK`: Wrappers to dense SVD solvers in Lapack. - `LANCZOS`: Lanczos. - `TRLANCZOS`: Thick-restart Lanczos. - `RANDOMIZED`: Iterative RSVD for low-rank matrices. Wrappers to external SVD solvers (should be enabled during installation of SLEPc) - `SCALAPACK`: - `KSVD`: - `ELEMENTAL`: - `PRIMME`: """ 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). """ 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. """ 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. """ 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. """ 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. """ 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. """ 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 (Qa). - `UPPER`: Joint bidiagonalization, both Qa and Qb in upper bidiagonal form. - `LOWER`: Joint bidiagonalization, Qa lower bidiagonal, Qb upper bidiagonal. """ SINGLE = SVD_TRLANCZOS_GBIDIAG_SINGLE UPPER = SVD_TRLANCZOS_GBIDIAG_UPPER LOWER = SVD_TRLANCZOS_GBIDIAG_LOWER # ----------------------------------------------------------------------------- cdef class SVD(Object): """ SVD """ 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): """ Prints the SVD data structure. Parameters ---------- viewer: Viewer, optional Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDView(self.svd, vwr) ) def destroy(self): """ Destroys the SVD object. """ CHKERR( SVDDestroy(&self.svd) ) self.svd = NULL return self def reset(self): """ Resets the SVD object. """ CHKERR( SVDReset(self.svd) ) def create(self, comm=None): """ Creates the SVD object. Parameters ---------- comm: Comm, optional MPI communicator; if not provided, it defaults to all processes. """ 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): """ Selects the particular solver to be used in the SVD object. Parameters ---------- svd_type: `SVD.Type` enumerate The solver to be used. Notes ----- See `SVD.Type` for available methods. 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. """ cdef SlepcSVDType cval = NULL svd_type = str2bytes(svd_type, &cval) CHKERR( SVDSetType(self.svd, cval) ) def getType(self): """ Gets the SVD type of this object. Returns ------- type: `SVD.Type` enumerate The solver currently being used. """ cdef SlepcSVDType svd_type = NULL CHKERR( SVDGetType(self.svd, &svd_type) ) return bytes2str(svd_type) def getOptionsPrefix(self): """ Gets the prefix used for searching for all SVD options in the database. Returns ------- prefix: string The prefix string set for this SVD object. """ cdef const char *prefix = NULL CHKERR( SVDGetOptionsPrefix(self.svd, &prefix) ) return bytes2str(prefix) def setOptionsPrefix(self, prefix): """ Sets the prefix used for searching for all SVD options in the database. Parameters ---------- prefix: string 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_") """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SVDSetOptionsPrefix(self.svd, cval) ) def appendOptionsPrefix(self, prefix): """ Appends to the prefix used for searching for all SVD options in the database. Parameters ---------- prefix: string The prefix string to prepend to all SVD option requests. """ cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SVDAppendOptionsPrefix(self.svd, cval) ) def setFromOptions(self): """ Sets SVD options from the options database. This routine must be called before `setUp()` if the user is to be allowed to set the solver type. Notes ----- To see all options, run your program with the ``-help`` option. """ CHKERR( SVDSetFromOptions(self.svd) ) def getProblemType(self): """ Gets the problem type from the SVD object. Returns ------- problem_type: `SVD.ProblemType` enumerate The problem type that was previously set. """ cdef SlepcSVDProblemType val = SVD_STANDARD CHKERR( SVDGetProblemType(self.svd, &val) ) return val def setProblemType(self, problem_type): """ Specifies the type of the singular value problem. Parameters ---------- problem_type: `SVD.ProblemType` enumerate The problem type to be set. """ cdef SlepcSVDProblemType val = problem_type CHKERR( SVDSetProblemType(self.svd, val) ) def isGeneralized(self): """ Tells whether the SVD object corresponds to a generalized singular value problem. Returns ------- flag: bool True if two matrices were set with `setOperators()`. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDIsGeneralized(self.svd, &tval) ) return toBool(tval) def isHyperbolic(self): """ Tells whether the SVD object corresponds to a hyperbolic singular value problem. Returns ------- flag: bool True if the problem was specified as hyperbolic. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDIsHyperbolic(self.svd, &tval) ) return toBool(tval) # def getImplicitTranspose(self): """ Gets the mode used to handle the transpose of the matrix associated with the singular value problem. Returns ------- impl: bool How to handle the transpose (implicitly or not). """ cdef PetscBool val = PETSC_FALSE CHKERR( SVDGetImplicitTranspose(self.svd, &val) ) return toBool(val) def setImplicitTranspose(self, mode): """ Indicates how to handle the transpose of the matrix associated with the singular value problem. Parameters ---------- impl: bool 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 MatTranspose operation). If this flag is set to true, the solver does not build the transpose, but handles it implicitly via MatMultTranspose(). """ cdef PetscBool val = asBool(mode) CHKERR( SVDSetImplicitTranspose(self.svd, val) ) def getWhichSingularTriplets(self): """ Returns which singular triplets are to be sought. Returns ------- which: `SVD.Which` enumerate The singular values to be sought (either largest or smallest). """ cdef SlepcSVDWhich val = SVD_LARGEST CHKERR( SVDGetWhichSingularTriplets(self.svd, &val) ) return val def setWhichSingularTriplets(self, which): """ Specifies which singular triplets are to be sought. Parameters ---------- which: `SVD.Which` enumerate The singular values to be sought (either largest or smallest). """ cdef SlepcSVDWhich val = which CHKERR( SVDSetWhichSingularTriplets(self.svd, val) ) def getThreshold(self): """ Gets the threshold used in the threshold stopping test. Returns ------- thres: float The threshold. rel: bool Whether the threshold is relative or not. """ cdef PetscReal rval = 0 cdef PetscBool tval = PETSC_FALSE CHKERR( SVDGetThreshold(self.svd, &rval, &tval) ) return (toReal(rval), toBool(tval)) def setThreshold(self, thres, rel=False): """ Sets the threshold used in the threshold stopping test. Parameters ---------- thres: float The threshold. rel: bool, optional 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). """ cdef PetscReal rval = asReal(thres) cdef PetscBool tval = asBool(rel) CHKERR( SVDSetThreshold(self.svd, rval, tval) ) def getTolerances(self): """ Gets 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 """ cdef PetscReal rval = 0 cdef PetscInt ival = 0 CHKERR( SVDGetTolerances(self.svd, &rval, &ival) ) return (toReal(rval), toInt(ival)) def setTolerances(self, tol=None, max_it=None): """ Sets the tolerance and maximum iteration count used by the default SVD convergence tests. Parameters ---------- tol: float, optional The convergence tolerance. max_it: int, optional The maximum number of iterations Notes ----- Use `DECIDE` for `max_it` to assign a reasonably good value, which is dependent on the solution method. """ 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( SVDSetTolerances(self.svd, rval, ival) ) def getConvergenceTest(self): """ Return the method used to compute the error estimate used in the convergence test. Returns ------- conv: SVD.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcSVDConv conv = SVD_CONV_REL CHKERR( SVDGetConvergenceTest(self.svd, &conv) ) return conv def setConvergenceTest(self, conv): """ Specifies how to compute the error estimate used in the convergence test. Parameters ---------- conv: SVD.Conv The method used to compute the error estimate used in the convergence test. """ cdef SlepcSVDConv tconv = conv CHKERR( SVDSetConvergenceTest(self.svd, tconv) ) def getTrackAll(self): """ Returns the flag indicating whether all residual norms must be computed or not. Returns ------- trackall: bool Whether the solver compute all residuals or not. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDGetTrackAll(self.svd, &tval) ) return toBool(tval) def setTrackAll(self, trackall): """ Specifies if the solver must compute the residual of all approximate singular triplets or not. Parameters ---------- trackall: bool Whether compute all residuals or not. """ cdef PetscBool tval = asBool(trackall) CHKERR( SVDSetTrackAll(self.svd, tval) ) def getDimensions(self): """ Gets the number of singular values to compute and the dimension of the subspace. 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. """ 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=None, ncv=None, mpd=None): """ Sets the number of singular values to compute and the dimension of the subspace. Parameters ---------- nsv: int, optional Number of singular values to compute. ncv: int, optional Maximum dimension of the subspace to be used by the solver. mpd: int, optional Maximum dimension allowed for the projected problem. Notes ----- Use `DECIDE` 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. """ cdef PetscInt ival1 = PETSC_DEFAULT cdef PetscInt ival2 = PETSC_DEFAULT cdef PetscInt ival3 = PETSC_DEFAULT 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): """ Obtain the basis vectors objects associated to the SVD object. Returns ------- V: BV The basis vectors context for right singular vectors. U: BV The basis vectors context for left singular vectors. """ 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): """ Associates basis vectors objects to the SVD solver. Parameters ---------- V: BV The basis vectors context for right singular vectors. U: BV The basis vectors context for left singular vectors. """ 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): """ Obtain the direct solver associated to the singular value solver. Returns ------- ds: DS The direct solver context. """ cdef DS ds = DS() CHKERR( SVDGetDS(self.svd, &ds.ds) ) CHKERR( PetscINCREF(ds.obj) ) return ds def setDS(self, DS ds): """ Associates a direct solver object to the singular value solver. Parameters ---------- ds: DS The direct solver context. """ CHKERR( SVDSetDS(self.svd, ds.ds) ) def getOperators(self): """ Gets the matrices associated with the singular value problem. Returns ------- A: Mat The matrix associated with the singular value problem. B: Mat The second matrix in the case of GSVD. """ cdef Mat A = Mat() cdef Mat B = Mat() CHKERR( SVDGetOperators(self.svd, &A.mat, &B.mat) ) CHKERR( PetscINCREF(A.obj) ) CHKERR( PetscINCREF(B.obj) ) return (A, B) def setOperators(self, Mat A, Mat B=None): """ Sets the matrices associated with the singular value problem. Parameters ---------- A: Mat The matrix associated with the singular value problem. B: Mat, optional The second matrix in the case of GSVD; if not provided, a usual SVD is assumed. """ 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): """ Gets the signature matrix defining a hyperbolic singular value problem. Parameters ---------- omega: Vec Optional vector to store the diagonal elements of the signature matrix. Returns ------- omega: Vec A vector containing the diagonal elements of the signature matrix. """ 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): """ Sets the signature matrix defining a hyperbolic singular value problem. Parameters ---------- omega: Vec, optional A vector containing the diagonal elements of the signature matrix. """ cdef PetscVec Ovec = omega.vec if omega is not None else NULL CHKERR( SVDSetSignature(self.svd, Ovec) ) # def setInitialSpaces(self, spaceright=None, spaceleft=None): """ Sets the initial spaces from which the SVD solver starts to iterate. Parameters ---------- spaceright: sequence of Vec The right initial space. spaceleft: sequence of Vec The left initial space. """ 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, args=None, kargs=None): """ Sets a function to decide when to stop the outer iteration of the eigensolver. """ 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): """ Gets the stopping function. """ return self.get_attr('__stopping__') # def setMonitor(self, monitor, args=None, kargs=None): """ Appends a monitor function to the list of monitors. """ 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): """ Gets the list of monitor functions. """ return self.get_attr('__monitor__') def cancelMonitor(self): """ Clears all monitors for an `SVD` object. """ CHKERR( SVDMonitorCancel(self.svd) ) self.set_attr('__monitor__', None) # def setUp(self): """ Sets up all the internal data structures necessary for the execution of the singular value solver. Notes ----- 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. """ CHKERR( SVDSetUp(self.svd) ) def solve(self): """ Solves the singular value problem. """ CHKERR( SVDSolve(self.svd) ) def getIterationNumber(self): """ Gets 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 ------- its: int Iteration number. """ cdef PetscInt ival = 0 CHKERR( SVDGetIterationNumber(self.svd, &ival) ) return toInt(ival) def getConvergedReason(self): """ Gets the reason why the `solve()` iteration was stopped. Returns ------- reason: `SVD.ConvergedReason` enumerate Negative value indicates diverged, positive value converged. """ cdef SlepcSVDConvergedReason val = SVD_CONVERGED_ITERATING CHKERR( SVDGetConvergedReason(self.svd, &val) ) return val def getConverged(self): """ Gets the number of converged singular triplets. Returns ------- nconv: int Number of converged singular triplets. Notes ----- This function should be called after `solve()` has finished. """ cdef PetscInt ival = 0 CHKERR( SVDGetConverged(self.svd, &ival) ) return toInt(ival) def getValue(self, int i): """ Gets the i-th singular value as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. Returns ------- s: 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()`. """ cdef PetscReal rval = 0 CHKERR( SVDGetSingularTriplet(self.svd, i, &rval, NULL, NULL) ) return toReal(rval) def getVectors(self, int i, Vec U, Vec V): """ Gets the i-th left and right singular vectors as computed by `solve()`. Parameters ---------- i: int Index of the solution to be obtained. U: Vec Placeholder for the returned left singular vector. V: Vec 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()`. """ cdef PetscReal dummy = 0 CHKERR( SVDGetSingularTriplet(self.svd, i, &dummy, U.vec, V.vec) ) def getSingularTriplet(self, int i, Vec U=None, Vec V=None): """ Gets 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: int Index of the solution to be obtained. U: Vec Placeholder for the returned left singular vector. V: Vec Placeholder for the returned right singular vector. Returns ------- s: 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()`. """ 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, int i, etype=None): """ Computes the error (based on the residual norm) associated with the i-th singular triplet. Parameters ---------- i: int Index of the solution to be considered. etype: `SVD.ErrorType` enumerate The error type to compute. Returns ------- e: real The relative error bound, computed in various ways from the residual norm ``sqrt(n1^2+n2^2)`` where ``n1 = ||A*v-sigma*u||_2``, ``n2 = ||A^T*u-sigma*v||_2``, ``sigma`` is the singular value, ``u`` and ``v`` are the left and right singular vectors. Notes ----- The index ``i`` should be a value between ``0`` and ``nconv-1`` (see `getConverged()`). """ 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=None, Viewer viewer=None): """ Displays the errors associated with the computed solution (as well as the eigenvalues). Parameters ---------- etype: `SVD.ErrorType` enumerate, optional The error type to compute. viewer: Viewer, optional. 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. """ 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): """ Displays the computed singular values in a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDValuesView(self.svd, vwr) ) def vectorsView(self, Viewer viewer=None): """ Outputs computed singular vectors to a viewer. Parameters ---------- viewer: Viewer, optional. Visualization context; if not provided, the standard output is used. """ cdef PetscViewer vwr = def_Viewer(viewer) CHKERR( SVDVectorsView(self.svd, vwr) ) # def setCrossEPS(self, EPS eps): """ Associate an eigensolver object (`EPS`) to the singular value solver. Parameters ---------- eps: EPS The eigensolver object. """ CHKERR( SVDCrossSetEPS(self.svd, eps.eps) ) def getCrossEPS(self): """ Retrieve the eigensolver object (`EPS`) associated to the singular value solver. Returns ------- eps: EPS The eigensolver object. """ cdef EPS eps = EPS() CHKERR( SVDCrossGetEPS(self.svd, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setCrossExplicitMatrix(self, flag=True): """ Indicate if the eigensolver operator ``A^T*A`` must be computed explicitly. Parameters ---------- flag: bool True if ``A^T*A`` is built explicitly. """ cdef PetscBool tval = asBool(flag) CHKERR( SVDCrossSetExplicitMatrix(self.svd, tval) ) def getCrossExplicitMatrix(self): """ Returns the flag indicating if ``A^T*A`` is built explicitly. Returns ------- flag: bool True if ``A^T*A`` is built explicitly. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDCrossGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) def setCyclicEPS(self, EPS eps): """ Associate an eigensolver object (`EPS`) to the singular value solver. Parameters ---------- eps: EPS The eigensolver object. """ CHKERR( SVDCyclicSetEPS(self.svd, eps.eps) ) def getCyclicEPS(self): """ Retrieve the eigensolver object (`EPS`) associated to the singular value solver. Returns ------- eps: EPS The eigensolver object. """ cdef EPS eps = EPS() CHKERR( SVDCyclicGetEPS(self.svd, &eps.eps) ) CHKERR( PetscINCREF(eps.obj) ) return eps def setCyclicExplicitMatrix(self, flag=True): """ Indicate if the eigensolver operator ``H(A) = [ 0 A ; A^T 0 ]`` must be computed explicitly. Parameters ---------- flag: bool True if ``H(A)`` is built explicitly. """ cdef PetscBool tval = asBool(flag) CHKERR( SVDCyclicSetExplicitMatrix(self.svd, tval) ) def getCyclicExplicitMatrix(self): """ Returns the flag indicating if ``H(A) = [ 0 A ; A^T 0 ]`` is built explicitly. Returns ------- flag: bool True if ``H(A)`` is built explicitly. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDCyclicGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) def setLanczosOneSide(self, flag=True): """ Indicate if the variant of the Lanczos method to be used is one-sided or two-sided. Parameters ---------- flag: bool 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. """ cdef PetscBool tval = asBool(flag) CHKERR( SVDLanczosSetOneSide(self.svd, tval) ) def getLanczosOneSide(self): """ Gets if the variant of the Lanczos method to be used is one-sided or two-sided. Returns ------- delayed: bool True if the method is one-sided. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDLanczosGetOneSide(self.svd, &tval) ) return toBool(tval) def setTRLanczosOneSide(self, flag=True): """ Indicate if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Parameters ---------- flag: bool 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. """ cdef PetscBool tval = asBool(flag) CHKERR( SVDLanczosSetOneSide(self.svd, tval) ) def getTRLanczosOneSide(self): """ Gets if the variant of the thick-restart Lanczos method to be used is one-sided or two-sided. Returns ------- delayed: bool True if the method is one-sided. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetOneSide(self.svd, &tval) ) return toBool(tval) def setTRLanczosGBidiag(self, bidiag): """ Sets the bidiagonalization choice to use in the GSVD TRLanczos solver. Parameters ---------- bidiag: `SVD.TRLanczosGBidiag` enumerate The bidiagonalization choice. """ cdef SlepcSVDTRLanczosGBidiag val = bidiag CHKERR( SVDTRLanczosSetGBidiag(self.svd, val) ) def getTRLanczosGBidiag(self): """ Returns bidiagonalization choice used in the GSVD TRLanczos solver. Returns ------- bidiag: `SVD.TRLanczosGBidiag` enumerate The bidiagonalization choice. """ cdef SlepcSVDTRLanczosGBidiag val = SVD_TRLANCZOS_GBIDIAG_LOWER CHKERR( SVDTRLanczosGetGBidiag(self.svd, &val) ) return val def setTRLanczosRestart(self, keep): """ Sets the restart parameter for the thick-restart Lanczos method, in particular the proportion of basis vectors that must be kept after restart. Parameters ---------- keep: float 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. """ cdef PetscReal val = asReal(keep) CHKERR( SVDTRLanczosSetRestart(self.svd, val) ) def getTRLanczosRestart(self): """ Gets the restart parameter used in the thick-restart Lanczos method. Returns ------- keep: float The number of vectors to be kept at restart. """ cdef PetscReal val = 0 CHKERR( SVDTRLanczosGetRestart(self.svd, &val) ) return toReal(val) def setTRLanczosLocking(self, lock): """ Choose between locking and non-locking variants of the thick-restart Lanczos method. Parameters ---------- lock: bool True if the locking variant must be selected. Notes ----- The default is to lock converged singular triplets when the method restarts. This behaviour can be changed so that all directions are kept in the working subspace even if already converged to working accuracy (the non-locking variant). """ cdef PetscBool val = asBool(lock) CHKERR( SVDTRLanczosSetLocking(self.svd, val) ) def getTRLanczosLocking(self): """ Gets the locking flag used in the thick-restart Lanczos method. Returns ------- lock: bool The locking flag. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetLocking(self.svd, &tval) ) return toBool(tval) def setTRLanczosKSP(self, KSP ksp): """ Associate a linear solver object to the SVD solver. Parameters ---------- ksp: `KSP` The linear solver object. """ CHKERR( SVDTRLanczosSetKSP(self.svd, ksp.ksp) ) def getTRLanczosKSP(self): """ Retrieve the linear solver object associated with the SVD solver. Returns ------- ksp: `KSP` The linear solver object. """ cdef KSP ksp = KSP() CHKERR( SVDTRLanczosGetKSP(self.svd, &ksp.ksp) ) CHKERR( PetscINCREF(ksp.obj) ) return ksp def setTRLanczosExplicitMatrix(self, flag=True): """ Indicate if the matrix ``Z=[A;B]`` must be built explicitly. Parameters ---------- flag: bool True if ``Z=[A;B]`` is built explicitly. """ cdef PetscBool tval = asBool(flag) CHKERR( SVDTRLanczosSetExplicitMatrix(self.svd, tval) ) def getTRLanczosExplicitMatrix(self): """ Returns the flag indicating if ``Z=[A;B]`` is built explicitly. Returns ------- flag: bool True if ``Z=[A;B]`` is built explicitly. """ cdef PetscBool tval = PETSC_FALSE CHKERR( SVDTRLanczosGetExplicitMatrix(self.svd, &tval) ) return toBool(tval) setOperator = setOperators # backward compatibility # property problem_type: def __get__(self): return self.getProblemType() def __set__(self, value): self.setProblemType(value) property transpose_mode: def __get__(self): return self.getTransposeMode() def __set__(self, value): self.setTransposeMode(value) property which: def __get__(self): return self.getWhichSingularTriplets() def __set__(self, value): self.setWhichSingularTriplets(value) property tol: def __get__(self): return self.getTolerances()[0] def __set__(self, value): self.setTolerances(tol=value) property max_it: def __get__(self): return self.getTolerances()[1] def __set__(self, value): self.setTolerances(max_it=value) property track_all: def __get__(self): return self.getTrackAll() def __set__(self, value): self.setTrackAll(value) property ds: def __get__(self): 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/Sys.pyx000066400000000000000000000037671500534120000201260ustar00rootroot00000000000000# ----------------------------------------------------------------------------- cdef class Sys: @classmethod def getVersion(cls, devel=False, date=False, author=False): 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): 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): return toBool(SlepcInitializeCalled) @classmethod def isFinalized(cls): return toBool(SlepcFinalizeCalled) # --- xxx --- @classmethod def hasExternalPackage(cls, package): cdef const char *cpackage = NULL package = str2bytes(package, &cpackage) cdef PetscBool has = PETSC_FALSE CHKERR( SlepcHasExternalPackage(cpackage, &has) ) return toBool(has) # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/Util.pyx000066400000000000000000000014261500534120000202530ustar00rootroot00000000000000# ----------------------------------------------------------------------------- cdef class Util: @classmethod def createMatBSE(cls, Mat R, Mat C): """ Create a matrix that can be used to define a structured eigenvalue problem of type BSE (Bethe-Salpeter Equation). Parameters ---------- R: Mat The matrix for the diagonal block (resonant). C: Mat The matrix for the off-diagonal block (coupling). Returns ------- H: Mat The matrix with the block form H = [ R C; -C^H -R^T ]. """ cdef Mat H = Mat() CHKERR( MatCreateBSE(R.mat, C.mat, &H.mat) ) return H # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/allocate.pxi000066400000000000000000000013221500534120000210750ustar00rootroot00000000000000# ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/arraynpy.pxi000066400000000000000000000166751500534120000211770ustar00rootroot00000000000000# -------------------------------------------------------------------- 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_FARRAY 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*) 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 # -------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcbv.pxi000066400000000000000000000137321500534120000207570ustar00rootroot00000000000000cdef 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 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 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 slepc4py-3.23.1/src/slepc4py/SLEPc/slepcds.pxi000066400000000000000000000074471500534120000207640ustar00rootroot00000000000000cdef 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 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**) slepc4py-3.23.1/src/slepc4py/SLEPc/slepceps.pxi000066400000000000000000000425311500534120000211360ustar00rootroot00000000000000cdef 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 EPSTRLAN 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 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 # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- 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) # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcfn.pxi000066400000000000000000000043501500534120000207470ustar00rootroot00000000000000cdef 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*) slepc4py-3.23.1/src/slepc4py/SLEPc/slepcmfn.pxi000066400000000000000000000057561500534120000211370ustar00rootroot00000000000000cdef 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcmpi.pxi000066400000000000000000000013601500534120000211270ustar00rootroot00000000000000# ----------------------------------------------------------------------------- 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() # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcnep.pxi000066400000000000000000000325471500534120000211370ustar00rootroot00000000000000cdef 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 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 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 # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcpep.pxi000066400000000000000000000274761500534120000211460ustar00rootroot00000000000000cdef 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 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 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 # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcrg.pxi000066400000000000000000000044471500534120000207630ustar00rootroot00000000000000cdef 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*) slepc4py-3.23.1/src/slepc4py/SLEPc/slepcst.pxi000066400000000000000000000050141500534120000207700ustar00rootroot00000000000000cdef 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 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*) 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*) slepc4py-3.23.1/src/slepc4py/SLEPc/slepcsvd.pxi000066400000000000000000000210001500534120000211270ustar00rootroot00000000000000cdef 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 # ----------------------------------------------------------------------------- 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 # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/SLEPc/slepcsys.pxi000066400000000000000000000064031500534120000211630ustar00rootroot00000000000000cdef extern from * nogil: enum: PETSC_DECIDE enum: PETSC_DEFAULT enum: PETSC_DETERMINE ctypedef enum PetscBool: PETSC_TRUE, PETSC_YES, PETSC_FALSE, PETSC_NO, 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 slepc4py-3.23.1/src/slepc4py/SLEPc/slepcutil.pxi000066400000000000000000000001301500534120000213110ustar00rootroot00000000000000cdef extern from * nogil: PetscErrorCode MatCreateBSE(PetscMat,PetscMat,PetscMat*) slepc4py-3.23.1/src/slepc4py/__init__.pxd000066400000000000000000000000701500534120000201340ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com slepc4py-3.23.1/src/slepc4py/__init__.py000066400000000000000000000042021500534120000177720ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # ----------------------------------------------------------------------------- """ 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. .. _SLEPc: https://slepc.upv.es .. _PETSc: https://petsc.org """ __author__ = 'Lisandro Dalcin' __version__ = '3.23.1' __credits__ = 'SLEPc Team ' # ----------------------------------------------------------------------------- def init(args=None, arch=None): """ Initialize SLEPc. :Parameters: - `args`: command-line arguments, usually the 'sys.argv' list. - `arch`: specific configuration to use. .. note:: 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) 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. Using Python distutils (or perhaps 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') # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/__main__.py000066400000000000000000000043371500534120000177640ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com """ 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 '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() slepc4py-3.23.1/src/slepc4py/include/000077500000000000000000000000001500534120000173065ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py/include/slepc4py/000077500000000000000000000000001500534120000210515ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py/include/slepc4py/slepc4py.h000066400000000000000000000004741500534120000227720ustar00rootroot00000000000000/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ #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 */ slepc4py-3.23.1/src/slepc4py/include/slepc4py/slepc4py.i000066400000000000000000000030241500534120000227650ustar00rootroot00000000000000/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ /* ---------------------------------------------------------------- */ %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 %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 ) /* ---------------------------------------------------------------- */ /* * Local Variables: * mode: C * End: */ slepc4py-3.23.1/src/slepc4py/lib/000077500000000000000000000000001500534120000164315ustar00rootroot00000000000000slepc4py-3.23.1/src/slepc4py/lib/__init__.py000066400000000000000000000032761500534120000205520ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # ----------------------------------------------------------------------------- """ 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) # ----------------------------------------------------------------------------- slepc4py-3.23.1/src/slepc4py/lib/slepc.cfg000066400000000000000000000001221500534120000202130ustar00rootroot00000000000000SLEPC_DIR = %(SLEPC_DIR)s PETSC_DIR = %(PETSC_DIR)s PETSC_ARCH = %(PETSC_ARCH)s slepc4py-3.23.1/test/000077500000000000000000000000001500534120000143105ustar00rootroot00000000000000slepc4py-3.23.1/test/runtests.py000066400000000000000000000170421500534120000165550ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com import 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()) slepc4py-3.23.1/test/test_object.py000066400000000000000000000134451500534120000171760ustar00rootroot00000000000000from 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 # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main()