slepc4py-3.20.2/ 0000755 0001751 0001751 00000000000 14575030440 014143 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/PKG-INFO 0000644 0001751 0001751 00000004731 14575030440 015245 0 ustar jroman jroman 0000000 0000000 Metadata-Version: 2.1
Name: slepc4py
Version: 3.20.2
Summary: SLEPc for Python
Home-page: https://gitlab.com/slepc/slepc
Author: Lisandro Dalcin
Author-email: dalcinl@gmail.com
Maintainer: SLEPc Team
Maintainer-email: slepc-maint@upv.es
License: BSD-2-Clause
Download-URL: https://pypi.io/packages/source/s/slepc4py/slepc4py-3.20.2.tar.gz
Description: SLEPc for Python
================
Python bindings for SLEPc.
Install
-------
If you have a working MPI implementation and the ``mpicc`` compiler
wrapper is on your search path, it highly recommended to install
``mpi4py`` first::
$ pip install mpi4py
Ensure you have NumPy installed::
$ pip install numpy
and finally::
$ pip install petsc petsc4py slepc slepc4py
Citations
---------
If SLEPc for Python been significant to a project that leads to an
academic publication, please acknowledge that fact by citing the
project.
* L. Dalcin, P. Kler, R. Paz, and A. Cosimo,
*Parallel Distributed Computing using Python*,
Advances in Water Resources, 34(9):1124-1139, 2011.
https://doi.org/10.1016/j.advwatres.2011.04.013
* V. Hernandez, J.E. Roman and V. Vidal.
*SLEPc: A Scalable and Flexible Toolkit for the
Solution of Eigenvalue Problems*,
ACM Transactions on Mathematical Software, 31(3):351-362, 2005.
https://doi.org/10.1145/1089014.1089019
Keywords: scientific computing,parallel computing,MPI,SLEPc,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
slepc4py-3.20.2/README.rst 0000644 0001751 0001751 00000001740 14575027370 015644 0 ustar jroman jroman 0000000 0000000 ================
SLEPc for Python
================
Overview
--------
Welcome to SLEPc for Python. This package provides Python bindings for
SLEPc_, the * Scalable Library for Eigenvalue Problem Computations*.
Dependencies
------------
* Python_ 2.7, 3.3 or above.
* A recent NumPy_ release.
* A matching version of SLEPc_ built with *shared/dynamic libraries*.
* A matching version of PETSc_ built with *shared/dynamic libraries*.
* A matching version of petsc4py_.
* To work with the in-development version, you need Cython_.
.. _Python: https://www.python.org
.. _NumPy: https://www.numpy.org
.. _SLEPc: https://slepc.upv.es
.. _PETSc: https://petsc.org
.. _petsc4py: https://gitlab.com/petsc/petsc
.. _Cython: https://cython.org
Documentation
-------------
* https://slepc4py.readthedocs.org/, This does not contain the epydoc-generated API reference.
* https://slepc.upv.es/slepc4py-current/docs/, This is for the last release, not the in-development version.
slepc4py-3.20.2/docs/ 0000755 0001751 0001751 00000000000 14575030440 015073 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/docs/source/ 0000755 0001751 0001751 00000000000 14575030440 016373 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/docs/source/tutorial.rst 0000644 0001751 0001751 00000017513 14575027370 021007 0 ustar jroman jroman 0000000 0000000 Tutorial
========
This tutorial is intended for basic use of slepc4py. For more advanced
use, the reader is referred to SLEPc tutorials as well as to slepc4py
reference documentation.
Commented source of a simple example
------------------------------------
In this section, we include the source code of example ``demo/ex1.py``
available in the slepc4py distribution, with comments inserted inline.
The first thing to do is initialize the libraries. This is normally
not required, as it is done automatically at import time. However, if
you want to gain access to the facilities for accessing command-line
options, the following lines must be executed by the main script prior
to any petsc4py or slepc4py calls::
import sys, slepc4py
slepc4py.init(sys.argv)
Next, we have to import the relevant modules. Normally, both PETSc and
SLEPc modules have to be imported in all slepc4py programs. It may be
useful to import NumPy as well::
from petsc4py import PETSc
from slepc4py import SLEPc
import numpy
At this point, we can use any petsc4py and slepc4py operations. For
instance, the following lines allow the user to specify an integer
command-line argument ``n`` with a default value of 30 (see the next
section for example usage of command-line options)::
opts = PETSc.Options()
n = opts.getInt('n', 30)
It is necessary to build a matrix to define an eigenproblem (or two in
the case of generalized eigenproblems). The following fragment of code
creates the matrix object and then fills the non-zero elements one by
one. The matrix of this particular example is tridiagonal, with value
2 in the diagonal, and -1 in off-diagonal positions. See petsc4py
documentation for details about matrix objects::
A = PETSc.Mat().create()
A.setSizes([n, n])
A.setFromOptions()
A.setUp()
rstart, rend = A.getOwnershipRange()
# first row
if rstart == 0:
A[0, :2] = [2, -1]
rstart += 1
# last row
if rend == n:
A[n-1, -2:] = [-1, 2]
rend -= 1
# other rows
for i in range(rstart, rend):
A[i, i-1:i+2] = [-1, 2, -1]
A.assemble()
The solver object is created in a similar way as other objects in
petsc4py::
E = SLEPc.EPS(); E.create()
Once the object is created, the eigenvalue problem must be
specified. At least one matrix must be provided. The problem type must
be indicated as well, in this case it is HEP (Hermitian eigenvalue
problem). Apart from these, other settings could be provided here (for
instance, the tolerance for the computation). After all options have
been set, the user should call the ``setFromOptions()`` operation, so
that any options specified at run time in the command line are passed
to the solver object::
E.setOperators(A)
E.setProblemType(SLEPc.EPS.ProblemType.HEP)
E.setFromOptions()
After that, the ``solve()`` method will run the selected eigensolver,
keeping the solution stored internally::
E.solve()
Once the computation has finished, we are ready to print the results.
First, some informative data can be retrieved from the solver object::
Print = PETSc.Sys.Print
Print()
Print("******************************")
Print("*** SLEPc Solution Results ***")
Print("******************************")
Print()
its = E.getIterationNumber()
Print("Number of iterations of the method: %d" % its)
eps_type = E.getType()
Print("Solution method: %s" % eps_type)
nev, ncv, mpd = E.getDimensions()
Print("Number of requested eigenvalues: %d" % nev)
tol, maxit = E.getTolerances()
Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit))
For retrieving the solution, it is necessary to find out how many
eigenpairs have converged to the requested precision::
nconv = E.getConverged()
Print("Number of converged eigenpairs %d" % nconv)
For each of the ``nconv`` eigenpairs, we can retrieve the eigenvalue
``k``, and the eigenvector, which is represented by means of two
petsc4py vectors ``vr`` and ``vi`` (the real and imaginary part of the
eigenvector, since for real matrices the eigenvalue and eigenvector
may be complex). We also compute the corresponding relative errors in
order to make sure that the computed solution is indeed correct::
if nconv > 0:
# Create the results vectors
vr, wr = A.getVecs()
vi, wi = A.getVecs()
#
Print()
Print(" k ||Ax-kx||/||kx|| ")
Print("----------------- ------------------")
for i in range(nconv):
k = E.getEigenpair(i, vr, vi)
error = E.computeError(i)
if k.imag != 0.0:
Print(" %9f%+9f j %12g" % (k.real, k.imag, error))
else:
Print(" %12f %12g" % (k.real, error))
Print()
Example of command-line usage
-----------------------------
Now we illustrate how to specify command-line options in order to
extract the full potential of slepc4py.
A simple execution of the ``demo/ex1.py`` script will result in the
following output::
$ python demo/ex1.py
******************************
*** SLEPc Solution Results ***
******************************
Number of iterations of the method: 4
Solution method: krylovschur
Number of requested eigenvalues: 1
Stopping condition: tol=1e-07, maxit=100
Number of converged eigenpairs 4
k ||Ax-kx||/||kx||
----------------- ------------------
3.989739 5.76012e-09
3.959060 1.41957e-08
3.908279 6.74118e-08
3.837916 8.34269e-08
For specifying different setting for the solver parameters, we can use
SLEPc command-line options with the ``-eps`` prefix. For instance, to
change the number of requested eigenvalues and the tolerance::
$ python demo/ex1.py -eps_nev 10 -eps_tol 1e-11
The method used by the solver object can also be set at run time::
$ python demo/ex1.py -eps_type subspace
All the above settings can also be changed within the source code by
making use of the appropriate slepc4py method. Since options can be
set from within the code and the command-line, it is often useful to
view the particular settings that are currently being used::
$ python demo/ex1.py -eps_view
EPS Object: 1 MPI process
type: krylovschur
50% of basis vectors kept after restart
using the locking variant
problem type: symmetric eigenvalue problem
selected portion of the spectrum: largest eigenvalues in magnitude
number of eigenvalues (nev): 1
number of column vectors (ncv): 16
maximum dimension of projected problem (mpd): 16
maximum number of iterations: 100
tolerance: 1e-08
convergence test: relative to the eigenvalue
BV Object: 1 MPI process
type: mat
17 columns of global length 30
orthogonalization method: classical Gram-Schmidt
orthogonalization refinement: if needed (eta: 0.7071)
block orthogonalization method: GS
doing matmult as a single matrix-matrix product
DS Object: 1 MPI process
type: hep
solving the problem with: Implicit QR method (_steqr)
ST Object: 1 MPI process
type: shift
shift: 0
number of matrices: 1
Note that for computing eigenvalues of smallest magnitude we can use
the option ``-eps_smallest_magnitude``, but for interior eigenvalues
things are not so straightforward. One possibility is to try with
harmonic extraction, for instance to get the eigenvalues closest to
0.6::
$ python demo/ex1.py -eps_harmonic -eps_target 0.6
Depending on the problem, harmonic extraction may fail to converge. In
those cases, it is necessary to specify a spectral transformation
other than the default. In the command-line, this is indicated with
the ``-st_`` prefix. For example, shift-and-invert with a value of the
shift equal to 0.6 would be::
$ python demo/ex1.py -st_type sinvert -eps_target 0.6
slepc4py-3.20.2/docs/source/Makefile 0000644 0001751 0001751 00000001141 14575027370 020040 0 ustar jroman jroman 0000000 0000000 # Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = python -msphinx
SPHINXPROJ = petsc4py
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
slepc4py-3.20.2/docs/source/abstract.txt 0000644 0001751 0001751 00000001223 14575027370 020745 0 ustar jroman jroman 0000000 0000000 .. topic:: Abstract
This document describes slepc4py_, a Python_ port to the SLEPc_
libraries.
SLEPc_ is a software package for the parallel solution of
large-scale eigenvalue problems. It can be used for computing
eigenvalues and eigenvectors of large, sparse matrices, or matrix
pairs, and also for computing singular values and vectors of a
rectangular matrix.
SLEPc_ relies on PETSc_ for basic functionality such as the
representation of matrices and vectors, and the solution of linear
systems of equations. Thus, slepc4py_ must be used together with
its companion petsc4py_.
.. Local Variables:
.. mode: rst
.. End:
slepc4py-3.20.2/docs/source/manual.rst 0000644 0001751 0001751 00000000200 14575027370 020402 0 ustar jroman jroman 0000000 0000000 ================
SLEPc for Python
================
.. include:: abstract.txt
.. include:: toctree.txt
.. include:: links.txt
slepc4py-3.20.2/docs/source/overview.rst 0000644 0001751 0001751 00000016312 14575027370 021006 0 ustar jroman jroman 0000000 0000000 Overview
========
*SLEPc for Python* (slepc4py) is a Python package that provides
convenient access to the functionality of SLEPc.
SLEPc [1]_, [2]_ implements algorithms and tools for the numerical
solution of large, sparse eigenvalue problems on parallel
computers. It can be used for linear eigenvalue problems in either
standard or generalized form, with real or complex arithmetic.
It can also be used for computing a partial SVD of a large, sparse,
rectangular matrix, and to solve nonlinear eigenvalue problems
(polynomial or general). Additionally, SLEPc provides solvers for
the computation of the action of a matrix function on a vector.
SLEPc is intended for computing a subset of the spectrum of a matrix
(or matrix pair). One can for instance approximate the largest
magnitude eigenvalues, or the smallest ones, or even those eigenvalues
located near a given region of the complex plane. Interior eigenvalues
are harder to compute, so SLEPc provides different methodologies. One
such method is to use a spectral transformation. Cheaper alternatives
are also available.
.. [1] J. E. Roman, C. Campos, L. Dalcin, E. Romero, A. Tomas.
SLEPc Users Manual. DSIC-II/24/02 - Revision 3.20
D. Sistemas Informaticos y Computacion, Universitat Politecnica de
Valencia. 2023.
.. [2] Vicente Hernandez, Jose E. Roman and Vicente Vidal.
SLEPc: A Scalable and Flexible Toolkit for the Solution of
Eigenvalue Problems, ACM Trans. Math. Softw. 31(3), pp. 351-362,
2005.
.. include:: links.txt
Features
--------
Currently, the following types of eigenproblems can be addressed:
* Standard eigenvalue problem, *Ax=kx*, either for Hermitian or
non-Hermitian matrices.
* Generalized eigenvalue problem, *Ax=kBx*, either Hermitian
positive-definite or not.
* Partial singular value decomposition of a rectangular matrix,
*Au=sv*.
* Polynomial eigenvalue problem, *P(k)x=0*.
* Nonlinear eigenvalue problem, *T(k)x=0*.
* Computing the action of a matrix function on a vector, *w=f(alpha A)v*.
For the linear eigenvalue problem, the following methods are available:
* Krylov eigensolvers, particularly Krylov-Schur, Arnoldi, and
Lanczos.
* Davidson-type eigensolvers, including Generalized Davidson and
Jacobi-Davidson.
* Subspace iteration and single vector iterations (inverse iteration,
RQI).
* Conjugate gradient for the minimization of the Rayleigh quotient.
* A contour integral solver.
For singular value computations, the following alternatives can be
used:
* Use an eigensolver via the cross-product matrix *A'A* or the cyclic
matrix *[0 A; A' 0]*.
* Explicitly restarted Lanczos bidiagonalization.
* Implicitly restarted Lanczos bidiagonalization (thick-restart
Lanczos).
For polynomial eigenvalue problems, the following methods are available:
* Use an eigensolver to solve the generalized eigenvalue problem
obtained after linearization.
* TOAR and Q-Arnoldi, memory efficient variants of Arnoldi for polynomial
eigenproblems.
For general nonlinear eigenvalue problems, the following methods can be used:
* Solve a polynomial eigenproblem obtained via polynomial interpolation.
* Rational interpolation and linearization (NLEIGS).
* Newton-type methods such as SLP or RII.
Computation of interior eigenvalues is supported by means of the
following methodologies:
* Spectral transformations, such as shift-and-invert. This technique
implicitly uses the inverse of the shifted matrix *(A-tI)* in order
to compute eigenvalues closest to a given target value, *t*.
* Harmonic extraction, a cheap alternative to shift-and-invert that
also tries to approximate eigenvalues closest to a target, *t*, but
without requiring a matrix inversion.
Other remarkable features include:
* High computational efficiency, by using NumPy and SLEPc under the
hood.
* Data-structure neutral implementation, by using efficient sparse
matrix storage provided by PETSc. Implicit matrix representation is
also available by providing basic operations such as matrix-vector
products as user-defined Python functions.
* Run-time flexibility, by specifying numerous setting at the command
line.
* Ability to do the computation in parallel.
Components
----------
SLEPc provides the following components, which are mirrored by slepc4py
for its use from Python. The first five components are solvers for
different classes of problems, while the rest can be considered
auxiliary object.
:EPS: The Eigenvalue Problem Solver is the component that provides all
the functionality necessary to define and solve an
eigenproblem. It provides mechanisms for completely specifying
the problem: the problem type (e.g. standard symmetric), number
of eigenvalues to compute, part of the spectrum of
interest. Once the problem has been defined, a collection of
solvers can be used to compute the required solutions. The
behaviour of the solvers can be tuned by means of a few
parameters, such as the maximum dimension of the subspace to be
used during the computation.
:SVD: This component is the analog of EPS for the case of Singular
Value Decompositions. The user provides a rectangular matrix and
specifies how many singular values and vectors are to be
computed, whether the largest or smallest ones, as well as some
other parameters for fine tuning the computation. Different
solvers are available, as in the case of EPS.
:PEP: This component is the analog of EPS for the case of Polynomial
Eigenvalue Problems. The user provides the coefficient matrices of
the polynomial. Several parameters can be specified, as in
the case of EPS. It is also possible to indicate whether the
problem belongs to a special type, e.g., symmetric or gyroscopic.
:NEP: This component covers the case of general nonlinear eigenproblems,
T(lambda)x=0. The user provides the parameter-dependent matrix T
via the split form or by means of callback functions.
:MFN: This component provides the functionality for computing the action
of a matrix function on a vector. Given a matrix A and a vector b,
the call MFNSolve(mfn,b,x) computes x=f(A)b, where f is a function
such as the exponential.
:ST: The Spectral Transformation is a component that provides
convenient implementations of common spectral
transformations. These are simple transformations that map
eigenvalues to different positions, in such a way that
convergence to wanted eigenvalues is enhanced. The most common
spectral transformation is shift-and-invert, that allows for the
computation of eigenvalues closest to a given target value.
:BV: This component encapsulates the concept of a set of Basis Vectors
spanning a vector space. This component provides convenient access
to common operations such as orthogonalization of vectors. The
BV component is usually not required by end-users.
:DS: The Dense System (or Direct Solver) component, used internally to
solve dense eigenproblems of small size that appear in the course
of iterative eigensolvers.
:FN: A component used to define mathematical functions. This is required
by the end-user for instance to define function T(.) when solving
nonlinear eigenproblems with NEP in split form.
slepc4py-3.20.2/docs/source/conf.py 0000644 0001751 0001751 00000014342 14575027370 017706 0 ustar jroman jroman 0000000 0000000 # -*- coding: utf-8 -*-
#
# SLEPc for Python documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 1 15:52:05 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
def get_version():
import sys, os, re
here = os.path.dirname(__file__)
pardir = [os.path.pardir] * 2
topdir = os.path.join(here, *pardir)
srcdir = os.path.join(topdir, 'src')
with open(os.path.join(srcdir, 'slepc4py', '__init__.py')) as f:
m = re.search(r"__version__\s*=\s*'(.*)'", f.read())
return m.groups()[0]
pkg_version = get_version()
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']
templates_path = []
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The main toctree document.
main_doc = 'index'
# General information about the project.
project = u'SLEPc for Python'
copyright = u'2023, Lisandro Dalcin and Jose Roman'
author = u'Lisandro Dalcin'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = pkg_version[:3]
# The full version, including alpha/beta/rc tags.
release = pkg_version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
html_static_path = []
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
# html_sidebars = {
# '**': [
# 'about.html',
# 'navigation.html',
# 'relations.html', # needs 'show_related': True theme option to display
# 'searchbox.html',
# 'donate.html',
# ]
# }
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'slepc4py-man'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
'papersize': 'a4',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
#'printmodindex': '',
#'printindex': '',
#'preamble' : '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('manual', 'slepc4py.tex', project, author, 'howto'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(main_doc, 'slepc4py', project, [author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(main_doc, 'slepc4py', project, author,
'slepc4py', project+u'.', 'Miscellaneous'),
]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
slepc4py-3.20.2/docs/source/contents.rst 0000644 0001751 0001751 00000000000 14575027370 020760 0 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/docs/source/make.bat 0000644 0001751 0001751 00000001446 14575027370 020015 0 ustar jroman jroman 0000000 0000000 @ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=python -msphinx
)
set SOURCEDIR=.
set BUILDDIR=_build
set SPHINXPROJ=petsc4py
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The Sphinx module was not found. Make sure you have Sphinx installed,
echo.then set the SPHINXBUILD environment variable to point to the full
echo.path of the 'sphinx-build' executable. Alternatively you may add the
echo.Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
slepc4py-3.20.2/docs/source/index.rst 0000644 0001751 0001751 00000000474 14575027370 020251 0 ustar jroman jroman 0000000 0000000 ================
SLEPc for Python
================
:Authors: Lisandro Dalcin, Jose E. Roman
:Contact: dalcinl@gmail.com, jroman@dsic.upv.es
:Web Site: https://gitlab.com/slepc/slepc
:Date: |today|
.. include:: abstract.txt
Contents
========
.. include:: toctree.txt
.. include:: links.txt
slepc4py-3.20.2/docs/source/toctree.txt 0000644 0001751 0001751 00000000165 14575027370 020613 0 ustar jroman jroman 0000000 0000000 .. toctree::
:maxdepth: 2
overview
tutorial
install
citing
.. Local Variables:
.. mode: rst
.. End:
slepc4py-3.20.2/docs/source/citing.rst 0000644 0001751 0001751 00000001130 14575027370 020405 0 ustar jroman jroman 0000000 0000000 Citations
=========
If SLEPc for Python been significant to a project that leads to an
academic publication, please acknowledge that fact by citing the
project.
* L. Dalcin, P. Kler, R. Paz, and A. Cosimo,
*Parallel Distributed Computing using Python*,
Advances in Water Resources, 34(9):1124-1139, 2011.
http://dx.doi.org/10.1016/j.advwatres.2011.04.013
* V. Hernandez, J.E. Roman, and V. Vidal,
*SLEPc: A scalable and flexible toolkit for the solution of eigenvalue problems*,
ACM Transactions on Mathematical Software, 31(3):351-362, 2005.
http://dx.doi.org/10.1145/1089014.1089019
slepc4py-3.20.2/docs/source/install.rst 0000644 0001751 0001751 00000007701 14575027370 020610 0 ustar jroman jroman 0000000 0000000 Installation
============
Using **pip** or **easy_install**
---------------------------------
You can use :program:`pip` to install :mod:`slepc4py` and its
dependencies (:mod:`mpi4py` is optional but highly recommended)::
$ pip install [--user] numpy mpi4py
$ pip install [--user] petsc petsc4py
$ pip install [--user] slepc slepc4py
Alternatively, you can use :program:`easy_install` (deprecated)::
$ easy_install [--user] slepc4py
If you already have working PETSc and SLEPc installs, set environment
variables :envvar:`SLEPC_DIR` and :envvar:`PETSC_DIR` (and perhaps
:envvar:`PETSC_ARCH` for non-prefix installs) to appropriate values
and next use :program:`pip`::
$ export SLEPC_DIR=/path/to/slepc
$ export PETSC_DIR=/path/to/petsc
$ export PETSC_ARCH=arch-linux2-c-opt
$ pip install [--user] petsc4py slepc4py
Using **distutils**
-------------------
Requirements
^^^^^^^^^^^^
You need to have the following software properly installed in order to
build *SLEPc for Python*:
* Any MPI_ implementation [#]_ (e.g., MPICH_ or `Open MPI`_),
built with shared libraries.
* A matching version of PETSc_ built with shared libraries.
* A matching version of SLEPc_ built with shared libraries.
* NumPy_ package.
* petsc4py_ package.
.. [#] Unless you have appropriately configured and built SLEPc and
PETSc without MPI (configure option ``--with-mpi=0``).
.. [#] You may need to use a parallelized version of the Python
interpreter with some MPI-1 implementations (e.g. MPICH1).
.. include:: links.txt
Downloading
^^^^^^^^^^^
The *SLEPc for Python* package is available for download at the
Python Package Index. You can use
:program:`curl` or :program:`wget` to get a release tarball.
* Using :program:`curl`::
$ curl -LO https://pypi.io/packages/source/s/slepc4py/slepc4py-X.Y.Z.tar.gz
* Using :program:`wget`::
$ wget https://pypi.io/packages/source/s/slepc4py/slepc4py-X.Y.Z.tar.gz
Building
^^^^^^^^
After unpacking the release tarball::
$ tar -zxf slepc4py-X.Y.tar.gz
$ cd slepc4py-X.Y
the distribution is ready for building.
.. note:: **Mac OS X** users employing a Python distribution built
with **universal binaries** may need to set the environment
variables :envvar:`MACOSX_DEPLOYMENT_TARGET`, :envvar:`SDKROOT`,
and :envvar:`ARCHFLAGS` to appropriate values. As an example,
assume your Mac is running **Snow Leopard** on a **64-bit Intel**
processor and you want to override the hard-wired cross-development
SDK in Python configuration, your environment should be modified
like this::
$ export MACOSX_DEPLOYMENT_TARGET=10.6
$ export SDKROOT=/
$ export ARCHFLAGS='-arch x86_64'
Some environment configuration is needed to inform the location of
PETSc and SLEPc. You can set (using :command:`setenv`,
:command:`export` or what applies to you shell or system) the
environment variables :envvar:`SLEPC_DIR``, :envvar:`PETSC_DIR`, and
:envvar:`PETSC_ARCH` indicating where you have built/installed SLEPc
and PETSc::
$ export SLEPC_DIR=/usr/local/slepc
$ export PETSC_DIR=/usr/local/petsc
$ export PETSC_ARCH=arch-linux2-c-opt
Alternatively, you can edit the file :file:`setup.cfg` and provide the
required information below the ``[config]`` section::
[config]
slepc_dir = /usr/local/slepc
petsc_dir = /usr/local/petsc
petsc_arch = arch-linux2-c-opt
...
Finally, you can build the distribution by typing::
$ python setup.py build
Installing
^^^^^^^^^^
After building, the distribution is ready for installation.
If you have root privileges (either by log-in as the root user of by
using :command:`sudo`) and you want to install *SLEPc for Python* in
your system for all users, just do::
$ python setup.py install
The previous steps will install the :mod:`slepc4py` package at standard
location :file:`{prefix}/lib/python{X}.{X}/site-packages`.
If you do not have root privileges or you want to install *SLEPc for
Python* for your private use, just do::
$ python setup.py install --user
slepc4py-3.20.2/docs/source/links.txt 0000644 0001751 0001751 00000000743 14575027370 020270 0 ustar jroman jroman 0000000 0000000 .. _MPI: https://www.mpi-forum.org
.. _MPICH: https://www.mpich.org
.. _Open MPI: https://www.open-mpi.org
.. _PETSc: https://petsc.org
.. _SLEPc: https://slepc.upv.es
.. _Python: https://www.python.org
.. _NumPy: https://www.numpy.org
.. _mpi4py: https://github.com/mpi4py/mpi4py
.. _petsc4py: https://gitlab.com/petsc/petsc
.. _slepc4py: https://gitlab.com/slepc/slepc
.. Local Variables:
.. mode: rst
.. End:
slepc4py-3.20.2/docs/index.rst 0000644 0001751 0001751 00000003361 14575027370 016747 0 ustar jroman jroman 0000000 0000000 ================
SLEPc for Python
================
:Author: Lisandro Dalcin
:Contact: dalcinl@gmail.com
Online Documentation
--------------------
+ `User Manual (HTML)`_ (generated with Sphinx_).
+ `User Manual (PDF)`_ (generated with Sphinx_).
+ `API Reference`_ (generated with Epydoc_).
.. _User Manual (HTML): usrman/index.html
.. _User Manual (PDF): slepc4py.pdf
.. _API Reference: apiref/index.html
.. _Sphinx: https://www.sphinx-doc.org/
.. _Epydoc: https://epydoc.sourceforge.net/
Discussion and Support
----------------------
+ Mailing Lists: petsc-users@mcs.anl.gov, slepc-maint@upv.es
Downloads and Development
-------------------------
+ Issue Tracker: https://gitlab.com/slepc/slepc/-/issues
+ Git Repository: https://gitlab.com/slepc/slepc.git
+ The source code is in ``src/binding/slepc4py``
+ Previous source releases: https://pypi.org/project/slepc4py/
Citations
---------
If SLEPc for Python been significant to a project that leads to an
academic publication, please acknowledge that fact by citing the
project.
* L. Dalcin, P. Kler, R. Paz, and A. Cosimo,
*Parallel Distributed Computing using Python*,
Advances in Water Resources, 34(9):1124-1139, 2011.
http://dx.doi.org/10.1016/j.advwatres.2011.04.013
* V. Hernandez, J.E. Roman, and V. Vidal,
*SLEPc: A scalable and flexible toolkit for the solution of eigenvalue problems*,
ACM Transactions on Mathematical Software, 31(3):351-362, 2005.
http://dx.doi.org/10.1145/1089014.1089019
Acknowledgments
---------------
This project was partially supported by the
Extreme Computing Research Center (ECRC),
Division of Computer, Electrical, and
Mathematical Sciences & Engineering (CEMSE),
King Abdullah University of Science and Technology (KAUST).
slepc4py-3.20.2/conf/ 0000755 0001751 0001751 00000000000 14575030440 015070 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/conf/confpetsc.py 0000644 0001751 0001751 00000104752 14575027370 017447 0 ustar jroman jroman 0000000 0000000 # --------------------------------------------------------------------
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 = '3.0.0'
def cython_req():
return CYTHON
def cython_chk(VERSION, verbose=True):
#
def warn(message):
if not verbose: return
ruler, ws, nl = "*"*80, " " ,"\n"
pyexe = sys.executable
advise = "$ %s -m pip install --upgrade cython" % pyexe
def printer(*s): sys.stderr.write(" ".join(s)+"\n")
printer(ruler, nl)
printer(ws, message, nl)
printer(ws, ws, advise, nl)
printer(ruler)
#
try:
import Cython
except ImportError:
warn("You need Cython to generate C source files.")
return False
#
CYTHON_VERSION = Cython.__version__
m = re.match(r"(\d+\.\d+(?:\.\d+)?).*", CYTHON_VERSION)
if not m:
warn("Cannot parse Cython version string {0!r}"
.format(CYTHON_VERSION))
return False
REQUIRED = Version(VERSION)
PROVIDED = Version(m.groups()[0])
if PROVIDED < REQUIRED:
warn("You need Cython >= {0} (you have version {1})"
.format(VERSION, CYTHON_VERSION))
return False
#
if verbose:
log.info("using Cython %s" % CYTHON_VERSION)
return True
def cython_run(
source, target=None,
depends=(), includes=(),
workdir=None, force=False,
VERSION="0.0",
):
if target is None:
target = os.path.splitext(source)[0]+'.c'
cwd = os.getcwd()
try:
if workdir:
os.chdir(workdir)
alldeps = [source]
for dep in depends:
alldeps += glob.glob(dep)
if not (force or 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(r'-arch\s+\w+', ' ', str(flag))
if count and ARCHFLAGS:
flag = flag + ' ' + ARCHFLAGS
values[i] = flag
if 'SDKROOT' in os.environ:
SDKROOT = os.environ['SDKROOT']
for i, flag in enumerate(list(values)):
flag, count = re.subn(r'-isysroot [^ \t]*', ' ', str(flag))
if count and SDKROOT:
flag = flag + ' ' + '-isysroot ' + SDKROOT
values[i] = flag
return values
def get_config_vars(*names):
# Core Python configuration
values = sysconfig.get_config_vars(*names)
# Do any distutils flags fixup right now
values = fix_config_vars(names, values)
return values
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
user_options += [(
'inplace',
'i',
"ignore build-lib and put compiled extensions into the source "
"directory alongside your pure Python modules",
)]
user_options += cmd_petsc_opts
boolean_options = _build.boolean_options
boolean_options += ['inplace']
def initialize_options(self):
_build.initialize_options(self)
self.inplace = None
self.petsc_dir = None
self.petsc_arch = None
def finalize_options(self):
_build.finalize_options(self)
if self.inplace is None:
self.inplace = False
self.set_undefined_options('config',
('petsc_dir', 'petsc_dir'),
('petsc_arch', 'petsc_arch'))
self.petsc_dir = config.get_petsc_dir(self.petsc_dir)
self.petsc_arch = config.get_petsc_arch(self.petsc_dir,
self.petsc_arch)
sub_commands = \
[('build_src', lambda *args: True)] + \
_build.sub_commands
class build_src(Command):
description = "build C sources from Cython files"
user_options = [
('force', 'f',
"forcibly build everything (ignore file timestamps)"),
]
boolean_options = ['force']
def initialize_options(self):
self.force = False
def finalize_options(self):
self.set_undefined_options('build',
('force', 'force'),
)
def run(self):
sources = getattr(self, 'sources', [])
for source in sources:
cython_run(
force=self.force,
VERSION=cython_req(),
**source
)
class build_ext(_build_ext):
user_options = _build_ext.user_options + cmd_petsc_opts
def initialize_options(self):
_build_ext.initialize_options(self)
self.inplace = None
self.petsc_dir = None
self.petsc_arch = None
self._outputs = []
def finalize_options(self):
_build_ext.finalize_options(self)
self.set_undefined_options('build', ('inplace', 'inplace'))
self.set_undefined_options('build',
('petsc_dir', 'petsc_dir'),
('petsc_arch', 'petsc_arch'))
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(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = _re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = _re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def makefile(fileobj, dct=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
fp = TextFile(file=fileobj,
strip_comments=1,
skip_blanks=1,
join_lines=1)
if dct is None:
dct = {}
done = {}
notdone = {}
while 1:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = str.strip(v)
if "$" in v:
notdone[n] = v
else:
try: v = int(v)
except ValueError: pass
done[n] = v
try: del notdone[n]
except KeyError: pass
fp.close()
# do variable interpolation here
while notdone:
for name in list(notdone.keys()):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
found = True
if n in done:
item = str(done[n])
elif n in notdone:
# get it on a subsequent round
found = False
else:
done[n] = item = ""
if found:
after = value[m.end():]
value = value[:m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = str.strip(value)
else:
done[name] = value
del notdone[name]
else:
# bogus variable reference;
# just drop it since we can't deal
del notdone[name]
# save the results in the global dictionary
dct.update(done)
return dct
# --------------------------------------------------------------------
slepc4py-3.20.2/conf/cythonize.sh 0000755 0001751 0001751 00000000223 14575027370 017450 0 ustar jroman jroman 0000000 0000000 #!/bin/sh
topdir=$(cd $(dirname "$0")/.. && pwd)
python$py "$topdir/conf/cythonize.py" \
--working "$topdir/src" $@ \
"slepc4py/SLEPc.pyx"
slepc4py-3.20.2/conf/epydoc.cfg 0000644 0001751 0001751 00000010553 14575027370 017050 0 ustar jroman jroman 0000000 0000000 [epydoc] # Epydoc section marker (required by ConfigParser)
# The list of objects to document. Objects can be named using
# dotted names, module filenames, or package directory names.
# Alases for this option include "objects" and "values".
modules: slepc4py
# The type of output that should be generated. Should be one
# of: html, text, latex, dvi, ps, pdf.
#output: html
# The path to the output directory. May be relative or absolute.
#target: docs/html/
# An integer indicating how verbose epydoc should be. The default
# value is 0; negative values will suppress warnings and errors;
# positive values will give more verbose output.
verbosity: 0
# A boolean value indicating that Epydoc should show a tracaback
# in case of unexpected error. By default don't show tracebacks
#debug: 0
# If True, don't try to use colors or cursor control when doing
# textual output. The default False assumes a rich text prompt
#simple-term: 0
### Generation options
# The default markup language for docstrings, for modules that do
# not define __docformat__. Defaults to epytext.
docformat: reStructuredText
# Whether or not parsing should be used to examine objects.
parse: yes
# Whether or not introspection should be used to examine objects.
introspect: yes
# Don't examine in any way the modules whose dotted name match this
# regular expression pattern.
exclude: slepc4py.__main__
# Don't perform introspection on the modules whose dotted name match this
# regular expression pattern.
#exclude-introspect
# Don't perform parsing on the modules whose dotted name match this
# regular expression pattern.
#exclude-parse:
# The format for showing inheritance objects.
# It should be one of: 'grouped', 'listed', 'included'.
inheritance: listed
# Whether or not to include private variables. (Even if included,
# private variables will be hidden by default.)
private: yes
# Whether or not to list each module's imports.
imports: no
# Whether or not to include syntax highlighted source code in
# the output (HTML only).
sourcecode: no
# Whether or not to include a a page with Epydoc log, containing
# effective option at the time of generation and the reported logs.
include-log: no
### Output options
# The documented project's name.
name: SLEPc for Python
# The documented project's URL.
url: https://gitlab.com/slepc/slepc
# The CSS stylesheet for HTML output. Can be the name of a builtin
# stylesheet, or the name of a file.
css: white
# HTML code for the project link in the navigation bar. If left
# unspecified, the project link will be generated based on the
# project's name and URL.
#link: My Cool Project
# The "top" page for the documentation. Can be a URL, the name
# of a module or class, or one of the special names "trees.html",
# "indices.html", or "help.html"
#top: os.path
# An alternative help file. The named file should contain the
# body of an HTML file; navigation bars will be added to it.
#help: my_helpfile.html
# Whether or not to include a frames-based table of contents.
frames: yes
# Whether each class should be listed in its own section when
# generating LaTeX or PDF output.
separate-classes: no
### API linking options
# Define a new API document. A new interpreted text role
# will be created
#external-api: epydoc
# Use the records in this file to resolve objects in the API named NAME.
#external-api-file: epydoc:api-objects.txt
# Use this URL prefix to configure the string returned for external API.
#external-api-root: epydoc:http://epydoc.sourceforge.net/api
### Graph options
# The list of graph types that should be automatically included
# in the output. Graphs are generated using the Graphviz "dot"
# executable. Graph types include: "classtree", "callgraph",
# "umlclasstree". Use "all" to include all graph types
graph: classtree
# The path to the Graphviz "dot" executable, used to generate
# graphs.
#dotpath: /usr/local/bin/dot
# The name of one or more pstat files (generated by the profile
# or hotshot module). These are used to generate call graphs.
#pstat: profile.out
# Specify the font used to generate Graphviz graphs.
# (e.g., helvetica or times).
graph-font: Helvetica
# Specify the font size used to generate Graphviz graphs.
graph-font-size: 10
### Return value options
# The condition upon which Epydoc should exit with a non-zero
# exit status. Possible values are error, warning, docstring_warning
#fail-on: error
slepc4py-3.20.2/conf/__init__.py 0000644 0001751 0001751 00000000000 14575027370 017177 0 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/conf/confslepc.py 0000644 0001751 0001751 00000021413 14575027370 017427 0 ustar jroman jroman 0000000 0000000 import os
import sys
from confpetsc import setup as _setup
from confpetsc import Extension
from confpetsc import config as _config
from confpetsc import build as _build
from confpetsc import build_src as _build_src
from confpetsc import build_ext as _build_ext
from confpetsc import install as _install
from confpetsc import log
from confpetsc import makefile
from confpetsc import strip_prefix
from confpetsc import split_quoted
from confpetsc import DistutilsError
from confpetsc import PetscConfig
# --------------------------------------------------------------------
class SlepcConfig(PetscConfig):
def __init__(self, slepc_dir, petsc_dir, petsc_arch, dest_dir=None):
PetscConfig.__init__(self, petsc_dir, petsc_arch, dest_dir='')
if dest_dir is None:
dest_dir = os.environ.get('DESTDIR')
if not slepc_dir:
raise DistutilsError("SLEPc not found")
if not os.path.isdir(slepc_dir):
raise DistutilsError("invalid SLEPC_DIR")
self.sversion = self._get_slepc_version(slepc_dir)
self._get_slepc_config(petsc_dir,slepc_dir)
self.SLEPC_DIR = self['SLEPC_DIR']
self.SLEPC_DESTDIR = dest_dir
self.SLEPC_LIB = self['SLEPC_LIB']
self.SLEPC_EXTERNAL_LIB_DIR = self['SLEPC_EXTERNAL_LIB_DIR']
def _get_slepc_version(self, slepc_dir):
import re
version_re = {
'major' : re.compile(r"#define\s+SLEPC_VERSION_MAJOR\s+(\d+)"),
'minor' : re.compile(r"#define\s+SLEPC_VERSION_MINOR\s+(\d+)"),
'micro' : re.compile(r"#define\s+SLEPC_VERSION_SUBMINOR\s+(\d+)"),
'release': re.compile(r"#define\s+SLEPC_VERSION_RELEASE\s+(-*\d+)"),
}
slepcversion_h = os.path.join(slepc_dir, 'include', 'slepcversion.h')
with open(slepcversion_h, 'rt') as f: data = f.read()
major = int(version_re['major'].search(data).groups()[0])
minor = int(version_re['minor'].search(data).groups()[0])
micro = int(version_re['micro'].search(data).groups()[0])
release = int(version_re['release'].search(data).groups()[0])
return (major, minor, micro), (release == 1)
def _get_slepc_config(self, petsc_dir, slepc_dir):
from os.path import join, isdir
PETSC_DIR = petsc_dir
SLEPC_DIR = slepc_dir
PETSC_ARCH = self.PETSC_ARCH
confdir = join('lib', 'slepc', 'conf')
if not (PETSC_ARCH and isdir(join(SLEPC_DIR, PETSC_ARCH))):
PETSC_ARCH = ''
variables = join(SLEPC_DIR, confdir, 'slepc_variables')
slepcvariables = join(SLEPC_DIR, PETSC_ARCH, confdir, 'slepcvariables')
with open(variables) as f:
contents = f.read()
with open(slepcvariables) as f:
contents += f.read()
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
confstr = 'PETSC_DIR = %s\n' % PETSC_DIR
confstr += 'PETSC_ARCH = %s\n' % PETSC_ARCH
confstr = 'SLEPC_DIR = %s\n' % SLEPC_DIR
confstr += contents
slepc_confdict = makefile(StringIO(confstr))
self.configdict['SLEPC_DIR'] = SLEPC_DIR
self.configdict['SLEPC_LIB'] = slepc_confdict['SLEPC_LIB']
dirlist = []
flags = split_quoted(slepc_confdict['SLEPC_EXTERNAL_LIB'])
for entry in [lib[2:] for lib in flags if lib.startswith('-L')]:
if entry not in dirlist:
dirlist.append(entry)
self.configdict['SLEPC_EXTERNAL_LIB_DIR'] = dirlist
def configure_extension(self, extension):
PetscConfig.configure_extension(self, extension)
SLEPC_DIR = self.SLEPC_DIR
PETSC_ARCH = self.PETSC_ARCH
SLEPC_DESTDIR = self.SLEPC_DESTDIR
# take into account the case of prefix PETSc with non-prefix SLEPc
SLEPC_ARCH_DIR = PETSC_ARCH or os.environ.get('PETSC_ARCH', '')
# includes and libraries
SLEPC_INCLUDE = [
os.path.join(SLEPC_DIR, SLEPC_ARCH_DIR, 'include'),
os.path.join(SLEPC_DIR, 'include'),
]
SLEPC_LIB_DIR = [
os.path.join(SLEPC_DIR, SLEPC_ARCH_DIR, 'lib'),
os.path.join(SLEPC_DIR, 'lib'),
] + self.SLEPC_EXTERNAL_LIB_DIR
slepc_cfg = { }
slepc_cfg['include_dirs'] = SLEPC_INCLUDE
slepc_cfg['library_dirs'] = SLEPC_LIB_DIR
slepc_cfg['libraries'] = [
lib[2:] for lib in split_quoted(self.SLEPC_LIB)
if lib.startswith('-l')
]
slepc_cfg['runtime_library_dirs'] = [
strip_prefix(SLEPC_DESTDIR, d) for d in SLEPC_LIB_DIR
]
self._configure_ext(extension, slepc_cfg, append=True)
if self['BUILDSHAREDLIB'] == 'no':
from petsc4py.lib import ImportPETSc
PETSc = ImportPETSc(PETSC_ARCH)
extension.extra_objects.append(PETSc.__file__)
# extra configuration
cflags = []
extension.extra_compile_args.extend(cflags)
lflags = []
extension.extra_link_args.extend(lflags)
def log_info(self):
if not self.SLEPC_DIR: return
version = ".".join([str(i) for i in self.sversion[0]])
release = ("development", "release")[self.sversion[1]]
version_info = version + ' ' + release
log.info('SLEPC_DIR: %s' % self.SLEPC_DIR)
log.info('version: %s' % version_info)
PetscConfig.log_info(self)
# --------------------------------------------------------------------
cmd_slepc_opts = [
('slepc-dir=', None,
"define SLEPC_DIR, overriding environmental variable.")
]
class config(_config):
Configure = SlepcConfig
user_options = _config.user_options + cmd_slepc_opts
def initialize_options(self):
_config.initialize_options(self)
self.slepc_dir = None
def get_config_arch(self, arch):
return config.Configure(self.slepc_dir, self.petsc_dir, arch)
def run(self):
self.slepc_dir = config.get_slepc_dir(self.slepc_dir)
if self.slepc_dir is None: return
log.info('-' * 70)
log.info('SLEPC_DIR: %s' % self.slepc_dir)
_config.run(self)
#@staticmethod
def get_slepc_dir(slepc_dir):
if not slepc_dir: return None
slepc_dir = os.path.expandvars(slepc_dir)
if not slepc_dir or '$SLEPC_DIR' in slepc_dir:
try:
import slepc
slepc_dir = slepc.get_slepc_dir()
except ImportError:
log.warn("SLEPC_DIR not specified")
return None
slepc_dir = os.path.expanduser(slepc_dir)
slepc_dir = os.path.abspath(slepc_dir)
if not os.path.isdir(slepc_dir):
log.warn('invalid SLEPC_DIR: %s' % slepc_dir)
return None
return slepc_dir
get_slepc_dir = staticmethod(get_slepc_dir)
class build(_build):
user_options = _build.user_options + cmd_slepc_opts
def initialize_options(self):
_build.initialize_options(self)
self.slepc_dir = None
def finalize_options(self):
_build.finalize_options(self)
self.set_undefined_options('config',
('slepc_dir', 'slepc_dir'),)
self.slepc_dir = config.get_slepc_dir(self.slepc_dir)
class build_src(_build_src):
pass
class build_ext(_build_ext):
user_options = _build_ext.user_options + cmd_slepc_opts
def initialize_options(self):
_build_ext.initialize_options(self)
self.slepc_dir = None
def finalize_options(self):
_build_ext.finalize_options(self)
self.set_undefined_options('build',
('slepc_dir', 'slepc_dir'))
def get_config_arch(self, arch):
return config.Configure(self.slepc_dir, self.petsc_dir, arch)
def get_config_data(self, arch_list):
DESTDIR = None
for arch in arch_list:
conf = self.get_config_arch(arch)
DESTDIR = conf.SLEPC_DESTDIR # all archs will have same value
template = "\n".join([
"SLEPC_DIR = %(SLEPC_DIR)s",
"PETSC_DIR = %(PETSC_DIR)s",
"PETSC_ARCH = %(PETSC_ARCH)s",
]) + "\n"
variables = {
'SLEPC_DIR' : strip_prefix(DESTDIR, self.slepc_dir),
'PETSC_DIR' : self.petsc_dir,
'PETSC_ARCH' : os.path.pathsep.join(arch_list)
}
return template, variables
class install(_install):
pass
cmdclass_list = [
config,
build,
build_src,
build_ext,
install,
]
# --------------------------------------------------------------------
def setup(**attrs):
cmdclass = attrs.setdefault('cmdclass', {})
for cmd in cmdclass_list:
cmdclass.setdefault(cmd.__name__, cmd)
return _setup(**attrs)
# --------------------------------------------------------------------
slepc4py-3.20.2/conf/cythonize.py 0000755 0001751 0001751 00000002445 14575027370 017476 0 ustar jroman jroman 0000000 0000000 #!/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('slepc4py', 'SLEPc.pyx')
target = os.path.join('slepc4py', 'SLEPc.c')
args += ['--working', srcdir]
args += [source, '--output-file', target]
sys.exit(cythonize(args))
if __name__ == "__main__":
main()
slepc4py-3.20.2/conf/epydocify.py 0000755 0001751 0001751 00000005505 14575027370 017455 0 ustar jroman jroman 0000000 0000000 #!/usr/bin/env python
# --------------------------------------------------------------------
from slepc4py import SLEPc
# --------------------------------------------------------------------
try:
from docutils.nodes import NodeVisitor
NodeVisitor.unknown_visit = lambda self, node: None
NodeVisitor.unknown_departure = lambda self, node: None
except ImportError:
pass
try: # epydoc 3.0.1 + docutils 0.6
from docutils.nodes import Text
from UserString import UserString
if not isinstance(Text, UserString):
def Text_get_data(s):
try:
return s._data
except AttributeError:
return s.astext()
def Text_set_data(s, d):
s.astext = lambda: d
s._data = d
Text.data = property(Text_get_data, Text_set_data)
except ImportError:
pass
# --------------------------------------------------------------------
from epydoc.docwriter import dotgraph
import re
dotgraph._DOT_VERSION_RE = \
re.compile(r'dot (?:- Graphviz )version ([\d\.]+)')
try:
dotgraph.DotGraph.DEFAULT_HTML_IMAGE_FORMAT
dotgraph.DotGraph.DEFAULT_HTML_IMAGE_FORMAT = 'png'
except AttributeError:
DotGraph_to_html = dotgraph.DotGraph.to_html
DotGraph_run_dot = dotgraph.DotGraph._run_dot
def to_html(self, image_file, image_url, center=True):
if image_file[-4:] == '.gif':
image_file = image_file[:-4] + '.png'
if image_url[-4:] == '.gif':
image_url = image_url[:-4] + '.png'
return DotGraph_to_html(self, image_file, image_url)
def _run_dot(self, *options):
if '-Tgif' in options:
opts = list(options)
for i, o in enumerate(opts):
if o == '-Tgif': opts[i] = '-Tpng'
options = type(options)(opts)
return DotGraph_run_dot(self, *options)
dotgraph.DotGraph.to_html = to_html
dotgraph.DotGraph._run_dot = _run_dot
# --------------------------------------------------------------------
import re
_SIGNATURE_RE = re.compile(
# Class name (for builtin methods)
r'^\s*((?P\w+)\.)?' +
# The function name
r'(?P\w+)' +
# The parameters
r'\(((?P(?:self|cls|mcs)),?)?(?P.*)\)' +
# The return value (optional)
r'(\s*(->)\s*(?P\S.*?))?'+
# The end marker
r'\s*(\n|\s+(--|<=+>)\s+|$|\.\s+|\.\n)')
from epydoc import docstringparser as dsp
dsp._SIGNATURE_RE = _SIGNATURE_RE
# --------------------------------------------------------------------
import sys, os
import epydoc.cli
def epydocify():
dirname = os.path.dirname(__file__)
config = os.path.join(dirname, 'epydoc.cfg')
sys.argv.append('--config=' + config)
epydoc.cli.cli()
if __name__ == '__main__':
epydocify()
# --------------------------------------------------------------------
slepc4py-3.20.2/src/ 0000755 0001751 0001751 00000000000 14575030440 014732 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/src/slepc4py/ 0000755 0001751 0001751 00000000000 14575030440 016475 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/src/slepc4py/SLEPc/ 0000755 0001751 0001751 00000000000 14575030440 017403 5 ustar jroman jroman 0000000 0000000 slepc4py-3.20.2/src/slepc4py/SLEPc/RG.pyx 0000644 0001751 0001751 00000041162 14575027370 020471 0 ustar jroman jroman 0000000 0000000 # -----------------------------------------------------------------------------
class RGType(object):
"""
RG type
"""
INTERVAL = S_(RGINTERVAL)
POLYGON = S_(RGPOLYGON)
ELLIPSE = S_(RGELLIPSE)
RING = S_(RGRING)
class RGQuadRule(object):
"""
RG quadrature rule for contour integral methods
- `TRAPEZOIDAL`: Trapezoidal rule.
- `CHEBYSHEV`: Chebyshev points.
"""
TRAPEZOIDAL = EPS_CISS_QUADRULE_TRAPEZOIDAL
CHEBYSHEV = EPS_CISS_QUADRULE_CHEBYSHEV
# -----------------------------------------------------------------------------
cdef class RG(Object):
"""
RG
"""
Type = RGType
QuadRule = RGQuadRule
def __cinit__(self):
self.obj = &self.rg
self.rg = NULL
def view(self, Viewer viewer=None):
"""
Prints the RG data structure.
Parameters
----------
viewer: Viewer, optional
Visualization context; if not provided, the standard
output is used.
"""
cdef PetscViewer vwr = def_Viewer(viewer)
CHKERR( RGView(self.rg, vwr) )
def destroy(self):
"""
Destroys the RG object.
"""
CHKERR( RGDestroy(&self.rg) )
self.rg = NULL
return self
def create(self, comm=None):
"""
Creates the RG object.
Parameters
----------
comm: Comm, optional
MPI communicator; if not provided, it defaults to all
processes.
"""
cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT())
cdef SlepcRG newrg = NULL
CHKERR( RGCreate(ccomm, &newrg) )
CHKERR( SlepcCLEAR(self.obj) ); self.rg = newrg
return self
def setType(self, rg_type):
"""
Selects the type for the RG object.
Parameters
----------
rg_type: `RG.Type` enumerate
The inner product type to be used.
"""
cdef SlepcRGType cval = NULL
rg_type = str2bytes(rg_type, &cval)
CHKERR( RGSetType(self.rg, cval) )
def getType(self):
"""
Gets the RG type of this object.
Returns
-------
type: `RG.Type` enumerate
The inner product type currently being used.
"""
cdef SlepcRGType rg_type = NULL
CHKERR( RGGetType(self.rg, &rg_type) )
return bytes2str(rg_type)
def setOptionsPrefix(self, prefix):
"""
Sets the prefix used for searching for all RG options in the
database.
Parameters
----------
prefix: string
The prefix string to prepend to all RG option
requests.
Notes
-----
A hyphen (``-``) must NOT be given at the beginning of the
prefix name. The first character of all runtime options is
AUTOMATICALLY the hyphen.
"""
cdef const char *cval = NULL
prefix = str2bytes(prefix, &cval)
CHKERR( RGSetOptionsPrefix(self.rg, cval) )
def getOptionsPrefix(self):
"""
Gets the prefix used for searching for all RG options in the
database.
Returns
-------
prefix: string
The prefix string set for this RG object.
"""
cdef const char *prefix = NULL
CHKERR( RGGetOptionsPrefix(self.rg, &prefix) )
return bytes2str(prefix)
def setFromOptions(self):
"""
Sets RG options from the options database.
Notes
-----
To see all options, run your program with the ``-help``
option.
"""
CHKERR( RGSetFromOptions(self.rg) )
#
def isTrivial(self):
"""
Tells whether it is the trivial region (whole complex plane).
Returns
-------
flag: bool
True if the region is equal to the whole complex plane, e.g.,
an interval region with all four endpoints unbounded or an
ellipse with infinite radius.
"""
cdef PetscBool tval = PETSC_FALSE
CHKERR( RGIsTrivial(self.rg, &tval) )
return toBool(tval)
def isAxisymmetric(self, vertical=False):
"""
Determines if the region is symmetric with respect to the real
or imaginary axis.
Parameters
----------
vertical: bool, optional
True if symmetry must be checked against the vertical axis.
Returns
-------
symm: bool
True if the region is axisymmetric.
"""
cdef PetscBool val = asBool(vertical)
cdef PetscBool tval = PETSC_FALSE
CHKERR( RGIsAxisymmetric(self.rg, val, &tval) )
return toBool(tval)
def getComplement(self):
"""
Returns the flag indicating whether the region is complemented or not.
Returns
-------
flg: bool
Whether the region is complemented or not.
"""
cdef PetscBool tval = PETSC_FALSE
CHKERR( RGGetComplement(self.rg, &tval) )
return toBool(tval)
def setComplement(self, comp=True):
"""
Sets a flag to indicate that the region is the complement
of the specified one.
Parameters
----------
comp: bool, optional
Activate/deactivate the complementation of the region.
"""
cdef PetscBool tval = asBool(comp)
CHKERR( RGSetComplement(self.rg, tval) )
def setScale(self, sfactor=None):
"""
Sets the scaling factor to be used when checking that a
point is inside the region and when computing the contour.
Parameters
----------
sfactor: float, optional
The scaling factor (default=1).
"""
cdef PetscReal rval = 1.0
if sfactor is not None: rval = asReal(sfactor)
CHKERR( RGSetScale(self.rg, rval) )
def getScale(self):
"""
Gets the scaling factor.
Returns
-------
sfactor: float
The scaling factor.
"""
cdef PetscReal rval = 0
CHKERR( RGGetScale(self.rg, &rval) )
return toReal(rval)
def checkInside(self, a):
"""
Determines if a set of given points are inside the region or not.
Parameters
----------
a: list of float (complex)
The coordinates of the points.
Returns
-------
inside: list of int
Computed result for each point (1=inside, 0=on the contour, -1=outside).
"""
cdef Py_ssize_t i = 0, n = len(a)
cdef PetscScalar *ar = NULL, *ai = NULL
cdef PetscInt *inside = NULL
cdef tmp1 = allocate(n*sizeof(PetscScalar),&ar)
cdef tmp2
if sizeof(PetscScalar) == sizeof(PetscReal):
tmp2 = allocate(n*sizeof(PetscScalar),&ai)
for i in range(n):
ar[i] = asComplexReal(a[i])
ai[i] = asComplexImag(a[i])
else:
for i in range(n): ar[i] = asScalar(a[i])
cdef tmp3 = allocate(n*sizeof(PetscInt),&inside)
CHKERR( RGCheckInside(self.rg, n, ar, ai, inside) )
return array_i(n, inside)
def computeContour(self, n):
"""
Computes the coordinates of several points lying on the contour
of the region.
Parameters
----------
n: int
The number of points to compute.
Returns
-------
x: list of float (complex)
Computed points.
"""
cdef PetscInt k = asInt(n), i = 0
cdef PetscScalar *cr = NULL, *ci = NULL
cdef tmp1 = allocate(k*sizeof(PetscScalar),&cr)
cdef tmp2
if sizeof(PetscScalar) == sizeof(PetscReal):
tmp2 = allocate(k*sizeof(PetscScalar),&ci)
CHKERR( RGComputeContour(self.rg, k, cr, ci) )
if sizeof(PetscScalar) == sizeof(PetscReal):
return [toComplex(cr[i],ci[i]) for i from 0 <= i k*sizeof(PetscScalar),&z)
cdef tmp2 = allocate(k*sizeof(PetscScalar),&zn)
cdef tmp3 = allocate(k*sizeof(PetscScalar),&w)
CHKERR( RGComputeQuadrature(self.rg, val, k, z, zn, w) )
return (array_s(k, z), array_s(k, zn), array_s(k, w))
#
def setEllipseParameters(self, center, radius, vscale=None):
"""
Sets the parameters defining the ellipse region.
Parameters
----------
center: float (real or complex)
The center.
radius: float
The radius.
vscale: float, optional
The vertical scale.
"""
cdef PetscScalar sval = asScalar(center)
cdef PetscReal val1 = asReal(radius)
cdef PetscReal val2 = 1.0
if vscale is not None: val2 = asReal(vscale)
CHKERR( RGEllipseSetParameters(self.rg, sval, val1, val2) )
def getEllipseParameters(self):
"""
Gets the parameters that define the ellipse region.
Returns
-------
center: float (real or complex)
The center.
radius: float
The radius.
vscale: float
The vertical scale.
"""
cdef PetscScalar sval = 0
cdef PetscReal val1 = 0
cdef PetscReal val2 = 0
CHKERR( RGEllipseGetParameters(self.rg, &sval, &val1, &val2) )
return (toScalar(sval), toReal(val1), toReal(val2))
def setIntervalEndpoints(self, a, b, c, d):
"""
Sets the parameters defining the interval region.
Parameters
----------
a: float
The left endpoint in the real axis.
b: float
The right endpoint in the real axis.
c: float
The upper endpoint in the imaginary axis.
d: float
The lower endpoint in the imaginary axis.
"""
cdef PetscReal va = asReal(a)
cdef PetscReal vb = asReal(b)
cdef PetscReal vc = asReal(c)
cdef PetscReal vd = asReal(d)
CHKERR( RGIntervalSetEndpoints(self.rg, va, vb, vc, vd) )
def getIntervalEndpoints(self):
"""
Gets the parameters that define the interval region.
Returns
-------
a: float
The left endpoint in the real axis.
b: float
The right endpoint in the real axis.
c: float
The upper endpoint in the imaginary axis.
d: float
The lower endpoint in the imaginary axis.
"""
cdef PetscReal va = 0
cdef PetscReal vb = 0
cdef PetscReal vc = 0
cdef PetscReal vd = 0
CHKERR( RGIntervalGetEndpoints(self.rg, &va, &vb, &vc, &vd) )
return (toReal(va), toReal(vb), toReal(vc), toReal(vd))
def setPolygonVertices(self, v):
"""
Sets the vertices that define the polygon region.
Parameters
----------
v: list of float (complex)
The vertices.
"""
cdef Py_ssize_t i = 0, n = len(v)
cdef PetscScalar *vr = NULL, *vi = NULL
cdef tmp1 = allocate(n*sizeof(PetscScalar),&vr)
cdef tmp2
if sizeof(PetscScalar) == sizeof(PetscReal):
tmp2 = allocate(n*sizeof(PetscScalar),&vi)
for i in range(n):
vr[i] = asComplexReal(v[i])
vi[i] = asComplexImag(v[i])
else:
for i in range(n): vr[i] = asScalar(v[i])
CHKERR( RGPolygonSetVertices(self.rg, n, vr, vi) )
def getPolygonVertices(self):
"""
Gets the parameters that define the interval region.
Returns
-------
v: list of float (complex)
The vertices.
"""
cdef PetscInt n = 0
cdef PetscScalar *vr = NULL, *vi = NULL
CHKERR( RGPolygonGetVertices(self.rg, &n, &vr, &vi) )
if sizeof(PetscScalar) == sizeof(PetscReal):
v = [toComplex(vr[i],vi[i]) for i from 0 <= i