pax_global_header00006660000000000000000000000064145410404730014514gustar00rootroot0000000000000052 comment=3d6aeca64b5ce306aa0ab25c9746e301722e9d38 petsc4py-3.19.6/000077500000000000000000000000001454104047300133675ustar00rootroot00000000000000petsc4py-3.19.6/CHANGES.rst000066400000000000000000000141341454104047300151740ustar00rootroot00000000000000========================= CHANGES: PETSc for Python ========================= :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Release 3.19.0 ============== - Update to PETSc 3.19 release. - Expose ``PetscDevice`` and ``PetscDeviceContext`` API as ``PETSc.Device`` and ``PETSc.DeviceContext`` classes respectively. Release 3.18.0 ============== - Update to PETSc 3.18 release. Release 3.17.0 ============== - Update to PETSc 3.17 release. Release 3.16.0 ============== - Update to PETSc 3.16 release. Release 3.15.0 ============== - Update to PETSc 3.15 release. Release 3.14.1 ============== - Fix build issues after changes in recent PETSc patch releases. - Add various missing types and enums definitions. - Update Cython build, require ``Cython >= 0.24``. Release 3.14.0 ============== - Update to PETSc 3.14 release. Release 3.13.0 ============== - Update to PETSc 3.13 release. Release 3.12.0 ============== - Update to PETSc 3.12 release. Release 3.11.0 ============== - Update to PETSc 3.11 release. Release 3.10.1 ============== - Fix for removal of ``SNESTEST``. - Fix ``Mat`` in-place divide. Release 3.10.0 ============== - Update to PETSc 3.10 release. Release 3.9.1 ============= - Add ``Mat.zeroRowsColumnsLocal()``. - Add ``Mat.getISLocalMat()``. - Add ``Mat.convertISToAIJ()``. Release 3.9.0 ============= - Update to PETSc 3.9 release. Release 3.8.0 ============= - Update to PETSc 3.8 release. Release 3.7.0 ============= - Update to PETSc 3.7 release. Release 3.6.0 ============= - Update to PETSc 3.6 release. Release 3.5.1 ============= - Add ``Log.{begin|view|destroy}()``. - Add ``Mat.SOR()`` and ``Mat.SORType``. - Add ``DMPlex.createCoarsePointIS()``. - Add ``LGMap.createSF()``. - Add ``SNES.getVIInactiveSet()``. - Add ``Vec.isaxpy()``. - Add ``PC.setReusePreconditioner()``. - Return correct type in ``DM.getCoordinateDM()``. - Fix SWIG wrappers to handle 64bit ``PetscInt``. - Fix linker flags for Python from Fink. Release 3.5 =========== - Update to PETSc 3.5 release. Release 3.4 =========== - Update to PETSc 3.4 release. - Add support for ``DMComposite`` and ``DMPlex``. - Change ``Mat.getSizes()`` to return ``((m,M),(n,N))``. Release 3.3.1 ============= - Fix ``Options.getAll()`` mishandling values with negative numbers. - Minor backward compatibility fix for PETSc 3.2 . - Minor bugfix for TSPYTHON subtype. Release 3.3 =========== - Update to PETSc 3.3 release. - Change ``Vec.getLocalForm()`` to ``Vec.localForm()`` for use with context manager and add ``Vec.setMPIGhost()``. - Add ``AO.createMemoryScalable()`` and ``LGMap.block()`` / ``LGMap.unblock()`` - Add ``Object.handle`` property (C pointer as a Python integer). Can be used with ``ctypes`` to pass a PETSc handle. - Add ``Comm.tompi4py()`` to get a ``mpi4py`` communicator instance. Release 1.2 =========== - Update to PETSc 3.2 release. - Add new ``DM`` class , make ``DA`` inherit from ``DM``. - Better support for inplace LU/ILU and Cholesky/ICC factorization and factor PC subtypes. - Now the ``Mat``/``PC``/``KSP``/``SNES``/``TS`` Python subtypes are implemented with Cython. - Better interaction between Python garbage collector and PETSc objects. - Support for PEP 3118 and legacy Python's buffer interface. Release 1.1.2 ============= This is a new-features and bug-fix release. - Add support for copying and computing complements in ``IS`` (``IS.copy()`` and ``IS.complement()``). - Add support for coarsening in ``DA`` (``DA.coarsen()``). - Support for shallow copy and deep copy operations (use ``copy.copy`` and ``copy.deepcopy``). Deep copy is only supported for a bunch of types (``IS``, ``Scatter``, ``Vec``, ``Mat``) - Support for ``pip install petsc4py`` to download and install PETSc. Release 1.1.1 ============= This is a new-features and bug-fix release. - Support for setting PETSC_COMM_WORLD before PETSc initialization. - Support for coordinates, refinement and interpolation in DA. Many thanks to Blaise Bourdin. - Workaround build failures when PETSc is built with *mpiuni*. - Workaround GIL-related APIs for non-threaded Python builds. Release 1.1 =========== - Update for API cleanups, changes, and new calls in PETSc 3.1 and some other missing features. - Add support for Jed Brown's THETA an GL timestepper implementations. - Fix the annoying issues related to Open MPI shared libraries dependencies and Python dynamic loading. - Many minor bug-fixes. Many thanks to Ethan Coon, Dmitry Karpeev, Juha Jaykka, and Michele De Stefano. Release 1.0.3 ============= This is a bug-fix release. - Added a quick fix to solve build issues. The macro __SDIR__ is no longer passed to the compiler in the command line. Release 1.0.2 ============= This is a new-features and bug-fix release. - Now ``petsc4py`` works against core PETSc built with complex scalars. - Added support for PETSc logging features like stages, classes and events. Stages and events support the context manager interface (``with`` statement). - Documentation generated with Epydoc and Sphinx is now included in the release tarball. - Removed enumeration-like classes from the ``petsc4py.PETSc`` module namespace. For example, now you have to use ``PETSc.KSP.Type`` instead of ``PETSc.KSPType``. - The ``PETSc.IS`` to ``numpy.ndarray`` conversion now works for stride and block index sets. - Implemented a more robust import machinery for multi-arch ``petsc4py`` installations. Now a wrong value in the ``PETSC_ARCH`` environmental variable emit a warning (instead of failing) at import time. - The unittest-based testsuite now can run under ``nose`` with its default options. - Removed the dependency on ``numpy.distutils``, just use core Python ``distutils``. Release 1.0.1 ============= This is a bug-fix release. Compile Cython-generated C sources with ``-Wwrite-strings`` removed, as this flag (inherited from PETSc) made GCC emit a lot of (harmless but annoying) warnings about conversion of string literals to non-const char pointers. Release 1.0.0 ============= This is the fist release of the all-new, Cython-based, implementation of *PETSc for Python*. petsc4py-3.19.6/DESCRIPTION.rst000066400000000000000000000024251454104047300157070ustar00rootroot00000000000000PETSc for Python ================ Python bindings for PETSc. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py Citations --------- If PETSc 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 * S. Balay, S. Abhyankar, M. Adams, S. Benson, J. Brown, P. Brune, K. Buschelman, E. Constantinescu, L. Dalcin, A. Dener, V. Eijkhout, J. Faibussowitsch, W. Gropp, V. Hapla, T. Isaac, P. Jolivet, D. Karpeyev, D. Kaushik, M. Knepley, F. Kong, S. Kruger, D. May, L. Curfman McInnes, R. Mills, L. Mitchell, T. Munson, J. Roman, K. Rupp, P. Sanan, J Sarich, B. Smith, S. Zampini, H. Zhang, and H. Zhang, J. Zhang, *PETSc/TAO Users Manual*, ANL-21/39 - Revision 3.19, 2023. http://dx.doi.org/10.2172/1968587, https://petsc.org/release/docs/manual/manual.pdf petsc4py-3.19.6/LICENSE.rst000066400000000000000000000026311454104047300152050ustar00rootroot00000000000000========================= LICENSE: PETSc for Python ========================= :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com Copyright (c) 2023, Lisandro Dalcin. 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. petsc4py-3.19.6/MANIFEST.in000066400000000000000000000011301454104047300151200ustar00rootroot00000000000000include setup*.py *.toml *.cfg *.rst recursive-include demo [M,m]akefile* *.py *.pyx *.i *.[hc] recursive-include demo .f2py_f2cmap *.pyf *.[fF]90 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/petsc4py/PETSc.c exclude src/petsc4py/PETSc.h exclude src/petsc4py/PETSc_api.h include docs/*.html include docs/*.pdf include docs/*.info include docs/*.[137] include docs/*.rst recursive-include docs/usrman * recursive-include docs/apiref * recursive-include docs/source * petsc4py-3.19.6/PKG-INFO000066400000000000000000000047531454104047300144750ustar00rootroot00000000000000Metadata-Version: 2.1 Name: petsc4py Version: 3.19.6 Summary: PETSc for Python Home-page: https://gitlab.com/petsc/petsc Download-URL: https://pypi.io/packages/source/p/petsc4py/petsc4py-3.19.6.tar.gz Author: Lisandro Dalcin Author-email: dalcinl@gmail.com Maintainer: PETSc Team Maintainer-email: petsc-maint@mcs.anl.gov License: BSD-2-Clause Keywords: scientific computing,parallel computing,MPI,PETSc Platform: POSIX Platform: Linux Platform: macOS Platform: FreeBSD Classifier: License :: OSI Approved :: BSD License 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 :: 2 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 PETSc for Python ================ Python bindings for PETSc. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py Citations --------- If PETSc 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 * S. Balay, S. Abhyankar, M. Adams, S. Benson, J. Brown, P. Brune, K. Buschelman, E. Constantinescu, L. Dalcin, A. Dener, V. Eijkhout, J. Faibussowitsch, W. Gropp, V. Hapla, T. Isaac, P. Jolivet, D. Karpeyev, D. Kaushik, M. Knepley, F. Kong, S. Kruger, D. May, L. Curfman McInnes, R. Mills, L. Mitchell, T. Munson, J. Roman, K. Rupp, P. Sanan, J Sarich, B. Smith, S. Zampini, H. Zhang, and H. Zhang, J. Zhang, *PETSc/TAO Users Manual*, ANL-21/39 - Revision 3.19, 2023. http://dx.doi.org/10.2172/1968587, https://petsc.org/release/docs/manual/manual.pdf petsc4py-3.19.6/README.rst000066400000000000000000000014521454104047300150600ustar00rootroot00000000000000================ PETSc for Python ================ Overview -------- Welcome to PETSc for Python. This package provides Python bindings for PETSc_, the *Portable, Extensible Toolkit for Scientific Computation*. Dependencies ------------ * Python_ 2.7, 3.3 or above. * A recent NumPy_ release. * A matching version of PETSc_ built with *shared/dynamic libraries*. * To work with the in-development version, you need Cython_. .. _Python: https://www.python.org .. _NumPy: https://www.numpy.org .. _PETSc: https://petsc.org .. _Cython: https://www.cython.org Documentation ------------- * https://petsc4py.readthedocs.org/, This does not contain the epydoc-generated API reference. * https://www.mcs.anl.gov/petsc/petsc4py-current/docs/, This is for the last release, not the in-development version. petsc4py-3.19.6/conf/000077500000000000000000000000001454104047300143145ustar00rootroot00000000000000petsc4py-3.19.6/conf/__init__.py000066400000000000000000000000001454104047300164130ustar00rootroot00000000000000petsc4py-3.19.6/conf/confpetsc.py000066400000000000000000001040131454104047300166510ustar00rootroot00000000000000# -------------------------------------------------------------------- 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 dep_util except ImportError: from distutils import dep_util 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 = '0.29.36' 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 dep_util.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('-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('-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 from distutils.unixccompiler import UnixCCompiler rpath_option_orig = UnixCCompiler.runtime_library_dir_option def rpath_option(compiler, dir): option = rpath_option_orig(compiler, dir) if sys.platform[:5] == 'linux': if option.startswith('-R'): option = option.replace('-R', '-Wl,-rpath,', 1) elif option.startswith('-Wl,-R'): option = option.replace('-Wl,-R', '-Wl,-rpath,', 1) return option UnixCCompiler.runtime_library_dir_option = rpath_option # -------------------------------------------------------------------- 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']) petsc_lib['runtime_library_dirs'].append(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)] 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 = 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 # if sys.platform == 'darwin': for attr in ('preprocessor', 'compiler', 'compiler_cxx', 'compiler_so', 'linker_so', 'linker_exe'): compiler_cmd = getattr(compiler, attr, []) while '-mno-fused-madd' in compiler_cmd: compiler_cmd.remove('-mno-fused-madd') 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 + cmd_petsc_opts def initialize_options(self): _build.initialize_options(self) self.petsc_dir = None self.petsc_arch = None def finalize_options(self): _build.finalize_options(self) 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.petsc_dir = None self.petsc_arch = None self._outputs = [] def finalize_options(self): _build_ext.finalize_options(self) self.set_undefined_options('build', ('petsc_dir', 'petsc_dir'), ('petsc_arch', 'petsc_arch')) if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu') or sys.platform.startswith('sunos')) and sysconfig.get_config_var('Py_ENABLE_SHARED')): py_version = sysconfig.get_python_version() bad_pylib_dir = os.path.join(sys.prefix, "lib", "python" + py_version, "config") try: self.library_dirs.remove(bad_pylib_dir) except ValueError: pass pylib_dir = sysconfig.get_config_var("LIBDIR") if pylib_dir not in self.library_dirs: self.library_dirs.append(pylib_dir) if pylib_dir not in self.rpath: self.rpath.append(pylib_dir) if sys.exec_prefix == '/usr': self.library_dirs.remove(pylib_dir) self.rpath.remove(pylib_dir) 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("([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 # -------------------------------------------------------------------- petsc4py-3.19.6/conf/cythonize.py000077500000000000000000000024451454104047300167120ustar00rootroot00000000000000#!/usr/bin/env python """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('petsc4py', 'PETSc.pyx') target = os.path.join('petsc4py', 'PETSc.c') args += ['--working', srcdir] args += [source, '--output-file', target] sys.exit(cythonize(args)) if __name__ == "__main__": main() petsc4py-3.19.6/conf/cythonize.sh000077500000000000000000000002231454104047300166640ustar00rootroot00000000000000#!/bin/sh topdir=$(cd $(dirname "$0")/.. && pwd) python$py "$topdir/conf/cythonize.py" \ --working "$topdir/src" $@ \ "petsc4py/PETSc.pyx" petsc4py-3.19.6/conf/epydoc.cfg000066400000000000000000000105531454104047300162640ustar00rootroot00000000000000[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: petsc4py # 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: petsc4py.__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 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: PETSc for Python # The documented project's URL. url: https://gitlab.com/petsc/petsc # 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 petsc4py-3.19.6/conf/epydocify.py000077500000000000000000000055051454104047300166710ustar00rootroot00000000000000#!/usr/bin/env python # -------------------------------------------------------------------- from petsc4py import PETSc # -------------------------------------------------------------------- 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() # -------------------------------------------------------------------- petsc4py-3.19.6/demo/000077500000000000000000000000001454104047300143135ustar00rootroot00000000000000petsc4py-3.19.6/demo/binary-io/000077500000000000000000000000001454104047300162045ustar00rootroot00000000000000petsc4py-3.19.6/demo/binary-io/makefile000066400000000000000000000004551454104047300177100ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: ${MPIEXEC} ${PYTHON} matvecio.py .PHONY:clean clean: ${RM} matrix-*.dat* vector-*.dat* ${RM} *.py[co] ${RM} -r __pycache__ petsc4py-3.19.6/demo/binary-io/matvecio.py000066400000000000000000000021121454104047300203610ustar00rootroot00000000000000try: range = xrange except NameError: pass import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc m, n = 16, 32 A = PETSc.Mat().create(PETSc.COMM_WORLD) A.setSizes([m*n, m*n]) A.setFromOptions() A.setUp() Istart, Iend = A.getOwnershipRange() for I in range(Istart, Iend): A[I,I] = 4 i = I//n if i>0 : J = I-n; A[I,J] = -1 if i0 : J = I-1; A[I,J] = -1 if j x(2:m-1, 2:n-1) ! center uN => x(2:m-1, 1:n-2) ! north uS => x(2:m-1, 3:n ) ! south uW => x(1:m-2, 2:n-1) ! west uE => x(3:m, 2:n-1) ! east ! compute nonlinear function hx = 1.0/(m-1) ! x grid spacing hy = 1.0/(n-1) ! y grid spacing f(:,:) = x f(2:m-1, 2:n-1) = & (2*u - uE - uW) * (hy/hx) & + (2*u - uN - uS) * (hx/hy) & - alpha * exp(u) * (hx*hy) end subroutine bratu2d petsc4py-3.19.6/demo/bratu2d/bratu2dnpy.py000066400000000000000000000010571454104047300203250ustar00rootroot00000000000000# file: bratu2dnpy.py def bratu2d(alpha, x, f): # get 'exp' from numpy from numpy import exp # setup 5-points stencil u = x[1:-1, 1:-1] # center uN = x[1:-1, :-2] # north uS = x[1:-1, 2: ] # south uW = x[ :-2, 1:-1] # west uE = x[2:, 1:-1] # east # compute nonlinear function nx, ny = x.shape hx = 1.0/(nx-1) # x grid spacing hy = 1.0/(ny-1) # y grid spacing f[:,:] = x f[1:-1, 1:-1] = \ (2*u - uE - uW) * (hy/hx) \ + (2*u - uN - uS) * (hx/hy) \ - alpha * exp(u) * (hx*hy) petsc4py-3.19.6/demo/bratu2d/makefile000066400000000000000000000013161454104047300173570ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python F2PY = f2py --quiet F2PY_FLAGS = F2PY_FLAGS = -DF2PY_REPORT_ATEXIT -DF2PY_REPORT_ON_ARRAY_COPY=0 F2PY_FLAGS =--noarch --f90flags='' F2PY_FLAGS +=-DF2PY_REPORT_ON_ARRAY_COPY=1 -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: run_py run_f90 .PHONY:run_py run_py: ${MPIEXEC} ${PYTHON} bratu2d.py -impl python MODULE=bratu2df90 .PHONY:${MODULE} ${MODULE}: ${MODULE}.so ${MODULE}.so: ${MODULE}.f90 ${F2PY} ${F2PY_FLAGS} -c $< -m ${MODULE} .PHONY:run_f90 run_f90: ${MODULE} ${MPIEXEC} ${PYTHON} bratu2d.py -impl fortran .PHONY:clean clean: ${RM} *.py[co] ${MODULE}*.so ${RM} -r __pycache__ petsc4py-3.19.6/demo/bratu3d/000077500000000000000000000000001454104047300156575ustar00rootroot00000000000000petsc4py-3.19.6/demo/bratu3d/bratu3d.py000066400000000000000000000153321454104047300176010ustar00rootroot00000000000000# ------------------------------------------------------------------------ # # Solid Fuel Ignition (SFI) problem. This problem is modeled by the # partial differential equation # # -Laplacian(u) - lambda * exp(u) = 0, 0 < x,y,z < 1, # # with boundary conditions # # u = 0 for x = 0, x = 1, y = 0, y = 1, z = 0, z = 1 # # A finite difference approximation with the usual 7-point stencil # is used to discretize the boundary value problem to obtain a # nonlinear system of equations. The problem is solved in a 3D # rectangular domain, using distributed arrays (DAs) to partition # the parallel grid. # # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, petsc4py petsc4py.init(sys.argv) from numpy import exp, sqrt from petsc4py import PETSc class Bratu3D(object): def __init__(self, da, lambda_): assert da.getDim() == 3 self.da = da self.lambda_ = lambda_ self.localX = da.createLocalVec() def formInitGuess(self, snes, X): # x = self.da.getVecArray(X) # mx, my, mz = self.da.getSizes() hx, hy, hz = [1.0/(m-1) for m in [mx, my, mz]] lambda_ = self.lambda_ scale = lambda_/(lambda_ + 1.0) # (xs, xe), (ys, ye), (zs, ze) = self.da.getRanges() for k in range(zs, ze): min_k = min(k,mz-k-1)*hz for j in range(ys, ye): min_j = min(j,my-j-1)*hy for i in range(xs, xe): min_i = min(i,mx-i-1)*hx if (i==0 or j==0 or k==0 or i==mx-1 or j==my-1 or k==mz-1): # boundary points x[i, j, k] = 0.0 else: # interior points min_kij = min(min_i,min_j,min_k) x[i, j, k] = scale*sqrt(min_kij) def formFunction(self, snes, X, F): # self.da.globalToLocal(X, self.localX) x = self.da.getVecArray(self.localX) f = self.da.getVecArray(F) # mx, my, mz = self.da.getSizes() hx, hy, hz = [1.0/m for m in [mx, my, mz]] hxhyhz = hx*hy*hz hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; lambda_ = self.lambda_ # (xs, xe), (ys, ye), (zs, ze) = self.da.getRanges() for k in range(zs, ze): for j in range(ys, ye): for i in range(xs, xe): if (i==0 or j==0 or k==0 or i==mx-1 or j==my-1 or k==mz-1): f[i, j, k] = x[i, j, k] - 0 else: u = x[ i , j , k ] # center u_e = x[i+1 , j , k ] # east u_w = x[i-1 , j , k ] # west u_n = x[ i , j+1 , k ] # north u_s = x[ i , j-1 , k ] # south u_u = x[ i , j , k+1] # up u_d = x[ i , j , k-1] # down u_xx = (-u_e + 2*u - u_w)*hyhzdhx u_yy = (-u_n + 2*u - u_s)*hxhzdhy u_zz = (-u_u + 2*u - u_d)*hxhydhz f[i, j, k] = u_xx + u_yy + u_zz \ - lambda_*exp(u)*hxhyhz def formJacobian(self, snes, X, J, P): # self.da.globalToLocal(X, self.localX) x = self.da.getVecArray(self.localX) # mx, my, mz = self.da.getSizes() hx, hy, hz = [1.0/m for m in [mx, my, mz]] hxhyhz = hx*hy*hz hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; lambda_ = self.lambda_ # P.zeroEntries() row = PETSc.Mat.Stencil() col = PETSc.Mat.Stencil() # (xs, xe), (ys, ye), (zs, ze) = self.da.getRanges() for k in range(zs, ze): for j in range(ys, ye): for i in range(xs, xe): row.index = (i,j,k) row.field = 0 if (i==0 or j==0 or k==0 or i==mx-1 or j==my-1 or k==mz-1): P.setValueStencil(row, row, 1.0) else: u = x[i,j,k] diag = (2*(hyhzdhx+hxhzdhy+hxhydhz) - lambda_*exp(u)*hxhyhz) for index, value in [ ((i,j,k-1), -hxhydhz), ((i,j-1,k), -hxhzdhy), ((i-1,j,k), -hyhzdhx), ((i, j, k), diag), ((i+1,j,k), -hyhzdhx), ((i,j+1,k), -hxhzdhy), ((i,j,k+1), -hxhydhz), ]: col.index = index col.field = 0 P.setValueStencil(row, col, value) P.assemble() if J != P: J.assemble() # matrix-free operator return PETSc.Mat.Structure.SAME_NONZERO_PATTERN OptDB = PETSc.Options() n = OptDB.getInt('n', 16) nx = OptDB.getInt('nx', n) ny = OptDB.getInt('ny', n) nz = OptDB.getInt('nz', n) lambda_ = OptDB.getReal('lambda', 6.0) da = PETSc.DMDA().create([nx, ny, nz], stencil_width=1) pde = Bratu3D(da, lambda_) snes = PETSc.SNES().create() F = da.createGlobalVec() snes.setFunction(pde.formFunction, F) fd = OptDB.getBool('fd', False) mf = OptDB.getBool('mf', False) if mf: J = None snes.setUseMF() else: J = da.createMat() snes.setJacobian(pde.formJacobian, J) if fd: snes.setUseFD() snes.getKSP().setType('cg') snes.setFromOptions() X = da.createGlobalVec() pde.formInitGuess(snes, X) snes.solve(None, X) U = da.createNaturalVec() da.globalToNatural(X, U) if OptDB.getBool('plot_mpl', False): def plot_mpl(da, U): comm = da.getComm() rank = comm.getRank() scatter, U0 = PETSc.Scatter.toZero(U) scatter.scatter(U, U0, False, PETSc.Scatter.Mode.FORWARD) if rank == 0: try: from matplotlib import pylab except ImportError: PETSc.Sys.Print("matplotlib not available") else: from numpy import mgrid nx, ny, nz = da.sizes solution = U0[...].reshape(da.sizes, order='f') xx, yy = mgrid[0:1:1j*nx,0:1:1j*ny] pylab.contourf(xx, yy, solution[:, :, nz//2]) pylab.axis('equal') pylab.xlabel('X') pylab.ylabel('Y') pylab.title('Z/2') pylab.show() comm.barrier() plot_mpl(da, U) petsc4py-3.19.6/demo/bratu3d/makefile000066400000000000000000000006221454104047300173570ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: run_fd run_mf .PHONY:run_fd run_fd: ${MPIEXEC} ${PYTHON} bratu3d.py -fd -nx 7 -ny 8 -nz 9 .PHONY:run_mf run_mf: ${MPIEXEC} ${PYTHON} bratu3d.py -mf -nx 9 -ny 8 -nz 7 .PHONY:clean clean: ${RM} *.py[co] ${RM} -r __pycache__ petsc4py-3.19.6/demo/dmplex/000077500000000000000000000000001454104047300156045ustar00rootroot00000000000000petsc4py-3.19.6/demo/dmplex/anisotropic_adaptation.py000066400000000000000000000062421454104047300227200ustar00rootroot00000000000000import sys,petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np def sensor(x, y): """ Classic hyperbolic sensor function for testing multi-scale anisotropic mesh adaptation: f:[-1, 1]² → R, f(x, y) = sin(50xy)/100 if |xy| > 2Ï€/50 else sin(50xy) (mapped to have domain [0,1]² in this case). """ xy = (2*x - 1)*(2*y - 1) ret = np.sin(50*xy) if np.abs(xy) > 2*np.pi/50: ret *= 0.01 return ret # Set metric parameters h_min = 1.0e-10 # Minimum tolerated metric magnitude ~ cell size h_max = 1.0e-01 # Maximum tolerated metric magnitude ~ cell size a_max = 1.0e+05 # Maximum tolerated anisotropy targetComplexity = 10000.0 # Analogous to number of vertices in adapted mesh p = 1.0 # Láµ– normalization order # Create a uniform mesh OptDB = PETSc.Options() dim = OptDB.getInt('dim', 2) numEdges = 10 simplex = True plex = PETSc.DMPlex().createBoxMesh([numEdges]*dim, simplex=simplex) plex.distribute() plex.view() viewer = PETSc.Viewer().createVTK("anisotropic_mesh_0.vtk", "w") viewer(plex) # Do four mesh adaptation iterations for i in range(1, 5): vStart, vEnd = plex.getDepthStratum(0) # Create a P1 sensor function comm = plex.getComm() fe = PETSc.FE().createLagrange(dim, 1, simplex, 1, -1, comm=comm) plex.setField(0, fe) plex.createDS() f = plex.createLocalVector() csec = plex.getCoordinateSection() coords = plex.getCoordinatesLocal() pf = f.getArray() pcoords = coords.getArray() for v in range(vStart, vEnd): off = csec.getOffset(v) x = pcoords[off] y = pcoords[off+1] pf[off//dim] = sensor(x, y) f.setName("Sensor") viewer = PETSc.Viewer().createVTK(f"sensor_{i}.vtk", "w") viewer(f) # Recover the gradient of the sensor function dmGrad = plex.clone() fe = PETSc.FE().createLagrange(dim, dim, simplex, 1, -1, comm=comm) dmGrad.setField(0, fe) dmGrad.createDS() g = dmGrad.createLocalVector() plex.computeGradientClementInterpolant(f, g) g.setName("Gradient") viewer = PETSc.Viewer().createVTK(f"gradient_{i}.vtk", "w") viewer(g) # Recover the Hessian of the sensor function dmHess = plex.clone() H = dmHess.metricCreate() dmGrad.computeGradientClementInterpolant(g, H) H.setName("Hessian") viewer = PETSc.Viewer().createVTK(f"hessian_{i}.vtk", "w") viewer(H) # Obtain a metric by Láµ– normalization dmHess.metricSetMinimumMagnitude(h_min) dmHess.metricSetMaximumMagnitude(h_max) dmHess.metricSetMaximumAnisotropy(a_max) dmHess.metricSetNormalizationOrder(p) dmHess.metricSetTargetComplexity(targetComplexity) metric = dmHess.metricCreate() det = dmHess.metricDeterminantCreate() dmHess.metricNormalize(H, metric, det) metric.setName("Metric") viewer = PETSc.Viewer().createVTK(f"metric_{i}.vtk", "w") viewer(metric) # Call adapt routine - boundary label None by default plex = plex.adaptMetric(metric) plex.distribute() plex.view() # Write to VTK file viewer = PETSc.Viewer().createVTK(f"anisotropic_mesh_{i}.vtk", "w") viewer(plex) petsc4py-3.19.6/demo/dmplex/distribute_field.py000066400000000000000000000034341454104047300215030ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Created on Fri Dec 25 17:03:18 2015 @author: ale """ import sys,petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np dim = 2 if not PETSc.COMM_WORLD.rank: coords = np.asarray([[0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [0.0, 0.5], [0.5, 0.5], [1.0, 0.5], [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]], dtype=PETSc.RealType) cells = np.asarray([[0,1,4,3], [1,2,5,4], [3,4,7,6], [4,5,8,7]], dtype=PETSc.IntType) else: coords = np.zeros((0, 2), dtype=PETSc.RealType) cells = np.zeros((0, 4), dtype=PETSc.IntType) plex = PETSc.DMPlex().createFromCellList(dim, cells, coords, comm=PETSc.COMM_WORLD) pStart, pEnd = plex.getChart() plex.view() print("pStart, pEnd: ", pStart, pEnd) # Create section with 1 field with 1 DoF per vertex, edge and cell numComp = 1 # Start with an empty vector numDof = [0] * 3 # Field defined on vertices numDof[0] = 1 # Field defined on edges numDof[1] = 1 # Field defined on cells numDof[2] = 1 plex.setNumFields(1) origSect = plex.createSection(numComp, numDof) origSect.setFieldName(0, 'TestField') origSect.setUp() origSect.view() plex.setSection(origSect) origVec = plex.createGlobalVec() origVec.view() origVec.setValues(list(range(pStart, pEnd)),list(range(pStart,pEnd))) origVec.assemblyBegin() origVec.assemblyEnd() origVec.view() if PETSc.COMM_WORLD.size > 1: sf = plex.distribute() sf.view() newSect, newVec = plex.distributeField(sf, origSect, origVec) else: newSect = origSect newVec = origVec newSect.view() newVec.view() petsc4py-3.19.6/demo/dmplex/isotropic_adaptation.py000066400000000000000000000016571454104047300224060ustar00rootroot00000000000000import sys,petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np OptDB = PETSc.Options() dim = OptDB.getInt('dim', 2) plex = PETSc.DMPlex().createBoxMesh([4]*dim, simplex=True) plex.distribute() plex.view() # Create two metric tensor fields corresponding to uniform mesh sizes of 0.1 and 0.2 metric1 = plex.metricCreateUniform(100.0) metric2 = plex.metricCreateUniform(25.0) # The metrics can be combined using intersection, the result of which corresponds to # the maximum ellipsoid at each point metric = plex.metricCreate() plex.metricIntersection2(metric1, metric2, metric) metric1.axpy(-1, metric) assert np.isclose(metric1.norm(), 0.0) # Call adapt routine - boundary label None by default newplex = plex.adaptMetric(metric) newplex.view() # Write to VTK file viewer = PETSc.Viewer().createVTK('base_mesh.vtk', 'w') viewer(plex) viewer = PETSc.Viewer().createVTK('isotropic_mesh.vtk', 'w') viewer(newplex) petsc4py-3.19.6/demo/kspsolve/000077500000000000000000000000001454104047300161615ustar00rootroot00000000000000petsc4py-3.19.6/demo/kspsolve/makefile000066400000000000000000000006201454104047300176570ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: run_1 run_2 SCRIPT1=test_mat_cg .PHONY:run_1 run_1: ${MPIEXEC} ${PYTHON} ${SCRIPT1}.py SCRIPT2= test_mat_ksp .PHONY:run_2 run_2: ${MPIEXEC} ${PYTHON} ${SCRIPT2}.py .PHONY:clean clean: ${RM} *.py[co] ${RM} -r __pycache__ petsc4py-3.19.6/demo/kspsolve/petsc-cg.py000066400000000000000000000013361454104047300202430ustar00rootroot00000000000000def cg(A, b, x, imax=50, eps=1e-6): """ A, b, x : matrix, rhs, solution imax : maximum allowed iterations eps : tolerance for convergence """ # allocate work vectors r = b.duplicate() d = b.duplicate() q = b.duplicate() # initialization i = 0 A.mult(x, r) r.aypx(-1, b) r.copy(d) delta_0 = r.dot(r) delta = delta_0 # enter iteration loop while i < imax and \ delta > delta_0 * eps**2: A.mult(d, q) alpha = delta / d.dot(q) x.axpy(+alpha, d) r.axpy(-alpha, q) delta_old = delta delta = r.dot(r) beta = delta / delta_old d.aypx(beta, r) i = i + 1 return i, delta**0.5 petsc4py-3.19.6/demo/kspsolve/petsc-ksp.py000066400000000000000000000004641454104047300204500ustar00rootroot00000000000000# create linear solver ksp = PETSc.KSP() ksp.create(PETSc.COMM_WORLD) # use conjugate gradients ksp.setType('cg') # and incomplete Cholesky ksp.getPC().setType('icc') # obtain sol & rhs vectors x, b = A.createVecs() x.set(0) b.set(1) # and next solve ksp.setOperators(A) ksp.setFromOptions() ksp.solve(b, x) petsc4py-3.19.6/demo/kspsolve/petsc-mat.py000066400000000000000000000016601454104047300204330ustar00rootroot00000000000000try: range = xrange except: pass from petsc4py import PETSc # grid size and spacing m, n = 32, 32 hx = 1.0/(m-1) hy = 1.0/(n-1) # create sparse matrix A = PETSc.Mat() A.create(PETSc.COMM_WORLD) A.setSizes([m*n, m*n]) A.setType('aij') # sparse A.setPreallocationNNZ(5) # precompute values for setting # diagonal and non-diagonal entries diagv = 2.0/hx**2 + 2.0/hy**2 offdx = -1.0/hx**2 offdy = -1.0/hy**2 # loop over owned block of rows on this # processor and insert entry values 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 # communicate off-processor values # and setup internal data structures # for performing parallel operations A.assemblyBegin() A.assemblyEnd() petsc4py-3.19.6/demo/kspsolve/test_mat_cg.py000066400000000000000000000025231454104047300210260ustar00rootroot00000000000000try: execfile except NameError: def execfile(file, globals=globals(), locals=locals()): fh = open(file, "r") try: exec(fh.read()+"\n", globals, locals) finally: fh.close() import petsc4py, sys petsc4py.init(sys.argv) from petsc4py import PETSc execfile('petsc-mat.py') execfile('petsc-cg.py') x, b = A.createVecs() ksp = PETSc.KSP().create() ksp.setType('cg') ksp.getPC().setType('none') ksp.setOperators(A) ksp.setFromOptions() ksp.max_it = 100 ksp.rtol = 1e-5 ksp.atol = 0 x.set(0) b.set(1) ksp.solve(b,x) print("iterations: %d residual norm: %g" % (ksp.its, ksp.norm)) x.set(0) b.set(1) its, norm = cg(A,b,x,100,1e-5) print("iterations: %d residual norm: %g" % (its, norm)) OptDB = PETSc.Options() if OptDB.getBool('plot', True): da = PETSc.DMDA().create([m,n]) u = da.createGlobalVec() x.copy(u) draw = PETSc.Viewer.DRAW() OptDB['draw_pause'] = 1 draw(u) if OptDB.getBool('plot_mpl', False): try: from matplotlib import pylab except ImportError: print("matplotlib not available") else: from numpy import mgrid X, Y = mgrid[0:1:1j*m,0:1:1j*n] Z = x[...].reshape(m,n) pylab.figure() pylab.contourf(X,Y,Z) pylab.plot(X.ravel(),Y.ravel(),'.k') pylab.axis('equal') pylab.colorbar() pylab.show() petsc4py-3.19.6/demo/kspsolve/test_mat_ksp.py000066400000000000000000000017161454104047300212350ustar00rootroot00000000000000try: execfile except NameError: def execfile(file, globals=globals(), locals=locals()): fh = open(file, "r") try: exec(fh.read()+"\n", globals, locals) finally: fh.close() import petsc4py, sys petsc4py.init(sys.argv) from petsc4py import PETSc execfile('petsc-mat.py') execfile('petsc-ksp.py') OptDB = PETSc.Options() if OptDB.getBool('plot', True): da = PETSc.DMDA().create([m,n]) u = da.createGlobalVec() x.copy(u) draw = PETSc.Viewer.DRAW() OptDB['draw_pause'] = 1 draw(u) if OptDB.getBool('plot_mpl', False): try: from matplotlib import pylab except ImportError: print("matplotlib not available") else: from numpy import mgrid X, Y = mgrid[0:1:1j*m,0:1:1j*n] Z = x[...].reshape(m,n) pylab.figure() pylab.contourf(X,Y,Z) pylab.plot(X.ravel(),Y.ravel(),'.k') pylab.axis('equal') pylab.colorbar() pylab.show() petsc4py-3.19.6/demo/makefile000066400000000000000000000017651454104047300160240ustar00rootroot00000000000000.PHONY:all -include ../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables all: petsc -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C binary-io -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C kspsolve -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C bratu2d -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C bratu3d -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C poisson2d -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C poisson3d -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C perftest -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C wrap-swig -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C wrap-f2py .PHONY:petsc petsc: -@PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}${PETSC_MPI4PY_PYTHONPATH} ${MAKE} -C petsc-examples petsc4py-3.19.6/demo/ode/000077500000000000000000000000001454104047300150625ustar00rootroot00000000000000petsc4py-3.19.6/demo/ode/bouncing_ball.py000066400000000000000000000032251454104047300202340ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class BouncingBall(object): n = 2 comm = PETSc.COMM_SELF def __init__(self): pass def initialCondition(self, u): u[0] = 0.0 u[1] = 20.0 u.assemble() def evalRHSFunction(self, ts, t, u, f): f[0] = u[1] f[1] = -9.8 f.assemble() def evalRHSJacobian(self, ts, t, u, A, B): J = A J[0,0] = 0.0 J[1,0] = 0.0 J[0,1] = 1.0 J[1,1] = 0.0 J.assemble() if A != B: B.assemble() return True # same nonzero pattern class Monitor(object): def __init__(self): pass def __call__(self, ts, k, t, x): PETSc.Sys.Print(f"Position at time {t}: {x[0]}") ode = BouncingBall() J = PETSc.Mat().create() J.setSizes([ode.n,ode.n]) J.setType('aij') J.setUp() J.assemble() u = PETSc.Vec().createSeq(ode.n, comm=ode.comm) f = u.duplicate() ts = PETSc.TS().create(comm=ode.comm) ts.setProblemType(ts.ProblemType.NONLINEAR) ts.setType(ts.Type.BEULER) ts.setRHSFunction(ode.evalRHSFunction, f) ts.setRHSJacobian(ode.evalRHSJacobian, J) #ts.setSaveTrajectory() ts.setTime(0.0) ts.setTimeStep(0.01) ts.setMaxTime(15.0) #ts.setMaxSteps(1000) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.MATCHSTEP) #ts.setMonitor(Monitor()) direction = [-1] terminate = [False] def event(ts, t, X, fvalue): fvalue[0] = X[0] def postevent(ts, events, t, X, forward): X[0] = 0.0 X[1] = -0.9*X[1] X.assemble() ts.setEventHandler(direction, terminate, event, postevent) ts.setEventTolerances(1e-6, vtol=[1e-9]) ts.setFromOptions() ode.initialCondition(u) ts.solve(u) petsc4py-3.19.6/demo/ode/ce.py000066400000000000000000000034651454104047300160330ustar00rootroot00000000000000# Stiff scalar valued ODE problem with an exact solution import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc from math import sin, cos, exp class CE(object): n = 1 comm = PETSc.COMM_SELF def __init__(self, lambda_=1.0): self.lambda_ = lambda_ def evalSolution(self, t, x): l = self.lambda_ x[0] = l/(l*l+1)*(l*cos(t)+sin(t)) - l*l/(l*l+1)*exp(-l*t) x.assemble() def evalFunction(self, ts, t, x, xdot, f): l = self.lambda_ f[0] = xdot[0] + l*(x[0] - cos(t)) f.assemble() def evalJacobian(self, ts, t, x, xdot, a, A, B): J = B l = self.lambda_ J[0,0] = a + l J.assemble() if A != B: A.assemble() return True # same nonzero pattern OptDB = PETSc.Options() lambda_ = OptDB.getScalar('lambda', 10.0) ode = CE(lambda_) J = PETSc.Mat().createDense([ode.n,ode.n], comm=ode.comm) J.setUp() x = PETSc.Vec().createSeq(ode.n, comm=ode.comm) f = x.duplicate() ts = PETSc.TS().create(comm=ode.comm) ts.setProblemType(ts.ProblemType.NONLINEAR) ts.setType(ts.Type.GLLE) ts.setIFunction(ode.evalFunction, f) ts.setIJacobian(ode.evalJacobian, J) ts.setTime(0.0) ts.setTimeStep(0.001) ts.setMaxTime(10) ts.setMaxSteps(10000) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE) class Monitor(object): def __init__(self, ode): self.ode = ode self.x = PETSc.Vec().createSeq(ode.n, comm=ode.comm) def __call__(self, ts, k, t, x): ode.evalSolution(t, self.x) self.x.axpy(-1, x) e = self.x.norm() h = ts.getTimeStep() PETSc.Sys.Print("step %3d t=%8.2e h=%8.2e error=%8.2e" % (k, t, h, e), comm=self.ode.comm) ts.setMonitor(Monitor(ode)) ts.setFromOptions() ode.evalSolution(0.0, x) ts.solve(x) del ode, J, x, f, ts petsc4py-3.19.6/demo/ode/heat.py000066400000000000000000000132701454104047300163600ustar00rootroot00000000000000# Solves Heat equation on a periodic domain, using raw VecScatter from __future__ import division import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc from mpi4py import MPI import numpy class Heat(object): def __init__(self,comm,N): self.comm = comm self.N = N # global problem size self.h = 1/N # grid spacing on unit interval self.n = N // comm.size + int(comm.rank < (N % comm.size)) # owned part of global problem self.start = comm.exscan(self.n) if comm.rank == 0: self.start = 0 gindices = numpy.arange(self.start-1, self.start+self.n+1, dtype=PETSc.IntType) % N # periodic self.mat = PETSc.Mat().create(comm=comm) size = (self.n, self.N) # local and global sizes self.mat.setSizes((size,size)) self.mat.setFromOptions() self.mat.setPreallocationNNZ((3,1)) # Conservative preallocation for 3 "local" columns and one non-local # Allow matrix insertion using local indices [0:n+2] lgmap = PETSc.LGMap().create(list(gindices), comm=comm) self.mat.setLGMap(lgmap, lgmap) # Global and local vectors self.gvec = self.mat.createVecRight() self.lvec = PETSc.Vec().create(comm=PETSc.COMM_SELF) self.lvec.setSizes(self.n+2) self.lvec.setUp() # Configure scatter from global to local isg = PETSc.IS().createGeneral(list(gindices), comm=comm) self.g2l = PETSc.Scatter().create(self.gvec, isg, self.lvec, None) self.tozero, self.zvec = PETSc.Scatter.toZero(self.gvec) self.history = [] if False: # Print some diagnostics print('[%d] local size %d, global size %d, starting offset %d' % (comm.rank, self.n, self.N, self.start)) self.gvec.setArray(numpy.arange(self.start,self.start+self.n)) self.gvec.view() self.g2l.scatter(self.gvec, self.lvec, PETSc.InsertMode.INSERT) for rank in range(comm.size): if rank == comm.rank: print('Contents of local Vec on rank %d' % rank) self.lvec.view() comm.barrier() def evalSolution(self, t, x): assert t == 0.0, "only for t=0.0" coord = numpy.arange(self.start, self.start+self.n) / self.N x.setArray((numpy.abs(coord-0.5) < 0.1) * 1.0) def evalFunction(self, ts, t, x, xdot, f): self.g2l.scatter(x, self.lvec, PETSc.InsertMode.INSERT) # lvec is a work vector h = self.h with self.lvec as u, xdot as udot: f.setArray(udot*h + 2*u[1:-1]/h - u[:-2]/h - u[2:]/h) # Scale equation by volume element def evalJacobian(self, ts, t, x, xdot, a, A, B): h = self.h for i in range(self.n): lidx = i + 1 gidx = self.start + i B.setValuesLocal([lidx], [lidx-1,lidx,lidx+1], [-1/h, a*h+2/h, -1/h]) B.assemble() if A != B: A.assemble() # If operator is different from preconditioning matrix return True # same nonzero pattern def monitor(self, ts, i, t, x): if self.history: lasti, lastt, lastx = self.history[-1] if i < lasti + 4 or t < lastt + 1e-4: return self.tozero.scatter(x, self.zvec, PETSc.InsertMode.INSERT) xx = self.zvec[:].tolist() self.history.append((i, t, xx)) def plotHistory(self): try: from matplotlib import pylab, rcParams except ImportError: print("matplotlib not available") raise SystemExit rcParams.update({'text.usetex':True, 'figure.figsize':(10,6)}) #rc('figure', figsize=(600,400)) pylab.title('Heat: TS \\texttt{%s}' % ts.getType()) x = numpy.arange(self.N) / self.N for i,t,u in self.history: pylab.plot(x, u, label='step=%d t=%8.2g'%(i,t)) pylab.xlabel('$x$') pylab.ylabel('$u$') pylab.legend(loc='upper right') pylab.savefig('heat-history.png') #pylab.show() OptDB = PETSc.Options() ode = Heat(MPI.COMM_WORLD, OptDB.getInt('n',100)) x = ode.gvec.duplicate() f = ode.gvec.duplicate() ts = PETSc.TS().create(comm=ode.comm) ts.setType(ts.Type.ROSW) # Rosenbrock-W. ARKIMEX is a nonlinearly implicit alternative. ts.setIFunction(ode.evalFunction, ode.gvec) ts.setIJacobian(ode.evalJacobian, ode.mat) ts.setMonitor(ode.monitor) ts.setTime(0.0) ts.setTimeStep(ode.h**2) ts.setMaxTime(1) ts.setMaxSteps(100) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE) ts.setMaxSNESFailures(-1) # allow an unlimited number of failures (step will be rejected and retried) snes = ts.getSNES() # Nonlinear solver snes.setTolerances(max_it=10) # Stop nonlinear solve after 10 iterations (TS will retry with shorter step) ksp = snes.getKSP() # Linear solver ksp.setType(ksp.Type.CG) # Conjugate gradients pc = ksp.getPC() # Preconditioner if False: # Configure algebraic multigrid, could use run-time options instead pc.setType(pc.Type.GAMG) # PETSc's native AMG implementation, mostly based on smoothed aggregation OptDB['mg_coarse_pc_type'] = 'svd' # more specific multigrid options OptDB['mg_levels_pc_type'] = 'sor' ts.setFromOptions() # Apply run-time options, e.g. -ts_adapt_monitor -ts_type arkimex -snes_converged_reason ode.evalSolution(0.0, x) ts.solve(x) if ode.comm.rank == 0: print('steps %d (%d rejected, %d SNES fails), nonlinear its %d, linear its %d' % (ts.getStepNumber(), ts.getStepRejections(), ts.getSNESFailures(), ts.getSNESIterations(), ts.getKSPIterations())) if OptDB.getBool('plot_history', True) and ode.comm.rank == 0: ode.plotHistory() petsc4py-3.19.6/demo/ode/orego.py000066400000000000000000000072711454104047300165560ustar00rootroot00000000000000# Oregonator: stiff 3-variable oscillatory ODE system from chemical reactions, # problem OREGO in Hairer&Wanner volume 2 # See also http://www.scholarpedia.org/article/Oregonator import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class Orego(object): n = 3 comm = PETSc.COMM_SELF def evalSolution(self, t, x): assert t == 0.0, "only for t=0.0" x.setArray([1, 2, 3]) def evalFunction(self, ts, t, x, xdot, f): f.setArray([xdot[0] - 77.27*(x[1] + x[0]*(1 - 8.375e-6*x[0] - x[1])), xdot[1] - 1/77.27*(x[2] - (1 + x[0])*x[1]), xdot[2] - 0.161*(x[0] - x[2])]) def evalJacobian(self, ts, t, x, xdot, a, A, B): B[:,:] = [[a - 77.27*((1 - 8.375e-6*x[0] - x[1]) - 8.375e-6*x[0]), -77.27*(1 - x[0]), 0], [1/77.27*x[1], a + 1/77.27*(1 + x[0]), -1/77.27], [-0.161, 0, a + 0.161]] B.assemble() if A != B: A.assemble() return True # same nonzero pattern OptDB = PETSc.Options() ode = Orego() J = PETSc.Mat().createDense([ode.n, ode.n], comm=ode.comm) J.setUp() x = PETSc.Vec().createSeq(ode.n, comm=ode.comm) f = x.duplicate() ts = PETSc.TS().create(comm=ode.comm) ts.setType(ts.Type.ROSW) # Rosenbrock-W. ARKIMEX is a nonlinearly implicit alternative. ts.setIFunction(ode.evalFunction, f) ts.setIJacobian(ode.evalJacobian, J) history = [] def monitor(ts, i, t, x): xx = x[:].tolist() history.append((i, t, xx)) ts.setMonitor(monitor) ts.setTime(0.0) ts.setTimeStep(0.1) ts.setMaxTime(360) ts.setMaxSteps(2000) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE) ts.setMaxSNESFailures(-1) # allow an unlimited number of failures (step will be rejected and retried) # Set a different tolerance on each variable. Can use a scalar or a vector for either or both atol and rtol. vatol = x.duplicate(array=[1e-2, 1e-1, 1e-4]) ts.setTolerances(atol=vatol,rtol=1e-3) # adaptive controller attempts to match this tolerance snes = ts.getSNES() # Nonlinear solver snes.setTolerances(max_it=10) # Stop nonlinear solve after 10 iterations (TS will retry with shorter step) ksp = snes.getKSP() # Linear solver ksp.setType(ksp.Type.PREONLY) # Just use the preconditioner without a Krylov method pc = ksp.getPC() # Preconditioner pc.setType(pc.Type.LU) # Use a direct solve ts.setFromOptions() # Apply run-time options, e.g. -ts_adapt_monitor -ts_type arkimex -snes_converged_reason ode.evalSolution(0.0, x) ts.solve(x) print('steps %d (%d rejected, %d SNES fails), nonlinear its %d, linear its %d' % (ts.getStepNumber(), ts.getStepRejections(), ts.getSNESFailures(), ts.getSNESIterations(), ts.getKSPIterations())) if OptDB.getBool('plot_history', True): try: from matplotlib import pylab from matplotlib import rc except ImportError: print("matplotlib not available") raise SystemExit import numpy as np ii = np.asarray([v[0] for v in history]) tt = np.asarray([v[1] for v in history]) xx = np.asarray([v[2] for v in history]) rc('text', usetex=True) pylab.suptitle('Oregonator: TS \\texttt{%s}' % ts.getType()) pylab.subplot(2,2,1) pylab.subplots_adjust(wspace=0.3) pylab.semilogy(ii[:-1], np.diff(tt), ) pylab.xlabel('step number') pylab.ylabel('timestep') for i in range(0,3): pylab.subplot(2,2,i+2) pylab.semilogy(tt, xx[:,i], "rgb"[i]) pylab.xlabel('time') pylab.ylabel('$x_%d$' % i) # pylab.savefig('orego-history.png') pylab.show() petsc4py-3.19.6/demo/ode/rober.py000066400000000000000000000043041454104047300165460ustar00rootroot00000000000000# Stiff 3-variable ODE system from chemical reactions, # due to Robertson (1966), # problem ROBER in Hairer&Wanner, ODE 2, 1996 import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class Rober(object): n = 3 comm = PETSc.COMM_SELF def evalSolution(self, t, x): assert t == 0.0, "only for t=0.0" x[:] = [1, 0, 0] x.assemble() def evalFunction(self, ts, t, x, xdot, f): f[:] = [xdot[0] + 0.04*x[0] - 1e4*x[1]*x[2], xdot[1] - 0.04*x[0] + 1e4*x[1]*x[2] + 3e7*x[1]**2, xdot[2] - 3e7*x[1]**2] f.assemble() def evalJacobian(self, ts, t, x, xdot, a, A, B): J = B J[:,:] = [[a + 0.04, -1e4*x[2], -1e4*x[1]], [-0.04, a + 1e4*x[2] + 3e7*2*x[1], 1e4*x[1]], [0, -3e7*2*x[1], a]] J.assemble() if A != B: A.assemble() return True # same nonzero pattern OptDB = PETSc.Options() ode = Rober() J = PETSc.Mat().createDense([ode.n, ode.n], comm=ode.comm) J.setUp() x = PETSc.Vec().createSeq(ode.n, comm=ode.comm) f = x.duplicate() ts = PETSc.TS().create(comm=ode.comm) ts.setProblemType(ts.ProblemType.NONLINEAR) ts.setType(ts.Type.THETA) ts.setIFunction(ode.evalFunction, f) ts.setIJacobian(ode.evalJacobian, J) history = [] def monitor(ts, i, t, x): xx = x[:].tolist() history.append((i, t, xx)) ts.setMonitor(monitor) ts.setTime(0.0) ts.setTimeStep(.001) ts.setMaxTime(1e30) ts.setMaxSteps(100) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE) ts.setFromOptions() ode.evalSolution(0.0, x) ts.solve(x) del ode, J, x, ts try: from matplotlib import pylab except ImportError: print("matplotlib not available") raise SystemExit import numpy as np ii = np.asarray([v[0] for v in history]) tt = np.asarray([v[1] for v in history]) xx = np.asarray([v[2] for v in history]) pylab.suptitle('Rober') pylab.subplot(2,2,1) pylab.subplots_adjust(wspace=0.3) pylab.semilogy(ii[:-1], np.diff(tt), ) pylab.xlabel('step number') pylab.ylabel('timestep') for i in range(0,3): pylab.subplot(2,2,i+2) pylab.semilogx(tt, xx[:,i], "rgb"[i]) pylab.xlabel('t') pylab.ylabel('x%d' % i) pylab.show() petsc4py-3.19.6/demo/ode/vanderpol.py000066400000000000000000000157451454104047300174420ustar00rootroot00000000000000# Testing TSAdjoint and matrix-free Jacobian # Basic usage: # python vanderpol.py # Test implicit methods using implicit form: # python -implicitform # Test explicit methods: # python -implicitform 0 # Test IMEX methods: # python -imexform # Matrix-free implementations can be enabled with an additional option -mf import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class VDP(object): n = 2 comm = PETSc.COMM_SELF def __init__(self, mu_=1.0e3, mf_=False, imex_=False): self.mu_ = mu_ self.mf_ = mf_ self.imex_ = imex_ if self.mf_: self.Jim_ = PETSc.Mat().createDense([self.n,self.n], comm=self.comm) self.Jim_.setUp() self.JimP_ = PETSc.Mat().createDense([self.n,1], comm=self.comm) self.JimP_.setUp() self.Jex_ = PETSc.Mat().createDense([self.n,self.n], comm=self.comm) self.Jex_.setUp() self.JexP_ = PETSc.Mat().createDense([self.n,1], comm=self.comm) self.JexP_.setUp() def initialCondition(self, u): mu = self.mu_ u[0] = 2.0 u[1] = -2.0/3.0 + 10.0/(81.0*mu) - 292.0/(2187.0*mu*mu) u.assemble() def evalFunction(self, ts, t, u, f): mu = self.mu_ f[0] = u[1] if self.imex_: f[1] = 0.0 else: f[1] = mu*((1.-u[0]*u[0])*u[1]-u[0]) f.assemble() def evalJacobian(self, ts, t, u, A, B): if not self.mf_: J = A else : J = self.Jex_ mu = self.mu_ J[0,0] = 0 J[0,1] = 1.0 if self.imex_: J[1,0] = 0 J[1,1] = 0 else: J[1,0] = -mu*(2.0*u[1]*u[0]+1.) J[1,1] = mu*(1.0-u[0]*u[0]) J.assemble() if A != B: B.assemble() return True # same nonzero pattern def evalJacobianP(self, ts, t, u, C): if not self.mf_: Jp = C else: Jp = self.JexP_ if not self.imex_: Jp[0,0] = 0 Jp[1,0] = (1.-u[0]*u[0])*u[1]-u[0] Jp.assemble() return True def evalIFunction(self, ts, t, u, udot, f): mu = self.mu_ if self.imex_: f[0] = udot[0] else: f[0] = udot[0]-u[1] f[1] = udot[1]-mu*((1.-u[0]*u[0])*u[1]-u[0]) f.assemble() def evalIJacobian(self, ts, t, u, udot, shift, A, B): if not self.mf_: J = A else : J = self.Jim_ mu = self.mu_ if self.imex_: J[0,0] = shift J[0,1] = 0.0 else: J[0,0] = shift J[0,1] = -1.0 J[1,0] = mu*(2.0*u[1]*u[0]+1.) J[1,1] = shift-mu*(1.0-u[0]*u[0]) J.assemble() if A != B: B.assemble() return True # same nonzero pattern def evalIJacobianP(self, ts, t, u, udot, shift, C): if not self.mf_: Jp = C else: Jp = self.JimP_ Jp[0,0] = 0 Jp[1,0] = u[0]-(1.-u[0]*u[0])*u[1] Jp.assemble() return True class JacShell: def __init__(self, ode): self.ode_ = ode def mult(self, A, x, y): "y <- A * x" self.ode_.Jex_.mult(x,y) def multTranspose(self, A, x, y): "y <- A' * x" self.ode_.Jex_.multTranspose(x, y) class JacPShell: def __init__(self, ode): self.ode_ = ode def multTranspose(self, A, x, y): "y <- A' * x" self.ode_.JexP_.multTranspose(x, y) class IJacShell: def __init__(self, ode): self.ode_ = ode def mult(self, A, x, y): "y <- A * x" self.ode_.Jim_.mult(x,y) def multTranspose(self, A, x, y): "y <- A' * x" self.ode_.Jim_.multTranspose(x, y) class IJacPShell: def __init__(self, ode): self.ode_ = ode def multTranspose(self, A, x, y): "y <- A' * x" self.ode_.JimP_.multTranspose(x, y) OptDB = PETSc.Options() mu_ = OptDB.getScalar('mu', 1.0e3) mf_ = OptDB.getBool('mf', False) implicitform_ = OptDB.getBool('implicitform', False) imexform_ = OptDB.getBool('imexform', False) ode = VDP(mu_,mf_,imexform_) if not mf_: Jim = PETSc.Mat().createDense([ode.n,ode.n], comm=ode.comm) Jim.setUp() JimP = PETSc.Mat().createDense([ode.n,1], comm=ode.comm) JimP.setUp() Jex = PETSc.Mat().createDense([ode.n,ode.n], comm=ode.comm) Jex.setUp() JexP = PETSc.Mat().createDense([ode.n,1], comm=ode.comm) JexP.setUp() else: Jim = PETSc.Mat().create() Jim.setSizes([ode.n,ode.n]) Jim.setType('python') shell = IJacShell(ode) Jim.setPythonContext(shell) Jim.setUp() Jim.assemble() JimP = PETSc.Mat().create() JimP.setSizes([ode.n,1]) JimP.setType('python') shell = IJacPShell(ode) JimP.setPythonContext(shell) JimP.setUp() JimP.assemble() Jex = PETSc.Mat().create() Jex.setSizes([ode.n,ode.n]) Jex.setType('python') shell = JacShell(ode) Jex.setPythonContext(shell) Jex.setUp() Jex.assemble() JexP = PETSc.Mat().create() JexP.setSizes([ode.n,1]) JexP.setType('python') shell = JacPShell(ode) JexP.setPythonContext(shell) JexP.setUp() JexP.zeroEntries() JexP.assemble() u = PETSc.Vec().createSeq(ode.n, comm=ode.comm) f = u.duplicate() adj_u = [] adj_u.append(PETSc.Vec().createSeq(ode.n, comm=ode.comm)) adj_u.append(PETSc.Vec().createSeq(ode.n, comm=ode.comm)) adj_p = [] adj_p.append(PETSc.Vec().createSeq(1, comm=ode.comm)) adj_p.append(PETSc.Vec().createSeq(1, comm=ode.comm)) ts = PETSc.TS().create(comm=ode.comm) ts.setProblemType(ts.ProblemType.NONLINEAR) if imexform_: ts.setType(ts.Type.ARKIMEX) ts.setIFunction(ode.evalIFunction, f) ts.setIJacobian(ode.evalIJacobian, Jim) ts.setIJacobianP(ode.evalIJacobianP, JimP) ts.setRHSFunction(ode.evalFunction, f) ts.setRHSJacobian(ode.evalJacobian, Jex) ts.setRHSJacobianP(ode.evalJacobianP, JexP) else: if implicitform_: ts.setType(ts.Type.CN) ts.setIFunction(ode.evalIFunction, f) ts.setIJacobian(ode.evalIJacobian, Jim) ts.setIJacobianP(ode.evalIJacobianP, JimP) else: ts.setType(ts.Type.RK) ts.setRHSFunction(ode.evalFunction, f) ts.setRHSJacobian(ode.evalJacobian, Jex) ts.setRHSJacobianP(ode.evalJacobianP, JexP) ts.setSaveTrajectory() ts.setTime(0.0) ts.setTimeStep(0.001) ts.setMaxTime(0.5) ts.setMaxSteps(1000) ts.setExactFinalTime(PETSc.TS.ExactFinalTime.MATCHSTEP) ts.setFromOptions() ode.initialCondition(u) ts.solve(u) adj_u[0][0] = 1 adj_u[0][1] = 0 adj_u[0].assemble() adj_u[1][0] = 0 adj_u[1][1] = 1 adj_u[1].assemble() adj_p[0][0] = 0 adj_p[0].assemble() adj_p[1][0] = 0 adj_p[1].assemble() ts.setCostGradients(adj_u,adj_p) ts.adjointSolve() adj_u[0].view() adj_u[1].view() adj_p[0].view() adj_p[1].view() def compute_derp(du,dp): print(du[1]*(-10.0/(81.0*mu_*mu_)+2.0*292.0/(2187.0*mu_*mu_*mu_))+dp[0]) compute_derp(adj_u[0],adj_p[0]) compute_derp(adj_u[1],adj_p[1]) del ode, Jim, JimP, Jex, JexP, u, f, ts, adj_u, adj_p petsc4py-3.19.6/demo/perftest/000077500000000000000000000000001454104047300161475ustar00rootroot00000000000000petsc4py-3.19.6/demo/perftest/App.f90000066400000000000000000000057311454104047300172150ustar00rootroot00000000000000subroutine formFunction_C(nx, ny, nz, h, t, x, xdot, f) & bind(C, name="formFunction") use ISO_C_BINDING, only: C_INT, C_DOUBLE implicit none integer(kind=C_INT), intent(in) :: nx, ny, nz real(kind=C_DOUBLE), intent(in) :: h(3), t real(kind=C_DOUBLE), intent(in) :: x(nx,ny,nz), xdot(nx,ny,nz) real(kind=C_DOUBLE), intent(inout) :: f(nx,ny,nz) call formfunction_f(nx, ny, nz, h, t, x, xdot, f) end subroutine formFunction_C subroutine formInitial_C(nx, ny, nz, h, t, x) & bind(C, name="formInitial") use ISO_C_BINDING, only: C_INT, C_DOUBLE implicit none integer(kind=C_INT), intent(in) :: nx, ny, nz real(kind=C_DOUBLE), intent(in) :: h(3), t real(kind=C_DOUBLE), intent(inout) :: x(nx,ny,nz) call forminitial_f(nx, ny, nz, h, t, x) end subroutine formInitial_C subroutine evalK (P, K) real(kind=8), intent(in) :: P real(kind=8), intent(out) :: K if (P >= 0.0) then K = 1.0 else K = 1.0/(1+P**2) end if end subroutine evalK subroutine fillK (P, K) real(kind=8), intent(in) :: P(-1:1) real(kind=8), intent(out) :: K(-1:1) real(kind=8) Ka, Kb call evalK((P(-1)+P( 0))/2.0, Ka) call evalK((P( 0)+P( 1))/2.0, Kb) K(-1) = -Ka K( 0) = Ka + Kb K(+1) = -Kb end subroutine fillK subroutine forminitial_f(nx, ny, nz, h, t, x) implicit none integer, intent(in) :: nx, ny, nz real(kind=8), intent(in) :: h(3), t real(kind=8), intent(inout) :: x(nx,ny,nz) ! x(:,:,:) = 0.0 end subroutine forminitial_f subroutine formfunction_f(nx, ny, nz, h, t, x, xdot, f) implicit none integer, intent(in) :: nx, ny, nz real(kind=8), intent(in) :: h(3), t real(kind=8), intent(in) :: x(nx,ny,nz), xdot(nx,ny,nz) real(kind=8), intent(inout) :: f(nx,ny,nz) ! integer :: i,j,k,ii(-1:1),jj(-1:1),kk(-1:1) real(kind=8) :: K1(-1:1), K2(-1:1), K3(-1:1) real(kind=8) :: P1(-1:1), P2(-1:1), P3(-1:1) ! do k=1,nz do j=1,ny do i=1,nx ! ii = (/i-1, i, i+1/) if (i == 1) then ii(-1) = i else if (i == nx) then ii(+1) = i endif ! jj = (/j-1, j, j+1/) if (j == 1) then jj(-1) = j else if (j == ny) then jj(+1) = j end if ! kk = (/k-1, k, k+1/) if (k == 1) then kk(-1) = k else if (k == nz) then kk(+1) = k end if ! P1 = x(ii,j,k) P2 = x(i,jj,k) P3 = x(i,j,kk) call fillK(P1,K1) call fillK(P2,K2) call fillK(P3,K3) f(i,j,k) = & xdot(i,j,k) + & sum(K1*P1)/h(1)**2 + & sum(K2*P2)/h(2)**2 + & sum(K3*P3)/h(3)**2 ! end do !i end do !j end do !k ! i = nx/4+1 j = ny/4+1 k = nz/2+1 f(i,j,k:nz) = f(i,j,k:nz) + 300.0 ! end subroutine formfunction_f petsc4py-3.19.6/demo/perftest/App.pyf000066400000000000000000000015651454104047300174160ustar00rootroot00000000000000! -*- f90 -*- python module App interface subroutine formFunction(nx, ny, nz, h, t, x, xdot, f) intent(c) formFunction integer, intent(in), intent(hide) :: nx = shape(x,0) integer, intent(in), intent(hide) :: ny = shape(x,1) integer, intent(in), intent(hide) :: nz = shape(x,2) real(kind=8), intent(in) :: h(3), t real(kind=8), intent(in) :: x(nx,ny,nz), xdot(nx,ny,nz) real(kind=8), intent(inout) :: f(nx,ny,nz) end subroutine formFunction subroutine formInitial(nx, ny, nz, h, t, x) intent(c) formInitial integer, intent(in), intent(hide) :: nx = shape(x,0) integer, intent(in), intent(hide) :: ny = shape(x,1) integer, intent(in), intent(hide) :: nz = shape(x,2) real(kind=8), intent(in) :: h(3), t real(kind=8), intent(inout) :: x(nx,ny,nz) end subroutine formFunction end python module App petsc4py-3.19.6/demo/perftest/driver.c000066400000000000000000000070351454104047300176130ustar00rootroot00000000000000#include EXTERN_C_BEGIN extern void formInitial(int*,int*,int*,double*, double*,double*); extern void formFunction(const int*,const int*,const int*,const double*, const double*,const double[],const double[],double[]); EXTERN_C_END typedef struct AppCtx { PetscInt nx,ny,nz; PetscScalar h[3]; } AppCtx; PetscErrorCode FormInitial(PetscReal t, Vec X, void *ctx) { PetscScalar *x; AppCtx *app = (AppCtx*) ctx; PetscFunctionBegin; PetscCall(VecGetArray(X,&x)); /**/ formInitial(&app->nx,&app->ny,&app->nz,app->h,&t,x); /**/ PetscCall(VecRestoreArray(X,&x)); PetscFunctionReturn(PETSC_SUCCESS); } PetscErrorCode FormFunction(TS ts, PetscReal t, Vec X, Vec Xdot,Vec F, void *ctx) { const PetscScalar *x; const PetscScalar *xdot; PetscScalar *f; AppCtx *app = (AppCtx*) ctx; PetscFunctionBegin; PetscCall(VecGetArrayRead(X,&x)); PetscCall(VecGetArrayRead(Xdot,&xdot)); PetscCall(VecGetArray(F,&f)); /**/ formFunction(&app->nx,&app->ny,&app->nz,app->h,&t,x,xdot,f); /**/ PetscCall(VecRestoreArrayRead(X,&x)); PetscCall(VecRestoreArrayRead(Xdot,&xdot)); PetscCall(VecRestoreArray(F,&f)); PetscFunctionReturn(PETSC_SUCCESS); } PetscErrorCode RunTest(int nx, int ny, int nz, int loops, double *wt) { Vec x,f; TS ts; AppCtx _app,*app=&_app; double t1,t2; PetscFunctionBegin; app->nx = nx; app->h[0] = 1./(nx-1); app->ny = ny; app->h[1] = 1./(ny-1); app->nz = nz; app->h[2] = 1./(nz-1); PetscCall(VecCreate(PETSC_COMM_SELF,&x)); PetscCall(VecSetSizes(x,nx*ny*nz,nx*ny*nz)); PetscCall(VecSetUp(x)); PetscCall(VecDuplicate(x,&f)); PetscCall(TSCreate(PETSC_COMM_SELF,&ts)); PetscCall(TSSetProblemType(ts,TS_NONLINEAR)); PetscCall(TSSetType(ts,TSTHETA)); PetscCall(TSThetaSetTheta(ts,1.0)); PetscCall(TSSetTimeStep(ts,0.01)); PetscCall(TSSetTime(ts,0.0)); PetscCall(TSSetMaxTime(ts,1.0)); PetscCall(TSSetMaxSteps(ts,10)); PetscCall(TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER)); PetscCall(TSSetSolution(ts,x)); PetscCall(TSSetIFunction(ts,f,FormFunction,app)); PetscCall(PetscOptionsSetValue(NULL,"-snes_mf","1")); { SNES snes; KSP ksp; PetscCall(TSGetSNES(ts,&snes)); PetscCall(SNESGetKSP(snes,&ksp)); PetscCall(KSPSetType(ksp,KSPCG)); } PetscCall(TSSetFromOptions(ts)); PetscCall(TSSetUp(ts)); *wt = 1e300; while (loops-- > 0) { PetscCall(FormInitial(0.0,x,app)); PetscCall(PetscTime(&t1)); PetscCall(TSSolve(ts,x)); PetscCall(PetscTime(&t2)); *wt = PetscMin(*wt,t2-t1); } PetscCall(VecDestroy(&x)); PetscCall(VecDestroy(&f)); PetscCall(TSDestroy(&ts)); PetscFunctionReturn(PETSC_SUCCESS); } PetscErrorCode GetInt(const char* name, PetscInt *v, PetscInt defv) { PetscFunctionBegin; *v = defv; PetscCall(PetscOptionsGetInt(NULL,NULL,name,v,NULL)); PetscFunctionReturn(PETSC_SUCCESS); } int main(int argc, char *argv[]) { double wt; PetscInt n,start,step,stop,samples; PetscCall(PetscInitialize(&argc,&argv,NULL,NULL)); PetscCall(GetInt("-start", &start, 12)); PetscCall(GetInt("-step", &step, 4)); PetscCall(GetInt("-stop", &stop, start)); PetscCall(GetInt("-samples", &samples, 1)); for (n=start; n<=stop; n+=step) { int nx=n+1, ny=n+1, nz=n+1; PetscCall(RunTest(nx,ny,nz,samples,&wt)); PetscCall(PetscPrintf(PETSC_COMM_SELF,"Grid %3d x %3d x %3d -> %f seconds (%2d samples)\n",nx,ny,nz,wt,samples)); } PetscCall(PetscFinalize()); return 0; } petsc4py-3.19.6/demo/perftest/driver.py000066400000000000000000000067201454104047300200210ustar00rootroot00000000000000#!/usr/bin/env python import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np try: from matplotlib import pylab except ImportError: pylab = None # this user class is an application # context for the nonlinear problem # at hand; it contains some parameters # and knows how to compute residuals class AppCtx: def __init__(self, nx, ny, nz): self.n = np.array([nx, ny, nz], dtype='i') self.h = np.array([1.0/(n-1) for n in self.n], dtype='d') from App import formFunction from App import formInitial self._formFunction = formFunction self._formInitial = formInitial def formInitial(self, t, X): xx = X.getArray(readonly=0).reshape(self.n, order='f') self._formInitial(self.h, t, xx) def formFunction(self, ts, t, X, Xdot, F): n = self.n h = self.h x = X.getArray(readonly=1).reshape(n, order='f') xdot = Xdot.getArray(readonly=1).reshape(n, order='f') f = F[...].reshape(n, order='f') self._formFunction(h, t, x, xdot, f) def plot(self, t, x): nx, ny, nz = self.n from numpy import mgrid # U = x.getArray(readonly=1).reshape(nx,ny,nz, order='f') # X, Y = mgrid[0:1:1j*nx,0:1:1j*ny] Z = U[:,:,nz//2] pylab.figure(0) pylab.contourf(X,Y,Z) pylab.colorbar() pylab.plot(X.ravel(),Y.ravel(),'.k') pylab.title('z=0.50') pylab.xlabel('x') pylab.ylabel('y') pylab.axis('equal') # X, Y = mgrid[0:1:1j*nx,0:1:1j*nz] Z = U[:,ny//4,:] pylab.figure(1) pylab.contourf(X,Y,Z) pylab.colorbar() pylab.plot(X.ravel(),Y.ravel(),'.k') pylab.title('y=0.25') pylab.xlabel('x') pylab.ylabel('z') pylab.axis('equal') # X, Y = mgrid[0:1:1j*ny,0:1:1j*nz] Z = U[nx//2,:,:] pylab.figure(2) pylab.contourf(X,Y,Z) pylab.colorbar() pylab.plot(X.ravel(),Y.ravel(),'.k') pylab.title('x=0.50') pylab.xlabel('y') pylab.ylabel('z') pylab.axis('equal') def run_test(nx,ny,nz,samples,plot=False): ts = PETSc.TS().create() ts.setType('theta') ts.setTheta(1.0) ts.setTimeStep(0.01) ts.setTime(0.0) ts.setMaxTime(1.0) ts.setMaxSteps(10) eft = PETSc.TS.ExactFinalTime.STEPOVER ts.setExactFinalTime(eft) x = PETSc.Vec().createSeq(nx*ny*nz) ts.setSolution(x) app = AppCtx(nx, ny, nz) f = PETSc.Vec().createSeq(nx*ny*nz) ts.setIFunction(app.formFunction, f) ts.snes.setUseMF(1) ts.snes.ksp.setType('cg') ts.setFromOptions() ts.setUp() wt = 1e300 for i in range(samples): app.formInitial(0, x) t1 = PETSc.Log.getTime() ts.solve(x) t2 = PETSc.Log.getTime() wt = min(wt,t2-t1) if plot and pylab: app.plot(ts.time, x) return wt OptDB = PETSc.Options() start = OptDB.getInt('start', 12) step = OptDB.getInt('step', 4) stop = OptDB.getInt('stop', start) samples = OptDB.getInt('samples', 1) plot = OptDB.getBool('plot', False) if plot and not pylab: PETSc.Sys.Print("matplotlib not available") for n in range(start, stop+step, step): nx = ny = nz = n+1 wt = run_test(nx,ny,nz,samples,plot) PETSc.Sys.Print("Grid %3d x %3d x %3d -> %f seconds (%2d samples)" % (nx,ny,nz,wt,samples)) if plot and pylab: pylab.show() petsc4py-3.19.6/demo/perftest/makefile000066400000000000000000000011421454104047300176450ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: run_py run_cc SCRIPT=driver MODULE=App .PHONY:run_py run_py: ${MODULE}.so ${MPIEXEC} ${PYTHON} ${SCRIPT}.py EXECUTABLE=driver .PHONY:run_cc run_cc: ${EXECUTABLE}.exe ${MPIEXEC} ./${EXECUTABLE}.exe ${MODULE}.so: ${MAKE} -f makefile.f2py ${EXECUTABLE}.exe: ${MAKE} -f makefile.petsc \ PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} .PHONY:clean clean: ${RM} -r __pycache__ *.py[co] ${RM} ${MODULE}.so ${EXECUTABLE}.exe petsc4py-3.19.6/demo/perftest/makefile.f2py000066400000000000000000000004741454104047300205330ustar00rootroot00000000000000-include ../../../../../petscdir.mk.f2py # -*- makefile -*- MODULE=App .PHONY:all all: ${MODULE}.so F2PY = f2py F2PY_FLAGS = --quiet F2PY_FLAGS += --noarch --f90flags='' F2PY_FLAGS += -DF2PY_REPORT_ON_ARRAY_COPY=1 ${MODULE}.so: ${MODULE}.pyf ${MODULE}.f90 ${F2PY} ${F2PY_FLAGS} -m ${MODULE} -c $< ${MODULE}.f90 petsc4py-3.19.6/demo/perftest/makefile.petsc000066400000000000000000000011631454104047300207650ustar00rootroot00000000000000# -*- makefile -*- EXECUTABLE=driver -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:all all: ${EXECUTABLE}.exe SOURCEC=${EXECUTABLE}.c SOURCEF=App.f90 OBJSC=${SOURCEC:.c=.o} OBJSF=${SOURCEF:.f90=.o} ${EXECUTABLE}.exe: ${SOURCEC} ${SOURCEF} ${FC} -o ${OBJSF} ${SOURCEF} -c ${FC_FLAGS} ${FFLAGS} ${CC} -o ${OBJSC} ${SOURCEC} -c ${CC_FLAGS} ${CFLAGS} ${CCPPFLAGS} ${CLINKER} -o $@ ${OBJSC} ${OBJSF} ${PETSC_TS_LIB} ${RM} ${OBJSC} ${OBJSF} include ${PETSC_DIR}/lib/petsc/conf/variables include ${PETSC_DIR}/lib/petsc/conf/rules OBJSC=${SOURCEC:.c=.o} OBJSF=${SOURCEF:.f90=.o} petsc4py-3.19.6/demo/petsc-examples/000077500000000000000000000000001454104047300172455ustar00rootroot00000000000000petsc4py-3.19.6/demo/petsc-examples/ksp/000077500000000000000000000000001454104047300200425ustar00rootroot00000000000000petsc4py-3.19.6/demo/petsc-examples/ksp/ex2.py000066400000000000000000000146531454104047300211230ustar00rootroot00000000000000 ''' Ex2 from PETSc example files implemented for PETSc4py. https://petsc.org/release/src/ksp/ksp/tutorials/ex2.c.html By: Miguel Arriaga Solves a linear system in parallel with KSP. Input parameters include: -view_exact_sol : write exact solution vector to stdout -m : number of mesh points in x-direction -n : number of mesh points in y-direction Vec x,b,u; # approx solution, RHS, exact solution Mat A; # linear system matrix KSP ksp; # linear solver context PetscReal norm; # norm of solution error ''' import sys import petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np comm = PETSc.COMM_WORLD size = comm.getSize() rank = comm.getRank() OptDB = PETSc.Options() m = OptDB.getInt('m', 8) n = OptDB.getInt('n', 7) ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Compute the matrix and right-hand-side vector that define the linear system, Ax = b. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' ''' Create parallel matrix, specifying only its global dimensions. When using MatCreate(), the matrix format can be specified at runtime. Also, the parallel partitioning of the matrix is determined by PETSc at runtime. Performance tuning note: For problems of substantial size, preallocation of matrix memory is crucial for attaining good performance. See the matrix chapter of the users manual for details. ''' A = PETSc.Mat().create(comm=comm) A.setSizes((m*n,m*n)) A.setFromOptions() A.setPreallocationNNZ((5,5)) ''' Currently, all PETSc parallel matrix formats are partitioned by contiguous chunks of rows across the processors. Determine which rows of the matrix are locally owned. ''' Istart,Iend = A.getOwnershipRange() ''' Set matrix elements for the 2-D, five-point stencil in parallel. - Each processor needs to insert only elements that it owns locally (but any non-local elements will be sent to the appropriate processor during matrix assembly). - Always specify global rows and columns of matrix entries. Note: this uses the less common natural ordering that orders first all the unknowns for x = h then for x = 2h etc; Hence you see J = Ii +- n instead of J = I +- m as you might expect. The more standard ordering would first do all variables for y = h, then y = 2h etc. ''' for Ii in range(Istart,Iend): v = -1.0 i = int(Ii/n) j = int(Ii - i*n) if (i>0): J = Ii - n A.setValues(Ii,J,v,addv=True) if (i0): J = Ii - 1 A.setValues(Ii,J,v,addv=True) if (j -pc_type -ksp_monitor -ksp_rtol These options will override those specified above as long as KSPSetFromOptions() is called _after_ any other customization routines. ''' ksp.setFromOptions() ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve the linear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' ksp.solve(b,x) ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Check the solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' x = x - u # x.axpy(-1.0,u) norm = x.norm(PETSc.NormType.NORM_2) its = ksp.getIterationNumber() ''' Print convergence information. PetscPrintf() produces a single print statement from all processes that share a communicator. An alternative is PetscFPrintf(), which prints to a file. ''' if norm > rtol*10: PETSc.Sys.Print("Norm of error {}, Iterations {}".format(norm,its),comm=comm) else: if size==1: PETSc.Sys.Print("- Serial OK",comm=comm) else: PETSc.Sys.Print("- Parallel OK",comm=comm) petsc4py-3.19.6/demo/petsc-examples/ksp/ex23.py000066400000000000000000000117471454104047300212070ustar00rootroot00000000000000 ''' Ex23 from PETSc example files implemented for PETSc4py. https://petsc.org/release/src/ksp/ksp/tutorials/ex23.c.html By: Miguel Arriaga Solves a tridiagonal linear system. Vec x, b, u; approx solution, RHS, exact solution Mat A; linear system matrix KSP ksp; linear solver context PC pc; preconditioner context PetscReal norm; norm of solution error ''' import sys import petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np comm = PETSc.COMM_WORLD size = comm.getSize() rank = comm.getRank() n = 12 # Size of problem tol = 1E-11 # Tolerance of Result. tol=1000.*PETSC_MACHINE_EPSILON; ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Compute the matrix and right-hand-side vector that define the linear system, Ax = b. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create vectors. Note that we form 1 vector from scratch and then duplicate as needed. For this simple case let PETSc decide how many elements of the vector are stored on each processor. The second argument to VecSetSizes() below causes PETSc to decide. ''' x = PETSc.Vec().create(comm=comm) x.setSizes(n) x.setFromOptions() b = x.duplicate() u = x.duplicate() ''' Identify the starting and ending mesh points on each processor for the interior part of the mesh. We let PETSc decide above. ''' rstart,rend = x.getOwnershipRange() nlocal = x.getLocalSize() ''' Create matrix. When using MatCreate(), the matrix format can be specified at runtime. Performance tuning note: For problems of substantial size, preallocation of matrix memory is crucial for attaining good performance. See the matrix chapter of the users manual for details. We pass in nlocal as the "local" size of the matrix to force it to have the same parallel layout as the vector created above. ''' A = PETSc.Mat().create(comm=comm) A.setSizes(n,nlocal) A.setFromOptions() A.setUp() ''' Assemble matrix. The linear system is distributed across the processors by chunks of contiguous rows, which correspond to contiguous sections of the mesh on which the problem is discretized. For matrix assembly, each processor contributes entries for the part that it owns locally. ''' col = np.zeros(3,dtype=PETSc.IntType) value = np.zeros(3,dtype=PETSc.ScalarType) if not rstart: rstart = 1 i = 0; col[0] = 0; col[1] = 1; value[0] = 2.0; value[1] = -1.0 A.setValues(i,col[0:2],value[0:2]) if rend == n: rend = n-1 i = n-1; col[0] = n-2; col[1] = n-1; value[0] = -1.0; value[1] = 2.0 A.setValues(i,col[0:2],value[0:2]) ''' Set entries corresponding to the mesh interior ''' value[0] = -1.0; value[1] = 2.0; value[2] = -1.0 for i in range(rstart,rend): col[0] = i-1; col[1] = i; col[2] = i+1 A.setValues(i,col,value) ''' Assemble the matrix ''' A.assemblyBegin(A.AssemblyType.FINAL) A.assemblyEnd(A.AssemblyType.FINAL) ''' Set exact solution; then compute right-hand-side vector. ''' u.set(1.0) b = A(u) ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the linear solver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' ''' Create linear solver context ''' ksp = PETSc.KSP().create() ''' Set operators. Here the matrix that defines the linear system also serves as the preconditioning matrix. ''' ksp.setOperators(A,A) ''' Set linear solver defaults for this problem (optional). - By extracting the KSP and PC contexts from the KSP context, we can then directly call any KSP and PC routines to set various options. - The following four statements are optional; all of these parameters could alternatively be specified at runtime via KSPSetFromOptions(); ''' pc = ksp.getPC() pc.setType('jacobi') ksp.setTolerances(rtol=1.e-7) ''' Set runtime options, e.g., -ksp_type -pc_type -ksp_monitor -ksp_rtol These options will override those specified above as long as KSPSetFromOptions() is called _after_ any other customization routines. ''' ksp.setFromOptions() ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve the linear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' ''' Solve linear system ''' ksp.solve(b,x) ''' View solver info; we could instead use the option -ksp_view to print this info to the screen at the conclusion of KSPSolve(). ''' # ksp.view() ''' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Check solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ''' ''' Check the error ''' x = x - u # x.axpy(-1.0,u) norm = x.norm(PETSc.NormType.NORM_2) its = ksp.getIterationNumber() if norm > tol: PETSc.Sys.Print("Norm of error {}, Iterations {}\n".format(norm,its),comm=comm) else: if size==1: PETSc.Sys.Print("- Serial OK",comm=comm) else: PETSc.Sys.Print("- Parallel OK",comm=comm) petsc4py-3.19.6/demo/petsc-examples/ksp/makefile000066400000000000000000000003561454104047300215460ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC=mpiexec -n 2 PYTHON=python3 -include ../../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables scripts = ex2 ex23 all: $(scripts) $(scripts): ${PYTHON} $@.py ${MPIEXEC} ${PYTHON} $@.py petsc4py-3.19.6/demo/petsc-examples/makefile000066400000000000000000000001041454104047300207400ustar00rootroot00000000000000-include ../../../../../petscdir.mk .PHONY:all all: ${MAKE} -C ksp petsc4py-3.19.6/demo/poisson2d/000077500000000000000000000000001454104047300162335ustar00rootroot00000000000000petsc4py-3.19.6/demo/poisson2d/makefile000066400000000000000000000004311454104047300177310ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: ${MPIEXEC} ${PYTHON} poisson2d.py -nx 15 -ny 16 .PHONY:clean clean: ${RM} *.py[co] ${RM} -r __pycache__ petsc4py-3.19.6/demo/poisson2d/poisson2d.py000066400000000000000000000052031454104047300205250ustar00rootroot00000000000000# ------------------------------------------------------------------------ # # Poisson problem. This problem is modeled by the partial # differential equation # # -Laplacian(u) = 1, 0 < x,y < 1, # # with boundary conditions # # u = 0 for x = 0, x = 1, y = 0, y = 1 # # A finite difference approximation with the usual 7-point stencil # is used to discretize the boundary value problem to obtain a # nonlinear system of equations. The problem is solved in a 2D # rectangular domain, using distributed arrays (DAs) to partition # the parallel grid. # # ------------------------------------------------------------------------ try: range = xrange except: pass import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class Poisson2D(object): def __init__(self, da): assert da.getDim() == 2 self.da = da self.localX = da.createLocalVec() def formRHS(self, B): b = self.da.getVecArray(B) mx, my = self.da.getSizes() hx, hy = [1.0/m for m in [mx, my]] (xs, xe), (ys, ye) = self.da.getRanges() for j in range(ys, ye): for i in range(xs, xe): b[i, j] = 1*hx*hy def mult(self, mat, X, Y): # self.da.globalToLocal(X, self.localX) x = self.da.getVecArray(self.localX) y = self.da.getVecArray(Y) # mx, my = self.da.getSizes() hx, hy = [1.0/m for m in [mx, my]] (xs, xe), (ys, ye) = self.da.getRanges() for j in range(ys, ye): for i in range(xs, xe): u = x[i, j] # center u_e = u_w = u_n = u_s = 0 if i > 0: u_w = x[i-1, j] # west if i < mx-1: u_e = x[i+1, j] # east if j > 0: u_s = x[i, j-1] # south if j < ny-1: u_n = x[i, j+1] # north u_xx = (-u_e + 2*u - u_w)*hy/hx u_yy = (-u_n + 2*u - u_s)*hx/hy y[i, j] = u_xx + u_yy OptDB = PETSc.Options() n = OptDB.getInt('n', 16) nx = OptDB.getInt('nx', n) ny = OptDB.getInt('ny', n) da = PETSc.DMDA().create([nx, ny], stencil_width=1) pde = Poisson2D(da) x = da.createGlobalVec() b = da.createGlobalVec() # A = da.createMat('python') A = PETSc.Mat().createPython( [x.getSizes(), b.getSizes()], comm=da.comm) A.setPythonContext(pde) A.setUp() ksp = PETSc.KSP().create() ksp.setOperators(A) ksp.setType('cg') pc = ksp.getPC() pc.setType('none') ksp.setFromOptions() pde.formRHS(b) ksp.solve(b, x) u = da.createNaturalVec() da.globalToNatural(x, u) if OptDB.getBool('plot', True): draw = PETSc.Viewer.DRAW(x.comm) OptDB['draw_pause'] = 1 draw(x) petsc4py-3.19.6/demo/poisson3d/000077500000000000000000000000001454104047300162345ustar00rootroot00000000000000petsc4py-3.19.6/demo/poisson3d/del2lib.f90000066400000000000000000000012021454104047300200640ustar00rootroot00000000000000! file: del2lib.f90 ! to build a Python module, use this: ! $$ f2py -m del2lib -c del2lib.f90 subroutine del2apply (n, F, x, y) !f2py intent(hide) :: n=shape(F,0)-2 integer , intent(in) :: n real(kind=8) , intent(inout) :: F(0:n+1,0:n+1,0:n+1) real(kind=8) , intent(in) :: x(n,n,n) real(kind=8) , intent(inout) :: y(n,n,n) F(1:n,1:n,1:n) = x y(:,:,:) = 6.0 * F(1:n,1:n,1:n) & - F(0:n-1,1:n,1:n) & - F(2:n+1,1:n,1:n) & - F(1:n,0:n-1,1:n) & - F(1:n,2:n+1,1:n) & - F(1:n,1:n,0:n-1) & - F(1:n,1:n,2:n+1) end subroutine del2apply petsc4py-3.19.6/demo/poisson3d/del2mat.h000066400000000000000000000021121454104047300177310ustar00rootroot00000000000000/* file: del2mat.h */ #ifndef DEL2MAT_H #define DEL2MAT_H #include #include #include /* external Fortran 90 subroutine */ #define Del2Apply del2apply_ EXTERN_C_BEGIN extern void Del2Apply(int*,double*,const double*,double*); EXTERN_C_END /* user data structure and routines * defining the matrix-free operator */ typedef struct { PetscInt N; PetscScalar *F; } Del2Mat; /* y <- A * x */ PetscErrorCode Del2Mat_mult(Mat A, Vec x, Vec y) { Del2Mat *ctx; const PetscScalar *xx; PetscScalar *yy; PetscFunctionBegin; PetscCall(MatShellGetContext(A,&ctx)); /* get raw vector arrays */ PetscCall(VecGetArrayRead(x,&xx)); PetscCall(VecGetArray(y,&yy)); /* call external Fortran subroutine */ Del2Apply(&ctx->N,ctx->F,xx,yy); /* restore raw vector arrays */ PetscCall(VecRestoreArrayRead(x,&xx)); PetscCall(VecRestoreArray(y,&yy)); PetscFunctionReturn(PETSC_SUCCESS); } /*D_i <- A_ii */ PetscErrorCode Del2Mat_diag(Mat A, Vec D) { PetscFunctionBegin; PetscCall(VecSet(D,6.0)); PetscFunctionReturn(PETSC_SUCCESS); } #endif petsc4py-3.19.6/demo/poisson3d/del2mat.py000066400000000000000000000015071454104047300201410ustar00rootroot00000000000000# file: del2mat.py from numpy import zeros from del2lib import del2apply class Del2Mat: def __init__(self, n=1): self.N = (n, n, n) self.F = zeros([n+2]*3, order='f') def create(self, A): N = self.N mat_size = A.getSize() grid_eqs = N[0]*N[1]*N[2] assert mat_size[0] == grid_eqs assert mat_size[1] == grid_eqs def mult(self, A, x, y): "y <- A * x" N, F = self.N, self.F # get 3D arrays from vectos xx = x.getArray(readonly=1).reshape(N, order='f') yy = y.getArray(readonly=0).reshape(N, order='f') # call Fortran subroutine del2apply(F, xx, yy) def multTranspose(self, A, x, y): "y <- A' * x" self.mult(x, y) def getDiagonal(self, A, D): "D[i] <- A[i,i]" D[...] = 6.0 petsc4py-3.19.6/demo/poisson3d/makefile000066400000000000000000000013771454104047300177440ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python F2PY = f2py F2PY_FLAGS = --quiet F2PY_FLAGS += --noarch --f90flags='' F2PY_FLAGS += -DF2PY_REPORT_ON_ARRAY_COPY=1 -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean .PHONY:run run: run_py run_cc SCRIPT=poisson3d MODULE=del2lib .PHONY:run_py run_py: ${MODULE}.so ${MPIEXEC} ${PYTHON} ${SCRIPT}.py ${MODULE}.so: ${MODULE}.f90 ${F2PY} ${F2PY_FLAGS} -c $< -m ${MODULE} EXECUTABLE=poisson3d .PHONY:run_cc run_cc: ${EXECUTABLE}.exe ${MPIEXEC} ./${EXECUTABLE}.exe ${EXECUTABLE}.exe: ${MAKE} -f makefile.petsc \ PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} .PHONY:clean clean: ${RM} *.py[co] ${MODULE}*.so ${EXECUTABLE}.exe ${RM} -r __pycache__ petsc4py-3.19.6/demo/poisson3d/makefile.petsc000066400000000000000000000011011454104047300210420ustar00rootroot00000000000000# -*- makefile -*- EXECUTABLE=poisson3d -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:all all: ${EXECUTABLE}.exe SOURCEC=${EXECUTABLE}.c SOURCEF=del2lib.f90 SOURCEH=del2mat.h OBJSC=${SOURCEC:.c=.o} OBJSF=${SOURCEF:.f90=.o} ${EXECUTABLE}.exe: ${SOURCEC} ${SOURCEF} ${SOURCEH} ${PETSC_FCOMPILE} ${PETSC_COMPILE} ${CLINKER} -o $@ ${OBJSC} ${OBJSF} ${PETSC_TS_LIB} ${RM} ${OBJSC} ${OBJSF} include ${PETSC_DIR}/lib/petsc/conf/variables include ${PETSC_DIR}/lib/petsc/conf/rules OBJSC=${SOURCEC:.c=.o} OBJSF=${SOURCEF:.f90=.o} petsc4py-3.19.6/demo/poisson3d/poisson3d.c000066400000000000000000000036451454104047300203310ustar00rootroot00000000000000#include #include #include #include #include "del2mat.h" #define DEL2MAT_MULT ((void(*)(void))Del2Mat_mult) #define DEL2MAT_DIAG ((void(*)(void))Del2Mat_diag) int main(int argc,char **argv) { PetscInt n; PetscScalar h; Del2Mat shell; Mat A; Vec x,b; KSP ksp; PC pc; PetscMPIInt size; /* PETSc initialization */ PetscInitialize(&argc, &argv, NULL, NULL); MPI_Comm_size(PETSC_COMM_WORLD,&size); if (size != 1) { PetscPrintf(PETSC_COMM_WORLD, "This a sequential example\n"); PetscFinalize(); return 1; } /* number of nodes in each direction * excluding those at the boundary */ n = 32; h = 1.0/(n+1); /* grid spacing */ /* setup linear system (shell) matrix */ MatCreate(PETSC_COMM_SELF, &A); MatSetSizes(A, n*n*n, n*n*n, n*n*n, n*n*n); MatSetType(A, MATSHELL); shell.N = n; PetscMalloc((n+2)*(n+2)*(n+2)*sizeof(PetscScalar),&shell.F); PetscMemzero(shell.F, (n+2)*(n+2)*(n+2)*sizeof(PetscScalar)); MatShellSetContext(A, &shell); MatShellSetOperation(A, MATOP_MULT, DEL2MAT_MULT); MatShellSetOperation(A, MATOP_MULT_TRANSPOSE, DEL2MAT_MULT); MatShellSetOperation(A, MATOP_GET_DIAGONAL, DEL2MAT_DIAG); MatSetUp(A); /* setup linear system vectors */ MatCreateVecs(A, &x, &b); VecSet(x, 0); VecSet(b, 1); /* setup Krylov linear solver */ KSPCreate(PETSC_COMM_SELF, &ksp); KSPGetPC(ksp, &pc); KSPSetType(ksp, KSPCG); /* use conjugate gradients */ PCSetType(pc, PCNONE); /* with no preconditioning */ KSPSetFromOptions(ksp); /* iteratively solve linear system of equations A*x=b */ KSPSetOperators(ksp,A,A); KSPSolve(ksp, b, x); /* scale solution vector to account for grid spacing */ VecScale(x, h*h); /* free memory and destroy objects */ PetscFree(shell.F); VecDestroy(&x); VecDestroy(&b); MatDestroy(&A); KSPDestroy(&ksp); /* finalize PETSc */ PetscFinalize(); return 0; } petsc4py-3.19.6/demo/poisson3d/poisson3d.py000066400000000000000000000023121454104047300205250ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc from del2mat import Del2Mat # this a sequential example assert PETSc.COMM_WORLD.getSize() == 1 # number of nodes in each direction # excluding those at the boundary n = 32 h = 1.0/(n+1) # grid spacing # setup linear system matrix A = PETSc.Mat().create() A.setSizes([n**3, n**3]) A.setType('python') shell = Del2Mat(n) # shell context A.setPythonContext(shell) A.setUp() # setup linear system vectors x, b = A.createVecs() x.set(0.0) b.set(1.0) # setup Krylov solver ksp = PETSc.KSP().create() pc = ksp.getPC() ksp.setType('cg') pc.setType('none') # iteratively solve linear # system of equations A*x=b ksp.setOperators(A) ksp.setFromOptions() ksp.solve(b, x) # scale solution vector to # account for grid spacing x.scale(h**2) OptDB = PETSc.Options() if OptDB.getBool('plot_mpl', False): try: from matplotlib import pylab except ImportError: PETSc.Sys.Print("matplotlib not available") else: from numpy import mgrid X, Y = mgrid[0:1:1j*n,0:1:1j*n] Z = x[...].reshape(n,n,n)[:,:,n/2-2] pylab.contourf(X, Y, Z) pylab.axis('equal') pylab.colorbar() pylab.show() petsc4py-3.19.6/demo/taosolve/000077500000000000000000000000001454104047300161475ustar00rootroot00000000000000petsc4py-3.19.6/demo/taosolve/chwirut.py000066400000000000000000000034611454104047300202120ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) import numpy as np from petsc4py import PETSc class Chwirut(object): """ Finds the nonlinear least-squares solution to the model y = exp(-b1*x)/(b2+b3*x) + e """ def __init__(self): BETA = [0.2, 0.12, 0.08] NOBSERVATIONS = 100 NPARAMETERS = 3 np.random.seed(456) x = np.random.rand(NOBSERVATIONS) e = np.random.rand(NOBSERVATIONS) y = np.exp(-BETA[0]*x)/(BETA[1] + BETA[2]*x) + e self.NOBSERVATIONS = NOBSERVATIONS self.NPARAMETERS = NPARAMETERS self.x = x self.y = y def createVecs(self): X = PETSc.Vec().create(PETSc.COMM_SELF) X.setSizes(self.NPARAMETERS) F = PETSc.Vec().create(PETSc.COMM_SELF) F.setSizes(self.NOBSERVATIONS) return X, F def formInitialGuess(self, X): X[0] = 0.15 X[1] = 0.08 X[2] = 0.05 def formResidual(self, tao, X, F): x, y = self.x, self.y b1, b2, b3 = X.array F.array = y - np.exp(-b1*x)/(b2 + b3*x) def plotSolution(self, X): try: from matplotlib import pylab except ImportError: return b1, b2, b3 = X.array x, y = self.x, self.y u = np.linspace(x.min(), x.max(), 100) v = np.exp(-b1*u)/(b2+b3*u) pylab.plot(x, y, 'ro') pylab.plot(u, v, 'b-') pylab.show() OptDB = PETSc.Options() user = Chwirut() x, f = user.createVecs() x.setFromOptions() f.setFromOptions() tao = PETSc.TAO().create(PETSc.COMM_SELF) tao.setType(PETSc.TAO.Type.POUNDERS) tao.setResidual(user.formResidual, f) tao.setFromOptions() user.formInitialGuess(x) tao.solve(x) plot = OptDB.getBool('plot', False) if plot: user.plotSolution(x) x.destroy() f.destroy() tao.destroy() petsc4py-3.19.6/demo/taosolve/rosenbrock.py000066400000000000000000000070571454104047300207010ustar00rootroot00000000000000""" This example demonstrates the use of TAO for Python to solve an unconstrained minimization problem on a single processor. We minimize the extended Rosenbrock function:: sum_{i=0}^{n/2-1} ( alpha*(x_{2i+1}-x_{2i}^2)^2 + (1-x_{2i})^2 ) """ try: range = xrange except NameError: pass # the two lines below are only # needed to build options database # from command line arguments import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc class AppCtx(object): """ Extended Rosenbrock function. """ def __init__(self, n=2, alpha=99.0): self.size = int(n) self.alpha = float(alpha) def formObjective(self, tao, x): #print 'AppCtx.formObjective()' alpha = self.alpha nn = self.size // 2 ff = 0.0 for i in range(nn): t1 = x[2*i+1] - x[2*i] * x[2*i] t2 = 1 - x[2*i]; ff += alpha*t1*t1 + t2*t2; return ff def formGradient(self, tao, x, G): #print 'AppCtx.formGradient()' alpha = self.alpha nn = self.size // 2 G.zeroEntries() for i in range(nn): t1 = x[2*i+1] - x[2*i] * x[2*i] t2 = 1 - x[2*i]; G[2*i] = -4*alpha*t1*x[2*i] - 2*t2; G[2*i+1] = 2*alpha*t1; def formObjGrad(self, tao, x, G): #print 'AppCtx.formObjGrad()' alpha = self.alpha nn = self.size // 2 ff = 0.0 G.zeroEntries() for i in range(nn): t1 = x[2*i+1] - x[2*i] * x[2*i] t2 = 1 - x[2*i]; ff += alpha*t1*t1 + t2*t2; G[2*i] = -4*alpha*t1*x[2*i] - 2*t2; G[2*i+1] = 2*alpha*t1; return ff def formHessian(self, tao, x, H, HP): #print 'AppCtx.formHessian()' alpha = self.alpha nn = self.size // 2 idx = [0, 0] v = [[0.0, 0.0], [0.0, 0.0]] H.zeroEntries() for i in range(nn): v[1][1] = 2*alpha v[0][0] = -4*alpha*(x[2*i+1]-3*x[2*i]*x[2*i]) + 2 v[1][0] = v[0][1] = -4.0*alpha*x[2*i]; idx[0] = 2*i idx[1] = 2*i+1 H[idx,idx] = v H.assemble() # access PETSc options database OptDB = PETSc.Options() # create user application context # and configure user parameters user = AppCtx() user.size = OptDB.getInt ( 'n', user.size) user.alpha = OptDB.getReal('alpha', user.alpha) # create solution vector x = PETSc.Vec().create(PETSc.COMM_SELF) x.setSizes(user.size) x.setFromOptions() # create Hessian matrix H = PETSc.Mat().create(PETSc.COMM_SELF) H.setSizes([user.size, user.size]) H.setFromOptions() H.setOption(PETSc.Mat.Option.SYMMETRIC, True) H.setUp() # pass the following to command line: # $ ... -methods nm,lmvm,nls,ntr,cg,blmvm,tron # to try many methods methods = OptDB.getString('methods', '') methods = methods.split(',') for meth in methods: # create TAO Solver tao = PETSc.TAO().create(PETSc.COMM_SELF) if meth: tao.setType(meth) tao.setFromOptions() # solve the problem tao.setObjectiveGradient(user.formObjGrad) tao.setObjective(user.formObjective) tao.setGradient(user.formGradient) tao.setHessian(user.formHessian, H) #app.getKSP().getPC().setFromOptions() x.set(0) # zero initial guess tao.setSolution(x) tao.solve() tao.destroy() ## # this is just for testing ## x = app.getSolution() ## G = app.getGradient() ## H, HP = app.getHessian() ## f = tao.computeObjective(x) ## tao.computeGradient(x, G) ## f = tao.computeObjectiveGradient(x, G) ## tao.computeHessian(x, H, HP) petsc4py-3.19.6/demo/wrap-cython/000077500000000000000000000000001454104047300165665ustar00rootroot00000000000000petsc4py-3.19.6/demo/wrap-cython/Bratu3D.pyx000066400000000000000000000022701454104047300205750ustar00rootroot00000000000000from petsc4py.PETSc cimport Vec, PetscVec from petsc4py.PETSc cimport Mat, PetscMat from petsc4py.PETSc cimport DM, PetscDM from petsc4py.PETSc cimport SNES, PetscSNES from petsc4py.PETSc import Error cdef extern from "Bratu3Dimpl.h": ctypedef struct Params: double lambda_ int FormInitGuess(PetscDM da, PetscVec x, Params *p) int FormFunction (PetscDM da, PetscVec x, PetscVec F, Params *p) int FormJacobian (PetscDM da, PetscVec x, PetscMat J, Params *p) def formInitGuess(Vec x, DM da, double lambda_): cdef int ierr cdef Params p = {"lambda_" : lambda_} ierr = FormInitGuess(da.dm, x.vec, &p) if ierr != 0: raise Error(ierr) def formFunction(SNES snes, Vec x, Vec f, DM da, double lambda_): cdef int ierr cdef Params p = {"lambda_" : lambda_} ierr = FormFunction(da.dm, x.vec, f.vec, &p) if ierr != 0: raise Error(ierr) def formJacobian(SNES snes, Vec x, Mat J, Mat P, DM da, double lambda_): cdef int ierr cdef Params p = {"lambda_" : lambda_} ierr = FormJacobian(da.dm, x.vec, P.mat, &p) if ierr != 0: raise Error(ierr) if J != P: J.assemble() # for matrix-free operator return Mat.Structure.SAME_NONZERO_PATTERN petsc4py-3.19.6/demo/wrap-cython/Bratu3Dimpl.c000066400000000000000000000204201454104047300210560ustar00rootroot00000000000000/* ------------------------------------------------------------------------ Solid Fuel Ignition (SFI) problem. This problem is modeled by the partial differential equation -Laplacian(u) - lambda * exp(u) = 0, 0 < x,y,z < 1, with boundary conditions u = 0 for x = 0, x = 1, y = 0, y = 1, z = 0, z = 1 A finite difference approximation with the usual 7-point stencil is used to discretize the boundary value problem to obtain a nonlinear system of equations. The problem is solved in a 3D rectangular domain, using distributed arrays (DAs) to partition the parallel grid. ------------------------------------------------------------------------- */ #include "Bratu3Dimpl.h" PetscErrorCode FormInitGuess(DM da, Vec X, Params *p) { PetscInt i,j,k,Mx,My,Mz,xs,ys,zs,xm,ym,zm; PetscReal lambda,temp1,hx,hy,hz,tempk,tempj; PetscScalar ***x; PetscFunctionBegin; PetscCall(DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My,&Mz,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE)); lambda = p->lambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); temp1 = lambda/(lambda + 1.0); /* Get a pointer to vector data. - For default PETSc vectors, VecGetArray() returns a pointer to the data array. Otherwise, the routine is implementation dependent. - You MUST call VecRestoreArray() when you no longer need access to the array. */ PetscCall(DMDAVecGetArray(da,X,&x)); /* Get local grid boundaries (for 3-dimensional DMDA): - xs, ys, zs: starting grid indices (no ghost points) - xm, ym, zm: widths of local grid (no ghost points) */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute initial guess over the locally owned part of the grid */ for (k=zs; klambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); sc = hx*hy*hz*lambda; hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; /* */ PetscCall(DMGetLocalVector(da,&localX)); /* Scatter ghost points to local vector,using the 2-step process DMGlobalToLocalBegin(),DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX)); PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX)); /* Get pointers to vector data. */ PetscCall(DMDAVecGetArray(da,localX,&x)); PetscCall(DMDAVecGetArray(da,F,&f)); /* Get local grid boundaries. */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute function over the locally owned part of the grid. */ for (k=zs; klambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); sc = hx*hy*hz*lambda; hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; /* */ PetscCall(DMGetLocalVector(da,&localX)); /* Scatter ghost points to local vector, using the 2-step process DMGlobalToLocalBegin(), DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX)); PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX)); /* Get pointer to vector data. */ PetscCall(DMDAVecGetArray(da,localX,&x)); /* Get local grid boundaries. */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute entries for the locally owned part of the Jacobian. - Currently, all PETSc parallel matrix formats are partitioned by contiguous chunks of rows across the processors. - Each processor needs to insert only elements that it owns locally (but any non-local elements will be sent to the appropriate processor during matrix assembly). - Here, we set all entries for a particular row at once. - We can set matrix entries either using either MatSetValuesLocal() or MatSetValues(), as discussed above. */ for (k=zs; k typedef struct Params { double lambda_; } Params; PetscErrorCode FormInitGuess(DM da, Vec x, Params *p); PetscErrorCode FormFunction(DM da, Vec x, Vec F, Params *p); PetscErrorCode FormJacobian(DM da, Vec x, Mat J, Params *p); #endif /* !BRATU3D_H */ petsc4py-3.19.6/demo/wrap-cython/makefile000066400000000000000000000011611454104047300202650ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean SCRIPT=run_demo MODULE=Bratu3D .PHONY:build build: ${MODULE}.so .PHONY:run run: build ${MPIEXEC} ${PYTHON} ${SCRIPT}.py ${MODULE}.so: ${MODULE}.pyx ${MODULE}impl.h ${MODULE}impl.c CC=${CC} F90=${FC} \ ${PYTHON} setup.py -q build_ext --inplace ${RM} -r build ${MODULE}.c .PHONY:clean clean:: ${RM} ${MODULE}.c ${MODULE}*.so ${RM} *.py[co] ${RM} -r __pycache__ include ${PETSC_DIR}/lib/petsc/conf/variables include ${PETSC_DIR}/lib/petsc/conf/rules MPIEXEC= petsc4py-3.19.6/demo/wrap-cython/run_demo.py000066400000000000000000000024371454104047300207560ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import Bratu3D as Bratu3D OptDB = PETSc.Options() N = OptDB.getInt('N', 16) lambda_ = OptDB.getReal('lambda', 6.0) do_plot = OptDB.getBool('plot', False) da = PETSc.DMDA().create([N, N, N], stencil_width=1) #app = App(da, lambda_) snes = PETSc.SNES().create() F = da.createGlobalVec() snes.setFunction(Bratu3D.formFunction, F, args=(da, lambda_)) J = da.createMat() snes.setJacobian(Bratu3D.formJacobian, J, args=(da, lambda_)) snes.setFromOptions() X = da.createGlobalVec() Bratu3D.formInitGuess(X, da, lambda_) snes.solve(None, X) U = da.createNaturalVec() da.globalToNatural(X, U) def plot(da, U): scatter, U0 = PETSc.Scatter.toZero(U) scatter.scatter(U, U0, False, PETSc.Scatter.Mode.FORWARD) rank = PETSc.COMM_WORLD.getRank() if rank == 0: solution = U0[...].reshape(da.sizes, order='f').copy() try: from matplotlib import pyplot pyplot.contourf(solution[:, :, N//2]) pyplot.axis('equal') pyplot.show() except: pass PETSc.COMM_WORLD.barrier() scatter.destroy() U0.destroy() if do_plot: plot(da, U) U.destroy() X.destroy() F.destroy() J.destroy() da.destroy() snes.destroy() petsc4py-3.19.6/demo/wrap-cython/setup.py000066400000000000000000000027221454104047300203030ustar00rootroot00000000000000#!/usr/bin/env python #$ python setup.py build_ext --inplace from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy import petsc4py def configure(): INCLUDE_DIRS = [] LIBRARY_DIRS = [] LIBRARIES = [] # PETSc import os PETSC_DIR = os.environ['PETSC_DIR'] PETSC_ARCH = os.environ.get('PETSC_ARCH', '') from os.path import join, isdir if PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH)): INCLUDE_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'include'), join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'lib')] else: if PETSC_ARCH: pass # XXX should warn ... INCLUDE_DIRS += [join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, 'lib')] LIBRARIES += ['petsc'] # PETSc for Python INCLUDE_DIRS += [petsc4py.get_include()] # NumPy INCLUDE_DIRS += [numpy.get_include()] return dict( include_dirs=INCLUDE_DIRS + [os.curdir], libraries=LIBRARIES, library_dirs=LIBRARY_DIRS, runtime_library_dirs=LIBRARY_DIRS, ) extensions = [ Extension('Bratu3D', sources = ['Bratu3D.pyx', 'Bratu3Dimpl.c'], depends = ['Bratu3Dimpl.h'], **configure()), ] setup(name = "Bratu3D", ext_modules = cythonize( extensions, include_path=[petsc4py.get_include()]), ) petsc4py-3.19.6/demo/wrap-f2py/000077500000000000000000000000001454104047300161425ustar00rootroot00000000000000petsc4py-3.19.6/demo/wrap-f2py/.f2py_f2cmap000066400000000000000000000000431454104047300202500ustar00rootroot00000000000000{'integer':{'HANDLE_KIND':'long'}} petsc4py-3.19.6/demo/wrap-f2py/Bratu2D.F90000066400000000000000000000161041454104047300176670ustar00rootroot00000000000000! --------------------------------------------------------------------- ! ! Solid Fuel Ignition (SFI) problem. This problem is modeled by ! the partial differential equation ! ! -Laplacian(u) - lambda * exp(u) = 0, 0 < x,y < 1, ! ! with boundary conditions ! ! u = 0 for x = 0, x = 1, y = 0, y = 1, ! ! A finite difference approximation with the usual 5-point stencil ! is used to discretize the boundary value problem to obtain a ! nonlinear system of equations. The problem is solved in a 2D ! rectangular domain, using distributed arrays (DAs) to partition ! the parallel grid. ! ! -------------------------------------------------------------------- #include module Bratu2D use petsc implicit none type gridinfo PetscInt mx,xs,xe,xm,gxs,gxe,gxm PetscInt my,ys,ye,ym,gys,gye,gym end type gridinfo contains subroutine GetGridInfo(da, grd, ierr) implicit none DM da type(gridinfo) grd PetscErrorCode ierr ! PetscCall(DMDAGetInfo(da, PETSC_NULL_INTEGER,grd%mx, grd%my, PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,ierr)) PetscCall(DMDAGetCorners(da,grd%xs,grd%ys,PETSC_NULL_INTEGER,grd%xm,grd%ym,PETSC_NULL_INTEGER,ierr)) PetscCall(DMDAGetGhostCorners(da,grd%gxs,grd%gys,PETSC_NULL_INTEGER,grd%gxm,grd%gym,PETSC_NULL_INTEGER,ierr)) grd%xs = grd%xs+1 grd%ys = grd%ys+1 grd%gxs = grd%gxs+1 grd%gys = grd%gys+1 grd%ye = grd%ys+grd%ym-1 grd%xe = grd%xs+grd%xm-1 grd%gye = grd%gys+grd%gym-1 grd%gxe = grd%gxs+grd%gxm-1 end subroutine GetGridInfo subroutine InitGuessLocal(grd, x, lambda, ierr) implicit none type(gridinfo) grd PetscScalar x(grd%xs:grd%xe,grd%ys:grd%ye) PetscReal lambda PetscErrorCode ierr ! PetscInt i, j PetscReal hx,hy,temp,temp1,one one = 1.0 hx = one/(dble(grd%mx-1)) hy = one/(dble(grd%my-1)) temp1 = lambda/(lambda+one) do j=grd%ys,grd%ye temp = dble(min(j-1,grd%my-j))*hy do i=grd%xs,grd%xe if (i==1 .or. j==1 .or. i==grd%mx .or. j==grd%my) then ! boundary points x(i,j) = 0.0 else ! interior grid points x(i,j) = temp1*sqrt(min(dble(min(i-1,grd%mx-i)*hx),dble(temp))) end if end do end do ierr = 0 end subroutine InitGuessLocal subroutine FunctionLocal(grd, x, f, lambda, ierr) implicit none type(gridinfo) grd PetscScalar x(grd%gxs:grd%gxe,grd%gys:grd%gye) PetscScalar f(grd%xs:grd%xe,grd%ys:grd%ye) PetscReal lambda PetscErrorCode ierr ! PetscInt i,j PetscReal hx,hy,hxdhy,hydhx,sc,one,two PetscScalar u,uxx,uyy one = 1.0 two = 2.0 hx = one/dble(grd%mx-1) hy = one/dble(grd%my-1) sc = hx*hy hxdhy = hx/hy hydhx = hy/hx do j=grd%ys,grd%ye do i=grd%xs,grd%xe if (i==1 .or. j==1 .or. i==grd%mx .or. j==grd%my) then ! boundary points f(i,j) = x(i,j) - 0.0 else ! interior grid points u = x(i,j) uxx = (two*u - x(i-1,j) - x(i+1,j)) * hydhx uyy = (two*u - x(i,j-1) - x(i,j+1)) * hxdhy f(i,j) = uxx + uyy - lambda*exp(u)*sc end if end do end do ierr = 0 end subroutine FunctionLocal subroutine JacobianLocal(grd, x, Jac, lambda, ierr) implicit none type(gridinfo) grd PetscScalar x(grd%gxs:grd%gxe,grd%gys:grd%gye) Mat Jac PetscReal lambda PetscErrorCode ierr ! PetscInt i,j,row(1),col(5) PetscInt ione,ifive PetscReal hx,hy,hxdhy,hydhx,sc,v(5),one,two ione = 1 ifive = 5 one = 1.0 two = 2.0 hx = one/dble(grd%mx-1) hy = one/dble(grd%my-1) sc = hx*hy hxdhy = hx/hy hydhx = hy/hx do j=grd%ys,grd%ye row = (j - grd%gys)*grd%gxm + grd%xs - grd%gxs - 1 do i=grd%xs,grd%xe row = row + 1 if (i==1 .or. j==1 .or. i==grd%mx .or. j==grd%my) then ! boundary points col(1) = row(1) v(1) = one PetscCall(MatSetValuesLocal(Jac,ione,row,ione,col,v,INSERT_VALUES,ierr)) else ! interior grid points v(1) = -hxdhy v(2) = -hydhx v(3) = two*(hydhx + hxdhy) - lambda*exp(x(i,j))*sc v(4) = -hydhx v(5) = -hxdhy col(1) = row(1) - grd%gxm col(2) = row(1) - 1 col(3) = row(1) col(4) = row(1) + 1 col(5) = row(1) + grd%gxm PetscCall(MatSetValuesLocal(Jac,ione,row,ifive,col,v,INSERT_VALUES,ierr)) end if end do end do end subroutine JacobianLocal end module Bratu2D ! -------------------------------------------------------------------- subroutine FormInitGuess(da, X, lambda, ierr) use Bratu2D implicit none DM da Vec X PetscReal lambda PetscErrorCode ierr ! type(gridinfo) :: grd PetscScalar,pointer :: xx(:) PetscCall(VecGetArrayF90(X,xx,ierr)) PetscCall(GetGridInfo(da,grd,ierr)) PetscCall(InitGuessLocal(grd,xx,lambda,ierr)) PetscCall(VecRestoreArrayF90(X,xx,ierr)) end subroutine FormInitGuess subroutine FormFunction(da, X, F, lambda, ierr) use Bratu2D implicit none DM da Vec X Vec F PetscReal lambda PetscErrorCode ierr ! type(gridinfo) :: grd Vec :: localX PetscScalar,pointer :: xx(:) PetscScalar,pointer :: ff(:) PetscCall(DMGetLocalVector(da,localX,ierr)) PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX,ierr)) PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX,ierr)) PetscCall(VecGetArrayF90(localX,xx,ierr)) PetscCall(VecGetArrayF90(F,ff,ierr)) PetscCall(GetGridInfo(da,grd,ierr)) PetscCall(FunctionLocal(grd,xx,ff,lambda,ierr)) PetscCall(VecRestoreArrayF90(F,ff,ierr)) PetscCall(VecRestoreArrayF90(localX,xx,ierr)) PetscCall(DMRestoreLocalVector(da,localX,ierr)) end subroutine FormFunction subroutine FormJacobian(da, X, J, lambda, ierr) use Bratu2D implicit none DM da Vec X Mat J PetscReal lambda PetscErrorCode ierr ! type(gridinfo) :: grd Vec :: localX PetscScalar,pointer :: xx(:) PetscCall(DMGetLocalVector(da,localX,ierr)) PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX,ierr)) PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX,ierr)) PetscCall(VecGetArrayF90(localX,xx,ierr)) PetscCall(GetGridInfo(da,grd,ierr)) PetscCall(JacobianLocal(grd,xx,J,lambda,ierr)) PetscCall(VecRestoreArrayF90(localX,xx,ierr)) PetscCall(DMRestoreLocalVector(da,localX,ierr)) PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY,ierr)) PetscCall(MatAssemblyEnd (J,MAT_FINAL_ASSEMBLY,ierr)) end subroutine FormJacobian ! -------------------------------------------------------------------- ! Local Variables: ! mode: f90 ! End: petsc4py-3.19.6/demo/wrap-f2py/Bratu2D.pyf000066400000000000000000000020431454104047300201240ustar00rootroot00000000000000! -*- f90 -*- python module Bratu2D usercode ''' #include "Bratu2Dmodule.h" ''' interface subroutine FormInitGuess(dm, x, param, ierr) !integer, parameter :: HANDLE_KIND=4 integer(kind=HANDLE_KIND) dm ! DM integer(kind=HANDLE_KIND) x ! Vec real(kind=8) param integer, intent(out) :: ierr end subroutine FormInitGuess subroutine FormFunction(dm, x, f, param, ierr) !integer, parameter :: HANDLE_KIND=4 integer(kind=HANDLE_KIND) dm ! DM integer(kind=HANDLE_KIND) x ! Vec integer(kind=HANDLE_KIND) f ! Vec real(kind=8) param integer, intent(out) :: ierr end subroutine FormFunction subroutine FormJacobian(dm, x, J, param, ierr) !integer, parameter :: HANDLE_KIND=4 integer(kind=HANDLE_KIND) dm ! DM integer(kind=HANDLE_KIND) x ! Vec integer(kind=HANDLE_KIND) J ! Vec real(kind=8) param integer, intent(out) :: ierr end subroutine FormJacobian end interface end python module Bratu2D petsc4py-3.19.6/demo/wrap-f2py/Bratu2Dmodule.h000066400000000000000000000007251454104047300207700ustar00rootroot00000000000000#define FormInitGuess forminitguess #define FormFunction formfunction #define FormJacobian formjacobian #define FormInitGuess_ forminitguess_ #define FormFunction_ formfunction_ #define FormJacobian_ formjacobian_ #define _FormInitGuess _forminitguess #define _FormFunction _formfunction #define _FormJacobian _formjacobian #define _FormInitGuess_ _forminitguess_ #define _FormFunction_ _formfunction_ #define _FormJacobian_ _formjacobian_ petsc4py-3.19.6/demo/wrap-f2py/makefile000066400000000000000000000012731454104047300176450ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean SCRIPT=run_demo MODULE=Bratu2D .PHONY:build build: ${MODULE}.so .PHONY:run run: build ${PYTHON} ${SCRIPT}.py ${MODULE}.so: ${MODULE}.pyf ${MODULE}.F90 env \ F77="${FC}" F77FLAGS="${FC_FLAGS}" \ F90="${FC}" F90FLAGS="${FC_FLAGS}" \ LDSHARED="${FC_LINKER}" \ ${PYTHON} setup.py -q build_ext --inplace ${RM} -r build ${MODULE}module.c .PHONY:clean clean:: ${RM} ${MODULE}*.so ${RM} *.py[co] ${RM} -r __pycache__ include ${PETSC_DIR}/lib/petsc/conf/variables include ${PETSC_DIR}/lib/petsc/conf/rules MPIEXEC= petsc4py-3.19.6/demo/wrap-f2py/run_demo.py000066400000000000000000000043231454104047300203260ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import Bratu2D as Bratu2D class App(object): def __init__(self, da, lambda_): assert da.getDim() == 2 self.da = da self.lambda_ = lambda_ def formInitGuess(self, snes, X): X.zeroEntries() # just in case da = self.da.fortran vec_X = X.fortran ierr = Bratu2D.FormInitGuess(da, vec_X, self.lambda_) if ierr: raise PETSc.Error(ierr) def formFunction(self, snes, X, F): F.zeroEntries() # just in case da = self.da.fortran vec_X = X.fortran vec_F = F.fortran ierr = Bratu2D.FormFunction(da, vec_X, vec_F, self.lambda_) if ierr: raise PETSc.Error(ierr) def formJacobian(self, snes, X, J, P): P.zeroEntries() # just in case da = self.da.fortran vec_X = X.fortran mat_P = P.fortran ierr = Bratu2D.FormJacobian(da, vec_X, mat_P, self.lambda_) if ierr: raise PETSc.Error(ierr) if J != P: J.assemble() # matrix-free operator return PETSc.Mat.Structure.SAME_NONZERO_PATTERN OptDB = PETSc.Options() N = OptDB.getInt('N', 16) lambda_ = OptDB.getReal('lambda', 6.0) do_plot = OptDB.getBool('plot', False) da = PETSc.DA().create([N, N], stencil_width=1) app = App(da, lambda_) snes = PETSc.SNES().create() F = da.createGlobalVec() snes.setFunction(app.formFunction, F) J = da.createMat() snes.setJacobian(app.formJacobian, J) snes.setFromOptions() X = da.createGlobalVec() app.formInitGuess(snes, X) snes.solve(None, X) U = da.createNaturalVec() da.globalToNatural(X, U) def plot(da, U): comm = da.getComm() scatter, U0 = PETSc.Scatter.toZero(U) scatter.scatter(U, U0, False, PETSc.Scatter.Mode.FORWARD) rank = comm.getRank() if rank == 0: solution = U0[...] solution = solution.reshape(da.sizes, order='f').copy() try: from matplotlib import pyplot pyplot.contourf(solution) pyplot.axis('equal') pyplot.show() except: pass comm.barrier() scatter.destroy() U0.destroy() if do_plot: plot(da, U) U.destroy() X.destroy() F.destroy() J.destroy() da.destroy() snes.destroy() petsc4py-3.19.6/demo/wrap-f2py/setup.py000066400000000000000000000040421454104047300176540ustar00rootroot00000000000000#!/usr/bin/env python #$ python setup.py build_ext --inplace # a bit of monkeypatching ... try: from numpy.distutils.fcompiler import FCompiler def runtime_library_dir_option(self, dir): return self.c_compiler.runtime_library_dir_option(dir) FCompiler.runtime_library_dir_option = \ runtime_library_dir_option except Exception: pass def configuration(parent_package='',top_path=None): INCLUDE_DIRS = [] LIBRARY_DIRS = [] LIBRARIES = [] # PETSc import os PETSC_DIR = os.environ['PETSC_DIR'] PETSC_ARCH = os.environ.get('PETSC_ARCH', '') from os.path import join, isdir if PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH)): INCLUDE_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'include'), join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'lib')] else: if PETSC_ARCH: pass # XXX should warn ... INCLUDE_DIRS += [join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, 'lib')] LIBRARIES += [#'petscts', 'petscsnes', 'petscksp', #'petscdm', 'petscmat', 'petscvec', 'petsc'] # PETSc for Python import petsc4py INCLUDE_DIRS += [petsc4py.get_include()] # Configuration from numpy.distutils.misc_util import Configuration config = Configuration('', parent_package, top_path) config.add_extension('Bratu2D', sources = ['Bratu2D.pyf', 'Bratu2D.F90'], depends = ['Bratu2Dmodule.h'], f2py_options=['--quiet'], define_macros=[('F2PY_REPORT_ON_ARRAY_COPY',1)], include_dirs=INCLUDE_DIRS + [os.curdir], libraries=LIBRARIES, library_dirs=LIBRARY_DIRS, runtime_library_dirs=LIBRARY_DIRS) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) petsc4py-3.19.6/demo/wrap-swig/000077500000000000000000000000001454104047300162335ustar00rootroot00000000000000petsc4py-3.19.6/demo/wrap-swig/Bratu3D.c000066400000000000000000000203631454104047300176470ustar00rootroot00000000000000/* ------------------------------------------------------------------------ Solid Fuel Ignition (SFI) problem. This problem is modeled by the partial differential equation -Laplacian(u) - lambda * exp(u) = 0, 0 < x,y,z < 1, with boundary conditions u = 0 for x = 0, x = 1, y = 0, y = 1, z = 0, z = 1 A finite difference approximation with the usual 7-point stencil is used to discretize the boundary value problem to obtain a nonlinear system of equations. The problem is solved in a 3D rectangular domain, using distributed arrays (DAs) to partition the parallel grid. ------------------------------------------------------------------------- */ #include "Bratu3D.h" PetscErrorCode FormInitGuess(DM da, Vec X, Params *p) { PetscInt i,j,k,Mx,My,Mz,xs,ys,zs,xm,ym,zm; PetscReal lambda,temp1,hx,hy,hz,tempk,tempj; PetscScalar ***x; PetscFunctionBegin; PetscCall(DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My,&Mz,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE)); lambda = p->lambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); temp1 = lambda/(lambda + 1.0); /* Get a pointer to vector data. - For default PETSc vectors, VecGetArray() returns a pointer to the data array. Otherwise, the routine is implementation dependent. - You MUST call VecRestoreArray() when you no longer need access to the array. */ PetscCall(DMDAVecGetArray(da,X,&x)); /* Get local grid boundaries (for 3-dimensional DMDA): - xs, ys, zs: starting grid indices (no ghost points) - xm, ym, zm: widths of local grid (no ghost points) */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute initial guess over the locally owned part of the grid */ for (k=zs; klambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); sc = hx*hy*hz*lambda; hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; PetscCall(DMGetLocalVector(da,&localX)); /* Scatter ghost points to local vector,using the 2-step process DMGlobalToLocalBegin(),DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX)); PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX)); /* Get pointers to vector data. */ PetscCall(DMDAVecGetArray(da,localX,&x)); PetscCall(DMDAVecGetArray(da,F,&f)); /* Get local grid boundaries. */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute function over the locally owned part of the grid. */ for (k=zs; klambda_; hx = 1.0/(PetscReal)(Mx-1); hy = 1.0/(PetscReal)(My-1); hz = 1.0/(PetscReal)(Mz-1); sc = hx*hy*hz*lambda; hxhzdhy = hx*hz/hy; hyhzdhx = hy*hz/hx; hxhydhz = hx*hy/hz; PetscCall(DMGetLocalVector(da,&localX)); /* Scatter ghost points to local vector, using the 2-step process DMGlobalToLocalBegin(), DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ PetscCall(DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX)); PetscCall(DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX)); /* Get pointer to vector data. */ PetscCall(DMDAVecGetArray(da,localX,&x)); /* Get local grid boundaries. */ PetscCall(DMDAGetCorners(da,&xs,&ys,&zs,&xm,&ym,&zm)); /* Compute entries for the locally owned part of the Jacobian. - Currently, all PETSc parallel matrix formats are partitioned by contiguous chunks of rows across the processors. - Each processor needs to insert only elements that it owns locally (but any non-local elements will be sent to the appropriate processor during matrix assembly). - Here, we set all entries for a particular row at once. - We can set matrix entries either using either MatSetValuesLocal() or MatSetValues(), as discussed above. */ for (k=zs; k typedef struct Params { double lambda_; } Params; PetscErrorCode FormInitGuess(DM da, Vec x, Params *p); PetscErrorCode FormFunction(DM da, Vec x, Vec F, Params *p); PetscErrorCode FormJacobian(DM da, Vec x, Mat J, Params *p); #endif/*BRATU3D_H*/ petsc4py-3.19.6/demo/wrap-swig/Bratu3D.i000066400000000000000000000002141454104047300176460ustar00rootroot00000000000000%module Bratu3D %include petsc4py/petsc4py.i %{ #include "Bratu3D.h" %} %include Bratu3D.h /* * Local Variables: * mode: C * End: */ petsc4py-3.19.6/demo/wrap-swig/makefile000066400000000000000000000012501454104047300177310ustar00rootroot00000000000000# -*- makefile -*- MPIEXEC= PYTHON=python -include ../../../../../petscdir.mk -include ${PETSC_DIR}/lib/petsc/conf/variables .PHONY:test test: run clean SCRIPT=run_demo MODULE=Bratu3D .PHONY:build build: ${MODULE}.py _${MODULE}.so .PHONY:run run: build ${MPIEXEC} ${PYTHON} ${SCRIPT}.py ${MODULE}.py _${MODULE}.so: ${MODULE}.i ${MODULE}.c ${MODULE}.h CC=${CC} F90=${FC} LDSHARED='${CLINKER} -shared' \ ${PYTHON} setup.py -q build_ext --inplace ${RM} -r build ${MODULE}_wrap.c .PHONY:clean clean:: ${RM} ${MODULE}.py _${MODULE}*.so ${RM} *.py[co] ${RM} -r __pycache__ include ${PETSC_DIR}/lib/petsc/conf/variables include ${PETSC_DIR}/lib/petsc/conf/rules MPIEXEC= petsc4py-3.19.6/demo/wrap-swig/run_demo.py000066400000000000000000000035731454104047300204250ustar00rootroot00000000000000import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc import Bratu3D as Bratu3D class App(object): def __init__(self, da, lambda_): assert da.getDim() == 3 self.da = da self.params = Bratu3D.Params() self.params.lambda_ = lambda_ def formInitGuess(self, X): X.zeroEntries() # just in case Bratu3D.FormInitGuess(self.da, X, self.params) def formFunction(self, snes, X, F): F.zeroEntries() # just in case Bratu3D.FormFunction(self.da, X, F, self.params) def formJacobian(self, snes, X, J, P): P.zeroEntries() # just in case Bratu3D.FormJacobian(self.da, X, P, self.params) if J != P: J.assemble() # matrix-free operator return PETSc.Mat.Structure.SAME_NONZERO_PATTERN OptDB = PETSc.Options() N = OptDB.getInt('N', 16) lambda_ = OptDB.getReal('lambda', 6.0) do_plot = OptDB.getBool('plot', False) da = PETSc.DMDA().create([N, N, N], stencil_width=1) app = App(da, lambda_) snes = PETSc.SNES().create() F = da.createGlobalVec() snes.setFunction(app.formFunction, F) J = da.createMat() snes.setJacobian(app.formJacobian, J) snes.setFromOptions() X = da.createGlobalVec() app.formInitGuess(X) snes.solve(None, X) U = da.createNaturalVec() da.globalToNatural(X, U) def plot(da, U): scatter, U0 = PETSc.Scatter.toZero(U) scatter.scatter(U, U0, False, PETSc.Scatter.Mode.FORWARD) rank = PETSc.COMM_WORLD.getRank() if rank == 0: solution = U0[...].reshape(da.sizes, order='f').copy() try: from matplotlib import pyplot pyplot.contourf(solution[:, :, N//2]) pyplot.axis('equal') pyplot.show() except: pass PETSc.COMM_WORLD.barrier() scatter.destroy() U0.destroy() if do_plot: plot(da, U) U.destroy() X.destroy() F.destroy() J.destroy() da.destroy() snes.destroy() petsc4py-3.19.6/demo/wrap-swig/setup.py000066400000000000000000000040001454104047300177370ustar00rootroot00000000000000#!/usr/bin/env python #$ python setup.py build_ext --inplace # a bit of monkeypatching ... try: from numpy.distutils.fcompiler import FCompiler from numpy.distutils.unixccompiler import UnixCCompiler try: # Python 2 meth = UnixCCompiler.runtime_library_dir_option.im_func except AttributeError: # Python 3 meth = UnixCCompiler.runtime_library_dir_option FCompiler.runtime_library_dir_option = meth except Exception: pass def configuration(parent_package='',top_path=None): INCLUDE_DIRS = [] LIBRARY_DIRS = [] LIBRARIES = [] # PETSc import os PETSC_DIR = os.environ['PETSC_DIR'] PETSC_ARCH = os.environ.get('PETSC_ARCH', '') from os.path import join, isdir if PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH)): INCLUDE_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'include'), join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, PETSC_ARCH, 'lib')] else: if PETSC_ARCH: pass # XXX should warn ... INCLUDE_DIRS += [join(PETSC_DIR, 'include')] LIBRARY_DIRS += [join(PETSC_DIR, 'lib')] LIBRARIES += [#'petscts', 'petscsnes', 'petscksp', #'petscdm', 'petscmat', 'petscvec', 'petsc'] # PETSc for Python import petsc4py INCLUDE_DIRS += [petsc4py.get_include()] # Configuration from numpy.distutils.misc_util import Configuration config = Configuration('', parent_package, top_path) config.add_extension('_Bratu3D', sources = ['Bratu3D.i', 'Bratu3D.c'], depends = ['Bratu3D.h'], include_dirs=INCLUDE_DIRS + [os.curdir], libraries=LIBRARIES, library_dirs=LIBRARY_DIRS, runtime_library_dirs=LIBRARY_DIRS) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) petsc4py-3.19.6/docs/000077500000000000000000000000001454104047300143175ustar00rootroot00000000000000petsc4py-3.19.6/docs/index.rst000066400000000000000000000035771454104047300161740ustar00rootroot00000000000000================ PETSc 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): petsc4py.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, petsc-dev@mcs.anl.gov Downloads and Development ------------------------- + Issue Tracker: https://gitlab.com/petsc/petsc/-/issues + Git Repository: https://gitlab.com/petsc/petsc.git + The source code is in ``src/binding/petsc4py`` + Previous source releases: https://pypi.org/project/petsc4py/ Citations --------- If PETSc 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 * S. Balay, S. Abhyankar, M. Adams, J. Brown, P. Brune, K. Buschelman, L. Dalcin, A. Dener, V. Eijkhout, W. Gropp, D. Karpeyev, D. Kaushik, M. Knepley, D. May, L. Curfman McInnes, R. Mills, T. Munson, K. Rupp, P. Sanan, B. Smith, S. Zampini, H. Zhang, and H. Zhang, *PETSc Users Manual*, ANL-95/11 - Revision 3.17, 2022. https://petsc.org/release/docs/manual 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). petsc4py-3.19.6/docs/source/000077500000000000000000000000001454104047300156175ustar00rootroot00000000000000petsc4py-3.19.6/docs/source/Makefile000066400000000000000000000011411454104047300172540ustar00rootroot00000000000000# 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) petsc4py-3.19.6/docs/source/abstract.txt000066400000000000000000000015431454104047300201660ustar00rootroot00000000000000.. topic:: Abstract This document describes petsc4py_, a Python_ port to the PETSc_ libraries. PETSc_ (the Portable, Extensible Toolkit for Scientific Computation) is a suite of data structures and routines for the scalable (parallel) solution of scientific applications modeled by partial differential equations. It employs the MPI_ standard for all message-passing communication. This package provides an important subset of PETSc functionalities and uses NumPy_ to efficiently manage input and output of array data. A *good friend* of petsc4py is: * mpi4py_: Python bindings for MPI_, the *Message Passing Interface*. Other projects depends on petsc4py: * slepc4py_: Python bindings for SLEPc_, the *Scalable Library for Eigenvalue Problem Computations*. .. Local Variables: .. mode: rst .. End: petsc4py-3.19.6/docs/source/citing.rst000066400000000000000000000016471454104047300176360ustar00rootroot00000000000000Citations ========= If PETSc 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 * S. Balay, S. Abhyankar, M. Adams, S. Benson, J. Brown, P. Brune, K. Buschelman, E. Constantinescu, L. Dalcin, A. Dener, V. Eijkhout, J. Faibussowitsch, W. Gropp, V. Hapla, T. Isaac, P. Jolivet, D. Karpeyev, D. Kaushik, M. Knepley, F. Kong, S. Kruger, D. May, L. Curfman McInnes, R. Mills, L. Mitchell, T. Munson, J. Roman, K. Rupp, P. Sanan, J Sarich, B. Smith, S. Zampini, H. Zhang, and H. Zhang, J. Zhang, *PETSc/TAO Users Manual*, ANL-21/39 - Revision 3.19, 2023. http://dx.doi.org/10.2172/1968587, https://petsc.org/release/docs/manual/manual.pdf petsc4py-3.19.6/docs/source/conf.py000066400000000000000000000143231454104047300171210ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # PETSc 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, 'petsc4py', '__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'PETSc for Python' copyright = u'2023, Lisandro Dalcin' 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 = 'petsc4py-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', 'petsc4py.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, 'petsc4py', 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, 'petsc4py', project, author, 'petsc4py', 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'] petsc4py-3.19.6/docs/source/index.rst000066400000000000000000000004311454104047300174560ustar00rootroot00000000000000================ PETSc for Python ================ :Author: Lisandro Dalcin :Contact: dalcinl@gmail.com :Web Site: https://gitlab.com/petsc/petsc :Date: |today| .. include:: abstract.txt Contents ======== .. include:: toctree.txt .. include:: links.txt petsc4py-3.19.6/docs/source/install.rst000066400000000000000000000046621454104047300200270ustar00rootroot00000000000000Installation ============ .. _petsc4py_install: Using **pip** ------------- You can use :program:`pip` to install :mod:`petsc4py` and its dependencies (:mod:`mpi4py` is optional but highly recommended):: $ python -m pip install [--user] numpy mpi4py (or pip install [--user] numpy mpi4py) $ python -m pip install [--user] petsc petsc4py (or pip install [--user] petsc petsc4py) Using **setuptools** -------------------- You can also install dependencies manually and then invoke setuptools from the `petsc4py` source directory: $ python setup.py build $ python setup.py install You may use the `--install-lib` argument to the `install` command to alter the `site-packages` directory where the package is to be installed. If you are cross-compiling, and the `numpy` module cannot be loaded on your build host, then before invoking `setup.py`, set `NUMPY_INCLUDE` environment variable to the path that would be returned by `import numpy; numpy.get_include()`: $ export NUMPY_INCLUDE=/usr/lib/pythonX/site-packages/numpy/core/include From PETSc source ----------------- If you already have downloaded PETSc source and have installed the dependencies of `petsc4py`, then to build the `petsc4py` module along with PETSc, add the `--with-petsc4py=1` argument to the configure command when building PETSc: $ ./configure --with-petsc4py=1 $ make $ make install This will install PETSc and the `petsc4py` module into the PETSc directory under the prefix specified to the PETSc configure command. If you wish to make the module importable without having to set the `PYTHONPATH` environment variable, you may add a shortcut to the system-wide `site-packages` directory creating a special `.pth` file with exactly one line of Python code. This can be done by the following command, where the system-wide path is assumed to be `/usr/lib/pythonX/site-packages` (replace `X` with your python version): $ echo \ "import sys, os;" \ "p = os.getenv('PETSC_DIR');" \ "a = os.getenv('PETSC_ARCH') or '';" \ "p = p and os.path.join(p, a, 'lib');" \ "p and (p in sys.path or sys.path.append(p))" \ > /usr/lib/pythonX/site-packages/petsc4py.pth If you are cross-compiling, and `numpy` cannot be loaded on your build host, then pass `--have-numpy=1 --with-numpy-include=PATH`, where `PATH` is the path that would be returned by `import numpy; print(numpy.get_include())`. This will suppress autodetection of the include path on the build host. petsc4py-3.19.6/docs/source/links.txt000066400000000000000000000007031454104047300175000ustar00rootroot00000000000000.. _MPI: http://www.mpi-forum.org .. _MPICH: http://www.mpich.org/ .. _Open MPI: http://www.open-mpi.org .. _PETSc: http://www.mcs.anl.gov/petsc/ .. _SLEPc: http://slepc.upv.es .. _Python: http://www.python.org .. _NumPy: http://www.numpy.org .. _mpi4py: http://github.com/mpi4py/mpi4py .. _petsc4py: http://gitlab.com/petsc/petsc4py .. _slepc4py: http://gitlab.com/slepc/slepc4py petsc4py-3.19.6/docs/source/make.bat000066400000000000000000000014461454104047300172310ustar00rootroot00000000000000@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 petsc4py-3.19.6/docs/source/manual.rst000066400000000000000000000002001454104047300176160ustar00rootroot00000000000000================ PETSc for Python ================ .. include:: abstract.txt .. include:: toctree.txt .. include:: links.txt petsc4py-3.19.6/docs/source/overview.rst000066400000000000000000000103071454104047300202200ustar00rootroot00000000000000Overview ======== PETSc_ is a suite of data structures and routines for the scalable (parallel) solution of scientific applications modeled by partial differential equations. It employs the MPI_ standard for all message-passing communication. PETSc is intended for use in large-scale application projects [petsc-efficient]_, and several ongoing computational science projects are built around the PETSc libraries. With strict attention to component interoperability, PETSc facilitates the integration of independently developed application modules, which often most naturally employ different coding styles and data structures. PETSc is easy to use for beginners [petsc-user-ref]_. Moreover, its careful design allows advanced users to have detailed control over the solution process. PETSc includes an expanding suite of parallel linear and nonlinear equation solvers that are easily used in application codes written in C, C++, and Fortran. PETSc provides many of the mechanisms needed within parallel application codes, such as simple parallel matrix and vector assembly routines that allow the overlap of communication and computation. .. [petsc-user-ref] S. Balay, S. Abhyankar, M. Adams, S. Benson, J. Brown, P. Brune, K. Buschelman, E. Constantinescu, L. Dalcin, A. Dener, V. Eijkhout, J. Faibussowitsch, W. Gropp, V. Hapla, T. Isaac, P. Jolivet, D. Karpeyev, D. Kaushik, M. Knepley, F. Kong, S. Kruger, D. May, L. Curfman McInnes, R. Mills, L. Mitchell, T. Munson, J. Roman, K. Rupp, P. Sanan, J Sarich, B. Smith, S. Zampini, H. Zhang, and H. Zhang, J. Zhang, *PETSc/TAO Users Manual*, ANL-21/39 - Revision 3.19, 2023. http://dx.doi.org/10.2172/1968587, https://petsc.org/release/docs/manual/manual.pdf .. [petsc-efficient] Satish Balay, Victor Eijkhout, William D. Gropp, Lois Curfman McInnes and Barry F. Smith. Efficient Management of Parallelism in Object Oriented Numerical Software Libraries. Modern Software Tools in Scientific Computing. E. Arge, A. M. Bruaset and H. P. Langtangen, editors. 163--202. Birkhauser Press. 1997. .. include:: links.txt Components ---------- PETSc is designed with an object-oriented style. Almost all user-visible types are abstract interfaces with implementations that may be chosen at runtime. Those objects are managed through handles to opaque data structures which are created, accessed and destroyed by calling appropriate library routines. PETSc consists of a variety of components. Each component manipulates a particular family of objects and the operations one would like to perform on these objects. These components provide the functionality required for many parallel solutions of PDEs. :Vec: Provides the vector operations required for setting up and solving large-scale linear and nonlinear problems. Includes easy-to-use parallel scatter and gather operations, as well as special-purpose code for handling ghost points for regular data structures. :Mat: A large suite of data structures and code for the manipulation of parallel sparse matrices. Includes four different parallel matrix data structures, each appropriate for a different class of problems. :PC: A collection of sequential and parallel preconditioners, including (sequential) ILU(k), LU, and (both sequential and parallel) block Jacobi, overlapping additive Schwarz methods and (through BlockSolve95) ILU(0) and ICC(0). :KSP: Parallel implementations of many popular Krylov subspace iterative methods, including GMRES, CG, CGS, Bi-CG-Stab, two variants of TFQMR, CR, and LSQR. All are coded so that they are immediately usable with any preconditioners and any matrix data structures, including matrix-free methods. :SNES: Data-structure-neutral implementations of Newton-like methods for nonlinear systems. Includes both line search and trust region techniques with a single interface. Employs by default the above data structures and linear solvers. Users can set custom monitoring routines, convergence criteria, etc. :TS: Code for the time evolution of solutions of PDEs. In addition, provides pseudo-transient continuation techniques for computing steady-state solutions. petsc4py-3.19.6/docs/source/requirements.txt000066400000000000000000000001051454104047300210770ustar00rootroot00000000000000sphinx==1.8.6 docutils==0.17.1 epydoc; python_version <= "2.7" numpy petsc4py-3.19.6/docs/source/toctree.txt000066400000000000000000000001651454104047300200270ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 overview install tutorial citing .. Local Variables: .. mode: rst .. End: petsc4py-3.19.6/docs/source/tutorial.rst000066400000000000000000000001031454104047300202060ustar00rootroot00000000000000Tutorial ======== XXX To be written ... Any contribution welcome! petsc4py-3.19.6/setup.cfg000066400000000000000000000002511454104047300152060ustar00rootroot00000000000000[config] 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 petsc4py-3.19.6/setup.py000077500000000000000000000176551454104047300151220ustar00rootroot00000000000000#!/usr/bin/env python # 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 < (2, 6) or (3, 0) <= pyver < (3, 2): raise RuntimeError("Python version 2.6, 2.7 or >= 3.2 required") if pyver == (2, 6) or pyver == (3, 2): sys.stderr.write( "WARNING: Python %d.%d is not supported.\n" % pyver) PNAME = 'PETSc' EMAIL = 'petsc-maint@mcs.anl.gov' PLIST = [PNAME] # -------------------------------------------------------------------- # 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 = """ License :: OSI Approved :: BSD License 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 :: 2 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(): 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 setup_args['install_requires'] = ['numpy'] 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['install_requires'] += [package] if F('{pyname}') != 'petsc4py': package = requires('petsc4py', x, y, release) 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() # -------------------------------------------------------------------- petsc4py-3.19.6/src/000077500000000000000000000000001454104047300141565ustar00rootroot00000000000000petsc4py-3.19.6/src/cython.h000066400000000000000000000033231454104047300156340ustar00rootroot00000000000000static void *Cython_ImportFunction(PyObject *module, const char *funcname, const char *signature) { PyObject *capi = NULL, *capsule = NULL; void *p = NULL; capi = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); if (!capi) goto bad; capsule = PyDict_GetItemString(capi, (char *)funcname); if (!capsule) { PyErr_Format(PyExc_ImportError, "%s does not export expected C function %s", PyModule_GetName(module), funcname); goto bad; } #if PY_VERSION_HEX < 0x03020000 if (PyCObject_Check(capsule)) { const char *desc, *s1, *s2; desc = (const char *)PyCObject_GetDesc(capsule); if (!desc) goto bad; s1 = desc; s2 = signature; while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } if (*s1 != *s2) { PyErr_Format(PyExc_TypeError, "C function %s.%s has wrong signature " "(expected %s, got %s)", PyModule_GetName(module), funcname, signature, desc); goto bad; } p = PyCObject_AsVoidPtr(capsule); } #endif #if PY_VERSION_HEX >= 0x02070000 if (PyCapsule_CheckExact(capsule)) { if (!PyCapsule_IsValid(capsule, signature)) { const char *desc = PyCapsule_GetName(capsule); PyErr_Format(PyExc_TypeError, "C function %s.%s has wrong signature " "(expected %s, got %s)", PyModule_GetName(module), funcname, signature, desc); goto bad; } p = PyCapsule_GetPointer(capsule, signature); } #endif Py_DECREF(capi); return p; bad: Py_XDECREF(capi); return NULL; } /* Local variables: c-basic-offset: 2 indent-tabs-mode: nil End: */ petsc4py-3.19.6/src/lib-petsc/000077500000000000000000000000001454104047300160405ustar00rootroot00000000000000petsc4py-3.19.6/src/lib-petsc/compat.h000066400000000000000000000005761454104047300175040ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_H #define PETSC4PY_COMPAT_H #include #include "compat/mpi.h" #include "compat/hdf5.h" #include "compat/mumps.h" #include "compat/hypre.h" #include "compat/hpddm.h" #include "compat/viennacl.h" #include "compat/cuda.h" #include "compat/hip.h" #include "compat/tao.h" #include "compat/h2opus.h" #include "compat/spai.h" #endif/*PETSC4PY_COMPAT_H*/ petsc4py-3.19.6/src/lib-petsc/compat/000077500000000000000000000000001454104047300173235ustar00rootroot00000000000000petsc4py-3.19.6/src/lib-petsc/compat/cuda.h000066400000000000000000000020351454104047300204100ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_CUDA_H #define PETSC4PY_COMPAT_CUDA_H #if !defined(PETSC_HAVE_CUDA) #define PetscCUDAError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires CUDA",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode MatDenseCUDAGetArrayRead(Mat A, const PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatDenseCUDARestoreArrayRead(Mat A, const PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatDenseCUDAGetArrayWrite(Mat A, PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatDenseCUDARestoreArrayWrite(Mat A, PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatDenseCUDAGetArray(Mat A, PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatDenseCUDARestoreArray(Mat A, PetscScalar **gpuarray) {PetscCUDAError;} PetscErrorCode MatCreateDenseCUDA(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscScalar gpuarray[], Mat *A) {PetscCUDAError;} #undef PetscCUDAError #endif #endif/*PETSC4PY_COMPAT_CUDA_H*/ petsc4py-3.19.6/src/lib-petsc/compat/h2opus.h000066400000000000000000000017571454104047300207260ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_H2OPUS_H #define PETSC4PY_COMPAT_H2OPUS_H #if !defined(PETSC_HAVE_H2OPUS) #define PetscMatH2OPUSError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires H2OPUS",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode MatCreateH2OpusFromMat(PETSC_UNUSED Mat a,PETSC_UNUSED PetscInt b,PETSC_UNUSED const PetscReal c[],PETSC_UNUSED PetscBool d,PETSC_UNUSED PetscReal e,PETSC_UNUSED PetscInt f,PETSC_UNUSED PetscInt g,PETSC_UNUSED PetscInt h,PETSC_UNUSED PetscReal i,PETSC_UNUSED Mat* l) {PetscMatH2OPUSError;} PetscErrorCode MatH2OpusOrthogonalize(PETSC_UNUSED Mat a) {PetscMatH2OPUSError;} PetscErrorCode MatH2OpusCompress(PETSC_UNUSED Mat a,PETSC_UNUSED PetscReal b) {PetscMatH2OPUSError;} PetscErrorCode MatH2OpusLowRankUpdate(PETSC_UNUSED Mat a,PETSC_UNUSED Mat b,PETSC_UNUSED Mat c,PETSC_UNUSED PetscScalar d) {PetscMatH2OPUSError;} #undef PetscMatH2OPUSError #endif #endif/*PETSC4PY_COMPAT_H2OPUS_H*/ petsc4py-3.19.6/src/lib-petsc/compat/hdf5.h000066400000000000000000000024231454104047300203230ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_HDF5_H #define PETSC4PY_COMPAT_HDF5_H #include #if !defined(PETSC_HAVE_HDF5) #define PetscViewerHDF5Error do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires HDF5",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode PetscViewerHDF5PushGroup(PETSC_UNUSED PetscViewer vw,PETSC_UNUSED const char g[]){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5PopGroup(PETSC_UNUSED PetscViewer vw){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5GetGroup(PETSC_UNUSED PetscViewer vw, PETSC_UNUSED const char p[], PETSC_UNUSED char *g[]){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5PushTimestepping(PETSC_UNUSED PetscViewer vw){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5PopTimestepping(PETSC_UNUSED PetscViewer vw){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5SetTimestep(PETSC_UNUSED PetscViewer vw, PETSC_UNUSED PetscInt n){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5GetTimestep(PETSC_UNUSED PetscViewer vw, PETSC_UNUSED PetscInt*n){PetscViewerHDF5Error;} PetscErrorCode PetscViewerHDF5IncrementTimestep(PETSC_UNUSED PetscViewer vw){PetscViewerHDF5Error;} #undef PetscViewerHDF5Error #endif #endif/*PETSC4PY_COMPAT_HDF5_H*/ petsc4py-3.19.6/src/lib-petsc/compat/hip.h000066400000000000000000000005321454104047300202540ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_HIP_H #define PETSC4PY_COMPAT_HIP_H #if !defined(PETSC_HAVE_HIP) #define PetscHIPError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires HIP",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) #undef PetscHIPError #endif #endif/*PETSC4PY_COMPAT_HIP_H*/ petsc4py-3.19.6/src/lib-petsc/compat/hpddm.h000066400000000000000000000025071454104047300205740ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_HPDDM_H #define PETSC4PY_COMPAT_HPDDM_H #if !defined(PETSC_HAVE_HPDDM) || !defined(PETSC_HAVE_DYNAMIC_LIBRARIES) || !defined(PETSC_USE_SHARED_LIBRARIES) #define PetscPCHPDDMError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires HPDDM",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode PCHPDDMSetAuxiliaryMat(PETSC_UNUSED PC pc,PETSC_UNUSED IS is,PETSC_UNUSED Mat aux,PETSC_UNUSED PetscErrorCode (*setup)(Mat,PetscReal,Vec,Vec,PetscReal,IS,void*),PETSC_UNUSED void* ctx){PetscPCHPDDMError;} PetscErrorCode PCHPDDMSetRHSMat(PETSC_UNUSED PC pc,PETSC_UNUSED Mat B){PetscPCHPDDMError;} PetscErrorCode PCHPDDMHasNeumannMat(PETSC_UNUSED PC pc,PETSC_UNUSED PetscBool has){PetscPCHPDDMError;} PetscErrorCode PCHPDDMSetCoarseCorrectionType(PETSC_UNUSED PC pc,PETSC_UNUSED PCHPDDMCoarseCorrectionType type){PetscPCHPDDMError;} PetscErrorCode PCHPDDMGetCoarseCorrectionType(PETSC_UNUSED PC pc,PETSC_UNUSED PCHPDDMCoarseCorrectionType *type){PetscPCHPDDMError;} PetscErrorCode PCHPDDMGetSTShareSubKSP(PETSC_UNUSED PC pc,PETSC_UNUSED PetscBool *share){PetscPCHPDDMError;} PetscErrorCode PCHPDDMSetDeflationMat(PETSC_UNUSED PC pc,PETSC_UNUSED IS is,PETSC_UNUSED Mat U){PetscPCHPDDMError;} #undef PetscPCHPDDMError #endif #endif/*PETSC4PY_COMPAT_HPDDM_H*/ petsc4py-3.19.6/src/lib-petsc/compat/hypre.h000066400000000000000000000026371454104047300206330ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_HYPRE_H #define PETSC4PY_COMPAT_HYPRE_H #if !defined(PETSC_HAVE_HYPRE) #define PetscPCHYPREError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires HYPRE",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode PCHYPREGetType(PETSC_UNUSED PC pc,PETSC_UNUSED const char *name[]){PetscPCHYPREError;} PetscErrorCode PCHYPRESetType(PETSC_UNUSED PC pc,PETSC_UNUSED const char name[]){PetscPCHYPREError;} PetscErrorCode PCHYPRESetDiscreteCurl(PETSC_UNUSED PC pc,PETSC_UNUSED Mat C){PetscPCHYPREError;} PetscErrorCode PCHYPRESetDiscreteGradient(PETSC_UNUSED PC pc,PETSC_UNUSED Mat G){PetscPCHYPREError;} PetscErrorCode PCHYPRESetAlphaPoissonMatrix(PETSC_UNUSED PC pc,PETSC_UNUSED Mat A){PetscPCHYPREError;} PetscErrorCode PCHYPRESetBetaPoissonMatrix(PETSC_UNUSED PC pc,PETSC_UNUSED Mat B){PetscPCHYPREError;} PetscErrorCode PCHYPRESetInterpolations(PETSC_UNUSED PC pc,PETSC_UNUSED PetscInt dim,PETSC_UNUSED Mat RT_Pi_Full,PETSC_UNUSED Mat RT_Pi[],PETSC_UNUSED Mat ND_Pi_Full,PETSC_UNUSED Mat ND_Pi[]){PetscPCHYPREError;} PetscErrorCode PCHYPRESetEdgeConstantVectors(PETSC_UNUSED PC pc,PETSC_UNUSED Vec ozz,PETSC_UNUSED Vec zoz,PETSC_UNUSED Vec zzo){PetscPCHYPREError;} PetscErrorCode PCHYPREAMSSetInteriorNodes(PETSC_UNUSED PC pc,PETSC_UNUSED Vec interior){PetscPCHYPREError;} #undef PetscPCHYPREError #endif #endif/*PETSC4PY_COMPAT_HYPRE_H*/ petsc4py-3.19.6/src/lib-petsc/compat/mpi.h000066400000000000000000000111361454104047300202630ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_MPI_H #define PETSC4PY_COMPAT_MPI_H #if defined(OPEN_MPI) /* * The hackery below redefines the actual calls to 'MPI_Init()' and * 'MPI_Init_thread()' in order to preload the main MPI dynamic * library with appropriate flags to 'dlopen()' ensuring global * availability of library symbols. */ #if !defined(OPENMPI_DLOPEN_LIBMPI) && defined(OMPI_MAJOR_VERSION) #if OMPI_MAJOR_VERSION >= 3 && OMPI_MAJOR_VERSION < 10 #define OPENMPI_DLOPEN_LIBMPI 0 #endif #endif #ifndef OPENMPI_DLOPEN_LIBMPI #define OPENMPI_DLOPEN_LIBMPI 1 #endif #if OPENMPI_DLOPEN_LIBMPI #if HAVE_DLOPEN #if HAVE_DLFCN_H #include #else #if defined(__linux__) #define RTLD_LAZY 0x00001 #define RTLD_NOW 0x00002 #define RTLD_LOCAL 0x00000 #define RTLD_GLOBAL 0x00100 #define RTLD_NOLOAD 0x00004 #define RTLD_NODELETE 0x01000 #define RTLD_DEEPBIND 0x00008 #elif defined(__APPLE__) #define RTLD_LAZY 0x1 #define RTLD_NOW 0x2 #define RTLD_LOCAL 0x4 #define RTLD_GLOBAL 0x8 #define RTLD_NOLOAD 0x10 #define RTLD_NODELETE 0x80 #define RTLD_FIRST 0x100 #elif defined(__CYGWIN__) #define RTLD_LAZY 1 #define RTLD_NOW 2 #define RTLD_LOCAL 0 #define RTLD_GLOBAL 4 #endif #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern void *dlopen(const char *, int); extern void *dlsym(void *, const char *); extern int dlclose(void *); extern char *dlerror(void); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif #ifndef RTLD_LAZY #define RTLD_LAZY 1 #endif #ifndef RTLD_NOW #define RTLD_NOW RTLD_LAZY #endif #ifndef RTLD_LOCAL #define RTLD_LOCAL 0 #endif #ifndef RTLD_GLOBAL #define RTLD_GLOBAL RTLD_LOCAL #endif /* static void * my_dlopen(const char *name, int mode) { void *handle; static int called = 0; if (!called) { called = 1; #if HAVE_DLFCN_H printf("HAVE_DLFCN_H: yes\n"); #else printf("HAVE_DLFCN_H: no\n"); #endif printf("\n"); printf("RTLD_LAZY: 0x%X\n", RTLD_LAZY); printf("RTLD_NOW: 0x%X\n", RTLD_NOW); printf("RTLD_LOCAL: 0x%X\n", RTLD_LOCAL); printf("RTLD_GLOBAL: 0x%X\n", RTLD_GLOBAL); #ifdef RTLD_NOLOAD printf("RTLD_NOLOAD: 0x%X\n", RTLD_NOLOAD); #endif printf("\n"); } handle = dlopen(name, mode); printf("dlopen(\"%s\",0x%X) -> %p\n", name, mode, handle); printf("dlerror() -> %s\n\n", dlerror()); return handle; } #define dlopen my_dlopen */ static void OPENMPI_dlopen_libmpi(void) { void *handle = 0; int mode = RTLD_NOW | RTLD_GLOBAL; #if defined(__APPLE__) /* macOS */ #ifdef RTLD_NOLOAD mode |= RTLD_NOLOAD; #endif #if defined(OMPI_MAJOR_VERSION) #if OMPI_MAJOR_VERSION == 3 if (!handle) handle = dlopen("libmpi.40.dylib", mode); #elif OMPI_MAJOR_VERSION == 2 if (!handle) handle = dlopen("libmpi.20.dylib", mode); #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 10 if (!handle) handle = dlopen("libmpi.12.dylib", mode); #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 6 if (!handle) handle = dlopen("libmpi.1.dylib", mode); #elif OMPI_MAJOR_VERSION == 1 if (!handle) handle = dlopen("libmpi.0.dylib", mode); #endif #endif if (!handle) handle = dlopen("libmpi.dylib", mode); #else /* GNU/Linux and others */ #ifdef RTLD_NOLOAD mode |= RTLD_NOLOAD; #endif #if defined(OMPI_MAJOR_VERSION) #if OMPI_MAJOR_VERSION >= 10 /* IBM Spectrum MPI */ if (!handle) handle = dlopen("libmpi_ibm.so.2", mode); if (!handle) handle = dlopen("libmpi_ibm.so.1", mode); if (!handle) handle = dlopen("libmpi_ibm.so", mode); #elif OMPI_MAJOR_VERSION == 3 if (!handle) handle = dlopen("libmpi.so.40", mode); #elif OMPI_MAJOR_VERSION == 2 if (!handle) handle = dlopen("libmpi.so.20", mode); #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 10 if (!handle) handle = dlopen("libmpi.so.12", mode); #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 6 if (!handle) handle = dlopen("libmpi.so.1", mode); #elif OMPI_MAJOR_VERSION == 1 if (!handle) handle = dlopen("libmpi.so.0", mode); #endif #endif if (!handle) handle = dlopen("libmpi.so", mode); #endif } static PetscErrorCode PetscInitialize_OpenMPI(int *argc,char ***args, const char file[], const char help[]) { OPENMPI_dlopen_libmpi(); return PetscInitialize(argc,args,file,help); } #undef PetscInitialize #define PetscInitialize PetscInitialize_OpenMPI #endif /* HAVE_DLOPEN */ #endif /* OPENMPI_DLOPEN_LIBMPI */ #endif /* OPEN_MPI */ #endif/*PETSC4PY_COMPAT_MPI_H*/ petsc4py-3.19.6/src/lib-petsc/compat/mumps.h000066400000000000000000000025761454104047300206470ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_MUMPS_H #define PETSC4PY_COMPAT_MUMPS_H #include #if !defined(PETSC_HAVE_MUMPS) #define PetscMUMPSError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires MUMPS",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode MatMumpsSetIcntl(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscInt ival){PetscMUMPSError;} PetscErrorCode MatMumpsGetIcntl(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscInt *ival){PetscMUMPSError;} PetscErrorCode MatMumpsSetCntl(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscReal val){PetscMUMPSError;} PetscErrorCode MatMumpsGetCntl(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscReal *val){PetscMUMPSError;} PetscErrorCode MatMumpsGetInfo(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscInt *ival){PetscMUMPSError;} PetscErrorCode MatMumpsGetInfog(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscInt *ival){PetscMUMPSError;} PetscErrorCode MatMumpsGetRinfo(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscReal *val){PetscMUMPSError;} PetscErrorCode MatMumpsGetRinfog(PETSC_UNUSED Mat F,PETSC_UNUSED PetscInt icntl,PETSC_UNUSED PetscReal *val){PetscMUMPSError;} #undef PetscMUMPSError #endif #endif/*PETSC4PY_COMPAT_MUMPS_H*/ petsc4py-3.19.6/src/lib-petsc/compat/spai.h000066400000000000000000000021051454104047300204260ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_SPAI_H #define PETSC4PY_COMPAT_SPAI_H #if !defined(PETSC_HAVE_SPAI) #define PetscSPAIError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires SPAI",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode PCSPAISetEpsilon(PETSC_UNUSED PC a,PETSC_UNUSED PetscReal b) {PetscSPAIError;} PetscErrorCode PCSPAISetNBSteps(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetMax(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetMaxNew(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetBlockSize(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetCacheSize(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetVerbose(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} PetscErrorCode PCSPAISetSp(PETSC_UNUSED PC a,PETSC_UNUSED PetscInt b) {PetscSPAIError;} #undef PetscSPAIError #endif #endif/*PETSC4PY_COMPAT_SPAI_H*/ petsc4py-3.19.6/src/lib-petsc/compat/tao.h000066400000000000000000000030321454104047300202550ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_TAO_H #define PETSC4PY_COMPAT_TAO_H #if defined(PETSC_USE_COMPLEX) #define PetscTaoError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() not supported with complex scalars",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode TaoLMVMSetH0(PETSC_UNUSED Tao tao,PETSC_UNUSED Mat mat) {PetscTaoError;} PetscErrorCode TaoLMVMGetH0(PETSC_UNUSED Tao tao,PETSC_UNUSED Mat *mat) {PetscTaoError;} PetscErrorCode TaoLMVMGetH0KSP(PETSC_UNUSED Tao tao,PETSC_UNUSED KSP *ksp) {PetscTaoError;} PetscErrorCode TaoBRGNGetSubsolver(PETSC_UNUSED Tao tao,PETSC_UNUSED Tao *subsolver) {PetscTaoError;} PetscErrorCode TaoBRGNSetRegularizerObjectiveAndGradientRoutine(PETSC_UNUSED Tao tao,PETSC_UNUSED PetscErrorCode (*func)(Tao,Vec,PetscReal*,Vec,void*),PETSC_UNUSED void *ctx) {PetscTaoError;} PetscErrorCode TaoBRGNSetRegularizerHessianRoutine(PETSC_UNUSED Tao tao,PETSC_UNUSED Mat H,PETSC_UNUSED PetscErrorCode (*func)(Tao,Vec,Mat,void*),PETSC_UNUSED void *ctx) {PetscTaoError;} PetscErrorCode TaoBRGNSetRegularizerWeight(PETSC_UNUSED Tao tao,PETSC_UNUSED PetscReal weight) {PetscTaoError;} PetscErrorCode TaoBRGNSetL1SmoothEpsilon(PETSC_UNUSED Tao tao,PETSC_UNUSED PetscReal epsilon) {PetscTaoError;} PetscErrorCode TaoBRGNSetDictionaryMatrix(PETSC_UNUSED Tao tao,PETSC_UNUSED Mat D) {PetscTaoError;} PetscErrorCode TaoBRGNGetDampingVector(PETSC_UNUSED Tao tao,PETSC_UNUSED Vec *d) {PetscTaoError;} #undef PetscTaoError #endif/*PETSC_USE_COMPLEX*/ #endif/*PETSC4PY_COMPAT_TAO_H*/ petsc4py-3.19.6/src/lib-petsc/compat/viennacl.h000066400000000000000000000016671454104047300213050ustar00rootroot00000000000000#ifndef PETSC4PY_COMPAT_VIENNACL_H #define PETSC4PY_COMPAT_VIENNACL_H #if !defined(PETSC_HAVE_VIENNACL) #define PetscViennaCLError do { \ PetscFunctionBegin; \ SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"%s() requires ViennaCL",PETSC_FUNCTION_NAME); \ PetscFunctionReturn(PETSC_ERR_SUP);} while (0) PetscErrorCode VecCreateSeqViennaCLWithArrays(MPI_Comm comm,PetscInt bs,PetscInt n,PetscScalar cpuarray[],PetscScalar* viennaclvec,Vec *V) {PetscViennaCLError;} PetscErrorCode VecCreateMPIViennaCLWithArrays(MPI_Comm comm,PetscInt bs,PetscInt n,PetscInt N,PetscScalar cpuarray[],PetscScalar *viennaclvec,Vec *vv) {PetscViennaCLError;} #undef PetscViennaCLError # else PetscErrorCode VecCreateSeqViennaCLWithArrays(MPI_Comm,PetscInt,PetscInt,PetscScalar[],PetscScalar[],Vec*); PetscErrorCode VecCreateMPIViennaCLWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscScalar[],Vec*); #endif #endif/*PETSC4PY_COMPAT_VIENNACL_H*/ petsc4py-3.19.6/src/lib-petsc/custom.h000066400000000000000000000553031454104047300175310ustar00rootroot00000000000000#ifndef PETSC4PY_CUSTOM_H #define PETSC4PY_CUSTOM_H #include #include #include #include #include #include #include #include #include /* ---------------------------------------------------------------- */ #ifndef PETSC_ERR_PYTHON #define PETSC_ERR_PYTHON ((PetscErrorCode)(-1)) #endif #define PetscERROR(comm,FUNCT,n,t,msg,arg) \ PetscError(comm,__LINE__,FUNCT,__FILE__,n,t,msg,arg) /* ---------------------------------------------------------------- */ typedef PetscErrorCode (*PetscErrorHandlerFunction) (MPI_Comm,int,const char*,const char*, PetscErrorCode,PetscErrorType,const char*,void*); #define PetscTBEH PetscTraceBackErrorHandler /* ---------------------------------------------------------------- */ PETSC_EXTERN PetscErrorCode (*PetscPythonMonitorSet_C)(PetscObject,const char*); /* ---------------------------------------------------------------- */ #if !defined(PETSC_USE_LOG) static PetscStageLog petsc_stageLog = NULL; #endif #define PetscCLASSID(stageLog,index) \ ((stageLog)->classLog->classInfo[(index)].classid) static PetscErrorCode PetscLogStageFindId(const char name[], PetscLogStage *stageid) { int s; PetscStageLog stageLog = 0; PetscBool match = PETSC_FALSE; PetscFunctionBegin; PetscValidCharPointer(name,1); PetscValidIntPointer(stageid,2); *stageid = -1; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ for (s = 0; s < stageLog->numStages; s++) { const char *sname = stageLog->stageInfo[s].name; PetscCall(PetscStrcasecmp(sname, name, &match)); if (match) { *stageid = s; break; } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscLogClassFindId(const char name[], PetscClassId *classid) { int c; PetscStageLog stageLog = 0; PetscBool match = PETSC_FALSE; PetscFunctionBegin; PetscValidCharPointer(name,1); PetscValidIntPointer(classid,2); *classid = -1; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ for (c = 0; c < stageLog->classLog->numClasses; c++) { const char *cname = stageLog->classLog->classInfo[c].name; PetscClassId id = PetscCLASSID(stageLog,c); PetscCall(PetscStrcasecmp(cname, name, &match)); if (match) { *classid = id; break; } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscLogEventFindId(const char name[], PetscLogEvent *eventid) { int e; PetscStageLog stageLog = 0; PetscBool match = PETSC_FALSE; PetscFunctionBegin; PetscValidCharPointer(name,1); PetscValidIntPointer(eventid,2); *eventid = -1; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ for (e = 0; e < stageLog->eventLog->numEvents; e++) { const char *ename = stageLog->eventLog->eventInfo[e].name; PetscCall(PetscStrcasecmp(ename, name, &match)); if (match) { *eventid = e; break; } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscLogStageFindName(PetscLogStage stageid, const char *name[]) { PetscStageLog stageLog = 0; PetscFunctionBegin; PetscValidPointer(name,3); *name = 0; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ if (stageid >=0 && stageid < stageLog->numStages) { *name = stageLog->stageInfo[stageid].name; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscLogClassFindName(PetscClassId classid, const char *name[]) { int c; PetscStageLog stageLog = 0; PetscFunctionBegin; PetscValidPointer(name,3); *name = 0; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ for (c = 0; c < stageLog->classLog->numClasses; c++) { if (classid == PetscCLASSID(stageLog,c)) { *name = stageLog->classLog->classInfo[c].name; break; } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscLogEventFindName(PetscLogEvent eventid, const char *name[]) { PetscStageLog stageLog = 0; PetscFunctionBegin; PetscValidPointer(name,3); *name = 0; if (!(stageLog=petsc_stageLog)) PetscFunctionReturn(PETSC_SUCCESS); /* logging is off ? */ if (eventid >=0 && eventid < stageLog->eventLog->numEvents) { *name = stageLog->eventLog->eventInfo[eventid].name; } PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode PetscObjectComposedDataGetIntPy(PetscObject o, PetscInt id, PetscInt *v, PetscBool *exist) { PetscFunctionBegin; PetscCall(PetscObjectComposedDataGetInt(o,id,*v,*exist)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscObjectComposedDataSetIntPy(PetscObject o, PetscInt id, PetscInt v) { PetscFunctionBegin; PetscCall(PetscObjectComposedDataSetInt(o,id,v)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode PetscObjectComposedDataRegisterPy(PetscInt *id) { PetscFunctionBegin; PetscCall(PetscObjectComposedDataRegister(id)); PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ /* The object is not used so far. I expect PETSc will sooner or later support a different device context for each object */ static PetscErrorCode PetscObjectGetDeviceId(PetscObject o, PetscInt *id) { #if defined(PETSC_HAVE_DEVICE) PetscDeviceContext dctx; PetscDevice device; #endif PetscFunctionBegin; PetscValidHeader(o,1); #if defined(PETSC_HAVE_DEVICE) PetscCall(PetscDeviceContextGetCurrentContext(&dctx)); PetscCall(PetscDeviceContextGetDevice(dctx,&device)); PetscCall(PetscDeviceGetDeviceId(device,id)); #else *id = 0; #endif PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode VecGetCurrentMemType(Vec v, PetscMemType *m) { PetscBool bound; PetscFunctionBegin; PetscValidHeaderSpecific(v,VEC_CLASSID,1); PetscValidPointer(m,2); *m = PETSC_MEMTYPE_HOST; PetscCall(VecBoundToCPU(v,&bound)); if (!bound) { VecType rtype; char *iscuda = NULL, *iship = NULL, *iskok = NULL; PetscCall(VecGetRootType_Private(v,&rtype)); PetscCall(PetscStrstr(rtype,"cuda",&iscuda)); PetscCall(PetscStrstr(rtype,"hip",&iship)); PetscCall(PetscStrstr(rtype,"kokkos",&iskok)); if (iscuda) *m = PETSC_MEMTYPE_CUDA; else if (iship) *m = PETSC_MEMTYPE_HIP; else if (iskok) *m = PETSC_MEMTYPE_KOKKOS; } PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode MatIsPreallocated(Mat A,PetscBool *flag) { PetscFunctionBegin; PetscValidHeaderSpecific(A,MAT_CLASSID,1); PetscValidPointer(flag,2); *flag = A->preallocated; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode MatHasPreallocationAIJ(Mat A,PetscBool *aij,PetscBool *baij,PetscBool *sbaij,PetscBool *is) { void (*f)(void) = 0; PetscFunctionBegin; PetscValidHeaderSpecific(A,MAT_CLASSID,1); PetscValidType(A,1); PetscValidPointer(aij,2); PetscValidPointer(baij,3); PetscValidPointer(sbaij,4); PetscValidPointer(is,5); *aij = *baij = *sbaij = *is = PETSC_FALSE; if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatMPIAIJSetPreallocation_C",&f)); if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatSeqAIJSetPreallocation_C",&f)); if (f) {*aij = PETSC_TRUE; goto done;}; if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatMPIBAIJSetPreallocation_C",&f)); if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatSeqBAIJSetPreallocation_C",&f)); if (f) {*baij = PETSC_TRUE; goto done;}; if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatMPISBAIJSetPreallocation_C",&f)); if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatSeqSBAIJSetPreallocation_C",&f)); if (f) {*sbaij = PETSC_TRUE; goto done;}; if (!f) PetscCall(PetscObjectQueryFunction((PetscObject)A,"MatISSetPreallocation_C",&f)); if (f) {*is = PETSC_TRUE; goto done;}; done: PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m) { PetscBool bound; PetscFunctionBegin; PetscValidHeaderSpecific(A,MAT_CLASSID,1); PetscValidPointer(m,2); *m = PETSC_MEMTYPE_HOST; PetscCall(MatBoundToCPU(A,&bound)); if (!bound) { VecType rtype; char *iscuda = NULL, *iship = NULL, *iskok = NULL; PetscCall(MatGetRootType_Private(A,&rtype)); PetscCall(PetscStrstr(rtype,"cuda",&iscuda)); PetscCall(PetscStrstr(rtype,"hip",&iship)); PetscCall(PetscStrstr(rtype,"kokkos",&iskok)); if (iscuda) *m = PETSC_MEMTYPE_CUDA; else if (iship) *m = PETSC_MEMTYPE_HIP; else if (iskok) *m = PETSC_MEMTYPE_KOKKOS; } PetscFunctionReturn(PETSC_SUCCESS); } #ifndef MatNullSpaceFunction typedef PetscErrorCode MatNullSpaceFunction(MatNullSpace,Vec,void*); #endif /* ---------------------------------------------------------------- */ static PetscErrorCode MatFactorInfoDefaults(PetscBool incomplete,PetscBool cholesky,MatFactorInfo *info) { PetscFunctionBegin; PetscValidPointer(info,2); PetscCall(MatFactorInfoInitialize(info)); if (incomplete) { info->levels = (PetscReal)0; info->diagonal_fill = (PetscReal)0; info->fill = (PetscReal)1.0; info->usedt = (PetscReal)0; info->dt = (PetscReal)PETSC_DEFAULT; info->dtcount = (PetscReal)PETSC_DEFAULT; info->dtcol = (PetscReal)PETSC_DEFAULT; info->zeropivot = (PetscReal)100.0*PETSC_MACHINE_EPSILON; info->pivotinblocks = (PetscReal)1; } else { info->fill = (PetscReal)5.0; info->dtcol = (PetscReal)1.e-6; info->zeropivot = (PetscReal)100.0*PETSC_MACHINE_EPSILON; info->pivotinblocks = (PetscReal)1; } if (incomplete) { if (cholesky) info->shifttype = (PetscReal)MAT_SHIFT_POSITIVE_DEFINITE; else info->shifttype = (PetscReal)MAT_SHIFT_NONZERO; info->shiftamount = (PetscReal)100.0*PETSC_MACHINE_EPSILON; } else { info->shifttype = (PetscReal)MAT_SHIFT_NONE; info->shiftamount = (PetscReal)0.0; } PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode KSPSetIterationNumber(KSP ksp, PetscInt its) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); PetscCheck(its >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"iteration number must be nonnegative"); ksp->its = its; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPSetResidualNorm(KSP ksp, PetscReal rnorm) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); PetscCheck(rnorm >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"residual norm must be nonnegative"); ksp->rnorm = rnorm; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPConvergenceTestCall(KSP ksp, PetscInt its, PetscReal rnorm, KSPConvergedReason *reason) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); PetscValidPointer(reason,4); PetscCheck(its >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"iteration number must be nonnegative"); PetscCheck(rnorm >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"residual norm must be nonnegative"); PetscCall((*ksp->converged)(ksp,its,rnorm,reason,ksp->cnvP)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPSetConvergedReason(KSP ksp, KSPConvergedReason reason) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); ksp->reason = reason; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPConverged(KSP ksp,PetscInt iter,PetscReal rnorm,KSPConvergedReason *reason) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); if (reason) PetscValidPointer(reason,2); if (!iter) ksp->rnorm0 = rnorm; if (!iter) { ksp->reason = KSP_CONVERGED_ITERATING; ksp->ttol = PetscMax(rnorm*ksp->rtol,ksp->abstol); } if (ksp->converged) { PetscCall(ksp->converged(ksp,iter,rnorm,&ksp->reason,ksp->cnvP)); } else { PetscCall(KSPConvergedSkip(ksp,iter,rnorm,&ksp->reason,NULL)); /*PetscCall(KSPConvergedDefault(ksp,iter,rnorm,&ksp->reason,NULL));*/ } ksp->rnorm = rnorm; if (reason) *reason = ksp->reason; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPLogHistory(KSP ksp,PetscReal rnorm) { PetscFunctionBegin; PetscValidHeaderSpecific(ksp,KSP_CLASSID,1); PetscCall(KSPLogResidualHistory(ksp,rnorm)); PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode SNESConvergenceTestCall(SNES snes, PetscInt its, PetscReal xnorm, PetscReal ynorm, PetscReal fnorm, SNESConvergedReason *reason) { PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscValidPointer(reason,4); PetscCheck(its >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"iteration number must be nonnegative"); PetscCheck(xnorm >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"solution norm must be nonnegative"); PetscCheck(ynorm >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"step norm must be nonnegative"); PetscCheck(fnorm >= 0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"function norm must be nonnegative"); PetscUseTypeMethod(snes,converged ,its,xnorm,ynorm,fnorm,reason,snes->cnvP); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESConverged(SNES snes,PetscInt iter,PetscReal xnorm,PetscReal ynorm,PetscReal fnorm,SNESConvergedReason *reason) { PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); if (reason) PetscValidPointer(reason,2); if (!iter) { snes->reason = SNES_CONVERGED_ITERATING; snes->ttol = fnorm*snes->rtol; } if (snes->ops->converged) { PetscUseTypeMethod(snes,converged ,iter,xnorm,ynorm,fnorm,&snes->reason,snes->cnvP); } else { PetscCall(SNESConvergedSkip(snes,iter,xnorm,ynorm,fnorm,&snes->reason,0)); /*PetscCall(SNESConvergedDefault(snes,iter,xnorm,ynorm,fnorm,&snes->reason,0));*/ } snes->norm = fnorm; if (reason) *reason = snes->reason; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESLogHistory(SNES snes,PetscReal rnorm,PetscInt lits) { PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscCall(SNESLogConvergenceHistory(snes,rnorm,lits)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESGetUseMFFD(SNES snes,PetscBool *flag) { PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL; Mat J = NULL; PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscValidPointer(flag,2); *flag = PETSC_FALSE; PetscCall(SNESGetJacobian(snes,&J,0,&jac,0)); if (J) PetscCall(PetscObjectTypeCompare((PetscObject)J,MATMFFD,flag)); else if (jac == MatMFFDComputeJacobian) *flag = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESSetUseMFFD(SNES snes,PetscBool flag) { const char* prefix = NULL; PetscBool flg = PETSC_FALSE; Vec r = NULL; Mat A = NULL,B = NULL,J = NULL; void* funP = NULL; void* jacP = NULL; PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscCall(SNESGetUseMFFD(snes,&flg)); if (flg && flag) PetscFunctionReturn(PETSC_SUCCESS); if (!flg && !flag) PetscFunctionReturn(PETSC_SUCCESS); if (flg && !flag) { SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "cannot change matrix-free once it is set"); PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE); } PetscCall(SNESGetOptionsPrefix(snes,&prefix)); PetscCall(SNESGetFunction(snes,&r,0,&funP)); PetscCall(SNESGetJacobian(snes,&A,&B,0,&jacP)); if (!r) { SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first"); PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE); } PetscCall(MatCreateSNESMF(snes,&J)); PetscCall(MatSetOptionsPrefix(J,prefix)); PetscCall(MatSetFromOptions(J)); if (!B) { KSP ksp; PC pc; PetscBool shell,python; PetscCall(SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,jacP)); PetscCall(SNESGetKSP(snes,&ksp)); PetscCall(KSPGetPC(ksp,&pc)); PetscCall(PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&shell)); PetscCall(PetscObjectTypeCompare((PetscObject)pc,PCPYTHON,&python)); if (!shell && !python) PetscCall(PCSetType(pc,PCNONE)); } else PetscCall(SNESSetJacobian(snes,J,0,0,0)); PetscCall(MatDestroy(&J)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESGetUseFDColoring(SNES snes,PetscBool *flag) { PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL; PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscValidPointer(flag,2); *flag = PETSC_FALSE; PetscCall(SNESGetJacobian(snes,0,0,&jac,0)); if (jac == SNESComputeJacobianDefaultColor) *flag = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SNESSetUseFDColoring(SNES snes,PetscBool flag) { PetscBool flg = PETSC_FALSE; PetscErrorCode (*fun)(SNES,Vec,Vec,void*) = NULL; void* funP = NULL; Mat A = NULL,B = NULL; PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL; void* jacP = NULL; PetscFunctionBegin; PetscValidHeaderSpecific(snes,SNES_CLASSID,1); PetscCall(SNESGetUseFDColoring(snes,&flg)); if (flg && flag) PetscFunctionReturn(PETSC_SUCCESS); if (!flg && !flag) PetscFunctionReturn(PETSC_SUCCESS); if (flg && !flag) { SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "cannot change colored finite differences once it is set"); PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE); } PetscCall(SNESGetFunction(snes,NULL,&fun,&funP)); PetscCall(SNESGetJacobian(snes,&A,&B,&jac,&jacP)); PetscCall(SNESSetJacobian(snes,A,B,SNESComputeJacobianDefaultColor,0)); { DM dm; DMSNES sdm; PetscCall(SNESGetDM(snes,&dm)); PetscCall(DMGetDMSNES(dm,&sdm)); PetscCall(DMSNESUnsetJacobianContext_Internal(dm)); } PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode TaoConverged(Tao tao, TaoConvergedReason *reason) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscValidBoolPointer(reason,2); if (tao->ops->convergencetest) { PetscUseTypeMethod(tao,convergencetest,tao->cnvP); } else { PetscCall(TaoDefaultConvergenceTest(tao,tao->cnvP)); } *reason = tao->reason; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoCheckReals(Tao tao, PetscReal f, PetscReal g) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscCheck(!PetscIsInfOrNanReal(f) && !PetscIsInfOrNanReal(g),PetscObjectComm((PetscObject)tao),PETSC_ERR_USER,"User provided compute function generated Inf or NaN"); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoCreateDefaultKSP(Tao tao) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscCall(KSPDestroy(&tao->ksp)); PetscCall(KSPCreate(((PetscObject)tao)->comm,&tao->ksp)); PetscCall(PetscObjectIncrementTabLevel((PetscObject)tao->ksp,(PetscObject)tao,1)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoCreateDefaultLineSearch(Tao tao) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscCall(TaoLineSearchDestroy(&tao->linesearch)); PetscCall(TaoLineSearchCreate(((PetscObject)tao)->comm,&tao->linesearch)); PetscCall(PetscObjectIncrementTabLevel((PetscObject)tao->linesearch,(PetscObject)tao,1)); PetscCall(TaoLineSearchSetType(tao->linesearch,TAOLINESEARCHMT)); PetscCall(TaoLineSearchUseTaoRoutines(tao->linesearch,tao)); PetscCall(TaoLineSearchSetInitialStepLength(tao->linesearch,1.0)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoHasGradientRoutine(Tao tao, PetscBool* flg) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscValidBoolPointer(flg,2); *flg = (PetscBool)(tao->ops->computegradient || tao->ops->computeobjectiveandgradient); PetscFunctionReturn(PETSC_SUCCESS); } #if 0 static PetscErrorCode TaoHasHessianRoutine(Tao tao, PetscBool* flg) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscValidBoolPointer(flg,2); *flg = tao->ops->computehessian; PetscFunctionReturn(PETSC_SUCCESS); } #endif static PetscErrorCode TaoComputeUpdate(Tao tao) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscTryTypeMethod(tao,update,tao->niter,tao->user_update); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoGetVecs(Tao tao, Vec *X, Vec *G, Vec *S) { PetscBool has_g; PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscCall(TaoHasGradientRoutine(tao,&has_g)); if (X) *X = tao->solution; if (G) { if (has_g && !tao->gradient) PetscCall(VecDuplicate(tao->solution,&tao->gradient)); *G = has_g ? tao->gradient : NULL; } if (S) { if (has_g && !tao->stepdirection) PetscCall(VecDuplicate(tao->solution,&tao->stepdirection)); *S = has_g ? tao->stepdirection : NULL; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode TaoApplyLineSearch(Tao tao, PetscReal* f, PetscReal *s, TaoLineSearchConvergedReason *lsr) { PetscFunctionBegin; PetscValidHeaderSpecific(tao,TAO_CLASSID,1); PetscValidRealPointer(f,2); PetscValidRealPointer(s,3); PetscCall(TaoLineSearchApply(tao->linesearch,tao->solution,f,tao->gradient,tao->stepdirection,s,lsr)); PetscCall(TaoAddLineSearchCounts(tao)); PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ static PetscErrorCode DMDACreateND(MPI_Comm comm, PetscInt dim,PetscInt dof, PetscInt M,PetscInt N,PetscInt P, PetscInt m,PetscInt n,PetscInt p, const PetscInt lx[],const PetscInt ly[],const PetscInt lz[], DMBoundaryType bx,DMBoundaryType by,DMBoundaryType bz, DMDAStencilType stencil_type,PetscInt stencil_width, DM *dm) { DM da; PetscFunctionBegin; PetscValidPointer(dm,18); PetscCall(DMDACreate(comm,&da)); PetscCall(DMSetDimension(da,dim)); PetscCall(DMDASetDof(da,dof)); PetscCall(DMDASetSizes(da,M,N,P)); PetscCall(DMDASetNumProcs(da,m,n,p)); PetscCall(DMDASetOwnershipRanges(da,lx,ly,lz)); PetscCall(DMDASetBoundaryType(da,bx,by,bz)); PetscCall(DMDASetStencilType(da,stencil_type)); PetscCall(DMDASetStencilWidth(da,stencil_width)); *dm = (DM)da; PetscFunctionReturn(PETSC_SUCCESS); } /* ---------------------------------------------------------------- */ #endif/* PETSC4PY_CUSTOM_H*/ /* Local variables: c-basic-offset: 2 indent-tabs-mode: nil End: */ petsc4py-3.19.6/src/lib-petsc/initpkg.h000066400000000000000000000017361454104047300176650ustar00rootroot00000000000000static PetscErrorCode PetscInitializePackageAll(void) { PetscFunctionBegin; PetscCall(PetscSysInitializePackage()); PetscCall(PetscDrawInitializePackage()); PetscCall(PetscViewerInitializePackage()); PetscCall(PetscRandomInitializePackage()); PetscCall(PetscDeviceInitializePackage()); PetscCall(ISInitializePackage()); PetscCall(AOInitializePackage()); PetscCall(PFInitializePackage()); PetscCall(PetscSFInitializePackage()); PetscCall(VecInitializePackage()); PetscCall(MatInitializePackage()); PetscCall(PCInitializePackage()); PetscCall(KSPInitializePackage()); PetscCall(SNESInitializePackage()); PetscCall(TaoInitializePackage()); PetscCall(TSInitializePackage()); PetscCall(PetscPartitionerInitializePackage()); PetscCall(DMInitializePackage()); PetscCall(PetscDSInitializePackage()); PetscCall(PetscFEInitializePackage()); PetscFunctionReturn(PETSC_SUCCESS); } /* Local variables: c-basic-offset: 2 indent-tabs-mode: nil End: */ petsc4py-3.19.6/src/petsc4py.egg-info/000077500000000000000000000000001454104047300174235ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py.egg-info/PKG-INFO000066400000000000000000000047531454104047300205310ustar00rootroot00000000000000Metadata-Version: 2.1 Name: petsc4py Version: 3.19.6 Summary: PETSc for Python Home-page: https://gitlab.com/petsc/petsc Download-URL: https://pypi.io/packages/source/p/petsc4py/petsc4py-3.19.6.tar.gz Author: Lisandro Dalcin Author-email: dalcinl@gmail.com Maintainer: PETSc Team Maintainer-email: petsc-maint@mcs.anl.gov License: BSD-2-Clause Keywords: scientific computing,parallel computing,MPI,PETSc Platform: POSIX Platform: Linux Platform: macOS Platform: FreeBSD Classifier: License :: OSI Approved :: BSD License 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 :: 2 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 PETSc for Python ================ Python bindings for PETSc. Install ------- If you have a working MPI implementation and the ``mpicc`` compiler wrapper is on your search path, it is highly recommended to install ``mpi4py`` first:: $ pip install mpi4py Ensure you have NumPy installed:: $ pip install numpy and finally:: $ pip install petsc petsc4py Citations --------- If PETSc 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 * S. Balay, S. Abhyankar, M. Adams, S. Benson, J. Brown, P. Brune, K. Buschelman, E. Constantinescu, L. Dalcin, A. Dener, V. Eijkhout, J. Faibussowitsch, W. Gropp, V. Hapla, T. Isaac, P. Jolivet, D. Karpeyev, D. Kaushik, M. Knepley, F. Kong, S. Kruger, D. May, L. Curfman McInnes, R. Mills, L. Mitchell, T. Munson, J. Roman, K. Rupp, P. Sanan, J Sarich, B. Smith, S. Zampini, H. Zhang, and H. Zhang, J. Zhang, *PETSc/TAO Users Manual*, ANL-21/39 - Revision 3.19, 2023. http://dx.doi.org/10.2172/1968587, https://petsc.org/release/docs/manual/manual.pdf petsc4py-3.19.6/src/petsc4py.egg-info/SOURCES.txt000066400000000000000000000142611454104047300213130ustar00rootroot00000000000000CHANGES.rst DESCRIPTION.rst LICENSE.rst MANIFEST.in README.rst setup.cfg setup.py conf/__init__.py conf/confpetsc.py conf/cythonize.py conf/cythonize.sh conf/epydoc.cfg conf/epydocify.py demo/makefile demo/binary-io/makefile demo/binary-io/matvecio.py demo/bratu2d/bratu2d.py demo/bratu2d/bratu2df90.f90 demo/bratu2d/bratu2dnpy.py demo/bratu2d/makefile demo/bratu3d/bratu3d.py demo/bratu3d/makefile demo/dmplex/anisotropic_adaptation.py demo/dmplex/distribute_field.py demo/dmplex/isotropic_adaptation.py demo/kspsolve/makefile demo/kspsolve/petsc-cg.py demo/kspsolve/petsc-ksp.py demo/kspsolve/petsc-mat.py demo/kspsolve/test_mat_cg.py demo/kspsolve/test_mat_ksp.py demo/ode/bouncing_ball.py demo/ode/ce.py demo/ode/heat.py demo/ode/orego.py demo/ode/rober.py demo/ode/vanderpol.py demo/perftest/App.f90 demo/perftest/App.pyf demo/perftest/driver.c demo/perftest/driver.py demo/perftest/makefile demo/perftest/makefile.f2py demo/perftest/makefile.petsc demo/petsc-examples/makefile demo/petsc-examples/ksp/ex2.py demo/petsc-examples/ksp/ex23.py demo/petsc-examples/ksp/makefile demo/poisson2d/makefile demo/poisson2d/poisson2d.py demo/poisson3d/del2lib.f90 demo/poisson3d/del2mat.h demo/poisson3d/del2mat.py demo/poisson3d/makefile demo/poisson3d/makefile.petsc demo/poisson3d/poisson3d.c demo/poisson3d/poisson3d.py demo/taosolve/chwirut.py demo/taosolve/rosenbrock.py demo/wrap-cython/Bratu3D.pyx demo/wrap-cython/Bratu3Dimpl.c demo/wrap-cython/Bratu3Dimpl.h demo/wrap-cython/makefile demo/wrap-cython/run_demo.py demo/wrap-cython/setup.py demo/wrap-f2py/.f2py_f2cmap demo/wrap-f2py/Bratu2D.F90 demo/wrap-f2py/Bratu2D.pyf demo/wrap-f2py/Bratu2Dmodule.h demo/wrap-f2py/makefile demo/wrap-f2py/run_demo.py demo/wrap-f2py/setup.py demo/wrap-swig/Bratu3D.c demo/wrap-swig/Bratu3D.h demo/wrap-swig/Bratu3D.i demo/wrap-swig/makefile demo/wrap-swig/run_demo.py demo/wrap-swig/setup.py docs/index.rst docs/source/Makefile docs/source/abstract.txt docs/source/citing.rst docs/source/conf.py 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/requirements.txt docs/source/toctree.txt docs/source/tutorial.rst src/cython.h src/lib-petsc/compat.h src/lib-petsc/custom.h src/lib-petsc/initpkg.h src/lib-petsc/compat/cuda.h src/lib-petsc/compat/h2opus.h src/lib-petsc/compat/hdf5.h src/lib-petsc/compat/hip.h src/lib-petsc/compat/hpddm.h src/lib-petsc/compat/hypre.h src/lib-petsc/compat/mpi.h src/lib-petsc/compat/mumps.h src/lib-petsc/compat/spai.h src/lib-petsc/compat/tao.h src/lib-petsc/compat/viennacl.h src/petsc4py/PETSc.pxd src/petsc4py/PETSc.py src/petsc4py/PETSc.pyx src/petsc4py/__init__.pxd src/petsc4py/__init__.py src/petsc4py/__main__.py src/petsc4py.egg-info/PKG-INFO src/petsc4py.egg-info/SOURCES.txt src/petsc4py.egg-info/dependency_links.txt src/petsc4py.egg-info/not-zip-safe src/petsc4py.egg-info/requires.txt src/petsc4py.egg-info/top_level.txt src/petsc4py/PETSc/AO.pyx src/petsc4py/PETSc/CAPI.pyx src/petsc4py/PETSc/Comm.pyx src/petsc4py/PETSc/Const.pyx src/petsc4py/PETSc/DM.pyx src/petsc4py/PETSc/DMComposite.pyx src/petsc4py/PETSc/DMDA.pyx src/petsc4py/PETSc/DMLabel.pyx src/petsc4py/PETSc/DMPlex.pyx src/petsc4py/PETSc/DMShell.pyx src/petsc4py/PETSc/DMStag.pyx src/petsc4py/PETSc/DMSwarm.pyx src/petsc4py/PETSc/DMUtils.pyx src/petsc4py/PETSc/DS.pyx src/petsc4py/PETSc/DT.pyx src/petsc4py/PETSc/Device.pyx src/petsc4py/PETSc/Error.pyx src/petsc4py/PETSc/FE.pyx src/petsc4py/PETSc/IS.pyx src/petsc4py/PETSc/KSP.pyx src/petsc4py/PETSc/Log.pyx src/petsc4py/PETSc/Mat.pyx src/petsc4py/PETSc/MatPartitioning.pyx src/petsc4py/PETSc/Object.pyx src/petsc4py/PETSc/Options.pyx src/petsc4py/PETSc/PC.pyx src/petsc4py/PETSc/PETSc.pyx src/petsc4py/PETSc/Partitioner.pyx src/petsc4py/PETSc/Random.pyx src/petsc4py/PETSc/SF.pyx src/petsc4py/PETSc/SNES.pyx src/petsc4py/PETSc/Scatter.pyx src/petsc4py/PETSc/Section.pyx src/petsc4py/PETSc/Space.pyx src/petsc4py/PETSc/Sys.pyx src/petsc4py/PETSc/TAO.pyx src/petsc4py/PETSc/TS.pyx src/petsc4py/PETSc/Vec.pyx src/petsc4py/PETSc/Viewer.pyx src/petsc4py/PETSc/arraynpy.pxi src/petsc4py/PETSc/cyclicgc.pxi src/petsc4py/PETSc/dlpack.pxi src/petsc4py/PETSc/libpetsc4py.pyx src/petsc4py/PETSc/petscao.pxi src/petsc4py/PETSc/petscdef.pxi src/petsc4py/PETSc/petscdevice.pxi src/petsc4py/PETSc/petscdm.pxi src/petsc4py/PETSc/petscdmcomposite.pxi src/petsc4py/PETSc/petscdmda.pxi src/petsc4py/PETSc/petscdmlabel.pxi src/petsc4py/PETSc/petscdmplex.pxi src/petsc4py/PETSc/petscdmshell.pxi src/petsc4py/PETSc/petscdmstag.pxi src/petsc4py/PETSc/petscdmswarm.pxi src/petsc4py/PETSc/petscdmutils.pxi src/petsc4py/PETSc/petscds.pxi src/petsc4py/PETSc/petscdt.pxi src/petsc4py/PETSc/petscfe.pxi src/petsc4py/PETSc/petscis.pxi src/petsc4py/PETSc/petscksp.pxi src/petsc4py/PETSc/petsclayout.pxi src/petsc4py/PETSc/petsclog.pxi src/petsc4py/PETSc/petscmat.pxi src/petsc4py/PETSc/petscmatpartitioning.pxi src/petsc4py/PETSc/petscmem.pxi src/petsc4py/PETSc/petscmpi.pxi src/petsc4py/PETSc/petscobj.pxi src/petsc4py/PETSc/petscopt.pxi src/petsc4py/PETSc/petscpartitioner.pxi src/petsc4py/PETSc/petscpc.pxi src/petsc4py/PETSc/petscpyappctx.pxi src/petsc4py/PETSc/petscrand.pxi src/petsc4py/PETSc/petscsct.pxi src/petsc4py/PETSc/petscsec.pxi src/petsc4py/PETSc/petscsf.pxi src/petsc4py/PETSc/petscsnes.pxi src/petsc4py/PETSc/petscspace.pxi src/petsc4py/PETSc/petscsys.pxi src/petsc4py/PETSc/petsctao.pxi src/petsc4py/PETSc/petscts.pxi src/petsc4py/PETSc/petscvec.pxi src/petsc4py/PETSc/petscvwr.pxi src/petsc4py/include/petsc4py/numpy.h src/petsc4py/include/petsc4py/petsc4py.h src/petsc4py/include/petsc4py/petsc4py.i src/petsc4py/include/petsc4py/pybuffer.h src/petsc4py/include/petsc4py/pyscalar.h src/petsc4py/lib/__init__.py src/petsc4py/lib/petsc.cfg test/runtests.py test/test_comm.py test/test_dmda.py test/test_dmplex.py test/test_dmshell.py test/test_dmstag.py test/test_gc.py test/test_is.py test/test_ksp.py test/test_ksp_py.py test/test_lgmap.py test/test_log.py test/test_mat_aij.py test/test_mat_dense.py test/test_mat_fact.py test/test_mat_py.py test/test_nsp.py test/test_object.py test/test_optdb.py test/test_pc_py.py test/test_snes.py test/test_snes_py.py test/test_stdout.py test/test_sys.py test/test_tao.py test/test_tao_py.py test/test_ts.py test/test_ts_py.py test/test_vec.pypetsc4py-3.19.6/src/petsc4py.egg-info/dependency_links.txt000066400000000000000000000000011454104047300234710ustar00rootroot00000000000000 petsc4py-3.19.6/src/petsc4py.egg-info/not-zip-safe000066400000000000000000000000011454104047300216510ustar00rootroot00000000000000 petsc4py-3.19.6/src/petsc4py.egg-info/requires.txt000066400000000000000000000000061454104047300220170ustar00rootroot00000000000000numpy petsc4py-3.19.6/src/petsc4py.egg-info/top_level.txt000066400000000000000000000000111454104047300221450ustar00rootroot00000000000000petsc4py petsc4py-3.19.6/src/petsc4py/000077500000000000000000000000001454104047300157315ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py/PETSc.pxd000066400000000000000000000171441454104047300173730ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # -------------------------------------------------------------------- cdef extern from "": ctypedef struct _p_MPI_Comm ctypedef _p_MPI_Comm* MPI_Comm ctypedef struct _p_MPI_Op ctypedef _p_MPI_Op* MPI_Op ctypedef struct _p_MPI_Datatype ctypedef _p_MPI_Datatype* MPI_Datatype ctypedef struct _p_PetscObject ctypedef _p_PetscObject* PetscObject struct _p_PetscViewer ctypedef _p_PetscViewer* PetscViewer struct _p_PetscRandom ctypedef _p_PetscRandom* PetscRandom struct _n_PetscDevice ctypedef _n_PetscDevice* PetscDevice struct _p_PetscDeviceContext ctypedef _p_PetscDeviceContext* PetscDeviceContext struct _p_IS ctypedef _p_IS* PetscIS "IS" struct _p_ISLocalToGlobalMapping ctypedef _p_ISLocalToGlobalMapping* PetscLGMap "ISLocalToGlobalMapping" struct _p_PetscSF ctypedef _p_PetscSF* PetscSF "PetscSF" struct _p_Vec ctypedef _p_Vec* PetscVec "Vec" struct _p_VecScatter ctypedef _p_VecScatter* PetscScatter "VecScatter" struct _p_PetscSpace ctypedef _p_PetscSpace* PetscSpace "PetscSpace" struct _p_PetscDualSpace ctypedef _p_PetscDualSpace* PetscDualSpace "PetscDualSpace" struct _p_PetscFE ctypedef _p_PetscFE* PetscFE "PetscFE" struct _p_PetscQuadrature ctypedef _p_PetscQuadrature* PetscQuadrature "PetscQuadrature" struct _p_DMLabel ctypedef _p_DMLabel* PetscDMLabel "DMLabel" struct _p_PetscSection ctypedef _p_PetscSection* PetscSection struct _p_Mat ctypedef _p_Mat* PetscMat "Mat" struct _p_MatPartitioning ctypedef _p_Mat* PetscMatPartitioning "MatPartitioning" struct _p_MatNullSpace ctypedef _p_MatNullSpace* PetscNullSpace "MatNullSpace" struct _p_PC ctypedef _p_PC* PetscPC "PC" struct _p_KSP ctypedef _p_KSP* PetscKSP "KSP" struct _p_SNES ctypedef _p_SNES* PetscSNES "SNES" struct _p_SNESLineSearch ctypedef _p_SNESLineSearch* PetscSNESLineSearch "SNESLineSearch" struct _p_TS ctypedef _p_TS* PetscTS "TS" struct _p_TAO "_p_Tao" ctypedef _p_TAO* PetscTAO "Tao" struct _p_TAOLineSearch "_p_TaoLineSearch" ctypedef _p_TAOLineSearch* PetscTAOLineSearch "TaoLineSearch" struct _p_AO ctypedef _p_AO* PetscAO "AO" struct _p_DM ctypedef _p_DM* PetscDM "DM" struct _p_DMPlexTransform ctypedef _p_DMPlexTransform* PetscDMPlexTransform "DMPlexTransform" struct _p_PetscDS ctypedef _p_PetscDS* PetscDS struct _p_PetscPartitioner ctypedef _p_PetscPartitioner* PetscPartitioner "PetscPartitioner" # -------------------------------------------------------------------- ctypedef public api class Comm [ type PyPetscComm_Type, object PyPetscCommObject, ]: cdef MPI_Comm comm cdef int isdup cdef object base ctypedef public api class Object [ type PyPetscObject_Type, object PyPetscObjectObject, ]: cdef __weakref__ cdef __dummy__ cdef PetscObject oval cdef PetscObject *obj cdef object get_attr(self, char name[]) cdef object set_attr(self, char name[], object attr) cdef object get_dict(self) ctypedef public api class Viewer(Object) [ type PyPetscViewer_Type, object PyPetscViewerObject, ]: cdef PetscViewer vwr ctypedef public api class Random(Object) [ type PyPetscRandom_Type, object PyPetscRandomObject, ]: cdef PetscRandom rnd ctypedef public api class Device [ type PyPetscDevice_Type, object PyPetscDeviceObject, ]: cdef PetscDevice device cdef object __weakref__ ctypedef public api class DeviceContext(Object) [ type PyPetscDeviceContext_Type, object PyPetscDeviceContextObject, ]: cdef PetscDeviceContext dctx ctypedef public api class IS(Object) [ type PyPetscIS_Type, object PyPetscISObject, ]: cdef PetscIS iset ctypedef public api class LGMap(Object) [ type PyPetscLGMap_Type, object PyPetscLGMapObject, ]: cdef PetscLGMap lgm ctypedef public api class SF(Object) [ type PyPetscSF_Type, object PyPetscSFObject, ]: cdef PetscSF sf ctypedef public api class Vec(Object) [ type PyPetscVec_Type, object PyPetscVecObject, ]: cdef PetscVec vec ctypedef public api class Space(Object) [ type PyPetscSpace_Type, object PyPetscSpaceObject, ]: cdef PetscSpace space ctypedef public api class DualSpace(Object) [ type PyPetscDualSpace_Type, object PyPetscDualSpaceObject, ]: cdef PetscDualSpace dualspace ctypedef public api class FE(Object) [ type PyPetscFE_Type, object PyPetscFEObject, ]: cdef PetscFE fe ctypedef public api class Quad(Object) [ type PyPetscQuad_Type, object PyPetscQuadObject, ]: cdef PetscQuadrature quad ctypedef public api class Scatter(Object) [ type PyPetscScatter_Type, object PyPetscScatterObject, ]: cdef PetscScatter sct ctypedef public api class Section(Object) [ type PyPetscSection_Type, object PyPetscSectionObject, ]: cdef PetscSection sec ctypedef public api class Mat(Object) [ type PyPetscMat_Type, object PyPetscMatObject, ]: cdef PetscMat mat ctypedef public api class MatPartitioning(Object) [ type PyPetscMatPartitioning_Type, object PyPetscMatPartitioningObject, ]: cdef PetscMatPartitioning part ctypedef public api class NullSpace(Object) [ type PyPetscNullSpace_Type, object PyPetscNullSpaceObject, ]: cdef PetscNullSpace nsp ctypedef public api class PC(Object) [ type PyPetscPC_Type, object PyPetscPCObject, ]: cdef PetscPC pc ctypedef public api class KSP(Object) [ type PyPetscKSP_Type, object PyPetscKSPObject, ]: cdef PetscKSP ksp ctypedef public api class SNES(Object) [ type PyPetscSNES_Type, object PyPetscSNESObject, ]: cdef PetscSNES snes ctypedef public api class TS(Object) [ type PyPetscTS_Type, object PyPetscTSObject, ]: cdef PetscTS ts ctypedef public api class TAO(Object) [ type PyPetscTAO_Type, object PyPetscTAOObject, ]: cdef PetscTAO tao ctypedef public api class AO(Object) [ type PyPetscAO_Type, object PyPetscAOObject, ]: cdef PetscAO ao ctypedef public api class DM(Object) [ type PyPetscDM_Type, object PyPetscDMObject, ]: cdef PetscDM dm ctypedef public api class DMPlexTransform(Object) [ type PyPetscDMPlexTransform_Type, object PyPetscDMPlexTransformObject, ]: cdef PetscDMPlexTransform tr ctypedef public api class DS(Object) [ type PyPetscDS_Type, object PyPetscDSObject, ]: cdef PetscDS ds ctypedef public api class Partitioner(Object) [ type PyPetscPartitioner_Type, object PyPetscPartitionerObject, ]: cdef PetscPartitioner part ctypedef public api class DMLabel(Object) [ type PyPetscDMLabel_Type, object PyPetscDMLabelObject, ]: cdef PetscDMLabel dmlabel # -------------------------------------------------------------------- cdef MPI_Comm GetComm(object, MPI_Comm) except * cdef MPI_Comm GetCommDefault() cdef int PyPetscType_Register(int, type) except -1 cdef type PyPetscType_Lookup(int) # -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscErrorCode: PETSC_SUCCESS PETSC_ERR_PLIB PETSC_ERR_SUP PETSC_ERR_USER PETSC_ERR_MEM PETSC_ERR_MPI PETSC_ERR_PYTHON ctypedef enum PetscErrorType: PETSC_ERROR_INITIAL PETSC_ERROR_REPEAT cdef PetscErrorCode CHKERR(PetscErrorCode) nogil except PETSC_ERR_PYTHON petsc4py-3.19.6/src/petsc4py/PETSc.py000066400000000000000000000002201454104047300172130ustar00rootroot00000000000000ARCH = None from petsc4py.lib import ImportPETSc # noqa: E402 PETSc = ImportPETSc(ARCH) PETSc._initialize() del PETSc del ImportPETSc del ARCH petsc4py-3.19.6/src/petsc4py/PETSc.pyx000066400000000000000000000007241454104047300174140ustar00rootroot00000000000000#cython: language_level=3str #cython: embedsignature=True #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 from __future__ import absolute_import cimport cython include "PETSc/PETSc.pyx" petsc4py-3.19.6/src/petsc4py/PETSc/000077500000000000000000000000001454104047300166475ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py/PETSc/AO.pyx000066400000000000000000000105421454104047300177120ustar00rootroot00000000000000# -------------------------------------------------------------------- class AOType(object): BASIC = S_(AOBASIC) ADVANCED = S_(AOADVANCED) MAPPING = S_(AOMAPPING) MEMORYSCALABLE = S_(AOMEMORYSCALABLE) # -------------------------------------------------------------------- cdef class AO(Object): Type = AOType def __cinit__(self): self.obj = &self.ao self.ao = NULL def view(self, Viewer viewer=None): cdef PetscViewer cviewer = NULL if viewer is not None: cviewer = viewer.vwr CHKERR( AOView(self.ao, cviewer) ) def destroy(self): CHKERR( AODestroy(&self.ao) ) return self def createBasic(self, app, petsc=None, comm=None): cdef PetscIS isapp = NULL, ispetsc = NULL cdef PetscInt napp = 0, *idxapp = NULL, cdef PetscInt npetsc = 0, *idxpetsc = NULL cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscAO newao = NULL if isinstance(app, IS): isapp = (app).iset if petsc is not None: ispetsc = (petsc).iset CHKERR( AOCreateBasicIS(isapp, ispetsc, &newao) ) else: app = iarray_i(app, &napp, &idxapp) if petsc is not None: petsc = iarray_i(petsc, &npetsc, &idxpetsc) assert napp == npetsc, "incompatible array sizes" CHKERR( AOCreateBasic(ccomm, napp, idxapp, idxpetsc, &newao) ) PetscCLEAR(self.obj); self.ao = newao return self def createMemoryScalable(self, app, petsc=None, comm=None): cdef PetscIS isapp = NULL, ispetsc = NULL cdef PetscInt napp = 0, *idxapp = NULL, cdef PetscInt npetsc = 0, *idxpetsc = NULL cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscAO newao = NULL if isinstance(app, IS): isapp = (app).iset if petsc is not None: ispetsc = (petsc).iset CHKERR( AOCreateMemoryScalableIS(isapp, ispetsc, &newao) ) else: app = iarray_i(app, &napp, &idxapp) if petsc is not None: petsc = iarray_i(petsc, &npetsc, &idxpetsc) assert napp == npetsc, "incompatible array sizes" CHKERR( AOCreateMemoryScalable(ccomm, napp, idxapp, idxpetsc, &newao) ) PetscCLEAR(self.obj); self.ao = newao return self def createMapping(self, app, petsc=None, comm=None): cdef PetscIS isapp = NULL, ispetsc = NULL cdef PetscInt napp = 0, *idxapp = NULL, cdef PetscInt npetsc = 0, *idxpetsc = NULL cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscAO newao = NULL if isinstance(app, IS): isapp = (app).iset if petsc is not None: ispetsc = (petsc).iset CHKERR( AOCreateMappingIS(isapp, ispetsc, &newao) ) else: app = iarray_i(app, &napp, &idxapp) if petsc is not None: petsc = iarray_i(petsc, &npetsc, &idxpetsc) assert napp == npetsc, "incompatible array sizes" CHKERR( AOCreateMapping(ccomm, napp, idxapp, idxpetsc, &newao) ) PetscCLEAR(self.obj); self.ao = newao return self def getType(self): cdef PetscAOType cval = NULL CHKERR( AOGetType(self.ao, &cval) ) return bytes2str(cval) def app2petsc(self, indices): cdef PetscIS iset = NULL cdef PetscInt nidx = 0, *idx = NULL if isinstance(indices, IS): iset = (indices).iset CHKERR( AOApplicationToPetscIS(self.ao, iset) ) else: indices = oarray_i(indices, &nidx, &idx) CHKERR( AOApplicationToPetsc(self.ao, nidx, idx) ) return indices def petsc2app(self, indices): cdef PetscIS iset = NULL cdef PetscInt nidx = 0, *idx = NULL if isinstance(indices, IS): iset = (indices).iset CHKERR( AOPetscToApplicationIS(self.ao, iset) ) else: indices = oarray_i(indices, &nidx, &idx) CHKERR( AOPetscToApplication(self.ao, nidx, idx) ) return indices # -------------------------------------------------------------------- del AOType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/CAPI.pyx000066400000000000000000000223101454104047300201230ustar00rootroot00000000000000#--------------------------------------------------------------------- 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 #--------------------------------------------------------------------- # -- Error -- cdef api int PyPetscError_Set(PetscErrorCode ierr): return SETERR(ierr) # -- Comm -- cdef api object PyPetscComm_New(MPI_Comm arg): cdef Comm retv = Comm() retv.comm = arg return retv cdef api MPI_Comm PyPetscComm_Get(object arg) except *: cdef MPI_Comm retv = MPI_COMM_NULL cdef Comm ob = arg retv = ob.comm return retv cdef api MPI_Comm* PyPetscComm_GetPtr(object arg) except NULL: cdef MPI_Comm *retv = NULL cdef Comm ob = arg retv = &ob.comm return retv # -- Object -- cdef api object PyPetscObject_New(PetscObject arg): cdef Object retv = subtype_Object(arg)() setref(&retv.obj[0], arg) return retv cdef api PetscObject PyPetscObject_Get(object arg) except ? NULL: cdef PetscObject retv = NULL cdef Object ob = arg retv = ob.obj[0] return retv cdef api PetscObject* PyPetscObject_GetPtr(object arg) except NULL: cdef PetscObject *retv = NULL cdef Object ob = arg retv = ob.obj return retv # -- Viewer -- cdef api object PyPetscViewer_New(PetscViewer arg): cdef Viewer retv = Viewer() setref(&retv.vwr, arg) return retv cdef api PetscViewer PyPetscViewer_Get(object arg) except ? NULL: cdef PetscViewer retv = NULL cdef Viewer ob = arg retv = ob.vwr return retv # -- Random -- cdef api object PyPetscRandom_New(PetscRandom arg): cdef Random retv = Random() setref(&retv.rnd, arg) return retv cdef api PetscRandom PyPetscRandom_Get(object arg) except ? NULL: cdef PetscRandom retv = NULL cdef Random ob = arg retv = ob.rnd return retv # -- Device -- cdef api Device PyPetscDevice_New(PetscDevice arg): cdef Device ret = Device() ret.device = arg return ret cdef api PetscDevice PyPetscDevice_Get(object arg) except ? NULL: cdef Device obj = arg cdef PetscDevice ret = obj.device return ret # -- DeviceContext -- cdef api DeviceContext PyPetscDeviceContext_New(PetscDeviceContext arg): cdef DeviceContext retv = DeviceContext() setref(&retv.dctx, arg) return retv cdef api PetscDeviceContext PyPetscDeviceContext_Get(object arg) except ? NULL: cdef DeviceContext obj = arg cdef PetscDeviceContext ret = obj.dctx return ret # -- IS -- cdef api object PyPetscIS_New(PetscIS arg): cdef IS retv = IS() setref(&retv.iset, arg) return retv cdef api PetscIS PyPetscIS_Get(object arg) except? NULL: cdef PetscIS retv = NULL cdef IS ob = arg retv = ob.iset return retv # -- LGMap -- cdef api object PyPetscLGMap_New(PetscLGMap arg): cdef LGMap retv = LGMap() setref(&retv.lgm, arg) return retv cdef api PetscLGMap PyPetscLGMap_Get(object arg) except ? NULL: cdef PetscLGMap retv = NULL cdef LGMap ob = arg retv = ob.lgm return retv # -- SF -- cdef api object PyPetscSF_New(PetscSF arg): cdef SF retv = SF() setref(&retv.sf, arg) return retv cdef api PetscSF PyPetscSF_Get(object arg) except? NULL: cdef PetscSF retv = NULL cdef SF ob = arg retv = ob.sf return retv # -- Vec -- cdef api object PyPetscVec_New(PetscVec arg): cdef Vec retv = Vec() setref(&retv.vec, arg) return retv cdef api PetscVec PyPetscVec_Get(object arg) except ? NULL: cdef PetscVec retv = NULL cdef Vec ob = arg retv = ob.vec return retv # -- Scatter -- cdef api object PyPetscScatter_New(PetscScatter arg): cdef Scatter retv = Scatter() setref(&retv.sct, arg) return retv cdef api PetscScatter PyPetscScatter_Get(object arg) except ? NULL: cdef PetscScatter retv = NULL cdef Scatter ob = arg retv = ob.sct return retv # -- Section -- cdef api object PyPetscSection_New(PetscSection arg): cdef Section retv = Section() setref(&retv.sec, arg) return retv cdef api PetscSection PyPetscSection_Get(object arg) except ? NULL: cdef PetscSection retv = NULL cdef Section ob = arg retv = ob.sec return retv # -- Mat -- cdef api object PyPetscMat_New(PetscMat arg): cdef Mat retv = Mat() setref(&retv.mat, arg) return retv cdef api PetscMat PyPetscMat_Get(object arg) except ? NULL: cdef PetscMat retv = NULL cdef Mat ob = arg retv = ob.mat return retv # -- MatPartitioning -- cdef api object PyPetscMatPartitioning_New(PetscMatPartitioning arg): cdef MatPartitioning retv = MatPartitioning() setref(&retv.part, arg) return retv cdef api PetscMatPartitioning PyPetscMatPartitioning_Get(object arg) except ? NULL: cdef PetscMatPartitioning retv = NULL cdef MatPartitioning ob = arg retv = ob.part return retv # -- PC -- cdef api object PyPetscPC_New(PetscPC arg): cdef PC retv = PC() setref(&retv.pc, arg) return retv cdef api PetscPC PyPetscPC_Get(object arg) except ? NULL: cdef PetscPC retv = NULL cdef PC ob = arg retv = ob.pc return retv # -- KSP -- cdef api object PyPetscKSP_New(PetscKSP arg): cdef KSP retv = KSP() setref(&retv.ksp, arg) return retv cdef api PetscKSP PyPetscKSP_Get(object arg) except ? NULL: cdef PetscKSP retv = NULL cdef KSP ob = arg retv = ob.ksp return retv # -- SNES -- cdef api object PyPetscSNES_New(PetscSNES arg): cdef SNES retv = SNES() setref(&retv.snes, arg) return retv cdef api PetscSNES PyPetscSNES_Get(object arg) except ? NULL: cdef PetscSNES retv = NULL cdef SNES ob = arg retv = ob.snes return retv # -- TS -- cdef api object PyPetscTS_New(PetscTS arg): cdef TS retv = TS() setref(&retv.ts, arg) return retv cdef api PetscTS PyPetscTS_Get(object arg) except ? NULL: cdef PetscTS retv = NULL cdef TS ob = arg retv = ob.ts return retv # -- TAO -- cdef api object PyPetscTAO_New(PetscTAO arg): cdef TAO retv = TAO() setref(&retv.tao, arg) return retv cdef api PetscTAO PyPetscTAO_Get(object arg) except ? NULL: cdef PetscTAO retv = NULL cdef TAO ob = arg retv = ob.tao return retv # -- AO -- cdef api object PyPetscAO_New(PetscAO arg): cdef AO retv = AO() setref(&retv.ao, arg) return retv cdef api PetscAO PyPetscAO_Get(object arg) except ? NULL: cdef PetscAO retv = NULL cdef AO ob = arg retv = ob.ao return retv # -- DM -- cdef api object PyPetscDM_New(PetscDM arg): cdef DM retv = subtype_DM(arg)() setref(&retv.dm, arg) return retv cdef api PetscDM PyPetscDM_Get(object arg) except ? NULL: cdef PetscDM retv = NULL cdef DM ob = arg retv = ob.dm return retv # -- DS -- cdef api object PyPetscDS_New(PetscDS arg): cdef DS retv = DS() setref(&retv.ds, arg) return retv cdef api PetscDS PyPetscDS_Get(object arg) except ? NULL: cdef PetscDS retv = NULL cdef DS ob = arg retv = ob.ds return retv # -- Partitioner -- cdef api object PyPetscPartitioner_New(PetscPartitioner arg): cdef Partitioner retv = Partitioner() setref(&retv.part, arg) return retv cdef api PetscPartitioner PyPetscPartitioner_Get(object arg) except ? NULL: cdef PetscPartitioner retv = NULL cdef Partitioner ob = arg retv = ob.part return retv # -- FE -- cdef api object PyPetscFE_New(PetscFE arg): cdef FE retv = FE() setref(&retv.fe, arg) return retv cdef api PetscFE PyPetscFE_Get(object arg) except ? NULL: cdef PetscFE retv = NULL cdef FE ob = arg retv = ob.fe return retv # -- QUAD -- cdef api object PyPetscQuad_New(PetscQuadrature arg): cdef Quad retv = Quad() setref(&retv.quad, arg) return retv cdef api PetscQuadrature PyPetscQuad_Get(object arg) except ? NULL: cdef PetscQuadrature retv = NULL cdef Quad ob = arg retv = ob.quad return retv # -- DMLabel -- cdef api object PyPetscDMLabel_New(PetscDMLabel arg): cdef DMLabel retv = DMLabel() setref(&retv.dmlabel, arg) return retv cdef api PetscDMLabel PyPetscDMLabel_Get(object arg) except ? NULL: cdef PetscDMLabel retv = NULL cdef DMLabel ob = arg retv = ob.dmlabel return retv # -- SPACE -- cdef api object PyPetscSpace_New(PetscSpace arg): cdef Space retv = Space() setref(&retv.space, arg) return retv cdef api PetscSpace PyPetscSpace_Get(object arg) except ? NULL: cdef PetscSpace retv = NULL cdef Space ob = arg retv = ob.space return retv # -- DUALSPACE -- cdef api object PyPetscDualSpace_New(PetscDualSpace arg): cdef DualSpace retv = DualSpace() setref(&retv.dualspace, arg) return retv cdef api PetscDualSpace PyPetscDualSpace_Get(object arg) except ? NULL: cdef PetscDualSpace retv = NULL cdef DualSpace ob = arg retv = ob.dualspace return retv #--------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Comm.pyx000066400000000000000000000074121454104047300203100ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class Comm: # def __cinit__(self, comm=None): self.comm = def_Comm(comm, MPI_COMM_NULL) self.isdup = 0 if self.comm != MPI_COMM_NULL: self.base = comm else: self.base = None def __dealloc__(self): if self.isdup: CHKERR( PetscCommDEALLOC(&self.comm) ) self.comm = MPI_COMM_NULL self.isdup = 0 self.base = None def __richcmp__(self, other, int op): if not isinstance(self, Comm): return NotImplemented if not isinstance(other, Comm): return NotImplemented if op!=2 and op!=3: raise TypeError("only '==' and '!='") cdef Comm s = self cdef Comm o = other cdef int eq = (op == 2) cdef MPI_Comm comm1 = s.comm cdef MPI_Comm comm2 = o.comm cdef int flag = 0 if comm1 != MPI_COMM_NULL and comm2 != MPI_COMM_NULL: CHKERR( MPI_Comm_compare(comm1, comm2, &flag) ) if eq: return (flag==MPI_IDENT or flag==MPI_CONGRUENT) else: return (flag!=MPI_IDENT and flag!=MPI_CONGRUENT) else: if eq: return (comm1 == comm2) else: return (comm1 != comm2) def __nonzero__(self): return self.comm != MPI_COMM_NULL # def destroy(self): if self.comm == MPI_COMM_NULL: return if not self.isdup: raise ValueError("communicator not owned") CHKERR( PetscCommDestroy(&self.comm) ) self.comm = MPI_COMM_NULL self.isdup = 0 self.base = None def duplicate(self): if self.comm == MPI_COMM_NULL: raise ValueError("null communicator") cdef MPI_Comm newcomm = MPI_COMM_NULL CHKERR( PetscCommDuplicate(self.comm, &newcomm, NULL) ) cdef Comm comm = type(self)() comm.comm = newcomm comm.isdup = 1 comm.base = self.base return comm def getSize(self): if self.comm == MPI_COMM_NULL: raise ValueError("null communicator") cdef int size=0 MPI_Comm_size(self.comm, &size) return size def getRank(self): if self.comm == MPI_COMM_NULL: raise ValueError("null communicator") cdef int rank=0 MPI_Comm_rank(self.comm, &rank) return rank def barrier(self): if self.comm == MPI_COMM_NULL: raise ValueError("null communicator") MPI_Barrier(self.comm) # --- properties --- property size: def __get__(self): return self.getSize() property rank: def __get__(self): return self.getRank() # --- Fortran support --- property fortran: def __get__(self): cdef MPI_Comm comm = self.comm return MPI_Comm_c2f(comm) # --- mpi4py support --- def tompi4py(self): cdef MPI_Comm comm = self.comm return mpi4py_Comm_New(comm) # --- mpi4py compatibility API --- Free = destroy Clone = duplicate Dup = duplicate Get_size = getSize Get_rank = getRank Barrier = barrier # -------------------------------------------------------------------- cdef Comm __COMM_NULL__ = Comm() cdef Comm __COMM_SELF__ = Comm() cdef Comm __COMM_WORLD__ = Comm() COMM_NULL = __COMM_NULL__ COMM_SELF = __COMM_SELF__ COMM_WORLD = __COMM_WORLD__ # -------------------------------------------------------------------- cdef MPI_Comm PETSC_COMM_DEFAULT = MPI_COMM_NULL cdef MPI_Comm GetComm(object comm, MPI_Comm defv) except *: return def_Comm(comm, defv) cdef MPI_Comm GetCommDefault(): return PETSC_COMM_DEFAULT # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Const.pyx000066400000000000000000000041701454104047300205010ustar00rootroot00000000000000# -------------------------------------------------------------------- DECIDE = PETSC_DECIDE DEFAULT = PETSC_DEFAULT DETERMINE = PETSC_DETERMINE # -------------------------------------------------------------------- INFINITY = toReal(PETSC_INFINITY) NINFINITY = toReal(PETSC_NINFINITY) PINFINITY = toReal(PETSC_INFINITY) # -------------------------------------------------------------------- class InsertMode(object): # native NOT_SET_VALUES = PETSC_NOT_SET_VALUES INSERT_VALUES = PETSC_INSERT_VALUES ADD_VALUES = PETSC_ADD_VALUES MAX_VALUES = PETSC_MAX_VALUES INSERT_ALL_VALUES = PETSC_INSERT_ALL_VALUES ADD_ALL_VALUES = PETSC_ADD_ALL_VALUES INSERT_BC_VALUES = PETSC_INSERT_BC_VALUES ADD_BC_VALUES = PETSC_ADD_BC_VALUES # aliases INSERT = INSERT_VALUES ADD = ADD_VALUES MAX = MAX_VALUES INSERT_ALL = INSERT_ALL_VALUES ADD_ALL = ADD_ALL_VALUES INSERT_BC = INSERT_BC_VALUES ADD_BC = ADD_BC_VALUES # -------------------------------------------------------------------- class ScatterMode(object): # native SCATTER_FORWARD = PETSC_SCATTER_FORWARD SCATTER_REVERSE = PETSC_SCATTER_REVERSE SCATTER_FORWARD_LOCAL = PETSC_SCATTER_FORWARD_LOCAL SCATTER_REVERSE_LOCAL = PETSC_SCATTER_REVERSE_LOCAL # aliases FORWARD = SCATTER_FORWARD REVERSE = SCATTER_REVERSE FORWARD_LOCAL = SCATTER_FORWARD_LOCAL REVERSE_LOCAL = SCATTER_REVERSE_LOCAL # -------------------------------------------------------------------- class NormType(object): # native NORM_1 = PETSC_NORM_1 NORM_2 = PETSC_NORM_2 NORM_1_AND_2 = PETSC_NORM_1_AND_2 NORM_FROBENIUS = PETSC_NORM_FROBENIUS NORM_INFINITY = PETSC_NORM_INFINITY NORM_MAX = PETSC_NORM_MAX # aliases N1 = NORM_1 N2 = NORM_2 N12 = NORM_1_AND_2 MAX = NORM_MAX FROBENIUS = NORM_FROBENIUS INFINITY = NORM_INFINITY # extra aliases FRB = FROBENIUS INF = INFINITY # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/DM.pyx000066400000000000000000000630101454104047300177110ustar00rootroot00000000000000# -------------------------------------------------------------------- class DMType(object): DA = S_(DMDA_type) COMPOSITE = S_(DMCOMPOSITE) SLICED = S_(DMSLICED) SHELL = S_(DMSHELL) PLEX = S_(DMPLEX) REDUNDANT = S_(DMREDUNDANT) PATCH = S_(DMPATCH) MOAB = S_(DMMOAB) NETWORK = S_(DMNETWORK) FOREST = S_(DMFOREST) P4EST = S_(DMP4EST) P8EST = S_(DMP8EST) SWARM = S_(DMSWARM) PRODUCT = S_(DMPRODUCT) STAG = S_(DMSTAG) class DMBoundaryType(object): NONE = DM_BOUNDARY_NONE GHOSTED = DM_BOUNDARY_GHOSTED MIRROR = DM_BOUNDARY_MIRROR PERIODIC = DM_BOUNDARY_PERIODIC TWIST = DM_BOUNDARY_TWIST class DMPolytopeType(object): POINT = DM_POLYTOPE_POINT SEGMENT = DM_POLYTOPE_SEGMENT POINT_PRISM_TENSOR = DM_POLYTOPE_POINT_PRISM_TENSOR TRIANGLE = DM_POLYTOPE_TRIANGLE QUADRILATERAL = DM_POLYTOPE_QUADRILATERAL SEG_PRISM_TENSOR = DM_POLYTOPE_SEG_PRISM_TENSOR TETRAHEDRON = DM_POLYTOPE_TETRAHEDRON HEXAHEDRON = DM_POLYTOPE_HEXAHEDRON TRI_PRISM = DM_POLYTOPE_TRI_PRISM TRI_PRISM_TENSOR = DM_POLYTOPE_TRI_PRISM_TENSOR QUAD_PRISM_TENSOR = DM_POLYTOPE_QUAD_PRISM_TENSOR PYRAMID = DM_POLYTOPE_PYRAMID FV_GHOST = DM_POLYTOPE_FV_GHOST INTERIOR_GHOST = DM_POLYTOPE_INTERIOR_GHOST UNKNOWN = DM_POLYTOPE_UNKNOWN # -------------------------------------------------------------------- cdef class DM(Object): Type = DMType BoundaryType = DMBoundaryType PolytopeType = DMPolytopeType # def __cinit__(self): self.obj = &self.dm self.dm = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( DMView(self.dm, vwr) ) def load(self, Viewer viewer): CHKERR( DMLoad(self.dm, viewer.vwr) ) return self def destroy(self): CHKERR( DMDestroy(&self.dm) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMCreate(ccomm, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def clone(self): cdef DM dm = type(self)() CHKERR( DMClone(self.dm, &dm.dm) ) return dm def setType(self, dm_type): cdef PetscDMType cval = NULL dm_type = str2bytes(dm_type, &cval) CHKERR( DMSetType(self.dm, cval) ) def getType(self): cdef PetscDMType cval = NULL CHKERR( DMGetType(self.dm, &cval) ) return bytes2str(cval) def getDimension(self): cdef PetscInt dim = 0 CHKERR( DMGetDimension(self.dm, &dim) ) return toInt(dim) def setDimension(self, dim): cdef PetscInt cdim = asInt(dim) CHKERR( DMSetDimension(self.dm, cdim) ) def getCoordinateDim(self): cdef PetscInt dim = 0 CHKERR( DMGetCoordinateDim(self.dm, &dim) ) return toInt(dim) def setCoordinateDim(self, dim): cdef PetscInt cdim = asInt(dim) CHKERR( DMSetCoordinateDim(self.dm, cdim) ) def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( DMSetOptionsPrefix(self.dm, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( DMGetOptionsPrefix(self.dm, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( DMAppendOptionsPrefix(self.dm, cval) ) def setFromOptions(self): CHKERR( DMSetFromOptions(self.dm) ) def viewFromOptions(self, name, Object obj=None): cdef const char *cname = NULL _ = str2bytes(name, &cname) cdef PetscObject cobj = NULL if obj is not None: cobj = obj.obj[0] CHKERR( DMViewFromOptions(self.dm, cobj, cname) ) def setUp(self): CHKERR( DMSetUp(self.dm) ) return self # --- application context --- def setAppCtx(self, appctx): self.set_attr('__appctx__', appctx) def getAppCtx(self): return self.get_attr('__appctx__') # def setBasicAdjacency(self, useCone, useClosure): cdef PetscBool uC = useCone cdef PetscBool uCl = useClosure CHKERR( DMSetBasicAdjacency(self.dm, uC, uCl) ) def getBasicAdjacency(self): cdef PetscBool uC = PETSC_FALSE cdef PetscBool uCl = PETSC_FALSE CHKERR( DMGetBasicAdjacency(self.dm, &uC, &uCl) ) return toBool(uC), toBool(uCl) def setFieldAdjacency(self, field, useCone, useClosure): cdef PetscInt f = asInt(field) cdef PetscBool uC = useCone cdef PetscBool uCl = useClosure CHKERR( DMSetAdjacency(self.dm, f, uC, uCl) ) def getFieldAdjacency(self, field): cdef PetscInt f = asInt(field) cdef PetscBool uC = PETSC_FALSE cdef PetscBool uCl = PETSC_FALSE CHKERR( DMGetAdjacency(self.dm, f, &uC, &uCl) ) return toBool(uC), toBool(uCl) # def createSubDM(self, fields): cdef IS iset = IS() cdef DM subdm = DM() cdef PetscInt *ifields = NULL cdef PetscInt numFields = 0 fields = iarray_i(fields, &numFields, &ifields) CHKERR( DMCreateSubDM( self.dm, numFields, ifields, &iset.iset, &subdm.dm) ) return iset, subdm # def setAuxiliaryVec(self, Vec aux, label=None, value=0, part=0): cdef PetscInt cvalue = asInt(value) cdef PetscInt cpart = asInt(part) cdef const char *cval = NULL cdef PetscDMLabel clbl = NULL label = str2bytes(label, &cval) if cval == NULL: cval = b"" # XXX Should be fixed upstream CHKERR( DMGetLabel(self.dm, cval, &clbl) ) CHKERR( DMSetAuxiliaryVec(self.dm, clbl, cvalue, cpart, aux.vec) ) def getAuxiliaryVec(self, label=None, value=0, part=0): cdef PetscInt cvalue = asInt(value) cdef PetscInt cpart = asInt(part) cdef const char *cval = NULL cdef PetscDMLabel clbl = NULL cdef Vec aux = Vec() label = str2bytes(label, &cval) if cval == NULL: cval = b"" # XXX Should be fixed upstream CHKERR( DMGetLabel(self.dm, cval, &clbl) ) CHKERR( DMGetAuxiliaryVec(self.dm, clbl, cvalue, cpart, &aux.vec) ) return aux def setNumFields(self, numFields): cdef PetscInt cnum = asInt(numFields) CHKERR( DMSetNumFields(self.dm, cnum) ) def getNumFields(self): cdef PetscInt cnum = 0 CHKERR( DMGetNumFields(self.dm, &cnum) ) return toInt(cnum) def setField(self, index, Object field, label=None): cdef PetscInt cidx = asInt(index) cdef PetscObject cobj = field.obj[0] cdef PetscDMLabel clbl = NULL assert label is None CHKERR( DMSetField(self.dm, cidx, clbl, cobj) ) def getField(self, index): cdef PetscInt cidx = asInt(index) cdef PetscObject cobj = NULL cdef PetscDMLabel clbl = NULL CHKERR( DMGetField(self.dm, cidx, &clbl, &cobj) ) assert clbl == NULL cdef Object field = subtype_Object(cobj)() field.obj[0] = cobj PetscINCREF(field.obj) return (field, None) def addField(self, Object field, label=None): cdef PetscObject cobj = field.obj[0] cdef PetscDMLabel clbl = NULL assert label is None CHKERR( DMAddField(self.dm, clbl, cobj) ) def clearFields(self): CHKERR( DMClearFields(self.dm) ) def copyFields(self, DM dm): CHKERR( DMCopyFields(self.dm, dm.dm) ) def createDS(self): CHKERR( DMCreateDS(self.dm) ) def clearDS(self): CHKERR( DMClearDS(self.dm) ) def getDS(self): cdef DS ds = DS() CHKERR( DMGetDS(self.dm, &ds.ds) ) PetscINCREF(ds.obj) return ds def copyDS(self, DM dm): CHKERR( DMCopyDS(self.dm, dm.dm) ) def copyDisc(self, DM dm): CHKERR( DMCopyDisc(self.dm, dm.dm) ) # def getBlockSize(self): cdef PetscInt bs = 1 CHKERR( DMGetBlockSize(self.dm, &bs) ) return toInt(bs) def setVecType(self, vec_type): cdef PetscVecType vtype = NULL vec_type = str2bytes(vec_type, &vtype) CHKERR( DMSetVecType(self.dm, vtype) ) def createGlobalVec(self): cdef Vec vg = Vec() CHKERR( DMCreateGlobalVector(self.dm, &vg.vec) ) return vg def createLocalVec(self): cdef Vec vl = Vec() CHKERR( DMCreateLocalVector(self.dm, &vl.vec) ) return vl def getGlobalVec(self): cdef Vec vg = Vec() CHKERR( DMGetGlobalVector(self.dm, &vg.vec) ) PetscINCREF(vg.obj) return vg def restoreGlobalVec(self, Vec vg): CHKERR( PetscObjectDereference(vg.vec) ) CHKERR( DMRestoreGlobalVector(self.dm, &vg.vec) ) def getLocalVec(self): cdef Vec vl = Vec() CHKERR( DMGetLocalVector(self.dm, &vl.vec) ) PetscINCREF(vl.obj) return vl def restoreLocalVec(self, Vec vl): CHKERR( PetscObjectDereference(vl.vec) ) CHKERR( DMRestoreLocalVector(self.dm, &vl.vec) ) def globalToLocal(self, Vec vg, Vec vl, addv=None): cdef PetscInsertMode im = insertmode(addv) CHKERR( DMGlobalToLocalBegin(self.dm, vg.vec, im, vl.vec) ) CHKERR( DMGlobalToLocalEnd (self.dm, vg.vec, im, vl.vec) ) def localToGlobal(self, Vec vl, Vec vg, addv=None): cdef PetscInsertMode im = insertmode(addv) CHKERR( DMLocalToGlobalBegin(self.dm, vl.vec, im, vg.vec) ) CHKERR( DMLocalToGlobalEnd(self.dm, vl.vec, im, vg.vec) ) def localToLocal(self, Vec vl, Vec vlg, addv=None): cdef PetscInsertMode im = insertmode(addv) CHKERR( DMLocalToLocalBegin(self.dm, vl.vec, im, vlg.vec) ) CHKERR( DMLocalToLocalEnd (self.dm, vl.vec, im, vlg.vec) ) def getLGMap(self): cdef LGMap lgm = LGMap() CHKERR( DMGetLocalToGlobalMapping(self.dm, &lgm.lgm) ) PetscINCREF(lgm.obj) return lgm # def getCoordinateDM(self): cdef DM cdm = type(self)() CHKERR( DMGetCoordinateDM(self.dm, &cdm.dm) ) PetscINCREF(cdm.obj) return cdm def getCoordinateSection(self): cdef Section sec = Section() CHKERR( DMGetCoordinateSection(self.dm, &sec.sec) ) PetscINCREF(sec.obj) return sec def setCoordinates(self, Vec c): CHKERR( DMSetCoordinates(self.dm, c.vec) ) def getCoordinates(self): cdef Vec c = Vec() CHKERR( DMGetCoordinates(self.dm, &c.vec) ) PetscINCREF(c.obj) return c def setCoordinatesLocal(self, Vec c): CHKERR( DMSetCoordinatesLocal(self.dm, c.vec) ) def getCoordinatesLocal(self): cdef Vec c = Vec() CHKERR( DMGetCoordinatesLocal(self.dm, &c.vec) ) PetscINCREF(c.obj) return c def projectCoordinates(self, FE disc): CHKERR( DMProjectCoordinates(self.dm, disc.fe)) return self def getBoundingBox(self): cdef PetscInt i,dim=0 CHKERR( DMGetCoordinateDim(self.dm, &dim) ) cdef PetscReal gmin[3], gmax[3] CHKERR( DMGetBoundingBox(self.dm, gmin, gmax) ) return tuple([(toReal(gmin[i]), toReal(gmax[i])) for i from 0 <= i < dim]) def getLocalBoundingBox(self): cdef PetscInt i,dim=0 CHKERR( DMGetCoordinateDim(self.dm, &dim) ) cdef PetscReal lmin[3], lmax[3] CHKERR( DMGetLocalBoundingBox(self.dm, lmin, lmax) ) return tuple([(toReal(lmin[i]), toReal(lmax[i])) for i from 0 <= i < dim]) def localizeCoordinates(self): CHKERR( DMLocalizeCoordinates(self.dm) ) # def setMatType(self, mat_type): """Set matrix type to be used by DM.createMat""" cdef PetscMatType mtype = NULL mat_type = str2bytes(mat_type, &mtype) CHKERR( DMSetMatType(self.dm, mtype) ) def createMat(self): cdef Mat mat = Mat() CHKERR( DMCreateMatrix(self.dm, &mat.mat) ) return mat def createMassMatrix(self, DM dmf): cdef Mat mat = Mat() CHKERR( DMCreateMassMatrix(self.dm, dmf.dm, &mat.mat) ) return mat def createInterpolation(self, DM dm): cdef Mat A = Mat() cdef Vec scale = Vec() CHKERR( DMCreateInterpolation(self.dm, dm.dm, &A.mat, &scale.vec)) return(A, scale) def createInjection(self, DM dm): cdef Mat inject = Mat() CHKERR( DMCreateInjection(self.dm, dm.dm, &inject.mat) ) return inject def createRestriction(self, DM dm): cdef Mat mat = Mat() CHKERR( DMCreateRestriction(self.dm, dm.dm, &mat.mat) ) return mat def convert(self, dm_type): cdef PetscDMType cval = NULL dm_type = str2bytes(dm_type, &cval) cdef PetscDM newdm = NULL CHKERR( DMConvert(self.dm, cval, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm return dm def refine(self, comm=None): cdef MPI_Comm dmcomm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.dm, &dmcomm) ) dmcomm = def_Comm(comm, dmcomm) cdef PetscDM newdm = NULL CHKERR( DMRefine(self.dm, dmcomm, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm return dm def coarsen(self, comm=None): cdef MPI_Comm dmcomm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.dm, &dmcomm) ) dmcomm = def_Comm(comm, dmcomm) cdef PetscDM newdm = NULL CHKERR( DMCoarsen(self.dm, dmcomm, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm return dm def refineHierarchy(self, nlevels): cdef PetscInt i, n = asInt(nlevels) cdef PetscDM *newdmf = NULL cdef object tmp = oarray_p(empty_p(n), NULL, &newdmf) CHKERR( DMRefineHierarchy(self.dm, n, newdmf) ) cdef DM dmf = None cdef list hierarchy = [] for i from 0 <= i < n: dmf = subtype_DM(newdmf[i])() dmf.dm = newdmf[i] hierarchy.append(dmf) return hierarchy def coarsenHierarchy(self, nlevels): cdef PetscInt i, n = asInt(nlevels) cdef PetscDM *newdmc = NULL cdef object tmp = oarray_p(empty_p(n),NULL, &newdmc) CHKERR( DMCoarsenHierarchy(self.dm, n, newdmc) ) cdef DM dmc = None cdef list hierarchy = [] for i from 0 <= i < n: dmc = subtype_DM(newdmc[i])() dmc.dm = newdmc[i] hierarchy.append(dmc) return hierarchy def getRefineLevel(self): cdef PetscInt n = 0 CHKERR( DMGetRefineLevel(self.dm, &n) ) return toInt(n) def setRefineLevel(self, level): cdef PetscInt clevel = asInt(level) CHKERR( DMSetRefineLevel(self.dm, clevel) ) def getCoarsenLevel(self): cdef PetscInt n = 0 CHKERR( DMGetCoarsenLevel(self.dm, &n) ) return toInt(n) # def adaptLabel(self, label): cdef const char *cval = NULL cdef PetscDMLabel clbl = NULL label = str2bytes(label, &cval) CHKERR( DMGetLabel(self.dm, cval, &clbl) ) cdef DM newdm = DMPlex() CHKERR( DMAdaptLabel(self.dm, clbl, &newdm.dm) ) return newdm def adaptMetric(self, Vec metric, bdLabel=None, rgLabel=None): cdef const char *cval = NULL cdef PetscDMLabel cbdlbl = NULL cdef PetscDMLabel crglbl = NULL bdLabel = str2bytes(bdLabel, &cval) if cval == NULL: cval = b"" # XXX Should be fixed upstream CHKERR( DMGetLabel(self.dm, cval, &cbdlbl) ) rgLabel = str2bytes(rgLabel, &cval) if cval == NULL: cval = b"" # XXX Should be fixed upstream CHKERR( DMGetLabel(self.dm, cval, &crglbl) ) cdef DM newdm = DMPlex() CHKERR( DMAdaptMetric(self.dm, metric.vec, cbdlbl, crglbl, &newdm.dm) ) return newdm def getLabel(self, name): cdef const char *cname = NULL cdef DMLabel dmlabel = DMLabel() name = str2bytes(name, &cname) CHKERR( DMGetLabel(self.dm, cname, &dmlabel.dmlabel) ) PetscINCREF(dmlabel.obj) return dmlabel # def setSection(self, Section sec): CHKERR( DMSetSection(self.dm, sec.sec) ) def getSection(self): cdef Section sec = Section() CHKERR( DMGetSection(self.dm, &sec.sec) ) PetscINCREF(sec.obj) return sec def setLocalSection(self, Section sec): CHKERR( DMSetLocalSection(self.dm, sec.sec) ) def getLocalSection(self): cdef Section sec = Section() CHKERR( DMGetLocalSection(self.dm, &sec.sec) ) PetscINCREF(sec.obj) return sec def setGlobalSection(self, Section sec): CHKERR( DMSetGlobalSection(self.dm, sec.sec) ) def getGlobalSection(self): cdef Section sec = Section() CHKERR( DMGetGlobalSection(self.dm, &sec.sec) ) PetscINCREF(sec.obj) return sec setDefaultSection = setSection getDefaultSection = getSection setDefaultLocalSection = setLocalSection getDefaultLocalSection = getLocalSection setDefaultGlobalSection = setGlobalSection getDefaultGlobalSection = getGlobalSection def createSectionSF(self, Section localsec, Section globalsec): CHKERR( DMCreateSectionSF(self.dm, localsec.sec, globalsec.sec) ) def getSectionSF(self): cdef SF sf = SF() CHKERR( DMGetSectionSF(self.dm, &sf.sf) ) PetscINCREF(sf.obj) return sf def setSectionSF(self, SF sf): CHKERR( DMSetSectionSF(self.dm, sf.sf) ) createDefaultSF = createSectionSF getDefaultSF = getSectionSF setDefaultSF = setSectionSF def getPointSF(self): cdef SF sf = SF() CHKERR( DMGetPointSF(self.dm, &sf.sf) ) PetscINCREF(sf.obj) return sf def setPointSF(self, SF sf): CHKERR( DMSetPointSF(self.dm, sf.sf) ) def getNumLabels(self): cdef PetscInt nLabels = 0 CHKERR( DMGetNumLabels(self.dm, &nLabels) ) return toInt(nLabels) def getLabelName(self, index): cdef PetscInt cindex = asInt(index) cdef const char *cname = NULL CHKERR( DMGetLabelName(self.dm, cindex, &cname) ) return bytes2str(cname) def hasLabel(self, name): cdef PetscBool flag = PETSC_FALSE cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMHasLabel(self.dm, cname, &flag) ) return toBool(flag) def createLabel(self, name): cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMCreateLabel(self.dm, cname) ) def removeLabel(self, name): cdef const char *cname = NULL cdef PetscDMLabel clbl = NULL name = str2bytes(name, &cname) CHKERR( DMRemoveLabel(self.dm, cname, &clbl) ) # TODO: Once DMLabel is wrapped, this should return the label, like the C function. CHKERR( DMLabelDestroy(&clbl) ) def getLabelValue(self, name, point): cdef PetscInt cpoint = asInt(point), value = 0 cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMGetLabelValue(self.dm, cname, cpoint, &value) ) return toInt(value) def setLabelValue(self, name, point, value): cdef PetscInt cpoint = asInt(point), cvalue = asInt(value) cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMSetLabelValue(self.dm, cname, cpoint, cvalue) ) def clearLabelValue(self, name, point, value): cdef PetscInt cpoint = asInt(point), cvalue = asInt(value) cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMClearLabelValue(self.dm, cname, cpoint, cvalue) ) def getLabelSize(self, name): cdef PetscInt size = 0 cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMGetLabelSize(self.dm, cname, &size) ) return toInt(size) def getLabelIdIS(self, name): cdef const char *cname = NULL name = str2bytes(name, &cname) cdef IS lis = IS() CHKERR( DMGetLabelIdIS(self.dm, cname, &lis.iset) ) return lis def getStratumSize(self, name, value): cdef PetscInt size = 0 cdef PetscInt cvalue = asInt(value) cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMGetStratumSize(self.dm, cname, cvalue, &size) ) return toInt(size) def getStratumIS(self, name, value): cdef PetscInt cvalue = asInt(value) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef IS sis = IS() CHKERR( DMGetStratumIS(self.dm, cname, cvalue, &sis.iset) ) return sis def clearLabelStratum(self, name, value): cdef PetscInt cvalue = asInt(value) cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMClearLabelStratum(self.dm, cname, cvalue) ) def setLabelOutput(self, name, output): cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscBool coutput = output CHKERR( DMSetLabelOutput(self.dm, cname, coutput) ) def getLabelOutput(self, name): cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscBool coutput = PETSC_FALSE CHKERR( DMGetLabelOutput(self.dm, cname, &coutput) ) return coutput # backward compatibility createGlobalVector = createGlobalVec createLocalVector = createLocalVec getMatrix = createMatrix = createMat def setKSPComputeOperators(self, operators, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (operators, args, kargs) self.set_attr('__operators__', context) CHKERR( DMKSPSetComputeOperators(self.dm, KSP_ComputeOps, context) ) def createFieldDecomposition(self): cdef PetscInt clen = 0 cdef PetscIS *cis = NULL cdef PetscDM *cdm = NULL cdef char** cnamelist = NULL CHKERR( DMCreateFieldDecomposition(self.dm, &clen, &cnamelist, &cis, &cdm) ) cdef list isets = [ref_IS(cis[i]) for i from 0 <= i < clen] cdef list dms = [] cdef list names = [] cdef DM dm = None for i from 0 <= i < clen: if cdm != NULL: dm = subtype_DM(cdm[i])() dm.dm = cdm[i] PetscINCREF(dm.obj) dms.append(dm) else: dms.append(None) name = bytes2str(cnamelist[i]) names.append(name) CHKERR( PetscFree(cnamelist[i]) ) CHKERR( ISDestroy(&cis[i]) ) CHKERR( DMDestroy(&cdm[i]) ) CHKERR( PetscFree(cis) ) CHKERR( PetscFree(cdm) ) CHKERR( PetscFree(cnamelist) ) return (names, isets, dms) def setSNESFunction(self, function, args=None, kargs=None): 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( DMSNESSetFunction(self.dm, SNES_Function, context) ) else: CHKERR( DMSNESSetFunction(self.dm, NULL, NULL) ) def setSNESJacobian(self, jacobian, args=None, kargs=None): 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( DMSNESSetJacobian(self.dm, SNES_Jacobian, context) ) else: CHKERR( DMSNESSetJacobian(self.dm, NULL, NULL) ) def addCoarsenHook(self, coarsenhook, restricthook, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} if coarsenhook is not None: coarsencontext = (coarsenhook, args, kargs) coarsenhooks = self.get_attr('__coarsenhooks__') if coarsenhooks is None: coarsenhooks = [coarsencontext] CHKERR( DMCoarsenHookAdd(self.dm, DM_PyCoarsenHook, NULL, NULL) ) else: coarsenhooks.append(coarsencontext) self.set_attr('__coarsenhooks__', coarsenhooks) if restricthook is not None: restrictcontext = (restricthook, args, kargs) restricthooks = self.get_attr('__restricthooks__') if restricthooks is None: restricthooks = [restrictcontext] CHKERR( DMCoarsenHookAdd(self.dm, NULL, DM_PyRestrictHook, NULL) ) else: restricthooks.append(restrictcontext) self.set_attr('__restricthooks__', restricthooks) # --- application context --- property appctx: def __get__(self): return self.getAppCtx() def __set__(self, value): self.setAppCtx(value) # --- discretization space --- property ds: def __get__(self): return self.getDS() def __set__(self, value): self.setDS(value) # -------------------------------------------------------------------- del DMType del DMBoundaryType del DMPolytopeType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/DMComposite.pyx000066400000000000000000000074341454104047300216040ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class DMComposite(DM): def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMCompositeCreate(ccomm, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def addDM(self, DM dm, *args): """Add DM to composite""" CHKERR( DMCompositeAddDM(self.dm, dm.dm) ) cdef object item for item in args: dm = item CHKERR( DMCompositeAddDM(self.dm, dm.dm) ) def getNumber(self): """Get number of sub-DMs contained in the DMComposite""" cdef PetscInt n = 0 CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) return toInt(n) getNumberDM = getNumber def getEntries(self): """Get tuple of sub-DMs contained in the DMComposite""" cdef PetscInt i, n = 0 cdef PetscDM *cdms = NULL CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) cdef object tmp = oarray_p(empty_p(n), NULL, &cdms) CHKERR( DMCompositeGetEntriesArray(self.dm, cdms) ) cdef DM entry = None cdef list entries = [] for i from 0 <= i < n: entry = subtype_DM(cdms[i])() entry.dm = cdms[i] PetscINCREF(entry.obj) entries.append(entry) return tuple(entries) def scatter(self, Vec gvec, lvecs): """Scatter coupled global vector into split local vectors""" cdef PetscInt i, n = 0 CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) cdef PetscVec *clvecs = NULL cdef object tmp = oarray_p(empty_p(n), NULL, &clvecs) for i from 0 <= i < n: clvecs[i] = (lvecs[i]).vec CHKERR( DMCompositeScatterArray(self.dm, gvec.vec, clvecs) ) def gather(self, Vec gvec, imode, lvecs): """Gather split local vectors into coupled global vector""" cdef PetscInsertMode cimode = insertmode(imode) cdef PetscInt i, n = 0 CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) cdef PetscVec *clvecs = NULL cdef object tmp = oarray_p(empty_p(n), NULL, &clvecs) for i from 0 <= i < n: clvecs[i] = (lvecs[i]).vec CHKERR( DMCompositeGatherArray(self.dm, cimode, gvec.vec, clvecs) ) def getGlobalISs(self): cdef PetscInt i, n = 0 cdef PetscIS *cis = NULL CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) CHKERR( DMCompositeGetGlobalISs(self.dm, &cis) ) cdef object isets = [ref_IS(cis[i]) for i from 0 <= i < n] for i from 0 <= i < n: CHKERR( ISDestroy(&cis[i]) ) CHKERR( PetscFree(cis) ) return isets def getLocalISs(self): cdef PetscInt i, n = 0 cdef PetscIS *cis = NULL CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) CHKERR( DMCompositeGetLocalISs(self.dm, &cis) ) cdef object isets = [ref_IS(cis[i]) for i from 0 <= i < n] for i from 0 <= i < n: CHKERR( ISDestroy(&cis[i]) ) CHKERR( PetscFree(cis) ) return isets def getLGMaps(self): cdef PetscInt i, n = 0 cdef PetscLGMap *clgm = NULL CHKERR( DMCompositeGetNumberDM(self.dm, &n) ) CHKERR( DMCompositeGetISLocalToGlobalMappings(self.dm, &clgm) ) cdef object lgms = [ref_LGMap(clgm[i]) for i from 0 <= i < n] for i from 0 <= i < n: CHKERR( ISLocalToGlobalMappingDestroy(&clgm[i]) ) CHKERR( PetscFree(clgm) ) return lgms def getAccess(self, Vec gvec, locs=None): """Get access to specified parts of global vector. Use via 'with' context manager (PEP 343). """ return _DMComposite_access(self, gvec, locs) petsc4py-3.19.6/src/petsc4py/PETSc/DMDA.pyx000066400000000000000000000441401454104047300201210ustar00rootroot00000000000000# -------------------------------------------------------------------- class DMDAStencilType(object): STAR = DMDA_STENCIL_STAR BOX = DMDA_STENCIL_BOX class DMDAInterpolationType(object): Q0 = DMDA_INTERPOLATION_Q0 Q1 = DMDA_INTERPOLATION_Q1 class DMDAElementType(object): P1 = DMDA_ELEMENT_P1 Q1 = DMDA_ELEMENT_Q1 # -------------------------------------------------------------------- cdef class DMDA(DM): StencilType = DMDAStencilType InterpolationType = DMDAInterpolationType ElementType = DMDAElementType # def create(self, dim=None, dof=None, sizes=None, proc_sizes=None, boundary_type=None, stencil_type=None, stencil_width=None, bint setup=True, ownership_ranges=None, comm=None): # cdef object arg = None try: arg = tuple(dim) except TypeError: pass else: dim, sizes = None, arg # cdef PetscInt ndim = PETSC_DECIDE cdef PetscInt ndof = PETSC_DECIDE cdef PetscInt M = 1, m = PETSC_DECIDE, *lx = NULL cdef PetscInt N = 1, n = PETSC_DECIDE, *ly = NULL cdef PetscInt P = 1, p = PETSC_DECIDE, *lz = NULL cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE cdef PetscDMDAStencilType stype = DMDA_STENCIL_BOX cdef PetscInt swidth = PETSC_DECIDE # grid and proc sizes cdef object gsizes = sizes cdef object psizes = proc_sizes cdef PetscInt gdim = PETSC_DECIDE cdef PetscInt pdim = PETSC_DECIDE if sizes is not None: gdim = asDims(gsizes, &M, &N, &P) if psizes is not None: pdim = asDims(psizes, &m, &n, &p) if gdim>=0 and pdim>=0: assert gdim == pdim # dim and dof if dim is not None: ndim = asInt(dim) if dof is not None: ndof = asInt(dof) if ndim==PETSC_DECIDE: ndim = gdim if ndof==PETSC_DECIDE: ndof = 1 # vertex distribution if ownership_ranges is not None: ownership_ranges = asOwnershipRanges(ownership_ranges, ndim, &m, &n, &p, &lx, &ly, &lz) # periodicity, stencil type & width if boundary_type is not None: asBoundary(boundary_type, &btx, &bty, &btz) if stencil_type is not None: stype = asStencil(stencil_type) if stencil_width is not None: swidth = asInt(stencil_width) if setup and swidth == PETSC_DECIDE: swidth = 0 # create the DMDA object cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newda = NULL CHKERR( DMDACreateND(ccomm, ndim, ndof, M, N, P, m, n, p, lx, ly, lz, btx, bty, btz, stype, swidth, &newda) ) if setup and ndim > 0: CHKERR( DMSetUp(newda) ) PetscCLEAR(self.obj); self.dm = newda return self def duplicate(self, dof=None, boundary_type=None, stencil_type=None, stencil_width=None): cdef PetscInt ndim = 0, ndof = 0 cdef PetscInt M = 1, N = 1, P = 1 cdef PetscInt m = 1, n = 1, p = 1 cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE cdef PetscDMDAStencilType stype = DMDA_STENCIL_BOX cdef PetscInt swidth = PETSC_DECIDE CHKERR( DMDAGetInfo(self.dm, &ndim, &M, &N, &P, &m, &n, &p, &ndof, &swidth, &btx, &bty, &btz, &stype) ) cdef const PetscInt *lx = NULL, *ly = NULL, *lz = NULL CHKERR( DMDAGetOwnershipRanges(self.dm, &lx, &ly, &lz) ) cdef MPI_Comm comm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.dm, &comm) ) # if dof is not None: ndof = asInt(dof) if boundary_type is not None: asBoundary(boundary_type, &btx, &bty, &btz) if stencil_type is not None: stype = asStencil(stencil_type) if stencil_width is not None: swidth = asInt(stencil_width) # cdef DMDA da = DMDA() CHKERR( DMDACreateND(comm, ndim, ndof, M, N, P, m, n, p, lx, ly, lz, btx, bty, btz, stype, swidth, &da.dm) ) CHKERR( DMSetUp(da.dm) ) return da # def setDim(self, dim): return self.setDimension(dim) def getDim(self): return self.getDimension() def setDof(self, dof): cdef PetscInt ndof = asInt(dof) CHKERR( DMDASetDof(self.dm, ndof) ) def getDof(self): cdef PetscInt dof = 0 CHKERR( DMDAGetInfo(self.dm, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dof, NULL, NULL, NULL, NULL, NULL) ) return toInt(dof) def setSizes(self, sizes): cdef tuple gsizes = tuple(sizes) cdef PetscInt gdim = PETSC_DECIDE cdef PetscInt M = 1 cdef PetscInt N = 1 cdef PetscInt P = 1 gdim = asDims(gsizes, &M, &N, &P) cdef PetscInt dim = PETSC_DECIDE CHKERR( DMDAGetDim(self.dm, &dim) ) if dim == PETSC_DECIDE: CHKERR( DMSetDimension(self.dm, gdim) ) CHKERR( DMDASetSizes(self.dm, M, N, P) ) def getSizes(self): cdef PetscInt dim = 0 cdef PetscInt M = PETSC_DECIDE cdef PetscInt N = PETSC_DECIDE cdef PetscInt P = PETSC_DECIDE CHKERR( DMDAGetInfo(self.dm, &dim, &M, &N, &P, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) ) return toDims(dim, M, N, P) def setProcSizes(self, proc_sizes): cdef tuple psizes = tuple(proc_sizes) cdef PetscInt pdim = PETSC_DECIDE cdef PetscInt m = PETSC_DECIDE cdef PetscInt n = PETSC_DECIDE cdef PetscInt p = PETSC_DECIDE pdim = asDims(psizes, &m, &n, &p) cdef PetscInt dim = PETSC_DECIDE CHKERR( DMDAGetDim(self.dm, &dim) ) if dim == PETSC_DECIDE: CHKERR( DMSetDimension(self.dm, pdim) ) CHKERR( DMDASetNumProcs(self.dm, m, n, p) ) def getProcSizes(self): cdef PetscInt dim = 0 cdef PetscInt m = PETSC_DECIDE cdef PetscInt n = PETSC_DECIDE cdef PetscInt p = PETSC_DECIDE CHKERR( DMDAGetInfo(self.dm, &dim, NULL, NULL, NULL, &m, &n, &p, NULL, NULL, NULL, NULL, NULL, NULL) ) return toDims(dim, m, n, p) def setBoundaryType(self, boundary_type): cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE asBoundary(boundary_type, &btx, &bty, &btz) CHKERR( DMDASetBoundaryType(self.dm, btx, bty, btz) ) def getBoundaryType(self): cdef PetscInt dim = 0 cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE CHKERR( DMDAGetInfo(self.dm, &dim, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &btx, &bty, &btz, NULL) ) return toDims(dim, btx, bty, btz) def setStencilType(self, stencil_type): cdef PetscDMDAStencilType stype = asStencil(stencil_type) CHKERR( DMDASetStencilType(self.dm, stype) ) def getStencilType(self): cdef PetscDMDAStencilType stype = DMDA_STENCIL_BOX CHKERR( DMDAGetInfo(self.dm, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &stype) ) return stype def setStencilWidth(self, stencil_width): cdef PetscInt swidth = asInt(stencil_width) CHKERR( DMDASetStencilWidth(self.dm, swidth) ) def getStencilWidth(self): cdef PetscInt swidth = 0 CHKERR( DMDAGetInfo(self.dm, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &swidth, NULL, NULL, NULL, NULL) ) return toInt(swidth) def setStencil(self, stencil_type, stencil_width): cdef PetscDMDAStencilType stype = asStencil(stencil_type) cdef PetscInt swidth = asInt(stencil_width) CHKERR( DMDASetStencilType(self.dm, stype) ) CHKERR( DMDASetStencilWidth(self.dm, swidth) ) def getStencil(self): cdef PetscDMDAStencilType stype = DMDA_STENCIL_BOX cdef PetscInt swidth = 0 CHKERR( DMDAGetInfo(self.dm, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &swidth, NULL, NULL, NULL, &stype) ) return (toStencil(stype), toInt(swidth)) # def getRanges(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0 CHKERR( DMDAGetDim(self.dm, &dim) ) CHKERR( DMDAGetCorners(self.dm, &x, &y, &z, &m, &n, &p) ) return ((toInt(x), toInt(x+m)), (toInt(y), toInt(y+n)), (toInt(z), toInt(z+p)))[:dim] def getGhostRanges(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0 CHKERR( DMDAGetDim(self.dm, &dim) ) CHKERR( DMDAGetGhostCorners(self.dm, &x, &y, &z, &m, &n, &p) ) return ((toInt(x), toInt(x+m)), (toInt(y), toInt(y+n)), (toInt(z), toInt(z+p)))[:dim] def getOwnershipRanges(self): cdef PetscInt dim=0, m=0, n=0, p=0 cdef const PetscInt *lx = NULL, *ly = NULL, *lz = NULL CHKERR( DMDAGetInfo(self.dm, &dim, NULL, NULL, NULL, &m, &n, &p, NULL, NULL, NULL, NULL, NULL, NULL) ) CHKERR( DMDAGetOwnershipRanges(self.dm, &lx, &ly, &lz) ) return toOwnershipRanges(dim, m, n, p, lx, ly, lz) def getCorners(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0 CHKERR( DMDAGetDim(self.dm, &dim) ) CHKERR( DMDAGetCorners(self.dm, &x, &y, &z, &m, &n, &p) ) return ((toInt(x), toInt(y), toInt(z))[:dim], (toInt(m), toInt(n), toInt(p))[:dim]) def getGhostCorners(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0 CHKERR( DMDAGetDim(self.dm, &dim) ) CHKERR( DMDAGetGhostCorners(self.dm, &x, &y, &z, &m, &n, &p) ) return ((toInt(x), toInt(y), toInt(z))[:dim], (toInt(m), toInt(n), toInt(p))[:dim]) # def setFieldName(self, field, name): cdef PetscInt ival = asInt(field) cdef const char *cval = NULL name = str2bytes(name, &cval) CHKERR( DMDASetFieldName(self.dm, ival, cval) ) def getFieldName(self, field): cdef PetscInt ival = asInt(field) cdef const char *cval = NULL CHKERR( DMDAGetFieldName(self.dm, ival, &cval) ) return bytes2str(cval) # def getVecArray(self, Vec vec): return _DMDA_Vec_array(self, vec) # def setUniformCoordinates(self, xmin=0, xmax=1, ymin=0, ymax=1, zmin=0, zmax=1): cdef PetscReal _xmin = asReal(xmin), _xmax = asReal(xmax) cdef PetscReal _ymin = asReal(ymin), _ymax = asReal(ymax) cdef PetscReal _zmin = asReal(zmin), _zmax = asReal(zmax) CHKERR( DMDASetUniformCoordinates(self.dm, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax) ) def setCoordinateName(self, index, name): cdef PetscInt ival = asInt(index) cdef const char *cval = NULL name = str2bytes(name, &cval) CHKERR( DMDASetCoordinateName(self.dm, ival, cval) ) def getCoordinateName(self, index): cdef PetscInt ival = asInt(index) cdef const char *cval = NULL CHKERR( DMDAGetCoordinateName(self.dm, ival, &cval) ) return bytes2str(cval) # def createNaturalVec(self): cdef Vec vn = Vec() CHKERR( DMDACreateNaturalVector(self.dm, &vn.vec) ) return vn def globalToNatural(self, Vec vg, Vec vn, addv=None): cdef PetscInsertMode im = insertmode(addv) CHKERR( DMDAGlobalToNaturalBegin(self.dm, vg.vec, im, vn.vec) ) CHKERR( DMDAGlobalToNaturalEnd (self.dm, vg.vec, im, vn.vec) ) def naturalToGlobal(self, Vec vn, Vec vg, addv=None): cdef PetscInsertMode im = insertmode(addv) CHKERR( DMDANaturalToGlobalBegin(self.dm, vn.vec, im, vg.vec) ) CHKERR( DMDANaturalToGlobalEnd (self.dm, vn.vec, im, vg.vec) ) # def getAO(self): cdef AO ao = AO() CHKERR( DMDAGetAO(self.dm, &ao.ao) ) PetscINCREF(ao.obj) return ao def getScatter(self): cdef Scatter l2g = Scatter() cdef Scatter g2l = Scatter() CHKERR( DMDAGetScatter(self.dm, &l2g.sct, &g2l.sct) ) PetscINCREF(l2g.obj) PetscINCREF(g2l.obj) return (l2g, g2l) # def setRefinementFactor(self, refine_x=2, refine_y=2, refine_z=2): cdef PetscInt refine[3] refine[0] = asInt(refine_x) refine[1] = asInt(refine_y) refine[2] = asInt(refine_z) CHKERR( DMDASetRefinementFactor(self.dm, refine[0], refine[1], refine[2]) ) def getRefinementFactor(self): cdef PetscInt i, dim = 0, refine[3] CHKERR( DMDAGetDim(self.dm, &dim) ) CHKERR( DMDAGetRefinementFactor(self.dm, &refine[0], &refine[1], &refine[2]) ) return tuple([toInt(refine[i]) for 0 <= i < dim]) def setInterpolationType(self, interp_type): cdef PetscDMDAInterpolationType ival = dainterpolationtype(interp_type) CHKERR( DMDASetInterpolationType(self.dm, ival) ) def getInterpolationType(self): cdef PetscDMDAInterpolationType ival = DMDA_INTERPOLATION_Q0 CHKERR( DMDAGetInterpolationType(self.dm, &ival) ) return ival # def setElementType(self, elem_type): cdef PetscDMDAElementType ival = daelementtype(elem_type) CHKERR( DMDASetElementType(self.dm, ival) ) def getElementType(self): cdef PetscDMDAElementType ival = DMDA_ELEMENT_Q1 CHKERR( DMDAGetElementType(self.dm, &ival) ) return ival def getElements(self, elem_type=None): cdef PetscInt dim=0 cdef PetscDMDAElementType etype cdef PetscInt nel=0, nen=0 cdef const PetscInt *elems=NULL cdef object elements CHKERR( DMDAGetDim(self.dm, &dim) ) if elem_type is not None: etype = daelementtype(elem_type) CHKERR( DMDASetElementType(self.dm, etype) ) try: CHKERR( DMDAGetElements(self.dm, &nel, &nen, &elems) ) elements = array_i(nel*nen, elems) elements.shape = (toInt(nel), toInt(nen)) finally: CHKERR( DMDARestoreElements(self.dm, &nel, &nen, &elems) ) return elements # property dim: def __get__(self): return self.getDim() property dof: def __get__(self): return self.getDof() property sizes: def __get__(self): return self.getSizes() property proc_sizes: def __get__(self): return self.getProcSizes() property boundary_type: def __get__(self): return self.getBoundaryType() property stencil: def __get__(self): return self.getStencil() property stencil_type: def __get__(self): return self.getStencilType() property stencil_width: def __get__(self): return self.getStencilWidth() property ranges: def __get__(self): return self.getRanges() property ghost_ranges: def __get__(self): return self.getGhostRanges() property corners: def __get__(self): return self.getCorners() property ghost_corners: def __get__(self): return self.getGhostCorners() # backward compatibility createNaturalVector = createNaturalVec # backward compatibility alias DA = DMDA # -------------------------------------------------------------------- del DMDAStencilType del DMDAInterpolationType del DMDAElementType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/DMLabel.pyx000066400000000000000000000136641454104047300206630ustar00rootroot00000000000000 cdef class DMLabel(Object): def __cinit__(self): self.obj = &self.dmlabel self.dmlabel = NULL def destroy(self): CHKERR( DMLabelDestroy(&self.dmlabel) ) return self def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( DMLabelView(self.dmlabel, vwr) ) def create(self, name, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_SELF) cdef PetscDMLabel newdmlabel = NULL cdef const char *cname = NULL name = str2bytes(name, &cname) CHKERR( DMLabelCreate(ccomm, cname, &newdmlabel) ) PetscCLEAR(self.obj); self.dmlabel = newdmlabel return self def duplicate(self): cdef DMLabel new = DMLabel() CHKERR( DMLabelDuplicate(self.dmlabel, &new.dmlabel) ) return new def reset(self): CHKERR( DMLabelReset(self.dmlabel) ) def insertIS(self, IS iset, value): cdef PetscInt cvalue = asInt(value) CHKERR( DMLabelInsertIS(self.dmlabel, iset.iset, cvalue) ) return self def setValue(self, point, value): cdef PetscInt cpoint = asInt(point) cdef PetscInt cvalue = asInt(value) CHKERR( DMLabelSetValue(self.dmlabel, cpoint, cvalue) ) def getValue(self, point): cdef PetscInt cpoint = asInt(point) cdef PetscInt cvalue = 0 CHKERR( DMLabelGetValue(self.dmlabel, cpoint, &cvalue) ) return toInt(cvalue) def getDefaultValue(self): cdef PetscInt cvalue = 0 CHKERR( DMLabelGetDefaultValue(self.dmlabel, &cvalue) ) return toInt(cvalue) def setDefaultValue(self, value): cdef PetscInt cvalue = asInt(value) CHKERR( DMLabelSetDefaultValue(self.dmlabel, cvalue) ) def clearValue(self, point, value): cdef PetscInt cpoint = asInt(point) cdef PetscInt cvalue = asInt(value) CHKERR( DMLabelClearValue(self.dmlabel, cpoint, cvalue) ) def addStratum(self, value): cdef PetscInt cvalue = asInt(value) CHKERR( DMLabelAddStratum(self.dmlabel, cvalue) ) def addStrata(self, strata): cdef PetscInt *istrata = NULL cdef PetscInt numStrata = 0 fields = iarray_i(strata, &numStrata, &istrata) CHKERR( DMLabelAddStrata(self.dmlabel, numStrata, istrata) ) def addStrataIS(self, IS iset): CHKERR( DMLabelAddStrataIS(self.dmlabel, iset.iset) ) def getNumValues(self): cdef PetscInt numValues = 0 CHKERR( DMLabelGetNumValues(self.dmlabel, &numValues) ) return toInt(numValues) def getValueIS(self): cdef IS iset = IS() CHKERR( DMLabelGetValueIS(self.dmlabel, &iset.iset) ) return iset def stratumHasPoint(self, value, point): cdef PetscInt cpoint = asInt(point) cdef PetscInt cvalue = asInt(value) cdef PetscBool ccontains = PETSC_FALSE CHKERR( DMLabelStratumHasPoint(self.dmlabel, cvalue, cpoint, &ccontains) ) return toBool(ccontains) def hasStratum(self, value): cdef PetscInt cvalue = asInt(value) cdef PetscBool cexists = PETSC_FALSE CHKERR( DMLabelHasStratum(self.dmlabel, cvalue, &cexists) ) return toBool(cexists) def getStratumSize(self, stratum): cdef PetscInt cstratum = asInt(stratum) cdef PetscInt csize = 0 CHKERR( DMLabelGetStratumSize(self.dmlabel, stratum, &csize) ) return toInt(csize) def getStratumIS(self, stratum): cdef PetscInt cstratum = asInt(stratum) cdef IS iset = IS() CHKERR( DMLabelGetStratumIS(self.dmlabel, cstratum, &iset.iset) ) return iset def setStratumIS(self, stratum, IS iset): cdef PetscInt cstratum = asInt(stratum) CHKERR( DMLabelSetStratumIS(self.dmlabel, cstratum, iset.iset) ) def clearStratum(self, stratum): cdef PetscInt cstratum = asInt(stratum) CHKERR( DMLabelClearStratum(self.dmlabel, cstratum) ) def computeIndex(self): CHKERR( DMLabelComputeIndex(self.dmlabel) ) def createIndex(self, pStart, pEnd): cdef PetscInt cpstart = 0, cpend = 0 CHKERR( DMLabelCreateIndex(self.dmlabel, cpstart, cpend) ) def destroyIndex(self): CHKERR( DMLabelDestroyIndex(self.dmlabel) ) def hasValue(self, value): cdef PetscInt cvalue = asInt(value) cdef PetscBool cexists = PETSC_FALSE CHKERR( DMLabelHasValue(self.dmlabel, cvalue, &cexists) ) return toBool(cexists) def hasPoint(self, point): cdef PetscInt cpoint = asInt(point) cdef PetscBool cexists = PETSC_FALSE CHKERR( DMLabelHasPoint(self.dmlabel, cpoint, &cexists) ) return toBool(cexists) def getBounds(self): cdef PetscInt cpstart = 0, cpend = 0 CHKERR( DMLabelGetBounds(self.dmlabel, &cpstart, &cpend) ) return toInt(cpstart), toInt(cpend) def filter(self, start, end): cdef PetscInt cstart = 0, cend = 0 CHKERR( DMLabelFilter(self.dmlabel, cstart, cend) ) def permute(self, IS permutation): cdef DMLabel new = DMLabel() CHKERR( DMLabelPermute(self.dmlabel, permutation.iset, &new.dmlabel) ) return new def distribute(self, SF sf): cdef DMLabel new = DMLabel() CHKERR( DMLabelDistribute(self.dmlabel, sf.sf, &new.dmlabel) ) return new def gather(self, SF sf): cdef DMLabel new = DMLabel() CHKERR( DMLabelGather(self.dmlabel, sf.sf, &new.dmlabel) ) return new def convertToSection(self): cdef Section section = Section() cdef IS iset = IS() CHKERR( DMLabelConvertToSection(self.dmlabel, §ion.sec, &iset.iset) ) return section, iset def getNonEmptyStratumValuesIS(self): cdef IS iset = IS() CHKERR( DMLabelGetNonEmptyStratumValuesIS(self.dmlabel, &iset.iset) ) return iset petsc4py-3.19.6/src/petsc4py/PETSc/DMPlex.pyx000066400000000000000000001214451454104047300205510ustar00rootroot00000000000000# -------------------------------------------------------------------- class DMPlexReorderDefaultFlag(object): NOTSET = DMPLEX_REORDER_DEFAULT_NOTSET FALSE = DMPLEX_REORDER_DEFAULT_FALSE TRUE = DMPLEX_REORDER_DEFAULT_TRUE # -------------------------------------------------------------------- cdef class DMPlex(DM): ReorderDefaultFlag = DMPlexReorderDefaultFlag # def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMPlexCreate(ccomm, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createFromCellList(self, dim, cells, coords, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef PetscInt cdim = asInt(dim) cdef PetscInt numCells = 0 cdef PetscInt numCorners = 0 cdef PetscInt *cellVertices = NULL cdef PetscInt numVertices = 0 cdef PetscInt spaceDim= 0 cdef PetscReal *vertexCoords = NULL cdef int npy_flags = NPY_ARRAY_ALIGNED|NPY_ARRAY_NOTSWAPPED|NPY_ARRAY_CARRAY cells = PyArray_FROM_OTF(cells, NPY_PETSC_INT, npy_flags) coords = PyArray_FROM_OTF(coords, NPY_PETSC_REAL, npy_flags) if PyArray_NDIM(cells) != 2: raise ValueError( ("cell indices must have two dimensions: " "cells.ndim=%d") % (PyArray_NDIM(cells)) ) if PyArray_NDIM(coords) != 2: raise ValueError( ("coords vertices must have two dimensions: " "coords.ndim=%d") % (PyArray_NDIM(coords)) ) numCells = PyArray_DIM(cells, 0) numCorners = PyArray_DIM(cells, 1) numVertices = PyArray_DIM(coords, 0) spaceDim = PyArray_DIM(coords, 1) cellVertices = PyArray_DATA(cells) vertexCoords = PyArray_DATA(coords) CHKERR( DMPlexCreateFromCellListPetsc(ccomm, cdim, numCells, numVertices, numCorners, interp, cellVertices, spaceDim, vertexCoords, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createBoxMesh(self, faces, lower=(0,0,0), upper=(1,1,1), simplex=True, periodic=False, interpolate=True, comm=None): cdef Py_ssize_t i = 0 cdef PetscInt dim = 0, *cfaces = NULL faces = iarray_i(faces, &dim, &cfaces) assert dim >= 1 and dim <= 3 cdef PetscReal clower[3] clower[0] = clower[1] = clower[2] = 0 for i from 0 <= i < dim: clower[i] = lower[i] cdef PetscReal cupper[3] cupper[0] = cupper[1] = cupper[2] = 1 for i from 0 <= i < dim: cupper[i] = upper[i] cdef PetscDMBoundaryType btype[3]; asBoundary(periodic, &btype[0], &btype[1], &btype[2]) cdef PetscBool csimplex = simplex cdef PetscBool cinterp = interpolate cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMPlexCreateBoxMesh(ccomm, dim, csimplex, cfaces, clower, cupper, btype, cinterp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createBoxSurfaceMesh(self, faces, lower=(0,0,0), upper=(1,1,1), interpolate=True, comm=None): cdef Py_ssize_t i = 0 cdef PetscInt dim = 0, *cfaces = NULL faces = iarray_i(faces, &dim, &cfaces) assert dim >= 1 and dim <= 3 cdef PetscReal clower[3] clower[0] = clower[1] = clower[2] = 0 for i from 0 <= i < dim: clower[i] = lower[i] cdef PetscReal cupper[3] cupper[0] = cupper[1] = cupper[2] = 1 for i from 0 <= i < dim: cupper[i] = upper[i] cdef PetscBool cinterp = interpolate cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMPlexCreateBoxSurfaceMesh(ccomm, dim, cfaces, clower, cupper, cinterp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createFromFile(self, filename, plexname="unnamed", interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef const char *cfile = NULL cdef const char *pname = NULL filename = str2bytes(filename, &cfile) plexname = str2bytes(plexname, &pname) CHKERR( DMPlexCreateFromFile(ccomm, cfile, pname, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createCGNS(self, cgid, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef PetscInt ccgid = asInt(cgid) CHKERR( DMPlexCreateCGNS(ccomm, ccgid, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createCGNSFromFile(self, filename, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef const char *cfile = NULL filename = str2bytes(filename, &cfile) CHKERR( DMPlexCreateCGNSFromFile(ccomm, cfile, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createExodusFromFile(self, filename, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef const char *cfile = NULL filename = str2bytes(filename, &cfile) CHKERR( DMPlexCreateExodusFromFile(ccomm, cfile, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createExodus(self, exoid, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL cdef PetscInt cexoid = asInt(exoid) CHKERR( DMPlexCreateExodus(ccomm, cexoid, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createGmsh(self, Viewer viewer, interpolate=True, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool interp = interpolate cdef PetscDM newdm = NULL CHKERR( DMPlexCreateGmsh(ccomm, viewer.vwr, interp, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def createCohesiveSubmesh(self, hasLagrange, value): cdef PetscBool flag = hasLagrange cdef PetscInt cvalue = asInt(value) cdef DM subdm = DMPlex() CHKERR( DMPlexCreateCohesiveSubmesh(self.dm, flag, NULL, cvalue, &subdm.dm) ) return subdm def getChart(self): cdef PetscInt pStart = 0, pEnd = 0 CHKERR( DMPlexGetChart(self.dm, &pStart, &pEnd) ) return toInt(pStart), toInt(pEnd) def setChart(self, pStart, pEnd): cdef PetscInt cStart = asInt(pStart) cdef PetscInt cEnd = asInt(pEnd) CHKERR( DMPlexSetChart(self.dm, cStart, cEnd) ) def getConeSize(self, p): cdef PetscInt cp = asInt(p) cdef PetscInt pStart = 0, pEnd = 0 CHKERR( DMPlexGetChart(self.dm, &pStart, &pEnd) ) assert cp>=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cp=pStart and cpsec.sec, &ccomm) ) CHKERR( PetscSectionCreate(ccomm, &newsec.sec) ) if newvec.vec == NULL: CHKERR( PetscObjectGetComm(vec.vec, &ccomm) ) CHKERR( VecCreate(ccomm, &newvec.vec) ) CHKERR( DMPlexDistributeField(self.dm, sf.sf, sec.sec, vec.vec, newsec.sec, newvec.vec)) return (newsec, newvec) def getMinRadius(self): cdef PetscReal cminradius = 0. CHKERR( DMPlexGetMinRadius(self.dm, &cminradius)) return asReal(cminradius) def createCoarsePointIS(self): cdef IS fpoint = IS() CHKERR( DMPlexCreateCoarsePointIS(self.dm, &fpoint.iset) ) return fpoint def createSection(self, numComp, numDof, bcField=None, bcComps=None, bcPoints=None, IS perm=None): # topological dimension cdef PetscInt dim = 0 CHKERR( DMGetDimension(self.dm, &dim) ) # components and DOFs cdef PetscInt ncomp = 0, ndof = 0 cdef PetscInt *icomp = NULL, *idof = NULL numComp = iarray_i(numComp, &ncomp, &icomp) numDof = iarray_i(numDof, &ndof, &idof) assert ndof == ncomp*(dim+1) # boundary conditions cdef PetscInt nbc = 0, i = 0 cdef PetscInt *bcfield = NULL cdef PetscIS *bccomps = NULL cdef PetscIS *bcpoints = NULL if bcField is not None: bcField = iarray_i(bcField, &nbc, &bcfield) if bcComps is not None: bcComps = list(bcComps) assert len(bcComps) == nbc tmp1 = oarray_p(empty_p(nbc), NULL, &bccomps) for i from 0 <= i < nbc: bccomps[i] = (bcComps[i]).iset if bcPoints is not None: bcPoints = list(bcPoints) assert len(bcPoints) == nbc tmp2 = oarray_p(empty_p(nbc), NULL, &bcpoints) for i from 0 <= i < nbc: bcpoints[i] = (bcPoints[i]).iset else: raise ValueError("bcPoints is a required argument") else: assert bcComps is None assert bcPoints is None # optional chart permutations cdef PetscIS cperm = NULL if perm is not None: cperm = perm.iset # create section cdef Section sec = Section() CHKERR( DMPlexCreateSection(self.dm, NULL, icomp, idof, nbc, bcfield, bccomps, bcpoints, cperm, &sec.sec) ) return sec def getPointLocal(self, point): cdef PetscInt start = 0, end = 0 cdef PetscInt cpoint = asInt(point) CHKERR( DMPlexGetPointLocal(self.dm, cpoint, &start, &end) ) return toInt(start), toInt(end) def getPointLocalField(self, point, field): cdef PetscInt start = 0, end = 0 cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) CHKERR( DMPlexGetPointLocalField(self.dm, cpoint, cfield, &start, &end) ) return toInt(start), toInt(end) def getPointGlobal(self, point): cdef PetscInt start = 0, end = 0 cdef PetscInt cpoint = asInt(point) CHKERR( DMPlexGetPointGlobal(self.dm, cpoint, &start, &end) ) return toInt(start), toInt(end) def getPointGlobalField(self, point, field): cdef PetscInt start = 0, end = 0 cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) CHKERR( DMPlexGetPointGlobalField(self.dm, cpoint, cfield, &start, &end) ) return toInt(start), toInt(end) def createClosureIndex(self, Section sec or None): cdef PetscSection csec = sec.sec if sec is not None else NULL CHKERR( DMPlexCreateClosureIndex(self.dm, csec) ) # def setRefinementUniform(self, refinementUniform=True): cdef PetscBool flag = refinementUniform CHKERR( DMPlexSetRefinementUniform(self.dm, flag) ) def getRefinementUniform(self): cdef PetscBool flag = PETSC_FALSE CHKERR( DMPlexGetRefinementUniform(self.dm, &flag) ) return toBool(flag) def setRefinementLimit(self, refinementLimit): cdef PetscReal rval = asReal(refinementLimit) CHKERR( DMPlexSetRefinementLimit(self.dm, rval) ) def getRefinementLimit(self): cdef PetscReal rval = 0.0 CHKERR( DMPlexGetRefinementLimit(self.dm, &rval) ) return toReal(rval) def getOrdering(self, otype): cdef PetscMatOrderingType cval = NULL cdef PetscDMLabel label = NULL otype = str2bytes(otype, &cval) cdef IS perm = IS() CHKERR( DMPlexGetOrdering(self.dm, cval, label, &perm.iset) ) return perm def permute(self, IS perm): cdef DMPlex dm = type(self)() CHKERR( DMPlexPermute(self.dm, perm.iset, &dm.dm) ) return dm def reorderGetDefault(self): cdef PetscDMPlexReorderDefaultFlag reorder = DMPLEX_REORDER_DEFAULT_NOTSET CHKERR( DMPlexReorderGetDefault(self.dm, &reorder) ) return reorder def reorderSetDefault(self, flag): cdef PetscDMPlexReorderDefaultFlag reorder = flag CHKERR( DMPlexReorderSetDefault(self.dm, reorder) ) return # def computeCellGeometryFVM(self, cell): cdef PetscInt cdim = 0 cdef PetscInt ccell = asInt(cell) CHKERR( DMGetCoordinateDim(self.dm, &cdim) ) cdef PetscReal vol = 0, centroid[3], normal[3] CHKERR( DMPlexComputeCellGeometryFVM(self.dm, ccell, &vol, centroid, normal) ) return (toReal(vol), array_r(cdim, centroid), array_r(cdim, normal)) def constructGhostCells(self, labelName=None): cdef const char *cname = NULL labelName = str2bytes(labelName, &cname) cdef PetscInt numGhostCells = 0 cdef PetscDM dmGhosted = NULL CHKERR( DMPlexConstructGhostCells(self.dm, cname, &numGhostCells, &dmGhosted)) PetscCLEAR(self.obj); self.dm = dmGhosted return toInt(numGhostCells) # Metric def metricSetFromOptions(self): CHKERR( DMPlexMetricSetFromOptions(self.dm) ) def metricSetUniform(self, PetscBool uniform): CHKERR( DMPlexMetricSetUniform(self.dm, uniform) ) def metricIsUniform(self): cdef PetscBool uniform = PETSC_FALSE CHKERR( DMPlexMetricIsUniform(self.dm, &uniform) ) return toBool(uniform) def metricSetIsotropic(self, PetscBool isotropic): CHKERR( DMPlexMetricSetIsotropic(self.dm, isotropic) ) def metricIsIsotropic(self): cdef PetscBool isotropic = PETSC_FALSE CHKERR( DMPlexMetricIsIsotropic(self.dm, &isotropic) ) return toBool(isotropic) def metricSetRestrictAnisotropyFirst(self, PetscBool restrictAnisotropyFirst): CHKERR( DMPlexMetricSetRestrictAnisotropyFirst(self.dm, restrictAnisotropyFirst) ) def metricRestrictAnisotropyFirst(self): cdef PetscBool restrictAnisotropyFirst = PETSC_FALSE CHKERR( DMPlexMetricRestrictAnisotropyFirst(self.dm, &restrictAnisotropyFirst) ) return toBool(restrictAnisotropyFirst) def metricSetNoInsertion(self, PetscBool noInsert): CHKERR( DMPlexMetricSetNoInsertion(self.dm, noInsert) ) def metricNoInsertion(self): cdef PetscBool noInsert = PETSC_FALSE CHKERR( DMPlexMetricNoInsertion(self.dm, &noInsert) ) return toBool(noInsert) def metricSetNoSwapping(self, PetscBool noSwap): CHKERR( DMPlexMetricSetNoSwapping(self.dm, noSwap) ) def metricNoSwapping(self): cdef PetscBool noSwap = PETSC_FALSE CHKERR( DMPlexMetricNoSwapping(self.dm, &noSwap) ) return toBool(noSwap) def metricSetNoMovement(self, PetscBool noMove): CHKERR( DMPlexMetricSetNoMovement(self.dm, noMove) ) def metricNoMovement(self): cdef PetscBool noMove = PETSC_FALSE CHKERR( DMPlexMetricNoMovement(self.dm, &noMove) ) return toBool(noMove) def metricSetNoSurf(self, PetscBool noSurf): CHKERR( DMPlexMetricSetNoSurf(self.dm, noSurf) ) def metricNoSurf(self): cdef PetscBool noSurf = PETSC_FALSE CHKERR( DMPlexMetricNoSurf(self.dm, &noSurf) ) return toBool(noSurf) def metricSetVerbosity(self, PetscInt verbosity): CHKERR( DMPlexMetricSetVerbosity(self.dm, verbosity) ) def metricGetVerbosity(self): cdef PetscInt verbosity CHKERR( DMPlexMetricGetVerbosity(self.dm, &verbosity) ) return verbosity def metricSetNumIterations(self, PetscInt numIter): CHKERR( DMPlexMetricSetNumIterations(self.dm, numIter) ) def metricGetNumIterations(self): cdef PetscInt numIter CHKERR( DMPlexMetricGetNumIterations(self.dm, &numIter) ) return numIter def metricSetMinimumMagnitude(self, PetscReal h_min): CHKERR( DMPlexMetricSetMinimumMagnitude(self.dm, h_min) ) def metricGetMinimumMagnitude(self): cdef PetscReal h_min CHKERR( DMPlexMetricGetMinimumMagnitude(self.dm, &h_min) ) return h_min def metricSetMaximumMagnitude(self, PetscReal h_max): CHKERR( DMPlexMetricSetMaximumMagnitude(self.dm, h_max) ) def metricGetMaximumMagnitude(self): cdef PetscReal h_max CHKERR( DMPlexMetricGetMaximumMagnitude(self.dm, &h_max) ) return h_max def metricSetMaximumAnisotropy(self, PetscReal a_max): CHKERR( DMPlexMetricSetMaximumAnisotropy(self.dm, a_max) ) def metricGetMaximumAnisotropy(self): cdef PetscReal a_max CHKERR( DMPlexMetricGetMaximumAnisotropy(self.dm, &a_max) ) return a_max def metricSetTargetComplexity(self, PetscReal targetComplexity): CHKERR( DMPlexMetricSetTargetComplexity(self.dm, targetComplexity) ) def metricGetTargetComplexity(self): cdef PetscReal targetComplexity CHKERR( DMPlexMetricGetTargetComplexity(self.dm, &targetComplexity) ) return targetComplexity def metricSetNormalizationOrder(self, PetscReal p): CHKERR( DMPlexMetricSetNormalizationOrder(self.dm, p) ) def metricGetNormalizationOrder(self): cdef PetscReal p CHKERR( DMPlexMetricGetNormalizationOrder(self.dm, &p) ) return p def metricSetGradationFactor(self, PetscReal beta): CHKERR( DMPlexMetricSetGradationFactor(self.dm, beta) ) def metricGetGradationFactor(self): cdef PetscReal beta CHKERR( DMPlexMetricGetGradationFactor(self.dm, &beta) ) return beta def metricSetHausdorffNumber(self, PetscReal hausd): CHKERR( DMPlexMetricSetHausdorffNumber(self.dm, hausd) ) def metricGetHausdorffNumber(self): cdef PetscReal hausd CHKERR( DMPlexMetricGetHausdorffNumber(self.dm, &hausd) ) return hausd def metricCreate(self, field=0): cdef Vec metric = Vec() CHKERR( DMPlexMetricCreate(self.dm, field, &metric.vec) ) return metric def metricCreateUniform(self, PetscReal alpha, field=0): cdef Vec metric = Vec() CHKERR( DMPlexMetricCreateUniform(self.dm, field, alpha, &metric.vec) ) return metric def metricCreateIsotropic(self, Vec indicator, field=0): cdef Vec metric = Vec() CHKERR( DMPlexMetricCreateIsotropic(self.dm, field, indicator.vec, &metric.vec) ) return metric def metricDeterminantCreate(self, field=0): cdef Vec determinant = Vec() cdef DM dmDet = DM() CHKERR( DMPlexMetricDeterminantCreate(self.dm, field, &determinant.vec, &dmDet.dm) ) return determinant def metricEnforceSPD(self, Vec metric, Vec ometric, Vec determinant, restrictSizes=False, restrictAnisotropy=False): cdef DM dmDet = DM() CHKERR( DMPlexMetricEnforceSPD(self.dm, metric.vec, restrictSizes, restrictAnisotropy, ometric.vec, determinant.vec) ) return (ometric, determinant) def metricNormalize(self, Vec metric, Vec ometric, Vec determinant, restrictSizes=True, restrictAnisotropy=True): CHKERR( DMPlexMetricNormalize(self.dm, metric.vec, restrictSizes, restrictAnisotropy, ometric.vec, determinant.vec) ) return (ometric, determinant) def metricAverage2(self, Vec metric1, Vec metric2, Vec metricAvg): CHKERR( DMPlexMetricAverage2(self.dm, metric1.vec, metric2.vec, metricAvg.vec) ) return metricAvg def metricAverage3(self, Vec metric1, Vec metric2, Vec metric3, Vec metricAvg): CHKERR( DMPlexMetricAverage3(self.dm, metric1.vec, metric2.vec, metric3.vec, metricAvg.vec) ) return metricAvg def metricIntersection2(self, Vec metric1, Vec metric2, Vec metricInt): CHKERR( DMPlexMetricIntersection2(self.dm, metric1.vec, metric2.vec, metricInt.vec) ) return metricInt def metricIntersection3(self, Vec metric1, Vec metric2, Vec metric3, Vec metricInt): CHKERR( DMPlexMetricIntersection3(self.dm, metric1.vec, metric2.vec, metric3.vec, metricInt.vec) ) return metricInt def computeGradientClementInterpolant(self, Vec locX, Vec locC): CHKERR( DMPlexComputeGradientClementInterpolant(self.dm, locX.vec, locC.vec) ) return locC # View def topologyView(self, Viewer viewer): CHKERR( DMPlexTopologyView(self.dm, viewer.vwr)) def coordinatesView(self, Viewer viewer): CHKERR( DMPlexCoordinatesView(self.dm, viewer.vwr)) def labelsView(self, Viewer viewer): CHKERR( DMPlexLabelsView(self.dm, viewer.vwr)) def sectionView(self, Viewer viewer, DM sectiondm): CHKERR( DMPlexSectionView(self.dm, viewer.vwr, sectiondm.dm)) def globalVectorView(self, Viewer viewer, DM sectiondm, Vec vec): CHKERR( DMPlexGlobalVectorView(self.dm, viewer.vwr, sectiondm.dm, vec.vec)) def localVectorView(self, Viewer viewer, DM sectiondm, Vec vec): CHKERR( DMPlexLocalVectorView(self.dm, viewer.vwr, sectiondm.dm, vec.vec)) # Load def topologyLoad(self, Viewer viewer): cdef SF sf = SF() CHKERR( DMPlexTopologyLoad(self.dm, viewer.vwr, &sf.sf)) return sf def coordinatesLoad(self, Viewer viewer, SF sfxc): CHKERR( DMPlexCoordinatesLoad(self.dm, viewer.vwr, sfxc.sf)) def labelsLoad(self, Viewer viewer, SF sfxc): CHKERR( DMPlexLabelsLoad(self.dm, viewer.vwr, sfxc.sf)) def sectionLoad(self, Viewer viewer, DM sectiondm, SF sfxc): cdef SF gsf = SF() cdef SF lsf = SF() CHKERR( DMPlexSectionLoad(self.dm, viewer.vwr, sectiondm.dm, sfxc.sf, &gsf.sf, &lsf.sf)) return gsf, lsf def globalVectorLoad(self, Viewer viewer, DM sectiondm, SF sf, Vec vec): CHKERR( DMPlexGlobalVectorLoad(self.dm, viewer.vwr, sectiondm.dm, sf.sf, vec.vec)) def localVectorLoad(self, Viewer viewer, DM sectiondm, SF sf, Vec vec): CHKERR( DMPlexLocalVectorLoad(self.dm, viewer.vwr, sectiondm.dm, sf.sf, vec.vec)) # -------------------------------------------------------------------- del DMPlexReorderDefaultFlag # -------------------------------------------------------------------- class DMPlexTransformType(object): REFINEREGULAR = S_(DMPLEXREFINEREGULAR) REFINEALFELD = S_(DMPLEXREFINEALFELD) REFINEPOWELLSABIN = S_(DMPLEXREFINEPOWELLSABIN) REFINEBOUNDARYLAYER = S_(DMPLEXREFINEBOUNDARYLAYER) REFINESBR = S_(DMPLEXREFINESBR) REFINETOBOX = S_(DMPLEXREFINETOBOX) REFINETOSIMPLEX = S_(DMPLEXREFINETOSIMPLEX) REFINE1D = S_(DMPLEXREFINE1D) EXTRUDE = S_(DMPLEXEXTRUDE) TRANSFORMFILTER = S_(DMPLEXTRANSFORMFILTER) cdef class DMPlexTransform(Object): def __cinit__(self): self.obj = &self.tr self.tr = NULL def apply(self, DM dm): cdef DMPlex newdm = DMPlex() CHKERR( DMPlexTransformApply(self.tr, dm.dm, &newdm.dm) ) return newdm def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDMPlexTransform newtr = NULL CHKERR( DMPlexTransformCreate(ccomm, &newtr) ) PetscCLEAR(self.obj) self.tr = newtr return self def destroy(self): CHKERR( DMPlexTransformDestroy(&self.tr) ) return self def getType(self): cdef PetscDMPlexTransformType cval = NULL CHKERR( DMPlexTransformGetType(self.tr, &cval) ) return bytes2str(cval) def setUp(self): CHKERR( DMPlexTransformSetUp(self.tr) ) return self def setType(self, tr_type): cdef PetscDMPlexTransformType cval = NULL tr_type = str2bytes(tr_type, &cval) CHKERR( DMPlexTransformSetType(self.tr, cval) ) def setDM(self, DM dm): CHKERR( DMPlexTransformSetDM(self.tr, dm.dm) ) def setFromOptions(self): CHKERR( DMPlexTransformSetFromOptions(self.tr) ) def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( DMPlexTransformView(self.tr, vwr) )petsc4py-3.19.6/src/petsc4py/PETSc/DMShell.pyx000066400000000000000000000214751454104047300207120ustar00rootroot00000000000000cdef class DMShell(DM): def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMShellCreate(ccomm, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm return self def setMatrix(self, Mat mat): CHKERR( DMShellSetMatrix(self.dm, mat.mat) ) def setGlobalVector(self, Vec gv): CHKERR( DMShellSetGlobalVector(self.dm, gv.vec) ) def setLocalVector(self, Vec lv): CHKERR( DMShellSetLocalVector(self.dm, lv.vec) ) def setCreateGlobalVector(self, create_gvec, args=None, kargs=None): if create_gvec is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_gvec, args, kargs) self.set_attr('__create_global_vector__', context) CHKERR( DMShellSetCreateGlobalVector(self.dm, DMSHELL_CreateGlobalVector) ) else: CHKERR( DMShellSetCreateGlobalVector(self.dm, NULL) ) def setCreateLocalVector(self, create_lvec, args=None, kargs=None): if create_lvec is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_lvec, args, kargs) self.set_attr('__create_local_vector__', context) CHKERR( DMShellSetCreateLocalVector(self.dm, DMSHELL_CreateLocalVector) ) else: CHKERR( DMShellSetCreateLocalVector(self.dm, NULL) ) def setGlobalToLocal(self, begin, end, begin_args=None, begin_kargs=None, end_args=None, end_kargs=None): cdef PetscDMShellXToYFunction cbegin = NULL, cend = NULL if begin is not None: if begin_args is None: begin_args = () if begin_kargs is None: begin_kargs = {} context = (begin, begin_args, begin_kargs) self.set_attr('__g2l_begin__', context) cbegin = &DMSHELL_GlobalToLocalBegin if end is not None: if end_args is None: end_args = () if end_kargs is None: end_kargs = {} context = (end, end_args, end_kargs) self.set_attr('__g2l_end__', context) cend = &DMSHELL_GlobalToLocalEnd CHKERR( DMShellSetGlobalToLocal(self.dm, cbegin, cend) ) def setGlobalToLocalVecScatter(self, Scatter gtol): CHKERR( DMShellSetGlobalToLocalVecScatter(self.dm, gtol.sct) ) def setLocalToGlobal(self, begin, end, begin_args=None, begin_kargs=None, end_args=None, end_kargs=None): cdef PetscDMShellXToYFunction cbegin = NULL, cend = NULL if begin is not None: if begin_args is None: begin_args = () if begin_kargs is None: begin_kargs = {} context = (begin, begin_args, begin_kargs) self.set_attr('__l2g_begin__', context) cbegin = &DMSHELL_LocalToGlobalBegin if end is not None: if end_args is None: end_args = () if end_kargs is None: end_kargs = {} context = (end, end_args, end_kargs) self.set_attr('__l2g_end__', context) cend = &DMSHELL_LocalToGlobalEnd CHKERR( DMShellSetLocalToGlobal(self.dm, cbegin, cend) ) def setLocalToGlobalVecScatter(self, Scatter ltog): CHKERR( DMShellSetLocalToGlobalVecScatter(self.dm, ltog.sct) ) def setLocalToLocal(self, begin, end, begin_args=None, begin_kargs=None, end_args=None, end_kargs=None): cdef PetscDMShellXToYFunction cbegin = NULL, cend = NULL cbegin = NULL cend = NULL if begin is not None: if begin_args is None: begin_args = () if begin_kargs is None: begin_kargs = {} context = (begin, begin_args, begin_kargs) self.set_attr('__l2l_begin__', context) cbegin = &DMSHELL_LocalToLocalBegin if end is not None: if end_args is None: end_args = () if end_kargs is None: end_kargs = {} context = (end, end_args, end_kargs) self.set_attr('__l2l_end__', context) cend = &DMSHELL_LocalToLocalEnd CHKERR( DMShellSetLocalToLocal(self.dm, cbegin, cend) ) def setLocalToLocalVecScatter(self, Scatter ltol): CHKERR( DMShellSetLocalToLocalVecScatter(self.dm, ltol.sct) ) def setCreateMatrix(self, create_matrix, args=None, kargs=None): if create_matrix is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_matrix, args, kargs) self.set_attr('__create_matrix__', context) CHKERR( DMShellSetCreateMatrix(self.dm, DMSHELL_CreateMatrix) ) else: CHKERR( DMShellSetCreateMatrix(self.dm, NULL) ) def setCoarsen(self, coarsen, args=None, kargs=None): if coarsen is not None: if args is None: args = () if kargs is None: kargs = {} context = (coarsen, args, kargs) self.set_attr('__coarsen__', context) CHKERR( DMShellSetCoarsen(self.dm, DMSHELL_Coarsen) ) else: CHKERR( DMShellSetCoarsen(self.dm, NULL) ) def setRefine(self, refine, args=None, kargs=None): if refine is not None: if args is None: args = () if kargs is None: kargs = {} context = (refine, args, kargs) self.set_attr('__refine__', context) CHKERR( DMShellSetRefine(self.dm, DMSHELL_Refine) ) else: CHKERR( DMShellSetRefine(self.dm, NULL) ) def setCreateInterpolation(self, create_interpolation, args=None, kargs=None): if create_interpolation is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_interpolation, args, kargs) self.set_attr('__create_interpolation__', context) CHKERR( DMShellSetCreateInterpolation(self.dm, DMSHELL_CreateInterpolation) ) else: CHKERR( DMShellSetCreateInterpolation(self.dm, NULL) ) def setCreateInjection(self, create_injection, args=None, kargs=None): if create_injection is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_injection, args, kargs) self.set_attr('__create_injection__', context) CHKERR( DMShellSetCreateInjection(self.dm, DMSHELL_CreateInjection) ) else: CHKERR( DMShellSetCreateInjection(self.dm, NULL) ) def setCreateRestriction(self, create_restriction, args=None, kargs=None): if create_restriction is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_restriction, args, kargs) self.set_attr('__create_restriction__', context) CHKERR( DMShellSetCreateRestriction(self.dm, DMSHELL_CreateRestriction) ) else: CHKERR( DMShellSetCreateRestriction(self.dm, NULL) ) def setCreateFieldDecomposition(self, decomp, args=None, kargs=None): if decomp is not None: if args is None: args = () if kargs is None: kargs = {} context = (decomp, args, kargs) self.set_attr('__create_field_decomp__', context) CHKERR( DMShellSetCreateFieldDecomposition(self.dm, DMSHELL_CreateFieldDecomposition) ) else: CHKERR( DMShellSetCreateFieldDecomposition(self.dm, NULL) ) def setCreateDomainDecomposition(self, decomp, args=None, kargs=None): if decomp is not None: if args is None: args = () if kargs is None: kargs = {} context = (decomp, args, kargs) self.set_attr('__create_domain_decomp__', context) CHKERR( DMShellSetCreateDomainDecomposition(self.dm, DMSHELL_CreateDomainDecomposition) ) else: CHKERR( DMShellSetCreateDomainDecomposition(self.dm, NULL) ) def setCreateDomainDecompositionScatters(self, scatter, args=None, kargs=None): if scatter is not None: if args is None: args = () if kargs is None: kargs = {} context = (scatter, args, kargs) self.set_attr('__create_domain_decomp_scatters__', context) CHKERR( DMShellSetCreateDomainDecompositionScatters(self.dm, DMSHELL_CreateDomainDecompositionScatters) ) else: CHKERR( DMShellSetCreateDomainDecompositionScatters(self.dm, NULL) ) def setCreateSubDM(self, create_subdm, args=None, kargs=None): if create_subdm is not None: if args is None: args = () if kargs is None: kargs = {} context = (create_subdm, args, kargs) self.set_attr('__create_subdm__', context) CHKERR( DMShellSetCreateSubDM(self.dm, DMSHELL_CreateSubDM) ) else: CHKERR( DMShellSetCreateSubDM(self.dm, NULL) ) petsc4py-3.19.6/src/petsc4py/PETSc/DMStag.pyx000066400000000000000000000343041454104047300205340ustar00rootroot00000000000000# -------------------------------------------------------------------- class DMStagStencilType(object): STAR = DMSTAG_STENCIL_STAR BOX = DMSTAG_STENCIL_BOX NONE = DMSTAG_STENCIL_NONE class DMStagStencilLocation(object): NULLLOC = DMSTAG_NULL_LOCATION BACK_DOWN_LEFT = DMSTAG_BACK_DOWN_LEFT BACK_DOWN = DMSTAG_BACK_DOWN BACK_DOWN_RIGHT = DMSTAG_BACK_DOWN_RIGHT BACK_LEFT = DMSTAG_BACK_LEFT BACK = DMSTAG_BACK BACK_RIGHT = DMSTAG_BACK_RIGHT BACK_UP_LEFT = DMSTAG_BACK_UP_LEFT BACK_UP = DMSTAG_BACK_UP BACK_UP_RIGHT = DMSTAG_BACK_UP_RIGHT DOWN_LEFT = DMSTAG_DOWN_LEFT DOWN = DMSTAG_DOWN DOWN_RIGHT = DMSTAG_DOWN_RIGHT LEFT = DMSTAG_LEFT ELEMENT = DMSTAG_ELEMENT RIGHT = DMSTAG_RIGHT UP_LEFT = DMSTAG_UP_LEFT UP = DMSTAG_UP UP_RIGHT = DMSTAG_UP_RIGHT FRONT_DOWN_LEFT = DMSTAG_FRONT_DOWN_LEFT FRONT_DOWN = DMSTAG_FRONT_DOWN FRONT_DOWN_RIGHT = DMSTAG_FRONT_DOWN_RIGHT FRONT_LEFT = DMSTAG_FRONT_LEFT FRONT = DMSTAG_FRONT FRONT_RIGHT = DMSTAG_FRONT_RIGHT FRONT_UP_LEFT = DMSTAG_FRONT_UP_LEFT FRONT_UP = DMSTAG_FRONT_UP FRONT_UP_RIGHT = DMSTAG_FRONT_UP_RIGHT # -------------------------------------------------------------------- cdef class DMStag(DM): StencilType = DMStagStencilType StencilLocation = DMStagStencilLocation def create(self, dim, dofs=None, sizes=None, boundary_types=None, stencil_type=None, stencil_width=None, proc_sizes=None, ownership_ranges=None, comm=None, setUp=False): # ndim cdef PetscInt ndim = asInt(dim) # sizes cdef object gsizes = sizes cdef PetscInt nsizes=PETSC_DECIDE, M=1, N=1, P=1 if sizes is not None: nsizes = asStagDims(gsizes, &M, &N, &P) assert(nsizes==ndim) # dofs cdef object cdofs = dofs cdef PetscInt ndofs=PETSC_DECIDE, dof0=1, dof1=0, dof2=0, dof3=0 if dofs is not None: ndofs = asDofs(cdofs, &dof0, &dof1, &dof2, &dof3) assert(ndofs==ndim+1) # boundary types cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE asBoundary(boundary_types, &btx, &bty, &btz) # stencil cdef PetscInt swidth = 0 if stencil_width is not None: swidth = asInt(stencil_width) cdef PetscDMStagStencilType stype = DMSTAG_STENCIL_NONE if stencil_type is not None: stype = asStagStencil(stencil_type) # comm cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) # proc sizes cdef object psizes = proc_sizes cdef PetscInt nprocs=PETSC_DECIDE, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE if proc_sizes is not None: nprocs = asStagDims(psizes, &m, &n, &p) assert(nprocs==ndim) # ownership ranges cdef PetscInt *lx = NULL, *ly = NULL, *lz = NULL if ownership_ranges is not None: nranges = asStagOwnershipRanges(ownership_ranges, ndim, &m, &n, &p, &lx, &ly, &lz) assert(nranges==ndim) # create cdef PetscDM newda = NULL if dim == 1: CHKERR( DMStagCreate1d(ccomm, btx, M, dof0, dof1, stype, swidth, lx, &newda) ) if dim == 2: CHKERR( DMStagCreate2d(ccomm, btx, bty, M, N, m, n, dof0, dof1, dof2, stype, swidth, lx, ly, &newda) ) if dim == 3: CHKERR( DMStagCreate3d(ccomm, btx, bty, btz, M, N, P, m, n, p, dof0, dof1, dof2, dof3, stype, swidth, lx, ly, lz, &newda) ) PetscCLEAR(self.obj); self.dm = newda if setUp: CHKERR( DMSetUp(self.dm) ) return self # Setters def setStencilWidth(self,swidth): cdef PetscInt sw = asInt(swidth) CHKERR( DMStagSetStencilWidth(self.dm, sw) ) def setStencilType(self, stenciltype): cdef PetscDMStagStencilType stype = asStagStencil(stenciltype) CHKERR( DMStagSetStencilType(self.dm, stype) ) def setBoundaryTypes(self, boundary_types): cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE asBoundary(boundary_types, &btx, &bty, &btz) CHKERR( DMStagSetBoundaryTypes(self.dm, btx, bty, btz) ) def setDof(self, dofs): cdef tuple gdofs = tuple(dofs) cdef PetscInt gdim=PETSC_DECIDE, dof0=1, dof1=0, dof2=0, dof3=0 gdim = asDofs(gdofs, &dof0, &dof1, &dof2, &dof3) CHKERR( DMStagSetDOF(self.dm, dof0, dof1, dof2, dof3) ) def setGlobalSizes(self, sizes): cdef tuple gsizes = tuple(sizes) cdef PetscInt gdim=PETSC_DECIDE, M=1, N=1, P=1 gdim = asStagDims(gsizes, &M, &N, &P) CHKERR( DMStagSetGlobalSizes(self.dm, M, N, P) ) def setProcSizes(self, sizes): cdef tuple psizes = tuple(sizes) cdef PetscInt pdim=PETSC_DECIDE, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE pdim = asStagDims(psizes, &m, &n, &p) CHKERR( DMStagSetNumRanks(self.dm, m, n, p) ) def setOwnershipRanges(self, ranges): cdef PetscInt dim=0, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE cdef PetscInt *lx = NULL, *ly = NULL, *lz = NULL CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetNumRanks(self.dm, &m, &n, &p) ) ownership_ranges = asStagOwnershipRanges(ranges, dim, &m, &n, &p, &lx, &ly, &lz) CHKERR( DMStagSetOwnershipRanges(self.dm, lx, ly, lz) ) # Getters def getDim(self): return self.getDimension() def getEntriesPerElement(self): cdef PetscInt epe=0 CHKERR( DMStagGetEntriesPerElement(self.dm, &epe) ) return toInt(epe) def getStencilWidth(self): cdef PetscInt swidth=0 CHKERR( DMStagGetStencilWidth(self.dm, &swidth) ) return toInt(swidth) def getDof(self): cdef PetscInt dim=0, dof0=0, dof1=0, dof2=0, dof3=0 CHKERR( DMStagGetDOF(self.dm, &dof0, &dof1, &dof2, &dof3) ) CHKERR( DMGetDimension(self.dm, &dim) ) return toDofs(dim+1,dof0,dof1,dof2,dof3) def getCorners(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0, nExtrax=0, nExtray=0, nExtraz=0 CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetCorners(self.dm, &x, &y, &z, &m, &n, &p, &nExtrax, &nExtray, &nExtraz) ) return (asInt(x), asInt(y), asInt(z))[:dim], (asInt(m), asInt(n), asInt(p))[:dim], (asInt(nExtrax), asInt(nExtray), asInt(nExtraz))[:dim] def getGhostCorners(self): cdef PetscInt dim=0, x=0, y=0, z=0, m=0, n=0, p=0 CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetGhostCorners(self.dm, &x, &y, &z, &m, &n, &p) ) return (asInt(x), asInt(y), asInt(z))[:dim], (asInt(m), asInt(n), asInt(p))[:dim] def getLocalSizes(self): cdef PetscInt dim=0, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetLocalSizes(self.dm, &m, &n, &p) ) return toStagDims(dim, m, n, p) def getGlobalSizes(self): cdef PetscInt dim=0, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetGlobalSizes(self.dm, &m, &n, &p) ) return toStagDims(dim, m, n, p) def getProcSizes(self): cdef PetscInt dim=0, m=PETSC_DECIDE, n=PETSC_DECIDE, p=PETSC_DECIDE CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetNumRanks(self.dm, &m, &n, &p) ) return toStagDims(dim, m, n, p) def getStencilType(self): cdef PetscDMStagStencilType stype = DMSTAG_STENCIL_BOX CHKERR( DMStagGetStencilType(self.dm, &stype) ) return toStagStencil(stype) def getOwnershipRanges(self): cdef PetscInt dim=0, m=0, n=0, p=0 cdef const PetscInt *lx = NULL, *ly = NULL, *lz = NULL CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetNumRanks(self.dm, &m, &n, &p) ) CHKERR( DMStagGetOwnershipRanges(self.dm, &lx, &ly, &lz) ) return toStagOwnershipRanges(dim, m, n, p, lx, ly, lz) def getBoundaryTypes(self): cdef PetscInt dim=0 cdef PetscDMBoundaryType btx = DM_BOUNDARY_NONE cdef PetscDMBoundaryType bty = DM_BOUNDARY_NONE cdef PetscDMBoundaryType btz = DM_BOUNDARY_NONE CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetBoundaryTypes(self.dm, &btx, &bty, &btz) ) return toStagBoundaryTypes(dim, btx, bty, btz) def getIsFirstRank(self): cdef PetscBool rank0=PETSC_FALSE, rank1=PETSC_FALSE, rank2=PETSC_FALSE cdef PetscInt dim=0 CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetIsFirstRank(self.dm, &rank0, &rank1, &rank2) ) return toStagDims(dim, rank0, rank1, rank2) def getIsLastRank(self): cdef PetscBool rank0=PETSC_FALSE, rank1=PETSC_FALSE, rank2=PETSC_FALSE cdef PetscInt dim=0 CHKERR( DMGetDimension(self.dm, &dim) ) CHKERR( DMStagGetIsLastRank(self.dm, &rank0, &rank1, &rank2) ) return toStagDims(dim, rank0, rank1, rank2) # Coordinate-related functions def setUniformCoordinatesExplicit(self, xmin=0, xmax=1, ymin=0, ymax=1, zmin=0, zmax=1): cdef PetscReal _xmin = asReal(xmin), _xmax = asReal(xmax) cdef PetscReal _ymin = asReal(ymin), _ymax = asReal(ymax) cdef PetscReal _zmin = asReal(zmin), _zmax = asReal(zmax) CHKERR( DMStagSetUniformCoordinatesExplicit(self.dm, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax) ) def setUniformCoordinatesProduct(self, xmin=0, xmax=1, ymin=0, ymax=1, zmin=0, zmax=1): cdef PetscReal _xmin = asReal(xmin), _xmax = asReal(xmax) cdef PetscReal _ymin = asReal(ymin), _ymax = asReal(ymax) cdef PetscReal _zmin = asReal(zmin), _zmax = asReal(zmax) CHKERR( DMStagSetUniformCoordinatesProduct(self.dm, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax) ) def setUniformCoordinates(self, xmin=0, xmax=1, ymin=0, ymax=1, zmin=0, zmax=1): cdef PetscReal _xmin = asReal(xmin), _xmax = asReal(xmax) cdef PetscReal _ymin = asReal(ymin), _ymax = asReal(ymax) cdef PetscReal _zmin = asReal(zmin), _zmax = asReal(zmax) CHKERR( DMStagSetUniformCoordinates(self.dm, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax) ) def setCoordinateDMType(self, dmtype): cdef PetscDMType cval = NULL dmtype = str2bytes(dmtype, &cval) CHKERR( DMStagSetCoordinateDMType(self.dm, cval) ) # Location slot related functions def getLocationSlot(self, loc, c): cdef PetscInt slot=0 cdef PetscInt comp=asInt(c) cdef PetscDMStagStencilLocation sloc = asStagStencilLocation(loc) CHKERR( DMStagGetLocationSlot(self.dm, sloc, comp, &slot) ) return toInt(slot) def getProductCoordinateLocationSlot(self, loc): cdef PetscInt slot=0 cdef PetscDMStagStencilLocation sloc = asStagStencilLocation(loc) CHKERR( DMStagGetProductCoordinateLocationSlot(self.dm, sloc, &slot) ) return toInt(slot) def getLocationDof(self, loc): cdef PetscInt dof=0 cdef PetscDMStagStencilLocation sloc = asStagStencilLocation(loc) CHKERR( DMStagGetLocationDOF(self.dm, sloc, &dof) ) return toInt(dof) # Random other functions def migrateVec(self, Vec vec, DM dmTo, Vec vecTo): CHKERR( DMStagMigrateVec(self.dm, vec.vec, dmTo.dm, vecTo.vec ) ) def createCompatibleDMStag(self, dofs): cdef tuple gdofs = tuple(dofs) cdef PetscInt gdim=PETSC_DECIDE, dof0=1, dof1=0, dof2=0, dof3=0 gdim = asDofs(gdofs, &dof0, &dof1, &dof2, &dof3) cdef PetscDM newda = NULL CHKERR( DMStagCreateCompatibleDMStag(self.dm, dof0, dof1, dof2, dof3, &newda) ) cdef DM newdm = type(self)() PetscCLEAR(newdm.obj); newdm.dm = newda return newdm def VecSplitToDMDA(self, Vec vec, loc, c): cdef PetscInt pc = asInt(c) cdef PetscDMStagStencilLocation sloc = asStagStencilLocation(loc) cdef PetscDM pda = NULL cdef PetscVec pdavec = NULL CHKERR( DMStagVecSplitToDMDA(self.dm, vec.vec, sloc, pc, &pda, &pdavec) ) cdef DM da = DMDA() PetscCLEAR(da.obj); da.dm = pda cdef Vec davec = Vec() PetscCLEAR(davec.obj); davec.vec = pdavec return (da,davec) def getVecArray(self, Vec vec): raise NotImplementedError('getVecArray for DMStag not yet implemented in petsc4py') def get1dCoordinatecArrays(self): raise NotImplementedError('get1dCoordinatecArrays for DMStag not yet implemented in petsc4py') property dim: def __get__(self): return self.getDim() property dofs: def __get__(self): return self.getDof() property entries_per_element: def __get__(self): return self.getEntriesPerElement() property global_sizes: def __get__(self): return self.getGlobalSizes() property local_sizes: def __get__(self): return self.getLocalSizes() property proc_sizes: def __get__(self): return self.getProcSizes() property boundary_types: def __get__(self): return self.getBoundaryTypes() property stencil_type: def __get__(self): return self.getStencilType() property stencil_width: def __get__(self): return self.getStencilWidth() property corners: def __get__(self): return self.getCorners() property ghost_corners: def __get__(self): return self.getGhostCorners() # -------------------------------------------------------------------- del DMStagStencilType del DMStagStencilLocation # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/DMSwarm.pyx000066400000000000000000000264301454104047300207300ustar00rootroot00000000000000# -------------------------------------------------------------------- class DMSwarmType(object): BASIC = DMSWARM_BASIC PIC = DMSWARM_PIC class DMSwarmMigrateType(object): MIGRATE_BASIC = DMSWARM_MIGRATE_BASIC MIGRATE_DMCELLNSCATTER = DMSWARM_MIGRATE_DMCELLNSCATTER MIGRATE_DMCELLEXACT = DMSWARM_MIGRATE_DMCELLEXACT MIGRATE_USER = DMSWARM_MIGRATE_USER class DMSwarmCollectType(object): COLLECT_BASIC = DMSWARM_COLLECT_BASIC COLLECT_DMDABOUNDINGBOX = DMSWARM_COLLECT_DMDABOUNDINGBOX COLLECT_GENERAL = DMSWARM_COLLECT_GENERAL COLLECT_USER = DMSWARM_COLLECT_USER class DMSwarmPICLayoutType(object): LAYOUT_REGULAR = DMSWARMPIC_LAYOUT_REGULAR LAYOUT_GAUSS = DMSWARMPIC_LAYOUT_GAUSS LAYOUT_SUBDIVISION = DMSWARMPIC_LAYOUT_SUBDIVISION cdef class DMSwarm(DM): Type = DMSwarmType MigrateType = DMSwarmMigrateType CollectType = DMSwarmCollectType PICLayoutType = DMSwarmPICLayoutType def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDM newdm = NULL CHKERR( DMCreate(ccomm, &newdm) ) PetscCLEAR(self.obj); self.dm = newdm CHKERR( DMSetType(self.dm, DMSWARM) ) return self def createGlobalVectorFromField(self, fieldname): cdef const char *cfieldname = NULL cdef Vec vg = Vec() fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmCreateGlobalVectorFromField(self.dm, cfieldname, &vg.vec) ) return vg def destroyGlobalVectorFromField(self, fieldname): cdef const char *cfieldname = NULL cdef PetscVec vec = NULL fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmDestroyGlobalVectorFromField(self.dm, cfieldname, &vec) ) def createLocalVectorFromField(self, fieldname): cdef const char *cfieldname = NULL cdef Vec vl = Vec() fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmCreateLocalVectorFromField(self.dm, cfieldname, &vl.vec) ) return vl def destroyLocalVectorFromField(self, fieldname): cdef const char *cfieldname = NULL cdef PetscVec vec fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmDestroyLocalVectorFromField(self.dm, cfieldname, &vec) ) def initializeFieldRegister(self): CHKERR( DMSwarmInitializeFieldRegister(self.dm) ) def finalizeFieldRegister(self): CHKERR( DMSwarmFinalizeFieldRegister(self.dm) ) def setLocalSizes(self, nlocal, buffer): cdef PetscInt cnlocal = asInt(nlocal) cdef PetscInt cbuffer = asInt(buffer) CHKERR( DMSwarmSetLocalSizes(self.dm, cnlocal, cbuffer) ) return self def registerField(self, fieldname, blocksize, dtype=ScalarType): cdef const char *cfieldname = NULL cdef PetscInt cblocksize = asInt(blocksize) cdef PetscDataType ctype = PETSC_DATATYPE_UNKNOWN if dtype == IntType: ctype = PETSC_INT if dtype == RealType: ctype = PETSC_REAL if dtype == ScalarType: ctype = PETSC_SCALAR if dtype == ComplexType: ctype = PETSC_COMPLEX assert ctype != PETSC_DATATYPE_UNKNOWN fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmRegisterPetscDatatypeField(self.dm, cfieldname, cblocksize, ctype) ) def getField(self, fieldname): cdef const char *cfieldname = NULL cdef PetscInt blocksize = 0 cdef PetscDataType ctype = PETSC_DATATYPE_UNKNOWN cdef PetscReal *data = NULL cdef PetscInt nlocal = 0 fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmGetField(self.dm, cfieldname, &blocksize, &ctype, &data) ) CHKERR( DMSwarmGetLocalSize(self.dm, &nlocal) ) cdef int typenum = -1 if ctype == PETSC_INT: typenum = NPY_PETSC_INT if ctype == PETSC_REAL: typenum = NPY_PETSC_REAL if ctype == PETSC_SCALAR: typenum = NPY_PETSC_SCALAR if ctype == PETSC_COMPLEX: typenum = NPY_PETSC_COMPLEX assert typenum != -1 cdef npy_intp s = nlocal * blocksize return PyArray_SimpleNewFromData(1, &s, typenum, data) def restoreField(self, fieldname): cdef const char *cfieldname = NULL cdef PetscInt blocksize = 0 cdef PetscDataType ctype = PETSC_DATATYPE_UNKNOWN fieldname = str2bytes(fieldname, &cfieldname) CHKERR( DMSwarmRestoreField(self.dm, cfieldname, &blocksize, &ctype, 0) ) def vectorDefineField(self, fieldname): cdef const char *cval = NULL fieldname = str2bytes(fieldname, &cval) CHKERR( DMSwarmVectorDefineField(self.dm, cval) ) def addPoint(self): CHKERR( DMSwarmAddPoint(self.dm) ) def addNPoints(self, npoints): cdef PetscInt cnpoints = asInt(npoints) CHKERR( DMSwarmAddNPoints(self.dm, cnpoints) ) def removePoint(self): CHKERR( DMSwarmRemovePoint(self.dm) ) def removePointAtIndex(self, index): cdef PetscInt cindex = asInt(index) CHKERR( DMSwarmRemovePointAtIndex(self.dm, cindex) ) def copyPoint(self, pi, pj): cdef PetscInt cpi = asInt(pi) cdef PetscInt cpj = asInt(pj) CHKERR( DMSwarmCopyPoint(self.dm, cpi, cpj) ) def getLocalSize(self): cdef PetscInt size = asInt(0) CHKERR( DMSwarmGetLocalSize(self.dm, &size) ) return toInt(size) def getSize(self): cdef PetscInt size = asInt(0) CHKERR( DMSwarmGetSize(self.dm, &size) ) return toInt(size) def migrate(self, remove_sent_points=False): cdef PetscBool remove_pts = asBool(remove_sent_points) CHKERR( DMSwarmMigrate(self.dm, remove_pts) ) def collectViewCreate(self): CHKERR( DMSwarmCollectViewCreate(self.dm) ) def collectViewDestroy(self): CHKERR( DMSwarmCollectViewDestroy(self.dm) ) def setCellDM(self, DM dm): CHKERR( DMSwarmSetCellDM(self.dm, dm.dm) ) def getCellDM(self): cdef PetscDM newdm = NULL CHKERR( DMSwarmGetCellDM(self.dm, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setType(self, dmswarm_type): cdef PetscDMSwarmType cval = dmswarm_type CHKERR( DMSwarmSetType(self.dm, cval) ) def setPointsUniformCoordinates(self, min, max, npoints, mode=None): cdef PetscInt dim = asInt(0) CHKERR( DMGetDimension(self.dm, &dim) ) cdef PetscReal cmin[3] cmin[0] = cmin[1] = cmin[2] = asReal(0.) for i from 0 <= i < dim: cmin[i] = min[i] cdef PetscReal cmax[3] cmax[0] = cmax[1] = cmax[2] = asReal(0.) for i from 0 <= i < dim: cmax[i] = max[i] cdef PetscInt cnpoints[3] cnpoints[0] = cnpoints[1] = cnpoints[2] = asInt(0) for i from 0 <= i < dim: cnpoints[i] = npoints[i] cdef PetscInsertMode cmode = insertmode(mode) CHKERR( DMSwarmSetPointsUniformCoordinates(self.dm, cmin, cmax, cnpoints, cmode) ) return self def setPointCoordinates(self, coordinates, redundant=False, mode=None): cdef ndarray xyz = iarray(coordinates, NPY_PETSC_REAL) if PyArray_ISFORTRAN(xyz): xyz = PyArray_Copy(xyz) if PyArray_NDIM(xyz) != 2: raise ValueError( ("coordinates must have two dimensions: " "coordinates.ndim=%d") % (PyArray_NDIM(xyz)) ) cdef PetscInt cnpoints = PyArray_DIM(xyz, 0) cdef PetscBool credundant = asBool(redundant) cdef PetscInsertMode cmode = insertmode(mode) cdef PetscReal *coords = PyArray_DATA(xyz) CHKERR( DMSwarmSetPointCoordinates(self.dm, cnpoints, coords, credundant, cmode) ) def insertPointUsingCellDM(self, layoutType, fill_param): cdef PetscDMSwarmPICLayoutType clayoutType = layoutType cdef PetscInt cfill_param = asInt(fill_param) CHKERR( DMSwarmInsertPointsUsingCellDM(self.dm, clayoutType, cfill_param) ) def setPointCoordinatesCellwise(self, coordinates): cdef ndarray xyz = iarray(coordinates, NPY_PETSC_REAL) if PyArray_ISFORTRAN(xyz): xyz = PyArray_Copy(xyz) if PyArray_NDIM(xyz) != 2: raise ValueError( ("coordinates must have two dimensions: " "coordinates.ndim=%d") % (PyArray_NDIM(xyz)) ) cdef PetscInt cnpoints = PyArray_DIM(xyz, 0) cdef PetscReal *coords = PyArray_DATA(xyz) CHKERR( DMSwarmSetPointCoordinatesCellwise(self.dm, cnpoints, coords) ) def viewFieldsXDMF(self, filename, fieldnames): cdef const char *cval = NULL cdef const char *cfilename = NULL filename = str2bytes(filename, &cfilename) cdef PetscInt cnfields = len(fieldnames) cdef const char** cfieldnames = NULL cdef object tmp = oarray_p(empty_p(cnfields), NULL, &cfieldnames) fieldnames = list(fieldnames) for i from 0 <= i < cnfields: fieldnames[i] = str2bytes(fieldnames[i], &cval) cfieldnames[i] = cval CHKERR( DMSwarmViewFieldsXDMF(self.dm, cfilename, cnfields, cfieldnames ) ) def viewXDMF(self, filename): cdef const char *cval = NULL filename = str2bytes(filename, &cval) CHKERR( DMSwarmViewXDMF(self.dm, cval) ) def sortGetAccess(self): CHKERR( DMSwarmSortGetAccess(self.dm) ) def sortRestoreAccess(self): CHKERR( DMSwarmSortRestoreAccess(self.dm) ) def sortGetPointsPerCell(self, e): cdef PetscInt ce = asInt(e) cdef PetscInt cnpoints = asInt(0) cdef PetscInt *cpidlist = NULL cdef list pidlist = [] CHKERR( DMSwarmSortGetPointsPerCell(self.dm, ce, &cnpoints, &cpidlist) ) npoints = asInt(cnpoints) for i from 0 <= i < npoints: pidlist.append(asInt(cpidlist[i])) return pidlist def sortGetNumberOfPointsPerCell(self, e): cdef PetscInt ce = asInt(e) cdef PetscInt npoints = asInt(0) CHKERR( DMSwarmSortGetNumberOfPointsPerCell(self.dm, ce, &npoints) ) return toInt(npoints) def sortGetIsValid(self): cdef PetscBool isValid = asBool(False) CHKERR( DMSwarmSortGetIsValid(self.dm, &isValid) ) return toBool(isValid) def sortGetSizes(self): cdef PetscInt ncells = asInt(0) cdef PetscInt npoints = asInt(0) CHKERR( DMSwarmSortGetSizes(self.dm, &ncells, &npoints) ) return (toInt(ncells), toInt(npoints)) def projectFields(self, fieldnames, reuse=False): cdef PetscBool creuse = asBool(reuse) cdef const char *cval = NULL cdef PetscInt cnfields = len(fieldnames) cdef const char** cfieldnames = NULL cdef object tmp = oarray_p(empty_p(cnfields), NULL, &cfieldnames) cdef PetscVec *cfieldvecs fieldnames = list(fieldnames) for i from 0 <= i < cnfields: fieldnames[i] = str2bytes(fieldnames[i], &cval) cfieldnames[i] = cval CHKERR( DMSwarmProjectFields(self.dm, cnfields, cfieldnames, &cfieldvecs, creuse) ) cdef list fieldvecs = [] for i from 0 <= i < cnfields: newVec = Vec() newVec.vec = cfieldvecs[i] fieldvecs.append(newVec) return fieldvecs del DMSwarmType del DMSwarmMigrateType del DMSwarmCollectType del DMSwarmPICLayoutType petsc4py-3.19.6/src/petsc4py/PETSc/DMUtils.pyx000066400000000000000000000036261454104047300207410ustar00rootroot00000000000000 cdef class DMInterpolation: cdef PetscDMInterpolation dminterp def __cinit__(self): self.dminterp = NULL def __dealloc__(self): self.destroy() def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_SELF) cdef PetscDMInterpolation new = NULL CHKERR( DMInterpolationCreate(ccomm, &new) ) self.dminterp = new def destroy(self): CHKERR( DMInterpolationDestroy(&self.dminterp)) def evaluate(self, DM dm, Vec x): cdef Vec v = Vec() CHKERR( DMInterpolationEvaluate(self.dminterp, dm.dm, x.vec, v.vec ) ) return v def getCoordinates(self): cdef Vec coords = Vec() CHKERR( DMInterpolationGetCoordinates(self.dminterp, &coords.vec) ) return coords def getDim(self): cdef PetscInt cdim = 0 CHKERR( DMInterpolationGetDim(self.dminterp, &cdim) ) return toInt(cdim) def getDof(self): cdef PetscInt cdof = 0 CHKERR( DMInterpolationGetDof(self.dminterp, &cdof) ) return toInt(cdof) def setDim(self, dim): cdef PetscInt cdim = asInt(dim) CHKERR( DMInterpolationSetDim(self.dminterp, cdim) ) def setDof(self, dof): cdef PetscInt cdof = asInt(dof) CHKERR( DMInterpolationSetDof(self.dminterp, cdof) ) def setUp(self, DM dm, redundantPoints=False, ignoreOutsideDomain=False): cdef PetscBool credundantPoints = asBool(redundantPoints) cdef PetscBool cignoreOutsideDomain = asBool(ignoreOutsideDomain) CHKERR( DMInterpolationSetUp(self.dminterp, dm.dm, credundantPoints, cignoreOutsideDomain) ) def getVector(self): cdef Vec vec = Vec() CHKERR( DMInterpolationGetVector(self.dminterp, &vec.vec)) return vec def restoreVector(self, Vec vec): CHKERR( DMInterpolationRestoreVector(self.dminterp, &vec.vec) ) return vecpetsc4py-3.19.6/src/petsc4py/PETSc/DS.pyx000066400000000000000000000056701454104047300177270ustar00rootroot00000000000000# -------------------------------------------------------------------- class DSType(object): BASIC = S_(PETSCDSBASIC) # -------------------------------------------------------------------- cdef class DS(Object): Type = DSType # def __cinit__(self): self.obj = &self.ds self.ds = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscDSView(self.ds, vwr) ) def destroy(self): CHKERR( PetscDSDestroy(&self.ds) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDS newds = NULL CHKERR( PetscDSCreate(ccomm, &newds) ) PetscCLEAR(self.obj); self.ds = newds return self def setType(self, ds_type): cdef PetscDSType cval = NULL ds_type = str2bytes(ds_type, &cval) CHKERR( PetscDSSetType(self.ds, cval) ) def getType(self): cdef PetscDSType cval = NULL CHKERR( PetscDSGetType(self.ds, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( PetscDSSetFromOptions(self.ds) ) def setUp(self): CHKERR( PetscDSSetUp(self.ds) ) return self # def getSpatialDimension(self): cdef PetscInt dim = 0 CHKERR( PetscDSGetSpatialDimension(self.ds, &dim) ) return toInt(dim) def getCoordinateDimension(self): cdef PetscInt dim = 0 CHKERR( PetscDSGetCoordinateDimension(self.ds, &dim) ) return toInt(dim) def getNumFields(self): cdef PetscInt nf = 0 CHKERR( PetscDSGetNumFields(self.ds, &nf) ) return toInt(nf) def getFieldIndex(self, Object disc): cdef PetscInt field = 0 CHKERR( PetscDSGetFieldIndex(self.ds, disc.obj[0], &field) ) return toInt(field) def getTotalDimensions(self): cdef PetscInt tdim = 0 CHKERR( PetscDSGetTotalDimension(self.ds, &tdim) ) return toInt(tdim) def getTotalComponents(self): cdef PetscInt tcmp = 0 CHKERR( PetscDSGetTotalComponents(self.ds, &tcmp) ) return toInt(tcmp) def getDimensions(self): cdef PetscInt nf = 0, *dims = NULL CHKERR( PetscDSGetNumFields(self.ds, &nf) ) CHKERR( PetscDSGetDimensions(self.ds, &dims) ) return array_i(nf, dims) def getComponents(self): cdef PetscInt nf = 0, *cmps = NULL CHKERR( PetscDSGetNumFields(self.ds, &nf) ) CHKERR( PetscDSGetComponents(self.ds, &cmps) ) return array_i(nf, cmps) def setDiscretisation(self, f, disc): cdef PetscInt cf = asInt(f) cdef FE fe = disc CHKERR( PetscDSSetDiscretization(self.ds, cf, fe.fe) ) # -------------------------------------------------------------------- del DSType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/DT.pyx000066400000000000000000000036221454104047300177230ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class Quad(Object): def __cinit__(self): self.obj = &self.quad self.quad = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscQuadratureView(self.quad, vwr) ) def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscQuadrature newquad = NULL CHKERR( PetscQuadratureCreate(ccomm, &newquad) ) PetscCLEAR(self.obj); self.quad = newquad return self def duplicate(self): cdef Quad newquad = Quad() CHKERR( PetscQuadratureDuplicate(self.quad, &newquad.quad) ) return newquad def destroy(self): CHKERR( PetscQuadratureDestroy(&self.quad) ) return self def getData(self): cdef PetscInt cdim = 0 cdef PetscInt cnc = 0 cdef PetscInt cnpoints = 0 cdef const PetscReal *cpoints = NULL cdef const PetscReal *cweights = NULL CHKERR( PetscQuadratureGetData(self.quad, &cdim, &cnc, &cnpoints, &cpoints, &cweights)) return array_r(cnpoints*cdim, cpoints), array_r(cnpoints*cnc, cweights) def getNumComponents(self): cdef PetscInt cnc = 0 CHKERR( PetscQuadratureGetNumComponents(self.quad, &cnc) ) return toInt(cnc) def setNumComponents(self, nc): cdef PetscInt cnc = asInt(nc) CHKERR( PetscQuadratureSetNumComponents(self.quad, cnc) ) def getOrder(self): cdef PetscInt corder = 0 CHKERR( PetscQuadratureGetOrder(self.quad, &corder)) return toInt(corder) def setOrder(self, order): cdef PetscInt corder = asInt(order) CHKERR( PetscQuadratureSetOrder(self.quad, corder)) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Device.pyx000066400000000000000000000161111454104047300206100ustar00rootroot00000000000000# -------------------------------------------------------------------- class staticproperty(property): def __get__(self, *args, **kwargs): return self.fget.__get__(*args, **kwargs)() cdef object make_enum_class(str class_name, tuple args): cdef dict enum2str = {} cdef dict attrs = {} for name, c_enum in args: enum2str[c_enum] = name attrs[name] = c_enum attrs['__enum2str'] = enum2str return type(class_name, (object, ), attrs) DeviceType = make_enum_class( "DeviceType", ( ("HOST" , PETSC_DEVICE_HOST), ("CUDA" , PETSC_DEVICE_CUDA), ("HIP" , PETSC_DEVICE_HIP), ("SYCL" , PETSC_DEVICE_SYCL), ("DEFAULT" , staticproperty(lambda *_,**__: PETSC_DEVICE_DEFAULT())) ) ) StreamType = make_enum_class( "StreamType", ( ("GLOBAL_BLOCKING" , PETSC_STREAM_GLOBAL_BLOCKING), ("DEFAULT_BLOCKING" , PETSC_STREAM_DEFAULT_BLOCKING), ("GLOBAL_NONBLOCKING" , PETSC_STREAM_GLOBAL_NONBLOCKING), ) ) DeviceJoinMode = make_enum_class( "DeviceJoinMode", ( ("DESTROY" , PETSC_DEVICE_CONTEXT_JOIN_DESTROY), ("SYNC" , PETSC_DEVICE_CONTEXT_JOIN_SYNC), ("NO_SYNC" , PETSC_DEVICE_CONTEXT_JOIN_NO_SYNC), ) ) # -------------------------------------------------------------------- cdef class Device: Type = DeviceType def __cinit__(self): self.device = NULL def __dealloc__(self): self.destroy() @classmethod def create(cls, dtype = None, device_id = PETSC_DECIDE): cdef PetscInt cdevice_id = asInt(device_id) cdef PetscDeviceType cdevice_type = asDeviceType(dtype if dtype is not None else cls.Type.DEFAULT) cdef Device device = cls() CHKERR(PetscDeviceCreate(cdevice_type, cdevice_id, &device.device)) return device def destroy(self): CHKERR(PetscDeviceDestroy(&self.device)) def configure(self): CHKERR(PetscDeviceConfigure(self.device)) def view(self, Viewer viewer = None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR(PetscDeviceView(self.device, vwr)) def getDeviceType(self): cdef PetscDeviceType cdtype CHKERR(PetscDeviceGetType(self.device, &cdtype)) return toDeviceType(cdtype) property type: def __get__(self): return self.getDeviceType() def getDeviceId(self): cdef PetscInt cdevice_id = 0 CHKERR(PetscDeviceGetDeviceId(self.device, &cdevice_id)) return toInt(cdevice_id) property device_id: def __get__(self): return self.getDeviceId() @staticmethod def setDefaultType(device_type): cdef PetscDeviceType cdevice_type = asDeviceType(device_type) CHKERR(PetscDeviceSetDefaultDeviceType(cdevice_type)) # -------------------------------------------------------------------- cdef class DeviceContext(Object): JoinMode = DeviceJoinMode StreamType = StreamType def __cinit__(self): self.obj = &self.dctx self.dctx = NULL def __dealloc__(self): self.destroy() @classmethod def create(cls): cdef DeviceContext dctx = cls() CHKERR(PetscDeviceContextCreate(&dctx.dctx)) return dctx def getStreamType(self): cdef PetscStreamType cstream_type = PETSC_STREAM_DEFAULT_BLOCKING CHKERR(PetscDeviceContextGetStreamType(self.dctx, &cstream_type)) return toStreamType(cstream_type) def setStreamType(self, stream_type): cdef PetscStreamType cstream_type = asStreamType(stream_type) CHKERR(PetscDeviceContextSetStreamType(self.dctx, cstream_type)) property stream_type: def __get__(self): return self.getStreamType() def __set__(self, stype): self.setStreamType(stype) def getDevice(self): cdef PetscDevice device = NULL CHKERR(PetscDeviceContextGetDevice(self.dctx, &device)) return PyPetscDevice_New(device) def setDevice(self, Device device not None): cdef PetscDevice cdevice = PyPetscDevice_Get(device) CHKERR(PetscDeviceContextSetDevice(self.dctx, cdevice)) property device: def __get__(self): return self.getDevice() def __set__(self, device): self.setDevice(device) def setUp(self): CHKERR(PetscDeviceContextSetUp(self.dctx)) def duplicate(self): cdef PetscDeviceContext octx = NULL CHKERR(PetscDeviceContextDuplicate(self.dctx, &octx)) return PyPetscDeviceContext_New(octx) def idle(self): cdef PetscBool is_idle = PETSC_FALSE CHKERR(PetscDeviceContextQueryIdle(self.dctx, &is_idle)) return toBool(is_idle) def waitFor(self, other): cdef PetscDeviceContext cother = NULL if other is not None: cother = PyPetscDeviceContext_Get(other) CHKERR(PetscDeviceContextWaitForContext(self.dctx, cother)) def fork(self, PetscInt n, stream_type = None): cdef PetscDeviceContext *subctx = NULL cdef PetscStreamType cstream_type = PETSC_STREAM_DEFAULT_BLOCKING try: if stream_type is None: CHKERR(PetscDeviceContextFork(self.dctx, n, &subctx)) else: cstream_type = asStreamType(stream_type) CHKERR(PetscDeviceContextForkWithStreamType(self.dctx, cstream_type, n, &subctx)) return [PyPetscDeviceContext_New(subctx[i]) for i in range(n)] finally: CHKERR(PetscFree(subctx)) def join(self, join_mode, py_sub_ctxs): cdef PetscDeviceContext *np_subctx_copy = NULL cdef PetscDeviceContext *np_subctx = NULL cdef PetscInt nsub = 0 cdef PetscDeviceContextJoinMode cjoin_mode = asJoinMode(join_mode) tmp = oarray_p(py_sub_ctxs, &nsub, &np_subctx) try: CHKERR(PetscMalloc((nsub) * sizeof(PetscDeviceContext *), &np_subctx_copy)) CHKERR(PetscMemcpy(np_subctx_copy, np_subctx, (nsub) * sizeof(PetscDeviceContext *))) CHKERR(PetscDeviceContextJoin(self.dctx, nsub, cjoin_mode, &np_subctx_copy)) finally: CHKERR(PetscFree(np_subctx_copy)) if cjoin_mode == PETSC_DEVICE_CONTEXT_JOIN_DESTROY: for i in range(nsub): py_sub_ctxs[i] = None def synchronize(self): CHKERR(PetscDeviceContextSynchronize(self.dctx)) def setFromOptions(self, comm = None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_SELF) CHKERR(PetscDeviceContextSetFromOptions(ccomm, self.dctx)) def viewFromOptions(self, name, Object obj = None): cdef const char *cname = NULL cdef PetscObject cobj = NULL if obj is not None: cobj = obj.obj[0] _ = str2bytes(name, &cname) CHKERR(PetscDeviceContextViewFromOptions(self.dctx, cobj, cname)) @staticmethod def getCurrent(): cdef PetscDeviceContext dctx = NULL CHKERR(PetscDeviceContextGetCurrentContext(&dctx)) return PyPetscDeviceContext_New(dctx) @staticmethod def setCurrent(dctx): cdef PetscDeviceContext cdctx = NULL if dctx is not None: cdctx = PyPetscDeviceContext_Get(dctx) CHKERR(PetscDeviceContextSetCurrentContext(cdctx)) property current: def __get__(self): return self.getCurrent() def __set__(self, dctx): self.setCurrent(dctx) # -------------------------------------------------------------------- del DeviceType del DeviceJoinMode del StreamType del staticproperty petsc4py-3.19.6/src/petsc4py/PETSc/Error.pyx000066400000000000000000000016271454104047300205100ustar00rootroot00000000000000# -------------------------------------------------------------------- class Error(RuntimeError): _traceback_ = [] def __init__(self, int ierr=0): self.ierr = ierr RuntimeError.__init__(self, self.ierr) def __nonzero__(self): cdef int ierr = self.ierr return ierr != 0 def __repr__(self): return 'PETSc.Error(%d)' % self.ierr def __str__(self): cdef int csize=1, crank=0 if not (PetscFinalizeCalled): MPI_Comm_size(PETSC_COMM_WORLD, &csize) MPI_Comm_rank(PETSC_COMM_WORLD, &crank) width, rank = len(str(csize-1)), crank tblist = ['error code %d' % self.ierr] for entry in self._traceback_: tbline = '[%*d] %s' % (width, rank, entry) tblist.append(tbline) return '\n'.join(tblist) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/FE.pyx000066400000000000000000000124001454104047300177000ustar00rootroot00000000000000# -------------------------------------------------------------------- class FEType(object): BASIC = S_(PETSCFEBASIC) OPENCL = S_(PETSCFEOPENCL) COMPOSITE = S_(PETSCFECOMPOSITE) # -------------------------------------------------------------------- cdef class FE(Object): Type = FEType def __cinit__(self): self.obj = &self.fe self.fe = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscFEView(self.fe, vwr) ) def destroy(self): CHKERR( PetscFEDestroy(&self.fe) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscFE newfe = NULL CHKERR( PetscFECreate(ccomm, &newfe) ) PetscCLEAR(self.obj); self.fe = newfe return self def createDefault(self, dim, nc, isSimplex, qorder, prefix=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscFE newfe = NULL cdef PetscInt cdim = asInt(dim) cdef PetscInt cnc = asInt(nc) cdef PetscInt cqorder = asInt(qorder) cdef PetscBool cisSimplex = asBool(isSimplex) cdef const char *cprefix = NULL if prefix: prefix = str2bytes(prefix, &cprefix) CHKERR( PetscFECreateDefault(ccomm, cdim, cnc, cisSimplex, cprefix, cqorder, &newfe)) PetscCLEAR(self.obj); self.fe = newfe return self def createLagrange(self, dim, nc, isSimplex, k, qorder, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscFE newfe = NULL cdef PetscInt cdim = asInt(dim) cdef PetscInt cnc = asInt(nc) cdef PetscInt ck = asInt(k) cdef PetscInt cqorder = asInt(qorder) cdef PetscBool cisSimplex = asBool(isSimplex) CHKERR( PetscFECreateLagrange(ccomm, cdim, cnc, cisSimplex, ck, cqorder, &newfe)) PetscCLEAR(self.obj); self.fe = newfe return self def getQuadrature(self): cdef Quad quad = Quad() CHKERR( PetscFEGetQuadrature(self.fe, &quad.quad) ) return quad def getDimension(self): cdef PetscInt cdim = 0 CHKERR( PetscFEGetDimension(self.fe, &cdim) ) return toInt(cdim) def getSpatialDimension(self): cdef PetscInt csdim = 0 CHKERR( PetscFEGetSpatialDimension(self.fe, &csdim) ) return toInt(csdim) def getNumComponents(self): cdef PetscInt comp = 0 CHKERR( PetscFEGetNumComponents(self.fe, &comp) ) return toInt(comp) def setNumComponents(self, comp): cdef PetscInt ccomp = asInt(comp) CHKERR( PetscFESetNumComponents(self.fe, comp) ) def getNumDof(self): cdef const PetscInt *numDof = NULL cdef PetscInt cdim = 0 CHKERR( PetscFEGetDimension(self.fe, &cdim) ) CHKERR( PetscFEGetNumDof(self.fe, &numDof) ) return array_i(cdim, numDof) def getTileSizes(self): cdef PetscInt blockSize = 0, numBlocks = 0 cdef PetscInt batchSize = 0, numBatches = 0 CHKERR( PetscFEGetTileSizes(self.fe, &blockSize, &numBlocks, &batchSize, &numBatches) ) return toInt(blockSize), toInt(numBlocks), toInt(batchSize), toInt(numBatches) def setTileSizes(self, blockSize, numBlocks, batchSize, numBatches): cdef PetscInt cblockSize = asInt(blockSize), cnumBlocks = asInt(numBlocks) cdef PetscInt cbatchSize = asInt(batchSize), cnumBatches = asInt(numBatches) CHKERR( PetscFESetTileSizes(self.fe, blockSize, numBlocks, batchSize, numBatches) ) def getFaceQuadrature(self): cdef Quad quad = Quad() CHKERR( PetscFEGetFaceQuadrature(self.fe, &quad.quad) ) return quad def setQuadrature(self, Quad quad): CHKERR( PetscFESetQuadrature(self.fe, quad.quad) ) return self def setFaceQuadrature(self, Quad quad): CHKERR( PetscFESetFaceQuadrature(self.fe, quad.quad) ) return self def setType(self, fe_type): cdef PetscFEType cval = NULL fe_type = str2bytes(fe_type, &cval) CHKERR( PetscFESetType(self.fe, cval) ) return self def getBasisSpace(self): cdef Space sp = Space() CHKERR( PetscFEGetBasisSpace(self.fe, &sp.space ) ) return sp def setBasisSpace(self, Space sp): CHKERR( PetscFESetBasisSpace(self.fe, sp.space ) ) def setFromOptions(self): CHKERR( PetscFESetFromOptions(self.fe) ) def setUp(self): CHKERR( PetscFESetUp(self.fe) ) def getDualSpace(self): cdef DualSpace dspace = DualSpace() CHKERR( PetscFEGetDualSpace(self.fe, &dspace.dualspace) ) return dspace def setDualSpace(self, DualSpace dspace): CHKERR( PetscFESetDualSpace(self.fe, dspace.dualspace) ) def viewFromOptions(self, name, Object obj=None): cdef const char *cname = NULL _ = str2bytes(name, &cname) cdef PetscObject cobj = NULL if obj is not None: cobj = obj.obj[0] CHKERR( PetscFEViewFromOptions(self.fe, cobj, cname) ) # -------------------------------------------------------------------- del FEType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/IS.pyx000066400000000000000000000444271454104047300177370ustar00rootroot00000000000000# -------------------------------------------------------------------- class ISType(object): GENERAL = S_(ISGENERAL) BLOCK = S_(ISBLOCK) STRIDE = S_(ISSTRIDE) # -------------------------------------------------------------------- cdef class IS(Object): Type = ISType # def __cinit__(self): self.obj = &self.iset self.iset = NULL # buffer interface (PEP 3118) def __getbuffer__(self, Py_buffer *view, int flags): cdef _IS_buffer buf = _IS_buffer(self) buf.acquirebuffer(view, flags) def __releasebuffer__(self, Py_buffer *view): cdef _IS_buffer buf = <_IS_buffer>(view.obj) buf.releasebuffer(view) self # unused # 'with' statement (PEP 343) def __enter__(self): cdef _IS_buffer buf = _IS_buffer(self) self.set_attr('__buffer__', buf) return buf.enter() def __exit__(self, *exc): cdef _IS_buffer buf = self.get_attr('__buffer__') self.set_attr('__buffer__', None) return buf.exit() # def view(self, Viewer viewer=None): cdef PetscViewer cviewer = NULL if viewer is not None: cviewer = viewer.vwr CHKERR( ISView(self.iset, cviewer) ) def destroy(self): CHKERR( ISDestroy(&self.iset) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscIS newiset = NULL CHKERR( ISCreate(ccomm, &newiset) ) PetscCLEAR(self.obj); self.iset = newiset return self def setType(self, is_type): cdef PetscISType cval = NULL is_type = str2bytes(is_type, &cval) CHKERR( ISSetType(self.iset, cval) ) def getType(self): cdef PetscISType cval = NULL CHKERR( ISGetType(self.iset, &cval) ) return bytes2str(cval) def createGeneral(self, indices, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt nidx = 0, *idx = NULL cdef PetscCopyMode cm = PETSC_COPY_VALUES cdef PetscIS newiset = NULL indices = iarray_i(indices, &nidx, &idx) CHKERR( ISCreateGeneral(ccomm, nidx, idx, cm, &newiset) ) PetscCLEAR(self.obj); self.iset = newiset return self def createBlock(self, bsize, indices, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs = asInt(bsize) cdef PetscInt nidx = 0, *idx = NULL cdef PetscCopyMode cm = PETSC_COPY_VALUES cdef PetscIS newiset = NULL indices = iarray_i(indices, &nidx, &idx) CHKERR( ISCreateBlock(ccomm, bs, nidx, idx, cm, &newiset) ) PetscCLEAR(self.obj); self.iset = newiset return self def createStride(self, size, first=0, step=0, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt csize = asInt(size) cdef PetscInt cfirst = asInt(first) cdef PetscInt cstep = asInt(step) cdef PetscIS newiset = NULL CHKERR( ISCreateStride(ccomm, csize, cfirst, cstep, &newiset) ) PetscCLEAR(self.obj); self.iset = newiset return self def duplicate(self): cdef IS iset = type(self)() CHKERR( ISDuplicate(self.iset, &iset.iset) ) return iset def copy(self, IS result=None): if result is None: result = type(self)() if result.iset == NULL: CHKERR( ISDuplicate(self.iset, &result.iset) ) CHKERR( ISCopy(self.iset, result.iset) ) return result def load(self, Viewer viewer): cdef MPI_Comm comm = MPI_COMM_NULL cdef PetscObject obj = (viewer.vwr) if self.iset == NULL: CHKERR( PetscObjectGetComm(obj, &comm) ) CHKERR( ISCreate(comm, &self.iset) ) CHKERR( ISLoad(self.iset, viewer.vwr) ) return self def allGather(self): cdef IS iset = IS() CHKERR( ISAllGather(self.iset, &iset.iset) ) return iset def toGeneral(self): CHKERR( ISToGeneral(self.iset) ) return self def buildTwoSided(self, IS toindx=None): cdef PetscIS ctoindx = NULL if toindx is not None: ctoindx = toindx.iset cdef IS result = IS() CHKERR( ISBuildTwoSided(self.iset, ctoindx, &result.iset) ) return result def invertPermutation(self, nlocal=None): cdef PetscInt cnlocal = PETSC_DECIDE if nlocal is not None: cnlocal = asInt(nlocal) cdef IS iset = IS() CHKERR( ISInvertPermutation(self.iset, cnlocal, &iset.iset) ) return iset def getSize(self): cdef PetscInt N = 0 CHKERR( ISGetSize(self.iset, &N) ) return toInt(N) def getLocalSize(self): cdef PetscInt n = 0 CHKERR( ISGetLocalSize(self.iset, &n) ) return toInt(n) def getSizes(self): cdef PetscInt n = 0, N = 0 CHKERR( ISGetLocalSize(self.iset, &n) ) CHKERR( ISGetSize(self.iset, &N) ) return (toInt(n), toInt(N)) def getBlockSize(self): cdef PetscInt bs = 1 CHKERR( ISGetBlockSize(self.iset, &bs) ) return toInt(bs) def setBlockSize(self, bs): cdef PetscInt cbs = asInt(bs) CHKERR( ISSetBlockSize(self.iset, cbs) ) def sort(self): CHKERR( ISSort(self.iset) ) return self def isSorted(self): cdef PetscBool flag = PETSC_FALSE CHKERR( ISSorted(self.iset, &flag) ) return toBool(flag) def setPermutation(self): CHKERR( ISSetPermutation(self.iset) ) return self def isPermutation(self): cdef PetscBool flag = PETSC_FALSE CHKERR( ISPermutation(self.iset, &flag) ) return toBool(flag) def setIdentity(self): CHKERR( ISSetIdentity(self.iset) ) return self def isIdentity(self): cdef PetscBool flag = PETSC_FALSE CHKERR( ISIdentity(self.iset, &flag) ) return toBool(flag) def equal(self, IS iset): cdef PetscBool flag = PETSC_FALSE CHKERR( ISEqual(self.iset, iset.iset, &flag) ) return toBool(flag) def sum(self, IS iset): cdef IS out = IS() CHKERR( ISSum(self.iset, iset.iset, &out.iset) ) return out def expand(self, IS iset): cdef IS out = IS() CHKERR( ISExpand(self.iset, iset.iset, &out.iset) ) return out def union(self, IS iset): # XXX review this cdef PetscBool flag1=PETSC_FALSE, flag2=PETSC_FALSE CHKERR( ISSorted(self.iset, &flag1) ) CHKERR( ISSorted(iset.iset, &flag2) ) cdef IS out = IS() if flag1==PETSC_TRUE and flag2==PETSC_TRUE: CHKERR( ISSum(self.iset, iset.iset, &out.iset) ) else: CHKERR( ISExpand(self.iset, iset.iset, &out.iset) ) return out def difference(self, IS iset): cdef IS out = IS() CHKERR( ISDifference(self.iset, iset.iset, &out.iset) ) return out def complement(self, nmin, nmax): cdef PetscInt cnmin = asInt(nmin) cdef PetscInt cnmax = asInt(nmax) cdef IS out = IS() CHKERR( ISComplement(self.iset, cnmin, cnmax, &out.iset) ) return out def embed(self, IS iset, drop): cdef PetscBool bval = drop cdef IS out = IS() CHKERR( ISEmbed(self.iset, iset.iset, bval, &out.iset) ) return out def renumber(self, IS mult=None): cdef PetscIS mlt = NULL if mult is not None: mlt = mult.iset cdef IS out = IS() cdef PetscInt n = 0 CHKERR( ISRenumber(self.iset, mlt, &n, &out.iset) ) return (toInt(n), out) # def setIndices(self, indices): cdef PetscInt nidx = 0, *idx = NULL cdef PetscCopyMode cm = PETSC_COPY_VALUES indices = iarray_i(indices, &nidx, &idx) CHKERR( ISGeneralSetIndices(self.iset, nidx, idx, cm) ) def getIndices(self): cdef PetscInt size = 0 cdef const PetscInt *indices = NULL CHKERR( ISGetLocalSize(self.iset, &size) ) CHKERR( ISGetIndices(self.iset, &indices) ) cdef object oindices = None try: oindices = array_i(size, indices) finally: CHKERR( ISRestoreIndices(self.iset, &indices) ) return oindices def setBlockIndices(self, bsize, indices): cdef PetscInt bs = asInt(bsize) cdef PetscInt nidx = 0, *idx = NULL cdef PetscCopyMode cm = PETSC_COPY_VALUES indices = iarray_i(indices, &nidx, &idx) CHKERR( ISBlockSetIndices(self.iset, bs, nidx, idx, cm) ) def getBlockIndices(self): cdef PetscInt size = 0, bs = 1 cdef const PetscInt *indices = NULL CHKERR( ISGetLocalSize(self.iset, &size) ) CHKERR( ISGetBlockSize(self.iset, &bs) ) CHKERR( ISBlockGetIndices(self.iset, &indices) ) cdef object oindices = None try: oindices = array_i(size//bs, indices) finally: CHKERR( ISBlockRestoreIndices(self.iset, &indices) ) return oindices def setStride(self, size, first=0, step=1): cdef PetscInt csize = asInt(size) cdef PetscInt cfirst = asInt(first) cdef PetscInt cstep = asInt(step) CHKERR( ISStrideSetStride(self.iset, csize, cfirst, cstep) ) def getStride(self): cdef PetscInt size=0, first=0, step=0 CHKERR( ISGetLocalSize(self.iset, &size) ) CHKERR( ISStrideGetInfo(self.iset, &first, &step) ) return (toInt(size), toInt(first), toInt(step)) def getInfo(self): cdef PetscInt first = 0, step = 0 CHKERR( ISStrideGetInfo(self.iset, &first, &step) ) return (toInt(first), toInt(step)) # property permutation: def __get__(self): return self.isPermutation() property identity: def __get__(self): return self.isIdentity() property sorted: def __get__(self): return self.isSorted() # property sizes: def __get__(self): return self.getSizes() property size: def __get__(self): return self.getSize() property local_size: def __get__(self): return self.getLocalSize() property block_size: def __get__(self): return self.getBlockSize() property indices: def __get__(self): return self.getIndices() property array: def __get__(self): return asarray(self) # --- NumPy array interface (legacy) --- property __array_interface__: def __get__(self): cdef _IS_buffer buf = _IS_buffer(self) return buf.__array_interface__ # -------------------------------------------------------------------- class GLMapMode(object): MASK = PETSC_IS_GTOLM_MASK DROP = PETSC_IS_GTOLM_DROP class LGMapType(object): BASIC = S_(ISLOCALTOGLOBALMAPPINGBASIC) HASH = S_(ISLOCALTOGLOBALMAPPINGHASH) # -------------------------------------------------------------------- cdef class LGMap(Object): MapMode = GLMapMode Type = LGMapType # def __cinit__(self): self.obj = &self.lgm self.lgm = NULL def __call__(self, indices, result=None): self.apply(indices, result) # def setType(self, lgmap_type): cdef PetscISLocalToGlobalMappingType cval = NULL lgmap_type = str2bytes(lgmap_type, &cval) CHKERR( ISLocalToGlobalMappingSetType(self.lgm, cval) ) def setFromOptions(self): CHKERR( ISLocalToGlobalMappingSetFromOptions(self.lgm) ) def view(self, Viewer viewer=None): cdef PetscViewer cviewer = NULL if viewer is not None: cviewer = viewer.vwr CHKERR( ISLocalToGlobalMappingView(self.lgm, cviewer) ) def destroy(self): CHKERR( ISLocalToGlobalMappingDestroy(&self.lgm) ) return self def create(self, indices, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs = 1, nidx = 0, *idx = NULL cdef PetscCopyMode cm = PETSC_COPY_VALUES cdef PetscLGMap newlgm = NULL if bsize is not None: bs = asInt(bsize) if bs == PETSC_DECIDE: bs = 1 indices = iarray_i(indices, &nidx, &idx) CHKERR( ISLocalToGlobalMappingCreate( ccomm, bs, nidx, idx, cm, &newlgm) ) PetscCLEAR(self.obj); self.lgm = newlgm return self def createIS(self, IS iset): cdef PetscLGMap newlgm = NULL CHKERR( ISLocalToGlobalMappingCreateIS( iset.iset, &newlgm) ) PetscCLEAR(self.obj); self.lgm = newlgm return self def createSF(self, SF sf, start): cdef PetscLGMap newlgm = NULL cdef PetscInt cstart = asInt(start) CHKERR( ISLocalToGlobalMappingCreateSF(sf.sf, cstart, &newlgm) ) PetscCLEAR(self.obj); self.lgm = newlgm return self def getSize(self): cdef PetscInt n = 0 CHKERR( ISLocalToGlobalMappingGetSize(self.lgm, &n) ) return toInt(n) def getBlockSize(self): cdef PetscInt bs = 1 CHKERR( ISLocalToGlobalMappingGetBlockSize(self.lgm, &bs) ) return toInt(bs) def getIndices(self): cdef PetscInt size = 0 cdef const PetscInt *indices = NULL CHKERR( ISLocalToGlobalMappingGetSize( self.lgm, &size) ) CHKERR( ISLocalToGlobalMappingGetIndices( self.lgm, &indices) ) cdef object oindices = None try: oindices = array_i(size, indices) finally: CHKERR( ISLocalToGlobalMappingRestoreIndices( self.lgm, &indices) ) return oindices def getBlockIndices(self): cdef PetscInt size = 0, bs = 1 cdef const PetscInt *indices = NULL CHKERR( ISLocalToGlobalMappingGetSize( self.lgm, &size) ) CHKERR( ISLocalToGlobalMappingGetBlockSize( self.lgm, &bs) ) CHKERR( ISLocalToGlobalMappingGetBlockIndices( self.lgm, &indices) ) cdef object oindices = None try: oindices = array_i(size//bs, indices) finally: CHKERR( ISLocalToGlobalMappingRestoreBlockIndices( self.lgm, &indices) ) return oindices def getInfo(self): cdef PetscInt i, nproc = 0, *procs = NULL, cdef PetscInt *numprocs = NULL, **indices = NULL cdef object neighs = { } CHKERR( ISLocalToGlobalMappingGetInfo( self.lgm, &nproc, &procs, &numprocs, &indices) ) try: for i from 0 <= i < nproc: neighs[toInt(procs[i])] = array_i(numprocs[i], indices[i]) finally: ISLocalToGlobalMappingRestoreInfo( self.lgm, &nproc, &procs, &numprocs, &indices) return neighs def getBlockInfo(self): cdef PetscInt i, nproc = 0, *procs = NULL, cdef PetscInt *numprocs = NULL, **indices = NULL cdef object neighs = { } CHKERR( ISLocalToGlobalMappingGetBlockInfo( self.lgm, &nproc, &procs, &numprocs, &indices) ) try: for i from 0 <= i < nproc: neighs[toInt(procs[i])] = array_i(numprocs[i], indices[i]) finally: ISLocalToGlobalMappingRestoreBlockInfo( self.lgm, &nproc, &procs, &numprocs, &indices) return neighs # def apply(self, indices, result=None): cdef PetscInt niidx = 0, *iidx = NULL cdef PetscInt noidx = 0, *oidx = NULL indices = iarray_i(indices, &niidx, &iidx) if result is None: result = empty_i(niidx) result = oarray_i(result, &noidx, &oidx) assert niidx == noidx, "incompatible array sizes" CHKERR( ISLocalToGlobalMappingApply( self.lgm, niidx, iidx, oidx) ) return result def applyBlock(self, indices, result=None): cdef PetscInt niidx = 0, *iidx = NULL cdef PetscInt noidx = 0, *oidx = NULL indices = iarray_i(indices, &niidx, &iidx) if result is None: result = empty_i(niidx) result = oarray_i(result, &noidx, &oidx) assert niidx == noidx, "incompatible array sizes" CHKERR( ISLocalToGlobalMappingApplyBlock( self.lgm, niidx, iidx, oidx) ) return result def applyIS(self, IS iset): cdef IS result = IS() CHKERR( ISLocalToGlobalMappingApplyIS( self.lgm, iset.iset, &result.iset) ) return result def applyInverse(self, indices, mode=None): cdef PetscGLMapMode cmode = PETSC_IS_GTOLM_MASK if mode is not None: cmode = mode cdef PetscInt n = 0, *idx = NULL indices = iarray_i(indices, &n, &idx) cdef PetscInt nout = n, *idxout = NULL if cmode != PETSC_IS_GTOLM_MASK: CHKERR( ISGlobalToLocalMappingApply( self.lgm, cmode, n, idx, &nout, NULL) ) result = oarray_i(empty_i(nout), &nout, &idxout) CHKERR( ISGlobalToLocalMappingApply( self.lgm, cmode, n, idx, &nout, idxout) ) return result def applyBlockInverse(self, indices, mode=None): cdef PetscGLMapMode cmode = PETSC_IS_GTOLM_MASK if mode is not None: cmode = mode cdef PetscInt n = 0, *idx = NULL indices = iarray_i(indices, &n, &idx) cdef PetscInt nout = n, *idxout = NULL if cmode != PETSC_IS_GTOLM_MASK: CHKERR( ISGlobalToLocalMappingApply( self.lgm, cmode, n, idx, &nout, NULL) ) result = oarray_i(empty_i(nout), &nout, &idxout) CHKERR( ISGlobalToLocalMappingApplyBlock( self.lgm, cmode, n, idx, &nout, idxout) ) return result # property size: def __get__(self): return self.getSize() property block_size: def __get__(self): return self.getBlockSize() property indices: def __get__(self): return self.getIndices() property block_indices: def __get__(self): return self.getBlockIndices() property info: def __get__(self): return self.getInfo() property block_info: def __get__(self): return self.getBlockInfo() # -------------------------------------------------------------------- del ISType del GLMapMode del LGMapType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/KSP.pyx000066400000000000000000000536741454104047300200650ustar00rootroot00000000000000# -------------------------------------------------------------------- class KSPType(object): RICHARDSON = S_(KSPRICHARDSON) CHEBYSHEV = S_(KSPCHEBYSHEV) CG = S_(KSPCG) GROPPCG = S_(KSPGROPPCG) PIPECG = S_(KSPPIPECG) PIPECGRR = S_(KSPPIPECGRR) PIPELCG = S_(KSPPIPELCG) PIPEPRCG = S_(KSPPIPEPRCG) PIPECG2 = S_(KSPPIPECG2) CGNE = S_(KSPCGNE) NASH = S_(KSPNASH) STCG = S_(KSPSTCG) GLTR = S_(KSPGLTR) FCG = S_(KSPFCG) PIPEFCG = S_(KSPPIPEFCG) GMRES = S_(KSPGMRES) PIPEFGMRES = S_(KSPPIPEFGMRES) FGMRES = S_(KSPFGMRES) LGMRES = S_(KSPLGMRES) DGMRES = S_(KSPDGMRES) PGMRES = S_(KSPPGMRES) TCQMR = S_(KSPTCQMR) BCGS = S_(KSPBCGS) IBCGS = S_(KSPIBCGS) QMRCGS = S_(KSPQMRCGS) FBCGS = S_(KSPFBCGS) FBCGSR = S_(KSPFBCGSR) BCGSL = S_(KSPBCGSL) PIPEBCGS = S_(KSPPIPEBCGS) CGS = S_(KSPCGS) TFQMR = S_(KSPTFQMR) CR = S_(KSPCR) PIPECR = S_(KSPPIPECR) LSQR = S_(KSPLSQR) PREONLY = S_(KSPPREONLY) NONE = S_(KSPNONE) QCG = S_(KSPQCG) BICG = S_(KSPBICG) MINRES = S_(KSPMINRES) SYMMLQ = S_(KSPSYMMLQ) LCD = S_(KSPLCD) PYTHON = S_(KSPPYTHON) GCR = S_(KSPGCR) PIPEGCR = S_(KSPPIPEGCR) TSIRM = S_(KSPTSIRM) CGLS = S_(KSPCGLS) FETIDP = S_(KSPFETIDP) HPDDM = S_(KSPHPDDM) class KSPNormType(object): # native NORM_DEFAULT = KSP_NORM_DEFAULT NORM_NONE = KSP_NORM_NONE NORM_PRECONDITIONED = KSP_NORM_PRECONDITIONED NORM_UNPRECONDITIONED = KSP_NORM_UNPRECONDITIONED NORM_NATURAL = KSP_NORM_NATURAL # aliases DEFAULT = NORM_DEFAULT NONE = NO = NORM_NONE PRECONDITIONED = NORM_PRECONDITIONED UNPRECONDITIONED = NORM_UNPRECONDITIONED NATURAL = NORM_NATURAL class KSPConvergedReason(object): #iterating CONVERGED_ITERATING = KSP_CONVERGED_ITERATING ITERATING = KSP_CONVERGED_ITERATING # converged CONVERGED_RTOL_NORMAL = KSP_CONVERGED_RTOL_NORMAL CONVERGED_ATOL_NORMAL = KSP_CONVERGED_ATOL_NORMAL CONVERGED_RTOL = KSP_CONVERGED_RTOL CONVERGED_ATOL = KSP_CONVERGED_ATOL CONVERGED_ITS = KSP_CONVERGED_ITS CONVERGED_NEG_CURVE = KSP_CONVERGED_NEG_CURVE CONVERGED_STEP_LENGTH = KSP_CONVERGED_STEP_LENGTH CONVERGED_HAPPY_BREAKDOWN = KSP_CONVERGED_HAPPY_BREAKDOWN # diverged DIVERGED_NULL = KSP_DIVERGED_NULL DIVERGED_MAX_IT = KSP_DIVERGED_MAX_IT DIVERGED_DTOL = KSP_DIVERGED_DTOL DIVERGED_BREAKDOWN = KSP_DIVERGED_BREAKDOWN DIVERGED_BREAKDOWN_BICG = KSP_DIVERGED_BREAKDOWN_BICG DIVERGED_NONSYMMETRIC = KSP_DIVERGED_NONSYMMETRIC DIVERGED_INDEFINITE_PC = KSP_DIVERGED_INDEFINITE_PC DIVERGED_NANORINF = KSP_DIVERGED_NANORINF DIVERGED_INDEFINITE_MAT = KSP_DIVERGED_INDEFINITE_MAT DIVERGED_PCSETUP_FAILED = KSP_DIVERGED_PC_FAILED # -------------------------------------------------------------------- cdef class KSP(Object): Type = KSPType NormType = KSPNormType ConvergedReason = KSPConvergedReason # --- xxx --- def __cinit__(self): self.obj = &self.ksp self.ksp = NULL def __call__(self, b, x=None): if x is None: # XXX do this better x = self.getOperators()[0].createVecLeft() self.solve(b, x) return x # --- xxx --- def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( KSPView(self.ksp, vwr) ) def destroy(self): CHKERR( KSPDestroy(&self.ksp) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscKSP newksp = NULL CHKERR( KSPCreate(ccomm, &newksp) ) PetscCLEAR(self.obj); self.ksp = newksp return self def setType(self, ksp_type): cdef PetscKSPType cval = NULL ksp_type = str2bytes(ksp_type, &cval) CHKERR( KSPSetType(self.ksp, cval) ) def getType(self): cdef PetscKSPType cval = NULL CHKERR( KSPGetType(self.ksp, &cval) ) return bytes2str(cval) def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( KSPSetOptionsPrefix(self.ksp, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( KSPGetOptionsPrefix(self.ksp, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( KSPAppendOptionsPrefix(self.ksp, cval) ) def setFromOptions(self): CHKERR( KSPSetFromOptions(self.ksp) ) # --- application context --- def setAppCtx(self, appctx): self.set_attr('__appctx__', appctx) def getAppCtx(self): return self.get_attr('__appctx__') # --- discretization space --- def getDM(self): cdef PetscDM newdm = NULL CHKERR( KSPGetDM(self.ksp, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setDM(self, DM dm): CHKERR( KSPSetDM(self.ksp, dm.dm) ) def setDMActive(self, bint flag): cdef PetscBool cflag = PETSC_FALSE if flag: cflag = PETSC_TRUE CHKERR( KSPSetDMActive(self.ksp, cflag) ) # --- operators and preconditioner --- def setComputeRHS(self, rhs, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (rhs, args, kargs) self.set_attr('__rhs__', context) CHKERR( KSPSetComputeRHS(self.ksp, KSP_ComputeRHS, context) ) def setComputeOperators(self, operators, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (operators, args, kargs) self.set_attr('__operators__', context) CHKERR( KSPSetComputeOperators(self.ksp, KSP_ComputeOps, context) ) def setOperators(self, Mat A=None, Mat P=None): cdef PetscMat amat=NULL if A is not None: amat = A.mat cdef PetscMat pmat=amat if P is not None: pmat = P.mat CHKERR( KSPSetOperators(self.ksp, amat, pmat) ) def getOperators(self): cdef Mat A = Mat(), P = Mat() CHKERR( KSPGetOperators(self.ksp, &A.mat, &P.mat) ) PetscINCREF(A.obj) PetscINCREF(P.obj) return (A, P) def setPC(self, PC pc): CHKERR( KSPSetPC(self.ksp, pc.pc) ) def getPC(self): cdef PC pc = PC() CHKERR( KSPGetPC(self.ksp, &pc.pc) ) PetscINCREF(pc.obj) return pc # --- tolerances and convergence --- def setTolerances(self, rtol=None, atol=None, divtol=None, max_it=None): cdef PetscReal crtol, catol, cdivtol crtol = catol = cdivtol = PETSC_DEFAULT; if rtol is not None: crtol = asReal(rtol) if atol is not None: catol = asReal(atol) if divtol is not None: cdivtol = asReal(divtol) cdef PetscInt cmaxits = PETSC_DEFAULT if max_it is not None: cmaxits = asInt(max_it) CHKERR( KSPSetTolerances(self.ksp, crtol, catol, cdivtol, cmaxits) ) def getTolerances(self): cdef PetscReal crtol=0, catol=0, cdivtol=0 cdef PetscInt cmaxits=0 CHKERR( KSPGetTolerances(self.ksp, &crtol, &catol, &cdivtol, &cmaxits) ) return (toReal(crtol), toReal(catol), toReal(cdivtol), toInt(cmaxits)) def setConvergenceTest(self, converged, args=None, kargs=None): cdef PetscKSPNormType normtype = KSP_NORM_NONE cdef void* cctx = NULL if converged is not None: CHKERR( KSPSetConvergenceTest( self.ksp, KSP_Converged, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} self.set_attr('__converged__', (converged, args, kargs)) else: CHKERR( KSPGetNormType(self.ksp, &normtype) ) if normtype != KSP_NORM_NONE: CHKERR( KSPConvergedDefaultCreate(&cctx) ) CHKERR( KSPSetConvergenceTest( self.ksp, KSPConvergedDefault, cctx, KSPConvergedDefaultDestroy) ) else: CHKERR( KSPSetConvergenceTest( self.ksp, KSPConvergedSkip, NULL, NULL) ) self.set_attr('__converged__', None) def getConvergenceTest(self): return self.get_attr('__converged__') def callConvergenceTest(self, its, rnorm): cdef PetscInt ival = asInt(its) cdef PetscReal rval = asReal(rnorm) cdef PetscKSPConvergedReason reason = KSP_CONVERGED_ITERATING CHKERR( KSPConvergenceTestCall(self.ksp, ival, rval, &reason) ) return reason def setConvergenceHistory(self, length=None, reset=False): cdef PetscReal *data = NULL cdef PetscInt size = 10000 cdef PetscBool flag = PETSC_FALSE if length is True: pass elif length is not None: size = asInt(length) if size < 0: size = 10000 if reset: flag = PETSC_TRUE cdef object hist = oarray_r(empty_r(size), NULL, &data) self.set_attr('__history__', hist) CHKERR( KSPSetResidualHistory(self.ksp, data, size, flag) ) def getConvergenceHistory(self): cdef const PetscReal *data = NULL cdef PetscInt size = 0 CHKERR( KSPGetResidualHistory(self.ksp, &data, &size) ) return array_r(size, data) def logConvergenceHistory(self, rnorm): cdef PetscReal rval = asReal(rnorm) CHKERR( KSPLogResidualHistory(self.ksp, rval) ) # --- monitoring --- def setMonitor(self, monitor, args=None, kargs=None): if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( KSPMonitorSet(self.ksp, KSP_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} monitorlist.append((monitor, args, kargs)) def getMonitor(self): return self.get_attr('__monitor__') def monitorCancel(self): CHKERR( KSPMonitorCancel(self.ksp) ) self.set_attr('__monitor__', None) cancelMonitor = monitorCancel def monitor(self, its, rnorm): cdef PetscInt ival = asInt(its) cdef PetscReal rval = asReal(rnorm) CHKERR( KSPMonitor(self.ksp, ival, rval) ) # --- customization --- def setPCSide(self, side): CHKERR( KSPSetPCSide(self.ksp, side) ) def getPCSide(self): cdef PetscPCSide side = PC_LEFT CHKERR( KSPGetPCSide(self.ksp, &side) ) return side def setNormType(self, normtype): CHKERR( KSPSetNormType(self.ksp, normtype) ) def getNormType(self): cdef PetscKSPNormType normtype = KSP_NORM_NONE CHKERR( KSPGetNormType(self.ksp, &normtype) ) return normtype def setComputeEigenvalues(self, bint flag): cdef PetscBool compute = PETSC_FALSE if flag: compute = PETSC_TRUE CHKERR( KSPSetComputeEigenvalues(self.ksp, compute) ) def getComputeEigenvalues(self): cdef PetscBool flag = PETSC_FALSE CHKERR( KSPGetComputeEigenvalues(self.ksp, &flag) ) return toBool(flag) def setComputeSingularValues(self, bint flag): cdef PetscBool compute = PETSC_FALSE if flag: compute = PETSC_TRUE CHKERR( KSPSetComputeSingularValues(self.ksp, compute) ) def getComputeSingularValues(self): cdef PetscBool flag = PETSC_FALSE CHKERR( KSPGetComputeSingularValues(self.ksp, &flag) ) return toBool(flag) # --- initial guess --- def setInitialGuessNonzero(self, bint flag): cdef PetscBool guess_nonzero = PETSC_FALSE if flag: guess_nonzero = PETSC_TRUE CHKERR( KSPSetInitialGuessNonzero(self.ksp, guess_nonzero) ) def getInitialGuessNonzero(self): cdef PetscBool flag = PETSC_FALSE CHKERR( KSPGetInitialGuessNonzero(self.ksp, &flag) ) return toBool(flag) def setInitialGuessKnoll(self, bint flag): cdef PetscBool guess_knoll = PETSC_FALSE if flag: guess_knoll = PETSC_TRUE CHKERR( KSPSetInitialGuessKnoll(self.ksp, guess_knoll) ) def getInitialGuessKnoll(self): cdef PetscBool flag = PETSC_FALSE CHKERR( KSPGetInitialGuessKnoll(self.ksp, &flag) ) return toBool(flag) def setUseFischerGuess(self, model, size): cdef PetscInt ival1 = asInt(model) cdef PetscInt ival2 = asInt(size) CHKERR( KSPSetUseFischerGuess(self.ksp, ival1, ival2) ) # --- solving --- def setUp(self): CHKERR( KSPSetUp(self.ksp) ) def reset(self): CHKERR( KSPReset(self.ksp) ) def setUpOnBlocks(self): CHKERR( KSPSetUpOnBlocks(self.ksp) ) def solve(self, Vec b or None, Vec x or None): cdef PetscVec b_vec = NULL cdef PetscVec x_vec = NULL if b is not None: b_vec = b.vec if x is not None: x_vec = x.vec CHKERR( KSPSolve(self.ksp, b_vec, x_vec) ) def solveTranspose(self, Vec b, Vec x): CHKERR( KSPSolveTranspose(self.ksp, b.vec, x.vec) ) def matSolve(self, Mat B, Mat X): CHKERR( KSPMatSolve(self.ksp, B.mat, X.mat) ) def matSolveTranspose(self, Mat B, Mat X): CHKERR( KSPMatSolveTranspose(self.ksp, B.mat, X.mat) ) def setIterationNumber(self, its): cdef PetscInt ival = asInt(its) CHKERR( KSPSetIterationNumber(self.ksp, ival) ) def getIterationNumber(self): cdef PetscInt ival = 0 CHKERR( KSPGetIterationNumber(self.ksp, &ival) ) return toInt(ival) def setResidualNorm(self, rnorm): cdef PetscReal rval = asReal(rnorm) CHKERR( KSPSetResidualNorm(self.ksp, rval) ) def getResidualNorm(self): cdef PetscReal rval = 0 CHKERR( KSPGetResidualNorm(self.ksp, &rval) ) return toReal(rval) def setConvergedReason(self, reason): cdef PetscKSPConvergedReason val = reason CHKERR( KSPSetConvergedReason(self.ksp, val) ) def getConvergedReason(self): cdef PetscKSPConvergedReason reason = KSP_CONVERGED_ITERATING CHKERR( KSPGetConvergedReason(self.ksp, &reason) ) return reason def setErrorIfNotConverged(self, bint flag): cdef PetscBool ernc = PETSC_FALSE if flag: ernc = PETSC_TRUE CHKERR( KSPSetErrorIfNotConverged(self.ksp, ernc) ) def getErrorIfNotConverged(self): cdef PetscBool flag = PETSC_FALSE CHKERR( KSPGetErrorIfNotConverged(self.ksp, &flag) ) return toBool(flag) def getRhs(self): cdef Vec vec = Vec() CHKERR( KSPGetRhs(self.ksp, &vec.vec) ) PetscINCREF(vec.obj) return vec def getSolution(self): cdef Vec vec = Vec() CHKERR( KSPGetSolution(self.ksp, &vec.vec) ) PetscINCREF(vec.obj) return vec def getWorkVecs(self, right=None, left=None): cdef bint R = right is not None cdef bint L = left is not None cdef PetscInt i=0, nr=0, nl=0 cdef PetscVec *vr=NULL, *vl=NULL if R: nr = asInt(right) if L: nl = asInt(left) cdef object vecsr = [] if R else None cdef object vecsl = [] if L else None CHKERR( KSPCreateVecs(self.ksp, nr, &vr, nl, &vr) ) try: for i from 0 <= i < nr: vecsr.append(ref_Vec(vr[i])) for i from 0 <= i < nl: vecsl.append(ref_Vec(vl[i])) finally: if nr > 0 and vr != NULL: VecDestroyVecs(nr, &vr) # XXX errors? if nl > 0 and vl !=NULL: VecDestroyVecs(nl, &vl) # XXX errors? # if R and L: return (vecsr, vecsl) elif R: return vecsr elif L: return vecsl else: return None def buildSolution(self, Vec x=None): if x is None: x = Vec() if x.vec == NULL: CHKERR( KSPGetSolution(self.ksp, &x.vec) ) CHKERR( VecDuplicate(x.vec, &x.vec) ) CHKERR( KSPBuildSolution(self.ksp, x.vec, NULL) ) return x def buildResidual(self, Vec r=None): if r is None: r = Vec() if r.vec == NULL: CHKERR( KSPGetRhs(self.ksp, &r.vec) ) CHKERR( VecDuplicate(r.vec, &r.vec) ) CHKERR( KSPBuildResidual(self.ksp , NULL, r.vec, &r.vec) ) return r def computeEigenvalues(self): cdef PetscInt its = 0 cdef PetscInt neig = 0 cdef PetscReal *rdata = NULL cdef PetscReal *idata = NULL CHKERR( KSPGetIterationNumber(self.ksp, &its) ) cdef ndarray r = oarray_r(empty_r(its), NULL, &rdata) cdef ndarray i = oarray_r(empty_r(its), NULL, &idata) CHKERR( KSPComputeEigenvalues(self.ksp, its, rdata, idata, &neig) ) eigen = empty_c(neig) eigen.real = r[:neig] eigen.imag = i[:neig] return eigen def computeExtremeSingularValues(self): cdef PetscReal smax = 0 cdef PetscReal smin = 0 CHKERR( KSPComputeExtremeSingularValues(self.ksp, &smax, &smin) ) return smax, smin # --- GMRES --- def setGMRESRestart(self, restart): cdef PetscInt ival = asInt(restart) CHKERR( KSPGMRESSetRestart(self.ksp, ival) ) # --- Python --- def createPython(self, context=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscKSP newksp = NULL CHKERR( KSPCreate(ccomm, &newksp) ) PetscCLEAR(self.obj); self.ksp = newksp CHKERR( KSPSetType(self.ksp, KSPPYTHON) ) CHKERR( KSPPythonSetContext(self.ksp, context) ) return self def setPythonContext(self, context): CHKERR( KSPPythonSetContext(self.ksp, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( KSPPythonGetContext(self.ksp, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( KSPPythonSetType(self.ksp, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( KSPPythonGetType(self.ksp, &cval) ) return bytes2str(cval) # --- application context --- property appctx: def __get__(self): return self.getAppCtx() def __set__(self, value): self.setAppCtx(value) # --- discretization space --- property dm: def __get__(self): return self.getDM() def __set__(self, value): self.setDM(value) # --- vectors --- property vec_sol: def __get__(self): return self.getSolution() property vec_rhs: def __get__(self): return self.getRhs() # --- operators --- property mat_op: def __get__(self): return self.getOperators()[0] property mat_pc: def __get__(self): return self.getOperators()[1] # --- initial guess --- property guess_nonzero: def __get__(self): return self.getInitialGuessNonzero() def __set__(self, value): self.setInitialGuessNonzero(value) property guess_knoll: def __get__(self): return self.getInitialGuessKnoll() def __set__(self, value): self.setInitialGuessKnoll(value) # --- preconditioner --- property pc: def __get__(self): return self.getPC() property pc_side: def __get__(self): return self.getPCSide() def __set__(self, value): self.setPCSide(value) property norm_type: def __get__(self): return self.getNormType() def __set__(self, value): self.setNormType(value) # --- tolerances --- property rtol: def __get__(self): return self.getTolerances()[0] def __set__(self, value): self.setTolerances(rtol=value) property atol: def __get__(self): return self.getTolerances()[1] def __set__(self, value): self.setTolerances(atol=value) property divtol: def __get__(self): return self.getTolerances()[2] def __set__(self, value): self.setTolerances(divtol=value) property max_it: def __get__(self): return self.getTolerances()[3] def __set__(self, value): self.setTolerances(max_it=value) # --- iteration --- property its: def __get__(self): return self.getIterationNumber() def __set__(self, value): self.setIterationNumber(value) property norm: def __get__(self): return self.getResidualNorm() def __set__(self, value): self.setResidualNorm(value) property history: def __get__(self): return self.getConvergenceHistory() # --- convergence --- property reason: def __get__(self): return self.getConvergedReason() def __set__(self, value): self.setConvergedReason(value) property iterating: def __get__(self): return self.reason == 0 property converged: def __get__(self): return self.reason > 0 property diverged: def __get__(self): return self.reason < 0 # -------------------------------------------------------------------- del KSPType del KSPNormType del KSPConvergedReason # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Log.pyx000066400000000000000000000241611454104047300201360ustar00rootroot00000000000000# -------------------------------------------------------------------- import functools cdef class Log: @classmethod def Stage(cls, name): if not name: raise ValueError("empty name") cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscLogStage stageid = -1 cdef LogStage stage = get_LogStage(name) if stage is not None: return stage CHKERR( PetscLogStageFindId(cname, &stageid) ) if stageid == -1: CHKERR( PetscLogStageRegister(cname, &stageid) ) stage = reg_LogStage(name, stageid) return stage @classmethod def Class(cls, name): if not name: raise ValueError("empty name") cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscLogClass classid = -1 cdef LogClass klass = get_LogClass(name) if klass is not None: return klass CHKERR( PetscLogClassFindId(cname, &classid) ) if classid == -1: CHKERR( PetscLogClassRegister(cname, &classid) ) klass = reg_LogClass(name, classid) return klass @classmethod def Event(cls, name, klass=None): if not name: raise ValueError("empty name") cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscLogClass classid = PETSC_OBJECT_CLASSID cdef PetscLogEvent eventid = -1 if klass is not None: classid = klass cdef LogEvent event = get_LogEvent(name) if event is not None: return event CHKERR( PetscLogEventFindId(cname, &eventid) ) if eventid == -1: CHKERR( PetscLogEventRegister(cname, classid, &eventid) ) event = reg_LogEvent(name, eventid) return event @classmethod def begin(cls, all=False): if all: CHKERR( PetscLogAllBegin() ) else: CHKERR( PetscLogDefaultBegin() ) @classmethod def view(cls, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr if vwr == NULL: vwr = PETSC_VIEWER_STDOUT_WORLD CHKERR( PetscLogView(vwr) ) @classmethod def logFlops(cls, flops): cdef PetscLogDouble cflops=flops CHKERR( PetscLogFlops(cflops) ) @classmethod def addFlops(cls, flops): cdef PetscLogDouble cflops=flops CHKERR( PetscLogFlops(cflops) ) @classmethod def getFlops(cls): cdef PetscLogDouble cflops=0 CHKERR( PetscGetFlops(&cflops) ) return cflops @classmethod def getTime(cls): cdef PetscLogDouble wctime=0 CHKERR( PetscTime(&wctime) ) return wctime @classmethod def getCPUTime(cls): cdef PetscLogDouble cputime=0 CHKERR( PetscGetCPUTime(&cputime) ) return cputime @classmethod def EventDecorator(cls, name=None, klass=None): """Decorate a function with a PETSc event. If no event name is specified it will default to the name of the function. Usage: @EventDecorator("My Function") def myfunc(): ... or @EventDecorator() def myfunc(): ... """ def decorator(func): @functools.wraps(func) def wrapped_func(*args, **kwargs): if name: name_ = name else: name_ = ".".join([func.__module__, getattr(func, "__qualname__", func.__name__)]) with cls.Event(name_, klass): return func(*args, **kwargs) return wrapped_func return decorator @classmethod def isActive(cls): """Return ``True`` if logging is switched on and ``False`` otherwise.""" cdef PetscBool flag = PETSC_FALSE CHKERR( PetscLogIsActive(&flag) ) return toBool(flag) # -------------------------------------------------------------------- cdef class LogStage: cdef readonly PetscLogStage id def __cinit__(self): self.id = 0 def __int__(self): return self.id def __enter__(self): self.push() return self def __exit__(self, *exc): self.pop() # def push(self): CHKERR( PetscLogStagePush(self.id) ) def pop(self): self # unused CHKERR( PetscLogStagePop() ) # def getName(self): cdef const char *cval = NULL CHKERR( PetscLogStageFindName(self.id, &cval) ) return bytes2str(cval) property name: def __get__(self): return self.getName() def __set__(self, value): self; value; # unused raise TypeError("readonly attribute") # def activate(self): CHKERR( PetscLogStageSetActive(self.id, PETSC_TRUE) ) def deactivate(self): CHKERR( PetscLogStageSetActive(self.id, PETSC_FALSE) ) def getActive(self): cdef PetscBool flag = PETSC_FALSE CHKERR( PetscLogStageGetActive(self.id, &flag) ) return toBool(flag) def setActive(self, flag): cdef PetscBool tval = PETSC_FALSE if flag: tval = PETSC_TRUE CHKERR( PetscLogStageSetActive(self.id, tval) ) property active: def __get__(self): return self.getActive() def __set__(self, value): self.setActive(value) # def getVisible(self): cdef PetscBool flag = PETSC_FALSE CHKERR( PetscLogStageGetVisible(self.id, &flag) ) return toBool(flag) def setVisible(self, flag): cdef PetscBool tval = PETSC_FALSE if flag: tval = PETSC_TRUE CHKERR( PetscLogStageSetVisible(self.id, tval) ) property visible: def __get__(self): return self.getVisible() def __set__(self, value): self.setVisible(value) cdef dict stage_registry = { } cdef LogStage get_LogStage(object name): return stage_registry.get(name) cdef LogStage reg_LogStage(object name, PetscLogStage stageid): cdef LogStage stage = LogStage() stage.id = stageid stage_registry[name] = stage return stage # -------------------------------------------------------------------- cdef class LogClass: cdef readonly PetscLogClass id def __cinit__(self): self.id = PETSC_OBJECT_CLASSID def __int__(self): return self.id # def getName(self): cdef const char *cval = NULL CHKERR( PetscLogClassFindName(self.id, &cval) ) return bytes2str(cval) property name: def __get__(self): return self.getName() def __set__(self, value): self; value; # unused raise TypeError("readonly attribute") # def activate(self): CHKERR( PetscLogClassActivate(self.id) ) def deactivate(self): CHKERR( PetscLogClassDeactivate(self.id) ) def getActive(self): self # unused raise NotImplementedError def setActive(self, flag): if flag: CHKERR( PetscLogClassActivate(self.id) ) else: CHKERR( PetscLogClassDeactivate(self.id) ) property active: def __get__(self): return self.getActive() def __set__(self, value): self.setActive(value) cdef dict class_registry = { } cdef LogClass get_LogClass(object name): return class_registry.get(name) cdef LogClass reg_LogClass(object name, PetscLogClass classid): cdef LogClass klass = LogClass() klass.id = classid class_registry[name] = klass return klass # -------------------------------------------------------------------- cdef class LogEvent: cdef readonly PetscLogEvent id def __cinit__(self): self.id = 0 def __int__(self): return self.id def __enter__(self): self.begin() return self def __exit__(self, *exc): self.end() # def begin(self, *objs): cdef PetscObject o[4] event_args2objs(objs, o) CHKERR( PetscLogEventBegin(self.id, o[0], o[1], o[2], o[3]) ) def end(self, *objs): cdef PetscObject o[4] event_args2objs(objs, o) CHKERR( PetscLogEventEnd(self.id, o[0], o[1], o[2], o[3]) ) # def getName(self): cdef const char *cval = NULL CHKERR( PetscLogEventFindName(self.id, &cval) ) return bytes2str(cval) property name: def __get__(self): return self.getName() def __set__(self, value): self; value; # unused raise TypeError("readonly attribute") # def activate(self): CHKERR( PetscLogEventActivate(self.id) ) def deactivate(self): CHKERR( PetscLogEventDeactivate(self.id) ) def getActive(self): self # unused raise NotImplementedError def setActive(self, flag): if flag: CHKERR( PetscLogEventActivate(self.id) ) else: CHKERR( PetscLogEventDeactivate(self.id) ) property active: def __get__(self): return self.getActive() def __set__(self, value): self.setActive(value) def getActiveAll(self): self # unused raise NotImplementedError def setActiveAll(self, flag): cdef PetscBool tval = PETSC_FALSE if flag: tval = PETSC_TRUE CHKERR( PetscLogEventSetActiveAll(self.id, tval) ) property active_all: def __get__(self): self.getActiveAll() def __set__(self, value): self.setActiveAll(value) # def getPerfInfo(self, stage=None): cdef PetscEventPerfInfo info cdef PetscInt cstage = PETSC_DETERMINE if stage is not None: cstage = asInt(stage) CHKERR( PetscLogEventGetPerfInfo(cstage, self.id, &info) ) return info cdef dict event_registry = { } cdef LogEvent get_LogEvent(object name): return event_registry.get(name) cdef LogEvent reg_LogEvent(object name, PetscLogEvent eventid): cdef LogEvent event = LogEvent() event.id = eventid event_registry[name] = event return event # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Mat.pyx000066400000000000000000002300321454104047300201320ustar00rootroot00000000000000# -------------------------------------------------------------------- class MatType(object): SAME = S_(MATSAME) MAIJ = S_(MATMAIJ) SEQMAIJ = S_(MATSEQMAIJ) MPIMAIJ = S_(MATMPIMAIJ) KAIJ = S_(MATKAIJ) SEQKAIJ = S_(MATSEQKAIJ) MPIKAIJ = S_(MATMPIKAIJ) IS = S_(MATIS) AIJ = S_(MATAIJ) SEQAIJ = S_(MATSEQAIJ) MPIAIJ = S_(MATMPIAIJ) AIJCRL = S_(MATAIJCRL) SEQAIJCRL = S_(MATSEQAIJCRL) MPIAIJCRL = S_(MATMPIAIJCRL) AIJCUSPARSE = S_(MATAIJCUSPARSE) SEQAIJCUSPARSE = S_(MATSEQAIJCUSPARSE) MPIAIJCUSPARSE = S_(MATMPIAIJCUSPARSE) AIJVIENNACL = S_(MATAIJVIENNACL) SEQAIJVIENNACL = S_(MATSEQAIJVIENNACL) MPIAIJVIENNACL = S_(MATMPIAIJVIENNACL) AIJPERM = S_(MATAIJPERM) SEQAIJPERM = S_(MATSEQAIJPERM) MPIAIJPERM = S_(MATMPIAIJPERM) AIJSELL = S_(MATAIJSELL) SEQAIJSELL = S_(MATSEQAIJSELL) MPIAIJSELL = S_(MATMPIAIJSELL) AIJMKL = S_(MATAIJMKL) SEQAIJMKL = S_(MATSEQAIJMKL) MPIAIJMKL = S_(MATMPIAIJMKL) BAIJMKL = S_(MATBAIJMKL) SEQBAIJMKL = S_(MATSEQBAIJMKL) MPIBAIJMKL = S_(MATMPIBAIJMKL) SHELL = S_(MATSHELL) DENSE = S_(MATDENSE) DENSECUDA = S_(MATDENSECUDA) SEQDENSE = S_(MATSEQDENSE) SEQDENSECUDA = S_(MATSEQDENSECUDA) MPIDENSE = S_(MATMPIDENSE) MPIDENSECUDA = S_(MATMPIDENSECUDA) ELEMENTAL = S_(MATELEMENTAL) BAIJ = S_(MATBAIJ) SEQBAIJ = S_(MATSEQBAIJ) MPIBAIJ = S_(MATMPIBAIJ) MPIADJ = S_(MATMPIADJ) SBAIJ = S_(MATSBAIJ) SEQSBAIJ = S_(MATSEQSBAIJ) MPISBAIJ = S_(MATMPISBAIJ) MFFD = S_(MATMFFD) NORMAL = S_(MATNORMAL) NORMALHERMITIAN = S_(MATNORMALHERMITIAN) LRC = S_(MATLRC) SCATTER = S_(MATSCATTER) BLOCKMAT = S_(MATBLOCKMAT) COMPOSITE = S_(MATCOMPOSITE) FFT = S_(MATFFT) FFTW = S_(MATFFTW) SEQCUFFT = S_(MATSEQCUFFT) TRANSPOSE = S_(MATTRANSPOSEVIRTUAL) HERMITIANTRANSPOSE = S_(MATHERMITIANTRANSPOSEVIRTUAL) SCHURCOMPLEMENT = S_(MATSCHURCOMPLEMENT) PYTHON = S_(MATPYTHON) HYPRE = S_(MATHYPRE) HYPRESTRUCT = S_(MATHYPRESTRUCT) HYPRESSTRUCT = S_(MATHYPRESSTRUCT) SUBMATRIX = S_(MATSUBMATRIX) LOCALREF = S_(MATLOCALREF) NEST = S_(MATNEST) PREALLOCATOR = S_(MATPREALLOCATOR) SELL = S_(MATSELL) SEQSELL = S_(MATSEQSELL) MPISELL = S_(MATMPISELL) DUMMY = S_(MATDUMMY) LMVM = S_(MATLMVM) LMVMDFP = S_(MATLMVMDFP) LMVMBFGS = S_(MATLMVMBFGS) LMVMSR1 = S_(MATLMVMSR1) LMVMBROYDEN = S_(MATLMVMBROYDEN) LMVMBADBROYDEN = S_(MATLMVMBADBROYDEN) LMVMSYMBROYDEN = S_(MATLMVMSYMBROYDEN) LMVMSYMBADBROYDEN = S_(MATLMVMSYMBADBROYDEN) LMVMDIAGBBROYDEN = S_(MATLMVMDIAGBROYDEN) CONSTANTDIAGONAL = S_(MATCONSTANTDIAGONAL) H2OPUS = S_(MATH2OPUS) class MatOption(object): OPTION_MIN = MAT_OPTION_MIN UNUSED_NONZERO_LOCATION_ERR = MAT_UNUSED_NONZERO_LOCATION_ERR ROW_ORIENTED = MAT_ROW_ORIENTED SYMMETRIC = MAT_SYMMETRIC STRUCTURALLY_SYMMETRIC = MAT_STRUCTURALLY_SYMMETRIC FORCE_DIAGONAL_ENTRIES = MAT_FORCE_DIAGONAL_ENTRIES IGNORE_OFF_PROC_ENTRIES = MAT_IGNORE_OFF_PROC_ENTRIES USE_HASH_TABLE = MAT_USE_HASH_TABLE KEEP_NONZERO_PATTERN = MAT_KEEP_NONZERO_PATTERN IGNORE_ZERO_ENTRIES = MAT_IGNORE_ZERO_ENTRIES USE_INODES = MAT_USE_INODES HERMITIAN = MAT_HERMITIAN SYMMETRY_ETERNAL = MAT_SYMMETRY_ETERNAL NEW_NONZERO_LOCATION_ERR = MAT_NEW_NONZERO_LOCATION_ERR IGNORE_LOWER_TRIANGULAR = MAT_IGNORE_LOWER_TRIANGULAR ERROR_LOWER_TRIANGULAR = MAT_ERROR_LOWER_TRIANGULAR GETROW_UPPERTRIANGULAR = MAT_GETROW_UPPERTRIANGULAR SPD = MAT_SPD NO_OFF_PROC_ZERO_ROWS = MAT_NO_OFF_PROC_ZERO_ROWS NO_OFF_PROC_ENTRIES = MAT_NO_OFF_PROC_ENTRIES NEW_NONZERO_LOCATIONS = MAT_NEW_NONZERO_LOCATIONS NEW_NONZERO_ALLOCATION_ERR = MAT_NEW_NONZERO_ALLOCATION_ERR SUBSET_OFF_PROC_ENTRIES = MAT_SUBSET_OFF_PROC_ENTRIES SUBMAT_SINGLEIS = MAT_SUBMAT_SINGLEIS STRUCTURE_ONLY = MAT_STRUCTURE_ONLY SORTED_FULL = MAT_SORTED_FULL OPTION_MAX = MAT_OPTION_MAX class MatAssemblyType(object): # native FINAL_ASSEMBLY = MAT_FINAL_ASSEMBLY FLUSH_ASSEMBLY = MAT_FLUSH_ASSEMBLY # aliases FINAL = FINAL_ASSEMBLY FLUSH = FLUSH_ASSEMBLY class MatInfoType(object): LOCAL = MAT_LOCAL GLOBAL_MAX = MAT_GLOBAL_MAX GLOBAL_SUM = MAT_GLOBAL_SUM class MatStructure(object): # native SAME_NONZERO_PATTERN = MAT_SAME_NONZERO_PATTERN DIFFERENT_NONZERO_PATTERN = MAT_DIFFERENT_NONZERO_PATTERN SUBSET_NONZERO_PATTERN = MAT_SUBSET_NONZERO_PATTERN UNKNOWN_NONZERO_PATTERN = MAT_UNKNOWN_NONZERO_PATTERN # aliases SAME = SAME_NZ = SAME_NONZERO_PATTERN SUBSET = SUBSET_NZ = SUBSET_NONZERO_PATTERN DIFFERENT = DIFFERENT_NZ = DIFFERENT_NONZERO_PATTERN UNKNOWN = UNKNOWN_NZ = UNKNOWN_NONZERO_PATTERN class MatDuplicateOption(object): DO_NOT_COPY_VALUES = MAT_DO_NOT_COPY_VALUES COPY_VALUES = MAT_COPY_VALUES SHARE_NONZERO_PATTERN = MAT_SHARE_NONZERO_PATTERN class MatOrderingType(object): NATURAL = S_(MATORDERINGNATURAL) ND = S_(MATORDERINGND) OWD = S_(MATORDERING1WD) RCM = S_(MATORDERINGRCM) QMD = S_(MATORDERINGQMD) ROWLENGTH = S_(MATORDERINGROWLENGTH) WBM = S_(MATORDERINGWBM) SPECTRAL = S_(MATORDERINGSPECTRAL) AMD = S_(MATORDERINGAMD) METISND = S_(MATORDERINGMETISND) class MatSolverType(object): SUPERLU = S_(MATSOLVERSUPERLU) SUPERLU_DIST = S_(MATSOLVERSUPERLU_DIST) STRUMPACK = S_(MATSOLVERSTRUMPACK) UMFPACK = S_(MATSOLVERUMFPACK) CHOLMOD = S_(MATSOLVERCHOLMOD) KLU = S_(MATSOLVERKLU) SPARSEELEMENTAL = S_(MATSOLVERSPARSEELEMENTAL) ELEMENTAL = S_(MATSOLVERELEMENTAL) SCALAPACK = S_(MATSOLVERSCALAPACK) ESSL = S_(MATSOLVERESSL) LUSOL = S_(MATSOLVERLUSOL) MUMPS = S_(MATSOLVERMUMPS) MKL_PARDISO = S_(MATSOLVERMKL_PARDISO) MKL_CPARDISO = S_(MATSOLVERMKL_CPARDISO) PASTIX = S_(MATSOLVERPASTIX) MATLAB = S_(MATSOLVERMATLAB) PETSC = S_(MATSOLVERPETSC) BAS = S_(MATSOLVERBAS) CUSPARSE = S_(MATSOLVERCUSPARSE) CUDA = S_(MATSOLVERCUDA) SPQR = S_(MATSOLVERSPQR) class MatFactorShiftType(object): # native NONE = MAT_SHIFT_NONE NONZERO = MAT_SHIFT_NONZERO POSITIVE_DEFINITE = MAT_SHIFT_POSITIVE_DEFINITE INBLOCKS = MAT_SHIFT_INBLOCKS # aliases NZ = MAT_SHIFT_NONZERO PD = MAT_SHIFT_POSITIVE_DEFINITE class MatSORType(object): FORWARD_SWEEP = SOR_FORWARD_SWEEP BACKWARD_SWEEP = SOR_BACKWARD_SWEEP SYMMETRY_SWEEP = SOR_SYMMETRIC_SWEEP LOCAL_FORWARD_SWEEP = SOR_LOCAL_FORWARD_SWEEP LOCAL_BACKWARD_SWEEP = SOR_LOCAL_BACKWARD_SWEEP LOCAL_SYMMETRIC_SWEEP = SOR_LOCAL_SYMMETRIC_SWEEP ZERO_INITIAL_GUESS = SOR_ZERO_INITIAL_GUESS EISENSTAT = SOR_EISENSTAT APPLY_UPPER = SOR_APPLY_UPPER APPLY_LOWER = SOR_APPLY_LOWER # -------------------------------------------------------------------- cdef class Mat(Object): Type = MatType Option = MatOption AssemblyType = MatAssemblyType InfoType = MatInfoType Structure = MatStructure DuplicateOption = MatDuplicateOption OrderingType = MatOrderingType SolverType = MatSolverType FactorShiftType = MatFactorShiftType SORType = MatSORType # def __cinit__(self): self.obj = &self.mat self.mat = NULL # unary operations def __pos__(self): return mat_pos(self) def __neg__(self): return mat_neg(self) # inplace binary operations def __iadd__(self, other): return mat_iadd(self, other) def __isub__(self, other): return mat_isub(self, other) def __imul__(self, other): return mat_imul(self, other) def __idiv__(self, other): return mat_idiv(self, other) def __itruediv__(self, other): return mat_idiv(self, other) # binary operations def __add__(self, other): if isinstance(self, Mat): return mat_add(self, other) else: return mat_radd(other, self) def __sub__(self, other): if isinstance(self, Mat): return mat_sub(self, other) else: return mat_rsub(other, self) def __mul__(self, other): if isinstance(self, Mat): if isinstance(other, Vec): return mat_mul_vec(self, other) else: return mat_mul(self, other) else: return mat_rmul(other, self) def __div__(self, other): if isinstance(self, Mat): return mat_div(self, other) else: return mat_rdiv(other, self) def __truediv__(self, other): if isinstance(self, Mat): return mat_div(self, other) else: return mat_rdiv(other, self) # def __getitem__(self, ij): return mat_getitem(self, ij) def __setitem__(self, ij, v): mat_setitem(self, ij, v) def __call__(self, x, y=None): if y is None: y = self.createVecLeft() self.mult(x, y) return y # def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( MatView(self.mat, vwr) ) def destroy(self): CHKERR( MatDestroy(&self.mat) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscMat newmat = NULL CHKERR( MatCreate(ccomm, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def setType(self, mat_type): cdef PetscMatType cval = NULL mat_type = str2bytes(mat_type, &cval) CHKERR( MatSetType(self.mat, cval) ) def setSizes(self, size, bsize=None): cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 Mat_Sizes(size, bsize, &rbs, &cbs, &m, &n, &M, &N) CHKERR( MatSetSizes(self.mat, m, n, M, N) ) if rbs != PETSC_DECIDE: if cbs != PETSC_DECIDE: CHKERR( MatSetBlockSizes(self.mat, rbs, cbs) ) else: CHKERR( MatSetBlockSize(self.mat, rbs) ) def setBlockSize(self, bsize): cdef PetscInt bs = asInt(bsize) CHKERR( MatSetBlockSize(self.mat, bs) ) def setBlockSizes(self, row_bsize, col_bsize): cdef PetscInt rbs = asInt(row_bsize) cdef PetscInt cbs = asInt(col_bsize) CHKERR( MatSetBlockSizes(self.mat, rbs, cbs) ) def setVecType(self, vec_type): cdef PetscVecType cval = NULL vec_type = str2bytes(vec_type, &cval) CHKERR( MatSetVecType(self.mat, cval) ) def getVecType(self): cdef PetscVecType cval = NULL CHKERR( MatGetVecType(self.mat, &cval) ) return bytes2str(cval) # def createAIJ(self, size, bsize=None, nnz=None, csr=None, comm=None): # create matrix cdef PetscMat newmat = NULL Mat_Create(MATAIJ, comm, size, bsize, &newmat) PetscCLEAR(self.obj); self.mat = newmat # preallocate matrix Mat_AllocAIJ(self.mat, nnz, csr) return self def createBAIJ(self, size, bsize, nnz=None, csr=None, comm=None): # create matrix cdef PetscMat newmat = NULL Mat_Create(MATBAIJ, comm, size, bsize, &newmat) PetscCLEAR(self.obj); self.mat = newmat # preallocate matrix Mat_AllocAIJ(self.mat, nnz, csr) return self def createSBAIJ(self, size, bsize, nnz=None, csr=None, comm=None): # create matrix cdef PetscMat newmat = NULL Mat_Create(MATSBAIJ, comm, size, bsize, &newmat) PetscCLEAR(self.obj); self.mat = newmat # preallocate matrix Mat_AllocAIJ(self.mat, nnz, csr) return self def createAIJCRL(self, size, bsize=None, nnz=None, csr=None, comm=None): # create matrix cdef PetscMat newmat = NULL Mat_Create(MATAIJCRL, comm, size, bsize, &newmat) PetscCLEAR(self.obj); self.mat = newmat # preallocate matrix Mat_AllocAIJ(self.mat, nnz, csr) return self def setPreallocationNNZ(self, nnz): cdef PetscBool done = PETSC_FALSE CHKERR( MatIsPreallocated(self.mat, &done) ) # if done: raise Error(PETSC_ERR_ORDER) Mat_AllocAIJ_NNZ(self.mat, nnz) return self def setPreallocationCSR(self, csr): cdef PetscBool done = PETSC_FALSE CHKERR( MatIsPreallocated(self.mat, &done) ) # if done: raise Error(PETSC_ERR_ORDER) Mat_AllocAIJ_CSR(self.mat, csr) return self def createAIJWithArrays(self, size, csr, bsize=None, comm=None): # communicator cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) # sizes and block sizes cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 Mat_Sizes(size, bsize, &rbs, &cbs, &m, &n, &M, &N) if rbs == PETSC_DECIDE: rbs = 1 if cbs == PETSC_DECIDE: cbs = rbs Sys_Layout(ccomm, rbs, &m, &M) Sys_Layout(ccomm, cbs, &n, &N) # unpack CSR argument cdef object pi, pj, pv, poi, poj, pov try: (pi, pj, pv), (poi, poj, pov) = csr except (TypeError, ValueError): pi, pj, pv = csr poi = poj = pov = None # rows, cols, and values cdef PetscInt ni=0, noi=0, *i=NULL, *oi=NULL cdef PetscInt nj=0, noj=0, *j=NULL, *oj=NULL pi = iarray_i(pi, &ni, &i) # Row pointers (diagonal) pj = iarray_i(pj, &nj, &j) # Column indices (diagonal) if ni != m+1: raise ValueError( "A matrix with %d rows requires a row pointer of length %d (given: %d)" % (toInt(m), toInt(m+1), toInt(ni))) if poi is not None and poj is not None: poi = iarray_i(poi, &noi, &oi) # Row pointers (off-diagonal) poj = iarray_i(poj, &noj, &oj) # Column indices (off-diagonal) cdef PetscInt nv=0, nov=0 cdef PetscScalar *v=NULL, *ov=NULL pv = iarray_s(pv, &nv, &v) # Non-zero values (diagonal) if nj != nv: raise ValueError( "Given %d column indices but %d non-zero values" % (toInt(nj), toInt(nv))) if pov is not None: pov = iarray_s(pov, &nov, &ov) # Non-zero values (off-diagonal) # create matrix cdef PetscMat newmat = NULL if comm_size(ccomm) == 1: CHKERR( MatCreateSeqAIJWithArrays( ccomm, m, n, i, j, v, &newmat) ) csr = (pi, pj, pv) else: if oi != NULL and oj != NULL and ov != NULL: CHKERR( MatCreateMPIAIJWithSplitArrays( ccomm, m, n, M, N, i, j, v, oi, oj, ov, &newmat) ) csr = ((pi, pj, pv), (poi, poj, pov)) else: CHKERR( MatCreateMPIAIJWithArrays( ccomm, m, n, M, N, i, j, v, &newmat) ) csr = None PetscCLEAR(self.obj); self.mat = newmat self.set_attr('__csr__', csr) return self # def createDense(self, size, bsize=None, array=None, comm=None): # create matrix cdef PetscMat newmat = NULL Mat_Create(MATDENSE, comm, size, bsize, &newmat) PetscCLEAR(self.obj); self.mat = newmat # preallocate matrix if array is not None: array = Mat_AllocDense(self.mat, array) self.set_attr('__array__', array) return self def createDenseCUDA(self, size, bsize=None, array=None, cudahandle=None, comm=None): """ Returns an instance of :class:`Mat`, a MATDENSECUDA with user provided memory spaces for CPU and GPU arrays. :arg size: A list denoting the size of the Mat. :arg bsize: A :class:`int` denoting the block size. :arg array: A :class:`numpy.ndarray`. Will be lazily allocated if *None*. :arg cudahandle: Address of the array on the GPU. Will be lazily allocated if *None*. If cudahandle is provided, array will be ignored. :arg comm: MPI communicator """ # create matrix cdef PetscMat newmat = NULL # communicator cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) # sizes and block sizes cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 if cudahandle is not None: Mat_Sizes(size, None, &rbs, &cbs, &m, &n, &M, &N) if rbs == PETSC_DECIDE: rbs = 1 if cbs == PETSC_DECIDE: cbs = rbs Sys_Layout(ccomm, rbs, &m, &M) Sys_Layout(ccomm, cbs, &n, &N) # create matrix and set sizes CHKERR( MatCreateDenseCUDA(ccomm, m, n, M, N, (cudahandle), &newmat) ) # Does block size make sense for MATDENSE? CHKERR( MatSetBlockSizes(newmat, rbs, cbs) ) else: Mat_Create(MATDENSECUDA, comm, size, bsize, &newmat) if array is not None: array = Mat_AllocDense(self.mat, array) self.set_attr('__array__', array) PetscCLEAR(self.obj); self.mat = newmat return self def setPreallocationDense(self, array): cdef PetscBool done = PETSC_FALSE CHKERR( MatIsPreallocated(self.mat, &done) ) # if done: raise Error(PETSC_ERR_ORDER) array = Mat_AllocDense(self.mat, array) self.set_attr('__array__', array) return self # def createScatter(self, Scatter scatter, comm=None): if comm is None: comm = scatter.getComm() cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscMat newmat = NULL CHKERR( MatCreateScatter(ccomm, scatter.sct, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createNormal(self, Mat mat): cdef PetscMat newmat = NULL CHKERR( MatCreateNormal(mat.mat, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createTranspose(self, Mat mat): cdef PetscMat newmat = NULL CHKERR( MatCreateTranspose(mat.mat, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createNormalHermitian(self, Mat mat): cdef PetscMat newmat = NULL CHKERR( MatCreateNormalHermitian(mat.mat, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createHermitianTranspose(self, Mat mat): cdef PetscMat newmat = NULL CHKERR( MatCreateHermitianTranspose(mat.mat, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createLRC(self, Mat A or None, Mat U, Vec c or None, Mat V or None): cdef PetscMat Amat = NULL cdef PetscMat Umat = U.mat cdef PetscVec cvec = NULL cdef PetscMat Vmat = NULL cdef PetscMat newmat = NULL if A is not None: Amat = A.mat if c is not None: cvec = c.vec if V is not None: Vmat = V.mat CHKERR( MatCreateLRC(Amat, Umat, cvec, Vmat, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createSubMatrixVirtual(self, Mat A, IS isrow, IS iscol=None): if iscol is None: iscol = isrow cdef PetscMat newmat = NULL CHKERR( MatCreateSubMatrixVirtual(A.mat, isrow.iset, iscol.iset, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createNest(self, mats, isrows=None, iscols=None, comm=None): cdef object mat mats = [list(mat) for mat in mats] if isrows: isrows = list(isrows) assert len(isrows) == len(mats) else: isrows = None if iscols: iscols = list(iscols) assert len(iscols) == len(mats[0]) else: iscols = None cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Py_ssize_t i, mr = len(mats) cdef Py_ssize_t j, mc = len(mats[0]) cdef PetscInt nr = mr cdef PetscInt nc = mc cdef PetscMat *cmats = NULL cdef PetscIS *cisrows = NULL cdef PetscIS *ciscols = NULL cdef object tmp1, tmp2, tmp3 tmp1 = oarray_p(empty_p(nr*nc), NULL, &cmats) for i from 0 <= i < mr: for j from 0 <= j < mc: mat = mats[i][j] cmats[i*mc+j] = (mat).mat if mat is not None else NULL if isrows is not None: tmp2 = oarray_p(empty_p(nr), NULL, &cisrows) for i from 0 <= i < mr: cisrows[i] = (isrows[i]).iset if iscols is not None: tmp3 = oarray_p(empty_p(nc), NULL, &ciscols) for j from 0 <= j < mc: ciscols[j] = (iscols[j]).iset cdef PetscMat newmat = NULL CHKERR( MatCreateNest(ccomm, nr, cisrows, nc, ciscols, cmats, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createH2OpusFromMat(self, Mat A, coordinates=None, dist=None, eta=None, leafsize=None, maxrank=None, bs=None, rtol=None): cdef PetscInt cdim = 1 cdef PetscReal *coords = NULL cdef PetscBool cdist = PETSC_FALSE cdef PetscReal peta = PETSC_DECIDE cdef PetscInt lsize = PETSC_DECIDE cdef PetscInt maxr = PETSC_DECIDE cdef PetscInt pbs = PETSC_DECIDE cdef PetscReal tol = PETSC_DECIDE cdef ndarray xyz cdef PetscInt nvtx cdef PetscInt rl = 0, cl = 0 if dist is not None: cdist = asBool(dist) if eta is not None: peta = asReal(eta) if leafsize is not None: lsize = asInt(leafsize) if maxrank is not None: maxr = asInt(maxrank) if bs is not None: pbs = asInt(bs) if rtol is not None: tol = asReal(rtol) if coordinates is not None: xyz = iarray(coordinates, NPY_PETSC_REAL) if PyArray_ISFORTRAN(xyz): xyz = PyArray_Copy(xyz) if PyArray_NDIM(xyz) != 2: raise ValueError( ("coordinates must have two dimensions: " "coordinates.ndim=%d") % (PyArray_NDIM(xyz)) ) nvtx = PyArray_DIM(xyz, 0) CHKERR( MatGetLocalSize(A.mat, &rl, &cl) ) if cl != rl: raise ValueError("Not for rectangular matrices") if nvtx < rl: raise ValueError( ("coordinates size must be at least %d" % rl )) cdim = PyArray_DIM(xyz, 1) coords = PyArray_DATA(xyz) cdef PetscMat newmat = NULL CHKERR( MatCreateH2OpusFromMat(A.mat, cdim, coords, cdist, peta, lsize, maxr, pbs, tol, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createIS(self, size, LGMap lgmapr=None, LGMap lgmapc=None, comm=None): # communicator and sizes if comm is None and lgmapr is not None: comm = lgmapr.getComm() if comm is None and lgmapc is not None: comm = lgmapc.getComm() cdef PetscLGMap lgmr = NULL cdef PetscLGMap lgmc = NULL cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 Mat_Sizes(size, None, &rbs, &cbs, &m, &n, &M, &N) Sys_Layout(ccomm, rbs, &m, &M) Sys_Layout(ccomm, cbs, &n, &N) # create matrix cdef PetscMat newmat = NULL cdef PetscInt bs = 1 if rbs == cbs: bs = rbs if lgmapr is not None: lgmr = lgmapr.lgm if lgmapc is not None: lgmc = lgmapc.lgm CHKERR( MatCreateIS(ccomm, bs, m, n, M, N, lgmr, lgmc, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat return self def createPython(self, size, context=None, comm=None): # communicator and sizes cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 Mat_Sizes(size, None, &rbs, &cbs, &m, &n, &M, &N) Sys_Layout(ccomm, rbs, &m, &M) Sys_Layout(ccomm, cbs, &n, &N) # create matrix cdef PetscMat newmat = NULL CHKERR( MatCreate(ccomm, &newmat) ) PetscCLEAR(self.obj); self.mat = newmat CHKERR( MatSetSizes(self.mat, m, n, M, N) ) CHKERR( MatSetType(self.mat, MATPYTHON) ) CHKERR( MatPythonSetContext(self.mat, context) ) return self def setPythonContext(self, context): CHKERR( MatPythonSetContext(self.mat, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( MatPythonGetContext(self.mat, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( MatPythonSetType(self.mat, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( MatPythonGetType(self.mat, &cval) ) return bytes2str(cval) # def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MatSetOptionsPrefix(self.mat, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( MatGetOptionsPrefix(self.mat, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( MatAppendOptionsPrefix(self.mat, cval) ) def setFromOptions(self): CHKERR( MatSetFromOptions(self.mat) ) def setUp(self): CHKERR( MatSetUp(self.mat) ) return self def setOption(self, option, flag): CHKERR( MatSetOption(self.mat, option, flag) ) def getOption(self, option): cdef PetscBool flag = PETSC_FALSE CHKERR( MatGetOption(self.mat, option, &flag) ) return toBool(flag) def getType(self): cdef PetscMatType cval = NULL CHKERR( MatGetType(self.mat, &cval) ) return bytes2str(cval) def getSize(self): cdef PetscInt M = 0, N = 0 CHKERR( MatGetSize(self.mat, &M, &N) ) return (toInt(M), toInt(N)) def getLocalSize(self): cdef PetscInt m = 0, n = 0 CHKERR( MatGetLocalSize(self.mat, &m, &n) ) return (toInt(m), toInt(n)) def getSizes(self): cdef PetscInt m = 0, n = 0 cdef PetscInt M = 0, N = 0 CHKERR( MatGetLocalSize(self.mat, &m, &n) ) CHKERR( MatGetSize(self.mat, &M, &N) ) return ((toInt(m), toInt(M)), (toInt(n), toInt(N))) def getBlockSize(self): cdef PetscInt bs = 0 CHKERR( MatGetBlockSize(self.mat, &bs) ) return toInt(bs) def getBlockSizes(self): cdef PetscInt rbs = 0, cbs = 0 CHKERR( MatGetBlockSizes(self.mat, &rbs, &cbs) ) return (toInt(rbs), toInt(cbs)) def getOwnershipRange(self): cdef PetscInt ival1 = 0, ival2 = 0 CHKERR( MatGetOwnershipRange(self.mat, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def getOwnershipRanges(self): cdef const PetscInt *rowrng = NULL CHKERR( MatGetOwnershipRanges(self.mat, &rowrng) ) cdef MPI_Comm comm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.mat, &comm) ) cdef int size = -1 CHKERR( MPI_Comm_size(comm, &size) ) return array_i(size+1, rowrng) def getOwnershipRangeColumn(self): cdef PetscInt ival1 = 0, ival2 = 0 CHKERR( MatGetOwnershipRangeColumn(self.mat, &ival1, &ival2) ) return (toInt(ival1), toInt(ival2)) def getOwnershipRangesColumn(self): cdef const PetscInt *colrng = NULL CHKERR( MatGetOwnershipRangesColumn(self.mat, &colrng) ) cdef MPI_Comm comm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.mat, &comm) ) cdef int size = -1 CHKERR( MPI_Comm_size(comm, &size) ) return array_i(size+1, colrng) def getOwnershipIS(self): cdef IS rows = IS() cdef IS cols = IS() CHKERR( MatGetOwnershipIS(self.mat, &rows.iset, &cols.iset) ) return (rows, cols) def getInfo(self, info=None): cdef PetscMatInfoType itype = infotype(info) cdef PetscMatInfo cinfo CHKERR( MatGetInfo(self.mat, itype, &cinfo) ) return cinfo def duplicate(self, copy=False): cdef PetscMatDuplicateOption flag = MAT_DO_NOT_COPY_VALUES if copy: flag = MAT_COPY_VALUES if copy > MAT_COPY_VALUES: flag = MAT_SHARE_NONZERO_PATTERN cdef Mat mat = type(self)() CHKERR( MatDuplicate(self.mat, flag, &mat.mat) ) return mat def copy(self, Mat result=None, structure=None): cdef PetscMatDuplicateOption copy = MAT_COPY_VALUES cdef PetscMatStructure mstr = matstructure(structure) if result is None: result = type(self)() if result.mat == NULL: CHKERR( MatDuplicate(self.mat, copy, &result.mat) ) else: CHKERR( MatCopy(self.mat, result.mat, mstr) ) return result def load(self, Viewer viewer): cdef MPI_Comm comm = MPI_COMM_NULL cdef PetscObject obj = (viewer.vwr) if self.mat == NULL: CHKERR( PetscObjectGetComm(obj, &comm) ) CHKERR( MatCreate(comm, &self.mat) ) CHKERR( MatLoad(self.mat, viewer.vwr) ) return self def convert(self, mat_type=None, Mat out=None): cdef PetscMatType mtype = MATSAME cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX mat_type = str2bytes(mat_type, &mtype) if mtype == NULL: mtype = MATSAME if out is None: out = self if out.mat == self.mat: reuse = MAT_INPLACE_MATRIX elif out.mat == NULL: reuse = MAT_INITIAL_MATRIX else: reuse = MAT_REUSE_MATRIX CHKERR( MatConvert(self.mat, mtype, reuse, &out.mat) ) return out def transpose(self, Mat out=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX if out is None: out = self if out.mat == self.mat: reuse = MAT_INPLACE_MATRIX elif out.mat == NULL: reuse = MAT_INITIAL_MATRIX else: reuse = MAT_REUSE_MATRIX CHKERR( MatTranspose(self.mat, reuse, &out.mat) ) return out def setTransposePrecursor(self, Mat out): CHKERR( MatTransposeSetPrecursor(self.mat, out.mat) ) return out def hermitianTranspose(self, Mat out=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX if out is None: out = self if out.mat == self.mat: reuse = MAT_INPLACE_MATRIX elif out.mat == NULL: reuse = MAT_INITIAL_MATRIX else: reuse = MAT_REUSE_MATRIX CHKERR( MatHermitianTranspose(self.mat, reuse, &out.mat) ) return out def realPart(self, Mat out=None): if out is None: out = self elif out.mat == NULL: CHKERR( MatDuplicate(self.mat, MAT_COPY_VALUES, &out.mat) ) CHKERR( MatRealPart(out.mat) ) return out def imagPart(self, Mat out=None): if out is None: out = self elif out.mat == NULL: CHKERR( MatDuplicate(self.mat, MAT_COPY_VALUES, &out.mat) ) CHKERR( MatImaginaryPart(out.mat) ) return out def conjugate(self, Mat out=None): if out is None: out = self elif out.mat == NULL: CHKERR( MatDuplicate(self.mat, MAT_COPY_VALUES, &out.mat) ) CHKERR( MatConjugate(out.mat) ) return out def permute(self, IS row, IS col): cdef Mat mat = Mat() CHKERR( MatPermute(self.mat, row.iset, col.iset, &mat.mat) ) return mat def equal(self, Mat mat): cdef PetscBool flag = PETSC_FALSE CHKERR( MatEqual(self.mat, mat.mat, &flag) ) return toBool(flag) def isTranspose(self, Mat mat=None, tol=0): if mat is None: mat = self cdef PetscReal rval = asReal(tol) cdef PetscBool flag = PETSC_FALSE CHKERR( MatIsTranspose(self.mat, mat.mat, rval, &flag) ) return toBool(flag) def isSymmetric(self, tol=0): cdef PetscReal rval = asReal(tol) cdef PetscBool flag = PETSC_FALSE CHKERR( MatIsSymmetric(self.mat, rval, &flag) ) return toBool(flag) def isSymmetricKnown(self): cdef PetscBool flag1 = PETSC_FALSE cdef PetscBool flag2 = PETSC_FALSE CHKERR( MatIsSymmetricKnown(self.mat, &flag1, &flag2) ) return (toBool(flag1), toBool(flag2)) def isHermitian(self, tol=0): cdef PetscReal rval = asReal(tol) cdef PetscBool flag = PETSC_FALSE CHKERR( MatIsHermitian(self.mat, rval, &flag) ) return toBool(flag) def isHermitianKnown(self): cdef PetscBool flag1 = PETSC_FALSE cdef PetscBool flag2 = PETSC_FALSE CHKERR( MatIsHermitianKnown(self.mat, &flag1, &flag2) ) return (toBool(flag1), toBool(flag2)) def isStructurallySymmetric(self): cdef PetscBool flag = PETSC_FALSE CHKERR( MatIsStructurallySymmetric(self.mat, &flag) ) return toBool(flag) def zeroEntries(self): CHKERR( MatZeroEntries(self.mat) ) def getValue(self, row, col): cdef PetscInt ival1 = asInt(row) cdef PetscInt ival2 = asInt(col) cdef PetscScalar sval = 0 CHKERR( MatGetValues(self.mat, 1, &ival1, 1, &ival2, &sval) ) return toScalar(sval) def getValues(self, rows, cols, values=None): return matgetvalues(self.mat, rows, cols, values) def getValuesCSR(self): # row ownership cdef PetscInt rstart=0, rend=0, nrows=0 CHKERR( MatGetOwnershipRange(self.mat, &rstart, &rend) ) nrows = rend - rstart # first pass: row pointer array cdef PetscInt *AI = NULL cdef ndarray ai = oarray_i(empty_i(nrows+1), NULL, &AI) cdef PetscInt irow=0, ncols=0 AI[0] = 0 for irow from 0 <= irow < nrows: CHKERR( MatGetRow(self.mat, irow+rstart, &ncols, NULL, NULL) ) AI[irow+1] = AI[irow] + ncols CHKERR( MatRestoreRow(self.mat, irow+rstart, &ncols, NULL, NULL) ) # second pass: column indices and values cdef PetscInt *AJ = NULL cdef ndarray aj = oarray_i(empty_i(AI[nrows]), NULL, &AJ) cdef PetscScalar *AV = NULL cdef ndarray av = oarray_s(empty_s(AI[nrows]), NULL, &AV) cdef const PetscInt *cols = NULL cdef const PetscScalar *vals = NULL for irow from 0 <= irow < nrows: CHKERR( MatGetRow(self.mat, irow+rstart, &ncols, &cols, &vals) ) CHKERR( PetscMemcpy(AJ+AI[irow], cols, ncols*sizeof(PetscInt)) ) CHKERR( PetscMemcpy(AV+AI[irow], vals, ncols*sizeof(PetscScalar)) ) CHKERR( MatRestoreRow(self.mat, irow+rstart, &ncols, &cols, &vals) ) # return (ai, aj, av) def getRow(self, row): cdef PetscInt irow = asInt(row) cdef PetscInt ncols = 0 cdef const PetscInt *icols=NULL cdef const PetscScalar *svals=NULL CHKERR( MatGetRow(self.mat, irow, &ncols, &icols, &svals) ) cdef object cols = array_i(ncols, icols) cdef object vals = array_s(ncols, svals) CHKERR( MatRestoreRow(self.mat, irow, &ncols, &icols, &svals) ) return (cols, vals) def getRowIJ(self, symmetric=False, compressed=False): cdef PetscInt shift=0 cdef PetscBool symm=symmetric cdef PetscBool bcmp=compressed cdef PetscInt n=0 cdef const PetscInt *ia=NULL cdef const PetscInt *ja=NULL cdef PetscBool done=PETSC_FALSE CHKERR( MatGetRowIJ(self.mat, shift, symm, bcmp, &n, &ia, &ja, &done) ) cdef object ai=None, aj=None if done != PETSC_FALSE: ai = array_i( n+1, ia) if done != PETSC_FALSE: aj = array_i(ia[n], ja) CHKERR( MatRestoreRowIJ(self.mat, shift, symm, bcmp, &n, &ia, &ja, &done) ) return (ai, aj) def getColumnIJ(self, symmetric=False, compressed=False): cdef PetscInt shift=0 cdef PetscBool symm=symmetric, bcmp=compressed cdef PetscInt n=0 cdef const PetscInt *ia=NULL cdef const PetscInt *ja=NULL cdef PetscBool done=PETSC_FALSE CHKERR( MatGetColumnIJ(self.mat, shift, symm, bcmp, &n, &ia, &ja, &done) ) cdef object ai=None, aj=None if done != PETSC_FALSE: ai = array_i( n+1, ia) if done != PETSC_FALSE: aj = array_i(ia[n], ja) CHKERR( MatRestoreColumnIJ(self.mat, shift, symm, bcmp, &n, &ia, &ja, &done) ) return (ai, aj) def setValue(self, row, col, value, addv=None): cdef PetscInt ival1 = asInt(row) cdef PetscInt ival2 = asInt(col) cdef PetscScalar sval = asScalar(value) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( MatSetValues(self.mat, 1, &ival1, 1, &ival2, &sval, caddv) ) def setValues(self, rows, cols, values, addv=None): matsetvalues(self.mat, rows, cols, values, addv, 0, 0) def setValuesRCV(self, R, C, V, addv=None): matsetvalues_rcv(self.mat, R, C, V, addv, 0, 0) def setValuesIJV(self, I, J, V, addv=None, rowmap=None): matsetvalues_ijv(self.mat, I, J, V, addv, rowmap, 0, 0) def setValuesCSR(self, I, J, V, addv=None): matsetvalues_csr(self.mat, I, J, V, addv, 0, 0) def setValuesBlocked(self, rows, cols, values, addv=None): matsetvalues(self.mat, rows, cols, values, addv, 1, 0) def setValuesBlockedRCV(self, R, C, V, addv=None): matsetvalues_rcv(self.mat, R, C, V, addv, 1, 0) def setValuesBlockedIJV(self, I, J, V, addv=None, rowmap=None): matsetvalues_ijv(self.mat, I, J, V, addv, rowmap, 1, 0) def setValuesBlockedCSR(self, I, J, V, addv=None): matsetvalues_csr(self.mat, I, J, V, addv, 1, 0) def setLGMap(self, LGMap rmap, LGMap cmap=None): if cmap is None: cmap = rmap CHKERR( MatSetLocalToGlobalMapping(self.mat, rmap.lgm, cmap.lgm) ) def getLGMap(self): cdef LGMap cmap = LGMap() cdef LGMap rmap = LGMap() CHKERR( MatGetLocalToGlobalMapping(self.mat, &rmap.lgm, &cmap.lgm) ) PetscINCREF(cmap.obj) PetscINCREF(rmap.obj) return (rmap, cmap) def setValueLocal(self, row, col, value, addv=None): cdef PetscInt ival1 = asInt(row) cdef PetscInt ival2 = asInt(col) cdef PetscScalar sval = asScalar(value) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( MatSetValuesLocal( self.mat, 1, &ival1, 1, &ival2, &sval, caddv) ) def setValuesLocal(self, rows, cols, values, addv=None): matsetvalues(self.mat, rows, cols, values, addv, 0, 1) def setValuesLocalRCV(self, R, C, V, addv=None): matsetvalues_rcv(self.mat, R, C, V, addv, 0, 1) def setValuesLocalIJV(self, I, J, V, addv=None, rowmap=None): matsetvalues_ijv(self.mat, I, J, V, addv, rowmap, 0, 1) def setValuesLocalCSR(self, I, J, V, addv=None): matsetvalues_csr(self.mat, I, J, V, addv, 0, 1) def setValuesBlockedLocal(self, rows, cols, values, addv=None): matsetvalues(self.mat, rows, cols, values, addv, 1, 1) def setValuesBlockedLocalRCV(self, R, C, V, addv=None): matsetvalues_rcv(self.mat, R, C, V, addv, 1, 1) def setValuesBlockedLocalIJV(self, I, J, V, addv=None, rowmap=None): matsetvalues_ijv(self.mat, I, J, V, addv, rowmap, 1, 1) def setValuesBlockedLocalCSR(self, I, J, V, addv=None): matsetvalues_csr(self.mat, I, J, V, addv, 1, 1) # Stencil = _Mat_Stencil def setStencil(self, dims, starts=None, dof=1): cdef PetscInt ndim, ndof cdef PetscInt cdims[3], cstarts[3] cdims[0] = cdims[1] = cdims[2] = 1 cstarts[0] = cstarts[1] = cstarts[2] = 0 ndim = asDims(dims, &cdims[0], &cdims[1], &cdims[2]) ndof = asInt(dof) if starts is not None: asDims(dims, &cstarts[0], &cstarts[1], &cstarts[2]) CHKERR( MatSetStencil(self.mat, ndim, cdims, cstarts, ndof) ) def setValueStencil(self, row, col, value, addv=None): cdef _Mat_Stencil r = row, c = col cdef PetscInsertMode im = insertmode(addv) matsetvaluestencil(self.mat, r, c, value, im, 0) def setValueStagStencil(self, row, col, value, addv=None): raise NotImplementedError('setValueStagStencil not yet implemented in petsc4py') def setValueBlockedStencil(self, row, col, value, addv=None): cdef _Mat_Stencil r = row, c = col cdef PetscInsertMode im = insertmode(addv) matsetvaluestencil(self.mat, r, c, value, im, 1) def setValueBlockedStagStencil(self, row, col, value, addv=None): raise NotImplementedError('setValueBlockedStagStencil not yet implemented in petsc4py') def zeroRows(self, rows, diag=1, Vec x=None, Vec b=None): cdef PetscInt ni=0, *i=NULL cdef PetscScalar sval = asScalar(diag) cdef PetscVec xvec=NULL, bvec=NULL if x is not None: xvec = x.vec if b is not None: bvec = b.vec if isinstance(rows, IS): CHKERR( MatZeroRowsIS(self.mat, (rows).iset, sval, xvec, bvec) ) else: rows = iarray_i(rows, &ni, &i) CHKERR( MatZeroRows(self.mat, ni, i, sval, xvec, bvec) ) def zeroRowsLocal(self, rows, diag=1, Vec x=None, Vec b=None): cdef PetscInt ni=0, *i=NULL cdef PetscScalar sval = asScalar(diag) cdef PetscVec xvec=NULL, bvec=NULL if x is not None: xvec = x.vec if b is not None: bvec = b.vec if isinstance(rows, IS): CHKERR( MatZeroRowsLocalIS(self.mat, (rows).iset, sval, xvec, bvec) ) else: rows = iarray_i(rows, &ni, &i) CHKERR( MatZeroRowsLocal(self.mat, ni, i, sval, xvec, bvec) ) def zeroRowsColumns(self, rows, diag=1, Vec x=None, Vec b=None): cdef PetscInt ni=0, *i=NULL cdef PetscScalar sval = asScalar(diag) cdef PetscVec xvec=NULL, bvec=NULL if x is not None: xvec = x.vec if b is not None: bvec = b.vec if isinstance(rows, IS): CHKERR( MatZeroRowsColumnsIS(self.mat, (rows).iset, sval, xvec, bvec) ) else: rows = iarray_i(rows, &ni, &i) CHKERR( MatZeroRowsColumns(self.mat, ni, i, sval, xvec, bvec) ) def zeroRowsColumnsLocal(self, rows, diag=1, Vec x=None, Vec b=None): cdef PetscInt ni=0, *i=NULL cdef PetscScalar sval = asScalar(diag) cdef PetscVec xvec=NULL, bvec=NULL if x is not None: xvec = x.vec if b is not None: bvec = b.vec if isinstance(rows, IS): CHKERR( MatZeroRowsColumnsLocalIS(self.mat, (rows).iset, sval, xvec, bvec) ) else: rows = iarray_i(rows, &ni, &i) CHKERR( MatZeroRowsColumnsLocal(self.mat, ni, i, sval, xvec, bvec) ) def zeroRowsColumnsStencil(self, rows, diag=1, Vec x=None, Vec b=None): cdef PetscScalar sval = asScalar(diag) cdef PetscInt nrows = asInt(len(rows)) cdef PetscMatStencil st cdef _Mat_Stencil r cdef PetscMatStencil *crows = NULL CHKERR( PetscMalloc((nrows+1)*sizeof(st), &crows) ) for i in range(nrows): r = rows[i] crows[i] = r.stencil cdef PetscVec xvec = NULL, bvec = NULL if x is not None: xvec = x.vec if b is not None: bvec = b.vec CHKERR( MatZeroRowsColumnsStencil(self.mat, nrows, crows, sval, xvec, bvec) ) CHKERR( PetscFree( crows ) ) def storeValues(self): CHKERR( MatStoreValues(self.mat) ) def retrieveValues(self): CHKERR( MatRetrieveValues(self.mat) ) def assemblyBegin(self, assembly=None): cdef PetscMatAssemblyType flag = assemblytype(assembly) CHKERR( MatAssemblyBegin(self.mat, flag) ) def assemblyEnd(self, assembly=None): cdef PetscMatAssemblyType flag = assemblytype(assembly) CHKERR( MatAssemblyEnd(self.mat, flag) ) def assemble(self, assembly=None): cdef PetscMatAssemblyType flag = assemblytype(assembly) CHKERR( MatAssemblyBegin(self.mat, flag) ) CHKERR( MatAssemblyEnd(self.mat, flag) ) def isAssembled(self): cdef PetscBool flag = PETSC_FALSE CHKERR( MatAssembled(self.mat, &flag) ) return toBool(flag) def findZeroRows(self): cdef IS zerorows = IS() CHKERR( MatFindZeroRows(self.mat, &zerorows.iset) ) return zerorows def createVecs(self, side=None): cdef Vec vecr, vecl if side is None: vecr = Vec(); vecl = Vec(); CHKERR( MatCreateVecs(self.mat, &vecr.vec, &vecl.vec) ) return (vecr, vecl) elif side in ('r', 'R', 'right', 'Right', 'RIGHT'): vecr = Vec() CHKERR( MatCreateVecs(self.mat, &vecr.vec, NULL) ) return vecr elif side in ('l', 'L', 'left', 'Left', 'LEFT'): vecl = Vec() CHKERR( MatCreateVecs(self.mat, NULL, &vecl.vec) ) return vecl else: raise ValueError("side '%r' not understood" % side) def createVecRight(self): cdef Vec vecr = Vec() CHKERR( MatCreateVecs(self.mat, &vecr.vec, NULL) ) return vecr def createVecLeft(self): cdef Vec vecl = Vec() CHKERR( MatCreateVecs(self.mat, NULL, &vecl.vec) ) return vecl getVecs = createVecs getVecRight = createVecRight getVecLeft = createVecLeft # def getColumnVector(self, column, Vec result=None): cdef PetscInt ival = asInt(column) if result is None: result = Vec() if result.vec == NULL: CHKERR( MatCreateVecs(self.mat, NULL, &result.vec) ) CHKERR( MatGetColumnVector(self.mat, result.vec, ival) ) return result def getRedundantMatrix(self, nsubcomm, subcomm=None, Mat out=None): cdef PetscInt _nsubcomm = asInt(nsubcomm) cdef MPI_Comm _subcomm = MPI_COMM_NULL if subcomm: _subcomm = def_Comm(subcomm, PETSC_COMM_DEFAULT) cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX if out is None: out = Mat() if out.mat != NULL: reuse = MAT_REUSE_MATRIX CHKERR( MatCreateRedundantMatrix(self.mat, _nsubcomm, _subcomm, reuse, &out.mat)) return out def getDiagonal(self, Vec result=None): if result is None: result = Vec() if result.vec == NULL: CHKERR( MatCreateVecs(self.mat, NULL, &result.vec) ) CHKERR( MatGetDiagonal(self.mat, result.vec) ) return result def getRowSum(self, Vec result=None): if result is None: result = Vec() if result.vec == NULL: CHKERR( MatCreateVecs(self.mat, NULL, &result.vec) ) CHKERR( MatGetRowSum(self.mat, result.vec) ) return result def setDiagonal(self, Vec diag, addv=None): cdef PetscInsertMode caddv = insertmode(addv) CHKERR( MatDiagonalSet(self.mat, diag.vec, caddv) ) def diagonalScale(self, Vec L=None, Vec R=None): cdef PetscVec vecl=NULL, vecr=NULL if L is not None: vecl = L.vec if R is not None: vecr = R.vec CHKERR( MatDiagonalScale(self.mat, vecl, vecr) ) def invertBlockDiagonal(self): cdef PetscInt bs = 0, m = 0 cdef const PetscScalar *cibdiag = NULL CHKERR( MatGetBlockSize(self.mat, &bs) ) CHKERR( MatGetLocalSize(self.mat, &m, NULL) ) CHKERR( MatInvertBlockDiagonal(self.mat, &cibdiag) ) cdef ndarray ibdiag = array_s(m*bs, cibdiag) ibdiag.shape = (toInt(m//bs), toInt(bs), toInt(bs)) return ibdiag.transpose(0, 2, 1) # null space def setNullSpace(self, NullSpace nsp): CHKERR( MatSetNullSpace(self.mat, nsp.nsp) ) def getNullSpace(self): cdef NullSpace nsp = NullSpace() CHKERR( MatGetNullSpace(self.mat, &nsp.nsp) ) PetscINCREF(nsp.obj) return nsp def setTransposeNullSpace(self, NullSpace nsp): CHKERR( MatSetTransposeNullSpace(self.mat, nsp.nsp) ) def getTransposeNullSpace(self): cdef NullSpace nsp = NullSpace() CHKERR( MatGetTransposeNullSpace(self.mat, &nsp.nsp) ) PetscINCREF(nsp.obj) return nsp def setNearNullSpace(self, NullSpace nsp): CHKERR( MatSetNearNullSpace(self.mat, nsp.nsp) ) def getNearNullSpace(self): cdef NullSpace nsp = NullSpace() CHKERR( MatGetNearNullSpace(self.mat, &nsp.nsp) ) PetscINCREF(nsp.obj) return nsp # matrix-vector product def mult(self, Vec x, Vec y): CHKERR( MatMult(self.mat, x.vec, y.vec) ) def multAdd(self, Vec x, Vec v, Vec y): CHKERR( MatMultAdd(self.mat, x.vec, v.vec, y.vec) ) def multTranspose(self, Vec x, Vec y): CHKERR( MatMultTranspose(self.mat, x.vec, y.vec) ) def multTransposeAdd(self, Vec x, Vec v, Vec y): CHKERR( MatMultTransposeAdd(self.mat, x.vec, v.vec, y.vec) ) def multHermitian(self, Vec x, Vec y): CHKERR( MatMultHermitian(self.mat, x.vec, y.vec) ) def multHermitianAdd(self, Vec x, Vec v, Vec y): CHKERR( MatMultHermitianAdd(self.mat, x.vec, v.vec, y.vec) ) # SOR def SOR(self, Vec b, Vec x, omega=1.0, sortype=None, shift=0.0, its=1, lits=1): cdef PetscReal comega = asReal(omega) cdef PetscMatSORType csortype = SOR_LOCAL_SYMMETRIC_SWEEP if sortype is not None: csortype = asInt(sortype) cdef PetscInt cshift = asInt(shift) cdef PetscInt cits = asInt(its) cdef PetscInt clits = asInt(lits) CHKERR( MatSOR(self.mat, b.vec, comega, csortype, cshift, cits, clits, x.vec) ) # def getDiagonalBlock(self): cdef Mat submat = Mat() CHKERR( MatGetDiagonalBlock(self.mat, &submat.mat) ) PetscINCREF(submat.obj) return submat def increaseOverlap(self, IS iset, overlap=1): cdef PetscInt ival = asInt(overlap) CHKERR( MatIncreaseOverlap(self.mat, 1, &iset.iset, ival) ) def createSubMatrix(self, IS isrow, IS iscol=None, Mat submat=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscIS ciscol = NULL if iscol is not None: ciscol = iscol.iset if submat is None: submat = Mat() if submat.mat != NULL: reuse = MAT_REUSE_MATRIX CHKERR( MatCreateSubMatrix(self.mat, isrow.iset, ciscol, reuse, &submat.mat) ) return submat def createSubMatrices(self, isrows, iscols=None, submats=None): if iscols is None: iscols = isrows isrows = [isrows] if isinstance(isrows, IS) else list(isrows) iscols = [iscols] if isinstance(iscols, IS) else list(iscols) assert len(isrows) == len(iscols) cdef Py_ssize_t i, n = len(isrows) cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscIS *cisrows = NULL cdef PetscIS *ciscols = NULL cdef PetscMat *cmats = NULL cdef object tmp1, tmp2 cdef Mat mat tmp1 = oarray_p(empty_p(n), NULL, &cisrows) for i from 0 <= i < n: cisrows[i] = (isrows[i]).iset tmp2 = oarray_p(empty_p(n), NULL, &ciscols) for i from 0 <= i < n: ciscols[i] = (iscols[i]).iset if submats is not None: reuse = MAT_REUSE_MATRIX submats = list(submats) assert len(submats) == len(isrows) CHKERR( PetscMalloc((n+1)*sizeof(PetscMat), &cmats) ) for i from 0 <= i < n: cmats[i] = (submats[i]).mat CHKERR( MatCreateSubMatrices(self.mat, n, cisrows, ciscols, reuse, &cmats) ) for i from 0 <= i < n: PetscINCREF(&cmats[i]) if reuse == MAT_INITIAL_MATRIX: submats = [None] * n for i from 0 <= i < n: submats[i] = mat = Mat() mat.mat = cmats[i] CHKERR( MatDestroyMatrices(n, &cmats) ) return submats # def getLocalSubMatrix(self, IS isrow, IS iscol, Mat submat=None): if submat is None: submat = Mat() else: CHKERR( MatDestroy(&submat.mat) ) CHKERR( MatGetLocalSubMatrix(self.mat, isrow.iset, iscol.iset, &submat.mat) ) return submat def restoreLocalSubMatrix(self, IS isrow, IS iscol, Mat submat): CHKERR( MatRestoreLocalSubMatrix(self.mat, isrow.iset, iscol.iset, &submat.mat) ) # def norm(self, norm_type=None): cdef PetscNormType norm_1_2 = PETSC_NORM_1_AND_2 cdef PetscNormType ntype = PETSC_NORM_FROBENIUS if norm_type is not None: ntype = norm_type cdef PetscReal rval[2] CHKERR( MatNorm(self.mat, ntype, rval) ) if ntype != norm_1_2: return toReal(rval[0]) else: return (toReal(rval[0]), toReal(rval[1])) def scale(self, alpha): cdef PetscScalar sval = asScalar(alpha) CHKERR( MatScale(self.mat, sval) ) def shift(self, alpha): cdef PetscScalar sval = asScalar(alpha) CHKERR( MatShift(self.mat, sval) ) def chop(self, tol): cdef PetscReal rval = asReal(tol) CHKERR( MatChop(self.mat, rval) ) def setRandom(self, Random random=None): cdef PetscRandom rnd = NULL if random is not None: rnd = random.rnd CHKERR( MatSetRandom(self.mat, rnd) ) def axpy(self, alpha, Mat X, structure=None): cdef PetscScalar sval = asScalar(alpha) cdef PetscMatStructure flag = matstructure(structure) CHKERR( MatAXPY(self.mat, sval, X.mat, flag) ) def aypx(self, alpha, Mat X, structure=None): cdef PetscScalar sval = asScalar(alpha) cdef PetscMatStructure flag = matstructure(structure) CHKERR( MatAYPX(self.mat, sval, X.mat, flag) ) # matrix-matrix product def matMult(self, Mat mat, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal rval = 2 if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: rval = asReal(fill) CHKERR( MatMatMult(self.mat, mat.mat, reuse, rval, &result.mat) ) return result def matTransposeMult(self, Mat mat, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal rval = 2 if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: rval = asReal(fill) CHKERR( MatMatTransposeMult(self.mat, mat.mat, reuse, rval, &result.mat) ) return result def transposeMatMult(self, Mat mat, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal rval = 2 if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: rval = asReal(fill) CHKERR( MatTransposeMatMult(self.mat, mat.mat, reuse, rval, &result.mat) ) return result def ptap(self, Mat P, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal cfill = PETSC_DEFAULT if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: cfill = asReal(fill) CHKERR( MatPtAP(self.mat, P.mat, reuse, cfill, &result.mat) ) return result def rart(self, Mat R, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal cfill = PETSC_DEFAULT if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: cfill = asReal(fill) CHKERR( MatRARt(self.mat, R.mat, reuse, cfill, &result.mat) ) return result def matMatMult(self, Mat B, Mat C, Mat result=None, fill=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX cdef PetscReal cfill = PETSC_DEFAULT if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX if fill is not None: cfill = asReal(fill) CHKERR( MatMatMatMult(self.mat, B.mat, C.mat, reuse, cfill, &result.mat) ) return result def kron(self, Mat mat, Mat result=None): cdef PetscMatReuse reuse = MAT_INITIAL_MATRIX if result is None: result = Mat() elif result.mat != NULL: reuse = MAT_REUSE_MATRIX CHKERR( MatSeqAIJKron(self.mat, mat.mat, reuse, &result.mat) ) return result def bindToCPU(self, flg): cdef PetscBool bindFlg = asBool(flg) CHKERR( MatBindToCPU(self.mat, bindFlg) ) def boundToCPU(self): cdef PetscBool flg = PETSC_TRUE CHKERR( MatBoundToCPU(self.mat, &flg) ) return toBool(flg) # XXX factorization def getOrdering(self, ord_type): cdef PetscMatOrderingType cval = NULL ord_type = str2bytes(ord_type, &cval) cdef IS rp = IS(), cp = IS() CHKERR( MatGetOrdering(self.mat, cval, &rp.iset, &cp.iset) ) return (rp, cp) def reorderForNonzeroDiagonal(self, IS isrow, IS iscol, atol=0): cdef PetscReal rval = asReal(atol) cdef PetscIS rp = isrow.iset, cp = iscol.iset CHKERR( MatReorderForNonzeroDiagonal(self.mat, rval, rp, cp) ) def factorLU(self, IS isrow, IS iscol, options=None): cdef PetscMatFactorInfo info matfactorinfo(PETSC_FALSE, PETSC_FALSE, options, &info) CHKERR( MatLUFactor(self.mat, isrow.iset, iscol.iset, &info) ) def factorSymbolicLU(self, Mat mat, IS isrow, IS iscol, options=None): self; mat; isrow; iscol; options; # unused raise NotImplementedError def factorNumericLU(self, Mat mat, options=None): self; mat; options; # unused raise NotImplementedError def factorILU(self, IS isrow, IS iscol, options=None): cdef PetscMatFactorInfo info matfactorinfo(PETSC_TRUE, PETSC_FALSE, options, &info) CHKERR( MatILUFactor(self.mat, isrow.iset, iscol.iset, &info) ) def factorSymbolicILU(self, IS isrow, IS iscol, options=None): self; isrow; iscol; options; # unused raise NotImplementedError def factorCholesky(self, IS isperm, options=None): cdef PetscMatFactorInfo info matfactorinfo(PETSC_FALSE, PETSC_TRUE, options, &info) CHKERR( MatCholeskyFactor(self.mat, isperm.iset, &info) ) def factorSymbolicCholesky(self, IS isperm, options=None): self; isperm; options; # unused raise NotImplementedError def factorNumericCholesky(self, Mat mat, options=None): self; mat; options; # unused raise NotImplementedError def factorICC(self, IS isperm, options=None): cdef PetscMatFactorInfo info matfactorinfo(PETSC_TRUE, PETSC_TRUE, options, &info) CHKERR( MatICCFactor(self.mat, isperm.iset, &info) ) def factorSymbolicICC(self, IS isperm, options=None): self; isperm; options; # unused raise NotImplementedError def getInertia(self): cdef PetscInt ival1 = 0, ival2 = 0, ival3 = 0 CHKERR( MatGetInertia(self.mat, &ival1, &ival2, &ival3) ) return (toInt(ival1), toInt(ival2), toInt(ival3)) def setUnfactored(self): CHKERR( MatSetUnfactored(self.mat) ) # IS def fixISLocalEmpty(self, fix): cdef PetscBool cfix = asBool(fix) CHKERR( MatISFixLocalEmpty(self.mat, cfix) ) def getISLocalMat(self): cdef Mat local = Mat() CHKERR( MatISGetLocalMat(self.mat, &local.mat) ) PetscINCREF(local.obj) return local def restoreISLocalMat(self, Mat local not None): CHKERR( MatISRestoreLocalMat(self.mat, &local.mat) ) def setISLocalMat(self, Mat local not None): CHKERR( MatISSetLocalMat(self.mat, local.mat) ) def setISPreallocation(self, nnz, onnz): cdef PetscInt *cnnz = NULL cdef PetscInt *connz = NULL nnz = iarray_i(nnz, NULL, &cnnz) onnz = iarray_i(onnz, NULL, &connz) CHKERR( MatISSetPreallocation(self.mat, 0, cnnz, 0, connz) ) return self # LRC def getLRCMats(self): cdef Mat A = Mat() cdef Mat U = Mat() cdef Vec c = Vec() cdef Mat V = Mat() CHKERR( MatLRCGetMats(self.mat, &A.mat, &U.mat, &c.vec, &V.mat) ) PetscINCREF(A.obj) PetscINCREF(U.obj) PetscINCREF(c.obj) PetscINCREF(V.obj) return (A, U, c, V) # H2Opus def H2OpusOrthogonalize(self): CHKERR( MatH2OpusOrthogonalize(self.mat) ) return self def H2OpusCompress(self, tol): cdef PetscReal _tol = asReal(tol) CHKERR( MatH2OpusCompress(self.mat, _tol) ) return self def H2OpusLowRankUpdate(self, Mat U, Mat V=None, s = 1.0): cdef PetscScalar _s = asScalar(s) cdef PetscMat vmat = NULL if V is not None: vmat = V.mat CHKERR( MatH2OpusLowRankUpdate(self.mat, U.mat, vmat, _s) ) return self # MUMPS def setMumpsIcntl(self, icntl, ival): cdef PetscInt _icntl = asInt(icntl) cdef PetscInt _ival = asInt(ival) CHKERR( MatMumpsSetIcntl(self.mat, _icntl, _ival) ); def getMumpsIcntl(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscInt ival = 0 CHKERR( MatMumpsGetIcntl(self.mat, _icntl, &ival) ); return toInt(ival) def setMumpsCntl(self, icntl, val): cdef PetscInt _icntl = asInt(icntl) cdef PetscReal _val = asReal(val) CHKERR( MatMumpsSetCntl(self.mat, _icntl, _val) ); def getMumpsCntl(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscReal val = 0 CHKERR( MatMumpsGetCntl(self.mat, _icntl, &val) ); return toReal(val) def getMumpsInfo(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscInt ival = 0 CHKERR( MatMumpsGetInfo(self.mat, _icntl, &ival) ); return toInt(ival) def getMumpsInfog(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscInt ival = 0 CHKERR( MatMumpsGetInfog(self.mat, _icntl, &ival) ); return toInt(ival) def getMumpsRinfo(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscReal val = 0 CHKERR( MatMumpsGetRinfo(self.mat, _icntl, &val) ); return toReal(val) def getMumpsRinfog(self, icntl): cdef PetscInt _icntl = asInt(icntl) cdef PetscReal val = 0 CHKERR( MatMumpsGetRinfog(self.mat, _icntl, &val) ); return toReal(val) # solve def solveForward(self, Vec b, Vec x): CHKERR( MatForwardSolve(self.mat, b.vec, x.vec) ) def solveBackward(self, Vec b, Vec x): CHKERR( MatBackwardSolve(self.mat, b.vec, x.vec) ) def solve(self, Vec b, Vec x): CHKERR( MatSolve(self.mat, b.vec, x.vec) ) def solveTranspose(self, Vec b, Vec x): CHKERR( MatSolveTranspose(self.mat, b.vec, x.vec) ) def solveAdd(self, Vec b, Vec y, Vec x): CHKERR( MatSolveAdd(self.mat, b.vec, y.vec, x.vec) ) def solveTransposeAdd(self, Vec b, Vec y, Vec x): CHKERR( MatSolveTransposeAdd(self.mat, b.vec, y.vec, x.vec) ) def matSolve(self, Mat B, Mat X): CHKERR( MatMatSolve(self.mat, B.mat, X.mat) ) # dense matrices def setDenseLDA(self, lda): cdef PetscInt _ilda = asInt(lda) CHKERR( MatDenseSetLDA(self.mat, _ilda) ) def getDenseLDA(self): cdef PetscInt lda=0 CHKERR( MatDenseGetLDA(self.mat, &lda) ) return toInt(lda) def getDenseArray(self,readonly=False): cdef PetscInt m=0, N=0, lda=0 cdef PetscScalar *data = NULL CHKERR( MatGetLocalSize(self.mat, &m, NULL) ) CHKERR( MatGetSize(self.mat, NULL, &N) ) CHKERR( MatDenseGetLDA(self.mat, &lda) ) if readonly: CHKERR( MatDenseGetArrayRead(self.mat, &data) ) else: CHKERR( MatDenseGetArray(self.mat, &data) ) cdef int typenum = NPY_PETSC_SCALAR cdef int itemsize = sizeof(PetscScalar) cdef int flags = NPY_ARRAY_FARRAY cdef npy_intp dims[2], strides[2] dims[0] = m; strides[0] = sizeof(PetscScalar); dims[1] = N; strides[1] = (lda*sizeof(PetscScalar)); array = PyArray_New(ndarray, 2, dims, typenum, strides, data, itemsize, flags, NULL) if readonly: CHKERR( MatDenseRestoreArrayRead(self.mat, &data) ) else: CHKERR( MatDenseRestoreArray(self.mat, &data) ) return array def getDenseLocalMatrix(self): cdef Mat mat = type(self)() CHKERR( MatDenseGetLocalMatrix(self.mat, &mat.mat) ) PetscINCREF(mat.obj) return mat def getDenseColumnVec(self, i, mode='rw'): if mode is None: mode = 'rw' if mode not in ['rw', 'r', 'w']: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") cdef Vec v = Vec() cdef PetscInt _i = asInt(i) if mode == 'rw': CHKERR( MatDenseGetColumnVec(self.mat, _i, &v.vec) ) elif mode == 'r': CHKERR( MatDenseGetColumnVecRead(self.mat, _i, &v.vec) ) else: CHKERR( MatDenseGetColumnVecWrite(self.mat, _i, &v.vec) ) PetscINCREF(v.obj) return v def restoreDenseColumnVec(self, i, mode='rw'): cdef PetscInt _i = asInt(i) if mode == 'rw': CHKERR( MatDenseRestoreColumnVec(self.mat, _i, NULL) ) elif mode == 'r': CHKERR( MatDenseRestoreColumnVecRead(self.mat, _i, NULL) ) else: CHKERR( MatDenseRestoreColumnVecWrite(self.mat, _i, NULL) ) # Nest def getNestSize(self): cdef PetscInt nrows, ncols CHKERR( MatNestGetSize(self.mat, &nrows, &ncols) ) return toInt(nrows), toInt(ncols) def getNestISs(self): cdef PetscInt i, nrows =0, ncols = 0 cdef PetscIS *cisrows = NULL cdef PetscIS *ciscols = NULL CHKERR( MatNestGetSize(self.mat, &nrows, &ncols) ) cdef object tmpr = oarray_p(empty_p(nrows), NULL, &cisrows) cdef object tmpc = oarray_p(empty_p(ncols), NULL, &ciscols) CHKERR( MatNestGetISs(self.mat, cisrows, ciscols) ) cdef object isetsrows = [ref_IS(cisrows[i]) for i from 0 <= i < nrows] cdef object isetscols = [ref_IS(ciscols[i]) for i from 0 <= i < ncols] return isetsrows, isetscols def getNestLocalISs(self): cdef PetscInt i, nrows =0, ncols = 0 cdef PetscIS *cisrows = NULL cdef PetscIS *ciscols = NULL CHKERR( MatNestGetSize(self.mat, &nrows, &ncols) ) cdef object tmpr = oarray_p(empty_p(nrows), NULL, &cisrows) cdef object tmpc = oarray_p(empty_p(ncols), NULL, &ciscols) CHKERR( MatNestGetLocalISs(self.mat, cisrows, ciscols) ) cdef object isetsrows = [ref_IS(cisrows[i]) for i from 0 <= i < nrows] cdef object isetscols = [ref_IS(ciscols[i]) for i from 0 <= i < ncols] return isetsrows, isetscols def getNestSubMatrix(self, i, j): cdef Mat submat = Mat() cdef PetscInt idxm = asInt(i) cdef PetscInt jdxm = asInt(j) CHKERR( MatNestGetSubMat(self.mat, idxm, jdxm, &submat.mat) ) PetscINCREF(submat.obj) return submat # MatIS def getISLocalMat(self): cdef Mat localmat = type(self)() CHKERR( MatISGetLocalMat(self.mat, &localmat.mat) ) PetscINCREF(localmat.obj) return localmat # DM def getDM(self): cdef PetscDM newdm = NULL CHKERR( MatGetDM(self.mat, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setDM(self, DM dm): CHKERR( MatSetDM(self.mat, dm.dm) ) # backward compatibility PtAP = ptap # property sizes: def __get__(self): return self.getSizes() def __set__(self, value): self.setSizes(value) property size: def __get__(self): return self.getSize() property local_size: def __get__(self): return self.getLocalSize() property block_size: def __get__(self): return self.getBlockSize() property block_sizes: def __get__(self): return self.getBlockSizes() property owner_range: def __get__(self): return self.getOwnershipRange() property owner_ranges: def __get__(self): return self.getOwnershipRanges() # property assembled: def __get__(self): return self.isAssembled() property symmetric: def __get__(self): return self.isSymmetric() property hermitian: def __get__(self): return self.isHermitian() property structsymm: def __get__(self): return self.isStructurallySymmetric() # TODO Stream def __dlpack__(self, stream=-1): return self.toDLPack('rw') def __dlpack_device__(self): (dltype, devId, _, _, _) = mat_get_dlpack_ctx(self) return (dltype, devId) def toDLPack(self, mode='rw'): if mode is None: mode = 'rw' if mode not in ['rw', 'r', 'w']: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") cdef int64_t ndim = 0 (device_type, device_id, ndim, shape, strides) = mat_get_dlpack_ctx(self) hostmem = (device_type == kDLCPU) cdef DLManagedTensor* dlm_tensor = malloc(sizeof(DLManagedTensor)) cdef DLTensor* dl_tensor = &dlm_tensor.dl_tensor cdef PetscScalar *a = NULL cdef int64_t* shape_strides = NULL dl_tensor.byte_offset = 0 # DLPack does not currently play well with our get/restore model # Call restore right-away and hope that the consumer will do the right thing # and not modify memory requested with read access # By restoring now, we guarantee the sanity of the ObjectState if mode == 'w': if hostmem: CHKERR( MatDenseGetArrayWrite(self.mat, &a) ) CHKERR( MatDenseRestoreArrayWrite(self.mat, NULL) ) else: CHKERR( MatDenseCUDAGetArrayWrite(self.mat, &a) ) CHKERR( MatDenseCUDARestoreArrayWrite(self.mat, NULL) ) elif mode == 'r': if hostmem: CHKERR( MatDenseGetArrayRead(self.mat, &a) ) CHKERR( MatDenseRestoreArrayRead(self.mat, NULL) ) else: CHKERR( MatDenseCUDAGetArrayRead(self.mat, &a) ) CHKERR( MatDenseCUDARestoreArrayRead(self.mat, NULL) ) else: if hostmem: CHKERR( MatDenseGetArray(self.mat, &a) ) CHKERR( MatDenseRestoreArray(self.mat, NULL) ) else: CHKERR( MatDenseCUDAGetArray(self.mat, &a) ) CHKERR( MatDenseCUDARestoreArray(self.mat, NULL) ) dl_tensor.data = a cdef DLContext* ctx = &dl_tensor.ctx ctx.device_type = device_type ctx.device_id = device_id shape_strides = malloc(sizeof(int64_t)*2*ndim) for i in range(ndim): shape_strides[i] = shape[i] for i in range(ndim): shape_strides[i+ndim] = strides[i] dl_tensor.ndim = ndim dl_tensor.shape = shape_strides dl_tensor.strides = shape_strides + ndim cdef DLDataType* dtype = &dl_tensor.dtype dtype.code = DLDataTypeCode.kDLFloat if sizeof(PetscScalar) == 8: dtype.bits = 64 elif sizeof(PetscScalar) == 4: dtype.bits = 32 else: raise ValueError('Unsupported PetscScalar type') dtype.lanes = 1 dlm_tensor.manager_ctx = self.mat CHKERR( PetscObjectReference(self.mat) ) dlm_tensor.manager_deleter = manager_deleter dlm_tensor.del_obj = PetscDEALLOC return PyCapsule_New(dlm_tensor, 'dltensor', pycapsule_deleter) # -------------------------------------------------------------------- cdef class NullSpace(Object): # def __cinit__(self): self.obj = &self.nsp self.nsp = NULL def __call__(self, vec): self.remove(vec) # def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( MatNullSpaceView(self.nsp, vwr) ) def destroy(self): CHKERR( MatNullSpaceDestroy(&self.nsp) ) return self def create(self, constant=False, vectors=(), comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscBool has_const = PETSC_FALSE if constant: has_const = PETSC_TRUE cdef PetscInt i = 0, nv = len(vectors) cdef PetscVec *v = NULL cdef object tmp2 = oarray_p(empty_p(nv), NULL, &v) for i from 0 <= i < nv: v[i] = ((vectors[i])).vec cdef PetscNullSpace newnsp = NULL CHKERR( MatNullSpaceCreate(ccomm, has_const, nv, v, &newnsp) ) PetscCLEAR(self.obj); self.nsp = newnsp return self def createRigidBody(self, Vec coords): cdef PetscNullSpace newnsp = NULL CHKERR( MatNullSpaceCreateRigidBody(coords.vec, &newnsp) ) PetscCLEAR(self.obj); self.nsp = newnsp return self def setFunction(self, function, args=None, kargs=None): if function is not None: CHKERR( MatNullSpaceSetFunction( self.nsp, NullSpace_Function, NULL) ) if args is None: args = () if kargs is None: kargs = {} self.set_attr('__function__', (function, args, kargs)) else: CHKERR( MatNullSpaceSetFunction(self.nsp, NULL, NULL) ) self.set_attr('__function__', None) # def hasConstant(self): cdef PetscBool flag = PETSC_FALSE CHKERR( MatNullSpaceGetVecs(self.nsp, &flag, NULL, NULL) ) return toBool(flag) def getVecs(self): cdef PetscInt i = 0, nv = 0 cdef const PetscVec *v = NULL CHKERR( MatNullSpaceGetVecs(self.nsp, NULL, &nv, &v) ) cdef Vec vec = None cdef list vectors = [] for i from 0 <= i < nv: vec = Vec() vec.vec = v[i] PetscINCREF(vec.obj) vectors.append(vec) return vectors def getFunction(self): return self.get_attr('__function__') # def remove(self, Vec vec): CHKERR( MatNullSpaceRemove(self.nsp, vec.vec) ) def test(self, Mat mat): cdef PetscBool flag = PETSC_FALSE CHKERR( MatNullSpaceTest(self.nsp, mat.mat, &flag) ) return toBool(flag) # -------------------------------------------------------------------- del MatType del MatOption del MatAssemblyType del MatInfoType del MatStructure del MatDuplicateOption del MatOrderingType del MatSolverType del MatFactorShiftType del MatSORType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/MatPartitioning.pyx000066400000000000000000000042001454104047300225160ustar00rootroot00000000000000# -------------------------------------------------------------------- class MatPartitioningType(object): PARTITIONINGCURRENT = S_(MATPARTITIONINGCURRENT) PARTITIONINGAVERAGE = S_(MATPARTITIONINGAVERAGE) PARTITIONINGSQUARE = S_(MATPARTITIONINGSQUARE) PARTITIONINGPARMETIS = S_(MATPARTITIONINGPARMETIS) PARTITIONINGCHACO = S_(MATPARTITIONINGCHACO) PARTITIONINGPARTY = S_(MATPARTITIONINGPARTY) PARTITIONINGPTSCOTCH = S_(MATPARTITIONINGPTSCOTCH) PARTITIONINGHIERARCH = S_(MATPARTITIONINGHIERARCH) # -------------------------------------------------------------------- cdef class MatPartitioning(Object): Type = MatPartitioningType def __cinit__(self): self.obj = &self.part self.part = NULL def __call__(self): return self.getValue() def view(self, Viewer viewer=None): assert self.obj != NULL cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( MatPartitioningView(self.part, vwr) ) def destroy(self): CHKERR( MatPartitioningDestroy(&self.part) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) CHKERR( MatPartitioningCreate(ccomm, &self.part) ) return self def setType(self, matpartitioning_type): cdef PetscMatPartitioningType cval = NULL matpartitioning_type = str2bytes(matpartitioning_type, &cval) CHKERR( MatPartitioningSetType(self.part, cval) ) def getType(self): cdef PetscMatPartitioningType cval = NULL CHKERR( MatPartitioningGetType(self.part, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( MatPartitioningSetFromOptions(self.part) ) def setAdjacency(self, Mat adj): CHKERR( MatPartitioningSetAdjacency(self.part, adj.mat) ) def apply(self, IS partitioning): CHKERR( MatPartitioningApply(self.part, &partitioning.iset) ) # -------------------------------------------------------------------- del MatPartitioningType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Object.pyx000066400000000000000000000207661454104047300206320ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class Object: # --- special methods --- def __cinit__(self): self.oval = NULL self.obj = &self.oval def __dealloc__(self): CHKERR( PetscDEALLOC(&self.obj[0]) ) self.obj = NULL def __richcmp__(self, other, int op): if not isinstance(self, Object): return NotImplemented if not isinstance(other, Object): return NotImplemented cdef Object s = self, o = other if op == 2: return (s.obj[0] == o.obj[0]) elif op == 3: return (s.obj[0] != o.obj[0]) else: raise TypeError("only '==' and '!='") def __nonzero__(self): return self.obj[0] != NULL def __copy__(self): cdef Object obj = type(self)() cdef PetscObject o = self.obj[0] if o != NULL: CHKERR( PetscObjectReference(o) ) obj.obj[0] = o return obj def __deepcopy__(self, dict memo): cdef object obj_copy = None try: obj_copy = self.copy except AttributeError: raise NotImplementedError memo # unused return obj_copy() # --- attribute management --- cdef object get_attr(self, char name[]): return PetscGetPyObj(self.obj[0], name) cdef object set_attr(self, char name[], object attr): return PetscSetPyObj(self.obj[0], name, attr) cdef object get_dict(self): return PetscGetPyDict(self.obj[0], True) # def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscObjectView(self.obj[0], vwr) ) def destroy(self): CHKERR( PetscObjectDestroy(&self.obj[0]) ) return self def getType(self): cdef const char *cval = NULL CHKERR( PetscObjectGetType(self.obj[0], &cval) ) return bytes2str(cval) # def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PetscObjectSetOptionsPrefix(self.obj[0], cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( PetscObjectGetOptionsPrefix(self.obj[0], &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PetscObjectAppendOptionsPrefix(self.obj[0], cval) ) def setFromOptions(self): CHKERR( PetscObjectSetFromOptions(self.obj[0]) ) def viewFromOptions(self, name, Object prefix=None): cdef PetscObject pobj = NULL cdef const char *cval = NULL pobj = prefix.obj[0] if prefix is not None else NULL name = str2bytes(name, &cval) CHKERR( PetscObjectViewFromOptions(self.obj[0], pobj, cval) ) # def getComm(self): cdef Comm comm = Comm() CHKERR( PetscObjectGetComm(self.obj[0], &comm.comm) ) return comm def getName(self): cdef const char *cval = NULL CHKERR( PetscObjectGetName(self.obj[0], &cval) ) return bytes2str(cval) def setName(self, name): cdef const char *cval = NULL name = str2bytes(name, &cval) CHKERR( PetscObjectSetName(self.obj[0], cval) ) def getClassId(self): cdef PetscClassId classid = 0 CHKERR( PetscObjectGetClassId(self.obj[0], &classid) ) return classid def getClassName(self): cdef const char *cval = NULL CHKERR( PetscObjectGetClassName(self.obj[0], &cval) ) return bytes2str(cval) def getRefCount(self): if self.obj[0] == NULL: return 0 cdef PetscInt refcnt = 0 CHKERR( PetscObjectGetReference(self.obj[0], &refcnt) ) return toInt(refcnt) # --- general support --- def compose(self, name, Object obj or None): cdef const char *cval = NULL cdef PetscObject cobj = NULL name = str2bytes(name, &cval) if obj is not None: cobj = obj.obj[0] CHKERR( PetscObjectCompose(self.obj[0], cval, cobj) ) def query(self, name): cdef const char *cval = NULL cdef PetscObject cobj = NULL name = str2bytes(name, &cval) CHKERR( PetscObjectQuery(self.obj[0], cval, &cobj) ) if cobj == NULL: return None cdef Object obj = subtype_Object(cobj)() obj.obj[0] = cobj PetscINCREF(obj.obj) return obj def incRef(self): cdef PetscObject obj = self.obj[0] cdef PetscInt refct = 0 if obj != NULL: CHKERR( PetscObjectReference(obj) ) CHKERR( PetscObjectGetReference(obj, &refct) ) return (refct) def decRef(self): cdef PetscObject obj = self.obj[0] cdef PetscInt refct = 0 if obj != NULL: CHKERR( PetscObjectGetReference(obj, &refct) ) CHKERR( PetscObjectDereference(obj) ) if refct == 1: self.obj[0] = NULL refct -= 1 return (refct) def getAttr(self, name): cdef const char *cval = NULL name = str2bytes(name, &cval) return self.get_attr(cval) def setAttr(self, name, attr): cdef const char *cval = NULL name = str2bytes(name, &cval) self.set_attr(cval, attr) def getDict(self): return self.get_dict() # --- state manipulation --- def stateIncrease(self): PetscINCSTATE(self.obj) def stateGet(self): cdef PetscObjectState state = 0 CHKERR( PetscObjectStateGet(self.obj[0], &state) ) return toInt(state) def stateSet(self, state): cdef PetscObjectState cstate = asInt(state) CHKERR( PetscObjectStateSet(self.obj[0], cstate) ) # --- tab level --- def incrementTabLevel(self, tab, Object parent=None): cdef PetscInt ctab = asInt(tab) cdef PetscObject cobj = NULL if parent is None else parent.obj[0] CHKERR( PetscObjectIncrementTabLevel(self.obj[0], cobj, ctab) ) def setTabLevel(self, level): cdef PetscInt clevel = asInt(level) CHKERR( PetscObjectSetTabLevel(self.obj[0], clevel) ) def getTabLevel(self): cdef PetscInt clevel = 0 CHKERR( PetscObjectGetTabLevel(self.obj[0], &clevel) ) return toInt(clevel) # --- properties --- property type: def __get__(self): return self.getType() def __set__(self, value): self.setType(value) property prefix: def __get__(self): return self.getOptionsPrefix() def __set__(self, value): self.setOptionsPrefix(value) property comm: def __get__(self): return self.getComm() property name: def __get__(self): return self.getName() def __set__(self, value): self.setName(value) property classid: def __get__(self): return self.getClassId() property klass: def __get__(self): return self.getClassName() property refcount: def __get__(self): return self.getRefCount() # --- ctypes support --- property handle: def __get__(self): cdef PetscObject obj = self.obj[0] return PyLong_FromVoidPtr(obj) # --- Fortran support --- property fortran: def __get__(self): cdef PetscObject obj = self.obj[0] return Object_toFortran(obj) # -------------------------------------------------------------------- include "cyclicgc.pxi" cdef dict type_registry = { 0 : None } __type_registry__ = type_registry cdef int PyPetscType_Register(int classid, type cls) except -1: global type_registry cdef object key = classid cdef object value = cls cdef const char *dummy = NULL if key not in type_registry: type_registry[key] = cls reg_LogClass(str2bytes(cls.__name__, &dummy), classid) TypeEnableGC(cls) else: value = type_registry[key] if cls is not value: raise ValueError( "key: %d, cannot register: %s, " \ "already registered: %s" % (key, cls, value)) return 0 cdef type PyPetscType_Lookup(int classid): global type_registry cdef object key = classid cdef type cls = Object try: cls = type_registry[key] except KeyError: cls = Object return cls # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Options.pyx000066400000000000000000000100631454104047300210440ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class Options: cdef PetscOptions opt cdef object _prefix def __init__(self, prefix=None): self.opt = NULL self.prefix = prefix def __dealloc__(self): if self.opt == NULL: return CHKERR( PetscOptionsDestroy(&self.opt) ) def __contains__(self, item): return self.hasName(item) def __getitem__(self, item): return self.getString(item) def __setitem__(self, item, value): self.setValue(item, value) def __delitem__(self, item): self.delValue(item) property prefix: def __get__(self): return self._prefix def __set__(self, prefix): self._prefix = getprefix(prefix) def __del__(self): self._prefix = None # def create(self): if self.opt != NULL: return CHKERR( PetscOptionsCreate(&self.opt) ) return self def destroy(self): if self.opt == NULL: return CHKERR( PetscOptionsDestroy(&self.opt) ) return self def clear(self): if self.opt == NULL: return CHKERR( PetscOptionsClear(self.opt) ) return self def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscOptionsView(self.opt, vwr) ) def prefixPush(self, prefix): prefix = getprefix(prefix) cdef const char *cprefix = NULL prefix = str2bytes(prefix, &cprefix) CHKERR( PetscOptionsPrefixPush(self.opt, cprefix) ) def prefixPop(self): CHKERR( PetscOptionsPrefixPop(self.opt) ) # def hasName(self, name): cdef const char *pr = NULL cdef const char *nm = NULL tmp = getpair(self.prefix, name, &pr, &nm) cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsHasName(self.opt, pr, nm, &flag) ) return toBool(flag) def setValue(self, name, value): cdef const char *pr = NULL cdef const char *nm = NULL tmp = getpair(self.prefix, name, &pr, &nm) if pr == NULL: option = bytes2str(nm) else: option = '-%s%s' % (bytes2str(pr), bytes2str(&nm[1])) if type(value) is bool: value = str(value).lower() elif value is not None : value = str(value) cdef const char *key = NULL cdef const char *val = NULL option = str2bytes(option, &key) value = str2bytes(value, &val) CHKERR( PetscOptionsSetValue(self.opt, key, val) ) def delValue(self, name): cdef const char *pr = NULL cdef const char *nm = NULL tmp = getpair(self.prefix, name, &pr, &nm) if pr == NULL: option = bytes2str(nm) else: option = '-%s%s' % (bytes2str(pr), bytes2str(&nm[1])) cdef const char *key = NULL option = str2bytes(option, &key) CHKERR( PetscOptionsClearValue(self.opt, key) ) # def getBool(self, name, default=None): return getopt(self.opt, OPT_BOOL, self.prefix, name, default) def getInt(self, name, default=None): return getopt(self.opt, OPT_INT, self.prefix, name, default) def getReal(self, name, default=None): return getopt(self.opt, OPT_REAL, self.prefix, name, default) def getScalar(self, name, default=None): return getopt(self.opt, OPT_SCALAR, self.prefix, name, default) def getString(self, name, default=None): return getopt(self.opt, OPT_STRING, self.prefix, name, default) # def insertString(self, string): cdef const char *cstring = NULL string = str2bytes(string, &cstring) CHKERR( PetscOptionsInsertString(self.opt, cstring) ) def getAll(self): cdef char *allopts = NULL CHKERR( PetscOptionsGetAll(self.opt, &allopts) ) options = bytes2str(allopts) CHKERR( PetscFree(allopts) ) return parseopt(options, self.prefix) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/PC.pyx000066400000000000000000001075051454104047300177230ustar00rootroot00000000000000# -------------------------------------------------------------------- class PCType(object): NONE = S_(PCNONE) JACOBI = S_(PCJACOBI) SOR = S_(PCSOR) LU = S_(PCLU) QR = S_(PCQR) SHELL = S_(PCSHELL) BJACOBI = S_(PCBJACOBI) VPBJACOBI = S_(PCVPBJACOBI) MG = S_(PCMG) EISENSTAT = S_(PCEISENSTAT) ILU = S_(PCILU) ICC = S_(PCICC) ASM = S_(PCASM) GASM = S_(PCGASM) KSP = S_(PCKSP) COMPOSITE = S_(PCCOMPOSITE) REDUNDANT = S_(PCREDUNDANT) SPAI = S_(PCSPAI) NN = S_(PCNN) CHOLESKY = S_(PCCHOLESKY) PBJACOBI = S_(PCPBJACOBI) MAT = S_(PCMAT) HYPRE = S_(PCHYPRE) PARMS = S_(PCPARMS) FIELDSPLIT = S_(PCFIELDSPLIT) TFS = S_(PCTFS) ML = S_(PCML) GALERKIN = S_(PCGALERKIN) EXOTIC = S_(PCEXOTIC) CP = S_(PCCP) BFBT = S_(PCBFBT) LSC = S_(PCLSC) PYTHON = S_(PCPYTHON) PFMG = S_(PCPFMG) SYSPFMG = S_(PCSYSPFMG) REDISTRIBUTE = S_(PCREDISTRIBUTE) SVD = S_(PCSVD) GAMG = S_(PCGAMG) CHOWILUVIENNACL = S_(PCCHOWILUVIENNACL) ROWSCALINGVIENNACL = S_(PCROWSCALINGVIENNACL) SAVIENNACL = S_(PCSAVIENNACL) BDDC = S_(PCBDDC) KACZMARZ = S_(PCKACZMARZ) TELESCOPE = S_(PCTELESCOPE) PATCH = S_(PCPATCH) LMVM = S_(PCLMVM) HMG = S_(PCHMG) DEFLATION = S_(PCDEFLATION) HPDDM = S_(PCHPDDM) H2OPUS = S_(PCH2OPUS) class PCSide(object): # native LEFT = PC_LEFT RIGHT = PC_RIGHT SYMMETRIC = PC_SYMMETRIC # aliases L = LEFT R = RIGHT S = SYMMETRIC class PCASMType(object): NONE = PC_ASM_NONE BASIC = PC_ASM_BASIC RESTRICT = PC_ASM_RESTRICT INTERPOLATE = PC_ASM_INTERPOLATE class PCGASMType(object): NONE = PC_GASM_NONE BASIC = PC_GASM_BASIC RESTRICT = PC_GASM_RESTRICT INTERPOLATE = PC_GASM_INTERPOLATE class PCMGType(object): MULTIPLICATIVE = PC_MG_MULTIPLICATIVE ADDITIVE = PC_MG_ADDITIVE FULL = PC_MG_FULL KASKADE = PC_MG_KASKADE class PCMGCycleType(object): V = PC_MG_CYCLE_V W = PC_MG_CYCLE_W class PCGAMGType(object): AGG = S_(PCGAMGAGG) GEO = S_(PCGAMGGEO) CLASSICAL = S_(PCGAMGCLASSICAL) class PCCompositeType(object): ADDITIVE = PC_COMPOSITE_ADDITIVE MULTIPLICATIVE = PC_COMPOSITE_MULTIPLICATIVE SYMMETRIC_MULTIPLICATIVE = PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE SPECIAL = PC_COMPOSITE_SPECIAL SCHUR = PC_COMPOSITE_SCHUR class PCFieldSplitSchurPreType(object): SELF = PC_FIELDSPLIT_SCHUR_PRE_SELF SELFP = PC_FIELDSPLIT_SCHUR_PRE_SELFP A11 = PC_FIELDSPLIT_SCHUR_PRE_A11 USER = PC_FIELDSPLIT_SCHUR_PRE_USER FULL = PC_FIELDSPLIT_SCHUR_PRE_FULL class PCFieldSplitSchurFactType(object): DIAG = PC_FIELDSPLIT_SCHUR_FACT_DIAG LOWER = PC_FIELDSPLIT_SCHUR_FACT_LOWER UPPER = PC_FIELDSPLIT_SCHUR_FACT_UPPER FULL = PC_FIELDSPLIT_SCHUR_FACT_FULL class PCPatchConstructType(object): STAR = PC_PATCH_STAR VANKA = PC_PATCH_VANKA PARDECOMP = PC_PATCH_PARDECOMP USER = PC_PATCH_USER PYTHON = PC_PATCH_PYTHON class PCHPDDMCoarseCorrectionType(object): DEFLATED = PC_HPDDM_COARSE_CORRECTION_DEFLATED ADDITIVE = PC_HPDDM_COARSE_CORRECTION_ADDITIVE BALANCED = PC_HPDDM_COARSE_CORRECTION_BALANCED class PCDeflationSpaceType(object): HAAR = PC_DEFLATION_SPACE_HAAR DB2 = PC_DEFLATION_SPACE_DB2 DB4 = PC_DEFLATION_SPACE_DB4 DB8 = PC_DEFLATION_SPACE_DB8 DB16 = PC_DEFLATION_SPACE_DB16 BIORTH22 = PC_DEFLATION_SPACE_BIORTH22 MEYER = PC_DEFLATION_SPACE_MEYER AGGERGATION = PC_DEFLATION_SPACE_AGGREGATION USER = PC_DEFLATION_SPACE_USER class PCFailedReason(object): SETUP_ERROR = PC_SETUP_ERROR NOERROR = PC_NOERROR FACTOR_STRUCT_ZEROPIVOT = PC_FACTOR_STRUCT_ZEROPIVOT FACTOR_NUMERIC_ZEROPIVOT = PC_FACTOR_NUMERIC_ZEROPIVOT FACTOR_OUTMEMORY = PC_FACTOR_OUTMEMORY FACTOR_OTHER = PC_FACTOR_OTHER SUBPC_ERROR = PC_SUBPC_ERROR # -------------------------------------------------------------------- cdef class PC(Object): Type = PCType Side = PCSide ASMType = PCASMType GASMType = PCGASMType MGType = PCMGType MGCycleType = PCMGCycleType GAMGType = PCGAMGType CompositeType = PCCompositeType SchurFactType = PCFieldSplitSchurFactType SchurPreType = PCFieldSplitSchurPreType PatchConstructType = PCPatchConstructType HPDDMCoarseCorrectionType = PCHPDDMCoarseCorrectionType DeflationSpaceType = PCDeflationSpaceType FailedReason = PCFailedReason # --- xxx --- def __cinit__(self): self.obj = &self.pc self.pc = NULL def __call__(self, x, y=None): if y is None: # XXX do this better y = self.getOperators()[0].createVecLeft() self.apply(x, y) return y # --- xxx --- def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PCView(self.pc, vwr) ) def destroy(self): CHKERR( PCDestroy(&self.pc) ) self.pc = NULL return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscPC newpc = NULL CHKERR( PCCreate(ccomm, &newpc) ) PetscCLEAR(self.obj); self.pc = newpc return self def setType(self, pc_type): cdef PetscPCType cval = NULL pc_type = str2bytes(pc_type, &cval) CHKERR( PCSetType(self.pc, cval) ) def getType(self): cdef PetscPCType cval = NULL CHKERR( PCGetType(self.pc, &cval) ) return bytes2str(cval) def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PCSetOptionsPrefix(self.pc, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( PCGetOptionsPrefix(self.pc, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( PCAppendOptionsPrefix(self.pc, cval) ) def setFromOptions(self): CHKERR( PCSetFromOptions(self.pc) ) def setOperators(self, Mat A=None, Mat P=None): cdef PetscMat amat=NULL if A is not None: amat = A.mat cdef PetscMat pmat=amat if P is not None: pmat = P.mat CHKERR( PCSetOperators(self.pc, amat, pmat) ) def getOperators(self): cdef Mat A = Mat(), P = Mat() CHKERR( PCGetOperators(self.pc, &A.mat, &P.mat) ) PetscINCREF(A.obj) PetscINCREF(P.obj) return (A, P) def setUseAmat(self, flag): cdef PetscBool cflag = PETSC_FALSE if flag: cflag = PETSC_TRUE CHKERR( PCSetUseAmat(self.pc, cflag) ) def getUseAmat(self): cdef PetscBool cflag = PETSC_FALSE CHKERR( PCGetUseAmat(self.pc, &cflag) ) return toBool(cflag) def setReusePreconditioner(self, flag): cdef PetscBool cflag = PETSC_FALSE if flag: cflag = PETSC_TRUE CHKERR( PCSetReusePreconditioner(self.pc, cflag) ) def setFailedReason(self, reason): cdef PetscPCFailedReason val = reason CHKERR( PCSetFailedReason(self.pc, val) ) def getFailedReason(self): cdef PetscPCFailedReason reason = PC_NOERROR CHKERR( PCGetFailedReason(self.pc, &reason) ) return reason def getFailedReasonRank(self): cdef PetscPCFailedReason reason = PC_NOERROR CHKERR( PCGetFailedReasonRank(self.pc, &reason) ) return reason def setUp(self): CHKERR( PCSetUp(self.pc) ) def reset(self): CHKERR( PCReset(self.pc) ) def setUpOnBlocks(self): CHKERR( PCSetUpOnBlocks(self.pc) ) def apply(self, Vec x, Vec y): CHKERR( PCApply(self.pc, x.vec, y.vec) ) def matApply(self, Mat x, Mat y): CHKERR( PCMatApply(self.pc, x.mat, y.mat) ) def applyTranspose(self, Vec x, Vec y): CHKERR( PCApplyTranspose(self.pc, x.vec, y.vec) ) def applySymmetricLeft(self, Vec x, Vec y): CHKERR( PCApplySymmetricLeft(self.pc, x.vec, y.vec) ) def applySymmetricRight(self, Vec x, Vec y): CHKERR( PCApplySymmetricRight(self.pc, x.vec, y.vec) ) # --- discretization space --- def getDM(self): cdef PetscDM newdm = NULL CHKERR( PCGetDM(self.pc, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setDM(self, DM dm): CHKERR( PCSetDM(self.pc, dm.dm) ) def setCoordinates(self, coordinates): cdef ndarray xyz = iarray(coordinates, NPY_PETSC_REAL) if PyArray_ISFORTRAN(xyz): xyz = PyArray_Copy(xyz) if PyArray_NDIM(xyz) != 2: raise ValueError( ("coordinates must have two dimensions: " "coordinates.ndim=%d") % (PyArray_NDIM(xyz)) ) cdef PetscInt nvtx = PyArray_DIM(xyz, 0) cdef PetscInt ndim = PyArray_DIM(xyz, 1) cdef PetscReal *coords = PyArray_DATA(xyz) CHKERR( PCSetCoordinates(self.pc, ndim, nvtx, coords) ) # --- Python --- def createPython(self, context=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscPC newpc = NULL CHKERR( PCCreate(ccomm, &newpc) ) PetscCLEAR(self.obj); self.pc = newpc CHKERR( PCSetType(self.pc, PCPYTHON) ) CHKERR( PCPythonSetContext(self.pc, context) ) return self def setPythonContext(self, context): CHKERR( PCPythonSetContext(self.pc, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( PCPythonGetContext(self.pc, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( PCPythonSetType(self.pc, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( PCPythonGetType(self.pc, &cval) ) return bytes2str(cval) # --- ASM --- def setASMType(self, asmtype): cdef PetscPCASMType cval = asmtype CHKERR( PCASMSetType(self.pc, cval) ) def setASMOverlap(self, overlap): cdef PetscInt ival = asInt(overlap) CHKERR( PCASMSetOverlap(self.pc, ival) ) def setASMLocalSubdomains(self, nsd, is_=None, is_local=None): cdef PetscInt n = asInt(nsd) cdef PetscInt i = 0 cdef PetscIS *isets = NULL cdef PetscIS *isets_local = NULL if is_ is not None: assert len(is_) == nsd CHKERR( PetscMalloc(n*sizeof(PetscIS), &isets) ) for i in range(n): isets[i] = (is_[i]).iset if is_local is not None: assert len(is_local) == nsd CHKERR( PetscMalloc(n*sizeof(PetscIS), &isets_local) ) for i in range(n): isets_local[i] = (is_local[i]).iset CHKERR( PCASMSetLocalSubdomains(self.pc, n, isets, isets_local) ) CHKERR( PetscFree(isets) ) CHKERR( PetscFree(isets_local) ) def setASMTotalSubdomains(self, nsd, is_=None, is_local=None): cdef PetscInt n = asInt(nsd) cdef PetscInt i = 0 cdef PetscIS *isets = NULL cdef PetscIS *isets_local = NULL if is_ is not None: assert len(is_) == nsd CHKERR( PetscMalloc(n*sizeof(PetscIS), &isets) ) for i in range(n): isets[i] = (is_[i]).iset if is_local is not None: assert len(is_local) == nsd CHKERR( PetscMalloc(n*sizeof(PetscIS), &isets_local) ) for i in range(n): isets_local[i] = (is_local[i]).iset CHKERR( PCASMSetTotalSubdomains(self.pc, n, isets, isets_local) ) CHKERR( PetscFree(isets) ) CHKERR( PetscFree(isets_local) ) def getASMSubKSP(self): cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL CHKERR( PCASMGetSubKSP(self.pc, &n, NULL, &p) ) return [ref_KSP(p[i]) for i from 0 <= i dim*sizeof(PetscMat), &RT_Pi_mat) assert len(RT_Pi) == dim for i in range(dim): RT_Pi_mat[i] = (RT_Pi[i]).mat cdef PetscMat *ND_Pi_mat = NULL if ND_Pi is not None: PetscMalloc(dim*sizeof(PetscMat), &ND_Pi_mat) assert len(ND_Pi) == dim for i in range(dim): ND_Pi_mat[dim] = (ND_Pi[i]).mat CHKERR (PCHYPRESetInterpolations(self.pc, idim, RT_full_mat, RT_Pi_mat, ND_full_mat, ND_Pi_mat)) CHKERR (PetscFree(RT_Pi_mat)) CHKERR (PetscFree(ND_Pi_mat)) def setHYPRESetEdgeConstantVectors(self, Vec ozz, Vec zoz, Vec zzo=None): cdef PetscVec zzo_vec = NULL if zzo is not None: zzo_vec = zzo.vec CHKERR( PCHYPRESetEdgeConstantVectors(self.pc, ozz.vec, zoz.vec, zzo_vec) ) def setHYPREAMSSetInteriorNodes(self, Vec interior): CHKERR(PCHYPREAMSSetInteriorNodes(self.pc, interior.vec)) # --- Factor --- def setFactorSolverType(self, solver): cdef PetscMatSolverType cval = NULL solver = str2bytes(solver, &cval) CHKERR( PCFactorSetMatSolverType(self.pc, cval) ) def getFactorSolverType(self): cdef PetscMatSolverType cval = NULL CHKERR( PCFactorGetMatSolverType(self.pc, &cval) ) return bytes2str(cval) def setFactorSetUpSolverType(self): CHKERR( PCFactorSetUpMatSolverType(self.pc) ) def setFactorOrdering(self, ord_type=None, nzdiag=None, reuse=None): cdef PetscMatOrderingType cval = NULL if ord_type is not None: ord_type = str2bytes(ord_type, &cval) CHKERR( PCFactorSetMatOrderingType(self.pc, cval) ) cdef PetscReal rval = 0 if nzdiag is not None: rval = asReal(nzdiag) CHKERR( PCFactorReorderForNonzeroDiagonal(self.pc, rval) ) cdef PetscBool bval = PETSC_FALSE if reuse is not None: bval = PETSC_TRUE if reuse else PETSC_FALSE CHKERR( PCFactorSetReuseOrdering(self.pc, bval) ) def setFactorPivot(self, zeropivot=None, inblocks=None): cdef PetscReal rval = 0 if zeropivot is not None: rval = asReal(zeropivot) CHKERR( PCFactorSetZeroPivot(self.pc, rval) ) cdef PetscBool bval = PETSC_FALSE if inblocks is not None: bval = PETSC_TRUE if inblocks else PETSC_FALSE CHKERR( PCFactorSetPivotInBlocks(self.pc, bval) ) def setFactorShift(self, shift_type=None, amount=None): cdef PetscMatFactorShiftType cval = MAT_SHIFT_NONE if shift_type is not None: cval = matfactorshifttype(shift_type) CHKERR( PCFactorSetShiftType(self.pc, cval) ) cdef PetscReal rval = 0 if amount is not None: rval = asReal(amount) CHKERR( PCFactorSetShiftAmount(self.pc, rval) ) def setFactorLevels(self, levels): cdef PetscInt ival = asInt(levels) CHKERR( PCFactorSetLevels(self.pc, ival) ) def getFactorMatrix(self): cdef Mat mat = Mat() CHKERR( PCFactorGetMatrix(self.pc, &mat.mat) ) PetscINCREF(mat.obj) return mat # --- FieldSplit --- def setFieldSplitType(self, ctype): cdef PetscPCCompositeType cval = ctype CHKERR( PCFieldSplitSetType(self.pc, cval) ) def setFieldSplitIS(self, *fields): cdef object name = None cdef IS field = None cdef const char *cname = NULL for name, field in fields: name = str2bytes(name, &cname) CHKERR( PCFieldSplitSetIS(self.pc, cname, field.iset) ) def setFieldSplitFields(self, bsize, *fields): cdef PetscInt bs = asInt(bsize) CHKERR( PCFieldSplitSetBlockSize(self.pc, bs) ) cdef object name = None cdef object field = None cdef const char *cname = NULL cdef PetscInt nfields = 0, *ifields = NULL for name, field in fields: name = str2bytes(name, &cname) field = iarray_i(field, &nfields, &ifields) CHKERR( PCFieldSplitSetFields(self.pc, cname, nfields, ifields, ifields) ) def getFieldSplitSubKSP(self): cdef PetscInt i = 0, n = 0 cdef PetscKSP *p = NULL cdef object subksp = None try: CHKERR( PCFieldSplitGetSubKSP(self.pc, &n, &p) ) subksp = [ref_KSP(p[i]) for i from 0 <= i &cisfields) for i from 0 <= i < n: cisfields[i] = (isfields[i]).iset CHKERR( PCBDDCSetDofsSplitting(self.pc, n, cisfields) ) def setBDDCDofsSplittingLocal(self, isfields): isfields = [isfields] if isinstance(isfields, IS) else list(isfields) cdef Py_ssize_t i, n = len(isfields) cdef PetscIS *cisfields = NULL cdef object tmp tmp = oarray_p(empty_p(n), NULL, &cisfields) for i from 0 <= i < n: cisfields[i] = (isfields[i]).iset CHKERR( PCBDDCSetDofsSplittingLocal(self.pc, n, cisfields) ) # --- Patch --- def setPatchCellNumbering(self, Section sec not None): CHKERR( PCPatchSetCellNumbering(self.pc, sec.sec) ) def setPatchDiscretisationInfo(self, dms, bs, cellNodeMaps, subspaceOffsets, ghostBcNodes, globalBcNodes): cdef PetscInt numSubSpaces = 0 cdef PetscInt numGhostBcs = 0, numGlobalBcs = 0 cdef PetscInt *nodesPerCell = NULL cdef const PetscInt **ccellNodeMaps = NULL cdef PetscDM *cdms = NULL cdef PetscInt *cbs = NULL cdef PetscInt *csubspaceOffsets = NULL cdef PetscInt *cghostBcNodes = NULL cdef PetscInt *cglobalBcNodes = NULL cdef PetscInt i = 0 bs = iarray_i(bs, &numSubSpaces, &cbs) ghostBcNodes = iarray_i(ghostBcNodes, &numGhostBcs, &cghostBcNodes) globalBcNodes = iarray_i(globalBcNodes, &numGlobalBcs, &cglobalBcNodes) subspaceOffsets = iarray_i(subspaceOffsets, NULL, &csubspaceOffsets) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscInt), &nodesPerCell) ) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscDM), &cdms) ) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscInt*), &ccellNodeMaps) ) for i in range(numSubSpaces): cdms[i] = (dms[i]).dm _, nodes = asarray(cellNodeMaps[i]).shape cellNodeMaps[i] = iarray_i(cellNodeMaps[i], NULL, &(ccellNodeMaps[i])) nodesPerCell[i] = asInt(nodes) # TODO: refactor on the PETSc side to take ISes? CHKERR( PCPatchSetDiscretisationInfo(self.pc, numSubSpaces, cdms, cbs, nodesPerCell, ccellNodeMaps, csubspaceOffsets, numGhostBcs, cghostBcNodes, numGlobalBcs, cglobalBcNodes) ) CHKERR( PetscFree(nodesPerCell) ) CHKERR( PetscFree(cdms) ) CHKERR( PetscFree(ccellNodeMaps) ) def setPatchComputeOperator(self, operator, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (operator, args, kargs) self.set_attr("__patch_compute_operator__", context) CHKERR( PCPatchSetComputeOperator(self.pc, PCPatch_ComputeOperator, context) ) def setPatchComputeOperatorInteriorFacets(self, operator, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (operator, args, kargs) self.set_attr("__patch_compute_operator_interior_facets__", context) CHKERR( PCPatchSetComputeOperatorInteriorFacets(self.pc, PCPatch_ComputeOperatorInteriorFacets, context) ) def setPatchComputeFunction(self, function, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr("__patch_compute_function__", context) CHKERR( PCPatchSetComputeFunction(self.pc, PCPatch_ComputeFunction, context) ) def setPatchComputeFunctionInteriorFacets(self, function, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr("__patch_compute_function_interior_facets__", context) CHKERR( PCPatchSetComputeFunction(self.pc, PCPatch_ComputeFunctionInteriorFacets, context) ) def setPatchConstructType(self, typ, operator=None, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} if typ in {PC.PatchConstructType.PYTHON, PC.PatchConstructType.USER} and operator is None: raise ValueError("Must provide operator for USER or PYTHON type") if operator is not None: context = (operator, args, kargs) else: context = None self.set_attr("__patch_construction_operator__", context) CHKERR( PCPatchSetConstructType(self.pc, typ, PCPatch_UserConstructOperator, context) ) # --- HPDDM --- def setHPDDMAuxiliaryMat(self, IS uis, Mat uaux): CHKERR( PCHPDDMSetAuxiliaryMat(self.pc, uis.iset, uaux.mat, NULL, NULL) ) def setHPDDMRHSMat(self, Mat B): CHKERR( PCHPDDMSetRHSMat(self.pc, B.mat) ) def setHPDDMHasNeumannMat(self, has): cdef PetscBool phas = has CHKERR( PCHPDDMHasNeumannMat(self.pc, phas) ) def setHPDDMCoarseCorrectionType(self, correction_type): cdef PetscPCHPDDMCoarseCorrectionType ctype = correction_type CHKERR( PCHPDDMSetCoarseCorrectionType(self.pc, ctype) ) def getHPDDMCoarseCorrectionType(self): cdef PetscPCHPDDMCoarseCorrectionType cval = PC_HPDDM_COARSE_CORRECTION_DEFLATED CHKERR( PCHPDDMGetCoarseCorrectionType(self.pc, &cval) ) return cval def getHPDDMSTShareSubKSP(self): cdef PetscBool cval = PETSC_FALSE CHKERR( PCHPDDMGetSTShareSubKSP(self.pc, &cval) ) return toBool(cval) def setHPDDMDeflationMat(self, IS uis, Mat U): CHKERR( PCHPDDMSetDeflationMat(self.pc, uis.iset, U.mat) ) # --- SPAI --- def setSPAIEpsilon(self, val): cdef PetscReal cval = asReal(val) CHKERR( PCSPAISetEpsilon(self.pc, cval) ) def setSPAINBSteps(self, nbsteps): cdef PetscInt cval = asInt(nbsteps) CHKERR( PCSPAISetNBSteps(self.pc, cval) ) def setSPAIMax(self, maxval): cdef PetscInt cval = asInt(maxval) CHKERR( PCSPAISetMax(self.pc, cval) ) def setSPAIMaxNew(self, maxval): cdef PetscInt cval = asInt(maxval) CHKERR( PCSPAISetMaxNew(self.pc, cval) ) def setSPAIBlockSize(self, n): cdef PetscInt cval = asInt(n) CHKERR( PCSPAISetBlockSize(self.pc, cval) ) def setSPAICacheSize(self, size): cdef PetscInt cval = asInt(size) CHKERR( PCSPAISetCacheSize(self.pc, cval) ) def setSPAIVerbose(self, level): cdef PetscInt cval = asInt(level) CHKERR( PCSPAISetVerbose(self.pc, cval) ) def setSPAISp(self, sym): cdef PetscInt cval = asInt(sym) CHKERR( PCSPAISetSp(self.pc, cval) ) # --- DEFLATION --- def setDeflationInitOnly(self, flg): cdef PetscBool cflg = asBool(flg) CHKERR( PCDeflationSetInitOnly(self.pc, cflg) ) def setDeflationLevels(self, levels): cdef PetscInt clevels = asInt(levels) CHKERR( PCDeflationSetLevels(self.pc, clevels) ) def setDeflationReductionFactor(self, red): cdef PetscInt cred = asInt(red) CHKERR( PCDeflationSetReductionFactor(self.pc, cred) ) def setDeflationCorrectionFactor(self, fact): cdef PetscScalar cfact = asScalar(fact) CHKERR( PCDeflationSetCorrectionFactor(self.pc, fact) ) def setDeflationSpaceToCompute(self, space_type, size): cdef PetscInt csize = asInt(size) cdef PetscPCDeflationSpaceType ctype = space_type CHKERR( PCDeflationSetSpaceToCompute(self.pc, space_type, csize) ) def setDeflationSpace(self, Mat W, transpose): cdef PetscBool ctranspose = asBool(transpose) CHKERR( PCDeflationSetSpace(self.pc, W.mat, ctranspose) ) def setDeflationProjectionNullSpaceMat(self, Mat mat): CHKERR( PCDeflationSetProjectionNullSpaceMat(self.pc, mat.mat) ) def setDeflationCoarseMat(self, Mat mat): CHKERR( PCDeflationSetCoarseMat(self.pc, mat.mat) ) def getDeflationCoarseKSP(self): cdef KSP ksp = KSP() CHKERR( PCDeflationGetCoarseKSP(self.pc, &ksp.ksp) ) PetscINCREF(ksp.obj) return ksp def getDeflationPC(self): cdef PC apc = PC() CHKERR( PCDeflationGetPC(self.pc, &apc.pc) ) PetscINCREF(apc.obj) return apc # -------------------------------------------------------------------- del PCType del PCSide del PCASMType del PCGASMType del PCMGType del PCMGCycleType del PCGAMGType del PCCompositeType del PCFieldSplitSchurPreType del PCFieldSplitSchurFactType del PCPatchConstructType del PCHPDDMCoarseCorrectionType del PCDeflationSpaceType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/PETSc.pyx000066400000000000000000000465101454104047300203350ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: """ #include "lib-petsc/compat.h" #include "lib-petsc/custom.h" """ # -------------------------------------------------------------------- cdef extern from * nogil: ctypedef ssize_t Py_intptr_t ctypedef size_t Py_uintptr_t # -------------------------------------------------------------------- cdef inline object bytes2str(const char p[]): if p == NULL: return None cdef bytes s = p if isinstance(s, str): return s else: return s.decode() cdef inline object str2bytes(object s, const char *p[]): if s is None: p[0] = NULL return None if not isinstance(s, bytes): s = s.encode() p[0] = (s) return s cdef inline object S_(const char p[]): if p == NULL: return None cdef object s = p return s if isinstance(s, str) else s.decode() # -------------------------------------------------------------------- # Vile hack for raising a exception and not contaminating traceback cdef extern from *: void PyErr_SetObject(object, object) void *PyExc_RuntimeError # SETERR Support # -------------- cdef object PetscError = PyExc_RuntimeError cdef PetscErrorCode SETERR(PetscErrorCode ierr) with gil: if (PetscError) != NULL: PyErr_SetObject(PetscError, ierr) else: PyErr_SetObject(PyExc_RuntimeError, ierr) return ierr cdef inline PetscErrorCode CHKERR(PetscErrorCode ierr) nogil except PETSC_ERR_PYTHON: if ierr == PETSC_SUCCESS: return ierr # no error if ierr == PETSC_ERR_PYTHON: return ierr # error in python code SETERR(ierr) return PETSC_ERR_PYTHON # SETERRMPI Support # ----------------- cdef extern from * nogil: enum: MPI_SUCCESS = 0 enum: MPI_MAX_ERROR_STRING int MPI_Error_string(int, char *, int *) PetscErrorCode PetscERROR(MPI_Comm, char[], PetscErrorCode, int, char[], char[]) cdef inline int SETERRMPI(int ierr) with gil: cdef char[MPI_MAX_ERROR_STRING] mpi_err_str cdef int result_len = sizeof(mpi_err_str) memset(mpi_err_str, 0, result_len) MPI_Error_string(ierr, mpi_err_str, &result_len); result_len cdef str error_str = "MPI Error " + bytes2str(mpi_err_str) + " " + str(ierr) cdef const char *c_error_str = NULL str2bytes(error_str, &c_error_str) PetscERROR(PETSC_COMM_SELF, "Unknown Python Function", PETSC_ERR_MPI, PETSC_ERROR_INITIAL, "%s", c_error_str) SETERR(PETSC_ERR_MPI) return ierr cdef inline PetscErrorCode CHKERRMPI(int ierr) nogil except PETSC_ERR_PYTHON: if ierr == MPI_SUCCESS: return PETSC_SUCCESS SETERRMPI(ierr) return PETSC_ERR_PYTHON # -------------------------------------------------------------------- # PETSc support # ------------- cdef extern from * nogil: ctypedef long PetscInt ctypedef double PetscReal ctypedef double PetscScalar cdef extern from "": object PyPetscScalar_FromPetscScalar(PetscScalar) PetscScalar PyPetscScalar_AsPetscScalar(object) except? -1.0 cdef extern from "": int PyPetscBuffer_FillInfo(Py_buffer*,void*,PetscInt,char,int,int) except -1 void PyPetscBuffer_Release(Py_buffer*) 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 inline object toScalar(PetscScalar value): return PyPetscScalar_FromPetscScalar(value) cdef inline PetscScalar asScalar(object value) except? -1.0: return PyPetscScalar_AsPetscScalar(value) # -------------------------------------------------------------------- # 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) include "dlpack.pxi" # -------------------------------------------------------------------- include "petscdef.pxi" include "petscmem.pxi" include "petscopt.pxi" include "petscmpi.pxi" include "petscsys.pxi" include "petsclog.pxi" include "petscobj.pxi" include "petscvwr.pxi" include "petscrand.pxi" include "petscdevice.pxi" include "petsclayout.pxi" include "petscis.pxi" include "petscsf.pxi" include "petscvec.pxi" include "petscdt.pxi" include "petscfe.pxi" include "petscsct.pxi" include "petscsec.pxi" include "petscmat.pxi" include "petscmatpartitioning.pxi" include "petscpc.pxi" include "petscksp.pxi" include "petscsnes.pxi" include "petscts.pxi" include "petsctao.pxi" include "petscao.pxi" include "petscdm.pxi" include "petscds.pxi" include "petscdmda.pxi" include "petscdmplex.pxi" include "petscdmstag.pxi" include "petscdmcomposite.pxi" include "petscdmshell.pxi" include "petscdmlabel.pxi" include "petscdmswarm.pxi" include "petscpartitioner.pxi" include "petscspace.pxi" include "petscdmutils.pxi" include "petscpyappctx.pxi" # -------------------------------------------------------------------- __doc__ = u""" Portable, Extensible Toolkit for Scientific Computation """ include "Const.pyx" include "Error.pyx" include "Options.pyx" include "Sys.pyx" include "Log.pyx" include "Comm.pyx" include "Object.pyx" include "Viewer.pyx" include "Random.pyx" include "Device.pyx" include "IS.pyx" include "SF.pyx" include "Vec.pyx" include "DT.pyx" include "FE.pyx" include "Scatter.pyx" include "Section.pyx" include "Mat.pyx" include "MatPartitioning.pyx" include "PC.pyx" include "KSP.pyx" include "SNES.pyx" include "TS.pyx" include "TAO.pyx" include "AO.pyx" include "DM.pyx" include "DS.pyx" include "DMDA.pyx" include "DMPlex.pyx" include "DMStag.pyx" include "DMComposite.pyx" include "DMShell.pyx" include "DMLabel.pyx" include "DMSwarm.pyx" include "Partitioner.pyx" include "Space.pyx" include "DMUtils.pyx" # -------------------------------------------------------------------- include "CAPI.pyx" include "libpetsc4py.pyx" # -------------------------------------------------------------------- cdef extern from "Python.h": int Py_IsInitialized() nogil int PyList_Insert(object,Py_ssize_t,object) except -1 int PyList_Append(object,object) except -1 cdef extern from * nogil: PetscErrorCode PetscTBEH(MPI_Comm,int,char*,char*,int,PetscErrorType,char*,void*) cdef object tracebacklist = [] cdef PetscErrorCode traceback( MPI_Comm comm, int line, const char *cfunc, const char *cfile, PetscErrorCode n, PetscErrorType p, const char *mess, void *ctx, ) with gil: cdef PetscLogDouble mem=0 cdef PetscLogDouble rss=0 cdef const char *text=NULL global tracebacklist cdef object tbl = tracebacklist cdef object fun = bytes2str(cfunc) cdef object fnm = bytes2str(cfile) cdef object m = "%s() at %s:%d" % (fun, fnm, line) PyList_Insert(tbl, 0, m) if p != PETSC_ERROR_INITIAL: return n # del tbl[1:] # clear any previous stuff if n == PETSC_ERR_MEM: # special case PetscMallocGetCurrentUsage(&mem) PetscMemoryGetCurrentUsage(&rss) m = ( "Out of memory. " "Allocated: %d, " "Used by process: %d" ) % (mem, rss) PyList_Append(tbl, m) else: PetscErrorMessage(n, &text, NULL) if text != NULL: PyList_Append(tbl, bytes2str(text)) if mess != NULL: PyList_Append(tbl, bytes2str(mess)) comm # unused ctx # unused return n cdef PetscErrorCode PetscPythonErrorHandler( MPI_Comm comm, int line, const char *cfunc, const char *cfile, PetscErrorCode n, PetscErrorType p, const char *mess, void *ctx, ) nogil: global tracebacklist if (tracebacklist) != NULL and Py_IsInitialized(): return traceback(comm, line, cfunc, cfile, n, p, mess, ctx) else: return PetscTBEH(comm, line, cfunc, cfile, n, p, mess, ctx) # -------------------------------------------------------------------- cdef extern from "" nogil: void* malloc(size_t) void* realloc (void*,size_t) void free(void*) cdef extern from "" nogil: ctypedef struct va_list: pass cdef extern from "" nogil: void* memset(void*,int,size_t) void* memcpy(void*,void*,size_t) char* strdup(char*) cdef extern from "" nogil: ctypedef struct FILE FILE *stderr int fprintf(FILE *, char *, ...) cdef extern from "Python.h": int Py_AtExit(void (*)()) void PySys_WriteStderr(char*,...) cdef extern from * nogil: """ #include "lib-petsc/initpkg.h" """ PetscErrorCode PetscInitializePackageAll() cdef int PyPetsc_Argc = 0 cdef char** PyPetsc_Argv = NULL cdef int getinitargs(object args, int *argc, char **argv[]) except -1: # allocate command line arguments cdef int i, c = 0 cdef char **v = NULL if args is None: args = [] args = [str(a).encode() for a in args] args = [a for a in args if a] c = len(args) v = malloc((c+1)*sizeof(char*)) if v == NULL: raise MemoryError memset(v, 0, (c+1)*sizeof(char*)) try: for 0 <= i < c: v[i] = strdup(args[i]) if v[i] == NULL: raise MemoryError except: delinitargs(&c, &v); raise argc[0] = c; argv[0] = v return 0 cdef void delinitargs(int *argc, char **argv[]) nogil: # dallocate command line arguments cdef int i, c = argc[0] cdef char** v = argv[0] argc[0] = 0; argv[0] = NULL; if c >= 0 and v != NULL: for 0 <= i < c: if v[i] != NULL: free(v[i]) free(v) cdef void finalize() nogil: cdef int ierr = 0 # deallocate command line arguments global PyPetsc_Argc, PyPetsc_Argv global PetscVFPrintf, prevfprintf delinitargs(&PyPetsc_Argc, &PyPetsc_Argv) # manage PETSc finalization if not (PetscInitializeCalled): return if (PetscFinalizeCalled): return # stop stdout/stderr redirect if (prevfprintf != NULL): PetscVFPrintf = prevfprintf prevfprintf = NULL # deinstall Python error handler ierr = PetscPopErrorHandler() if ierr != 0: fprintf(stderr, "PetscPopErrorHandler() failed " "[error code: %d]\n", ierr) # finalize PETSc ierr = PetscFinalize() if ierr != 0: fprintf(stderr, "PetscFinalize() failed " "[error code: %d]\n", ierr) # and we are done, see you later !! # -------------------------------------------------------------------- cdef extern from * nogil: PetscErrorCode (*PetscVFPrintf)(FILE*,const char*,va_list) cdef PetscErrorCode (*prevfprintf)(FILE*,const char*,va_list) nogil prevfprintf = NULL cdef PetscErrorCode PetscVFPrintf_PythonStdStream( FILE *fd, const char formt[], va_list ap, ) with gil: import sys cdef char cstring[8192] cdef size_t stringlen = sizeof(cstring) cdef size_t final_pos if (fd == PETSC_STDOUT) and not (sys.stdout == sys.__stdout__): CHKERR( PetscVSNPrintf(&cstring[0],stringlen,formt,&final_pos,ap)) if final_pos > 0 and cstring[final_pos-1] == '\x00': final_pos -= 1 ustring = cstring[:final_pos].decode('UTF-8') sys.stdout.write(ustring) elif (fd == PETSC_STDERR) and not (sys.stderr == sys.__stderr__): CHKERR( PetscVSNPrintf(&cstring[0],stringlen,formt,&final_pos,ap)) if final_pos > 0 and cstring[final_pos-1] == '\x00': final_pos -= 1 ustring = cstring[:final_pos].decode('UTF-8') sys.stderr.write(ustring) else: PetscVFPrintfDefault(fd, formt, ap) return PETSC_SUCCESS cdef int _push_vfprintf( PetscErrorCode (*vfprintf)(FILE*, const char*, va_list) nogil, ) except -1: global PetscVFPrintf, prevfprintf assert prevfprintf == NULL prevfprintf = PetscVFPrintf PetscVFPrintf = vfprintf cdef int _pop_vfprintf() except -1: global PetscVFPrintf, prevfprintf assert prevfprintf != NULL PetscVFPrintf = prevfprintf prevfprintf == NULL cdef int initialize(object args, object comm) except -1: if (PetscInitializeCalled): return 1 if (PetscFinalizeCalled): return 0 # allocate command line arguments global PyPetsc_Argc, PyPetsc_Argv getinitargs(args, &PyPetsc_Argc, &PyPetsc_Argv) # communicator global PETSC_COMM_WORLD PETSC_COMM_WORLD = def_Comm(comm, PETSC_COMM_WORLD) # initialize PETSc CHKERR( PetscInitialize(&PyPetsc_Argc, &PyPetsc_Argv, NULL, NULL) ) # install Python error handler cdef PetscErrorHandlerFunction handler = NULL handler = PetscPythonErrorHandler CHKERR( PetscPushErrorHandler(handler, NULL) ) # redirect PETSc std streams import sys if (sys.stdout != sys.__stdout__) or (sys.stderr != sys.__stderr__): _push_vfprintf(&PetscVFPrintf_PythonStdStream) # register finalization function if Py_AtExit(finalize) < 0: PySys_WriteStderr(b"warning: could not register %s with Py_AtExit()", b"PetscFinalize()") return 1 # and we are done, enjoy !! cdef extern from * nogil: PetscClassId PETSC_OBJECT_CLASSID "PETSC_OBJECT_CLASSID" PetscClassId PETSC_VIEWER_CLASSID "PETSC_VIEWER_CLASSID" PetscClassId PETSC_RANDOM_CLASSID "PETSC_RANDOM_CLASSID" PetscClassId PETSC_IS_CLASSID "IS_CLASSID" PetscClassId PETSC_LGMAP_CLASSID "IS_LTOGM_CLASSID" PetscClassId PETSC_SF_CLASSID "PETSCSF_CLASSID" PetscClassId PETSC_VEC_CLASSID "VEC_CLASSID" PetscClassId PETSC_SECTION_CLASSID "PETSC_SECTION_CLASSID" PetscClassId PETSC_MAT_CLASSID "MAT_CLASSID" PetscClassId PETSC_MAT_PARTITIONING_CLASSID "MAT_PARTITIONING_CLASSID" PetscClassId PETSC_NULLSPACE_CLASSID "MAT_NULLSPACE_CLASSID" PetscClassId PETSC_PC_CLASSID "PC_CLASSID" PetscClassId PETSC_KSP_CLASSID "KSP_CLASSID" PetscClassId PETSC_SNES_CLASSID "SNES_CLASSID" PetscClassId PETSC_TS_CLASSID "TS_CLASSID" PetscClassId PETSC_TAO_CLASSID "TAO_CLASSID" PetscClassId PETSC_AO_CLASSID "AO_CLASSID" PetscClassId PETSC_DM_CLASSID "DM_CLASSID" PetscClassId PETSC_DS_CLASSID "PETSCDS_CLASSID" PetscClassId PETSC_PARTITIONER_CLASSID "PETSCPARTITIONER_CLASSID" PetscClassId PETSC_FE_CLASSID "PETSCFE_CLASSID" PetscClassId PETSC_DMLABEL_CLASSID "DMLABEL_CLASSID" PetscClassId PETSC_SPACE_CLASSID "PETSCSPACE_CLASSID" PetscClassId PETSC_DUALSPACE_CLASSID "PETSCDUALSPACE_CLASSID" PetscClassId PETSC_DEVICE_CLASSID "PETSC_DEVICE_CLASSID" PetscClassId PETSC_DEVICE_CONTEXT_CLASSID "PETSC_DEVICE_CONTEXT_CLASSID" cdef bint registercalled = 0 cdef const char *citation = b"""\ @Article{Dalcin2011, Author = {Lisandro D. Dalcin and Rodrigo R. Paz and Pablo A. Kler and Alejandro Cosimo}, Title = {Parallel distributed computing using {P}ython}, Journal = {Advances in Water Resources}, Note = {New Computational Methods and Software Tools}, Volume = {34}, Number = {9}, Pages = {1124--1139}, Year = {2011}, DOI = {https://doi.org/10.1016/j.advwatres.2011.04.013} } """ cdef int register() except -1: global registercalled if registercalled: return 0 registercalled = True # register citation CHKERR( PetscCitationsRegister(citation, NULL) ) # make sure all PETSc packages are initialized CHKERR( PetscInitializePackageAll() ) # register custom implementations CHKERR( PetscPythonRegisterAll() ) # register Python types PyPetscType_Register(PETSC_OBJECT_CLASSID, Object) PyPetscType_Register(PETSC_VIEWER_CLASSID, Viewer) PyPetscType_Register(PETSC_RANDOM_CLASSID, Random) PyPetscType_Register(PETSC_DEVICE_CLASSID, Device) PyPetscType_Register(PETSC_DEVICE_CONTEXT_CLASSID, DeviceContext) PyPetscType_Register(PETSC_IS_CLASSID, IS) PyPetscType_Register(PETSC_LGMAP_CLASSID, LGMap) PyPetscType_Register(PETSC_SF_CLASSID, SF) PyPetscType_Register(PETSC_VEC_CLASSID, Vec) PyPetscType_Register(PETSC_SECTION_CLASSID, Section) PyPetscType_Register(PETSC_MAT_CLASSID, Mat) PyPetscType_Register(PETSC_MAT_PARTITIONING_CLASSID, MatPartitioning) PyPetscType_Register(PETSC_NULLSPACE_CLASSID, NullSpace) PyPetscType_Register(PETSC_PC_CLASSID, PC) PyPetscType_Register(PETSC_KSP_CLASSID, KSP) PyPetscType_Register(PETSC_SNES_CLASSID, SNES) PyPetscType_Register(PETSC_TS_CLASSID, TS) PyPetscType_Register(PETSC_TAO_CLASSID, TAO) PyPetscType_Register(PETSC_PARTITIONER_CLASSID, Partitioner) PyPetscType_Register(PETSC_AO_CLASSID, AO) PyPetscType_Register(PETSC_DM_CLASSID, DM) PyPetscType_Register(PETSC_DS_CLASSID, DS) PyPetscType_Register(PETSC_FE_CLASSID, FE) PyPetscType_Register(PETSC_DMLABEL_CLASSID, DMLabel) PyPetscType_Register(PETSC_SPACE_CLASSID, Space) PyPetscType_Register(PETSC_DUALSPACE_CLASSID, DualSpace) return 0 # and we are done, enjoy !! # -------------------------------------------------------------------- def _initialize(args=None, comm=None): import atexit global tracebacklist Error._traceback_ = tracebacklist global PetscError PetscError = Error # cdef int ready = initialize(args, comm) if ready: register() # global __COMM_SELF__, __COMM_WORLD__ __COMM_SELF__.comm = PETSC_COMM_SELF __COMM_WORLD__.comm = PETSC_COMM_WORLD # global PETSC_COMM_DEFAULT PETSC_COMM_DEFAULT = PETSC_COMM_WORLD # Register finalizer atexit.register(_pre_finalize) def _pre_finalize(): # Called while the Python interpreter is still running garbage_cleanup() def _finalize(): finalize() # global __COMM_SELF__ __COMM_SELF__.comm = MPI_COMM_NULL global __COMM_WORLD__ __COMM_WORLD__.comm = MPI_COMM_NULL # global PETSC_COMM_DEFAULT PETSC_COMM_DEFAULT = MPI_COMM_NULL # global type_registry type_registry.clear() global stage_registry stage_registry.clear() global class_registry class_registry.clear() global event_registry event_registry.clear() global citations_registry citations_registry.clear() def _push_python_vfprintf(): _push_vfprintf(&PetscVFPrintf_PythonStdStream) def _pop_python_vfprintf(): _pop_vfprintf() def _stdout_is_stderr(): global PETSC_STDOUT, PETSC_STDERR return PETSC_STDOUT == PETSC_STDERR # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Partitioner.pyx000066400000000000000000000051171454104047300217150ustar00rootroot00000000000000# -------------------------------------------------------------------- class PartitionerType(object): PARMETIS = S_(PETSCPARTITIONERPARMETIS) PTSCOTCH = S_(PETSCPARTITIONERPTSCOTCH) CHACO = S_(PETSCPARTITIONERCHACO) SIMPLE = S_(PETSCPARTITIONERSIMPLE) SHELL = S_(PETSCPARTITIONERSHELL) GATHER = S_(PETSCPARTITIONERGATHER) MATPARTITIONING = S_(PETSCPARTITIONERMATPARTITIONING) # -------------------------------------------------------------------- cdef class Partitioner(Object): Type = PartitionerType def __cinit__(self): self.obj = &self.part self.part = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscPartitionerView(self.part, vwr) ) def destroy(self): CHKERR( PetscPartitionerDestroy(&self.part) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscPartitioner newpart = NULL CHKERR( PetscPartitionerCreate(ccomm, &newpart) ) PetscCLEAR(self.obj); self.part = newpart return self def setType(self, part_type): cdef PetscPartitionerType cval = NULL part_type = str2bytes(part_type, &cval) CHKERR( PetscPartitionerSetType(self.part, cval) ) def getType(self): cdef PetscPartitionerType cval = NULL CHKERR( PetscPartitionerGetType(self.part, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( PetscPartitionerSetFromOptions(self.part) ) def setUp(self): CHKERR( PetscPartitionerSetUp(self.part) ) def reset(self): CHKERR( PetscPartitionerReset(self.part) ) def setShellPartition(self, numProcs, sizes=None, points=None): cdef PetscInt cnumProcs = asInt(numProcs) cdef PetscInt *csizes = NULL cdef PetscInt *cpoints = NULL cdef PetscInt nsize = 0 if sizes is not None: sizes = iarray_i(sizes, &nsize, &csizes) if nsize != cnumProcs: raise ValueError("sizes array should have %d entries (has %d)" % numProcs, toInt(nsize)) if points is None: raise ValueError("Must provide both sizes and points arrays") if points is not None: points = iarray_i(points, NULL, &cpoints) CHKERR( PetscPartitionerShellSetPartition(self.part, cnumProcs, csizes, cpoints) ) petsc4py-3.19.6/src/petsc4py/PETSc/Random.pyx000066400000000000000000000056131454104047300206360ustar00rootroot00000000000000# -------------------------------------------------------------------- class RandomType(object): RAND = S_(PETSCRAND) RAND48 = S_(PETSCRAND48) SPRNG = S_(PETSCSPRNG) RANDER48 = S_(PETSCRANDER48) RANDOM123 = S_(PETSCRANDOM123) # -------------------------------------------------------------------- cdef class Random(Object): Type = RandomType def __cinit__(self): self.obj = &self.rnd self.rnd = NULL def __call__(self): return self.getValue() def view(self, Viewer viewer=None): assert self.obj != NULL cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscRandomView(self.rnd, vwr) ) def destroy(self): CHKERR( PetscRandomDestroy(&self.rnd) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) CHKERR( PetscRandomCreate(ccomm, &self.rnd) ) return self def setType(self, rnd_type): cdef PetscRandomType cval = NULL rnd_type = str2bytes(rnd_type, &cval) CHKERR( PetscRandomSetType(self.rnd, cval) ) def getType(self): cdef PetscRandomType cval = NULL CHKERR( PetscRandomGetType(self.rnd, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( PetscRandomSetFromOptions(self.rnd) ) def getValue(self): cdef PetscScalar sval = 0 CHKERR( PetscRandomGetValue(self.rnd, &sval) ) return toScalar(sval) def getValueReal(self): cdef PetscReal rval = 0 CHKERR( PetscRandomGetValueReal(self.rnd, &rval) ) return toReal(rval) def getSeed(self): cdef unsigned long seed = 0 CHKERR( PetscRandomGetSeed(self.rnd, &seed) ) return seed def setSeed(self, seed=None): if seed is not None: CHKERR( PetscRandomSetSeed(self.rnd, seed) ) CHKERR( PetscRandomSeed(self.rnd) ) def getInterval(self): cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 1 CHKERR( PetscRandomGetInterval(self.rnd, &sval1, &sval2) ) return (toScalar(sval1), toScalar(sval2)) def setInterval(self, interval): cdef PetscScalar sval1 = 0 cdef PetscScalar sval2 = 1 low, high = interval sval1 = asScalar(low) sval2 = asScalar(high) CHKERR( PetscRandomSetInterval(self.rnd, sval1, sval2) ) # property seed: def __get__(self): return self.getSeed() def __set__(self, value): self.setSeed(value) property interval: def __get__(self): return self.getInterval() def __set__(self, value): self.setInterval(value) # -------------------------------------------------------------------- del RandomType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/SF.pyx000066400000000000000000000225011454104047300177210ustar00rootroot00000000000000# -------------------------------------------------------------------- class SFType(object): BASIC = S_(PETSCSFBASIC) NEIGHBOR = S_(PETSCSFNEIGHBOR) ALLGATHERV = S_(PETSCSFALLGATHERV) ALLGATHER = S_(PETSCSFALLGATHER) GATHERV = S_(PETSCSFGATHERV) GATHER = S_(PETSCSFGATHER) ALLTOALL = S_(PETSCSFALLTOALL) WINDOW = S_(PETSCSFWINDOW) # -------------------------------------------------------------------- cdef class SF(Object): Type = SFType def __cinit__(self): self.obj = &self.sf self.sf = NULL def __dealloc__(self): CHKERR( PetscSFDestroy(&self.sf) ) self.sf = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscSFView(self.sf, vwr) ) def destroy(self): CHKERR( PetscSFDestroy(&self.sf) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscSF newsf = NULL CHKERR( PetscSFCreate(ccomm, &newsf) ) PetscCLEAR(self.obj); self.sf = newsf return self def setType(self, sf_type): cdef PetscSFType cval = NULL sf_type = str2bytes(sf_type, &cval) CHKERR( PetscSFSetType(self.sf, cval) ) def getType(self): cdef PetscSFType cval = NULL CHKERR( PetscSFGetType(self.sf, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( PetscSFSetFromOptions(self.sf) ) def setUp(self): CHKERR( PetscSFSetUp(self.sf) ) def reset(self): CHKERR( PetscSFReset(self.sf) ) # def getGraph(self): """nleaves can be determined from the size of local""" cdef PetscInt nroots = 0, nleaves = 0 cdef const PetscInt *ilocal = NULL cdef const PetscSFNode *iremote = NULL CHKERR( PetscSFGetGraph(self.sf, &nroots, &nleaves, &ilocal, &iremote) ) if ilocal == NULL: local = arange(0, nleaves, 1) else: local = array_i(nleaves, ilocal) remote = array_i(nleaves*2, iremote) remote = remote.reshape(nleaves, 2) return toInt(nroots), local, remote def setGraph(self, nroots, local, remote): """ The nleaves argument is determined from the size of local and/or remote. local may be None, meaning contiguous storage. remote should be 2*nleaves long as (rank, index) pairs. """ cdef PetscInt cnroots = asInt(nroots) cdef PetscInt nleaves = 0 cdef PetscInt nremote = 0 cdef PetscInt *ilocal = NULL cdef PetscSFNode* iremote = NULL remote = iarray_i(remote, &nremote, &iremote) if local is not None: local = iarray_i(local, &nleaves, &ilocal) assert 2*nleaves == nremote else: assert nremote % 2 == 0 nleaves = nremote // 2 CHKERR( PetscSFSetGraph(self.sf, cnroots, nleaves, ilocal, PETSC_COPY_VALUES, iremote, PETSC_COPY_VALUES) ) def setRankOrder(self, flag): cdef PetscBool bval = asBool(flag) CHKERR( PetscSFSetRankOrder(self.sf, bval) ) # def getMulti(self): cdef SF sf = SF() CHKERR( PetscSFGetMultiSF(self.sf, &sf.sf) ) PetscINCREF(sf.obj) return sf def createInverse(self): cdef SF sf = SF() CHKERR( PetscSFCreateInverseSF(self.sf, &sf.sf) ) return sf def computeDegree(self): cdef const PetscInt *cdegree = NULL cdef PetscInt nroots CHKERR( PetscSFComputeDegreeBegin(self.sf, &cdegree) ) CHKERR( PetscSFComputeDegreeEnd(self.sf, &cdegree) ) CHKERR( PetscSFGetGraph(self.sf, &nroots, NULL, NULL, NULL) ) degree = array_i(nroots, cdegree) return degree def createEmbeddedRootSF(self, selected): cdef PetscInt nroots = asInt(len(selected)) cdef PetscInt *cselected = NULL selected = iarray_i(selected, &nroots, &cselected) cdef SF sf = SF() CHKERR( PetscSFCreateEmbeddedRootSF(self.sf, nroots, cselected, &sf.sf) ) return sf def createEmbeddedLeafSF(self, selected): cdef PetscInt nleaves = asInt(len(selected)) cdef PetscInt *cselected = NULL selected = iarray_i(selected, &nleaves, &cselected) cdef SF sf = SF() CHKERR( PetscSFCreateEmbeddedLeafSF(self.sf, nleaves, cselected, &sf.sf) ) return sf def createSectionSF(self, Section rootSection, remoteOffsets, Section leafSection): cdef SF sectionSF = SF() cdef PetscInt noffsets = 0 cdef PetscInt *cremoteOffsets = NULL if remoteOffsets is not None: remoteOffsets = iarray_i(remoteOffsets, &noffsets, &cremoteOffsets) CHKERR( PetscSFCreateSectionSF(self.sf, rootSection.sec, cremoteOffsets, leafSection.sec, §ionSF.sf) ) return sectionSF def distributeSection(self, Section rootSection, Section leafSection=None): cdef PetscInt lpStart cdef PetscInt lpEnd cdef PetscInt *cremoteOffsets = NULL cdef ndarray remoteOffsets cdef MPI_Comm ccomm = def_Comm(self.comm, PETSC_COMM_DEFAULT) if leafSection is None: leafSection = Section() if leafSection.sec == NULL: CHKERR( PetscSectionCreate(ccomm, &leafSection.sec) ) CHKERR( PetscSFDistributeSection(self.sf, rootSection.sec, &cremoteOffsets, leafSection.sec) ) CHKERR( PetscSectionGetChart(leafSection.sec, &lpStart, &lpEnd) ) remoteOffsets = array_i(lpEnd-lpStart, cremoteOffsets) CHKERR( PetscFree(cremoteOffsets) ) return (remoteOffsets, leafSection) def compose(self, SF sf): cdef SF csf = SF() CHKERR( PetscSFCompose(self.sf, sf.sf, &csf.sf)) return csf def bcastBegin(self, unit, ndarray rootdata, ndarray leafdata, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFBcastBegin(self.sf, dtype, PyArray_DATA(rootdata), PyArray_DATA(leafdata), cop) ) def bcastEnd(self, unit, ndarray rootdata, ndarray leafdata, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFBcastEnd(self.sf, dtype, PyArray_DATA(rootdata), PyArray_DATA(leafdata), cop) ) def reduceBegin(self, unit, ndarray leafdata, ndarray rootdata, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFReduceBegin(self.sf, dtype, PyArray_DATA(leafdata), PyArray_DATA(rootdata), cop) ) def reduceEnd(self, unit, ndarray leafdata, ndarray rootdata, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFReduceEnd(self.sf, dtype, PyArray_DATA(leafdata), PyArray_DATA(rootdata), cop) ) def scatterBegin(self, unit, ndarray multirootdata, ndarray leafdata): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) CHKERR( PetscSFScatterBegin(self.sf, dtype, PyArray_DATA(multirootdata), PyArray_DATA(leafdata)) ) def scatterEnd(self, unit, ndarray multirootdata, ndarray leafdata): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) CHKERR( PetscSFScatterEnd(self.sf, dtype, PyArray_DATA(multirootdata), PyArray_DATA(leafdata)) ) def gatherBegin(self, unit, ndarray leafdata, ndarray multirootdata): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) CHKERR( PetscSFGatherBegin(self.sf, dtype, PyArray_DATA(leafdata), PyArray_DATA(multirootdata)) ) def gatherEnd(self, unit, ndarray leafdata, ndarray multirootdata): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) CHKERR( PetscSFGatherEnd(self.sf, dtype, PyArray_DATA(leafdata), PyArray_DATA(multirootdata)) ) def fetchAndOpBegin(self, unit, rootdata, leafdata, leafupdate, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFFetchAndOpBegin(self.sf, dtype, PyArray_DATA(rootdata), PyArray_DATA(leafdata), PyArray_DATA(leafupdate), cop) ) def fetchAndOpEnd(self, unit, rootdata, leafdata, leafupdate, op): cdef MPI_Datatype dtype = mpi4py_Datatype_Get(unit) cdef MPI_Op cop = mpi4py_Op_Get(op) CHKERR( PetscSFFetchAndOpEnd(self.sf, dtype, PyArray_DATA(rootdata), PyArray_DATA(leafdata), PyArray_DATA(leafupdate), cop) ) # -------------------------------------------------------------------- del SFType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/SNES.pyx000066400000000000000000001065741454104047300201760ustar00rootroot00000000000000# -------------------------------------------------------------------- class SNESType(object): NEWTONLS = S_(SNESNEWTONLS) NEWTONTR = S_(SNESNEWTONTR) PYTHON = S_(SNESPYTHON) NRICHARDSON = S_(SNESNRICHARDSON) KSPONLY = S_(SNESKSPONLY) KSPTRANSPOSEONLY = S_(SNESKSPTRANSPOSEONLY) VINEWTONRSLS = S_(SNESVINEWTONRSLS) VINEWTONSSLS = S_(SNESVINEWTONSSLS) NGMRES = S_(SNESNGMRES) QN = S_(SNESQN) SHELL = S_(SNESSHELL) NGS = S_(SNESNGS) NCG = S_(SNESNCG) FAS = S_(SNESFAS) MS = S_(SNESMS) NASM = S_(SNESNASM) ANDERSON = S_(SNESANDERSON) ASPIN = S_(SNESASPIN) COMPOSITE = S_(SNESCOMPOSITE) PATCH = S_(SNESPATCH) class SNESNormSchedule(object): # native NORM_DEFAULT = SNES_NORM_DEFAULT NORM_NONE = SNES_NORM_NONE NORM_ALWAYS = SNES_NORM_ALWAYS NORM_INITIAL_ONLY = SNES_NORM_INITIAL_ONLY NORM_FINAL_ONLY = SNES_NORM_FINAL_ONLY NORM_INITIAL_FINAL_ONLY = SNES_NORM_INITIAL_FINAL_ONLY # aliases DEFAULT = NORM_DEFAULT NONE = NORM_NONE ALWAYS = NORM_ALWAYS INITIAL_ONLY = NORM_INITIAL_ONLY FINAL_ONLY = NORM_FINAL_ONLY INITIAL_FINAL_ONLY = NORM_INITIAL_FINAL_ONLY class SNESConvergedReason(object): # iterating CONVERGED_ITERATING = SNES_CONVERGED_ITERATING ITERATING = SNES_CONVERGED_ITERATING # converged CONVERGED_FNORM_ABS = SNES_CONVERGED_FNORM_ABS CONVERGED_FNORM_RELATIVE = SNES_CONVERGED_FNORM_RELATIVE CONVERGED_SNORM_RELATIVE = SNES_CONVERGED_SNORM_RELATIVE CONVERGED_ITS = SNES_CONVERGED_ITS # diverged DIVERGED_FUNCTION_DOMAIN = SNES_DIVERGED_FUNCTION_DOMAIN DIVERGED_FUNCTION_COUNT = SNES_DIVERGED_FUNCTION_COUNT DIVERGED_LINEAR_SOLVE = SNES_DIVERGED_LINEAR_SOLVE DIVERGED_FNORM_NAN = SNES_DIVERGED_FNORM_NAN DIVERGED_MAX_IT = SNES_DIVERGED_MAX_IT DIVERGED_LINE_SEARCH = SNES_DIVERGED_LINE_SEARCH DIVERGED_INNER = SNES_DIVERGED_INNER DIVERGED_LOCAL_MIN = SNES_DIVERGED_LOCAL_MIN DIVERGED_DTOL = SNES_DIVERGED_DTOL DIVERGED_JACOBIAN_DOMAIN = SNES_DIVERGED_JACOBIAN_DOMAIN DIVERGED_TR_DELTA = SNES_DIVERGED_TR_DELTA # -------------------------------------------------------------------- cdef class SNES(Object): Type = SNESType NormSchedule = SNESNormSchedule ConvergedReason = SNESConvergedReason # --- xxx --- def __cinit__(self): self.obj = &self.snes self.snes = NULL # --- xxx --- def view(self, Viewer viewer=None): cdef PetscViewer cviewer = NULL if viewer is not None: cviewer = viewer.vwr CHKERR( SNESView(self.snes, cviewer) ) def destroy(self): CHKERR( SNESDestroy(&self.snes) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscSNES newsnes = NULL CHKERR( SNESCreate(ccomm, &newsnes) ) PetscCLEAR(self.obj); self.snes = newsnes return self def setType(self, snes_type): cdef PetscSNESType cval = NULL snes_type = str2bytes(snes_type, &cval) CHKERR( SNESSetType(self.snes, cval) ) def getType(self): cdef PetscSNESType cval = NULL CHKERR( SNESGetType(self.snes, &cval) ) return bytes2str(cval) def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SNESSetOptionsPrefix(self.snes, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( SNESGetOptionsPrefix(self.snes, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( SNESAppendOptionsPrefix(self.snes, cval) ) def setFromOptions(self): CHKERR( SNESSetFromOptions(self.snes) ) # --- application context --- def setApplicationContext(self, appctx): self.set_attr('__appctx__', appctx) if appctx is not None: registerAppCtx(appctx) CHKERR( SNESSetApplicationContext(self.snes, appctx) ) else: CHKERR( SNESSetApplicationContext(self.snes, NULL) ) def getApplicationContext(self): cdef void *ctx appctx = self.get_attr('__appctx__') if appctx is None: CHKERR( SNESGetApplicationContext(self.snes, &ctx) ) appctx = toAppCtx(ctx) return appctx # backward compatibility setAppCtx = setApplicationContext getAppCtx = getApplicationContext # --- discretization space --- def getDM(self): cdef PetscDM newdm = NULL CHKERR( SNESGetDM(self.snes, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setDM(self, DM dm): CHKERR( SNESSetDM(self.snes, dm.dm) ) # --- FAS --- def setFASInterpolation(self, level, Mat mat): cdef PetscInt clevel = asInt(level) CHKERR( SNESFASSetInterpolation(self.snes, clevel, mat.mat) ) def getFASInterpolation(self, level): cdef PetscInt clevel = asInt(level) cdef Mat mat = Mat() CHKERR( SNESFASGetInterpolation(self.snes, clevel, &mat.mat) ) PetscINCREF(mat.obj) return mat def setFASRestriction(self, level, Mat mat): cdef PetscInt clevel = asInt(level) CHKERR( SNESFASSetRestriction(self.snes, clevel, mat.mat) ) def getFASRestriction(self, level): cdef PetscInt clevel = asInt(level) cdef Mat mat = Mat() CHKERR( SNESFASGetRestriction(self.snes, clevel, &mat.mat) ) PetscINCREF(mat.obj) return mat def setFASInjection(self, level, Mat mat): cdef PetscInt clevel = asInt(level) CHKERR( SNESFASSetInjection(self.snes, clevel, mat.mat) ) def getFASInjection(self, level): cdef PetscInt clevel = asInt(level) cdef Mat mat = Mat() CHKERR( SNESFASGetInjection(self.snes, clevel, &mat.mat) ) PetscINCREF(mat.obj) return mat def setFASRScale(self, level, Vec vec): cdef PetscInt clevel = asInt(level) CHKERR( SNESFASSetRScale(self.snes, clevel, vec.vec) ) def setFASLevels(self, levels, comms=None): cdef PetscInt clevels = asInt(levels) cdef MPI_Comm *ccomms = NULL cdef Py_ssize_t i = 0 if comms is not None: if clevels != len(comms): raise ValueError("Must provide as many communicators as levels") CHKERR( PetscMalloc(sizeof(MPI_Comm)*clevels, &ccomms) ) try: for i, comm in enumerate(comms): ccomms[i] = def_Comm(comm, MPI_COMM_NULL) CHKERR( SNESFASSetLevels(self.snes, clevels, ccomms) ) finally: CHKERR( PetscFree(ccomms) ) else: CHKERR( SNESFASSetLevels(self.snes, clevels, ccomms) ) def getFASLevels(self): cdef PetscInt levels = 0 CHKERR( SNESFASGetLevels(self.snes, &levels) ) return toInt(levels) def getFASCycleSNES(self, level): cdef PetscInt clevel = asInt(level) cdef SNES lsnes = SNES() CHKERR( SNESFASGetCycleSNES(self.snes, clevel, &lsnes.snes) ) PetscINCREF(lsnes.obj) return lsnes def getFASCoarseSolve(self): cdef SNES smooth = SNES() CHKERR( SNESFASGetCoarseSolve(self.snes, &smooth.snes) ) PetscINCREF(smooth.obj) return smooth def getFASSmoother(self, level): cdef PetscInt clevel = asInt(level) cdef SNES smooth = SNES() CHKERR( SNESFASGetSmoother(self.snes, clevel, &smooth.snes) ) PetscINCREF(smooth.obj) return smooth def getFASSmootherDown(self, level): cdef PetscInt clevel = asInt(level) cdef SNES smooth = SNES() CHKERR( SNESFASGetSmootherDown(self.snes, clevel, &smooth.snes) ) PetscINCREF(smooth.obj) return smooth def getFASSmootherUp(self, level): cdef PetscInt clevel = asInt(level) cdef SNES smooth = SNES() CHKERR( SNESFASGetSmootherUp(self.snes, clevel, &smooth.snes) ) PetscINCREF(smooth.obj) return smooth # --- nonlinear preconditioner --- def getNPC(self): cdef SNES snes = SNES() CHKERR( SNESGetNPC(self.snes, &snes.snes) ) PetscINCREF(snes.obj) return snes def hasNPC(self): cdef PetscBool flag = PETSC_FALSE CHKERR( SNESHasNPC(self.snes, &flag) ) return toBool(flag) def setNPC(self, SNES snes): CHKERR( SNESSetNPC(self.snes, snes.snes) ) def setNPCSide(self, side): CHKERR( SNESSetNPCSide(self.snes, side) ) def getNPCSide(self): cdef PetscPCSide side = PC_RIGHT CHKERR( SNESGetNPCSide(self.snes, &side) ) return side # --- user Function/Jacobian routines --- def setLineSearchPreCheck(self, precheck, args=None, kargs=None): cdef PetscSNESLineSearch snesls = NULL CHKERR( SNESGetLineSearch(self.snes, &snesls) ) if precheck is not None: if args is None: args = () if kargs is None: kargs = {} context = (precheck, args, kargs) self.set_attr('__precheck__', context) CHKERR( SNESLineSearchSetPreCheck(snesls, SNES_PreCheck, context) ) else: self.set_attr('__precheck__', None) CHKERR( SNESLineSearchSetPreCheck(snesls, NULL, NULL) ) def setInitialGuess(self, initialguess, args=None, kargs=None): if initialguess is not None: if args is None: args = () if kargs is None: kargs = {} context = (initialguess, args, kargs) self.set_attr('__initialguess__', context) CHKERR( SNESSetInitialGuess(self.snes, SNES_InitialGuess, context) ) else: self.set_attr('__initialguess__', None) CHKERR( SNESSetInitialGuess(self.snes, NULL, NULL) ) def getInitialGuess(self): return self.get_attr('__initialguess__') def setFunction(self, function, Vec f or None, args=None, kargs=None): cdef PetscVec fvec=NULL if f is not None: fvec = f.vec 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( SNESSetFunction(self.snes, fvec, SNES_Function, context) ) else: CHKERR( SNESSetFunction(self.snes, fvec, NULL, NULL) ) def getFunction(self): cdef Vec f = Vec() cdef void* ctx cdef PetscErrorCode (*fun)(PetscSNES,PetscVec,PetscVec,void*) CHKERR( SNESGetFunction(self.snes, &f.vec, &fun, &ctx) ) PetscINCREF(f.obj) cdef object function = self.get_attr('__function__') cdef object context if function is not None: return (f, function) if ctx != NULL and SNES_Function == fun: context = ctx if context is not None: assert type(context) is tuple return (f, context) return (f, None) def setUpdate(self, update, args=None, kargs=None): if update is not None: if args is None: args = () if kargs is None: kargs = {} context = (update, args, kargs) self.set_attr('__update__', context) CHKERR( SNESSetUpdate(self.snes, SNES_Update) ) else: self.set_attr('__update__', None) CHKERR( SNESSetUpdate(self.snes, NULL) ) def getUpdate(self): return self.get_attr('__update__') def setJacobian(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): cdef PetscMat Jmat=NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat=Jmat if P is not None: Pmat = P.mat 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( SNESSetJacobian(self.snes, Jmat, Pmat, SNES_Jacobian, context) ) else: CHKERR( SNESSetJacobian(self.snes, Jmat, Pmat, NULL, NULL) ) def getJacobian(self): cdef Mat J = Mat() cdef Mat P = Mat() CHKERR( SNESGetJacobian(self.snes, &J.mat, &P.mat, NULL, NULL) ) PetscINCREF(J.obj) PetscINCREF(P.obj) cdef object jacobian = self.get_attr('__jacobian__') return (J, P, jacobian) def setObjective(self, objective, args=None, kargs=None): if objective is not None: if args is None: args = () if kargs is None: kargs = {} context = (objective, args, kargs) self.set_attr('__objective__', context) CHKERR( SNESSetObjective(self.snes, SNES_Objective, context) ) else: CHKERR( SNESSetObjective(self.snes, NULL, NULL) ) def getObjective(self): CHKERR( SNESGetObjective(self.snes, NULL, NULL) ) cdef object objective = self.get_attr('__objective__') return objective def computeFunction(self, Vec x, Vec f): CHKERR( SNESComputeFunction(self.snes, x.vec, f.vec) ) def computeJacobian(self, Vec x, Mat J, Mat P=None): cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( SNESComputeJacobian(self.snes, x.vec, jmat, pmat) ) def computeObjective(self, Vec x): cdef PetscReal o = 0 CHKERR( SNESComputeObjective(self.snes, x.vec, &o) ) return toReal(o) def setNGS(self, ngs, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (ngs, args, kargs) self.set_attr('__ngs__', context) CHKERR( SNESSetNGS(self.snes, SNES_NGS, context) ) def getNGS(self): CHKERR( SNESGetNGS(self.snes, NULL, NULL) ) cdef object ngs = self.get_attr('__ngs__') return ngs def computeNGS(self, Vec x, Vec b=None): cdef PetscVec bvec = NULL if b is not None: bvec = b.vec CHKERR( SNESComputeNGS(self.snes, bvec, x.vec) ) # --- tolerances and convergence --- def setTolerances(self, rtol=None, atol=None, stol=None, max_it=None): cdef PetscReal crtol, catol, cstol crtol = catol = cstol = PETSC_DEFAULT cdef PetscInt cmaxit = PETSC_DEFAULT if rtol is not None: crtol = asReal(rtol) if atol is not None: catol = asReal(atol) if stol is not None: cstol = asReal(stol) if max_it is not None: cmaxit = asInt(max_it) CHKERR( SNESSetTolerances(self.snes, catol, crtol, cstol, cmaxit, PETSC_DEFAULT) ) def getTolerances(self): cdef PetscReal crtol=0, catol=0, cstol=0 cdef PetscInt cmaxit=0 CHKERR( SNESGetTolerances(self.snes, &catol, &crtol, &cstol, &cmaxit, NULL) ) return (toReal(crtol), toReal(catol), toReal(cstol), toInt(cmaxit)) def setNormSchedule(self, normsched): CHKERR( SNESSetNormSchedule(self.snes, normsched) ) def getNormSchedule(self): cdef PetscSNESNormSchedule normsched = SNES_NORM_NONE CHKERR( SNESGetNormSchedule(self.snes, &normsched) ) return normsched def setConvergenceTest(self, converged, args=None, kargs=None): if converged == "skip": self.set_attr('__converged__', None) CHKERR( SNESSetConvergenceTest(self.snes, SNESConvergedSkip, NULL, NULL) ) elif converged is None or converged == "default": self.set_attr('__converged__', None) CHKERR( SNESSetConvergenceTest(self.snes, SNESConvergedDefault, NULL, NULL) ) else: assert callable(converged) if args is None: args = () if kargs is None: kargs = {} context = (converged, args, kargs) self.set_attr('__converged__', context) CHKERR( SNESSetConvergenceTest(self.snes, SNES_Converged, context, NULL) ) def getConvergenceTest(self): return self.get_attr('__converged__') def callConvergenceTest(self, its, xnorm, ynorm, fnorm): cdef PetscInt ival = asInt(its) cdef PetscReal rval1 = asReal(xnorm) cdef PetscReal rval2 = asReal(ynorm) cdef PetscReal rval3 = asReal(fnorm) cdef PetscSNESConvergedReason reason = SNES_CONVERGED_ITERATING CHKERR( SNESConvergenceTestCall(self.snes, ival, rval1, rval2, rval3, &reason) ) return reason def setConvergenceHistory(self, length=None, reset=False): cdef PetscReal *rdata = NULL cdef PetscInt *idata = NULL cdef PetscInt size = 1000 cdef PetscBool flag = PETSC_FALSE if length is True: pass elif length is not None: size = asInt(length) if size < 0: size = 1000 if reset: flag = PETSC_TRUE cdef object rhist = oarray_r(empty_r(size), NULL, &rdata) cdef object ihist = oarray_i(empty_i(size), NULL, &idata) self.set_attr('__history__', (rhist, ihist)) CHKERR( SNESSetConvergenceHistory(self.snes, rdata, idata, size, flag) ) def getConvergenceHistory(self): cdef PetscReal *rdata = NULL cdef PetscInt *idata = NULL cdef PetscInt size = 0 CHKERR( SNESGetConvergenceHistory(self.snes, &rdata, &idata, &size) ) cdef object rhist = array_r(size, rdata) cdef object ihist = array_i(size, idata) return (rhist, ihist) def logConvergenceHistory(self, norm, linear_its=0): cdef PetscReal rval = asReal(norm) cdef PetscInt ival = asInt(linear_its) CHKERR( SNESLogConvergenceHistory(self.snes, rval, ival) ) def setResetCounters(self, reset=True): cdef PetscBool flag = reset CHKERR( SNESSetCountersReset(self.snes, flag) ) # --- monitoring --- def setMonitor(self, monitor, args=None, kargs=None): if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( SNESMonitorSet(self.snes, SNES_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} context = (monitor, args, kargs) monitorlist.append(context) def getMonitor(self): return self.get_attr('__monitor__') def monitorCancel(self): CHKERR( SNESMonitorCancel(self.snes) ) self.set_attr('__monitor__', None) cancelMonitor = monitorCancel def monitor(self, its, rnorm): cdef PetscInt ival = asInt(its) cdef PetscReal rval = asReal(rnorm) CHKERR( SNESMonitor(self.snes, ival, rval) ) # --- more tolerances --- def setMaxFunctionEvaluations(self, max_funcs): cdef PetscReal r = PETSC_DEFAULT cdef PetscInt i = PETSC_DEFAULT cdef PetscInt ival = asInt(max_funcs) CHKERR( SNESSetTolerances(self.snes, r, r, r, i, ival) ) def getMaxFunctionEvaluations(self): cdef PetscReal *r = NULL cdef PetscInt *i = NULL cdef PetscInt ival = 0 CHKERR( SNESGetTolerances(self.snes, r, r, r, i, &ival) ) return toInt(ival) def getFunctionEvaluations(self): cdef PetscInt ival = 0 CHKERR( SNESGetNumberFunctionEvals(self.snes, &ival) ) return toInt(ival) def setMaxStepFailures(self, max_fails): cdef PetscInt ival = asInt(max_fails) CHKERR( SNESSetMaxNonlinearStepFailures(self.snes, ival) ) def getMaxStepFailures(self): cdef PetscInt ival = 0 CHKERR( SNESGetMaxNonlinearStepFailures(self.snes, &ival) ) return toInt(ival) def getStepFailures(self): cdef PetscInt ival = 0 CHKERR( SNESGetNonlinearStepFailures(self.snes, &ival) ) return toInt(ival) def setMaxKSPFailures(self, max_fails): cdef PetscInt ival = asInt(max_fails) CHKERR( SNESSetMaxLinearSolveFailures(self.snes, ival) ) def getMaxKSPFailures(self): cdef PetscInt ival = 0 CHKERR( SNESGetMaxLinearSolveFailures(self.snes, &ival) ) return toInt(ival) def getKSPFailures(self): cdef PetscInt ival = 0 CHKERR( SNESGetLinearSolveFailures(self.snes, &ival) ) return toInt(ival) setMaxNonlinearStepFailures = setMaxStepFailures getMaxNonlinearStepFailures = getMaxStepFailures getNonlinearStepFailures = getStepFailures setMaxLinearSolveFailures = setMaxKSPFailures getMaxLinearSolveFailures = getMaxKSPFailures getLinearSolveFailures = getKSPFailures # --- solving --- def setUp(self): CHKERR( SNESSetUp(self.snes) ) def reset(self): CHKERR( SNESReset(self.snes) ) def solve(self, Vec b = None, Vec x = None): cdef PetscVec rhs = NULL cdef PetscVec sol = NULL if b is not None: rhs = b.vec if x is not None: sol = x.vec CHKERR( SNESSolve(self.snes, rhs, sol) ) def setConvergedReason(self, reason): cdef PetscSNESConvergedReason eval = reason CHKERR( SNESSetConvergedReason(self.snes, eval) ) def getConvergedReason(self): cdef PetscSNESConvergedReason reason = SNES_CONVERGED_ITERATING CHKERR( SNESGetConvergedReason(self.snes, &reason) ) return reason def setErrorIfNotConverged(self, bint flag): cdef PetscBool ernc = PETSC_FALSE if flag: ernc = PETSC_TRUE CHKERR( SNESSetErrorIfNotConverged(self.snes, ernc) ) def getErrorIfNotConverged(self): cdef PetscBool flag = PETSC_FALSE CHKERR( SNESGetErrorIfNotConverged(self.snes, &flag) ) return toBool(flag) def setIterationNumber(self, its): cdef PetscInt ival = asInt(its) CHKERR( SNESSetIterationNumber(self.snes, ival) ) def getIterationNumber(self): cdef PetscInt ival = 0 CHKERR( SNESGetIterationNumber(self.snes, &ival) ) return toInt(ival) def setForceIteration(self, force): cdef PetscBool bval = asBool(force) CHKERR( SNESSetForceIteration(self.snes, bval) ) def setFunctionNorm(self, norm): cdef PetscReal rval = asReal(norm) CHKERR( SNESSetFunctionNorm(self.snes, rval) ) def getFunctionNorm(self): cdef PetscReal rval = 0 CHKERR( SNESGetFunctionNorm(self.snes, &rval) ) return toReal(rval) def getLinearSolveIterations(self): cdef PetscInt ival = 0 CHKERR( SNESGetLinearSolveIterations(self.snes, &ival) ) return toInt(ival) def getRhs(self): cdef Vec vec = Vec() CHKERR( SNESGetRhs(self.snes, &vec.vec) ) PetscINCREF(vec.obj) return vec def getSolution(self): cdef Vec vec = Vec() CHKERR( SNESGetSolution(self.snes, &vec.vec) ) PetscINCREF(vec.obj) return vec def setSolution(self, Vec vec): CHKERR( SNESSetSolution(self.snes, vec.vec) ) def getSolutionUpdate(self): cdef Vec vec = Vec() CHKERR( SNESGetSolutionUpdate(self.snes, &vec.vec) ) PetscINCREF(vec.obj) return vec # --- linear solver --- def setKSP(self, KSP ksp): CHKERR( SNESSetKSP(self.snes, ksp.ksp) ) def getKSP(self): cdef KSP ksp = KSP() CHKERR( SNESGetKSP(self.snes, &ksp.ksp) ) PetscINCREF(ksp.obj) return ksp def setUseEW(self, flag=True, *targs, **kargs): cdef PetscBool bval = flag CHKERR( SNESKSPSetUseEW(self.snes, bval) ) if targs or kargs: self.setParamsEW(*targs, **kargs) def getUseEW(self): cdef PetscBool flag = PETSC_FALSE CHKERR( SNESKSPGetUseEW(self.snes, &flag) ) return toBool(flag) def setParamsEW(self, version=None, rtol_0=None, rtol_max=None, gamma=None, alpha=None, alpha2=None, threshold=None): cdef PetscInt cversion = PETSC_DEFAULT cdef PetscReal crtol_0 = PETSC_DEFAULT cdef PetscReal crtol_max = PETSC_DEFAULT cdef PetscReal cgamma = PETSC_DEFAULT cdef PetscReal calpha = PETSC_DEFAULT cdef PetscReal calpha2 = PETSC_DEFAULT cdef PetscReal cthreshold = PETSC_DEFAULT if version is not None: cversion = asInt(version) if rtol_0 is not None: crtol_0 = asReal(rtol_0) if rtol_max is not None: crtol_max = asReal(rtol_max) if gamma is not None: cgamma = asReal(gamma) if alpha is not None: calpha = asReal(alpha) if alpha2 is not None: calpha2 = asReal(alpha2) if threshold is not None: cthreshold = asReal(threshold) CHKERR( SNESKSPSetParametersEW( self.snes, cversion, crtol_0, crtol_max, cgamma, calpha, calpha2, cthreshold) ) def getParamsEW(self): cdef PetscInt version=0 cdef PetscReal rtol_0=0, rtol_max=0 cdef PetscReal gamma=0, alpha=0, alpha2=0 cdef PetscReal threshold=0 CHKERR( SNESKSPGetParametersEW( self.snes, &version, &rtol_0, &rtol_max, &gamma, &alpha, &alpha2, &threshold) ) return {'version' : toInt(version), 'rtol_0' : toReal(rtol_0), 'rtol_max' : toReal(rtol_max), 'gamma' : toReal(gamma), 'alpha' : toReal(alpha), 'alpha2' : toReal(alpha2), 'threshold' : toReal(threshold),} # --- matrix free / finite differences --- def setUseMF(self, flag=True): cdef PetscBool bval = flag CHKERR( SNESSetUseMFFD(self.snes, bval) ) def getUseMF(self): cdef PetscBool flag = PETSC_FALSE CHKERR( SNESGetUseMFFD(self.snes, &flag) ) return toBool(flag) def setUseFD(self, flag=True): cdef PetscBool bval = flag CHKERR( SNESSetUseFDColoring(self.snes, bval) ) def getUseFD(self): cdef PetscBool flag = PETSC_FALSE CHKERR( SNESGetUseFDColoring(self.snes, &flag) ) return toBool(flag) # --- VI --- def setVariableBounds(self, Vec xl, Vec xu): CHKERR( SNESVISetVariableBounds(self.snes, xl.vec, xu.vec) ) def getVIInactiveSet(self): cdef IS inact = IS() CHKERR( SNESVIGetInactiveSet(self.snes, &inact.iset) ) PetscINCREF(inact.obj) return inact # --- Python --- def createPython(self, context=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscSNES newsnes = NULL CHKERR( SNESCreate(ccomm, &newsnes) ) PetscCLEAR(self.obj); self.snes = newsnes CHKERR( SNESSetType(self.snes, SNESPYTHON) ) CHKERR( SNESPythonSetContext(self.snes, context) ) return self def setPythonContext(self, context): CHKERR( SNESPythonSetContext(self.snes, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( SNESPythonGetContext(self.snes, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( SNESPythonSetType(self.snes, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( SNESPythonGetType(self.snes, &cval) ) return bytes2str(cval) # --- Composite --- def getCompositeSNES(self, n): cdef PetscInt cn cdef SNES snes = SNES() cn = asInt(n) CHKERR( SNESCompositeGetSNES(self.snes, cn, &snes.snes) ) PetscINCREF(snes.obj) return snes def getCompositeNumber(self): cdef PetscInt cn = 0 CHKERR( SNESCompositeGetNumber(self.snes, &cn) ) return toInt(cn) # --- NASM --- def getNASMSNES(self, n): cdef PetscInt cn = asInt(n) cdef SNES snes = SNES() CHKERR( SNESNASMGetSNES(self.snes, cn, &snes.snes) ) PetscINCREF(snes.obj) return snes def getNASMNumber(self): cdef PetscInt cn = 0 CHKERR( SNESNASMGetNumber(self.snes, &cn) ) return toInt(cn) # --- Patch --- def setPatchCellNumbering(self, Section sec not None): CHKERR( SNESPatchSetCellNumbering(self.snes, sec.sec) ) def setPatchDiscretisationInfo(self, dms, bs, cellNodeMaps, subspaceOffsets, ghostBcNodes, globalBcNodes): cdef PetscInt numSubSpaces = 0 cdef PetscInt numGhostBcs = 0, numGlobalBcs = 0 cdef PetscInt *nodesPerCell = NULL cdef const PetscInt **ccellNodeMaps = NULL cdef PetscDM *cdms = NULL cdef PetscInt *cbs = NULL cdef PetscInt *csubspaceOffsets = NULL cdef PetscInt *cghostBcNodes = NULL cdef PetscInt *cglobalBcNodes = NULL cdef PetscInt i = 0 bs = iarray_i(bs, &numSubSpaces, &cbs) ghostBcNodes = iarray_i(ghostBcNodes, &numGhostBcs, &cghostBcNodes) globalBcNodes = iarray_i(globalBcNodes, &numGlobalBcs, &cglobalBcNodes) subspaceOffsets = iarray_i(subspaceOffsets, NULL, &csubspaceOffsets) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscInt), &nodesPerCell) ) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscDM), &cdms) ) CHKERR( PetscMalloc(numSubSpaces*sizeof(PetscInt*), &ccellNodeMaps) ) for i in range(numSubSpaces): cdms[i] = (dms[i]).dm _, nodes = asarray(cellNodeMaps[i]).shape cellNodeMaps[i] = iarray_i(cellNodeMaps[i], NULL, &(ccellNodeMaps[i])) nodesPerCell[i] = asInt(nodes) # TODO: refactor on the PETSc side to take ISes? CHKERR( SNESPatchSetDiscretisationInfo(self.snes, numSubSpaces, cdms, cbs, nodesPerCell, ccellNodeMaps, csubspaceOffsets, numGhostBcs, cghostBcNodes, numGlobalBcs, cglobalBcNodes) ) CHKERR( PetscFree(nodesPerCell) ) CHKERR( PetscFree(cdms) ) CHKERR( PetscFree(ccellNodeMaps) ) def setPatchComputeOperator(self, operator, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (operator, args, kargs) self.set_attr("__patch_compute_operator__", context) CHKERR( SNESPatchSetComputeOperator(self.snes, PCPatch_ComputeOperator, context) ) def setPatchComputeFunction(self, function, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr("__patch_compute_function__", context) CHKERR( SNESPatchSetComputeFunction(self.snes, PCPatch_ComputeFunction, context) ) def setPatchConstructType(self, typ, operator=None, args=None, kargs=None): if args is None: args = () if kargs is None: kargs = {} if typ in {PC.PatchConstructType.PYTHON, PC.PatchConstructType.USER} and operator is None: raise ValueError("Must provide operator for USER or PYTHON type") if operator is not None: context = (operator, args, kargs) else: context = None self.set_attr("__patch_construction_operator__", context) CHKERR( SNESPatchSetConstructType(self.snes, typ, PCPatch_UserConstructOperator, context) ) # --- application context --- property appctx: def __get__(self): return self.getAppCtx() def __set__(self, value): self.setAppCtx(value) # --- discretization space --- property dm: def __get__(self): return self.getDM() def __set__(self, value): self.setDM(value) # --- nonlinear preconditioner --- property npc: def __get__(self): return self.getNPC() def __set__(self, value): self.setNPC(value) # --- vectors --- property vec_sol: def __get__(self): return self.getSolution() property vec_upd: def __get__(self): return self.getSolutionUpdate() property vec_rhs: def __get__(self): return self.getRhs() # --- linear solver --- property ksp: def __get__(self): return self.getKSP() def __set__(self, value): self.setKSP(value) property use_ew: def __get__(self): return self.getUseEW() def __set__(self, value): self.setUseEW(value) # --- tolerances --- property rtol: def __get__(self): return self.getTolerances()[0] def __set__(self, value): self.setTolerances(rtol=value) property atol: def __get__(self): return self.getTolerances()[1] def __set__(self, value): self.setTolerances(atol=value) property stol: def __get__(self): return self.getTolerances()[2] def __set__(self, value): self.setTolerances(stol=value) property max_it: def __get__(self): return self.getTolerances()[3] def __set__(self, value): self.setTolerances(max_it=value) # --- more tolerances --- property max_funcs: def __get__(self): return self.getMaxFunctionEvaluations() def __set__(self, value): self.setMaxFunctionEvaluations(value) # --- iteration --- property its: def __get__(self): return self.getIterationNumber() def __set__(self, value): self.setIterationNumber(value) property norm: def __get__(self): return self.getFunctionNorm() def __set__(self, value): self.setFunctionNorm(value) property history: def __get__(self): return self.getConvergenceHistory() # --- convergence --- property reason: def __get__(self): return self.getConvergedReason() def __set__(self, value): self.setConvergedReason(value) property iterating: def __get__(self): return self.reason == 0 property converged: def __get__(self): return self.reason > 0 property diverged: def __get__(self): return self.reason < 0 # --- matrix free / finite differences --- property use_mf: def __get__(self): return self.getUseMF() def __set__(self, value): self.setUseMF(value) property use_fd: def __get__(self): return self.getUseFD() def __set__(self, value): self.setUseFD(value) # -------------------------------------------------------------------- del SNESType del SNESNormSchedule del SNESConvergedReason # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Scatter.pyx000066400000000000000000000104061454104047300210170ustar00rootroot00000000000000# -------------------------------------------------------------------- class ScatterType(object): BASIC = S_(PETSCSFBASIC) NEIGHBOR = S_(PETSCSFNEIGHBOR) ALLGATHERV = S_(PETSCSFALLGATHERV) ALLGATHER = S_(PETSCSFALLGATHER) GATHERV = S_(PETSCSFGATHERV) GATHER = S_(PETSCSFGATHER) ALLTOALL = S_(PETSCSFALLTOALL) WINDOW = S_(PETSCSFWINDOW) # -------------------------------------------------------------------- cdef class Scatter(Object): Type = ScatterType Mode = ScatterMode # def __cinit__(self): self.obj = &self.sct self.sct = NULL def __call__(self, x, y, addv=None, mode=None): self.scatter(x, y, addv, mode) # def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( VecScatterView(self.sct, vwr) ) def destroy(self): CHKERR( VecScatterDestroy(&self.sct) ) return self def create(self, Vec vec_from, IS is_from or None, Vec vec_to, IS is_to or None): cdef PetscIS cisfrom = NULL, cisto = NULL if is_from is not None: cisfrom = is_from.iset if is_to is not None: cisto = is_to.iset cdef PetscScatter newsct = NULL CHKERR( VecScatterCreate( vec_from.vec, cisfrom, vec_to.vec, cisto, &newsct) ) PetscCLEAR(self.obj); self.sct = newsct return self def setType(self, scatter_type): cdef PetscScatterType cval = NULL vec_type = str2bytes(scatter_type, &cval) CHKERR( VecScatterSetType(self.sct, cval) ) def getType(self): cdef PetscScatterType cval = NULL CHKERR( VecScatterGetType(self.sct, &cval) ) return bytes2str(cval) def setFromOptions(self): CHKERR( VecScatterSetFromOptions(self.sct) ) def setUp(self): CHKERR( VecScatterSetUp(self.sct) ) return self def copy(self): cdef Scatter scatter = Scatter() CHKERR( VecScatterCopy(self.sct, &scatter.sct) ) return scatter @classmethod def toAll(cls, Vec vec): cdef Scatter scatter = Scatter() cdef Vec ovec = Vec() CHKERR( VecScatterCreateToAll( vec.vec, &scatter.sct, &ovec.vec) ) return (scatter, ovec) @classmethod def toZero(cls, Vec vec): cdef Scatter scatter = Scatter() cdef Vec ovec = Vec() CHKERR( VecScatterCreateToZero( vec.vec, &scatter.sct, &ovec.vec) ) return (scatter, ovec) # def begin(self, Vec vec_from, Vec vec_to, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecScatterBegin(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) def end(self, Vec vec_from, Vec vec_to, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecScatterEnd(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) # def scatterBegin(self, Vec vec_from, Vec vec_to, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecScatterBegin(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) def scatterEnd(self, Vec vec_from, Vec vec_to, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecScatterEnd(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) def scatter(self, Vec vec_from, Vec vec_to, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecScatterBegin(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) CHKERR( VecScatterEnd(self.sct, vec_from.vec, vec_to.vec, caddv, csctm) ) # -------------------------------------------------------------------- del ScatterType # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Section.pyx000066400000000000000000000215611454104047300210220ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef class Section(Object): def __cinit__(self): self.obj = &self.sec self.sec = NULL def __dealloc__(self): CHKERR( PetscSectionDestroy(&self.sec) ) self.sec = NULL def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscSectionView(self.sec, vwr) ) def destroy(self): CHKERR( PetscSectionDestroy(&self.sec) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscSection newsec = NULL CHKERR( PetscSectionCreate(ccomm, &newsec) ) PetscCLEAR(self.obj); self.sec = newsec return self def clone(self): cdef Section sec =
type(self)() CHKERR( PetscSectionClone(self.sec, &sec.sec) ) return sec def setUp(self): CHKERR( PetscSectionSetUp(self.sec) ) def reset(self): CHKERR( PetscSectionReset(self.sec) ) def getNumFields(self): cdef PetscInt numFields = 0 CHKERR( PetscSectionGetNumFields(self.sec, &numFields) ) return toInt(numFields) def setNumFields(self,numFields): cdef PetscInt cnumFields = asInt(numFields) CHKERR( PetscSectionSetNumFields(self.sec, cnumFields) ) def getFieldName(self,field): cdef PetscInt cfield = asInt(field) cdef const char *fieldName = NULL CHKERR( PetscSectionGetFieldName(self.sec,cfield,&fieldName) ) return bytes2str(fieldName) def setFieldName(self,field,fieldName): cdef PetscInt cfield = asInt(field) cdef const char *cname = NULL fieldName = str2bytes(fieldName, &cname) CHKERR( PetscSectionSetFieldName(self.sec,cfield,cname) ) def getFieldComponents(self,field): cdef PetscInt cfield = asInt(field), cnumComp = 0 CHKERR( PetscSectionGetFieldComponents(self.sec,cfield,&cnumComp) ) return toInt(cnumComp) def setFieldComponents(self,field,numComp): cdef PetscInt cfield = asInt(field) cdef PetscInt cnumComp = asInt(numComp) CHKERR( PetscSectionSetFieldComponents(self.sec,cfield,cnumComp) ) def getChart(self): cdef PetscInt pStart = 0, pEnd = 0 CHKERR( PetscSectionGetChart(self.sec, &pStart, &pEnd) ) return toInt(pStart), toInt(pEnd) def setChart(self, pStart, pEnd): cdef PetscInt cStart = asInt(pStart) cdef PetscInt cEnd = asInt(pEnd) CHKERR( PetscSectionSetChart(self.sec, cStart, cEnd) ) def getPermutation(self): cdef IS perm = IS() CHKERR( PetscSectionGetPermutation(self.sec, &perm.iset)) PetscINCREF(perm.obj) return perm def setPermutation(self, IS perm): CHKERR( PetscSectionSetPermutation(self.sec, perm.iset)) def getDof(self,point): cdef PetscInt cpoint = asInt(point), cnumDof = 0 CHKERR( PetscSectionGetDof(self.sec,cpoint,&cnumDof) ) return toInt(cnumDof) def setDof(self,point,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionSetDof(self.sec,cpoint,cnumDof) ) def addDof(self,point,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionAddDof(self.sec,cpoint,cnumDof) ) def getFieldDof(self,point,field): cdef PetscInt cpoint = asInt(point), cnumDof = 0 cdef PetscInt cfield = asInt(field) CHKERR( PetscSectionGetFieldDof(self.sec,cpoint,cfield,&cnumDof) ) return toInt(cnumDof) def setFieldDof(self,point,field,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionSetFieldDof(self.sec,cpoint,cfield,cnumDof) ) def addFieldDof(self,point,field,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionAddFieldDof(self.sec,cpoint,cfield,cnumDof) ) def getConstraintDof(self,point): cdef PetscInt cpoint = asInt(point), cnumDof = 0 CHKERR( PetscSectionGetConstraintDof(self.sec,cpoint,&cnumDof) ) return toInt(cnumDof) def setConstraintDof(self,point,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionSetConstraintDof(self.sec,cpoint,cnumDof) ) def addConstraintDof(self,point,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionAddConstraintDof(self.sec,cpoint,cnumDof) ) def getFieldConstraintDof(self,point,field): cdef PetscInt cpoint = asInt(point), cnumDof = 0 cdef PetscInt cfield = asInt(field) CHKERR( PetscSectionGetFieldConstraintDof(self.sec,cpoint,cfield,&cnumDof) ) return toInt(cnumDof) def setFieldConstraintDof(self,point,field,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionSetFieldConstraintDof(self.sec,cpoint,cfield,cnumDof) ) def addFieldConstraintDof(self,point,field,numDof): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt cnumDof = asInt(numDof) CHKERR( PetscSectionAddFieldConstraintDof(self.sec,cpoint,cfield,cnumDof) ) def getConstraintIndices(self,point): cdef PetscInt cpoint = asInt(point) cdef PetscInt nindex = 0 cdef const PetscInt *indices = NULL CHKERR( PetscSectionGetConstraintDof(self.sec, cpoint, &nindex) ) CHKERR( PetscSectionGetConstraintIndices(self.sec, cpoint, &indices) ) return array_i(nindex, indices) def setConstraintIndices(self,point,indices): cdef PetscInt cpoint = asInt(point) cdef PetscInt nindex = 0 cdef PetscInt *cindices = NULL indices = iarray_i(indices, &nindex, &cindices) CHKERR( PetscSectionSetConstraintDof(self.sec,cpoint,nindex) ) CHKERR( PetscSectionSetConstraintIndices(self.sec,cpoint,cindices) ) def getFieldConstraintIndices(self,point,field): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt nindex = 0 cdef const PetscInt *indices = NULL CHKERR( PetscSectionGetFieldConstraintDof(self.sec,cpoint,cfield,&nindex) ) CHKERR( PetscSectionGetFieldConstraintIndices(self.sec,cpoint,cfield,&indices) ) return array_i(nindex, indices) def setFieldConstraintIndices(self,point,field,indices): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt nindex = 0 cdef PetscInt *cindices = NULL indices = iarray_i(indices, &nindex, &cindices) CHKERR( PetscSectionSetFieldConstraintDof(self.sec,cpoint,cfield,nindex) ) CHKERR( PetscSectionSetFieldConstraintIndices(self.sec,cpoint,cfield,cindices) ) def getMaxDof(self): cdef PetscInt maxDof = 0 CHKERR( PetscSectionGetMaxDof(self.sec,&maxDof) ) return toInt(maxDof) def getStorageSize(self): cdef PetscInt size = 0 CHKERR( PetscSectionGetStorageSize(self.sec,&size) ) return toInt(size) def getConstrainedStorageSize(self): cdef PetscInt size = 0 CHKERR( PetscSectionGetConstrainedStorageSize(self.sec,&size) ) return toInt(size) def getOffset(self,point): cdef PetscInt cpoint = asInt(point), offset = 0 CHKERR( PetscSectionGetOffset(self.sec,cpoint,&offset) ) return toInt(offset) def setOffset(self,point,offset): cdef PetscInt cpoint = asInt(point) cdef PetscInt coffset = asInt(offset) CHKERR( PetscSectionSetOffset(self.sec,cpoint,coffset) ) def getFieldOffset(self,point,field): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt offset = 0 CHKERR( PetscSectionGetFieldOffset(self.sec,cpoint,cfield,&offset) ) return toInt(offset) def setFieldOffset(self,point,field,offset): cdef PetscInt cpoint = asInt(point) cdef PetscInt cfield = asInt(field) cdef PetscInt coffset = asInt(offset) CHKERR( PetscSectionSetFieldOffset(self.sec,cpoint,cfield,coffset) ) def getOffsetRange(self): cdef PetscInt oStart = 0, oEnd = 0 CHKERR( PetscSectionGetOffsetRange(self.sec,&oStart,&oEnd) ) return toInt(oStart),toInt(oEnd) def createGlobalSection(self, SF sf): cdef Section gsec = Section() CHKERR( PetscSectionCreateGlobalSection(self.sec,sf.sf,PETSC_FALSE,PETSC_FALSE,&gsec.sec) ) return gsec petsc4py-3.19.6/src/petsc4py/PETSc/Space.pyx000066400000000000000000000266251454104047300204570ustar00rootroot00000000000000# -------------------------------------------------------------------- class SpaceType(object): POLYNOMIAL = S_(PETSCSPACEPOLYNOMIAL) PTRIMMED = S_(PETSCSPACEPTRIMMED) TENSOR = S_(PETSCSPACETENSOR) SUM = S_(PETSCSPACESUM) POINT = S_(PETSCSPACEPOINT) SUBSPACE = S_(PETSCSPACESUBSPACE) WXY = S_(PETSCSPACEWXY) # -------------------------------------------------------------------- cdef class Space(Object): Type = SpaceType def __cinit__(self): self.obj = &self.space self.space = NULL def setUp(self): CHKERR( PetscSpaceSetUp(self.space) ) def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscSpace newsp = NULL CHKERR( PetscSpaceCreate(ccomm, &newsp) ) PetscCLEAR(self.obj); self.space = newsp return self def destroy(self): CHKERR( PetscSpaceDestroy(&self.space) ) return self def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscSpaceView(self.space, vwr) ) def setFromOptions(self): CHKERR( PetscSpaceSetFromOptions(self.space) ) def getDimension(self): cdef PetscInt cdim CHKERR( PetscSpaceGetDimension(self.space, &cdim)) return toInt(cdim) def getDegree(self): cdef PetscInt cdegmax, cdegmin CHKERR( PetscSpaceGetDegree(self.space, &cdegmin, &cdegmax)) return toInt(cdegmin), toInt(cdegmax) def setDegree(self, degree, maxDegree): assert( (degree != None) & (maxDegree != None)) cdef PetscInt cdegree = PETSC_DETERMINE if degree is not None: cdegree = asInt(degree) cdef PetscInt cmaxdegree = PETSC_DETERMINE if maxDegree is not None: cmaxdegree = asInt(maxDegree) CHKERR( PetscSpaceSetDegree(self.space, cdegree, cmaxdegree) ) def getNumVariables(self): cdef PetscInt cnvars CHKERR( PetscSpaceGetNumVariables(self.space, &cnvars)) return toInt(cnvars) def setNumVariables(self, n): cdef PetscInt cn = asInt(n) CHKERR( PetscSpaceSetNumVariables(self.space, cn) ) def getNumComponents(self): cdef PetscInt cncomps CHKERR( PetscSpaceGetNumComponents(self.space, &cncomps)) return toInt(cncomps) def setNumComponents(self, nc): cdef PetscInt cnc = asInt(nc) CHKERR( PetscSpaceSetNumComponents(self.space, cnc) ) #def evaluate(self, points): # cdef PetscInt cnpoints = 0, cdim=0, cnfuncs=0 # cdef PetscReal *cpoints = NULL # cdef PetscReal *B = NULL, *D = NULL, *H = NULL # points = iarray_r(points, &cnpoints, &cpoints) # # Get the dimension of the space # CHKERR( PetscSpaceGetDimension( self.space, &cnfuncs) ) # CHKERR( PetscSpace) # CHKERR( PetscSpaceEvaluate(self.space, cnpoints, &cpoints, &B, &D, &H) ) # return array_r(cnpoints*cdim, B), array_r(cnpoints*cnc, D), array_r(, H) def getType(self): cdef PetscSpaceType cval = NULL CHKERR( PetscSpaceGetType(self.space, &cval) ) return bytes2str(cval) def setType(self, space_type): cdef PetscSpaceType cval = NULL space_type = str2bytes(space_type, &cval) CHKERR( PetscSpaceSetType(self.space, cval) ) return self def getSumConcatenate(self): cdef PetscBool concatenate CHKERR( PetscSpaceSumGetConcatenate(self.space, &concatenate)) return toBool(concatenate) def setSumConcatenate(self, concatenate): cdef PetscBool cconcatenate = asBool(concatenate) CHKERR( PetscSpaceSumSetConcatenate(self.space, concatenate)) def getSumNumSubspaces(self): cdef PetscInt numSumSpaces CHKERR( PetscSpaceSumGetNumSubspaces(self.space, &numSumSpaces)) return toInt(numSumSpaces) def getSumSubspace(self, s): cdef Space subsp = Space() cdef PetscInt cs = asInt(s) CHKERR( PetscSpaceSumGetSubspace(self.space, s, &subsp.space) ) return subsp def setSumSubspace(self, s, Space subsp): cdef PetscInt cs = asInt(s) CHKERR( PetscSpaceSumSetSubspace(self.space, cs, subsp.space) ) def setSumNumSubspaces(self, numSumSpaces): cdef PetscInt cnumSumSpaces = asInt(numSumSpaces) CHKERR( PetscSpaceSumSetNumSubspaces(self.space, cnumSumSpaces) ) def getTensorNumSubspaces(self): cdef PetscInt cnumTensSpaces = 0 CHKERR( PetscSpaceTensorGetNumSubspaces(self.space, &cnumTensSpaces) ) return toInt(cnumTensSpaces) def setTensorSubspace(self, s, Space subsp): cdef PetscInt cs = asInt(s) CHKERR( PetscSpaceTensorSetSubspace(self.space, cs, subsp.space) ) def getTensorSubspace(self, s): cdef PetscInt cs = asInt(s) cdef Space subsp = Space() CHKERR( PetscSpaceTensorGetSubspace(self.space, cs, &subsp.space) ) return subsp def setTensorNumSubspaces(self, numTensSpaces): cdef PetscInt cnumTensSpaces = asInt(numTensSpaces) CHKERR( PetscSpaceTensorSetNumSubspaces(self.space, cnumTensSpaces) ) def getPolynomialTensor(self): cdef PetscBool ctensor CHKERR( PetscSpacePolynomialGetTensor(self.space, &ctensor) ) return toBool(ctensor) def setPolynomialTensor(self, tensor): cdef PetscBool ctensor = asBool(tensor) CHKERR( PetscSpacePolynomialSetTensor(self.space, ctensor) ) def setPointPoints(self, Quad quad): CHKERR( PetscSpacePointSetPoints(self.space, quad.quad)) def getPointPoints(self): cdef Quad quad = Quad() CHKERR( PetscSpacePointGetPoints(self.space, &quad.quad)) return quad def setPTrimmedFormDegree(self, formDegree): cdef PetscInt cformDegree = asInt(formDegree) CHKERR( PetscSpacePTrimmedSetFormDegree(self.space, cformDegree) ) def getPTrimmedFormDegree(self): cdef PetscInt cformDegree = 0 CHKERR( PetscSpacePTrimmedGetFormDegree(self.space, &cformDegree) ) return toInt(cformDegree) def viewFromOptions(self, name, Object obj=None): cdef const char *cname = NULL _ = str2bytes(name, &cname) cdef PetscObject cobj = NULL if obj is not None: cobj = obj.obj[0] CHKERR( PetscSpaceViewFromOptions(self.space, cobj, cname) ) # -------------------------------------------------------------------- class DualSpaceType(object): LAGRANGE = S_(PETSCDUALSPACELAGRANGE) SIMPLE = S_(PETSCDUALSPACESIMPLE) REFINED = S_(PETSCDUALSPACEREFINED) BDM = S_(PETSCDUALSPACEBDM) # -------------------------------------------------------------------- cdef class DualSpace(Object): Type = DualSpaceType def __cinit__(self): self.obj = &self.dualspace self.dualspace = NULL def setUp(self): CHKERR( PetscDualSpaceSetUp(self.dualspace) ) def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscDualSpace newdsp = NULL CHKERR( PetscDualSpaceCreate(ccomm, &newdsp) ) PetscCLEAR(self.obj); self.dualspace = newdsp return self def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( PetscDualSpaceView(self.dualspace, vwr) ) def destroy(self): CHKERR( PetscDualSpaceDestroy(&self.dualspace) ) return self def duplicate(self): cdef DualSpace spNew = DualSpace() CHKERR( PetscDualSpaceDuplicate(self.dualspace, &spNew.dualspace) ) def getDM(self): cdef DM dm = DM() CHKERR( PetscDualSpaceGetDM(self.dualspace, &dm.dm) ) return dm def setDM(self, DM dm): CHKERR( PetscDualSpaceSetDM(self.dualspace, dm.dm) ) def getDimension(self): cdef PetscInt cdim CHKERR( PetscDualSpaceGetDimension(self.dualspace, &cdim)) return toInt(cdim) def getNumComponents(self): cdef PetscInt cncomps CHKERR( PetscDualSpaceGetNumComponents(self.dualspace, &cncomps)) return toInt(cncomps) def setNumComponents(self, nc): cdef PetscInt cnc = asInt(nc) CHKERR( PetscDualSpaceSetNumComponents(self.dualspace, cnc) ) def getType(self): cdef PetscDualSpaceType cval = NULL CHKERR( PetscDualSpaceGetType(self.dualspace, &cval) ) return bytes2str(cval) def setType(self, dualspace_type): cdef PetscDualSpaceType cval = NULL space_type = str2bytes(dualspace_type, &cval) CHKERR( PetscDualSpaceSetType(self.dualspace, cval) ) return self def getOrder(self): cdef PetscInt corder CHKERR( PetscDualSpaceGetOrder(self.dualspace, &corder)) return toInt(corder) def setOrder(self, order): cdef PetscInt corder = asInt(order) CHKERR( PetscDualSpaceSetOrder(self.dualspace, corder) ) def getNumDof(self): cdef const PetscInt *cndof = NULL cdef PetscInt cdim = 0 CHKERR( PetscDualSpaceGetDimension(self.dualspace, &cdim) ) CHKERR( PetscDualSpaceGetNumDof(self.dualspace, &cndof) ) return array_i(cdim + 1, cndof) def getFunctional(self, i): cdef PetscInt ci = asInt(i) cdef Quad functional = Quad() CHKERR( PetscDualSpaceGetFunctional( self.dualspace, ci, &functional.quad) ) return functional def getInteriorDimension(self, intdim): cdef PetscInt cintdim = asInt(intdim) CHKERR( PetscDualSpaceGetInteriorDimension(self.dualspace, &cintdim) ) return toInt(cintdim) def getLagrangeContinuity(self): cdef PetscBool ccontinuous = PETSC_FALSE CHKERR( PetscDualSpaceLagrangeGetContinuity(self.dualspace, &ccontinuous)) return toBool(ccontinuous) def setLagrangeContinuity(self, continuous): cdef PetscBool ccontinuous = asBool(continuous) CHKERR( PetscDualSpaceLagrangeSetContinuity(self.dualspace, ccontinuous)) def getLagrangeTensor(self): cdef PetscBool ctensor = PETSC_FALSE CHKERR( PetscDualSpaceLagrangeGetTensor(self.dualspace, &ctensor)) return toBool(ctensor) def setLagrangeTensor(self, tensor): cdef PetscBool ctensor = asBool(tensor) CHKERR( PetscDualSpaceLagrangeSetTensor(self.dualspace, ctensor)) def getLagrangeTrimmed(self): cdef PetscBool ctrimmed = PETSC_FALSE CHKERR( PetscDualSpaceLagrangeGetTrimmed(self.dualspace, &ctrimmed)) return toBool(ctrimmed) def setLagrangeTrimmed(self, trimmed): cdef PetscBool ctrimmed = asBool(trimmed) CHKERR( PetscDualSpaceLagrangeSetTrimmed(self.dualspace, ctrimmed)) def viewFromOptions(self, name, Object obj=None): cdef const char *cname = NULL _ = str2bytes(name, &cname) cdef PetscObject cobj = NULL if obj is not None: cobj = obj.obj[0] CHKERR( PetscDualSpaceViewFromOptions(self.dualspace, cobj, cname) ) def setSimpleDimension(self, dim): cdef PetscInt cdim = asInt(dim) CHKERR( PetscDualSpaceSimpleSetDimension(self.dualspace, cdim) ) def setSimpleFunctional(self, func, Quad functional): cdef PetscInt cfunc = asInt(func) CHKERR( PetscDualSpaceSimpleSetFunctional(self.dualspace, cfunc, functional.quad) ) del SpaceType del DualSpaceTypepetsc4py-3.19.6/src/petsc4py/PETSc/Sys.pyx000066400000000000000000000150631454104047300201740ustar00rootroot00000000000000# -------------------------------------------------------------------- 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( PetscGetVersion(cversion, sizeof(cversion)) ) CHKERR( PetscGetVersionNumber(&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(PETSC_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(PetscInitializeCalled) @classmethod def isFinalized(cls): return toBool(PetscFinalizeCalled) # --- xxx --- @classmethod def getDefaultComm(cls): cdef Comm comm = Comm() comm.comm = PETSC_COMM_DEFAULT return comm @classmethod def setDefaultComm(cls, comm): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_WORLD) if ccomm == MPI_COMM_NULL: raise ValueError("null communicator") global PETSC_COMM_DEFAULT PETSC_COMM_DEFAULT = ccomm # --- xxx --- @classmethod def Print(cls, *args, **kargs): cdef object comm = kargs.get('comm', None) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef object sep = kargs.get('sep', ' ') cdef object end = kargs.get('end', '\n') if comm_rank(ccomm) == 0: if not args: args = ('',) format = ['%s', sep] * len(args) format[-1] = end message = ''.join(format) % args else: message = '' cdef const char *m = NULL message = str2bytes(message, &m) CHKERR( PetscPrintf(ccomm, '%s', m) ) @classmethod def syncPrint(cls, *args, **kargs): cdef object comm = kargs.get('comm', None) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef object sep = kargs.get('sep', ' ') cdef object end = kargs.get('end', '\n') cdef object flush = kargs.get('flush', False) if not args: args = ('',) format = ['%s', sep] * len(args) format[-1] = end message = ''.join(format) % args cdef const char *m = NULL message = str2bytes(message, &m) CHKERR( PetscSynchronizedPrintf(ccomm, '%s', m) ) if flush: CHKERR( PetscSynchronizedFlush(ccomm, PETSC_STDOUT) ) @classmethod def syncFlush(cls, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) CHKERR( PetscSynchronizedFlush(ccomm, PETSC_STDOUT) ) # --- xxx --- @classmethod def splitOwnership(cls, size, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Sys_Sizes(size, bsize, &bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if n > 0: n = n // bs if N > 0: N = N // bs CHKERR( PetscSplitOwnership(ccomm, &n, &N) ) n = n * bs N = N * bs return (toInt(n), toInt(N)) @classmethod def sleep(cls, seconds=1): cdef int s = seconds CHKERR( PetscSleep(s) ) # --- xxx --- @classmethod def pushErrorHandler(cls, errhandler): cdef PetscErrorHandlerFunction handler = NULL if errhandler == "python": handler = \ PetscPythonErrorHandler elif errhandler == "debugger": handler = PetscAttachDebuggerErrorHandler elif errhandler == "emacs": handler = PetscEmacsClientErrorHandler elif errhandler == "traceback": handler = PetscTraceBackErrorHandler elif errhandler == "ignore": handler = PetscIgnoreErrorHandler elif errhandler == "mpiabort": handler = PetscMPIAbortErrorHandler elif errhandler == "abort": handler = PetscAbortErrorHandler else: raise ValueError( "unknown error handler: %s" % errhandler) CHKERR( PetscPushErrorHandler(handler, NULL) ) @classmethod def popErrorHandler(cls): CHKERR( PetscPopErrorHandler() ) @classmethod def popSignalHandler(cls): CHKERR( PetscPopSignalHandler() ) @classmethod def infoAllow(cls, flag, filename=None, mode="w"): cdef PetscBool tval = PETSC_FALSE cdef const char *cfilename = NULL cdef const char *cmode = NULL if flag: tval = PETSC_TRUE CHKERR( PetscInfoAllow(tval) ) if filename is not None: filename = str2bytes(filename, &cfilename) mode = str2bytes(mode, &cmode) CHKERR( PetscInfoSetFile(cfilename, cmode) ) @classmethod def registerCitation(cls, citation): if not citation: raise ValueError("empty citation") cdef const char *cit = NULL citation = str2bytes(citation, &cit) cdef PetscBool flag = get_citation(citation) CHKERR( PetscCitationsRegister(cit, &flag) ) set_citation(citation, toBool(flag)) @classmethod def hasExternalPackage(cls, package): cdef const char *cpackage = NULL package = str2bytes(package, &cpackage) cdef PetscBool has = PETSC_FALSE CHKERR( PetscHasExternalPackage(cpackage, &has) ) return toBool(has) cdef dict citations_registry = { } cdef PetscBool get_citation(object citation): cdef bint is_set = citations_registry.get(citation) return PETSC_TRUE if is_set else PETSC_FALSE cdef set_citation(object citation, bint is_set): citations_registry[citation] = is_set # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/TAO.pyx000066400000000000000000000673301454104047300200450ustar00rootroot00000000000000# -------------------------------------------------------------------- class TAOType: """ TAO Solver Types """ LMVM = S_(TAOLMVM) NLS = S_(TAONLS) NTR = S_(TAONTR) NTL = S_(TAONTL) CG = S_(TAOCG) TRON = S_(TAOTRON) OWLQN = S_(TAOOWLQN) BMRM = S_(TAOBMRM) BLMVM = S_(TAOBLMVM) BQNLS = S_(TAOBQNLS) BNCG = S_(TAOBNCG) BNLS = S_(TAOBNLS) BNTR = S_(TAOBNTR) BNTL = S_(TAOBNTL) BQNKLS = S_(TAOBQNKLS) BQNKTR = S_(TAOBQNKTR) BQNKTL = S_(TAOBQNKTL) BQPIP = S_(TAOBQPIP) GPCG = S_(TAOGPCG) NM = S_(TAONM) POUNDERS = S_(TAOPOUNDERS) BRGN = S_(TAOBRGN) LCL = S_(TAOLCL) SSILS = S_(TAOSSILS) SSFLS = S_(TAOSSFLS) ASILS = S_(TAOASILS) ASFLS = S_(TAOASFLS) IPM = S_(TAOIPM) PDIPM = S_(TAOPDIPM) SHELL = S_(TAOSHELL) ADMM = S_(TAOADMM) ALMM = S_(TAOALMM) PYTHON = S_(TAOPYTHON) class TAOConvergedReason: """ TAO Solver Termination Reasons """ # iterating CONTINUE_ITERATING = TAO_CONTINUE_ITERATING # iterating CONVERGED_ITERATING = TAO_CONTINUE_ITERATING # iterating ITERATING = TAO_CONTINUE_ITERATING # iterating # converged CONVERGED_GATOL = TAO_CONVERGED_GATOL # ||g(X)|| < gatol CONVERGED_GRTOL = TAO_CONVERGED_GRTOL # ||g(X)||/f(X) < grtol CONVERGED_GTTOL = TAO_CONVERGED_GTTOL # ||g(X)||/||g(X0)|| < gttol CONVERGED_STEPTOL = TAO_CONVERGED_STEPTOL # small step size CONVERGED_MINF = TAO_CONVERGED_MINF # f(X) < F_min CONVERGED_USER = TAO_CONVERGED_USER # user defined # diverged DIVERGED_MAXITS = TAO_DIVERGED_MAXITS # DIVERGED_NAN = TAO_DIVERGED_NAN # DIVERGED_MAXFCN = TAO_DIVERGED_MAXFCN # DIVERGED_LS_FAILURE = TAO_DIVERGED_LS_FAILURE # DIVERGED_TR_REDUCTION = TAO_DIVERGED_TR_REDUCTION # DIVERGED_USER = TAO_DIVERGED_USER # user defined # -------------------------------------------------------------------- cdef class TAO(Object): """ TAO Solver """ Type = TAOType Reason = TAOConvergedReason def __cinit__(self): self.obj = &self.tao self.tao = NULL def view(self, Viewer viewer=None): """ """ cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( TaoView(self.tao, vwr) ) def destroy(self): """ """ CHKERR( TaoDestroy(&self.tao) ) return self def create(self, comm=None): """ """ cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscTAO newtao = NULL CHKERR( TaoCreate(ccomm, &newtao) ) PetscCLEAR(self.obj); self.tao = newtao return self def setType(self, tao_type): """ """ cdef PetscTAOType ctype = NULL tao_type = str2bytes(tao_type, &ctype) CHKERR( TaoSetType(self.tao, ctype) ) def getType(self): """ """ cdef PetscTAOType ctype = NULL CHKERR( TaoGetType(self.tao, &ctype) ) return bytes2str(ctype) def setOptionsPrefix(self, prefix): """ """ cdef const char *cprefix = NULL prefix = str2bytes(prefix, &cprefix) CHKERR( TaoSetOptionsPrefix(self.tao, cprefix) ) def appendOptionsPrefix(self, prefix): """ """ cdef const char *cprefix = NULL prefix = str2bytes(prefix, &cprefix) CHKERR( TaoAppendOptionsPrefix(self.tao, cprefix) ) def getOptionsPrefix(self): """ """ cdef const char *prefix = NULL CHKERR( TaoGetOptionsPrefix(self.tao, &prefix) ) return bytes2str(prefix) def setFromOptions(self): """ """ CHKERR( TaoSetFromOptions(self.tao) ) def setUp(self): """ """ CHKERR( TaoSetUp(self.tao) ) # def setInitialTrustRegionRadius(self, radius): cdef PetscReal cradius = asReal(radius) CHKERR( TaoSetInitialTrustRegionRadius(self.tao, cradius) ) # -------------- def setAppCtx(self, appctx): self.set_attr("__appctx__", appctx) def getAppCtx(self): return self.get_attr("__appctx__") def setSolution(self, Vec x): """ """ CHKERR( TaoSetSolution(self.tao, x.vec) ) def setObjective(self, objective, args=None, kargs=None): """ """ if args is None: args = () if kargs is None: kargs = {} context = (objective, args, kargs) self.set_attr("__objective__", context) CHKERR( TaoSetObjective(self.tao, TAO_Objective, context) ) def setResidual(self, residual, Vec R=None, args=None, kargs=None): """ """ cdef PetscVec Rvec = NULL if R is not None: Rvec = R.vec if args is None: args = () if kargs is None: kargs = {} context = (residual, args, kargs) self.set_attr("__residual__", context) CHKERR( TaoSetResidualRoutine(self.tao, Rvec, TAO_Residual, context) ) def setJacobianResidual(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): """ """ cdef PetscMat Jmat = NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat = Jmat if P is not None: Pmat = P.mat if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr("__jacobian_residual__", context) CHKERR( TaoSetJacobianResidualRoutine(self.tao, Jmat, Pmat, TAO_JacobianResidual, context) ) def setGradient(self, gradient, Vec g or None, args=None, kargs=None): """ """ cdef PetscVec gvec = NULL if g is not None: gvec = g.vec if args is None: args = () if kargs is None: kargs = {} context = (gradient, args, kargs) self.set_attr("__gradient__", context) CHKERR( TaoSetGradient(self.tao, gvec, TAO_Gradient, context) ) def getGradient(self): """ """ cdef Vec vec = Vec() CHKERR( TaoGetGradient(self.tao, &vec.vec, NULL, NULL) ) PetscINCREF(vec.obj) cdef object gradient = self.get_attr("__gradient__") return (vec, gradient) def setObjectiveGradient(self, objgrad, Vec g or None, args=None, kargs=None): """ """ cdef PetscVec gvec = NULL if g is not None: gvec = g.vec if args is None: args = () if kargs is None: kargs = {} context = (objgrad, args, kargs) self.set_attr("__objgrad__", context) CHKERR( TaoSetObjectiveAndGradient(self.tao, gvec, TAO_ObjGrad, context) ) def getObjectiveAndGradient(self): """ """ cdef Vec vec = Vec() CHKERR( TaoGetObjectiveAndGradient(self.tao, &vec.vec, NULL, NULL) ) PetscINCREF(vec.obj) cdef object objgrad = self.get_attr("__objgrad__") return (vec, objgrad) def setVariableBounds(self, varbounds, args=None, kargs=None): """ """ cdef Vec xl = None, xu = None if (isinstance(varbounds, list) or isinstance(varbounds, tuple)): ol, ou = varbounds xl = ol; xu = ou CHKERR( TaoSetVariableBounds(self.tao, xl.vec, xu.vec) ) return if isinstance(varbounds, Vec): ol = varbounds; ou = args xl = ol; xu = ou CHKERR( TaoSetVariableBounds(self.tao, xl.vec, xu.vec) ) return if args is None: args = () if kargs is None: kargs = {} context = (varbounds, args, kargs) self.set_attr("__varbounds__", context) CHKERR( TaoSetVariableBoundsRoutine(self.tao, TAO_VarBounds, context) ) def setConstraints(self, constraints, Vec C=None, args=None, kargs=None): """ """ cdef PetscVec Cvec = NULL if C is not None: Cvec = C.vec if args is None: args = () if kargs is None: kargs = {} context = (constraints, args, kargs) self.set_attr("__constraints__", context) CHKERR( TaoSetConstraintsRoutine(self.tao, Cvec, TAO_Constraints, context) ) def setHessian(self, hessian, Mat H=None, Mat P=None, args=None, kargs=None): cdef PetscMat Hmat = NULL if H is not None: Hmat = H.mat cdef PetscMat Pmat = Hmat if P is not None: Pmat = P.mat if args is None: args = () if kargs is None: kargs = {} context = (hessian, args, kargs) self.set_attr("__hessian__", context) CHKERR( TaoSetHessian(self.tao, Hmat, Pmat, TAO_Hessian, context) ) def getHessian(self): cdef Mat J = Mat() cdef Mat P = Mat() CHKERR( TaoGetHessian(self.tao, &J.mat, &P.mat, NULL, NULL) ) PetscINCREF(J.obj) PetscINCREF(P.obj) cdef object hessian = self.get_attr("__hessian__") return (J, P, hessian) def setJacobian(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): """ """ cdef PetscMat Jmat = NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat = Jmat if P is not None: Pmat = P.mat if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr("__jacobian__", context) CHKERR( TaoSetJacobianRoutine(self.tao, Jmat, Pmat, TAO_Jacobian, context) ) # def setStateDesignIS(self, IS state=None, IS design=None): """ """ cdef PetscIS s_is = NULL, d_is = NULL if state is not None: s_is = state.iset if design is not None: d_is = design.iset CHKERR( TaoSetStateDesignIS(self.tao, s_is, d_is) ) def setJacobianState(self, jacobian_state, Mat J=None, Mat P=None, Mat I=None, args=None, kargs=None): """ """ cdef PetscMat Jmat = NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat = Jmat if P is not None: Pmat = P.mat cdef PetscMat Imat = NULL if I is not None: Imat = I.mat if args is None: args = () if kargs is None: kargs = {} context = (jacobian_state, args, kargs) self.set_attr("__jacobian_state__", context) CHKERR( TaoSetJacobianStateRoutine(self.tao, Jmat, Pmat, Imat, TAO_JacobianState, context) ) def setJacobianDesign(self, jacobian_design, Mat J=None, args=None, kargs=None): """ """ cdef PetscMat Jmat = NULL if J is not None: Jmat = J.mat if args is None: args = () if kargs is None: kargs = {} context = (jacobian_design, args, kargs) self.set_attr("__jacobian_design__", context) CHKERR( TaoSetJacobianDesignRoutine(self.tao, Jmat, TAO_JacobianDesign, context) ) def setEqualityConstraints(self, equality_constraints, Vec c, args=None, kargs=None): """ """ if args is None: args = () if kargs is None: kargs = {} context = (equality_constraints, args, kargs) self.set_attr("__equality_constraints__", context) CHKERR( TaoSetEqualityConstraintsRoutine(self.tao, c.vec, TAO_EqualityConstraints, context) ) def setJacobianEquality(self, jacobian_equality, Mat J=None, Mat P=None, args=None, kargs=None): """ """ cdef PetscMat Jmat = NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat = Jmat if P is not None: Pmat = P.mat if args is None: args = () if kargs is None: kargs = {} context = (jacobian_equality, args, kargs) self.set_attr("__jacobian_equality__", context) CHKERR( TaoSetJacobianEqualityRoutine(self.tao, Jmat, Pmat, TAO_JacobianEquality, context) ) def setUpdate(self, update, args=None, kargs=None): """ """ if update is not None: if args is None: args = () if kargs is None: kargs = {} context = (update, args, kargs) self.set_attr('__update__', context) CHKERR( TaoSetUpdate(self.tao, TAO_Update, context) ) else: self.set_attr('__update__', None) CHKERR( TaoSetUpdate(self.tao, NULL, NULL) ) def getUpdate(self): return self.get_attr('__update__') # -------------- def computeObjective(self, Vec x): """ """ cdef PetscReal f = 0 CHKERR( TaoComputeObjective(self.tao, x.vec, &f) ) return toReal(f) def computeResidual(self, Vec x, Vec f): """ """ CHKERR( TaoComputeResidual(self.tao, x.vec, f.vec) ) def computeGradient(self, Vec x, Vec g): """ """ CHKERR( TaoComputeGradient(self.tao, x.vec, g.vec) ) def computeObjectiveGradient(self, Vec x, Vec g): """ """ cdef PetscReal f = 0 CHKERR( TaoComputeObjectiveAndGradient(self.tao, x.vec, &f, g.vec) ) return toReal(f) def computeDualVariables(self, Vec xl, Vec xu): """ """ CHKERR( TaoComputeDualVariables(self.tao, xl.vec, xu.vec) ) def computeVariableBounds(self, Vec xl, Vec xu): """ """ CHKERR( TaoComputeVariableBounds(self.tao) ) cdef PetscVec Lvec = NULL, Uvec = NULL CHKERR( TaoGetVariableBounds(self.tao, &Lvec, &Uvec) ) if xl.vec != NULL: if Lvec != NULL: CHKERR( VecCopy(Lvec, xl.vec) ) else: CHKERR( VecSet(xl.vec, PETSC_NINFINITY) ) if xu.vec != NULL: if Uvec != NULL: CHKERR( VecCopy(Uvec, xu.vec) ) else: CHKERR( VecSet(xu.vec, PETSC_INFINITY) ) def computeConstraints(self, Vec x, Vec c): """ """ CHKERR( TaoComputeConstraints(self.tao, x.vec, c.vec) ) def computeHessian(self, Vec x, Mat H, Mat P=None): """ """ cdef PetscMat hmat = H.mat, pmat = H.mat if P is not None: pmat = P.mat CHKERR( TaoComputeHessian(self.tao, x.vec, hmat, pmat) ) def computeJacobian(self, Vec x, Mat J, Mat P=None): """ """ cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( TaoComputeJacobian(self.tao, x.vec, jmat, pmat) ) # -------------- # def setTolerances(self, gatol=None, grtol=None, gttol=None): """ """ cdef PetscReal _gatol=PETSC_DEFAULT, _grtol=PETSC_DEFAULT, _gttol=PETSC_DEFAULT if gatol is not None: _gatol = asReal(gatol) if grtol is not None: _grtol = asReal(grtol) if gttol is not None: _gttol = asReal(gttol) CHKERR( TaoSetTolerances(self.tao, _gatol, _grtol, _gttol) ) def getTolerances(self): """ """ cdef PetscReal _gatol=PETSC_DEFAULT, _grtol=PETSC_DEFAULT, _gttol=PETSC_DEFAULT CHKERR( TaoGetTolerances(self.tao, &_gatol, &_grtol, &_gttol) ) return (toReal(_gatol), toReal(_grtol), toReal(_gttol)) def setMaximumIterations(self, mit): """ """ cdef PetscInt _mit = asInt(mit) CHKERR( TaoSetMaximumIterations(self.tao, _mit) ) def getMaximumIterations(self): """ """ cdef PetscInt _mit = PETSC_DEFAULT CHKERR( TaoGetMaximumIterations(self.tao, &_mit) ) return toInt(_mit) def setMaximumFunctionEvaluations(self, mit): """ """ cdef PetscInt _mit = asInt(mit) CHKERR( TaoSetMaximumFunctionEvaluations(self.tao, _mit) ) def getMaximumFunctionEvaluations(self): """ """ cdef PetscInt _mit = PETSC_DEFAULT CHKERR( TaoGetMaximumFunctionEvaluations(self.tao, &_mit) ) return toInt(_mit) def setConstraintTolerances(self, catol=None, crtol=None): """ """ cdef PetscReal _catol=PETSC_DEFAULT, _crtol=PETSC_DEFAULT if catol is not None: _catol = asReal(catol) if crtol is not None: _crtol = asReal(crtol) CHKERR( TaoSetConstraintTolerances(self.tao, _catol, _crtol) ) def getConstraintTolerances(self): """ """ cdef PetscReal _catol=PETSC_DEFAULT, _crtol=PETSC_DEFAULT CHKERR( TaoGetConstraintTolerances(self.tao, &_catol, &_crtol) ) return (toReal(_catol), toReal(_crtol)) def setConvergenceTest(self, converged, args=None, kargs=None): """ """ if converged is None: CHKERR( TaoSetConvergenceTest(self.tao, TaoDefaultConvergenceTest, NULL) ) self.set_attr('__converged__', None) else: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__converged__', (converged, args, kargs)) CHKERR( TaoSetConvergenceTest(self.tao, TAO_Converged, NULL) ) def getConvergenceTest(self): """ """ return self.get_attr('__converged__') def setConvergedReason(self, reason): """ """ cdef PetscTAOConvergedReason creason = reason CHKERR( TaoSetConvergedReason(self.tao, creason) ) def getConvergedReason(self): """ """ cdef PetscTAOConvergedReason creason = TAO_CONTINUE_ITERATING CHKERR( TaoGetConvergedReason(self.tao, &creason) ) return creason def setMonitor(self, monitor, args=None, kargs=None): """ """ if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if args is None: args = () if kargs is None: kargs = {} if monitorlist is None: CHKERR( TaoSetMonitor(self.tao, TAO_Monitor, NULL, NULL) ) self.set_attr('__monitor__', [(monitor, args, kargs)]) else: monitorlist.append((monitor, args, kargs)) def getMonitor(self): """ """ return self.get_attr('__monitor__') def cancelMonitor(self): """ """ CHKERR( TaoCancelMonitors(self.tao) ) self.set_attr('__monitor__', None) # Tao overwrites this statistics. Copy user defined only if present def monitor(self, its=None, f=None, res=None, cnorm=None, step=None): cdef PetscInt cits = 0 cdef PetscReal cf = 0.0 cdef PetscReal cres = 0.0 cdef PetscReal ccnorm = 0.0 cdef PetscReal cstep = 0.0 CHKERR( TaoGetSolutionStatus(self.tao, &cits, &cf, &cres, &ccnorm, &cstep, NULL) ) if its is not None: cits = asInt(its) if f is not None: cf = asReal(f) if res is not None: cres = asReal(res) if cnorm is not None: ccnorm = asReal(cnorm) if step is not None: cstep = asReal(step) CHKERR( TaoMonitor(self.tao, cits, cf, cres, ccnorm, cstep) ) # def solve(self, Vec x=None): """ """ if x is not None: CHKERR( TaoSetSolution(self.tao, x.vec) ) CHKERR( TaoSolve(self.tao) ) def getSolution(self): """ """ cdef Vec vec = Vec() CHKERR( TaoGetSolution(self.tao, &vec.vec) ) PetscINCREF(vec.obj) return vec def setGradientNorm(self, Mat mat): """ """ CHKERR( TaoSetGradientNorm(self.tao, mat.mat) ) def getGradientNorm(self): """ """ cdef Mat mat = Mat() CHKERR( TaoGetGradientNorm(self.tao, &mat.mat) ) PetscINCREF(mat.obj) return mat def setLMVMH0(self, Mat mat): """ """ CHKERR( TaoLMVMSetH0(self.tao, mat.mat) ) def getLMVMH0(self): """ """ cdef Mat mat = Mat() CHKERR( TaoLMVMGetH0(self.tao, &mat.mat) ) PetscINCREF(mat.obj) return mat def getLMVMH0KSP(self): """ """ cdef KSP ksp = KSP() CHKERR( TaoLMVMGetH0KSP(self.tao, &ksp.ksp) ) PetscINCREF(ksp.obj) return ksp def getVariableBounds(self): """ """ cdef Vec xl = Vec(), xu = Vec() CHKERR( TaoGetVariableBounds(self.tao, &xl.vec, &xu.vec) ) PetscINCREF(xl.obj); PetscINCREF(xu.obj) return (xl, xu) def setIterationNumber(self, its): """ """ cdef PetscInt ival = asInt(its) CHKERR( TaoSetIterationNumber(self.tao, ival) ) def getIterationNumber(self): """ """ cdef PetscInt its=0 CHKERR( TaoGetIterationNumber(self.tao, &its) ) return toInt(its) def getObjectiveValue(self): """ """ cdef PetscReal fval=0 CHKERR( TaoGetSolutionStatus(self.tao, NULL, &fval, NULL, NULL, NULL, NULL) ) return toReal(fval) getFunctionValue = getObjectiveValue def getConvergedReason(self): """ """ cdef PetscTAOConvergedReason reason = TAO_CONTINUE_ITERATING CHKERR( TaoGetConvergedReason(self.tao, &reason) ) return reason def getSolutionNorm(self): """ """ cdef PetscReal gnorm=0 cdef PetscReal cnorm=0 cdef PetscReal fval=0 CHKERR( TaoGetSolutionStatus(self.tao, NULL, &fval, &gnorm, &cnorm, NULL, NULL) ) return (toReal(fval), toReal(gnorm), toReal(cnorm)) def getSolutionStatus(self): """ """ cdef PetscInt its=0 cdef PetscReal fval=0, gnorm=0, cnorm=0, xdiff=0 cdef PetscTAOConvergedReason reason = TAO_CONTINUE_ITERATING CHKERR( TaoGetSolutionStatus(self.tao, &its, &fval, &gnorm, &cnorm, &xdiff, &reason) ) return (toInt(its), toReal(fval), toReal(gnorm), toReal(cnorm), toReal(xdiff), reason) def getKSP(self): """ """ cdef KSP ksp = KSP() CHKERR( TaoGetKSP(self.tao, &ksp.ksp) ) PetscINCREF(ksp.obj) return ksp # BRGN routines def getBRGNSubsolver(self): """ """ cdef TAO subsolver = TAO() CHKERR( TaoBRGNGetSubsolver(self.tao, &subsolver.tao) ) PetscINCREF(subsolver.obj) return subsolver def setBRGNRegularizerObjectiveGradient(self, objgrad, args=None, kargs=None): """ """ if args is None: args = () if kargs is None: kargs = {} context = (objgrad, args, kargs) self.set_attr("__brgnregobjgrad__", context) CHKERR( TaoBRGNSetRegularizerObjectiveAndGradientRoutine(self.tao, TAO_BRGNRegObjGrad, context) ) def setBRGNRegularizerHessian(self, hessian, Mat H=None, args=None, kargs=None): cdef PetscMat Hmat = NULL if H is not None: Hmat = H.mat if args is None: args = () if kargs is None: kargs = {} context = (hessian, args, kargs) self.set_attr("__brgnreghessian__", context) CHKERR( TaoBRGNSetRegularizerHessianRoutine(self.tao, Hmat, TAO_BRGNRegHessian, context) ) def setBRGNRegularizerWeight(self, weight): """ """ cdef PetscReal cweight = asReal(weight) CHKERR( TaoBRGNSetRegularizerWeight(self.tao, cweight) ) def setBRGNSmoothL1Epsilon(self, epsilon): """ """ cdef PetscReal ceps = asReal(epsilon) CHKERR( TaoBRGNSetL1SmoothEpsilon(self.tao, ceps) ) def setBRGNDictionaryMatrix(self, Mat D): """ """ CHKERR( TaoBRGNSetDictionaryMatrix(self.tao, D.mat) ) def getBRGNDampingVector(self): """ """ cdef Vec damp = Vec() CHKERR( TaoBRGNGetDampingVector(self.tao, &damp.vec) ) PetscINCREF(damp.obj) return damp def createPython(self, context=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscTAO tao = NULL CHKERR( TaoCreate(ccomm, &tao) ) PetscCLEAR(self.obj); self.tao = tao CHKERR( TaoSetType(self.tao, TAOPYTHON) ) CHKERR( TaoPythonSetContext(self.tao, context) ) return self def setPythonContext(self, context): CHKERR( TaoPythonSetContext(self.tao, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( TaoPythonGetContext(self.tao, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( TaoPythonSetType(self.tao, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( TaoPythonGetType(self.tao, &cval) ) return bytes2str(cval) # --- backward compatibility --- setInitial = setSolution # --- application context --- property appctx: def __get__(self): return self.getAppCtx() def __set__(self, value): self.setAppCtx(value) # --- linear solver --- property ksp: def __get__(self): return self.getKSP() # --- tolerances --- property ftol: def __get__(self): return self.getFunctionTolerances() def __set__(self, value): if isinstance(value, (tuple, list)): self.setFunctionTolerances(*value) elif isinstance(value, dict): self.setFunctionTolerances(**value) else: raise TypeError("expecting tuple/list or dict") property gtol: def __get__(self): return self.getGradientTolerances() def __set__(self, value): if isinstance(value, (tuple, list)): self.getGradientTolerances(*value) elif isinstance(value, dict): self.getGradientTolerances(**value) else: raise TypeError("expecting tuple/list or dict") property ctol: def __get__(self): return self.getConstraintTolerances() def __set__(self, value): if isinstance(value, (tuple, list)): self.getConstraintTolerances(*value) elif isinstance(value, dict): self.getConstraintTolerances(**value) else: raise TypeError("expecting tuple/list or dict") # --- iteration --- property its: def __get__(self): return self.getIterationNumber() property gnorm: def __get__(self): return self.getSolutionNorm()[1] property cnorm: def __get__(self): return self.getSolutionNorm()[2] property solution: def __get__(self): return self.getSolution() property objective: def __get__(self): return self.getObjectiveValue() property function: def __get__(self): return self.getFunctionValue() property gradient: def __get__(self): return self.getGradient()[0] # --- convergence --- property reason: def __get__(self): return self.getConvergedReason() property iterating: def __get__(self): return self.reason == 0 property converged: def __get__(self): return self.reason > 0 property diverged: def __get__(self): return self.reason < 0 # -------------------------------------------------------------------- del TAOType del TAOConvergedReason # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/TS.pyx000066400000000000000000001061171454104047300177450ustar00rootroot00000000000000# ----------------------------------------------------------------------------- class TSType(object): # native EULER = S_(TSEULER) BEULER = S_(TSBEULER) BASICSYMPLECTIC = S_(TSBASICSYMPLECTIC) PSEUDO = S_(TSPSEUDO) CN = S_(TSCN) SUNDIALS = S_(TSSUNDIALS) RK = S_(TSRK) PYTHON = S_(TSPYTHON) THETA = S_(TSTHETA) ALPHA = S_(TSALPHA) ALPHA2 = S_(TSALPHA2) GLLE = S_(TSGLLE) GLEE = S_(TSGLEE) SSP = S_(TSSSP) ARKIMEX = S_(TSARKIMEX) ROSW = S_(TSROSW) EIMEX = S_(TSEIMEX) MIMEX = S_(TSMIMEX) BDF = S_(TSBDF) RADAU5 = S_(TSRADAU5) MPRK = S_(TSMPRK) DISCGRAD = S_(TSDISCGRAD) # aliases FE = EULER BE = BEULER TH = THETA CRANK_NICOLSON = CN RUNGE_KUTTA = RK class TSRKType(object): RK1FE = S_(TSRK1FE) RK2A = S_(TSRK2A) RK2B = S_(TSRK2B) RK4 = S_(TSRK4) RK3BS = S_(TSRK3BS) RK3 = S_(TSRK3) RK5F = S_(TSRK5F) RK5DP = S_(TSRK5DP) RK5BS = S_(TSRK5BS) RK6VR = S_(TSRK6VR) RK7VR = S_(TSRK7VR) RK8VR = S_(TSRK8VR) class TSARKIMEXType(object): ARKIMEX1BEE = S_(TSARKIMEX1BEE) ARKIMEXA2 = S_(TSARKIMEXA2) ARKIMEXL2 = S_(TSARKIMEXL2) ARKIMEXARS122 = S_(TSARKIMEXARS122) ARKIMEX2C = S_(TSARKIMEX2C) ARKIMEX2D = S_(TSARKIMEX2D) ARKIMEX2E = S_(TSARKIMEX2E) ARKIMEXPRSSP2 = S_(TSARKIMEXPRSSP2) ARKIMEX3 = S_(TSARKIMEX3) ARKIMEXBPR3 = S_(TSARKIMEXBPR3) ARKIMEXARS443 = S_(TSARKIMEXARS443) ARKIMEX4 = S_(TSARKIMEX4) ARKIMEX5 = S_(TSARKIMEX5) class TSProblemType(object): LINEAR = TS_LINEAR NONLINEAR = TS_NONLINEAR class TSEquationType(object): UNSPECIFIED = TS_EQ_UNSPECIFIED EXPLICIT = TS_EQ_EXPLICIT ODE_EXPLICIT = TS_EQ_ODE_EXPLICIT DAE_SEMI_EXPLICIT_INDEX1 = TS_EQ_DAE_SEMI_EXPLICIT_INDEX1 DAE_SEMI_EXPLICIT_INDEX2 = TS_EQ_DAE_SEMI_EXPLICIT_INDEX2 DAE_SEMI_EXPLICIT_INDEX3 = TS_EQ_DAE_SEMI_EXPLICIT_INDEX3 DAE_SEMI_EXPLICIT_INDEXHI = TS_EQ_DAE_SEMI_EXPLICIT_INDEXHI IMPLICIT = TS_EQ_IMPLICIT ODE_IMPLICIT = TS_EQ_ODE_IMPLICIT DAE_IMPLICIT_INDEX1 = TS_EQ_DAE_IMPLICIT_INDEX1 DAE_IMPLICIT_INDEX2 = TS_EQ_DAE_IMPLICIT_INDEX2 DAE_IMPLICIT_INDEX3 = TS_EQ_DAE_IMPLICIT_INDEX3 DAE_IMPLICIT_INDEXHI = TS_EQ_DAE_IMPLICIT_INDEXHI class TSExactFinalTime(object): UNSPECIFIED = TS_EXACTFINALTIME_UNSPECIFIED STEPOVER = TS_EXACTFINALTIME_STEPOVER INTERPOLATE = TS_EXACTFINALTIME_INTERPOLATE MATCHSTEP = TS_EXACTFINALTIME_MATCHSTEP class TSConvergedReason(object): # iterating CONVERGED_ITERATING = TS_CONVERGED_ITERATING ITERATING = TS_CONVERGED_ITERATING # converged CONVERGED_TIME = TS_CONVERGED_TIME CONVERGED_ITS = TS_CONVERGED_ITS CONVERGED_USER = TS_CONVERGED_USER CONVERGED_EVENT = TS_CONVERGED_EVENT # diverged DIVERGED_NONLINEAR_SOLVE = TS_DIVERGED_NONLINEAR_SOLVE DIVERGED_STEP_REJECTED = TS_DIVERGED_STEP_REJECTED # ----------------------------------------------------------------------------- cdef class TS(Object): Type = TSType RKType = TSRKType ARKIMEXType = TSARKIMEXType ProblemType = TSProblemType EquationType = TSEquationType ExactFinalTime = TSExactFinalTime ExactFinalTimeOption = TSExactFinalTime ConvergedReason = TSConvergedReason # --- xxx --- def __cinit__(self): self.obj = &self.ts self.ts = NULL # --- xxx --- def view(self, Viewer viewer=None): cdef PetscViewer cviewer = NULL if viewer is not None: cviewer = viewer.vwr CHKERR( TSView(self.ts, cviewer) ) def load(self, Viewer viewer): CHKERR( TSLoad(self.ts, viewer.vwr) ) def destroy(self): CHKERR( TSDestroy(&self.ts) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscTS newts = NULL CHKERR( TSCreate(ccomm, &newts) ) PetscCLEAR(self.obj); self.ts = newts return self def clone(self): cdef TS ts = TS() CHKERR( TSClone(self.ts, &ts.ts) ) return ts def setType(self, ts_type): cdef PetscTSType cval = NULL ts_type = str2bytes(ts_type, &cval) CHKERR( TSSetType(self.ts, cval) ) def setRKType(self, ts_type): cdef PetscTSRKType cval = NULL ts_type = str2bytes(ts_type, &cval) CHKERR( TSRKSetType(self.ts, cval) ) def setARKIMEXType(self, ts_type): cdef PetscTSARKIMEXType cval = NULL ts_type = str2bytes(ts_type, &cval) CHKERR( TSARKIMEXSetType(self.ts, cval) ) def setARKIMEXFullyImplicit(self, flag): cdef PetscBool bval = asBool(flag) CHKERR( TSARKIMEXSetFullyImplicit(self.ts, bval) ) def getType(self): cdef PetscTSType cval = NULL CHKERR( TSGetType(self.ts, &cval) ) return bytes2str(cval) def getRKType(self): cdef PetscTSRKType cval = NULL CHKERR( TSRKGetType(self.ts, &cval) ) return bytes2str(cval) def getARKIMEXType(self): cdef PetscTSARKIMEXType cval = NULL CHKERR( TSARKIMEXGetType(self.ts, &cval) ) return bytes2str(cval) def setProblemType(self, ptype): CHKERR( TSSetProblemType(self.ts, ptype) ) def getProblemType(self): cdef PetscTSProblemType ptype = TS_NONLINEAR CHKERR( TSGetProblemType(self.ts, &ptype) ) return ptype def setEquationType(self, eqtype): CHKERR( TSSetEquationType(self.ts, eqtype) ) def getEquationType(self): cdef PetscTSEquationType eqtype = TS_EQ_UNSPECIFIED CHKERR( TSGetEquationType(self.ts, &eqtype) ) return eqtype def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( TSSetOptionsPrefix(self.ts, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( TSGetOptionsPrefix(self.ts, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( TSAppendOptionsPrefix(self.ts, cval) ) def setFromOptions(self): CHKERR( TSSetFromOptions(self.ts) ) # --- application context --- def setAppCtx(self, appctx): self.set_attr('__appctx__', appctx) def getAppCtx(self): return self.get_attr('__appctx__') # --- user RHS Function/Jacobian routines --- def setRHSFunction(self, function, Vec f=None, args=None, kargs=None): cdef PetscVec fvec=NULL if f is not None: fvec = f.vec if function is not None: if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr('__rhsfunction__', context) CHKERR( TSSetRHSFunction(self.ts, fvec, TS_RHSFunction, context) ) else: CHKERR( TSSetRHSFunction(self.ts, fvec, NULL, NULL) ) def setRHSJacobian(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): cdef PetscMat Jmat=NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat=Jmat if P is not None: Pmat = P.mat if jacobian is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr('__rhsjacobian__', context) CHKERR( TSSetRHSJacobian(self.ts, Jmat, Pmat, TS_RHSJacobian, context) ) else: CHKERR( TSSetRHSJacobian(self.ts, Jmat, Pmat, NULL, NULL) ) def computeRHSFunction(self, t, Vec x, Vec f): cdef PetscReal time = asReal(t) CHKERR( TSComputeRHSFunction(self.ts, time, x.vec, f.vec) ) def computeRHSFunctionLinear(self, t, Vec x, Vec f): cdef PetscReal time = asReal(t) CHKERR( TSComputeRHSFunctionLinear(self.ts, time, x.vec, f.vec, NULL) ) def computeRHSJacobian(self, t, Vec x, Mat J, Mat P=None): cdef PetscReal time = asReal(t) cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( TSComputeRHSJacobian(self.ts, time, x.vec, jmat, pmat) ) def computeRHSJacobianConstant(self, t, Vec x, Mat J, Mat P=None): cdef PetscReal time = asReal(t) cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( TSComputeRHSJacobianConstant(self.ts, time, x.vec, jmat, pmat, NULL) ) def getRHSFunction(self): cdef Vec f = Vec() CHKERR( TSGetRHSFunction(self.ts, &f.vec, NULL, NULL) ) PetscINCREF(f.obj) cdef object function = self.get_attr('__rhsfunction__') return (f, function) def getRHSJacobian(self): cdef Mat J = Mat(), P = Mat() CHKERR( TSGetRHSJacobian(self.ts, &J.mat, &P.mat, NULL, NULL) ) PetscINCREF(J.obj); PetscINCREF(P.obj) cdef object jacobian = self.get_attr('__rhsjacobian__') return (J, P, jacobian) # --- user Implicit Function/Jacobian routines --- def setIFunction(self, function, Vec f=None, args=None, kargs=None): cdef PetscVec fvec=NULL if f is not None: fvec = f.vec if function is not None: if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr('__ifunction__', context) CHKERR( TSSetIFunction(self.ts, fvec, TS_IFunction, context) ) else: CHKERR( TSSetIFunction(self.ts, fvec, NULL, NULL) ) def setIJacobian(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): cdef PetscMat Jmat=NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat=Jmat if P is not None: Pmat = P.mat if jacobian is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr('__ijacobian__', context) CHKERR( TSSetIJacobian(self.ts, Jmat, Pmat, TS_IJacobian, context) ) else: CHKERR( TSSetIJacobian(self.ts, Jmat, Pmat, NULL, NULL) ) def setIJacobianP(self, jacobian, Mat J=None, args=None, kargs=None): cdef PetscMat Jmat=NULL if J is not None: Jmat = J.mat if jacobian is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr('__ijacobianp__', context) CHKERR( TSSetIJacobianP(self.ts, Jmat, TS_IJacobianP, context) ) else: CHKERR( TSSetIJacobianP(self.ts, Jmat, NULL, NULL) ) def computeIFunction(self, t, Vec x, Vec xdot, Vec f, imex=False): cdef PetscReal rval = asReal(t) cdef PetscBool bval = imex CHKERR( TSComputeIFunction(self.ts, rval, x.vec, xdot.vec, f.vec, bval) ) def computeIJacobian(self, t, Vec x, Vec xdot, a, Mat J, Mat P=None, imex=False): cdef PetscReal rval1 = asReal(t) cdef PetscReal rval2 = asReal(a) cdef PetscBool bval = imex cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( TSComputeIJacobian(self.ts, rval1, x.vec, xdot.vec, rval2, jmat, pmat, bval) ) def computeIJacobianP(self, t, Vec x, Vec xdot, a, Mat J, imex=False): cdef PetscReal rval1 = asReal(t) cdef PetscReal rval2 = asReal(a) cdef PetscBool bval = asBool(imex) cdef PetscMat jmat = J.mat CHKERR( TSComputeIJacobianP(self.ts, rval1, x.vec, xdot.vec, rval2, jmat, bval) ) def getIFunction(self): cdef Vec f = Vec() CHKERR( TSGetIFunction(self.ts, &f.vec, NULL, NULL) ) PetscINCREF(f.obj) cdef object function = self.get_attr('__ifunction__') return (f, function) def getIJacobian(self): cdef Mat J = Mat(), P = Mat() CHKERR( TSGetIJacobian(self.ts, &J.mat, &P.mat, NULL, NULL) ) PetscINCREF(J.obj); PetscINCREF(P.obj) cdef object jacobian = self.get_attr('__ijacobian__') return (J, P, jacobian) def setI2Function(self, function, Vec f=None, args=None, kargs=None): cdef PetscVec fvec=NULL if f is not None: fvec = f.vec if function is not None: if args is None: args = () if kargs is None: kargs = {} context = (function, args, kargs) self.set_attr('__i2function__', context) CHKERR( TSSetI2Function(self.ts, fvec, TS_I2Function, context) ) else: CHKERR( TSSetI2Function(self.ts, fvec, NULL, NULL) ) def setI2Jacobian(self, jacobian, Mat J=None, Mat P=None, args=None, kargs=None): cdef PetscMat Jmat=NULL if J is not None: Jmat = J.mat cdef PetscMat Pmat=Jmat if P is not None: Pmat = P.mat if jacobian is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobian, args, kargs) self.set_attr('__i2jacobian__', context) CHKERR( TSSetI2Jacobian(self.ts, Jmat, Pmat, TS_I2Jacobian, context) ) else: CHKERR( TSSetI2Jacobian(self.ts, Jmat, Pmat, NULL, NULL) ) def computeI2Function(self, t, Vec x, Vec xdot, Vec xdotdot, Vec f): cdef PetscReal rval = asReal(t) CHKERR( TSComputeI2Function(self.ts, rval, x.vec, xdot.vec, xdotdot.vec, f.vec) ) def computeI2Jacobian(self, t, Vec x, Vec xdot, Vec xdotdot, v, a, Mat J, Mat P=None): cdef PetscReal rval1 = asReal(t) cdef PetscReal rval2 = asReal(v) cdef PetscReal rval3 = asReal(a) cdef PetscMat jmat = J.mat, pmat = J.mat if P is not None: pmat = P.mat CHKERR( TSComputeI2Jacobian(self.ts, rval1, x.vec, xdot.vec, xdotdot.vec, rval2, rval3, jmat, pmat) ) def getI2Function(self): cdef Vec f = Vec() CHKERR( TSGetI2Function(self.ts, &f.vec, NULL, NULL) ) PetscINCREF(f.obj) cdef object function = self.get_attr('__i2function__') return (f, function) def getI2Jacobian(self): cdef Mat J = Mat(), P = Mat() CHKERR( TSGetI2Jacobian(self.ts, &J.mat, &P.mat, NULL, NULL) ) PetscINCREF(J.obj); PetscINCREF(P.obj) cdef object jacobian = self.get_attr('__i2jacobian__') return (J, P, jacobian) # --- solution vector --- def setSolution(self, Vec u): CHKERR( TSSetSolution(self.ts, u.vec) ) def getSolution(self): cdef Vec u = Vec() CHKERR( TSGetSolution(self.ts, &u.vec) ) PetscINCREF(u.obj) return u def setSolution2(self, Vec u, Vec v): CHKERR( TS2SetSolution(self.ts, u.vec, v.vec) ) def getSolution2(self): cdef Vec u = Vec() cdef Vec v = Vec() CHKERR( TS2GetSolution(self.ts, &u.vec, &v.vec) ) PetscINCREF(u.obj) PetscINCREF(v.obj) return (u, v) # --- time span --- def setTimeSpan(self, tspan): cdef PetscInt nt = 0 cdef PetscReal *rtspan = NULL cdef object tmp = oarray_r(tspan, &nt, &rtspan) CHKERR( TSSetTimeSpan(self.ts, nt, rtspan) ) def getTimeSpan(self): cdef const PetscReal *rtspan = NULL cdef PetscInt nt = 0 CHKERR( TSGetTimeSpan(self.ts, &nt, &rtspan) ) cdef object tspan = array_r(nt, rtspan) return tspan def getTimeSpanSolutions(self): cdef PetscInt nt = 0 cdef PetscVec *sols = NULL CHKERR( TSGetTimeSpanSolutions(self.ts, &nt, &sols) ) cdef object sollist = None if sols != NULL: sollist = [ref_Vec(sols[i]) for i from 0 <= i < nt] return sollist # --- inner solver --- def getSNES(self): cdef SNES snes = SNES() CHKERR( TSGetSNES(self.ts, &snes.snes) ) PetscINCREF(snes.obj) return snes def getKSP(self): cdef KSP ksp = KSP() CHKERR( TSGetKSP(self.ts, &ksp.ksp) ) PetscINCREF(ksp.obj) return ksp # --- discretization space --- def getDM(self): cdef PetscDM newdm = NULL CHKERR( TSGetDM(self.ts, &newdm) ) cdef DM dm = subtype_DM(newdm)() dm.dm = newdm PetscINCREF(dm.obj) return dm def setDM(self, DM dm): CHKERR( TSSetDM(self.ts, dm.dm) ) # --- customization --- def setTime(self, t): cdef PetscReal rval = asReal(t) CHKERR( TSSetTime(self.ts, rval) ) def getTime(self): cdef PetscReal rval = 0 CHKERR( TSGetTime(self.ts, &rval) ) return toReal(rval) def getPrevTime(self): cdef PetscReal rval = 0 CHKERR( TSGetPrevTime(self.ts, &rval) ) return toReal(rval) def getSolveTime(self): cdef PetscReal rval = 0 CHKERR( TSGetSolveTime(self.ts, &rval) ) return toReal(rval) def setTimeStep(self, time_step): cdef PetscReal rval = asReal(time_step) CHKERR( TSSetTimeStep(self.ts, rval) ) def getTimeStep(self): cdef PetscReal tstep = 0 CHKERR( TSGetTimeStep(self.ts, &tstep) ) return toReal(tstep) def setStepNumber(self, step_number): cdef PetscInt ival = asInt(step_number) CHKERR( TSSetStepNumber(self.ts, ival) ) def getStepNumber(self): cdef PetscInt ival = 0 CHKERR( TSGetStepNumber(self.ts, &ival) ) return toInt(ival) def setMaxTime(self, max_time): cdef PetscReal rval = asReal(max_time) CHKERR( TSSetMaxTime(self.ts, rval) ) def getMaxTime(self): cdef PetscReal rval = 0 CHKERR( TSGetMaxTime(self.ts, &rval) ) return toReal(rval) def setMaxSteps(self, max_steps): cdef PetscInt ival = asInt(max_steps) CHKERR( TSSetMaxSteps(self.ts, ival) ) def getMaxSteps(self): cdef PetscInt ival = 0 CHKERR( TSGetMaxSteps(self.ts, &ival) ) return toInt(ival) def getSNESIterations(self): cdef PetscInt n = 0 CHKERR( TSGetSNESIterations(self.ts, &n) ) return toInt(n) def getKSPIterations(self): cdef PetscInt n = 0 CHKERR( TSGetKSPIterations(self.ts, &n) ) return toInt(n) def setMaxStepRejections(self, n): cdef PetscInt rej = asInt(n) CHKERR( TSSetMaxStepRejections(self.ts, rej)) #def getMaxStepRejections(self): # cdef PetscInt n = 0 # CHKERR( TSGetMaxStepRejections(self.ts, &n)) # return toInt(n) def getStepRejections(self): cdef PetscInt n = 0 CHKERR( TSGetStepRejections(self.ts, &n) ) return toInt(n) def setMaxSNESFailures(self, n): cdef PetscInt fails = asInt(n) CHKERR( TSSetMaxSNESFailures(self.ts, fails)) #def getMaxSNESFailures(self, n): # cdef PetscInt n = 0 # CHKERR( TSGetMaxSNESFailures(self.ts, &n)) # return toInt(n) def getSNESFailures(self): cdef PetscInt n = 0 CHKERR( TSGetSNESFailures(self.ts, &n) ) return toInt(n) def setErrorIfStepFails(self, flag=True): cdef PetscBool bval = flag CHKERR( TSSetErrorIfStepFails(self.ts, bval)) def setTolerances(self, rtol=None, atol=None): cdef PetscReal rrtol = PETSC_DEFAULT cdef PetscReal ratol = PETSC_DEFAULT cdef PetscVec vrtol = NULL cdef PetscVec vatol = NULL if rtol is None: pass elif isinstance(rtol, Vec): vrtol = (rtol).vec else: rrtol = asReal(rtol) if atol is None: pass elif isinstance(atol, Vec): vatol = (atol).vec else: ratol = asReal(atol) CHKERR( TSSetTolerances(self.ts, ratol, vatol, rrtol, vrtol) ) def getTolerances(self): cdef PetscReal rrtol = PETSC_DEFAULT cdef PetscReal ratol = PETSC_DEFAULT cdef PetscVec vrtol = NULL cdef PetscVec vatol = NULL CHKERR( TSGetTolerances(self.ts, &ratol, &vatol, &rrtol, &vrtol) ) cdef object rtol = None if vrtol != NULL: rtol = ref_Vec(vrtol) else: rtol = toReal(rrtol) cdef object atol = None if vatol != NULL: atol = ref_Vec(vatol) else: atol = toReal(ratol) return (rtol, atol) def setExactFinalTime(self, option): cdef PetscTSExactFinalTimeOption oval = option CHKERR( TSSetExactFinalTime(self.ts, oval) ) def setConvergedReason(self, reason): cdef PetscTSConvergedReason cval = reason CHKERR( TSSetConvergedReason(self.ts, cval) ) def getConvergedReason(self): cdef PetscTSConvergedReason reason = TS_CONVERGED_ITERATING CHKERR( TSGetConvergedReason(self.ts, &reason) ) return reason # --- monitoring --- def setMonitor(self, monitor, args=None, kargs=None): if monitor is None: return cdef object monitorlist = self.get_attr('__monitor__') if monitorlist is None: monitorlist = [] self.set_attr('__monitor__', monitorlist) CHKERR( TSMonitorSet(self.ts, TS_Monitor, NULL, NULL) ) if args is None: args = () if kargs is None: kargs = {} context = (monitor, args, kargs) monitorlist.append(context) def getMonitor(self): return self.get_attr('__monitor__') def monitorCancel(self): self.set_attr('__monitor__', None) CHKERR( TSMonitorCancel(self.ts) ) cancelMonitor = monitorCancel def monitor(self, step, time, Vec u=None): cdef PetscInt ival = asInt(step) cdef PetscReal rval = asReal(time) cdef PetscVec uvec = NULL if u is not None: uvec = u.vec if uvec == NULL: CHKERR( TSGetSolution(self.ts, &uvec) ) CHKERR( TSMonitor(self.ts, ival, rval, uvec) ) # --- event handling --- def setEventHandler(self, direction, terminate, eventhandler, postevent=None, args=None, kargs=None): cdef PetscInt ndirs = 0 cdef PetscInt *idirs = NULL direction = iarray_i(direction, &ndirs, &idirs) cdef PetscInt nterm = 0 cdef PetscBool *iterm = NULL terminate = iarray_b(terminate, &nterm, &iterm) assert nterm == ndirs cdef PetscInt nevents = ndirs if eventhandler is not None: if args is None: args = () if kargs is None: kargs = {} self.set_attr('__eventhandler__', (eventhandler, args, kargs)) if postevent is not None: self.set_attr('__postevent__', (postevent, args, kargs)) CHKERR( TSSetEventHandler(self.ts, nevents, idirs, iterm, TS_EventHandler, TS_PostEvent, NULL) ) else: self.set_attr('__postevent__', None) CHKERR( TSSetEventHandler(self.ts, nevents, idirs, iterm, TS_EventHandler, NULL, NULL) ) else: CHKERR( TSSetEventHandler(self.ts, nevents, idirs, iterm, NULL, NULL, NULL) ) def setEventTolerances(self, tol=None, vtol=None): cdef PetscInt nevents = 0 cdef PetscReal tolr = PETSC_DEFAULT cdef PetscInt ntolr = 0 cdef PetscReal *vtolr = NULL if tol is not None: tolr = asReal(tol) if vtol is not None: CHKERR( TSGetNumEvents(self.ts, &nevents) ) vtol = iarray_r(vtol, &ntolr, &vtolr) assert ntolr == nevents CHKERR( TSSetEventTolerances(self.ts, tolr, vtolr) ) def getNumEvents(self): cdef PetscInt nevents = 0 CHKERR( TSGetNumEvents(self.ts, &nevents) ) return toInt(nevents) # --- solving --- def setPreStep(self, prestep, args=None, kargs=None): if prestep is not None: if args is None: args = () if kargs is None: kargs = {} context = (prestep, args, kargs) self.set_attr('__prestep__', context) CHKERR( TSSetPreStep(self.ts, TS_PreStep) ) else: self.set_attr('__prestep__', None) CHKERR( TSSetPreStep(self.ts, NULL) ) def getPreStep(self): return self.get_attr('__prestep__') def setPostStep(self, poststep, args=None, kargs=None): if poststep is not None: if args is None: args = () if kargs is None: kargs = {} context = (poststep, args, kargs) self.set_attr('__poststep__', context) CHKERR( TSSetPostStep(self.ts, TS_PostStep) ) else: self.set_attr('__poststep__', None) CHKERR( TSSetPostStep(self.ts, NULL) ) def getPostStep(self): return self.get_attr('__poststep__') def setUp(self): CHKERR( TSSetUp(self.ts) ) def reset(self): CHKERR( TSReset(self.ts) ) def step(self): CHKERR( TSStep(self.ts) ) def restartStep(self): CHKERR( TSRestartStep(self.ts) ) def rollBack(self): CHKERR( TSRollBack(self.ts) ) def solve(self, Vec u): CHKERR( TSSolve(self.ts, u.vec) ) def interpolate(self, t, Vec u): cdef PetscReal rval = asReal(t) CHKERR( TSInterpolate(self.ts, rval, u.vec) ) def setStepLimits(self, hmin, hmax): cdef PetscTSAdapt tsadapt = NULL cdef PetscReal hminr = toReal(hmin) cdef PetscReal hmaxr = toReal(hmax) TSGetAdapt(self.ts, &tsadapt) CHKERR( TSAdaptSetStepLimits(tsadapt, hminr, hmaxr) ) def getStepLimits(self): cdef PetscTSAdapt tsadapt = NULL cdef PetscReal hminr = 0. cdef PetscReal hmaxr = 0. TSGetAdapt(self.ts, &tsadapt) CHKERR( TSAdaptGetStepLimits(tsadapt, &hminr, &hmaxr) ) return (asReal(hminr), asReal(hmaxr)) # --- Adjoint methods --- def setSaveTrajectory(self): CHKERR(TSSetSaveTrajectory(self.ts)) def removeTrajectory(self): CHKERR(TSRemoveTrajectory(self.ts)) def getCostIntegral(self): cdef Vec cost = Vec() CHKERR( TSGetCostIntegral(self.ts, &cost.vec) ) PetscINCREF(cost.obj) return cost def setCostGradients(self, vl, vm=None): cdef PetscInt n = 0; cdef PetscVec *vecl = NULL cdef PetscVec *vecm = NULL cdef mem1 = None, mem2 = None if isinstance(vl, Vec): vl = [vl] if isinstance(vm, Vec): vm = [vm] if vl is not None: n = len(vl) elif vm is not None: n = len(vm) if vl is not None: assert len(vl) == n mem1 = oarray_p(empty_p(n), NULL, &vecl) for i from 0 <= i < n: vecl[i] = (vl[i]).vec if vm is not None: assert len(vm) == n mem2 = oarray_p(empty_p(n), NULL, &vecm) for i from 0 <= i < n: vecm[i] = (vm[i]).vec self.set_attr('__costgradients_memory', (mem1, mem2)) CHKERR( TSSetCostGradients(self.ts, n, vecl, vecm) ) def getCostGradients(self): cdef PetscInt i = 0, n = 0 cdef PetscVec *vecl = NULL cdef PetscVec *vecm = NULL CHKERR( TSGetCostGradients(self.ts, &n, &vecl, &vecm) ) cdef object vl = None, vm = None if vecl != NULL: vl = [ref_Vec(vecl[i]) for i from 0 <= i < n] if vecm != NULL: vm = [ref_Vec(vecm[i]) for i from 0 <= i < n] return (vl, vm) def setRHSJacobianP(self, jacobianp, Mat A=None, args=None, kargs=None): cdef PetscMat Amat=NULL if A is not None: Amat = A.mat if jacobianp is not None: if args is None: args = () if kargs is None: kargs = {} context = (jacobianp, args, kargs) self.set_attr('__rhsjacobianp__', context) CHKERR( TSSetRHSJacobianP(self.ts, Amat, TS_RHSJacobianP, context) ) else: CHKERR( TSSetRHSJacobianP(self.ts, Amat, NULL, NULL) ) def createQuadratureTS(self, forward=True): cdef TS qts = TS() cdef PetscBool fwd = forward CHKERR( TSCreateQuadratureTS(self.ts, fwd, &qts.ts) ) PetscINCREF(qts.obj) return qts def getQuadratureTS(self): cdef TS qts = TS() cdef PetscBool fwd = PETSC_FALSE CHKERR( TSGetQuadratureTS(self.ts, &fwd, &qts.ts) ) PetscINCREF(qts.obj) return (toBool(fwd), qts) def setRHSJacobianP(self, rhsjacobianp, Mat A=None, args=None, kargs=None): cdef PetscMat Amat=NULL if A is not None: Amat = A.mat if rhsjacobianp is not None: if args is None: args = () if kargs is None: kargs = {} context = (rhsjacobianp, args, kargs) self.set_attr('__rhsjacobianp__', context) CHKERR( TSSetRHSJacobianP(self.ts, Amat, TS_RHSJacobianP, context) ) else: CHKERR( TSSetRHSJacobianP(self.ts, Amat, NULL, NULL) ) def computeRHSJacobianP(self, t, Vec x, Mat J): cdef PetscReal rval = asReal(t) CHKERR( TSComputeRHSJacobianP(self.ts, rval, x.vec, J.mat) ) def adjointSetSteps(self, adjoint_steps): cdef PetscInt ival = asInt(adjoint_steps) CHKERR( TSAdjointSetSteps(self.ts, ival) ) def adjointSetUp(self): CHKERR(TSAdjointSetUp(self.ts)) def adjointSolve(self): CHKERR( TSAdjointSolve(self.ts) ) def adjointStep(self): CHKERR(TSAdjointStep(self.ts)) def adjointReset(self): CHKERR(TSAdjointReset(self.ts)) # --- Python --- def createPython(self, context=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscTS newts = NULL CHKERR( TSCreate(ccomm, &newts) ) PetscCLEAR(self.obj); self.ts = newts CHKERR( TSSetType(self.ts, TSPYTHON) ) CHKERR( TSPythonSetContext(self.ts, context) ) return self def setPythonContext(self, context): CHKERR( TSPythonSetContext(self.ts, context) ) def getPythonContext(self): cdef void *context = NULL CHKERR( TSPythonGetContext(self.ts, &context) ) if context == NULL: return None else: return context def setPythonType(self, py_type): cdef const char *cval = NULL py_type = str2bytes(py_type, &cval) CHKERR( TSPythonSetType(self.ts, cval) ) def getPythonType(self): cdef const char *cval = NULL CHKERR( TSPythonGetType(self.ts, &cval) ) return bytes2str(cval) # --- Theta --- def setTheta(self, theta): cdef PetscReal rval = asReal(theta) CHKERR( TSThetaSetTheta(self.ts, rval) ) def getTheta(self): cdef PetscReal rval = 0 CHKERR( TSThetaGetTheta(self.ts, &rval) ) return toReal(rval) def setThetaEndpoint(self, flag=True): cdef PetscBool bval = flag CHKERR( TSThetaSetEndpoint(self.ts, bval) ) def getThetaEndpoint(self): cdef PetscBool flag = PETSC_FALSE CHKERR( TSThetaGetEndpoint(self.ts, &flag) ) return toBool(flag) # --- Alpha --- def setAlphaRadius(self, radius): cdef PetscReal rval = asReal(radius) CHKERR( TSAlphaSetRadius(self.ts, rval) ) def setAlphaParams(self, alpha_m=None,alpha_f=None, gamma=None): cdef PetscReal rval1 = 0, rval2 = 0, rval3 = 0 try: CHKERR( TSAlphaGetParams(self.ts, &rval1, &rval2, &rval3) ) except PetscError: pass if alpha_m is not None: rval1 = asReal(alpha_m) if alpha_f is not None: rval2 = asReal(alpha_f) if gamma is not None: rval3 = asReal(gamma) CHKERR( TSAlphaSetParams(self.ts, rval1, rval2, rval3) ) def getAlphaParams(self): cdef PetscReal rval1 = 0, rval2 = 0, rval3 = 0 CHKERR( TSAlphaGetParams(self.ts, &rval1, &rval2, &rval3) ) return (toReal(rval1), toReal(rval2), toReal(rval3)) # --- application context --- property appctx: def __get__(self): return self.getAppCtx() def __set__(self, value): self.setAppCtx(value) # --- discretization space --- property dm: def __get__(self): return self.getDM() def __set__(self, value): self.setDM(value) # --- xxx --- property problem_type: def __get__(self): return self.getProblemType() def __set__(self, value): self.setProblemType(value) property equation_type: def __get__(self): return self.getEquationType() def __set__(self, value): self.setEquationType(value) property snes: def __get__(self): return self.getSNES() property ksp: def __get__(self): return self.getKSP() property vec_sol: def __get__(self): return self.getSolution() # --- xxx --- property time: def __get__(self): return self.getTime() def __set__(self, value): self.setTime(value) property time_step: def __get__(self): return self.getTimeStep() def __set__(self, value): self.setTimeStep(value) property step_number: def __get__(self): return self.getStepNumber() def __set__(self, value): self.setStepNumber(value) property max_time: def __get__(self): return self.getMaxTime() def __set__(self, value): self.setMaxTime(value) property max_steps: def __get__(self): return self.getMaxSteps() def __set__(self, value): self.setMaxSteps(value) # --- convergence --- property rtol: def __get__(self): return self.getTolerances()[0] def __set__(self, value): self.setTolerances(rtol=value) property atol: def __get__(self): return self.getTolerances()[1] def __set__(self, value): self.setTolerances(atol=value) property reason: def __get__(self): return self.getConvergedReason() def __set__(self, value): self.setConvergedReason(value) property iterating: def __get__(self): return self.reason == 0 property converged: def __get__(self): return self.reason > 0 property diverged: def __get__(self): return self.reason < 0 # ----------------------------------------------------------------------------- del TSType del TSRKType del TSARKIMEXType del TSProblemType del TSEquationType del TSExactFinalTime del TSConvergedReason # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Vec.pyx000066400000000000000000001412361454104047300201350ustar00rootroot00000000000000# -------------------------------------------------------------------- class VecType(object): SEQ = S_(VECSEQ) MPI = S_(VECMPI) STANDARD = S_(VECSTANDARD) SHARED = S_(VECSHARED) SEQVIENNACL= S_(VECSEQVIENNACL) MPIVIENNACL= S_(VECMPIVIENNACL) VIENNACL = S_(VECVIENNACL) SEQCUDA = S_(VECSEQCUDA) MPICUDA = S_(VECMPICUDA) CUDA = S_(VECCUDA) SEQHIP = S_(VECSEQHIP) MPIHIP = S_(VECMPIHIP) HIP = S_(VECHIP) NEST = S_(VECNEST) SEQKOKKOS = S_(VECSEQKOKKOS) MPIKOKKOS = S_(VECMPIKOKKOS) KOKKOS = S_(VECKOKKOS) class VecOption(object): IGNORE_OFF_PROC_ENTRIES = VEC_IGNORE_OFF_PROC_ENTRIES IGNORE_NEGATIVE_INDICES = VEC_IGNORE_NEGATIVE_INDICES # -------------------------------------------------------------------- cdef class Vec(Object): Type = VecType Option = VecOption # def __cinit__(self): self.obj = &self.vec self.vec = NULL # unary operations def __pos__(self): return vec_pos(self) def __neg__(self): return vec_neg(self) def __abs__(self): return vec_abs(self) # inplace binary operations def __iadd__(self, other): return vec_iadd(self, other) def __isub__(self, other): return vec_isub(self, other) def __imul__(self, other): return vec_imul(self, other) def __idiv__(self, other): return vec_idiv(self, other) def __itruediv__(self, other): return vec_idiv(self, other) # binary operations def __add__(self, other): if isinstance(self, Vec): return vec_add(self, other) else: return vec_radd(other, self) def __sub__(self, other): if isinstance(self, Vec): return vec_sub(self, other) else: return vec_rsub(other, self) def __mul__(self, other): if isinstance(self, Vec): return vec_mul(self, other) else: return vec_rmul(other, self) def __div__(self, other): if isinstance(self, Vec): return vec_div(self, other) else: return vec_rdiv(other, self) def __truediv__(self, other): if isinstance(self, Vec): return vec_div(self, other) else: return vec_rdiv(other, self) # #def __len__(self): # cdef PetscInt size = 0 # CHKERR( VecGetSize(self.vec, &size) ) # return size def __getitem__(self, i): return vec_getitem(self, i) def __setitem__(self, i, v): vec_setitem(self, i, v) # buffer interface (PEP 3118) def __getbuffer__(self, Py_buffer *view, int flags): cdef _Vec_buffer buf = _Vec_buffer(self) buf.acquirebuffer(view, flags) def __releasebuffer__(self, Py_buffer *view): cdef _Vec_buffer buf = <_Vec_buffer>(view.obj) buf.releasebuffer(view) self # unused # 'with' statement (PEP 343) def __enter__(self): cdef _Vec_buffer buf = _Vec_buffer(self) self.set_attr('__buffer__', buf) return buf.enter() def __exit__(self, *exc): cdef _Vec_buffer buf = self.get_attr('__buffer__') self.set_attr('__buffer__', None) return buf.exit() # def view(self, Viewer viewer=None): cdef PetscViewer vwr = NULL if viewer is not None: vwr = viewer.vwr CHKERR( VecView(self.vec, vwr) ) def destroy(self): CHKERR( VecDestroy(&self.vec) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscVec newvec = NULL CHKERR( VecCreate(ccomm, &newvec) ) PetscCLEAR(self.obj); self.vec = newvec return self def setType(self, vec_type): cdef PetscVecType cval = NULL vec_type = str2bytes(vec_type, &cval) CHKERR( VecSetType(self.vec, cval) ) def setSizes(self, size, bsize=None): cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) CHKERR( VecSetSizes(self.vec, n, N) ) if bs != PETSC_DECIDE: CHKERR( VecSetBlockSize(self.vec, bs) ) # def createSeq(self, size, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_SELF) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 cdef PetscVec newvec = NULL CHKERR( VecCreate(ccomm,&newvec) ) CHKERR( VecSetSizes(newvec, n, N) ) CHKERR( VecSetBlockSize(newvec, bs) ) CHKERR( VecSetType(newvec, VECSEQ) ) PetscCLEAR(self.obj); self.vec = newvec return self def createMPI(self, size, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 cdef PetscVec newvec = NULL CHKERR( VecCreate(ccomm, &newvec) ) CHKERR( VecSetSizes(newvec, n, N) ) CHKERR( VecSetBlockSize(newvec, bs) ) CHKERR( VecSetType(newvec, VECMPI) ) PetscCLEAR(self.obj); self.vec = newvec return self def createWithArray(self, array, size=None, bsize=None, comm=None): cdef PetscInt na=0 cdef PetscScalar *sa=NULL array = iarray_s(array, &na, &sa) if size is None: size = (toInt(na), toInt(PETSC_DECIDE)) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if na < n: raise ValueError( "array size %d and vector local size %d block size %d" % (toInt(na), toInt(n), toInt(bs))) cdef PetscVec newvec = NULL if comm_size(ccomm) == 1: CHKERR( VecCreateSeqWithArray(ccomm,bs,N,sa,&newvec) ) else: CHKERR( VecCreateMPIWithArray(ccomm,bs,n,N,sa,&newvec) ) PetscCLEAR(self.obj); self.vec = newvec self.set_attr('__array__', array) return self def createCUDAWithArrays(self, cpuarray=None, cudahandle=None, size=None, bsize=None, comm=None): """ Returns an instance of :class:`Vec`, a VECCUDA with user provided memory spaces for CPU and GPU arrays. :arg cpuarray: A :class:`numpy.ndarray`. Will be lazily allocated if *None*. :arg cudahandle: Address of the array on the GPU. Will be lazily allocated if *None*. :arg size: A :class:`int` denoting the size of the Vec. :arg bsize: A :class:`int` denoting the block size. """ cdef PetscInt na=0 cdef PetscScalar *sa=NULL cdef PetscScalar *gpuarray = NULL if cudahandle: gpuarray = (cudahandle) if cpuarray is not None: cpuarray = iarray_s(cpuarray, &na, &sa) if size is None: size = (toInt(na), toInt(PETSC_DECIDE)) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if na < n: raise ValueError( "array size %d and vector local size %d block size %d" % (toInt(na), toInt(n), toInt(bs))) cdef PetscVec newvec = NULL if comm_size(ccomm) == 1: CHKERR( VecCreateSeqCUDAWithArrays(ccomm,bs,N,sa,gpuarray,&newvec) ) else: CHKERR( VecCreateMPICUDAWithArrays(ccomm,bs,n,N,sa,gpuarray,&newvec) ) PetscCLEAR(self.obj); self.vec = newvec if cpuarray is not None: self.set_attr('__array__', cpuarray) return self def createHIPWithArrays(self, cpuarray=None, hiphandle=None, size=None, bsize=None, comm=None): """ Returns an instance of :class:`Vec`, a VECHIP with user provided memory spaces for CPU and GPU arrays. :arg cpuarray: A :class:`numpy.ndarray`. Will be lazily allocated if *None*. :arg hiphandle: Address of the array on the GPU. Will be lazily allocated if *None*. :arg size: A :class:`int` denoting the size of the Vec. :arg bsize: A :class:`int` denoting the block size. """ cdef PetscInt na=0 cdef PetscScalar *sa=NULL cdef PetscScalar *gpuarray = NULL if hiphandle: gpuarray = (hiphandle) if cpuarray is not None: cpuarray = iarray_s(cpuarray, &na, &sa) if size is None: size = (toInt(na), toInt(PETSC_DECIDE)) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if na < n: raise ValueError( "array size %d and vector local size %d block size %d" % (toInt(na), toInt(n), toInt(bs))) cdef PetscVec newvec = NULL if comm_size(ccomm) == 1: CHKERR( VecCreateSeqHIPWithArrays(ccomm,bs,N,sa,gpuarray,&newvec) ) else: CHKERR( VecCreateMPIHIPWithArrays(ccomm,bs,n,N,sa,gpuarray,&newvec) ) PetscCLEAR(self.obj); self.vec = newvec if cpuarray is not None: self.set_attr('__array__', cpuarray) return self def createViennaCLWithArrays(self, cpuarray=None, viennaclvechandle=None, size=None, bsize=None, comm=None): """ Returns an instance :class:`Vec`, a VECVIENNACL with user provided memory spaces for CPU and GPU arrays. :arg cpuarray: A :class:`numpy.ndarray`. Will be lazily allocated if *None*. :arg viennaclvechandle: Address of the array on the GPU. Will be lazily allocated if *None*. :arg size: A :class:`int` denoting the size of the Vec. :arg size: A :class:`int` denoting the block size. """ cdef PetscInt na=0 cdef PetscScalar *sa=NULL cdef PetscScalar *vclvec = NULL if viennaclvechandle: vclvec = (viennaclvechandle) if cpuarray is not None: cpuarray = iarray_s(cpuarray, &na, &sa) if size is None: size = (toInt(na), toInt(PETSC_DECIDE)) cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if na < n: raise ValueError( "array size %d and vector local size %d block size %d" % (toInt(na), toInt(n), toInt(bs))) cdef PetscVec newvec = NULL if comm_size(ccomm) == 1: CHKERR( VecCreateSeqViennaCLWithArrays(ccomm,bs,N,sa,vclvec,&newvec) ) else: CHKERR( VecCreateMPIViennaCLWithArrays(ccomm,bs,n,N,sa,vclvec,&newvec) ) PetscCLEAR(self.obj); self.vec = newvec if cpuarray is not None: self.set_attr('__array__', cpuarray) return self def createWithDLPack(self, object dltensor, size=None, bsize=None, comm=None): """ Returns an instance :class:`Vec`, a PETSc vector from a DLPack object sharing the same memory. This operation does not modify the storage of the original tensor and should be used with contiguous tensors only. If the tensor is stored in row-major order (e.g. PyTorch tensors), the resulting vector will look like an unrolled tensor using row-major order. :arg dltensor: An object with a __dlpack__ method or a DLPack tensor object (for backward compatibility) :arg size: A :class:`int` denoting the size of the Vec. :arg bsize: A :class:`int` denoting the block size. """ cdef DLManagedTensor* ptr = NULL cdef int bits = 0 cdef PetscInt nz = 1 cdef int64_t ndim = 0 cdef int64_t* shape = NULL cdef int64_t* strides = NULL cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs = 0,n = 0,N = 0 cdef DLContext* ctx = NULL if not PyCapsule_CheckExact(dltensor): dltensor = dltensor.__dlpack__() if PyCapsule_IsValid(dltensor, 'dltensor'): ptr = PyCapsule_GetPointer(dltensor, 'dltensor') bits = ptr.dl_tensor.dtype.bits if bits != 8*sizeof(PetscScalar): raise TypeError("Tensor dtype = {} does not match PETSc precision".format(ptr.dl_tensor.dtype)) ndim = ptr.dl_tensor.ndim shape = ptr.dl_tensor.shape for s in shape[:ndim]: nz = nz*s strides = ptr.dl_tensor.strides PyCapsule_SetName(dltensor, 'used_dltensor') else: raise ValueError("Expect a dltensor field, pycapsule.PyCapsule can only be consumed once") if size is None: size = (toInt(nz), toInt(PETSC_DECIDE)) Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if bs == PETSC_DECIDE: bs = 1 if nz < n: raise ValueError( "array size %d and vector local size %d block size %d" % (toInt(nz), toInt(n), toInt(bs))) cdef PetscVec newvec = NULL cdef PetscDLDeviceType dltype = ptr.dl_tensor.ctx.device_type if dltype in [kDLCUDA,kDLCUDAManaged]: if comm_size(ccomm) == 1: CHKERR( VecCreateSeqCUDAWithArray(ccomm,bs,N,(ptr.dl_tensor.data),&newvec) ) else: CHKERR( VecCreateMPICUDAWithArray(ccomm,bs,n,N,(ptr.dl_tensor.data),&newvec) ) elif dltype in [kDLCPU,kDLCUDAHost,kDLROCMHost]: if comm_size(ccomm) == 1: CHKERR( VecCreateSeqWithArray(ccomm,bs,N,(ptr.dl_tensor.data),&newvec) ) else: CHKERR( VecCreateMPIWithArray(ccomm,bs,n,N,(ptr.dl_tensor.data),&newvec) ) elif dltype == kDLROCM: if comm_size(ccomm) == 1: CHKERR( VecCreateSeqHIPWithArray(ccomm,bs,N,(ptr.dl_tensor.data),&newvec) ) else: CHKERR( VecCreateMPIHIPWithArray(ccomm,bs,n,N,(ptr.dl_tensor.data),&newvec) ) else: raise TypeError("Device type {} not supported".format(dltype)) PetscCLEAR(self.obj); self.vec = newvec self.set_attr('__array__', dltensor) cdef int64_t* shape_arr = NULL cdef int64_t* strides_arr = NULL cdef object s1 = oarray_p(empty_p(ndim), NULL, &shape_arr) cdef object s2 = oarray_p(empty_p(ndim), NULL, &strides_arr) for i in range(ndim): shape_arr[i] = shape[i] strides_arr[i] = strides[i] self.set_attr('__dltensor_ctx__', (ptr.dl_tensor.ctx.device_type, ptr.dl_tensor.ctx.device_id, ndim, s1, s2)) if ptr.manager_deleter != NULL: ptr.manager_deleter(ptr) # free the manager return self def attachDLPackInfo(self, Vec vec=None, object dltensor=None): """ Attach the tensor information from an input vector (vec) or a DLPack tensor if it is not available in current vector. The input vector is typically created with createWithDlpack(). This operation does not copy the data from the input parameters, it simply uses their meta information. Note that the auxiliary tensor information is required when converting a PETSc vector to a DLPack object. See also :meth:`Vec.clearDLPackInfo`. :arg vec: A :class:'Vec' containing auxiliary tensor information :arg dltensor: A DLPack tensor object """ cdef object ctx0 = self.get_attr('__dltensor_ctx__'), ctx = None cdef DLManagedTensor* ptr = NULL cdef int64_t* shape_arr = NULL cdef int64_t* strides_arr = NULL cdef object s1 = None, s2 = None if vec is None and dltensor is None: raise ValueError('Missing input parameters') if vec is not None: ctx = (vec).get_attr('__dltensor_ctx__') if ctx is None: raise ValueError('Input vector has no tensor information') self.set_attr('__dltensor_ctx__', ctx) else: if PyCapsule_IsValid(dltensor, 'dltensor'): ptr = PyCapsule_GetPointer(dltensor, 'dltensor') elif PyCapsule_IsValid(dltensor, 'used_dltensor'): ptr = PyCapsule_GetPointer(dltensor, 'used_dltensor') else: raise ValueError("Expect a dltensor or used_dltensor field") bits = ptr.dl_tensor.dtype.bits if bits != 8*sizeof(PetscScalar): raise TypeError("Tensor dtype = {} does not match PETSc precision".format(ptr.dl_tensor.dtype)) ndim = ptr.dl_tensor.ndim shape = ptr.dl_tensor.shape strides = ptr.dl_tensor.strides s1 = oarray_p(empty_p(ndim), NULL, &shape_arr) s2 = oarray_p(empty_p(ndim), NULL, &strides_arr) for i in range(ndim): shape_arr[i] = shape[i] strides_arr[i] = strides[i] self.set_attr('__dltensor_ctx__', (ptr.dl_tensor.ctx.device_type, ptr.dl_tensor.ctx.device_id, ndim, s1, s2)) return self def clearDLPackInfo(self): """ Clear the tensor information See also :meth:`Vec.attachDLPackInfo`. """ self.set_attr('__dltensor_ctx__', None) return self # TODO Stream def __dlpack__(self, stream=-1): return self.toDLPack('rw') def __dlpack_device__(self): (dltype, devId, _, _, _) = vec_get_dlpack_ctx(self) return (dltype, devId) def toDLPack(self, mode='rw'): """ Return a DLPack capsule. """ if mode is None: mode = 'rw' if mode not in ['rw', 'r', 'w']: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") cdef int64_t ndim = 0 (device_type, device_id, ndim, shape, strides) = vec_get_dlpack_ctx(self) hostmem = (device_type == kDLCPU) cdef DLManagedTensor* dlm_tensor = malloc(sizeof(DLManagedTensor)) cdef DLTensor* dl_tensor = &dlm_tensor.dl_tensor cdef PetscScalar *a = NULL cdef int64_t* shape_strides = NULL dl_tensor.byte_offset = 0 # DLPack does not currently play well with our get/restore model # Call restore right-away and hope that the consumer will do the right thing # and not modify memory requested with read access # By restoring now, we guarantee the sanity of the ObjectState if mode == 'w': if hostmem: CHKERR( VecGetArrayWrite(self.vec, &a) ) CHKERR( VecRestoreArrayWrite(self.vec, NULL) ) else: CHKERR( VecGetArrayWriteAndMemType(self.vec, &a, NULL) ) CHKERR( VecRestoreArrayWriteAndMemType(self.vec, NULL) ) elif mode == 'r': if hostmem: CHKERR( VecGetArrayRead(self.vec, &a) ) CHKERR( VecRestoreArrayRead(self.vec, NULL) ) else: CHKERR( VecGetArrayReadAndMemType(self.vec, &a, NULL) ) CHKERR( VecRestoreArrayReadAndMemType(self.vec, NULL) ) else: if hostmem: CHKERR( VecGetArray(self.vec, &a) ) CHKERR( VecRestoreArray(self.vec, NULL) ) else: CHKERR( VecGetArrayAndMemType(self.vec, &a, NULL) ) CHKERR( VecRestoreArrayAndMemType(self.vec, NULL) ) dl_tensor.data = a cdef DLContext* ctx = &dl_tensor.ctx ctx.device_type = device_type ctx.device_id = device_id shape_strides = malloc(sizeof(int64_t)*2*ndim) for i in range(ndim): shape_strides[i] = shape[i] for i in range(ndim): shape_strides[i+ndim] = strides[i] dl_tensor.ndim = ndim dl_tensor.shape = shape_strides dl_tensor.strides = shape_strides + ndim cdef DLDataType* dtype = &dl_tensor.dtype dtype.code = DLDataTypeCode.kDLFloat if sizeof(PetscScalar) == 8: dtype.bits = 64 elif sizeof(PetscScalar) == 4: dtype.bits = 32 else: raise ValueError('Unsupported PetscScalar type') dtype.lanes = 1 dlm_tensor.manager_ctx = self.vec CHKERR( PetscObjectReference(self.vec) ) dlm_tensor.manager_deleter = manager_deleter dlm_tensor.del_obj = PetscDEALLOC return PyCapsule_New(dlm_tensor, 'dltensor', pycapsule_deleter) def createGhost(self, ghosts, size, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt ng=0, *ig=NULL ghosts = iarray_i(ghosts, &ng, &ig) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) cdef PetscVec newvec = NULL if bs == PETSC_DECIDE: CHKERR( VecCreateGhost( ccomm, n, N, ng, ig, &newvec) ) else: CHKERR( VecCreateGhostBlock( ccomm, bs, n, N, ng, ig, &newvec) ) PetscCLEAR(self.obj); self.vec = newvec return self def createGhostWithArray(self, ghosts, array, size=None, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt ng=0, *ig=NULL ghosts = iarray_i(ghosts, &ng, &ig) cdef PetscInt na=0 cdef PetscScalar *sa=NULL array = oarray_s(array, &na, &sa) cdef PetscInt b = 1 if bsize is None else asInt(bsize) if size is None: size = (toInt(na-ng*b), toInt(PETSC_DECIDE)) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) if na < (n+ng*b): raise ValueError( "ghosts size %d, array size %d, and " "vector local size %d block size %d" % (toInt(ng), toInt(na), toInt(n), toInt(b))) cdef PetscVec newvec = NULL if bs == PETSC_DECIDE: CHKERR( VecCreateGhostWithArray( ccomm, n, N, ng, ig, sa, &newvec) ) else: CHKERR( VecCreateGhostBlockWithArray( ccomm, bs, n, N, ng, ig, sa, &newvec) ) PetscCLEAR(self.obj); self.vec = newvec self.set_attr('__array__', array) return self def createShared(self, size, bsize=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscInt bs=0, n=0, N=0 Vec_Sizes(size, bsize, &bs, &n, &N) Sys_Layout(ccomm, bs, &n, &N) cdef PetscVec newvec = NULL CHKERR( VecCreateShared(ccomm, n, N, &newvec) ) PetscCLEAR(self.obj); self.vec = newvec if bs != PETSC_DECIDE: CHKERR( VecSetBlockSize(self.vec, bs) ) return self def createNest(self, vecs, isets=None, comm=None): vecs = list(vecs) if isets: isets = list(isets) assert len(isets) == len(vecs) else: isets = None cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Py_ssize_t i, m = len(vecs) cdef PetscInt n = m cdef PetscVec *cvecs = NULL cdef PetscIS *cisets = NULL cdef object tmp1, tmp2 tmp1 = oarray_p(empty_p(n), NULL, &cvecs) for i from 0 <= i < m: cvecs[i] = (vecs[i]).vec if isets is not None: tmp2 = oarray_p(empty_p(n), NULL, &cisets) for i from 0 <= i < m: cisets[i] = (isets[i]).iset cdef PetscVec newvec = NULL CHKERR( VecCreateNest(ccomm, n, cisets, cvecs,&newvec) ) PetscCLEAR(self.obj); self.vec = newvec return self # def setOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( VecSetOptionsPrefix(self.vec, cval) ) def getOptionsPrefix(self): cdef const char *cval = NULL CHKERR( VecGetOptionsPrefix(self.vec, &cval) ) return bytes2str(cval) def appendOptionsPrefix(self, prefix): cdef const char *cval = NULL prefix = str2bytes(prefix, &cval) CHKERR( VecAppendOptionsPrefix(self.vec, cval) ) def setFromOptions(self): CHKERR( VecSetFromOptions(self.vec) ) def setUp(self): CHKERR( VecSetUp(self.vec) ) return self def setOption(self, option, flag): CHKERR( VecSetOption(self.vec, option, flag) ) def getType(self): cdef PetscVecType cval = NULL CHKERR( VecGetType(self.vec, &cval) ) return bytes2str(cval) def getSize(self): cdef PetscInt N = 0 CHKERR( VecGetSize(self.vec, &N) ) return toInt(N) def getLocalSize(self): cdef PetscInt n = 0 CHKERR( VecGetLocalSize(self.vec, &n) ) return toInt(n) def getSizes(self): cdef PetscInt n = 0, N = 0 CHKERR( VecGetLocalSize(self.vec, &n) ) CHKERR( VecGetSize(self.vec, &N) ) return (toInt(n), toInt(N)) def setBlockSize(self, bsize): cdef PetscInt bs = asInt(bsize) CHKERR( VecSetBlockSize(self.vec, bs) ) def getBlockSize(self): cdef PetscInt bs=0 CHKERR( VecGetBlockSize(self.vec, &bs) ) return toInt(bs) def getOwnershipRange(self): cdef PetscInt low=0, high=0 CHKERR( VecGetOwnershipRange(self.vec, &low, &high) ) return (toInt(low), toInt(high)) def getOwnershipRanges(self): cdef const PetscInt *rng = NULL CHKERR( VecGetOwnershipRanges(self.vec, &rng) ) cdef MPI_Comm comm = MPI_COMM_NULL CHKERR( PetscObjectGetComm(self.vec, &comm) ) cdef int size = -1 CHKERR( MPI_Comm_size(comm, &size) ) return array_i(size+1, rng) def createLocalVector(self): lvec = Vec() CHKERR( VecCreateLocalVector(self.vec, &lvec.vec) ) return lvec def getLocalVector(self, Vec lvec, readonly=False): if readonly: CHKERR( VecGetLocalVectorRead(self.vec, lvec.vec) ) else: CHKERR( VecGetLocalVector(self.vec, lvec.vec) ) def restoreLocalVector(self, Vec lvec, readonly=False): if readonly: CHKERR( VecRestoreLocalVectorRead(self.vec, lvec.vec) ) else: CHKERR( VecRestoreLocalVector(self.vec, lvec.vec) ) def getBuffer(self, readonly=False): if readonly: return vec_getbuffer_r(self) else: return vec_getbuffer_w(self) def getArray(self, readonly=False): if readonly: return vec_getarray_r(self) else: return vec_getarray_w(self) def setArray(self, array): vec_setarray(self, array) def placeArray(self, array): cdef PetscInt nv=0 cdef PetscInt na=0 cdef PetscScalar *a = NULL CHKERR( VecGetLocalSize(self.vec, &nv) ) array = oarray_s(array, &na, &a) if (na != nv): raise ValueError( "cannot place input array size %d, vector size %d" % (toInt(na), toInt(nv))) CHKERR( VecPlaceArray(self.vec, a) ) self.set_attr('__placed_array__', array) def resetArray(self, force=False): cdef object array = None array = self.get_attr('__placed_array__') if array is None and not force: return None CHKERR( VecResetArray(self.vec) ) self.set_attr('__placed_array__', None) return array def bindToCPU(self, flg): """ If *flg* is *True*, all subsequent operations of *self* would be performed on CPU. If *flg* is *False*, all subsequent operations of *self* would be offloaded to the device, provided that the VecType is capable of offloading. :arg flg: An instance of :class:`bool`. """ cdef PetscBool bindFlg = asBool(flg) CHKERR( VecBindToCPU(self.vec, bindFlg) ) def boundToCPU(self): cdef PetscBool flg = PETSC_TRUE CHKERR( VecBoundToCPU(self.vec, &flg) ) return toBool(flg) def getCUDAHandle(self, mode='rw'): cdef PetscScalar *hdl = NULL cdef const char *m = NULL if mode is not None: mode = str2bytes(mode, &m) if m == NULL or (m[0] == c'r' and m[1] == c'w'): CHKERR( VecCUDAGetArray(self.vec, &hdl) ) elif m[0] == c'r': CHKERR( VecCUDAGetArrayRead(self.vec, &hdl) ) elif m[0] == c'w': CHKERR( VecCUDAGetArrayWrite(self.vec, &hdl) ) else: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") return hdl def restoreCUDAHandle(self, handle, mode='rw'): cdef PetscScalar *hdl = (handle) cdef const char *m = NULL if mode is not None: mode = str2bytes(mode, &m) if m == NULL or (m[0] == c'r' and m[1] == c'w'): CHKERR( VecCUDARestoreArray(self.vec, &hdl) ) elif m[0] == c'r': CHKERR( VecCUDARestoreArrayRead(self.vec, &hdl) ) elif m[0] == c'w': CHKERR( VecCUDARestoreArrayWrite(self.vec, &hdl) ) else: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") def getHIPHandle(self, mode='rw'): cdef PetscScalar *hdl = NULL cdef const char *m = NULL if mode is not None: mode = str2bytes(mode, &m) if m == NULL or (m[0] == c'r' and m[1] == c'w'): CHKERR( VecHIPGetArray(self.vec, &hdl) ) elif m[0] == c'r': CHKERR( VecHIPGetArrayRead(self.vec, &hdl) ) elif m[0] == c'w': CHKERR( VecHIPGetArrayWrite(self.vec, &hdl) ) else: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") return hdl def restoreHIPHandle(self, handle, mode='rw'): cdef PetscScalar *hdl = (handle) cdef const char *m = NULL if mode is not None: mode = str2bytes(mode, &m) if m == NULL or (m[0] == c'r' and m[1] == c'w'): CHKERR( VecHIPRestoreArray(self.vec, &hdl) ) elif m[0] == c'r': CHKERR( VecHIPRestoreArrayRead(self.vec, &hdl) ) elif m[0] == c'w': CHKERR( VecHIPRestoreArrayWrite(self.vec, &hdl) ) else: raise ValueError("Invalid mode: expected 'rw', 'r', or 'w'") def getOffloadMask(self): """ Returns :class:`int` of the Vec's PetscOffloadMask enum value. """ cdef PetscOffloadMask mask CHKERR( VecGetOffloadMask(self.vec, &mask) ) return mask def getCLContextHandle(self): """ Returns a Vec's CL Context as :class:`int`. To interface with :mod:`pyopencl` refer :meth:`pyopencl.Context.from_int_ptr` """ cdef Py_uintptr_t ctxhdl = 0 CHKERR( VecViennaCLGetCLContext(self.vec, &ctxhdl) ) return ctxhdl def getCLQueueHandle(self): """ Returns a Vec's CL Context as :class:`int`. To interface with :mod:`pyopencl` refer :meth:`pyopencl.Context.from_int_ptr` """ cdef Py_uintptr_t queuehdl = 0 CHKERR( VecViennaCLGetCLQueue(self.vec, &queuehdl) ) return queuehdl def getCLMemHandle(self, mode='rw'): """ Returns a Vec's CL buffer as :class:`int`. To interface with :mod:`pyopencl` refer :meth:`pyopencl.MemoryObject.from_int_ptr`. :arg mode: An instance of class:`str` denoting the intended access usage to the CL buffer. Can be one of 'r'(read-only), 'w' (write-only) or 'rw' (read-write). See also :meth:`Vec.restoreCLMemHandle`. """ cdef Py_uintptr_t memhdl = 0 cdef const char *m = NULL mode = str2bytes(mode, &m) if m == NULL or (m[0] == c'r' and m[1] == c'w'): CHKERR( VecViennaCLGetCLMem(self.vec, &memhdl) ) elif m[0] == c'r': CHKERR( VecViennaCLGetCLMemRead(self.vec, &memhdl) ) elif m[0] == c'w': CHKERR( VecViennaCLGetCLMemWrite(self.vec, &memhdl) ) else: raise ValueError("Invalid mode: expected 'r', 'w' or 'rw'") return memhdl def restoreCLMemHandle(self): """ To be called after accessing a Vec's cl_mem in 'w' or 'rw' modes. See also :meth:`Vec.getCLMemHandle`. """ CHKERR( VecViennaCLRestoreCLMemWrite(self.vec) ) def duplicate(self, array=None): cdef Vec vec = type(self)() CHKERR( VecDuplicate(self.vec, &vec.vec) ) # duplicate tensor context cdef object ctx0 = self.get_attr('__dltensor_ctx__') if ctx0 is not None: vec.set_attr('__dltensor_ctx__', ctx0) if array is not None: vec_setarray(vec, array) return vec def copy(self, Vec result=None): if result is None: result = type(self)() if result.vec == NULL: CHKERR( VecDuplicate(self.vec, &result.vec) ) CHKERR( VecCopy(self.vec, result.vec) ) return result def chop(self, tol): cdef PetscReal rval = asReal(tol) CHKERR( VecChop(self.vec, rval) ) def load(self, Viewer viewer): cdef MPI_Comm comm = MPI_COMM_NULL cdef PetscObject obj = (viewer.vwr) if self.vec == NULL: CHKERR( PetscObjectGetComm(obj, &comm) ) CHKERR( VecCreate(comm, &self.vec) ) CHKERR( VecLoad(self.vec, viewer.vwr) ) return self def equal(self, Vec vec): cdef PetscBool flag = PETSC_FALSE CHKERR( VecEqual(self.vec, vec.vec, &flag) ) return toBool(flag) def dot(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecDot(self.vec, vec.vec, &sval) ) return toScalar(sval) def dotBegin(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecDotBegin(self.vec, vec.vec, &sval) ) def dotEnd(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecDotEnd(self.vec, vec.vec, &sval) ) return toScalar(sval) def tDot(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecTDot(self.vec, vec.vec, &sval) ) return toScalar(sval) def tDotBegin(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecTDotBegin(self.vec, vec.vec, &sval) ) def tDotEnd(self, Vec vec): cdef PetscScalar sval = 0 CHKERR( VecTDotEnd(self.vec, vec.vec, &sval) ) return toScalar(sval) def mDot(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def mDotBegin(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def mDotEnd(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def mtDot(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def mtDotBegin(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def mtDotEnd(self, vecs, out=None): self; vecs; out; # unused raise NotImplementedError def norm(self, norm_type=None): cdef PetscNormType norm_1_2 = PETSC_NORM_1_AND_2 cdef PetscNormType ntype = PETSC_NORM_2 if norm_type is not None: ntype = norm_type cdef PetscReal rval[2] CHKERR( VecNorm(self.vec, ntype, rval) ) if ntype != norm_1_2: return toReal(rval[0]) else: return (toReal(rval[0]), toReal(rval[1])) def normBegin(self, norm_type=None): cdef PetscNormType ntype = PETSC_NORM_2 if norm_type is not None: ntype = norm_type cdef PetscReal dummy[2] CHKERR( VecNormBegin(self.vec, ntype, dummy) ) def normEnd(self, norm_type=None): cdef PetscNormType norm_1_2 = PETSC_NORM_1_AND_2 cdef PetscNormType ntype = PETSC_NORM_2 if norm_type is not None: ntype = norm_type cdef PetscReal rval[2] CHKERR( VecNormEnd(self.vec, ntype, rval) ) if ntype != norm_1_2: return toReal(rval[0]) else: return (toReal(rval[0]), toReal(rval[1])) def sum(self): cdef PetscScalar sval = 0 CHKERR( VecSum(self.vec, &sval) ) return toScalar(sval) def min(self): cdef PetscInt ival = 0 cdef PetscReal rval = 0 CHKERR( VecMin(self.vec, &ival, &rval) ) return (toInt(ival), toReal(rval)) def max(self): cdef PetscInt ival = 0 cdef PetscReal rval = 0 CHKERR( VecMax(self.vec, &ival, &rval) ) return (toInt(ival), toReal(rval)) def normalize(self): cdef PetscReal rval = 0 CHKERR( VecNormalize(self.vec, &rval) ) return toReal(rval) def reciprocal(self): CHKERR( VecReciprocal(self.vec) ) def exp(self): CHKERR( VecExp(self.vec) ) def log(self): CHKERR( VecLog(self.vec) ) def sqrtabs(self): CHKERR( VecSqrtAbs(self.vec) ) def abs(self): CHKERR( VecAbs(self.vec) ) def conjugate(self): CHKERR( VecConjugate(self.vec) ) def setRandom(self, Random random=None): cdef PetscRandom rnd = NULL if random is not None: rnd = random.rnd CHKERR( VecSetRandom(self.vec, rnd) ) def permute(self, IS order, invert=False): cdef PetscBool cinvert = PETSC_FALSE if invert: cinvert = PETSC_TRUE CHKERR( VecPermute(self.vec, order.iset, cinvert) ) def zeroEntries(self): CHKERR( VecZeroEntries(self.vec) ) def set(self, alpha): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecSet(self.vec, sval) ) def isset(self, IS idx, alpha): cdef PetscScalar aval = asScalar(alpha) CHKERR( VecISSet(self.vec, idx.iset, aval) ) def scale(self, alpha): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecScale(self.vec, sval) ) def shift(self, alpha): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecShift(self.vec, sval) ) def chop(self, tol): cdef PetscReal rval = asReal(tol) CHKERR( VecChop(self.vec, rval) ) def swap(self, Vec vec): CHKERR( VecSwap(self.vec, vec.vec) ) def axpy(self, alpha, Vec x): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecAXPY(self.vec, sval, x.vec) ) def isaxpy(self, IS idx, alpha, Vec x): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecISAXPY(self.vec, idx.iset, sval, x.vec) ) def aypx(self, alpha, Vec x): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecAYPX(self.vec, sval, x.vec) ) def axpby(self, alpha, beta, Vec y): cdef PetscScalar sval1 = asScalar(alpha) cdef PetscScalar sval2 = asScalar(beta) CHKERR( VecAXPBY(self.vec, sval1, sval2, y.vec) ) def waxpy(self, alpha, Vec x, Vec y): cdef PetscScalar sval = asScalar(alpha) CHKERR( VecWAXPY(self.vec, sval, x.vec, y.vec) ) def maxpy(self, alphas, vecs): cdef PetscInt n = 0 cdef PetscScalar *a = NULL cdef PetscVec *v = NULL cdef object tmp1 = iarray_s(alphas, &n, &a) cdef object tmp2 = oarray_p(empty_p(n),NULL, &v) assert n == len(vecs) cdef Py_ssize_t i=0 for i from 0 <= i < n: v[i] = ((vecs[i])).vec CHKERR( VecMAXPY(self.vec, n, a, v) ) def pointwiseMult(self, Vec x, Vec y): CHKERR( VecPointwiseMult(self.vec, x.vec, y.vec) ) def pointwiseDivide(self, Vec x, Vec y): CHKERR( VecPointwiseDivide(self.vec, x.vec, y.vec) ) def pointwiseMin(self, Vec x, Vec y): CHKERR( VecPointwiseMin(self.vec, x.vec, y.vec) ) def pointwiseMax(self, Vec x, Vec y): CHKERR( VecPointwiseMax(self.vec, x.vec, y.vec) ) def pointwiseMaxAbs(self, Vec x, Vec y): CHKERR( VecPointwiseMaxAbs(self.vec, x.vec, y.vec) ) def maxPointwiseDivide(self, Vec vec): cdef PetscReal rval = 0 CHKERR( VecMaxPointwiseDivide(self.vec, vec.vec, &rval) ) return toReal(rval) def getValue(self, index): cdef PetscInt ival = asInt(index) cdef PetscScalar sval = 0 CHKERR( VecGetValues(self.vec, 1, &ival, &sval) ) return toScalar(sval) def getValues(self, indices, values=None): return vecgetvalues(self.vec, indices, values) def getValuesStagStencil(self, indices, values=None): raise NotImplementedError('getValuesStagStencil not yet implemented in petsc4py') def setValue(self, index, value, addv=None): cdef PetscInt ival = asInt(index) cdef PetscScalar sval = asScalar(value) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( VecSetValues(self.vec, 1, &ival, &sval, caddv) ) def setValues(self, indices, values, addv=None): vecsetvalues(self.vec, indices, values, addv, 0, 0) def setValuesBlocked(self, indices, values, addv=None): vecsetvalues(self.vec, indices, values, addv, 1, 0) def setValuesStagStencil(self, indices, values, addv=None): raise NotImplementedError('setValuesStagStencil not yet implemented in petsc4py') def setLGMap(self, LGMap lgmap): CHKERR( VecSetLocalToGlobalMapping(self.vec, lgmap.lgm) ) def getLGMap(self): cdef LGMap cmap = LGMap() CHKERR( VecGetLocalToGlobalMapping(self.vec, &cmap.lgm) ) PetscINCREF(cmap.obj) return cmap def setValueLocal(self, index, value, addv=None): cdef PetscInt ival = asInt(index) cdef PetscScalar sval = asScalar(value) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( VecSetValuesLocal(self.vec, 1, &ival, &sval, caddv) ) def setValuesLocal(self, indices, values, addv=None): vecsetvalues(self.vec, indices, values, addv, 0, 1) def setValuesBlockedLocal(self, indices, values, addv=None): vecsetvalues(self.vec, indices, values, addv, 1, 1) def assemblyBegin(self): CHKERR( VecAssemblyBegin(self.vec) ) def assemblyEnd(self): CHKERR( VecAssemblyEnd(self.vec) ) def assemble(self): CHKERR( VecAssemblyBegin(self.vec) ) CHKERR( VecAssemblyEnd(self.vec) ) # --- methods for strided vectors --- def strideScale(self, field, alpha): cdef PetscInt ival = asInt(field) cdef PetscScalar sval = asScalar(alpha) CHKERR( VecStrideScale(self.vec, ival, sval) ) def strideSum(self, field): cdef PetscInt ival = asInt(field) cdef PetscScalar sval = 0 CHKERR( VecStrideSum(self.vec, ival, &sval) ) return toScalar(sval) def strideMin(self, field): cdef PetscInt ival1 = asInt(field) cdef PetscInt ival2 = 0 cdef PetscReal rval = 0 CHKERR( VecStrideMin(self.vec, ival1, &ival2, &rval) ) return (toInt(ival2), toReal(rval)) def strideMax(self, field): cdef PetscInt ival1 = asInt(field) cdef PetscInt ival2 = 0 cdef PetscReal rval = 0 CHKERR( VecStrideMax(self.vec, ival1, &ival2, &rval) ) return (toInt(ival2), toReal(rval)) def strideNorm(self, field, norm_type=None): cdef PetscInt ival = asInt(field) cdef PetscNormType norm_1_2 = PETSC_NORM_1_AND_2 cdef PetscNormType ntype = PETSC_NORM_2 if norm_type is not None: ntype = norm_type cdef PetscReal rval[2] CHKERR( VecStrideNorm(self.vec, ival, ntype, rval) ) if ntype != norm_1_2: return toReal(rval[0]) else: return (toReal(rval[0]), toReal(rval[1])) def strideScatter(self, field, Vec vec, addv=None): cdef PetscInt ival = asInt(field) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( VecStrideScatter(self.vec, ival, vec.vec, caddv) ) def strideGather(self, field, Vec vec, addv=None): cdef PetscInt ival = asInt(field) cdef PetscInsertMode caddv = insertmode(addv) CHKERR( VecStrideGather(self.vec, ival, vec.vec, caddv) ) # --- methods for vectors with ghost values --- def localForm(self): """ Intended for use in context manager:: with vec.localForm() as lf: use(lf) """ return _Vec_LocalForm(self) def ghostUpdateBegin(self, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecGhostUpdateBegin(self.vec, caddv, csctm) ) def ghostUpdateEnd(self, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecGhostUpdateEnd(self.vec, caddv, csctm) ) def ghostUpdate(self, addv=None, mode=None): cdef PetscInsertMode caddv = insertmode(addv) cdef PetscScatterMode csctm = scattermode(mode) CHKERR( VecGhostUpdateBegin(self.vec, caddv, csctm) ) CHKERR( VecGhostUpdateEnd(self.vec, caddv, csctm) ) def setMPIGhost(self, ghosts): "Alternative to createGhost()" cdef PetscInt ng=0, *ig=NULL ghosts = iarray_i(ghosts, &ng, &ig) CHKERR( VecMPISetGhost(self.vec, ng, ig) ) # def getSubVector(self, IS iset, Vec subvec=None): if subvec is None: subvec = Vec() else: CHKERR( VecDestroy(&subvec.vec) ) CHKERR( VecGetSubVector(self.vec, iset.iset, &subvec.vec) ) return subvec def restoreSubVector(self, IS iset, Vec subvec): CHKERR( VecRestoreSubVector(self.vec, iset.iset, &subvec.vec) ) def getNestSubVecs(self): cdef PetscInt N=0 cdef PetscVec* sx=NULL CHKERR( VecNestGetSubVecs(self.vec, &N, &sx) ) output = [] for i in range(N): pyvec = Vec() pyvec.vec = sx[i] CHKERR( PetscObjectReference( pyvec.vec) ) output.append(pyvec) return output def setNestSubVecs(self, sx, idxm=None): if idxm is None: idxm = range(len(sx)) else: assert len(idxm) == len(sx) cdef PetscInt N = 0 cdef PetscInt* cidxm = NULL idxm = iarray_i(idxm, &N, &cidxm) cdef PetscVec* csx = NULL tmp = oarray_p(empty_p(N), NULL, &csx) for i from 0 <= i < N: csx[i] = (sx[i]).vec CHKERR( VecNestSetSubVecs(self.vec, N, cidxm, csx) ) # def setDM(self, DM dm): CHKERR( VecSetDM(self.vec, dm.dm) ) def getDM(self): cdef DM dm = DM() CHKERR( VecGetDM(self.vec, &dm.dm) ) return dm # property sizes: def __get__(self): return self.getSizes() def __set__(self, value): self.setSizes(value) property size: def __get__(self): return self.getSize() property local_size: def __get__(self): return self.getLocalSize() property block_size: def __get__(self): return self.getBlockSize() property owner_range: def __get__(self): return self.getOwnershipRange() property owner_ranges: def __get__(self): return self.getOwnershipRanges() property buffer_w: "Vec buffer (writable)" def __get__(self): return self.getBuffer() property buffer_r: "Vec buffer (read-only)" def __get__(self): return self.getBuffer(True) property array_w: "Vec array (writable)" def __get__(self): return self.getArray() def __set__(self, value): cdef buf = self.getBuffer() with buf as array: array[:] = value property array_r: "Vec array (read-only)" def __get__(self): return self.getArray(True) property buffer: def __get__(self): return self.buffer_w property array: def __get__(self): return self.array_w def __set__(self, value): self.array_w = value # --- NumPy array interface (legacy) --- property __array_interface__: def __get__(self): cdef buf = self.getBuffer() return buf.__array_interface__ # -------------------------------------------------------------------- del VecType del VecOption # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/Viewer.pyx000066400000000000000000000360401454104047300206550ustar00rootroot00000000000000# -------------------------------------------------------------------- class ViewerType(object): SOCKET = S_(PETSCVIEWERSOCKET) ASCII = S_(PETSCVIEWERASCII) BINARY = S_(PETSCVIEWERBINARY) STRING = S_(PETSCVIEWERSTRING) DRAW = S_(PETSCVIEWERDRAW) VU = S_(PETSCVIEWERVU) MATHEMATICA = S_(PETSCVIEWERMATHEMATICA) HDF5 = S_(PETSCVIEWERHDF5) VTK = S_(PETSCVIEWERVTK) MATLAB = S_(PETSCVIEWERMATLAB) SAWS = S_(PETSCVIEWERSAWS) GLVIS = S_(PETSCVIEWERGLVIS) ADIOS = S_(PETSCVIEWERADIOS) EXODUSII = S_(PETSCVIEWEREXODUSII) class ViewerFormat(object): DEFAULT = PETSC_VIEWER_DEFAULT ASCII_MATLAB = PETSC_VIEWER_ASCII_MATLAB ASCII_MATHEMATICA = PETSC_VIEWER_ASCII_MATHEMATICA ASCII_IMPL = PETSC_VIEWER_ASCII_IMPL ASCII_INFO = PETSC_VIEWER_ASCII_INFO ASCII_INFO_DETAIL = PETSC_VIEWER_ASCII_INFO_DETAIL ASCII_COMMON = PETSC_VIEWER_ASCII_COMMON ASCII_SYMMODU = PETSC_VIEWER_ASCII_SYMMODU ASCII_INDEX = PETSC_VIEWER_ASCII_INDEX ASCII_DENSE = PETSC_VIEWER_ASCII_DENSE ASCII_MATRIXMARKET= PETSC_VIEWER_ASCII_MATRIXMARKET ASCII_VTK = PETSC_VIEWER_ASCII_VTK_DEPRECATED ASCII_VTK_CELL = PETSC_VIEWER_ASCII_VTK_CELL_DEPRECATED ASCII_VTK_COORDS = PETSC_VIEWER_ASCII_VTK_COORDS_DEPRECATED ASCII_PCICE = PETSC_VIEWER_ASCII_PCICE ASCII_PYTHON = PETSC_VIEWER_ASCII_PYTHON ASCII_FACTOR_INFO = PETSC_VIEWER_ASCII_FACTOR_INFO ASCII_LATEX = PETSC_VIEWER_ASCII_LATEX ASCII_XML = PETSC_VIEWER_ASCII_XML ASCII_GLVIS = PETSC_VIEWER_ASCII_GLVIS ASCII_CSV = PETSC_VIEWER_ASCII_CSV DRAW_BASIC = PETSC_VIEWER_DRAW_BASIC DRAW_LG = PETSC_VIEWER_DRAW_LG DRAW_LG_XRANGE = PETSC_VIEWER_DRAW_LG_XRANGE DRAW_CONTOUR = PETSC_VIEWER_DRAW_CONTOUR DRAW_PORTS = PETSC_VIEWER_DRAW_PORTS VTK_VTS = PETSC_VIEWER_VTK_VTS VTK_VTR = PETSC_VIEWER_VTK_VTR VTK_VTU = PETSC_VIEWER_VTK_VTU BINARY_MATLAB = PETSC_VIEWER_BINARY_MATLAB NATIVE = PETSC_VIEWER_NATIVE HDF5_PETSC = PETSC_VIEWER_HDF5_PETSC HDF5_VIZ = PETSC_VIEWER_HDF5_VIZ HDF5_XDMF = PETSC_VIEWER_HDF5_XDMF HDF5_MAT = PETSC_VIEWER_HDF5_MAT NOFORMAT = PETSC_VIEWER_NOFORMAT LOAD_BALANCE = PETSC_VIEWER_LOAD_BALANCE FAILED = PETSC_VIEWER_FAILED class FileMode(object): # native READ = PETSC_FILE_MODE_READ WRITE = PETSC_FILE_MODE_WRITE APPEND = PETSC_FILE_MODE_APPEND UPDATE = PETSC_FILE_MODE_UPDATE APPEND_UPDATE = PETSC_FILE_MODE_APPEND_UPDATE # aliases R, W, A, U = READ, WRITE, APPEND, UPDATE AU = UA = APPEND_UPDATE class DrawSize(object): # native FULL_SIZE = PETSC_DRAW_FULL_SIZE HALF_SIZE = PETSC_DRAW_HALF_SIZE THIRD_SIZE = PETSC_DRAW_THIRD_SIZE QUARTER_SIZE = PETSC_DRAW_QUARTER_SIZE # aliases FULL = FULL_SIZE HALF = HALF_SIZE THIRD = THIRD_SIZE QUARTER = QUARTER_SIZE # -------------------------------------------------------------------- cdef class Viewer(Object): Type = ViewerType Format = ViewerFormat Mode = FileMode Size = DrawSize # def __cinit__(self): self.obj = &self.vwr self.vwr = NULL def __call__(self, Object obj): assert obj.obj != NULL CHKERR( PetscObjectView(obj.obj[0], self.vwr) ) # def view(self, obj=None): if obj is None: CHKERR( PetscViewerView(self.vwr, NULL) ) elif isinstance(obj, Viewer): CHKERR( PetscViewerView(self.vwr, (obj).vwr) ) else: assert (obj).obj != NULL CHKERR( PetscObjectView((obj).obj[0], self.vwr) ) def destroy(self): CHKERR( PetscViewerDestroy(&self.vwr) ) return self def create(self, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr return self def createASCII(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = PETSC_FILE_MODE_WRITE if mode is not None: cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr CHKERR( PetscViewerSetType(self.vwr, PETSCVIEWERASCII) ) CHKERR( PetscViewerFileSetMode(self.vwr, cmode) ) CHKERR( PetscViewerFileSetName(self.vwr, cname) ) return self def createBinary(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerBinaryOpen(ccomm, cname, cmode, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr return self def createMPIIO(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr CHKERR( PetscViewerSetType(self.vwr, PETSCVIEWERBINARY) ) CHKERR( PetscViewerBinarySetUseMPIIO(self.vwr, PETSC_TRUE) ) CHKERR( PetscViewerFileSetMode(self.vwr, cmode) ) CHKERR( PetscViewerFileSetName(self.vwr, cname) ) return self def createVTK(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr CHKERR( PetscViewerSetType(self.vwr, PETSCVIEWERVTK) ) CHKERR( PetscViewerFileSetMode(self.vwr, cmode) ) CHKERR( PetscViewerFileSetName(self.vwr, cname) ) return self def createHDF5(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr CHKERR( PetscViewerSetType(self.vwr, PETSCVIEWERHDF5) ) CHKERR( PetscViewerFileSetMode(self.vwr, cmode) ) CHKERR( PetscViewerFileSetName(self.vwr, cname) ) return self def createDraw(self, display=None, title=None, position=None, size=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cdisplay = NULL cdef const char *ctitle = NULL display = str2bytes(display, &cdisplay) title = str2bytes(title, &ctitle) cdef int x, y, h, w x = y = h = w = PETSC_DECIDE if position not in (None, PETSC_DECIDE): x, y = position if size not in (None, PETSC_DECIDE): try: w, h = size except TypeError: w = h = size cdef PetscViewer newvwr = NULL CHKERR( PetscViewerDrawOpen(ccomm, cdisplay, ctitle, x, y, w, h, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr return self def setType(self, vwr_type): cdef PetscViewerType cval = NULL vwr_type = str2bytes(vwr_type, &cval) CHKERR( PetscViewerSetType(self.vwr, cval) ) def getType(self): cdef PetscViewerType cval = NULL CHKERR( PetscViewerGetType(self.vwr, &cval) ) return bytes2str(cval) def getFormat(self): cdef PetscViewerFormat format = PETSC_VIEWER_DEFAULT CHKERR( PetscViewerGetFormat(self.vwr, &format) ) return format def pushFormat(self, format): CHKERR( PetscViewerPushFormat(self.vwr, format) ) def popFormat(self): CHKERR( PetscViewerPopFormat(self.vwr) ) def getSubViewer(self, comm = None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_SELF) cdef Viewer sub = Viewer() CHKERR( PetscViewerGetSubViewer(self.vwr, ccomm, &sub.vwr) ) return sub def restoreSubViewer(self, Viewer sub): cdef MPI_Comm ccomm = def_Comm(sub.getComm(), PETSC_COMM_SELF) CHKERR( PetscViewerRestoreSubViewer(self.vwr, ccomm, &sub.vwr) ) @classmethod def STDOUT(cls, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Viewer viewer = Viewer() viewer.vwr = PETSC_VIEWER_STDOUT_(ccomm) PetscINCREF(viewer.obj) return viewer @classmethod def STDERR(cls, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Viewer viewer = Viewer() viewer.vwr = PETSC_VIEWER_STDERR_(ccomm) PetscINCREF(viewer.obj) return viewer @classmethod def ASCII(cls, name, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef Viewer viewer = Viewer() CHKERR( PetscViewerASCIIOpen(ccomm, cname, &viewer.vwr) ) return viewer @classmethod def BINARY(cls, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Viewer viewer = Viewer() viewer.vwr = PETSC_VIEWER_BINARY_(ccomm) PetscINCREF(viewer.obj) return viewer @classmethod def DRAW(cls, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef Viewer viewer = Viewer() viewer.vwr = PETSC_VIEWER_DRAW_(ccomm) PetscINCREF(viewer.obj) return viewer # --- ASCII viewers --- def setASCIITab(self, tabs): cdef PetscInt ctabs = asInt(tabs) CHKERR( PetscViewerASCIISetTab(self.vwr, ctabs) ) def getASCIITab(self): cdef PetscInt tabs = 0 CHKERR( PetscViewerASCIIGetTab(self.vwr, &tabs) ) return toInt(tabs) def addASCIITab(self, tabs): cdef PetscInt ctabs = asInt(tabs) CHKERR( PetscViewerASCIIAddTab(self.vwr, ctabs) ) def subtractASCIITab(self, tabs): cdef PetscInt ctabs = asInt(tabs) CHKERR( PetscViewerASCIISubtractTab(self.vwr, ctabs) ) def pushASCIISynchronized(self): CHKERR( PetscViewerASCIIPushSynchronized(self.vwr) ) def popASCIISynchronized(self): CHKERR( PetscViewerASCIIPopSynchronized(self.vwr) ) def pushASCIITab(self): CHKERR( PetscViewerASCIIPushTab(self.vwr) ) def popASCIITab(self): CHKERR( PetscViewerASCIIPopTab(self.vwr) ) def useASCIITabs(self, flag): cdef PetscBool flg = flag CHKERR( PetscViewerASCIIUseTabs(self.vwr, flg) ) def printfASCII(self, msg): cdef const char *cmsg = NULL msg = str2bytes(msg, &cmsg) CHKERR( PetscViewerASCIIPrintf(self.vwr, '%s', cmsg) ) def printfASCIISynchronized(self, msg): cdef const char *cmsg = NULL msg = str2bytes(msg, &cmsg) CHKERR( PetscViewerASCIISynchronizedPrintf(self.vwr, '%s', cmsg) ) # --- methods specific to file viewers --- def flush(self): CHKERR( PetscViewerFlush(self.vwr) ) def setFileMode(self, mode): CHKERR( PetscViewerFileSetMode(self.vwr, filemode(mode)) ) def getFileMode(self): cdef PetscFileMode mode = PETSC_FILE_MODE_READ CHKERR( PetscViewerFileGetMode(self.vwr, &mode) ) return mode def setFileName(self, name): cdef const char *cval = NULL name = str2bytes(name, &cval) CHKERR( PetscViewerFileSetName(self.vwr, cval) ) def getFileName(self): cdef const char *cval = NULL CHKERR( PetscViewerFileGetName(self.vwr, &cval) ) return bytes2str(cval) # --- methods specific to draw viewers --- def setDrawInfo(self, display=None, title=None, position=None, size=None): cdef const char *cdisplay = NULL cdef const char *ctitle = NULL display = str2bytes(display, &cdisplay) title = str2bytes(title, &ctitle) cdef int x, y, h, w x = y = h = w = PETSC_DECIDE if position not in (None, PETSC_DECIDE): x, y = position if size not in (None, PETSC_DECIDE): try: w, h = size except TypeError: w = h = size CHKERR( PetscViewerDrawSetInfo(self.vwr, cdisplay, ctitle, x, y, w, h) ) def clearDraw(self): CHKERR( PetscViewerDrawClear(self.vwr) ) # -------------------------------------------------------------------- cdef class ViewerHDF5(Viewer): def create(self, name, mode=None, comm=None): cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) cdef const char *cname = NULL name = str2bytes(name, &cname) cdef PetscFileMode cmode = filemode(mode) cdef PetscViewer newvwr = NULL CHKERR( PetscViewerCreate(ccomm, &newvwr) ) PetscCLEAR(self.obj); self.vwr = newvwr CHKERR( PetscViewerSetType(self.vwr, PETSCVIEWERHDF5) ) CHKERR( PetscViewerFileSetMode(self.vwr, cmode) ) CHKERR( PetscViewerFileSetName(self.vwr, cname) ) return self def pushTimestepping(self): CHKERR( PetscViewerHDF5PushTimestepping(self.vwr) ) def popTimestepping(self): CHKERR( PetscViewerHDF5PopTimestepping(self.vwr) ) def getTimestep(self): cdef PetscInt ctimestep = 0 CHKERR( PetscViewerHDF5GetTimestep(self.vwr, &ctimestep) ) return toInt(ctimestep) def setTimestep(self, timestep): CHKERR( PetscViewerHDF5SetTimestep(self.vwr, asInt(timestep)) ) def incrementTimestep(self): CHKERR( PetscViewerHDF5IncrementTimestep(self.vwr) ) def pushGroup(self, group): cdef const char *cgroup = NULL group = str2bytes(group, &cgroup) CHKERR( PetscViewerHDF5PushGroup(self.vwr, cgroup) ) def popGroup(self): CHKERR( PetscViewerHDF5PopGroup(self.vwr) ) def getGroup(self): cdef char *cgroup = NULL CHKERR( PetscViewerHDF5GetGroup(self.vwr, NULL, &cgroup) ) group = bytes2str(cgroup) CHKERR( PetscFree(cgroup) ) return group # -------------------------------------------------------------------- del ViewerType del ViewerFormat del FileMode del DrawSize # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/arraynpy.pxi000066400000000000000000000166751454104047300212550ustar00rootroot00000000000000# -------------------------------------------------------------------- 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 # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/cyclicgc.pxi000066400000000000000000000053371454104047300211610ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: int printf(char *, ...) cdef extern from "Python.h": ctypedef struct PyObject ctypedef struct PyTypeObject ctypedef int visitproc(PyObject *, void *) ctypedef int traverseproc(PyObject *, visitproc, void *) ctypedef int inquiry(PyObject *) ctypedef struct PyTypeObject: char* tp_name traverseproc tp_traverse inquiry tp_clear PyTypeObject *Py_TYPE(PyObject *) cdef extern from "" nogil: PetscErrorCode PetscGarbageCleanup(MPI_Comm) PetscErrorCode PetscGarbageView(MPI_Comm,PetscViewer); cdef int tp_traverse(PyObject *o, visitproc visit, void *arg): ## printf("%s.tp_traverse(%p)\n", Py_TYPE(o).tp_name, o) cdef PetscObject p = (o).obj[0] if p == NULL: return 0 cdef PyObject *d = p.python_context if d == NULL: return 0 return visit(d, arg) cdef int tp_clear(PyObject *o): ## printf("%s.tp_clear(%p)\n", Py_TYPE(o).tp_name, o) cdef PetscObject *p = (o).obj PetscDEALLOC(p) return 0 cdef inline void TypeEnableGC(PyTypeObject *t): ## printf("%s: enforcing GC support\n", t.tp_name) t.tp_traverse = tp_traverse t.tp_clear = tp_clear def garbage_cleanup(comm=None): """Cleans up unused PETSc objects on the communicator `comm`. If no communicator is provided first clean up on PETSC_COMM_WORLD, then clean up on PETSC_COMM_SELF. Optional argument `comm=None`. No return value. """ if not (PetscInitializeCalled): return if (PetscFinalizeCalled): return cdef MPI_Comm ccomm if comm is None: ccomm = GetComm(COMM_WORLD, MPI_COMM_NULL) CHKERR( PetscGarbageCleanup(ccomm) ) ccomm = GetComm(COMM_SELF, MPI_COMM_NULL) CHKERR( PetscGarbageCleanup(ccomm) ) else: ccomm = GetComm(comm, MPI_COMM_NULL) if ccomm == MPI_COMM_NULL: raise ValueError("null communicator") CHKERR( PetscGarbageCleanup(ccomm) ) def garbage_view(comm=None): """Prints out summary of the unused PETSc objects on each rank of the communicator `comm`. If no communicator is provided then PETSC_COMM_WORLD is used. Optional argument `comm=None`. No return value. """ if not (PetscInitializeCalled): return if (PetscFinalizeCalled): return cdef MPI_Comm ccomm if comm is None: comm = COMM_WORLD ccomm = GetComm(comm, MPI_COMM_NULL) if ccomm == MPI_COMM_NULL: raise ValueError("null communicator") CHKERR( PetscGarbageView(ccomm, NULL) ) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/dlpack.pxi000066400000000000000000000045041454104047300206320ustar00rootroot00000000000000# DLPack interface cdef extern from "Python.h": ctypedef void (*PyCapsule_Destructor)(object) bint PyCapsule_IsValid(object, const char*) void* PyCapsule_GetPointer(object, const char*) except? NULL int PyCapsule_SetName(object, const char*) except -1 object PyCapsule_New(void*, const char*, PyCapsule_Destructor) int PyCapsule_CheckExact(object) cdef extern from "" nogil: ctypedef signed long int64_t ctypedef unsigned long long uint64_t ctypedef unsigned char uint8_t ctypedef unsigned short uint16_t void free(void* ptr) void* malloc(size_t size) cdef struct DLDataType: uint8_t code uint8_t bits uint16_t lanes cdef enum PetscDLDeviceType: kDLCPU = 1 kDLCUDA = 2 kDLCUDAHost = 3 #kDLOpenCL = 4 #kDLVulkan = 7 #kDLMetal = 8 #kDLVPI = 9 kDLROCM = 10 kDLROCMHost = 11 #kDLExtDev = 12 kDLCUDAManaged = 13 #kDLOneAPI = 14 ctypedef struct DLContext: PetscDLDeviceType device_type int device_id cdef enum DLDataTypeCode: kDLInt = 0 kDLUInt = 1 kDLFloat = 2 cdef struct DLTensor: void* data DLContext ctx int ndim DLDataType dtype int64_t* shape int64_t* strides uint64_t byte_offset ctypedef int (*dlpack_manager_del_obj)(void*) nogil cdef struct DLManagedTensor: DLTensor dl_tensor void* manager_ctx void (*manager_deleter)(DLManagedTensor*) nogil dlpack_manager_del_obj del_obj cdef void pycapsule_deleter(object dltensor): cdef DLManagedTensor* dlm_tensor = NULL try: dlm_tensor = PyCapsule_GetPointer(dltensor, 'used_dltensor') return # we do not call a used capsule's deleter except Exception: dlm_tensor = PyCapsule_GetPointer(dltensor, 'dltensor') manager_deleter(dlm_tensor) cdef void manager_deleter(DLManagedTensor* tensor) nogil: if tensor.manager_ctx is NULL: return free(tensor.dl_tensor.shape) if tensor.del_obj is not NULL: tensor.del_obj(&tensor.manager_ctx) free(tensor) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/libpetsc4py.pyx000066400000000000000000003052471454104047300216660ustar00rootroot00000000000000#cython: cdivision=True #cython: binding=False #cython: auto_pickle=False #cython: autotestdict=False #cython: warn.multiple_declarators=False # -------------------------------------------------------------------- cdef extern from "Python.h": ctypedef struct PyObject void Py_INCREF(PyObject*) void Py_DECREF(PyObject*) void Py_CLEAR(PyObject*) object PyModule_New(const char[]) bint PyModule_Check(object) object PyImport_Import(object) # -------------------------------------------------------------------- cdef extern from * nogil: ctypedef struct _p_PetscOptionItems ctypedef _p_PetscOptionItems* PetscOptionItems PetscErrorCode PetscOptionsString(char[],char[],char[],char[],char[],size_t,PetscBool*) cdef extern from * nogil: # custom.h PetscErrorCode PetscObjectComposedDataRegisterPy(PetscInt*) PetscErrorCode PetscObjectComposedDataGetIntPy(PetscObject,PetscInt,PetscInt*,PetscBool*) PetscErrorCode PetscObjectComposedDataSetIntPy(PetscObject,PetscInt,PetscInt) # -------------------------------------------------------------------- cdef char *FUNCT = NULL cdef char *fstack[1024] cdef int istack = 0 cdef inline void FunctionBegin(char name[]) nogil: global istack, fstack, FUNCT FUNCT = name fstack[istack] = FUNCT istack += 1 if istack >= 1024: istack = 0 return cdef inline PetscErrorCode FunctionEnd() nogil: global istack, fstack, FUNCT FUNCT = NULL istack -= 1 if istack < 0: istack = 1024 FUNCT = fstack[istack] return PETSC_SUCCESS cdef PetscErrorCode PetscSETERR(PetscErrorCode ierr,char msg[]) nogil: global istack, fstack istack = 0 fstack[istack] = NULL; return PetscERROR(PETSC_COMM_SELF,FUNCT,ierr, PETSC_ERROR_INITIAL, msg, NULL) cdef PetscErrorCode UNSUPPORTED(char msg[]) nogil: return PetscERROR(PETSC_COMM_SELF,FUNCT,PETSC_ERR_USER, PETSC_ERROR_INITIAL,b"method %s()",msg) # -------------------------------------------------------------------- cdef inline PetscInt getRef(void *pobj) nogil: cdef PetscObject obj = pobj if obj == NULL: return 0 else: return obj.refct cdef inline void addRef(void *pobj) nogil: cdef PetscObject obj = pobj if obj != NULL: obj.refct += 1 cdef inline void delRef(void *pobj) nogil: cdef PetscObject obj = pobj if obj != NULL: obj.refct -= 1 cdef inline PetscObject newRef(void *pobj) nogil: cdef PetscObject obj = pobj cdef int ierr = 0 if obj != NULL: ierr = PetscObjectReference(obj) if ierr: return NULL # XXX warning! return obj cdef inline const char* getPrefix(void *pobj) nogil: cdef PetscObject obj = pobj if obj == NULL: return NULL return obj.prefix cdef inline int getCommSize(void *pobj) nogil: cdef PetscObject obj = pobj if obj == NULL: return 0 cdef int size = 0 MPI_Comm_size(obj.comm, &size) return size cdef inline Viewer Viewer_(PetscViewer p): cdef Viewer ob = Viewer.__new__(Viewer) ob.obj[0] = newRef(p) return ob cdef inline IS IS_(PetscIS p): cdef IS ob = IS.__new__(IS) ob.obj[0] = newRef(p) return ob cdef inline Vec Vec_(PetscVec p): cdef Vec ob = Vec.__new__(Vec) ob.obj[0] = newRef(p) return ob cdef inline Mat Mat_(PetscMat p): cdef Mat ob = Mat.__new__(Mat) ob.obj[0] = newRef(p) return ob cdef inline PC PC_(PetscPC p): cdef PC ob = PC.__new__(PC) ob.obj[0] = newRef(p) return ob cdef inline KSP KSP_(PetscKSP p): cdef KSP ob = KSP.__new__(KSP) ob.obj[0] = newRef(p) return ob cdef inline SNES SNES_(PetscSNES p): cdef SNES ob = SNES.__new__(SNES) ob.obj[0] = newRef(p) return ob cdef inline TS TS_(PetscTS p): cdef TS ob = TS.__new__(TS) ob.obj[0] = newRef(p) return ob cdef inline TAO TAO_(PetscTAO p): cdef TAO ob = TAO.__new__(TAO) ob.obj[0] = newRef(p) return ob # -------------------------------------------------------------------- cdef object parse_url(object url): path, name = url.rsplit(":", 1) return (path, name) cdef dict module_cache = {} cdef object load_module(object path): if path in module_cache: return module_cache[path] module = PyModule_New("__petsc__") module.__file__ = path module.__package__ = None module_cache[path] = module try: with open(path, 'r') as source: code = compile(source.read(), path, 'exec') exec(code, module.__dict__) except: del module_cache[path] raise return module # ----------------------------------------------------------------------------- @cython.internal cdef class _PyObj: cdef object self cdef bytes name def __getattr__(self, attr): return getattr(self.self, attr, None) cdef int setcontext(self, void *ctx, Object base) except -1: # if ctx == self.self: return 0 # cdef object destroy = self.destroy if destroy is not None: destroy(base) destroy = None # if ctx == NULL: self.self = None self.name = None return 0 # self.self = ctx self.name = None cdef object create = self.create if create is not None: create(base) create = None return 0 cdef int getcontext(self, void **ctx) except -1: if ctx == NULL: return 0 if self.self is not None: ctx[0] = self.self else: ctx[0] = NULL return 0 cdef int setname(self, char name[]) except -1: if name != NULL and name[0] != 0: self.name = name else: self.name = None return 0 cdef char* getname(self) except? NULL: if self.self is None: return NULL if self.name is not None: return self.name cdef ctx = self.self cdef name = None if PyModule_Check(ctx): name = getattr(ctx, '__name__', None) else: modname = getattr(ctx, '__module__', None) clsname = None cls = getattr(ctx, '__class__', None) if cls: clsname = getattr(cls, '__name__', None) if not modname: modname = getattr(cls, '__module__', None) if modname and clsname: name = modname + '.' + clsname elif clsname: name = clsname elif modname: name = modname if name is not None: self.name = name.encode() if self.name is not None: return self.name return NULL cdef createcontext(char name_p[]): if name_p == NULL: return None cdef name = bytes2str(name_p) cdef mod, path, modname=None cdef cls, attr, clsname=None # path/to/filename.py:{function|class} if ':' in name: path, attr = parse_url(name) mod = load_module(path) if attr: cls = getattr(mod, attr) return cls() else: return mod # package.module[.{function|class}] if '.' in name: modname, clsname = name.rsplit('.', 1) mod = PyImport_Import(modname) if hasattr(mod, clsname): cls = getattr(mod, clsname) if not PyModule_Check(cls): return cls() # package[.module] mod = PyImport_Import(name) return mod cdef int viewcontext(_PyObj ctx, PetscViewer viewer) except -1: cdef PetscBool isascii = PETSC_FALSE, isstring = PETSC_FALSE CHKERR( PetscObjectTypeCompare(viewer, PETSCVIEWERASCII, &isascii) ) CHKERR( PetscObjectTypeCompare(viewer, PETSCVIEWERSTRING, &isstring) ) cdef char *name = ctx.getname() if isascii: if name == NULL: name = b"unknown/no yet set" CHKERR( PetscViewerASCIIPrintf(viewer, b" Python: %s\n", name) ) if isstring: if name == NULL: name = b"" CHKERR( PetscViewerStringSPrintf(viewer, "%s", name) ) return 0 # -------------------------------------------------------------------- cdef extern from * nogil: struct _MatOps: PetscErrorCode (*destroy)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscMat,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscMat,PetscViewer) except PETSC_ERR_PYTHON PetscErrorCode (*duplicate)(PetscMat,PetscMatDuplicateOption,PetscMat*) except PETSC_ERR_PYTHON PetscErrorCode (*copy)(PetscMat,PetscMat,PetscMatStructure) except PETSC_ERR_PYTHON PetscErrorCode (*createsubmatrix)(PetscMat,PetscIS,PetscIS,PetscMatReuse,PetscMat*) except PETSC_ERR_PYTHON PetscErrorCode (*setoption)(PetscMat,PetscMatOption,PetscBool) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*assemblybegin)(PetscMat,PetscMatAssemblyType) except PETSC_ERR_PYTHON PetscErrorCode (*assemblyend)(PetscMat,PetscMatAssemblyType) except PETSC_ERR_PYTHON PetscErrorCode (*zeroentries)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*zerorowscolumns)(PetscMat,PetscInt,PetscInt*,PetscScalar,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*scale)(PetscMat,PetscScalar) except PETSC_ERR_PYTHON PetscErrorCode (*shift)(PetscMat,PetscScalar) except PETSC_ERR_PYTHON PetscErrorCode (*sor)(PetscMat,PetscVec,PetscReal,PetscMatSORType,PetscReal,PetscInt,PetscInt,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*getvecs)(PetscMat,PetscVec*,PetscVec*) except PETSC_ERR_PYTHON PetscErrorCode (*mult)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multtranspose)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multhermitian"multhermitiantranspose")(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multadd)(PetscMat,PetscVec,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multtransposeadd)(PetscMat,PetscVec,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multhermitianadd"multhermitiantransposeadd")(PetscMat,PetscVec,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*multdiagonalblock)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*solve)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*solvetranspose)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*solveadd)(PetscMat,PetscVec,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*solvetransposeadd)(PetscMat,PetscVec,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*getdiagonal)(PetscMat,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*setdiagonal"diagonalset")(PetscMat,PetscVec,PetscInsertMode) except PETSC_ERR_PYTHON PetscErrorCode (*diagonalscale)(PetscMat,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*missingdiagonal)(PetscMat,PetscBool*,PetscInt*) except PETSC_ERR_PYTHON PetscErrorCode (*norm)(PetscMat,PetscNormType,PetscReal*) except PETSC_ERR_PYTHON PetscErrorCode (*realpart)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*imagpart"imaginarypart")(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*conjugate)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*getdiagonalblock)(PetscMat,PetscMat*) except PETSC_ERR_PYTHON PetscErrorCode (*productsetfromoptions)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*productsymbolic)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*productnumeric)(PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*hasoperation)(PetscMat,PetscMatOperation,PetscBool*) except PETSC_ERR_PYTHON ctypedef _MatOps *MatOps ctypedef struct Mat_Product: void *data struct _p_Mat: void *data MatOps ops PetscBool assembled PetscBool preallocated PetscLayout rmap, cmap Mat_Product *product @cython.internal cdef class _PyMat(_PyObj): pass cdef inline _PyMat PyMat(PetscMat mat): if mat != NULL and mat.data != NULL: return <_PyMat>mat.data else: return _PyMat.__new__(_PyMat) cdef public PetscErrorCode MatPythonGetContext(PetscMat mat, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"MatPythonGetContext") PyMat(mat).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode MatPythonSetContext(PetscMat mat, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"MatPythonSetContext") PyMat(mat).setcontext(ctx, Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatPythonSetType_PYTHON(PetscMat mat, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) MatPythonSetContext(mat, ctx) PyMat(mat).setname(name) return FunctionEnd() cdef PetscErrorCode MatPythonGetType_PYTHON(PetscMat mat, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatPythonGetType_PYTHON") name[0] = PyMat(mat).getname() return FunctionEnd() cdef dict dMatOps = { 3 : 'mult', 4 : 'multAdd', 5 : 'multTranspose', 6 : 'multTransposeAdd', 7 : 'solve', 8 : 'solveAdd', 9 : 'solveTranspose', 10 : 'solveTransposeAdd', 13 : 'SOR', 17 : 'getDiagonal', 18 : 'diagonalScale', 19 : 'norm', 23 : 'zeroEntries', 32 : 'getDiagonalBlock', 34 : 'duplicate', 43 : 'copy', 45 : 'scale', 46 : 'shift', 47 : 'setDiagonal', 48 : 'zeroRowsColumns', 59 : 'createSubMatrix', 88 : 'getVecs', 102 : 'conjugate', 105 : 'realPart', 106 : 'imagPart', 113 : 'missingDiagonal', 119 : 'multDiagonalBlock', 121 : 'multHermitian', 122 : 'multHermitianAdd', } cdef PetscErrorCode MatCreate_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatCreate_Python") # cdef MatOps ops = mat.ops ops.destroy = MatDestroy_Python ops.setfromoptions = MatSetFromOptions_Python ops.view = MatView_Python ops.duplicate = MatDuplicate_Python ops.copy = MatCopy_Python ops.createsubmatrix = MatCreateSubMatrix_Python ops.setoption = MatSetOption_Python ops.setup = MatSetUp_Python ops.assemblybegin = MatAssemblyBegin_Python ops.assemblyend = MatAssemblyEnd_Python ops.zeroentries = MatZeroEntries_Python ops.zerorowscolumns = MatZeroRowsColumns_Python ops.scale = MatScale_Python ops.shift = MatShift_Python ops.getvecs = MatCreateVecs_Python ops.mult = MatMult_Python ops.sor = MatSOR_Python ops.multtranspose = MatMultTranspose_Python ops.multhermitian = MatMultHermitian_Python ops.multadd = MatMultAdd_Python ops.multtransposeadd = MatMultTransposeAdd_Python ops.multhermitianadd = MatMultHermitianAdd_Python ops.multdiagonalblock = MatMultDiagonalBlock_Python ops.solve = MatSolve_Python ops.solvetranspose = MatSolveTranspose_Python ops.solveadd = MatSolveAdd_Python ops.solvetransposeadd = MatSolveTransposeAdd_Python ops.getdiagonal = MatGetDiagonal_Python ops.setdiagonal = MatSetDiagonal_Python ops.diagonalscale = MatDiagonalScale_Python ops.missingdiagonal = MatMissingDiagonal_Python ops.norm = MatNorm_Python ops.realpart = MatRealPart_Python ops.imagpart = MatImagPart_Python ops.conjugate = MatConjugate_Python ops.hasoperation = MatHasOperation_Python ops.getdiagonalblock = MatGetDiagonalBlock_Python ops.productsetfromoptions = MatProductSetFromOptions_Python # mat.assembled = PETSC_TRUE # XXX mat.preallocated = PETSC_FALSE # XXX # CHKERR( PetscObjectComposeFunction( mat, b"MatPythonSetType_C", MatPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( mat, b"MatPythonGetType_C", MatPythonGetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( mat, b"MatProductSetFromOptions_anytype_C", MatProductSetFromOptions_Python) ) CHKERR( PetscObjectChangeTypeName( mat, MATPYTHON) ) # cdef ctx = PyMat(NULL) mat.data = ctx Py_INCREF(mat.data) return FunctionEnd() cdef inline PetscErrorCode MatDestroy_Python_inner( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(mat) MatPythonSetContext(mat, NULL) finally: delRef(mat) Py_DECREF(mat.data) mat.data = NULL return PETSC_SUCCESS cdef PetscErrorCode MatDestroy_Python( PetscMat mat, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"MatDestroy_Python") CHKERR( PetscObjectComposeFunction( mat, b"MatPythonSetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( mat, b"MatPythonGetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( mat, b"MatProductSetFromOptions_anytype_C", NULL) ) CHKERR( PetscObjectChangeTypeName( mat, NULL) ) if Py_IsInitialized(): MatDestroy_Python_inner(mat) return FunctionEnd() cdef PetscErrorCode MatSetFromOptions_Python( PetscMat mat, PetscOptionItems *PetscOptionsObject, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSetFromOptions_Python") # cdef char name[2048], *defval = PyMat(mat).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-mat_python_type", b"Python [package.]module[.{class|function}]", b"MatPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( MatPythonSetType_PYTHON(mat, name) ) # cdef setFromOptions = PyMat(mat).setFromOptions if setFromOptions is not None: setFromOptions(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatView_Python( PetscMat mat, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatView_Python") viewcontext(PyMat(mat), vwr) cdef view = PyMat(mat).view if view is not None: view(Mat_(mat), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode MatDuplicate_Python( PetscMat mat, PetscMatDuplicateOption op, PetscMat* out, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatDuplicate_Python") cdef duplicate = PyMat(mat).duplicate if duplicate is None: return UNSUPPORTED(b"duplicate") cdef Mat m = duplicate(Mat_(mat), op) out[0] = m.mat; m.mat = NULL return FunctionEnd() cdef PetscErrorCode MatCopy_Python( PetscMat mat, PetscMat out, PetscMatStructure op, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatCopy_Python") cdef copy = PyMat(mat).copy if copy is None: return UNSUPPORTED(b"copy") copy(Mat_(mat), Mat_(out), op) return FunctionEnd() cdef PetscErrorCode MatGetDiagonalBlock_Python( PetscMat mat, PetscMat *out ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatGetDiagonalBlock_Python") cdef getDiagonalBlock = PyMat(mat).getDiagonalBlock if getDiagonalBlock is None: try: mat.ops.getdiagonalblock = NULL CHKERR( MatGetDiagonalBlock(mat, out) ) finally: mat.ops.getdiagonalblock = MatGetDiagonalBlock_Python return FunctionEnd() cdef Mat sub = getDiagonalBlock(Mat_(mat)) if sub is not None: out[0] = sub.mat return FunctionEnd() cdef PetscErrorCode MatCreateSubMatrix_Python( PetscMat mat, PetscIS row, PetscIS col, PetscMatReuse op, PetscMat *out, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatCreateSubMatrix_Python") cdef createSubMatrix = PyMat(mat).createSubMatrix if createSubMatrix is None: try: mat.ops.createsubmatrix = NULL CHKERR( MatCreateSubMatrix(mat, row, col, op, out) ) finally: mat.ops.createsubmatrix = MatCreateSubMatrix_Python return FunctionEnd() cdef Mat sub = None if op == MAT_IGNORE_MATRIX: sub = None elif op == MAT_INITIAL_MATRIX: sub = createSubMatrix(Mat_(mat), IS_(row), IS_(col), None) if sub is not None: addRef(sub.mat) elif op == MAT_REUSE_MATRIX: sub = createSubMatrix(Mat_(mat), IS_(row), IS_(col), Mat_(out[0])) if sub is not None: out[0] = sub.mat return FunctionEnd() cdef PetscErrorCode MatSetOption_Python( PetscMat mat, PetscMatOption op, PetscBool flag, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSetOption_Python") cdef setOption = PyMat(mat).setOption if setOption is not None: setOption(Mat_(mat), op, (flag)) return FunctionEnd() cdef PetscErrorCode MatSetUp_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSetUp_Python") cdef PetscInt rbs = -1, cbs = -1 CHKERR( PetscLayoutGetBlockSize(mat.rmap, &rbs) ) CHKERR( PetscLayoutGetBlockSize(mat.cmap, &cbs) ) if rbs == -1: rbs = 1 if cbs == -1: cbs = rbs CHKERR( PetscLayoutSetBlockSize(mat.rmap, rbs) ) CHKERR( PetscLayoutSetBlockSize(mat.cmap, cbs) ) CHKERR( PetscLayoutSetUp(mat.rmap) ) CHKERR( PetscLayoutSetUp(mat.cmap) ) mat.preallocated = PETSC_TRUE # cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PyMat(mat).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(mat), b"-mat_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( MatPythonSetType_PYTHON(mat, name) ) if PyMat(mat).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * MatPythonSetType(mat, \"[package.]module.class\")\n" " * MatSetFromOptions(mat) and pass option " "-mat_python_type [package.]module.class") # cdef setUp = PyMat(mat).setUp if setUp is not None: setUp(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatAssemblyBegin_Python( PetscMat mat, PetscMatAssemblyType at, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatAssemblyBegin_Python") cdef assembly = PyMat(mat).assemblyBegin if assembly is not None: assembly(Mat_(mat), at) return FunctionEnd() cdef PetscErrorCode MatAssemblyEnd_Python( PetscMat mat, PetscMatAssemblyType at, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatAssemblyEnd_Python") cdef assembly = PyMat(mat).assemblyEnd if assembly is None: assembly = PyMat(mat).assembly if assembly is not None: assembly(Mat_(mat), at) return FunctionEnd() cdef PetscErrorCode MatZeroEntries_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatZeroEntries_Python") cdef zeroEntries = PyMat(mat).zeroEntries if zeroEntries is None: return UNSUPPORTED(b"zeroEntries") zeroEntries(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatZeroRowsColumns_Python( PetscMat mat, PetscInt numRows, const PetscInt* rows, PetscScalar diag, PetscVec x, PetscVec b, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatZeroRowsColumns_Python") cdef zeroRowsColumns = PyMat(mat).zeroRowsColumns if zeroRowsColumns is None: return UNSUPPORTED(b"zeroRowsColumns") cdef ndarray pyrows = array_i(numRows, rows) zeroRowsColumns(Mat_(mat), pyrows, toScalar(diag), Vec_(x), Vec_(b)) return FunctionEnd() cdef PetscErrorCode MatScale_Python( PetscMat mat, PetscScalar s, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatScale_Python") cdef scale = PyMat(mat).scale if scale is None: return UNSUPPORTED(b"scale") scale(Mat_(mat), toScalar(s)) return FunctionEnd() cdef PetscErrorCode MatShift_Python( PetscMat mat, PetscScalar s, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatShift_Python") cdef shift = PyMat(mat).shift if shift is None: return UNSUPPORTED(b"shift") shift(Mat_(mat), toScalar(s)) return FunctionEnd() cdef PetscErrorCode MatCreateVecs_Python( PetscMat mat, PetscVec *x, PetscVec *y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatCreateVecs_Python") cdef createVecs = PyMat(mat).createVecs if createVecs is None: try: mat.ops.getvecs = NULL CHKERR( MatCreateVecs(mat, x, y) ) finally: mat.ops.getvecs = MatCreateVecs_Python return FunctionEnd() cdef Vec u, v u, v = createVecs(Mat_(mat)) if x != NULL: x[0] = u.vec u.vec = NULL if y != NULL: y[0] = v.vec v.vec = NULL return FunctionEnd() cdef PetscErrorCode MatMult_Python( PetscMat mat, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMult_Python") cdef mult = PyMat(mat).mult if mult is None: return UNSUPPORTED(b"mult") mult(Mat_(mat), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultTranspose_Python( PetscMat mat, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultTranspose_Python") cdef multTranspose = PyMat(mat).multTranspose if multTranspose is None: try: mat.ops.multtranspose = NULL CHKERR( MatMultTranspose(mat, x, y) ) finally: mat.ops.multtranspose = MatMultTranspose_Python return FunctionEnd() multTranspose(Mat_(mat), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultHermitian_Python( PetscMat mat, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultHermitian_Python") cdef multHermitian = PyMat(mat).multHermitian if multHermitian is None: try: mat.ops.multhermitian = NULL CHKERR( MatMultHermitian(mat, x, y) ) finally: mat.ops.multhermitian = MatMultHermitian_Python return FunctionEnd() multHermitian(Mat_(mat), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultAdd_Python( PetscMat mat, PetscVec x, PetscVec v, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultAdd_Python") cdef multAdd = PyMat(mat).multAdd cdef PetscVec t = NULL if multAdd is None: if v == y: CHKERR( VecDuplicate(y, &t) ) CHKERR( MatMult(mat, x, t) ) CHKERR( VecAXPY(y, 1.0, t) ) CHKERR( VecDestroy(&t) ) else: CHKERR( MatMult(mat, x, y) ) CHKERR( VecAXPY(y, 1.0, v) ) return FunctionEnd() if multAdd is None: return UNSUPPORTED(b"multAdd") multAdd(Mat_(mat), Vec_(x), Vec_(v), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultTransposeAdd_Python( PetscMat mat, PetscVec x, PetscVec v, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultTransposeAdd_Python") cdef multTransposeAdd = PyMat(mat).multTransposeAdd cdef PetscVec t = NULL if multTransposeAdd is None: if v == y: CHKERR( VecDuplicate(y, &t) ) CHKERR( MatMultTranspose(mat, x, t) ) CHKERR( VecAXPY(y, 1.0, t) ) CHKERR( VecDestroy(&t) ) else: CHKERR( MatMultTranspose(mat, x, y) ) CHKERR( VecAXPY(y, 1.0, v) ) return FunctionEnd() if multTransposeAdd is None: return UNSUPPORTED(b"multTransposeAdd") multTransposeAdd(Mat_(mat), Vec_(x), Vec_(v), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultHermitianAdd_Python( PetscMat mat, PetscVec x, PetscVec v, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultHermitianAdd_Python") cdef multHermitianAdd = PyMat(mat).multHermitianAdd if multHermitianAdd is None: try: mat.ops.multhermitianadd = NULL CHKERR( MatMultHermitianAdd(mat, x, v, y) ) finally: mat.ops.multhermitianadd = MatMultHermitianAdd_Python return FunctionEnd() multHermitianAdd(Mat_(mat), Vec_(x), Vec_(v), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatMultDiagonalBlock_Python( PetscMat mat, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMultDiagonalBlock_Python") cdef multDiagonalBlock = PyMat(mat).multDiagonalBlock if multDiagonalBlock is None: return UNSUPPORTED(b"multDiagonalBlock") multDiagonalBlock(Mat_(mat), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode MatSolve_Python( PetscMat mat, PetscVec b, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSolve_Python") cdef solve = PyMat(mat).solve if solve is None: return UNSUPPORTED(b"solve") solve(Mat_(mat), Vec_(b), Vec_(x)) return FunctionEnd() cdef PetscErrorCode MatSolveTranspose_Python( PetscMat mat, PetscVec b, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSolveTranspose_Python") cdef solveTranspose = PyMat(mat).solveTranspose if solveTranspose is None: try: mat.ops.solvetranspose = NULL CHKERR( MatSolveTranspose(mat, b, x) ) finally: mat.ops.solvetranspose = MatSolveTranspose_Python solveTranspose(Mat_(mat), Vec_(b), Vec_(x)) return FunctionEnd() cdef PetscErrorCode MatSolveAdd_Python( PetscMat mat, PetscVec b, PetscVec y, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSolveAdd_Python") cdef solveAdd = PyMat(mat).solveAdd if solveAdd is None: try: mat.ops.solveadd = NULL CHKERR( MatSolveAdd(mat, b, y, x) ) finally: mat.ops.solveadd = MatSolveAdd_Python return FunctionEnd() solveAdd(Mat_(mat), Vec_(b), Vec_(y), Vec_(x)) return FunctionEnd() cdef PetscErrorCode MatSolveTransposeAdd_Python( PetscMat mat, PetscVec b, PetscVec y, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSolveTransposeAdd_Python") cdef solveTransposeAdd = PyMat(mat).solveTransposeAdd if solveTransposeAdd is None: try: mat.ops.solvetransposeadd = NULL CHKERR( MatSolveTransposeAdd(mat, b, y, x) ) finally: mat.ops.solvetransposeadd = MatSolveTransposeAdd_Python return FunctionEnd() solveTransposeAdd(Mat_(mat), Vec_(b), Vec_(y), Vec_(x)) return FunctionEnd() cdef PetscErrorCode MatSOR_Python( PetscMat mat, PetscVec b, PetscReal omega, PetscMatSORType sortype, PetscReal shift, PetscInt its, PetscInt lits, PetscVec x )\ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSOR_Python") cdef SOR = PyMat(mat).SOR if SOR is None: return UNSUPPORTED(b"SOR") SOR(Mat_(mat), Vec_(b), asReal(omega), asInt(sortype), asReal(shift), asInt(its), asInt(lits), Vec_(x)) return FunctionEnd() cdef PetscErrorCode MatGetDiagonal_Python( PetscMat mat, PetscVec v, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatGetDiagonal_Python") cdef getDiagonal = PyMat(mat).getDiagonal if getDiagonal is None: return UNSUPPORTED(b"getDiagonal") getDiagonal(Mat_(mat), Vec_(v)) return FunctionEnd() cdef PetscErrorCode MatSetDiagonal_Python( PetscMat mat, PetscVec v, PetscInsertMode im, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatSetDiagonal_Python") cdef setDiagonal = PyMat(mat).setDiagonal cdef bint addv = True if im == PETSC_ADD_VALUES else False if setDiagonal is None: return UNSUPPORTED(b"setDiagonal") setDiagonal(Mat_(mat), Vec_(v), addv) return FunctionEnd() cdef PetscErrorCode MatDiagonalScale_Python( PetscMat mat, PetscVec l, PetscVec r, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatDiagonalScale_Python") cdef diagonalScale = PyMat(mat).diagonalScale if diagonalScale is None: return UNSUPPORTED(b"diagonalScale") diagonalScale(Mat_(mat), Vec_(l), Vec_(r)) return FunctionEnd() cdef PetscErrorCode MatMissingDiagonal_Python( PetscMat mat, PetscBool *missing, PetscInt *loc ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatMissingDiagonal_Python") cdef missingDiagonal = PyMat(mat).missingDiagonal if missingDiagonal is None: return UNSUPPORTED(b"missingDiagonal") pymissing, pyloc = missingDiagonal(Mat_(mat)) missing[0] = pymissing if loc: loc[0] = asInt(pyloc) return FunctionEnd() cdef PetscErrorCode MatNorm_Python( PetscMat mat, PetscNormType ntype, PetscReal *nrm, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatNorm_Python") cdef norm = PyMat(mat).norm if norm is None: return UNSUPPORTED(b"norm") retval = norm(Mat_(mat), ntype) nrm[0] = retval return FunctionEnd() cdef PetscErrorCode MatRealPart_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatRealPart_Python") cdef realPart = PyMat(mat).realPart if realPart is None: return UNSUPPORTED(b"realPart") realPart(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatImagPart_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatImagPart_Python") cdef imagPart = PyMat(mat).imagPart if imagPart is None: return UNSUPPORTED(b"imagPart") imagPart(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatConjugate_Python( PetscMat mat, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatConjugate_Python") cdef conjugate = PyMat(mat).conjugate if conjugate is None: return UNSUPPORTED(b"conjugate") conjugate(Mat_(mat)) return FunctionEnd() cdef PetscErrorCode MatHasOperation_Python( PetscMat mat, PetscMatOperation op, PetscBool *flag ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatHasOperation_Python") flag[0] = PETSC_FALSE cdef long i = op global dMatOps name = dMatOps.get(i, None) cdef void** ops = NULL if name is None: ops = mat.ops if ops and ops[i]: flag[0] = PETSC_TRUE else: flag[0] = PETSC_TRUE if getattr(PyMat(mat), name) is not None else PETSC_FALSE return FunctionEnd() cdef PetscErrorCode MatProductNumeric_Python( PetscMat mat ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatProductNumeric_Python") cdef PetscMat A = NULL cdef PetscMat B = NULL cdef PetscMat C = NULL cdef PetscMatProductType mtype = MATPRODUCT_UNSPECIFIED CHKERR( MatProductGetMats(mat, &A, &B, &C) ) CHKERR( MatProductGetType(mat, &mtype) ) mtypes = {MATPRODUCT_AB : 'AB', MATPRODUCT_ABt : 'ABt', MATPRODUCT_AtB : 'AtB', MATPRODUCT_PtAP : 'PtAP', MATPRODUCT_RARt: 'RARt', MATPRODUCT_ABC: 'ABC'} cdef Mat_Product *product = mat.product cdef PetscInt i = product.data if i < 0 or i > 2: return PetscSETERR(PETSC_ERR_PLIB, "Corrupted composed id") cdef PetscMat pM = C if i == 2 else B if i == 1 else A cdef Mat PyA = Mat_(A) cdef Mat PyB = Mat_(B) cdef Mat PyC = Mat_(C) if mtype == MATPRODUCT_ABC: mats = (PyA, PyB, PyC) else: mats = (PyA, PyB, None) cdef productNumeric = PyMat(pM).productNumeric if productNumeric is None: return UNSUPPORTED(b"productNumeric") productNumeric(PyC if C == pM else PyB if B == pM else PyA, Mat_(mat), mtypes[mtype], *mats) return FunctionEnd() cdef PetscInt matmatid = -1 cdef PetscErrorCode MatProductSymbolic_Python( PetscMat mat ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatProductSymbolic_Python") cdef PetscMat A = NULL cdef PetscMat B = NULL cdef PetscMat C = NULL cdef PetscMatProductType mtype = MATPRODUCT_UNSPECIFIED CHKERR( MatProductGetMats(mat, &A, &B, &C) ) CHKERR( MatProductGetType(mat, &mtype) ) mtypes = {MATPRODUCT_AB : 'AB', MATPRODUCT_ABt : 'ABt', MATPRODUCT_AtB : 'AtB', MATPRODUCT_PtAP : 'PtAP', MATPRODUCT_RARt: 'RARt', MATPRODUCT_ABC: 'ABC'} global matmatid cdef PetscInt i = -1 cdef PetscBool flg = PETSC_FALSE CHKERR( PetscObjectComposedDataGetIntPy(mat, matmatid, &i, &flg) ) if flg is not PETSC_TRUE: return PetscSETERR(PETSC_ERR_PLIB, "Missing composed id") if i < 0 or i > 2: return PetscSETERR(PETSC_ERR_PLIB, "Corrupted composed id") cdef PetscMat pM = C if i == 2 else B if i == 1 else A cdef Mat PyA = Mat_(A) cdef Mat PyB = Mat_(B) cdef Mat PyC = Mat_(C) if mtype == MATPRODUCT_ABC: mats = (PyA, PyB, PyC) else: mats = (PyA, PyB, None) cdef productSymbolic = PyMat(pM).productSymbolic if productSymbolic is None: return UNSUPPORTED(b"productSymbolic") productSymbolic(PyC if C == pM else PyB if B == pM else PyA, Mat_(mat), mtypes[mtype], *mats) # Store id in matrix product cdef Mat_Product *product = mat.product product.data = i cdef MatOps ops = mat.ops ops.productnumeric = MatProductNumeric_Python return FunctionEnd() cdef PetscErrorCode MatProductSetFromOptions_Python( PetscMat mat ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"MatProductSetFromOptions_Python") cdef PetscMat A = NULL cdef PetscMat B = NULL cdef PetscMat C = NULL CHKERR( MatProductGetMats(mat, &A, &B, &C) ) if A == NULL or B == NULL: return PetscSETERR(PETSC_ERR_PLIB, "Missing matrices") cdef PetscMatProductType mtype = MATPRODUCT_UNSPECIFIED CHKERR( MatProductGetType(mat, &mtype) ) if mtype == MATPRODUCT_UNSPECIFIED: return PetscSETERR(PETSC_ERR_PLIB, "Unknown product type") mtypes = {MATPRODUCT_AB : 'AB', MATPRODUCT_ABt : 'ABt', MATPRODUCT_AtB : 'AtB', MATPRODUCT_PtAP : 'PtAP', MATPRODUCT_RARt: 'RARt', MATPRODUCT_ABC: 'ABC'} cdef Mat PyA = Mat_(A) cdef Mat PyB = Mat_(B) cdef Mat PyC = Mat_(C) if mtype == MATPRODUCT_ABC: mats = (PyA, PyB, PyC) else: mats = (PyA, PyB, None) # Find Python matrix in mats able to perform the product found = False cdef PetscBool mispy = PETSC_FALSE cdef PetscMat pM = NULL cdef Mat mm cdef PetscInt i = -1 for i in range(len(mats)): if mats[i] is None: continue mm = mats[i] pM = mm.mat CHKERR( PetscObjectTypeCompare(pM, MATPYTHON, &mispy) ) if mispy: if PyMat(pM).productSetFromOptions is not None: found = PyMat(pM).productSetFromOptions(PyC if C == pM else PyB if B == pM else PyA, mtypes[mtype], *mats) if found: break if not found: return FunctionEnd() cdef MatOps ops = mat.ops ops.productsymbolic = MatProductSymbolic_Python # Store index (within the product) of the Python matrix which is capable of performing the operation # Cannot be stored in mat.product.data at this stage # Symbolic operation will get this index and store it in the product data global matmatid if matmatid < 0: CHKERR( PetscObjectComposedDataRegisterPy(&matmatid) ) CHKERR( PetscObjectComposedDataSetIntPy(mat, matmatid, i) ) return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: struct _PCOps: PetscErrorCode (*destroy)(PetscPC) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscPC) except PETSC_ERR_PYTHON PetscErrorCode (*reset)(PetscPC) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscPC,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscPC,PetscViewer) except PETSC_ERR_PYTHON PetscErrorCode (*presolve)(PetscPC,PetscKSP,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*postsolve)(PetscPC,PetscKSP,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*apply)(PetscPC,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*matapply)(PetscPC,PetscMat,PetscMat) except PETSC_ERR_PYTHON PetscErrorCode (*applytranspose)(PetscPC,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*applysymmetricleft)(PetscPC,PetscVec,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*applysymmetricright)(PetscPC,PetscVec,PetscVec) except PETSC_ERR_PYTHON ctypedef _PCOps *PCOps struct _p_PC: void *data PCOps ops @cython.internal cdef class _PyPC(_PyObj): pass cdef inline _PyPC PyPC(PetscPC pc): if pc != NULL and pc.data != NULL: return <_PyPC>pc.data else: return _PyPC.__new__(_PyPC) cdef public PetscErrorCode PCPythonGetContext(PetscPC pc, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"PCPythonGetContext") PyPC(pc).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode PCPythonSetContext(PetscPC pc, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"PCPythonSetContext") PyPC(pc).setcontext(ctx, PC_(pc)) return FunctionEnd() cdef PetscErrorCode PCPythonSetType_PYTHON(PetscPC pc, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) PCPythonSetContext(pc, ctx) PyPC(pc).setname(name) return FunctionEnd() cdef PetscErrorCode PCPythonGetType_PYTHON(PetscPC pc, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCPythonGetType_PYTHON") name[0] = PyPC(pc).getname() return FunctionEnd() cdef PetscErrorCode PCCreate_Python( PetscPC pc, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCCreate_Python") # cdef PCOps ops = pc.ops ops.reset = PCReset_Python ops.destroy = PCDestroy_Python ops.setup = PCSetUp_Python ops.setfromoptions = PCSetFromOptions_Python ops.view = PCView_Python ops.presolve = PCPreSolve_Python ops.postsolve = PCPostSolve_Python ops.apply = PCApply_Python ops.matapply = PCMatApply_Python ops.applytranspose = PCApplyTranspose_Python ops.applysymmetricleft = PCApplySymmetricLeft_Python ops.applysymmetricright = PCApplySymmetricRight_Python # CHKERR( PetscObjectComposeFunction( pc, b"PCPythonSetType_C", PCPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( pc, b"PCPythonGetType_C", PCPythonGetType_PYTHON) ) # cdef ctx = PyPC(NULL) pc.data = ctx Py_INCREF(pc.data) return FunctionEnd() cdef inline PetscErrorCode PCDestroy_Python_inner( PetscPC pc, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(pc) PCPythonSetContext(pc, NULL) finally: delRef(pc) Py_DECREF(pc.data) pc.data = NULL return PETSC_SUCCESS cdef PetscErrorCode PCDestroy_Python( PetscPC pc, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"PCDestroy_Python") CHKERR( PetscObjectComposeFunction( pc, b"PCPythonSetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( pc, b"PCPythonGetType_C", NULL) ) # if Py_IsInitialized(): PCDestroy_Python_inner(pc) return FunctionEnd() cdef PetscErrorCode PCSetUp_Python( PetscPC pc, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCSetUp_Python") # cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PyPC(pc).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(pc), b"-pc_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( PCPythonSetType_PYTHON(pc, name) ) if PyPC(pc).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * PCPythonSetType(pc, \"[package.]module.class\")\n" " * PCSetFromOptions(pc) and pass option " "-pc_python_type [package.]module.class") # cdef setUp = PyPC(pc).setUp if setUp is not None: setUp(PC_(pc)) # cdef o = PyPC(pc) cdef PCOps ops = pc.ops if o.applyTranspose is None: ops.applytranspose = NULL if o.applySymmetricLeft is None: ops.applysymmetricleft = NULL if o.applySymmetricRight is None: ops.applysymmetricright = NULL # return FunctionEnd() cdef inline PetscErrorCode PCReset_Python_inner( PetscPC pc, ) \ except PETSC_ERR_PYTHON with gil: cdef reset = PyPC(pc).reset if reset is not None: reset(PC_(pc)) return PETSC_SUCCESS cdef PetscErrorCode PCReset_Python( PetscPC pc, ) \ nogil except PETSC_ERR_PYTHON: if getRef(pc) == 0: return PETSC_SUCCESS FunctionBegin(b"PCReset_Python") if Py_IsInitialized(): PCReset_Python_inner(pc) return FunctionEnd() cdef PetscErrorCode PCSetFromOptions_Python( PetscPC pc, PetscOptionItems *PetscOptionsObject, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCSetFromOptions_Python") # cdef char name[2048], *defval = PyPC(pc).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-pc_python_type", b"Python [package.]module[.{class|function}]", b"PCPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( PCPythonSetType_PYTHON(pc, name) ) # cdef setFromOptions = PyPC(pc).setFromOptions if setFromOptions is not None: setFromOptions(PC_(pc)) return FunctionEnd() cdef PetscErrorCode PCView_Python( PetscPC pc, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCView_Python") viewcontext(PyPC(pc), vwr) cdef view = PyPC(pc).view if view is not None: view(PC_(pc), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode PCPreSolve_Python( PetscPC pc, PetscKSP ksp, PetscVec b, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCPreSolve_Python") cdef preSolve = PyPC(pc).preSolve if preSolve is not None: preSolve(PC_(pc), KSP_(ksp), Vec_(b), Vec_(x)) return FunctionEnd() cdef PetscErrorCode PCPostSolve_Python( PetscPC pc, PetscKSP ksp, PetscVec b, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCPostSolve_Python") cdef postSolve = PyPC(pc).postSolve if postSolve is not None: postSolve(PC_(pc), KSP_(ksp), Vec_(b), Vec_(x)) return FunctionEnd() cdef PetscErrorCode PCApply_Python( PetscPC pc, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCApply_Python") cdef apply = PyPC(pc).apply apply(PC_(pc), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode PCApplyTranspose_Python( PetscPC pc, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCApplyTranspose_Python") cdef applyTranspose = PyPC(pc).applyTranspose applyTranspose(PC_(pc), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode PCApplySymmetricLeft_Python( PetscPC pc, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCApplySymmetricLeft_Python") cdef applySymmetricLeft = PyPC(pc).applySymmetricLeft applySymmetricLeft(PC_(pc), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode PCApplySymmetricRight_Python( PetscPC pc, PetscVec x, PetscVec y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCApplySymmetricRight_Python") cdef applySymmetricRight = PyPC(pc).applySymmetricRight applySymmetricRight(PC_(pc), Vec_(x), Vec_(y)) return FunctionEnd() cdef PetscErrorCode PCMatApply_Python( PetscPC pc, PetscMat X, PetscMat Y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PCMatApply_Python") cdef matApply = PyPC(pc).matApply if matApply is None: try: pc.ops.matapply = NULL CHKERR( PCMatApply(pc, X, Y) ) finally: pc.ops.matapply = PCMatApply_Python return FunctionEnd() matApply(PC_(pc), Mat_(X), Mat_(Y)) return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: struct _KSPOps: PetscErrorCode (*destroy)(PetscKSP) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscKSP) except PETSC_ERR_PYTHON PetscErrorCode (*reset)(PetscKSP) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscKSP,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscKSP,PetscViewer) except PETSC_ERR_PYTHON PetscErrorCode (*solve)(PetscKSP) except PETSC_ERR_PYTHON PetscErrorCode (*buildsolution)(PetscKSP,PetscVec,PetscVec*) except PETSC_ERR_PYTHON PetscErrorCode (*buildresidual)(PetscKSP,PetscVec,PetscVec,PetscVec*) except PETSC_ERR_PYTHON ctypedef _KSPOps *KSPOps struct _p_KSP: void *data KSPOps ops PetscBool transpose_solve PetscInt iter"its",max_its"max_it" PetscReal norm"rnorm" PetscKSPConvergedReason reason cdef extern from * nogil: # custom.h PetscErrorCode KSPConverged(PetscKSP,PetscInt,PetscReal,PetscKSPConvergedReason*) PetscErrorCode KSPLogHistory(PetscKSP,PetscReal) @cython.internal cdef class _PyKSP(_PyObj): pass cdef inline _PyKSP PyKSP(PetscKSP ksp): if ksp != NULL and ksp.data != NULL: return <_PyKSP>ksp.data else: return _PyKSP.__new__(_PyKSP) cdef public PetscErrorCode KSPPythonGetContext(PetscKSP ksp, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"KSPPythonGetContext") PyKSP(ksp).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode KSPPythonSetContext(PetscKSP ksp, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"KSPPythonSetContext") PyKSP(ksp).setcontext(ctx, KSP_(ksp)) return FunctionEnd() cdef PetscErrorCode KSPPythonSetType_PYTHON(PetscKSP ksp, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) KSPPythonSetContext(ksp, ctx) PyKSP(ksp).setname(name) return FunctionEnd() cdef PetscErrorCode KSPPythonGetType_PYTHON(PetscKSP ksp, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPPythonGetType_PYTHON") name[0] = PyKSP(ksp).getname() return FunctionEnd() cdef PetscErrorCode KSPCreate_Python( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPCreate_Python") # cdef KSPOps ops = ksp.ops ops.reset = KSPReset_Python ops.destroy = KSPDestroy_Python ops.setup = KSPSetUp_Python ops.setfromoptions = KSPSetFromOptions_Python ops.view = KSPView_Python ops.solve = KSPSolve_Python ops.buildsolution = KSPBuildSolution_Python ops.buildresidual = KSPBuildResidual_Python # CHKERR( PetscObjectComposeFunction( ksp, b"KSPPythonSetType_C", KSPPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( ksp, b"KSPPythonGetType_C", KSPPythonGetType_PYTHON) ) # cdef ctx = PyKSP(NULL) ksp.data = ctx Py_INCREF(ksp.data) # CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_PRECONDITIONED, PC_LEFT, 3) ) CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_UNPRECONDITIONED, PC_RIGHT, 3) ) CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_UNPRECONDITIONED, PC_LEFT, 2) ) CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_PRECONDITIONED, PC_RIGHT, 2) ) CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_PRECONDITIONED, PC_SYMMETRIC, 1) ) CHKERR( KSPSetSupportedNorm( ksp, KSP_NORM_UNPRECONDITIONED, PC_SYMMETRIC, 1) ) return FunctionEnd() cdef inline PetscErrorCode KSPDestroy_Python_inner( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(ksp) KSPPythonSetContext(ksp, NULL) finally: delRef(ksp) Py_DECREF(ksp.data) ksp.data = NULL return PETSC_SUCCESS cdef PetscErrorCode KSPDestroy_Python( PetscKSP ksp, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"KSPDestroy_Python") CHKERR( PetscObjectComposeFunction( ksp, b"KSPPythonSetType_C", NULL)) CHKERR( PetscObjectComposeFunction( ksp, b"KSPPythonGetType_C", NULL)) # if Py_IsInitialized(): KSPDestroy_Python_inner(ksp) return FunctionEnd() cdef PetscErrorCode KSPSetUp_Python( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPSetUp_Python") # cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PyKSP(ksp).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(ksp), b"-ksp_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( KSPPythonSetType_PYTHON(ksp, name) ) if PyKSP(ksp).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * KSPPythonSetType(ksp, \"[package.]module.class\")\n" " * KSPSetFromOptions(ksp) and pass option " "-ksp_python_type [package.]module.class") # cdef setUp = PyKSP(ksp).setUp if setUp is not None: setUp(KSP_(ksp)) return FunctionEnd() cdef inline PetscErrorCode KSPReset_Python_inner( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: cdef reset = PyKSP(ksp).reset if reset is not None: reset(KSP_(ksp)) return PETSC_SUCCESS cdef PetscErrorCode KSPReset_Python( PetscKSP ksp, ) \ nogil except PETSC_ERR_PYTHON: if getRef(ksp) == 0: return PETSC_SUCCESS FunctionBegin(b"KSPReset_Python") CHKERR( PetscObjectCompose(ksp, b"@ksp.vec_work_sol", NULL) ) CHKERR( PetscObjectCompose(ksp, b"@ksp.vec_work_res", NULL) ) if Py_IsInitialized(): KSPReset_Python_inner(ksp) return FunctionEnd() cdef PetscErrorCode KSPSetFromOptions_Python( PetscKSP ksp, PetscOptionItems *PetscOptionsObject ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPSetFromOptions_Python") # cdef char name[2048], *defval = PyKSP(ksp).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-ksp_python_type", b"Python [package.]module[.{class|function}]", b"KSPPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( KSPPythonSetType_PYTHON(ksp, name) ) # cdef setFromOptions = PyKSP(ksp).setFromOptions if setFromOptions is not None: setFromOptions(KSP_(ksp)) return FunctionEnd() cdef PetscErrorCode KSPView_Python( PetscKSP ksp, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPView_Python") viewcontext(PyKSP(ksp), vwr) cdef view = PyKSP(ksp).view if view is not None: view(KSP_(ksp), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode KSPBuildSolution_Python( PetscKSP ksp, PetscVec v, PetscVec *V, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPBuildSolution_Python") cdef PetscVec x = v cdef buildSolution = PyKSP(ksp).buildSolution if buildSolution is not None: if x == NULL: pass # XXX buildSolution(KSP_(ksp), Vec_(x)) if V != NULL: V[0] = x else: CHKERR( KSPBuildSolutionDefault(ksp, v, V) ) return FunctionEnd() cdef PetscErrorCode KSPBuildResidual_Python( PetscKSP ksp, PetscVec t, PetscVec v, PetscVec *V, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPBuildResidual_Python") cdef buildResidual = PyKSP(ksp).buildResidual if buildResidual is not None: buildResidual(KSP_(ksp), Vec_(t), Vec_(v)) if V != NULL: V[0] = v else: CHKERR( KSPBuildResidualDefault(ksp, t, v, V) ) return FunctionEnd() cdef PetscErrorCode KSPSolve_Python( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPSolve_Python") cdef PetscVec B = NULL, X = NULL CHKERR( KSPGetRhs(ksp, &B) ) CHKERR( KSPGetSolution(ksp, &X) ) # ksp.iter = 0 ksp.reason = KSP_CONVERGED_ITERATING # cdef solve = None if ksp.transpose_solve: solve = PyKSP(ksp).solveTranspose else: solve = PyKSP(ksp).solve if solve is not None: solve(KSP_(ksp), Vec_(B), Vec_(X)) else: KSPSolve_Python_default(ksp, B, X) return FunctionEnd() cdef PetscErrorCode KSPSolve_Python_default( PetscKSP ksp, PetscVec B, PetscVec X, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPSolve_Python_default") # cdef PetscVec t = NULL CHKERR( PetscObjectQuery( ksp, b"@ksp.vec_work_sol", &t) ) if t == NULL: CHKERR( VecDuplicate(X, &t) ) CHKERR( PetscObjectCompose( ksp, b"@ksp.vec_work_sol", t) ) cdef PetscVec v = NULL CHKERR( PetscObjectQuery( ksp, b"@ksp.vec_work_res", &v) ) if v == NULL: CHKERR( VecDuplicate(B, &v) ) CHKERR( PetscObjectCompose( ksp, b"@ksp.vec_work_res", v) ) # cdef PetscInt its = 0 cdef PetscVec R = NULL cdef PetscReal rnorm = 0 # CHKERR( KSPBuildResidual(ksp, t, v, &R) ) CHKERR( VecNorm(R, PETSC_NORM_2, &rnorm) ) # CHKERR( KSPConverged(ksp, ksp.iter, rnorm, &ksp.reason) ) CHKERR( KSPLogHistory(ksp, ksp.norm) ) CHKERR( KSPMonitor(ksp, ksp.iter, ksp.norm) ) for its from 0 <= its < ksp.max_its: if ksp.reason: break KSPPreStep_Python(ksp) # KSPStep_Python(ksp, B, X) CHKERR( KSPBuildResidual(ksp, t, v, &R) ) CHKERR( VecNorm(R, PETSC_NORM_2, &rnorm) ) ksp.iter += 1 # KSPPostStep_Python(ksp) CHKERR( KSPConverged(ksp, ksp.iter, rnorm, &ksp.reason) ) CHKERR( KSPLogHistory(ksp, ksp.norm) ) CHKERR( KSPMonitor(ksp, ksp.iter, ksp.norm) ) if ksp.iter == ksp.max_its: if ksp.reason == KSP_CONVERGED_ITERATING: ksp.reason = KSP_DIVERGED_MAX_IT # return FunctionEnd() cdef PetscErrorCode KSPPreStep_Python( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPPreStep_Python") cdef preStep = PyKSP(ksp).preStep if preStep is not None: preStep(KSP_(ksp)) return FunctionEnd() cdef PetscErrorCode KSPPostStep_Python( PetscKSP ksp, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPPostStep_Python") cdef postStep = PyKSP(ksp).postStep if postStep is not None: postStep(KSP_(ksp)) return FunctionEnd() cdef PetscErrorCode KSPStep_Python( PetscKSP ksp, PetscVec B, PetscVec X, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"KSPStep_Python") cdef step = None if ksp.transpose_solve: step = PyKSP(ksp).stepTranspose if step is None: return UNSUPPORTED(b"stepTranspose") else: step = PyKSP(ksp).step if step is None: return UNSUPPORTED(b"step") step(KSP_(ksp), Vec_(B), Vec_(X)) return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: struct _SNESOps: PetscErrorCode (*destroy)(PetscSNES) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscSNES) except PETSC_ERR_PYTHON PetscErrorCode (*reset)(PetscSNES) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscSNES,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscSNES,PetscViewer) except PETSC_ERR_PYTHON PetscErrorCode (*solve)(PetscSNES) except PETSC_ERR_PYTHON ctypedef _SNESOps *SNESOps struct _p_SNES: void *data SNESOps ops PetscInt iter,max_its,linear_its PetscReal norm,rtol,ttol PetscSNESConvergedReason reason PetscVec vec_sol,vec_sol_update,vec_func PetscMat jacobian,jacobian_pre PetscKSP ksp cdef extern from * nogil: # custom.h PetscErrorCode SNESConverged(PetscSNES,PetscInt,PetscReal,PetscReal,PetscReal,PetscSNESConvergedReason*) PetscErrorCode SNESLogHistory(PetscSNES,PetscReal,PetscInt) @cython.internal cdef class _PySNES(_PyObj): pass cdef inline _PySNES PySNES(PetscSNES snes): if snes != NULL and snes.data != NULL: return <_PySNES>snes.data else: return _PySNES.__new__(_PySNES) cdef public PetscErrorCode SNESPythonGetContext(PetscSNES snes, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"SNESPythonGetContext ") PySNES(snes).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode SNESPythonSetContext(PetscSNES snes, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"SNESPythonSetContext ") PySNES(snes).setcontext(ctx, SNES_(snes)) return FunctionEnd() cdef PetscErrorCode SNESPythonSetType_PYTHON(PetscSNES snes, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) SNESPythonSetContext(snes, ctx) PySNES(snes).setname(name) return FunctionEnd() cdef PetscErrorCode SNESPythonGetType_PYTHON(PetscSNES snes, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESPythonGetType_PYTHON") name[0] = PySNES(snes).getname() return FunctionEnd() cdef PetscErrorCode SNESCreate_Python( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESCreate_Python") # cdef SNESOps ops = snes.ops cdef PetscSNESLineSearch ls = NULL ops.reset = SNESReset_Python ops.destroy = SNESDestroy_Python ops.setup = SNESSetUp_Python ops.setfromoptions = SNESSetFromOptions_Python ops.view = SNESView_Python ops.solve = SNESSolve_Python # CHKERR( PetscObjectComposeFunction( snes, b"SNESPythonSetType_C", SNESPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( snes, b"SNESPythonGetType_C", SNESPythonGetType_PYTHON) ) # cdef ctx = PySNES(NULL) snes.data = ctx # Ensure that the SNES has a linesearch object early enough that # it gets setFromOptions. CHKERR( SNESGetLineSearch(snes, &ls) ) Py_INCREF(snes.data) return FunctionEnd() cdef inline PetscErrorCode SNESDestroy_Python_inner( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(snes) SNESPythonSetContext(snes, NULL) finally: delRef(snes) Py_DECREF(snes.data) snes.data = NULL return PETSC_SUCCESS cdef PetscErrorCode SNESDestroy_Python( PetscSNES snes, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"SNESDestroy_Python") CHKERR( PetscObjectComposeFunction( snes, b"SNESPythonSetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( snes, b"SNESPythonGetType_C", NULL) ) # if Py_IsInitialized(): SNESDestroy_Python_inner(snes) return FunctionEnd() cdef PetscErrorCode SNESSetUp_Python( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESSetUp_Python") # #SNESGetKSP(snes,&snes.ksp) # cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PySNES(snes).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(snes), b"-snes_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( SNESPythonSetType_PYTHON(snes, name) ) if PySNES(snes).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * SNESPythonSetType(snes, \"[package.]module.class\")\n" " * SNESSetFromOptions(snes) and pass option " "-snes_python_type [package.]module.class") # cdef setUp = PySNES(snes).setUp if setUp is not None: setUp(SNES_(snes)) return FunctionEnd() cdef inline PetscErrorCode SNESReset_Python_inner( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: cdef reset = PySNES(snes).reset if reset is not None: reset(SNES_(snes)) return PETSC_SUCCESS cdef PetscErrorCode SNESReset_Python( PetscSNES snes, ) \ nogil except PETSC_ERR_PYTHON: if getRef(snes) == 0: return PETSC_SUCCESS FunctionBegin(b"SNESReset_Python") if Py_IsInitialized(): SNESReset_Python_inner(snes) return FunctionEnd() cdef PetscErrorCode SNESSetFromOptions_Python( PetscSNES snes, PetscOptionItems *PetscOptionsObject, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESSetFromOptions_Python") # cdef char name[2048], *defval = PySNES(snes).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-snes_python_type", b"Python [package.]module[.{class|function}]", b"SNESPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( SNESPythonSetType_PYTHON(snes, name) ) # cdef setFromOptions = PySNES(snes).setFromOptions if setFromOptions is not None: setFromOptions(SNES_(snes)) return FunctionEnd() cdef PetscErrorCode SNESView_Python( PetscSNES snes, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESView_Python") viewcontext(PySNES(snes), vwr) cdef view = PySNES(snes).view if view is not None: view(SNES_(snes), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode SNESSolve_Python( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESSolve_Python") cdef PetscVec b = NULL, x = NULL CHKERR( SNESGetRhs(snes, &b) ) CHKERR( SNESGetSolution(snes, &x) ) # snes.iter = 0 snes.reason = SNES_CONVERGED_ITERATING # cdef solve = PySNES(snes).solve if solve is not None: solve(SNES_(snes), Vec_(b) if b != NULL else None, Vec_(x)) else: SNESSolve_Python_default(snes) # return FunctionEnd() cdef PetscErrorCode SNESSolve_Python_default( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESSolve_Python_default") # cdef PetscVec X=NULL, F=NULL, Y=NULL cdef PetscSNESLineSearch ls CHKERR( SNESGetSolution(snes, &X) ) CHKERR( SNESGetFunction(snes, &F, NULL, NULL) ) CHKERR( SNESGetSolutionUpdate(snes, &Y) ) CHKERR( SNESGetLineSearch(snes, &ls) ) cdef PetscInt its=0, lits=0 cdef PetscReal xnorm = 0.0 cdef PetscReal fnorm = 0.0 cdef PetscReal ynorm = 0.0 # CHKERR( VecSet(Y, 0.0) ) CHKERR( SNESComputeFunction(snes, X, F) ) CHKERR( VecNorm(X, PETSC_NORM_2, &xnorm) ) CHKERR( VecNorm(F, PETSC_NORM_2, &fnorm) ) # CHKERR( SNESConverged(snes, snes.iter, xnorm, ynorm, fnorm, &snes.reason) ) CHKERR( SNESLogHistory(snes, snes.norm, lits) ) CHKERR( SNESMonitor(snes, snes.iter, snes.norm) ) cdef PetscObjectState ostate = -1 cdef PetscObjectState nstate = -1 for its from 0 <= its < snes.max_its: if snes.reason: break CHKERR( PetscObjectStateGet(X, &ostate) ) SNESPreStep_Python(snes) CHKERR( PetscObjectStateGet(X, &nstate) ) if ostate != nstate: CHKERR( SNESComputeFunction(snes, X, F) ) CHKERR( VecNorm(F, PETSC_NORM_2, &fnorm) ) # lits = -snes.linear_its SNESStep_Python(snes, X, F, Y) lits += snes.linear_its # CHKERR( SNESLineSearchApply(ls, X, F, NULL, Y) ) CHKERR( SNESLineSearchGetNorms(ls, &xnorm, &fnorm, &ynorm) ) snes.iter += 1 # SNESPostStep_Python(snes) CHKERR( SNESConverged(snes, snes.iter, xnorm, ynorm, fnorm, &snes.reason) ) CHKERR( SNESLogHistory(snes, snes.norm, lits) ) CHKERR( SNESMonitor(snes, snes.iter, snes.norm) ) if snes.iter == snes.max_its: if snes.reason == SNES_CONVERGED_ITERATING: snes.reason = SNES_DIVERGED_MAX_IT # return FunctionEnd() cdef PetscErrorCode SNESPreStep_Python( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESPreStep_Python") cdef preStep = PySNES(snes).preStep if preStep is not None: preStep(SNES_(snes)) return FunctionEnd() cdef PetscErrorCode SNESPostStep_Python( PetscSNES snes, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESPostStep_Python") cdef postStep = PySNES(snes).postStep if postStep is not None: postStep(SNES_(snes)) return FunctionEnd() cdef PetscErrorCode SNESStep_Python( PetscSNES snes, PetscVec X, PetscVec F, PetscVec Y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESStep_Python") cdef step = PySNES(snes).step if step is not None: step(SNES_(snes), Vec_(X), Vec_(F), Vec_(Y)) else: SNESStep_Python_default(snes, X, F, Y) return FunctionEnd() cdef PetscErrorCode SNESStep_Python_default( PetscSNES snes, PetscVec X, PetscVec F, PetscVec Y, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"SNESStep_Python_default") cdef PetscMat J = NULL, P = NULL cdef PetscInt lits = 0 CHKERR( SNESGetJacobian(snes, &J, &P, NULL, NULL) ) CHKERR( SNESComputeJacobian(snes, X, J, P) ) CHKERR( KSPSetOperators(snes.ksp, J, P) ) CHKERR( KSPSolve(snes.ksp, F, Y) ) CHKERR( KSPGetIterationNumber(snes.ksp, &lits) ) snes.linear_its += lits return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: struct _TSOps: PetscErrorCode (*destroy)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*reset)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscTS,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscTS,PetscViewer) except PETSC_ERR_PYTHON PetscErrorCode (*step)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*rollback)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*interpolate)(PetscTS,PetscReal,PetscVec) except PETSC_ERR_PYTHON PetscErrorCode (*evaluatestep)(PetscTS,PetscInt,PetscVec,PetscBool*) except PETSC_ERR_PYTHON PetscErrorCode (*solve)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*snesfunction)(PetscSNES,PetscVec,PetscVec,PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*snesjacobian)(PetscSNES,PetscVec,PetscMat,PetscMat,PetscTS) except PETSC_ERR_PYTHON ctypedef _TSOps *TSOps struct _TSUserOps: PetscErrorCode (*prestep)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*prestage)(PetscTS,PetscReal) except PETSC_ERR_PYTHON PetscErrorCode (*poststage)(PetscTS,PetscReal,PetscInt,PetscVec*) except PETSC_ERR_PYTHON PetscErrorCode (*poststep)(PetscTS) except PETSC_ERR_PYTHON PetscErrorCode (*rhsfunction)(PetscTS,PetscReal,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON PetscErrorCode (*ifunction) (PetscTS,PetscReal,PetscVec,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON PetscErrorCode (*rhsjacobian)(PetscTS,PetscReal,PetscVec,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON PetscErrorCode (*ijacobian) (PetscTS,PetscReal,PetscVec,PetscVec,PetscReal,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef _TSUserOps *TSUserOps struct _p_TS: void *data PetscDM dm PetscTSAdapt adapt TSOps ops TSUserOps userops PetscTSProblemType problem_type PetscInt snes_its PetscInt ksp_its PetscInt reject PetscInt max_reject PetscInt steps PetscReal ptime PetscVec vec_sol PetscReal time_step PetscInt max_steps PetscReal max_time PetscTSConvergedReason reason PetscSNES snes PetscBool usessnes @cython.internal cdef class _PyTS(_PyObj): pass cdef inline _PyTS PyTS(PetscTS ts): if ts != NULL and ts.data != NULL: return <_PyTS>ts.data else: return _PyTS.__new__(_PyTS) cdef public PetscErrorCode TSPythonGetContext(PetscTS ts, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"TSPythonGetContext") PyTS(ts).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode TSPythonSetContext(PetscTS ts, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"TSPythonSetContext") PyTS(ts).setcontext(ctx, TS_(ts)) return FunctionEnd() cdef PetscErrorCode TSPythonSetType_PYTHON(PetscTS ts, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) TSPythonSetContext(ts, ctx) PyTS(ts).setname(name) return FunctionEnd() cdef PetscErrorCode TSPythonGetType_PYTHON(PetscTS ts, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSPythonGetType_PYTHON") name[0] = PyTS(ts).getname() return FunctionEnd() cdef PetscErrorCode TSCreate_Python( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSCreate_Python") # cdef TSOps ops = ts.ops ops.reset = TSReset_Python ops.destroy = TSDestroy_Python ops.setup = TSSetUp_Python ops.setfromoptions = TSSetFromOptions_Python ops.view = TSView_Python ops.step = TSStep_Python ops.rollback = TSRollBack_Python ops.interpolate = TSInterpolate_Python ops.evaluatestep = TSEvaluateStep_Python ops.snesfunction = SNESTSFormFunction_Python ops.snesjacobian = SNESTSFormJacobian_Python # CHKERR( PetscObjectComposeFunction( ts, b"TSPythonSetType_C", TSPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( ts, b"TSPythonGetType_C", TSPythonGetType_PYTHON) ) # ts.usessnes = PETSC_TRUE # cdef ctx = PyTS(NULL) ts.data = ctx Py_INCREF(ts.data) return FunctionEnd() cdef inline PetscErrorCode TSDestroy_Python_inner( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(ts) TSPythonSetContext(ts, NULL) finally: delRef(ts) Py_DECREF(ts.data) ts.data = NULL return PETSC_SUCCESS cdef PetscErrorCode TSDestroy_Python( PetscTS ts, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"TSDestroy_Python") CHKERR( PetscObjectComposeFunction( ts, b"TSPythonSetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( ts, b"TSPythonGetType_C", NULL) ) # if Py_IsInitialized(): TSDestroy_Python_inner(ts) return FunctionEnd() cdef PetscErrorCode TSSetUp_Python( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSSetUp_Python") # cdef PetscVec vec_update = NULL CHKERR( VecDuplicate(ts.vec_sol, &vec_update) ) CHKERR( PetscObjectCompose(ts, b"@ts.vec_update", vec_update) ) CHKERR( VecDestroy(&vec_update) ) cdef PetscVec vec_dot = NULL CHKERR( VecDuplicate(ts.vec_sol, &vec_dot) ) CHKERR( PetscObjectCompose(ts, b"@ts.vec_dot", vec_dot) ) CHKERR( VecDestroy(&vec_dot) ) # cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PyTS(ts).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(ts), b"-ts_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( TSPythonSetType_PYTHON(ts, name) ) if PyTS(ts).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * TSPythonSetType(ts, \"[package.]module.class\")\n" " * TSSetFromOptions(ts) and pass option " "-ts_python_type [package.]module.class") # cdef setUp = PyTS(ts).setUp if setUp is not None: setUp(TS_(ts)) return FunctionEnd() cdef inline PetscErrorCode TSReset_Python_inner( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: cdef reset = PyTS(ts).reset if reset is not None: reset(TS_(ts)) return PETSC_SUCCESS cdef PetscErrorCode TSReset_Python( PetscTS ts, ) \ nogil except PETSC_ERR_PYTHON: if getRef(ts) == 0: return PETSC_SUCCESS FunctionBegin(b"TSReset_Python") CHKERR( PetscObjectCompose(ts, b"@ts.vec_update", NULL) ) CHKERR( PetscObjectCompose(ts, b"@ts.vec_dot", NULL) ) if Py_IsInitialized(): TSReset_Python_inner(ts) return FunctionEnd() cdef PetscErrorCode TSSetFromOptions_Python( PetscTS ts, PetscOptionItems *PetscOptionsObject, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSSetFromOptions_Python") cdef char name[2048], *defval = PyTS(ts).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-ts_python_type", b"Python [package.]module[.{class|function}]", b"TSPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( TSPythonSetType_PYTHON(ts, name) ) # cdef setFromOptions = PyTS(ts).setFromOptions if setFromOptions is not None: setFromOptions(TS_(ts)) CHKERR( SNESSetFromOptions(ts.snes) ) return FunctionEnd() cdef PetscErrorCode TSView_Python( PetscTS ts, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSView_Python") viewcontext(PyTS(ts), vwr) cdef view = PyTS(ts).view if view is not None: view(TS_(ts), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode TSStep_Python( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSStep_Python") cdef step = PyTS(ts).step if step is not None: step(TS_(ts)) else: TSStep_Python_default(ts) return FunctionEnd() cdef PetscErrorCode TSRollBack_Python( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSRollBack_Python") cdef rollback = PyTS(ts).rollback if rollback is None: return UNSUPPORTED(b"rollback") rollback(TS_(ts)) return FunctionEnd() cdef PetscErrorCode TSInterpolate_Python( PetscTS ts, PetscReal t, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSInterpolate _Python") cdef interpolate = PyTS(ts).interpolate if interpolate is None: return UNSUPPORTED(b"interpolate") interpolate(TS_(ts), toReal(t), Vec_(x)) return FunctionEnd() cdef PetscErrorCode TSEvaluateStep_Python( PetscTS ts, PetscInt o, PetscVec x, PetscBool *flag, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSEvaluateStep _Python") cdef evaluatestep = PyTS(ts).evaluatestep if evaluatestep is None: return UNSUPPORTED(b"evaluatestep") cdef done = evaluatestep(TS_(ts), toInt(o), Vec_(x)) if flag != NULL: flag[0] = PETSC_TRUE if done else PETSC_FALSE elif not done: return PetscSETERR(PETSC_ERR_USER, "Cannot evaluate step") return FunctionEnd() cdef PetscErrorCode SNESTSFormFunction_Python( PetscSNES snes, PetscVec x, PetscVec f, PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: # cdef formSNESFunction = PyTS(ts).formSNESFunction if formSNESFunction is not None: args = (SNES_(snes), Vec_(x), Vec_(f), TS_(ts)) formSNESFunction(args) return FunctionEnd() # cdef PetscVec dx = NULL CHKERR( PetscObjectQuery( ts, b"@ts.vec_dot", &dx) ) # cdef PetscReal t = ts.ptime + ts.time_step cdef PetscReal a = 1.0/ts.time_step CHKERR( VecCopy(ts.vec_sol, dx) ) CHKERR( VecAXPBY(dx, +a, -a, x) ) CHKERR( TSComputeIFunction(ts, t, x, dx, f, PETSC_FALSE) ) return FunctionEnd() cdef PetscErrorCode SNESTSFormJacobian_Python( PetscSNES snes, PetscVec x, PetscMat A, PetscMat B, PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: # cdef formSNESJacobian = PyTS(ts).formSNESJacobian if formSNESJacobian is not None: args = (SNES_(snes), Vec_(x), Mat_(A), Mat_(B), TS_(ts)) formSNESJacobian(*args) return FunctionEnd() # cdef PetscVec dx = NULL CHKERR( PetscObjectQuery( ts, b"@ts.vec_dot", &dx) ) # cdef PetscReal t = ts.ptime + ts.time_step cdef PetscReal a = 1.0/ts.time_step CHKERR( VecCopy(ts.vec_sol, dx) ) CHKERR( VecAXPBY(dx, +a, -a, x) ) CHKERR( TSComputeIJacobian(ts, t, x, dx, a, A, B, PETSC_FALSE) ) return FunctionEnd() cdef PetscErrorCode TSSolveStep_Python( PetscTS ts, PetscReal t, PetscVec x, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSSolveStep_Python") # cdef solveStep = PyTS(ts).solveStep if solveStep is not None: solveStep(TS_(ts), t, Vec_(x)) return FunctionEnd() # cdef PetscInt nits = 0, lits = 0 CHKERR( SNESSolve(ts.snes, NULL, x) ) CHKERR( SNESGetIterationNumber(ts.snes, &nits) ) CHKERR( SNESGetLinearSolveIterations(ts.snes, &lits) ) ts.snes_its += nits ts.ksp_its += lits return FunctionEnd() cdef PetscErrorCode TSAdaptStep_Python( PetscTS ts, PetscReal t, PetscVec x, PetscReal *nextdt, PetscBool *stepok, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSAdaptStep_Python") nextdt[0] = ts.time_step stepok[0] = PETSC_TRUE # cdef adaptStep = PyTS(ts).adaptStep if adaptStep is None: return FunctionEnd() cdef object retval cdef double dt cdef bint ok retval = adaptStep(TS_(ts), t, Vec_(x)) if retval is None: pass elif isinstance(retval, float): dt = retval nextdt[0] = dt stepok[0] = PETSC_TRUE elif isinstance(retval, bool): ok = retval nextdt[0] = ts.time_step stepok[0] = PETSC_TRUE if ok else PETSC_FALSE else: dt, ok = retval nextdt[0] = dt stepok[0] = PETSC_TRUE if ok else PETSC_FALSE return FunctionEnd() cdef PetscErrorCode TSStep_Python_default( PetscTS ts, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TSStep_Python_default") cdef PetscVec vec_update = NULL CHKERR( PetscObjectQuery( ts, b"@ts.vec_update", &vec_update) ) # cdef PetscInt r = 0 cdef PetscReal tt = ts.ptime cdef PetscReal dt = ts.time_step cdef PetscBool accept = PETSC_TRUE cdef PetscBool stageok = PETSC_TRUE for r from 0 <= r < ts.max_reject: tt = ts.ptime + ts.time_step CHKERR( VecCopy(ts.vec_sol, vec_update) ) CHKERR( TSPreStage(ts, tt+dt) ) TSSolveStep_Python(ts, tt, vec_update) CHKERR( TSPostStage(ts, tt+dt, 0, &vec_update) ); CHKERR( TSAdaptCheckStage(ts.adapt, ts, tt+dt, vec_update, &stageok) ); if not stageok: ts.reject += 1 continue TSAdaptStep_Python(ts, tt, vec_update, &dt, &accept) if not accept: ts.time_step = dt ts.reject += 1 continue CHKERR( VecCopy(vec_update, ts.vec_sol) ) ts.ptime += ts.time_step ts.time_step = dt break if (not stageok or not accept) and ts.reason == 0: ts.reason = TS_DIVERGED_STEP_REJECTED return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: struct _TaoOps: PetscErrorCode (*destroy)(PetscTAO) except PETSC_ERR_PYTHON PetscErrorCode (*setup)(PetscTAO) except PETSC_ERR_PYTHON PetscErrorCode (*solve)(PetscTAO) except PETSC_ERR_PYTHON PetscErrorCode (*setfromoptions)(PetscTAO,PetscOptionItems*) except PETSC_ERR_PYTHON PetscErrorCode (*view)(PetscTAO,PetscViewer) except PETSC_ERR_PYTHON ctypedef _TaoOps *TaoOps struct _p_TAO: void *data TaoOps ops PetscInt niter, max_it PetscTAOConvergedReason reason PetscInt ksp_its, ksp_tot_its PetscKSP ksp PetscVec gradient PetscVec stepdirection PetscTAOLineSearch linesearch cdef extern from * nogil: # custom.h PetscErrorCode TaoConverged(PetscTAO,PetscTAOConvergedReason*) cdef extern from * nogil: # custom.h PetscErrorCode TaoGetVecs(PetscTAO,PetscVec*,PetscVec*,PetscVec*) PetscErrorCode TaoCheckReals(PetscTAO,PetscReal,PetscReal) PetscErrorCode TaoComputeUpdate(PetscTAO) PetscErrorCode TaoCreateDefaultLineSearch(PetscTAO) PetscErrorCode TaoCreateDefaultKSP(PetscTAO) PetscErrorCode TaoApplyLineSearch(PetscTAO,PetscReal*,PetscReal*,PetscTAOLineSearchConvergedReason*) @cython.internal cdef class _PyTao(_PyObj): pass cdef inline _PyTao PyTao(PetscTAO tao): if tao != NULL and tao.data != NULL: return <_PyTao>tao.data else: return _PyTao.__new__(_PyTao) cdef public PetscErrorCode TaoPythonGetContext(PetscTAO tao, void **ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"TaoPythonGetContext") PyTao(tao).getcontext(ctx) return FunctionEnd() cdef public PetscErrorCode TaoPythonSetContext(PetscTAO tao, void *ctx) \ except PETSC_ERR_PYTHON: FunctionBegin(b"TaoPythonSetContext") PyTao(tao).setcontext(ctx, TAO_(tao)) return FunctionEnd() cdef PetscErrorCode TaoPythonSetType_PYTHON(PetscTAO tao, char name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoPythonSetType_PYTHON") if name == NULL: return FunctionEnd() # XXX cdef object ctx = createcontext(name) TaoPythonSetContext(tao, ctx) PyTao(tao).setname(name) return FunctionEnd() cdef PetscErrorCode TaoPythonGetType_PYTHON(PetscTAO tao, const char *name[]) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoPythonGetType_PYTHON") name[0] = PyTao(tao).getname() return FunctionEnd() cdef PetscErrorCode TaoCreate_Python( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoCreate_Python") # cdef TaoOps ops = tao.ops ops.destroy = TaoDestroy_Python ops.view = TaoView_Python ops.solve = TaoSolve_Python ops.setup = TaoSetUp_Python ops.setfromoptions = TaoSetFromOptions_Python # CHKERR( PetscObjectComposeFunction( tao, b"TaoPythonSetType_C", TaoPythonSetType_PYTHON) ) CHKERR( PetscObjectComposeFunction( tao, b"TaoPythonGetType_C", TaoPythonGetType_PYTHON) ) # CHKERR( TaoCreateDefaultLineSearch(tao) ) CHKERR( TaoCreateDefaultKSP(tao) ) # cdef ctx = PyTao(NULL) tao.data = ctx Py_INCREF(tao.data) return FunctionEnd() cdef inline PetscErrorCode TaoDestroy_Python_inner( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: try: addRef(tao) TaoPythonSetContext(tao, NULL) finally: delRef(tao) Py_DECREF(tao.data) tao.data = NULL return PETSC_SUCCESS cdef PetscErrorCode TaoDestroy_Python( PetscTAO tao, ) \ nogil except PETSC_ERR_PYTHON: FunctionBegin(b"TaoDestroy_Python") CHKERR( PetscObjectComposeFunction( tao, b"TaoPythonSetType_C", NULL) ) CHKERR( PetscObjectComposeFunction( tao, b"TaoPythonGetType_C", NULL) ) # if Py_IsInitialized(): TaoDestroy_Python_inner(tao) return FunctionEnd() cdef PetscErrorCode TaoSetUp_Python( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoSetUp_Python") cdef char name[2048] cdef PetscBool found = PETSC_FALSE if PyTao(tao).self is None: CHKERR( PetscOptionsGetString(NULL, getPrefix(tao), b"-tao_python_type", name, sizeof(name), &found) ) if found and name[0]: CHKERR( TaoPythonSetType_PYTHON(tao, name) ) if PyTao(tao).self is None: return PetscSETERR(PETSC_ERR_USER, "Python context not set, call one of \n" " * TaoPythonSetType(tao, \"[package.]module.class\")\n" " * TaoSetFromOptions(tao) and pass option " "-tao_python_type [package.]module.class") # cdef setUp = PyTao(tao).setUp if setUp is not None: setUp(TAO_(tao)) return FunctionEnd() cdef PetscErrorCode TaoSetFromOptions_Python( PetscTAO tao, PetscOptionItems *PetscOptionsObject, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoSetFromOptions_Python") # cdef char name[2048], *defval = PyTao(tao).getname() cdef PetscBool found = PETSC_FALSE cdef PetscOptionItems *opts "PetscOptionsObject" = PetscOptionsObject CHKERR( PetscOptionsString( b"-tao_python_type", b"Python [package.]module[.{class|function}]", b"TaoPythonSetType", defval, name, sizeof(name), &found) ); opts; if found and name[0]: CHKERR( TaoPythonSetType_PYTHON(tao, name) ) # cdef setFromOptions = PyTao(tao).setFromOptions if setFromOptions is not None: setFromOptions(TAO_(tao)) CHKERR( KSPSetFromOptions(tao.ksp) ) return FunctionEnd() cdef PetscErrorCode TaoView_Python( PetscTAO tao, PetscViewer vwr, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoView_Python") viewcontext(PyTao(tao), vwr) cdef view = PyTao(tao).view if view is not None: view(TAO_(tao), Viewer_(vwr)) return FunctionEnd() cdef PetscErrorCode TaoSolve_Python( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoSolve_Python") # tao.niter = 0 tao.ksp_its = 0 tao.reason = TAO_CONTINUE_ITERATING # cdef solve = PyTao(tao).solve if solve is not None: solve(TAO_(tao)) else: TaoSolve_Python_default(tao) # return FunctionEnd() cdef PetscErrorCode TaoSolve_Python_default( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoSolve_Python_default") # cdef PetscVec X = NULL, G = NULL, S = NULL CHKERR( TaoGetVecs(tao, &X, &G, &S) ) # cdef PetscReal f = 0.0 cdef PetscReal gnorm = 0.0 cdef PetscReal step = 1.0 # if G != NULL: CHKERR( TaoComputeObjectiveAndGradient(tao, X, &f, G) ) CHKERR( VecNorm(G, PETSC_NORM_2, &gnorm) ) else: CHKERR( TaoComputeObjective(tao, X, &f) ) CHKERR( TaoCheckReals(tao, f, gnorm) ) CHKERR( TaoLogConvergenceHistory(tao, f, gnorm, 0.0, tao.ksp_its) ) CHKERR( TaoMonitor(tao, tao.niter, f, gnorm, 0.0, step) ) CHKERR( TaoConverged(tao, &tao.reason) ) cdef PetscObjectState ostate = -1 cdef PetscObjectState nstate = -1 cdef PetscInt its = 0 cdef PetscTAOLineSearchConvergedReason lsr = TAOLINESEARCH_SUCCESS for its from 0 <= its < tao.max_it: if tao.reason: break CHKERR( PetscObjectStateGet(X, &ostate) ) CHKERR( TaoComputeUpdate(tao) ) TaoPreStep_Python(tao) CHKERR( PetscObjectStateGet(X, &nstate) ) if ostate != nstate: if G != NULL: CHKERR( TaoComputeObjectiveAndGradient(tao, X, &f, G) ) CHKERR( VecNorm(G, PETSC_NORM_2, &gnorm) ) else: CHKERR( TaoComputeObjective(tao, X, &f) ) # tao.ksp_its = 0 TaoStep_Python(tao, X, G, S) CHKERR( KSPGetIterationNumber(tao.ksp, &tao.ksp_its) ) tao.ksp_tot_its += tao.ksp_its # if G != NULL: CHKERR( TaoApplyLineSearch(tao, &f, &step, &lsr) ) CHKERR( VecNorm(G, PETSC_NORM_2, &gnorm) ) if lsr < TAOLINESEARCH_CONTINUE_ITERATING: tao.reason = TAO_DIVERGED_LS_FAILURE else: CHKERR( TaoComputeObjective(tao, X, &f) ) CHKERR( TaoCheckReals(tao, f, gnorm) ) tao.niter += 1 # TaoPostStep_Python(tao) CHKERR( TaoLogConvergenceHistory(tao, f, gnorm, 0.0, tao.ksp_its) ) CHKERR( TaoMonitor(tao, tao.niter, f, gnorm, 0.0, step) ) CHKERR( TaoConverged(tao, &tao.reason) ) if tao.niter == tao.max_it: if tao.reason <= 0: tao.reason = TAO_DIVERGED_MAXITS # return FunctionEnd() cdef PetscErrorCode TaoStep_Python( PetscTAO tao, PetscVec X, PetscVec G, PetscVec S, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoStep_Python") cdef step = PyTao(tao).step if step is not None: step(TAO_(tao), Vec_(X), Vec_(G) if G != NULL else None, Vec_(S) if S != NULL else None) else: # TaoStep_Python_default(tao,X,G,S) CHKERR( TaoComputeGradient(tao, X, S) ) CHKERR( VecCopy(G, S) ) CHKERR( VecScale(S, -1.0) ) return FunctionEnd() cdef PetscErrorCode TaoPreStep_Python( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoPreStep_Python") cdef preStep = PyTao(tao).preStep if preStep is not None: preStep(TAO_(tao)) return FunctionEnd() cdef PetscErrorCode TaoPostStep_Python( PetscTAO tao, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"TaoPostStep_Python") cdef postStep = PyTao(tao).postStep if postStep is not None: postStep(TAO_(tao)) return FunctionEnd() # -------------------------------------------------------------------- cdef PetscErrorCode PetscPythonMonitorSet_Python( PetscObject obj_p, const char *url_p, ) \ except PETSC_ERR_PYTHON with gil: FunctionBegin(b"PetscPythonMonitorSet_Python") assert obj_p != NULL assert url_p != NULL assert url_p[0] != 0 # cdef PetscClassId classid = 0 CHKERR( PetscObjectGetClassId(obj_p, &classid) ) cdef type klass = PyPetscType_Lookup(classid) cdef Object ob = klass() ob.obj[0] = newRef(obj_p) # cdef url = bytes2str(url_p) if ':' in url: path, names = parse_url(url) else: path, names = url, 'monitor' module = load_module(path) for attr in names.split(','): monitor = getattr(module, attr) if isinstance(monitor, type): monitor = monitor(ob) ob.setMonitor(monitor) # return FunctionEnd() # -------------------------------------------------------------------- cdef extern from * nogil: ctypedef PetscErrorCode MatCreateFunction (PetscMat) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PCCreateFunction (PetscPC) except PETSC_ERR_PYTHON ctypedef PetscErrorCode KSPCreateFunction (PetscKSP) except PETSC_ERR_PYTHON ctypedef PetscErrorCode SNESCreateFunction (PetscSNES) except PETSC_ERR_PYTHON ctypedef PetscErrorCode TSCreateFunction (PetscTS) except PETSC_ERR_PYTHON ctypedef PetscErrorCode TaoCreateFunction (PetscTAO) except PETSC_ERR_PYTHON PetscErrorCode MatRegister (const char[],MatCreateFunction* ) PetscErrorCode PCRegister (const char[],PCCreateFunction* ) PetscErrorCode KSPRegister (const char[],KSPCreateFunction* ) PetscErrorCode SNESRegister (const char[],SNESCreateFunction*) PetscErrorCode TSRegister (const char[],TSCreateFunction* ) PetscErrorCode TaoRegister (const char[],TaoCreateFunction* ) PetscErrorCode (*PetscPythonMonitorSet_C) \ (PetscObject, const char[]) except PETSC_ERR_PYTHON cdef public PetscErrorCode PetscPythonRegisterAll() except PETSC_ERR_PYTHON: FunctionBegin(b"PetscPythonRegisterAll") # Python subtypes CHKERR( MatRegister ( MATPYTHON, MatCreate_Python ) ) CHKERR( PCRegister ( PCPYTHON, PCCreate_Python ) ) CHKERR( KSPRegister ( KSPPYTHON, KSPCreate_Python ) ) CHKERR( SNESRegister( SNESPYTHON, SNESCreate_Python ) ) CHKERR( TSRegister ( TSPYTHON, TSCreate_Python ) ) CHKERR( TaoRegister ( TAOPYTHON, TaoCreate_Python ) ) # Python monitors global PetscPythonMonitorSet_C PetscPythonMonitorSet_C = PetscPythonMonitorSet_Python return FunctionEnd() # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscao.pxi000066400000000000000000000020541454104047300210300ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscAOType "AOType" PetscAOType AOBASIC PetscAOType AOADVANCED PetscAOType AOMAPPING PetscAOType AOMEMORYSCALABLE PetscErrorCode AOView(PetscAO,PetscViewer) PetscErrorCode AODestroy(PetscAO*) PetscErrorCode AOCreateBasic(MPI_Comm,PetscInt,const PetscInt[],const PetscInt[],PetscAO*) PetscErrorCode AOCreateBasicIS(PetscIS,PetscIS,PetscAO*) PetscErrorCode AOCreateMemoryScalable(MPI_Comm,PetscInt,const PetscInt[],const PetscInt[],PetscAO*) PetscErrorCode AOCreateMemoryScalableIS(PetscIS,PetscIS,PetscAO*) PetscErrorCode AOCreateMapping(MPI_Comm,PetscInt,const PetscInt[],const PetscInt[],PetscAO*) PetscErrorCode AOCreateMappingIS(PetscIS,PetscIS,PetscAO*) PetscErrorCode AOGetType(PetscAO,PetscAOType*) PetscErrorCode AOApplicationToPetsc(PetscAO,PetscInt,PetscInt[]) PetscErrorCode AOApplicationToPetscIS(PetscAO,PetscIS) PetscErrorCode AOPetscToApplication(PetscAO,PetscInt,PetscInt[]) PetscErrorCode AOPetscToApplicationIS(PetscAO,PetscIS) petsc4py-3.19.6/src/petsc4py/PETSc/petscdef.pxi000066400000000000000000000040761454104047300211750ustar00rootroot00000000000000cdef extern from * nogil: enum: PETSC_DECIDE enum: PETSC_DEFAULT enum: PETSC_DETERMINE PetscReal PETSC_INFINITY PetscReal PETSC_NINFINITY ctypedef enum PetscBool: PETSC_FALSE PETSC_TRUE ctypedef enum PetscInsertMode "InsertMode": PETSC_NOT_SET_VALUES "NOT_SET_VALUES" PETSC_INSERT_VALUES "INSERT_VALUES" PETSC_ADD_VALUES "ADD_VALUES" PETSC_MAX_VALUES "MAX_VALUES" PETSC_INSERT_ALL_VALUES "INSERT_ALL_VALUES" PETSC_ADD_ALL_VALUES "ADD_ALL_VALUES" PETSC_INSERT_BC_VALUES "INSERT_BC_VALUES" PETSC_ADD_BC_VALUES "ADD_BC_VALUES" ctypedef enum PetscScatterMode "ScatterMode": PETSC_SCATTER_FORWARD "SCATTER_FORWARD" PETSC_SCATTER_REVERSE "SCATTER_REVERSE" PETSC_SCATTER_FORWARD_LOCAL "SCATTER_FORWARD_LOCAL" PETSC_SCATTER_REVERSE_LOCAL "SCATTER_REVERSE_LOCAL" 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 PetscCopyMode: PETSC_COPY_VALUES PETSC_OWN_POINTER PETSC_USE_POINTER cdef inline PetscInsertMode insertmode(object mode) \ except (-1): if mode is None: return PETSC_INSERT_VALUES elif mode is True: return PETSC_ADD_VALUES elif mode is False: return PETSC_INSERT_VALUES else: return mode cdef inline PetscScatterMode scattermode(object mode) \ except (-1): if mode is None: return PETSC_SCATTER_FORWARD if mode is False: return PETSC_SCATTER_FORWARD if mode is True: return PETSC_SCATTER_REVERSE if isinstance(mode, str): if mode == 'forward': return PETSC_SCATTER_FORWARD if mode == 'reverse': return PETSC_SCATTER_REVERSE else: raise ValueError("unknown scatter mode: %s" % mode) return mode petsc4py-3.19.6/src/petsc4py/PETSc/petscdevice.pxi000066400000000000000000000112121454104047300216640ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscOffloadMask: PETSC_OFFLOAD_UNALLOCATED PETSC_OFFLOAD_CPU PETSC_OFFLOAD_GPU PETSC_OFFLOAD_BOTH PETSC_OFFLOAD_KOKKOS ctypedef enum PetscMemType: PETSC_MEMTYPE_HOST PETSC_MEMTYPE_CUDA PETSC_MEMTYPE_HIP PETSC_MEMTYPE_SYCL ctypedef enum PetscDeviceType: PETSC_DEVICE_HOST PETSC_DEVICE_CUDA PETSC_DEVICE_HIP PETSC_DEVICE_SYCL ctypedef enum PetscStreamType: PETSC_STREAM_GLOBAL_BLOCKING PETSC_STREAM_DEFAULT_BLOCKING PETSC_STREAM_GLOBAL_NONBLOCKING ctypedef enum PetscDeviceContextJoinMode: PETSC_DEVICE_CONTEXT_JOIN_DESTROY PETSC_DEVICE_CONTEXT_JOIN_SYNC PETSC_DEVICE_CONTEXT_JOIN_NO_SYNC PetscErrorCode PetscDeviceCreate(PetscDeviceType, PetscInt, PetscDevice *) PetscErrorCode PetscDeviceDestroy(PetscDevice *) PetscErrorCode PetscDeviceConfigure(PetscDevice) PetscErrorCode PetscDeviceView(PetscDevice, PetscViewer) PetscErrorCode PetscDeviceGetType(PetscDevice, PetscDeviceType *) PetscErrorCode PetscDeviceGetDeviceId(PetscDevice, PetscInt *) PetscDeviceType PETSC_DEVICE_DEFAULT() PetscErrorCode PetscDeviceSetDefaultDeviceType(PetscDeviceType) PetscErrorCode PetscDeviceInitialize(PetscDeviceType) PetscBool PetscDeviceInitialized(PetscDeviceType) PetscErrorCode PetscDeviceContextCreate(PetscDeviceContext *) PetscErrorCode PetscDeviceContextDestroy(PetscDeviceContext *) PetscErrorCode PetscDeviceContextSetStreamType(PetscDeviceContext, PetscStreamType) PetscErrorCode PetscDeviceContextGetStreamType(PetscDeviceContext, PetscStreamType *) PetscErrorCode PetscDeviceContextSetDevice(PetscDeviceContext, PetscDevice) PetscErrorCode PetscDeviceContextGetDevice(PetscDeviceContext, PetscDevice *) PetscErrorCode PetscDeviceContextGetDeviceType(PetscDeviceContext, PetscDeviceType *) PetscErrorCode PetscDeviceContextSetUp(PetscDeviceContext) PetscErrorCode PetscDeviceContextDuplicate(PetscDeviceContext, PetscDeviceContext *) PetscErrorCode PetscDeviceContextQueryIdle(PetscDeviceContext, PetscBool *) PetscErrorCode PetscDeviceContextWaitForContext(PetscDeviceContext, PetscDeviceContext) PetscErrorCode PetscDeviceContextForkWithStreamType(PetscDeviceContext, PetscStreamType, PetscInt, PetscDeviceContext **) PetscErrorCode PetscDeviceContextFork(PetscDeviceContext, PetscInt, PetscDeviceContext **) PetscErrorCode PetscDeviceContextJoin(PetscDeviceContext, PetscInt, PetscDeviceContextJoinMode, PetscDeviceContext **) PetscErrorCode PetscDeviceContextSynchronize(PetscDeviceContext) PetscErrorCode PetscDeviceContextSetFromOptions(MPI_Comm, PetscDeviceContext) PetscErrorCode PetscDeviceContextView(PetscDeviceContext, PetscViewer) PetscErrorCode PetscDeviceContextViewFromOptions(PetscDeviceContext, PetscObject, const char name[]) PetscErrorCode PetscDeviceContextGetCurrentContext(PetscDeviceContext *) PetscErrorCode PetscDeviceContextSetCurrentContext(PetscDeviceContext) cdef inline PetscDeviceType asDeviceType(object dtype) except (-1): if isinstance(dtype, str): dtype = dtype.upper() try: return getattr(Device.Type, dtype) except AttributeError: raise ValueError("unknown device type: %s" % dtype) return dtype cdef inline str toDeviceType(PetscDeviceType dtype): try: return Device.Type.__enum2str[dtype] except KeyError: raise NotImplementedError("unhandled PetscDeviceType %d" % dtype) cdef inline PetscStreamType asStreamType(object stype) except (-1): if isinstance(stype, str): stype = stype.upper() try: return getattr(DeviceContext.StreamType, stype) except AttributeError: raise ValueError("unknown stream type: %s" % stype) return stype cdef inline str toStreamType(PetscStreamType stype): try: return DeviceContext.StreamType.__enum2str[stype] except KeyError: raise NotImplementedError("unhandled PetscStreamType %d" % stype) cdef inline PetscDeviceContextJoinMode asJoinMode(object jmode) except (-1): if isinstance(jmode, str): jmode = jmode.upper() try: return getattr(DeviceContext.JoinMode, jmode) except AttributeError: raise ValueError("unknown join mode: %s" % jmode) return jmode cdef inline str toJoinMode(PetscDeviceContextJoinMode jmode): try: return DeviceContext.JoinMode.__enum2str[jmode] except KeyError: raise NotImplementedError("unhandled PetscDeviceContextJoinMode %d" % jmode) petsc4py-3.19.6/src/petsc4py/PETSc/petscdm.pxi000066400000000000000000000300051454104047300210260ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef const char* PetscDMType "DMType" PetscDMType DMDA_type "DMDA" PetscDMType DMCOMPOSITE PetscDMType DMSLICED PetscDMType DMSHELL PetscDMType DMPLEX PetscDMType DMREDUNDANT PetscDMType DMPATCH PetscDMType DMMOAB PetscDMType DMNETWORK PetscDMType DMFOREST PetscDMType DMP4EST PetscDMType DMP8EST PetscDMType DMSWARM PetscDMType DMPRODUCT PetscDMType DMSTAG ctypedef enum PetscDMBoundaryType"DMBoundaryType": DM_BOUNDARY_NONE DM_BOUNDARY_GHOSTED DM_BOUNDARY_MIRROR DM_BOUNDARY_PERIODIC DM_BOUNDARY_TWIST ctypedef enum PetscDMPolytopeType "DMPolytopeType": DM_POLYTOPE_POINT DM_POLYTOPE_SEGMENT DM_POLYTOPE_POINT_PRISM_TENSOR DM_POLYTOPE_TRIANGLE DM_POLYTOPE_QUADRILATERAL DM_POLYTOPE_SEG_PRISM_TENSOR DM_POLYTOPE_TETRAHEDRON DM_POLYTOPE_HEXAHEDRON DM_POLYTOPE_TRI_PRISM DM_POLYTOPE_TRI_PRISM_TENSOR DM_POLYTOPE_QUAD_PRISM_TENSOR DM_POLYTOPE_PYRAMID DM_POLYTOPE_FV_GHOST DM_POLYTOPE_INTERIOR_GHOST DM_POLYTOPE_UNKNOWN DM_NUM_POLYTOPES ctypedef PetscErrorCode (*PetscDMCoarsenHook)(PetscDM, PetscDM, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMRestrictHook)(PetscDM, PetscMat, PetscVec, PetscMat, PetscDM, void*) except PETSC_ERR_PYTHON PetscErrorCode DMCreate(MPI_Comm,PetscDM*) PetscErrorCode DMClone(PetscDM,PetscDM*) PetscErrorCode DMDestroy(PetscDM*) PetscErrorCode DMView(PetscDM,PetscViewer) PetscErrorCode DMLoad(PetscDM,PetscViewer) PetscErrorCode DMSetType(PetscDM,PetscDMType) PetscErrorCode DMGetType(PetscDM,PetscDMType*) PetscErrorCode DMGetDimension(PetscDM,PetscInt*) PetscErrorCode DMSetDimension(PetscDM,PetscInt) PetscErrorCode DMSetOptionsPrefix(PetscDM,char[]) PetscErrorCode DMGetOptionsPrefix(PetscDM,char*[]) PetscErrorCode DMAppendOptionsPrefix(PetscDM,char[]) PetscErrorCode DMSetFromOptions(PetscDM) PetscErrorCode DMViewFromOptions(PetscDM,PetscObject,char[]) PetscErrorCode DMSetUp(PetscDM) PetscErrorCode DMGetAdjacency(PetscDM,PetscInt,PetscBool*,PetscBool*) PetscErrorCode DMSetAdjacency(PetscDM,PetscInt,PetscBool,PetscBool) PetscErrorCode DMGetBasicAdjacency(PetscDM,PetscBool*,PetscBool*) PetscErrorCode DMSetBasicAdjacency(PetscDM,PetscBool,PetscBool) PetscErrorCode DMSetNumFields(PetscDM,PetscInt) PetscErrorCode DMGetNumFields(PetscDM,PetscInt*) PetscErrorCode DMSetField(PetscDM,PetscInt,PetscDMLabel,PetscObject) PetscErrorCode DMAddField(PetscDM,PetscDMLabel,PetscObject) PetscErrorCode DMGetField(PetscDM,PetscInt,PetscDMLabel*,PetscObject*) PetscErrorCode DMClearFields(PetscDM) PetscErrorCode DMCopyFields(PetscDM,PetscDM) PetscErrorCode DMCreateDS(PetscDM) PetscErrorCode DMClearDS(PetscDM) PetscErrorCode DMGetDS(PetscDM,PetscDS*) PetscErrorCode DMCopyDS(PetscDM,PetscDM) PetscErrorCode DMCopyDisc(PetscDM,PetscDM) PetscErrorCode DMGetBlockSize(PetscDM,PetscInt*) PetscErrorCode DMSetVecType(PetscDM,PetscVecType) PetscErrorCode DMCreateLocalVector(PetscDM,PetscVec*) PetscErrorCode DMCreateGlobalVector(PetscDM,PetscVec*) PetscErrorCode DMGetLocalVector(PetscDM,PetscVec*) PetscErrorCode DMRestoreLocalVector(PetscDM,PetscVec*) PetscErrorCode DMGetGlobalVector(PetscDM,PetscVec*) PetscErrorCode DMRestoreGlobalVector(PetscDM,PetscVec*) PetscErrorCode DMSetMatType(PetscDM,PetscMatType) PetscErrorCode DMCreateMatrix(PetscDM,PetscMat*) PetscErrorCode DMCreateMassMatrix(PetscDM,PetscDM,PetscMat*) PetscErrorCode DMGetCoordinateDM(PetscDM,PetscDM*) PetscErrorCode DMGetCoordinateSection(PetscDM,PetscSection*) PetscErrorCode DMSetCoordinates(PetscDM,PetscVec) PetscErrorCode DMGetCoordinates(PetscDM,PetscVec*) PetscErrorCode DMSetCoordinatesLocal(PetscDM,PetscVec) PetscErrorCode DMGetCoordinatesLocal(PetscDM,PetscVec*) PetscErrorCode DMGetCoordinateDim(PetscDM,PetscInt*) PetscErrorCode DMSetCoordinateDim(PetscDM,PetscInt) PetscErrorCode DMLocalizeCoordinates(PetscDM) PetscErrorCode DMProjectCoordinates(PetscDM, PetscFE) PetscErrorCode DMCreateInterpolation(PetscDM,PetscDM,PetscMat*,PetscVec*) PetscErrorCode DMCreateInjection(PetscDM,PetscDM,PetscMat*) PetscErrorCode DMCreateRestriction(PetscDM,PetscDM,PetscMat*) PetscErrorCode DMConvert(PetscDM,PetscDMType,PetscDM*) PetscErrorCode DMRefine(PetscDM,MPI_Comm,PetscDM*) PetscErrorCode DMCoarsen(PetscDM,MPI_Comm,PetscDM*) PetscErrorCode DMRefineHierarchy(PetscDM,PetscInt,PetscDM[]) PetscErrorCode DMCoarsenHierarchy(PetscDM,PetscInt,PetscDM[]) PetscErrorCode DMGetRefineLevel(PetscDM,PetscInt*) PetscErrorCode DMSetRefineLevel(PetscDM,PetscInt) PetscErrorCode DMGetCoarsenLevel(PetscDM,PetscInt*) PetscErrorCode DMAdaptLabel(PetscDM,PetscDMLabel,PetscDM*) PetscErrorCode DMAdaptMetric(PetscDM,PetscVec,PetscDMLabel,PetscDMLabel,PetscDM*) PetscErrorCode DMGlobalToLocalBegin(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMGlobalToLocalEnd(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMLocalToGlobalBegin(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMLocalToGlobalEnd(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMLocalToLocalBegin(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMLocalToLocalEnd(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMGetLocalToGlobalMapping(PetscDM,PetscLGMap*) PetscErrorCode DMSetSection(PetscDM,PetscSection) PetscErrorCode DMGetSection(PetscDM,PetscSection*) PetscErrorCode DMSetLocalSection(PetscDM,PetscSection) PetscErrorCode DMGetLocalSection(PetscDM,PetscSection*) PetscErrorCode DMSetGlobalSection(PetscDM,PetscSection) PetscErrorCode DMGetGlobalSection(PetscDM,PetscSection*) PetscErrorCode DMCreateSectionSF(PetscDM,PetscSection,PetscSection) PetscErrorCode DMGetSectionSF(PetscDM,PetscSF*) PetscErrorCode DMSetSectionSF(PetscDM,PetscSF) PetscErrorCode DMGetPointSF(PetscDM,PetscSF*) PetscErrorCode DMSetPointSF(PetscDM,PetscSF) PetscErrorCode DMCreateSubDM(PetscDM, PetscInt, const PetscInt[], PetscIS*, PetscDM*) PetscErrorCode DMSetAuxiliaryVec(PetscDM, PetscDMLabel, PetscInt, PetscInt, PetscVec) PetscErrorCode DMGetAuxiliaryVec(PetscDM, PetscDMLabel, PetscInt, PetscInt, PetscVec*) PetscErrorCode DMCreateLabel(PetscDM,const char[]) PetscErrorCode DMGetLabelValue(PetscDM,const char[],PetscInt,PetscInt*) PetscErrorCode DMSetLabelValue(PetscDM,const char[],PetscInt,PetscInt) PetscErrorCode DMHasLabel(PetscDM,const char[],PetscBool*) PetscErrorCode DMClearLabelValue(PetscDM,const char[],PetscInt,PetscInt) PetscErrorCode DMGetLabelSize(PetscDM,const char[],PetscInt*) PetscErrorCode DMGetLabelIdIS(PetscDM,const char[],PetscIS*) PetscErrorCode DMGetStratumSize(PetscDM,const char[],PetscInt,PetscInt*) PetscErrorCode DMGetStratumIS(PetscDM,const char[],PetscInt,PetscIS*) PetscErrorCode DMClearLabelStratum(PetscDM,const char[],PetscInt) PetscErrorCode DMSetLabelOutput(PetscDM,const char[],PetscBool) PetscErrorCode DMGetLabelOutput(PetscDM,const char[],PetscBool*) PetscErrorCode DMGetNumLabels(PetscDM,PetscInt*) PetscErrorCode DMGetLabelName(PetscDM,PetscInt,const char**) PetscErrorCode DMHasLabel(PetscDM,const char[],PetscBool*) PetscErrorCode DMGetLabel(PetscDM,const char*,PetscDMLabel*) PetscErrorCode DMAddLabel(PetscDM,PetscDMLabel) PetscErrorCode DMRemoveLabel(PetscDM,const char[],PetscDMLabel*) PetscErrorCode DMLabelDestroy(PetscDMLabel *) #int DMCopyLabels(PetscDM,PetscDM) PetscErrorCode DMShellSetGlobalVector(PetscDM,PetscVec) PetscErrorCode DMShellSetLocalVector(PetscDM,PetscVec) PetscErrorCode DMKSPSetComputeOperators(PetscDM,PetscKSPComputeOpsFunction,void*) PetscErrorCode DMCreateFieldDecomposition(PetscDM,PetscInt*,char***,PetscIS**,PetscDM**) PetscErrorCode DMSNESSetFunction(PetscDM,PetscSNESFunctionFunction,void*) PetscErrorCode DMSNESSetJacobian(PetscDM,PetscSNESJacobianFunction,void*) PetscErrorCode DMCoarsenHookAdd(PetscDM,PetscDMCoarsenHook,PetscDMRestrictHook,void*) # -------------------------------------------------------------------- cdef inline PetscDMBoundaryType asBoundaryType(object boundary) \ except (-1): if boundary is None: return DM_BOUNDARY_NONE if boundary is False: return DM_BOUNDARY_NONE if boundary is True: return DM_BOUNDARY_PERIODIC if isinstance(boundary, str): if boundary == 'none': return DM_BOUNDARY_NONE elif boundary == 'ghosted': return DM_BOUNDARY_GHOSTED elif boundary == 'mirror': return DM_BOUNDARY_MIRROR elif boundary == 'periodic': return DM_BOUNDARY_PERIODIC elif boundary == 'twist': return DM_BOUNDARY_TWIST else: raise ValueError("unknown boundary type: %s" % boundary) return boundary cdef inline PetscInt asBoundary(object boundary, PetscDMBoundaryType *_x, PetscDMBoundaryType *_y, PetscDMBoundaryType *_z) except -1: cdef PetscInt dim = 0 cdef object x=None, y=None, z=None if (boundary is None or isinstance(boundary, str) or isinstance(boundary, int)): _x[0] = _y[0] = _z[0] = asBoundaryType(boundary) else: _x[0] = _y[0] = _z[0] = DM_BOUNDARY_NONE boundary = tuple(boundary) dim = len(boundary) if dim == 0: pass elif dim == 1: (x,) = boundary elif dim == 2: (x, y) = boundary elif dim == 3: (x, y, z) = boundary if dim >= 1: _x[0] = asBoundaryType(x) if dim >= 2: _y[0] = asBoundaryType(y) if dim >= 3: _z[0] = asBoundaryType(z) return dim cdef inline object toBoundary(PetscInt dim, PetscDMBoundaryType x, PetscDMBoundaryType y, PetscDMBoundaryType z): if dim == 0: return () elif dim == 1: return (x,) elif dim == 2: return (x, y) elif dim == 3: return (x, y, z) # ----------------------------------------------------------------------------- cdef inline DM ref_DM(PetscDM dm): cdef DM ob = DM() ob.dm = dm PetscINCREF(ob.obj) return ob # -------------------------------------------------------------------- cdef PetscErrorCode DM_PyCoarsenHook( PetscDM fine, PetscDM coarse, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef DM Fine = ref_DM(fine) cdef DM Coarse = ref_DM(coarse) cdef object hooks = Fine.get_attr('__coarsenhooks__') assert hooks is not None and type(hooks) is list for hook in hooks: (hookop, args, kargs) = hook hookop(Fine, Coarse, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DM_PyRestrictHook( PetscDM fine, PetscMat mrestrict, PetscVec rscale, PetscMat inject, PetscDM coarse, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef DM Fine = ref_DM(fine) cdef Mat Mrestrict = ref_Mat(mrestrict) cdef Vec Rscale = ref_Vec(rscale) cdef Mat Inject = ref_Mat(inject) cdef DM Coarse = ref_DM(coarse) cdef object hooks = Fine.get_attr('__restricthooks__') assert hooks is not None and type(hooks) is list for hook in hooks: (hookop, args, kargs) = hook hookop(Fine, Mrestrict, Rscale, Inject, Coarse, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscdmcomposite.pxi000066400000000000000000000043611454104047300227570ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: PetscErrorCode DMCompositeCreate(MPI_Comm,PetscDM*) PetscErrorCode DMCompositeAddDM(PetscDM,PetscDM) PetscErrorCode DMCompositeGetNumberDM(PetscDM,PetscInt*) PetscErrorCode DMCompositeScatterArray(PetscDM,PetscVec,PetscVec*) PetscErrorCode DMCompositeGatherArray(PetscDM,PetscInsertMode,PetscVec,PetscVec*) PetscErrorCode DMCompositeGetEntriesArray(PetscDM,PetscDM*) PetscErrorCode DMCompositeGetAccessArray(PetscDM,PetscVec,PetscInt,const PetscInt*,PetscVec*) PetscErrorCode DMCompositeRestoreAccessArray(PetscDM,PetscVec,PetscInt,const PetscInt*,PetscVec*) PetscErrorCode DMCompositeGetGlobalISs(PetscDM,PetscIS**) PetscErrorCode DMCompositeGetLocalISs(PetscDM,PetscIS**) PetscErrorCode DMCompositeGetISLocalToGlobalMappings(PetscDM,PetscLGMap**) cdef class _DMComposite_access: cdef PetscDM dm cdef PetscVec gvec cdef PetscInt nlocs cdef PetscInt *locs cdef PetscVec *vecs cdef object locs_mem cdef object vecs_mem cdef object access def __cinit__(self, DM dm, Vec gvec, locs=None): self.dm = dm.dm CHKERR( PetscINCREF(&self.dm) ) self.gvec = gvec.vec CHKERR( PetscINCREF(&self.gvec) ) if locs is None: CHKERR( DMCompositeGetNumberDM(self.dm, &self.nlocs) ) locs = arange(0, self.nlocs, 1) self.locs_mem = iarray_i(locs, &self.nlocs, &self.locs) self.vecs_mem = oarray_p(empty_p(self.nlocs), NULL, &self.vecs) self.access = None def __dealloc__(self): CHKERR( DMDestroy(&self.dm) ) CHKERR( VecDestroy(&self.gvec) ) def __enter__(self): cdef Py_ssize_t i, n = self.nlocs CHKERR( DMCompositeGetAccessArray(self.dm, self.gvec, self.nlocs, self.locs, self.vecs) ) self.access = [ref_Vec(self.vecs[i]) for i from 0 <= i < n] return tuple(self.access) def __exit__(self, *exc): cdef Py_ssize_t i, n = self.nlocs for i from 0 <= i < n: (self.access[i]).vec = NULL CHKERR( DMCompositeRestoreAccessArray(self.dm, self.gvec, self.nlocs, self.locs, self.vecs) ) self.access = None petsc4py-3.19.6/src/petsc4py/PETSc/petscdmda.pxi000066400000000000000000000303631454104047300213420ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscDMDAStencilType"DMDAStencilType": DMDA_STENCIL_STAR DMDA_STENCIL_BOX ctypedef enum PetscDMDAInterpolationType"DMDAInterpolationType": DMDA_INTERPOLATION_Q0 "DMDA_Q0" DMDA_INTERPOLATION_Q1 "DMDA_Q1" ctypedef enum PetscDMDAElementType"DMDAElementType": DMDA_ELEMENT_P1 DMDA_ELEMENT_Q1 PetscErrorCode DMDACreateND(MPI_Comm, PetscInt,PetscInt, # dim, dof PetscInt,PetscInt,PetscInt, # M, N, P PetscInt,PetscInt,PetscInt, # m, n, p PetscInt[],PetscInt[],PetscInt[], # lx, ly, lz PetscDMBoundaryType, # bx PetscDMBoundaryType, # by PetscDMBoundaryType, # bz PetscDMDAStencilType, # stencil type PetscInt, # stencil width PetscDM*) PetscErrorCode DMDASetDof(PetscDM,PetscInt) PetscErrorCode DMDASetSizes(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMDASetNumProcs(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMDASetBoundaryType(PetscDM,PetscDMBoundaryType,PetscDMBoundaryType,PetscDMBoundaryType) PetscErrorCode DMDASetStencilType(PetscDM,PetscDMDAStencilType) PetscErrorCode DMDASetStencilWidth(PetscDM,PetscInt) PetscErrorCode DMDAGetInfo(PetscDM, PetscInt*, PetscInt*,PetscInt*,PetscInt*, PetscInt*,PetscInt*,PetscInt*, PetscInt*,PetscInt*, PetscDMBoundaryType*, PetscDMBoundaryType*, PetscDMBoundaryType*, PetscDMDAStencilType*) PetscErrorCode DMDAGetCorners(PetscDM, PetscInt*,PetscInt*,PetscInt*, PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMDAGetGhostCorners(PetscDM, PetscInt*,PetscInt*,PetscInt*, PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMDAGetOwnershipRanges(PetscDM, const PetscInt*[], const PetscInt*[], const PetscInt*[]) PetscErrorCode DMDASetUniformCoordinates(PetscDM, PetscReal,PetscReal, PetscReal,PetscReal, PetscReal,PetscReal) PetscErrorCode DMGetBoundingBox(PetscDM,PetscReal[],PetscReal[]) PetscErrorCode DMGetLocalBoundingBox(PetscDM,PetscReal[],PetscReal[]) PetscErrorCode DMDACreateNaturalVector(PetscDM,PetscVec*) PetscErrorCode DMDAGlobalToNaturalBegin(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMDAGlobalToNaturalEnd(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMDANaturalToGlobalBegin(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMDANaturalToGlobalEnd(PetscDM,PetscVec,PetscInsertMode,PetscVec) PetscErrorCode DMDAGetAO(PetscDM,PetscAO*) PetscErrorCode DMDAGetScatter(PetscDM,PetscScatter*,PetscScatter*) PetscErrorCode DMDASetRefinementFactor(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMDAGetRefinementFactor(PetscDM,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMDASetInterpolationType(PetscDM,PetscDMDAInterpolationType) PetscErrorCode DMDAGetInterpolationType(PetscDM,PetscDMDAInterpolationType*) PetscErrorCode DMDASetElementType(PetscDM,PetscDMDAElementType) PetscErrorCode DMDAGetElementType(PetscDM,PetscDMDAElementType*) PetscErrorCode DMDAGetElements(PetscDM,PetscInt*,PetscInt*,const PetscInt**) PetscErrorCode DMDARestoreElements(PetscDM,PetscInt*,PetscInt*,const PetscInt**) PetscErrorCode DMDASetFieldName(PetscDM,PetscInt,const char[]) PetscErrorCode DMDAGetFieldName(PetscDM,PetscInt,const char*[]) PetscErrorCode DMDASetCoordinateName(PetscDM,PetscInt,const char[]) PetscErrorCode DMDAGetCoordinateName(PetscDM,PetscInt,const char*[]) # -------------------------------------------------------------------- cdef inline PetscDMDAStencilType asStencil(object stencil) \ except (-1): if isinstance(stencil, str): if stencil == "star": return DMDA_STENCIL_STAR elif stencil == "box": return DMDA_STENCIL_BOX else: raise ValueError("unknown stencil type: %s" % stencil) return stencil cdef inline object toStencil(PetscDMDAStencilType stype): if stype == DMDA_STENCIL_STAR: return "star" elif stype == DMDA_STENCIL_BOX: return "box" cdef inline PetscDMDAInterpolationType dainterpolationtype(object itype) \ except (-1): if (isinstance(itype, str)): if itype in ("q0", "Q0"): return DMDA_INTERPOLATION_Q0 if itype in ("q1", "Q1"): return DMDA_INTERPOLATION_Q1 else: raise ValueError("unknown interpolation type: %s" % itype) return itype cdef inline PetscDMDAElementType daelementtype(object etype) \ except (-1): if (isinstance(etype, str)): if etype in ("p1", "P1"): return DMDA_ELEMENT_P1 if etype in ("q1", "Q1"): return DMDA_ELEMENT_Q1 else: raise ValueError("unknown element type: %s" % etype) return etype cdef inline PetscErrorCode DMDAGetDim(PetscDM da, PetscInt *dim) nogil: return DMDAGetInfo(da, dim, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) cdef inline PetscInt asDims(dims, PetscInt *_M, PetscInt *_N, PetscInt *_P) except? -1: cdef PetscInt dim = PETSC_DECIDE cdef object M=None, N=None, P=None dims = tuple(dims) dim = len(dims) if dim == 0: pass elif dim == 1: M, = dims elif dim == 2: M, N = dims elif dim == 3: M, N, P = dims if dim >= 1: _M[0] = asInt(M) if dim >= 2: _N[0] = asInt(N) if dim >= 3: _P[0] = asInt(P) return dim cdef inline tuple toDims(PetscInt dim, PetscInt M, PetscInt N, PetscInt P): if dim == 0: return () elif dim == 1: return (toInt(M),) elif dim == 2: return (toInt(M), toInt(N)) elif dim == 3: return (toInt(M), toInt(N), toInt(P)) cdef inline tuple asOwnershipRanges(object ownership_ranges, PetscInt dim, PetscInt *m, PetscInt *n, PetscInt *p, PetscInt **_x, PetscInt **_y, PetscInt **_z): cdef object ranges = list(ownership_ranges) cdef PetscInt rdim = len(ranges) cdef PetscInt nlx=0, nly=0, nlz=0 if dim == PETSC_DECIDE: dim = rdim elif dim != rdim: raise ValueError( "number of dimensions %d and number ownership ranges %d" % (toInt(dim), toInt(rdim))) if dim >= 1: ranges[0] = iarray_i(ranges[0], &nlx, _x) if m[0] == PETSC_DECIDE: m[0] = nlx elif m[0] != nlx: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nlx), toInt(m[0]))) if dim >= 2: ranges[1] = iarray_i(ranges[1], &nly, _y) if n[0] == PETSC_DECIDE: n[0] = nly elif n[0] != nly: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nly), toInt(n[0]))) if dim >= 3: ranges[2] = iarray_i(ranges[2], &nlz, _z) if p[0] == PETSC_DECIDE: p[0] = nlz elif p[0] != nlz: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nlz), toInt(p[0]))) return tuple(ranges) cdef inline tuple toOwnershipRanges(PetscInt dim, PetscInt m, PetscInt n, PetscInt p, const PetscInt *lx, const PetscInt *ly, const PetscInt *lz): # Returns tuple of arrays containing ownership ranges as Python arrays ranges = [array_i(m, lx)] if dim > 1: ranges.append(array_i(n, ly)) if dim > 2: ranges.append(array_i(p, lz)) return tuple(ranges) # -------------------------------------------------------------------- cdef class _DMDA_Vec_array(object): cdef _Vec_buffer vecbuf cdef readonly tuple starts, sizes cdef readonly tuple shape, strides cdef readonly ndarray array def __cinit__(self, DMDA da, Vec vec, bint DOF=False): # cdef PetscInt dim=0, dof=0 CHKERR( DMDAGetInfo(da.dm, &dim, NULL, NULL, NULL, NULL, NULL, NULL, &dof, NULL, NULL, NULL, NULL, NULL) ) cdef PetscInt lxs=0, lys=0, lzs=0 cdef PetscInt lxm=0, lym=0, lzm=0 CHKERR( DMDAGetCorners(da.dm, &lxs, &lys, &lzs, &lxm, &lym, &lzm) ) cdef PetscInt gxs=0, gys=0, gzs=0 cdef PetscInt gxm=0, gym=0, gzm=0 CHKERR( DMDAGetGhostCorners(da.dm, &gxs, &gys, &gzs, &gxm, &gym, &gzm) ) # cdef PetscInt n=0 CHKERR( VecGetLocalSize(vec.vec, &n) ) cdef PetscInt xs, ys, zs, xm, ym, zm if (n == lxm*lym*lzm*dof): xs, ys, zs = lxs, lys, lzs xm, ym, zm = lxm, lym, lzm elif (n == gxm*gym*gzm*dof): xs, ys, zs = gxs, gys, gzs xm, ym, zm = gxm, gym, gzm else: raise ValueError( "Vector local size %d is not compatible " "with DMDA local sizes %s" % (n, toDims(dim, lxm, lym, lzm))) # cdef tuple starts = toDims(dim, xs, ys, zs) cdef tuple sizes = toDims(dim, xm, ym, zm) cdef Py_ssize_t k = sizeof(PetscScalar) cdef Py_ssize_t f = dof cdef Py_ssize_t d = dim cdef tuple shape = toDims(dim, xm, ym, zm) cdef tuple strides = (k*f, k*f*xm, k*f*xm*ym)[:d] if DOF or f > 1: shape += (f,) if DOF or f > 1: strides += (k,) # self.vecbuf = _Vec_buffer(vec) self.starts = starts self.sizes = sizes self.shape = shape self.strides = strides cdef int acquire(self) except -1: self.vecbuf.acquire() if self.array is None: self.array = asarray(self.vecbuf) self.array.shape = self.shape self.array.strides = self.strides return 0 cdef int release(self) except -1: self.vecbuf.release() self.array = None return 0 # def __getitem__(self, index): self.acquire() index = adjust_index_exp(self.starts, index) return self.array[index] def __setitem__(self, index, value): self.acquire() index = adjust_index_exp(self.starts, index) self.array[index] = value # 'with' statement (PEP 343) def __enter__(self): self.acquire() return self def __exit__(self, *exc): self.release() return None cdef object adjust_index_exp(object starts, object index): if not isinstance(index, tuple): return adjust_index(starts[0], index) index = list(index) for i, start in enumerate(starts): index[i] = adjust_index(start, index[i]) index = tuple(index) return index cdef object adjust_index(object lbound, object index): if index is None: return index if index is Ellipsis: return index if isinstance(index, slice): start = index.start stop = index.stop step = index.step if start is not None: start -= lbound if stop is not None: stop -= lbound return slice(start, stop, step) try: return index - lbound except TypeError: return index # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscdmlabel.pxi000066400000000000000000000046111454104047300220320ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from* nogil: PetscErrorCode DMLabelCreate(MPI_Comm,char[],PetscDMLabel*) PetscErrorCode DMLabelView(PetscDMLabel,PetscViewer) PetscErrorCode DMLabelReset(PetscDMLabel) PetscErrorCode DMLabelDestroy(PetscDMLabel*) PetscErrorCode DMLabelGetDefaultValue(PetscDMLabel,PetscInt*) PetscErrorCode DMLabelSetDefaultValue(PetscDMLabel,PetscInt) PetscErrorCode DMLabelDuplicate(PetscDMLabel,PetscDMLabel*) PetscErrorCode DMLabelGetValue(PetscDMLabel,PetscInt,PetscInt*) PetscErrorCode DMLabelSetValue(PetscDMLabel,PetscInt,PetscInt) PetscErrorCode DMLabelClearValue(PetscDMLabel,PetscInt,PetscInt) PetscErrorCode DMLabelAddStratum(PetscDMLabel,PetscInt) PetscErrorCode DMLabelAddStrata(PetscDMLabel,PetscInt,const PetscInt[]) PetscErrorCode DMLabelAddStrataIS(PetscDMLabel,PetscIS) PetscErrorCode DMLabelInsertIS(PetscDMLabel,PetscIS,PetscInt) PetscErrorCode DMLabelGetNumValues(PetscDMLabel,PetscInt*) PetscErrorCode DMLabelGetStratumBounds(PetscDMLabel,PetscInt,PetscInt*,PetscInt*) PetscErrorCode DMLabelGetValueIS(PetscDMLabel,PetscIS*) PetscErrorCode DMLabelStratumHasPoint(PetscDMLabel,PetscInt,PetscInt,PetscBool*) PetscErrorCode DMLabelHasStratum(PetscDMLabel,PetscInt,PetscBool*) PetscErrorCode DMLabelGetStratumSize(PetscDMLabel,PetscInt,PetscInt*) PetscErrorCode DMLabelGetStratumIS(PetscDMLabel,PetscInt,PetscIS*) PetscErrorCode DMLabelSetStratumIS(PetscDMLabel,PetscInt,PetscIS) PetscErrorCode DMLabelClearStratum(PetscDMLabel,PetscInt) PetscErrorCode DMLabelComputeIndex(PetscDMLabel) PetscErrorCode DMLabelCreateIndex(PetscDMLabel,PetscInt,PetscInt) PetscErrorCode DMLabelDestroyIndex(PetscDMLabel) PetscErrorCode DMLabelHasValue(PetscDMLabel,PetscInt,PetscBool*) PetscErrorCode DMLabelHasPoint(PetscDMLabel,PetscInt,PetscBool*) PetscErrorCode DMLabelGetBounds(PetscDMLabel,PetscInt*,PetscInt*) PetscErrorCode DMLabelFilter(PetscDMLabel,PetscInt,PetscInt) PetscErrorCode DMLabelPermute(PetscDMLabel,PetscIS,PetscDMLabel*) PetscErrorCode DMLabelDistribute(PetscDMLabel,PetscSF,PetscDMLabel*) PetscErrorCode DMLabelGather(PetscDMLabel,PetscSF,PetscDMLabel*) PetscErrorCode DMLabelConvertToSection(PetscDMLabel,PetscSection*,PetscIS*) PetscErrorCode DMLabelGetNonEmptyStratumValuesIS(PetscDMLabel, PetscIS*) petsc4py-3.19.6/src/petsc4py/PETSc/petscdmplex.pxi000066400000000000000000000355721454104047300217350ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscDMPlexReorderDefaultFlag "DMPlexReorderDefaultFlag": DMPLEX_REORDER_DEFAULT_NOTSET DMPLEX_REORDER_DEFAULT_FALSE DMPLEX_REORDER_DEFAULT_TRUE ctypedef const char* PetscDMPlexTransformType "DMPlexTransformType" PetscDMPlexTransformType DMPLEXREFINEREGULAR PetscDMPlexTransformType DMPLEXREFINEALFELD PetscDMPlexTransformType DMPLEXREFINEPOWELLSABIN PetscDMPlexTransformType DMPLEXREFINEBOUNDARYLAYER PetscDMPlexTransformType DMPLEXREFINESBR PetscDMPlexTransformType DMPLEXREFINETOBOX PetscDMPlexTransformType DMPLEXREFINETOSIMPLEX PetscDMPlexTransformType DMPLEXREFINE1D PetscDMPlexTransformType DMPLEXEXTRUDE PetscDMPlexTransformType DMPLEXTRANSFORMFILTER PetscErrorCode DMPlexCreate(MPI_Comm,PetscDM*) PetscErrorCode DMPlexCreateCohesiveSubmesh(PetscDM,PetscBool,const char[],PetscInt,PetscDM*) PetscErrorCode DMPlexCreateFromCellListPetsc(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscBool,PetscInt[],PetscInt,PetscReal[],PetscDM*) #int DMPlexCreateFromDAG(PetscDM,PetscInt,const PetscInt[],const PetscInt[],const PetscInt[],const PetscInt[],const PetscScalar[]) PetscErrorCode DMPlexGetChart(PetscDM,PetscInt*,PetscInt*) PetscErrorCode DMPlexSetChart(PetscDM,PetscInt,PetscInt) PetscErrorCode DMPlexGetConeSize(PetscDM,PetscInt,PetscInt*) PetscErrorCode DMPlexSetConeSize(PetscDM,PetscInt,PetscInt) PetscErrorCode DMPlexGetCone(PetscDM,PetscInt,const PetscInt*[]) PetscErrorCode DMPlexSetCone(PetscDM,PetscInt,const PetscInt[]) PetscErrorCode DMPlexInsertCone(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMPlexInsertConeOrientation(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMPlexGetConeOrientation(PetscDM,PetscInt,const PetscInt*[]) PetscErrorCode DMPlexSetConeOrientation(PetscDM,PetscInt,const PetscInt[]) PetscErrorCode DMPlexSetCellType(PetscDM,PetscInt,PetscDMPolytopeType) PetscErrorCode DMPlexGetCellType(PetscDM,PetscInt,PetscDMPolytopeType*) PetscErrorCode DMPlexGetCellTypeLabel(PetscDM,PetscDMLabel*) PetscErrorCode DMPlexGetSupportSize(PetscDM,PetscInt,PetscInt*) PetscErrorCode DMPlexSetSupportSize(PetscDM,PetscInt,PetscInt) PetscErrorCode DMPlexGetSupport(PetscDM,PetscInt,const PetscInt*[]) PetscErrorCode DMPlexSetSupport(PetscDM,PetscInt,const PetscInt[]) #int DMPlexInsertSupport(PetscDM,PetscInt,PetscInt,PetscInt) #int DMPlexGetConeSection(PetscDM,PetscSection*) #int DMPlexGetSupportSection(PetscDM,PetscSection*) #int DMPlexGetCones(PetscDM,PetscInt*[]) #int DMPlexGetConeOrientations(PetscDM,PetscInt*[]) PetscErrorCode DMPlexGetMaxSizes(PetscDM,PetscInt*,PetscInt*) PetscErrorCode DMPlexSymmetrize(PetscDM) PetscErrorCode DMPlexStratify(PetscDM) #int DMPlexEqual(PetscDM,PetscDM,PetscBool*) PetscErrorCode DMPlexOrient(PetscDM) PetscErrorCode DMPlexInterpolate(PetscDM,PetscDM*) PetscErrorCode DMPlexUninterpolate(PetscDM,PetscDM*) #int DMPlexLoad(PetscViewer,PetscDM) #int DMPlexSetPreallocationCenterDimension(PetscDM,PetscInt) #int DMPlexGetPreallocationCenterDimension(PetscDM,PetscInt*) #int DMPlexPreallocateOperator(PetscDM,PetscInt,PetscSection,PetscSection,PetscInt[],PetscInt[],PetscInt[],PetscInt[],Mat,PetscBool) PetscErrorCode DMPlexGetPointLocal(PetscDM,PetscInt,PetscInt*,PetscInt*) #int DMPlexPointLocalRef(PetscDM,PetscInt,PetscScalar*,void*) #int DMPlexPointLocalRead(PetscDM,PetscInt,const PetscScalar*,const void*) PetscErrorCode DMPlexGetPointGlobal(PetscDM,PetscInt,PetscInt*,PetscInt*) #int DMPlexPointGlobalRef(PetscDM,PetscInt,PetscScalar*,void*) #int DMPlexPointGlobalRead(PetscDM,PetscInt,const PetscScalar*,const void*) PetscErrorCode DMPlexGetPointLocalField(PetscDM,PetscInt,PetscInt,PetscInt*,PetscInt*) PetscErrorCode DMPlexGetPointGlobalField(PetscDM,PetscInt,PetscInt,PetscInt*,PetscInt*) PetscErrorCode DMPlexCreateClosureIndex(PetscDM,PetscSection) #int PetscSectionCreateGlobalSectionLabel(PetscSection,PetscSF,PetscBool,PetscDMLabel,PetscInt,PetscSection*) PetscErrorCode DMPlexGetCellNumbering(PetscDM,PetscIS*) PetscErrorCode DMPlexGetVertexNumbering(PetscDM,PetscIS*) PetscErrorCode DMPlexCreatePointNumbering(PetscDM,PetscIS*) PetscErrorCode DMPlexGetDepth(PetscDM,PetscInt*) #int DMPlexGetDepthLabel(PetscDM,PetscDMLabel*) PetscErrorCode DMPlexGetDepthStratum(PetscDM,PetscInt,PetscInt*,PetscInt*) PetscErrorCode DMPlexGetHeightStratum(PetscDM,PetscInt,PetscInt*,PetscInt*) PetscErrorCode DMPlexGetPointDepth(PetscDM,PetscInt,PetscInt*) PetscErrorCode DMPlexGetPointHeight(PetscDM,PetscInt,PetscInt*) PetscErrorCode DMPlexGetMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) #int DMPlexGetFullMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) PetscErrorCode DMPlexRestoreMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) PetscErrorCode DMPlexGetJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) PetscErrorCode DMPlexGetFullJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) PetscErrorCode DMPlexRestoreJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**) PetscErrorCode DMPlexGetTransitiveClosure(PetscDM,PetscInt,PetscBool,PetscInt*,PetscInt*[]) PetscErrorCode DMPlexRestoreTransitiveClosure(PetscDM,PetscInt,PetscBool,PetscInt*,PetscInt*[]) PetscErrorCode DMPlexVecGetClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscInt*,PetscScalar*[]) PetscErrorCode DMPlexVecRestoreClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscInt*,PetscScalar*[]) PetscErrorCode DMPlexVecSetClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscScalar[],PetscInsertMode) PetscErrorCode DMPlexMatSetClosure(PetscDM,PetscSection,PetscSection,PetscMat,PetscInt,PetscScalar[],PetscInsertMode) PetscErrorCode DMPlexGenerate(PetscDM,const char[],PetscBool ,PetscDM*) PetscErrorCode DMPlexTriangleSetOptions(PetscDM,const char*) PetscErrorCode DMPlexTetgenSetOptions(PetscDM,const char*) #int DMPlexCopyCoordinates(PetscDM,PetscDM) #int DMPlexCreateDoublet(MPI_Comm,PetscInt,PetscBool,PetscBool,PetscBool,PetscReal,PetscDM*) PetscErrorCode DMPlexCreateBoxMesh(MPI_Comm,PetscInt,PetscBool,PetscInt[],PetscReal[],PetscReal[],PetscDMBoundaryType[],PetscBool,PetscDM*) PetscErrorCode DMPlexCreateBoxSurfaceMesh(MPI_Comm,PetscInt,PetscInt[],PetscReal[],PetscReal[],PetscBool,PetscDM*) PetscErrorCode DMPlexCreateFromFile(MPI_Comm,const char[],const char[],PetscBool,PetscDM*) PetscErrorCode DMPlexCreateCGNS(MPI_Comm,PetscInt,PetscBool,PetscDM*) PetscErrorCode DMPlexCreateCGNSFromFile(MPI_Comm,const char[],PetscBool,PetscDM*) PetscErrorCode DMPlexCreateExodus(MPI_Comm,PetscInt,PetscBool,PetscDM*) PetscErrorCode DMPlexCreateExodusFromFile(MPI_Comm,const char[],PetscBool,PetscDM*) PetscErrorCode DMPlexCreateGmsh(MPI_Comm,PetscViewer,PetscBool,PetscDM*) #int DMPlexCreateConeSection(PetscDM,PetscSection*) #int DMPlexInvertCell(PetscInt,PetscInt,int[]) #int DMPlexCheckSymmetry(PetscDM) #int DMPlexCheckSkeleton(PetscDM,PetscBool,PetscInt) #int DMPlexCheckFaces(PetscDM,PetscBool,PetscInt) PetscErrorCode DMPlexSetAdjacencyUseAnchors(PetscDM,PetscBool) PetscErrorCode DMPlexGetAdjacencyUseAnchors(PetscDM,PetscBool*) PetscErrorCode DMPlexGetAdjacency(PetscDM,PetscInt,PetscInt*,PetscInt*[]) #int DMPlexCreateNeighborCSR(PetscDM,PetscInt,PetscInt*,PetscInt**,PetscInt**) PetscErrorCode DMPlexRebalanceSharedPoints(PetscDM,PetscInt,PetscBool,PetscBool,PetscBool*) PetscErrorCode DMPlexDistribute(PetscDM,PetscInt,PetscSF*,PetscDM*) PetscErrorCode DMPlexDistributeOverlap(PetscDM,PetscInt,PetscSF*,PetscDM*) PetscErrorCode DMPlexDistributeGetDefault(PetscDM,PetscBool*) PetscErrorCode DMPlexDistributeSetDefault(PetscDM,PetscBool) PetscErrorCode DMPlexSetPartitioner(PetscDM,PetscPartitioner) PetscErrorCode DMPlexGetPartitioner(PetscDM,PetscPartitioner*) PetscErrorCode DMPlexDistributeField(PetscDM,PetscSF,PetscSection,PetscVec,PetscSection,PetscVec) #int DMPlexDistributeData(PetscDM,PetscSF,PetscSection,MPI_Datatype,void*,PetscSection,void**) PetscErrorCode DMPlexIsDistributed(PetscDM,PetscBool*) PetscErrorCode DMPlexIsSimplex(PetscDM,PetscBool*) PetscErrorCode DMPlexDistributionSetName(PetscDM,const char[]) PetscErrorCode DMPlexDistributionGetName(PetscDM,const char*[]) PetscErrorCode DMPlexGetOrdering(PetscDM,PetscMatOrderingType,PetscDMLabel,PetscIS*) PetscErrorCode DMPlexPermute(PetscDM,PetscIS,PetscDM*) PetscErrorCode DMPlexReorderGetDefault(PetscDM,PetscDMPlexReorderDefaultFlag*) PetscErrorCode DMPlexReorderSetDefault(PetscDM,PetscDMPlexReorderDefaultFlag) #int DMPlexCreateSubmesh(PetscDM,PetscDMLabel,PetscInt,PetscDM*) #int DMPlexCreateHybridMesh(PetscDM,PetscDMLabel,PetscDMLabel,PetscInt,PetscDMLabel*,PetscDMLabel*,PetscDM *,PetscDM *) #int DMPlexGetSubpointMap(PetscDM,PetscDMLabel*) #int DMPlexSetSubpointMap(PetscDM,PetscDMLabel) #int DMPlexCreateSubpointIS(PetscDM,PetscIS*) PetscErrorCode DMPlexCreateCoarsePointIS(PetscDM,PetscIS*) PetscErrorCode DMPlexMarkBoundaryFaces(PetscDM,PetscInt,PetscDMLabel) PetscErrorCode DMPlexLabelComplete(PetscDM,PetscDMLabel) PetscErrorCode DMPlexLabelCohesiveComplete(PetscDM,PetscDMLabel,PetscDMLabel,PetscInt,PetscBool,PetscDM) PetscErrorCode DMPlexGetRefinementLimit(PetscDM,PetscReal*) PetscErrorCode DMPlexSetRefinementLimit(PetscDM,PetscReal) PetscErrorCode DMPlexGetRefinementUniform(PetscDM,PetscBool*) PetscErrorCode DMPlexSetRefinementUniform(PetscDM,PetscBool) PetscErrorCode DMPlexGetMinRadius(PetscDM, PetscReal*) #int DMPlexGetNumFaceVertices(PetscDM,PetscInt,PetscInt,PetscInt*) #int DMPlexGetOrientedFace(PetscDM,PetscInt,PetscInt,const PetscInt[],PetscInt,PetscInt[],PetscInt[],PetscInt[],PetscBool*) PetscErrorCode DMPlexCreateSection(PetscDM,PetscDMLabel[],const PetscInt[],const PetscInt[],PetscInt,const PetscInt[],const PetscIS[],const PetscIS[],PetscIS,PetscSection*) PetscErrorCode DMPlexComputeCellGeometryFVM(PetscDM,PetscInt,PetscReal*,PetscReal[],PetscReal[]) PetscErrorCode DMPlexConstructGhostCells(PetscDM,const char[],PetscInt*,PetscDM*) PetscErrorCode DMPlexMetricSetFromOptions(PetscDM) PetscErrorCode DMPlexMetricSetUniform(PetscDM,PetscBool) PetscErrorCode DMPlexMetricIsUniform(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetIsotropic(PetscDM,PetscBool) PetscErrorCode DMPlexMetricIsIsotropic(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetRestrictAnisotropyFirst(PetscDM,PetscBool) PetscErrorCode DMPlexMetricRestrictAnisotropyFirst(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetNoInsertion(PetscDM,PetscBool) PetscErrorCode DMPlexMetricNoInsertion(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetNoSwapping(PetscDM,PetscBool) PetscErrorCode DMPlexMetricNoSwapping(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetNoMovement(PetscDM,PetscBool) PetscErrorCode DMPlexMetricNoMovement(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetNoSurf(PetscDM,PetscBool) PetscErrorCode DMPlexMetricNoSurf(PetscDM,PetscBool*) PetscErrorCode DMPlexMetricSetVerbosity(PetscDM,PetscInt) PetscErrorCode DMPlexMetricGetVerbosity(PetscDM,PetscInt*) PetscErrorCode DMPlexMetricSetNumIterations(PetscDM,PetscInt) PetscErrorCode DMPlexMetricGetNumIterations(PetscDM,PetscInt*) PetscErrorCode DMPlexMetricSetMinimumMagnitude(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetMinimumMagnitude(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetMaximumMagnitude(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetMaximumMagnitude(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetMaximumAnisotropy(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetMaximumAnisotropy(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetTargetComplexity(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetTargetComplexity(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetNormalizationOrder(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetNormalizationOrder(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetGradationFactor(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetGradationFactor(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricSetHausdorffNumber(PetscDM,PetscReal) PetscErrorCode DMPlexMetricGetHausdorffNumber(PetscDM,PetscReal*) PetscErrorCode DMPlexMetricCreate(PetscDM,PetscInt,PetscVec*) PetscErrorCode DMPlexMetricCreateUniform(PetscDM,PetscInt,PetscReal,PetscVec*) PetscErrorCode DMPlexMetricCreateIsotropic(PetscDM,PetscInt,PetscVec,PetscVec*) PetscErrorCode DMPlexMetricDeterminantCreate(PetscDM,PetscInt,PetscVec*,PetscDM*) PetscErrorCode DMPlexMetricEnforceSPD(PetscDM,PetscVec,PetscBool,PetscBool,PetscVec,PetscVec) PetscErrorCode DMPlexMetricNormalize(PetscDM,PetscVec,PetscBool,PetscBool,PetscVec,PetscVec) PetscErrorCode DMPlexMetricAverage2(PetscDM,PetscVec,PetscVec,PetscVec) PetscErrorCode DMPlexMetricAverage3(PetscDM,PetscVec,PetscVec,PetscVec,PetscVec) PetscErrorCode DMPlexMetricIntersection2(PetscDM,PetscVec,PetscVec,PetscVec) PetscErrorCode DMPlexMetricIntersection3(PetscDM,PetscVec,PetscVec,PetscVec,PetscVec) PetscErrorCode DMPlexComputeGradientClementInterpolant(PetscDM,PetscVec,PetscVec) PetscErrorCode DMPlexTopologyView(PetscDM,PetscViewer) PetscErrorCode DMPlexCoordinatesView(PetscDM,PetscViewer) PetscErrorCode DMPlexLabelsView(PetscDM,PetscViewer) PetscErrorCode DMPlexSectionView(PetscDM,PetscViewer,PetscDM) PetscErrorCode DMPlexGlobalVectorView(PetscDM,PetscViewer,PetscDM,PetscVec) PetscErrorCode DMPlexLocalVectorView(PetscDM,PetscViewer,PetscDM,PetscVec) PetscErrorCode DMPlexTopologyLoad(PetscDM,PetscViewer,PetscSF*) PetscErrorCode DMPlexCoordinatesLoad(PetscDM,PetscViewer,PetscSF) PetscErrorCode DMPlexLabelsLoad(PetscDM,PetscViewer,PetscSF) PetscErrorCode DMPlexSectionLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscSF*,PetscSF*) PetscErrorCode DMPlexGlobalVectorLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscVec) PetscErrorCode DMPlexLocalVectorLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscVec) PetscErrorCode DMPlexTransformApply(PetscDMPlexTransform, PetscDM, PetscDM *); PetscErrorCode DMPlexTransformCreate(MPI_Comm, PetscDMPlexTransform *); PetscErrorCode DMPlexTransformDestroy(PetscDMPlexTransform*); PetscErrorCode DMPlexTransformGetType(PetscDMPlexTransform, PetscDMPlexTransformType *); PetscErrorCode DMPlexTransformSetType(PetscDMPlexTransform tr, PetscDMPlexTransformType method); PetscErrorCode DMPlexTransformSetFromOptions(PetscDMPlexTransform); PetscErrorCode DMPlexTransformSetDM(PetscDMPlexTransform, PetscDM); PetscErrorCode DMPlexTransformSetUp(PetscDMPlexTransform); PetscErrorCode DMPlexTransformView(PetscDMPlexTransform tr, PetscViewer v); petsc4py-3.19.6/src/petsc4py/PETSc/petscdmshell.pxi000066400000000000000000000443751454104047300220750ustar00rootroot00000000000000ctypedef PetscErrorCode (*PetscDMShellXToYFunction)(PetscDM, PetscVec, PetscInsertMode, PetscVec) except PETSC_ERR_PYTHON cdef extern from * nogil: ctypedef PetscErrorCode (*PetscDMShellCreateVectorFunction)(PetscDM, PetscVec*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateMatrixFunction)(PetscDM, PetscMat*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellTransferFunction)(PetscDM, MPI_Comm, PetscDM*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateInterpolationFunction)(PetscDM, PetscDM, PetscMat*, PetscVec*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateInjectionFunction)(PetscDM, PetscDM, PetscMat*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateRestrictionFunction)(PetscDM, PetscDM, PetscMat*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateFieldDecompositionFunction)(PetscDM, PetscInt*, char***, PetscIS**, PetscDM**) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateDomainDecompositionFunction)(PetscDM, PetscInt*, char***, PetscIS**, PetscIS**, PetscDM**) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateDomainDecompositionScattersFunction)(PetscDM, PetscInt, PetscDM*, PetscScatter**, PetscScatter**, PetscScatter**) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscDMShellCreateSubDM)(PetscDM, PetscInt, PetscInt[], PetscIS*, PetscDM*) except PETSC_ERR_PYTHON PetscErrorCode DMShellCreate(MPI_Comm,PetscDM*) PetscErrorCode DMShellSetMatrix(PetscDM,PetscMat) PetscErrorCode DMShellSetGlobalVector(PetscDM,PetscVec) PetscErrorCode DMShellSetLocalVector(PetscDM,PetscVec) PetscErrorCode DMShellSetCreateGlobalVector(PetscDM,PetscDMShellCreateVectorFunction) PetscErrorCode DMShellSetCreateLocalVector(PetscDM,PetscDMShellCreateVectorFunction) PetscErrorCode DMShellSetGlobalToLocal(PetscDM,PetscDMShellXToYFunction,PetscDMShellXToYFunction) PetscErrorCode DMShellSetGlobalToLocalVecScatter(PetscDM,PetscScatter) PetscErrorCode DMShellSetLocalToGlobal(PetscDM,PetscDMShellXToYFunction,PetscDMShellXToYFunction) PetscErrorCode DMShellSetLocalToGlobalVecScatter(PetscDM,PetscScatter) PetscErrorCode DMShellSetLocalToLocal(PetscDM,PetscDMShellXToYFunction,PetscDMShellXToYFunction) PetscErrorCode DMShellSetLocalToLocalVecScatter(PetscDM,PetscScatter) PetscErrorCode DMShellSetCreateMatrix(PetscDM,PetscDMShellCreateMatrixFunction) PetscErrorCode DMShellSetCoarsen(PetscDM,PetscDMShellTransferFunction) PetscErrorCode DMShellSetRefine(PetscDM,PetscDMShellTransferFunction) PetscErrorCode DMShellSetCreateInterpolation(PetscDM,PetscDMShellCreateInterpolationFunction) PetscErrorCode DMShellSetCreateInjection(PetscDM,PetscDMShellCreateInjectionFunction) PetscErrorCode DMShellSetCreateRestriction(PetscDM,PetscDMShellCreateRestrictionFunction) PetscErrorCode DMShellSetCreateFieldDecomposition(PetscDM,PetscDMShellCreateFieldDecompositionFunction) PetscErrorCode DMShellSetCreateDomainDecomposition(PetscDM,PetscDMShellCreateDomainDecompositionFunction) PetscErrorCode DMShellSetCreateDomainDecompositionScatters(PetscDM,PetscDMShellCreateDomainDecompositionScattersFunction) PetscErrorCode DMShellSetCreateSubDM(PetscDM,PetscDMShellCreateSubDM) PetscErrorCode VecGetDM(PetscVec,PetscDM*) PetscErrorCode VecSetDM(PetscVec,PetscDM) PetscErrorCode MatGetDM(PetscMat,PetscDM*) PetscErrorCode MatSetDM(PetscMat,PetscDM) cdef PetscErrorCode DMSHELL_CreateGlobalVector( PetscDM dm, PetscVec *v) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec vec Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__create_global_vector__') assert context is not None and type(context) is tuple (create_gvec, args, kargs) = context vec = create_gvec(Dm, *args, **kargs) PetscINCREF(vec.obj) v[0] = vec.vec cdef PetscDM odm = NULL CHKERR( VecGetDM(v[0], &odm) ) if odm == NULL: CHKERR( VecSetDM(v[0], dm) ) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateLocalVector( PetscDM dm, PetscVec *v) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec vec Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__create_local_vector__') assert context is not None and type(context) is tuple (create_lvec, args, kargs) = context vec = create_lvec(Dm, *args, **kargs) PetscINCREF(vec.obj) v[0] = vec.vec cdef PetscDM odm = NULL CHKERR( VecGetDM(v[0], &odm) ) if odm == NULL: CHKERR( VecSetDM(v[0], dm) ) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_GlobalToLocalBegin( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__g2l_begin__') assert context is not None and type(context) is tuple (begin, args, kargs) = context begin(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_GlobalToLocalEnd( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__g2l_end__') assert context is not None and type(context) is tuple (end, args, kargs) = context end(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_LocalToGlobalBegin( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__l2g_begin__') assert context is not None and type(context) is tuple (begin, args, kargs) = context begin(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_LocalToGlobalEnd( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__l2g_end__') assert context is not None and type(context) is tuple (end, args, kargs) = context end(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_LocalToLocalBegin( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__l2l_begin__') assert context is not None and type(context) is tuple (begin, args, kargs) = context begin(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_LocalToLocalEnd( PetscDM dm, PetscVec g, PetscInsertMode mode, PetscVec l) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Vec gvec = ref_Vec(g) cdef Vec lvec = ref_Vec(l) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__l2l_end__') assert context is not None and type(context) is tuple (end, args, kargs) = context end(Dm, gvec, mode, lvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateMatrix( PetscDM dm, PetscMat *cmat) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef Mat mat Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__create_matrix__') assert context is not None and type(context) is tuple (matrix, args, kargs) = context mat = matrix(Dm, *args, **kargs) PetscINCREF(mat.obj) cmat[0] = mat.mat cdef PetscDM odm = NULL CHKERR( MatGetDM(cmat[0], &odm) ) if odm == NULL: CHKERR( MatSetDM(cmat[0], dm) ) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_Coarsen( PetscDM dm, MPI_Comm comm, PetscDM *dmc) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef DM Dmc cdef Comm Comm = new_Comm(comm) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__coarsen__') assert context is not None and type(context) is tuple (coarsen, args, kargs) = context Dmc = coarsen(Dm, Comm, *args, **kargs) PetscINCREF(Dmc.obj) dmc[0] = Dmc.dm return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_Refine( PetscDM dm, MPI_Comm comm, PetscDM *dmf) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef DM Dmf cdef Comm Comm = new_Comm(comm) Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__refine__') assert context is not None and type(context) is tuple (refine, args, kargs) = context Dmf = refine(Dm, Comm, *args, **kargs) PetscINCREF(Dmf.obj) dmf[0] = Dmf.dm return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateInterpolation( PetscDM dmc, PetscDM dmf, PetscMat *cmat, PetscVec *cvec) except PETSC_ERR_PYTHON with gil: cdef DM Dmc = subtype_DM(dmc)() cdef DM Dmf = subtype_DM(dmf)() cdef Mat mat cdef Vec vec Dmc.dm = dmc PetscINCREF(Dmc.obj) Dmf.dm = dmf PetscINCREF(Dmf.obj) context = Dmc.get_attr('__create_interpolation__') assert context is not None and type(context) is tuple (interpolation, args, kargs) = context mat, vec = interpolation(Dmc, Dmf, *args, **kargs) PetscINCREF(mat.obj) cmat[0] = mat.mat if cvec == NULL: return PETSC_SUCCESS if vec is None: cvec[0] = NULL else: PetscINCREF(vec.obj) cvec[0] = vec.vec return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateInjection( PetscDM dmc, PetscDM dmf, PetscMat *cmat) except PETSC_ERR_PYTHON with gil: cdef DM Dmc = subtype_DM(dmc)() cdef DM Dmf = subtype_DM(dmf)() cdef Mat mat Dmc.dm = dmc PetscINCREF(Dmc.obj) Dmf.dm = dmf PetscINCREF(Dmf.obj) context = Dmc.get_attr('__create_injection__') assert context is not None and type(context) is tuple (injection, args, kargs) = context mat = injection(Dmc, Dmf, *args, **kargs) PetscINCREF(mat.obj) cmat[0] = mat.mat return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateRestriction( PetscDM dmf, PetscDM dmc, PetscMat *cmat) except PETSC_ERR_PYTHON with gil: cdef DM Dmf = subtype_DM(dmf)() cdef DM Dmc = subtype_DM(dmc)() cdef Mat mat Dmf.dm = dmf PetscINCREF(Dmf.obj) Dmc.dm = dmc PetscINCREF(Dmc.obj) context = Dmf.get_attr('__create_restriction__') assert context is not None and type(context) is tuple (restriction, args, kargs) = context mat = restriction(Dmf, Dmc, *args, **kargs) PetscINCREF(mat.obj) cmat[0] = mat.mat return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateFieldDecomposition( PetscDM dm, PetscInt *clen, char ***namelist, PetscIS **islist, PetscDM **dmlist) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef int i cdef const char *cname = NULL Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__create_field_decomp__') assert context is not None and type(context) is tuple (decomp, args, kargs) = context names, ises, dms = decomp(Dm, *args, **kargs) if clen != NULL: if names is not None: clen[0] = len(names) elif ises is not None: clen[0] = len(ises) elif dms is not None: clen[0] = len(dms) else: clen[0] = 0 if namelist != NULL and names is not None: CHKERR( PetscMalloc(len(names)*sizeof(char**), namelist) ) for i in range(len(names)): names[i] = str2bytes(names[i], &cname) CHKERR( PetscStrallocpy(cname, &(namelist[0][i])) ) if islist != NULL and ises is not None: CHKERR( PetscMalloc(len(ises)*sizeof(PetscIS), islist) ) for i in range(len(ises)): islist[0][i] = (ises[i]).iset PetscINCREF((ises[i]).obj) if dmlist != NULL and dms is not None: CHKERR( PetscMalloc(len(dms)*sizeof(PetscDM), dmlist) ) for i in range(len(dms)): dmlist[0][i] = (dms[i]).dm PetscINCREF((dms[i]).obj) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateDomainDecomposition( PetscDM dm, PetscInt *clen, char ***namelist, PetscIS **innerislist, PetscIS **outerislist, PetscDM **dmlist) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef int i cdef const char *cname = NULL Dm.dm = dm PetscINCREF(Dm.obj) context = Dm.get_attr('__create_domain_decomp__') assert context is not None and type(context) is tuple (decomp, args, kargs) = context names, innerises, outerises, dms = decomp(Dm, *args, **kargs) if clen != NULL: if names is not None: clen[0] = len(names) elif innerises is not None: clen[0] = len(innerises) elif outerises is not None: clen[0] = len(outerises) elif dms is not None: clen[0] = len(dms) else: clen[0] = 0 if namelist != NULL and names is not None: CHKERR( PetscMalloc(len(names)*sizeof(char**), namelist) ) for i in range(len(names)): names[i] = str2bytes(names[i], &cname) CHKERR( PetscStrallocpy(cname, &(namelist[0][i])) ) if innerislist != NULL and innerises is not None: CHKERR( PetscMalloc(len(innerises)*sizeof(PetscIS), innerislist) ) for i in range(len(innerises)): innerislist[0][i] = (innerises[i]).iset PetscINCREF((innerises[i]).obj) if outerislist != NULL and outerises is not None: CHKERR( PetscMalloc(len(outerises)*sizeof(PetscIS), outerislist) ) for i in range(len(outerises)): outerislist[0][i] = (outerises[i]).iset PetscINCREF((outerises[i]).obj) if dmlist != NULL and dms is not None: CHKERR( PetscMalloc(len(dms)*sizeof(PetscDM), dmlist) ) for i in range(len(dms)): dmlist[0][i] = (dms[i]).dm PetscINCREF((dms[i]).obj) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateDomainDecompositionScatters( PetscDM dm, PetscInt clen, PetscDM *subdms, PetscScatter** iscat, PetscScatter** oscat, PetscScatter** gscat) except PETSC_ERR_PYTHON with gil: cdef DM Dm = subtype_DM(dm)() cdef int i cdef const char *cname = NULL cdef DM subdm = None Dm.dm = dm PetscINCREF(Dm.obj) psubdms = [] for i from 0 <= i < clen: subdm = subtype_DM(subdms[i])() subdm.dm = subdms[i] PetscINCREF(subdm.obj) psubdms.append(subdm) context = Dm.get_attr('__create_domain_decomp_scatters__') assert context is not None and type(context) is tuple (scatters, args, kargs) = context (iscatter, oscatter, gscatter) = scatters(Dm, psubdms, *args, **kargs) assert len(iscatter) == clen assert len(oscatter) == clen assert len(gscatter) == clen CHKERR ( PetscMalloc(clen*sizeof(PetscScatter), iscat) ) CHKERR ( PetscMalloc(clen*sizeof(PetscScatter), oscat) ) CHKERR ( PetscMalloc(clen*sizeof(PetscScatter), gscat) ) for i in range(clen): iscat[0][i] = (iscatter[i]).sct PetscINCREF((iscatter[i]).obj) oscat[0][i] = (oscatter[i]).sct PetscINCREF((oscatter[i]).obj) gscat[0][i] = (gscatter[i]).sct PetscINCREF((gscatter[i]).obj) return PETSC_SUCCESS cdef PetscErrorCode DMSHELL_CreateSubDM( PetscDM cdm, PetscInt numFields, const PetscInt cfields[], PetscIS *ciset, PetscDM *csubdm) except PETSC_ERR_PYTHON with gil: cdef DM dm = subtype_DM(cdm)() cdef IS iset cdef DM subdm dm.dm = cdm PetscINCREF(dm.obj) context = dm.get_attr('__create_subdm__') assert context is not None and type(context) is tuple (create_subdm, args, kargs) = context fields = array_i(numFields, cfields) iset, subdm = create_subdm(dm, fields, *args, **kargs) PetscINCREF(iset.obj) PetscINCREF(subdm.obj) ciset[0] = iset.iset csubdm[0] = subdm.dm return PETSC_SUCCESS petsc4py-3.19.6/src/petsc4py/PETSc/petscdmstag.pxi000066400000000000000000000300171454104047300217100ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscDMStagStencilType"DMStagStencilType": DMSTAG_STENCIL_STAR DMSTAG_STENCIL_BOX DMSTAG_STENCIL_NONE ctypedef enum PetscDMStagStencilLocation"DMStagStencilLocation": DMSTAG_NULL_LOCATION DMSTAG_BACK_DOWN_LEFT DMSTAG_BACK_DOWN DMSTAG_BACK_DOWN_RIGHT DMSTAG_BACK_LEFT DMSTAG_BACK DMSTAG_BACK_RIGHT DMSTAG_BACK_UP_LEFT DMSTAG_BACK_UP DMSTAG_BACK_UP_RIGHT DMSTAG_DOWN_LEFT DMSTAG_DOWN DMSTAG_DOWN_RIGHT DMSTAG_LEFT DMSTAG_ELEMENT DMSTAG_RIGHT DMSTAG_UP_LEFT DMSTAG_UP DMSTAG_UP_RIGHT DMSTAG_FRONT_DOWN_LEFT DMSTAG_FRONT_DOWN DMSTAG_FRONT_DOWN_RIGHT DMSTAG_FRONT_LEFT DMSTAG_FRONT DMSTAG_FRONT_RIGHT DMSTAG_FRONT_UP_LEFT DMSTAG_FRONT_UP DMSTAG_FRONT_UP_RIGHT PetscErrorCode DMStagCreate1d(MPI_Comm,PetscDMBoundaryType,PetscInt,PetscInt,PetscInt,PetscDMStagStencilType,PetscInt,const PetscInt[],PetscDM*) PetscErrorCode DMStagCreate2d(MPI_Comm,PetscDMBoundaryType,PetscDMBoundaryType,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscDMStagStencilType,PetscInt,const PetscInt[],const PetscInt[],PetscDM*) PetscErrorCode DMStagCreate3d(MPI_Comm,PetscDMBoundaryType,PetscDMBoundaryType,PetscDMBoundaryType,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscDMStagStencilType,PetscInt,const PetscInt[],const PetscInt[],const PetscInt[],PetscDM*) PetscErrorCode DMStagGetCorners(PetscDM,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetGhostCorners(PetscDM,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetLocalSizes(PetscDM,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetEntriesPerElement(PetscDM,PetscInt*) PetscErrorCode DMStagGetDOF(PetscDM,PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetNumRanks(PetscDM,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetGlobalSizes(PetscDM,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode DMStagGetBoundaryTypes(PetscDM,PetscDMBoundaryType*,PetscDMBoundaryType*,PetscDMBoundaryType*) PetscErrorCode DMStagGetStencilWidth(PetscDM,PetscInt*) PetscErrorCode DMStagGetStencilType(PetscDM,PetscDMStagStencilType*) PetscErrorCode DMStagGetOwnershipRanges(PetscDM,const PetscInt*[],const PetscInt*[],const PetscInt*[]) PetscErrorCode DMStagSetDOF(PetscDM,PetscInt,PetscInt,PetscInt,PetscInt) PetscErrorCode DMStagSetNumRanks(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMStagSetGlobalSizes(PetscDM,PetscInt,PetscInt,PetscInt) PetscErrorCode DMStagSetBoundaryTypes(PetscDM,PetscDMBoundaryType,PetscDMBoundaryType,PetscDMBoundaryType) PetscErrorCode DMStagSetStencilWidth(PetscDM,PetscInt) PetscErrorCode DMStagSetStencilType(PetscDM,PetscDMStagStencilType) PetscErrorCode DMStagSetOwnershipRanges(PetscDM,const PetscInt[],const PetscInt[],const PetscInt[]) PetscErrorCode DMStagGetLocationSlot(PetscDM,PetscDMStagStencilLocation,PetscInt,PetscInt*) PetscErrorCode DMStagGetLocationDOF(PetscDM,PetscDMStagStencilLocation,PetscInt*) PetscErrorCode DMStagGetProductCoordinateLocationSlot(PetscDM,PetscDMStagStencilLocation,PetscInt*) PetscErrorCode DMStagGetIsFirstRank(PetscDM,PetscBool*,PetscBool*,PetscBool*) PetscErrorCode DMStagGetIsLastRank(PetscDM,PetscBool*,PetscBool*,PetscBool*) PetscErrorCode DMStagSetUniformCoordinatesExplicit(PetscDM,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode DMStagSetUniformCoordinatesProduct(PetscDM,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode DMStagSetCoordinateDMType(PetscDM,PetscDMType) PetscErrorCode DMStagSetUniformCoordinates(PetscDM,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode DMStagCreateCompatibleDMStag(PetscDM,PetscInt,PetscInt,PetscInt,PetscInt,PetscDM*) PetscErrorCode DMStagVecSplitToDMDA(PetscDM,PetscVec,PetscDMStagStencilLocation,PetscInt,PetscDM*,PetscVec*) PetscErrorCode DMStagMigrateVec(PetscDM,PetscVec,PetscDM,PetscVec) # -------------------------------------------------------------------- cdef inline PetscDMStagStencilType asStagStencil(object stencil) \ except (-1): if isinstance(stencil, str): if stencil == "star": return DMSTAG_STENCIL_STAR elif stencil == "box": return DMSTAG_STENCIL_BOX elif stencil == "none": return DMSTAG_STENCIL_NONE else: raise ValueError("unknown stencil type: %s" % stencil) return stencil cdef inline object toStagStencil(PetscDMStagStencilType stype): if stype == DMSTAG_STENCIL_STAR: return "star" elif stype == DMSTAG_STENCIL_BOX: return "box" elif stype == DMSTAG_STENCIL_NONE: return "none" cdef inline PetscDMStagStencilLocation asStagStencilLocation(object stencil_location) \ except (-1): if isinstance(stencil_location, str): if stencil_location == "null": return DMSTAG_NULL_LOCATION elif stencil_location == "back_down_left": return DMSTAG_BACK_DOWN_LEFT elif stencil_location == "back_down": return DMSTAG_BACK_DOWN elif stencil_location == "back_down_right": return DMSTAG_BACK_DOWN_RIGHT elif stencil_location == "back_left": return DMSTAG_BACK_LEFT elif stencil_location == "back": return DMSTAG_BACK elif stencil_location == "back_right": return DMSTAG_BACK_RIGHT elif stencil_location == "back_up_left": return DMSTAG_BACK_UP_LEFT elif stencil_location == "back_up": return DMSTAG_BACK_UP elif stencil_location == "back_up_right": return DMSTAG_BACK_UP_RIGHT elif stencil_location == "down_left": return DMSTAG_DOWN_LEFT elif stencil_location == "down": return DMSTAG_DOWN elif stencil_location == "down_right": return DMSTAG_DOWN_RIGHT elif stencil_location == "left": return DMSTAG_LEFT elif stencil_location == "element": return DMSTAG_ELEMENT elif stencil_location == "right": return DMSTAG_RIGHT elif stencil_location == "up_left": return DMSTAG_UP_LEFT elif stencil_location == "up": return DMSTAG_UP elif stencil_location == "up_right": return DMSTAG_UP_RIGHT elif stencil_location == "front_down_left": return DMSTAG_FRONT_DOWN_LEFT elif stencil_location == "front_down": return DMSTAG_FRONT_DOWN elif stencil_location == "front_down_right": return DMSTAG_FRONT_DOWN_RIGHT elif stencil_location == "front_left": return DMSTAG_FRONT_LEFT elif stencil_location == "front": return DMSTAG_FRONT elif stencil_location == "front_right": return DMSTAG_FRONT_RIGHT elif stencil_location == "front_up_left": return DMSTAG_FRONT_UP_LEFT elif stencil_location == "front_up": return DMSTAG_FRONT_UP elif stencil_location == "front_up_right": return DMSTAG_FRONT_UP_RIGHT else: raise ValueError("unknown stencil location type: %s" % stencil_location) return stencil_location cdef inline PetscInt asStagDims(dims, PetscInt *_M, PetscInt *_N, PetscInt *_P) except? -1: cdef PetscInt dim = PETSC_DECIDE cdef object M=None, N=None, P=None dims = tuple(dims) dim = len(dims) if dim == 0: pass elif dim == 1: M, = dims elif dim == 2: M, N = dims elif dim == 3: M, N, P = dims if dim >= 1: _M[0] = asInt(M) if dim >= 2: _N[0] = asInt(N) if dim >= 3: _P[0] = asInt(P) return dim cdef inline tuple toStagDims(PetscInt dim, PetscInt M, PetscInt N, PetscInt P): if dim == 0: return () elif dim == 1: return (toInt(M),) elif dim == 2: return (toInt(M), toInt(N)) elif dim == 3: return (toInt(M), toInt(N), toInt(P)) cdef inline PetscInt asDofs(dofs, PetscInt *_dof0, PetscInt *_dof1, PetscInt *_dof2, PetscInt *_dof3) except? -1: cdef PetscInt ndofs = PETSC_DECIDE cdef object dof0=None, dof1=None, dof2=None, dof3=None dofs = tuple(dofs) ndofs = len(dofs) if ndofs == 2: dof0, dof1 = dofs elif ndofs == 3: dof0, dof1, dof2 = dofs elif ndofs == 4: dof0, dof1, dof2, dof3 = dofs if ndofs >= 2: _dof0[0] = asInt(dof0) if ndofs >= 2: _dof1[0] = asInt(dof1) if ndofs >= 3: _dof2[0] = asInt(dof2) if ndofs >= 4: _dof3[0] = asInt(dof3) return ndofs cdef inline tuple toDofs(PetscInt ndofs, PetscInt dof0, PetscInt dof1, PetscInt dof2, PetscInt dof3): if ndofs == 2: return (toInt(dof0), toInt(dof1)) elif ndofs == 3: return (toInt(dof0), toInt(dof1), toInt(dof2)) elif ndofs == 4: return (toInt(dof0), toInt(dof1), toInt(dof2), toInt(dof3)) cdef inline tuple asStagOwnershipRanges(object ownership_ranges, PetscInt dim, PetscInt *m, PetscInt *n, PetscInt *p, PetscInt **_x, PetscInt **_y, PetscInt **_z): cdef object ranges = list(ownership_ranges) cdef PetscInt rdim = len(ranges) cdef PetscInt nlx=0, nly=0, nlz=0 if dim == PETSC_DECIDE: dim = rdim elif dim != rdim: raise ValueError( "number of dimensions %d and number ownership ranges %d" % (toInt(dim), toInt(rdim))) if dim >= 1: ranges[0] = iarray_i(ranges[0], &nlx, _x) if m[0] == PETSC_DECIDE: m[0] = nlx elif m[0] != nlx: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nlx), toInt(m[0]))) if dim >= 2: ranges[1] = iarray_i(ranges[1], &nly, _y) if n[0] == PETSC_DECIDE: n[0] = nly elif n[0] != nly: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nly), toInt(n[0]))) if dim >= 3: ranges[2] = iarray_i(ranges[2], &nlz, _z) if p[0] == PETSC_DECIDE: p[0] = nlz elif p[0] != nlz: raise ValueError( "ownership range size %d and number or processors %d" % (toInt(nlz), toInt(p[0]))) return tuple(ranges) cdef inline tuple toStagOwnershipRanges(PetscInt dim, PetscInt m, PetscInt n, PetscInt p, const PetscInt *lx, const PetscInt *ly, const PetscInt *lz): # Returns tuple of arrays containing ownership ranges as Python arrays ranges = [array_i(m, lx)] if dim > 1: ranges.append(array_i(n, ly)) if dim > 2: ranges.append(array_i(p, lz)) return tuple(ranges) cdef inline object toStagBoundary(PetscDMBoundaryType btype): if btype == DM_BOUNDARY_NONE: return "none" elif btype == DM_BOUNDARY_PERIODIC: return "periodic" elif btype == DM_BOUNDARY_GHOSTED: return "ghosted" cdef inline tuple toStagBoundaryTypes(PetscInt dim, PetscDMBoundaryType btx, PetscDMBoundaryType bty, PetscDMBoundaryType btz): if dim == 1: return (toStagBoundary(btx), ) if dim == 2: return (toStagBoundary(btx), toStagBoundary(bty)) if dim == 3: return (toStagBoundary(btx), toStagBoundary(bty), toStagBoundary(btz)) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscdmswarm.pxi000066400000000000000000000067361454104047300221160ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum PetscDMSwarmType "DMSwarmType": DMSWARM_BASIC DMSWARM_PIC ctypedef enum PetscDMSwarmMigrateType "DMSwarmMigrateType": DMSWARM_MIGRATE_BASIC DMSWARM_MIGRATE_DMCELLNSCATTER DMSWARM_MIGRATE_DMCELLEXACT DMSWARM_MIGRATE_USER ctypedef enum PetscDMSwarmCollectType "DMSwarmCollectType": DMSWARM_COLLECT_BASIC DMSWARM_COLLECT_DMDABOUNDINGBOX DMSWARM_COLLECT_GENERAL DMSWARM_COLLECT_USER ctypedef enum PetscDMSwarmPICLayoutType 'DMSwarmPICLayoutType': DMSWARMPIC_LAYOUT_REGULAR DMSWARMPIC_LAYOUT_GAUSS DMSWARMPIC_LAYOUT_SUBDIVISION PetscErrorCode DMSwarmCreateGlobalVectorFromField(PetscDM,const char[],PetscVec*) PetscErrorCode DMSwarmDestroyGlobalVectorFromField(PetscDM,const char[],PetscVec*) PetscErrorCode DMSwarmCreateLocalVectorFromField(PetscDM,const char[],PetscVec*) PetscErrorCode DMSwarmDestroyLocalVectorFromField(PetscDM,const char[],PetscVec*) PetscErrorCode DMSwarmInitializeFieldRegister(PetscDM) PetscErrorCode DMSwarmFinalizeFieldRegister(PetscDM) PetscErrorCode DMSwarmSetLocalSizes(PetscDM,PetscInt,PetscInt) PetscErrorCode DMSwarmRegisterPetscDatatypeField(PetscDM,const char[],PetscInt,PetscDataType) # PetscErrorCode DMSwarmRegisterUserStructField(PetscDM,const char[],size_t) # PetscErrorCode DMSwarmRegisterUserDatatypeField(PetscDM,const char[],size_t,PetscInt) PetscErrorCode DMSwarmGetField(PetscDM,const char[],PetscInt*,PetscDataType*,void**) PetscErrorCode DMSwarmRestoreField(PetscDM,const char[],PetscInt*,PetscDataType*,void**) PetscErrorCode DMSwarmVectorDefineField(PetscDM,const char[]) PetscErrorCode DMSwarmAddPoint(PetscDM) PetscErrorCode DMSwarmAddNPoints(PetscDM,PetscInt) PetscErrorCode DMSwarmRemovePoint(PetscDM) PetscErrorCode DMSwarmRemovePointAtIndex(PetscDM,PetscInt) PetscErrorCode DMSwarmCopyPoint(PetscDM,PetscInt,PetscInt) PetscErrorCode DMSwarmGetLocalSize(PetscDM,PetscInt*) PetscErrorCode DMSwarmGetSize(PetscDM,PetscInt*) PetscErrorCode DMSwarmMigrate(PetscDM,PetscBool) PetscErrorCode DMSwarmCollectViewCreate(PetscDM) PetscErrorCode DMSwarmCollectViewDestroy(PetscDM) PetscErrorCode DMSwarmSetCellDM(PetscDM,PetscDM) PetscErrorCode DMSwarmGetCellDM(PetscDM,PetscDM*) PetscErrorCode DMSwarmSetType(PetscDM, PetscDMSwarmType) PetscErrorCode DMSwarmSetPointsUniformCoordinates(PetscDM,PetscReal[],PetscReal[],PetscInt[],PetscInsertMode) PetscErrorCode DMSwarmSetPointCoordinates(PetscDM,PetscInt,PetscReal*,PetscBool,PetscInsertMode) PetscErrorCode DMSwarmInsertPointsUsingCellDM(PetscDM,PetscDMSwarmPICLayoutType,PetscInt) PetscErrorCode DMSwarmSetPointCoordinatesCellwise(PetscDM,PetscInt,PetscReal*) PetscErrorCode DMSwarmViewFieldsXDMF(PetscDM,const char*,PetscInt,const char**) PetscErrorCode DMSwarmViewXDMF(PetscDM,const char*) PetscErrorCode DMSwarmSortGetAccess(PetscDM) PetscErrorCode DMSwarmSortRestoreAccess(PetscDM) PetscErrorCode DMSwarmSortGetPointsPerCell(PetscDM,PetscInt,PetscInt*,PetscInt**) PetscErrorCode DMSwarmSortGetNumberOfPointsPerCell(PetscDM,PetscInt,PetscInt*) PetscErrorCode DMSwarmSortGetIsValid(PetscDM,PetscBool*) PetscErrorCode DMSwarmSortGetSizes(PetscDM,PetscInt*,PetscInt*) PetscErrorCode DMSwarmProjectFields(PetscDM,PetscInt,const char**,PetscVec**,PetscBool) petsc4py-3.19.6/src/petsc4py/PETSc/petscdmutils.pxi000066400000000000000000000017541454104047300221200ustar00rootroot00000000000000 cdef extern from * nogil: struct _DMInterpolationInfo ctypedef _DMInterpolationInfo* PetscDMInterpolation "DMInterpolationInfo" PetscErrorCode DMInterpolationCreate(MPI_Comm, PetscDMInterpolation*) PetscErrorCode DMInterpolationDestroy(PetscDMInterpolation*) PetscErrorCode DMInterpolationEvaluate(PetscDMInterpolation, PetscDM, PetscVec, PetscVec) PetscErrorCode DMInterpolationGetCoordinates(PetscDMInterpolation, PetscVec*) PetscErrorCode DMInterpolationGetDim(PetscDMInterpolation, PetscInt*) PetscErrorCode DMInterpolationGetDof(PetscDMInterpolation, PetscInt*) PetscErrorCode DMInterpolationGetVector(PetscDMInterpolation, PetscVec*) PetscErrorCode DMInterpolationRestoreVector(PetscDMInterpolation, PetscVec*) PetscErrorCode DMInterpolationSetDim(PetscDMInterpolation, PetscInt) PetscErrorCode DMInterpolationSetDof(PetscDMInterpolation, PetscInt) PetscErrorCode DMInterpolationSetUp(PetscDMInterpolation, PetscDM, PetscBool, PetscBool) petsc4py-3.19.6/src/petsc4py/PETSc/petscds.pxi000066400000000000000000000034031454104047300210360ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscDSType PetscDSType PETSCDSBASIC PetscErrorCode PetscDSCreate(MPI_Comm,PetscDS*) PetscErrorCode PetscDSDestroy(PetscDS*) PetscErrorCode PetscDSView(PetscDS,PetscViewer) PetscErrorCode PetscDSSetType(PetscDS,PetscDSType) PetscErrorCode PetscDSGetType(PetscDS,PetscDSType*) PetscErrorCode PetscDSSetFromOptions(PetscDS) PetscErrorCode PetscDSSetUp(PetscDS) PetscErrorCode PetscDSGetHeightSubspace(PetscDS,PetscInt,PetscDS*) PetscErrorCode PetscDSGetSpatialDimension(PetscDS,PetscInt*) PetscErrorCode PetscDSGetCoordinateDimension(PetscDS,PetscInt*) PetscErrorCode PetscDSSetCoordinateDimension(PetscDS,PetscInt) PetscErrorCode PetscDSGetNumFields(PetscDS,PetscInt*) PetscErrorCode PetscDSGetTotalDimension(PetscDS,PetscInt*) PetscErrorCode PetscDSGetTotalComponents(PetscDS,PetscInt*) PetscErrorCode PetscDSGetFieldIndex(PetscDS,PetscObject,PetscInt*) PetscErrorCode PetscDSGetFieldSize(PetscDS,PetscInt,PetscInt*) PetscErrorCode PetscDSGetFieldOffset(PetscDS,PetscInt,PetscInt*) PetscErrorCode PetscDSGetDimensions(PetscDS,PetscInt*[]) PetscErrorCode PetscDSGetComponents(PetscDS,PetscInt*[]) PetscErrorCode PetscDSGetComponentOffset(PetscDS,PetscInt,PetscInt*) PetscErrorCode PetscDSGetComponentOffsets(PetscDS,PetscInt*[]) PetscErrorCode PetscDSGetComponentDerivativeOffsets(PetscDS,PetscInt*[]) PetscErrorCode PetscDSGetDiscretization(PetscDS,PetscInt,PetscObject*) PetscErrorCode PetscDSSetDiscretization(PetscDS,PetscInt,PetscObject) PetscErrorCode PetscDSAddDiscretization(PetscDS,PetscObject) PetscErrorCode PetscDSGetImplicit(PetscDS,PetscInt,PetscBool*) PetscErrorCode PetscDSSetImplicit(PetscDS,PetscInt,PetscBool) petsc4py-3.19.6/src/petsc4py/PETSc/petscdt.pxi000066400000000000000000000066641454104047300210530ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef enum int "PetscGaussLobattoLegendreCreateType": PETSCGAUSSLOBATTOLEGENDRE_VIA_LINEAR_ALGEBRA PETSCGAUSSLOBATTOLEGENDRE_VIA_NEWTON PetscErrorCode PetscFECreateDefault(MPI_Comm, PetscInt, PetscInt, PetscBool, const char [], PetscInt, PetscFE*) PetscErrorCode PetscQuadratureCreate(MPI_Comm, PetscQuadrature*) PetscErrorCode PetscQuadratureDuplicate(PetscQuadrature, PetscQuadrature*) PetscErrorCode PetscQuadratureGetOrder(PetscQuadrature, PetscInt*) PetscErrorCode PetscQuadratureSetOrder(PetscQuadrature, PetscInt) PetscErrorCode PetscQuadratureGetNumComponents(PetscQuadrature, PetscInt*) PetscErrorCode PetscQuadratureSetNumComponents(PetscQuadrature, PetscInt) PetscErrorCode PetscQuadratureGetData(PetscQuadrature, PetscInt*, PetscInt*, PetscInt*, const PetscReal *[], const PetscReal *[]) PetscErrorCode PetscQuadratureSetData(PetscQuadrature, PetscInt, PetscInt, PetscInt, const PetscReal [], const PetscReal []) PetscErrorCode PetscQuadratureView(PetscQuadrature, PetscViewer) PetscErrorCode PetscQuadratureDestroy(PetscQuadrature *) PetscErrorCode PetscQuadratureExpandComposite(PetscQuadrature, PetscInt, const PetscReal[], const PetscReal[], PetscQuadrature *) PetscErrorCode PetscDTLegendreEval(PetscInt,const PetscReal*,PetscInt,const PetscInt*,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode PetscDTGaussQuadrature(PetscInt,PetscReal,PetscReal,PetscReal*,PetscReal*) PetscErrorCode PetscDTGaussLobattoLegendreQuadrature(PetscInt,PetscGaussLobattoLegendreCreateType,PetscReal*,PetscReal*) PetscErrorCode PetscDTReconstructPoly(PetscInt,PetscInt,const PetscReal*,PetscInt,const PetscReal*,PetscReal*) PetscErrorCode PetscDTGaussTensorQuadrature(PetscInt,PetscInt,PetscInt,PetscReal,PetscReal,PetscQuadrature*) PetscErrorCode PetscDTGaussJacobiQuadrature(PetscInt,PetscInt,PetscInt,PetscReal,PetscReal,PetscQuadrature*) PetscErrorCode PetscDTTanhSinhTensorQuadrature(PetscInt, PetscInt, PetscReal, PetscReal, PetscQuadrature *) PetscErrorCode PetscDTTanhSinhIntegrate(void (*)(PetscReal *, void *, PetscReal *), PetscReal, PetscReal, PetscInt, PetscReal *) PetscErrorCode PetscDTTanhSinhIntegrateMPFR(void (*)(PetscReal *, void *, PetscReal *), PetscReal, PetscReal, PetscInt, PetscReal *) PetscErrorCode PetscGaussLobattoLegendreIntegrate(PetscInt, PetscReal *, PetscReal *, const PetscReal *, PetscReal *) PetscErrorCode PetscGaussLobattoLegendreElementLaplacianCreate(PetscInt, PetscReal *, PetscReal *, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementLaplacianDestroy(PetscInt, PetscReal *, PetscReal *, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementGradientCreate(PetscInt, PetscReal *, PetscReal *, PetscReal ***, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementGradientDestroy(PetscInt, PetscReal *, PetscReal *, PetscReal ***, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementAdvectionCreate(PetscInt, PetscReal *, PetscReal *, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementAdvectionDestroy(PetscInt, PetscReal *, PetscReal *, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementMassCreate(PetscInt, PetscReal *, PetscReal *, PetscReal ***) PetscErrorCode PetscGaussLobattoLegendreElementMassDestroy(PetscInt, PetscReal *, PetscReal *, PetscReal ***) petsc4py-3.19.6/src/petsc4py/PETSc/petscfe.pxi000066400000000000000000000034751454104047300210330ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef const char* PetscFEType PetscFEType PETSCFEBASIC PetscFEType PETSCFEOPENCL PetscFEType PETSCFECOMPOSITE PetscErrorCode PetscFECreate(MPI_Comm, PetscFE*) PetscErrorCode PetscFECreateDefault(MPI_Comm, PetscInt, PetscInt, PetscBool, const char [], PetscInt, PetscFE*) PetscErrorCode PetscFECreateLagrange(MPI_Comm, PetscInt, PetscInt, PetscBool, PetscInt, PetscInt, PetscFE*) PetscErrorCode PetscFESetType(PetscFE, PetscFEType) PetscErrorCode PetscFEGetQuadrature(PetscFE, PetscQuadrature*) PetscErrorCode PetscFEGetFaceQuadrature(PetscFE, PetscQuadrature*) PetscErrorCode PetscFESetQuadrature(PetscFE, PetscQuadrature) PetscErrorCode PetscFESetFaceQuadrature(PetscFE, PetscQuadrature) PetscErrorCode PetscFEDestroy(PetscFE*) PetscErrorCode PetscFEGetBasisSpace(PetscFE, PetscSpace*) PetscErrorCode PetscFESetBasisSpace(PetscFE, PetscSpace) PetscErrorCode PetscFEGetDimension(PetscFE, PetscInt*) PetscErrorCode PetscFEGetNumComponents(PetscFE, PetscInt*) PetscErrorCode PetscFESetNumComponents(PetscFE, PetscInt) PetscErrorCode PetscFEGetNumDof(PetscFE, const PetscInt**) PetscErrorCode PetscFEGetSpatialDimension(PetscFE, PetscInt*) PetscErrorCode PetscFEGetTileSizes(PetscFE, PetscInt*, PetscInt*, PetscInt*, PetscInt*) PetscErrorCode PetscFESetTileSizes(PetscFE, PetscInt, PetscInt, PetscInt, PetscInt) PetscErrorCode PetscFEGetDualSpace(PetscFE, PetscDualSpace*) PetscErrorCode PetscFESetDualSpace(PetscFE, PetscDualSpace) PetscErrorCode PetscFESetFromOptions(PetscFE) PetscErrorCode PetscFESetUp(PetscFE) PetscErrorCode PetscFEView(PetscFE, PetscViewer) PetscErrorCode PetscFEViewFromOptions(PetscFE, PetscObject, char[]) petsc4py-3.19.6/src/petsc4py/PETSc/petscis.pxi000066400000000000000000000204771454104047300210550ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscISType "ISType" PetscISType ISGENERAL PetscISType ISSTRIDE PetscISType ISBLOCK PetscErrorCode ISView(PetscIS,PetscViewer) PetscErrorCode ISDestroy(PetscIS*) PetscErrorCode ISCreate(MPI_Comm,PetscIS*) PetscErrorCode ISSetType(PetscIS,PetscISType) PetscErrorCode ISGetType(PetscIS,PetscISType*) PetscErrorCode ISCreateGeneral(MPI_Comm,PetscInt,PetscInt[],PetscCopyMode,PetscIS*) PetscErrorCode ISCreateBlock(MPI_Comm,PetscInt,PetscInt,PetscInt[],PetscCopyMode,PetscIS*) PetscErrorCode ISCreateStride(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscIS*) PetscErrorCode ISLoad(PetscIS,PetscViewer) PetscErrorCode ISDuplicate(PetscIS,PetscIS*) PetscErrorCode ISCopy(PetscIS,PetscIS) PetscErrorCode ISAllGather(PetscIS,PetscIS*) PetscErrorCode ISInvertPermutation(PetscIS,PetscInt,PetscIS*) PetscErrorCode ISGetSize(PetscIS,PetscInt*) PetscErrorCode ISGetLocalSize(PetscIS,PetscInt*) PetscErrorCode ISGetBlockSize(PetscIS,PetscInt*) PetscErrorCode ISSetBlockSize(PetscIS,PetscInt) PetscErrorCode ISGetIndices(PetscIS,const PetscInt*[]) PetscErrorCode ISRestoreIndices(PetscIS,const PetscInt*[]) PetscErrorCode ISEqual(PetscIS,PetscIS,PetscBool*) PetscErrorCode ISSetPermutation(PetscIS) PetscErrorCode ISPermutation(PetscIS,PetscBool*) PetscErrorCode ISSetIdentity(PetscIS) PetscErrorCode ISIdentity(PetscIS,PetscBool*) PetscErrorCode ISSort(PetscIS) PetscErrorCode ISSorted(PetscIS,PetscBool*) PetscErrorCode ISSum(PetscIS,PetscIS,PetscIS*) PetscErrorCode ISExpand(PetscIS,PetscIS,PetscIS*) PetscErrorCode ISDifference(PetscIS,PetscIS,PetscIS*) PetscErrorCode ISComplement(PetscIS,PetscInt,PetscInt,PetscIS*) PetscErrorCode ISEmbed(PetscIS,PetscIS,PetscBool,PetscIS*) PetscErrorCode ISRenumber(PetscIS,PetscIS,PetscInt*,PetscIS*) PetscErrorCode ISGeneralSetIndices(PetscIS,PetscInt,PetscInt[],PetscCopyMode) PetscErrorCode ISBlockSetIndices(PetscIS,PetscInt,PetscInt,PetscInt[],PetscCopyMode) PetscErrorCode ISBlockGetIndices(PetscIS,const PetscInt*[]) PetscErrorCode ISBlockRestoreIndices(PetscIS,const PetscInt*[]) PetscErrorCode ISStrideSetStride(PetscIS,PetscInt,PetscInt,PetscInt) PetscErrorCode ISStrideGetInfo(PetscIS,PetscInt*,PetscInt*) PetscErrorCode ISToGeneral(PetscIS) PetscErrorCode ISBuildTwoSided(PetscIS,PetscIS,PetscIS*) cdef extern from * nogil: ctypedef const char* PetscISLocalToGlobalMappingType "ISLocalToGlobalMappingType" PetscISLocalToGlobalMappingType ISLOCALTOGLOBALMAPPINGBASIC PetscISLocalToGlobalMappingType ISLOCALTOGLOBALMAPPINGHASH ctypedef enum PetscGLMapMode "ISGlobalToLocalMappingMode": PETSC_IS_GTOLM_MASK "IS_GTOLM_MASK" PETSC_IS_GTOLM_DROP "IS_GTOLM_DROP" PetscErrorCode ISLocalToGlobalMappingCreate(MPI_Comm,PetscInt,PetscInt,PetscInt[],PetscCopyMode,PetscLGMap*) PetscErrorCode ISLocalToGlobalMappingCreateIS(PetscIS,PetscLGMap*) PetscErrorCode ISLocalToGlobalMappingCreateSF(PetscSF,PetscInt,PetscLGMap*) PetscErrorCode ISLocalToGlobalMappingSetType(PetscLGMap,PetscISLocalToGlobalMappingType) PetscErrorCode ISLocalToGlobalMappingSetFromOptions(PetscLGMap) PetscErrorCode ISLocalToGlobalMappingView(PetscLGMap,PetscViewer) PetscErrorCode ISLocalToGlobalMappingDestroy(PetscLGMap*) PetscErrorCode ISLocalToGlobalMappingGetSize(PetscLGMap,PetscInt*) PetscErrorCode ISLocalToGlobalMappingGetBlockSize(PetscLGMap,PetscInt*) PetscErrorCode ISLocalToGlobalMappingGetIndices(PetscLGMap,const PetscInt*[]) PetscErrorCode ISLocalToGlobalMappingRestoreIndices(PetscLGMap,const PetscInt*[]) PetscErrorCode ISLocalToGlobalMappingGetBlockIndices(PetscLGMap,const PetscInt*[]) PetscErrorCode ISLocalToGlobalMappingRestoreBlockIndices(PetscLGMap,const PetscInt*[]) PetscErrorCode ISLocalToGlobalMappingGetInfo(PetscLGMap,PetscInt*,PetscInt*[],PetscInt*[],PetscInt**[]) PetscErrorCode ISLocalToGlobalMappingRestoreInfo(PetscLGMap,PetscInt*,PetscInt*[],PetscInt*[],PetscInt**[]) PetscErrorCode ISLocalToGlobalMappingGetBlockInfo(PetscLGMap,PetscInt*,PetscInt*[],PetscInt*[],PetscInt**[]) PetscErrorCode ISLocalToGlobalMappingRestoreBlockInfo(PetscLGMap,PetscInt*,PetscInt*[],PetscInt*[],PetscInt**[]) PetscErrorCode ISLocalToGlobalMappingApply(PetscLGMap,PetscInt,PetscInt[],PetscInt[]) PetscErrorCode ISLocalToGlobalMappingApplyBlock(PetscLGMap,PetscInt,PetscInt[],PetscInt[]) PetscErrorCode ISLocalToGlobalMappingApplyIS(PetscLGMap,PetscIS,PetscIS*) PetscErrorCode ISGlobalToLocalMappingApply(PetscLGMap,PetscGLMapMode,PetscInt,PetscInt[],PetscInt*,PetscInt[]) PetscErrorCode ISGlobalToLocalMappingApplyBlock(PetscLGMap,PetscGLMapMode,PetscInt,PetscInt[],PetscInt*,PetscInt[]) # -------------------------------------------------------------------- cdef inline IS ref_IS(PetscIS iset): cdef IS ob = IS() ob.iset = iset PetscINCREF(ob.obj) return ob cdef inline LGMap ref_LGMap(PetscLGMap lgm): cdef LGMap ob = LGMap() ob.lgm = lgm PetscINCREF(ob.obj) return ob # -------------------------------------------------------------------- cdef class _IS_buffer: cdef PetscIS iset cdef PetscInt size cdef const PetscInt *data cdef bint hasarray def __cinit__(self, IS iset): cdef PetscIS i = iset.iset CHKERR( PetscINCREF(&i) ) self.iset = i self.size = 0 self.data = NULL self.hasarray = 0 def __dealloc__(self): if self.hasarray and self.iset != NULL: CHKERR( ISRestoreIndices(self.iset, &self.data) ) CHKERR( ISDestroy(&self.iset) ) # cdef int acquire(self) except -1: if not self.hasarray and self.iset != NULL: CHKERR( ISGetLocalSize(self.iset, &self.size) ) CHKERR( ISGetIndices(self.iset, &self.data) ) self.hasarray = 1 return 0 cdef int release(self) except -1: if self.hasarray and self.iset != NULL: self.size = 0 CHKERR( ISRestoreIndices(self.iset, &self.data) ) self.hasarray = 0 self.data = NULL return 0 # buffer interface (PEP 3118) cdef int acquirebuffer(self, Py_buffer *view, int flags) except -1: self.acquire() PyPetscBuffer_FillInfo(view, self.data, self.size, c'i', 1, flags) view.obj = self return 0 cdef int releasebuffer(self, Py_buffer *view) except -1: PyPetscBuffer_Release(view) self.release() return 0 def __getbuffer__(self, Py_buffer *view, int flags): self.acquirebuffer(view, flags) def __releasebuffer__(self, Py_buffer *view): self.releasebuffer(view) # 'with' statement (PEP 343) cdef object enter(self): self.acquire() return asarray(self) cdef object exit(self): self.release() return None def __enter__(self): return self.enter() def __exit__(self, *exc): return self.exit() # buffer interface (legacy) cdef Py_ssize_t getbuffer(self, void **p) except -1: cdef PetscInt n = 0 if p != NULL: self.acquire() p[0] = self.data n = self.size elif self.iset != NULL: CHKERR( ISGetLocalSize(self.iset, &n) ) return (n*sizeof(PetscInt)) def __getsegcount__(self, Py_ssize_t *lenp): if lenp != NULL: lenp[0] = self.getbuffer(NULL) return 1 def __getreadbuffer__(self, Py_ssize_t idx, void **p): if idx != 0: raise SystemError( "accessing non-existent buffer segment") return self.getbuffer(p) # NumPy array interface (legacy) property __array_interface__: def __get__(self): cdef PetscInt n = 0 if self.iset != NULL: CHKERR( ISGetLocalSize(self.iset, &n) ) cdef object size = toInt(n) cdef dtype descr = PyArray_DescrFromType(NPY_PETSC_INT) cdef str typestr = "=%c%d" % (descr.kind, descr.itemsize) return dict(version=3, data=self, shape=(size,), typestr=typestr) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscksp.pxi000066400000000000000000000256101454104047300212310ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscKSPType "KSPType" PetscKSPType KSPRICHARDSON PetscKSPType KSPCHEBYSHEV PetscKSPType KSPCG PetscKSPType KSPGROPPCG PetscKSPType KSPPIPECG PetscKSPType KSPPIPECGRR PetscKSPType KSPPIPELCG PetscKSPType KSPPIPEPRCG PetscKSPType KSPPIPECG2 PetscKSPType KSPCGNE PetscKSPType KSPNASH PetscKSPType KSPSTCG PetscKSPType KSPGLTR PetscKSPType KSPFCG PetscKSPType KSPPIPEFCG PetscKSPType KSPGMRES PetscKSPType KSPPIPEFGMRES PetscKSPType KSPFGMRES PetscKSPType KSPLGMRES PetscKSPType KSPDGMRES PetscKSPType KSPPGMRES PetscKSPType KSPTCQMR PetscKSPType KSPBCGS PetscKSPType KSPIBCGS PetscKSPType KSPQMRCGS PetscKSPType KSPFBCGS PetscKSPType KSPFBCGSR PetscKSPType KSPBCGSL PetscKSPType KSPPIPEBCGS PetscKSPType KSPCGS PetscKSPType KSPTFQMR PetscKSPType KSPCR PetscKSPType KSPPIPECR PetscKSPType KSPLSQR PetscKSPType KSPPREONLY PetscKSPType KSPNONE PetscKSPType KSPQCG PetscKSPType KSPBICG PetscKSPType KSPMINRES PetscKSPType KSPSYMMLQ PetscKSPType KSPLCD PetscKSPType KSPPYTHON PetscKSPType KSPGCR PetscKSPType KSPPIPEGCR PetscKSPType KSPTSIRM PetscKSPType KSPCGLS PetscKSPType KSPFETIDP PetscKSPType KSPHPDDM ctypedef enum PetscKSPNormType "KSPNormType": KSP_NORM_DEFAULT KSP_NORM_NONE KSP_NORM_PRECONDITIONED KSP_NORM_UNPRECONDITIONED KSP_NORM_NATURAL ctypedef enum PetscKSPConvergedReason "KSPConvergedReason": # iterating KSP_CONVERGED_ITERATING # converged KSP_CONVERGED_RTOL_NORMAL KSP_CONVERGED_ATOL_NORMAL KSP_CONVERGED_RTOL KSP_CONVERGED_ATOL KSP_CONVERGED_ITS KSP_CONVERGED_NEG_CURVE KSP_CONVERGED_STEP_LENGTH KSP_CONVERGED_HAPPY_BREAKDOWN # diverged KSP_DIVERGED_NULL KSP_DIVERGED_MAX_IT "KSP_DIVERGED_ITS" KSP_DIVERGED_DTOL KSP_DIVERGED_BREAKDOWN KSP_DIVERGED_BREAKDOWN_BICG KSP_DIVERGED_NONSYMMETRIC KSP_DIVERGED_INDEFINITE_PC KSP_DIVERGED_NANORINF KSP_DIVERGED_INDEFINITE_MAT KSP_DIVERGED_PC_FAILED ctypedef PetscErrorCode (*PetscKSPCtxDel)(void*) ctypedef PetscErrorCode (*PetscKSPConvergedFunction)(PetscKSP, PetscInt, PetscReal, PetscKSPConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscKSPMonitorFunction)(PetscKSP, PetscInt, PetscReal, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscKSPComputeRHSFunction)(PetscKSP, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscKSPComputeOpsFunction)(PetscKSP, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON PetscErrorCode KSPCreate(MPI_Comm,PetscKSP*) PetscErrorCode KSPDestroy(PetscKSP*) PetscErrorCode KSPView(PetscKSP,PetscViewer) PetscErrorCode KSPSetType(PetscKSP,PetscKSPType) PetscErrorCode KSPGetType(PetscKSP,PetscKSPType*) PetscErrorCode KSPSetOptionsPrefix(PetscKSP,char[]) PetscErrorCode KSPAppendOptionsPrefix(PetscKSP,char[]) PetscErrorCode KSPGetOptionsPrefix(PetscKSP,char*[]) PetscErrorCode KSPSetFromOptions(PetscKSP) PetscErrorCode KSPSetTolerances(PetscKSP,PetscReal,PetscReal,PetscReal,PetscInt) PetscErrorCode KSPGetTolerances(PetscKSP,PetscReal*,PetscReal*,PetscReal*,PetscInt*) PetscErrorCode KSPSetNormType(PetscKSP,PetscKSPNormType) PetscErrorCode KSPGetNormType(PetscKSP,PetscKSPNormType*) PetscErrorCode KSPSetPCSide(PetscKSP,PetscPCSide) PetscErrorCode KSPGetPCSide(PetscKSP,PetscPCSide*) PetscErrorCode KSPSetSupportedNorm(PetscKSP,PetscKSPNormType,PetscPCSide,PetscInt) PetscErrorCode KSPSetConvergenceTest(PetscKSP,PetscKSPConvergedFunction,void*,PetscKSPCtxDel) PetscErrorCode KSPSetResidualHistory(PetscKSP,PetscReal[],PetscInt,PetscBool) PetscErrorCode KSPGetResidualHistory(PetscKSP,PetscReal*[],PetscInt*) PetscErrorCode KSPLogResidualHistory(PetscKSP,PetscReal) PetscErrorCode KSPConvergedDefaultCreate(void**) PetscErrorCode KSPConvergedDefaultDestroy(void*) PetscErrorCode KSPConvergedDefault(PetscKSP,PetscInt,PetscReal,PetscKSPConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode KSPConvergedSkip(PetscKSP,PetscInt,PetscReal,PetscKSPConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode KSPMonitorSet(PetscKSP,PetscKSPMonitorFunction,void*,PetscKSPCtxDel) PetscErrorCode KSPMonitorCancel(PetscKSP) PetscErrorCode KSPMonitor(PetscKSP,PetscInt,PetscReal) PetscErrorCode KSPSetInitialGuessNonzero(PetscKSP,PetscBool) PetscErrorCode KSPGetInitialGuessNonzero(PetscKSP,PetscBool*) PetscErrorCode KSPSetInitialGuessKnoll(PetscKSP,PetscBool) PetscErrorCode KSPGetInitialGuessKnoll(PetscKSP,PetscBool*) PetscErrorCode KSPSetUseFischerGuess(PetscKSP,PetscInt,PetscInt) PetscErrorCode KSPGetComputeEigenvalues(PetscKSP,PetscBool*) PetscErrorCode KSPSetComputeEigenvalues(PetscKSP,PetscBool) PetscErrorCode KSPGetComputeSingularValues(PetscKSP,PetscBool*) PetscErrorCode KSPSetComputeSingularValues(PetscKSP,PetscBool) PetscErrorCode KSPSetComputeRHS(PetscKSP,PetscKSPComputeRHSFunction,void*) PetscErrorCode KSPSetComputeOperators(PetscKSP,PetscKSPComputeOpsFunction,void*) PetscErrorCode KSPSetOperators(PetscKSP,PetscMat,PetscMat) PetscErrorCode KSPGetOperators(PetscKSP,PetscMat*,PetscMat*) PetscErrorCode KSPGetOperatorsSet(PetscKSP,PetscBool*,PetscBool*) PetscErrorCode KSPSetPC(PetscKSP,PetscPC) PetscErrorCode KSPGetPC(PetscKSP,PetscPC*) PetscErrorCode KSPGetDM(PetscKSP,PetscDM*) PetscErrorCode KSPSetDM(PetscKSP,PetscDM) PetscErrorCode KSPSetDMActive(PetscKSP,PetscBool) PetscErrorCode KSPSetUp(PetscKSP) PetscErrorCode KSPReset(PetscKSP) PetscErrorCode KSPSetUpOnBlocks(PetscKSP) PetscErrorCode KSPSolve(PetscKSP,PetscVec,PetscVec) PetscErrorCode KSPSolveTranspose(PetscKSP,PetscVec,PetscVec) PetscErrorCode KSPMatSolve(PetscKSP,PetscMat,PetscMat) PetscErrorCode KSPMatSolveTranspose(PetscKSP,PetscMat,PetscMat) PetscErrorCode KSPGetRhs(PetscKSP,PetscVec*) PetscErrorCode KSPGetSolution(PetscKSP,PetscVec*) PetscErrorCode KSPGetConvergedReason(PetscKSP,PetscKSPConvergedReason*) PetscErrorCode KSPGetIterationNumber(PetscKSP,PetscInt*) PetscErrorCode KSPGetResidualNorm(PetscKSP,PetscReal*) PetscErrorCode KSPSetErrorIfNotConverged(PetscKSP,PetscBool); PetscErrorCode KSPGetErrorIfNotConverged(PetscKSP,PetscBool*); PetscErrorCode KSPBuildSolution(PetscKSP,PetscVec,PetscVec*) PetscErrorCode KSPBuildSolutionDefault(PetscKSP,PetscVec,PetscVec*) PetscErrorCode KSPBuildResidual(PetscKSP,PetscVec,PetscVec,PetscVec*) PetscErrorCode KSPBuildResidualDefault(PetscKSP,PetscVec,PetscVec,PetscVec*) PetscErrorCode KSPSetDiagonalScale(PetscKSP,PetscBool) PetscErrorCode KSPGetDiagonalScale(PetscKSP,PetscBool*) PetscErrorCode KSPSetDiagonalScaleFix(PetscKSP,PetscBool) PetscErrorCode KSPGetDiagonalScaleFix(PetscKSP,PetscBool*) PetscErrorCode KSPComputeExplicitOperator(PetscKSP,PetscMat*) PetscErrorCode KSPComputeEigenvalues(PetscKSP,PetscInt,PetscReal[],PetscReal[],PetscInt*) PetscErrorCode KSPComputeExtremeSingularValues(PetscKSP,PetscReal*,PetscReal*) PetscErrorCode KSPCreateVecs(PetscKSP,PetscInt,PetscVec**,PetscInt,PetscVec**) PetscErrorCode KSPGMRESSetRestart(PetscKSP,PetscInt) PetscErrorCode KSPPythonSetType(PetscKSP,char[]) PetscErrorCode KSPPythonGetType(PetscKSP,char*[]) cdef extern from * nogil: # custom.h PetscErrorCode KSPSetIterationNumber(PetscKSP,PetscInt) PetscErrorCode KSPSetResidualNorm(PetscKSP,PetscReal) PetscErrorCode KSPConvergenceTestCall(PetscKSP,PetscInt,PetscReal,PetscKSPConvergedReason*) PetscErrorCode KSPSetConvergedReason(PetscKSP,PetscKSPConvergedReason) # ----------------------------------------------------------------------------- cdef inline KSP ref_KSP(PetscKSP ksp): cdef KSP ob = KSP() ob.ksp = ksp PetscINCREF(ob.obj) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode KSP_Converged( PetscKSP ksp, PetscInt its, PetscReal rnm, PetscKSPConvergedReason *r, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef KSP Ksp = ref_KSP(ksp) (converged, args, kargs) = Ksp.get_attr('__converged__') reason = converged(Ksp, toInt(its), toReal(rnm), *args, **kargs) if reason is None: r[0] = KSP_CONVERGED_ITERATING elif reason is False: r[0] = KSP_CONVERGED_ITERATING elif reason is True: r[0] = KSP_CONVERGED_ITS # XXX ? else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode KSP_Monitor( PetscKSP ksp, PetscInt its, PetscReal rnm, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef KSP Ksp = ref_KSP(ksp) cdef object monitorlist = Ksp.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS for (monitor, args, kargs) in monitorlist: monitor(Ksp, toInt(its), toReal(rnm), *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode KSP_ComputeRHS( PetscKSP ksp, PetscVec rhs, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef KSP Ksp = ref_KSP(ksp) cdef Vec Rhs = ref_Vec(rhs) cdef object context = Ksp.get_attr('__rhs__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (computerhs, args, kargs) = context computerhs(Ksp, Rhs, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode KSP_ComputeOps( PetscKSP ksp, PetscMat A, PetscMat B, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef KSP Ksp = ref_KSP(ksp) cdef Mat Amat = ref_Mat(A) cdef Mat Bmat = ref_Mat(B) cdef object context = Ksp.get_attr('__operators__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (computeops, args, kargs) = context computeops(Ksp, Amat, Bmat, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petsclayout.pxi000066400000000000000000000010371454104047300217460ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: struct _n_PetscLayout ctypedef _n_PetscLayout* PetscLayout PetscErrorCode PetscLayoutSetLocalSize(PetscLayout,PetscInt) PetscErrorCode PetscLayoutSetSize(PetscLayout,PetscInt) PetscErrorCode PetscLayoutGetBlockSize(PetscLayout,PetscInt*) PetscErrorCode PetscLayoutSetBlockSize(PetscLayout,PetscInt) PetscErrorCode PetscLayoutSetUp(PetscLayout) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petsclog.pxi000066400000000000000000000057421454104047300212210ustar00rootroot00000000000000cdef extern from * nogil: ctypedef double PetscLogDouble ctypedef struct PetscEventPerfInfo: int count PetscLogDouble flops, time PetscLogDouble numMessages PetscLogDouble messageLength PetscLogDouble numReductions PetscErrorCode PetscLogDefaultBegin() PetscErrorCode PetscLogAllBegin() PetscErrorCode PetscLogView(PetscViewer) PetscErrorCode PetscLogIsActive(PetscBool*) PetscErrorCode PetscLogFlops(PetscLogDouble) PetscErrorCode PetscGetFlops(PetscLogDouble*) PetscErrorCode PetscGetCPUTime(PetscLogDouble*) PetscErrorCode PetscMallocGetCurrentUsage(PetscLogDouble*) PetscErrorCode PetscMemoryGetCurrentUsage(PetscLogDouble*) PetscErrorCode PetscTime(PetscLogDouble*) PetscErrorCode PetscTimeSubtract(PetscLogDouble*) PetscErrorCode PetscTimeAdd(PetscLogDouble*) ctypedef int PetscLogStage PetscErrorCode PetscLogStageRegister(char[],PetscLogStage*) PetscErrorCode PetscLogStagePush(PetscLogStage) PetscErrorCode PetscLogStagePop() PetscErrorCode PetscLogStageSetActive(PetscLogStage,PetscBool) PetscErrorCode PetscLogStageGetActive(PetscLogStage,PetscBool*) PetscErrorCode PetscLogStageSetVisible(PetscLogStage,PetscBool) PetscErrorCode PetscLogStageGetVisible(PetscLogStage,PetscBool*) PetscErrorCode PetscLogStageGetId(char[],PetscLogStage*) ctypedef int PetscLogClass "PetscClassId" PetscErrorCode PetscLogClassRegister"PetscClassIdRegister"(char[],PetscLogClass*) PetscErrorCode PetscLogClassActivate"PetscLogEventActivateClass"(PetscLogClass) PetscErrorCode PetscLogClassDeactivate"PetscLogEventDeactivateClass"(PetscLogClass) ctypedef int PetscLogEvent PetscErrorCode PetscLogEventRegister(char[],PetscLogClass,PetscLogEvent*) PetscErrorCode PetscLogEventBegin(PetscLogEvent,PetscObject,PetscObject,PetscObject,PetscObject) PetscErrorCode PetscLogEventEnd(PetscLogEvent,PetscObject,PetscObject,PetscObject,PetscObject) PetscErrorCode PetscLogEventActivate(PetscLogEvent) PetscErrorCode PetscLogEventDeactivate(PetscLogEvent) PetscErrorCode PetscLogEventSetActiveAll(PetscLogEvent,PetscBool) PetscErrorCode PetscLogEventGetPerfInfo(PetscLogStage,PetscLogEvent,PetscEventPerfInfo*) cdef extern from * nogil: # custom.h PetscErrorCode PetscLogStageFindId(char[],PetscLogStage*) PetscErrorCode PetscLogClassFindId(char[],PetscLogClass*) PetscErrorCode PetscLogEventFindId(char[],PetscLogEvent*) PetscErrorCode PetscLogStageFindName(PetscLogStage,char*[]) PetscErrorCode PetscLogClassFindName(PetscLogClass,char*[]) PetscErrorCode PetscLogEventFindName(PetscLogEvent,char*[]) cdef inline int event_args2objs(object args, PetscObject o[4]) except -1: o[0] = o[1] = o[2] = o[3] = NULL cdef Py_ssize_t i=0, n = len(args) cdef Object tmp = None if n > 4: n = 4 for 0 <= i < n: tmp = args[i] if tmp is not None: o[i] = tmp.obj[0] return 0 petsc4py-3.19.6/src/petsc4py/PETSc/petscmat.pxi000066400000000000000000001444051454104047300212210ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscMatType "MatType" PetscMatType MATSAME PetscMatType MATMAIJ PetscMatType MATSEQMAIJ PetscMatType MATMPIMAIJ PetscMatType MATKAIJ PetscMatType MATSEQKAIJ PetscMatType MATMPIKAIJ PetscMatType MATIS PetscMatType MATAIJ PetscMatType MATSEQAIJ PetscMatType MATMPIAIJ PetscMatType MATAIJCRL PetscMatType MATSEQAIJCRL PetscMatType MATMPIAIJCRL PetscMatType MATAIJCUSPARSE PetscMatType MATSEQAIJCUSPARSE PetscMatType MATMPIAIJCUSPARSE PetscMatType MATAIJVIENNACL PetscMatType MATSEQAIJVIENNACL PetscMatType MATMPIAIJVIENNACL PetscMatType MATAIJPERM PetscMatType MATSEQAIJPERM PetscMatType MATMPIAIJPERM PetscMatType MATAIJSELL PetscMatType MATSEQAIJSELL PetscMatType MATMPIAIJSELL PetscMatType MATAIJMKL PetscMatType MATSEQAIJMKL PetscMatType MATMPIAIJMKL PetscMatType MATBAIJMKL PetscMatType MATSEQBAIJMKL PetscMatType MATMPIBAIJMKL PetscMatType MATSHELL PetscMatType MATDENSE PetscMatType MATSEQDENSE PetscMatType MATMPIDENSE PetscMatType MATDENSECUDA PetscMatType MATSEQDENSECUDA PetscMatType MATMPIDENSECUDA PetscMatType MATELEMENTAL PetscMatType MATBAIJ PetscMatType MATSEQBAIJ PetscMatType MATMPIBAIJ PetscMatType MATMPIADJ PetscMatType MATSBAIJ PetscMatType MATSEQSBAIJ PetscMatType MATMPISBAIJ PetscMatType MATMFFD PetscMatType MATNORMAL PetscMatType MATNORMALHERMITIAN PetscMatType MATLRC PetscMatType MATSCATTER PetscMatType MATBLOCKMAT PetscMatType MATCOMPOSITE PetscMatType MATFFT PetscMatType MATFFTW PetscMatType MATSEQCUFFT PetscMatType MATTRANSPOSEVIRTUAL PetscMatType MATHERMITIANTRANSPOSEVIRTUAL PetscMatType MATSCHURCOMPLEMENT PetscMatType MATPYTHON PetscMatType MATHYPRE PetscMatType MATHYPRESTRUCT PetscMatType MATHYPRESSTRUCT PetscMatType MATSUBMATRIX PetscMatType MATLOCALREF PetscMatType MATNEST PetscMatType MATPREALLOCATOR PetscMatType MATSELL PetscMatType MATSEQSELL PetscMatType MATMPISELL PetscMatType MATDUMMY PetscMatType MATLMVM PetscMatType MATLMVMDFP PetscMatType MATLMVMBFGS PetscMatType MATLMVMSR1 PetscMatType MATLMVMBROYDEN PetscMatType MATLMVMBADBROYDEN PetscMatType MATLMVMSYMBROYDEN PetscMatType MATLMVMSYMBADBROYDEN PetscMatType MATLMVMDIAGBROYDEN PetscMatType MATCONSTANTDIAGONAL PetscMatType MATH2OPUS ctypedef const char* PetscMatOrderingType "MatOrderingType" PetscMatOrderingType MATORDERINGNATURAL PetscMatOrderingType MATORDERINGND PetscMatOrderingType MATORDERING1WD PetscMatOrderingType MATORDERINGRCM PetscMatOrderingType MATORDERINGQMD PetscMatOrderingType MATORDERINGROWLENGTH PetscMatOrderingType MATORDERINGWBM PetscMatOrderingType MATORDERINGSPECTRAL PetscMatOrderingType MATORDERINGAMD PetscMatOrderingType MATORDERINGMETISND ctypedef const char* PetscMatSolverType "MatSolverType" PetscMatSolverType MATSOLVERSUPERLU PetscMatSolverType MATSOLVERSUPERLU_DIST PetscMatSolverType MATSOLVERSTRUMPACK PetscMatSolverType MATSOLVERUMFPACK PetscMatSolverType MATSOLVERCHOLMOD PetscMatSolverType MATSOLVERKLU PetscMatSolverType MATSOLVERSPARSEELEMENTAL PetscMatSolverType MATSOLVERELEMENTAL PetscMatSolverType MATSOLVERSCALAPACK PetscMatSolverType MATSOLVERESSL PetscMatSolverType MATSOLVERLUSOL PetscMatSolverType MATSOLVERMUMPS PetscMatSolverType MATSOLVERMKL_PARDISO PetscMatSolverType MATSOLVERMKL_CPARDISO PetscMatSolverType MATSOLVERPASTIX PetscMatSolverType MATSOLVERMATLAB PetscMatSolverType MATSOLVERPETSC PetscMatSolverType MATSOLVERBAS PetscMatSolverType MATSOLVERCUSPARSE PetscMatSolverType MATSOLVERCUDA PetscMatSolverType MATSOLVERSPQR ctypedef enum PetscMatReuse "MatReuse": MAT_INITIAL_MATRIX MAT_REUSE_MATRIX MAT_IGNORE_MATRIX MAT_INPLACE_MATRIX ctypedef enum PetscMatDuplicateOption "MatDuplicateOption": MAT_DO_NOT_COPY_VALUES MAT_COPY_VALUES MAT_SHARE_NONZERO_PATTERN ctypedef enum PetscMatSORType "MatSORType": SOR_FORWARD_SWEEP SOR_BACKWARD_SWEEP SOR_SYMMETRIC_SWEEP SOR_LOCAL_FORWARD_SWEEP SOR_LOCAL_BACKWARD_SWEEP SOR_LOCAL_SYMMETRIC_SWEEP SOR_ZERO_INITIAL_GUESS SOR_EISENSTAT SOR_APPLY_UPPER SOR_APPLY_LOWER ctypedef enum PetscMatProductType "MatProductType": MATPRODUCT_UNSPECIFIED MATPRODUCT_AB MATPRODUCT_AtB MATPRODUCT_ABt MATPRODUCT_PtAP MATPRODUCT_RARt MATPRODUCT_ABC ctypedef enum PetscMatAssemblyType "MatAssemblyType": MAT_FLUSH_ASSEMBLY MAT_FINAL_ASSEMBLY ctypedef enum PetscMatInfoType "MatInfoType": MAT_LOCAL MAT_GLOBAL_MAX MAT_GLOBAL_SUM 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" MAT_UNKNOWN_NONZERO_PATTERN "UNKNOWN_NONZERO_PATTERN" ctypedef enum PetscMatOption "MatOption": MAT_OPTION_MIN MAT_UNUSED_NONZERO_LOCATION_ERR MAT_ROW_ORIENTED MAT_SYMMETRIC MAT_STRUCTURALLY_SYMMETRIC MAT_FORCE_DIAGONAL_ENTRIES MAT_IGNORE_OFF_PROC_ENTRIES MAT_USE_HASH_TABLE MAT_KEEP_NONZERO_PATTERN MAT_IGNORE_ZERO_ENTRIES MAT_USE_INODES MAT_HERMITIAN MAT_SYMMETRY_ETERNAL MAT_NEW_NONZERO_LOCATION_ERR MAT_IGNORE_LOWER_TRIANGULAR MAT_ERROR_LOWER_TRIANGULAR MAT_GETROW_UPPERTRIANGULAR MAT_SPD MAT_NO_OFF_PROC_ZERO_ROWS MAT_NO_OFF_PROC_ENTRIES MAT_NEW_NONZERO_LOCATIONS MAT_NEW_NONZERO_ALLOCATION_ERR MAT_SUBSET_OFF_PROC_ENTRIES MAT_SUBMAT_SINGLEIS MAT_STRUCTURE_ONLY MAT_SORTED_FULL MAT_OPTION_MAX ctypedef enum PetscMatOperation "MatOperation": pass PetscErrorCode MatView(PetscMat,PetscViewer) PetscErrorCode MatDestroy(PetscMat*) PetscErrorCode MatCreate(MPI_Comm,PetscMat*) PetscErrorCode MatCreateDenseCUDA(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscMat*) PetscErrorCode MatCreateIS(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,PetscLGMap,PetscLGMap,PetscMat*) PetscErrorCode MatISGetLocalMat(PetscMat,PetscMat*) PetscErrorCode MatISGetMPIXAIJ(PetscMat,PetscMatReuse,PetscMat*) PetscErrorCode MatCreateScatter(MPI_Comm,PetscScatter,PetscMat*) PetscErrorCode MatScatterSetVecScatter(PetscMat,PetscScatter) PetscErrorCode MatScatterGetVecScatter(PetscMat,PetscScatter*) PetscErrorCode MatCreateNormal(PetscMat,PetscMat*) PetscErrorCode MatCreateTranspose(PetscMat,PetscMat*) PetscErrorCode MatCreateNormalHermitian(PetscMat,PetscMat*) PetscErrorCode MatCreateHermitianTranspose(PetscMat,PetscMat*) PetscErrorCode MatCreateLRC(PetscMat,PetscMat,PetscVec,PetscMat,PetscMat*) PetscErrorCode MatCreateSubMatrixVirtual(PetscMat,PetscIS,PetscIS,PetscMat*) PetscErrorCode MatCreateRedundantMatrix(PetscMat,PetscInt,MPI_Comm,PetscMatReuse,PetscMat*) PetscErrorCode MatCreateNest(MPI_Comm,PetscInt,PetscIS[],PetscInt,PetscIS[],PetscMat[],PetscMat*) PetscErrorCode MatCreateShell(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,void*,PetscMat*) PetscErrorCode MatCreateH2OpusFromMat(PetscMat,PetscInt,const PetscReal[],PetscBool,PetscReal,PetscInt,PetscInt,PetscInt,PetscReal,PetscMat*) PetscErrorCode MatCreateSeqAIJWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt[],PetscInt[],PetscScalar[],PetscMat*) PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt[],PetscInt[],PetscScalar[],PetscMat*) PetscErrorCode MatCreateMPIAIJWithSplitArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt[],PetscInt[],PetscScalar[],PetscInt[],PetscInt[],PetscScalar[],PetscMat*) PetscErrorCode MatSetSizes(PetscMat,PetscInt,PetscInt,PetscInt,PetscInt) PetscErrorCode MatSetBlockSize(PetscMat,PetscInt) PetscErrorCode MatSetBlockSizes(PetscMat,PetscInt,PetscInt) PetscErrorCode MatSetType(PetscMat,PetscMatType) PetscErrorCode MatSetVecType(PetscMat,PetscVecType) PetscErrorCode MatGetVecType(PetscMat,PetscVecType*) PetscErrorCode MatSetOption(PetscMat,PetscMatOption,PetscBool) PetscErrorCode MatGetOption(PetscMat,PetscMatOption,PetscBool*) enum: MAT_SKIP_ALLOCATION PetscErrorCode MatSeqAIJSetPreallocation (PetscMat,PetscInt,PetscInt[]) PetscErrorCode MatMPIAIJSetPreallocation (PetscMat,PetscInt,PetscInt[],PetscInt,PetscInt[]) PetscErrorCode MatSeqBAIJSetPreallocation (PetscMat,PetscInt,PetscInt,PetscInt[]) PetscErrorCode MatMPIBAIJSetPreallocation (PetscMat,PetscInt,PetscInt,PetscInt[],PetscInt,PetscInt[]) PetscErrorCode MatSeqSBAIJSetPreallocation(PetscMat,PetscInt,PetscInt,PetscInt[]) PetscErrorCode MatMPISBAIJSetPreallocation(PetscMat,PetscInt,PetscInt,PetscInt[],PetscInt,PetscInt[]) PetscErrorCode MatSeqAIJSetPreallocationCSR (PetscMat, PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatMPIAIJSetPreallocationCSR (PetscMat, PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatSeqBAIJSetPreallocationCSR (PetscMat,PetscInt,PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatMPIBAIJSetPreallocationCSR (PetscMat,PetscInt,PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatSeqSBAIJSetPreallocationCSR(PetscMat,PetscInt,PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatMPISBAIJSetPreallocationCSR(PetscMat,PetscInt,PetscInt[],PetscInt[],PetscScalar[]) PetscErrorCode MatSeqDenseSetPreallocation(PetscMat,PetscScalar[]) PetscErrorCode MatMPIDenseSetPreallocation(PetscMat,PetscScalar[]) PetscErrorCode MatISSetPreallocation(PetscMat,PetscInt,PetscInt[],PetscInt,PetscInt[]) PetscErrorCode MatSetOptionsPrefix(PetscMat,char[]) PetscErrorCode MatAppendOptionsPrefix(PetscMat,char[]) PetscErrorCode MatGetOptionsPrefix(PetscMat,char*[]) PetscErrorCode MatSetFromOptions(PetscMat) PetscErrorCode MatSetUp(PetscMat) PetscErrorCode MatGetType(PetscMat,PetscMatType*) PetscErrorCode MatGetSize(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetLocalSize(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetBlockSize(PetscMat,PetscInt*) PetscErrorCode MatGetBlockSizes(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetOwnershipRange(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetOwnershipRanges(PetscMat,const PetscInt*[]) PetscErrorCode MatGetOwnershipRangeColumn(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatGetOwnershipRangesColumn(PetscMat,const PetscInt*[]) PetscErrorCode MatGetOwnershipIS(PetscMat,PetscIS*,PetscIS*) PetscErrorCode MatNestGetISs(PetscMat,PetscIS*,PetscIS*) PetscErrorCode MatNestGetLocalISs(PetscMat,PetscIS*,PetscIS*) PetscErrorCode MatNestGetSize(PetscMat,PetscInt*,PetscInt*) PetscErrorCode MatNestGetSubMat(PetscMat,PetscInt,PetscInt,PetscMat*) PetscErrorCode MatEqual(PetscMat,PetscMat,PetscBool*) PetscErrorCode MatLoad(PetscMat,PetscViewer) PetscErrorCode MatDuplicate(PetscMat,PetscMatDuplicateOption,PetscMat*) PetscErrorCode MatCopy(PetscMat,PetscMat,PetscMatStructure) PetscErrorCode MatTranspose(PetscMat,PetscMatReuse,PetscMat*) PetscErrorCode MatTransposeSetPrecursor(PetscMat,PetscMat) PetscErrorCode MatHermitianTranspose(PetscMat,PetscMatReuse,PetscMat*) PetscErrorCode MatConvert(PetscMat,PetscMatType,PetscMatReuse,PetscMat*) PetscErrorCode MatIsSymmetric(PetscMat,PetscReal,PetscBool*) PetscErrorCode MatIsStructurallySymmetric(PetscMat,PetscBool*) PetscErrorCode MatIsHermitian(PetscMat,PetscReal,PetscBool*) PetscErrorCode MatIsSymmetricKnown(PetscMat,PetscBool*,PetscBool*) PetscErrorCode MatIsHermitianKnown(PetscMat,PetscBool*,PetscBool*) PetscErrorCode MatIsTranspose(PetscMat,PetscMat,PetscReal,PetscBool*) PetscErrorCode MatCreateVecs(PetscMat,PetscVec*,PetscVec*) PetscErrorCode MatSetValue(PetscMat,PetscInt,PetscInt,PetscScalar,PetscInsertMode) PetscErrorCode MatSetValues(PetscMat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatSetValuesBlocked(PetscMat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatSetLocalToGlobalMapping(PetscMat,PetscLGMap,PetscLGMap) PetscErrorCode MatGetLocalToGlobalMapping(PetscMat,PetscLGMap*,PetscLGMap*) PetscErrorCode MatSetValueLocal(PetscMat,PetscInt,PetscInt,PetscScalar,PetscInsertMode) PetscErrorCode MatSetValuesLocal(PetscMat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatSetValuesBlockedLocal(PetscMat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatSetStencil(PetscMat,PetscInt,const PetscInt[],const PetscInt[],PetscInt) ctypedef struct PetscMatStencil "MatStencil": PetscInt k,j,i,c PetscErrorCode MatSetValuesStencil(PetscMat,PetscInt,const PetscMatStencil[],PetscInt,const PetscMatStencil[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatSetValuesBlockedStencil(PetscMat,PetscInt,const PetscMatStencil[],PetscInt,const PetscMatStencil[],const PetscScalar[],PetscInsertMode) PetscErrorCode MatGetValues(PetscMat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],PetscScalar[]) PetscErrorCode MatGetRow(PetscMat,PetscInt,PetscInt*,const PetscInt*[],const PetscScalar*[]) PetscErrorCode MatRestoreRow(PetscMat,PetscInt,PetscInt*,const PetscInt*[],const PetscScalar*[]) PetscErrorCode MatGetRowIJ(PetscMat,PetscInt,PetscBool,PetscBool,PetscInt*,const PetscInt*[],const PetscInt*[],PetscBool*) PetscErrorCode MatRestoreRowIJ(PetscMat,PetscInt,PetscBool,PetscBool,PetscInt*,const PetscInt*[],const PetscInt*[],PetscBool*) PetscErrorCode MatGetColumnIJ(PetscMat,PetscInt,PetscBool,PetscBool,PetscInt*,const PetscInt*[],const PetscInt*[],PetscBool*) PetscErrorCode MatRestoreColumnIJ(PetscMat,PetscInt,PetscBool,PetscBool,PetscInt*,const PetscInt*[],const PetscInt*[],PetscBool*) PetscErrorCode MatZeroEntries(PetscMat) PetscErrorCode MatStoreValues(PetscMat) PetscErrorCode MatRetrieveValues(PetscMat) PetscErrorCode MatAssemblyBegin(PetscMat,PetscMatAssemblyType) PetscErrorCode MatAssemblyEnd(PetscMat,PetscMatAssemblyType) PetscErrorCode MatAssembled(PetscMat,PetscBool*) PetscErrorCode MatDiagonalSet(PetscMat,PetscVec,PetscInsertMode) PetscErrorCode MatDiagonalScale(PetscMat,PetscVec,PetscVec) PetscErrorCode MatScale(PetscMat,PetscScalar) PetscErrorCode MatShift(PetscMat,PetscScalar) PetscErrorCode MatChop(PetscMat,PetscReal) PetscErrorCode MatSetRandom(PetscMat,PetscRandom) PetscErrorCode MatAXPY(PetscMat,PetscScalar,PetscMat,PetscMatStructure) PetscErrorCode MatAYPX(PetscMat,PetscScalar,PetscMat,PetscMatStructure) PetscErrorCode MatMatMult(PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatMatTransposeMult(PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatTransposeMatMult(PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatPtAP(PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatRARt(PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatMatMatMult(PetscMat,PetscMat,PetscMat,PetscMatReuse,PetscReal,PetscMat*) PetscErrorCode MatSeqAIJKron(PetscMat,PetscMat,PetscMatReuse,PetscMat*) PetscErrorCode MatInterpolate(PetscMat,PetscVec,PetscVec) PetscErrorCode MatInterpolateAdd(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatRestrict(PetscMat,PetscVec,PetscVec) PetscErrorCode MatPermute(PetscMat,PetscIS,PetscIS,PetscMat*) PetscErrorCode MatPermuteSparsify(PetscMat,PetscInt,PetscReal,PetscReal,PetscIS,PetscIS,PetscMat*) PetscErrorCode MatMerge(MPI_Comm,PetscMat,PetscInt,PetscMatReuse,PetscMat*) PetscErrorCode MatCreateSubMatrix(PetscMat,PetscIS,PetscIS,PetscMatReuse,PetscMat*) PetscErrorCode MatCreateSubMatrices(PetscMat,PetscInt,PetscIS[],PetscIS[],PetscMatReuse,PetscMat*[]) PetscErrorCode MatIncreaseOverlap(PetscMat,PetscInt,PetscIS[],PetscInt) PetscErrorCode MatGetDiagonalBlock(PetscMat,PetscMat*) PetscErrorCode MatGetLocalSubMatrix(PetscMat,PetscIS,PetscIS,PetscMat*) PetscErrorCode MatRestoreLocalSubMatrix(PetscMat,PetscIS,PetscIS,PetscMat*) PetscErrorCode MatDestroyMatrices(PetscInt,PetscMat*[]) PetscErrorCode MatConjugate(PetscMat) PetscErrorCode MatRealPart(PetscMat) PetscErrorCode MatImaginaryPart(PetscMat) PetscErrorCode MatZeroRows(PetscMat,PetscInt,PetscInt[],PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsLocal(PetscMat,PetscInt,PetscInt[],PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsIS(PetscMat,PetscIS,PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsLocalIS(PetscMat,PetscIS,PetscScalar,PetscVec,PetscVec) PetscErrorCode MatFindZeroRows(PetscMat,PetscIS*) PetscErrorCode MatZeroRowsColumns(PetscMat,PetscInt,PetscInt[],PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsColumnsLocal(PetscMat,PetscInt,PetscInt[],PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsColumnsIS(PetscMat,PetscIS,PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsColumnsLocalIS(PetscMat,PetscIS,PetscScalar,PetscVec,PetscVec) PetscErrorCode MatZeroRowsColumnsStencil(PetscMat,PetscInt,const PetscMatStencil[],PetscScalar,PetscVec,PetscVec) PetscErrorCode MatGetDiagonal(PetscMat,PetscVec) PetscErrorCode MatGetRowSum(PetscMat,PetscVec) PetscErrorCode MatInvertBlockDiagonal(PetscMat,const PetscScalar**) PetscErrorCode MatGetRowMax(PetscMat,PetscVec,PetscInt[]) PetscErrorCode MatGetRowMaxAbs(PetscMat,PetscVec,PetscInt[]) PetscErrorCode MatGetColumnVector(PetscMat,PetscVec,PetscInt) PetscErrorCode MatNorm(PetscMat,PetscNormType,PetscReal*) PetscErrorCode MatMult(PetscMat,PetscVec,PetscVec) PetscErrorCode MatMultAdd(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatMultTranspose(PetscMat,PetscVec,PetscVec) PetscErrorCode MatMultTransposeAdd(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatMultHermitian"MatMultHermitianTranspose"(PetscMat,PetscVec,PetscVec) PetscErrorCode MatMultHermitianAdd"MatMultHermitianTransposeAdd"(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatBindToCPU(PetscMat,PetscBool) PetscErrorCode MatBoundToCPU(PetscMat,PetscBool*) PetscErrorCode MatSOR(PetscMat,PetscVec,PetscReal,PetscMatSORType,PetscReal,PetscInt,PetscInt,PetscVec) PetscErrorCode MatGetOrdering(PetscMat,PetscMatOrderingType,PetscIS*,PetscIS*) PetscErrorCode MatReorderForNonzeroDiagonal(PetscMat,PetscReal,PetscIS,PetscIS) PetscErrorCode MatISFixLocalEmpty(PetscMat,PetscBool) PetscErrorCode MatISGetLocalMat(PetscMat,PetscMat*) PetscErrorCode MatISRestoreLocalMat(PetscMat,PetscMat*) PetscErrorCode MatISSetLocalMat(PetscMat,PetscMat) PetscErrorCode MatH2OpusOrthogonalize(PetscMat) PetscErrorCode MatH2OpusCompress(PetscMat,PetscReal) PetscErrorCode MatH2OpusLowRankUpdate(PetscMat,PetscMat,PetscMat,PetscScalar) PetscErrorCode MatMissingDiagonal(Mat,PetscBool*,PetscInt*) ctypedef enum PetscMatFactorShiftType "MatFactorShiftType": MAT_SHIFT_NONE MAT_SHIFT_NONZERO MAT_SHIFT_POSITIVE_DEFINITE MAT_SHIFT_INBLOCKS ctypedef struct PetscMatFactorInfo "MatFactorInfo": PetscReal fill PetscReal levels, diagonal_fill PetscReal usedt, dt, dtcol, dtcount PetscReal zeropivot, pivotinblocks PetscReal shifttype, shiftamount ctypedef struct PetscMatInfo "MatInfo": PetscLogDouble block_size PetscLogDouble nz_allocated, nz_used, nz_unneeded PetscLogDouble memory PetscLogDouble assemblies PetscLogDouble mallocs PetscLogDouble fill_ratio_given, fill_ratio_needed PetscLogDouble factor_mallocs PetscErrorCode MatGetInfo(PetscMat,PetscMatInfoType,PetscMatInfo*) PetscErrorCode MatFactorInfoInitialize(PetscMatFactorInfo*) PetscErrorCode MatCholeskyFactor(PetscMat,PetscIS,PetscMatFactorInfo*) PetscErrorCode MatCholeskyFactorSymbolic(PetscMat,PetscIS,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatCholeskyFactorNumeric(PetscMat,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatLUFactor(PetscMat,PetscIS,PetscIS,PetscMatFactorInfo*) PetscErrorCode MatILUFactor(PetscMat,PetscIS,PetscIS,PetscMatFactorInfo*) PetscErrorCode MatICCFactor(PetscMat,PetscIS,PetscMatFactorInfo*) PetscErrorCode MatLUFactorSymbolic(PetscMat,PetscIS,PetscIS,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatILUFactorSymbolic(PetscMat,PetscIS,PetscIS,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatICCFactorSymbolic(PetscMat,PetscIS,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatLUFactorNumeric(PetscMat,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatILUDTFactor(PetscMat,PetscIS,PetscIS,PetscMatFactorInfo*,PetscMat*) PetscErrorCode MatGetInertia(PetscMat,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode MatSetUnfactored(PetscMat) PetscErrorCode MatLRCGetMats(PetscMat,PetscMat*,PetscMat*,PetscVec*,PetscMat*) PetscErrorCode MatMumpsSetIcntl(PetscMat,PetscInt,PetscInt) PetscErrorCode MatMumpsGetIcntl(PetscMat,PetscInt,PetscInt*) PetscErrorCode MatMumpsSetCntl(PetscMat,PetscInt,PetscReal) PetscErrorCode MatMumpsGetCntl(PetscMat,PetscInt,PetscReal*) PetscErrorCode MatMumpsGetInfo(PetscMat,PetscInt,PetscInt*) PetscErrorCode MatMumpsGetInfog(PetscMat,PetscInt,PetscInt*) PetscErrorCode MatMumpsGetRinfo(PetscMat,PetscInt,PetscReal*) PetscErrorCode MatMumpsGetRinfog(PetscMat,PetscInt,PetscReal*) PetscErrorCode MatForwardSolve(PetscMat,PetscVec,PetscVec) PetscErrorCode MatBackwardSolve(PetscMat,PetscVec,PetscVec) PetscErrorCode MatSolve(PetscMat,PetscVec,PetscVec) PetscErrorCode MatSolveTranspose(PetscMat,PetscVec,PetscVec) PetscErrorCode MatSolveAdd(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatSolveTransposeAdd(PetscMat,PetscVec,PetscVec,PetscVec) PetscErrorCode MatMatSolve(PetscMat,PetscMat,PetscMat) PetscErrorCode MatComputeExplicitOperator(PetscMat,PetscMat*) PetscErrorCode MatUseScaledForm(PetscMat,PetscBool) PetscErrorCode MatScaleSystem(PetscMat,PetscVec,PetscVec) PetscErrorCode MatUnScaleSystem(PetscMat,PetscVec,PetscVec) PetscErrorCode MatDenseSetLDA(PetscMat,PetscInt) PetscErrorCode MatDenseGetLDA(PetscMat,PetscInt*) PetscErrorCode MatDenseGetLocalMatrix(PetscMat,PetscMat*) PetscErrorCode MatDenseGetArray(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseRestoreArray(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseGetArrayWrite(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseRestoreArrayWrite(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseGetArrayRead(PetscMat,const PetscScalar*[]) PetscErrorCode MatDenseRestoreArrayRead(PetscMat,const PetscScalar*[]) PetscErrorCode MatDenseGetColumnVec(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseRestoreColumnVec(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseGetColumnVecRead(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseRestoreColumnVecRead(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseGetColumnVecWrite(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseRestoreColumnVecWrite(PetscMat,PetscInt,PetscVec*) PetscErrorCode MatDenseCUDAGetArray(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseCUDARestoreArray(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseCUDAGetArrayWrite(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseCUDARestoreArrayWrite(PetscMat,PetscScalar*[]) PetscErrorCode MatDenseCUDAGetArrayRead(PetscMat,const PetscScalar*[]) PetscErrorCode MatDenseCUDARestoreArrayRead(PetscMat,const PetscScalar*[]) PetscErrorCode MatProductGetType(PetscMat,PetscMatProductType*) PetscErrorCode MatProductGetMats(PetscMat,PetscMat*,PetscMat*,PetscMat*) PetscErrorCode MatPythonSetType(PetscMat,char[]) PetscErrorCode MatPythonGetType(PetscMat,char*[]) cdef extern from * nogil: # custom.h PetscErrorCode MatGetCurrentMemType(PetscMat,PetscMemType*) PetscErrorCode MatIsPreallocated(PetscMat,PetscBool*) PetscErrorCode MatHasPreallocationAIJ(PetscMat,PetscBool*,PetscBool*,PetscBool*,PetscBool*) # ----------------------------------------------------------------------------- cdef extern from * nogil: PetscErrorCode MatNullSpaceDestroy(PetscNullSpace*) PetscErrorCode MatNullSpaceView(PetscNullSpace,PetscViewer) PetscErrorCode MatNullSpaceCreate(MPI_Comm,PetscBool,PetscInt,PetscVec[], PetscNullSpace*) PetscErrorCode MatNullSpaceCreateRigidBody(PetscVec,PetscNullSpace*) PetscErrorCode MatNullSpaceGetVecs(PetscNullSpace,PetscBool*,PetscInt*,const PetscVec*[]) PetscErrorCode MatNullSpaceRemove(PetscNullSpace,PetscVec) PetscErrorCode MatNullSpaceTest(PetscNullSpace,PetscMat,PetscBool*) ctypedef PetscErrorCode MatNullSpaceFunction(PetscNullSpace, PetscVec, void*) except PETSC_ERR_PYTHON PetscErrorCode MatNullSpaceSetFunction(PetscNullSpace,MatNullSpaceFunction*,void*) PetscErrorCode MatSetNullSpace(PetscMat,PetscNullSpace) PetscErrorCode MatGetNullSpace(PetscMat,PetscNullSpace*) PetscErrorCode MatSetTransposeNullSpace(PetscMat,PetscNullSpace) PetscErrorCode MatGetTransposeNullSpace(PetscMat,PetscNullSpace*) PetscErrorCode MatSetNearNullSpace(PetscMat,PetscNullSpace) PetscErrorCode MatGetNearNullSpace(PetscMat,PetscNullSpace*) cdef inline NullSpace ref_NullSpace(PetscNullSpace nsp): cdef NullSpace ob = NullSpace() ob.nsp = nsp PetscINCREF(ob.obj) return ob cdef PetscErrorCode NullSpace_Function( PetscNullSpace n, PetscVec v, void * ctx, ) except PETSC_ERR_PYTHON with gil: cdef NullSpace nsp = ref_NullSpace(n) cdef Vec vec = ref_Vec(v) (function, args, kargs) = nsp.get_attr('__function__') function(nsp, vec, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef inline Mat ref_Mat(PetscMat mat): cdef Mat ob = Mat() ob.mat = mat PetscINCREF(ob.obj) return ob # ----------------------------------------------------------------------------- # unary operations cdef Mat mat_pos(Mat self): cdef Mat mat = type(self)() CHKERR( MatDuplicate(self.mat, MAT_COPY_VALUES, &mat.mat) ) return mat cdef Mat mat_neg(Mat self): cdef Mat mat = mat_pos(self) CHKERR( MatScale(mat.mat, -1) ) return mat # inplace binary operations cdef Mat mat_iadd(Mat self, other): if isinstance(other, Mat): self.axpy(1, other) elif isinstance(other, (tuple, list)): alpha, mat = other self.axpy(alpha, mat) elif isinstance(other, Vec): self.setDiagonal(other, PETSC_ADD_VALUES) else: self.shift(other) return self cdef Mat mat_isub(Mat self, other): if isinstance(other, Mat): self.axpy(-1, other) elif isinstance(other, (tuple, list)): alpha, mat = other self.axpy(-alpha, mat) elif isinstance(other, Vec): diag = other.copy() diag.scale(-1) self.setDiagonal(diag, PETSC_ADD_VALUES) diag.destroy() else: self.shift(other) return self cdef Mat mat_imul(Mat self, other): if (isinstance(other, tuple) or isinstance(other, list)): L, R = other self.diagonalScale(L, R) else: self.scale(other) return self cdef Mat mat_idiv(Mat self, other): if isinstance(other, (tuple, list)): L, R = other if isinstance(L, Vec): L = L.copy() L.reciprocal() if isinstance(R, Vec): R = R.copy() R.reciprocal() self.diagonalScale(L, R) else: other = 1/other self.scale(other) return self # binary operations cdef Mat mat_add(Mat self, other): return mat_iadd(mat_pos(self), other) cdef Mat mat_sub(Mat self, other): return mat_isub(mat_pos(self), other) cdef Mat mat_mul(Mat self, other): if isinstance(other, Mat): return self.matMult(other) else: return mat_imul(mat_pos(self), other) cdef Vec mat_mul_vec(Mat self, Vec other): cdef Vec result = self.createVecLeft() self.mult(other, result) return result cdef Mat mat_div(Mat self, other): return mat_idiv(mat_pos(self), other) # reflected binary operations cdef Mat mat_radd(Mat self, other): return mat_add(self, other) cdef Mat mat_rsub(Mat self, other): cdef Mat mat = mat_sub(self, other) mat.scale(-1) return mat cdef Mat mat_rmul(Mat self, other): return mat_mul(self, other) cdef Mat mat_rdiv(Mat self, other): self; other; # unused raise NotImplementedError # ----------------------------------------------------------------------------- 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 PetscMatAssemblyType assemblytype(object assembly) \ except (-1): if assembly is None: return MAT_FINAL_ASSEMBLY elif assembly is False: return MAT_FINAL_ASSEMBLY elif assembly is True: return MAT_FLUSH_ASSEMBLY else: return assembly cdef inline PetscMatInfoType infotype(object info) \ except (-1): if info is None: return MAT_GLOBAL_SUM else: return info # ----------------------------------------------------------------------------- cdef inline PetscErrorCode Mat_Sizes( object size, object bsize, PetscInt *r, PetscInt *c, PetscInt *m, PetscInt *n, PetscInt *M, PetscInt *N, ) except PETSC_ERR_PYTHON: # unpack row and column sizes cdef object rsize, csize try: rsize , csize = size except (TypeError, ValueError): rsize = csize = size # unpack row and column block sizes cdef object rbsize, cbsize try: rbsize , cbsize = bsize except (TypeError, ValueError): rbsize = cbsize = bsize # split row and column sizes Sys_Sizes(rsize, rbsize, r, m, M) Sys_Sizes(csize, cbsize, c, n, N) return PETSC_SUCCESS cdef inline PetscErrorCode Mat_Create( PetscMatType mtype, object comm, object size, object bsize, PetscMat *A, ) except PETSC_ERR_PYTHON: # communicator cdef MPI_Comm ccomm = def_Comm(comm, PETSC_COMM_DEFAULT) # sizes and block sizes cdef PetscInt rbs = 0, cbs = 0, m = 0, n = 0, M = 0, N = 0 Mat_Sizes(size, bsize, &rbs, &cbs, &m, &n, &M, &N) if rbs == PETSC_DECIDE: rbs = 1 if cbs == PETSC_DECIDE: cbs = rbs Sys_Layout(ccomm, rbs, &m, &M) Sys_Layout(ccomm, cbs, &n, &N) # create matrix and set sizes cdef PetscMat mat = NULL CHKERR( MatCreate(ccomm, &mat) ) CHKERR( MatSetSizes(mat, m, n, M, N) ) CHKERR( MatSetBlockSizes(mat, rbs, cbs) ) CHKERR( MatSetType(mat, mtype) ) A[0] = mat return PETSC_SUCCESS cdef inline PetscErrorCode Mat_AllocAIJ_NNZ( PetscMat A, object NNZ) except PETSC_ERR_PYTHON: # cdef PetscBool aij=PETSC_FALSE, baij=PETSC_FALSE, sbaij=PETSC_FALSE, aijis=PETSC_FALSE CHKERR( MatHasPreallocationAIJ(A, &aij, &baij, &sbaij, &aijis)) # local row size and block size cdef PetscInt m=0, bs=1 CHKERR( MatGetLocalSize(A, &m, NULL) ) if baij == PETSC_TRUE or sbaij == PETSC_TRUE: CHKERR( MatGetBlockSize(A, &bs) ) assert bs > 0, "block size not set" # unpack NNZ argument cdef object od_nnz, oo_nnz try: od_nnz, oo_nnz = NNZ except (TypeError, ValueError): od_nnz, oo_nnz = NNZ, None # diagonal and off-diagonal number of nonzeros cdef PetscInt d_nz=PETSC_DECIDE, d_n=0, *d_nnz=NULL if od_nnz is not None: od_nnz = iarray_i(od_nnz, &d_n, &d_nnz) if d_n == 0: d_nnz = NULL # just in case elif d_n == 1: d_nz = d_nnz[0]; d_n=0; d_nnz = NULL cdef PetscInt o_nz=PETSC_DECIDE, o_n=0, *o_nnz=NULL if oo_nnz is not None: oo_nnz = iarray_i(oo_nnz, &o_n, &o_nnz) if o_n == 0: o_nnz = NULL # just in case elif o_n == 1: o_nz = o_nnz[0]; o_n=0; o_nnz = NULL if m == PETSC_DECIDE: if d_n > 1 and d_n*bs > m: m = d_n*bs if o_n > 1 and o_n*bs > m: m = o_n*bs # check array sizes if d_n > 1 and d_n*bs != m: raise ValueError( "size(d_nnz) is %d, expected %d" % (toInt(d_n), toInt(m//bs)) ) if o_n > 1 and o_n*bs != m: raise ValueError( "size(o_nnz) is %d, expected %d" % (toInt(o_n), toInt(m//bs)) ) # preallocate if aij == PETSC_TRUE: CHKERR( MatSeqAIJSetPreallocation(A, d_nz, d_nnz) ) CHKERR( MatMPIAIJSetPreallocation(A, d_nz, d_nnz, o_nz, o_nnz) ) if baij == PETSC_TRUE: CHKERR( MatSeqBAIJSetPreallocation(A, bs, d_nz, d_nnz) ) CHKERR( MatMPIBAIJSetPreallocation(A, bs, d_nz, d_nnz, o_nz, o_nnz) ) if sbaij == PETSC_TRUE: CHKERR( MatSeqSBAIJSetPreallocation(A, bs, d_nz, d_nnz) ) CHKERR( MatMPISBAIJSetPreallocation(A, bs, d_nz, d_nnz, o_nz, o_nnz) ) if aijis == PETSC_TRUE: CHKERR( MatISSetPreallocation(A, d_nz, d_nnz, o_nz, o_nnz) ) return PETSC_SUCCESS cdef inline PetscErrorCode Mat_AllocAIJ_CSR(PetscMat A, object CSR) except PETSC_ERR_PYTHON: # cdef PetscBool aij=PETSC_FALSE, baij=PETSC_FALSE, sbaij=PETSC_FALSE, aijis=PETSC_FALSE CHKERR( MatHasPreallocationAIJ(A, &aij, &baij, &sbaij, &aijis)) # local row size and block size cdef PetscInt m=0, bs = 1 CHKERR( MatGetLocalSize(A, &m, NULL) ) if baij == PETSC_TRUE or sbaij == PETSC_TRUE: CHKERR( MatGetBlockSize(A, &bs) ) assert bs > 0, "block size not set" # unpack CSR argument cdef object oi, oj, ov try: oi, oj, ov = CSR except (TypeError, ValueError): oi, oj = CSR; ov = None # rows, cols, and values cdef PetscInt ni=0, *i=NULL cdef PetscInt nj=0, *j=NULL cdef PetscInt nv=0 cdef PetscScalar *v=NULL oi = iarray_i(oi, &ni, &i) oj = iarray_i(oj, &nj, &j) if ov is not None: ov = iarray_s(ov, &nv, &v) if m == PETSC_DECIDE: m = (ni-1)*bs # check array sizes if ((ni-1)*bs != m): raise ValueError("size(I) is %d, expected %d" % (toInt(ni), toInt(m//bs+1)) ) if (i[0] != 0): raise ValueError("I[0] is %d, expected %d" % (toInt(i[0]), toInt(0)) ) if (i[ni-1] != nj): raise ValueError("size(J) is %d, expected %d" % (toInt(nj), toInt(i[ni-1])) ) if v != NULL and (nj*bs*bs != nv): raise ValueError("size(V) is %d, expected %d" % (toInt(nv), toInt(nj*bs*bs)) ) # preallocate if aij == PETSC_TRUE: CHKERR( MatSeqAIJSetPreallocationCSR(A, i, j, v) ) CHKERR( MatMPIAIJSetPreallocationCSR(A, i, j, v) ) if baij == PETSC_TRUE: CHKERR( MatSeqBAIJSetPreallocationCSR(A, bs, i, j, v) ) CHKERR( MatMPIBAIJSetPreallocationCSR(A, bs, i, j, v) ) if sbaij == PETSC_TRUE: CHKERR( MatSeqSBAIJSetPreallocationCSR(A, bs, i, j, v) ) CHKERR( MatMPISBAIJSetPreallocationCSR(A, bs, i, j, v) ) return PETSC_SUCCESS cdef inline PetscErrorCode Mat_AllocAIJ(PetscMat A,object NNZ, object CSR) except PETSC_ERR_PYTHON: if CSR is not None: return Mat_AllocAIJ_CSR(A, CSR) if NNZ is not None: return Mat_AllocAIJ_NNZ(A, NNZ) return PETSC_SUCCESS cdef inline object Mat_AllocDense(PetscMat A, object array): cdef PetscInt m=0, N=0 CHKERR( MatGetLocalSize(A, &m, NULL) ) CHKERR( MatGetSize(A, NULL, &N) ) cdef PetscInt size=0 cdef PetscScalar *data=NULL if array is not None: array = ofarray_s(array, &size, &data) if m*N != size: raise ValueError( "size(array) is %d, expected %dx%d=%d" % (toInt(size), toInt(m), toInt(N), toInt(m*N)) ) CHKERR( MatSeqDenseSetPreallocation(A, data) ) CHKERR( MatMPIDenseSetPreallocation(A, data) ) return array # ----------------------------------------------------------------------------- ctypedef PetscErrorCode MatSetValuesFcn(PetscMat, PetscInt,const PetscInt*, PetscInt,const PetscInt*, const PetscScalar*,PetscInsertMode) cdef inline MatSetValuesFcn* matsetvalues_fcn(int blocked, int local): cdef MatSetValuesFcn *setvalues = NULL if blocked and local: setvalues = MatSetValuesBlockedLocal elif blocked: setvalues = MatSetValuesBlocked elif local: setvalues = MatSetValuesLocal else: setvalues = MatSetValues return setvalues cdef inline PetscErrorCode matsetvalues(PetscMat A, object oi, object oj, object ov, object oaddv, int blocked, int local) except PETSC_ERR_PYTHON: # block size cdef PetscInt rbs=1, cbs=1 if blocked: CHKERR( MatGetBlockSizes(A, &rbs, &cbs) ) if rbs < 1: rbs = 1 if cbs < 1: cbs = 1 # rows, cols, and values cdef PetscInt ni=0, *i=NULL cdef PetscInt nj=0, *j=NULL cdef PetscInt nv=0 cdef PetscScalar *v=NULL oi = iarray_i(oi, &ni, &i) oj = iarray_i(oj, &nj, &j) ov = iarray_s(ov, &nv, &v) if ni*nj*rbs*cbs != nv: raise ValueError( "incompatible array sizes: ni=%d, nj=%d, nv=%d" % (toInt(ni), toInt(nj), toInt(nv)) ) # MatSetValuesXXX function and insert mode cdef MatSetValuesFcn *setvalues = matsetvalues_fcn(blocked, local) cdef PetscInsertMode addv = insertmode(oaddv) # actual call CHKERR( setvalues(A, ni, i, nj, j, v, addv) ) return PETSC_SUCCESS cdef inline PetscErrorCode matsetvalues_rcv(PetscMat A, object oi, object oj, object ov, object oaddv, int blocked, int local) except PETSC_ERR_PYTHON: # block size cdef PetscInt rbs=1, cbs=1 if blocked: CHKERR( MatGetBlockSizes(A, &rbs, &cbs) ) if rbs < 1: rbs = 1 if cbs < 1: cbs = 1 # rows, cols, and values cdef PetscInt ni=0, *i=NULL cdef PetscInt nj=0, *j=NULL cdef PetscInt nv=0 cdef PetscScalar *v=NULL cdef ndarray ai = iarray_i(oi, &ni, &i) cdef ndarray aj = iarray_i(oj, &nj, &j) cdef ndarray av = iarray_s(ov, &nv, &v) # check various dimensions if PyArray_NDIM(ai) != 2: raise ValueError( ("row indices must have two dimensions: " "rows.ndim=%d") % (PyArray_NDIM(ai)) ) elif not PyArray_ISCONTIGUOUS(ai): raise ValueError( "expecting a C-contiguous array") if PyArray_NDIM(aj) != 2: raise ValueError( ("column indices must have two dimensions: " "cols.ndim=%d") % (PyArray_NDIM(aj)) ) elif not PyArray_ISCONTIGUOUS(aj): raise ValueError( "expecting a C-contiguous array") if PyArray_NDIM(av) < 2: raise ValueError( ("values must have two or more dimensions: " "vals.ndim=%d") % (PyArray_NDIM(av)) ) elif not PyArray_ISCONTIGUOUS(av): raise ValueError( "expecting a C-contiguous array") # check various shapes cdef Py_ssize_t nm = PyArray_DIM(ai, 0) cdef Py_ssize_t si = PyArray_DIM(ai, 1) cdef Py_ssize_t sj = PyArray_DIM(aj, 1) cdef Py_ssize_t sv = PyArray_SIZE(av) // PyArray_DIM(av, 0) if ((nm != PyArray_DIM(aj, 0)) or (nm != PyArray_DIM(av, 0)) or (si*rbs * sj*cbs != sv)): raise ValueError( ("input arrays have incompatible shapes: " "rows.shape=%s, cols.shape=%s, vals.shape=%s") % (ai.shape, aj.shape, av.shape)) # MatSetValuesXXX function and insert mode cdef MatSetValuesFcn *setvalues = \ matsetvalues_fcn(blocked, local) cdef PetscInsertMode addv = insertmode(oaddv) # actual calls cdef Py_ssize_t k=0 for k from 0 <= k < nm: CHKERR( setvalues(A, si, &i[k*si], sj, &j[k*sj], &v[k*sv], addv) ) return PETSC_SUCCESS cdef inline PetscErrorCode matsetvalues_ijv(PetscMat A, object oi, object oj, object ov, object oaddv, object om, int blocked, int local) except PETSC_ERR_PYTHON: # block size cdef PetscInt rbs=1, cbs=1 if blocked: CHKERR( MatGetBlockSizes(A, &rbs, &cbs) ) if rbs < 1: rbs = 1 if cbs < 1: cbs = 1 # column pointers, column indices, and values cdef PetscInt ni=0, *i=NULL cdef PetscInt nj=0, *j=NULL cdef PetscInt nv=0 cdef PetscScalar *v=NULL oi = iarray_i(oi, &ni, &i) oj = iarray_i(oj, &nj, &j) ov = iarray_s(ov, &nv, &v) # row indices cdef PetscInt nm=0, *m=NULL cdef PetscInt rs=0, re=ni-1 if om is not None: om = iarray_i(om, &nm, &m) else: if not local: CHKERR( MatGetOwnershipRange(A, &rs, &re) ) rs //= rbs; re //= rbs nm = re - rs # check various sizes if (ni-1 != nm): raise ValueError( "size(I) is %d, expected %d" % (toInt(ni), toInt(nm+1)) ) if (i[0] != 0):raise ValueError( "I[0] is %d, expected %d" % (toInt(i[0]), 0) ) if (i[ni-1] != nj): raise ValueError( "size(J) is %d, expected %d" % (toInt(nj), toInt(i[ni-1])) ) if (nj*rbs*cbs != nv): raise ValueError( "size(V) is %d, expected %d" % (toInt(nv), toInt(nj*rbs*cbs)) ) # MatSetValuesXXX function and insert mode cdef MatSetValuesFcn *setvalues = \ matsetvalues_fcn(blocked, local) cdef PetscInsertMode addv = insertmode(oaddv) # actual call cdef PetscInt k=0, l=0 cdef PetscInt irow=0, ncol=0, *icol=NULL cdef PetscScalar *sval=NULL for k from 0 <= k < nm: irow = m[k] if m!=NULL else rs+k ncol = i[k+1] - i[k] icol = j + i[k] if blocked: sval = v + i[k]*rbs*cbs for l from 0 <= l < ncol: CHKERR( setvalues(A, 1, &irow, 1, &icol[l], &sval[l*rbs*cbs], addv) ) else: sval = v + i[k] CHKERR( setvalues(A, 1, &irow, ncol, icol, sval, addv) ) return PETSC_SUCCESS cdef inline PetscErrorCode matsetvalues_csr(PetscMat A, object oi, object oj, object ov, object oaddv, int blocked, int local) except PETSC_ERR_PYTHON: matsetvalues_ijv(A, oi, oj, ov, oaddv, None, blocked, local) return PETSC_SUCCESS cdef inline matgetvalues(PetscMat mat, object orows, object ocols, object values): cdef PetscInt ni=0, nj=0, nv=0 cdef PetscInt *i=NULL, *j=NULL cdef PetscScalar *v=NULL cdef ndarray rows = iarray_i(orows, &ni, &i) cdef ndarray cols = iarray_i(ocols, &nj, &j) if values is None: values = empty_s(ni*nj) values.shape = rows.shape + cols.shape values = oarray_s(values, &nv, &v) if (ni*nj != nv): raise ValueError( "incompatible array sizes: ni=%d, nj=%d, nv=%d" % (toInt(ni), toInt(nj), toInt(nv))) CHKERR( MatGetValues(mat, ni, i, nj, j, v) ) return values # ----------------------------------------------------------------------------- cdef extern from * nogil: # custom.h PetscErrorCode MatFactorInfoDefaults(PetscBool,PetscBool,PetscMatFactorInfo*) cdef inline PetscMatFactorShiftType matfactorshifttype(object st) \ except (-1): if isinstance(st, str): if st == "none": return MAT_SHIFT_NONE if st == "nonzero": return MAT_SHIFT_NONZERO if st == "positive_definite": return MAT_SHIFT_POSITIVE_DEFINITE if st == "inblocks": return MAT_SHIFT_INBLOCKS if st == "na": return MAT_SHIFT_NONZERO if st == "pd": return MAT_SHIFT_POSITIVE_DEFINITE else: raise ValueError("unknown shift type: %s" % st) return st cdef PetscErrorCode matfactorinfo(PetscBool inc, PetscBool chol, object opts, PetscMatFactorInfo *info) except PETSC_ERR_PYTHON: CHKERR( MatFactorInfoDefaults(inc,chol,info) ) if opts is None: return PETSC_SUCCESS cdef dict options = dict(opts) # cdef fill = options.pop('fill', None) if fill is not None: info.fill = asReal(fill) # cdef zeropivot = options.pop('zeropivot', None) if zeropivot is not None: info.zeropivot = asReal(zeropivot) # cdef levels = options.pop('levels', None) if levels is not None: info.levels = asInt(levels) cdef diagonal_fill = options.pop('diagonal_fill', None) if diagonal_fill is not None: info.diagonal_fill = (diagonal_fill) # cdef dt = options.pop('dt', None) if dt is not None: info.dt = asReal(dt) cdef dtcol = options.pop('dtcol', None) if dtcol is not None: info.dtcol = asReal(dtcol) cdef dtcount = options.pop('dtcount', None) if dtcount is not None: info.dtcount = asInt(dtcount) if ((dt is not None) or (dtcol is not None) or (dtcount is not None)): info.usedt = PETSC_TRUE # cdef shifttype = options.pop('shifttype', None) if shifttype is not None: info.shifttype = matfactorshifttype(shifttype) cdef shiftamount = options.pop('shiftamount', None) if shiftamount is not None: info.shiftamount = asReal(shiftamount) # if options: raise ValueError("unknown options: %s" % list(options.keys())) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef object mat_getitem(Mat self, object ij): cdef PetscInt M=0, N=0 rows, cols = ij if isinstance(rows, slice): CHKERR( MatGetSize(self.mat, &M, NULL) ) start, stop, stride = rows.indices(toInt(M)) rows = arange(start, stop, stride) if isinstance(cols, slice): CHKERR( MatGetSize(self.mat, NULL, &N) ) start, stop, stride = cols.indices(toInt(N)) cols = arange(start, stop, stride) return matgetvalues(self.mat, rows, cols, None) cdef PetscErrorCode mat_setitem(Mat self, object ij, object v) except PETSC_ERR_PYTHON: cdef PetscInt M=0, N=0 rows, cols = ij if isinstance(rows, slice): CHKERR( MatGetSize(self.mat, &M, NULL) ) start, stop, stride = rows.indices(toInt(M)) rows = arange(start, stop, stride) if isinstance(cols, slice): CHKERR( MatGetSize(self.mat, NULL, &N) ) start, stop, stride = cols.indices(toInt(N)) cols = arange(start, stop, stride) matsetvalues(self.mat, rows, cols, v, None, 0, 0) return PETSC_SUCCESS # ----------------------------------------------------------------------------- #@cython.internal cdef class _Mat_Stencil: cdef PetscMatStencil stencil property i: def __set__(self, value): self.stencil.i = asInt(value) property j: def __set__(self, value): self.stencil.j = asInt(value) property k: def __set__(self, value): self.stencil.k = asInt(value) property c: def __set__(self, value): self.stencil.c = asInt(value) property index: def __set__(self, value): cdef PetscMatStencil *s = &self.stencil s.k = s.j = s.i = 0 asDims(value, &s.i, &s.j, &s.k) property field: def __set__(self, value): cdef PetscMatStencil *s = &self.stencil s.c = asInt(value) cdef matsetvaluestencil(PetscMat A, _Mat_Stencil r, _Mat_Stencil c, object value, PetscInsertMode im, int blocked): # block size cdef PetscInt rbs=1, cbs=1 if blocked: CHKERR( MatGetBlockSizes(A, &rbs, &cbs) ) if rbs < 1: rbs = 1 if cbs < 1: cbs = 1 # values cdef PetscInt nv = 1 cdef PetscScalar *v = NULL value = iarray_s(value, &nv, &v) if rbs*cbs != nv: raise ValueError( "incompatible array sizes: nv=%d" % toInt(nv) ) if blocked: CHKERR( MatSetValuesBlockedStencil(A, 1, &r.stencil, 1, &c.stencil, v, im) ) else: CHKERR( MatSetValuesStencil(A, 1, &r.stencil, 1, &c.stencil, v, im) ) return 0 cdef mat_get_dlpack_ctx(Mat self): if 'dense' not in self.getType(): raise NotImplementedError("Not for type {}".format(self.getType())) cdef object ctx0 = self.get_attr('__dltensor_ctx__') cdef PetscInt n = 0, m = 0, lda = 0 cdef int64_t ndim = 2 cdef int64_t* shape_arr = NULL cdef int64_t* strides_arr = NULL cdef object s1 = None cdef object s2 = None cdef PetscInt devId = 0 cdef PetscMemType mtype = PETSC_MEMTYPE_HOST if ctx0 is None: # First time in, create a linear memory view s1 = oarray_p(empty_p(ndim), NULL, &shape_arr) s2 = oarray_p(empty_p(ndim), NULL, &strides_arr) CHKERR( MatGetSize(self.mat, NULL, &n) ) CHKERR( MatGetLocalSize(self.mat, &m, NULL) ) CHKERR( MatDenseGetLDA(self.mat, &lda) ) shape_arr[0] = m shape_arr[1] = n strides_arr[0] = 1 strides_arr[1] = lda else: (_, _, ndim, s1, s2) = ctx0 devType_ = { PETSC_MEMTYPE_HOST : kDLCPU, PETSC_MEMTYPE_CUDA : kDLCUDA } CHKERR( MatGetCurrentMemType(self.mat, &mtype) ) dtype = devType_.get(mtype, kDLCPU) if dtype != kDLCPU: CHKERR( PetscObjectGetDeviceId(self.mat, &devId) ) ctx0 = (dtype, devId, ndim, s1, s2) self.set_attr('__dltensor_ctx__', ctx0) return ctx0 # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscmatpartitioning.pxi000066400000000000000000000021461454104047300236440ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscMatPartitioningType "MatPartitioningType" PetscMatPartitioningType MATPARTITIONINGCURRENT PetscMatPartitioningType MATPARTITIONINGAVERAGE PetscMatPartitioningType MATPARTITIONINGSQUARE PetscMatPartitioningType MATPARTITIONINGPARMETIS PetscMatPartitioningType MATPARTITIONINGCHACO PetscMatPartitioningType MATPARTITIONINGPARTY PetscMatPartitioningType MATPARTITIONINGPTSCOTCH PetscMatPartitioningType MATPARTITIONINGHIERARCH PetscErrorCode MatPartitioningCreate(MPI_Comm,PetscMatPartitioning*) PetscErrorCode MatPartitioningDestroy(PetscMatPartitioning*) PetscErrorCode MatPartitioningView(PetscMatPartitioning,PetscViewer) PetscErrorCode MatPartitioningSetType(PetscMatPartitioning,PetscMatPartitioningType) PetscErrorCode MatPartitioningGetType(PetscMatPartitioning,PetscMatPartitioningType*) PetscErrorCode MatPartitioningSetFromOptions(PetscMatPartitioning) PetscErrorCode MatPartitioningSetAdjacency(PetscMatPartitioning,PetscMat) PetscErrorCode MatPartitioningApply(PetscMatPartitioning,PetscIS*) petsc4py-3.19.6/src/petsc4py/PETSc/petscmem.pxi000066400000000000000000000005701454104047300212100ustar00rootroot00000000000000cdef extern from * nogil: PetscErrorCode PetscMalloc(size_t,void*) PetscErrorCode PetscFree(void*) PetscErrorCode PetscMemcpy(void*,void*,size_t) PetscErrorCode PetscMemmove(void*,void*,size_t) PetscErrorCode PetscMemzero(void*,size_t) PetscErrorCode PetscMemcmp(void*,void*,size_t,PetscBool*) PetscErrorCode PetscStrallocpy(const char[],char*[]) petsc4py-3.19.6/src/petsc4py/PETSc/petscmpi.pxi000066400000000000000000000077331454104047300212270ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: MPI_Comm MPI_COMM_NULL MPI_Comm MPI_COMM_SELF MPI_Comm MPI_COMM_WORLD MPI_Datatype MPI_DATATYPE_NULL MPI_Op MPI_OP_NULL enum: MPI_IDENT enum: MPI_CONGRUENT int MPI_Comm_compare(MPI_Comm,MPI_Comm,int*) int MPI_Comm_size(MPI_Comm,int*) int MPI_Comm_rank(MPI_Comm,int*) int MPI_Barrier(MPI_Comm) int MPI_Initialized(int*) int MPI_Finalized(int*) ctypedef int MPI_Fint MPI_Fint MPI_Comm_c2f(MPI_Comm) cdef extern from * nogil: MPI_Comm PETSC_COMM_SELF MPI_Comm PETSC_COMM_WORLD PetscErrorCode PetscCommDuplicate(MPI_Comm,MPI_Comm*,int*) PetscErrorCode PetscCommDestroy(MPI_Comm*) # -------------------------------------------------------------------- cdef extern from "cython.h": void *Cython_ImportFunction(object, char[], char[]) except? NULL ctypedef MPI_Comm* PyMPICommGet(object) except NULL ctypedef object PyMPICommNew(MPI_Comm) ctypedef MPI_Datatype* PyMPIDatatypeGet(object) except NULL ctypedef MPI_Op* PyMPIOpGet(object) except NULL cdef inline MPI_Comm mpi4py_Comm_Get(object comm) except *: from mpi4py import MPI cdef PyMPICommGet *commget = \ Cython_ImportFunction( MPI, b"PyMPIComm_Get", b"MPI_Comm *(PyObject *)") if commget == NULL: return MPI_COMM_NULL cdef MPI_Comm *ptr = commget(comm) if ptr == NULL: return MPI_COMM_NULL return ptr[0] cdef inline object mpi4py_Comm_New(MPI_Comm comm): from mpi4py import MPI cdef PyMPICommNew *commnew = \ Cython_ImportFunction( MPI, b"PyMPIComm_New", b"PyObject *(MPI_Comm)") if commnew == NULL: return None return commnew(comm) cdef inline MPI_Datatype mpi4py_Datatype_Get(object datatype) except *: from mpi4py import MPI cdef PyMPIDatatypeGet *datatypeget = \ Cython_ImportFunction( MPI, b"PyMPIDatatype_Get", b"MPI_Datatype *(PyObject *)") if datatypeget == NULL: return MPI_DATATYPE_NULL cdef MPI_Datatype *ptr = datatypeget(datatype) if ptr == NULL: return MPI_DATATYPE_NULL return ptr[0] cdef inline MPI_Op mpi4py_Op_Get(object op) except *: from mpi4py import MPI cdef PyMPIOpGet *opget = \ Cython_ImportFunction( MPI, b"PyMPIOp_Get", b"MPI_Op *(PyObject *)") if opget == NULL: return MPI_OP_NULL cdef MPI_Op *ptr = opget(op) if ptr == NULL: return MPI_OP_NULL return ptr[0] # -------------------------------------------------------------------- cdef inline PetscErrorCode PetscCommDEALLOC(MPI_Comm* comm): if comm == NULL: return PETSC_SUCCESS cdef MPI_Comm tmp = comm[0] if tmp == MPI_COMM_NULL: return PETSC_SUCCESS comm[0] = MPI_COMM_NULL if not (PetscInitializeCalled): return PETSC_SUCCESS if (PetscFinalizeCalled): return PETSC_SUCCESS return PetscCommDestroy(&tmp) cdef inline MPI_Comm def_Comm(object comm, MPI_Comm defv) except *: cdef MPI_Comm retv = MPI_COMM_NULL if comm is None: retv = defv elif isinstance(comm, Comm): retv = (comm).comm elif type(comm).__module__ == 'mpi4py.MPI': retv = mpi4py_Comm_Get(comm) else: retv = (comm).comm return retv cdef inline Comm new_Comm(MPI_Comm comm): cdef Comm ob = Comm() ob.comm = comm return ob # -------------------------------------------------------------------- cdef inline int comm_size(MPI_Comm comm) except ? -1: if comm == MPI_COMM_NULL: raise ValueError("null communicator") cdef int size = 0 CHKERR( MPI_Comm_size(comm, &size) ) return size cdef inline int comm_rank(MPI_Comm comm) except ? -1: if comm == MPI_COMM_NULL: raise ValueError("null communicator") cdef int rank = 0 CHKERR( MPI_Comm_rank(comm, &rank) ) return rank # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscobj.pxi000066400000000000000000000153101454104047300212020ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef int PetscClassId ctypedef int PetscObjectState PetscErrorCode PetscObjectView(PetscObject,PetscViewer) PetscErrorCode PetscObjectDestroy(PetscObject*) PetscErrorCode PetscObjectGetReference(PetscObject,PetscInt*) PetscErrorCode PetscObjectReference(PetscObject) PetscErrorCode PetscObjectDereference(PetscObject) PetscErrorCode PetscObjectSetOptionsPrefix(PetscObject,char[]) PetscErrorCode PetscObjectAppendOptionsPrefix(PetscObject,char[]) PetscErrorCode PetscObjectGetOptionsPrefix(PetscObject,char*[]) PetscErrorCode PetscObjectSetFromOptions(PetscObject) PetscErrorCode PetscObjectViewFromOptions(PetscObject,PetscObject,char[]) PetscErrorCode PetscObjectGetComm(PetscObject,MPI_Comm*) PetscErrorCode PetscObjectGetClassId(PetscObject,PetscClassId*) PetscErrorCode PetscObjectGetType(PetscObject,char*[]) PetscErrorCode PetscObjectGetClassName(PetscObject,char*[]) PetscErrorCode PetscObjectSetName(PetscObject,char[]) PetscErrorCode PetscObjectGetName(PetscObject,char*[]) PetscErrorCode PetscObjectStateIncrease(PetscObject) PetscErrorCode PetscObjectStateSet(PetscObject,PetscObjectState) PetscErrorCode PetscObjectStateGet(PetscObject,PetscObjectState*) PetscErrorCode PetscObjectTypeCompare(PetscObject,char[],PetscBool*) PetscErrorCode PetscObjectChangeTypeName(PetscObject,char[]) PetscErrorCode PetscObjectCompose(PetscObject,char[],PetscObject) PetscErrorCode PetscObjectQuery(PetscObject,char[],PetscObject*) ctypedef void (*PetscVoidFunction)() PetscErrorCode PetscObjectComposeFunction(PetscObject,char[],PetscVoidFunction) PetscErrorCode PetscObjectQueryFunction(PetscObject,char[],PetscVoidFunction*) PetscErrorCode PetscObjectIncrementTabLevel(PetscObject,PetscObject,PetscInt) PetscErrorCode PetscObjectGetTabLevel(PetscObject,PetscInt*) PetscErrorCode PetscObjectSetTabLevel(PetscObject,PetscInt) cdef extern from * nogil: # custom.h PetscErrorCode PetscObjectGetDeviceId(PetscObject,PetscInt*) cdef extern from "" nogil: PetscErrorCode PetscObjectDelayedDestroy(PetscObject*) # -------------------------------------------------------------------- cdef inline PetscErrorCode PetscINCREF(PetscObject *obj) nogil: if obj == NULL: return PETSC_SUCCESS if obj[0] == NULL: return PETSC_SUCCESS return PetscObjectReference(obj[0]) cdef inline PetscErrorCode PetscCLEAR(PetscObject* obj) nogil: 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 PetscErrorCode PetscDEALLOC(PetscObject* obj) nogil: if obj == NULL: return PETSC_SUCCESS if obj[0] == NULL: return PETSC_SUCCESS cdef PetscObject tmp tmp = obj[0]; obj[0] = NULL if not (PetscInitializeCalled): return PETSC_SUCCESS if (PetscFinalizeCalled): return PETSC_SUCCESS return PetscObjectDelayedDestroy(&tmp) cdef inline PetscErrorCode PetscINCSTATE(PetscObject *obj) nogil: if obj == NULL: return PETSC_SUCCESS if obj[0] == NULL: return PETSC_SUCCESS return PetscObjectStateIncrease(obj[0]) # -------------------------------------------------------------------- cdef extern from *: ctypedef struct PyObject void _Py_DecRef"Py_DECREF"(PyObject*) PyObject* PyDict_New() except NULL PyObject* PyDict_GetItem(PyObject*, PyObject*) except * int PyDict_SetItem(PyObject*, PyObject*, PyObject*) except -1 int PyDict_DelItem(PyObject*, PyObject*) except -1 cdef extern from * nogil: ctypedef struct _p_PetscObject: MPI_Comm comm const char *prefix PetscInt refct void *python_context PetscErrorCode (*python_destroy)(void*) cdef inline void Py_DecRef(PyObject *ob) with gil: _Py_DecRef(ob) cdef PetscErrorCode PetscDelPyDict(void* ptr) nogil: if ptr != NULL and Py_IsInitialized(): Py_DecRef(ptr) return PETSC_SUCCESS cdef object PetscGetPyDict(PetscObject obj, bint create): if obj.python_context != NULL: return obj.python_context if create: obj.python_destroy = PetscDelPyDict obj.python_context = PyDict_New() return obj.python_context return None cdef object PetscGetPyObj(PetscObject o, char name[]): cdef object dct = PetscGetPyDict(o, False) if dct is None: return None cdef object key = bytes2str(name) cdef PyObject *d = dct cdef PyObject *k = key cdef PyObject *v = NULL v = PyDict_GetItem(d, k) if v != NULL: return v return None cdef object PetscSetPyObj(PetscObject o, char name[], object p): cdef object dct if p is not None: dct = PetscGetPyDict(o, True) else: dct = PetscGetPyDict(o, False) if dct is None: return None cdef str key = bytes2str(name) cdef PyObject *d = dct cdef PyObject *k = key cdef PyObject *v = p PyDict_SetItem(d, k, v) if v == None: PyDict_DelItem(d, k) return None # -------------------------------------------------------------------- cdef extern from *: object PyLong_FromVoidPtr(void*) cdef inline Py_intptr_t Object_toFortran(PetscObject o) nogil: return o # -------------------------------------------------------------------- cdef inline type subtype_DM(PetscDM dm): cdef PetscObject obj = dm if obj == NULL: return DM # --- cdef PetscBool match = PETSC_FALSE CHKERR( PetscObjectTypeCompare(obj, b"da", &match) ) if match == PETSC_TRUE: return DMDA CHKERR( PetscObjectTypeCompare(obj, b"plex", &match) ) if match == PETSC_TRUE: return DMPlex CHKERR( PetscObjectTypeCompare(obj, b"composite", &match) ) if match == PETSC_TRUE: return DMComposite CHKERR( PetscObjectTypeCompare(obj, b"shell", &match) ) if match == PETSC_TRUE: return DMShell CHKERR( PetscObjectTypeCompare(obj, b"stag", &match) ) if match == PETSC_TRUE: return DMStag CHKERR( PetscObjectTypeCompare(obj, b"swarm", &match) ) if match == PETSC_TRUE: return DMSwarm # --- return DM cdef inline type subtype_Object(PetscObject obj): cdef type klass = Object if obj == NULL: return klass cdef PetscClassId classid = 0 CHKERR( PetscObjectGetClassId(obj,&classid) ) if classid == PETSC_DM_CLASSID: klass = subtype_DM(obj) else: klass = PyPetscType_Lookup(classid) return klass # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscopt.pxi000066400000000000000000000153541454104047300212420ustar00rootroot00000000000000cdef extern from * nogil: ctypedef struct _n_PetscOptions ctypedef _n_PetscOptions* PetscOptions PetscErrorCode PetscOptionsCreate(PetscOptions*) PetscErrorCode PetscOptionsDestroy(PetscOptions*) PetscErrorCode PetscOptionsView(PetscOptions,PetscViewer) PetscErrorCode PetscOptionsClear(PetscOptions) PetscErrorCode PetscOptionsPrefixPush(PetscOptions,char[]) PetscErrorCode PetscOptionsPrefixPop(PetscOptions) PetscErrorCode PetscOptionsHasName(PetscOptions,char[],char[],PetscBool*) PetscErrorCode PetscOptionsSetAlias(PetscOptions,char[],char[]) PetscErrorCode PetscOptionsSetValue(PetscOptions,char[],char[]) PetscErrorCode PetscOptionsClearValue(PetscOptions,char[]) PetscErrorCode PetscOptionsInsertString(PetscOptions,char[]) PetscErrorCode PetscOptionsInsertFile(PetscOptions,char[]) PetscErrorCode PetscOptionsGetAll(PetscOptions,char*[]) PetscErrorCode PetscOptionsGetBool(PetscOptions,char[],char[],PetscBool*,PetscBool*) PetscErrorCode PetscOptionsGetInt(PetscOptions,char[],char[],PetscInt*,PetscBool*) PetscErrorCode PetscOptionsGetReal(PetscOptions,char[],char[],PetscReal*,PetscBool*) PetscErrorCode PetscOptionsGetScalar(PetscOptions,char[],char[],PetscScalar*,PetscBool*) PetscErrorCode PetscOptionsGetString(PetscOptions,char[],char[],char[],size_t,PetscBool*) ctypedef struct _p_PetscToken ctypedef _p_PetscToken* PetscToken PetscErrorCode PetscTokenCreate(char[],char,PetscToken*) PetscErrorCode PetscTokenDestroy(PetscToken*) PetscErrorCode PetscTokenFind(PetscToken,char*[]) PetscErrorCode PetscOptionsValidKey(char[],PetscBool*) # cdef getprefix(prefix, deft=None): if prefix is None: prefix = deft elif isinstance(prefix, Options): prefix = prefix.prefix elif isinstance(prefix, Object): prefix = prefix.getOptionsPrefix() elif not isinstance(prefix, str): raise TypeError('option prefix must be string') if not prefix: return None if prefix.count(' '): raise ValueError('option prefix should not have spaces') if prefix.startswith('-'): raise ValueError('option prefix should not start with a hyphen') return prefix # cdef opt2str(const char *pre, const char *name): p = bytes2str(pre) if pre!=NULL else None n = bytes2str(name) if name[0]!=c'-' else bytes2str(&name[1]) return '(prefix:%s, name:%s)' % (p, n) cdef getopt_Bool(PetscOptions opt, const char *pre, const char *name, object deft): cdef PetscBool value = PETSC_FALSE cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsGetBool(opt, pre, name, &value, &flag) ) if flag==PETSC_TRUE: return toBool(value) if deft is not None: return deft raise KeyError(opt2str(pre, name)) cdef getopt_Int(PetscOptions opt, const char *pre, const char *name, object deft): cdef PetscInt value = 0 cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsGetInt(opt, pre, name, &value, &flag) ) if flag==PETSC_TRUE: return toInt(value) if deft is not None: return deft raise KeyError(opt2str(pre, name)) cdef getopt_Real(PetscOptions opt, const char *pre, const char *name, object deft): cdef PetscReal value = 0 cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsGetReal(opt, pre, name, &value, &flag) ) if flag==PETSC_TRUE: return toReal(value) if deft is not None: return deft raise KeyError(opt2str(pre, name)) cdef getopt_Scalar(PetscOptions opt, const char *pre, const char *name, object deft): cdef PetscScalar value = 0 cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsGetScalar(opt, pre, name, &value, &flag) ) if flag==PETSC_TRUE: return toScalar(value) if deft is not None: return deft raise KeyError(opt2str(pre, name)) cdef getopt_String(PetscOptions opt, const char *pre, const char *name, object deft): cdef char value[1024+1] cdef PetscBool flag = PETSC_FALSE CHKERR( PetscOptionsGetString(opt, pre, name, value, 1024, &flag) ) if flag==PETSC_TRUE: return bytes2str(value) if deft is not None: return deft raise KeyError(opt2str(pre, name)) cdef enum PetscOptType: OPT_BOOL OPT_INT OPT_REAL OPT_SCALAR OPT_STRING cdef getpair(prefix, name, const char **pr, const char **nm): # -- cdef const char *p = NULL prefix = str2bytes(prefix, &p) if p != NULL and p[0] == c'-': p = &p[1] # -- cdef const char *n = NULL name = str2bytes(name, &n) if n != NULL and n[0] != c'-': name = b'-' + name name = str2bytes(name, &n) # -- pr[0] = p nm[0] = n return (prefix, name) cdef getopt(PetscOptions opt, PetscOptType otype, prefix, name, deft): cdef const char *pr = NULL cdef const char *nm = NULL tmp = getpair(prefix, name, &pr, &nm) if otype == OPT_BOOL : return getopt_Bool (opt, pr, nm, deft) if otype == OPT_INT : return getopt_Int (opt, pr, nm, deft) if otype == OPT_REAL : return getopt_Real (opt, pr, nm, deft) if otype == OPT_SCALAR : return getopt_Scalar (opt, pr, nm, deft) if otype == OPT_STRING : return getopt_String (opt, pr, nm, deft) # simple minded options parser cdef tokenize(options): cdef PetscToken t = NULL cdef const char *s = NULL cdef const char *p = NULL options = str2bytes(options, &s) cdef list tokens = [] CHKERR( PetscTokenCreate(s, c' ', &t) ) try: CHKERR( PetscTokenFind(t, &p) ) while p != NULL: tokens.append(bytes2str(p)) CHKERR( PetscTokenFind(t, &p) ) finally: CHKERR( PetscTokenDestroy(&t) ) return tokens cdef bint iskey(key): cdef const char *k = NULL cdef PetscBool b = PETSC_FALSE if key: key = str2bytes(key, &k) CHKERR( PetscOptionsValidKey(k, &b) ) if b == PETSC_TRUE: return True return False cdef gettok(tokens): if tokens: return tokens.pop(0) else: return None cdef getkey(key, prefix): if not iskey(key): return None key = key[1:] if key[0] == '-': key = key[1:] if not key.startswith(prefix): return None return key.replace(prefix, '', 1) cdef parseopt(options, prefix): if isinstance(options, str): tokens = tokenize(options) else: tokens = list(options) prefix = prefix or '' # parser loop opts = {} first = gettok(tokens) while first: key = getkey(first, prefix) if not key: first = gettok(tokens) else: second = gettok(tokens) if getkey(second, prefix): value = None first = second else: value = second first = gettok(tokens) opts[key] = value # we are done return opts # petsc4py-3.19.6/src/petsc4py/PETSc/petscpartitioner.pxi000066400000000000000000000020631454104047300227710ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscPartitionerType PetscPartitionerType PETSCPARTITIONERPARMETIS PetscPartitionerType PETSCPARTITIONERPTSCOTCH PetscPartitionerType PETSCPARTITIONERCHACO PetscPartitionerType PETSCPARTITIONERSIMPLE PetscPartitionerType PETSCPARTITIONERSHELL PetscPartitionerType PETSCPARTITIONERGATHER PetscPartitionerType PETSCPARTITIONERMATPARTITIONING PetscErrorCode PetscPartitionerCreate(MPI_Comm,PetscPartitioner*) PetscErrorCode PetscPartitionerDestroy(PetscPartitioner*) PetscErrorCode PetscPartitionerView(PetscPartitioner,PetscViewer) PetscErrorCode PetscPartitionerSetType(PetscPartitioner,PetscPartitionerType) PetscErrorCode PetscPartitionerGetType(PetscPartitioner,PetscPartitionerType*) PetscErrorCode PetscPartitionerSetFromOptions(PetscPartitioner) PetscErrorCode PetscPartitionerSetUp(PetscPartitioner) PetscErrorCode PetscPartitionerReset(PetscPartitioner) PetscErrorCode PetscPartitionerShellSetPartition(PetscPartitioner,PetscInt,PetscInt*,PetscInt*) petsc4py-3.19.6/src/petsc4py/PETSc/petscpc.pxi000066400000000000000000000507321454104047300210410ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscPCType "PCType" PetscPCType PCNONE PetscPCType PCJACOBI PetscPCType PCSOR PetscPCType PCLU PetscPCType PCQR PetscPCType PCSHELL PetscPCType PCBJACOBI PetscPCType PCMG PetscPCType PCEISENSTAT PetscPCType PCILU PetscPCType PCICC PetscPCType PCASM PetscPCType PCGASM PetscPCType PCKSP PetscPCType PCCOMPOSITE PetscPCType PCREDUNDANT PetscPCType PCSPAI PetscPCType PCNN PetscPCType PCCHOLESKY PetscPCType PCPBJACOBI PetscPCType PCVPBJACOBI PetscPCType PCMAT PetscPCType PCHYPRE PetscPCType PCPARMS PetscPCType PCFIELDSPLIT PetscPCType PCTFS PetscPCType PCML PetscPCType PCGALERKIN PetscPCType PCEXOTIC PetscPCType PCCP PetscPCType PCBFBT PetscPCType PCLSC PetscPCType PCPYTHON PetscPCType PCPFMG PetscPCType PCSYSPFMG PetscPCType PCREDISTRIBUTE PetscPCType PCSVD PetscPCType PCGAMG PetscPCType PCCHOWILUVIENNACL PetscPCType PCROWSCALINGVIENNACL PetscPCType PCSAVIENNACL PetscPCType PCBDDC PetscPCType PCKACZMARZ PetscPCType PCTELESCOPE PetscPCType PCPATCH PetscPCType PCLMVM PetscPCType PCHMG PetscPCType PCDEFLATION PetscPCType PCHPDDM PetscPCType PCH2OPUS ctypedef enum PetscPCSide "PCSide": PC_SIDE_DEFAULT PC_LEFT PC_RIGHT PC_SYMMETRIC ctypedef enum PetscPCASMType "PCASMType": PC_ASM_BASIC PC_ASM_RESTRICT PC_ASM_INTERPOLATE PC_ASM_NONE ctypedef enum PetscPCGASMType "PCGASMType": PC_GASM_BASIC PC_GASM_RESTRICT PC_GASM_INTERPOLATE PC_GASM_NONE ctypedef enum PetscPCMGType "PCMGType": PC_MG_MULTIPLICATIVE PC_MG_ADDITIVE PC_MG_FULL PC_MG_KASKADE ctypedef enum PetscPCMGCycleType "PCMGCycleType": PC_MG_CYCLE_V PC_MG_CYCLE_W ctypedef const char* PetscPCGAMGType "PCGAMGType" PetscPCGAMGType PCGAMGAGG PetscPCGAMGType PCGAMGGEO PetscPCGAMGType PCGAMGCLASSICAL ctypedef const char* PetscPCHYPREType "const char*" ctypedef enum PetscPCCompositeType "PCCompositeType": PC_COMPOSITE_ADDITIVE PC_COMPOSITE_MULTIPLICATIVE PC_COMPOSITE_SYMMETRIC_MULTIPLICATIVE PC_COMPOSITE_SPECIAL PC_COMPOSITE_SCHUR ctypedef enum PetscPCFieldSplitSchurPreType "PCFieldSplitSchurPreType": PC_FIELDSPLIT_SCHUR_PRE_SELF PC_FIELDSPLIT_SCHUR_PRE_SELFP PC_FIELDSPLIT_SCHUR_PRE_A11 PC_FIELDSPLIT_SCHUR_PRE_USER PC_FIELDSPLIT_SCHUR_PRE_FULL ctypedef enum PetscPCFieldSplitSchurFactType "PCFieldSplitSchurFactType": PC_FIELDSPLIT_SCHUR_FACT_DIAG PC_FIELDSPLIT_SCHUR_FACT_LOWER PC_FIELDSPLIT_SCHUR_FACT_UPPER PC_FIELDSPLIT_SCHUR_FACT_FULL ctypedef enum PetscPCPatchConstructType "PCPatchConstructType": PC_PATCH_STAR PC_PATCH_VANKA PC_PATCH_PARDECOMP PC_PATCH_USER PC_PATCH_PYTHON ctypedef enum PetscPCHPDDMCoarseCorrectionType "PCHPDDMCoarseCorrectionType": PC_HPDDM_COARSE_CORRECTION_DEFLATED PC_HPDDM_COARSE_CORRECTION_ADDITIVE PC_HPDDM_COARSE_CORRECTION_BALANCED ctypedef enum PetscPCDeflationSpaceType "PCDeflationSpaceType": PC_DEFLATION_SPACE_HAAR PC_DEFLATION_SPACE_DB2 PC_DEFLATION_SPACE_DB4 PC_DEFLATION_SPACE_DB8 PC_DEFLATION_SPACE_DB16 PC_DEFLATION_SPACE_BIORTH22 PC_DEFLATION_SPACE_MEYER PC_DEFLATION_SPACE_AGGREGATION PC_DEFLATION_SPACE_USER ctypedef enum PetscPCFailedReason "PCFailedReason": PC_SETUP_ERROR PC_NOERROR PC_FACTOR_STRUCT_ZEROPIVOT PC_FACTOR_NUMERIC_ZEROPIVOT PC_FACTOR_OUTMEMORY PC_FACTOR_OTHER PC_SUBPC_ERROR PetscErrorCode PCCreate(MPI_Comm,PetscPC*) PetscErrorCode PCDestroy(PetscPC*) PetscErrorCode PCView(PetscPC,PetscViewer) PetscErrorCode PCSetType(PetscPC,PetscPCType) PetscErrorCode PCGetType(PetscPC,PetscPCType*) PetscErrorCode PCSetOptionsPrefix(PetscPC,char[]) PetscErrorCode PCAppendOptionsPrefix(PetscPC,char[]) PetscErrorCode PCGetOptionsPrefix(PetscPC,char*[]) PetscErrorCode PCSetFromOptions(PetscPC) PetscErrorCode PCSetFailedReason(PetscPC,PetscPCFailedReason) PetscErrorCode PCGetFailedReason(PetscPC,PetscPCFailedReason*) PetscErrorCode PCGetFailedReasonRank(PetscPC,PetscPCFailedReason*) PetscErrorCode PCSetUp(PetscPC) PetscErrorCode PCReset(PetscPC) PetscErrorCode PCSetUpOnBlocks(PetscPC) PetscErrorCode PCApply(PetscPC,PetscVec,PetscVec) PetscErrorCode PCMatApply(PetscPC,PetscMat,PetscMat) PetscErrorCode PCApplyTranspose(PetscPC,PetscVec,PetscVec) PetscErrorCode PCApplySymmetricLeft(PetscPC,PetscVec,PetscVec) PetscErrorCode PCApplySymmetricRight(PetscPC,PetscVec,PetscVec) PetscErrorCode PCApplyRichardson(PetscPC,PetscVec,PetscVec,PetscVec,PetscReal,PetscReal,PetscReal,PetscInt) PetscErrorCode PCApplyBAorAB(PetscPC,PetscPCSide,PetscVec,PetscVec,PetscVec) PetscErrorCode PCApplyBAorABTranspose(PetscPC,PetscPCSide,PetscVec,PetscVec,PetscVec) #int PCApplyTransposeExists(PetscPC,PetscBool*) #int PCApplyRichardsonExists(PetscPC,PetscBool*) PetscErrorCode PCGetDM(PetscPC,PetscDM*) PetscErrorCode PCSetDM(PetscPC,PetscDM) PetscErrorCode PCSetOperators(PetscPC,PetscMat,PetscMat) PetscErrorCode PCGetOperators(PetscPC,PetscMat*,PetscMat*) PetscErrorCode PCGetOperatorsSet(PetscPC,PetscBool*,PetscBool*) PetscErrorCode PCSetCoordinates(PetscPC,PetscInt,PetscInt,PetscReal[]) PetscErrorCode PCSetUseAmat(PetscPC,PetscBool) PetscErrorCode PCGetUseAmat(PetscPC,PetscBool*) PetscErrorCode PCComputeExplicitOperator(PetscPC,PetscMat*) PetscErrorCode PCDiagonalScale(PetscPC,PetscBool*) PetscErrorCode PCDiagonalScaleLeft(PetscPC,PetscVec,PetscVec) PetscErrorCode PCDiagonalScaleRight(PetscPC,PetscVec,PetscVec) PetscErrorCode PCDiagonalScaleSet(PetscPC,PetscVec) PetscErrorCode PCASMSetType(PetscPC,PetscPCASMType) PetscErrorCode PCASMSetOverlap(PetscPC,PetscInt) PetscErrorCode PCASMSetLocalSubdomains(PetscPC,PetscInt,PetscIS[],PetscIS[]) PetscErrorCode PCASMSetTotalSubdomains(PetscPC,PetscInt,PetscIS[],PetscIS[]) PetscErrorCode PCASMGetSubKSP(PetscPC,PetscInt*,PetscInt*,PetscKSP*[]) PetscErrorCode PCASMSetSortIndices(PetscPC,PetscBool) PetscErrorCode PCGASMSetType(PetscPC,PetscPCGASMType) PetscErrorCode PCGASMSetOverlap(PetscPC,PetscInt) PetscErrorCode PCGAMGSetType(PetscPC,PetscPCGAMGType) PetscErrorCode PCGAMGSetNlevels(PetscPC,PetscInt) PetscErrorCode PCGAMGSetNSmooths(PetscPC,PetscInt) PetscErrorCode PCHYPREGetType(PetscPC,PetscPCHYPREType*) PetscErrorCode PCHYPRESetType(PetscPC,PetscPCHYPREType) PetscErrorCode PCHYPRESetDiscreteCurl(PetscPC,PetscMat); PetscErrorCode PCHYPRESetDiscreteGradient(PetscPC,PetscMat); PetscErrorCode PCHYPRESetAlphaPoissonMatrix(PetscPC,PetscMat); PetscErrorCode PCHYPRESetBetaPoissonMatrix(PetscPC,PetscMat); PetscErrorCode PCHYPRESetEdgeConstantVectors(PetscPC,PetscVec,PetscVec,PetscVec); PetscErrorCode PCHYPRESetInterpolations(PetscPC, PetscInt, PetscMat, PetscMat[], PetscMat, PetscMat[]); PetscErrorCode PCHYPREAMSSetInteriorNodes(PetscPC, PetscVec); PetscErrorCode PCFactorGetMatrix(PetscPC,PetscMat*) PetscErrorCode PCFactorSetZeroPivot(PetscPC,PetscReal) PetscErrorCode PCFactorSetShiftType(PetscPC,PetscMatFactorShiftType) PetscErrorCode PCFactorSetShiftAmount(PetscPC,PetscReal) PetscErrorCode PCFactorSetMatSolverType(PetscPC,PetscMatSolverType) PetscErrorCode PCFactorGetMatSolverType(PetscPC,PetscMatSolverType*) PetscErrorCode PCFactorSetUpMatSolverType(PetscPC) PetscErrorCode PCFactorSetFill(PetscPC,PetscReal) PetscErrorCode PCFactorSetColumnPivot(PetscPC,PetscReal) PetscErrorCode PCFactorReorderForNonzeroDiagonal(PetscPC,PetscReal) PetscErrorCode PCFactorSetMatOrderingType(PetscPC,PetscMatOrderingType) PetscErrorCode PCFactorSetReuseOrdering(PetscPC,PetscBool ) PetscErrorCode PCFactorSetReuseFill(PetscPC,PetscBool ) PetscErrorCode PCFactorSetUseInPlace(PetscPC) PetscErrorCode PCFactorSetAllowDiagonalFill(PetscPC) PetscErrorCode PCFactorSetPivotInBlocks(PetscPC,PetscBool ) PetscErrorCode PCFactorSetLevels(PetscPC,PetscInt) PetscErrorCode PCFactorSetDropTolerance(PetscPC,PetscReal,PetscReal,PetscInt) PetscErrorCode PCFieldSplitSetType(PetscPC,PetscPCCompositeType) PetscErrorCode PCFieldSplitSetBlockSize(PetscPC,PetscInt) PetscErrorCode PCFieldSplitSetFields(PetscPC,char[],PetscInt,PetscInt*,PetscInt*) PetscErrorCode PCFieldSplitSetIS(PetscPC,char[],PetscIS) PetscErrorCode PCFieldSplitGetSubKSP(PetscPC,PetscInt*,PetscKSP*[]) PetscErrorCode PCFieldSplitSchurGetSubKSP(PetscPC,PetscInt*,PetscKSP*[]) PetscErrorCode PCFieldSplitSetSchurPre(PetscPC,PetscPCFieldSplitSchurPreType,PetscMat) PetscErrorCode PCFieldSplitSetSchurFactType(PetscPC,PetscPCFieldSplitSchurFactType) #int PCFieldSplitGetSchurBlocks(PetscPC,PetscMat*,PetscMat*,PetscMat*,PetscMat*) PetscErrorCode PCCompositeSetType(PetscPC,PetscPCCompositeType) PetscErrorCode PCCompositeGetPC(PetscPC,PetscInt,PetscPC*) PetscErrorCode PCCompositeAddPCType(PetscPC,PetscPCType) PetscErrorCode PCCompositeAddPC(PetscPC,PetscPC) PetscErrorCode PCKSPGetKSP(PetscPC,PetscKSP*) PetscErrorCode PCSetReusePreconditioner(PetscPC,PetscBool) # --- MG --- PetscErrorCode PCMGSetType(PetscPC,PetscPCMGType) PetscErrorCode PCMGGetType(PetscPC,PetscPCMGType*) PetscErrorCode PCMGSetInterpolation(PetscPC,PetscInt,PetscMat) PetscErrorCode PCMGGetInterpolation(PetscPC,PetscInt,PetscMat*) PetscErrorCode PCMGSetRestriction(PetscPC,PetscInt,PetscMat) PetscErrorCode PCMGGetRestriction(PetscPC,PetscInt,PetscMat*) PetscErrorCode PCMGSetRScale(PetscPC,PetscInt,PetscVec) PetscErrorCode PCMGGetRScale(PetscPC,PetscInt,PetscVec*) PetscErrorCode PCMGGetSmoother(PetscPC,PetscInt,PetscKSP*) PetscErrorCode PCMGGetSmootherUp(PetscPC,PetscInt,PetscKSP*) PetscErrorCode PCMGGetSmootherDown(PetscPC,PetscInt,PetscKSP*) PetscErrorCode PCMGGetCoarseSolve(PetscPC,PetscKSP*) PetscErrorCode PCMGSetRhs(PetscPC,PetscInt,PetscVec) PetscErrorCode PCMGSetX(PetscPC,PetscInt,PetscVec) PetscErrorCode PCMGSetR(PetscPC,PetscInt,PetscVec) PetscErrorCode PCMGSetLevels(PetscPC,PetscInt,MPI_Comm*) PetscErrorCode PCMGGetLevels(PetscPC,PetscInt*) PetscErrorCode PCMGSetCycleType(PetscPC,PetscPCMGCycleType) PetscErrorCode PCMGSetCycleTypeOnLevel(PetscPC,PetscInt,PetscPCMGCycleType) PetscErrorCode PCBDDCSetDiscreteGradient(PetscPC,PetscMat,PetscInt,PetscInt,PetscBool,PetscBool) PetscErrorCode PCBDDCSetDivergenceMat(PetscPC,PetscMat,PetscBool,PetscIS) PetscErrorCode PCBDDCSetChangeOfBasisMat(PetscPC,PetscMat,PetscBool) PetscErrorCode PCBDDCSetPrimalVerticesIS(PetscPC,PetscIS) PetscErrorCode PCBDDCSetPrimalVerticesLocalIS(PetscPC,PetscIS) PetscErrorCode PCBDDCSetCoarseningRatio(PetscPC,PetscInt) PetscErrorCode PCBDDCSetLevels(PetscPC,PetscInt) PetscErrorCode PCBDDCSetDirichletBoundaries(PetscPC,PetscIS) PetscErrorCode PCBDDCSetDirichletBoundariesLocal(PetscPC,PetscIS) PetscErrorCode PCBDDCSetNeumannBoundaries(PetscPC,PetscIS) PetscErrorCode PCBDDCSetNeumannBoundariesLocal(PetscPC,PetscIS) PetscErrorCode PCBDDCSetDofsSplitting(PetscPC,PetscInt,PetscIS[]) PetscErrorCode PCBDDCSetDofsSplittingLocal(PetscPC,PetscInt,PetscIS[]) # --- Patch --- ctypedef PetscErrorCode (*PetscPCPatchComputeOperator)(PetscPC, PetscInt, PetscVec, PetscMat, PetscIS, PetscInt, const PetscInt*, const PetscInt*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscPCPatchComputeFunction)(PetscPC, PetscInt, PetscVec, PetscVec, PetscIS, PetscInt, const PetscInt*, const PetscInt*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscPCPatchConstructOperator)(PetscPC, PetscInt*, PetscIS**, PetscIS*, void*) except PETSC_ERR_PYTHON PetscErrorCode PCPatchSetCellNumbering(PetscPC, PetscSection) PetscErrorCode PCPatchSetDiscretisationInfo(PetscPC, PetscInt, PetscDM*, PetscInt*, PetscInt*, const PetscInt**, const PetscInt*, PetscInt, const PetscInt*, PetscInt, const PetscInt*) PetscErrorCode PCPatchSetComputeOperator(PetscPC, PetscPCPatchComputeOperator, void*) PetscErrorCode PCPatchSetComputeOperatorInteriorFacets(PetscPC, PetscPCPatchComputeOperator, void*) PetscErrorCode PCPatchSetComputeFunction(PetscPC, PetscPCPatchComputeFunction, void*) PetscErrorCode PCPatchSetComputeFunctionInteriorFacets(PetscPC, PetscPCPatchComputeFunction, void*) PetscErrorCode PCPatchSetConstructType(PetscPC, PetscPCPatchConstructType, PetscPCPatchConstructOperator, void*) ctypedef PetscErrorCode (*PetscPCHPDDMAuxiliaryMat)(PetscMat, PetscReal, PetscVec, PetscVec, PetscReal, PetscIS, void*) except PETSC_ERR_PYTHON PetscErrorCode PCHPDDMSetAuxiliaryMat(PetscPC,PetscIS,PetscMat,PetscPCHPDDMAuxiliaryMat,void*) PetscErrorCode PCHPDDMSetRHSMat(PetscPC,PetscMat) PetscErrorCode PCHPDDMHasNeumannMat(PetscPC,PetscBool) PetscErrorCode PCHPDDMSetCoarseCorrectionType(PetscPC,PetscPCHPDDMCoarseCorrectionType) PetscErrorCode PCHPDDMGetCoarseCorrectionType(PetscPC,PetscPCHPDDMCoarseCorrectionType*) PetscErrorCode PCHPDDMGetSTShareSubKSP(PetscPC,PetscBool*) PetscErrorCode PCHPDDMSetDeflationMat(PetscPC,PetscIS,PetscMat) # --- SPAI --- PetscErrorCode PCSPAISetEpsilon(PetscPC,PetscReal) PetscErrorCode PCSPAISetNBSteps(PetscPC,PetscInt) PetscErrorCode PCSPAISetMax(PetscPC,PetscInt) PetscErrorCode PCSPAISetMaxNew(PetscPC,PetscInt) PetscErrorCode PCSPAISetBlockSize(PetscPC,PetscInt) PetscErrorCode PCSPAISetCacheSize(PetscPC,PetscInt) PetscErrorCode PCSPAISetVerbose(PetscPC,PetscInt) PetscErrorCode PCSPAISetSp(PetscPC,PetscInt) # --- DEFLATION --- PetscErrorCode PCDeflationSetInitOnly(PetscPC,PetscBool) PetscErrorCode PCDeflationSetLevels(PetscPC,PetscInt) PetscErrorCode PCDeflationSetReductionFactor(PetscPC,PetscInt) PetscErrorCode PCDeflationSetCorrectionFactor(PetscPC,PetscScalar) PetscErrorCode PCDeflationSetSpaceToCompute(PetscPC,PetscPCDeflationSpaceType,PetscInt) PetscErrorCode PCDeflationSetSpace(PetscPC,PetscMat,PetscBool) PetscErrorCode PCDeflationSetProjectionNullSpaceMat(PetscPC,PetscMat) PetscErrorCode PCDeflationSetCoarseMat(PetscPC,PetscMat) PetscErrorCode PCDeflationGetCoarseKSP(PetscPC,PetscKSP*) PetscErrorCode PCDeflationGetPC(PetscPC,PetscPC*) # --- PYTHON --- PetscErrorCode PCPythonSetType(PetscPC,char[]) PetscErrorCode PCPythonGetType(PetscPC,char*[]) # -------------------------------------------------------------------- cdef inline PC ref_PC(PetscPC pc): cdef PC ob = PC() ob.pc = pc PetscINCREF(ob.obj) return ob cdef PetscErrorCode PCPatch_ComputeOperator( PetscPC pc, PetscInt point, PetscVec vec, PetscMat mat, PetscIS cells, PetscInt ndof, const PetscInt *dofmap, const PetscInt *dofmapWithAll, void *ctx) except PETSC_ERR_PYTHON with gil: cdef Vec Vec = ref_Vec(vec) cdef Mat Mat = ref_Mat(mat) cdef PC Pc = ref_PC(pc) cdef IS Is = ref_IS(cells) cdef object context = Pc.get_attr("__patch_compute_operator__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple (op, args, kargs) = context cdef PetscInt[:] pydofs = dofmap cdef PetscInt[:] pydofsWithAll if dofmapWithAll != NULL: pydofsWithAll = dofmapWithAll dofsall = asarray(pydofsWithAll) else: dofsall = None op(Pc, toInt(point), Vec, Mat, Is, asarray(pydofs), dofsall, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode PCPatch_ComputeFunction( PetscPC pc, PetscInt point, PetscVec vec, PetscVec out, PetscIS cells, PetscInt ndof, const PetscInt *dofmap, const PetscInt *dofmapWithAll, void *ctx) except PETSC_ERR_PYTHON with gil: cdef Vec Out = ref_Vec(out) cdef Vec Vec = ref_Vec(vec) cdef PC Pc = ref_PC(pc) cdef IS Is = ref_IS(cells) cdef object context = Pc.get_attr("__patch_compute_function__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple (op, args, kargs) = context cdef PetscInt[:] pydofs = dofmap cdef PetscInt[:] pydofsWithAll = dofmapWithAll op(Pc, toInt(point), Vec, Out, Is, asarray(pydofs), asarray(pydofsWithAll), *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode PCPatch_ComputeOperatorInteriorFacets( PetscPC pc, PetscInt point, PetscVec vec, PetscMat mat, PetscIS facets, PetscInt ndof, const PetscInt *dofmap, const PetscInt *dofmapWithAll, void *ctx) except PETSC_ERR_PYTHON with gil: cdef Vec Vec = ref_Vec(vec) cdef Mat Mat = ref_Mat(mat) cdef PC Pc = ref_PC(pc) cdef IS Is = ref_IS(facets) cdef object context = Pc.get_attr("__patch_compute_operator_interior_facets__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple (op, args, kargs) = context cdef PetscInt[:] pydofs = dofmap cdef PetscInt[:] pydofsWithAll if dofmapWithAll != NULL: pydofsWithAll = dofmapWithAll dofsall = asarray(pydofsWithAll) else: dofsall = None op(Pc, toInt(point), Vec, Mat, Is, asarray(pydofs), dofsall, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode PCPatch_ComputeFunctionInteriorFacets( PetscPC pc, PetscInt point, PetscVec vec, PetscVec out, PetscIS facets, PetscInt ndof, const PetscInt *dofmap, const PetscInt *dofmapWithAll, void *ctx) except PETSC_ERR_PYTHON with gil: cdef Vec Out = ref_Vec(out) cdef Vec Vec = ref_Vec(vec) cdef PC Pc = ref_PC(pc) cdef IS Is = ref_IS(facets) cdef object context = Pc.get_attr("__patch_compute_function_interior_facets__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple (op, args, kargs) = context cdef PetscInt[:] pydofs = dofmap cdef PetscInt[:] pydofsWithAll = dofmapWithAll op(Pc, toInt(point), Vec, Out, Is, asarray(pydofs), asarray(pydofsWithAll), *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode PCPatch_UserConstructOperator( PetscPC pc, PetscInt *n, PetscIS **userIS, PetscIS *userIterationSet, void *ctx) except PETSC_ERR_PYTHON with gil: cdef PC Pc = ref_PC(pc) cdef PetscInt i cdef object context = Pc.get_attr("__patch_construction_operator__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple (op, args, kargs) = context (patches, iterationSet) = op(Pc, *args, **kargs) n[0] = len(patches) CHKERR(PetscMalloc(n[0]*sizeof(PetscIS), userIS)) for i in range(n[0]): userIS[0][i] = (patches[i]).iset PetscINCREF(&(userIS[0][i])) userIterationSet[0] = (iterationSet).iset PetscINCREF(&(userIterationSet[0])) return PETSC_SUCCESS petsc4py-3.19.6/src/petsc4py/PETSc/petscpyappctx.pxi000066400000000000000000000006531454104047300223040ustar00rootroot00000000000000cdef set appctx_registry = set() cdef inline object registerAppCtx(void *appctx): cdef object key = appctx appctx_registry.add(key) cdef inline object toAppCtx(void *appctx): cdef object key = appctx if key in appctx_registry: return appctx else: if appctx != NULL: return PyLong_FromVoidPtr(appctx) else: return None petsc4py-3.19.6/src/petsc4py/PETSc/petscrand.pxi000066400000000000000000000021671454104047300213620ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscRandomType PetscRandomType PETSCRAND PetscRandomType PETSCRAND48 PetscRandomType PETSCSPRNG PetscRandomType PETSCRANDER48 PetscRandomType PETSCRANDOM123 PetscErrorCode PetscRandomCreate(MPI_Comm,PetscRandom*) PetscErrorCode PetscRandomDestroy(PetscRandom*) PetscErrorCode PetscRandomView(PetscRandom,PetscViewer) PetscErrorCode PetscRandomSetType(PetscRandom,PetscRandomType) PetscErrorCode PetscRandomGetType(PetscRandom,PetscRandomType*) PetscErrorCode PetscRandomSetFromOptions(PetscRandom) PetscErrorCode PetscRandomGetValue(PetscRandom,PetscScalar*) PetscErrorCode PetscRandomGetValueReal(PetscRandom,PetscReal*) PetscErrorCode PetscRandomGetValueImaginary(PetscRandom,PetscScalar*) PetscErrorCode PetscRandomGetInterval(PetscRandom,PetscScalar*,PetscScalar*) PetscErrorCode PetscRandomSetInterval(PetscRandom,PetscScalar,PetscScalar) PetscErrorCode PetscRandomSetSeed(PetscRandom,unsigned long) PetscErrorCode PetscRandomGetSeed(PetscRandom,unsigned long*) PetscErrorCode PetscRandomSeed(PetscRandom) petsc4py-3.19.6/src/petsc4py/PETSc/petscsct.pxi000066400000000000000000000020751454104047300212250ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef PetscSFType PetscScatterType "VecScatterType" PetscErrorCode VecScatterView(PetscScatter,PetscViewer) PetscErrorCode VecScatterDestroy(PetscScatter*) PetscErrorCode VecScatterSetUp(PetscScatter) PetscErrorCode VecScatterCreate(PetscVec,PetscIS,PetscVec,PetscIS,PetscScatter*) PetscErrorCode VecScatterSetFromOptions(PetscScatter) PetscErrorCode VecScatterSetType(PetscScatter,PetscScatterType) PetscErrorCode VecScatterGetType(PetscScatter,PetscScatterType*) PetscErrorCode VecScatterCopy(PetscScatter, PetscScatter*) PetscErrorCode VecScatterCreateToAll(PetscVec,PetscScatter*,PetscVec*) PetscErrorCode VecScatterCreateToZero(PetscVec,PetscScatter*,PetscVec*) PetscErrorCode VecScatterBegin(PetscScatter,PetscVec,PetscVec,PetscInsertMode,PetscScatterMode) PetscErrorCode VecScatterEnd(PetscScatter,PetscVec,PetscVec,PetscInsertMode,PetscScatterMode) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscsec.pxi000066400000000000000000000073211454104047300212050ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: PetscErrorCode PetscSectionCreate(MPI_Comm,PetscSection*) PetscErrorCode PetscSectionClone(PetscSection,PetscSection*) PetscErrorCode PetscSectionSetUp(PetscSection) PetscErrorCode PetscSectionSetUpBC(PetscSection) PetscErrorCode PetscSectionView(PetscSection,PetscViewer) PetscErrorCode PetscSectionReset(PetscSection) PetscErrorCode PetscSectionDestroy(PetscSection*) PetscErrorCode PetscSectionGetNumFields(PetscSection,PetscInt*) PetscErrorCode PetscSectionSetNumFields(PetscSection,PetscInt) PetscErrorCode PetscSectionGetFieldName(PetscSection,PetscInt,const char*[]) PetscErrorCode PetscSectionSetFieldName(PetscSection,PetscInt,const char[]) PetscErrorCode PetscSectionGetFieldComponents(PetscSection,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetFieldComponents(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionGetChart(PetscSection,PetscInt*,PetscInt*) PetscErrorCode PetscSectionSetChart(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionGetPermutation(PetscSection,PetscIS*) PetscErrorCode PetscSectionSetPermutation(PetscSection,PetscIS) PetscErrorCode PetscSectionGetDof(PetscSection,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetDof(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionAddDof(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionGetFieldDof(PetscSection,PetscInt,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetFieldDof(PetscSection,PetscInt,PetscInt,PetscInt) PetscErrorCode PetscSectionAddFieldDof(PetscSection,PetscInt,PetscInt,PetscInt) PetscErrorCode PetscSectionGetConstraintDof(PetscSection,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetConstraintDof(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionAddConstraintDof(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionGetFieldConstraintDof(PetscSection,PetscInt,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetFieldConstraintDof(PetscSection,PetscInt,PetscInt,PetscInt) PetscErrorCode PetscSectionAddFieldConstraintDof(PetscSection,PetscInt,PetscInt,PetscInt) PetscErrorCode PetscSectionGetConstraintIndices(PetscSection,PetscInt,const PetscInt**) PetscErrorCode PetscSectionSetConstraintIndices(PetscSection,PetscInt,const PetscInt*) PetscErrorCode PetscSectionGetFieldConstraintIndices(PetscSection,PetscInt,PetscInt,const PetscInt**) PetscErrorCode PetscSectionSetFieldConstraintIndices(PetscSection,PetscInt,PetscInt,const PetscInt*) PetscErrorCode PetscSectionGetMaxDof(PetscSection,PetscInt*) PetscErrorCode PetscSectionGetStorageSize(PetscSection,PetscInt*) PetscErrorCode PetscSectionGetConstrainedStorageSize(PetscSection,PetscInt*) PetscErrorCode PetscSectionGetOffset(PetscSection,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetOffset(PetscSection,PetscInt,PetscInt) PetscErrorCode PetscSectionGetFieldOffset(PetscSection,PetscInt,PetscInt,PetscInt*) PetscErrorCode PetscSectionSetFieldOffset(PetscSection,PetscInt,PetscInt,PetscInt) PetscErrorCode PetscSectionGetOffsetRange(PetscSection,PetscInt*,PetscInt*) PetscErrorCode PetscSectionCreateGlobalSection(PetscSection,PetscSF,PetscBool,PetscBool,PetscSection*) #int PetscSectionCreateGlobalSectionCensored(PetscSection,PetscSF,PetscBool,PetscInt,const PetscInt[],PetscSection*) PetscErrorCode PetscSectionCreateSubsection(PetscSection,PetscInt,PetscInt[],PetscSection*) PetscErrorCode PetscSectionCreateSubmeshSection(PetscSection,IS,PetscSection*) #int PetscSectionGetPointLayout(MPI_Comm,PetscSection,PetscLayout*) #int PetscSectionGetValueLayout(MPI_Comm,PetscSection,PetscLayout*) petsc4py-3.19.6/src/petsc4py/PETSc/petscsf.pxi000066400000000000000000000051371454104047300210460ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef const char* PetscSFType PetscSFType PETSCSFBASIC PetscSFType PETSCSFNEIGHBOR PetscSFType PETSCSFALLGATHERV PetscSFType PETSCSFALLGATHER PetscSFType PETSCSFGATHERV PetscSFType PETSCSFGATHER PetscSFType PETSCSFALLTOALL PetscSFType PETSCSFWINDOW PetscErrorCode PetscSFCreate(MPI_Comm,PetscSF*) PetscErrorCode PetscSFSetType(PetscSF,PetscSFType) PetscErrorCode PetscSFGetType(PetscSF,PetscSFType*) PetscErrorCode PetscSFSetFromOptions(PetscSF) PetscErrorCode PetscSFSetUp(PetscSF) PetscErrorCode PetscSFView(PetscSF,PetscViewer) PetscErrorCode PetscSFReset(PetscSF) PetscErrorCode PetscSFDestroy(PetscSF*) ctypedef struct PetscSFNode: PetscInt rank PetscInt index PetscErrorCode PetscSFGetGraph(PetscSF,PetscInt*,PetscInt*,const PetscInt**,const PetscSFNode**) PetscErrorCode PetscSFSetGraph(PetscSF,PetscInt,PetscInt,const PetscInt*,PetscCopyMode,PetscSFNode*,PetscCopyMode) PetscErrorCode PetscSFSetRankOrder(PetscSF,PetscBool) PetscErrorCode PetscSFComputeDegreeBegin(PetscSF,const PetscInt**) PetscErrorCode PetscSFComputeDegreeEnd(PetscSF,const PetscInt**) PetscErrorCode PetscSFGetMultiSF(PetscSF,PetscSF*) PetscErrorCode PetscSFCreateInverseSF(PetscSF,PetscSF*) PetscErrorCode PetscSFCreateEmbeddedRootSF(PetscSF,PetscInt,const PetscInt*,PetscSF*) PetscErrorCode PetscSFCreateEmbeddedLeafSF(PetscSF,PetscInt,const PetscInt*,PetscSF*) PetscErrorCode PetscSFDistributeSection(PetscSF,PetscSection,PetscInt**,PetscSection) PetscErrorCode PetscSFCreateSectionSF(PetscSF,PetscSection,PetscInt*,PetscSection, PetscSF*) PetscErrorCode PetscSFCompose(PetscSF,PetscSF,PetscSF*) PetscErrorCode PetscSFBcastBegin(PetscSF,MPI_Datatype,const void*,void*,MPI_Op) PetscErrorCode PetscSFBcastEnd(PetscSF,MPI_Datatype,const void*,void*,MPI_Op) PetscErrorCode PetscSFReduceBegin(PetscSF,MPI_Datatype,const void*,void*,MPI_Op) PetscErrorCode PetscSFReduceEnd(PetscSF,MPI_Datatype,const void*,void*,MPI_Op) PetscErrorCode PetscSFScatterBegin(PetscSF,MPI_Datatype,const void*,void*) PetscErrorCode PetscSFScatterEnd(PetscSF,MPI_Datatype,const void*,void*) PetscErrorCode PetscSFGatherBegin(PetscSF,MPI_Datatype,const void*,void*) PetscErrorCode PetscSFGatherEnd(PetscSF,MPI_Datatype,const void*,void*) PetscErrorCode PetscSFFetchAndOpBegin(PetscSF,MPI_Datatype,void*,const void*,void*,MPI_Op) PetscErrorCode PetscSFFetchAndOpEnd(PetscSF,MPI_Datatype,void*,const void*,void*,MPI_Op) petsc4py-3.19.6/src/petsc4py/PETSc/petscsnes.pxi000066400000000000000000000460031454104047300214030ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscSNESType "SNESType" PetscSNESType SNESNEWTONLS PetscSNESType SNESNEWTONTR PetscSNESType SNESPYTHON PetscSNESType SNESNRICHARDSON PetscSNESType SNESKSPONLY PetscSNESType SNESKSPTRANSPOSEONLY PetscSNESType SNESVINEWTONRSLS PetscSNESType SNESVINEWTONSSLS PetscSNESType SNESNGMRES PetscSNESType SNESQN PetscSNESType SNESSHELL PetscSNESType SNESNGS PetscSNESType SNESNCG PetscSNESType SNESFAS PetscSNESType SNESMS PetscSNESType SNESNASM PetscSNESType SNESANDERSON PetscSNESType SNESASPIN PetscSNESType SNESCOMPOSITE PetscSNESType SNESPATCH ctypedef enum PetscSNESNormSchedule "SNESNormSchedule": SNES_NORM_DEFAULT SNES_NORM_NONE SNES_NORM_ALWAYS SNES_NORM_INITIAL_ONLY SNES_NORM_FINAL_ONLY SNES_NORM_INITIAL_FINAL_ONLY ctypedef enum PetscSNESConvergedReason "SNESConvergedReason": # iterating SNES_CONVERGED_ITERATING # converged SNES_CONVERGED_FNORM_ABS SNES_CONVERGED_FNORM_RELATIVE SNES_CONVERGED_SNORM_RELATIVE SNES_CONVERGED_ITS # diverged SNES_DIVERGED_FUNCTION_DOMAIN SNES_DIVERGED_FUNCTION_COUNT SNES_DIVERGED_LINEAR_SOLVE SNES_DIVERGED_FNORM_NAN SNES_DIVERGED_MAX_IT SNES_DIVERGED_LINE_SEARCH SNES_DIVERGED_INNER SNES_DIVERGED_LOCAL_MIN SNES_DIVERGED_DTOL SNES_DIVERGED_JACOBIAN_DOMAIN SNES_DIVERGED_TR_DELTA ctypedef PetscErrorCode (*PetscSNESCtxDel)(void*) ctypedef PetscErrorCode (*PetscSNESInitialGuessFunction)(PetscSNES, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESFunctionFunction)(PetscSNES, PetscVec, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESUpdateFunction)(PetscSNES, PetscInt) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESJacobianFunction)(PetscSNES, PetscVec, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESObjectiveFunction)(PetscSNES, PetscVec, PetscReal*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESConvergedFunction)(PetscSNES, PetscInt, PetscReal, PetscReal, PetscReal, PetscSNESConvergedReason*, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscSNESMonitorFunction)(PetscSNES, PetscInt, PetscReal, void*) except PETSC_ERR_PYTHON PetscErrorCode SNESCreate(MPI_Comm,PetscSNES*) PetscErrorCode SNESDestroy(PetscSNES*) PetscErrorCode SNESView(PetscSNES,PetscViewer) PetscErrorCode SNESSetType(PetscSNES,PetscSNESType) PetscErrorCode SNESGetType(PetscSNES,PetscSNESType*) PetscErrorCode SNESSetOptionsPrefix(PetscSNES,char[]) PetscErrorCode SNESAppendOptionsPrefix(PetscSNES,char[]) PetscErrorCode SNESGetOptionsPrefix(PetscSNES,char*[]) PetscErrorCode SNESSetFromOptions(PetscSNES) PetscErrorCode SNESSetApplicationContext(PetscSNES,void*) PetscErrorCode SNESGetApplicationContext(PetscSNES,void*) PetscErrorCode SNESGetKSP(PetscSNES,PetscKSP*) PetscErrorCode SNESSetKSP(PetscSNES,PetscKSP) PetscErrorCode SNESGetDM(PetscSNES,PetscDM*) PetscErrorCode SNESSetDM(PetscSNES,PetscDM) PetscErrorCode SNESFASSetInterpolation(PetscSNES,PetscInt,PetscMat) PetscErrorCode SNESFASGetInterpolation(PetscSNES,PetscInt,PetscMat*) PetscErrorCode SNESFASSetRestriction(PetscSNES,PetscInt,PetscMat) PetscErrorCode SNESFASGetRestriction(PetscSNES,PetscInt,PetscMat*) PetscErrorCode SNESFASSetInjection(PetscSNES,PetscInt,PetscMat) PetscErrorCode SNESFASGetInjection(PetscSNES,PetscInt,PetscMat*) PetscErrorCode SNESFASSetRScale(PetscSNES,PetscInt,PetscVec) PetscErrorCode SNESFASSetLevels(PetscSNES,PetscInt,MPI_Comm[]) PetscErrorCode SNESFASGetLevels(PetscSNES,PetscInt*) PetscErrorCode SNESFASGetCycleSNES(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESFASGetCoarseSolve(PetscSNES,PetscSNES*) PetscErrorCode SNESFASGetSmoother(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESFASGetSmootherDown(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESFASGetSmootherUp(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESGetNPC(PetscSNES,PetscSNES*) PetscErrorCode SNESHasNPC(PetscSNES,PetscBool*) PetscErrorCode SNESSetNPC(PetscSNES,PetscSNES) PetscErrorCode SNESSetNPCSide(PetscSNES,PetscPCSide) PetscErrorCode SNESGetNPCSide(PetscSNES,PetscPCSide*) PetscErrorCode SNESGetRhs(PetscSNES,PetscVec*) PetscErrorCode SNESGetSolution(PetscSNES,PetscVec*) PetscErrorCode SNESSetSolution(PetscSNES,PetscVec) PetscErrorCode SNESGetSolutionUpdate(PetscSNES,PetscVec*) PetscErrorCode SNESSetInitialGuess"SNESSetComputeInitialGuess"(PetscSNES,PetscSNESInitialGuessFunction,void*) PetscErrorCode SNESSetFunction(PetscSNES,PetscVec,PetscSNESFunctionFunction,void*) PetscErrorCode SNESGetFunction(PetscSNES,PetscVec*,void*,void**) PetscErrorCode SNESSetUpdate(PetscSNES,PetscSNESUpdateFunction) PetscErrorCode SNESSetJacobian(PetscSNES,PetscMat,PetscMat,PetscSNESJacobianFunction,void*) PetscErrorCode SNESGetJacobian(PetscSNES,PetscMat*,PetscMat*,PetscSNESJacobianFunction*,void**) PetscErrorCode SNESSetObjective(PetscSNES,PetscSNESObjectiveFunction,void*) PetscErrorCode SNESGetObjective(PetscSNES,PetscSNESObjectiveFunction*,void**) PetscErrorCode SNESComputeFunction(PetscSNES,PetscVec,PetscVec) PetscErrorCode SNESComputeJacobian(PetscSNES,PetscVec,PetscMat,PetscMat) PetscErrorCode SNESComputeObjective(PetscSNES,PetscVec,PetscReal*) ctypedef PetscErrorCode (*PetscSNESNGSFunction)(PetscSNES, PetscVec, PetscVec, void*) except PETSC_ERR_PYTHON PetscErrorCode SNESSetNGS(PetscSNES,PetscSNESNGSFunction,void*) PetscErrorCode SNESGetNGS(PetscSNES,PetscSNESNGSFunction*,void**) PetscErrorCode SNESComputeNGS(PetscSNES,PetscVec,PetscVec) PetscErrorCode SNESSetNormSchedule(PetscSNES,PetscSNESNormSchedule) PetscErrorCode SNESGetNormSchedule(PetscSNES,PetscSNESNormSchedule*) PetscErrorCode SNESSetTolerances(PetscSNES,PetscReal,PetscReal,PetscReal,PetscInt,PetscInt) PetscErrorCode SNESGetTolerances(PetscSNES,PetscReal*,PetscReal*,PetscReal*,PetscInt*,PetscInt*) PetscErrorCode SNESSetConvergenceTest(PetscSNES,PetscSNESConvergedFunction,void*,PetscSNESCtxDel*) PetscErrorCode SNESConvergedDefault(PetscSNES,PetscInt,PetscReal,PetscReal,PetscReal, PetscSNESConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode SNESConvergedSkip(PetscSNES,PetscInt,PetscReal,PetscReal,PetscReal, PetscSNESConvergedReason*,void*) except PETSC_ERR_PYTHON PetscErrorCode SNESSetConvergenceHistory(PetscSNES,PetscReal[],PetscInt[],PetscInt,PetscBool) PetscErrorCode SNESGetConvergenceHistory(PetscSNES,PetscReal*[],PetscInt*[],PetscInt*) PetscErrorCode SNESLogConvergenceHistory(PetscSNES,PetscReal,PetscInt) PetscErrorCode SNESMonitorSet(PetscSNES,PetscSNESMonitorFunction,void*,PetscSNESCtxDel) PetscErrorCode SNESMonitorCancel(PetscSNES) PetscErrorCode SNESMonitor(PetscSNES,PetscInt,PetscReal) PetscErrorCode SNESSetUp(PetscSNES) PetscErrorCode SNESReset(PetscSNES) PetscErrorCode SNESSolve(PetscSNES,PetscVec,PetscVec) PetscErrorCode SNESSetConvergedReason(PetscSNES,PetscSNESConvergedReason) PetscErrorCode SNESGetConvergedReason(PetscSNES,PetscSNESConvergedReason*) PetscErrorCode SNESSetErrorIfNotConverged(PetscSNES,PetscBool); PetscErrorCode SNESGetErrorIfNotConverged(PetscSNES,PetscBool*); PetscErrorCode SNESSetIterationNumber(PetscSNES,PetscInt) PetscErrorCode SNESGetIterationNumber(PetscSNES,PetscInt*) PetscErrorCode SNESSetForceIteration(PetscSNES,PetscBool) PetscErrorCode SNESSetFunctionNorm(PetscSNES,PetscReal) PetscErrorCode SNESGetFunctionNorm(PetscSNES,PetscReal*) PetscErrorCode SNESGetLinearSolveIterations(PetscSNES,PetscInt*) PetscErrorCode SNESSetCountersReset(PetscSNES,PetscBool) PetscErrorCode SNESGetNumberFunctionEvals(PetscSNES,PetscInt*) PetscErrorCode SNESSetMaxNonlinearStepFailures(PetscSNES,PetscInt) PetscErrorCode SNESGetMaxNonlinearStepFailures(PetscSNES,PetscInt*) PetscErrorCode SNESGetNonlinearStepFailures(PetscSNES,PetscInt*) PetscErrorCode SNESSetMaxLinearSolveFailures(PetscSNES,PetscInt) PetscErrorCode SNESGetMaxLinearSolveFailures(PetscSNES,PetscInt*) PetscErrorCode SNESGetLinearSolveFailures(PetscSNES,PetscInt*) PetscErrorCode SNESKSPSetUseEW(PetscSNES,PetscBool) PetscErrorCode SNESKSPGetUseEW(PetscSNES,PetscBool*) PetscErrorCode SNESKSPSetParametersEW(PetscSNES,PetscInt,PetscReal,PetscReal, PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode SNESKSPGetParametersEW(PetscSNES,PetscInt*,PetscReal*,PetscReal*, PetscReal*,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode SNESVISetVariableBounds(PetscSNES,PetscVec,PetscVec) #ctypedef PetscErrorCode (*PetscSNESVariableBoundsFunction)(PetscSNES,PetscVec,PetscVec) #int SNESVISetComputeVariableBounds(PetscSNES,PetscSNESVariableBoundsFunction) PetscErrorCode SNESVIGetInactiveSet(PetscSNES, PetscIS*) PetscErrorCode SNESCompositeGetSNES(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESCompositeGetNumber(PetscSNES,PetscInt*) PetscErrorCode SNESNASMGetSNES(PetscSNES,PetscInt,PetscSNES*) PetscErrorCode SNESNASMGetNumber(PetscSNES,PetscInt*) PetscErrorCode SNESPatchSetCellNumbering(PetscSNES, PetscSection) PetscErrorCode SNESPatchSetDiscretisationInfo(PetscSNES, PetscInt, PetscDM*, PetscInt*, PetscInt*, const PetscInt**, const PetscInt*, PetscInt, const PetscInt*, PetscInt, const PetscInt*) PetscErrorCode SNESPatchSetComputeOperator(PetscSNES, PetscPCPatchComputeOperator, void*) PetscErrorCode SNESPatchSetComputeFunction(PetscSNES, PetscPCPatchComputeFunction, void*) PetscErrorCode SNESPatchSetConstructType(PetscSNES, PetscPCPatchConstructType, PetscPCPatchConstructOperator, void*) PetscErrorCode SNESPythonSetType(PetscSNES,char[]) PetscErrorCode SNESPythonGetType(PetscSNES,char*[]) cdef extern from * nogil: # custom.h PetscErrorCode SNESSetUseMFFD(PetscSNES,PetscBool) PetscErrorCode SNESGetUseMFFD(PetscSNES,PetscBool*) PetscErrorCode SNESSetUseFDColoring(PetscSNES,PetscBool) PetscErrorCode SNESGetUseFDColoring(PetscSNES,PetscBool*) PetscErrorCode SNESConvergenceTestCall(PetscSNES,PetscInt, PetscReal,PetscReal,PetscReal, PetscSNESConvergedReason*) ctypedef const char* PetscSNESLineSearchType "SNESLineSearchType" PetscSNESLineSearchType SNESLINESEARCHBT PetscSNESLineSearchType SNESLINESEARCHNLEQERR PetscSNESLineSearchType SNESLINESEARCHBASIC PetscSNESLineSearchType SNESLINESEARCHNONE PetscSNESLineSearchType SNESLINESEARCHL2 PetscSNESLineSearchType SNESLINESEARCHCP PetscSNESLineSearchType SNESLINESEARCHSHELL PetscSNESLineSearchType SNESLINESEARCHNCGLINEAR PetscErrorCode SNESGetLineSearch(PetscSNES,PetscSNESLineSearch*) PetscErrorCode SNESLineSearchSetFromOptions(PetscSNESLineSearch) PetscErrorCode SNESLineSearchApply(PetscSNESLineSearch,PetscVec,PetscVec,PetscReal*,PetscVec) PetscErrorCode SNESLineSearchGetNorms(PetscSNESLineSearch,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode SNESLineSearchDestroy(PetscSNESLineSearch*) ctypedef PetscErrorCode (*PetscSNESPreCheckFunction)(PetscSNESLineSearch, PetscVec,PetscVec, PetscBool*, void*) except PETSC_ERR_PYTHON PetscErrorCode SNESLineSearchSetPreCheck(PetscSNESLineSearch,PetscSNESPreCheckFunction,void*) PetscErrorCode SNESLineSearchGetSNES(PetscSNESLineSearch,PetscSNES*) # ----------------------------------------------------------------------------- cdef inline SNES ref_SNES(PetscSNES snes): cdef SNES ob = SNES() ob.snes = snes PetscINCREF(ob.obj) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_InitialGuess( PetscSNES snes, PetscVec x, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef object context = Snes.get_attr('__initialguess__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (initialguess, args, kargs) = context initialguess(Snes, Xvec, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_PreCheck( PetscSNESLineSearch linesearch, PetscVec x, PetscVec y, PetscBool *changed, void* ctx ) except PETSC_ERR_PYTHON with gil: cdef PetscSNES snes = NULL; CHKERR( SNESLineSearchGetSNES(linesearch, &snes) ); cdef object b = False cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef Vec Yvec = ref_Vec(y) cdef object context = Snes.get_attr('__precheck__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (precheck, args, kargs) = context b = precheck(Xvec, Yvec, *args, **kargs) changed[0] = asBool(b) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Function( PetscSNES snes, PetscVec x, PetscVec f, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef Vec Fvec = ref_Vec(f) cdef object context = Snes.get_attr('__function__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (function, args, kargs) = context function(Snes, Xvec, Fvec, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Update( PetscSNES snes, PetscInt its, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef object context = Snes.get_attr('__update__') assert context is not None and type(context) is tuple # sanity check (update, args, kargs) = context update(Snes, toInt(its), *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Jacobian( PetscSNES snes, PetscVec x, PetscMat J, PetscMat P, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef Mat Jmat = ref_Mat(J) cdef Mat Pmat = ref_Mat(P) cdef object context = Snes.get_attr('__jacobian__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(Snes, Xvec, Jmat, Pmat, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Objective( PetscSNES snes, PetscVec x, PetscReal *o, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef object context = Snes.get_attr('__objective__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (objective, args, kargs) = context obj = objective(Snes, Xvec, *args, **kargs) o[0] = asReal(obj) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_NGS( PetscSNES snes, PetscVec x, PetscVec b, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef Vec Xvec = ref_Vec(x) cdef Vec Bvec = ref_Vec(b) cdef object context = Snes.get_attr('__ngs__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (ngs, args, kargs) = context ngs(Snes, Xvec, Bvec, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Converged( PetscSNES snes, PetscInt iters, PetscReal xnorm, PetscReal gnorm, PetscReal fnorm, PetscSNESConvergedReason *r, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef object it = toInt(iters) cdef object xn = toReal(xnorm) cdef object gn = toReal(gnorm) cdef object fn = toReal(fnorm) cdef object context = Snes.get_attr('__converged__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (converged, args, kargs) = context reason = converged(Snes, it, (xn, gn, fn), *args, **kargs) if reason is None: r[0] = SNES_CONVERGED_ITERATING elif reason is False: r[0] = SNES_CONVERGED_ITERATING elif reason is True: r[0] = SNES_CONVERGED_ITS # XXX ? else: r[0] = reason return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode SNES_Monitor( PetscSNES snes, PetscInt iters, PetscReal rnorm, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef SNES Snes = ref_SNES(snes) cdef object monitorlist = Snes.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS cdef object it = toInt(iters) cdef object rn = toReal(rnorm) for (monitor, args, kargs) in monitorlist: monitor(Snes, it, rn, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscspace.pxi000066400000000000000000000123711454104047300215270ustar00rootroot00000000000000 cdef extern from * nogil: ctypedef const char* PetscSpaceType PetscSpaceType PETSCSPACEPOLYNOMIAL PetscSpaceType PETSCSPACEPTRIMMED PetscSpaceType PETSCSPACETENSOR PetscSpaceType PETSCSPACESUM PetscSpaceType PETSCSPACEPOINT PetscSpaceType PETSCSPACESUBSPACE PetscSpaceType PETSCSPACEWXY PetscErrorCode PetscSpaceCreate(MPI_Comm, PetscSpace*) PetscErrorCode PetscSpaceSetUp(PetscSpace) PetscErrorCode PetscSpaceSetFromOptions(PetscSpace) PetscErrorCode PetscSpaceDestroy(PetscSpace*) PetscErrorCode PetscSpaceView(PetscSpace, PetscViewer) PetscErrorCode PetscSpaceSetType(PetscSpace, PetscSpaceType) PetscErrorCode PetscSpaceGetType(PetscSpace, PetscSpaceType*) #int PetscSpaceEvaluate(PetscSpace, PetscInt, const PetscReal [], PetscReal [], PetscReal []) PetscErrorCode PetscSpaceGetDimension(PetscSpace, PetscInt*) PetscErrorCode PetscSpaceGetDegree(PetscSpace, PetscInt*, PetscInt*) PetscErrorCode PetscSpaceGetNumVariables(PetscSpace, PetscInt*) PetscErrorCode PetscSpaceGetNumComponents(PetscSpace, PetscInt*) PetscErrorCode PetscSpaceSetDegree(PetscSpace, PetscInt, PetscInt) PetscErrorCode PetscSpaceSetNumComponents(PetscSpace, PetscInt) PetscErrorCode PetscSpaceSetNumVariables(PetscSpace, PetscInt) PetscErrorCode PetscSpaceSumGetConcatenate(PetscSpace, PetscBool*) PetscErrorCode PetscSpaceSumSetConcatenate(PetscSpace, PetscBool) PetscErrorCode PetscSpaceSumGetNumSubspaces(PetscSpace, PetscInt*) PetscErrorCode PetscSpaceSumGetSubspace(PetscSpace, PetscInt, PetscSpace*) PetscErrorCode PetscSpaceSumSetNumSubspaces(PetscSpace, PetscInt) PetscErrorCode PetscSpaceSumSetSubspace(PetscSpace,PetscInt, PetscSpace) PetscErrorCode PetscSpaceTensorGetNumSubspaces(PetscSpace, PetscInt*) PetscErrorCode PetscSpaceTensorGetSubspace(PetscSpace, PetscInt, PetscSpace*) PetscErrorCode PetscSpaceTensorSetNumSubspaces(PetscSpace, PetscInt) PetscErrorCode PetscSpaceTensorSetSubspace(PetscSpace, PetscInt, PetscSpace) PetscErrorCode PetscSpaceViewFromOptions(PetscSpace, PetscObject, char []) PetscErrorCode PetscSpacePolynomialSetTensor(PetscSpace, PetscBool) PetscErrorCode PetscSpacePolynomialGetTensor(PetscSpace, PetscBool*) PetscErrorCode PetscSpacePointSetPoints(PetscSpace, PetscQuadrature) PetscErrorCode PetscSpacePointGetPoints(PetscSpace, PetscQuadrature*) PetscErrorCode PetscSpacePTrimmedSetFormDegree(PetscSpace, PetscInt) PetscErrorCode PetscSpacePTrimmedGetFormDegree(PetscSpace, PetscInt*) # -------------------------------------------------------------------- cdef extern from * nogil: ctypedef const char* PetscDualSpaceType PetscDualSpaceType PETSCDUALSPACELAGRANGE PetscDualSpaceType PETSCDUALSPACESIMPLE PetscDualSpaceType PETSCDUALSPACEREFINED PetscDualSpaceType PETSCDUALSPACEBDM PetscErrorCode PetscDualSpaceCreate(MPI_Comm, PetscDualSpace*) PetscErrorCode PetscDualSpaceDestroy(PetscDualSpace*) PetscErrorCode PetscDualSpaceDuplicate(PetscDualSpace, PetscDualSpace*) PetscErrorCode PetscDualSpaceView(PetscDualSpace, PetscViewer) PetscErrorCode PetscDualSpaceGetDM(PetscDualSpace, PetscDM*) PetscErrorCode PetscDualSpaceSetDM(PetscDualSpace, PetscDM) PetscErrorCode PetscDualSpaceGetDimension(PetscDualSpace, PetscInt*) PetscErrorCode PetscDualSpaceGetNumComponents(PetscDualSpace, PetscInt*) PetscErrorCode PetscDualSpaceSetNumComponents(PetscDualSpace, PetscInt) PetscErrorCode PetscDualSpaceGetOrder(PetscDualSpace, PetscInt*) PetscErrorCode PetscDualSpaceSetOrder(PetscDualSpace, PetscInt) PetscErrorCode PetscDualSpaceGetNumDof(PetscDualSpace, const PetscInt**) PetscErrorCode PetscDualSpaceSetUp(PetscDualSpace) PetscErrorCode PetscDualSpaceViewFromOptions(PetscDualSpace,PetscObject, char[]) PetscErrorCode PetscDualSpaceGetFunctional(PetscDualSpace, PetscInt, PetscQuadrature*) PetscErrorCode PetscDualSpaceGetInteriorDimension(PetscDualSpace, PetscInt*) PetscErrorCode PetscDualSpaceLagrangeGetContinuity(PetscDualSpace, PetscBool*) PetscErrorCode PetscDualSpaceLagrangeGetTensor(PetscDualSpace, PetscBool*) PetscErrorCode PetscDualSpaceLagrangeGetTrimmed(PetscDualSpace, PetscBool*) PetscErrorCode PetscDualSpaceLagrangeSetContinuity(PetscDualSpace, PetscBool) PetscErrorCode PetscDualSpaceLagrangeSetTensor(PetscDualSpace, PetscBool) PetscErrorCode PetscDualSpaceLagrangeSetTrimmed(PetscDualSpace, PetscBool) PetscErrorCode PetscDualSpaceSimpleSetDimension(PetscDualSpace, PetscInt) PetscErrorCode PetscDualSpaceSimpleSetFunctional(PetscDualSpace, PetscInt, PetscQuadrature) PetscErrorCode PetscDualSpaceGetType(PetscDualSpace, PetscDualSpaceType*) PetscErrorCode PetscDualSpaceSetType(PetscDualSpace, PetscDualSpaceType) #int PetscDualSpaceSetFromOptions(PetscDualSpace) #int PetscDualSpaceRefinedSetCellSpaces(PetscDualSpace, const PetscDualSpace []) # Advanced #int PetscDualSpaceCreateAllDataDefault(PetscDualSpace, PetscQuadrature*, PetscMat*) #int PetscDualSpaceCreateInteriorDataDefault(PetscDualSpace, PetscQuadrature*, PetscMat*) #int PetscDualSpaceEqual(PetscDualSpace, PetscDualSpace, PetscBool*) #int PetscDualSpaceGetAllData(PetscDualSpace, PetscQuadrature*, PetscMat*)petsc4py-3.19.6/src/petsc4py/PETSc/petscsys.pxi000066400000000000000000000073261454104047300212560ustar00rootroot00000000000000cdef extern from * nogil: ctypedef enum PetscDataType: PETSC_INT PETSC_REAL PETSC_SCALAR PETSC_COMPLEX PETSC_DATATYPE_UNKNOWN const char PETSC_AUTHOR_INFO[] PetscErrorCode PetscGetVersion(char[],size_t) PetscErrorCode PetscGetVersionNumber(PetscInt*,PetscInt*,PetscInt*,PetscInt*) PetscErrorCode PetscInitialize(int*,char***,char[],char[]) PetscErrorCode PetscInitializeNoArguments() PetscErrorCode PetscFinalize() PetscBool PetscInitializeCalled PetscBool PetscFinalizeCalled ctypedef PetscErrorCode (*PetscErrorHandlerFunction)( MPI_Comm,int,char*,char*,int,PetscErrorType,char*,void*) PetscErrorHandlerFunction PetscAttachDebuggerErrorHandler PetscErrorHandlerFunction PetscEmacsClientErrorHandler PetscErrorHandlerFunction PetscTraceBackErrorHandler PetscErrorHandlerFunction PetscMPIAbortErrorHandler PetscErrorHandlerFunction PetscAbortErrorHandler PetscErrorHandlerFunction PetscIgnoreErrorHandler PetscErrorCode PetscPushErrorHandler(PetscErrorHandlerFunction,void*) PetscErrorCode PetscPopErrorHandler() PetscErrorCode PetscPopSignalHandler() PetscErrorCode PetscInfoAllow(PetscBool) PetscErrorCode PetscInfoSetFile(char*,char*) PetscErrorCode PetscErrorMessage(int,char*[],char**) PetscErrorCode PetscSplitOwnership(MPI_Comm,PetscInt*,PetscInt*) PetscErrorCode PetscSplitOwnershipBlock(MPI_Comm,PetscInt,PetscInt*,PetscInt*) FILE *PETSC_STDOUT FILE *PETSC_STDERR PetscErrorCode PetscPrintf(MPI_Comm,char[],...) PetscErrorCode PetscVSNPrintf(char*,size_t,const char[],size_t *,va_list) PetscErrorCode PetscVFPrintfDefault(FILE*,const char[],va_list) PetscErrorCode PetscSynchronizedPrintf(MPI_Comm,char[],...) PetscErrorCode PetscSynchronizedFlush(MPI_Comm,FILE*) PetscErrorCode PetscSequentialPhaseBegin(MPI_Comm,int) PetscErrorCode PetscSequentialPhaseEnd(MPI_Comm,int) PetscErrorCode PetscSleep(int) PetscErrorCode PetscCitationsRegister(const char[],PetscBool*) PetscErrorCode PetscHasExternalPackage(const char[],PetscBool*) cdef inline PetscErrorCode Sys_Sizes( object size, object bsize, PetscInt *_b, PetscInt *_n, PetscInt *_N, ) except PETSC_ERR_PYTHON: # get block size cdef PetscInt bs=PETSC_DECIDE, b=PETSC_DECIDE if bsize is not None: bs = b = asInt(bsize) if bs == PETSC_DECIDE: bs = 1 # 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) # check block, local, and and global sizes if (bs < 1): raise ValueError( "block size %d must be positive" % toInt(bs)) if n==PETSC_DECIDE and N==PETSC_DECIDE: raise ValueError( "local and global sizes cannot be both 'DECIDE'") if (n > 0) and (n % bs): raise ValueError( "local size %d not divisible by block size %d" % (toInt(n), toInt(bs)) ) if (N > 0) and (N % bs): raise ValueError( "global size %d not divisible by block size %d" % (toInt(N), toInt(bs)) ) # return result to the caller if _b != NULL: _b[0] = b if _n != NULL: _n[0] = n if _N != NULL: _N[0] = N return PETSC_SUCCESS cdef inline PetscErrorCode Sys_Layout( MPI_Comm comm, PetscInt bs, PetscInt *_n, PetscInt *_N, ) except PETSC_ERR_PYTHON: cdef PetscInt n = _n[0] cdef PetscInt N = _N[0] if bs < 0: bs = 1 if n > 0: n = n // bs if N > 0: N = N // bs CHKERR( PetscSplitOwnership(comm, &n, &N) ) _n[0] = n * bs _N[0] = N * bs return PETSC_SUCCESS petsc4py-3.19.6/src/petsc4py/PETSc/petsctao.pxi000066400000000000000000000503771454104047300212270ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscTAOType "TaoType" PetscTAOType TAOLMVM PetscTAOType TAONLS PetscTAOType TAONTR PetscTAOType TAONTL PetscTAOType TAOCG PetscTAOType TAOTRON PetscTAOType TAOOWLQN PetscTAOType TAOBMRM PetscTAOType TAOBLMVM PetscTAOType TAOBQNLS PetscTAOType TAOBNCG PetscTAOType TAOBNLS PetscTAOType TAOBNTR PetscTAOType TAOBNTL PetscTAOType TAOBQNKLS PetscTAOType TAOBQNKTR PetscTAOType TAOBQNKTL PetscTAOType TAOBQPIP PetscTAOType TAOGPCG PetscTAOType TAONM PetscTAOType TAOPOUNDERS PetscTAOType TAOBRGN PetscTAOType TAOLCL PetscTAOType TAOSSILS PetscTAOType TAOSSFLS PetscTAOType TAOASILS PetscTAOType TAOASFLS PetscTAOType TAOIPM PetscTAOType TAOPDIPM PetscTAOType TAOSHELL PetscTAOType TAOADMM PetscTAOType TAOALMM PetscTAOType TAOPYTHON ctypedef enum PetscTAOConvergedReason "TaoConvergedReason": #iterating TAO_CONTINUE_ITERATING # converged TAO_CONVERGED_GATOL TAO_CONVERGED_GRTOL TAO_CONVERGED_GTTOL TAO_CONVERGED_STEPTOL TAO_CONVERGED_MINF TAO_CONVERGED_USER # diverged TAO_DIVERGED_MAXITS TAO_DIVERGED_NAN TAO_DIVERGED_MAXFCN TAO_DIVERGED_LS_FAILURE TAO_DIVERGED_TR_REDUCTION TAO_DIVERGED_USER ctypedef enum PetscTAOLineSearchConvergedReason "TaoLineSearchConvergedReason": TAOLINESEARCH_CONTINUE_ITERATING TAOLINESEARCH_SUCCESS ctypedef PetscErrorCode (*PetscTaoMonitorDestroy)(void**) ctypedef PetscErrorCode PetscTaoConvergenceTest(PetscTAO,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoMonitor(PetscTAO,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoObjective(PetscTAO,PetscVec,PetscReal*,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoResidual(PetscTAO,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoGradient(PetscTAO,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoObjGrad(PetscTAO,PetscVec,PetscReal*,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoRegularizerObjGrad(PetscTAO,PetscVec,PetscReal*,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoVarBounds(PetscTAO,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoConstraints(PetscTAO,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoEqualityConstraints(PetscTAO,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoHessian(PetscTAO,PetscVec,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoRegularizerHessian(PetscTAO,PetscVec,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoJacobian(PetscTAO,PetscVec,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoJacobianResidual(PetscTAO,PetscVec,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoJacobianState(PetscTAO,PetscVec,PetscMat,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoJacobianDesign(PetscTAO,PetscVec,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoJacobianEquality(PetscTAO,PetscVec,PetscMat,PetscMat,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode PetscTaoUpdateFunction(PetscTAO,PetscInt,void*) except PETSC_ERR_PYTHON PetscErrorCode TaoMonitor(PetscTAO,PetscInt,PetscReal,PetscReal,PetscReal,PetscReal) PetscErrorCode TaoView(PetscTAO,PetscViewer) PetscErrorCode TaoDestroy(PetscTAO*) PetscErrorCode TaoCreate(MPI_Comm,PetscTAO*) PetscErrorCode TaoSetOptionsPrefix(PetscTAO,char[]) PetscErrorCode TaoAppendOptionsPrefix(PetscTAO,char[]) PetscErrorCode TaoGetOptionsPrefix(PetscTAO,char*[]) PetscErrorCode TaoSetFromOptions(PetscTAO) PetscErrorCode TaoSetType(PetscTAO,PetscTAOType) PetscErrorCode TaoGetType(PetscTAO,PetscTAOType*) PetscErrorCode TaoSetUp(PetscTAO) PetscErrorCode TaoSolve(PetscTAO) PetscErrorCode TaoSetTolerances(PetscTAO,PetscReal,PetscReal,PetscReal) PetscErrorCode TaoGetTolerances(PetscTAO,PetscReal*,PetscReal*,PetscReal*) PetscErrorCode TaoSetConstraintTolerances(PetscTAO,PetscReal,PetscReal) PetscErrorCode TaoGetConstraintTolerances(PetscTAO,PetscReal*,PetscReal*) PetscErrorCode TaoSetFunctionLowerBound(PetscTAO,PetscReal) PetscErrorCode TaoSetMaximumIterations(PetscTAO,PetscInt) PetscErrorCode TaoGetMaximumIterations(PetscTAO,PetscInt*) PetscErrorCode TaoSetMaximumFunctionEvaluations(PetscTAO,PetscInt) PetscErrorCode TaoGetMaximumFunctionEvaluations(PetscTAO,PetscInt*) PetscErrorCode TaoSetIterationNumber(PetscTAO,PetscInt) PetscErrorCode TaoGetIterationNumber(PetscTAO,PetscInt*) PetscErrorCode TaoSetTrustRegionTolerance(PetscTAO,PetscReal) PetscErrorCode TaoGetInitialTrustRegionRadius(PetscTAO,PetscReal*) PetscErrorCode TaoGetTrustRegionRadius(PetscTAO,PetscReal*) PetscErrorCode TaoSetTrustRegionRadius(PetscTAO,PetscReal) PetscErrorCode TaoDefaultConvergenceTest(PetscTAO,void*) except PETSC_ERR_PYTHON PetscErrorCode TaoSetConvergenceTest(PetscTAO,PetscTaoConvergenceTest*, void*) PetscErrorCode TaoSetConvergedReason(PetscTAO,PetscTAOConvergedReason) PetscErrorCode TaoGetConvergedReason(PetscTAO,PetscTAOConvergedReason*) PetscErrorCode TaoLogConvergenceHistory(PetscTAO,PetscReal,PetscReal,PetscReal,PetscInt) PetscErrorCode TaoGetSolutionStatus(PetscTAO,PetscInt*, PetscReal*,PetscReal*, PetscReal*,PetscReal*, PetscTAOConvergedReason*) PetscErrorCode TaoSetMonitor(PetscTAO,PetscTaoMonitor,void*,PetscTaoMonitorDestroy) PetscErrorCode TaoCancelMonitors(PetscTAO) PetscErrorCode TaoComputeObjective(PetscTAO,PetscVec,PetscReal*) PetscErrorCode TaoComputeResidual(PetscTAO,PetscVec,PetscVec) PetscErrorCode TaoComputeGradient(PetscTAO,PetscVec,PetscVec) PetscErrorCode TaoComputeObjectiveAndGradient(PetscTAO,PetscVec,PetscReal*,PetscVec) PetscErrorCode TaoComputeConstraints(PetscTAO,PetscVec,PetscVec) PetscErrorCode TaoComputeDualVariables(PetscTAO,PetscVec,PetscVec) PetscErrorCode TaoComputeVariableBounds(PetscTAO) PetscErrorCode TaoComputeHessian(PetscTAO,PetscVec,PetscMat,PetscMat) PetscErrorCode TaoComputeJacobian(PetscTAO,PetscVec,PetscMat,PetscMat) PetscErrorCode TaoSetSolution(PetscTAO,PetscVec) PetscErrorCode TaoSetConstraintsVec(PetscTAO,PetscVec) PetscErrorCode TaoSetVariableBounds(PetscTAO,PetscVec,PetscVec) PetscErrorCode TaoGetSolution(PetscTAO,PetscVec*) PetscErrorCode TaoSetGradientNorm(PetscTAO,PetscMat) PetscErrorCode TaoGetGradientNorm(PetscTAO,PetscMat*) PetscErrorCode TaoLMVMSetH0(PetscTAO,PetscMat) PetscErrorCode TaoLMVMGetH0(PetscTAO,PetscMat*) PetscErrorCode TaoLMVMGetH0KSP(PetscTAO,PetscKSP*) PetscErrorCode TaoGetVariableBounds(PetscTAO,PetscVec*,PetscVec*) PetscErrorCode TaoSetObjective(PetscTAO,PetscTaoObjective*,void*) PetscErrorCode TaoSetGradient(PetscTAO,PetscVec,PetscTaoGradient*,void*) PetscErrorCode TaoSetObjectiveAndGradient(PetscTAO,PetscVec,PetscTaoObjGrad*,void*) PetscErrorCode TaoSetHessian(PetscTAO,PetscMat,PetscMat,PetscTaoHessian*,void*) PetscErrorCode TaoGetObjective(PetscTAO,PetscTaoObjective**,void**) PetscErrorCode TaoGetGradient(PetscTAO,PetscVec*,PetscTaoGradient**,void**) PetscErrorCode TaoGetObjectiveAndGradient(PetscTAO,PetscVec*,PetscTaoObjGrad**,void**) PetscErrorCode TaoGetHessian(PetscTAO,PetscMat*,PetscMat*,PetscTaoHessian**,void**) PetscErrorCode TaoSetResidualRoutine(PetscTAO,PetscVec,PetscTaoResidual,void*) PetscErrorCode TaoSetVariableBoundsRoutine(PetscTAO,PetscTaoVarBounds*,void*) PetscErrorCode TaoSetConstraintsRoutine(PetscTAO,PetscVec,PetscTaoConstraints*,void*) PetscErrorCode TaoSetJacobianRoutine(PetscTAO,PetscMat,PetscMat,PetscTaoJacobian*,void*) PetscErrorCode TaoSetJacobianResidualRoutine(PetscTAO,PetscMat,PetscMat,PetscTaoJacobianResidual*,void*) PetscErrorCode TaoSetStateDesignIS(PetscTAO,PetscIS,PetscIS) PetscErrorCode TaoSetJacobianStateRoutine(PetscTAO,PetscMat,PetscMat,PetscMat,PetscTaoJacobianState*,void*) PetscErrorCode TaoSetJacobianDesignRoutine(PetscTAO,PetscMat,PetscTaoJacobianDesign*,void*) PetscErrorCode TaoSetEqualityConstraintsRoutine(PetscTAO,PetscVec,PetscTaoEqualityConstraints*,void*) PetscErrorCode TaoSetJacobianEqualityRoutine(PetscTAO,PetscMat,PetscMat,PetscTaoJacobianEquality*,void*) PetscErrorCode TaoSetUpdate(PetscTAO,PetscTaoUpdateFunction*,void*) PetscErrorCode TaoSetInitialTrustRegionRadius(PetscTAO,PetscReal) PetscErrorCode TaoGetKSP(PetscTAO,PetscKSP*) PetscErrorCode TaoBRGNGetSubsolver(PetscTAO,PetscTAO*) PetscErrorCode TaoBRGNSetRegularizerObjectiveAndGradientRoutine(PetscTAO,PetscTaoRegularizerObjGrad*,void*) PetscErrorCode TaoBRGNSetRegularizerHessianRoutine(PetscTAO,PetscMat,PetscTaoRegularizerHessian*,void*) PetscErrorCode TaoBRGNSetRegularizerWeight(PetscTAO,PetscReal) PetscErrorCode TaoBRGNSetL1SmoothEpsilon(PetscTAO,PetscReal) PetscErrorCode TaoBRGNSetDictionaryMatrix(PetscTAO,PetscMat) PetscErrorCode TaoBRGNGetDampingVector(PetscTAO,PetscVec*) PetscErrorCode TaoPythonSetType(PetscTAO,char[]) PetscErrorCode TaoPythonGetType(PetscTAO,char*[]) # -------------------------------------------------------------------- cdef inline TAO ref_TAO(PetscTAO tao): cdef TAO ob = TAO() ob.tao = tao PetscINCREF(ob.obj) return ob # -------------------------------------------------------------------- cdef PetscErrorCode TAO_Objective(PetscTAO _tao, PetscVec _x, PetscReal *_f, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) context = tao.get_attr("__objective__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (objective, args, kargs) = context retv = objective(tao, x, *args, **kargs) _f[0] = asReal(retv) return PETSC_SUCCESS cdef PetscErrorCode TAO_Residual(PetscTAO _tao, PetscVec _x, PetscVec _r, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec r = ref_Vec(_r) context = tao.get_attr("__residual__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (residual, args, kargs) = context residual(tao, x, r, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_Gradient(PetscTAO _tao, PetscVec _x, PetscVec _g, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec g = ref_Vec(_g) context = tao.get_attr("__gradient__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (gradient, args, kargs) = context gradient(tao, x, g, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_ObjGrad(PetscTAO _tao, PetscVec _x, PetscReal *_f, PetscVec _g, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec g = ref_Vec(_g) context = tao.get_attr("__objgrad__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (objgrad, args, kargs) = context retv = objgrad(tao, x, g, *args, **kargs) _f[0] = asReal(retv) return PETSC_SUCCESS cdef PetscErrorCode TAO_BRGNRegObjGrad(PetscTAO _tao, PetscVec _x, PetscReal *_f, PetscVec _g, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec g = ref_Vec(_g) context = tao.get_attr("__brgnregobjgrad__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (objgrad, args, kargs) = context retv = objgrad(tao, x, g, *args, **kargs) _f[0] = asReal(retv) return PETSC_SUCCESS cdef PetscErrorCode TAO_Constraints(PetscTAO _tao, PetscVec _x, PetscVec _r, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec r = ref_Vec(_r) context = tao.get_attr("__constraints__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (constraints, args, kargs) = context constraints(tao, x, r, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_VarBounds(PetscTAO _tao, PetscVec _xl, PetscVec _xu, void *ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec xl = ref_Vec(_xl) cdef Vec xu = ref_Vec(_xu) context = tao.get_attr("__varbounds__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (varbounds, args, kargs) = context varbounds(tao, xl, xu, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_Hessian(PetscTAO _tao, PetscVec _x, PetscMat _H, PetscMat _P, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat H = ref_Mat(_H) cdef Mat P = ref_Mat(_P) context = tao.get_attr("__hessian__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (hessian, args, kargs) = context hessian(tao, x, H, P, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_BRGNRegHessian(PetscTAO _tao, PetscVec _x, PetscMat _H, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat H = ref_Mat(_H) context = tao.get_attr("__brgnreghessian__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (hessian, args, kargs) = context hessian(tao, x, H, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_Jacobian(PetscTAO _tao, PetscVec _x, PetscMat _J, PetscMat _P, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat J = ref_Mat(_J) cdef Mat P = ref_Mat(_P) context = tao.get_attr("__jacobian__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(tao, x, J, P, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_JacobianResidual(PetscTAO _tao, PetscVec _x, PetscMat _J, PetscMat _P, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat J = ref_Mat(_J) cdef Mat P = ref_Mat(_P) context = tao.get_attr("__jacobian_residual__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(tao, x, J, P, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_JacobianState(PetscTAO _tao, PetscVec _x, PetscMat _J, PetscMat _P, PetscMat _I, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat J = ref_Mat(_J) cdef Mat P = ref_Mat(_P) cdef Mat I = ref_Mat(_I) context = tao.get_attr("__jacobian_state__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(tao, x, J, P, I, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_JacobianDesign(PetscTAO _tao, PetscVec _x, PetscMat _J, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat J = ref_Mat(_J) context = tao.get_attr("__jacobian_design__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(tao, x, J, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_EqualityConstraints(PetscTAO _tao, PetscVec _x, PetscVec _c, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Vec c = ref_Vec(_c) context = tao.get_attr("__equality_constraints__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (f, args, kargs) = context f(tao, x, c, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_JacobianEquality(PetscTAO _tao, PetscVec _x, PetscMat _J, PetscMat _P, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef Vec x = ref_Vec(_x) cdef Mat J = ref_Mat(_J) cdef Mat P = ref_Mat(_P) context = tao.get_attr("__jacobian_equality__") if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(tao, x, J, P, *args, **kargs) return PETSC_SUCCESS # ctx is unused cdef PetscErrorCode TAO_Update( PetscTAO _tao, PetscInt its, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef object context = tao.get_attr('__update__') assert context is not None and type(context) is tuple # sanity check (update, args, kargs) = context update(tao, toInt(its), *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TAO_Converged(PetscTAO _tao, void* ctx) except PETSC_ERR_PYTHON with gil: # call first the default convergence test CHKERR( TaoDefaultConvergenceTest(_tao, NULL) ) # call next the user-provided convergence test cdef TAO tao = ref_TAO(_tao) (converged, args, kargs) = tao.get_attr('__converged__') reason = converged(tao, *args, **kargs) if reason is None: return PETSC_SUCCESS # handle value of convergence reason cdef PetscTAOConvergedReason creason = TAO_CONTINUE_ITERATING if reason is False or reason == -1: creason = TAO_DIVERGED_USER elif reason is True or reason == 1: creason = TAO_CONVERGED_USER else: creason = reason assert creason >= TAO_DIVERGED_USER assert creason <= TAO_CONVERGED_USER CHKERR( TaoSetConvergedReason(_tao, creason) ) return PETSC_SUCCESS cdef PetscErrorCode TAO_Monitor(PetscTAO _tao, void* ctx) except PETSC_ERR_PYTHON with gil: cdef TAO tao = ref_TAO(_tao) cdef object monitorlist = tao.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS for (monitor, args, kargs) in monitorlist: monitor(tao, *args, **kargs) return PETSC_SUCCESS # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscts.pxi000066400000000000000000000566441454104047300210750ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscTSType "TSType" PetscTSType TSEULER PetscTSType TSBEULER PetscTSType TSBASICSYMPLECTIC PetscTSType TSPSEUDO PetscTSType TSCN PetscTSType TSSUNDIALS PetscTSType TSRK PetscTSType TSPYTHON PetscTSType TSTHETA PetscTSType TSALPHA PetscTSType TSALPHA2 PetscTSType TSGLLE PetscTSType TSGLEE PetscTSType TSSSP PetscTSType TSARKIMEX PetscTSType TSROSW PetscTSType TSEIMEX PetscTSType TSMIMEX PetscTSType TSBDF PetscTSType TSRADAU5 PetscTSType TSMPRK PetscTSType TSDISCGRAD ctypedef enum PetscTSProblemType "TSProblemType": TS_LINEAR TS_NONLINEAR ctypedef enum PetscTSEquationType "TSEquationType": TS_EQ_UNSPECIFIED TS_EQ_EXPLICIT TS_EQ_ODE_EXPLICIT TS_EQ_DAE_SEMI_EXPLICIT_INDEX1 TS_EQ_DAE_SEMI_EXPLICIT_INDEX2 TS_EQ_DAE_SEMI_EXPLICIT_INDEX3 TS_EQ_DAE_SEMI_EXPLICIT_INDEXHI TS_EQ_IMPLICIT TS_EQ_ODE_IMPLICIT TS_EQ_DAE_IMPLICIT_INDEX1 TS_EQ_DAE_IMPLICIT_INDEX2 TS_EQ_DAE_IMPLICIT_INDEX3 TS_EQ_DAE_IMPLICIT_INDEXHI ctypedef enum PetscTSConvergedReason "TSConvergedReason": # iterating TS_CONVERGED_ITERATING # converged TS_CONVERGED_TIME TS_CONVERGED_ITS TS_CONVERGED_USER TS_CONVERGED_EVENT # diverged TS_DIVERGED_NONLINEAR_SOLVE TS_DIVERGED_STEP_REJECTED ctypedef enum PetscTSExactFinalTimeOption "TSExactFinalTimeOption": TS_EXACTFINALTIME_UNSPECIFIED TS_EXACTFINALTIME_STEPOVER TS_EXACTFINALTIME_INTERPOLATE TS_EXACTFINALTIME_MATCHSTEP ctypedef PetscErrorCode PetscTSCtxDel(void*) ctypedef PetscErrorCode (*PetscTSFunctionFunction)(PetscTS, PetscReal, PetscVec, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSJacobianFunction)(PetscTS, PetscReal, PetscVec, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSIFunctionFunction)(PetscTS, PetscReal, PetscVec, PetscVec, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSIJacobianFunction)(PetscTS, PetscReal, PetscVec, PetscVec, PetscReal, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSIJacobianPFunction)(PetscTS, PetscReal, PetscVec, PetscVec, PetscReal, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSI2FunctionFunction)(PetscTS, PetscReal, PetscVec, PetscVec, PetscVec, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSI2JacobianFunction)(PetscTS, PetscReal, PetscVec, PetscVec, PetscVec, PetscReal, PetscReal, PetscMat, PetscMat, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSMonitorFunction)(PetscTS, PetscInt, PetscReal, PetscVec, void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSPreStepFunction) (PetscTS) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSPostStepFunction) (PetscTS) except PETSC_ERR_PYTHON PetscErrorCode TSCreate(MPI_Comm comm,PetscTS*) PetscErrorCode TSClone(PetscTS,PetscTS*) PetscErrorCode TSDestroy(PetscTS*) PetscErrorCode TSView(PetscTS,PetscViewer) PetscErrorCode TSLoad(PetscTS,PetscViewer) PetscErrorCode TSSetProblemType(PetscTS,PetscTSProblemType) PetscErrorCode TSGetProblemType(PetscTS,PetscTSProblemType*) PetscErrorCode TSSetEquationType(PetscTS,PetscTSEquationType) PetscErrorCode TSGetEquationType(PetscTS,PetscTSEquationType*) PetscErrorCode TSSetType(PetscTS,PetscTSType) PetscErrorCode TSGetType(PetscTS,PetscTSType*) PetscErrorCode TSSetOptionsPrefix(PetscTS,char[]) PetscErrorCode TSAppendOptionsPrefix(PetscTS,char[]) PetscErrorCode TSGetOptionsPrefix(PetscTS,char*[]) PetscErrorCode TSSetFromOptions(PetscTS) PetscErrorCode TSSetSolution(PetscTS,PetscVec) PetscErrorCode TSGetSolution(PetscTS,PetscVec*) PetscErrorCode TS2SetSolution(PetscTS,PetscVec,PetscVec) PetscErrorCode TS2GetSolution(PetscTS,PetscVec*,PetscVec*) PetscErrorCode TSGetRHSFunction(PetscTS,PetscVec*,PetscTSFunctionFunction*,void*) PetscErrorCode TSGetRHSJacobian(PetscTS,PetscMat*,PetscMat*,PetscTSJacobianFunction*,void**) PetscErrorCode TSSetRHSFunction(PetscTS,PetscVec,PetscTSFunctionFunction,void*) PetscErrorCode TSSetRHSJacobian(PetscTS,PetscMat,PetscMat,PetscTSJacobianFunction,void*) PetscErrorCode TSSetIFunction(PetscTS,PetscVec,PetscTSIFunctionFunction,void*) PetscErrorCode TSSetIJacobian(PetscTS,PetscMat,PetscMat,PetscTSIJacobianFunction,void*) PetscErrorCode TSSetIJacobianP(PetscTS,PetscMat,PetscTSIJacobianPFunction,void*) PetscErrorCode TSGetIFunction(PetscTS,PetscVec*,PetscTSIFunctionFunction*,void*) PetscErrorCode TSGetIJacobian(PetscTS,PetscMat*,PetscMat*,PetscTSIJacobianFunction*,void**) PetscErrorCode TSSetI2Function(PetscTS,PetscVec,PetscTSI2FunctionFunction,void*) PetscErrorCode TSSetI2Jacobian(PetscTS,PetscMat,PetscMat,PetscTSI2JacobianFunction,void*) PetscErrorCode TSGetI2Function(PetscTS,PetscVec*,PetscTSI2FunctionFunction*,void**) PetscErrorCode TSGetI2Jacobian(PetscTS,PetscMat*,PetscMat*,PetscTSI2JacobianFunction*,void**) PetscErrorCode TSGetKSP(PetscTS,PetscKSP*) PetscErrorCode TSGetSNES(PetscTS,PetscSNES*) PetscErrorCode TSGetDM(PetscTS,PetscDM*) PetscErrorCode TSSetDM(PetscTS,PetscDM) PetscErrorCode TSComputeRHSFunction(PetscTS,PetscReal,PetscVec,PetscVec) PetscErrorCode TSComputeRHSFunctionLinear(PetscTS,PetscReal,PetscVec,PetscVec,void*) PetscErrorCode TSComputeRHSJacobian(PetscTS,PetscReal,PetscVec,PetscMat,PetscMat) PetscErrorCode TSComputeRHSJacobianConstant(PetscTS,PetscReal,PetscVec,PetscMat,PetscMat,void*) PetscErrorCode TSComputeIFunction(PetscTS,PetscReal,PetscVec,PetscVec,PetscVec,PetscBool) PetscErrorCode TSComputeIJacobian(PetscTS,PetscReal,PetscVec,PetscVec,PetscReal,PetscMat,PetscMat,PetscBool) PetscErrorCode TSComputeIJacobianP(PetscTS,PetscReal,PetscVec,PetscVec,PetscReal,PetscMat,PetscBool) PetscErrorCode TSComputeI2Function(PetscTS,PetscReal,PetscVec,PetscVec,PetscVec,PetscVec) PetscErrorCode TSComputeI2Jacobian(PetscTS,PetscReal,PetscVec,PetscVec,PetscVec,PetscReal,PetscReal,PetscMat,PetscMat) PetscErrorCode TSSetTime(PetscTS,PetscReal) PetscErrorCode TSGetTime(PetscTS,PetscReal*) PetscErrorCode TSGetPrevTime(PetscTS,PetscReal*) PetscErrorCode TSGetSolveTime(PetscTS,PetscReal*) PetscErrorCode TSSetTimeStep(PetscTS,PetscReal) PetscErrorCode TSGetTimeStep(PetscTS,PetscReal*) PetscErrorCode TSSetStepNumber(PetscTS,PetscInt) PetscErrorCode TSGetStepNumber(PetscTS,PetscInt*) PetscErrorCode TSSetMaxSteps(PetscTS,PetscInt) PetscErrorCode TSGetMaxSteps(PetscTS,PetscInt*) PetscErrorCode TSSetMaxTime(PetscTS,PetscReal) PetscErrorCode TSGetMaxTime(PetscTS,PetscReal*) PetscErrorCode TSSetExactFinalTime(PetscTS,PetscTSExactFinalTimeOption) PetscErrorCode TSSetTimeSpan(PetscTS,PetscInt,PetscReal*) PetscErrorCode TSGetTimeSpan(PetscTS,PetscInt*,const PetscReal**) PetscErrorCode TSGetTimeSpanSolutions(PetscTS,PetscInt*,PetscVec**) PetscErrorCode TSSetConvergedReason(PetscTS,PetscTSConvergedReason) PetscErrorCode TSGetConvergedReason(PetscTS,PetscTSConvergedReason*) PetscErrorCode TSGetSNESIterations(PetscTS,PetscInt*) PetscErrorCode TSGetKSPIterations(PetscTS,PetscInt*) PetscErrorCode TSGetStepRejections(PetscTS,PetscInt*) PetscErrorCode TSSetMaxStepRejections(PetscTS,PetscInt) PetscErrorCode TSGetSNESFailures(PetscTS,PetscInt*) PetscErrorCode TSSetMaxSNESFailures(PetscTS,PetscInt) PetscErrorCode TSSetErrorIfStepFails(PetscTS,PetscBool) PetscErrorCode TSSetTolerances(PetscTS,PetscReal,PetscVec,PetscReal,PetscVec) PetscErrorCode TSGetTolerances(PetscTS,PetscReal*,PetscVec*,PetscReal*,PetscVec*) PetscErrorCode TSMonitorSet(PetscTS,PetscTSMonitorFunction,void*,PetscTSCtxDel*) PetscErrorCode TSMonitorCancel(PetscTS) PetscErrorCode TSMonitor(PetscTS,PetscInt,PetscReal,PetscVec) ctypedef PetscErrorCode (*PetscTSEventHandler)(PetscTS,PetscReal,PetscVec,PetscScalar[],void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSPostEvent)(PetscTS,PetscInt,PetscInt[],PetscReal,PetscVec, PetscBool, void*) except PETSC_ERR_PYTHON PetscErrorCode TSSetEventHandler(PetscTS, PetscInt, PetscInt[], PetscBool[], PetscTSEventHandler, PetscTSPostEvent, void*) PetscErrorCode TSSetEventTolerances(PetscTS, PetscReal, PetscReal[]) PetscErrorCode TSGetNumEvents(PetscTS, PetscInt*) ctypedef PetscErrorCode (*PetscTSAdjointR)(PetscTS,PetscReal,PetscVec,PetscVec,void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSAdjointDRDY)(PetscTS,PetscReal,PetscVec,PetscVec[],void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSAdjointDRDP)(PetscTS,PetscReal,PetscVec,PetscVec[],void*) except PETSC_ERR_PYTHON ctypedef PetscErrorCode (*PetscTSRHSJacobianP)(PetscTS,PetscReal,PetscVec,PetscMat,void*) except PETSC_ERR_PYTHON PetscErrorCode TSSetSaveTrajectory(PetscTS) PetscErrorCode TSRemoveTrajectory(PetscTS) PetscErrorCode TSSetCostGradients(PetscTS,PetscInt,PetscVec*,PetscVec*) PetscErrorCode TSGetCostGradients(PetscTS,PetscInt*,PetscVec**,PetscVec**) PetscErrorCode TSCreateQuadratureTS(PetscTS,PetscBool,PetscTS*) PetscErrorCode TSGetQuadratureTS(PetscTS,PetscBool*,PetscTS*) PetscErrorCode TSGetCostIntegral(PetscTS,PetscVec*) PetscErrorCode TSSetRHSJacobianP(PetscTS,PetscMat,PetscTSRHSJacobianP,void*) PetscErrorCode TSComputeRHSJacobianP(PetscTS,PetscReal,PetscVec,PetscMat) PetscErrorCode TSAdjointSolve(PetscTS) PetscErrorCode TSAdjointSetSteps(PetscTS,PetscInt) PetscErrorCode TSAdjointStep(PetscTS) PetscErrorCode TSAdjointSetUp(PetscTS) PetscErrorCode TSAdjointReset(PetscTS) PetscErrorCode TSAdjointComputeDRDPFunction(PetscTS,PetscReal,PetscVec,PetscVec*) PetscErrorCode TSAdjointComputeDRDYFunction(PetscTS,PetscReal,PetscVec,PetscVec*) PetscErrorCode TSAdjointCostIntegral(PetscTS) PetscErrorCode TSForwardSetSensitivities(PetscTS,PetscInt,PetscVec*,PetscInt,PetscVec*) PetscErrorCode TSForwardGetSensitivities(PetscTS,PetscInt*,PetscVec**,PetscInt*,PetscVec**) PetscErrorCode TSForwardSetIntegralGradients(PetscTS,PetscInt,PetscVec *,PetscVec *) PetscErrorCode TSForwardGetIntegralGradients(PetscTS,PetscInt*,PetscVec **,PetscVec **) PetscErrorCode TSForwardSetRHSJacobianP(PetscTS,PetscVec*,PetscTSCostIntegrandFunction,void*) PetscErrorCode TSForwardComputeRHSJacobianP(PetscTS,PetscReal,PetscVec,PetscVec*) PetscErrorCode TSForwardSetUp(PetscTS) PetscErrorCode TSForwardCostIntegral(PetscTS) PetscErrorCode TSForwardStep(PetscTS) PetscErrorCode TSSetPreStep(PetscTS, PetscTSPreStepFunction) PetscErrorCode TSSetPostStep(PetscTS, PetscTSPostStepFunction) PetscErrorCode TSSetUp(PetscTS) PetscErrorCode TSReset(PetscTS) PetscErrorCode TSStep(PetscTS) PetscErrorCode TSRestartStep(PetscTS) PetscErrorCode TSRollBack(PetscTS) PetscErrorCode TSSolve(PetscTS,PetscVec) PetscErrorCode TSInterpolate(PetscTS,PetscReal,PetscVec) PetscErrorCode TSPreStage(PetscTS,PetscReal) PetscErrorCode TSPostStage(PetscTS,PetscReal,PetscInt,PetscVec*) PetscErrorCode TSThetaSetTheta(PetscTS,PetscReal) PetscErrorCode TSThetaGetTheta(PetscTS,PetscReal*) PetscErrorCode TSThetaSetEndpoint(PetscTS,PetscBool) PetscErrorCode TSThetaGetEndpoint(PetscTS,PetscBool*) PetscErrorCode TSAlphaSetRadius(PetscTS,PetscReal) PetscErrorCode TSAlphaSetParams(PetscTS,PetscReal,PetscReal,PetscReal) PetscErrorCode TSAlphaGetParams(PetscTS,PetscReal*,PetscReal*,PetscReal*) ctypedef const char* PetscTSRKType "TSRKType" PetscTSRKType TSRK1FE PetscTSRKType TSRK2A PetscTSRKType TSRK2B PetscTSRKType TSRK3 PetscTSRKType TSRK3BS PetscTSRKType TSRK4 PetscTSRKType TSRK5F PetscTSRKType TSRK5DP PetscTSRKType TSRK5BS PetscTSRKType TSRK6VR PetscTSRKType TSRK7VR PetscTSRKType TSRK8VR PetscErrorCode TSRKGetType(PetscTS ts,PetscTSRKType*) PetscErrorCode TSRKSetType(PetscTS ts,PetscTSRKType) ctypedef const char* PetscTSARKIMEXType "TSARKIMEXType" PetscTSARKIMEXType TSARKIMEX1BEE PetscTSARKIMEXType TSARKIMEXA2 PetscTSARKIMEXType TSARKIMEXL2 PetscTSARKIMEXType TSARKIMEXARS122 PetscTSARKIMEXType TSARKIMEX2C PetscTSARKIMEXType TSARKIMEX2D PetscTSARKIMEXType TSARKIMEX2E PetscTSARKIMEXType TSARKIMEXPRSSP2 PetscTSARKIMEXType TSARKIMEX3 PetscTSARKIMEXType TSARKIMEXBPR3 PetscTSARKIMEXType TSARKIMEXARS443 PetscTSARKIMEXType TSARKIMEX4 PetscTSARKIMEXType TSARKIMEX5 PetscErrorCode TSARKIMEXGetType(PetscTS ts,PetscTSRKType*) PetscErrorCode TSARKIMEXSetType(PetscTS ts,PetscTSRKType) PetscErrorCode TSARKIMEXSetFullyImplicit(PetscTS ts,PetscBool) PetscErrorCode TSPythonSetType(PetscTS,char[]) PetscErrorCode TSPythonGetType(PetscTS,char*[]) cdef extern from * nogil: struct _p_TSAdapt ctypedef _p_TSAdapt *PetscTSAdapt "TSAdapt" PetscErrorCode TSGetAdapt(PetscTS,PetscTSAdapt*) PetscErrorCode TSAdaptGetStepLimits(PetscTSAdapt,PetscReal*,PetscReal*) PetscErrorCode TSAdaptSetStepLimits(PetscTSAdapt,PetscReal,PetscReal) PetscErrorCode TSAdaptCheckStage(PetscTSAdapt,PetscTS,PetscReal,PetscVec,PetscBool*) cdef extern from * nogil: # custom.h PetscErrorCode TSSetTimeStepNumber(PetscTS,PetscInt) # ----------------------------------------------------------------------------- cdef inline TS ref_TS(PetscTS ts): cdef TS ob = TS() ob.ts = ts PetscINCREF(ob.obj) return ob # ----------------------------------------------------------------------------- cdef PetscErrorCode TS_RHSFunction( PetscTS ts, PetscReal t, PetscVec x, PetscVec f, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec Fvec = ref_Vec(f) cdef object context = Ts.get_attr('__rhsfunction__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (function, args, kargs) = context function(Ts, toReal(t), Xvec, Fvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_RHSJacobian( PetscTS ts, PetscReal t, PetscVec x, PetscMat J, PetscMat P, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Mat Jmat = ref_Mat(J) cdef Mat Pmat = ref_Mat(P) cdef object context = Ts.get_attr('__rhsjacobian__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(Ts, toReal(t), Xvec, Jmat, Pmat, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode TS_IFunction( PetscTS ts, PetscReal t, PetscVec x, PetscVec xdot, PetscVec f, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec XDvec = ref_Vec(xdot) cdef Vec Fvec = ref_Vec(f) cdef object context = Ts.get_attr('__ifunction__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (function, args, kargs) = context function(Ts, toReal(t), Xvec, XDvec, Fvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_IJacobian( PetscTS ts, PetscReal t, PetscVec x, PetscVec xdot, PetscReal a, PetscMat J, PetscMat P, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec XDvec = ref_Vec(xdot) cdef Mat Jmat = ref_Mat(J) cdef Mat Pmat = ref_Mat(P) cdef object context = Ts.get_attr('__ijacobian__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(Ts, toReal(t), Xvec, XDvec, toReal(a), Jmat, Pmat, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_IJacobianP( PetscTS ts, PetscReal t, PetscVec x, PetscVec xdot, PetscReal a, PetscMat J, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec XDvec = ref_Vec(xdot) cdef Mat Jmat = ref_Mat(J) cdef object context = Ts.get_attr('__ijacobianp__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(Ts, toReal(t), Xvec, XDvec, toReal(a), Jmat, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_I2Function( PetscTS ts, PetscReal t, PetscVec x, PetscVec xdot, PetscVec xdotdot, PetscVec f, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec XDvec = ref_Vec(xdot) cdef Vec XDDvec = ref_Vec(xdotdot) cdef Vec Fvec = ref_Vec(f) cdef object context = Ts.get_attr('__i2function__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (function, args, kargs) = context function(Ts, toReal(t), Xvec, XDvec, XDDvec, Fvec, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_I2Jacobian( PetscTS ts, PetscReal t, PetscVec x, PetscVec xdot, PetscVec xdotdot, PetscReal v, PetscReal a, PetscMat J, PetscMat P, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Vec XDvec = ref_Vec(xdot) cdef Vec XDDvec = ref_Vec(xdotdot) cdef Mat Jmat = ref_Mat(J) cdef Mat Pmat = ref_Mat(P) cdef object context = Ts.get_attr('__i2jacobian__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobian, args, kargs) = context jacobian(Ts, toReal(t), Xvec, XDvec, XDDvec, toReal(v), toReal(a), Jmat, Pmat, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode TS_Monitor( PetscTS ts, PetscInt step, PetscReal time, PetscVec u, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Vu = ref_Vec(u) cdef object monitorlist = Ts.get_attr('__monitor__') if monitorlist is None: return PETSC_SUCCESS for (monitor, args, kargs) in monitorlist: monitor(Ts, toInt(step), toReal(time), Vu, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode TS_EventHandler( PetscTS ts, PetscReal time, PetscVec u, PetscScalar fvalue[], void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Vu = ref_Vec(u) cdef object context = Ts.get_attr('__eventhandler__') if context is None: return PETSC_SUCCESS (eventhandler, args, kargs) = context cdef PetscInt nevents = 0 CHKERR( TSGetNumEvents(ts, &nevents) ) cdef npy_intp s = nevents fvalue_array = PyArray_SimpleNewFromData(1, &s, NPY_PETSC_SCALAR, fvalue) eventhandler(Ts, toReal(time), Vu, fvalue_array, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_PostEvent( PetscTS ts, PetscInt nevents_zero, PetscInt events_zero[], PetscReal time, PetscVec u, PetscBool forward, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Vu = ref_Vec(u) cdef object context = Ts.get_attr('__postevent__') if context is None: return PETSC_SUCCESS (postevent, args, kargs) = context cdef npy_intp s = nevents_zero events_zero_array = PyArray_SimpleNewFromData(1, &s, NPY_PETSC_INT, events_zero) postevent(Ts, events_zero_array, toReal(time), Vu, toBool(forward), *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_PreStep( PetscTS ts, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) (prestep, args, kargs) = Ts.get_attr('__prestep__') prestep(Ts, *args, **kargs) return PETSC_SUCCESS cdef PetscErrorCode TS_PostStep( PetscTS ts, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) (poststep, args, kargs) = Ts.get_attr('__poststep__') poststep(Ts, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- cdef PetscErrorCode TS_RHSJacobianP( PetscTS ts, PetscReal t, PetscVec x, PetscMat J, void* ctx, ) except PETSC_ERR_PYTHON with gil: cdef TS Ts = ref_TS(ts) cdef Vec Xvec = ref_Vec(x) cdef Mat Jmat = ref_Mat(J) cdef object context = Ts.get_attr('__rhsjacobianp__') if context is None and ctx != NULL: context = ctx assert context is not None and type(context) is tuple # sanity check (jacobianp, args, kargs) = context jacobianp(Ts, toReal(t), Xvec, Jmat, *args, **kargs) return PETSC_SUCCESS # ----------------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/PETSc/petscvec.pxi000066400000000000000000000601101454104047300212030ustar00rootroot00000000000000# -------------------------------------------------------------------- cdef extern from * nogil: ctypedef const char* PetscVecType "VecType" PetscVecType VECSEQ PetscVecType VECMPI PetscVecType VECSTANDARD PetscVecType VECSHARED PetscVecType VECSEQVIENNACL PetscVecType VECMPIVIENNACL PetscVecType VECVIENNACL PetscVecType VECSEQCUDA PetscVecType VECMPICUDA PetscVecType VECCUDA PetscVecType VECSEQHIP PetscVecType VECMPIHIP PetscVecType VECHIP PetscVecType VECNEST PetscVecType VECSEQKOKKOS PetscVecType VECMPIKOKKOS PetscVecType VECKOKKOS ctypedef enum PetscVecOption "VecOption": VEC_IGNORE_OFF_PROC_ENTRIES VEC_IGNORE_NEGATIVE_INDICES PetscErrorCode VecView(PetscVec,PetscViewer) PetscErrorCode VecDestroy(PetscVec*) PetscErrorCode VecCreate(MPI_Comm,PetscVec*) PetscErrorCode VecSetOptionsPrefix(PetscVec,char[]) PetscErrorCode VecAppendOptionsPrefix(PetscVec,char[]) PetscErrorCode VecGetOptionsPrefix(PetscVec,char*[]) PetscErrorCode VecSetFromOptions(PetscVec) PetscErrorCode VecSetUp(PetscVec) PetscErrorCode VecCreateSeq(MPI_Comm,PetscInt,PetscVec*) PetscErrorCode VecCreateSeqWithArray(MPI_Comm,PetscInt,PetscInt,PetscScalar[],PetscVec*) PetscErrorCode VecCreateSeqCUDAWithArrays(MPI_Comm,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateSeqHIPWithArrays(MPI_Comm,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateSeqViennaCLWithArrays(MPI_Comm,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateMPI(MPI_Comm,PetscInt,PetscInt,PetscVec*) PetscErrorCode VecCreateMPIWithArray(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscVec*) PetscErrorCode VecCreateMPICUDAWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateMPIHIPWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateMPIViennaCLWithArrays(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscScalar[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateGhost(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt[],PetscVec*) PetscErrorCode VecCreateGhostWithArray(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateGhostBlock(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt[],PetscVec*) PetscErrorCode VecCreateGhostBlockWithArray(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscInt[],PetscScalar[],PetscVec*) PetscErrorCode VecCreateShared(MPI_Comm,PetscInt,PetscInt,PetscVec*) PetscErrorCode VecCreateNest(MPI_Comm,PetscInt,PetscIS[],PetscVec[],PetscVec*) PetscErrorCode VecGetType(PetscVec,PetscVecType*) PetscErrorCode VecSetType(PetscVec,PetscVecType) PetscErrorCode VecSetOption(PetscVec,PetscVecOption,PetscBool) PetscErrorCode VecSetSizes(PetscVec,PetscInt,PetscInt) PetscErrorCode VecGetSize(PetscVec,PetscInt*) PetscErrorCode VecGetLocalSize(PetscVec,PetscInt*) PetscErrorCode VecSetBlockSize(PetscVec,PetscInt) PetscErrorCode VecGetBlockSize(PetscVec,PetscInt*) PetscErrorCode VecGetOwnershipRange(PetscVec,PetscInt*,PetscInt*) PetscErrorCode VecGetOwnershipRanges(PetscVec,const PetscInt*[]) PetscErrorCode VecCreateLocalVector(PetscVec,PetscVec*) PetscErrorCode VecGetLocalVector(PetscVec,PetscVec) PetscErrorCode VecRestoreLocalVector(PetscVec,PetscVec) PetscErrorCode VecGetLocalVectorRead(PetscVec,PetscVec) PetscErrorCode VecRestoreLocalVectorRead(PetscVec,PetscVec) PetscErrorCode VecGetArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecRestoreArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecGetArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecRestoreArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecGetArray(PetscVec,PetscScalar*[]) PetscErrorCode VecRestoreArray(PetscVec,PetscScalar*[]) PetscErrorCode VecPlaceArray(PetscVec,PetscScalar[]) PetscErrorCode VecResetArray(PetscVec) PetscErrorCode VecGetArrayWriteAndMemType(PetscVec,PetscScalar*[],PetscMemType*) PetscErrorCode VecRestoreArrayWriteAndMemType(PetscVec,PetscScalar*[]) PetscErrorCode VecGetArrayReadAndMemType(PetscVec,const PetscScalar*[],PetscMemType*) PetscErrorCode VecRestoreArrayReadAndMemType(PetscVec,const PetscScalar*[]) PetscErrorCode VecGetArrayAndMemType(PetscVec,PetscScalar*[],PetscMemType*) PetscErrorCode VecRestoreArrayAndMemType(PetscVec,PetscScalar*[]) PetscErrorCode VecEqual(PetscVec,PetscVec,PetscBool*) PetscErrorCode VecLoad(PetscVec,PetscViewer) PetscErrorCode VecDuplicate(PetscVec,PetscVec*) PetscErrorCode VecCopy(PetscVec,PetscVec) PetscErrorCode VecChop(PetscVec,PetscReal) PetscErrorCode VecDuplicateVecs(PetscVec,PetscInt,PetscVec*[]) PetscErrorCode VecDestroyVecs(PetscInt,PetscVec*[]) PetscErrorCode VecGetValues(PetscVec,PetscInt,PetscInt[],PetscScalar[]) PetscErrorCode VecSetValue(PetscVec,PetscInt,PetscScalar,PetscInsertMode) PetscErrorCode VecSetValues(PetscVec,PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode VecSetValuesBlocked(PetscVec,PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode VecSetLocalToGlobalMapping(PetscVec,PetscLGMap) PetscErrorCode VecGetLocalToGlobalMapping(PetscVec,PetscLGMap*) PetscErrorCode VecSetValueLocal(PetscVec,PetscInt,PetscScalar,PetscInsertMode) PetscErrorCode VecSetValuesLocal(PetscVec,PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode VecSetValuesBlockedLocal(PetscVec,PetscInt,const PetscInt[],const PetscScalar[],PetscInsertMode) PetscErrorCode VecDot(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecDotBegin(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecDotEnd(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecTDot(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecTDotBegin(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecTDotEnd(PetscVec,PetscVec,PetscScalar*) PetscErrorCode VecMDot(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecMDotBegin(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecMDotEnd(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecMTDot(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecMTDotBegin(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecMTDotEnd(PetscVec,PetscInt,PetscVec[],PetscScalar*) PetscErrorCode VecNorm(PetscVec,PetscNormType,PetscReal*) PetscErrorCode VecNormBegin(PetscVec,PetscNormType,PetscReal*) PetscErrorCode VecNormEnd(PetscVec,PetscNormType,PetscReal*) PetscErrorCode VecAssemblyBegin(PetscVec) PetscErrorCode VecAssemblyEnd(PetscVec) PetscErrorCode VecZeroEntries(PetscVec) PetscErrorCode VecConjugate(PetscVec) PetscErrorCode VecNormalize(PetscVec,PetscReal*) PetscErrorCode VecSum(PetscVec,PetscScalar*) PetscErrorCode VecMax(PetscVec,PetscInt*,PetscReal*) PetscErrorCode VecMin(PetscVec,PetscInt*,PetscReal*) PetscErrorCode VecScale(PetscVec,PetscScalar) PetscErrorCode VecCopy(PetscVec,PetscVec) PetscErrorCode VecSetRandom(PetscVec,PetscRandom) PetscErrorCode VecSet(PetscVec,PetscScalar) PetscErrorCode VecSwap(PetscVec,PetscVec) PetscErrorCode VecAXPY(PetscVec,PetscScalar,PetscVec) PetscErrorCode VecAXPBY(PetscVec,PetscScalar,PetscScalar,PetscVec) PetscErrorCode VecAYPX(PetscVec,PetscScalar,PetscVec) PetscErrorCode VecWAXPY(PetscVec,PetscScalar,PetscVec,PetscVec) PetscErrorCode VecMAXPY(PetscVec,PetscInt,PetscScalar[],PetscVec[]) PetscErrorCode VecPointwiseMax(PetscVec,PetscVec,PetscVec) PetscErrorCode VecPointwiseMaxAbs(PetscVec,PetscVec,PetscVec) PetscErrorCode VecPointwiseMin(PetscVec,PetscVec,PetscVec) PetscErrorCode VecPointwiseMult(PetscVec,PetscVec,PetscVec) PetscErrorCode VecPointwiseDivide(PetscVec,PetscVec,PetscVec) PetscErrorCode VecMaxPointwiseDivide(PetscVec,PetscVec,PetscReal*) PetscErrorCode VecShift(PetscVec,PetscScalar) PetscErrorCode VecChop(PetscVec,PetscReal) PetscErrorCode VecReciprocal(PetscVec) PetscErrorCode VecPermute(PetscVec,PetscIS,PetscBool) PetscErrorCode VecExp(PetscVec) PetscErrorCode VecLog(PetscVec) PetscErrorCode VecSqrtAbs(PetscVec) PetscErrorCode VecAbs(PetscVec) PetscErrorCode VecStrideMin(PetscVec,PetscInt,PetscInt*,PetscReal*) PetscErrorCode VecStrideMax(PetscVec,PetscInt,PetscInt*,PetscReal*) PetscErrorCode VecStrideScale(PetscVec,PetscInt,PetscScalar) PetscErrorCode VecStrideGather(PetscVec,PetscInt,PetscVec,PetscInsertMode) PetscErrorCode VecStrideScatter(PetscVec,PetscInt,PetscVec,PetscInsertMode) PetscErrorCode VecStrideNorm(PetscVec,PetscInt,PetscNormType,PetscReal*) PetscErrorCode VecGhostGetLocalForm(PetscVec,PetscVec*) PetscErrorCode VecGhostRestoreLocalForm(PetscVec,PetscVec*) PetscErrorCode VecGhostUpdateBegin(PetscVec,PetscInsertMode,PetscScatterMode) PetscErrorCode VecGhostUpdateEnd(PetscVec,PetscInsertMode,PetscScatterMode) PetscErrorCode VecMPISetGhost(PetscVec,PetscInt,const PetscInt*) PetscErrorCode VecGetSubVector(PetscVec,PetscIS,PetscVec*) PetscErrorCode VecRestoreSubVector(PetscVec,PetscIS,PetscVec*) PetscErrorCode VecNestGetSubVecs(PetscVec,PetscInt*,PetscVec**) PetscErrorCode VecNestSetSubVecs(PetscVec,PetscInt,PetscInt*,PetscVec*) PetscErrorCode VecISAXPY(PetscVec,PetscIS,PetscScalar,PetscVec) PetscErrorCode VecISSet(PetscVec,PetscIS,PetscScalar) PetscErrorCode VecCUDAGetArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecCUDAGetArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecCUDAGetArray(PetscVec,PetscScalar*[]) PetscErrorCode VecCUDARestoreArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecCUDARestoreArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecCUDARestoreArray(PetscVec,PetscScalar*[]) PetscErrorCode VecHIPGetArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecHIPGetArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecHIPGetArray(PetscVec,PetscScalar*[]) PetscErrorCode VecHIPRestoreArrayRead(PetscVec,const PetscScalar*[]) PetscErrorCode VecHIPRestoreArrayWrite(PetscVec,PetscScalar*[]) PetscErrorCode VecHIPRestoreArray(PetscVec,PetscScalar*[]) PetscErrorCode VecBindToCPU(PetscVec,PetscBool) PetscErrorCode VecBoundToCPU(PetscVec,PetscBool*) PetscErrorCode VecGetOffloadMask(PetscVec,PetscOffloadMask*) PetscErrorCode VecViennaCLGetCLContext(PetscVec,Py_uintptr_t*) PetscErrorCode VecViennaCLGetCLQueue(PetscVec,Py_uintptr_t*) PetscErrorCode VecViennaCLGetCLMemRead(PetscVec,Py_uintptr_t*) PetscErrorCode VecViennaCLGetCLMemWrite(PetscVec,Py_uintptr_t*) PetscErrorCode VecViennaCLRestoreCLMemWrite(PetscVec) PetscErrorCode VecViennaCLGetCLMem(PetscVec,Py_uintptr_t*) PetscErrorCode VecViennaCLRestoreCLMem(PetscVec) PetscErrorCode VecCreateSeqCUDAWithArray(MPI_Comm,PetscInt,PetscInt,const PetscScalar*,PetscVec*) PetscErrorCode VecCreateMPICUDAWithArray(MPI_Comm,PetscInt,PetscInt,PetscInt,const PetscScalar*,PetscVec*) PetscErrorCode VecCreateSeqHIPWithArray(MPI_Comm,PetscInt,PetscInt,const PetscScalar*,PetscVec*) PetscErrorCode VecCreateMPIHIPWithArray(MPI_Comm,PetscInt,PetscInt,PetscInt,const PetscScalar*,PetscVec*) cdef extern from * nogil: # custom.h PetscErrorCode VecStrideSum(PetscVec,PetscInt,PetscScalar*) PetscErrorCode VecGetCurrentMemType(PetscVec,PetscMemType*) # -------------------------------------------------------------------- cdef inline Vec ref_Vec(PetscVec vec): cdef Vec ob = Vec() ob.vec = vec PetscINCREF(ob.obj) return ob # -------------------------------------------------------------------- # unary operations cdef Vec vec_pos(Vec self): cdef Vec vec = type(self)() CHKERR( VecDuplicate(self.vec, &vec.vec) ) CHKERR( VecCopy(self.vec, vec.vec) ) return vec cdef Vec vec_neg(Vec self): cdef Vec vec = vec_pos(self) CHKERR( VecScale(vec.vec, -1) ) return vec cdef Vec vec_abs(Vec self): cdef Vec vec = vec_pos(self) CHKERR( VecAbs(vec.vec) ) return vec # inplace binary operations cdef Vec vec_iadd(Vec self, other): cdef PetscScalar alpha = 1 cdef Vec vec if isinstance(other, Vec): alpha = 1; vec = other CHKERR( VecAXPY(self.vec, alpha, vec.vec) ) elif isinstance(other, tuple) or isinstance(other, list): other, vec = other alpha = asScalar(other) CHKERR( VecAXPY(self.vec, alpha, vec.vec) ) else: alpha = asScalar(other) CHKERR( VecShift(self.vec, alpha) ) return self cdef Vec vec_isub(Vec self, other): cdef PetscScalar alpha = 1 cdef Vec vec if isinstance(other, Vec): alpha = 1; vec = other CHKERR( VecAXPY(self.vec, -alpha, vec.vec) ) elif isinstance(other, tuple) or isinstance(other, list): other, vec = other alpha = asScalar(other) CHKERR( VecAXPY(self.vec, -alpha, vec.vec) ) else: alpha = asScalar(other) CHKERR( VecShift(self.vec, -alpha) ) return self cdef Vec vec_imul(Vec self, other): cdef PetscScalar alpha = 1 cdef Vec vec if isinstance(other, Vec): vec = other CHKERR( VecPointwiseMult(self.vec, self.vec, vec.vec) ) else: alpha = asScalar(other) CHKERR( VecScale(self.vec, alpha) ) return self cdef Vec vec_idiv(Vec self, other): cdef PetscScalar one = 1 cdef PetscScalar alpha = 1 cdef Vec vec if isinstance(other, Vec): vec = other CHKERR( VecPointwiseDivide(self.vec, self.vec, vec.vec) ) else: alpha = asScalar(other) CHKERR( VecScale(self.vec, one/alpha) ) return self # binary operations cdef Vec vec_add(Vec self, other): return vec_iadd(vec_pos(self), other) cdef Vec vec_sub(Vec self, other): return vec_isub(vec_pos(self), other) cdef Vec vec_mul(Vec self, other): return vec_imul(vec_pos(self), other) cdef Vec vec_div(Vec self, other): return vec_idiv(vec_pos(self), other) # reflected binary operations cdef Vec vec_radd(Vec self, other): return vec_add(self, other) cdef Vec vec_rsub(Vec self, other): cdef Vec vec = vec_sub(self, other) CHKERR( VecScale(vec.vec, -1) ) return vec cdef Vec vec_rmul(Vec self, other): return vec_mul(self, other) cdef Vec vec_rdiv(Vec self, other): cdef Vec vec = vec_div(self, other) CHKERR( VecReciprocal(vec.vec) ) return vec # -------------------------------------------------------------------- cdef inline int Vec_Sizes(object size, object bsize, PetscInt *b, PetscInt *n, PetscInt *N) except -1: Sys_Sizes(size, bsize, b, n, N) return 0 # -------------------------------------------------------------------- ctypedef PetscErrorCode VecSetValuesFcn(PetscVec, PetscInt,const PetscInt*, const PetscScalar*,PetscInsertMode) cdef inline VecSetValuesFcn* vecsetvalues_fcn(int blocked, int local): cdef VecSetValuesFcn *setvalues = NULL if blocked and local: setvalues = VecSetValuesBlockedLocal elif blocked: setvalues = VecSetValuesBlocked elif local: setvalues = VecSetValuesLocal else: setvalues = VecSetValues return setvalues cdef inline int vecsetvalues(PetscVec V, object oi, object ov, object oim, int blocked, int local) except -1: # block size cdef PetscInt bs=1 if blocked: CHKERR( VecGetBlockSize(V, &bs) ) if bs < 1: bs = 1 # indices and values cdef PetscInt ni=0, nv=0 cdef PetscInt *i=NULL cdef PetscScalar *v=NULL cdef object tmp1 = iarray_i(oi, &ni, &i) cdef object tmp2 = iarray_s(ov, &nv, &v) if ni*bs != nv: raise ValueError( "incompatible array sizes: ni=%d, nv=%d, bs=%d" % (toInt(ni), toInt(nv), toInt(bs)) ) # VecSetValuesXXX function and insert mode cdef VecSetValuesFcn *setvalues = vecsetvalues_fcn(blocked, local) cdef PetscInsertMode addv = insertmode(oim) # actual call CHKERR( setvalues(V, ni, i, v, addv) ) return 0 cdef object vecgetvalues(PetscVec vec, object oindices, object values): cdef PetscInt ni=0, nv=0 cdef PetscInt *i=NULL cdef PetscScalar *v=NULL cdef object indices = iarray_i(oindices, &ni, &i) if values is None: values = empty_s(ni) values.shape = indices.shape values = oarray_s(values, &nv, &v) if (ni != nv): raise ValueError( ("incompatible array sizes: " "ni=%d, nv=%d") % (toInt(ni), toInt(nv))) CHKERR( VecGetValues(vec, ni, i, v) ) return values # -------------------------------------------------------------------- cdef inline _Vec_buffer vec_getbuffer_r(Vec self): cdef _Vec_buffer buf = _Vec_buffer(self) buf.readonly = 1 return buf cdef inline _Vec_buffer vec_getbuffer_w(Vec self): cdef _Vec_buffer buf = _Vec_buffer(self) buf.readonly = 0 return buf cdef inline ndarray vec_getarray_r(Vec self): return asarray(vec_getbuffer_r(self)) cdef inline ndarray vec_getarray_w(Vec self): return asarray(vec_getbuffer_w(self)) cdef inline int vec_setarray(Vec self, object o) except -1: cdef PetscInt na=0, nv=0, i=0 cdef PetscScalar *va=NULL, *vv=NULL cdef ndarray ary = iarray_s(o, &na, &va) CHKERR( VecGetLocalSize(self.vec, &nv) ) if (na != nv) and PyArray_NDIM(ary) > 0: raise ValueError( "array size %d incompatible with vector local size %d" % (toInt(na), toInt(nv)) ) CHKERR( VecGetArray(self.vec, &vv) ) try: if PyArray_NDIM(ary) == 0: for i from 0 <= i < nv: vv[i] = va[0] else: CHKERR( PetscMemcpy(vv, va, nv*sizeof(PetscScalar)) ) finally: CHKERR( VecRestoreArray(self.vec, &vv) ) return 0 cdef object vec_getitem(Vec self, object i): cdef PetscInt N=0 if i is Ellipsis: return asarray(self) if isinstance(i, slice): CHKERR( VecGetSize(self.vec, &N) ) start, stop, stride = i.indices(toInt(N)) i = arange(start, stop, stride) return vecgetvalues(self.vec, i, None) cdef int vec_setitem(Vec self, object i, object v) except -1: cdef PetscInt N=0 if i is Ellipsis: return vec_setarray(self, v) if isinstance(i, slice): CHKERR( VecGetSize(self.vec, &N) ) start, stop, stride = i.indices(toInt(N)) i = arange(start, stop, stride) vecsetvalues(self.vec, i, v, None, 0, 0) return 0 cdef vec_get_dlpack_ctx(Vec self): cdef object ctx0 = self.get_attr('__dltensor_ctx__') cdef PetscInt n = 0 cdef int64_t ndim = 1 cdef int64_t* shape_arr = NULL cdef int64_t* strides_arr = NULL cdef object s1 = None cdef object s2 = None cdef PetscInt devId = 0 cdef PetscMemType mtype = PETSC_MEMTYPE_HOST if ctx0 is None: # First time in, create a linear memory view s1 = oarray_p(empty_p(ndim), NULL, &shape_arr) s2 = oarray_p(empty_p(ndim), NULL, &strides_arr) CHKERR( VecGetLocalSize(self.vec, &n) ) shape_arr[0] = n strides_arr[0] = 1 else: (_, _, ndim, s1, s2) = ctx0 devType_ = { PETSC_MEMTYPE_HOST : kDLCPU, PETSC_MEMTYPE_CUDA : kDLCUDA, PETSC_MEMTYPE_HIP : kDLROCM } CHKERR( VecGetCurrentMemType(self.vec, &mtype) ) dtype = devType_.get(mtype, kDLCPU) if dtype != kDLCPU: CHKERR( PetscObjectGetDeviceId(self.vec, &devId) ) ctx0 = (dtype, devId, ndim, s1, s2) self.set_attr('__dltensor_ctx__', ctx0) return ctx0 # -------------------------------------------------------------------- cdef int Vec_AcquireArray(PetscVec v, PetscScalar *a[], int ro) nogil except -1: if ro: CHKERR( VecGetArrayRead(v, a) ) else: CHKERR( VecGetArray(v, a) ) return 0 cdef int Vec_ReleaseArray(PetscVec v, PetscScalar *a[], int ro) nogil except -1: if ro: CHKERR( VecRestoreArrayRead(v, a) ) else: CHKERR( VecRestoreArray(v, a) ) return 0 cdef class _Vec_buffer: cdef PetscVec vec cdef PetscInt size cdef PetscScalar *data cdef bint readonly cdef bint hasarray def __cinit__(self, Vec vec, bint readonly=0): cdef PetscVec v = vec.vec CHKERR( PetscINCREF(&v) ) self.vec = v self.size = 0 self.data = NULL self.readonly = 1 if readonly else 0 self.hasarray = 0 def __dealloc__(self): if self.hasarray and self.vec != NULL: Vec_ReleaseArray(self.vec, &self.data, self.readonly) CHKERR( VecDestroy(&self.vec) ) # cdef int acquire(self) nogil except -1: if not self.hasarray and self.vec != NULL: CHKERR( VecGetLocalSize(self.vec, &self.size) ) Vec_AcquireArray(self.vec, &self.data, self.readonly) self.hasarray = 1 return 0 cdef int release(self) nogil except -1: if self.hasarray and self.vec != NULL: self.size = 0 Vec_ReleaseArray(self.vec, &self.data, self.readonly) self.hasarray = 0 return 0 # buffer interface (PEP 3118) cdef int acquirebuffer(self, Py_buffer *view, int flags) except -1: self.acquire() PyPetscBuffer_FillInfo(view, self.data, self.size, c's', self.readonly, flags) view.obj = self return 0 cdef int releasebuffer(self, Py_buffer *view) except -1: PyPetscBuffer_Release(view) self.release() return 0 def __getbuffer__(self, Py_buffer *view, int flags): self.acquirebuffer(view, flags) def __releasebuffer__(self, Py_buffer *view): self.releasebuffer(view) # 'with' statement (PEP 343) cdef object enter(self): self.acquire() return asarray(self) cdef object exit(self): self.release() return None def __enter__(self): return self.enter() def __exit__(self, *exc): return self.exit() # buffer interface (legacy) cdef Py_ssize_t getbuffer(self, void **p) except -1: cdef PetscInt n = 0 if p != NULL: self.acquire() p[0] = self.data n = self.size elif self.vec != NULL: CHKERR( VecGetLocalSize(self.vec, &n) ) return (n*sizeof(PetscScalar)) def __getsegcount__(self, Py_ssize_t *lenp): if lenp != NULL: lenp[0] = self.getbuffer(NULL) return 1 def __getreadbuffer__(self, Py_ssize_t idx, void **p): if idx != 0: raise SystemError( "accessing non-existent buffer segment") return self.getbuffer(p) def __getwritebuffer__(self, Py_ssize_t idx, void **p): if idx != 0: raise SystemError( "accessing non-existent buffer segment") if self.readonly: raise TypeError( "Object is not writable.") return self.getbuffer(p) # NumPy array interface (legacy) property __array_interface__: def __get__(self): cdef PetscInt n = 0 if self.vec != NULL: CHKERR( VecGetLocalSize(self.vec, &n) ) cdef object size = toInt(n) cdef dtype descr = PyArray_DescrFromType(NPY_PETSC_SCALAR) cdef str typestr = "=%c%d" % (descr.kind, descr.itemsize) return dict(version=3, data=self, shape=(size,), typestr=typestr) # -------------------------------------------------------------------- cdef class _Vec_LocalForm: "Context manager for `Vec` local form" cdef Vec gvec cdef Vec lvec def __init__(self, Vec gvec): self.gvec = gvec self.lvec = Vec() def __enter__(self): cdef PetscVec gvec = self.gvec.vec CHKERR( VecGhostGetLocalForm(gvec, &self.lvec.vec) ) return self.lvec def __exit__(self, *exc): cdef PetscVec gvec = self.gvec.vec CHKERR( VecGhostRestoreLocalForm(gvec, &self.lvec.vec) ) self.lvec.vec = NULL petsc4py-3.19.6/src/petsc4py/PETSc/petscvwr.pxi000066400000000000000000000153301454104047300212500ustar00rootroot00000000000000cdef extern from * nogil: ctypedef const char* PetscViewerType PetscViewerType PETSCVIEWERSOCKET PetscViewerType PETSCVIEWERASCII PetscViewerType PETSCVIEWERBINARY PetscViewerType PETSCVIEWERSTRING PetscViewerType PETSCVIEWERDRAW PetscViewerType PETSCVIEWERVU PetscViewerType PETSCVIEWERMATHEMATICA PetscViewerType PETSCVIEWERHDF5 PetscViewerType PETSCVIEWERVTK PetscViewerType PETSCVIEWERMATLAB PetscViewerType PETSCVIEWERSAWS PetscViewerType PETSCVIEWERGLVIS PetscViewerType PETSCVIEWERADIOS PetscViewerType PETSCVIEWEREXODUSII ctypedef enum PetscViewerFormat: PETSC_VIEWER_DEFAULT PETSC_VIEWER_ASCII_MATLAB PETSC_VIEWER_ASCII_MATHEMATICA PETSC_VIEWER_ASCII_IMPL PETSC_VIEWER_ASCII_INFO PETSC_VIEWER_ASCII_INFO_DETAIL PETSC_VIEWER_ASCII_COMMON PETSC_VIEWER_ASCII_SYMMODU PETSC_VIEWER_ASCII_INDEX PETSC_VIEWER_ASCII_DENSE PETSC_VIEWER_ASCII_MATRIXMARKET PETSC_VIEWER_ASCII_VTK_DEPRECATED PETSC_VIEWER_ASCII_VTK_CELL_DEPRECATED PETSC_VIEWER_ASCII_VTK_COORDS_DEPRECATED PETSC_VIEWER_ASCII_PCICE PETSC_VIEWER_ASCII_PYTHON PETSC_VIEWER_ASCII_FACTOR_INFO PETSC_VIEWER_ASCII_LATEX PETSC_VIEWER_ASCII_XML PETSC_VIEWER_ASCII_GLVIS PETSC_VIEWER_ASCII_CSV PETSC_VIEWER_DRAW_BASIC PETSC_VIEWER_DRAW_LG PETSC_VIEWER_DRAW_LG_XRANGE PETSC_VIEWER_DRAW_CONTOUR PETSC_VIEWER_DRAW_PORTS PETSC_VIEWER_VTK_VTS PETSC_VIEWER_VTK_VTR PETSC_VIEWER_VTK_VTU PETSC_VIEWER_BINARY_MATLAB PETSC_VIEWER_NATIVE PETSC_VIEWER_HDF5_PETSC PETSC_VIEWER_HDF5_VIZ PETSC_VIEWER_HDF5_XDMF PETSC_VIEWER_HDF5_MAT PETSC_VIEWER_NOFORMAT PETSC_VIEWER_LOAD_BALANCE PETSC_VIEWER_FAILED ctypedef enum PetscFileMode: PETSC_FILE_MODE_READ "FILE_MODE_READ" PETSC_FILE_MODE_WRITE "FILE_MODE_WRITE" PETSC_FILE_MODE_APPEND "FILE_MODE_APPEND" PETSC_FILE_MODE_UPDATE "FILE_MODE_UPDATE" PETSC_FILE_MODE_APPEND_UPDATE "FILE_MODE_APPEND_UPDATE" enum: PETSC_DRAW_FULL_SIZE enum: PETSC_DRAW_HALF_SIZE enum: PETSC_DRAW_THIRD_SIZE enum: PETSC_DRAW_QUARTER_SIZE PetscErrorCode PetscViewerView(PetscViewer,PetscViewer) PetscErrorCode PetscViewerDestroy(PetscViewer*) PetscErrorCode PetscViewerCreate(MPI_Comm,PetscViewer*) PetscErrorCode PetscViewerSetType(PetscViewer,PetscViewerType) PetscErrorCode PetscViewerGetType(PetscViewer,PetscViewerType*) PetscErrorCode PetscViewerSetOptionsPrefix(PetscViewer,char[]) PetscErrorCode PetscViewerAppendOptionsPrefix(PetscViewer,char[]) PetscErrorCode PetscViewerGetOptionsPrefix(PetscViewer,char*[]) PetscErrorCode PetscViewerSetFromOptions(PetscViewer) PetscErrorCode PetscViewerSetUp(PetscViewer) PetscErrorCode PetscViewerASCIIOpen(MPI_Comm,char[],PetscViewer*) PetscErrorCode PetscViewerBinaryCreate(MPI_Comm comm,PetscViewer*) PetscErrorCode PetscViewerBinaryOpen(MPI_Comm,char[],PetscFileMode,PetscViewer*) PetscErrorCode PetscViewerDrawOpen(MPI_Comm,char[],char[],int,int,int,int,PetscViewer*) PetscErrorCode PetscViewerBinarySetUseMPIIO(PetscViewer,PetscBool) PetscErrorCode PetscViewerSetFormat(PetscViewer,PetscViewerFormat) PetscErrorCode PetscViewerGetFormat(PetscViewer,PetscViewerFormat*) PetscErrorCode PetscViewerPushFormat(PetscViewer,PetscViewerFormat) PetscErrorCode PetscViewerPopFormat(PetscViewer) PetscErrorCode PetscViewerGetSubViewer(PetscViewer,MPI_Comm,PetscViewer*) PetscErrorCode PetscViewerRestoreSubViewer(PetscViewer,MPI_Comm,PetscViewer*) PetscErrorCode PetscViewerASCIISetTab(PetscViewer,PetscInt) PetscErrorCode PetscViewerASCIIGetTab(PetscViewer,PetscInt*) PetscErrorCode PetscViewerASCIIAddTab(PetscViewer,PetscInt) PetscErrorCode PetscViewerASCIISubtractTab(PetscViewer,PetscInt) PetscErrorCode PetscViewerASCIIPushSynchronized(PetscViewer) PetscErrorCode PetscViewerASCIIPopSynchronized(PetscViewer) PetscErrorCode PetscViewerASCIIPushTab(PetscViewer) PetscErrorCode PetscViewerASCIIPopTab(PetscViewer) PetscErrorCode PetscViewerASCIIUseTabs(PetscViewer,PetscBool) PetscErrorCode PetscViewerASCIIPrintf(PetscViewer,const char[],...) PetscErrorCode PetscViewerStringSPrintf(PetscViewer,char[],...) PetscErrorCode PetscViewerASCIISynchronizedPrintf(PetscViewer,const char[],...) PetscErrorCode PetscViewerFileGetName(PetscViewer,char*[]) PetscErrorCode PetscViewerFileSetName(PetscViewer,char[]) PetscErrorCode PetscViewerFileGetMode(PetscViewer,PetscFileMode*) PetscErrorCode PetscViewerFileSetMode(PetscViewer,PetscFileMode) PetscErrorCode PetscViewerFlush(PetscViewer) PetscErrorCode PetscViewerDrawClear(PetscViewer) PetscErrorCode PetscViewerDrawSetInfo(PetscViewer,char[],char[],int,int,int,int) PetscErrorCode PetscViewerHDF5PushTimestepping(PetscViewer) PetscErrorCode PetscViewerHDF5PopTimestepping(PetscViewer) PetscErrorCode PetscViewerHDF5GetTimestep(PetscViewer,PetscInt*) PetscErrorCode PetscViewerHDF5SetTimestep(PetscViewer,PetscInt) PetscErrorCode PetscViewerHDF5IncrementTimestep(PetscViewer) PetscErrorCode PetscViewerHDF5PushGroup(PetscViewer,char[]) PetscErrorCode PetscViewerHDF5PopGroup(PetscViewer) PetscErrorCode PetscViewerHDF5GetGroup(PetscViewer,char[],char*[]) PetscViewer PETSC_VIEWER_STDOUT_(MPI_Comm) except? NULL PetscViewer PETSC_VIEWER_STDOUT_SELF PetscViewer PETSC_VIEWER_STDOUT_WORLD PetscViewer PETSC_VIEWER_STDERR_(MPI_Comm) except? NULL PetscViewer PETSC_VIEWER_STDERR_SELF PetscViewer PETSC_VIEWER_STDERR_WORLD PetscViewer PETSC_VIEWER_BINARY_(MPI_Comm) except? NULL PetscViewer PETSC_VIEWER_BINARY_SELF PetscViewer PETSC_VIEWER_BINARY_WORLD PetscViewer PETSC_VIEWER_DRAW_(MPI_Comm) except? NULL PetscViewer PETSC_VIEWER_DRAW_SELF PetscViewer PETSC_VIEWER_DRAW_WORLD # --- cdef inline PetscFileMode filemode(object mode) except (-1): if mode is None: return PETSC_FILE_MODE_READ if isinstance(mode, str): if mode == 'r' : return PETSC_FILE_MODE_READ elif mode == 'w' : return PETSC_FILE_MODE_WRITE elif mode == 'a' : return PETSC_FILE_MODE_APPEND elif mode == 'r+' : return PETSC_FILE_MODE_UPDATE elif mode == 'w+' : return PETSC_FILE_MODE_UPDATE elif mode == 'a+' : return PETSC_FILE_MODE_APPEND_UPDATE elif mode == 'u' : return PETSC_FILE_MODE_UPDATE elif mode == 'au' : return PETSC_FILE_MODE_APPEND_UPDATE elif mode == 'ua' : return PETSC_FILE_MODE_APPEND_UPDATE return mode petsc4py-3.19.6/src/petsc4py/__init__.pxd000066400000000000000000000000701454104047300202020ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com petsc4py-3.19.6/src/petsc4py/__init__.py000066400000000000000000000052401454104047300200430ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # -------------------------------------------------------------------- """ PETSc for Python ================ This package is an interface to PETSc libraries. PETSc_ (the Portable, Extensible Toolkit for Scientific Computation) is a suite of data structures and routines for the scalable (parallel) solution of scientific applications modeled by partial differential equations. It employs the MPI_ standard for all message-passing communications. .. _PETSc: https://petsc.org .. _MPI: https://www.mpi-forum.org """ __author__ = 'Lisandro Dalcin' __version__ = '3.19.6' __credits__ = 'PETSc Team ' # -------------------------------------------------------------------- def init(args=None, arch=None, comm=None): """ Initialize PETSc. :Parameters: - `args`: command-line arguments, usually the 'sys.argv' list. - `arch`: specific configuration to use. - `comm`: MPI commmunicator .. note:: This function should be called only once, typically at the very beginning of the bootstrap script of an application. """ import petsc4py.lib PETSc = petsc4py.lib.ImportPETSc(arch) args = petsc4py.lib.getInitArgs(args) PETSc._initialize(args, comm) # -------------------------------------------------------------------- def get_include(): """ Return the directory in the package that contains header files. Extension modules that need to compile against petsc4py should use this function to locate the appropriate include directory. Using Python distutils (or perhaps NumPy distutils):: import petsc4py Extension('extension_name', ... include_dirs=[..., petsc4py.get_include()]) """ from os.path import dirname, join return join(dirname(__file__), 'include') # -------------------------------------------------------------------- def get_config(): """Return a dictionary with information about PETSc.""" import os import sys if sys.version_info[0] >= 3: from io import StringIO from configparser import ConfigParser else: from StringIO import StringIO from ConfigParser import ConfigParser pgkdir = os.path.dirname(__file__) filename = os.path.join(pgkdir, 'lib', 'petsc.cfg') with open(filename) as fp: stream = StringIO("[petsc]\n"+fp.read()) parser = ConfigParser() parser.optionxform = str if sys.version_info[0] >= 3: parser.read_file(stream, filename) else: parser.readfp(stream, filename) return dict(parser.items('petsc')) # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/__main__.py000066400000000000000000000040211454104047300200200ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com """ Command line access to the PETSc Options Database. This module provides command line access to PETSc Options Database. It outputs a listing of the many PETSc options indicating option names, default values and descriptions. Usage:: $ python -m petsc4py [vec|mat|pc|ksp|snes|ts|tao] [] """ def help(args=None): import shlex 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 = shlex.split(args) else: args = [str(a) for a in args] # import and initialize import petsc4py petsc4py.init([prog, '-help'] + args) from petsc4py import PETSc # help dispatcher COMM = PETSc.COMM_SELF if 'vec' in args: vec = PETSc.Vec().create(comm=COMM) vec.setSizes(0) vec.setFromOptions() vec.destroy() if 'mat' in args: mat = PETSc.Mat().create(comm=COMM) mat.setSizes([0, 0]) mat.setFromOptions() mat.destroy() if 'pc' in args: pc = PETSc.PC().create(comm=COMM) pc.setFromOptions() pc.destroy() if 'ksp' in args: ksp = PETSc.KSP().create(comm=COMM) ksp.setFromOptions() ksp.destroy() if 'snes' in args: snes = PETSc.SNES().create(comm=COMM) snes.setFromOptions() snes.destroy() if 'ts' in args: ts = PETSc.TS().create(comm=COMM) ts.setFromOptions() ts.destroy() if 'tao' in args: tao = PETSc.TAO().create(comm=COMM) tao.setFromOptions() tao.destroy() if 'dmda' in args: dmda = PETSc.DMDA().create(comm=COMM) dmda.setFromOptions() dmda.destroy() if 'dmplex' in args: dmplex = PETSc.DMPlex().create(comm=COMM) dmplex.setFromOptions() dmplex.destroy() if __name__ == '__main__': help() petsc4py-3.19.6/src/petsc4py/include/000077500000000000000000000000001454104047300173545ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py/include/petsc4py/000077500000000000000000000000001454104047300211275ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py/include/petsc4py/numpy.h000066400000000000000000000017321454104047300224530ustar00rootroot00000000000000#ifndef PETSC4PY_NUMPY_H #define PETSC4PY_NUMPY_H #include #include #include # define NPY_PETSC_BOOL NPY_INT #if defined(PETSC_USE_64BIT_INDICES) # define NPY_PETSC_INT NPY_INT64 #else # define NPY_PETSC_INT NPY_INT #endif #if defined(PETSC_USE_REAL_SINGLE) # define NPY_PETSC_REAL NPY_FLOAT # define NPY_PETSC_COMPLEX NPY_CFLOAT #elif defined(PETSC_USE_REAL_DOUBLE) # define NPY_PETSC_REAL NPY_DOUBLE # define NPY_PETSC_COMPLEX NPY_CDOUBLE #elif defined(PETSC_USE_REAL_LONG_DOUBLE) # define NPY_PETSC_REAL NPY_LONGDOUBLE # define NPY_PETSC_COMPLEX NPY_CLONGDOUBLE #elif defined(PETSC_USE_REAL___FLOAT128) # define NPY_PETSC_REAL NPY_FLOAT128 # define NPY_PETSC_COMPLEX NPY_COMPLEX256 #else # error "unsupported real precision" #endif #if defined(PETSC_USE_COMPLEX) # define NPY_PETSC_SCALAR NPY_PETSC_COMPLEX #else # define NPY_PETSC_SCALAR NPY_PETSC_REAL #endif #endif /* !PETSC4PY_NUMPY_H */ petsc4py-3.19.6/src/petsc4py/include/petsc4py/petsc4py.h000066400000000000000000000004741454104047300230600ustar00rootroot00000000000000/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ #ifndef PETSC4PY_H #define PETSC4PY_H #include #include #include "../../PETSc_api.h" static int import_petsc4py(void) { if (import_petsc4py__PETSc() < 0) goto bad; return 0; bad: return -1; } #endif /* !PETSC4PY_H */ petsc4py-3.19.6/src/petsc4py/include/petsc4py/petsc4py.i000066400000000000000000000505561454104047300230670ustar00rootroot00000000000000/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ /* ---------------------------------------------------------------- */ %header %{#include %} %init %{import_petsc4py();%} /* ---------------------------------------------------------------- */ %runtime %{ SWIGINTERNINLINE PyObject* SWIG_getattr_this(PyObject* obj) { if (!obj) return NULL; obj = PyObject_GetAttr(obj, SWIG_This()); if (!obj) PyErr_Clear(); return obj; } SWIGINTERNINLINE int SWIG_convert_ptr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) { int res = SWIG_ConvertPtr(obj, ptr, ty, flags); if (!SWIG_IsOK(res)) { PyObject* _this = SWIG_getattr_this(obj); res = SWIG_ConvertPtr(_this, ptr, ty, flags); Py_XDECREF(_this); } return res; } #undef SWIG_ConvertPtr #define SWIG_ConvertPtr(obj, pptr, type, flags) \ SWIG_convert_ptr(obj, pptr, type, flags) %} /* ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- */ /* PETSc Error Codes */ /* ---------------------------------------------------------------- */ %define %petsc4py_errt(Pkg, PyType, Type) %wrapper %{ #ifndef Py##Pkg##_ChkErrQ #define Py##Pkg##_ChkErrQ(ierr) \ do { \ if (ierr != PETSC_SUCCESS) { \ Py##Pkg##PyType##_Set((ierr)); SWIG_fail; \ } \ } while (0) #endif /* defined Py##Pkg##_ChkErrQ */ %} %typemap(out,noblock=1) Type { Py##Pkg##_ChkErrQ($1); %set_output(VOID_Object); } %enddef /* ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- */ /* Numeric Types */ /* ---------------------------------------------------------------- */ %define SWIG_TYPECHECK_PETSC_INT SWIG_TYPECHECK_INT32 %enddef %define SWIG_TYPECHECK_PETSC_REAL SWIG_TYPECHECK_DOUBLE %enddef %define SWIG_TYPECHECK_PETSC_COMPLEX SWIG_TYPECHECK_CPLXDBL %enddef %define SWIG_TYPECHECK_PETSC_SCALAR SWIG_TYPECHECK_CPLXDBL %enddef /* PetscInt */ /* -------- */ %fragment(SWIG_From_frag(PetscInt64),"header", fragment=SWIG_From_frag(long long), fragment=SWIG_From_frag(long)) { SWIGINTERN SWIG_Object SWIG_From_dec(PetscInt64)(PetscInt64 val) { %#if PETSC_SIZEOF_LONG == 8 return SWIG_From(long)(%numeric_cast(val,long)); %#else return SWIG_From(long long)(%numeric_cast(val,long long)); %#endif } } %fragment(SWIG_AsVal_frag(PetscInt64),"header", fragment=SWIG_AsVal_frag(long long), fragment=SWIG_AsVal_frag(long)) { SWIGINTERN int SWIG_AsVal_dec(PetscInt64)(SWIG_Object obj, PetscInt64 *val) { %#if PETSC_SIZEOF_LONG == 8 long v; int res = SWIG_AsVal(long)(obj, &v); %#else long long v; int res = SWIG_AsVal(long long)(obj, &v); %#endif if (SWIG_IsOK(res) && val) if (val) *val = %numeric_cast(v,PetscInt64); return res; } } %fragment(SWIG_From_frag(PetscInt),"header", fragment=SWIG_From_frag(PetscInt64), fragment=SWIG_From_frag(int)) { %#if defined(PETSC_USE_64BIT_INDICES) %define_as(SWIG_From(PetscInt), SWIG_From(PetscInt64)) %#else %define_as(SWIG_From(PetscInt), SWIG_From(int)) %#endif } %fragment(SWIG_AsVal_frag(PetscInt),"header", fragment=SWIG_AsVal_frag(PetscInt64), fragment=SWIG_AsVal_frag(int)) { %#if defined(PETSC_USE_64BIT_INDICES) %define_as(SWIG_AsVal(PetscInt), SWIG_AsVal(PetscInt64)) %#else %define_as(SWIG_AsVal(PetscInt), SWIG_AsVal(int)) %#endif } /* PetscReal */ /* --------- */ %fragment(SWIG_From_frag(long double),"header", fragment=SWIG_From_frag(double)) { SWIGINTERN SWIG_Object SWIG_From_dec(long double)(long double val) { return SWIG_From(double)((double)val); } } %fragment(SWIG_AsVal_frag(long double),"header", fragment=SWIG_AsVal_frag(double)) { SWIGINTERN int SWIG_AsVal_dec(long double)(SWIG_Object obj, long double *val) { double v; int res = SWIG_AsVal(double)(obj, &v); if (SWIG_IsOK(res) && val) if (val) *val = %numeric_cast(v,long double); return res; } } %fragment(SWIG_From_frag(PetscReal),"header", fragment=SWIG_From_frag(long double), fragment=SWIG_From_frag(double), fragment=SWIG_From_frag(float)) { %#if defined(PETSC_USE_REAL_SINGLE) %define_as(SWIG_From(PetscReal), SWIG_From(float)) %#elif defined(PETSC_USE_REAL_DOUBLE) %define_as(SWIG_From(PetscReal), SWIG_From(double)) %#elif defined(PETSC_USE_REAL_LONG_DOUBLE) %define_as(SWIG_From(PetscReal), SWIG_From(long double)) %#endif } %fragment(SWIG_AsVal_frag(PetscReal),"header", fragment=SWIG_AsVal_frag(long double), fragment=SWIG_AsVal_frag(double), fragment=SWIG_AsVal_frag(float)) { %#if defined(PETSC_USE_REAL_SINGLE) %define_as(SWIG_AsVal(PetscReal), SWIG_AsVal(float)) %#elif defined(PETSC_USE_REAL_DOUBLE) %define_as(SWIG_AsVal(PetscReal), SWIG_AsVal(double)) %#elif defined(PETSC_USE_REAL_LONG_DOUBLE) %define_as(SWIG_AsVal(PetscReal), SWIG_AsVal(long double)) %#endif } /* PetscComplex */ /* ------------ */ %include complex.i %fragment(SWIG_From_frag(PetscComplex),"header", #ifdef __cplusplus fragment=SWIG_From_frag(std::complex), fragment=SWIG_From_frag(std::complex), fragment=SWIG_From_frag(std::complex)) #else fragment=SWIG_From_frag(long double complex), fragment=SWIG_From_frag(double complex), fragment=SWIG_From_frag(float complex)) #endif { %#if defined(PETSC_CLANGUAGE_CXX) %define_as(SWIG_From(PetscComplex), SWIG_From(std::complex)) %#else %define_as(SWIG_From(PetscComplex), SWIG_From(double complex)) %#endif } %fragment(SWIG_AsVal_frag(PetscComplex),"header", #ifdef __cplusplus fragment=SWIG_AsVal_frag(std::complex), fragment=SWIG_AsVal_frag(std::complex), fragment=SWIG_AsVal_frag(std::complex)) #else fragment=SWIG_AsVal_frag(long double complex), fragment=SWIG_AsVal_frag(double complex), fragment=SWIG_AsVal_frag(float complex)) #endif { %#if defined(PETSC_CLANGUAGE_CXX) %define_as(SWIG_AsVal(PetscComplex), SWIG_AsVal(std::complex)) %#else %define_as(SWIG_AsVal(PetscComplex), SWIG_AsVal(double complex)) %#endif } /* PetscScalar */ /* ----------- */ %fragment(SWIG_From_frag(PetscScalar), "header", fragment=SWIG_From_frag(PetscReal), fragment=SWIG_From_frag(PetscComplex)) { %#if defined(PETSC_USE_COMPLEX) %define_as(SWIG_From(PetscScalar), SWIG_From(PetscComplex)) %#else %define_as(SWIG_From(PetscScalar), SWIG_From(PetscReal)) %#endif } %fragment(SWIG_AsVal_frag(PetscScalar), "header", fragment=SWIG_AsVal_frag(PetscReal), fragment=SWIG_AsVal_frag(PetscComplex)) { %#if defined(PETSC_USE_COMPLEX) %define_as(SWIG_AsVal(PetscScalar), SWIG_AsVal(PetscComplex)) %#else %define_as(SWIG_AsVal(PetscScalar), SWIG_AsVal(PetscReal)) %#endif } %define %petsc4py_numt(Pkg, PyType, Type, CheckCode, UNUSED) %types(Type,Type*); %typemaps_primitive(%checkcode(CheckCode), Type); /* INPUT value typemap*/ %typemap(typecheck, precedence=%checkcode(CheckCode), fragment=SWIG_AsVal_frag(Type)) Type, const Type & { int res = SWIG_AsVal(Type)($input, 0); $1 = SWIG_CheckState(res); } %typemap(in,noblock=1,fragment=SWIG_AsVal_frag(Type)) Type (Type val, int ecode = 0) { ecode = SWIG_AsVal(Type)($input, &val); if (!SWIG_IsOK(ecode)) %argument_fail(ecode, "$ltype", $symname, $argnum); $1 = %static_cast(val,$ltype); } %typemap(in,noblock=1,fragment=SWIG_AsVal_frag(Type)) const Type & ($*ltype temp, Type val, int ecode = 0) { ecode = SWIG_AsVal(Type)($input, &val); if (!SWIG_IsOK(ecode)) %argument_fail(ecode, "$*ltype", $symname, $argnum); temp = %static_cast(val,$*ltype); $1 = &temp; } %typemap(freearg) Type, const Type & ""; /* INPUT pointer/reference typemap */ %typemap(typecheck, precedence=%checkcode(CheckCode), fragment=SWIG_AsVal_frag(Type)) Type *INPUT, Type &INPUT { int res = SWIG_AsVal(Type)($input, 0); $1 = SWIG_CheckState(res); } %typemap(in,noblock=1,fragment=SWIG_AsVal_frag(Type)) Type *INPUT ($*ltype temp, int res = 0) { res = SWIG_AsVal(Type)($input, &temp); if (!SWIG_IsOK(res)) %argument_fail(res, "$*ltype",$symname, $argnum); $1 = &temp; } %typemap(in,noblock=1,fragment=SWIG_AsVal_frag(Type)) Type &INPUT ($*ltype temp, int res = 0) { res = SWIG_AsVal(Type)($input, &temp); if (!SWIG_IsOK(res)) %argument_fail(res, "$*ltype",$symname, $argnum); $1 = &temp; } %typemap(freearg) Type *INPUT, Type &INPUT ""; /* OUTPUT pointer/reference typemap */ %typemap(in,numinputs=0,noblock=1) Type *OUTPUT ($*ltype temp=0) "$1 = &temp;"; %typemap(in,numinputs=0,noblock=1) Type &OUTPUT ($*ltype temp=0) "$1 = &temp;"; %typemap(argout,noblock=1,fragment=SWIG_From_frag(Type)) Type* OUTPUT, Type &OUTPUT { %append_output(SWIG_From(Type)((*$1))); } %typemap(freearg) Type *OUTPUT ""; /* INOUT pointer/reference typemap */ %typemap(typecheck) Type *INOUT = Type *INPUT; %typemap(in) Type *INOUT = Type *INPUT; %typemap(argout) Type *INOUT = Type *OUTPUT; %typemap(freearg) Type *INOUT ""; %typemap(typecheck) Type &INOUT = Type &INPUT; %typemap(in) Type &INOUT = Type &INPUT; %typemap(argout) Type &INOUT = Type &OUTPUT; %typemap(freearg) Type &INOUT ""; /* default typemap for pointer argument */ %apply Type *OUTPUT { Type * } %enddef /* %petsc4py_numt */ /* ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- */ /* Enumerations */ /* ---------------------------------------------------------------- */ %define SWIG_TYPECHECK_PETSC_ENUM SWIG_TYPECHECK_INT32 %enddef %fragment(SWIG_From_frag(PetscEnum),"header", fragment=SWIG_From_frag(int)) { SWIGINTERN SWIG_Object SWIG_From_dec(PetscEnum)(PetscEnum val) { return SWIG_From(int)((PetscEnum)val); } } %fragment(SWIG_AsVal_frag(PetscEnum),"header", fragment=SWIG_AsVal_frag(int)) { SWIGINTERN int SWIG_AsVal_dec(PetscEnum)(SWIG_Object obj, PetscEnum *val) { int v; int res = SWIG_AsVal(int)(obj, &v); if (SWIG_IsOK(res) && val) *val = %static_cast(v,PetscEnum); return res; } } %typemaps_primitive(%checkcode(PETSC_ENUM), PetscEnum); %typemap(in,numinputs=0) PetscEnum *OUTPUT ($*ltype temp) "$1 = &temp;" %typemap(argout,noblock=1,fragment=SWIG_From_frag(PetscEnum)) PetscEnum *OUTPUT { %append_output(SWIG_From(PetscEnum)(%static_cast(*$1,PetscEnum))); } %apply PetscEnum *INPUT { PetscEnum const * } %typemap(argout) PetscEnum const* ""; %apply PetscEnum *OUTPUT { PetscEnum * } %define %petsc4py_enum(EnumType) %apply PetscEnum { EnumType } %apply PetscEnum * { EnumType * } %apply PetscEnum *INPUT { EnumType *INPUT } %apply PetscEnum *OUTPUT { EnumType *OUTPUT } %apply PetscEnum *INOUT { EnumType *INOUT } %enddef /* ---------------------------------------------------------------- */ %define %petsc4py_fragments(Pkg, PyType, Type, OBJECT_DEFAULT) /* AsVal */ /* ----- */ %fragment(SWIG_AsVal_frag(Type),"header") { SWIGINTERN int SWIG_AsVal_dec(Type)(SWIG_Object input, Type *v) { if (input == Py_None) { if (v) *v = OBJECT_DEFAULT; return SWIG_OK; } else if (PyObject_TypeCheck(input,&Py##Pkg##PyType##_Type)) { if (v) *v = Py##Pkg##PyType##_Get(input); return SWIG_OK; } else { void *argp = 0; int res = SWIG_ConvertPtr(input,&argp,%descriptor(p_##Type), 0); if (!SWIG_IsOK(res)) return res; if (!argp) return SWIG_ValueError; if (v) *v = *(%static_cast(argp,Type*)); return SWIG_OK; } } } /* AsPtr */ /* ----- */ %fragment(SWIG_AsPtr_frag(Type),"header", fragment=%fragment_name(GetPtr,Type)) { SWIGINTERN int SWIG_AsPtr_dec(Type)(SWIG_Object input, Type **p) { if (input == Py_None) { if (p) *p = 0; return SWIG_OK; } else if (PyObject_TypeCheck(input,&Py##Pkg##PyType##_Type)) { if (p) *p = Py##Pkg##PyType##_GetPtr(input); return SWIG_OK; } else { void *argp = 0; int res = SWIG_ConvertPtr(input,&argp,%descriptor(p_##Type), 0); if (!SWIG_IsOK(res)) return res; if (!argp) return SWIG_ValueError; if (p) *p = %static_cast(argp,Type*); return SWIG_OK; } } } /* From */ /* ---- */ %fragment(SWIG_From_frag(Type),"header") { SWIGINTERN SWIG_Object SWIG_From_dec(Type)(Type v) { return Py##Pkg##PyType##_New(v); } } %enddef /*petsc4py_fragments*/ /* ---------------------------------------------------------------- */ /* MPI Communicator */ /* ---------------------------------------------------------------- */ %define SWIG_TYPECHECK_MPI_COMM 600 %enddef %define %petsc4py_comm(Pkg, PyType, Type, CODE, OBJECT_NULL) /* pointer type */ %types(Type*); /* XXX find better way */ /* fragments */ %fragment(%fragment_name(GetPtr,MPI_Comm),"header") { } %petsc4py_fragments(Pkg, PyType, Type, PETSC_COMM_WORLD) /* base typemaps */ %typemaps_asvalfromn(%checkcode(MPI_COMM), Type); /* custom typemaps */ %typemap(check,noblock=1) Type { if ($1 == OBJECT_NULL) %argument_nullref("$ltype",$symname,$argnum); } %enddef /* %petsc4py_comm */ /* ---------------------------------------------------------------- */ /* PETSc Objects */ /* ---------------------------------------------------------------- */ %define SWIG_TYPECHECK_PETSC_OBJECT 500 %enddef %define SWIG_TYPECHECK_PETSC_VIEWER 501 %enddef %define SWIG_TYPECHECK_PETSC_RANDOM 502 %enddef %define SWIG_TYPECHECK_PETSC_DEVICE_CONTEXT 503 %enddef %define SWIG_TYPECHECK_PETSC_IS 510 %enddef %define SWIG_TYPECHECK_PETSC_IS_LTOGM 511 %enddef %define SWIG_TYPECHECK_PETSC_SF 512 %enddef %define SWIG_TYPECHECK_PETSC_VEC 513 %enddef %define SWIG_TYPECHECK_PETSC_VEC_SCATTER 514 %enddef %define SWIG_TYPECHECK_PETSC_SECTION 515 %enddef %define SWIG_TYPECHECK_PETSC_MAT 520 %enddef %define SWIG_TYPECHECK_PETSC_MAT_PARTITIONING 521 %enddef %define SWIG_TYPECHECK_PETSC_MAT_NULLSPACE 522 %enddef %define SWIG_TYPECHECK_PETSC_KSP 530 %enddef %define SWIG_TYPECHECK_PETSC_PC 531 %enddef %define SWIG_TYPECHECK_PETSC_SNES 532 %enddef %define SWIG_TYPECHECK_PETSC_TS 533 %enddef %define SWIG_TYPECHECK_PETSC_TAO 534 %enddef %define SWIG_TYPECHECK_PETSC_AO 540 %enddef %define SWIG_TYPECHECK_PETSC_DM 541 %enddef %define SWIG_TYPECHECK_PETSC_DS 542 %enddef %define SWIG_TYPECHECK_PETSC_PARTITIONER 543 %enddef %define SWIG_TYPECHECK_PETSC_FE 550 %enddef %define SWIG_TYPECHECK_PETSC_QUADRATURE 551 %enddef %define SWIG_TYPECHECK_PETSC_SPACE 552 %enddef %define SWIG_TYPECHECK_PETSC_DUALSPACE 553 %enddef %define SWIG_TYPECHECK_PETSC_DMLABEL 560 %enddef %define %petsc4py_objt(Pkg, PyType, Type, CODE) /* pointer type */ %types(Type*); /* XXX find better way */ /* fragments */ %fragment(%fragment_name(GetPtr,Type),"header") { /* XXX implement this better*/ %define_as(Py##Pkg##PyType##_GetPtr(ob), (Type *)PyPetscObject_GetPtr(ob)) } %petsc4py_fragments(Pkg, PyType, Type, NULL) /* base typemaps */ %typemaps_asptrfromn(%checkcode(CODE), Type); /* Custom Typemaps */ /* --------------- */ /* freearg */ %typemap(freearg) Type, Type*, Type& ""; /* check */ %typemap(check,noblock=1) Type INPUT { if ($1 == NULL) %argument_nullref("$type", $symname, $argnum); } /* input pointer */ %typemap(in,fragment=SWIG_AsPtr_frag(Type)) Type *INPUT (int res = SWIG_OLDOBJ) { Type *ptr = (Type *)0; res = SWIG_AsPtr(Type)($input, &ptr); if (!SWIG_IsOK(res)) { %argument_fail(res,"$type", $symname, $argnum); } $1 = ptr; } %typemap(check,noblock=1) Type *INPUT { if ($1 == NULL || (*$1) == NULL) %argument_nullref("$type", $symname, $argnum); } /* input reference */ %apply Type *INPUT { Type& } /* optional value */ %typemap(arginit) Type OPTIONAL "$1 = NULL;" %typemap(in,fragment=SWIG_AsPtr_frag(Type)) Type OPTIONAL (int res = 0) { Type *ptr = (Type *)0; res = SWIG_AsPtr(Type)($input, &ptr); if (!SWIG_IsOK(res)) { %argument_fail(res, "$type", $symname, $argnum); } if (ptr) $1 = *ptr; } /* optional reference */ %typemap(in,fragment=SWIG_AsPtr_frag(Type)) Type& OPTIONAL (int res = 0) { Type *ptr = (Type *)0; res = SWIG_AsPtr(Type)($input, &ptr); if (!SWIG_IsOK(res)) { %argument_fail(res, "$type", $symname, $argnum); } if (!ptr) %argument_nullref("$type", $symname, $argnum); $1 = ptr; if (SWIG_IsNewObj(res)) %delete(ptr); } %typemap(in,numinputs=0) Type* OUTREF, Type* OUTNEW ($*ltype temp = NULL) "$1 = &temp;"; %typemap(freearg) Type* OUTREF, Type* OUTNEW ""; %typemap(check) Type* OUTREF, Type* OUTNEW ""; %typemap(argout) Type* OUTREF { SWIG_Object o = Py##Pkg##PyType##_New(*$1); %append_output(o); } %typemap(argout) Type* OUTNEW { SWIG_Object o = Py##Pkg##PyType##_New(*$1); if (o!=NULL) PetscObjectDereference((PetscObject)(*$1)); %append_output(o); } %apply Type OPTIONAL { Type MAYBE } %apply Type& OPTIONAL { Type& MAYBE } %apply Type* OUTNEW { Type* NEWOBJ } %apply Type* OUTREF { Type* NEWREF } %enddef /* %petsc4py_objt */ /* ---------------------------------------------------------------- */ /* */ /* ---------------------------------------------------------------- */ %petsc4py_errt( Petsc , Error , PetscErrorCode ) %petsc4py_numt( Petsc , Int , PetscInt , PETSC_INT , 0 ) %petsc4py_numt( Petsc , Real , PetscReal , PETSC_REAL , 0 ) %petsc4py_numt( Petsc , Complex , PetscComplex , PETSC_COMPLEX , 0 ) %petsc4py_numt( Petsc , Scalar , PetscScalar , PETSC_SCALAR , 0 ) %petsc4py_comm( Petsc, Comm , MPI_Comm , MPI_COMM , MPI_COMM_NULL ) %petsc4py_objt( Petsc , Object , PetscObject , PETSC_OBJECT ) %petsc4py_objt( Petsc , Viewer , PetscViewer , PETSC_VIEWER ) %petsc4py_objt( Petsc , Random , PetscRandom , PETSC_RANDOM ) %petsc4py_objt( Petsc , DeviceContext , PetscDeviceContext , PETSC_DEVICE_CONTEXT ) %petsc4py_objt( Petsc , IS , IS , PETSC_IS ) %petsc4py_objt( Petsc , LGMap , ISLocalToGlobalMapping , PETSC_IS_LTOGM ) %petsc4py_objt( Petsc , SF , PetscSF , PETSC_SF ) %petsc4py_objt( Petsc , Vec , Vec , PETSC_VEC ) %petsc4py_objt( Petsc , Scatter , VecScatter , PETSC_VEC_SCATTER ) %petsc4py_objt( Petsc , Section , PetscSection , PETSC_SECTION ) %petsc4py_objt( Petsc , Mat , Mat , PETSC_MAT ) %petsc4py_objt( Petsc , MatPartitioning, MatPartitioning , PETSC_MAT_PARTITIONING ) %petsc4py_objt( Petsc , NullSpace , MatNullSpace , PETSC_MAT_NULLSPACE ) %petsc4py_objt( Petsc , KSP , KSP , PETSC_KSP ) %petsc4py_objt( Petsc , PC , PC , PETSC_PC ) %petsc4py_objt( Petsc , SNES , SNES , PETSC_SNES ) %petsc4py_objt( Petsc , TS , TS , PETSC_TS ) %petsc4py_objt( Petsc , TAO , Tao , PETSC_TAO ) %petsc4py_objt( Petsc , AO , AO , PETSC_AO ) %petsc4py_objt( Petsc , DM , DM , PETSC_DM ) %petsc4py_objt( Petsc , DS , PetscDS , PETSC_DS ) %petsc4py_objt( Petsc , Partitioner , PetscPartitioner , PETSC_PARTITIONER ) %petsc4py_objt( Petsc , FE , PetscFE , PETSC_FE ) %petsc4py_objt( Petsc , Quad , PetscQuadrature , PETSC_QUADRATURE ) %petsc4py_objt( Petsc , Space , PetscSpace , PETSC_SPACE ) %petsc4py_objt( Petsc , DualSpace , PetscDualSpace , PETSC_DUALSPACE ) %petsc4py_objt( Petsc , DMLabel , PetscDMLabel , PETSC_DMLABEL ) /* ---------------------------------------------------------------- */ /* * Local Variables: * mode: C * End: */ petsc4py-3.19.6/src/petsc4py/include/petsc4py/pybuffer.h000066400000000000000000000056541454104047300231340ustar00rootroot00000000000000#ifndef PETSC4PY_PYBUFFER_H #define PETSC4PY_PYBUFFER_H #include #include #if defined(PETSC_USE_64BIT_INDICES) # define _PyPetsc_FMT_PETSC_INT "q" #else # define _PyPetsc_FMT_PETSC_INT "i" #endif #if defined(PETSC_USE_REAL_SINGLE) # define _PyPetsc_FMT_PETSC_REAL "f" # define _PyPetsc_FMT_PETSC_COMPLEX "Zf" #elif defined(PETSC_USE_REAL_DOUBLE) # define _PyPetsc_FMT_PETSC_REAL "d" # define _PyPetsc_FMT_PETSC_COMPLEX "Zd" #elif defined(PETSC_USE_REAL_LONG_DOUBLE) # define _PyPetsc_FMT_PETSC_REAL "g" # define _PyPetsc_FMT_PETSC_COMPLEX "Zg" #elif defined(PETSC_USE_REAL___FLOAT128) # define _PyPetsc_FMT_PETSC_REAL "g" # define _PyPetsc_FMT_PETSC_COMPLEX "Zg" #else # error "unsupported real precision" #endif #if defined(PETSC_USE_COMPLEX) # define _PyPetsc_FMT_PETSC_SCALAR _PyPetsc_FMT_PETSC_COMPLEX #else # define _PyPetsc_FMT_PETSC_SCALAR _PyPetsc_FMT_PETSC_REAL #endif static inline int PyPetscBuffer_FillInfo(Py_buffer *view, void *buf, PetscInt count, char typechar, int readonly, int flags) { if (view == NULL) return 0; if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && (readonly == 1)) { PyErr_SetString(PyExc_BufferError, "Object is not writable."); return -1; } view->buf = buf; switch (typechar) { case 'i': view->itemsize = sizeof(PetscInt); break; case 'r': view->itemsize = sizeof(PetscReal); break; case 's': view->itemsize = sizeof(PetscScalar); break; case 'c': view->itemsize = sizeof(PetscReal)*2; break; default: view->itemsize = 1; } view->len = count*view->itemsize; view->readonly = readonly; view->format = NULL; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { switch (typechar) { case 'i': view->format = (char *) _PyPetsc_FMT_PETSC_INT; break; case 'r': view->format = (char *) _PyPetsc_FMT_PETSC_REAL; break; case 's': view->format = (char *) _PyPetsc_FMT_PETSC_SCALAR; break; case 'c': view->format = (char *) _PyPetsc_FMT_PETSC_COMPLEX; break; default: view->format = (char *) "B"; } } view->ndim = 0; view->shape = NULL; view->strides = NULL; view->suboffsets = NULL; view->internal = NULL; if ((flags & PyBUF_ND) == PyBUF_ND) { view->ndim = 1; view->internal = PyMem_Malloc(2*sizeof(Py_ssize_t)); if (!view->internal) { PyErr_NoMemory(); return -1; } view->shape = (Py_ssize_t *) view->internal; view->shape[0] = view->len/view->itemsize; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = view->shape + 1; view->strides[0] = view->itemsize; } } return 0; } static inline void PyPetscBuffer_Release(Py_buffer *view) { if (view == NULL) return; if (view->internal) PyMem_Free(view->internal); view->internal = NULL; } #undef _PyPetsc_FMT_PETSC_INT #undef _PyPetsc_FMT_PETSC_REAL #undef _PyPetsc_FMT_PETSC_SCALAR #undef _PyPetsc_FMT_PETSC_COMPLEX #endif/*!PETSC4PY_PYBUFFER_H*/ petsc4py-3.19.6/src/petsc4py/include/petsc4py/pyscalar.h000066400000000000000000000013201454104047300231120ustar00rootroot00000000000000#ifndef PETSC4PY_PYSCALAR_H #define PETSC4PY_PYSCALAR_H #include #include static inline PyObject *PyPetscScalar_FromPetscScalar(PetscScalar s) { #if defined(PETSC_USE_COMPLEX) double a = (double)PetscRealPart(s); double b = (double)PetscImaginaryPart(s); return PyComplex_FromDoubles(a, b); #else return PyFloat_FromDouble((double)s); #endif } static inline PetscScalar PyPetscScalar_AsPetscScalar(PyObject *o) { #if defined(PETSC_USE_COMPLEX) Py_complex cval = PyComplex_AsCComplex(o); PetscReal a = (PetscReal)cval.real; PetscReal b = (PetscReal)cval.imag; return a + b * PETSC_i; #else return (PetscScalar)PyFloat_AsDouble(o); #endif } #endif/*PETSC4PY_PYSCALAR_H*/ petsc4py-3.19.6/src/petsc4py/lib/000077500000000000000000000000001454104047300164775ustar00rootroot00000000000000petsc4py-3.19.6/src/petsc4py/lib/__init__.py000066400000000000000000000141101454104047300206050ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # -------------------------------------------------------------------- """ Extension modules for different PETSc configurations. PETSc 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 PETSc extension module built against specific PETSc configurations. It also provides a convenience function using of the ``importlib`` 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. """ # -------------------------------------------------------------------- def ImportPETSc(arch=None): """ Import the PETSc extension module for a given configuration name. """ path, arch = getPathArchPETSc(arch) return Import('petsc4py', 'PETSc', path, arch) def getPathArchPETSc(arch=None): """ Undocumented. """ import os path = os.path.abspath(os.path.dirname(__file__)) rcvar, rcfile = 'PETSC_ARCH', 'petsc.cfg' path, arch = getPathArch(path, arch, rcvar, rcfile) return (path, arch) # -------------------------------------------------------------------- def Import(pkg, name, path, arch): """ Import helper for PETSc-based extension modules. """ import os import sys import warnings try: import importlib.machinery import importlib.util except ImportError: importlib = None import imp def get_ext_suffix(): if importlib: return importlib.machinery.EXTENSION_SUFFIXES[0] else: return imp.get_suffixes()[0][0] def import_module(pkg, name, path, arch): fullname = '{}.{}'.format(pkg, name) pathlist = [os.path.join(path, arch)] if importlib: finder = importlib.machinery.PathFinder() spec = finder.find_spec(fullname, pathlist) module = importlib.util.module_from_spec(spec) sys.modules[fullname] = module spec.loader.exec_module(module) return module else: f, fn, info = imp.find_module(name, pathlist) with f: return imp.load_module(fullname, f, fn, info) # test if extension module was already imported module = sys.modules.get('{}.{}'.format(pkg, name)) filename = getattr(module, '__file__', '') if filename.endswith(get_ext_suffix()): # if 'arch' is None, do nothing; otherwise this # call may be invalid if extension module for # other 'arch' has been already imported. if arch is not None and arch != module.__arch__: raise ImportError("%s already imported" % module) return module # silence annoying Cython warning warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ndarray size changed") # import extension module from 'path/arch' directory module = import_module(pkg, name, path, arch) module.__arch__ = arch # save arch value setattr(sys.modules[pkg], name, module) return module def getPathArch(path, arch, rcvar='PETSC_ARCH', rcfile='petsc.cfg'): """ Undocumented. """ import os import warnings # path if not path: path = '.' elif os.path.isfile(path): path = os.path.dirname(path) elif not os.path.isdir(path): raise ValueError("invalid path: '%s'" % path) # arch if arch is not None: if not isinstance(arch, str): raise TypeError( "arch argument must be string") if not os.path.isdir(os.path.join(path, arch)): raise TypeError("invalid arch value: '%s'" % arch) return (path, arch) # helper function def arch_list(arch): arch = arch.strip().split(os.path.pathsep) arch = [a.strip() for a in arch if a] arch = [a for a in arch if a] return arch # try to get arch from the environment arch_env = arch_list(os.environ.get(rcvar, '')) for arch in arch_env: if os.path.isdir(os.path.join(path, arch)): return (path, arch) # configuration file if not os.path.isfile(rcfile): rcfile = os.path.join(path, rcfile) if not os.path.isfile(rcfile): # now point to continue return (path, '') # helper function def parse_rc(rcfile): with open(rcfile) as f: rcdata = f.read() lines = [ln.strip() for ln in rcdata.splitlines()] lines = [ln for ln in lines if not ln.startswith('#')] entries = [ln.split('=') for ln in lines if ln] entries = [(k.strip(), v.strip()) for k, v in entries] return dict(entries) # try to get arch from data in config file configrc = parse_rc(rcfile) arch_cfg = arch_list(configrc.get(rcvar, '')) for arch in arch_cfg: if os.path.isdir(os.path.join(path, arch)): if arch_env: warnings.warn( "ignored arch: '%s', using: '%s'" % \ (os.path.pathsep.join(arch_env), arch)) return (path, arch) # nothing good found return (path, '') def getInitArgs(args): """ Undocumented. """ import shlex import sys if args is None: args = [] elif isinstance(args, str): args = shlex.split(args) else: args = [str(a) for a in args] args = [a for a in args if a] if args and args[0].startswith('-'): sys_argv = getattr(sys, 'argv', None) sys_exec = getattr(sys, 'executable', 'python') if (sys_argv and sys_argv[0] and sys_argv[0] != '-c'): prog_name = sys_argv[0] else: prog_name = sys_exec args.insert(0, prog_name) return args # -------------------------------------------------------------------- petsc4py-3.19.6/src/petsc4py/lib/petsc.cfg000066400000000000000000000000671454104047300203010ustar00rootroot00000000000000PETSC_DIR = %(PETSC_DIR)s PETSC_ARCH = %(PETSC_ARCH)s petsc4py-3.19.6/test/000077500000000000000000000000001454104047300143465ustar00rootroot00000000000000petsc4py-3.19.6/test/runtests.py000066400000000000000000000170511454104047300166130ustar00rootroot00000000000000# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com import os import sys import optparse import unittest __unittest = True components = [ 'PETSc', ] 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') 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 = [ ('*%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()) petsc4py-3.19.6/test/test_comm.py000066400000000000000000000057261454104047300167240ustar00rootroot00000000000000from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class TestComm(unittest.TestCase): def testInit(self): comm_null1 = PETSc.Comm() comm_null2 = PETSc.Comm(PETSc.COMM_NULL) comm_world = PETSc.Comm(PETSc.COMM_WORLD) comm_self = PETSc.Comm(PETSc.COMM_SELF) self.assertEqual(comm_null1, PETSc.COMM_NULL) self.assertEqual(comm_null2, PETSc.COMM_NULL) self.assertEqual(comm_world, PETSc.COMM_WORLD) self.assertEqual(comm_self, PETSc.COMM_SELF) def testDupDestr(self): self.assertRaises(ValueError, PETSc.COMM_NULL.duplicate) comm = PETSc.COMM_SELF.duplicate() comm.destroy() self.assertEqual(comm, PETSc.COMM_NULL) del comm comm = PETSc.COMM_WORLD.duplicate() comm.destroy() self.assertEqual(comm, PETSc.COMM_NULL) del comm def testBarrier(self): self.assertRaises(ValueError, PETSc.COMM_NULL.barrier) PETSc.COMM_SELF.barrier() PETSc.COMM_WORLD.barrier() def testSize(self): self.assertRaises(ValueError, PETSc.COMM_NULL.getSize) self.assertTrue(PETSc.COMM_WORLD.getSize() >= 1) self.assertEqual(PETSc.COMM_SELF.getSize(), 1) def testRank(self): self.assertRaises(ValueError, PETSc.COMM_NULL.getRank) self.assertEqual(PETSc.COMM_SELF.getRank(), 0) self.assertTrue(PETSc.COMM_WORLD.getRank() >= 0) def testProperties(self): self.assertEqual(PETSc.COMM_SELF.getSize(), PETSc.COMM_SELF.size) self.assertEqual(PETSc.COMM_SELF.getRank(), PETSc.COMM_SELF.rank) self.assertEqual(PETSc.COMM_WORLD.getSize(), PETSc.COMM_WORLD.size) self.assertEqual(PETSc.COMM_WORLD.getRank(), PETSc.COMM_WORLD.rank) def testCompatMPI4PY(self): try: from mpi4py import MPI except ImportError: return # mpi4py -> petsc4py cn = PETSc.Comm(MPI.COMM_NULL) cs = PETSc.Comm(MPI.COMM_SELF) cw = PETSc.Comm(MPI.COMM_WORLD) self.assertEqual(cn, PETSc.COMM_NULL) self.assertEqual(cs, PETSc.COMM_SELF) self.assertEqual(cw, PETSc.COMM_WORLD) # petsc4py - > mpi4py cn = PETSc.COMM_NULL.tompi4py() self.assertTrue(isinstance(cn, MPI.Comm)) self.assertFalse(cn) cs = PETSc.COMM_SELF.tompi4py() self.assertTrue(isinstance(cs, MPI.Intracomm)) self.assertEqual(cs.Get_size(), 1) self.assertEqual(cs.Get_rank(), 0) cw = PETSc.COMM_WORLD.tompi4py() self.assertTrue(isinstance(cw, MPI.Intracomm)) self.assertEqual(cw.Get_size(), PETSc.COMM_WORLD.getSize()) self.assertEqual(cw.Get_rank(), PETSc.COMM_WORLD.getRank()) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_dmda.py000066400000000000000000000362701454104047300166740ustar00rootroot00000000000000from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestDA(object): COMM = PETSc.COMM_WORLD SIZES = None BOUNDARY = None DOF = 1 STENCIL = PETSc.DMDA.StencilType.STAR SWIDTH = 1 def setUp(self): self.da = PETSc.DMDA().create(dim=len(self.SIZES), dof=self.DOF, sizes=self.SIZES, boundary_type=self.BOUNDARY, stencil_type=self.STENCIL, stencil_width=self.SWIDTH, comm=self.COMM) def tearDown(self): self.da = None PETSc.garbage_cleanup() def testGetInfo(self): dim = self.da.getDim() dof = self.da.getDof() sizes = self.da.getSizes() psizes = self.da.getProcSizes() boundary = self.da.getBoundaryType() stencil_type = self.da.getStencilType() stencil_width = self.da.getStencilWidth() self.assertEqual(dim, len(self.SIZES)) self.assertEqual(dof, self.DOF) self.assertEqual(sizes, tuple(self.SIZES)) self.assertEqual(boundary, self.BOUNDARY or (0,)*dim) self.assertEqual(stencil_type, self.STENCIL) self.assertEqual(stencil_width, self.SWIDTH) def testRangesCorners(self): dim = self.da.getDim() ranges = self.da.getRanges() starts, lsizes = self.da.getCorners() self.assertEqual(dim, len(ranges)) self.assertEqual(dim, len(starts)) self.assertEqual(dim, len(lsizes)) for i in range(dim): s, e = ranges[i] self.assertEqual(s, starts[i]) self.assertEqual(e-s, lsizes[i]) def testGhostRangesCorners(self): dim = self.da.getDim() ranges = self.da.getGhostRanges() starts, lsizes = self.da.getGhostCorners() self.assertEqual(dim, len(ranges)) self.assertEqual(dim, len(starts)) self.assertEqual(dim, len(lsizes)) for i in range(dim): s, e = ranges[i] self.assertEqual(s, starts[i]) self.assertEqual(e-s, lsizes[i]) def testOwnershipRanges(self): dim = self.da.getDim() ownership_ranges = self.da.getOwnershipRanges() procsizes = self.da.getProcSizes() self.assertEqual(len(procsizes), len(ownership_ranges)) for i,m in enumerate(procsizes): self.assertEqual(m, len(ownership_ranges[i])) def testFieldName(self): for i in range(self.da.getDof()): self.da.setFieldName(i, "field%d" % i) for i in range(self.da.getDof()): name = self.da.getFieldName(i) self.assertEqual(name, "field%d" % i) def testCoordinates(self): self.da.setUniformCoordinates(0,1,0,1,0,1) # c = self.da.getCoordinates() self.da.setCoordinates(c) c.destroy() cda = self.da.getCoordinateDM() cda.destroy() # c = self.da.getCoordinates() self.da.setCoordinates(c) c.destroy() gc = self.da.getCoordinatesLocal() gc.destroy() def testCreateVecMat(self): vn = self.da.createNaturalVec() vg = self.da.createGlobalVec() vl = self.da.createLocalVec() mat = self.da.createMat() self.assertTrue(mat.getType() in ('aij', 'seqaij', 'mpiaij')) vn.set(1.0) self.da.naturalToGlobal(vn,vg) self.assertEqual(vg.max()[1], 1.0) self.assertEqual(vg.min()[1], 1.0) self.da.globalToLocal(vg,vl) self.assertEqual(vl.max()[1], 1.0) self.assertTrue (vl.min()[1] in (1.0, 0.0)) vn.set(0.0) self.da.globalToNatural(vg,vn) self.assertEqual(vn.max()[1], 1.0) self.assertEqual(vn.min()[1], 1.0) vl2 = self.da.createLocalVec() self.da.localToLocal(vl,vl2) self.assertEqual(vl2.max()[1], 1.0) self.assertTrue (vl2.min()[1] in (1.0, 0.0)) NONE = PETSc.DM.BoundaryType.NONE s = self.da.stencil_width btype = self.da.boundary_type psize = self.da.proc_sizes for b, p in zip(btype, psize): if b != NONE and p == 1: return vg2 = self.da.createGlobalVec() self.da.localToGlobal(vl2,vg2) def testGetVec(self): vg = self.da.getGlobalVec() vl = self.da.getLocalVec() try: vg.set(1.0) self.assertEqual(vg.max()[1], 1.0) self.assertEqual(vg.min()[1], 1.0) self.da.globalToLocal(vg,vl) self.assertEqual(vl.max()[1], 1.0) self.assertTrue (vl.min()[1] in (1.0, 0.0)) vl.set(2.0) NONE = PETSc.DM.BoundaryType.NONE s = self.da.stencil_width btype = self.da.boundary_type psize = self.da.proc_sizes for b, p in zip(btype, psize): if b != NONE and p == 1: return self.da.localToGlobal(vl,vg) self.assertEqual(vg.max()[1], 2.0) self.assertTrue (vg.min()[1] in (2.0, 0.0)) finally: self.da.restoreGlobalVec(vg) self.da.restoreLocalVec(vl) def testGetOther(self): ao = self.da.getAO() lgmap = self.da.getLGMap() l2g, g2l = self.da.getScatter() def testRefineCoarsen(self): da = self.da rda = da.refine() self.assertEqual(da.getDim(), rda.getDim()) self.assertEqual(da.getDof(), rda.getDof()) if da.dim != 1: self.assertEqual(da.getStencilType(), rda.getStencilType()) self.assertEqual(da.getStencilWidth(), rda.getStencilWidth()) cda = rda.coarsen() self.assertEqual(rda.getDim(), cda.getDim()) self.assertEqual(rda.getDof(), cda.getDof()) for n1, n2 in zip(self.da.getSizes(), cda.getSizes()): self.assertTrue(abs(n1-n2)<=1) def testCoarsenRefine(self): da = self.da cda = self.da.coarsen() self.assertEqual(da.getDim(), cda.getDim()) self.assertEqual(da.getDof(), cda.getDof()) if da.dim != 1: self.assertEqual(da.getStencilType(), cda.getStencilType()) self.assertEqual(da.getStencilWidth(), cda.getStencilWidth()) rda = cda.refine() for n1, n2 in zip(self.da.getSizes(), rda.getSizes()): self.assertTrue(abs(n1-n2)<=1) def testRefineHierarchy(self): levels = self.da.refineHierarchy(2) self.assertTrue(isinstance(levels, list)) self.assertEqual(len(levels), 2) for item in levels: self.assertTrue(isinstance(item, PETSc.DM)) def testCoarsenHierarchy(self): levels = self.da.coarsenHierarchy(2) self.assertTrue(isinstance(levels, list)) self.assertEqual(len(levels), 2) for item in levels: self.assertTrue(isinstance(item, PETSc.DM)) def testCreateInterpolation(self): da = self.da if da.dim == 1: return rda = da.refine() mat, vec = da.createInterpolation(rda) def testCreateInjection(self): da = self.da if da.dim == 1: return rda = da.refine() scatter = da.createInjection(rda) def testzeroRowsColumnsStencil(self): da = self.da A = da.createMatrix() x = da.createGlobalVector() x.set(2.0) A.setDiagonal(x) diag1 = x.duplicate() A.getDiagonal(diag1) if self.SIZES != 2: #only coded test for 2D case return istart,iend, jstart, jend = da.getRanges() self.assertTrue(x.equal(diag1)) zeroidx = [] for i in range(istart,iend): for j in range(jstart,jend): row = PETSc.Mat.Stencil() row.index = (i,j) zeroidx = zeroidx + [row] diag2 = x.duplicate() diag2.set(1.0) A.zeroRowsColumnsStencil(zeroidx, 1.0, x, diag2) ans = x.duplicate() ans.set(2.0) self.assertTrue(ans.equal(diag2)) MIRROR = PETSc.DMDA.BoundaryType.MIRROR GHOSTED = PETSc.DMDA.BoundaryType.GHOSTED PERIODIC = PETSc.DMDA.BoundaryType.PERIODIC TWIST = PETSc.DMDA.BoundaryType.TWIST SCALE = 4 class BaseTestDA_1D(BaseTestDA): SIZES = [100*SCALE] class BaseTestDA_2D(BaseTestDA): SIZES = [9*SCALE,11*SCALE] class BaseTestDA_3D(BaseTestDA): SIZES = [6*SCALE,7*SCALE,8*SCALE] # -------------------------------------------------------------------- class TestDA_1D(BaseTestDA_1D, unittest.TestCase): pass class TestDA_1D_W0(TestDA_1D): SWIDTH = 0 class TestDA_1D_W2(TestDA_1D): SWIDTH = 2 class TestDA_2D(BaseTestDA_2D, unittest.TestCase): pass class TestDA_2D_W0(TestDA_2D): SWIDTH = 0 class TestDA_2D_W0_N2(TestDA_2D): DOF = 2 SWIDTH = 0 class TestDA_2D_W2(TestDA_2D): SWIDTH = 2 class TestDA_2D_W2_N2(TestDA_2D): DOF = 2 SWIDTH = 2 class TestDA_2D_PXY(TestDA_2D): SIZES = [13*SCALE,17*SCALE] DOF = 2 SWIDTH = 5 BOUNDARY = (PERIODIC,)*2 class TestDA_2D_GXY(TestDA_2D): SIZES = [13*SCALE,17*SCALE] DOF = 2 SWIDTH = 5 BOUNDARY = (GHOSTED,)*2 class TestDA_2D_TXY(TestDA_2D): SIZES = [13*SCALE,17*SCALE] DOF = 2 SWIDTH = 5 BOUNDARY = (TWIST,)*2 class TestDA_3D(BaseTestDA_3D, unittest.TestCase): pass class TestDA_3D_W0(TestDA_3D): SWIDTH = 0 class TestDA_3D_W0_N2(TestDA_3D): DOF = 2 SWIDTH = 0 class TestDA_3D_W2(TestDA_3D): SWIDTH = 2 class TestDA_3D_W2_N2(TestDA_3D): DOF = 2 SWIDTH = 2 class TestDA_3D_PXYZ(TestDA_3D): SIZES = [11*SCALE,13*SCALE,17*SCALE] DOF = 2 SWIDTH = 3 BOUNDARY = (PERIODIC,)*3 class TestDA_3D_GXYZ(TestDA_3D): SIZES = [11*SCALE,13*SCALE,17*SCALE] DOF = 2 SWIDTH = 3 BOUNDARY = (GHOSTED,)*3 class TestDA_3D_TXYZ(TestDA_3D): SIZES = [11*SCALE,13*SCALE,17*SCALE] DOF = 2 SWIDTH = 3 BOUNDARY = (TWIST,)*3 # -------------------------------------------------------------------- DIM = (1,2,3,) DOF = (None,1,2,3,4,5,) BOUNDARY_TYPE = ( None, "none", (0,)*3, 0, "ghosted", (GHOSTED,)*3, GHOSTED, "periodic", (PERIODIC,)*3, PERIODIC, "twist", (TWIST,)*3, TWIST, ) STENCIL_TYPE = (None,"star","box") STENCIL_WIDTH = (None,0,1,2,3) DIM = (1,2,3) DOF = (None,2,5) BOUNDARY_TYPE = (None,"none","periodic","ghosted","twist") STENCIL_TYPE = (None,"box") STENCIL_WIDTH = (None,1,2) class TestDACreate(unittest.TestCase): pass counter = 0 for dim in DIM: for dof in DOF: for boundary in BOUNDARY_TYPE: if isinstance(boundary, tuple): boundary = boundary[:dim] for stencil in STENCIL_TYPE: for width in STENCIL_WIDTH: kargs = dict(sizes=[8*SCALE]*dim, dim=dim, dof=dof, boundary_type=boundary, stencil_type=stencil, stencil_width=width) def testCreate(self, kargs=kargs): kargs = dict(kargs) da = PETSc.DMDA().create(**kargs) da.destroy() setattr(TestDACreate, "testCreate%04d"%counter, testCreate) del testCreate, kargs counter += 1 del counter, dim, dof, boundary, stencil, width class TestDADuplicate(unittest.TestCase): pass counter = 0 for dim in DIM: for dof in DOF: for boundary in BOUNDARY_TYPE: if isinstance(boundary, tuple): boundary = boundary[:dim] for stencil in STENCIL_TYPE: for width in STENCIL_WIDTH: kargs = dict(dim=dim, dof=dof, boundary_type=boundary, stencil_type=stencil, stencil_width=width) def testDuplicate(self, kargs=kargs): kargs = dict(kargs) dim = kargs.pop('dim') dof = kargs['dof'] boundary = kargs['boundary_type'] stencil = kargs['stencil_type'] width = kargs['stencil_width'] da = PETSc.DMDA().create([8*SCALE]*dim) newda = da.duplicate(**kargs) self.assertEqual(newda.dim, da.dim) self.assertEqual(newda.sizes, da.sizes) self.assertEqual(newda.proc_sizes, da.proc_sizes) self.assertEqual(newda.ranges, da.ranges) self.assertEqual(newda.corners, da.corners) if (newda.boundary_type == da.boundary_type and newda.stencil_width == da.stencil_width): self.assertEqual(newda.ghost_ranges, da.ghost_ranges) self.assertEqual(newda.ghost_corners, da.ghost_corners) if dof is None: dof = da.dof if boundary is None: boundary = da.boundary_type elif boundary == "none": boundary = (0,) * dim elif boundary == "mirror": boundary = (MIRROR,) * dim elif boundary == "ghosted": boundary = (GHOSTED,) * dim elif boundary == "periodic": boundary = (PERIODIC,) * dim elif boundary == "twist": boundary = (TWIST,) * dim elif isinstance(boundary, int): boundary = (boundary,) * dim if stencil is None: stencil = da.stencil[0] if width is None: width = da.stencil_width self.assertEqual(newda.dof, dof) self.assertEqual(newda.boundary_type, boundary) if dim == 1: self.assertEqual(newda.stencil, (stencil, width)) newda.destroy() da.destroy() setattr(TestDADuplicate, "testDuplicate%04d"%counter, testDuplicate) del testDuplicate, kargs counter += 1 del counter, dim, dof, boundary, stencil, width # -------------------------------------------------------------------- if PETSc.COMM_WORLD.getSize() > 1: del TestDA_1D_W0 del TestDA_2D_W0, TestDA_2D_W0_N2 del TestDA_3D_W0, TestDA_3D_W0_N2 # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_dmplex.py000066400000000000000000000507641454104047300172640ustar00rootroot00000000000000import petsc4py from petsc4py import PETSc import unittest import os import filecmp import numpy as np # -------------------------------------------------------------------- ERR_ARG_OUTOFRANGE = 63 class BaseTestPlex(object): COMM = PETSc.COMM_WORLD DIM = 1 CELLS = [[0, 1], [1, 2]] COORDS = [[0.], [0.5], [1.]] COMP = 1 DOFS = [1, 0] def setUp(self): self.plex = PETSc.DMPlex().createFromCellList(self.DIM, self.CELLS, self.COORDS, comm=self.COMM) def tearDown(self): self.plex.destroy() self.plex = None PETSc.garbage_cleanup() def testTopology(self): rank = self.COMM.rank dim = self.plex.getDimension() pStart, pEnd = self.plex.getChart() cStart, cEnd = self.plex.getHeightStratum(0) vStart, vEnd = self.plex.getDepthStratum(0) numDepths = self.plex.getLabelSize("depth") coords_raw = self.plex.getCoordinates().getArray() coords = np.reshape(coords_raw, (vEnd - vStart, dim)) self.assertEqual(dim, self.DIM) self.assertEqual(numDepths, self.DIM+1) if rank == 0 and self.CELLS is not None: self.assertEqual(cEnd-cStart, len(self.CELLS)) if rank == 0 and self.COORDS is not None: self.assertEqual(vEnd-vStart, len(self.COORDS)) self.assertTrue((coords == self.COORDS).all()) def testClosure(self): pStart, pEnd = self.plex.getChart() for p in range(pStart, pEnd): closure = self.plex.getTransitiveClosure(p)[0] for c in closure: cone = self.plex.getCone(c) self.assertEqual(self.plex.getConeSize(c), len(cone)) for i in cone: self.assertIn(i, closure) star = self.plex.getTransitiveClosure(p, useCone=False)[0] for s in star: support = self.plex.getSupport(s) self.assertEqual(self.plex.getSupportSize(s), len(support)) for i in support: self.assertIn(i, star) def testAdjacency(self): PETSc.DMPlex.setAdjacencyUseAnchors(self.plex, False) flag = PETSc.DMPlex.getAdjacencyUseAnchors(self.plex) self.assertFalse(flag) PETSc.DMPlex.setAdjacencyUseAnchors(self.plex, True) flag = PETSc.DMPlex.getAdjacencyUseAnchors(self.plex) self.assertTrue(flag) PETSc.DMPlex.setBasicAdjacency(self.plex, False, False) flagA, flagB = PETSc.DMPlex.getBasicAdjacency(self.plex) self.assertFalse(flagA) self.assertFalse(flagB) PETSc.DMPlex.setBasicAdjacency(self.plex, True, True) flagA, flagB = PETSc.DMPlex.getBasicAdjacency(self.plex) self.assertTrue(flagA) self.assertTrue(flagB) pStart, pEnd = self.plex.getChart() for p in range(pStart, pEnd): adjacency = self.plex.getAdjacency(p) self.assertTrue(p in adjacency) self.assertTrue(len(adjacency) > 1) def testSectionDofs(self): self.plex.setNumFields(1) section = self.plex.createSection([self.COMP], [self.DOFS]) size = section.getStorageSize() entity_dofs = [self.plex.getStratumSize("depth", d) * self.DOFS[d] for d in range(self.DIM+1)] self.assertEqual(sum(entity_dofs), size) def testSectionClosure(self): section = self.plex.createSection([self.COMP], [self.DOFS]) self.plex.setSection(section) vec = self.plex.createLocalVec() pStart, pEnd = self.plex.getChart() for p in range(pStart, pEnd): for i in range(section.getDof(p)): off = section.getOffset(p) vec.setValue(off+i, p) for p in range(pStart, pEnd): point_closure = self.plex.getTransitiveClosure(p)[0] dof_closure = self.plex.vecGetClosure(section, vec, p) for p in dof_closure: self.assertIn(p, point_closure) def testBoundaryLabel(self): pStart, pEnd = self.plex.getChart() if (pEnd - pStart == 0): return self.assertFalse(self.plex.hasLabel("boundary")) self.plex.markBoundaryFaces("boundary") self.assertTrue(self.plex.hasLabel("boundary")) faces = self.plex.getStratumIS("boundary", 1) for f in faces.getIndices(): points, orient = self.plex.getTransitiveClosure(f, useCone=True) for p in points: self.plex.setLabelValue("boundary", p, 1) for p in range(pStart, pEnd): if self.plex.getLabelValue("boundary", p) != 1: self.plex.setLabelValue("boundary", p, 2) numBoundary = self.plex.getStratumSize("boundary", 1) numInterior = self.plex.getStratumSize("boundary", 2) self.assertNotEqual(numBoundary, pEnd - pStart) self.assertNotEqual(numInterior, pEnd - pStart) self.assertEqual(numBoundary + numInterior, pEnd - pStart) def testMetric(self): if self.DIM == 1: return self.plex.distribute() if self.CELLS is None and not self.plex.isSimplex(): return self.plex.orient() h_min = 1.0e-30 h_max = 1.0e+30 a_max = 1.0e+10 target = 8.0 p = 1.0 beta = 1.3 hausd = 0.01 self.plex.metricSetUniform(False) self.plex.metricSetIsotropic(False) self.plex.metricSetRestrictAnisotropyFirst(False) self.plex.metricSetNoInsertion(False) self.plex.metricSetNoSwapping(False) self.plex.metricSetNoMovement(False) self.plex.metricSetNoSurf(False) self.plex.metricSetVerbosity(-1) self.plex.metricSetNumIterations(3) self.plex.metricSetMinimumMagnitude(h_min) self.plex.metricSetMaximumMagnitude(h_max) self.plex.metricSetMaximumAnisotropy(a_max) self.plex.metricSetTargetComplexity(target) self.plex.metricSetNormalizationOrder(p) self.plex.metricSetGradationFactor(beta) self.plex.metricSetHausdorffNumber(hausd) self.assertFalse(self.plex.metricIsUniform()) self.assertFalse(self.plex.metricIsIsotropic()) self.assertFalse(self.plex.metricRestrictAnisotropyFirst()) self.assertFalse(self.plex.metricNoInsertion()) self.assertFalse(self.plex.metricNoSwapping()) self.assertFalse(self.plex.metricNoMovement()) self.assertFalse(self.plex.metricNoSurf()) assert self.plex.metricGetVerbosity() == -1 assert self.plex.metricGetNumIterations() == 3 assert np.isclose(self.plex.metricGetMinimumMagnitude(), h_min) assert np.isclose(self.plex.metricGetMaximumMagnitude(), h_max) assert np.isclose(self.plex.metricGetMaximumAnisotropy(), a_max) assert np.isclose(self.plex.metricGetTargetComplexity(), target) assert np.isclose(self.plex.metricGetNormalizationOrder(), p) assert np.isclose(self.plex.metricGetGradationFactor(), beta) assert np.isclose(self.plex.metricGetHausdorffNumber(), hausd) metric1 = self.plex.metricCreateUniform(0.5) metric2 = self.plex.metricCreateUniform(1.0) metric = self.plex.metricCreate() det = self.plex.metricDeterminantCreate() self.plex.metricAverage2(metric1, metric2, metric) metric1.array[:] *= 1.5 assert np.allclose(metric.array, metric1.array) self.plex.metricIntersection2(metric1, metric2, metric) assert np.allclose(metric.array, metric2.array) self.plex.metricEnforceSPD(metric, metric1, det) assert np.allclose(metric.array, metric1.array) self.plex.metricNormalize(metric, metric1, det, restrictSizes=False, restrictAnisotropy=False) metric2.scale(pow(target, 2.0/self.DIM)) assert np.allclose(metric1.array, metric2.array) def testAdapt(self): if self.DIM == 1: return self.plex.orient() plex = self.plex.refine() plex.distribute() if self.CELLS is None and not plex.isSimplex(): return if sum(self.DOFS) > 1: return metric = plex.metricCreateUniform(9.0) try: newplex = plex.adaptMetric(metric,"") except PETSc.Error as exc: if exc.ierr != ERR_ARG_OUTOFRANGE: raise # -------------------------------------------------------------------- class BaseTestPlex_2D(BaseTestPlex): DIM = 2 CELLS = [[0, 1, 3], [1, 3, 4], [1, 2, 4], [2, 4, 5], [3, 4, 6], [4, 6, 7], [4, 5, 7], [5, 7, 8]] COORDS = [[0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [0.0, 0.5], [0.5, 0.5], [1.0, 0.5], [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]] DOFS = [1, 0, 0] class BaseTestPlex_3D(BaseTestPlex): DIM = 3 CELLS = [[0, 2, 3, 7], [0, 2, 6, 7], [0, 4, 6, 7], [0, 1, 3, 7], [0, 1, 5, 7], [0, 4, 5, 7]] COORDS = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.], [0., 0., 1.], [1., 0., 1.], [0., 1., 1.], [1., 1., 1.]] DOFS = [1, 0, 0, 0] # -------------------------------------------------------------------- class TestPlex_1D(BaseTestPlex, unittest.TestCase): pass class TestPlex_2D(BaseTestPlex_2D, unittest.TestCase): def testTransform(self): plex = self.plex cstart, cend = plex.getHeightStratum(0) tr = PETSc.DMPlexTransform().create(comm=PETSc.COMM_WORLD) tr.setType(PETSc.DMPlexTransformType.REFINEALFELD) tr.setDM(plex) tr.setUp() newplex = tr.apply(plex) tr.destroy() newcstart, newcend = newplex.getHeightStratum(0) newplex.destroy() self.assertTrue((newcend-newcstart) == 3*(cend-cstart)) class TestPlex_3D(BaseTestPlex_3D, unittest.TestCase): pass class TestPlex_2D_P3(BaseTestPlex_2D, unittest.TestCase): DOFS = [1, 2, 1] class TestPlex_3D_P3(BaseTestPlex_3D, unittest.TestCase): DOFS = [1, 2, 1, 0] class TestPlex_3D_P4(BaseTestPlex_3D, unittest.TestCase): DOFS = [1, 3, 3, 1] class TestPlex_2D_BoxTensor(BaseTestPlex_2D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): self.plex = PETSc.DMPlex().createBoxMesh([3,3], simplex=False) class TestPlex_3D_BoxTensor(BaseTestPlex_3D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): self.plex = PETSc.DMPlex().createBoxMesh([3,3,3], simplex=False) try: raise PETSc.Error PETSc.DMPlex().createBoxMesh([2,2], simplex=True, comm=PETSc.COMM_SELF).destroy() except PETSc.Error: pass else: class TestPlex_2D_Box(BaseTestPlex_2D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): self.plex = PETSc.DMPlex().createBoxMesh([1,1], simplex=True) class TestPlex_2D_Boundary(BaseTestPlex_2D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): boundary = PETSc.DMPlex().create(self.COMM) boundary.createSquareBoundary([0., 0.], [1., 1.], [2, 2]) boundary.setDimension(self.DIM-1) self.plex = PETSc.DMPlex().generate(boundary) class TestPlex_3D_Box(BaseTestPlex_3D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): self.plex = PETSc.DMPlex().createBoxMesh([1,1,1], simplex=True) class TestPlex_3D_Boundary(BaseTestPlex_3D, unittest.TestCase): CELLS = None COORDS = None def setUp(self): boundary = PETSc.DMPlex().create(self.COMM) boundary.createCubeBoundary([0., 0., 0.], [1., 1., 1.], [1, 1, 1]) boundary.setDimension(self.DIM-1) self.plex = PETSc.DMPlex().generate(boundary) # -------------------------------------------------------------------- PETSC_DIR = petsc4py.get_config()['PETSC_DIR'] def check_dtype(method): def wrapper(self, *args, **kwargs): if PETSc.ScalarType is PETSc.ComplexType: return else: return method(self, *args, **kwargs) return wrapper def check_package(method): def wrapper(self, *args, **kwargs): if not PETSc.Sys.hasExternalPackage("hdf5"): return elif self.PARTITIONERTYPE != "simple" and \ not PETSc.Sys.hasExternalPackage(self.PARTITIONERTYPE): return else: return method(self, *args, **kwargs) return wrapper def check_nsize(method): def wrapper(self, *args, **kwargs): if PETSc.COMM_WORLD.size != self.NSIZE: return else: return method(self, *args, **kwargs) return wrapper class BaseTestPlexHDF5(object): NSIZE = 4 NTIMES = 3 def setUp(self): self.txtvwr = PETSc.Viewer() def tearDown(self): if not PETSc.COMM_WORLD.rank: if os.path.exists(self.outfile()): os.remove(self.outfile()) if os.path.exists(self.tmp_output_file()): os.remove(self.tmp_output_file()) self.txtvwr = None def _name(self): return "%s_outformat-%s_%s" % (self.SUFFIX, self.OUTFORMAT, self.PARTITIONERTYPE) def infile(self): return os.path.join(PETSC_DIR, "share/petsc/datafiles/", "meshes/blockcylinder-50.h5") def outfile(self): return os.path.join("./temp_test_dmplex_%s.h5" % self._name()) def informat(self): return PETSc.Viewer.Format.HDF5_XDMF def outformat(self): d = {"hdf5_petsc": PETSc.Viewer.Format.HDF5_PETSC, "hdf5_xdmf": PETSc.Viewer.Format.HDF5_XDMF} return d[self.OUTFORMAT] def partitionerType(self): d = {"simple": PETSc.Partitioner.Type.SIMPLE, "ptscotch": PETSc.Partitioner.Type.PTSCOTCH, "parmetis": PETSc.Partitioner.Type.PARMETIS} return d[self.PARTITIONERTYPE] def ref_output_file(self): return os.path.join(PETSC_DIR, "src/dm/impls/plex/tutorials/", "output/ex5_%s.out" % self._name()) def tmp_output_file(self): return os.path.join("./temp_test_dmplex_%s.out" % self._name()) def outputText(self, msg, comm): if not comm.rank: with open(self.tmp_output_file(), 'a') as f: f.write(msg) def outputPlex(self, plex): self.txtvwr.createASCII(self.tmp_output_file(), mode='a', comm=plex.comm) plex.view(viewer=self.txtvwr) self.txtvwr.destroy() @check_dtype @check_package @check_nsize def testViewLoadCycle(self): grank = PETSc.COMM_WORLD.rank for i in range(self.NTIMES): if i == 0: infname = self.infile() informt = self.informat() else: infname = self.outfile() informt = self.outformat() if self.HETEROGENEOUS: mycolor = (grank > self.NTIMES - i) else: mycolor = 0 try: import mpi4py except ImportError: self.skipTest('mpi4py') # throws special exception to signal test skip mpicomm = PETSc.COMM_WORLD.tompi4py() comm = PETSc.Comm(comm=mpicomm.Split(color=mycolor, key=grank)) if mycolor == 0: self.outputText("Begin cycle %d\n" % i, comm) plex = PETSc.DMPlex() vwr = PETSc.ViewerHDF5() # Create plex plex.create(comm=comm) plex.setName("DMPlex Object") # Load data from XDMF into dm in parallel vwr.create(infname, mode='r', comm=comm) vwr.pushFormat(format=informt) plex.load(viewer=vwr) plex.setOptionsPrefix("loaded_") plex.distributeSetDefault(False) plex.setFromOptions() vwr.popFormat() vwr.destroy() self.outputPlex(plex) # Test DM is indeed distributed flg = plex.isDistributed() self.outputText("Loaded mesh distributed? %s\n" % str(flg).upper(), comm) # Interpolate plex.interpolate() plex.setOptionsPrefix("interpolated_") plex.setFromOptions() self.outputPlex(plex) # Redistribute part = plex.getPartitioner() part.setType(self.partitionerType()) _ = plex.distribute(overlap=0) plex.setName("DMPlex Object") plex.setOptionsPrefix("redistributed_") plex.setFromOptions() self.outputPlex(plex) # Save redistributed dm to XDMF in parallel vwr.create(self.outfile(), mode='w', comm=comm) vwr.pushFormat(format=self.outformat()) plex.setName("DMPlex Object") plex.view(viewer=vwr) vwr.popFormat() vwr.destroy() # Destroy plex plex.destroy() self.outputText("End cycle %d\n--------\n" % i, comm) PETSc.COMM_WORLD.Barrier() # Check that the output is identical to that of plex/tutorial/ex5.c. self.assertTrue(filecmp.cmp(self.tmp_output_file(), self.ref_output_file(), shallow=False), 'Contents of the files not the same.') PETSc.COMM_WORLD.Barrier() class BaseTestPlexHDF5Homogeneous(BaseTestPlexHDF5): """Test save on N / load on N.""" SUFFIX = 0 HETEROGENEOUS = False class BaseTestPlexHDF5Heterogeneous(BaseTestPlexHDF5): """Test save on N / load on M.""" SUFFIX = 1 HETEROGENEOUS = True class TestPlexHDF5PETSCSimpleHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "simple" """ Skipping. PTScotch produces different distributions when run in a sequence in a single session. class TestPlexHDF5PETSCPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "ptscotch" """ class TestPlexHDF5PETSCParmetisHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "parmetis" class TestPlexHDF5XDMFSimpleHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "simple" """ Skipping. PTScotch produces different distributions when run in a sequence in a single session. class TestPlexHDF5XDMFPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "ptscotch" """ class TestPlexHDF5XDMFParmetisHomogeneous(BaseTestPlexHDF5Homogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "parmetis" class TestPlexHDF5PETSCSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "simple" """ Skipping. PTScotch produces different distributions when run in a sequence in a single session. class TestPlexHDF5PETSCPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "ptscotch" """ class TestPlexHDF5PETSCParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_petsc" PARTITIONERTYPE = "parmetis" class TestPlexHDF5XDMFSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "simple" class TestPlexHDF5XDMFPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "ptscotch" class TestPlexHDF5XDMFParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous, unittest.TestCase): OUTFORMAT = "hdf5_xdmf" PARTITIONERTYPE = "parmetis" # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_dmshell.py000066400000000000000000000172221454104047300174130ustar00rootroot00000000000000from petsc4py import PETSc import unittest import numpy as np class TestDMShell(unittest.TestCase): COMM = PETSc.COMM_WORLD def setUp(self): self.dm = PETSc.DMShell().create(comm=self.COMM) def tearDown(self): self.dm.destroy() self.dm = None PETSc.garbage_cleanup() def testSetGlobalVector(self): vec = PETSc.Vec().create(comm=self.COMM) vec.setSizes((10, None)) vec.setUp() self.dm.setGlobalVector(vec) gvec = self.dm.createGlobalVector() self.assertEqual(vec.getSizes(), gvec.getSizes()) self.assertEqual(vec.comm, gvec.comm) def testSetCreateGlobalVector(self): def create_vec(dm): v = PETSc.Vec().create(comm=dm.comm) v.setSizes((10, None)) v.setUp() return v self.dm.setCreateGlobalVector(create_vec) gvec = self.dm.createGlobalVector() self.assertEqual(gvec.comm, self.dm.comm) self.assertEqual(gvec.getLocalSize(), 10) def testSetLocalVector(self): vec = PETSc.Vec().create(comm=PETSc.COMM_SELF) vec.setSizes((1 + 10*self.COMM.rank, None)) vec.setUp() self.dm.setLocalVector(vec) lvec = self.dm.createLocalVector() self.assertEqual(vec.getSizes(), lvec.getSizes()) lsize, gsize = lvec.getSizes() self.assertEqual(lsize, gsize) self.assertEqual(lvec.comm, PETSc.COMM_SELF) def testSetCreateLocalVector(self): def create_vec(dm): v = PETSc.Vec().create(comm=PETSc.COMM_SELF) v.setSizes((1 + 10*dm.comm.rank, None)) v.setUp() return v self.dm.setCreateLocalVector(create_vec) lvec = self.dm.createLocalVector() lsize, gsize = lvec.getSizes() self.assertEqual(lsize, gsize) self.assertEqual(lsize, 1 + 10*self.dm.comm.rank) self.assertEqual(lvec.comm, PETSc.COMM_SELF) def testSetMatrix(self): mat = PETSc.Mat().create(comm=self.COMM) mat.setSizes(((10, None), (2, None))) mat.setUp() mat.assemble() self.dm.setMatrix(mat) nmat = self.dm.createMatrix() self.assertEqual(nmat.getSizes(), mat.getSizes()) def testSetCreateMatrix(self): def create_mat(dm): mat = PETSc.Mat().create(comm=self.COMM) mat.setSizes(((10, None), (2, None))) mat.setUp() return mat self.dm.setCreateMatrix(create_mat) nmat = self.dm.createMatrix() self.assertEqual(nmat.getSizes(), create_mat(self.dm).getSizes()) def testGlobalToLocal(self): def begin(dm, ivec, mode, ovec): if mode == PETSc.InsertMode.INSERT_VALUES: ovec[...] = ivec[...] elif mode == PETSc.InsertMode.ADD_VALUES: ovec[...] += ivec[...] def end(dm, ivec, mode, ovec): pass vec = PETSc.Vec().create(comm=self.COMM) vec.setSizes((10, None)) vec.setUp() vec[...] = self.dm.comm.rank + 1 ovec = PETSc.Vec().create(comm=PETSc.COMM_SELF) ovec.setSizes((10, None)) ovec.setUp() self.dm.setGlobalToLocal(begin, end) self.dm.globalToLocal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) self.assertTrue(np.allclose(vec.getArray(), ovec.getArray())) self.dm.globalToLocal(vec, ovec, addv=PETSc.InsertMode.ADD_VALUES) self.assertTrue(np.allclose(2*vec.getArray(), ovec.getArray())) def testLocalToGlobal(self): def begin(dm, ivec, mode, ovec): if mode == PETSc.InsertMode.INSERT_VALUES: ovec[...] = ivec[...] elif mode == PETSc.InsertMode.ADD_VALUES: ovec[...] += ivec[...] def end(dm, ivec, mode, ovec): pass vec = PETSc.Vec().create(comm=PETSc.COMM_SELF) vec.setSizes((10, None)) vec.setUp() vec[...] = self.dm.comm.rank + 1 ovec = PETSc.Vec().create(comm=self.COMM) ovec.setSizes((10, None)) ovec.setUp() self.dm.setLocalToGlobal(begin, end) self.dm.localToGlobal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) self.assertTrue(np.allclose(vec.getArray(), ovec.getArray())) self.dm.localToGlobal(vec, ovec, addv=PETSc.InsertMode.ADD_VALUES) self.assertTrue(np.allclose(2*vec.getArray(), ovec.getArray())) def testLocalToLocal(self): def begin(dm, ivec, mode, ovec): if mode == PETSc.InsertMode.INSERT_VALUES: ovec[...] = ivec[...] elif mode == PETSc.InsertMode.ADD_VALUES: ovec[...] += ivec[...] def end(dm, ivec, mode, ovec): pass vec = PETSc.Vec().create(comm=PETSc.COMM_SELF) vec.setSizes((10, None)) vec.setUp() vec[...] = self.dm.comm.rank + 1 ovec = vec.duplicate() self.dm.setLocalToLocal(begin, end) self.dm.localToLocal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) self.assertTrue(np.allclose(vec.getArray(), ovec.getArray())) self.dm.localToLocal(vec, ovec, addv=PETSc.InsertMode.ADD_VALUES) self.assertTrue(np.allclose(2*vec.getArray(), ovec.getArray())) def testGlobalToLocalVecScatter(self): vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() sct, ovec = PETSc.Scatter.toAll(vec) self.dm.setGlobalToLocalVecScatter(sct) self.dm.globalToLocal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) self.assertTrue(np.allclose(vec.getArray(), ovec.getArray())) def testGlobalToLocalVecScatter(self): vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() sct, ovec = PETSc.Scatter.toAll(vec) self.dm.setGlobalToLocalVecScatter(sct) self.dm.globalToLocal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) def testLocalToGlobalVecScatter(self): vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() sct, ovec = PETSc.Scatter.toAll(vec) self.dm.setLocalToGlobalVecScatter(sct) self.dm.localToGlobal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) def testLocalToLocalVecScatter(self): vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() sct, ovec = PETSc.Scatter.toAll(vec) self.dm.setLocalToLocalVecScatter(sct) self.dm.localToLocal(vec, ovec, addv=PETSc.InsertMode.INSERT_VALUES) def testCoarsenRefine(self): cdm = PETSc.DMShell().create(comm=self.COMM) def coarsen(dm, comm): return cdm def refine(dm, comm): return self.dm cdm.setRefine(refine) self.dm.setCoarsen(coarsen) coarsened = self.dm.coarsen() self.assertEqual(coarsened, cdm) refined = coarsened.refine() self.assertEqual(refined, self.dm) def testCreateInterpolation(self): mat = PETSc.Mat().create() mat.setSizes(((10, None), (10, None))) mat.setUp() vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() def create_interp(dm, dmf): return mat, vec self.dm.setCreateInterpolation(create_interp) m, v = self.dm.createInterpolation(self.dm) self.assertEqual(m, mat) self.assertEqual(v, vec) def testCreateInjection(self): mat = PETSc.Mat().create() mat.setSizes(((10, None), (10, None))) mat.setUp() def create_inject(dm, dmf): return mat self.dm.setCreateInjection(create_inject) m = self.dm.createInjection(self.dm) self.assertEqual(m, mat) if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_dmstag.py000066400000000000000000000376001454104047300172440ustar00rootroot00000000000000from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestDMStag(object): COMM = PETSc.COMM_WORLD STENCIL = PETSc.DMStag.StencilType.BOX SWIDTH = 1 PROC_SIZES = None OWNERSHIP_RANGES = None def setUp(self): dim = len(self.SIZES) self.da = PETSc.DMStag().create(dim, dofs=self.DOFS, sizes=self.SIZES, boundary_types=self.BOUNDARY, stencil_type=self.STENCIL, stencil_width=self.SWIDTH, comm=self.COMM, proc_sizes=self.PROC_SIZES, ownership_ranges=self.OWNERSHIP_RANGES, setUp=True) self.directda = PETSc.DMStag().create(dim) self.directda.setStencilType(self.STENCIL) self.directda.setStencilWidth(self.SWIDTH) self.directda.setBoundaryTypes(self.BOUNDARY) self.directda.setDof(self.DOFS) self.directda.setGlobalSizes(self.SIZES) if self.PROC_SIZES is not None: self.directda.setProcSizes(self.PROC_SIZES) if self.OWNERSHIP_RANGES is not None: self.directda.setOwnershipRanges(self.OWNERSHIP_RANGES) self.directda.setUp() def tearDown(self): self.da = None self.directda = None PETSc.garbage_cleanup() def testCoordinates(self): self.da.setCoordinateDMType('stag') self.da.setUniformCoordinates(0,1,0,1,0,1) self.da.setUniformCoordinatesExplicit(0,1,0,1,0,1) cda = self.da.getCoordinateDM() datype = cda.getType() self.assertEqual(datype,'stag') cda.destroy() c = self.da.getCoordinatesLocal() self.da.setCoordinatesLocal(c) gc = self.da.getCoordinatesLocal() self.assertEqual(c.max()[1], gc.max()[1]) self.assertEqual(c.min()[1], gc.min()[1]) c = self.da.getCoordinates() self.da.setCoordinates(c) gc = self.da.getCoordinates() self.assertEqual(c.max()[1], gc.max()[1]) self.assertEqual(c.min()[1], gc.min()[1]) self.directda.setCoordinateDMType('product') self.directda.setUniformCoordinates(0,1,0,1,0,1) self.directda.setUniformCoordinatesProduct(0,1,0,1,0,1) cda = self.directda.getCoordinateDM() datype = cda.getType() self.assertEqual(datype,'product') cda.destroy() def testGetVec(self): vg = self.da.getGlobalVec() vl = self.da.getLocalVec() vg.set(1.0) self.assertEqual(vg.max()[1], 1.0) self.assertEqual(vg.min()[1], 1.0) self.da.globalToLocal(vg,vl) self.assertEqual(vl.max()[1], 1.0) self.assertTrue (vl.min()[1] in (1.0, 0.0)) vl.set(2.0) self.da.localToGlobal(vl,vg) self.assertEqual(vg.max()[1], 2.0) self.assertTrue (vg.min()[1] in (2.0, 0.0)) self.da.restoreGlobalVec(vg) self.da.restoreLocalVec(vl) def testGetOther(self): lgmap = self.da.getLGMap() dlgmap = self.directda.getLGMap() def testDof(self): dim = self.da.getDim() dofs = self.da.getDof() if dim == 1: dof0 = self.da.getLocationDof('left') dof1 = self.da.getLocationDof('element') self.assertEqual(dofs[0],dof0) self.assertEqual(dofs[1],dof1) if dim == 2: dof0 = self.da.getLocationDof('down_left') dof1 = self.da.getLocationDof('left') dof2 = self.da.getLocationDof('element') self.assertEqual(dofs[0],dof0) self.assertEqual(dofs[1],dof1) self.assertEqual(dofs[2],dof2) if dim == 3: dof0 = self.da.getLocationDof('back_down_right') dof1 = self.da.getLocationDof('down_left') dof2 = self.da.getLocationDof('left') dof3 = self.da.getLocationDof('element') self.assertEqual(dofs[0],dof0) self.assertEqual(dofs[1],dof1) self.assertEqual(dofs[2],dof2) self.assertEqual(dofs[3],dof3) def testMigrateVec(self): vec = self.da.createGlobalVec() dmTo = self.da.createCompatibleDMStag(self.NEWDOF) vecTo = dmTo.createGlobalVec() self.da.migrateVec(vec, dmTo, vecTo) def testDMDAInterface(self): return self.da.setCoordinateDMType('stag') self.da.setUniformCoordinates(0,1,0,1,0,1) dim = self.da.getDim() dofs = self.da.getDof() vec = self.da.createGlobalVec() if dim == 1: da,davec = self.da.VecSplitToDMDA(vec,'left',-dofs[0]) da,davec = self.da.VecSplitToDMDA(vec,'element',-dofs[1]) if dim == 2: da,davec = self.da.VecSplitToDMDA(vec,'down_left',-dofs[0]) da,davec = self.da.VecSplitToDMDA(vec,'down_left',-dofs[1]) da,davec = self.da.VecSplitToDMDA(vec,'down_left',-dofs[2]) if dim == 3: da,davec = self.da.VecSplitToDMDA(vec,'back_down_right',-dofs[0]) da,davec = self.da.VecSplitToDMDA(vec,'down_left',-dofs[1]) da,davec = self.da.VecSplitToDMDA(vec,'left',-dofs[2]) da,davec = self.da.VecSplitToDMDA(vec,'element',-dofs[3]) GHOSTED = PETSc.DM.BoundaryType.GHOSTED PERIODIC = PETSc.DM.BoundaryType.PERIODIC NONE = PETSc.DM.BoundaryType.NONE SCALE = 4 class BaseTestDMStag_1D(BaseTestDMStag): SIZES = [100*SCALE,] BOUNDARY = [NONE,] class BaseTestDMStag_2D(BaseTestDMStag): SIZES = [9*SCALE, 11*SCALE] BOUNDARY = [NONE, NONE] class BaseTestDMStag_3D(BaseTestDMStag): SIZES = [6*SCALE, 7*SCALE, 8*SCALE] BOUNDARY = [NONE, NONE, NONE] # -------------------------------------------------------------------- class TestDMStag_1D_W0_N11(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 0 DOFS = (1,1) NEWDOF = (2,1) class TestDMStag_1D_W0_N21(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 0 DOFS = (2,1) NEWDOF = (2,2) class TestDMStag_1D_W0_N12(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 0 DOFS = (1,2) NEWDOF = (2,2) class TestDMStag_1D_W2_N11(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 2 DOFS = (1,1) NEWDOF = (2,1) class TestDMStag_1D_W2_N21(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 2 DOFS = (2,1) NEWDOF = (2,2) class TestDMStag_1D_W2_N12(BaseTestDMStag_1D, unittest.TestCase): SWIDTH = 2 DOFS = (1,2) NEWDOF = (2,2) class TestDMStag_2D_W0_N112(BaseTestDMStag_2D, unittest.TestCase): DOFS = (1,1,2) SWIDTH = 0 NEWDOF = (2,2,2) class TestDMStag_2D_W2_N112(BaseTestDMStag_2D, unittest.TestCase): DOFS = (1,1,2) SWIDTH = 2 NEWDOF = (2,2,2) class TestDMStag_2D_PXY(BaseTestDMStag_2D, unittest.TestCase): SIZES = [13*SCALE,17*SCALE] DOFS = (1,1,2) SWIDTH = 5 BOUNDARY = (PERIODIC,)*2 NEWDOF = (2,2,2) class TestDMStag_2D_GXY(BaseTestDMStag_2D, unittest.TestCase): SIZES = [13*SCALE,17*SCALE] DOFS = (1,1,2) SWIDTH = 5 BOUNDARY = (GHOSTED,)*2 NEWDOF = (2,2,2) class TestDMStag_3D_W0_N1123(BaseTestDMStag_3D, unittest.TestCase): DOFS = (1,1,2,3) SWIDTH = 0 NEWDOF = (2,2,3,3) class TestDMStag_3D_W2_N1123(BaseTestDMStag_3D, unittest.TestCase): DOFS = (1,1,2,3) SWIDTH = 2 NEWDOF = (2,2,3,3) class TestDMStag_3D_PXYZ(BaseTestDMStag_3D, unittest.TestCase): SIZES = [11*SCALE,13*SCALE,17*SCALE] DOFS = (1,1,2,3) NEWDOF = (2,2,3,3) SWIDTH = 3 BOUNDARY = (PERIODIC,)*3 class TestDMStag_3D_GXYZ(BaseTestDMStag_3D, unittest.TestCase): SIZES = [11*SCALE,13*SCALE,17*SCALE] DOFS = (1,1,2,3) NEWDOF = (2,2,3,3) SWIDTH = 3 BOUNDARY = (GHOSTED,)*3 # -------------------------------------------------------------------- DIM = (1,2,3) DOF0 = (0,1,2) DOF1 = (0,1,2) DOF2 = (0,1,2) DOF3 = (0,1,2) BOUNDARY_TYPE = ('none', 'ghosted', 'periodic') STENCIL_TYPE = ('none', 'star', 'box') STENCIL_WIDTH = (0,1,2,3) class TestDMStagCreate(unittest.TestCase): pass counter = 0 for dim in DIM: for dof0 in DOF0: for dof1 in DOF1: for dof2 in DOF2: if dim == 1 and dof2 > 0: continue for dof3 in DOF3: if dim == 2 and dof3 > 0: continue if dof0==0 and dof1==0 and dof2==0 and dof3==0: continue dofs = [dof0,dof1,dof2,dof3][:dim+1] for boundary in BOUNDARY_TYPE: if boundary == "periodic": continue # XXX broken for stencil in STENCIL_TYPE: if stencil == 'none' and boundary != 'none': continue for width in STENCIL_WIDTH: if stencil == 'none' and width > 0: continue if stencil in ['star','box'] and width == 0: continue kargs = dict(dim=dim, dofs=dofs, boundary_type=boundary, stencil_type=stencil, stencil_width=width) def testCreate(self,kargs=kargs): kargs = dict(kargs) cda = PETSc.DMStag().create(kargs['dim'], dofs = kargs['dofs'], sizes = [8*SCALE,]*kargs['dim'], boundary_types = [kargs['boundary_type'],]*kargs['dim'], stencil_type = kargs['stencil_type'], stencil_width = kargs['stencil_width'], setUp=True) dda = PETSc.DMStag().create(kargs['dim']) dda.setStencilType(kargs['stencil_type']) dda.setStencilWidth(kargs['stencil_width']) dda.setBoundaryTypes([kargs['boundary_type'],]*kargs['dim']) dda.setDof(kargs['dofs']) dda.setGlobalSizes([8*SCALE,]*kargs['dim']) dda.setUp() cdim = cda.getDim() cdof = cda.getDof() cgsizes = cda.getGlobalSizes() clsizes = cda.getLocalSizes() cboundary = cda.getBoundaryTypes() cstencil_type = cda.getStencilType() cstencil_width = cda.getStencilWidth() centries_per_element = cda.getEntriesPerElement() cstarts, csizes, cnextra = cda.getCorners() cisLastRank = cda.getIsLastRank() cisFirstRank = cda.getIsFirstRank() cownershipranges = cda.getOwnershipRanges() cprocsizes = cda.getProcSizes() ddim = dda.getDim() ddof = dda.getDof() dgsizes = dda.getGlobalSizes() dlsizes = dda.getLocalSizes() dboundary = dda.getBoundaryTypes() dstencil_type = dda.getStencilType() dstencil_width = dda.getStencilWidth() dentries_per_element = dda.getEntriesPerElement() dstarts, dsizes, dnextra = dda.getCorners() disLastRank = dda.getIsLastRank() disFirstRank = dda.getIsFirstRank() downershipranges = dda.getOwnershipRanges() dprocsizes = dda.getProcSizes() self.assertEqual(cdim,kargs['dim']) self.assertEqual(cdof,tuple(kargs['dofs'])) self.assertEqual(cboundary,tuple([kargs['boundary_type'],]*kargs['dim'])) self.assertEqual(cstencil_type,kargs['stencil_type']) self.assertEqual(cstencil_width,kargs['stencil_width']) self.assertEqual(cgsizes,tuple([8*SCALE,]*kargs['dim'])) self.assertEqual(cdim,ddim) self.assertEqual(cdof,ddof) self.assertEqual(cgsizes,dgsizes) self.assertEqual(clsizes,dlsizes) self.assertEqual(cboundary,dboundary) self.assertEqual(cstencil_type,dstencil_type) self.assertEqual(cstencil_width,dstencil_width) self.assertEqual(centries_per_element,dentries_per_element) self.assertEqual(cstarts,dstarts) self.assertEqual(csizes,dsizes) self.assertEqual(cnextra,dnextra) self.assertEqual(cisLastRank,disLastRank) self.assertEqual(cisFirstRank,disFirstRank) self.assertEqual(cprocsizes, dprocsizes) for co,do in zip(cownershipranges, downershipranges): for i,j in zip(co,do): self.assertEqual(i,j) self.assertEqual(cdim+1,len(cdof)) self.assertEqual(cdim,len(cgsizes)) self.assertEqual(cdim,len(clsizes)) self.assertEqual(cdim,len(cboundary)) self.assertEqual(cdim,len(cstarts)) self.assertEqual(cdim,len(csizes)) self.assertEqual(cdim,len(cnextra)) self.assertEqual(cdim,len(cisLastRank)) self.assertEqual(cdim,len(cisLastRank)) if cdim == 1: self.assertEqual(centries_per_element, cdof[0] + cdof[1]) if cdim == 2: self.assertEqual(centries_per_element, cdof[0] + 2*cdof[1] + cdof[2]) if cdim == 3: self.assertEqual(centries_per_element, cdof[0] + 3*cdof[1] + 3*cdof[2] + cdof[3]) for i in range(cdim): self.assertEqual(csizes[i], clsizes[i]) if cisLastRank[i]: self.assertEqual(cnextra[i],1) if (cnextra[i]==1): self.assertTrue(cisLastRank[i]) if (cisFirstRank[i]): self.assertEqual(cstarts[i],0) self.assertEqual(len(cprocsizes), len(cownershipranges)) self.assertEqual(len(cprocsizes), cdim) for i,m in enumerate(cprocsizes): self.assertEqual(m, len(cownershipranges[i])) dda.destroy() cda.destroy() setattr(TestDMStagCreate, "testCreate%05d"%counter, testCreate) del testCreate counter += 1 del counter, dim, dofs, dof0, dof1, dof2, dof3, boundary, stencil, width # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_gc.py000066400000000000000000000046471454104047300163630ustar00rootroot00000000000000from petsc4py import PETSc import unittest import gc, weakref import warnings # -------------------------------------------------------------------- ## gc.set_debug((gc.DEBUG_STATS | ## gc.DEBUG_LEAK) & ## ~gc.DEBUG_SAVEALL) # -------------------------------------------------------------------- class BaseTestGC(object): def setUp(self): self.obj = self.CLASS().create(comm=PETSc.COMM_SELF) def tearDown(self): wref = self.make_weakref() self.assertTrue(wref() is self.obj) self.obj = None gc.collect() self.assertTrue(wref() is None) PETSc.garbage_cleanup() def make_weakref(self): wref = weakref.ref(self.obj) return wref def testCycleInSelf(self): self.obj.setAttr('myself', self.obj) def testCycleInMethod(self): self.obj.setAttr('mymeth', self.obj.view) def testCycleInInstance(self): class A: pass a = A() a.obj = self.obj self.obj.setAttr('myinst', a) def testCycleInAllWays(self): self.testCycleInSelf() self.testCycleInMethod() self.testCycleInInstance() # -------------------------------------------------------------------- class TestGCVec(BaseTestGC, unittest.TestCase): CLASS = PETSc.Vec class TestGCVecSubType(TestGCVec): CLASS = type('_Vec', (PETSc.Vec,), {}) class TestGCMat(BaseTestGC, unittest.TestCase): CLASS = PETSc.Mat class TestGCMatSubType(TestGCMat): CLASS = type('_Mat', (PETSc.Mat,), {}) class TestGCPC(BaseTestGC, unittest.TestCase): CLASS = PETSc.PC class TestGCPCSubType(TestGCPC): CLASS = type('_PC', (PETSc.PC,), {}) class TestGCKSP(BaseTestGC, unittest.TestCase): CLASS = PETSc.KSP class TestGCKSPSubType(TestGCKSP): CLASS = type('_KSP', (PETSc.KSP,), {}) class TestGCSNES(BaseTestGC, unittest.TestCase): CLASS = PETSc.SNES def testCycleInAppCtx(self): self.obj.setAppCtx(self.obj) class TestGCSNESSubType(TestGCSNES): CLASS = type('_SNES', (PETSc.SNES,), {}) class TestGCTS(BaseTestGC, unittest.TestCase): CLASS = PETSc.TS def testCycleInAppCtx(self): self.obj.setAppCtx(self.obj) class TestGCTSSubType(TestGCTS): CLASS = type('_TS', (PETSc.TS,), {}) def testCycleInAppCtx(self): self.obj.setAppCtx(self.obj) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_is.py000066400000000000000000000112471454104047300163770ustar00rootroot00000000000000from petsc4py import PETSc import unittest import random # -------------------------------------------------------------------- class BaseTestIS(object): TYPE = None def tearDown(self): self.iset = None PETSc.garbage_cleanup() def testGetType(self): istype = self.iset.getType() self.assertEqual(istype, self.TYPE) def testGetSize(self): lsize = self.iset.getLocalSize() gsize = self.iset.getSize() self.assertTrue(lsize <= gsize) def testDuplicate(self): iset = self.iset.duplicate() self.assertTrue(self.iset.equal(iset)) del iset def testCopy(self): iset = self.iset.copy() self.assertTrue(self.iset.equal(iset)) del iset def testEqual(self): self.assertTrue(self.iset.equal(self.iset)) iset = self.iset.duplicate() self.assertTrue(self.iset.equal(iset)) del iset def testSort(self): self.iset.sort() self.assertTrue(self.iset.isSorted()) def testDifference(self): iset = self.iset.difference(self.iset) self.assertEqual(iset.getLocalSize(), 0) del iset def testComplement(self): self.iset.sort() nmin = self.iset.getIndices().min() nmax = self.iset.getIndices().max() iset = self.iset.complement(nmin, nmax+1) iset.complement(nmin, nmax+1) del iset def testSum(self): if self.iset.getComm().getSize() > 1: return self.iset.sort() iset = self.iset.duplicate() iset.sum(self.iset) self.assertTrue(self.iset.equal(iset)) del iset def testExpand(self): iset = self.iset.expand(self.iset) if self.iset.type == iset.type: self.assertTrue(self.iset.equal(iset)) del iset def testRenumber(self): (n1,is1) = self.iset.renumber() (n2,is2) = self.iset.renumber(self.iset) del is1 del is2 def testProperties(self): proplist = ['sizes', 'size', 'local_size', 'indices', 'permutation', 'identity', 'sorted'] for prop in proplist: self.assertTrue(hasattr(self.iset, prop)) def testArray(self): import numpy refs = self.iset.getRefCount() arr1 = numpy.asarray(self.iset) self.assertEqual(self.iset.getRefCount(), refs+1) arr2 = self.iset.array self.assertEqual(self.iset.getRefCount(), refs+2) self.assertTrue((arr1 == arr2).all()) del arr2 self.assertEqual(self.iset.getRefCount(), refs+1) del arr1 self.assertEqual(self.iset.getRefCount(), refs) # -------------------------------------------------------------------- class TestISGeneral(BaseTestIS, unittest.TestCase): TYPE = PETSc.IS.Type.GENERAL def setUp(self): self.idx = list(range(10)) random.shuffle(self.idx) self.iset = PETSc.IS().createGeneral(self.idx) def testGetIndices(self): idx = self.iset.getIndices() self.assertEqual(self.idx, list(idx)) class TestISStride(BaseTestIS, unittest.TestCase): TYPE = PETSc.IS.Type.STRIDE def setUp(self): self.info = (10, 7, 3) size, start, step = self.info self.iset = PETSc.IS().createStride(size, start, step) def testGetIndices(self): size, start, step = self.info indices = [start+i*step for i in range(size)] self.assertEqual(list(self.iset.getIndices()), indices) def testToGeneral(self): self.iset.toGeneral() self.assertEqual(self.iset.getType(), PETSc.IS.Type.GENERAL) class TestISBlock(BaseTestIS, unittest.TestCase): TYPE = PETSc.IS.Type.BLOCK def setUp(self): self.bsize = 3 self.index = list(range(0,10,2)) random.shuffle(self.index) self.iset = PETSc.IS().createBlock(self.bsize, self.index) self.assertEqual(self.iset.getType(), PETSc.IS.Type.BLOCK) def testGetSize(self): lsize = self.iset.getLocalSize() self.assertEqual(lsize/self.bsize, len(self.index)) def testGetBlockSize(self): bs = self.iset.getBlockSize() self.assertEqual(bs, self.bsize) def testGetBlockIndices(self): index = list(self.iset.getBlockIndices()) self.assertEqual(index, self.index) def testGetIndices(self): bs = self.bsize idx = [] for i in self.iset.getBlockIndices(): for j in range(bs): idx.append(i*bs+j) index = list(self.iset.getIndices()) #self.assertEqual(index, idx) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_ksp.py000066400000000000000000000154051454104047300165610ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest from sys import getrefcount # -------------------------------------------------------------------- class BaseTestKSP(object): KSP_TYPE = None PC_TYPE = None def setUp(self): ksp = PETSc.KSP() ksp.create(PETSc.COMM_SELF) if self.KSP_TYPE: ksp.setType(self.KSP_TYPE) if self.PC_TYPE: pc = ksp.getPC() pc.setType(self.PC_TYPE) self.ksp = ksp def tearDown(self): self.ksp = None PETSc.garbage_cleanup() def testGetSetType(self): self.assertEqual(self.ksp.getType(), self.KSP_TYPE) self.ksp.setType(self.KSP_TYPE) self.assertEqual(self.ksp.getType(), self.KSP_TYPE) def testTols(self): tols = self.ksp.getTolerances() self.ksp.setTolerances(*tols) tnames = ('rtol', 'atol', 'divtol', 'max_it') tolvals = [getattr(self.ksp, t) for t in tnames] self.assertEqual(tuple(tols), tuple(tolvals)) def testProperties(self): ksp = self.ksp # ksp.appctx = (1,2,3) self.assertEqual(ksp.appctx, (1,2,3)) ksp.appctx = None self.assertEqual(ksp.appctx, None) # side = ksp.pc_side ksp.pc_side = side self.assertEqual(ksp.pc_side, side) # nt = ksp.norm_type ksp.norm_type = nt self.assertEqual(ksp.norm_type, nt) # ksp.its = 1 self.assertEqual(ksp.its, 1) ksp.its = 0 self.assertEqual(ksp.its, 0) # ksp.norm = 1 self.assertEqual(ksp.norm, 1) ksp.norm = 0 self.assertEqual(ksp.norm, 0) # rh = ksp.history self.assertTrue(len(rh)==0) # reason = PETSc.KSP.ConvergedReason.CONVERGED_ITS ksp.reason = reason self.assertEqual(ksp.reason, reason) self.assertTrue(ksp.converged) self.assertFalse(ksp.diverged) self.assertFalse(ksp.iterating) reason = PETSc.KSP.ConvergedReason.DIVERGED_MAX_IT ksp.reason = reason self.assertEqual(ksp.reason, reason) self.assertFalse(ksp.converged) self.assertTrue(ksp.diverged) self.assertFalse(ksp.iterating) reason = PETSc.KSP.ConvergedReason.CONVERGED_ITERATING ksp.reason = reason self.assertEqual(ksp.reason, reason) self.assertFalse(ksp.converged) self.assertFalse(ksp.diverged) self.assertTrue(ksp.iterating) def testGetSetPC(self): oldpc = self.ksp.getPC() self.assertEqual(oldpc.getRefCount(), 2) newpc = PETSc.PC() newpc.create(self.ksp.getComm()) self.assertEqual(newpc.getRefCount(), 1) self.ksp.setPC(newpc) self.assertEqual(newpc.getRefCount(), 2) self.assertEqual(oldpc.getRefCount(), 1) oldpc.destroy() self.assertFalse(bool(oldpc)) pc = self.ksp.getPC() self.assertTrue(bool(pc)) self.assertEqual(pc, newpc) self.assertEqual(pc.getRefCount(), 3) newpc.destroy() self.assertFalse(bool(newpc)) self.assertEqual(pc.getRefCount(), 2) def testSolve(self): A = PETSc.Mat().create(PETSc.COMM_SELF) A.setSizes([3,3]) A.setType(PETSc.Mat.Type.SEQAIJ) A.setPreallocationNNZ(1) for i in range(3): A.setValue(i, i, 0.9/(i+1)) A.assemble() A.shift(1) x, b = A.createVecs() b.set(10) x.setRandom() self.ksp.setOperators(A) self.ksp.setConvergenceHistory() self.ksp.solve(b, x) r = b.duplicate() u = x.duplicate() self.ksp.buildSolution(u) self.ksp.buildResidual(u) rh = self.ksp.getConvergenceHistory() self.ksp.setConvergenceHistory(0) rh = self.ksp.getConvergenceHistory() self.assertEqual(len(rh), 0) del A, x, b def testResetAndSolve(self): self.ksp.reset() self.testSolve() self.ksp.reset() self.testSolve() self.ksp.reset() def testSetMonitor(self): reshist = {} def monitor(ksp, its, rnorm): reshist[its] = rnorm refcnt = getrefcount(monitor) self.ksp.setMonitor(monitor) self.assertEqual(getrefcount(monitor), refcnt + 1) ## self.testSolve() reshist = {} self.ksp.monitorCancel() self.assertEqual(getrefcount(monitor), refcnt) self.testSolve() self.assertEqual(len(reshist), 0) ## Monitor = PETSc.KSP.Monitor ## self.ksp.setMonitor(Monitor()) ## self.ksp.setMonitor(Monitor.DEFAULT) ## self.ksp.setMonitor(Monitor.TRUE_RESIDUAL_NORM) ## self.ksp.setMonitor(Monitor.SOLUTION) def testSetConvergenceTest(self): def converged(ksp, its, rnorm): if its > 10: return True return False refcnt = getrefcount(converged) self.ksp.setConvergenceTest(converged) self.assertEqual(getrefcount(converged), refcnt + 1) self.ksp.setConvergenceTest(None) self.assertEqual(getrefcount(converged), refcnt) # -------------------------------------------------------------------- class TestKSPPREONLY(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.PREONLY PC_TYPE = PETSc.PC.Type.LU class TestKSPRICHARDSON(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.RICHARDSON class TestKSPCHEBYCHEV(BaseTestKSP, unittest.TestCase): try: KSP_TYPE = PETSc.KSP.Type.CHEBYSHEV except AttributeError: KSP_TYPE = PETSc.KSP.Type.CHEBYCHEV class TestKSPCG(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.CG class TestKSPCGNE(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.CGNE class TestKSPSTCG(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.STCG class TestKSPBCGS(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.BCGS class TestKSPBCGSL(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.BCGSL class TestKSPCGS(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.CGS class TestKSPQCG(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.QCG PC_TYPE = PETSc.PC.Type.JACOBI class TestKSPBICG(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.BICG class TestKSPGMRES(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.GMRES class TestKSPFGMRES(BaseTestKSP, unittest.TestCase): KSP_TYPE = PETSc.KSP.Type.FGMRES # -------------------------------------------------------------------- if PETSc.ScalarType().dtype.char in 'FDG': del TestKSPSTCG # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_ksp_py.py000066400000000000000000000060131454104047300172640ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest from sys import getrefcount # -------------------------------------------------------------------- class MyKSP(object): def __init__(self): pass def create(self, ksp): self.work = [] def destroy(self, ksp): for v in self.work: v.destroy() def setUp(self, ksp): self.work[:] = ksp.getWorkVecs(right=2, left=None) def reset(self, ksp): for v in self.work: v.destroy() del self.work[:] def loop(self, ksp, r): its = ksp.getIterationNumber() rnorm = r.norm() ksp.setResidualNorm(rnorm) ksp.logConvergenceHistory(rnorm) ksp.monitor(its, rnorm) reason = ksp.callConvergenceTest(its, rnorm) if not reason: ksp.setIterationNumber(its+1) else: ksp.setConvergedReason(reason) return reason class MyRichardson(MyKSP): def solve(self, ksp, b, x): A, B = ksp.getOperators() P = ksp.getPC() r, z = self.work # A.mult(x, r) r.aypx(-1, b) P.apply(r, z) x.axpy(1, z) while not self.loop(ksp, z): A.mult(x, r) r.aypx(-1, b) P.apply(r, z) x.axpy(1, z) class MyCG(MyKSP): def setUp(self, ksp): super(MyCG, self).setUp(ksp) d = self.work[0].duplicate() q = d.duplicate() self.work += [d, q] def solve(self, ksp, b, x): A, B = ksp.getOperators() P = ksp.getPC() r, z, d, q = self.work # A.mult(x, r) r.aypx(-1, b) r.copy(d) delta_0 = r.dot(r) delta = delta_0 while not self.loop(ksp, r): A.mult(d, q) alpha = delta / d.dot(q) x.axpy(+alpha, d) r.axpy(-alpha, q) delta_old = delta delta = r.dot(r) beta = delta / delta_old d.aypx(beta, r) # -------------------------------------------------------------------- from test_ksp import BaseTestKSP class BaseTestKSPPYTHON(BaseTestKSP): KSP_TYPE = PETSc.KSP.Type.PYTHON ContextClass = None def setUp(self): super(BaseTestKSPPYTHON, self).setUp() ctx = self.ContextClass() self.ksp.setPythonContext(ctx) def testGetType(self): ctx = self.ksp.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.ksp.getPythonType() == pytype) def tearDown(self): self.ksp.destroy() PETSc.garbage_cleanup() class TestKSPPYTHON_RICH(BaseTestKSPPYTHON, unittest.TestCase): PC_TYPE = PETSc.PC.Type.JACOBI ContextClass = MyRichardson class TestKSPPYTHON_CG(BaseTestKSPPYTHON, unittest.TestCase): PC_TYPE = PETSc.PC.Type.NONE ContextClass = MyCG # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_lgmap.py000066400000000000000000000107371454104047300170670ustar00rootroot00000000000000from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestLGMap(object): def _mk_idx(self, comm): comm_size = comm.getSize() comm_rank = comm.getRank() lsize = 10 first = lsize * comm_rank last = first + lsize if comm_rank > 0: first -= 1 if comm_rank < (comm_size-1): last += 1 return list(range(first, last)) def tearDown(self): self.lgmap = None PETSc.garbage_cleanup() def testGetSize(self): size = self.lgmap.getSize() self.assertTrue(size >= 0) def testGetIndices(self): size = self.lgmap.getSize() idx = self.lgmap.getIndices() self.assertEqual(len(idx), size) for i, val in enumerate(self.idx): self.assertEqual(idx[i], val) def testGetInfo(self): info = self.lgmap.getInfo() self.assertEqual(type(info), dict) if self.lgmap.getComm().getSize() == 1: self.assertEqual(info, {}) else: self.assertTrue(len(info) > 1) self.assertTrue(len(info) < 4) def testApply(self): idxin = list(range(self.lgmap.getSize())) idxout = self.lgmap.apply(idxin) self.lgmap.apply(idxin, idxout) invmap = self.lgmap.applyInverse(idxout) def testApplyIS(self): is_in = PETSc.IS().createStride(self.lgmap.getSize()) is_out = self.lgmap.apply(is_in) def testProperties(self): for prop in ('size', 'indices', 'info'): self.assertTrue(hasattr(self.lgmap, prop)) # -------------------------------------------------------------------- class TestLGMap(BaseTestLGMap, unittest.TestCase): def setUp(self): self.idx = self._mk_idx(PETSc.COMM_WORLD) self.lgmap = PETSc.LGMap().create(self.idx, comm=PETSc.COMM_WORLD) class TestLGMapIS(BaseTestLGMap, unittest.TestCase): def setUp(self): self.idx = self._mk_idx(PETSc.COMM_WORLD) self.iset = PETSc.IS().createGeneral(self.idx, comm=PETSc.COMM_WORLD) self.lgmap = PETSc.LGMap().create(self.iset) def tearDown(self): self.iset = None self.lgmap = None def testSameComm(self): comm1 = self.lgmap.getComm() comm2 = self.iset.getComm() self.assertEqual(comm1, comm2) # -------------------------------------------------------------------- class TestLGMapBlock(unittest.TestCase): BS = 3 def setUp(self): comm = PETSc.COMM_WORLD comm_size = comm.getSize() comm_rank = comm.getRank() lsize = 10 first = lsize * comm_rank last = first + lsize if comm_rank > 0: first -= 1 if comm_rank < (comm_size-1): last += 1 self.idx = list(range(first, last)) bs = self.BS self.lgmap = PETSc.LGMap().create(self.idx, bs, comm=PETSc.COMM_WORLD) def tearDown(self): self.lgmap = None def testGetSize(self): size = self.lgmap.getSize() self.assertTrue(size >= 0) def testGetBlockSize(self): bs = self.lgmap.getBlockSize() self.assertEqual(bs, self.BS) def testGetBlockIndices(self): size = self.lgmap.getSize() bs = self.lgmap.getBlockSize() idx = self.lgmap.getBlockIndices() self.assertEqual(len(idx), size//bs) for i, val in enumerate(self.idx): self.assertEqual(idx[i], val) def testGetIndices(self): size = self.lgmap.getSize() bs = self.lgmap.getBlockSize() idx = self.lgmap.getIndices() self.assertEqual(len(idx), size) for i, val in enumerate(self.idx): for j in range(bs): self.assertEqual(idx[i*bs+j], val*bs+j) def testGetBlockInfo(self): info = self.lgmap.getBlockInfo() self.assertEqual(type(info), dict) if self.lgmap.getComm().getSize() == 1: self.assertEqual(info, {}) else: self.assertTrue(len(info) > 1) self.assertTrue(len(info) < 4) def testGetInfo(self): info = self.lgmap.getInfo() self.assertEqual(type(info), dict) if self.lgmap.getComm().getSize() == 1: self.assertEqual(info, {}) else: self.assertTrue(len(info) > 1) self.assertTrue(len(info) < 4) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_log.py000066400000000000000000000073361454104047300165510ustar00rootroot00000000000000# -------------------------------------------------------------------- if __name__ == "__main__": import sys, petsc4py petsc4py.init(sys.argv+['-log_summary']) # -------------------------------------------------------------------- from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class TestLog(unittest.TestCase): def setUp(self): #PETSc.Log.begin() # register stages self.stage1 = PETSc.Log.Stage('Stage 1') self.stage2 = PETSc.Log.Stage('Stage 2') # register classes self.klassA = PETSc.Log.Class('Class A') self.klassB = PETSc.Log.Class('Class B') # register events self.event1 = PETSc.Log.Event('Event 1') # no class self.event2 = PETSc.Log.Event('Event 2') # no class self.eventA = PETSc.Log.Event('Event A', self.klassA) self.eventB = PETSc.Log.Event('Event B', self.klassB) def testGetName(self): self.assertEqual(self.klassA.name, 'Class A') self.assertEqual(self.klassB.name, 'Class B') self.assertEqual(self.event1.name, 'Event 1') self.assertEqual(self.event2.name, 'Event 2') self.assertEqual(self.eventA.name, 'Event A') self.assertEqual(self.eventB.name, 'Event B') self.assertEqual(self.stage1.name, 'Stage 1') self.assertEqual(self.stage2.name, 'Stage 2') def testLogBeginEnd(self): # ----- self._run_events() # in main stage self._run_stages() # in user stages # ----- for event in self._get_events(): event.deactivate() event.setActive(False) event.active = False self._run_events() # should not be logged for event in self._get_events(): event.activate() event.setActive(True) event.active = True # ----- for klass in self._get_classes(): klass.deactivate() klass.setActive(False) klass.active = False self._run_events() # A and B should not be logged for klass in self._get_classes(): klass.activate() klass.setActive(True) klass.active = True # ----- for stage in self._get_stages(): active = stage.getActive() self.assertTrue(active) self.assertTrue(stage.active) stage.setActive(False) active = stage.getActive() self.assertFalse(active) self.assertFalse(stage.active) self._run_stages() # should not be logged for stage in self._get_stages(): stage.setActive(True) stage.active = True active = stage.getActive() self.assertTrue(active) self.assertTrue(stage.active) # ----- self._run_events() self._run_stages() def _run_stages(self): for stage in self._get_stages(): self._run_events(stage) def _get_stages(self): return (self.stage1, self.stage2) def _get_classes(self): return (self.klassA, self.klassB) def _get_events(self): return (self.event1, self.event2, self.eventA, self.eventB) def _run_events(self, stage=None): if stage is not None: stage.push() self._events_begin() self._events_end() if stage is not None: stage.pop() def _events_begin(self): for event in self._get_events(): event.begin() def _events_end(self): for event in reversed(self._get_events()): event.end() # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_mat_aij.py000066400000000000000000000711771454104047300174000ustar00rootroot00000000000000from petsc4py import PETSc import unittest import numpy as N import numpy as np def mkgraph(comm, m, n): start = m*n * comm.rank end = start + m*n idt = PETSc.IntType rows = [] for I in range(start, end) : rows.append([]) adj = rows[-1] i = I//n; j = I - i*n if i> 0 : J = I-n; adj.append(J) if j> 0 : J = I-1; adj.append(J) adj.append(I) if j< n-1: J = I+1; adj.append(J) if i< m-1: J = I+n; adj.append(J) nods = N.array(range(start, end), dtype=idt) xadj = N.array([0]*(len(rows)+1), dtype=idt) xadj[0] = 0 xadj[1:] = N.cumsum([len(r) for r in rows], dtype=idt) if not rows: adjy = N.array([],dtype=idt) else: adjy = N.concatenate(rows).astype(idt) return nods, xadj, adjy class BaseTestMatAnyAIJ(object): COMM = PETSc.COMM_NULL TYPE = None GRID = 0, 0 BSIZE = None def setUp(self): COMM = self.COMM GM, GN = self.GRID BS = self.BSIZE # try: rbs, cbs = BS rbs = rbs or 1 cbs = cbs or 1 except (TypeError, ValueError): rbs = cbs = BS or 1 sdt = dtype = PETSc.ScalarType self.rows, self.xadj, self.adjy = mkgraph(COMM, GM, GN) self.vals = N.array(range(1, 1 + len(self.adjy)*rbs*cbs), dtype=sdt) self.vals.shape = (-1, rbs, cbs) # m, n = GM, GN rowsz = (m*n*rbs, None) colsz = (m*n*cbs, None) A = self.A = PETSc.Mat().create(comm=COMM) A.setType(self.TYPE) A.setSizes([rowsz, colsz], BS) def tearDown(self): self.A.destroy() self.A = None PETSc.garbage_cleanup() def testSetPreallocNNZ(self): nnz = [5, 2] self.A.setPreallocationNNZ(nnz) self._chk_bs(self.A, self.BSIZE) opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetPreallocNNZ_2(self): _, ai, _, _ =self._get_aijv() d_nnz = N.diff(ai) nnz = [d_nnz, 3] self.A.setPreallocationNNZ(nnz) self._chk_bs(self.A, self.BSIZE) opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av =self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetPreallocCSR(self): if 'is' in self.A.getType(): return # XXX _, ai, aj, _ = self._get_aijv() csr = [ai, aj] self.A.setPreallocationCSR(csr) self._chk_bs(self.A, self.BSIZE) self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetPreallocCSR_2(self): if 'is' in self.A.getType(): return # XXX _, ai, aj, av =self._get_aijv() csr = [ai, aj, av] self.A.setPreallocationCSR(csr) self._chk_bs(self.A, self.BSIZE) self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetValues(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetValuesIJV(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def testGetValuesCSR(self): if 'is' in self.A.getType(): return # XXX self._preallocate() self._set_values_ijv() A = self.A A.assemble() if 'sbaij' in A.getType(): opt = PETSc.Mat.Option.GETROW_UPPERTRIANGULAR self.A.setOption(opt, True) ai, aj, av = A.getValuesCSR() rstart, rend = A.getOwnershipRange() for row in range(rstart, rend): cols, vals = A.getRow(row) i = row - rstart self.assertTrue(N.allclose(aj[ai[i]:ai[i+1]], cols)) self.assertTrue(N.allclose(av[ai[i]:ai[i+1]], vals)) def testConvertToSAME(self): self._preallocate() self._set_values_ijv() A = self.A A.assemble() A.convert('same') def testConvertToDENSE(self): self._preallocate() self._set_values_ijv() A = self.A A.assemble() x, y = A.getVecs() x.setRandom() z = y.duplicate() A.mult(x, y) if A.type.endswith('sbaij'): return B = PETSc.Mat() A.convert('dense', B) # initial B.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) A.convert('dense', B) # reuse B.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) A.convert('dense') # inplace A.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) def testConvertToAIJ(self): self._preallocate() self._set_values_ijv() A = self.A A.assemble() x, y = A.getVecs() x.setRandom() z = y.duplicate() A.mult(x, y) if A.type.endswith('sbaij'): return B = PETSc.Mat() A.convert('aij', B) # initial B.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) A.convert('aij', B) # reuse B.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) A.convert('aij') # inplace A.mult(x, z) self.assertTrue(np.allclose(y.array, z.array)) def testGetDiagonalBlock(self): if 'is' in self.A.getType(): return # XXX self._preallocate() self._set_values_ijv() self.A.assemble() B = self.A.getDiagonalBlock() self.assertEqual(self.A.getLocalSize(), B.getSize()) B.destroy() def testInvertBlockDiagonal(self): if 'is' in self.A.getType(): return # XXX try: _ = len(self.BSIZE) return except (TypeError, ValueError): pass self._preallocate() rbs, cbs = self.A.getBlockSizes() if rbs != cbs: return self._set_values_ijv() self.A.assemble() self.A.shift(1000) # Make nonsingular ibdiag = self.A.invertBlockDiagonal() bs = self.A.getBlockSize() m, _ = self.A.getLocalSize() self.assertEqual(ibdiag.shape, (m//bs, bs, bs)) tmp = N.empty((m//bs, bs, bs), dtype=PETSc.ScalarType) rstart, rend = self.A.getOwnershipRange() s, e = rstart//bs, rend//bs for i in range(s, e): rows = cols = N.arange(i*bs,(i+1)*bs, dtype=PETSc.IntType) vals = self.A.getValues(rows,cols) tmp[i-s,:,:] = N.linalg.inv(vals) self.assertTrue(N.allclose(ibdiag, tmp)) def testCreateSubMatrix(self): if 'baij' in self.A.getType(): return # XXX self._preallocate() self._set_values_ijv() self.A.assemble() # rank = self.A.getComm().getRank() rs, re = self.A.getOwnershipRange() cs, ce = self.A.getOwnershipRangeColumn() rows = N.array(range(rs, re), dtype=PETSc.IntType) cols = N.array(range(cs, ce), dtype=PETSc.IntType) rows = PETSc.IS().createGeneral(rows, comm=self.A.getComm()) cols = PETSc.IS().createGeneral(cols, comm=self.A.getComm()) # S = self.A.createSubMatrix(rows, None) S.zeroEntries() self.A.createSubMatrix(rows, None, S) S.destroy() # S = self.A.createSubMatrix(rows, cols) S.zeroEntries() self.A.createSubMatrix(rows, cols, S) S.destroy() def testCreateSubMatrices(self): if 'baij' in self.A.getType(): return # XXX if 'is' in self.A.getType(): return # XXX self._preallocate() self._set_values_ijv() self.A.assemble() # rs, re = self.A.getOwnershipRange() cs, ce = self.A.getOwnershipRangeColumn() rows = N.array(range(rs, re), dtype=PETSc.IntType) cols = N.array(range(cs, ce), dtype=PETSc.IntType) rows = PETSc.IS().createGeneral(rows, comm=self.A.getComm()) cols = PETSc.IS().createGeneral(cols, comm=self.A.getComm()) # (S,) = self.A.createSubMatrices(rows, cols) S.zeroEntries() self.A.createSubMatrices(rows, cols, submats=[S]) S.destroy() # (S1,) = self.A.createSubMatrices([rows], [cols]) (S2,) = self.A.createSubMatrices([rows], [cols]) self.assertTrue(S1.equal(S2)) S2.zeroEntries() self.A.createSubMatrices([rows], [cols], [S2]) self.assertTrue(S1.equal(S2)) S1.destroy() S2.destroy() # if 'seq' not in self.A.getType(): return # XXX S1, S2 = self.A.createSubMatrices([rows, rows], [cols, cols]) self.assertTrue(S1.equal(S2)) S1.zeroEntries() S2.zeroEntries() self.A.createSubMatrices([rows, rows], [cols, cols], [S1, S2]) self.assertTrue(S1.equal(S2)) S1.destroy() S2.destroy() def testGetRedundantMatrix(self): if 'aijcrl' in self.A.getType(): return # duplicate not supported if 'mpisbaij' in self.A.getType(): return # not working if 'is' in self.A.getType(): return # XXX self._preallocate() self._set_values_ijv() self.A.assemble() #Test the most simple case sizecommA = self.A.getComm().getSize() Ared = self.A.getRedundantMatrix(sizecommA) sizecommAred = Ared.getComm().getSize() self.assertEqual(1, sizecommAred) Ared.destroy() def testCreateTranspose(self): self._preallocate() self._set_values_ijv() self.A.assemble() A = self.A AT = PETSc.Mat().createTranspose(A) x, y = A.createVecs() xt, yt = AT.createVecs() # y.setRandom() A.multTranspose(y, x) y.copy(xt) AT.mult(xt, yt) self.assertTrue(yt.equal(x)) # x.setRandom() A.mult(x, y) x.copy(yt) AT.multTranspose(yt, xt) self.assertTrue(xt.equal(y)) def _get_aijv(self): return (self.rows, self.xadj, self.adjy, self.vals,) def _preallocate(self): self.A.setPreallocationNNZ([5, 2]) def _set_values(self): import sys if hasattr(sys, 'gettotalrefcount'): return self._set_values_ijv() # XXX Why the code below leak refs as a beast ??? row, ai, aj, av =self._get_aijv() if not self.BSIZE: setvalues = self.A.setValues else: setvalues = self.A.setValuesBlocked for i, r in enumerate(row): s, e = ai[i], ai[i+1] setvalues(r, aj[s:e], av[s:e]) return ai, aj, av def _set_values_ijv(self): row, ai, aj, av =self._get_aijv() if not self.BSIZE: setvalues = self.A.setValuesIJV else: setvalues = self.A.setValuesBlockedIJV setvalues(ai, aj, av, rowmap=row) setvalues(ai, aj, av, rowmap=None) return ai, aj, av def _chk_bs(self, A, bs): self.assertEqual(A.getBlockSize(), bs or 1) def _chk_bsizes(self, A, bsizes): try: rbs, cbs = bsizes except (TypeError, ValueError): rbs = cbs = bsizes self.assertEqual(A.getBlockSizes(), (rbs, cbs)) def _chk_aij(self, A, i, j): compressed = bool(self.BSIZE) ai, aj = A.getRowIJ(compressed=compressed) if ai is not None and aj is not None: self.assertTrue(N.all(i==ai)) self.assertTrue(N.all(j==aj)) ai, aj = A.getColumnIJ(compressed=compressed) if ai is not None and aj is not None: self.assertTrue(N.all(i==ai)) self.assertTrue(N.all(j==aj)) # -- AIJ --------------------- class BaseTestMatAIJ(BaseTestMatAnyAIJ, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.AIJ GRID = 0, 0 BSIZE = None # -- Seq AIJ -- class TestMatSeqAIJ(BaseTestMatAIJ): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQAIJ class TestMatSeqAIJ_G23(TestMatSeqAIJ): GRID = 2, 3 class TestMatSeqAIJ_G45(TestMatSeqAIJ): GRID = 4, 5 class TestMatSeqAIJ_G89(TestMatSeqAIJ): GRID = 8, 9 # -- MPI AIJ -- class TestMatMPIAIJ(BaseTestMatAIJ): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIAIJ class TestMatMPIAIJ_G23(TestMatMPIAIJ): GRID = 2, 3 class TestMatMPIAIJ_G45(TestMatMPIAIJ): GRID = 4, 5 class TestMatMPIAIJ_G89(TestMatMPIAIJ): GRID = 8, 9 # -- Block AIJ --------------- class BaseTestMatBAIJ(BaseTestMatAnyAIJ, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.BAIJ GRID = 0, 0 BSIZE = 1 # -- Seq Block AIJ -- class TestMatSeqBAIJ(BaseTestMatBAIJ): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQBAIJ # bs = 1 class TestMatSeqBAIJ_G23(TestMatSeqBAIJ): GRID = 2, 3 class TestMatSeqBAIJ_G45(TestMatSeqBAIJ): GRID = 4, 5 class TestMatSeqBAIJ_G89(TestMatSeqBAIJ): GRID = 8, 9 # bs = 2 class TestMatSeqBAIJ_G23_B2(TestMatSeqBAIJ_G23): BSIZE = 2 class TestMatSeqBAIJ_G45_B2(TestMatSeqBAIJ_G45): BSIZE = 2 class TestMatSeqBAIJ_G89_B2(TestMatSeqBAIJ_G89): BSIZE = 2 # bs = 3 class TestMatSeqBAIJ_G23_B3(TestMatSeqBAIJ_G23): BSIZE = 3 class TestMatSeqBAIJ_G45_B3(TestMatSeqBAIJ_G45): BSIZE = 3 class TestMatSeqBAIJ_G89_B3(TestMatSeqBAIJ_G89): BSIZE = 3 # bs = 4 class TestMatSeqBAIJ_G23_B4(TestMatSeqBAIJ_G23): BSIZE = 4 class TestMatSeqBAIJ_G45_B4(TestMatSeqBAIJ_G45): BSIZE = 4 class TestMatSeqBAIJ_G89_B4(TestMatSeqBAIJ_G89): BSIZE = 4 # bs = 5 class TestMatSeqBAIJ_G23_B5(TestMatSeqBAIJ_G23): BSIZE = 5 class TestMatSeqBAIJ_G45_B5(TestMatSeqBAIJ_G45): BSIZE = 5 class TestMatSeqBAIJ_G89_B5(TestMatSeqBAIJ_G89): BSIZE = 5 # -- MPI Block AIJ -- class TestMatMPIBAIJ(BaseTestMatBAIJ): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIBAIJ # bs = 1 class TestMatMPIBAIJ_G23(TestMatMPIBAIJ): GRID = 2, 3 class TestMatMPIBAIJ_G45(TestMatMPIBAIJ): GRID = 4, 5 class TestMatMPIBAIJ_G89(TestMatMPIBAIJ): GRID = 8, 9 # bs = 2 class TestMatMPIBAIJ_G23_B2(TestMatMPIBAIJ_G23): BSIZE = 2 class TestMatMPIBAIJ_G45_B2(TestMatMPIBAIJ_G45): BSIZE = 2 class TestMatMPIBAIJ_G89_B2(TestMatMPIBAIJ_G89): BSIZE = 2 # bs = 3 class TestMatMPIBAIJ_G23_B3(TestMatMPIBAIJ_G23): BSIZE = 3 class TestMatMPIBAIJ_G45_B3(TestMatMPIBAIJ_G45): BSIZE = 3 class TestMatMPIBAIJ_G89_B3(TestMatMPIBAIJ_G89): BSIZE = 3 # bs = 4 class TestMatMPIBAIJ_G23_B4(TestMatMPIBAIJ_G23): BSIZE = 4 class TestMatMPIBAIJ_G45_B4(TestMatMPIBAIJ_G45): BSIZE = 4 class TestMatMPIBAIJ_G89_B4(TestMatMPIBAIJ_G89): BSIZE = 4 # bs = 5 class TestMatMPIBAIJ_G23_B5(TestMatMPIBAIJ_G23): BSIZE = 5 class TestMatMPIBAIJ_G45_B5(TestMatMPIBAIJ_G45): BSIZE = 5 class TestMatMPIBAIJ_G89_B5(TestMatMPIBAIJ_G89): BSIZE = 5 # -- SymmBlock AIJ --------------- class BaseTestMatSBAIJ(BaseTestMatAnyAIJ, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.SBAIJ GRID = 0, 0 BSIZE = 1 def testInvertBlockDiagonal(self): pass def _chk_aij(self, A, i, j): ai, aj = A.getRowIJ(compressed=True) if ai is not None and aj is not None: if 0: # XXX Implement self.assertTrue(N.all(i==ai)) self.assertTrue(N.all(j==aj)) ai, aj = A.getColumnIJ(compressed=True) if ai is not None and aj is not None: if 0: # XXX Implement self.assertTrue(N.all(i==ai)) self.assertTrue(N.all(j==aj)) # -- Seq SymmBlock AIJ -- class TestMatSeqSBAIJ(BaseTestMatSBAIJ): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQSBAIJ # bs = 1 class TestMatSeqSBAIJ_G23(TestMatSeqSBAIJ): GRID = 2, 3 class TestMatSeqSBAIJ_G45(TestMatSeqSBAIJ): GRID = 4, 5 class TestMatSeqSBAIJ_G89(TestMatSeqSBAIJ): GRID = 8, 9 # bs = 2 class TestMatSeqSBAIJ_G23_B2(TestMatSeqSBAIJ_G23): BSIZE = 2 class TestMatSeqSBAIJ_G45_B2(TestMatSeqSBAIJ_G45): BSIZE = 2 class TestMatSeqSBAIJ_G89_B2(TestMatSeqSBAIJ_G89): BSIZE = 2 # bs = 3 class TestMatSeqSBAIJ_G23_B3(TestMatSeqSBAIJ_G23): BSIZE = 3 class TestMatSeqSBAIJ_G45_B3(TestMatSeqSBAIJ_G45): BSIZE = 3 class TestMatSeqSBAIJ_G89_B3(TestMatSeqSBAIJ_G89): BSIZE = 3 # bs = 4 class TestMatSeqSBAIJ_G23_B4(TestMatSeqSBAIJ_G23): BSIZE = 4 class TestMatSeqSBAIJ_G45_B4(TestMatSeqSBAIJ_G45): BSIZE = 4 class TestMatSeqSBAIJ_G89_B4(TestMatSeqSBAIJ_G89): BSIZE = 4 # bs = 5 class TestMatSeqSBAIJ_G23_B5(TestMatSeqSBAIJ_G23): BSIZE = 5 class TestMatSeqSBAIJ_G45_B5(TestMatSeqSBAIJ_G45): BSIZE = 5 class TestMatSeqSBAIJ_G89_B5(TestMatSeqSBAIJ_G89): BSIZE = 5 # -- MPI SymmBlock AIJ -- class TestMatMPISBAIJ(BaseTestMatSBAIJ): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPISBAIJ # bs = 1 class TestMatMPISBAIJ_G23(TestMatMPISBAIJ): GRID = 2, 3 class TestMatMPISBAIJ_G45(TestMatMPISBAIJ): GRID = 4, 5 class TestMatMPISBAIJ_G89(TestMatMPISBAIJ): GRID = 8, 9 # bs = 2 class TestMatMPISBAIJ_G23_B2(TestMatMPISBAIJ_G23): BSIZE = 2 class TestMatMPISBAIJ_G45_B2(TestMatMPISBAIJ_G45): BSIZE = 2 class TestMatMPISBAIJ_G89_B2(TestMatMPISBAIJ_G89): BSIZE = 2 # bs = 3 class TestMatMPISBAIJ_G23_B3(TestMatMPISBAIJ_G23): BSIZE = 3 class TestMatMPISBAIJ_G45_B3(TestMatMPISBAIJ_G45): BSIZE = 3 class TestMatMPISBAIJ_G89_B3(TestMatMPISBAIJ_G89): BSIZE = 3 # bs = 4 class TestMatMPISBAIJ_G23_B4(TestMatMPISBAIJ_G23): BSIZE = 4 class TestMatMPISBAIJ_G45_B4(TestMatMPISBAIJ_G45): BSIZE = 4 class TestMatMPISBAIJ_G89_B4(TestMatMPISBAIJ_G89): BSIZE = 4 # bs = 5 class TestMatMPISBAIJ_G23_B5(TestMatMPISBAIJ_G23): BSIZE = 5 class TestMatMPISBAIJ_G45_B5(TestMatMPISBAIJ_G45): BSIZE = 5 class TestMatMPISBAIJ_G89_B5(TestMatMPISBAIJ_G89): BSIZE = 5 # -- AIJ + Block --------------- class BaseTestMatAIJ_B(BaseTestMatAnyAIJ, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.AIJ GRID = 0, 0 BSIZE = 1 def testSetPreallocNNZ(self):pass def testSetPreallocNNZ_2(self):pass def testSetPreallocCSR(self):pass def testSetPreallocCSR_2(self):pass def testSetValues(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetValuesIJV(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def _preallocate(self): self.A.setPreallocationNNZ([5*self.BSIZE, 3*self.BSIZE]) self._chk_bs(self.A, self.BSIZE) def _chk_aij(self, A, i, j): bs = self.BSIZE or 1 ai, aj = A.getRowIJ() if ai is not None and aj is not None: ## XXX map and check !! #self.assertTrue(N.all(i==ai)) #self.assertTrue(N.all(j==aj)) pass ai, aj = A.getColumnIJ(compressed=bool(self.BSIZE)) if ai is not None and aj is not None: ## XXX map and check !! #self.assertTrue(N.all(i==ai)) #self.assertTrue(N.all(j==aj)) pass # -- Seq AIJ + Block -- class TestMatSeqAIJ_B(BaseTestMatAIJ_B): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQAIJ # bs = 1 class TestMatSeqAIJ_B_G23(TestMatSeqAIJ_B): GRID = 2, 3 class TestMatSeqAIJ_B_G45(TestMatSeqAIJ_B): GRID = 4, 5 class TestMatSeqAIJ_B_G89(TestMatSeqAIJ_B): GRID = 8, 9 # bs = 2 class TestMatSeqAIJ_B_G23_B2(TestMatSeqAIJ_B_G23): BSIZE = 2 class TestMatSeqAIJ_B_G45_B2(TestMatSeqAIJ_B_G45): BSIZE = 2 class TestMatSeqAIJ_B_G89_B2(TestMatSeqAIJ_B_G89): BSIZE = 2 # bs = 3 class TestMatSeqAIJ_B_G23_B3(TestMatSeqAIJ_B_G23): BSIZE = 3 class TestMatSeqAIJ_B_G45_B3(TestMatSeqAIJ_B_G45): BSIZE = 3 class TestMatSeqAIJ_B_G89_B3(TestMatSeqAIJ_B_G89): BSIZE = 3 # bs = 4 class TestMatSeqAIJ_B_G23_B4(TestMatSeqAIJ_B_G23): BSIZE = 4 class TestMatSeqAIJ_B_G45_B4(TestMatSeqAIJ_B_G45): BSIZE = 4 class TestMatSeqAIJ_B_G89_B4(TestMatSeqAIJ_B_G89): BSIZE = 4 # bs = 5 class TestMatSeqAIJ_B_G23_B5(TestMatSeqAIJ_B_G23): BSIZE = 5 class TestMatSeqAIJ_B_G45_B5(TestMatSeqAIJ_B_G45): BSIZE = 5 class TestMatSeqAIJ_B_G89_B5(TestMatSeqAIJ_B_G89): BSIZE = 5 # -- MPI AIJ + Block -- class TestMatMPIAIJ_B(BaseTestMatAIJ_B): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIAIJ # bs = 1 class TestMatMPIAIJ_B_G23(TestMatMPIAIJ_B): GRID = 2, 3 class TestMatMPIAIJ_B_G45(TestMatMPIAIJ_B): GRID = 4, 5 class TestMatMPIAIJ_B_G89(TestMatMPIAIJ_B): GRID = 8, 9 # bs = 2 class TestMatMPIAIJ_B_G23_B2(TestMatMPIAIJ_B_G23): BSIZE = 2 class TestMatMPIAIJ_B_G45_B2(TestMatMPIAIJ_B_G45): BSIZE = 2 class TestMatMPIAIJ_B_G89_B2(TestMatMPIAIJ_B_G89): BSIZE = 2 # bs = 3 class TestMatMPIAIJ_B_G23_B3(TestMatMPIAIJ_B_G23): BSIZE = 3 class TestMatMPIAIJ_B_G45_B3(TestMatMPIAIJ_B_G45): BSIZE = 3 class TestMatMPIAIJ_B_G89_B3(TestMatMPIAIJ_B_G89): BSIZE = 3 # bs = 4 class TestMatMPIAIJ_B_G23_B4(TestMatMPIAIJ_B_G23): BSIZE = 4 class TestMatMPIAIJ_B_G45_B4(TestMatMPIAIJ_B_G45): BSIZE = 4 class TestMatMPIAIJ_B_G89_B4(TestMatMPIAIJ_B_G89): BSIZE = 4 # bs = 5 class TestMatMPIAIJ_B_G23_B5(TestMatMPIAIJ_B_G23): BSIZE = 5 class TestMatMPIAIJ_B_G45_B5(TestMatMPIAIJ_B_G45): BSIZE = 5 class TestMatMPIAIJ_B_G89_B5(TestMatMPIAIJ_B_G89): BSIZE = 5 # -- Non-square blocks -- class BaseTestMatAIJ_B(BaseTestMatAnyAIJ, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.AIJ GRID = 0, 0 BSIZE = 4, 2 def _preallocate(self): try: rbs, cbs = self.BSIZE except (TypeError, ValueError): rbs = cbs = self.BSIZE self.A.setPreallocationNNZ([5*rbs, 3*cbs]) self._chk_bsizes(self.A, self.BSIZE) def testSetPreallocNNZ(self):pass def testSetPreallocNNZ_2(self):pass def testSetPreallocCSR(self):pass def testSetPreallocCSR_2(self):pass def testSetValues(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values() self.A.assemble() self._chk_aij(self.A, ai, aj) def testSetValuesIJV(self): self._preallocate() opt = PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) opt = PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR self.A.setOption(opt, True) ai, aj, av = self._set_values_ijv() self.A.assemble() self._chk_aij(self.A, ai, aj) def _chk_aij(self, A, i, j): bs = self.BSIZE or 1 ai, aj = A.getRowIJ() if ai is not None and aj is not None: ## XXX map and check !! #self.assertTrue(N.all(i==ai)) #self.assertTrue(N.all(j==aj)) pass ai, aj = A.getColumnIJ() if ai is not None and aj is not None: ## XXX map and check !! #self.assertTrue(N.all(i==ai)) #self.assertTrue(N.all(j==aj)) pass # -- AIJCRL --------------------- class BaseTestMatAIJCRL(BaseTestMatAIJ, unittest.TestCase): TYPE = PETSc.Mat.Type.AIJCRL # -- Seq AIJCRL -- class TestMatSeqAIJCRL(BaseTestMatAIJCRL): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQAIJCRL class TestMatSeqAIJCRL_G23(TestMatSeqAIJCRL): GRID = 2, 3 class TestMatSeqAIJCRL_G45(TestMatSeqAIJCRL): GRID = 4, 5 class TestMatSeqAIJCRL_G89(TestMatSeqAIJCRL): GRID = 8, 9 # -- MPI AIJCRL -- class TestMatMPIAIJCRL(BaseTestMatAIJCRL): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIAIJCRL class TestMatMPIAIJCRL_G23(TestMatMPIAIJCRL): GRID = 2, 3 class TestMatMPIAIJCRL_G45(TestMatMPIAIJCRL): GRID = 4, 5 class TestMatMPIAIJCRL_G89(TestMatMPIAIJCRL): GRID = 8, 9 # -- AIJCRL + Block ------------- class BaseTestMatAIJCRL_B(BaseTestMatAIJ_B, unittest.TestCase): TYPE = PETSc.Mat.Type.AIJCRL # -- Seq AIJCRL + Block -- class TestMatSeqAIJCRL_B(BaseTestMatAIJCRL_B): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQAIJCRL # bs = 1 class TestMatSeqAIJCRL_B_G23(TestMatSeqAIJCRL_B): GRID = 2, 3 class TestMatSeqAIJCRL_B_G45(TestMatSeqAIJCRL_B): GRID = 4, 5 class TestMatSeqAIJCRL_B_G89(TestMatSeqAIJCRL_B): GRID = 8, 9 # bs = 2 class TestMatSeqAIJCRL_B_G23_B2(TestMatSeqAIJCRL_B_G23): BSIZE = 2 class TestMatSeqAIJCRL_B_G45_B2(TestMatSeqAIJCRL_B_G45): BSIZE = 2 class TestMatSeqAIJCRL_B_G89_B2(TestMatSeqAIJCRL_B_G89): BSIZE = 2 # bs = 3 class TestMatSeqAIJCRL_B_G23_B3(TestMatSeqAIJCRL_B_G23): BSIZE = 3 class TestMatSeqAIJCRL_B_G45_B3(TestMatSeqAIJCRL_B_G45): BSIZE = 3 class TestMatSeqAIJCRL_B_G89_B3(TestMatSeqAIJCRL_B_G89): BSIZE = 3 # bs = 4 class TestMatSeqAIJCRL_B_G23_B4(TestMatSeqAIJCRL_B_G23): BSIZE = 4 class TestMatSeqAIJCRL_B_G45_B4(TestMatSeqAIJCRL_B_G45): BSIZE = 4 class TestMatSeqAIJCRL_B_G89_B4(TestMatSeqAIJCRL_B_G89): BSIZE = 4 # bs = 5 class TestMatSeqAIJCRL_B_G23_B5(TestMatSeqAIJCRL_B_G23): BSIZE = 5 class TestMatSeqAIJCRL_B_G45_B5(TestMatSeqAIJCRL_B_G45): BSIZE = 5 class TestMatSeqAIJCRL_B_G89_B5(TestMatSeqAIJCRL_B_G89): BSIZE = 5 # -- MPI AIJCRL + Block -- class TestMatMPIAIJCRL_B(BaseTestMatAIJCRL_B): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIAIJCRL # bs = 1 class TestMatMPIAIJCRL_B_G23(TestMatMPIAIJCRL_B): GRID = 2, 3 class TestMatMPIAIJCRL_B_G45(TestMatMPIAIJCRL_B): GRID = 4, 5 class TestMatMPIAIJCRL_B_G89(TestMatMPIAIJCRL_B): GRID = 8, 9 # bs = 2 class TestMatMPIAIJCRL_B_G23_B2(TestMatMPIAIJCRL_B_G23): BSIZE = 2 class TestMatMPIAIJCRL_B_G45_B2(TestMatMPIAIJCRL_B_G45): BSIZE = 2 class TestMatMPIAIJCRL_B_G89_B2(TestMatMPIAIJCRL_B_G89): BSIZE = 2 # bs = 3 class TestMatMPIAIJCRL_B_G23_B3(TestMatMPIAIJCRL_B_G23): BSIZE = 3 class TestMatMPIAIJCRL_B_G45_B3(TestMatMPIAIJCRL_B_G45): BSIZE = 3 class TestMatMPIAIJCRL_B_G89_B3(TestMatMPIAIJCRL_B_G89): BSIZE = 3 # bs = 4 class TestMatMPIAIJCRL_B_G23_B4(TestMatMPIAIJCRL_B_G23): BSIZE = 4 class TestMatMPIAIJCRL_B_G45_B4(TestMatMPIAIJCRL_B_G45): BSIZE = 4 class TestMatMPIAIJCRL_B_G89_B4(TestMatMPIAIJCRL_B_G89): BSIZE = 4 # bs = 5 class TestMatMPIAIJCRL_B_G23_B5(TestMatMPIAIJCRL_B_G23): BSIZE = 5 class TestMatMPIAIJCRL_B_G45_B5(TestMatMPIAIJCRL_B_G45): BSIZE = 5 class TestMatMPIAIJCRL_B_G89_B5(TestMatMPIAIJCRL_B_G89): BSIZE = 5 # -- MATIS -- class TestMatIS(BaseTestMatAIJ): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.IS class TestMatIS_G23(TestMatIS): GRID = 2, 3 class TestMatIS_G45(TestMatIS): GRID = 4, 5 class TestMatIS_G89(TestMatIS): GRID = 8, 9 # ----- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_mat_dense.py000066400000000000000000000153021454104047300177170ustar00rootroot00000000000000from petsc4py import PETSc import unittest import numpy as np def mkdata(comm, m, N, bs): start = m * comm.rank end = start + m idt = PETSc.IntType sdt = PETSc.ScalarType rows = np.array(range(start, end), dtype=idt) cols = np.array(range(0, N), dtype=idt) vals = np.array(range(0, m*N*bs*bs), dtype=sdt) vals.shape = (-1, bs, bs) return rows, cols, vals class BaseTestMatAnyDense(object): COMM = PETSc.COMM_NULL GRID = 0, 0 BSIZE = None TYPE = PETSc.Mat.Type.DENSE def setUp(self): COMM = self.COMM GM, GN = self.GRID BS = self.BSIZE #or 1 # self.A = PETSc.Mat().create(comm=COMM) bs = BS or 1; m, N = GM, GN; rowsz = (m*bs, None) colsz = (None, N*bs) self.A.setSizes([rowsz, colsz], BS) self.A.setType(self.TYPE) def tearDown(self): self.A.destroy() self.A = None PETSc.garbage_cleanup() def testSetValues(self): self._preallocate() r, c, v = self._set_values() self.A.assemble() self._chk_array(self.A, r, c, v) r, c, v = self._set_values() self.A.assemble() self._chk_array(self.A, r, c, v) def testGetDiagonalBlock(self): M, N = self.A.getSize() # only for square matrices if M != N: return self._preallocate() self._set_values() self.A.assemble() B = self.A.getDiagonalBlock() self.assertEqual(self.A.getLocalSize(), B.getSize()) B.destroy() def testCreateTranspose(self): self._preallocate() self._set_values() self.A.assemble() A = self.A AT = PETSc.Mat().createTranspose(A) x, y = A.createVecs() xt, yt = AT.createVecs() # y.setRandom() A.multTranspose(y, x) y.copy(xt) AT.mult(xt, yt) self.assertTrue(yt.equal(x)) # x.setRandom() A.mult(x, y) x.copy(yt) AT.multTranspose(yt, xt) self.assertTrue(xt.equal(y)) def _preallocate(self): self.A.setPreallocationDense(None) def _set_values(self): COMM = self.COMM GM, GN = self.GRID BS = self.BSIZE or 1 rows, cols, vals = mkdata(COMM, GM, GN, BS) if not self.BSIZE: setvalues = self.A.setValues else: setvalues = self.A.setValuesBlocked setvalues(rows, cols, vals) return rows, cols, vals def _chk_bs(self, A, bs): self.assertEqual(A.getBlockSize(), bs or 1) def _chk_array(self, A, r, c, v): return # XXX vals = self.A.getValues(r, c) vals.shape = v.shape self.assertTrue(np.allclose(vals, v)) # -- Dense --------------------- class BaseTestMatDense(BaseTestMatAnyDense, unittest.TestCase): COMM = PETSc.COMM_WORLD GRID = 0, 0 BSIZE = None # -- Seq Dense -- class TestMatSeqDense(BaseTestMatDense): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQDENSE class TestMatSeqDense_G23(TestMatSeqDense): GRID = 2, 3 class TestMatSeqDense_G45(TestMatSeqDense): GRID = 4, 5 class TestMatSeqDense_G77(TestMatSeqDense): GRID = 7, 7 class TestMatSeqDense_G89(TestMatSeqDense): GRID = 8, 9 # -- MPI Dense -- class TestMatMPIDense(BaseTestMatDense): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIDENSE class TestMatMPIDense_G23(TestMatMPIDense): GRID = 2, 3 class TestMatMPIDense_G45(TestMatMPIDense): GRID = 4, 5 class TestMatMPIDense_G77(TestMatMPIDense): GRID = 7, 7 class TestMatMPIDense_G89(TestMatMPIDense): GRID = 8, 9 # -- Dense + Block --------------- class BaseTestMatDense_B(BaseTestMatAnyDense, unittest.TestCase): COMM = PETSc.COMM_WORLD GRID = 0, 0 BSIZE = 1 def _preallocate(self): #self.A.setBlockSize(self.BSIZE) self.A.setPreallocationDense(None) #self.A.setBlockSize(self.BSIZE) self._chk_bs(self.A, self.BSIZE) # -- Seq Dense + Block -- class TestMatSeqDense_B(BaseTestMatDense_B): COMM = PETSc.COMM_SELF TYPE = PETSc.Mat.Type.SEQDENSE # bs = 1 class TestMatSeqDense_B_G23(TestMatSeqDense_B): GRID = 2, 3 class TestMatSeqDense_B_G45(TestMatSeqDense_B): GRID = 4, 5 class TestMatSeqDense_B_G89(TestMatSeqDense_B): GRID = 8, 9 # bs = 2 class TestMatSeqDense_B_G23_B2(TestMatSeqDense_B_G23): BSIZE = 2 class TestMatSeqDense_B_G45_B2(TestMatSeqDense_B_G45): BSIZE = 2 class TestMatSeqDense_B_G89_B2(TestMatSeqDense_B_G89): BSIZE = 2 # bs = 3 class TestMatSeqDense_B_G23_B3(TestMatSeqDense_B_G23): BSIZE = 3 class TestMatSeqDense_B_G45_B3(TestMatSeqDense_B_G45): BSIZE = 3 class TestMatSeqDense_B_G89_B3(TestMatSeqDense_B_G89): BSIZE = 3 # bs = 4 class TestMatSeqDense_B_G23_B4(TestMatSeqDense_B_G23): BSIZE = 4 class TestMatSeqDense_B_G45_B4(TestMatSeqDense_B_G45): BSIZE = 4 class TestMatSeqDense_B_G89_B4(TestMatSeqDense_B_G89): BSIZE = 4 # bs = 5 class TestMatSeqDense_B_G23_B5(TestMatSeqDense_B_G23): BSIZE = 5 class TestMatSeqDense_B_G45_B5(TestMatSeqDense_B_G45): BSIZE = 5 class TestMatSeqDense_B_G89_B5(TestMatSeqDense_B_G89): BSIZE = 5 # -- MPI Dense + Block -- class TestMatMPIDense_B(BaseTestMatDense_B): COMM = PETSc.COMM_WORLD TYPE = PETSc.Mat.Type.MPIDENSE # bs = 1 class TestMatMPIDense_B_G23(TestMatMPIDense_B): GRID = 2, 3 class TestMatMPIDense_B_G45(TestMatMPIDense_B): GRID = 4, 5 class TestMatMPIDense_B_G77(TestMatMPIDense_B): GRID = 7, 7 class TestMatMPIDense_B_G89(TestMatMPIDense_B): GRID = 8, 9 # bs = 2 class TestMatMPIDense_B_G23_B2(TestMatMPIDense_B_G23): BSIZE = 2 class TestMatMPIDense_B_G45_B2(TestMatMPIDense_B_G45): BSIZE = 2 class TestMatMPIDense_B_G77_B2(TestMatMPIDense_B_G77): BSIZE = 2 class TestMatMPIDense_B_G89_B2(TestMatMPIDense_B_G89): BSIZE = 2 # bs = 3 class TestMatMPIDense_B_G23_B3(TestMatMPIDense_B_G23): BSIZE = 3 class TestMatMPIDense_B_G45_B3(TestMatMPIDense_B_G45): BSIZE = 3 class TestMatMPIDense_B_G77_B3(TestMatMPIDense_B_G77): BSIZE = 3 class TestMatMPIDense_B_G89_B3(TestMatMPIDense_B_G89): BSIZE = 3 # bs = 4 class TestMatMPIDense_B_G23_B4(TestMatMPIDense_B_G23): BSIZE = 4 class TestMatMPIDense_B_G45_B4(TestMatMPIDense_B_G45): BSIZE = 4 class TestMatMPIDense_B_G77_B4(TestMatMPIDense_B_G77): BSIZE = 4 class TestMatMPIDense_B_G89_B4(TestMatMPIDense_B_G89): BSIZE = 4 # bs = 5 class TestMatMPIDense_B_G23_B5(TestMatMPIDense_B_G23): BSIZE = 5 class TestMatMPIDense_B_G45_B5(TestMatMPIDense_B_G45): BSIZE = 5 class TestMatMPIDense_B_G77_B5(TestMatMPIDense_B_G77): BSIZE = 5 class TestMatMPIDense_B_G89_B5(TestMatMPIDense_B_G89): BSIZE = 5 # ----- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_mat_fact.py000066400000000000000000000116171454104047300175430ustar00rootroot00000000000000from petsc4py import PETSc import unittest import numpy as N def mkmat(n, mtype, opts): A = PETSc.Mat().create(PETSc.COMM_SELF) A.setSizes([n,n]) A.setType(mtype) A.setUp() for o in opts: A.setOption(o, True) return A def mksys_diag(n, mtype, opts): A = mkmat(n, mtype, opts) x, b = A.createVecs() for i in range(n): A[i,i] = i+1 x[i] = 1.0/(i+1) b[i] = 1 A.assemble() x.assemble() b.assemble() return A, x, b def mksys_poi2(n, mtype, opts): A = mkmat(n, mtype, opts) x, b = A.createVecs() for i in range(n): if i == 0: cols = [i, i+1] vals = [2, -1] elif i == n-1: cols = [i-1, i] vals = [-1, 2] else: cols = [i-1, i, i+1] vals = [-1, 2, -1] A[i,cols] = vals x[i] = i+1 b[i] = 0 A.assemble() x.assemble() b.assemble() A.mult(x,b) return A, x, b class BaseTestMatFactor(object): MKSYS = None MTYPE = None MOPTS = () def setUp(self): A, x, b = self.MKSYS(10, self.MTYPE, self.MOPTS) self.A = A self.x = x self.b = b def tearDown(self): self.A.setUnfactored() self.A.destroy(); self.A = None self.x.destroy(); self.x = None self.b.destroy(); self.b = None PETSc.garbage_cleanup() class BaseTestMatFactorLU(BaseTestMatFactor): def testFactorLU(self): r, c = self.A.getOrdering("nd") self.A.reorderForNonzeroDiagonal(r, c) self.A.factorLU(r,c,{'zeropivot':1e-5}) x = self.x.duplicate() self.A.solve(self.b, x) x.axpy(-1, self.x) self.assertTrue(x.norm() < 1e-3) class BaseTestMatFactorILU(BaseTestMatFactor): def testFactorILU(self): r, c = self.A.getOrdering("natural") self.A.factorILU(r,c,{'levels':0}) x = self.x.duplicate() self.A.solve(self.b, x) x.axpy(-1, self.x) self.assertTrue(x.norm() < 1e-3) ## class BaseTestMatFactorILUDT(BaseTestMatFactor): ## ## def testFactorILUDT(self): ## r, c = self.A.getOrdering("natural") ## self.A = self.A.factorILUDT(r,c) ## x = self.x.duplicate() ## self.A.solve(self.b, x) ## x.axpy(-1, self.x) ## self.assertTrue(x.norm() < 1e-3) ## class BaseTestMatFactorChol(BaseTestMatFactor): def testFactorChol(self): r, c = self.A.getOrdering("natural") self.A.factorCholesky(r) x = self.x.duplicate() self.A.solve(self.b, x) x.axpy(-1, self.x) self.assertTrue(x.norm() < 1e-3) class BaseTestMatFactorICC(BaseTestMatFactor): def testFactorICC(self): r, c = self.A.getOrdering("natural") self.A.factorICC(r) x = self.x.duplicate() self.A.solve(self.b, x) x.axpy(-1, self.x) self.assertTrue(x.norm() < 1e-3) # -------------------------------------------------------------------- class TestMatFactorA1(BaseTestMatFactorLU, BaseTestMatFactorChol, unittest.TestCase): MKSYS = staticmethod(mksys_diag) MTYPE = PETSc.Mat.Type.SEQDENSE class TestMatFactorA2(BaseTestMatFactorLU, BaseTestMatFactorChol, unittest.TestCase): MKSYS = staticmethod(mksys_poi2) MTYPE = PETSc.Mat.Type.SEQDENSE # --- class TestMatFactorB1(BaseTestMatFactorLU, BaseTestMatFactorILU, ## BaseTestMatFactorILUDT, unittest.TestCase): MKSYS = staticmethod(mksys_diag) MTYPE = PETSc.Mat.Type.SEQAIJ class TestMatFactorB2(BaseTestMatFactorLU, BaseTestMatFactorILU, ## BaseTestMatFactorILUDT, unittest.TestCase): MKSYS = staticmethod(mksys_poi2) MTYPE = PETSc.Mat.Type.SEQAIJ # --- class TestMatFactorC1(BaseTestMatFactorLU, BaseTestMatFactorILU, unittest.TestCase): MKSYS = staticmethod(mksys_diag) MTYPE = PETSc.Mat.Type.SEQBAIJ class TestMatFactorC2(BaseTestMatFactorLU, BaseTestMatFactorILU, unittest.TestCase): MKSYS = staticmethod(mksys_poi2) MTYPE = PETSc.Mat.Type.SEQBAIJ # --- class TestMatFactorD1(BaseTestMatFactorChol, BaseTestMatFactorICC, unittest.TestCase): MKSYS = staticmethod(mksys_diag) MTYPE = PETSc.Mat.Type.SEQSBAIJ MOPTS = [PETSc.Mat.Option.IGNORE_LOWER_TRIANGULAR] class TestMatFactorD2(BaseTestMatFactorChol, BaseTestMatFactorICC, unittest.TestCase): MKSYS = staticmethod(mksys_poi2) MTYPE = PETSc.Mat.Type.SEQSBAIJ MOPTS = [PETSc.Mat.Option.IGNORE_LOWER_TRIANGULAR] # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_mat_py.py000066400000000000000000000506121454104047300172540ustar00rootroot00000000000000from petsc4py import PETSc import unittest, numpy from sys import getrefcount # -------------------------------------------------------------------- class Matrix(object): def __init__(self): pass def create(self, mat): pass def destroy(self, mat): pass class ScaledIdentity(Matrix): s = 2.0 def scale(self, mat, s): self.s *= s def shift(self, mat, s): self.s += s def mult(self, mat, x, y): x.copy(y) y.scale(self.s) def duplicate(self, mat, op): dmat = PETSc.Mat() dctx = ScaledIdentity() dmat.createPython(mat.getSizes(), dctx, comm=mat.getComm()) if op == PETSc.Mat.DuplicateOption.COPY_VALUES: dctx.s = self.s dmat.setUp() return dmat def getDiagonal(self, mat, vd): vd.set(self.s) def productSetFromOptions(self, mat, producttype, A, B, C): return True def productSymbolic(self, mat, product, producttype, A, B, C): if producttype == 'AB': if mat is A: # product = identity * B product.setType(B.getType()) product.setSizes(B.getSizes()) product.setUp() product.assemble() B.copy(product) elif mat is B: # product = A * identity product.setType(A.getType()) product.setSizes(A.getSizes()) product.setUp() product.assemble() A.copy(product) else: raise RuntimeError('wrong configuration') elif producttype == 'AtB': if mat is A: # product = identity^T * B product.setType(B.getType()) product.setSizes(B.getSizes()) product.setUp() product.assemble() B.copy(product) elif mat is B: # product = A^T * identity tmp = PETSc.Mat() A.transpose(tmp) product.setType(tmp.getType()) product.setSizes(tmp.getSizes()) product.setUp() product.assemble() tmp.copy(product) else: raise RuntimeError('wrong configuration') elif producttype == 'ABt': if mat is A: # product = identity * B^T tmp = PETSc.Mat() B.transpose(tmp) product.setType(tmp.getType()) product.setSizes(tmp.getSizes()) product.setUp() product.assemble() tmp.copy(product) elif mat is B: # product = A * identity^T product.setType(A.getType()) product.setSizes(A.getSizes()) product.setUp() product.assemble() A.copy(product) else: raise RuntimeError('wrong configuration') elif producttype == 'PtAP': if mat is A: # product = P^T * identity * P self.tmp = PETSc.Mat() B.transposeMatMult(B, self.tmp) product.setType(self.tmp.getType()) product.setSizes(self.tmp.getSizes()) product.setUp() product.assemble() self.tmp.copy(product) elif mat is B: # product = identity^T * A * identity product.setType(A.getType()) product.setSizes(A.getSizes()) product.setUp() product.assemble() A.copy(product) else: raise RuntimeError('wrong configuration') elif producttype == 'RARt': if mat is A: # product = R * identity * R^t self.tmp = PETSc.Mat() B.matTransposeMult(B, self.tmp) product.setType(self.tmp.getType()) product.setSizes(self.tmp.getSizes()) product.setUp() product.assemble() self.tmp.copy(product) elif mat is B: # product = identity * A * identity^T product.setType(A.getType()) product.setSizes(A.getSizes()) product.setUp() product.assemble() A.copy(product) else: raise RuntimeError('wrong configuration') elif producttype == 'ABC': if mat is A: # product = identity * B * C self.tmp = PETSc.Mat() B.matMult(C, self.tmp) product.setType(self.tmp.getType()) product.setSizes(self.tmp.getSizes()) product.setUp() product.assemble() self.tmp.copy(product) elif mat is B: # product = A * identity * C self.tmp = PETSc.Mat() A.matMult(C, self.tmp) product.setType(self.tmp.getType()) product.setSizes(self.tmp.getSizes()) product.setUp() product.assemble() self.tmp.copy(product) elif mat is C: # product = A * B * identity self.tmp = PETSc.Mat() A.matMult(B, self.tmp) product.setType(self.tmp.getType()) product.setSizes(self.tmp.getSizes()) product.setUp() product.assemble() self.tmp.copy(product) else: raise RuntimeError('wrong configuration') else: raise RuntimeError('Product {} not implemented'.format(producttype)) product.zeroEntries() def productNumeric(self, mat, product, producttype, A, B, C): if producttype == 'AB': if mat is A: # product = identity * B B.copy(product, structure=True) elif mat is B: # product = A * identity A.copy(product, structure=True) else: raise RuntimeError('wrong configuration') product.scale(self.s) elif producttype == 'AtB': if mat is A: # product = identity^T * B B.copy(product, structure=True) elif mat is B: # product = A^T * identity A.setTransposePrecursor(product) A.transpose(product) else: raise RuntimeError('wrong configuration') product.scale(self.s) elif producttype == 'ABt': if mat is A: # product = identity * B^T B.setTransposePrecursor(product) B.transpose(product) elif mat is B: # product = A * identity^T A.copy(product, structure=True) else: raise RuntimeError('wrong configuration') product.scale(self.s) elif producttype == 'PtAP': if mat is A: # product = P^T * identity * P B.transposeMatMult(B, self.tmp) self.tmp.copy(product, structure=True) product.scale(self.s) elif mat is B: # product = identity^T * A * identity A.copy(product, structure=True) product.scale(self.s**2) else: raise RuntimeError('wrong configuration') elif producttype == 'RARt': if mat is A: # product = R * identity * R^t B.matTransposeMult(B, self.tmp) self.tmp.copy(product, structure=True) product.scale(self.s) elif mat is B: # product = identity * A * identity^T A.copy(product, structure=True) product.scale(self.s**2) else: raise RuntimeError('wrong configuration') elif producttype == 'ABC': if mat is A: # product = identity * B * C B.matMult(C, self.tmp) self.tmp.copy(product, structure=True) elif mat is B: # product = A * identity * C A.matMult(C, self.tmp) self.tmp.copy(product, structure=True) elif mat is C: # product = A * B * identity A.matMult(B, self.tmp) self.tmp.copy(product, structure=True) else: raise RuntimeError('wrong configuration') product.scale(self.s) else: raise RuntimeError('Product {} not implemented'.format(producttype)) class Diagonal(Matrix): def create(self, mat): super(Diagonal,self).create(mat) mat.setUp() self.D = mat.createVecLeft() def destroy(self, mat): self.D.destroy() super(Diagonal,self).destroy(mat) def scale(self, mat, a): self.D.scale(a) def shift(self, mat, a): self.D.shift(a) def zeroEntries(self, mat): self.D.zeroEntries() def mult(self, mat, x, y): y.pointwiseMult(x, self.D) def duplicate(self, mat, op): dmat = PETSc.Mat() dctx = Diagonal() dmat.createPython(mat.getSizes(), dctx, comm=mat.getComm()) dctx.D = self.D.duplicate() if op == PETSc.Mat.DuplicateOption.COPY_VALUES: self.D.copy(dctx.D) dmat.setUp() return dmat def getDiagonal(self, mat, vd): self.D.copy(vd) def setDiagonal(self, mat, vd, im): if isinstance (im, bool): addv = im if addv: self.D.axpy(1, vd) else: vd.copy(self.D) elif im == PETSc.InsertMode.INSERT_VALUES: vd.copy(self.D) elif im == PETSc.InsertMode.ADD_VALUES: self.D.axpy(1, vd) else: raise ValueError('wrong InsertMode %d'% im) def diagonalScale(self, mat, vl, vr): if vl: self.D.pointwiseMult(self.D, vl) if vr: self.D.pointwiseMult(self.D, vr) # -------------------------------------------------------------------- class TestMatrix(unittest.TestCase): COMM = PETSc.COMM_WORLD PYMOD = __name__ PYCLS = 'Matrix' def _getCtx(self): return self.A.getPythonContext() def setUp(self): N = self.N = 13 self.A = PETSc.Mat() if 0: # command line way self.A.create(self.COMM) self.A.setSizes([N,N]) self.A.setType('python') OptDB = PETSc.Options(self.A) OptDB['mat_python_type'] = '%s.%s' % (self.PYMOD,self.PYCLS) self.A.setFromOptions() self.A.setUp() del OptDB['mat_python_type'] self.assertTrue(self._getCtx() is not None) else: # python way context = globals()[self.PYCLS]() self.A.createPython([N,N], context, comm=self.COMM) self.A.setUp() self.assertTrue(self._getCtx() is context) self.assertEqual(getrefcount(context), 3) del context self.assertEqual(getrefcount(self._getCtx()), 2) def tearDown(self): ctx = self.A.getPythonContext() self.assertEqual(getrefcount(ctx), 3) self.A.destroy() # XXX self.A = None PETSc.garbage_cleanup() self.assertEqual(getrefcount(ctx), 2) #import gc,pprint; pprint.pprint(gc.get_referrers(ctx)) def testBasic(self): ctx = self.A.getPythonContext() self.assertTrue(self._getCtx() is ctx) self.assertEqual(getrefcount(ctx), 3) def testZeroEntries(self): f = lambda : self.A.zeroEntries() self.assertRaises(Exception, f) def testMult(self): x, y = self.A.createVecs() f = lambda : self.A.mult(x, y) self.assertRaises(Exception, f) def testMultTranspose(self): x, y = self.A.createVecs() f = lambda : self.A.multTranspose(x, y) self.assertRaises(Exception, f) def testGetDiagonal(self): d = self.A.createVecLeft() f = lambda : self.A.getDiagonal(d) self.assertRaises(Exception, f) def testSetDiagonal(self): d = self.A.createVecLeft() f = lambda : self.A.setDiagonal(d) self.assertRaises(Exception, f) def testDiagonalScale(self): x, y = self.A.createVecs() f = lambda : self.A.diagonalScale(x, y) self.assertRaises(Exception, f) def testDuplicate(self): f1 = lambda : self.A.duplicate(x, True) f2 = lambda : self.A.duplicate(x, False) self.assertRaises(Exception, f1) self.assertRaises(Exception, f2) def testSetVecType(self): self.A.setVecType('mpi') self.assertTrue('mpi' == self.A.getVecType()) def testH2Opus(self): if not PETSc.Sys.hasExternalPackage("h2opus"): return if self.A.getComm().Get_size() > 1: return h = PETSc.Mat() # need matrix vector and its transpose for norm estimation AA = self.A.getPythonContext() if not hasattr(AA,'mult'): return AA.multTranspose = AA.mult # without coordinates h.createH2OpusFromMat(self.A,leafsize=2) h.assemble() h.destroy() # with coordinates coords = numpy.linspace((1,2,3),(10,20,30),self.A.getSize()[0],dtype=PETSc.RealType) h.createH2OpusFromMat(self.A,coords,leafsize=2) h.assemble() # test API h.H2OpusOrthogonalize() h.H2OpusCompress(1.e-1) # Low-rank update U = PETSc.Mat() U.createDense([h.getSizes()[0],3],comm=h.getComm()) U.setUp() U.setRandom() he = PETSc.Mat() h.convert('dense',he) he.axpy(1.0, U.matTransposeMult(U)) h.H2OpusLowRankUpdate(U) self.assertTrue(he.equal(h)) h.destroy() del AA.multTranspose def testGetType(self): ctx = self.A.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.A.getPythonType() == pytype) class TestScaledIdentity(TestMatrix): PYCLS = 'ScaledIdentity' def testMult(self): s = self._getCtx().s x, y = self.A.createVecs() x.setRandom() self.A.mult(x,y) self.assertTrue(y.equal(s*x)) def testMultTransposeSymmKnown(self): s = self._getCtx().s x, y = self.A.createVecs() x.setRandom() self.A.setOption(PETSc.Mat.Option.SYMMETRIC, True) self.A.multTranspose(x,y) self.assertTrue(y.equal(s*x)) self.A.setOption(PETSc.Mat.Option.SYMMETRIC, False) f = lambda : self.A.multTranspose(x, y) self.assertRaises(Exception, f) def testMultTransposeNewMeth(self): s = self._getCtx().s x, y = self.A.createVecs() x.setRandom() AA = self.A.getPythonContext() AA.multTranspose = AA.mult self.A.multTranspose(x,y) del AA.multTranspose self.assertTrue(y.equal(s*x)) def testGetDiagonal(self): s = self._getCtx().s d = self.A.createVecLeft() o = d.duplicate() o.set(s) self.A.getDiagonal(d) self.assertTrue(o.equal(d)) def testDuplicate(self): B = self.A.duplicate(False) self.assertTrue(B.getPythonContext().s == 2) B = self.A.duplicate(True) self.assertTrue(B.getPythonContext().s == self.A.getPythonContext().s) def testMatMat(self): s = self._getCtx().s R = PETSc.Random().create(self.COMM) R.setFromOptions() A = PETSc.Mat().create(self.COMM) A.setSizes(self.A.getSizes()) A.setType(PETSc.Mat.Type.AIJ) A.setPreallocationNNZ(None) A.setRandom(R) B = PETSc.Mat().create(self.COMM) B.setSizes(self.A.getSizes()) B.setType(PETSc.Mat.Type.AIJ) B.setPreallocationNNZ(None) B.setRandom(R) I = PETSc.Mat().create(self.COMM) I.setSizes(self.A.getSizes()) I.setType(PETSc.Mat.Type.AIJ) I.setUp() I.assemble() I.shift(s) self.assertTrue(self.A.matMult(A).equal(I.matMult(A))) self.assertTrue(A.matMult(self.A).equal(A.matMult(I))) if self.A.getComm().Get_size() == 1: self.assertTrue(self.A.matTransposeMult(A).equal(I.matTransposeMult(A))) self.assertTrue(A.matTransposeMult(self.A).equal(A.matTransposeMult(I))) self.assertTrue(self.A.transposeMatMult(A).equal(I.transposeMatMult(A))) self.assertTrue(A.transposeMatMult(self.A).equal(A.transposeMatMult(I))) self.assertAlmostEqual((self.A.ptap(A) - I.ptap(A)).norm(), 0.0, places=5) self.assertAlmostEqual((A.ptap(self.A) - A.ptap(I)).norm(), 0.0, places=5) if self.A.getComm().Get_size() == 1: self.assertAlmostEqual((self.A.rart(A) - I.rart(A)).norm(), 0.0, places=5) self.assertAlmostEqual((A.rart(self.A) - A.rart(I)).norm(), 0.0, places=5) self.assertAlmostEqual((self.A.matMatMult(A,B)-I.matMatMult(A,B)).norm(), 0.0, places=5) self.assertAlmostEqual((A.matMatMult(self.A,B)-A.matMatMult(I,B)).norm(), 0.0, places=5) self.assertAlmostEqual((A.matMatMult(B,self.A)-A.matMatMult(B,I)).norm(), 0.0, places=5) def testShift(self): sold = self._getCtx().s self.A.shift(-0.5) s = self._getCtx().s self.assertTrue(s == sold - 0.5) def testScale(self): sold = self._getCtx().s self.A.scale(-0.5) s = self._getCtx().s self.assertTrue(s == sold * -0.5) class TestDiagonal(TestMatrix): PYCLS = 'Diagonal' def setUp(self): super(TestDiagonal, self).setUp() D = self.A.createVecLeft() s, e = D.getOwnershipRange() for i in range(s, e): D[i] = i+1 D.assemble() self.A.setDiagonal(D) def testZeroEntries(self): self.A.zeroEntries() D = self._getCtx().D self.assertEqual(D.norm(), 0) def testMult(self): x, y = self.A.createVecs() x.set(1) self.A.mult(x,y) self.assertTrue(y.equal(self._getCtx().D)) def testMultTransposeSymmKnown(self): x, y = self.A.createVecs() x.set(1) self.A.setOption(PETSc.Mat.Option.SYMMETRIC, True) self.A.multTranspose(x,y) self.assertTrue(y.equal(self._getCtx().D)) self.A.setOption(PETSc.Mat.Option.SYMMETRIC, False) f = lambda : self.A.multTranspose(x, y) self.assertRaises(Exception, f) def testMultTransposeNewMeth(self): x, y = self.A.createVecs() x.set(1) AA = self.A.getPythonContext() AA.multTranspose = AA.mult self.A.multTranspose(x,y) del AA.multTranspose self.assertTrue(y.equal(self._getCtx().D)) def testDuplicate(self): B = self.A.duplicate(False) B = self.A.duplicate(True) self.assertTrue(B.getPythonContext().D.equal(self.A.getPythonContext().D)) def testGetDiagonal(self): d = self.A.createVecLeft() self.A.getDiagonal(d) self.assertTrue(d.equal(self._getCtx().D)) def testSetDiagonal(self): d = self.A.createVecLeft() d.setRandom() self.A.setDiagonal(d) self.assertTrue(d.equal(self._getCtx().D)) def testDiagonalScale(self): x, y = self.A.createVecs() x.set(2) y.set(3) old = self._getCtx().D.copy() self.A.diagonalScale(x, y) D = self._getCtx().D self.assertTrue(D.equal(old*6)) def testCreateTranspose(self): A = self.A A.setOption(PETSc.Mat.Option.SYMMETRIC, True) AT = PETSc.Mat().createTranspose(A) x, y = A.createVecs() xt, yt = AT.createVecs() # y.setRandom() A.multTranspose(y, x) y.copy(xt) AT.mult(xt, yt) self.assertTrue(yt.equal(x)) # x.setRandom() A.mult(x, y) x.copy(yt) AT.multTranspose(yt, xt) self.assertTrue(xt.equal(y)) del A def testConvert(self): self.assertTrue(self.A.convert(PETSc.Mat.Type.AIJ,PETSc.Mat()).equal(self.A)) self.assertTrue(self.A.convert(PETSc.Mat.Type.BAIJ,PETSc.Mat()).equal(self.A)) self.assertTrue(self.A.convert(PETSc.Mat.Type.SBAIJ,PETSc.Mat()).equal(self.A)) self.assertTrue(self.A.convert(PETSc.Mat.Type.DENSE,PETSc.Mat()).equal(self.A)) def testShift(self): old = self._getCtx().D.copy() self.A.shift(-0.5) D = self._getCtx().D self.assertTrue(D.equal(old-0.5)) def testScale(self): old = self._getCtx().D.copy() self.A.scale(-0.5) D = self._getCtx().D self.assertTrue(D.equal(-0.5*old)) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_nsp.py000066400000000000000000000047131454104047300165640ustar00rootroot00000000000000import unittest from petsc4py import PETSc import numpy as N from sys import getrefcount # -------------------------------------------------------------------- def allclose(seq1, seq2): for v1, v2 in zip(seq1, seq2): if abs(v1-v2) > 1e-5: return False return True class TestNullSpace(unittest.TestCase): def setUp(self): u1 = PETSc.Vec().createSeq(3) u2 = PETSc.Vec().createSeq(3) u1[0], u1[1], u1[2] = [1, 2, 0]; u1.normalize() u2[0], u2[1], u2[2] = [2, -1, 0]; u2.normalize() basis = [u1, u2] nullsp = PETSc.NullSpace().create(False, basis, comm=PETSc.COMM_SELF) self.basis = basis self.nullsp = nullsp def tearDown(self): self.basis = None self.nullsp = None PETSc.garbage_cleanup() def _remove(self): v = PETSc.Vec().createSeq(3); v[0], v[1], v[2] = [7, 8, 9] w = v.copy() self.nullsp.remove(w) return (v, w) def testRemove(self): v, w = self._remove() tols = (0, 1e-5) self.assertTrue(allclose(v.array, [7, 8, 9])) self.assertTrue(allclose(w.array, [0, 0, 9])) del v, w def testRemoveInplace(self): v, w = self._remove() self.nullsp.remove(v) self.assertTrue(v.equal(w)) del v, w def testRemoveWithFunction(self): def myremove(nsp, vec): vec.setArray([1,2,3]) self.nullsp.setFunction(myremove) v, w = self._remove() self.assertTrue(allclose(v.array, [7, 8, 9])) self.assertTrue(allclose(w.array, [1, 2, 3])) self.nullsp.remove(v) self.assertTrue(allclose(v.array, [1, 2, 3])) self.nullsp.setFunction(None) self.testRemove() def testGetSetFunction(self): def rem(nsp, vec): vec.set(0) self.nullsp.setFunction(rem) self.assertEqual(getrefcount(rem)-1, 2) dct = self.nullsp.getDict() self.assertTrue(dct is not None) self.assertEqual(getrefcount(dct)-1, 2) fun, a, kw = dct['__function__'] self.assertTrue(fun is rem) self.nullsp.setFunction(None) fun = dct.get('__function__') self.assertEqual(getrefcount(rem)-1, 1) self.assertTrue(fun is None) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_object.py000066400000000000000000000213401454104047300172250ustar00rootroot00000000000000import unittest from petsc4py import PETSc # -------------------------------------------------------------------- class BaseTestObject(object): CLASS, FACTORY = None, None 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 PETSc.garbage_cleanup() 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__ if name == 'DMDA': name = 'DM' 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): import copy try: myobj = copy.deepcopy(self.obj) except NotImplementedError: return 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): 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 def testStateInspection(self): state = self.obj.stateGet() self.obj.stateIncrease() self.assertTrue(state < self.obj.stateGet()) self.obj.stateSet(0) self.assertTrue(self.obj.stateGet() == 0) self.obj.stateSet(state) self.assertTrue(self.obj.stateGet() == state) # -------------------------------------------------------------------- class TestObjectRandom(BaseTestObject, unittest.TestCase): CLASS = PETSc.Random FACTORY = 'create' class TestObjectViewer(BaseTestObject, unittest.TestCase): CLASS = PETSc.Viewer FACTORY = 'create' class TestObjectIS(BaseTestObject, unittest.TestCase): CLASS = PETSc.IS FACTORY = 'createGeneral' TARGS = ([],) class TestObjectLGMap(BaseTestObject, unittest.TestCase): CLASS = PETSc.LGMap FACTORY = 'create' TARGS = ([],) class TestObjectAO(BaseTestObject, unittest.TestCase): CLASS = PETSc.AO FACTORY = 'createMapping' TARGS = ([], []) class TestObjectDMDA(BaseTestObject, unittest.TestCase): CLASS = PETSc.DMDA FACTORY = 'create' TARGS = ([3,3,3],) class TestObjectDS(BaseTestObject, unittest.TestCase): CLASS = PETSc.DS FACTORY = 'create' class TestObjectVec(BaseTestObject, unittest.TestCase): CLASS = PETSc.Vec FACTORY = 'createSeq' TARGS = (0,) def setUp(self): BaseTestObject.setUp(self) self.obj.assemble() class TestObjectMat(BaseTestObject, unittest.TestCase): CLASS = PETSc.Mat FACTORY = 'createAIJ' TARGS = (0,) KARGS = {'nnz':0, 'comm': PETSc.COMM_SELF} def setUp(self): BaseTestObject.setUp(self) self.obj.assemble() class TestObjectMatPartitioning(BaseTestObject, unittest.TestCase): CLASS = PETSc.MatPartitioning FACTORY = 'create' class TestObjectNullSpace(BaseTestObject, unittest.TestCase): CLASS = PETSc.NullSpace FACTORY = 'create' TARGS = (True, []) class TestObjectKSP(BaseTestObject, unittest.TestCase): CLASS = PETSc.KSP FACTORY = 'create' class TestObjectPC(BaseTestObject, unittest.TestCase): CLASS = PETSc.PC FACTORY = 'create' class TestObjectSNES(BaseTestObject, unittest.TestCase): CLASS = PETSc.SNES FACTORY = 'create' class TestObjectTS(BaseTestObject, unittest.TestCase): CLASS = PETSc.TS FACTORY = 'create' def setUp(self): super(TestObjectTS, self).setUp() self.obj.setProblemType(PETSc.TS.ProblemType.NONLINEAR) self.obj.setType(PETSc.TS.Type.BEULER) class TestObjectTAO(BaseTestObject, unittest.TestCase): CLASS = PETSc.TAO FACTORY = 'create' class TestObjectAOBasic(BaseTestObject, unittest.TestCase): CLASS = PETSc.AO FACTORY = 'createBasic' TARGS = ([], []) class TestObjectAOMapping(BaseTestObject, unittest.TestCase): CLASS = PETSc.AO FACTORY = 'createMapping' TARGS = ([], []) # class TestObjectFE(BaseTestObject, unittest.TestCase): # CLASS = PETSc.FE # FACTORY = 'create' # # class TestObjectQuad(BaseTestObject, unittest.TestCase): # CLASS = PETSc.Quad # FACTORY = 'create' class TestObjectDMLabel(BaseTestObject, unittest.TestCase): CLASS = PETSc.DMLabel FACTORY = 'create' TARGS = ("test",) class TestObjectSpace(BaseTestObject, unittest.TestCase): CLASS = PETSc.Space FACTORY = 'create' class TestObjectDualSpace(BaseTestObject, unittest.TestCase): CLASS = PETSc.DualSpace FACTORY = 'create' # -------------------------------------------------------------------- import numpy if numpy.iscomplexobj(PETSc.ScalarType()): del TestObjectTAO if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_optdb.py000066400000000000000000000053501454104047300170720ustar00rootroot00000000000000import unittest from petsc4py import PETSc from sys import getrefcount # -------------------------------------------------------------------- class TestOptions(unittest.TestCase): PREFIX = 'myopts-' OPTLIST = [('bool', True), ('int', -7), ('real', 5), ('scalar', 3), ('string', 'petsc4py'), ] def _putopts(self, opts=None, OPTLIST=None): if opts is None: opts = self.opts if OPTLIST is None: OPTLIST = self.OPTLIST for k,v in OPTLIST: opts[k] = v def _delopts(self, opts=None, OPTLIST=None): if opts is None: opts = self.opts if OPTLIST is None: OPTLIST = self.OPTLIST for k,v in OPTLIST: del opts[k] def setUp(self): self.opts = PETSc.Options(self.PREFIX) def tearDown(self): self.opts = None PETSc.garbage_cleanup() def testHasOpts(self): self._putopts() for k, v in self.OPTLIST: self.assertTrue(self.opts.hasName(k)) self.assertTrue(k in self.opts) missing = k+'-missing' self.assertFalse(self.opts.hasName(missing)) self.assertFalse(missing in self.opts) self._delopts() def testGetOpts(self): self._putopts() for k, v in self.OPTLIST: getopt = getattr(self.opts, 'get'+k.title()) self.assertEqual(getopt(k), v) self._delopts() def testGetAll(self): self._putopts() allopts = self.opts.getAll() self.assertTrue(type(allopts) is dict) optlist = [(k, str(v).lower()) for (k,v) in self.OPTLIST] for k,v in allopts.items(): self.assertTrue((k, v) in optlist) self._delopts() def testGetAllQuoted(self): dct = {'o0' : '"0 1 2"', 'o1' : '"a b c"', 'o2' : '"x y z"',} for k in dct: self.opts[k] = dct[k] allopts = self.opts.getAll() for k in dct: self.assertEqual(allopts[k], dct[k][1:-1]) del self.opts[k] def testMonitor(self): optlist = [] mon = lambda n,v: optlist.append((n,v)) self.opts.setMonitor(mon) self.assertEqual(getrefcount(mon)-1, 2) self._putopts() target = [(self.PREFIX+k, str(v).lower()) for k, v in self.OPTLIST] self.assertEqual(optlist, target) self.opts.cancelMonitor() self.assertEqual(getrefcount(mon)-1, 1) self._delopts() # -------------------------------------------------------------------- del TestOptions.testMonitor # XXX if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_pc_py.py000066400000000000000000000236151454104047300171000ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest from sys import getrefcount # -------------------------------------------------------------------- class BaseMyPC(object): def setup(self, pc): pass def reset(self, pc): pass def apply(self, pc, x, y): raise NotImplementedError def applyT(self, pc, x, y): self.apply(pc, x, y) def applyS(self, pc, x, y): self.apply(pc, x, y) def applySL(self, pc, x, y): self.applyS(pc, x, y) def applySR(self, pc, x, y): self.applyS(pc, x, y) def applyRich(self, pc, x, y, w, tols): self.apply(pc, x, y) def applyM(self, pc, x, y): raise NotImplementedError class MyPCNone(BaseMyPC): def apply(self, pc, x, y): x.copy(y) def applyM(self, pc, x, y): x.copy(y) class MyPCJacobi(BaseMyPC): def setup(self, pc): A, P = pc.getOperators() self.diag = P.getDiagonal() self.diag.reciprocal() def reset(self, pc): self.diag.destroy() del self.diag def apply(self, pc, x, y): y.pointwiseMult(self.diag, x) def applyS(self, pc, x, y): self.diag.copy(y) y.sqrtabs() y.pointwiseMult(y, x) def applyM(self, pc, x, y): x.copy(y) y.diagonalScale(L=self.diag) class PC_PYTHON_CLASS(object): def __init__(self): self.impl = None self.log = {} def _log(self, method, *args): self.log.setdefault(method, 0) self.log[method] += 1 def create(self, pc): self._log('create', pc) def destroy(self, pc): self._log('destroy') self.impl = None def reset(self, pc): self._log('reset', pc) def view(self, pc, vw): self._log('view', pc, vw) assert isinstance(pc, PETSc.PC) assert isinstance(vw, PETSc.Viewer) pass def setFromOptions(self, pc): self._log('setFromOptions', pc) assert isinstance(pc, PETSc.PC) OptDB = PETSc.Options(pc) impl = OptDB.getString('impl','MyPCNone') klass = globals()[impl] self.impl = klass() def setUp(self, pc): self._log('setUp', pc) assert isinstance(pc, PETSc.PC) self.impl.setup(pc) def preSolve(self, pc, ksp, b, x): self._log('preSolve', pc, ksp, b, x) def postSolve(self, pc, ksp, b, x): self._log('postSolve', pc, ksp, b, x) def apply(self, pc, x, y): self._log('apply', pc, x, y) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Vec) assert isinstance(y, PETSc.Vec) self.impl.apply(pc, x, y) def applySymmetricLeft(self, pc, x, y): self._log('applySymmetricLeft', pc, x, y) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Vec) assert isinstance(y, PETSc.Vec) self.impl.applySL(pc, x, y) def applySymmetricRight(self, pc, x, y): self._log('applySymmetricRight', pc, x, y) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Vec) assert isinstance(y, PETSc.Vec) self.impl.applySR(pc, x, y) def applyTranspose(self, pc, x, y): self._log('applyTranspose', pc, x, y) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Vec) assert isinstance(y, PETSc.Vec) self.impl.applyT(pc, x, y) def matApply(self, pc, x, y): self._log('matApply', pc, x, y) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Mat) assert isinstance(y, PETSc.Mat) self.impl.applyM(pc, x, y) def applyRichardson(self, pc, x, y, w, tols): self._log('applyRichardson', pc, x, y, w, tols) assert isinstance(pc, PETSc.PC) assert isinstance(x, PETSc.Vec) assert isinstance(y, PETSc.Vec) assert isinstance(w, PETSc.Vec) assert isinstance(tols, tuple) assert len(tols) == 4 self.impl.applyRich(pc, x, y, w, tols) class TestPCPYTHON(unittest.TestCase): PC_TYPE = PETSc.PC.Type.PYTHON PC_PREFIX = 'test-' def setUp(self): pc = self.pc = PETSc.PC() pc.create(PETSc.COMM_SELF) pc.setType(self.PC_TYPE) module = __name__ factory = 'PC_PYTHON_CLASS' self.pc.prefix = self.PC_PREFIX OptDB = PETSc.Options(self.pc) assert OptDB.prefix == self.pc.prefix OptDB['pc_python_type'] = '%s.%s' % (module, factory) self.pc.setFromOptions() del OptDB['pc_python_type'] assert self._getCtx().log['create'] == 1 assert self._getCtx().log['setFromOptions'] == 1 ctx = self._getCtx() self.assertEqual(getrefcount(ctx), 3) def testGetType(self): ctx = self.pc.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.pc.getPythonType() == pytype) def tearDown(self): ctx = self._getCtx() self.pc.destroy() # XXX self.pc = None PETSc.garbage_cleanup() assert ctx.log['destroy'] == 1 self.assertEqual(getrefcount(ctx), 2) def _prepare(self): A = PETSc.Mat().createAIJ([3,3], comm=PETSc.COMM_SELF) A.setUp() A.assemble() A.shift(10) x, y = A.createVecs() x.setRandom() self.pc.setOperators(A, A) X = PETSc.Mat().createDense([3,5], comm=PETSc.COMM_SELF).setUp() X.assemble() Y = PETSc.Mat().createDense([3,5], comm=PETSc.COMM_SELF).setUp() Y.assemble() assert (A,A) == self.pc.getOperators() return A, x, y, X, Y def _getCtx(self): return self.pc.getPythonContext() def _applyMeth(self, meth): A, x, y, X, Y = self._prepare() if meth == 'matApply': getattr(self.pc, meth)(X,Y) x.copy(y) else: getattr(self.pc, meth)(x,y) X.copy(Y) if 'reset' not in self._getCtx().log: assert self._getCtx().log['setUp'] == 1 assert self._getCtx().log[meth] == 1 else: nreset = self._getCtx().log['reset'] nsetup = self._getCtx().log['setUp'] nmeth = self._getCtx().log[meth] assert (nreset == nsetup) assert (nreset == nmeth) if isinstance(self._getCtx().impl, MyPCNone): self.assertTrue(y.equal(x)) self.assertTrue(Y.equal(X)) def testApply(self): self._applyMeth('apply') def testApplySymmetricLeft(self): self._applyMeth('applySymmetricLeft') def testApplySymmetricRight(self): self._applyMeth('applySymmetricRight') def testApplyTranspose(self): self._applyMeth('applyTranspose') def testApplyMat(self): self._applyMeth('matApply') ## def testApplyRichardson(self): ## x, y = self._prepare() ## w = x.duplicate() ## tols = 0,0,0,0 ## self.pc.applyRichardson(x,y,w,tols) ## assert self._getCtx().log['setUp'] == 1 ## assert self._getCtx().log['applyRichardson'] == 1 ## def testView(self): ## vw = PETSc.ViewerString(100, self.pc.comm) ## self.pc.view(vw) ## s = vw.getString() ## assert 'python' in s ## module = __name__ ## factory = 'self._getCtx()' ## assert '.'.join([module, factory]) in s def testResetAndApply(self): self.pc.reset() self.testApply() self.pc.reset() self.testApply() self.pc.reset() def testKSPSolve(self): A, x, y, _, _ = self._prepare() ksp = PETSc.KSP().create(self.pc.comm) ksp.setType(PETSc.KSP.Type.PREONLY) assert self.pc.getRefCount() == 1 ksp.setPC(self.pc) assert self.pc.getRefCount() == 2 # normal ksp solve, twice ksp.solve(x,y) assert self._getCtx().log['setUp' ] == 1 assert self._getCtx().log['apply' ] == 1 assert self._getCtx().log['preSolve' ] == 1 assert self._getCtx().log['postSolve'] == 1 ksp.solve(x,y) assert self._getCtx().log['setUp' ] == 1 assert self._getCtx().log['apply' ] == 2 assert self._getCtx().log['preSolve' ] == 2 assert self._getCtx().log['postSolve'] == 2 # transpose ksp solve, twice ksp.solveTranspose(x,y) assert self._getCtx().log['setUp' ] == 1 assert self._getCtx().log['applyTranspose'] == 1 ksp.solveTranspose(x,y) assert self._getCtx().log['setUp' ] == 1 assert self._getCtx().log['applyTranspose'] == 2 del ksp # ksp.destroy() PETSc.garbage_cleanup() self.assertEqual(self.pc.getRefCount(), 1) def testGetSetContext(self): ctx = self.pc.getPythonContext() self.pc.setPythonContext(ctx) self.assertEqual(getrefcount(ctx), 3) del ctx class TestPCPYTHON2(TestPCPYTHON): def setUp(self): OptDB = PETSc.Options(self.PC_PREFIX) OptDB['impl'] = 'MyPCJacobi' super(TestPCPYTHON2, self).setUp() clsname = type(self._getCtx().impl).__name__ assert clsname == OptDB['impl'] del OptDB['impl'] class TestPCPYTHON3(TestPCPYTHON): def setUp(self): pc = self.pc = PETSc.PC() ctx = PC_PYTHON_CLASS() pc.createPython(ctx, comm=PETSc.COMM_SELF) self.pc.prefix = self.PC_PREFIX self.pc.setFromOptions() assert self._getCtx().log['create'] == 1 assert self._getCtx().log['setFromOptions'] == 1 class TestPCPYTHON4(TestPCPYTHON3): def setUp(self): OptDB = PETSc.Options(self.PC_PREFIX) OptDB['impl'] = 'MyPCJacobi' super(TestPCPYTHON4, self).setUp() clsname = type(self._getCtx().impl).__name__ assert clsname == OptDB['impl'] del OptDB['impl'] # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_snes.py000066400000000000000000000313361454104047300167350ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest from sys import getrefcount import numpy # -------------------------------------------------------------------- class Function: def __call__(self, snes, x, f): f[0] = (x[0]*x[0] + x[0]*x[1] - 3.0).item() f[1] = (x[0]*x[1] + x[1]*x[1] - 6.0).item() f.assemble() class Jacobian: def __call__(self, snes, x, J, P): P[0,0] = (2.0*x[0] + x[1]).item() P[0,1] = (x[0]).item() P[1,0] = (x[1]).item() P[1,1] = (x[0] + 2.0*x[1]).item() P.assemble() if J != P: J.assemble() # -------------------------------------------------------------------- class BaseTestSNES(object): SNES_TYPE = None def setUp(self): snes = PETSc.SNES() snes.create(PETSc.COMM_SELF) if self.SNES_TYPE: snes.setType(self.SNES_TYPE) self.snes = snes def tearDown(self): self.snes = None PETSc.garbage_cleanup() def testGetSetType(self): self.assertEqual(self.snes.getType(), self.SNES_TYPE) self.snes.setType(self.SNES_TYPE) self.assertEqual(self.snes.getType(), self.SNES_TYPE) def testTols(self): tols = self.snes.getTolerances() self.snes.setTolerances(*tols) tnames = ('rtol', 'atol','stol', 'max_it') tolvals = [getattr(self.snes, t) for t in tnames] self.assertEqual(tuple(tols), tuple(tolvals)) def testProperties(self): snes = self.snes # snes.appctx = (1,2,3) self.assertEqual(snes.appctx, (1,2,3)) snes.appctx = None self.assertEqual(snes.appctx, None) # snes.its = 1 self.assertEqual(snes.its, 1) snes.its = 0 self.assertEqual(snes.its, 0) # snes.norm = 1 self.assertEqual(snes.norm, 1) snes.norm = 0 self.assertEqual(snes.norm, 0) # rh, ih = snes.history self.assertTrue(len(rh)==0) self.assertTrue(len(ih)==0) # reason = PETSc.SNES.ConvergedReason.CONVERGED_ITS snes.reason = reason self.assertEqual(snes.reason, reason) self.assertTrue(snes.converged) self.assertFalse(snes.diverged) self.assertFalse(snes.iterating) reason = PETSc.SNES.ConvergedReason.DIVERGED_MAX_IT snes.reason = reason self.assertEqual(snes.reason, reason) self.assertFalse(snes.converged) self.assertTrue(snes.diverged) self.assertFalse(snes.iterating) reason = PETSc.SNES.ConvergedReason.CONVERGED_ITERATING snes.reason = reason self.assertEqual(snes.reason, reason) self.assertFalse(snes.converged) self.assertFalse(snes.diverged) self.assertTrue(snes.iterating) # self.assertFalse(snes.use_ew) self.assertFalse(snes.use_mf) self.assertFalse(snes.use_fd) def testGetSetFunc(self): r, func = self.snes.getFunction() self.assertFalse(r) self.assertTrue(func is None) r = PETSc.Vec().createSeq(2) func = Function() refcnt = getrefcount(func) self.snes.setFunction(func, r) self.snes.setFunction(func, r) self.assertEqual(getrefcount(func), refcnt + 1) r2, func2 = self.snes.getFunction() self.assertEqual(r, r2) self.assertEqual(func, func2[0]) self.assertEqual(getrefcount(func), refcnt + 1) r3, func3 = self.snes.getFunction() self.assertEqual(r, r3) self.assertEqual(func, func3[0]) self.assertEqual(getrefcount(func), refcnt + 1) def testCompFunc(self): r = PETSc.Vec().createSeq(2) func = Function() self.snes.setFunction(func, r) x, y = r.duplicate(), r.duplicate() x[0], x[1] = [1, 2] self.snes.computeFunction(x, y) self.assertAlmostEqual(abs(y[0]), 0.0, places=5) self.assertAlmostEqual(abs(y[1]), 0.0, places=5) def testGetSetJac(self): A, P, jac = self.snes.getJacobian() self.assertFalse(A) self.assertFalse(P) self.assertTrue(jac is None) J = PETSc.Mat().create(PETSc.COMM_SELF) J.setSizes([2,2]) J.setType(PETSc.Mat.Type.SEQAIJ) J.setUp() jac = Jacobian() refcnt = getrefcount(jac) self.snes.setJacobian(jac, J) self.snes.setJacobian(jac, J) self.assertEqual(getrefcount(jac), refcnt + 1) J2, P2, jac2 = self.snes.getJacobian() self.assertEqual(J, J2) self.assertEqual(J2, P2) self.assertEqual(jac, jac2[0]) self.assertEqual(getrefcount(jac), refcnt + 1) J3, P3, jac3 = self.snes.getJacobian() self.assertEqual(J, J3) self.assertEqual(J3, P3) self.assertEqual(jac, jac3[0]) self.assertEqual(getrefcount(jac), refcnt + 1) def testCompJac(self): J = PETSc.Mat().create(PETSc.COMM_SELF) J.setSizes([2,2]) J.setType(PETSc.Mat.Type.SEQAIJ) J.setUp() jac = Jacobian() self.snes.setJacobian(jac, J) x = PETSc.Vec().createSeq(2) x[0], x[1] = [1, 2] self.snes.getKSP().getPC() self.snes.computeJacobian(x, J) def testGetSetUpd(self): self.assertTrue(self.snes.getUpdate() is None) upd = lambda snes, it: None refcnt = getrefcount(upd) self.snes.setUpdate(upd) self.assertEqual(getrefcount(upd), refcnt + 1) self.snes.setUpdate(upd) self.assertEqual(getrefcount(upd), refcnt + 1) self.snes.setUpdate(None) self.assertTrue(self.snes.getUpdate() is None) self.assertEqual(getrefcount(upd), refcnt) self.snes.setUpdate(upd) self.assertEqual(getrefcount(upd), refcnt + 1) upd2 = lambda snes, it: None refcnt2 = getrefcount(upd2) self.snes.setUpdate(upd2) self.assertEqual(getrefcount(upd), refcnt) self.assertEqual(getrefcount(upd2), refcnt2 + 1) tmp = self.snes.getUpdate()[0] self.assertTrue(tmp is upd2) self.assertEqual(getrefcount(upd2), refcnt2 + 2) del tmp self.snes.setUpdate(None) self.assertTrue(self.snes.getUpdate() is None) self.assertEqual(getrefcount(upd2), refcnt2) def testGetKSP(self): ksp = self.snes.getKSP() self.assertEqual(ksp.getRefCount(), 2) def testSolve(self): J = PETSc.Mat().create(PETSc.COMM_SELF) J.setSizes([2,2]) J.setType(PETSc.Mat.Type.SEQAIJ) J.setUp() r = PETSc.Vec().createSeq(2) x = PETSc.Vec().createSeq(2) b = PETSc.Vec().createSeq(2) self.snes.setFunction(Function(), r) self.snes.setJacobian(Jacobian(), J) x.setArray([2,3]) b.set(0) self.snes.setConvergenceHistory() self.snes.setFromOptions() self.snes.solve(b, x) rh, ih = self.snes.getConvergenceHistory() self.snes.setConvergenceHistory(0, reset=True) rh, ih = self.snes.getConvergenceHistory() self.assertEqual(len(rh), 0) self.assertEqual(len(ih), 0) self.assertAlmostEqual(abs(x[0]), 1.0, places=5) self.assertAlmostEqual(abs(x[1]), 2.0, places=5) # XXX this test should not be here ! reason = self.snes.callConvergenceTest(1, 0, 0, 0) self.assertTrue(reason > 0) # test interface x = self.snes.getSolution() x.setArray([2,3]) self.snes.solve() self.assertAlmostEqual(abs(x[0]), 1.0, places=5) self.assertAlmostEqual(abs(x[1]), 2.0, places=5) def testResetAndSolve(self): self.snes.reset() self.testSolve() self.snes.reset() self.testSolve() self.snes.reset() def testSetMonitor(self): reshist = {} def monitor(snes, its, fgnorm): reshist[its] = fgnorm refcnt = getrefcount(monitor) self.snes.setMonitor(monitor) self.assertEqual(getrefcount(monitor), refcnt + 1) self.testSolve() self.assertTrue(len(reshist) > 0) reshist = {} self.snes.monitorCancel() self.assertEqual(getrefcount(monitor), refcnt) self.testSolve() self.assertTrue(len(reshist) == 0) self.snes.setMonitor(monitor) self.snes.monitor(1, 7) self.assertTrue(reshist[1] == 7) ## Monitor = PETSc.SNES.Monitor ## self.snes.setMonitor(Monitor()) ## self.snes.setMonitor(Monitor.DEFAULT) ## self.snes.setMonitor(Monitor.SOLUTION) ## self.snes.setMonitor(Monitor.RESIDUAL) ## self.snes.setMonitor(Monitor.SOLUTION_UPDATE) def testSetGetStepFails(self): its = self.snes.getIterationNumber() self.assertEqual(its, 0) fails = self.snes.getNonlinearStepFailures() self.assertEqual(fails, 0) fails = self.snes.getMaxNonlinearStepFailures() self.assertEqual(fails, 1) self.snes.setMaxNonlinearStepFailures(5) fails = self.snes.getMaxNonlinearStepFailures() self.assertEqual(fails, 5) self.snes.setMaxNonlinearStepFailures(1) fails = self.snes.getMaxNonlinearStepFailures() self.assertEqual(fails, 1) def testSetGetLinFails(self): its = self.snes.getLinearSolveIterations() self.assertEqual(its, 0) fails = self.snes.getLinearSolveFailures() self.assertEqual(fails, 0) fails = self.snes.getMaxLinearSolveFailures() self.assertEqual(fails, 1) self.snes.setMaxLinearSolveFailures(5) fails = self.snes.getMaxLinearSolveFailures() self.assertEqual(fails, 5) self.snes.setMaxLinearSolveFailures(1) fails = self.snes.getMaxLinearSolveFailures() self.assertEqual(fails, 1) def testEW(self): self.snes.setUseEW(False) self.assertFalse(self.snes.getUseEW()) self.snes.setUseEW(True) self.assertTrue(self.snes.getUseEW()) params = self.snes.getParamsEW() params['version'] = 1 self.snes.setParamsEW(**params) params = self.snes.getParamsEW() self.assertEqual(params['version'], 1) params['version'] = PETSc.DEFAULT self.snes.setParamsEW(**params) params = self.snes.getParamsEW() self.assertEqual(params['version'], 1) def testMF(self): #self.snes.setOptionsPrefix('MF-') #opts = PETSc.Options(self.snes) #opts['mat_mffd_type'] = 'ds' #opts['snes_monitor'] = 'stdout' #opts['ksp_monitor'] = 'stdout' #opts['snes_view'] = 'stdout' J = PETSc.Mat().create(PETSc.COMM_SELF) J.setSizes([2,2]) J.setType(PETSc.Mat.Type.SEQAIJ) J.setUp() r = PETSc.Vec().createSeq(2) x = PETSc.Vec().createSeq(2) b = PETSc.Vec().createSeq(2) fun = Function() jac = Jacobian() self.snes.setFunction(fun, r) self.snes.setJacobian(jac, J) self.assertFalse(self.snes.getUseMF()) self.snes.setUseMF(False) self.assertFalse(self.snes.getUseMF()) self.snes.setUseMF(True) self.assertTrue(self.snes.getUseMF()) self.snes.setFromOptions() if self.snes.getType() != PETSc.SNES.Type.NEWTONTR: x.setArray([2,3]) b.set(0) self.snes.solve(b, x) self.assertAlmostEqual(abs(x[0]), 1.0, places=5) self.assertAlmostEqual(abs(x[1]), 2.0, places=5) def testFDColor(self): J = PETSc.Mat().create(PETSc.COMM_SELF) J.setSizes([2,2]) J.setType(PETSc.Mat.Type.SEQAIJ) J.setUp() r = PETSc.Vec().createSeq(2) x = PETSc.Vec().createSeq(2) b = PETSc.Vec().createSeq(2) fun = Function() jac = Jacobian() self.snes.setFunction(fun, r) self.snes.setJacobian(jac, J) self.assertFalse(self.snes.getUseFD()) jac(self.snes, x, J, J) self.snes.setUseFD(False) self.assertFalse(self.snes.getUseFD()) self.snes.setUseFD(True) self.assertTrue(self.snes.getUseFD()) self.snes.setFromOptions() x.setArray([2,3]) b.set(0) self.snes.solve(b, x) self.assertAlmostEqual(abs(x[0]), 1.0, places=4) self.assertAlmostEqual(abs(x[1]), 2.0, places=4) def testNPC(self): self.snes.appctx = (1,2,3) npc = self.snes.getNPC() self.assertEqual(npc.appctx, (1,2,3)) # -------------------------------------------------------------------- class TestSNESLS(BaseTestSNES, unittest.TestCase): SNES_TYPE = PETSc.SNES.Type.NEWTONLS class TestSNESTR(BaseTestSNES, unittest.TestCase): SNES_TYPE = PETSc.SNES.Type.NEWTONTR # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_snes_py.py000066400000000000000000000060271454104047300174440ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest from sys import getrefcount # -------------------------------------------------------------------- class MySNES(object): def __init__(self): self.trace = False self.call_log = {} def _log(self, method, *args): self.call_log.setdefault(method, 0) self.call_log[method] += 1 if not self.trace: return clsname = self.__class__.__name__ pargs = [] for a in args: pargs.append(a) if isinstance(a, PETSc.Object): pargs[-1] = type(a).__name__ pargs = tuple(pargs) print ('%-20s' % ('%s.%s%s'% (clsname, method, pargs))) def create(self,*args): self._log('create', *args) def destroy(self,*args): self._log('destroy', *args) if not self.trace: return for k, v in self.call_log.items(): print ('%-20s %2d' % (k, v)) def view(self, snes, viewer): self._log('view', snes, viewer) def setFromOptions(self, snes): OptDB = PETSc.Options(snes) self.trace = OptDB.getBool('trace',self.trace) self._log('setFromOptions',snes) def setUp(self, snes): self._log('setUp', snes) def reset(self, snes): self._log('reset', snes) #def preSolve(self, snes): # self._log('preSolve', snes) # #def postSolve(self, snes): # self._log('postSolve', snes) def preStep(self, snes): self._log('preStep', snes) def postStep(self, snes): self._log('postStep', snes) #def computeFunction(self, snes, x, F): # self._log('computeFunction', snes, x, F) # snes.computeFunction(x, F) # #def computeJacobian(self, snes, x, A, B): # self._log('computeJacobian', snes, x, A, B) # flag = snes.computeJacobian(x, A, B) # return flag # #def linearSolve(self, snes, b, x): # self._log('linearSolve', snes, b, x) # snes.ksp.solve(b,x) # ## return False # not succeed # if snes.ksp.getConvergedReason() < 0: # return False # not succeed # return True # succeed # #def lineSearch(self, snes, x, y, F): # self._log('lineSearch', snes, x, y, F) # x.axpy(-1,y) # snes.computeFunction(x, F) # ## return False # not succeed # return True # succeed from test_snes import BaseTestSNES class TestSNESPython(BaseTestSNES, unittest.TestCase): SNES_TYPE = PETSc.SNES.Type.PYTHON def setUp(self): super(TestSNESPython, self).setUp() self.snes.setPythonContext(MySNES()) def testGetType(self): ctx = self.snes.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.snes.getPythonType() == pytype) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_stdout.py000066400000000000000000000030141454104047300172770ustar00rootroot00000000000000import unittest # -------------------------------------------------------------------- class TestStdout(unittest.TestCase): def testStdoutRedirect(self): from io import StringIO import sys prevstdout = sys.stdout prevstderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() import numpy as np from petsc4py import PETSc if not (__name__ == '__main__'): PETSc._push_python_vfprintf() a = np.array([0.,0.,0.],dtype=PETSc.ScalarType) a_vec = PETSc.Vec().createWithArray(a,comm=PETSc.COMM_SELF) a_vec.view() v = PETSc.Viewer.STDERR(PETSc.COMM_SELF) v.printfASCII("Error message") newstdout = sys.stdout newstderr = sys.stderr sys.stdout = prevstdout sys.stderr = prevstderr output = newstdout.getvalue() error = newstderr.getvalue() if not (__name__ == '__main__'): PETSc._pop_python_vfprintf() stdoutshouldbe = \ """Vec Object: 1 MPI process type: seq 0. 0. 0. """ stderrshouldbe = "Error message" if PETSc._stdout_is_stderr(): stdoutshouldbe = stdoutshouldbe + stderrshouldbe stderrshouldbe = "" self.assertEqual(output,stdoutshouldbe) self.assertEqual(error,stderrshouldbe) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_sys.py000066400000000000000000000032171454104047300166000ustar00rootroot00000000000000import unittest from petsc4py import PETSc # -------------------------------------------------------------------- class TestVersion(unittest.TestCase): def testGetVersion(self): version = PETSc.Sys.getVersion() self.assertTrue(version > (0, 0, 0)) v, date = PETSc.Sys.getVersion(date=True) self.assertTrue(version == v) self.assertTrue(isinstance(date, str)) v, author = PETSc.Sys.getVersion(author=True) self.assertTrue(version == v) self.assertTrue(isinstance(author, (list,tuple))) def testGetVersionInfo(self): version = PETSc.Sys.getVersion() info = PETSc.Sys.getVersionInfo() self.assertEqual(version, (info['major'], info['minor'], info['subminor'],)) self.assertTrue(isinstance(info['release'], bool)) v, date = PETSc.Sys.getVersion(date=True) self.assertEqual(date, info['date']) def testGetSetDefaultComm(self): c = PETSc.Sys.getDefaultComm() self.assertEqual(c, PETSc.COMM_WORLD) PETSc.Sys.setDefaultComm(PETSc.COMM_SELF) c = PETSc.Sys.getDefaultComm() self.assertEqual(c, PETSc.COMM_SELF) PETSc.Sys.setDefaultComm(PETSc.COMM_WORLD) c = PETSc.Sys.getDefaultComm() self.assertEqual(c, PETSc.COMM_WORLD) f = lambda : PETSc.Sys.setDefaultComm(PETSc.COMM_NULL) self.assertRaises(ValueError, f) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_tao.py000066400000000000000000000061771454104047300165550ustar00rootroot00000000000000# -------------------------------------------------------------------- from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class Objective: def __call__(self, tao, x): return (x[0] - 2.0)**2 + (x[1] - 2.0)**2 - 2.0*(x[0] + x[1]) class Gradient: def __call__(self, tao, x, g): g[0] = 2.0*(x[0] - 2.0) - 2.0 g[1] = 2.0*(x[1] - 2.0) - 2.0 g.assemble() class EqConstraints: def __call__(self, tao, x, c): c[0] = x[0]**2 + x[1] - 2.0 c.assemble() class EqJacobian: def __call__(self, tao, x, J, P): P[0,0] = 2.0*x[0] P[0,1] = 1.0 P.assemble() if J != P: J.assemble() class BaseTestTAO(object): COMM = None def setUp(self): self.tao = PETSc.TAO().create(comm=self.COMM) def tearDown(self): self.tao = None PETSc.garbage_cleanup() def testSetRoutinesToNone(self): tao = self.tao objective, gradient, objgrad = None, None, None constraint, varbounds = None, None hessian, jacobian = None, None tao.setObjective(objective) tao.setGradient(gradient,None) tao.setVariableBounds(varbounds) tao.setObjectiveGradient(objgrad,None) tao.setConstraints(constraint) tao.setHessian(hessian) tao.setJacobian(jacobian) def testGetVecsAndMats(self): tao = self.tao x = tao.getSolution() (g, _) = tao.getGradient() l, u = tao.getVariableBounds() r = None#tao.getConstraintVec() H, HP = None,None#tao.getHessianMat() J, JP = None,None#tao.getJacobianMat() for o in [x, g, r, l, u ,H, HP, J, JP,]: self.assertFalse(o) def testGetKSP(self): ksp = self.tao.getKSP() self.assertFalse(ksp) def testEqualityConstraints(self): if self.tao.getComm().Get_size() > 1: return tao = self.tao x = PETSc.Vec().create(tao.getComm()) x.setType('standard') x.setSizes(2) c = PETSc.Vec().create(tao.getComm()) c.setSizes(1) c.setType(x.getType()) J = PETSc.Mat().create(tao.getComm()) J.setSizes([1, 2]) J.setType(PETSc.Mat.Type.DENSE) J.setUp() tao.setObjective(Objective()) tao.setGradient(Gradient(),None) tao.setEqualityConstraints(EqConstraints(),c) tao.setJacobianEquality(EqJacobian(),J,J) tao.setSolution(x) tao.setType(PETSc.TAO.Type.ALMM) tao.setTolerances(gatol=1.e-4) tao.setFromOptions() tao.solve() self.assertAlmostEqual(abs(x[0]**2 + x[1] - 2.0), 0.0, places=4) # -------------------------------------------------------------------- class TestTAOSelf(BaseTestTAO, unittest.TestCase): COMM = PETSc.COMM_SELF class TestTAOWorld(BaseTestTAO, unittest.TestCase): COMM = PETSc.COMM_WORLD # -------------------------------------------------------------------- import numpy if numpy.iscomplexobj(PETSc.ScalarType()): del BaseTestTAO del TestTAOSelf del TestTAOWorld if __name__ == '__main__': unittest.main() petsc4py-3.19.6/test/test_tao_py.py000066400000000000000000000073771454104047300172700ustar00rootroot00000000000000import unittest from petsc4py import PETSc from sys import getrefcount # -------------------------------------------------------------------- class Objective: def __call__(self, tao, x): return (x[0] - 1.0)**2 + (x[1] - 2.0)**2 class Gradient: def __call__(self, tao, x, g): g[0] = 2.0*(x[0] - 1.0) g[1] = 2.0*(x[1] - 2.0) g.assemble() class MyTao: def __init__(self): self.log = {} def _log(self, method): self.log.setdefault(method, 0) self.log[method] += 1 def create(self, tao): self._log('create') self.testvec = PETSc.Vec() def destroy(self, tao): self._log('destroy') self.testvec.destroy() def setFromOptions(self, tao): self._log('setFromOptions') def setUp(self, tao): self._log('setUp') self.testvec = tao.getSolution().duplicate() def solve(self, tao): self._log('solve') def step(self, tao, x, g, s): self._log('step') tao.computeGradient(x,g) g.copy(s) s.scale(-1.0) def preStep(self, tao): self._log('preStep') def postStep(self, tao): self._log('postStep') def monitor(self, tao): self._log('monitor') class TestTaoPython(unittest.TestCase): def setUp(self): self.tao = PETSc.TAO() self.tao.createPython(MyTao(), comm=PETSc.COMM_SELF) ctx = self.tao.getPythonContext() self.assertEqual(getrefcount(ctx), 3) self.assertEqual(ctx.log['create'], 1) self.nsolve = 0 def tearDown(self): ctx = self.tao.getPythonContext() self.assertEqual(getrefcount(ctx), 3) self.assertTrue('destroy' not in ctx.log) self.tao.destroy() self.tao = None PETSc.garbage_cleanup() self.assertEqual(ctx.log['destroy'], 1) self.assertEqual(getrefcount(ctx), 2) def testGetType(self): ctx = self.tao.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.tao.getPythonType() == pytype) def testSolve(self): tao = self.tao ctx = tao.getPythonContext() x = PETSc.Vec().create(tao.getComm()) x.setType('standard') x.setSizes(2) y1 = x.duplicate() y2 = x.duplicate() tao.setObjective(Objective()) tao.setGradient(Gradient(),None) tao.setMonitor(ctx.monitor) tao.setFromOptions() tao.setMaximumIterations(3) tao.setSolution(x) # Call the solve method of MyTAO x.set(0.5) tao.solve() n = tao.getIterationNumber() self.assertTrue(n == 0) # Call the default solve method and use step of MyTAO ctx.solve = None x.set(0.5) tao.solve() n = tao.getIterationNumber() self.assertTrue(n == 3) x.copy(y1) # Call the default solve method with the default step method ctx.step = None x.set(0.5) tao.solve() n = tao.getIterationNumber() self.assertTrue(n == 3) x.copy(y2) self.assertTrue(y1.equal(y2)) self.assertTrue(ctx.log['monitor'] == 2*(n+1)) self.assertTrue(ctx.log['preStep'] == 2*n) self.assertTrue(ctx.log['postStep'] == 2*n) self.assertTrue(ctx.log['solve'] == 1) self.assertTrue(ctx.log['setUp'] == 1) self.assertTrue(ctx.log['setFromOptions'] == 1) self.assertTrue(ctx.log['step'] == n) tao.cancelMonitor() # -------------------------------------------------------------------- import numpy if numpy.iscomplexobj(PETSc.ScalarType()): del TestTaoPython if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_ts.py000066400000000000000000000167031454104047300164140ustar00rootroot00000000000000import unittest from petsc4py import PETSc from sys import getrefcount # -------------------------------------------------------------------- class MyODE: """ du/dt + u**2 = 0; u0,u1,u2 = 1,2,3 """ def __init__(self): self.rhsfunction_calls = 0 self.rhsjacobian_calls = 0 self.ifunction_calls = 0 self.ijacobian_calls = 0 self.presolve_calls = 0 self.update_calls = 0 self.postsolve_calls = 0 self.monitor_calls = 0 def rhsfunction(self,ts,t,u,F): # print ('MyODE.rhsfunction()') self.rhsfunction_calls += 1 f = -(u * u) f.copy(F) def rhsjacobian(self,ts,t,u,J,P): # print ('MyODE.rhsjacobian()') self.rhsjacobian_calls += 1 P.zeroEntries() diag = -2 * u P.setDiagonal(diag) P.assemble() if J != P: J.assemble() return True # same_nz def ifunction(self,ts,t,u,du,F): # print ('MyODE.ifunction()') self.ifunction_calls += 1 f = du + u * u f.copy(F) def ijacobian(self,ts,t,u,du,a,J,P): # print ('MyODE.ijacobian()') self.ijacobian_calls += 1 P.zeroEntries() diag = a + 2 * u P.setDiagonal(diag) P.assemble() if J != P: J.assemble() return True # same_nz def monitor(self, ts, s, t, u): self.monitor_calls += 1 dt = ts.time_step ut = ts.vec_sol.norm() #prn = PETSc.Sys.Print #prn('TS: step %2d, T:%f, dT:%f, u:%f' % (s,t,dt,ut)) class BaseTestTSNonlinear(object): TYPE = None def setUp(self): self.ts = PETSc.TS().create(PETSc.COMM_SELF) eft = PETSc.TS.ExactFinalTime.STEPOVER self.ts.setExactFinalTime(eft) ptype = PETSc.TS.ProblemType.NONLINEAR self.ts.setProblemType(ptype) self.ts.setType(self.TYPE) if PETSc.ScalarType().dtype.char in 'fF': snes = self.ts.getSNES() snes.setTolerances(rtol=1e-6) def tearDown(self): self.ts = None PETSc.garbage_cleanup() class BaseTestTSNonlinearRHS(BaseTestTSNonlinear): def testSolveRHS(self): ts = self.ts dct = self.ts.getDict() self.assertTrue(dct is not None) self.assertTrue(type(dct) is dict) ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(3); J.setFromOptions() J.setUp() u, f = J.createVecs() ts.setAppCtx(ode) ts.setRHSFunction(ode.rhsfunction, f) ts.setRHSJacobian(ode.rhsjacobian, J, J) ts.setMonitor(ode.monitor) ts.snes.ksp.pc.setType('none') T0, dT, nT = 0.00, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[0], u[1], u[2] = 1, 2, 3 ts.solve(u) self.assertTrue(ode.rhsfunction_calls > 0) self.assertTrue(ode.rhsjacobian_calls > 0) dct = self.ts.getDict() self.assertTrue('__appctx__' in dct) self.assertTrue('__rhsfunction__' in dct) self.assertTrue('__rhsjacobian__' in dct) self.assertTrue('__monitor__' in dct) n = ode.monitor_calls ts.monitor(ts.step_number, ts.time) self.assertEqual(ode.monitor_calls, n+1) n = ode.monitor_calls ts.monitorCancel() ts.monitor(ts.step_number, ts.time) self.assertEqual(ode.monitor_calls, n) def testFDColorRHS(self): ts = self.ts ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(5); J.setType('aij') J.setPreallocationNNZ(nnz=1) u, f = J.createVecs() ts.setAppCtx(ode) ts.setRHSFunction(ode.rhsfunction, f) ts.setRHSJacobian(ode.rhsjacobian, J, J) ts.setMonitor(ode.monitor) T0, dT, nT = 0.00, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[0], u[1], u[2] = 1, 2, 3 ts.setSolution(u) ode.rhsjacobian(ts,0,u,J,J) ts.setUp() ts.snes.setUseFD(True) ts.solve(u) def testResetAndSolveRHS(self): self.ts.reset() self.ts.setStepNumber(0) self.testSolveRHS() self.ts.reset() self.ts.setStepNumber(0) self.testSolveRHS() self.ts.reset() class BaseTestTSNonlinearI(BaseTestTSNonlinear): def testSolveI(self): ts = self.ts dct = self.ts.getDict() self.assertTrue(dct is not None) self.assertTrue(type(dct) is dict) ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(3); J.setFromOptions() J.setUp() u, f = J.createVecs() ts.setAppCtx(ode) ts.setIFunction(ode.ifunction, f) ts.setIJacobian(ode.ijacobian, J, J) ts.setMonitor(ode.monitor) ts.snes.ksp.pc.setType('none') T0, dT, nT = 0.00, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[0], u[1], u[2] = 1, 2, 3 ts.solve(u) self.assertTrue(ode.ifunction_calls > 0) self.assertTrue(ode.ijacobian_calls > 0) dct = self.ts.getDict() self.assertTrue('__appctx__' in dct) self.assertTrue('__ifunction__' in dct) self.assertTrue('__ijacobian__' in dct) self.assertTrue('__monitor__' in dct) n = ode.monitor_calls ts.monitor(ts.step_number, ts.time) self.assertEqual(ode.monitor_calls, n+1) n = ode.monitor_calls ts.monitorCancel() ts.monitor(ts.step_number, ts.time) self.assertEqual(ode.monitor_calls, n) def testFDColorI(self): ts = self.ts ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(5); J.setType('aij') J.setPreallocationNNZ(nnz=1) J.setFromOptions() u, f = J.createVecs() ts.setAppCtx(ode) ts.setIFunction(ode.ifunction, f) ts.setIJacobian(ode.ijacobian, J, J) ts.setMonitor(ode.monitor) T0, dT, nT = 0.00, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[0], u[1], u[2] = 1, 2, 3 ts.setSolution(u) ode.ijacobian(ts,0,u,0*u,1,J,J) ts.setUp() ts.snes.setUseFD(True) ts.solve(u) def testResetAndSolveI(self): self.ts.reset() self.ts.setStepNumber(0) self.testSolveI() self.ts.reset() self.ts.setStepNumber(0) self.testSolveI() self.ts.reset() class TestTSBeuler(BaseTestTSNonlinearRHS,BaseTestTSNonlinearI, unittest.TestCase): TYPE = PETSc.TS.Type.BEULER class TestTSCN(BaseTestTSNonlinearRHS,BaseTestTSNonlinearI, unittest.TestCase): TYPE = PETSc.TS.Type.CN class TestTSTheta(BaseTestTSNonlinearRHS, BaseTestTSNonlinearI, unittest.TestCase): TYPE = PETSc.TS.Type.THETA class TestTSAlpha(BaseTestTSNonlinearRHS, BaseTestTSNonlinearI, unittest.TestCase): TYPE = PETSc.TS.Type.ALPHA # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_ts_py.py000066400000000000000000000121221454104047300171130ustar00rootroot00000000000000import unittest from petsc4py import PETSc from sys import getrefcount # -------------------------------------------------------------------- class MyODE: """ du/dt + u**2 = 0; u0 = 1 """ def __init__(self): self.function_calls = 0 self.jacobian_calls = 0 def function(self,ts,t,u,du,F): #print 'MyODE.function()' self.function_calls += 1 f = du + u * u f.copy(F) def jacobian(self,ts,t,u,du,a,J,P): #print 'MyODE.jacobian()' self.jacobian_calls += 1 P.zeroEntries() diag = a + 2 * u P.setDiagonal(diag) P.assemble() if J != P: J.assemble() return False # same_nz class MyTS(object): def __init__(self): self.log = {} def _log(self, method, *args): self.log.setdefault(method, 0) self.log[method] += 1 def create(self, ts, *args): self._log('create', *args) self.vec_update = PETSc.Vec() def destroy(self, ts, *args): self._log('destroy', *args) self.vec_update.destroy() def setFromOptions(self, ts, *args): self._log('setFromOptions', *args) def setUp(self, ts, *args): self._log('setUp', ts, *args) self.vec_update = ts.getSolution().duplicate() def reset(self, ts, *args): self._log('reset', ts, *args) def solveStep(self, ts, t, u, *args): self._log('solveStep', ts, t, u, *args) ts.snes.solve(None, u) def adaptStep(self, ts, t, u, *args): self._log('adaptStep', ts, t, u, *args) return (ts.getTimeStep(), True) class TestTSPython(unittest.TestCase): def setUp(self): self.ts = PETSc.TS() self.ts.createPython(MyTS(), comm=PETSc.COMM_SELF) eft = PETSc.TS.ExactFinalTime.STEPOVER self.ts.setExactFinalTime(eft) ctx = self.ts.getPythonContext() self.assertEqual(getrefcount(ctx), 3) self.assertEqual(ctx.log['create'], 1) self.nsolve = 0 def tearDown(self): ctx = self.ts.getPythonContext() self.assertEqual(getrefcount(ctx), 3) self.assertTrue('destroy' not in ctx.log) self.ts.destroy() # XXX self.ts = None PETSc.garbage_cleanup() self.assertEqual(ctx.log['destroy'], 1) self.assertEqual(getrefcount(ctx), 2) def testGetType(self): ctx = self.ts.getPythonContext() pytype = "{0}.{1}".format(ctx.__module__, type(ctx).__name__) self.assertTrue(self.ts.getPythonType() == pytype) def testSolve(self): ts = self.ts ts.setProblemType(ts.ProblemType.NONLINEAR) ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(3); J.setFromOptions() J.setUp() u, f = J.createVecs() ts.setAppCtx(ode) ts.setIFunction(ode.function, f) ts.setIJacobian(ode.jacobian, J, J) ts.snes.ksp.pc.setType('none') T0, dT, nT = 0.0, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[0], u[1], u[2] = 1, 2, 3 ts.solve(u) self.nsolve +=1 self.assertTrue(ode.function_calls > 0) self.assertTrue(ode.jacobian_calls > 0) ctx = self.ts.getPythonContext() ncalls = self.nsolve * ts.step_number self.assertTrue(ctx.log['solveStep'] == ncalls) self.assertTrue(ctx.log['adaptStep'] == ncalls) del ctx dct = self.ts.getDict() self.assertTrue('__appctx__' in dct) self.assertTrue('__ifunction__' in dct) self.assertTrue('__ijacobian__' in dct) def testFDColor(self): # ts = self.ts ts.setProblemType(ts.ProblemType.NONLINEAR) ode = MyODE() J = PETSc.Mat().create(ts.comm) J.setSizes(5); J.setType('aij'); J.setPreallocationNNZ(1) J.setFromOptions() u, f = J.createVecs() ts.setAppCtx(ode) ts.setIFunction(ode.function, f) ts.setIJacobian(ode.jacobian, J, J) T0, dT, nT = 0.00, 0.1, 10 T = T0 + nT*dT ts.setTime(T0) ts.setTimeStep(dT) ts.setMaxTime(T) ts.setMaxSteps(nT) ts.setFromOptions() u[:] = 1, 2, 3, 4, 5 ts.setSolution(u) ode.jacobian(ts,0.0,u,u,1.0,J,J) ts.snes.setUseFD(True) ts.solve(u) self.nsolve +=1 def testResetAndSolve(self): self.ts.reset() self.ts.setStepNumber(0) self.testSolve() self.ts.reset() self.ts.setStepNumber(0) self.testFDColor() self.ts.reset() self.ts.setStepNumber(0) self.testSolve() self.ts.reset() def testSetAdaptLimits(self): self.ts.setStepLimits(1.0, 2.0) hmin, hmax = self.ts.getStepLimits() self.assertEqual(1.0, hmin) self.assertEqual(2.0, hmax) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # -------------------------------------------------------------------- petsc4py-3.19.6/test/test_vec.py000066400000000000000000000235501454104047300165410ustar00rootroot00000000000000from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestVec(object): COMM = None TYPE = None def setUp(self): v = PETSc.Vec() v.create(self.COMM) v.setSizes(100) v.setType(self.TYPE) self.vec = v def tearDown(self): self.vec.destroy() self.vec = None PETSc.garbage_cleanup() def testDuplicate(self): self.vec.set(1) vec = self.vec.duplicate() self.assertFalse(self.vec.equal(vec)) self.assertEqual(self.vec.sizes, vec.sizes) del vec def testCopy(self): self.vec.set(1) vec = self.vec.duplicate() self.vec.copy(vec) self.assertTrue(self.vec.equal(vec)) del vec def testDot(self): self.vec.set(1) d = self.vec.dot(self.vec) self.assertAlmostEqual(abs(d), self.vec.getSize()) self.vec.dotBegin(self.vec) d = self.vec.dotEnd(self.vec) self.assertAlmostEqual(abs(d), self.vec.getSize()) def testNorm(self): from math import sqrt self.vec.set(1) n1 = self.vec.norm(PETSc.NormType.NORM_1) n2 = self.vec.norm(PETSc.NormType.NORM_2) ni = self.vec.norm(PETSc.NormType.NORM_INFINITY) self.assertAlmostEqual(n1, self.vec.getSize()) self.assertAlmostEqual(n2, sqrt(self.vec.getSize())) self.assertAlmostEqual(n2, self.vec.norm()) self.assertAlmostEqual(ni, 1.0) self.vec.normBegin(PETSc.NormType.NORM_1) nn1 = self.vec.normEnd(PETSc.NormType.NORM_1) self.assertAlmostEqual(nn1, n1) self.vec.normBegin() nn2 = self.vec.normEnd() self.assertAlmostEqual(nn2, n2) self.vec.normBegin(PETSc.NormType.NORM_INFINITY) nni = self.vec.normEnd(PETSc.NormType.NORM_INFINITY) self.assertAlmostEqual(nni, ni) def testNormalize(self): from math import sqrt self.vec.set(1) n2 = self.vec.normalize() self.assertAlmostEqual(n2, sqrt(self.vec.getSize())) self.assertAlmostEqual(1, self.vec.norm()) def testSumMinMax(self): self.vec.set(1) self.assertEqual(self.vec.sum(), self.vec.getSize()) self.vec.set(-7) self.assertEqual(self.vec.min()[1], -7) self.vec.set(10) self.assertEqual(self.vec.max()[1], 10) def testSwap(self): v1 = self.vec v2 = v1.duplicate() v1.set(1) v2.set(2) v1.swap(v2) idx, _ = self.vec.getOwnershipRange() self.assertEqual(v1[idx], 2) self.assertEqual(v2[idx], 1) def testBsize(self): self.vec.setBlockSize(1) self.assertEqual(self.vec.getBlockSize(), 1) self.vec.setBlockSize(1) def testGetSetVals(self): start, end = self.vec.getOwnershipRange() self.vec[start] = -7 self.vec[end-1] = -7 self.vec.assemble() self.assertEqual(self.vec[start], -7) self.assertEqual(self.vec[end-1], -7) for i in range(start, end): self.vec[i] = i self.vec.assemble() values = [self.vec[i] for i in range(start, end)] self.assertEqual(values, list(range(start, end))) sz = self.vec.getSize() self.assertEqual(self.vec.sum(), (sz-1)/2.0*sz) def testGetSetValsBlocked(self): return lsize, gsize = self.vec.getSizes() start, end = self.vec.getOwnershipRange() bsizes = list(range(1, lsize+1)) nblocks = list(range(1, lsize+1)) compat = [(bs, nb) for bs in bsizes if not (gsize%bs or lsize % bs) for nb in nblocks if bs*nb <= lsize] for bsize, nblock in compat: self.vec.setBlockSize(bsize) bindex = [start//bsize+i for i in range(nblock)] bvalue = [float(i) for i in range(nblock*bsize)] self.vec.setValuesBlocked(bindex, bvalue) self.vec.assemble() index = [start+i for i in range(nblock*bsize)] value = self.vec.getValues(index) self.assertEqual(bvalue, list(value)) def testGetSetArray(self): self.vec.set(1) arr0 = self.vec.getArray().copy() self.assertEqual(arr0.sum(), self.vec.getLocalSize()) arr0 = self.vec.getArray().copy() self.vec.setRandom() arr1 = self.vec.getArray().copy() self.vec.setArray(arr1) arr1 = self.vec.getArray().copy() arr2 = self.vec.getArray().copy() self.assertTrue((arr1 == arr2).all()) import numpy refs = self.vec.getRefCount() arr3 = numpy.asarray(self.vec) self.assertEqual(self.vec.getRefCount(), refs+1) self.assertTrue((arr1 == arr3).all()) arr3[:] = 0 self.assertAlmostEqual(abs(self.vec.sum()), 0) self.assertEqual(self.vec.max()[1], 0) self.assertEqual(self.vec.min()[1], 0) self.vec.set(1) self.assertAlmostEqual(abs(arr3.sum()), self.vec.getLocalSize()) self.assertEqual(arr3.min(), 1) self.assertEqual(arr3.max(), 1) del arr3 self.assertEqual(self.vec.getRefCount(), refs) def testPlaceArray(self): self.vec.set(1) array = self.vec.getArray().copy() self.vec.placeArray(array) array[:] = 2 self.assertAlmostEqual(abs(self.vec.sum()), 2*self.vec.getSize()) self.vec.resetArray() self.assertAlmostEqual(abs(self.vec.sum()), self.vec.getSize()) def testLocalVector(self): rank = self.vec.getComm().Get_rank() self.vec.getArray()[:] = rank + 1 ln = self.vec.getLocalSize() lvec = self.vec.createLocalVector() self.vec.getLocalVector(lvec) self.assertEqual(abs(lvec.sum()), (rank+1)*ln) self.vec.restoreLocalVector(lvec) self.vec.getLocalVector(lvec,readonly=True) self.assertEqual(abs(lvec.sum()), (rank+1)*ln) self.vec.restoreLocalVector(lvec,readonly=True) lvec.destroy() def testSetOption(self): opt1 = PETSc.Vec.Option.IGNORE_OFF_PROC_ENTRIES opt2 = PETSc.Vec.Option.IGNORE_NEGATIVE_INDICES for opt in [opt1, opt2]*2: for flag in [True,False]*2: self.vec.setOption(opt,flag) def testGetSetItem(self): v = self.vec w = v.duplicate() # v[...] = 7 self.assertEqual(v.max()[1], 7) self.assertEqual(v.min()[1], 7) # v.setRandom() w[...] = v self.assertTrue(w.equal(v)) # v.setRandom() w[...] = v.getArray() self.assertTrue(w.equal(v)) # s, e = v.getOwnershipRange() v.setRandom() w[s:e] = v.getArray().copy() w.assemble() self.assertTrue(w.equal(v)) w1, v1 = w[s], v[s] w2, v2 = w[e-1], v[e-1] self.assertEqual(w1, v1) self.assertEqual(w2, v2) def testMAXPY(self): y = self.vec y.set(1) x = [y.copy() for _ in range(3)] a = [1]*len(x) y.maxpy(a, x) z = y.duplicate() z.set(len(x)+1) assert (y.equal(z)) # -------------------------------------------------------------------- class TestVecSeq(BaseTestVec, unittest.TestCase): COMM = PETSc.COMM_SELF TYPE = PETSc.Vec.Type.SEQ class TestVecMPI(BaseTestVec, unittest.TestCase): COMM = PETSc.COMM_WORLD TYPE = PETSc.Vec.Type.MPI class TestVecShared(BaseTestVec, unittest.TestCase): if PETSc.COMM_WORLD.getSize() == 1: TYPE = PETSc.Vec.Type.SHARED else: TYPE = PETSc.Vec.Type.MPI COMM = PETSc.COMM_WORLD #class TestVecSieve(BaseTestVec, unittest.TestCase): # CLASS = PETSc.VecSieve # TARGS = ([],) #class TestVecGhost(BaseTestVec, unittest.TestCase): # CLASS = PETSc.VecGhost # TARGS = ([],) # -------------------------------------------------------------------- class TestVecWithArray(unittest.TestCase): def testCreateSeq(self): import numpy a = numpy.zeros(5, dtype=PETSc.ScalarType) v1 = PETSc.Vec().createWithArray(a, comm=PETSc.COMM_SELF) v2 = PETSc.Vec().createWithArray(a, size=5, comm=PETSc.COMM_SELF) v3 = PETSc.Vec().createWithArray(a, size=3, comm=PETSc.COMM_SELF) self.assertTrue(v1.size == 5) self.assertTrue(v2.size == 5) self.assertTrue(v3.size == 3) a1 = v1.getDict()['__array__']; self.assertTrue(a is a1) a2 = v2.getDict()['__array__']; self.assertTrue(a is a2) a3 = v3.getDict()['__array__']; self.assertTrue(a is a2) def testCreateMPI(self): import numpy a = numpy.zeros(5, dtype=PETSc.ScalarType) v1 = PETSc.Vec().createWithArray(a, comm=PETSc.COMM_WORLD) v2 = PETSc.Vec().createWithArray(a, size=(5,None), comm=PETSc.COMM_WORLD) v3 = PETSc.Vec().createWithArray(a, size=(3,None), comm=PETSc.COMM_WORLD) self.assertTrue(v1.local_size == 5) self.assertTrue(v2.local_size == 5) self.assertTrue(v3.local_size == 3) a1 = v1.getDict()['__array__']; self.assertTrue(a is a1) a2 = v2.getDict()['__array__']; self.assertTrue(a is a2) a3 = v3.getDict()['__array__']; self.assertTrue(a is a2) def testSetMPIGhost(self): import numpy v = PETSc.Vec().create() v.setType(PETSc.Vec.Type.MPI) v.setSizes((5,None)) ghosts = [i % v.size for i in range(v.owner_range[1],v.owner_range[1]+3)] v.setMPIGhost(ghosts) v.setArray(numpy.array(range(*v.owner_range),dtype=PETSc.ScalarType)) v.ghostUpdate() with v.localForm() as loc: self.assertTrue((loc[0:v.local_size] == range(*v.owner_range)).all()) self.assertTrue((loc[v.local_size:] == ghosts).all()) # -------------------------------------------------------------------- if __name__ == '__main__': unittest.main() # --------------------------------------------------------------------