Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • isuruf/pymbolic
  • inducer/pymbolic
  • xywei/pymbolic
  • wence-/pymbolic
  • kaushikcfd/pymbolic
  • fikl2/pymbolic
  • zweiner2/pymbolic
7 results
Show changes
Commits on Source (800)
# https://editorconfig.org/
# https://github.com/editorconfig/editorconfig-vim
# https://github.com/editorconfig/editorconfig-emacs
root = true
[*]
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.py]
indent_size = 4
[*.rst]
indent_size = 4
[*.cpp]
indent_size = 2
[*.hpp]
indent_size = 2
# There may be one in doc/
[Makefile]
indent_style = tab
# https://github.com/microsoft/vscode/issues/1679
[*.md]
trim_trailing_whitespace = false
version: 2
updates:
# Set update schedule for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
# vim: sw=4
name: Gitlab mirror
on:
push:
branches:
- main
jobs:
autopush:
name: Automatic push to gitlab.tiker.net
if: startsWith(github.repository, 'inducer/')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
mirror_github_to_gitlab
env:
GITLAB_AUTOPUSH_KEY: ${{ secrets.GITLAB_AUTOPUSH_KEY }}
# vim: sw=4
name: CI
on:
push:
branches:
- main
pull_request:
paths-ignore:
- 'doc/*.rst'
schedule:
- cron: '17 3 * * 0'
concurrency:
group: ${{ github.head_ref || github.ref_name }}
cancel-in-progress: true
jobs:
typos:
name: Typos
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: crate-ci/typos@master
ruff:
name: Ruff
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/setup-python@v5
- name: "Main Script"
run: |
pip install ruff
ruff check
pylint:
name: Pylint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
-
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: "Main Script"
run: |
EXTRA_INSTALL="numpy sympy scipy pexpect"
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
build_py_project_in_venv
# https://github.com/inducer/pymbolic/pull/66#issuecomment-950371315
pip install symengine || true
run_pylint pymbolic test/test_*.py
mypy:
name: Mypy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
-
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: "Main Script"
run: |
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
build_py_project_in_venv
pip install -e .[test]
python -m pip install mypy numpy
./run-mypy.sh
pytest:
name: Pytest on Py${{ matrix.python-version }}
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.12", "3.x"]
steps:
- uses: actions/checkout@v4
-
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: "Main Script"
run: |
EXTRA_INSTALL="numpy sympy pexpect"
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
build_py_project_in_venv
# https://github.com/inducer/pymbolic/pull/66#issuecomment-950371315
pip install symengine || true
test_py_project
docs:
name: Documentation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
-
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: "Main Script"
run: |
EXTRA_INSTALL="numpy sympy"
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
build_py_project_in_venv
build_docs
downstream_tests:
strategy:
matrix:
downstream_project: [loopy, pytential, pytato]
fail-fast: false
name: Tests for downstream project ${{ matrix.downstream_project }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: "Main Script"
env:
DOWNSTREAM_PROJECT: ${{ matrix.downstream_project }}
run: |
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
test_downstream "$DOWNSTREAM_PROJECT"
# vim: sw=4
......@@ -8,5 +8,8 @@ build
MANIFEST
dist
setuptools*egg
setuptools*tar.gz
setuptools.pth
_build
.cache
Python 3:
script: |
PY_EXE=python3
# pytest tries to import this, but it doesn't find symengine
rm pymbolic/interop/symengine.py
EXTRA_INSTALL="numpy sympy pexpect"
curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/build-and-test-py-project.sh
. ./build-and-test-py-project.sh
tags:
- python3
- maxima
except:
- tags
artifacts:
reports:
junit: test/pytest.xml
Python 3 Conda:
script: |
CONDA_ENVIRONMENT=.test-py3.yml
curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/build-and-test-py-project-within-miniconda.sh
. ./build-and-test-py-project-within-miniconda.sh
tags:
- linux
except:
- tags
artifacts:
reports:
junit: test/pytest.xml
Pylint:
script:
- EXTRA_INSTALL="numpy sympy symengine scipy pexpect"
- PY_EXE=python3
- curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/prepare-and-run-pylint.sh
- ". ./prepare-and-run-pylint.sh pymbolic test/test_*.py"
tags:
- python3
except:
- tags
Mypy:
script: |
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
build_py_project_in_venv
pip install -e .[test]
python -m pip install mypy numpy
./run-mypy.sh
tags:
- python3
except:
- tags
Documentation:
script:
- EXTRA_INSTALL="numpy sympy"
- curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/build-docs.sh
- ". ./build-docs.sh"
tags:
- linux
Ruff:
script: |
pipx install ruff
ruff check
tags:
- docker-runner
except:
- tags
Downstream:
parallel:
matrix:
- DOWNSTREAM_PROJECT: [loopy, pytential, pytato]
tags:
- large-node
- "docker-runner"
script: |
curl -L -O https://tiker.net/ci-support-v0
. ./ci-support-v0
test_downstream "$DOWNSTREAM_PROJECT"
- arg: ignored-modules
val:
- symengine
name: py3
channels:
- conda-forge
- defaults
dependencies:
- conda-forge::numpy
- conda-forge::sympy
- python
- python-symengine
# - pexpect
# - maxima
cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
- family-names: "Kloeckner"
given-names: "Andreas"
orcid: "https://orcid.org/0000-0003-1228-519X"
- family-names: "Wala"
given-names: "Matt"
- family-names: "Fernando"
given-names: "Isuru"
- family-names: "Kulkarni"
given-names: "Kaushik"
- family-names: "Fikl"
given-names: "Alex"
- family-names: "Weiner"
given-names: "Zach"
- family-names: "Kempf"
given-names: "Dominic"
- family-names: "Ham"
given-names: "David A."
- family-names: "Mitchell"
given-names: "Lawrence"
- family-names: "Wilcox"
given-names: "Lucas C"
- family-names: "Diener"
given-names: "Matthias"
- family-names: "Kapyshin"
given-names: "Pavlo"
- family-names: "Raksi"
given-names: "Reno"
- family-names: "Gibson"
given-names: "Thomas H."
title: "pymbolic"
version: 2022.1
doi: 10.5281/zenodo.6533945
date-released: 2022-05-08
url: "https://github.com/inducer/pymbolic"
license: MIT
pymbolic is licensed to you under the MIT/X Consortium license:
Copyright (c) 2009-16 Andreas Klöckner and Contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
include LITERATURE
include TODO
include distribute_setup.py
include LICENSE
include README.rst
......
Pymbolic
========
Pymbolic: Easy Expression Trees and Term Rewriting
==================================================
.. image:: https://gitlab.tiker.net/inducer/pymbolic/badges/main/pipeline.svg
:alt: Gitlab Build Status
:target: https://gitlab.tiker.net/inducer/pymbolic/commits/main
.. image:: https://github.com/inducer/pymbolic/workflows/CI/badge.svg?branch=main&event=push
:alt: Github Build Status
:target: https://github.com/inducer/pymbolic/actions?query=branch%3Amain+workflow%3ACI+event%3Apush
.. image:: https://badge.fury.io/py/pymbolic.png
:alt: Python Package Index Release Page
:target: https://pypi.org/project/pymbolic/
.. image:: https://zenodo.org/badge/2016193.svg
:alt: Zenodo DOI for latest release
:target: https://zenodo.org/badge/latestdoi/2016193
Pymbolic is a small expression tree and symbolic manipulation library. Two
things set it apart from other libraries of its kind:
......@@ -11,17 +24,17 @@ things set it apart from other libraries of its kind:
Pymbolic currently understands regular arithmetic expressions, derivatives,
sparse polynomials, fractions, term substitution, expansion. It automatically
performs constant folding, and it can compile its expressions into Python
performs constant folding, and it can compile its expressions into Python
bytecode for fast(er) execution.
If you are looking for a full-blown Computer Algebra System, look at
`sympy <http://pypi.python.org/pypi/sympy>`_ or
`PyGinac <http://pyginac.sourceforge.net/>`_. If you are looking for a
If you are looking for a full-blown Computer Algebra System, look at
`sympy <https://pypi.org/project/sympy/>`__ or
`PyGinac <https://pyginac.sourceforge.net/>`__. If you are looking for a
basic, small and extensible set of symbolic operations, pymbolic may
well be for you.
Resources:
* `documentation <http://documen.tician.de/pymbolic>`_
* `download <http://pypi.python.org/pypi/pymbolic>`_ (via the package index)
* `source code via git <http://github.com/inducer/pymbolic>`_ (also bug tracker)
* `PyPI package <https://pypi.org/project/pymbolic/>`__
* `Documentation <https://documen.tician.de/pymbolic/>`__
* `Source code (GitHub) <https://github.com/inducer/pymbolic>`__
#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import shutil
import sys
import time
import fnmatch
import tempfile
import tarfile
import optparse
from distutils import log
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
try:
import subprocess
def _python_cmd(*args):
args = (sys.executable,) + args
return subprocess.call(args) == 0
except ImportError:
# will be used for python 2.3
def _python_cmd(*args):
args = (sys.executable,) + args
# quoting arguments if windows
if sys.platform == 'win32':
def quote(arg):
if ' ' in arg:
return '"%s"' % arg
return arg
args = [quote(arg) for arg in args]
return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
DEFAULT_VERSION = "0.6.35"
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
SETUPTOOLS_FAKED_VERSION = "0.6c11"
SETUPTOOLS_PKG_INFO = """\
Metadata-Version: 1.0
Name: setuptools
Version: %s
Summary: xxxx
Home-page: xxx
Author: xxx
Author-email: xxx
License: xxx
Description: xxx
""" % SETUPTOOLS_FAKED_VERSION
def _install(tarball, install_args=()):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# installing
log.warn('Installing Distribute')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
def _build_egg(egg, tarball, to_dir):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# building an egg
log.warn('Building a Distribute egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
tarball = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, tarball, to_dir)
sys.path.insert(0, egg)
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15, no_fake=True):
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
was_imported = 'pkg_resources' in sys.modules or \
'setuptools' in sys.modules
try:
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
if not no_fake:
_fake_setuptools()
raise ImportError
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("distribute>=" + version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return _do_download(version, download_base, to_dir,
download_delay)
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir,
download_delay)
finally:
if not no_fake:
_create_fake_setuptools_pkg_info(to_dir)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
def _no_sandbox(function):
def __no_sandbox(*args, **kw):
try:
from setuptools.sandbox import DirectorySandbox
if not hasattr(DirectorySandbox, '_old'):
def violation(*args):
pass
DirectorySandbox._old = DirectorySandbox._violation
DirectorySandbox._violation = violation
patched = True
else:
patched = False
except ImportError:
patched = False
try:
return function(*args, **kw)
finally:
if patched:
DirectorySandbox._violation = DirectorySandbox._old
del DirectorySandbox._old
return __no_sandbox
def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True
_patch_file = _no_sandbox(_patch_file)
def _same_content(path, content):
f = open(path)
existing_content = f.read()
f.close()
return existing_content == content
def _rename_path(path):
new_name = path + '.OLD.%s' % time.time()
log.warn('Renaming %s to %s', path, new_name)
os.rename(path, new_name)
return new_name
def _remove_flat_installation(placeholder):
if not os.path.isdir(placeholder):
log.warn('Unkown installation at %s', placeholder)
return False
found = False
for file in os.listdir(placeholder):
if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
found = True
break
if not found:
log.warn('Could not locate setuptools*.egg-info')
return
log.warn('Moving elements out of the way...')
pkg_info = os.path.join(placeholder, file)
if os.path.isdir(pkg_info):
patched = _patch_egg_dir(pkg_info)
else:
patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
if not patched:
log.warn('%s already patched.', pkg_info)
return False
# now let's move the files out of the way
for element in ('setuptools', 'pkg_resources.py', 'site.py'):
element = os.path.join(placeholder, element)
if os.path.exists(element):
_rename_path(element)
else:
log.warn('Could not find the %s element of the '
'Setuptools distribution', element)
return True
_remove_flat_installation = _no_sandbox(_remove_flat_installation)
def _after_install(dist):
log.warn('After install bootstrap.')
placeholder = dist.get_command_obj('install').install_purelib
_create_fake_setuptools_pkg_info(placeholder)
def _create_fake_setuptools_pkg_info(placeholder):
if not placeholder or not os.path.exists(placeholder):
log.warn('Could not find the install location')
return
pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
setuptools_file = 'setuptools-%s-py%s.egg-info' % \
(SETUPTOOLS_FAKED_VERSION, pyver)
pkg_info = os.path.join(placeholder, setuptools_file)
if os.path.exists(pkg_info):
log.warn('%s already exists', pkg_info)
return
log.warn('Creating %s', pkg_info)
try:
f = open(pkg_info, 'w')
except EnvironmentError:
log.warn("Don't have permissions to write %s, skipping", pkg_info)
return
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
pth_file = os.path.join(placeholder, 'setuptools.pth')
log.warn('Creating %s', pth_file)
f = open(pth_file, 'w')
try:
f.write(os.path.join(os.curdir, setuptools_file))
finally:
f.close()
_create_fake_setuptools_pkg_info = _no_sandbox(
_create_fake_setuptools_pkg_info
)
def _patch_egg_dir(path):
# let's check if it's already patched
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
if os.path.exists(pkg_info):
if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
log.warn('%s already patched.', pkg_info)
return False
_rename_path(path)
os.mkdir(path)
os.mkdir(os.path.join(path, 'EGG-INFO'))
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
return True
_patch_egg_dir = _no_sandbox(_patch_egg_dir)
def _before_install():
log.warn('Before install bootstrap.')
_fake_setuptools()
def _under_prefix(location):
if 'install' not in sys.argv:
return True
args = sys.argv[sys.argv.index('install') + 1:]
for index, arg in enumerate(args):
for option in ('--root', '--prefix'):
if arg.startswith('%s=' % option):
top_dir = arg.split('root=')[-1]
return location.startswith(top_dir)
elif arg == option:
if len(args) > index:
top_dir = args[index + 1]
return location.startswith(top_dir)
if arg == '--user' and USER_SITE is not None:
return location.startswith(USER_SITE)
return True
def _fake_setuptools():
log.warn('Scanning installed packages')
try:
import pkg_resources
except ImportError:
# we're cool
log.warn('Setuptools or Distribute does not seem to be installed.')
return
ws = pkg_resources.working_set
try:
setuptools_dist = ws.find(
pkg_resources.Requirement.parse('setuptools', replacement=False)
)
except TypeError:
# old distribute API
setuptools_dist = ws.find(
pkg_resources.Requirement.parse('setuptools')
)
if setuptools_dist is None:
log.warn('No setuptools distribution found')
return
# detecting if it was already faked
setuptools_location = setuptools_dist.location
log.warn('Setuptools installation detected at %s', setuptools_location)
# if --root or --preix was provided, and if
# setuptools is not located in them, we don't patch it
if not _under_prefix(setuptools_location):
log.warn('Not patching, --root or --prefix is installing Distribute'
' in another location')
return
# let's see if its an egg
if not setuptools_location.endswith('.egg'):
log.warn('Non-egg installation')
res = _remove_flat_installation(setuptools_location)
if not res:
return
else:
log.warn('Egg installation')
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
if (os.path.exists(pkg_info) and
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
log.warn('Already patched.')
return
log.warn('Patching...')
# let's create a fake egg replacing setuptools one
res = _patch_egg_dir(setuptools_location)
if not res:
return
log.warn('Patching complete.')
_relaunch()
def _relaunch():
log.warn('Relaunching...')
# we have to relaunch the process
# pip marker to avoid a relaunch bug
_cmd1 = ['-c', 'install', '--single-version-externally-managed']
_cmd2 = ['-c', 'install', '--record']
if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2:
sys.argv[0] = 'setup.py'
args = [sys.executable] + sys.argv
sys.exit(subprocess.call(args))
def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
import copy
import operator
from tarfile import ExtractError
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)
# Reverse sort directories.
if sys.version_info < (2, 4):
def sorter(dir1, dir2):
return cmp(dir1.name, dir2.name)
directories.sort(sorter)
directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the distribute package
"""
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn("--user requires Python 2.6 or later")
raise SystemExit(1)
install_args.append('--user')
return install_args
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the distribute package')
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main(version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
tarball = download_setuptools(download_base=options.download_base)
return _install(tarball, _build_install_args(options))
if __name__ == '__main__':
sys.exit(main())
......@@ -3,7 +3,7 @@
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXBUILD = python `which sphinx-build`
PAPER =
BUILDDIR = _build
......
pre {
line-height: 100%;
}
.footer {
background-color: #eee;
}
body > div.container {
margin-top:10px;
}
dd {
margin-left: 40px;
}
tt.descname {
font-size: 100%;
}
code {
color: rgb(51,51,51);
}
h1 {
padding-bottom:5px;
border-bottom: 1px solid #ccc;
}
h2 {
padding-bottom:1px;
border-bottom: 1px solid #ccc;
}
h3 {
padding-bottom:1px;
border-bottom: 1px solid #ccc;
}
.rubric {
font-size: 120%;
padding-bottom:1px;
border-bottom: 1px solid #ccc;
}
.headerlink {
padding-left: 1ex;
padding-right: 1ex;
}
a.headerlink:hover {
text-decoration: none;
}
blockquote p {
font-size: 100%;
font-weight: normal;
line-height: normal;
};
{% extends "!layout.html" %}
{% set css_files = css_files + ['_static/akdoc.css']%}
......@@ -2,12 +2,3 @@ Algorithms
==========
.. automodule:: pymbolic.algorithm
.. autofunction:: integer_power
.. autofunction:: extended_euclidean
.. autofunction:: gcd
.. autofunction:: lcm
.. autofunction:: fft
.. autofunction:: ifft
.. autofunction:: sym_fft
# -*- coding: utf-8 -*-
#
# pymbolic documentation build configuration file, created by
# sphinx-quickstart on Fri May 24 11:29:00 2013.
#
# 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.
from importlib import metadata
from urllib.request import urlopen
#import sys, os
# 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.
#sys.path.insert(0, os.path.abspath('.'))
_conf_url = \
"https://raw.githubusercontent.com/inducer/sphinxconfig/main/sphinxconfig.py"
with urlopen(_conf_url) as _inf:
exec(compile(_inf.read(), _conf_url, "exec"), globals())
# -- 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 = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pymbolic'
copyright = u'2013, Andreas Kloeckner'
# 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.
ver_dic = {}
execfile("../pymbolic/version.py", ver_dic)
version = ".".join(str(x) for x in ver_dic["VERSION"])
# The full version, including alpha/beta/rc tags.
release = ver_dic["VERSION_TEXT"]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
copyright = "2013-24, Andreas Kloeckner"
release = metadata.version("pymbolic")
version = ".".join(release.split(".")[:2])
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
try:
import sphinx_bootstrap_theme
except:
from warnings import warn
warn("I would like to use the sphinx bootstrap theme, but can't find it.\n"
"'pip install sphinx_bootstrap_theme' to fix.")
else:
# Activate the theme.
html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
# 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 = {
"navbar_fixed_top": "true",
"navbar_class": "navbar navbar-inverse",
"navbar_site_name": "Contents",
}
# 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 themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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']
# 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'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
exclude_patterns = ["_build"]
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pymbolicdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
intersphinx_mapping = {
"galgebra": ("https://galgebra.readthedocs.io/en/latest/", None),
"mako": ("https://docs.makotemplates.org/en/latest/", None),
"matchpy": ("https://matchpy.readthedocs.io/en/latest/", None),
"numpy": ("https://numpy.org/doc/stable/", None),
"python": ("https://docs.python.org/3", None),
"sympy": ("https://docs.sympy.org/dev/", None),
"typing_extensions":
("https://typing-extensions.readthedocs.io/en/latest/", None),
"constantdict":
("https://matthiasdiener.github.io/constantdict/", None)
}
autodoc_type_aliases = {
"Expression": "Expression",
"ArithmeticExpression": "ArithmeticExpression",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pymbolic.tex', u'pymbolic Documentation',
u'Andreas Kloeckner', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pymbolic', u'pymbolic Documentation',
[u'Andreas Kloeckner'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
import sys
# -- Options for Texinfo output ------------------------------------------------
nitpick_ignore_regex = [
# Avoids this error in pymbolic.typing.
# <unknown>:1: WARNING: py:class reference target not found: ExpressionNode [ref.class] # noqa: E501
# Understandable, because typing can't import primitives, which would be needed
# to resolve the reference.
["py:class", r"ExpressionNode"],
["py:class", r"_Expression"],
["py:class", r"p\.AlgebraicLeaf"],
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pymbolic', u'pymbolic Documentation',
u'Andreas Kloeckner', 'pymbolic', 'One line description of project.',
'Miscellaneous'),
# Sphinx started complaining about these in 8.2.1(-ish)
# -AK, 2025-02-24
["py:class", r"TypeAliasForwardRef"],
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'http://docs.python.org/dev': None,
'http://docs.scipy.org/doc/numpy/': None,
'http://docs.makotemplates.org/en/latest/': None,
'http://docs.sympy.org/dev/': None,
}
autoclass_content = "both"
sys._BUILDING_SPHINX_DOCS = True
......@@ -3,123 +3,4 @@ Geometric Algebra
.. automodule:: pymbolic.geometric_algebra
Also see :ref:`ga-examples`.
Spaces
------
.. autoclass:: Space
.. autoattribute:: dimensions
.. autoattribute:: is_orthogonal
.. autoattribute:: is_euclidean
.. autofunction:: get_euclidean_space
Multivectors
------------
.. autoclass:: MultiVector
.. autoattribute:: mapper_method
.. rubric:: More products
.. automethod:: scalar_product
.. automethod:: x
.. automethod:: __pow__
.. rubric:: Unary operators
.. automethod:: inv
.. automethod:: rev
.. automethod:: invol
.. automethod:: dual
.. automethod:: norm_squared
.. automethod:: __abs__
.. autoattribute:: I
.. rubric:: Comparisons
:class:`MultiVector` objects have a truth value corresponding to whether
they have any blades with non-zero coefficients. They support testing
for (exact) equality.
.. automethod:: zap_near_zeros
.. automethod:: close_to
.. rubric:: Grade manipulation
.. automethod:: gen_blades
.. automethod:: project
.. automethod:: all_grades
.. automethod:: get_pure_grade
.. automethod:: odd
.. automethod:: even
.. automethod:: as_scalar
.. automethod:: as_vector
.. rubric:: Helper functions
.. automethod:: map
.. _ga-examples:
Example usage
-------------
This first example demonstrates how to compute a cross product using
:class:`MultiVector`:
.. doctest::
>>> import numpy as np
>>> import pymbolic.geometric_algebra as ga
>>> MV = ga.MultiVector
>>> a = np.array([3.344, 1.2, -0.5])
>>> b = np.array([7.4, 1.1, -2.0])
>>> np.cross(a, b)
array([-1.85 , 2.988 , -5.2016])
>>> mv_a = MV(a)
>>> mv_b = MV(b)
>>> print -mv_a.I*(mv_a^mv_b)
-1.85*e0 + 2.988*e1 + -5.2016*e2
This simple example demonstrates how a complex number is simply a special
case of a :class:`MultiVector`:
.. doctest::
>>> import numpy as np
>>> import pymbolic.geometric_algebra as ga
>>> MV = ga.MultiVector
>>>
>>> sp = ga.Space(metric_matrix=-np.eye(1))
>>> sp
Space(['e0'], array([[-1.]]))
>>> one = MV(1, sp)
>>> one
MultiVector({0: 1}, Space(['e0'], array([[-1.]])))
>>> print one
1
>>> print one.I
1*e0
>>> print one.I ** 2
-1.0
>>> print (3+5j)*(2+3j)/(3j)
(6.33333333333+3j)
>>> print (3+5*one.I)*(2+3*one.I)/(3*one.I)
6.33333333333 + 3.0*e0
The following test demonstrates the use of the object and shows many useful
properties:
.. literalinclude:: ../test/test_pymbolic.py
:start-after: START_GA_TEST
:end-before: END_GA_TEST
.. vim: sw=4
Welcome to pymbolic!
====================
Pymbolic is a simple and extensible package for precise manipulation of
symbolic expressions in Python. It doesn't try to compete with :mod:`sympy` as
a computer algebra system. Pymbolic emphasizes providing an extensible
expression tree and a flexible, extensible way to manipulate it.
A taste of :mod:`pymbolic`
--------------------------
Follow along on a simple example. Let's import :mod:`pymbolic` and create a
symbol, *x* in this case.
.. doctest::
>>> import pymbolic as pmbl
>>> x = pmbl.var("x")
>>> x
Variable('x')
Next, let's create an expression using *x*:
.. doctest::
>>> u = (x+1)**5
>>> u
Power(Sum((Variable('x'), 1)), 5)
>>> print(u)
(x + 1)**5
Note the two ways an expression can be printed, namely :func:`repr` and
:class:`str`. :mod:`pymbolic` purposefully distinguishes the two.
:mod:`pymbolic` does not perform any manipulations on expressions
you put in. It has a few of those built in, but that's not really the point:
.. doctest::
>>> print(pmbl.differentiate(u, 'x'))
5*(x + 1)**4
.. _custom-manipulation:
Manipulating expressions
^^^^^^^^^^^^^^^^^^^^^^^^
The point is for you to be able to easily write so-called *mappers* to
manipulate expressions. Suppose we would like all sums replaced by
products:
.. doctest::
>>> from pymbolic.mapper import IdentityMapper
>>> class MyMapper(IdentityMapper):
... def map_sum(self, expr):
... return pmbl.primitives.Product(expr.children)
...
>>> print(u)
(x + 1)**5
>>> print(MyMapper()(u))
(x*1)**5
Custom Objects
^^^^^^^^^^^^^^
You can also easily define your own objects to use inside an expression:
.. doctest::
>>> from pymbolic import ExpressionNode, expr_dataclass
>>> from pymbolic.typing import Expression
>>>
>>> @expr_dataclass()
... class FancyOperator(ExpressionNode):
... operand: Expression
...
>>> u
Power(Sum((Variable('x'), 1)), 5)
>>> 17*FancyOperator(u)
Product((17, FancyOperator(Power(Sum((..., 1)), 5))))
As a final example, we can now derive from *MyMapper* to multiply all
*FancyOperator* instances by 2.
.. doctest::
>>> FancyOperator.mapper_method
'map_fancy_operator'
>>> class MyMapper2(MyMapper):
... def map_fancy_operator(self, expr):
... return 2*FancyOperator(self.rec(expr.operand))
...
>>> MyMapper2()(FancyOperator(u))
Product((2, FancyOperator(Power(Product((..., 1)), 5))))
.. automodule:: pymbolic
Pymbolic around the web
-----------------------
* `download <http://pypi.python.org/pypi/pymbolic>`_ (via the package index)
* `documentation <http://documen.tician.de/pymbolic>`_
* `source code via git <http://github.com/inducer/pymbolic>`_ (also bug tracker)
* `PyPI package <https://pypi.org/project/pymbolic/>`__
* `Documentation <https://documen.tician.de/pymbolic/>`__
* `Source code (GitHub) <https://github.com/inducer/pymbolic>`__
Contents
--------
......@@ -22,6 +116,8 @@ Contents
algorithms
geometric-algebra
misc
🚀 Github <https://github.com/inducer/pymbolic>
💾 Download Releases <https://pypi.org/project/pymbolic>
* :ref:`genindex`
* :ref:`modindex`
......