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 (663)
# 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
......@@ -11,3 +11,5 @@ setuptools*egg
setuptools*tar.gz
setuptools.pth
_build
.cache
Python 2.7:
script:
- py_version=2.7
- EXTRA_INSTALL="numpy sympy pexpect"
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project.sh
- ". ./build-and-test-py-project.sh"
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:
- python2.7
- python3
- maxima
except:
- tags
Python 3.4:
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:
- py_version=3.4
- EXTRA_INSTALL="numpy sympy"
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project.sh
- ". ./build-and-test-py-project.sh"
- 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.4
- python3
except:
- tags
Python 2.6:
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:
- py_version=2.6
- EXTRA_INSTALL="numpy sympy"
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project.sh
- ". ./build-and-test-py-project.sh"
- curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/build-docs.sh
- ". ./build-docs.sh"
tags:
- python2.6
- 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 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,20 +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.
.. image:: https://badge.fury.io/py/pymbolic.png
:target: http://pypi.python.org/pypi/pymbolic
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>`__
pre {
line-height: 110%;
}
.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:7px;
border-bottom: 1px solid #ccc;
}
h2 {
padding-bottom:5px;
border-bottom: 1px solid #ccc;
}
h3 {
padding-bottom:5px;
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 bootswatch_css_custom = ['_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
from __future__ import absolute_import
# -*- 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 = {}
exec(compile(open("../pymbolic/version.py").read(), "../pymbolic/version.py", 'exec'), 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_site_name": "Contents",
'bootstrap_version': '3',
'source_link_position': 'footer',
}
# 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
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`
......
......@@ -3,7 +3,6 @@ Mappers
.. automodule:: pymbolic.mapper
More specialized mappers
------------------------
......@@ -12,57 +11,43 @@ Converting to strings and code
.. automodule:: pymbolic.mapper.stringifier
Mappers
*******
.. autoclass:: StringifyMapper
.. automethod:: __call__
.. autoclass:: CSESplittingStringifyMapperMixin
.. automodule:: pymbolic.mapper.c_code
.. autoclass:: CCodeMapper
.. automodule:: pymbolic.mapper.graphviz
.. autoclass:: GraphvizMapper
Some minimal mathematics
^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.evaluator
.. autoclass:: EvaluationMapper
.. automodule:: pymbolic.mapper.differentiator
.. autoclass:: DifferentiationMapper
.. automodule:: pymbolic.mapper.distributor
.. autoclass:: DistributeMapper
.. automodule:: pymbolic.mapper.collector
.. autoclass:: TermCollector
.. automodule:: pymbolic.mapper.constant_folder
.. autoclass:: ConstantFoldingMapper
.. autoclass:: CommutativeConstantFoldingMapper
.. automodule:: pymbolic.mapper.substitutor
Finding expression properties
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.dependency
.. autoclass:: DependencyMapper
.. automodule:: pymbolic.mapper.flop_counter
.. autoclass:: FlopCounter
.. autoclass:: CSEAwareFlopCounter
Analysis tools
^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.analysis
Simplification
^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.flattener
.. vim: sw=4
......@@ -5,28 +5,106 @@ This command should install :mod:`pymbolic`::
pip install pymbolic
You may need to run this with :command:`sudo`.
If you don't already have `pip <https://pypi.python.org/pypi/pip>`_,
You may need to run this with :command:`sudo` if you are not in a virtual environment
(not recommended). If you don't already have `pip <https://pypi.org/project/pip>`__,
run this beforehand::
curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
python get-pip.py
python -m ensurepip
For a more manual installation, download the source, unpack it,
and say::
For a more manual installation, download the source, unpack it, and run::
python setup.py install
pip install .
User-visible Changes
This should also install all the required dependencies (see ``pyproject.toml``
for a complete list).
For development, you may want to install in `editable mode
<https://setuptools.pypa.io/en/latest/userguide/development_mode.html>`__::
pip install --no-build-isolation --editable .[test]
Why pymbolic when there's already sympy?
========================================
(This is extracted from an email I (Andreas) sent to Aaron Meurer and Anthony
Scopatz.)
So why not use :mod:`sympy` as an AST for DSLs and code generation? It's a good
question. As you read the points I make below, please bear in mind that I'm not
saying this to 'attack' sympy or to diminish the achievement that it is. Very
much on the contrary--as I said above, sympy does a fantastic job being a
computer algebra. I just don't think it's as much in its element as an IR for
code generation. Personally, I think that's perfectly fine--IMO, the tradeoffs
are different for IRs and efficient computer algebra. In a sense, pymbolic
competes much harder with Python's ast module for being a usable program
representation than with Sympy for being a CAS.
At any rate, to answer your question, here goes:
* First, specifically *because* sympy is smart about its input, and will
rewrite it behind your back. pymbolic is *intended* to be a dumb and
static expression tree, and it will leave its input alone unless you
explicitly tell it not to. In terms of floating point math or around
custom node types that may or may not obey the same rules as scalars,
I feel like 'leave it alone' is a safer default.
* Pickling: https://github.com/sympy/sympy/issues/4297
The very moment code generation starts taking more than a second or
so, you'll want to implement a caching mechanism, likely using Pickle.
* Extensibility of transformation constructs: sympy's built-in traversal
behaviors (e.g. taking derivatives, conversion to string, code
generation) aren't particularly easy to extend. It's important to
understand what I'm talking about here: I would like to be able to
make something that, say, is *like* taking a derivative (or
evaluating, or...), but behaves just a bit differently for a few node
types. This is a need that I've found to be very common in code
generation. In (my understanding of) sympy, these behaviors are
attached to method names, so the only way I could conceivably obtain a
tweaked "diff" would be to temporarily monkeypatch "diff" for my node
type, which is kind of a nonstarter. (unless I'm missing something)
Pymbolic's "mapper" mechanism does somewhat better here--you
simply inherit from the base behavior, implement/override a few
methods, and you're done.
This part is a bit of a red herring though, since this can be
implemented for sympy (and, in fact, `I have
<https://github.com/inducer/pymbolic/blob/main/pymbolic/interop/sympy.py#L47>`__).
Also, I noticed that sympy's codegen module implements something similar (e.g.
`here
<https://github.com/sympy/sympy/blob/master/sympy/printing/fortran.py#L70>`__).
The remaining issue is that most of sympy's behaviors aren't available to
extend in this style.
* Representation of code-like constructs, such as:
* Indexing
* Bit shifts and other bitwise ops:
* Distinguishing floor-div and true-div
* Attribute Access
* I should also mention that pymbolic, aside from maintenance and bug
fixes, is effectively 'finished'. It's pretty tiny, it's not
ambitious, and it's not going to change much going forward. And that
is precisely what I want from a package that provides the core data
structure for something complicated and compiler-ish that I'm building
on top.
User-visible changes
====================
Version 2013.2
Version 2015.3
--------------
.. note::
This version is currently under development. You can get snapshots from
Pymbolic's `git repository <https://github.com/inducer/pymbolic>`_
Pymbolic's `git repository <https://github.com/inducer/pymbolic>`__
* Add :mod:`pymbolic.geometric_algebra`.
* First documented version.
......@@ -61,20 +139,14 @@ 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.
Frequently Asked Questions
==========================
The FAQ is maintained collaboratively on the
`Wiki FAQ page <http://wiki.tiker.net/Pymbolic/FrequentlyAskedQuestions>`_.
Glossary
========
.. glossary::
mix-in
See `Wikipedia article <https://en.wikipedia.org/wiki/Mixin>`_.
See `Wikipedia article <https://en.wikipedia.org/wiki/Mixin>`__.
Be sure to mention the mix-in before the base classe being mixed in the
Be sure to mention the mix-in before the base class being mixed in the
list of base classes. This way, the mix-in can override base class
behavior.
Primitives (Basic Objects)
==========================
.. automodule:: pymbolic.typing
.. automodule:: pymbolic.primitives
.. vim: sw=4