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 (522)
Showing with 733 additions and 536 deletions
# 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
Python 2.7: Python 3:
script: script: |
- py_version=2.7 PY_EXE=python3
- EXTRA_INSTALL="numpy sympy pexpect" # pytest tries to import this, but it doesn't find symengine
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project.sh rm pymbolic/interop/symengine.py
- ". ./build-and-test-py-project.sh" 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: tags:
- python2.7 - python3
- maxima - maxima
except: except:
- tags - tags
artifacts:
reports:
junit: test/pytest.xml
Python 2.7 Conda: Python 3 Conda:
script: script: |
- CONDA_ENVIRONMENT=.test-py2.yml CONDA_ENVIRONMENT=.test-py3.yml
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project-within-miniconda.sh 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" . ./build-and-test-py-project-within-miniconda.sh
tags:
- linux
except:
- tags
Python 3.5:
script:
- py_version=3.5
- 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"
tags:
- python3.5
- maxima
except:
- tags
Python 3.5 Conda:
script:
- CONDA_ENVIRONMENT=.test-py3.yml
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project-within-miniconda.sh
- ". ./build-and-test-py-project-within-miniconda.sh"
tags: tags:
- linux - linux
except: except:
- tags - tags
artifacts:
reports:
junit: test/pytest.xml
Python 3.5 Apple: Pylint:
script: script:
- CONDA_ENVIRONMENT=.test-py3.yml - EXTRA_INSTALL="numpy sympy symengine scipy pexpect"
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project-within-miniconda.sh - PY_EXE=python3
- ". ./build-and-test-py-project-within-miniconda.sh" - 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: tags:
- apple - python3
except: except:
- tags - tags
Python 2.6: Mypy:
script: script: |
- py_version=2.6 curl -L -O https://tiker.net/ci-support-v0
- EXTRA_INSTALL="numpy" . ./ci-support-v0
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-and-test-py-project.sh build_py_project_in_venv
- ". ./build-and-test-py-project.sh" pip install -e .[test]
python -m pip install mypy numpy
./run-mypy.sh
tags: tags:
- python2.6 - python3
except: except:
- tags - tags
Documentation: Documentation:
script: script:
- EXTRA_INSTALL="numpy" - EXTRA_INSTALL="numpy sympy"
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/build-docs.sh - curl -L -O https://gitlab.tiker.net/inducer/ci-support/raw/main/build-docs.sh
- ". ./build-docs.sh" - ". ./build-docs.sh"
tags: tags:
- python3.5 - linux
only:
- master
Flake8: Ruff:
script: script: |
- curl -L -O -k https://gitlab.tiker.net/inducer/ci-support/raw/master/prepare-and-run-flake8.sh pipx install ruff
- ". ./prepare-and-run-flake8.sh pymbolic test" ruff check
tags: tags:
- python3.5 - docker-runner
except: except:
- tags - 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: py2
channels:
- symengine
- conda-forge
- defaults
dependencies:
- pexpect
- pytools
- conda-forge::numpy
- conda-forge::sympy
- python=2.7
- symengine::python-symengine=0.3.0
- maxima
name: py3 name: py3
channels: channels:
- symengine
- conda-forge - conda-forge
- defaults - defaults
dependencies: dependencies:
- conda-forge::numpy - conda-forge::numpy
- conda-forge::sympy - conda-forge::sympy
- python=3.5 - python
- symengine::python-symengine=0.3.0 - python-symengine
# - pexpect # - pexpect
# - maxima # - 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 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 Pymbolic is a small expression tree and symbolic manipulation library. Two
things set it apart from other libraries of its kind: things set it apart from other libraries of its kind:
...@@ -11,20 +24,17 @@ 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, Pymbolic currently understands regular arithmetic expressions, derivatives,
sparse polynomials, fractions, term substitution, expansion. It automatically 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. bytecode for fast(er) execution.
If you are looking for a full-blown Computer Algebra System, look at If you are looking for a full-blown Computer Algebra System, look at
`sympy <http://pypi.python.org/pypi/sympy>`_ or `sympy <https://pypi.org/project/sympy/>`__ or
`PyGinac <http://pyginac.sourceforge.net/>`_. If you are looking for a `PyGinac <https://pyginac.sourceforge.net/>`__. If you are looking for a
basic, small and extensible set of symbolic operations, pymbolic may basic, small and extensible set of symbolic operations, pymbolic may
well be for you. well be for you.
.. image:: https://badge.fury.io/py/pymbolic.png
:target: http://pypi.python.org/pypi/pymbolic
Resources: Resources:
* `documentation <http://documen.tician.de/pymbolic>`_ * `PyPI package <https://pypi.org/project/pymbolic/>`__
* `download <http://pypi.python.org/pypi/pymbolic>`_ (via the package index) * `Documentation <https://documen.tician.de/pymbolic/>`__
* `source code via git <http://github.com/inducer/pymbolic>`_ (also bug tracker) * `Source code (GitHub) <https://github.com/inducer/pymbolic>`__
...@@ -2,12 +2,3 @@ Algorithms ...@@ -2,12 +2,3 @@ Algorithms
========== ==========
.. automodule:: pymbolic.algorithm .. 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 from importlib import metadata
# -*- coding: utf-8 -*- from urllib.request import urlopen
#
# 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.
#import sys, os
# If extensions (or modules to document with autodoc) are in another directory, _conf_url = \
# add these directories to sys.path here. If the directory is relative to the "https://raw.githubusercontent.com/inducer/sphinxconfig/main/sphinxconfig.py"
# documentation root, use os.path.abspath to make it absolute, like shown here. with urlopen(_conf_url) as _inf:
#sys.path.insert(0, os.path.abspath('.')) exec(compile(_inf.read(), _conf_url, "exec"), globals())
# -- General configuration ----------------------------------------------------- copyright = "2013-24, Andreas Kloeckner"
release = metadata.version("pymbolic")
# If your documentation needs a minimal Sphinx version, state it here. version = ".".join(release.split(".")[:2])
#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'
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
exclude_patterns = ['_build'] 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 = []
intersphinx_mapping = {
# -- Options for HTML output --------------------------------------------------- "galgebra": ("https://galgebra.readthedocs.io/en/latest/", None),
"mako": ("https://docs.makotemplates.org/en/latest/", None),
html_theme = "alabaster" "matchpy": ("https://matchpy.readthedocs.io/en/latest/", None),
"numpy": ("https://numpy.org/doc/stable/", None),
html_theme_options = { "python": ("https://docs.python.org/3", None),
"extra_nav_links": { "sympy": ("https://docs.sympy.org/dev/", None),
"🚀 Github": "https://github.com/inducer/pymbolic", "typing_extensions":
"💾 Download Releases": "https://pypi.python.org/pypi/pymbolic", ("https://typing-extensions.readthedocs.io/en/latest/", None),
} "constantdict":
} ("https://matthiasdiener.github.io/constantdict/", None)
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
]
} }
autodoc_type_aliases = {
# Theme options are theme-specific and customize the look and feel of a theme "Expression": "Expression",
# further. For a list of options available for each theme, see the "ArithmeticExpression": "ArithmeticExpression",
# 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 = {}
# 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': '',
} }
# 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 import sys
# 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. nitpick_ignore_regex = [
#latex_show_pagerefs = False # 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"],
# If true, show URL addresses after external links. # Sphinx started complaining about these in 8.2.1(-ish)
#latex_show_urls = False # -AK, 2025-02-24
["py:class", r"TypeAliasForwardRef"],
# 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
# -- 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 = [
('index', 'pymbolic', u'pymbolic Documentation',
u'Andreas Kloeckner', 'pymbolic', 'One line description of project.',
'Miscellaneous'),
]
# 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! 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 .. automodule:: pymbolic
Pymbolic around the web Pymbolic around the web
----------------------- -----------------------
* `download <http://pypi.python.org/pypi/pymbolic>`_ (via the package index) * `PyPI package <https://pypi.org/project/pymbolic/>`__
* `documentation <http://documen.tician.de/pymbolic>`_ * `Documentation <https://documen.tician.de/pymbolic/>`__
* `source code via git <http://github.com/inducer/pymbolic>`_ (also bug tracker) * `Source code (GitHub) <https://github.com/inducer/pymbolic>`__
Contents Contents
-------- --------
...@@ -22,6 +116,8 @@ Contents ...@@ -22,6 +116,8 @@ Contents
algorithms algorithms
geometric-algebra geometric-algebra
misc misc
🚀 Github <https://github.com/inducer/pymbolic>
💾 Download Releases <https://pypi.org/project/pymbolic>
* :ref:`genindex` * :ref:`genindex`
* :ref:`modindex` * :ref:`modindex`
......
...@@ -3,7 +3,6 @@ Mappers ...@@ -3,7 +3,6 @@ Mappers
.. automodule:: pymbolic.mapper .. automodule:: pymbolic.mapper
More specialized mappers More specialized mappers
------------------------ ------------------------
...@@ -12,57 +11,43 @@ Converting to strings and code ...@@ -12,57 +11,43 @@ Converting to strings and code
.. automodule:: pymbolic.mapper.stringifier .. automodule:: pymbolic.mapper.stringifier
Mappers
*******
.. autoclass:: StringifyMapper
.. automethod:: __call__
.. autoclass:: CSESplittingStringifyMapperMixin
.. automodule:: pymbolic.mapper.c_code .. automodule:: pymbolic.mapper.c_code
.. autoclass:: CCodeMapper
.. automodule:: pymbolic.mapper.graphviz .. automodule:: pymbolic.mapper.graphviz
.. autoclass:: GraphvizMapper
Some minimal mathematics Some minimal mathematics
^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.evaluator .. automodule:: pymbolic.mapper.evaluator
.. autoclass:: EvaluationMapper
.. automodule:: pymbolic.mapper.differentiator .. automodule:: pymbolic.mapper.differentiator
.. autoclass:: DifferentiationMapper
.. automodule:: pymbolic.mapper.distributor .. automodule:: pymbolic.mapper.distributor
.. autoclass:: DistributeMapper
.. automodule:: pymbolic.mapper.collector .. automodule:: pymbolic.mapper.collector
.. autoclass:: TermCollector
.. automodule:: pymbolic.mapper.constant_folder .. automodule:: pymbolic.mapper.constant_folder
.. automodule:: pymbolic.mapper.substitutor
.. autoclass:: ConstantFoldingMapper
.. autoclass:: CommutativeConstantFoldingMapper
Finding expression properties Finding expression properties
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.dependency .. automodule:: pymbolic.mapper.dependency
.. autoclass:: DependencyMapper
.. automodule:: pymbolic.mapper.flop_counter .. automodule:: pymbolic.mapper.flop_counter
.. autoclass:: FlopCounter .. autoclass:: FlopCounter
.. autoclass:: CSEAwareFlopCounter
Analysis tools
^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.analysis
Simplification
^^^^^^^^^^^^^^
.. automodule:: pymbolic.mapper.flattener
.. vim: sw=4 .. vim: sw=4
...@@ -5,17 +5,23 @@ This command should install :mod:`pymbolic`:: ...@@ -5,17 +5,23 @@ This command should install :mod:`pymbolic`::
pip install pymbolic pip install pymbolic
You may need to run this with :command:`sudo`. You may need to run this with :command:`sudo` if you are not in a virtual environment
If you don't already have `pip <https://pypi.python.org/pypi/pip>`_, (not recommended). If you don't already have `pip <https://pypi.org/project/pip>`__,
run this beforehand:: run this beforehand::
curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py python -m ensurepip
python get-pip.py
For a more manual installation, download the source, unpack it, For a more manual installation, download the source, unpack it, and run::
and say::
python setup.py install pip install .
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? Why pymbolic when there's already sympy?
======================================== ========================================
...@@ -65,10 +71,10 @@ At any rate, to answer your question, here goes: ...@@ -65,10 +71,10 @@ At any rate, to answer your question, here goes:
This part is a bit of a red herring though, since this can be This part is a bit of a red herring though, since this can be
implemented for sympy (and, in fact, `I have implemented for sympy (and, in fact, `I have
<https://github.com/inducer/pymbolic/blob/master/pymbolic/sympy_interface.py#L71>`_). <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. Also, I noticed that sympy's codegen module implements something similar (e.g.
`here `here
<https://github.com/sympy/sympy/blob/master/sympy/printing/fcode.py#L174>`_). <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 The remaining issue is that most of sympy's behaviors aren't available to
extend in this style. extend in this style.
...@@ -98,7 +104,7 @@ Version 2015.3 ...@@ -98,7 +104,7 @@ Version 2015.3
.. note:: .. note::
This version is currently under development. You can get snapshots from 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`. * Add :mod:`pymbolic.geometric_algebra`.
* First documented version. * First documented version.
...@@ -133,20 +139,14 @@ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ...@@ -133,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 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. 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
======== ========
.. glossary:: .. glossary::
mix-in 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 list of base classes. This way, the mix-in can override base class
behavior. behavior.
Primitives (Basic Objects) Primitives (Basic Objects)
========================== ==========================
.. automodule:: pymbolic.typing
.. automodule:: pymbolic.primitives .. automodule:: pymbolic.primitives
.. vim: sw=4 .. vim: sw=4
#! /bin/sh #! /bin/sh
rsync --verbose --archive --delete _build/html/* doc-upload:doc/pymbolic rsync --verbose --archive --delete _build/html/ doc-upload:doc/pymbolic
...@@ -8,7 +8,8 @@ Parser ...@@ -8,7 +8,8 @@ Parser
.. function:: parse(expr_str) .. function:: parse(expr_str)
Return a :class:`pymbolic.primitives.Expression` tree corresponding to *expr_str*. Return a :class:`pymbolic.primitives.ExpressionNode` tree corresponding
to *expr_str*.
The parser is also relatively easy to extend. See the source code of the following The parser is also relatively easy to extend. See the source code of the following
class. class.
...@@ -43,3 +44,14 @@ Interoperability with Python's :mod:`ast` module ...@@ -43,3 +44,14 @@ Interoperability with Python's :mod:`ast` module
------------------------------------------------ ------------------------------------------------
.. automodule:: pymbolic.interop.ast .. automodule:: pymbolic.interop.ast
Interoperability with :mod:`matchpy.functions` module
-----------------------------------------------------
.. automodule:: pymbolic.interop.matchpy
Visualizing Expressions
=======================
.. autofunction:: pymbolic.imperative.utils.get_dot_dependency_graph
# See https://github.com/inducer/pymbolic/pull/110 for context
import sys
from pymbolic import parse
from pymbolic.mapper import CachedIdentityMapper
from pymbolic.mapper.optimize import optimize_mapper
from pymbolic.primitives import Variable
code = ("(-1)*((cse_577[_pt_data_48[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
"_pt_data_49[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_48[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_577[_pt_data_46[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_47[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_46[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_577[_pt_data_7[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_43[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_7[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_577[_pt_data_44[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_45[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_44[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_579[_pt_data_68[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_69[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_68[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_579[_pt_data_66[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_67[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_66[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_579[_pt_data_50[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_63[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_50[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_579[_pt_data_64[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_65[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_64[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_581[_pt_data_88[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_89[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_88[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_581[_pt_data_86[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_87[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_86[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_581[_pt_data_70[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_83[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_70[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_581[_pt_data_84[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_85[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_84[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_582[_pt_data_107[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_108[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_107[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_582[_pt_data_105[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0],"
" _pt_data_106[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_105[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_582[_pt_data_90[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_102[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_90[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_582[_pt_data_103[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_104[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_103[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0))"
" + (cse_572[_pt_data_48[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_49[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_48[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0) "
"+ (cse_572[_pt_data_46[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_47[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_46[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0) "
"+ (cse_572[_pt_data_7[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_43[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_7[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_572[_pt_data_44[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_45[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_44[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_573[_pt_data_68[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_69[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_68[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_573[_pt_data_66[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_67[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_66[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_573[_pt_data_50[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_63[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_50[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_573[_pt_data_64[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_65[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_64[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_574[_pt_data_88[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_89[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_88[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_574[_pt_data_86[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_87[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_86[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0) "
"+ (cse_574[_pt_data_70[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_83[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_70[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_574[_pt_data_84[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_85[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_84[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_575[_pt_data_107[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_108[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_107[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_575[_pt_data_105[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_106[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_105[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_575[_pt_data_90[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_102[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_90[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
" + (cse_575[_pt_data_103[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0], _pt_data_104[(iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 10]]"
" if _pt_data_103[((iface_ensm15*1075540 + iel_ensm15*10 + idof_ensm15) % 4302160) // 10, 0] != -1 else 0)"
)
expr = parse(code)
expr = CachedIdentityMapper()(expr) # remove duplicate nodes
replacements = {
"iface_ensm15": Variable("_0"),
"iel_ensm15": Variable("_1"),
"idof_ensm15": Variable("_2"),
}
@optimize_mapper(drop_args=True, drop_kwargs=True,
# inline_cache=True, inline_rec=True,
inline_get_cache_key=True,
print_modified_code_file=sys.stdout)
class Renamer(CachedIdentityMapper):
def map_variable(self, expr):
return replacements.get(expr.name, expr)
def get_cache_key(self, expr):
# Must add 'type(expr)', to differentiate between python scalar types.
# In Python, the following conditions are true: "hash(4) == hash(4.0)"
# and "4 == 4.0", but their traversal results cannot be re-used.
return (type(expr), expr)
def main():
mapper = Renamer()
mapper(expr)
# print(type(new_expr))
if __name__ == "__main__":
from time import time
if 1:
t_start = time()
for _ in range(10_000):
main()
t_end = time()
print(f"Took: {t_end-t_start} secs.")
else:
import pyinstrument
from pyinstrument.renderers import SpeedscopeRenderer
prof = pyinstrument.Profiler()
with prof:
for _ in range(10_000):
main()
with open("ss.json", "w") as outf:
outf.write(prof.output(SpeedscopeRenderer(show_all=True)))
from __future__ import division from __future__ import annotations
from __future__ import absolute_import
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner" __copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
...@@ -24,137 +24,99 @@ THE SOFTWARE. ...@@ -24,137 +24,99 @@ THE SOFTWARE.
""" """
__doc__ = """ from functools import partial
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 from pytools import module_getattr_for_deprecations
a computer algebra system. Pymbolic emphasizes providing an extensible
expression tree and a flexible, extensible way to manipulate it. from . import compiler, parser, primitives
from .compiler import compile
A taste of :mod:`pymbolic` from .mapper import (
-------------------------- dependency,
differentiator,
Follow along on a simple example. Let's import :mod:`pymbolic` and create a distributor,
symbol, *x* in this case. evaluator,
flattener,
.. doctest:: stringifier,
substitutor,
>>> import pymbolic as pmbl )
from .mapper.differentiator import differentiate, differentiate as diff
>>> x = pmbl.var("x") from .mapper.distributor import distribute, distribute as expand
>>> x from .mapper.evaluator import evaluate, evaluate_kw
Variable('x') from .mapper.flattener import flatten
from .mapper.substitutor import substitute
Next, let's create an expression using *x*: from .parser import parse
from .primitives import ( # noqa: N813
.. doctest:: ExpressionNode,
Variable,
>>> u = (x+1)**5 Variable as var,
>>> u disable_subscript_by_getitem,
Power(Sum((Variable('x'), 1)), 5) expr_dataclass,
>>> print u flattened_product,
(x + 1)**5 flattened_sum,
linear_combination,
Note the two ways an expression can be printed, namely :func:`repr` and make_common_subexpression as cse,
:func:`str`. :mod:`pymbolic` purposefully distinguishes the two. make_sym_vector,
quotient,
:mod:`pymbolic` does not perform any manipulations on expressions subscript,
you put in. It has a few of those built in, but that's not really the point: variables,
)
.. doctest:: from .typing import (
ArithmeticExpression,
>>> print pmbl.differentiate(u, 'x') Bool,
5*(x + 1)**4 Expression,
Expression as _TypingExpression,
.. _custom-manipulation: Number,
RealNumber,
Manipulating expressions Scalar,
^^^^^^^^^^^^^^^^^^^^^^^^ )
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.primitives import Expression
>>> class FancyOperator(Expression):
... def __init__(self, operand):
... self.operand = operand
...
... def __getinitargs__(self):
... return (self.operand,)
...
... mapper_method = "map_fancy_operator"
...
>>> u
Power(Sum((Variable('x'), 1)), 5)
>>> 17*FancyOperator(u)
Product((17, FancyOperator(Power(Sum((Variable('x'), 1)), 5))))
As a final example, we can now derive from *MyMapper* to multiply all
*FancyOperator* instances by 2.
.. doctest::
>>> class MyMapper2(MyMapper):
... def map_fancy_operator(self, expr):
... return 2*FancyOperator(self.rec(expr.operand))
...
>>> MyMapper2()(FancyOperator(u))
Product((2, FancyOperator(Power(Product((Variable('x'), 1)), 5))))
"""
from pymbolic.version import VERSION_TEXT as __version__ # noqa from pymbolic.version import VERSION_TEXT as __version__ # noqa
import pymbolic.parser
import pymbolic.compiler
import pymbolic.mapper.evaluator
import pymbolic.mapper.stringifier
import pymbolic.mapper.dependency
import pymbolic.mapper.substitutor
import pymbolic.mapper.differentiator
import pymbolic.mapper.distributor
import pymbolic.mapper.flattener
import pymbolic.primitives
from pymbolic.polynomial import Polynomial # noqa
var = pymbolic.primitives.Variable
variables = pymbolic.primitives.variables
flattened_sum = pymbolic.primitives.flattened_sum
subscript = pymbolic.primitives.subscript
flattened_product = pymbolic.primitives.flattened_product
quotient = pymbolic.primitives.quotient
linear_combination = pymbolic.primitives.linear_combination
cse = pymbolic.primitives.make_common_subexpression
make_sym_vector = pymbolic.primitives.make_sym_vector
disable_subscript_by_getitem = pymbolic.primitives.disable_subscript_by_getitem
parse = pymbolic.parser.parse __all__ = (
evaluate = pymbolic.mapper.evaluator.evaluate "ArithmeticExpression",
evaluate_kw = pymbolic.mapper.evaluator.evaluate_kw "Bool",
compile = pymbolic.compiler.compile "Expression",
substitute = pymbolic.mapper.substitutor.substitute "ExpressionNode",
diff = differentiate = pymbolic.mapper.differentiator.differentiate "Number",
expand = pymbolic.mapper.distributor.distribute "RealNumber",
distribute = pymbolic.mapper.distributor.distribute "Scalar",
flatten = pymbolic.mapper.flattener.flatten "Variable",
"compile",
"compiler",
"cse",
"dependency",
"diff",
"differentiate",
"differentiator",
"disable_subscript_by_getitem",
"distribute",
"distributor",
"evaluate",
"evaluate_kw",
"evaluator",
"expand",
"expr_dataclass",
"flatten",
"flattened_product",
"flattened_sum",
"flattener",
"linear_combination",
"make_sym_vector",
"parse",
"parser",
"primitives",
"quotient",
"stringifier",
"subscript",
"substitute",
"substitutor",
"var",
"variables",
)
__getattr__ = partial(module_getattr_for_deprecations, __name__, {
"ExpressionT": ("pymbolic.typing.Expression", _TypingExpression, 2026),
"ArithmeticExpressionT": ("ArithmeticExpression", ArithmeticExpression, 2026),
"BoolT": ("Bool", Bool, 2026),
"ScalarT": ("Scalar", Scalar, 2026),
})