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
No results found
Show changes
Commits on Source (1050)
Showing
with 1662 additions and 654 deletions
[flake8] [flake8]
max-line-length=120 max-line-length=120
exclude=pystencils/jupyter.py, exclude=src/pystencils/jupyter.py,
pystencils/plot.py src/pystencils/plot.py
pystencils/session.py src/pystencils/session.py
ignore = W293 W503 W291 ignore = W293 W503 W291 C901 E741
src/pystencils/_version.py export-subst
__pycache__ __pycache__
.ipynb_checkpoints .ipynb_checkpoints
.coverage .coverage*
*.pyc *.pyc
*.vti *.vti
/build /build
/dist /dist
/*.egg-info *.egg-info
.cache .cache
_build _build
/html_doc
/.idea /.idea
.vscode
.cache .cache
_local_tmp _local_tmp
\ No newline at end of file RELEASE-VERSION
test-report
src/pystencils/boundaries/createindexlistcython.c
src/pystencils/boundaries/createindexlistcython.*.so
tests/tmp
tests/var
tests/kerncraft_inputs/.2d-5pt.c_kerncraft/
tests/kerncraft_inputs/.3d-7pt.c_kerncraft/
report.xml
coverage_report/
# macOS
**/.DS_Store
*.uuid
stages: stages:
- pretest
- test - test
- nightly
- docs
- deploy - deploy
# -------------------------- Templates ------------------------------------------------------------------------------------
# Base configuration for jobs meant to run at every commit
.every-commit:
rules:
- if: $CI_PIPELINE_SOURCE != "schedule"
# Configuration for jobs meant to run on each commit to pycodegen/pystencils/master
.every-commit-master:
rules:
- if: '$CI_PIPELINE_SOURCE != "schedule" && $CI_PROJECT_PATH == "pycodegen/pystencils" && $CI_COMMIT_BRANCH == "master"'
# Base configuration for jobs meant to run at a schedule
.scheduled:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
# -------------------------- Tests ------------------------------------------------------------------------------------ # -------------------------- Tests ------------------------------------------------------------------------------------
# Normal test - runs on every commit all but "long run" tests # Normal test - runs on every commit all but "long run" tests
tests-and-coverage: tests-and-coverage:
stage: test stage: pretest
except: extends: .every-commit
variables: image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full:cupy12.3
- $ENABLE_NIGHTLY_BUILDS before_script:
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full - pip install -e .
script: script:
- env
- pip list
- export NUM_CORES=$(nproc --all) - export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib - mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc - echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- mkdir public - mkdir public
- py.test -v -n $NUM_CORES --cov-report html --cov-report term --cov=. -m "not longrun" - pytest -v -n $NUM_CORES --cov-report html --cov-report xml --cov-report term --cov=. -m "not longrun" --html test-report/index.html --junitxml=report.xml
- python -m coverage xml
tags: tags:
- docker - docker
- cuda - cuda11
- AVX - AVX
coverage: /Total coverage:\s\d+.\d+\%/
artifacts: artifacts:
when: always when: always
paths: paths:
- coverage_report - coverage_report
- test-report
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
junit: report.xml
# Nightly test - runs "long run" jobs only # Normal test with longruns
test-longrun: tests-and-coverage-with-longrun:
stage: test stage: test
only: when: manual
variables: allow_failure: true
- $ENABLE_NIGHTLY_BUILDS image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full:cupy12.3
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full before_script:
- pip install sympy --upgrade
- pip install -e .
script: script:
- env
- pip list
- export NUM_CORES=$(nproc --all) - export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib - mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc - echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- py.test -v -n $NUM_CORES --cov-report html --cov-report term --cov=. - mkdir public
- py.test -v -n $NUM_CORES
tags:
- docker
- cuda11
- AVX
# pipeline with latest python version
latest-python:
stage: test
extends: .every-commit
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/latest_python
before_script:
- pip install -e .
script:
- env
- pip list
- pip install -e .
- export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- mkdir public
- py.test -v -n $NUM_CORES -m "not longrun" --junitxml=report.xml
tags: tags:
- docker - docker
- cuda
- AVX - AVX
artifacts: artifacts:
paths: when: always
- coverage_report reports:
junit: report.xml
# Minimal tests in windows environment # Minimal tests in windows environment
minimal-windows: #minimal-windows:
# stage: test
# tags:
# - win
# script:
# - export NUM_CORES=$(nproc --all)
# - source /cygdrive/c/Users/build/Miniconda3/Scripts/activate
# - source activate pystencils
# - pip install joblib
# - pip list
# - python -c "import numpy"
# - py.test -v -m "not (notebook or longrun)"
ubuntu:
stage: test stage: test
except: extends: .every-commit
variables: image: i10git.cs.fau.de:5005/pycodegen/pycodegen/ubuntu
- $ENABLE_NIGHTLY_BUILDS before_script:
tags: - ln -s /usr/include/locale.h /usr/include/xlocale.h
- win - pip3 install -e .
script: script:
- source /cygdrive/c/Users/build/Miniconda3/Scripts/activate - export NUM_CORES=$(nproc --all)
- source activate pystencils_dev - mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- sed -i 's/--doctest-modules //g' pytest.ini
- env - env
- conda env list - pip list
- python -c "import numpy" - pytest -v -n $NUM_CORES -m "not longrun" --junitxml=report.xml
- python setup.py quicktest tags:
- docker
- cuda11
- AVX
artifacts:
when: always
reports:
junit: report.xml
minimal-ubuntu: .multiarch_template:
stage: test stage: test
except: extends: .every-commit
variables: allow_failure: true
- $ENABLE_NIGHTLY_BUILDS before_script: &multiarch_before_script
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/minimal_ubuntu # - pip3 install -v .
- export PYTHONPATH=src
- python3 -c "import pystencils as ps; ps.cpu.cpujit.read_config()"
- sed -i '/^fail_under.*/d' pytest.ini
script: script:
- python3 setup.py quicktest - export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- sed -i 's/--doctest-modules //g' pytest.ini
- env
- pip3 list
- python3 -m pytest -v -n $NUM_CORES --cov-report html --cov-report xml --cov=. --junitxml=report.xml tests/test_*vec*.py tests/test_random.py tests/test_half_precision.py
- python3 -m coverage xml
tags: tags:
- docker - docker
- AVX
artifacts:
when: always
paths:
- coverage_report
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
junit: report.xml
arm64v8:
extends: .multiarch_template
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/arm64
variables:
QEMU_CPU: "cortex-a76"
before_script:
- *multiarch_before_script
- sed -i s/march=native/march=armv8-a/g ~/.config/pystencils/config.json
ppc64le:
extends: .multiarch_template
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/ppc64le
before_script:
- *multiarch_before_script
- sed -i s/mcpu=native/mcpu=power8/g ~/.config/pystencils/config.json
arm64v9:
# SVE support is still unreliable in GCC 11 (incorrect code for fixed-width vectors, internal compiler errors).
# For half precision Clang is necessary
extends: .multiarch_template
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/arm64
before_script:
- *multiarch_before_script
- sed -i s/march=native/march=armv9-a+sve2+sme/g ~/.config/pystencils/config.json
- sed -i s/g\+\+/clang++/g ~/.config/pystencils/config.json
riscv64:
# RISC-V vector extension are currently not supported by GCC.
extends: .multiarch_template
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/riscv64
variables:
# explicitly set SIMD as detection requires QEMU >= 8.1
PYSTENCILS_SIMD: "rvv"
QEMU_CPU: "rv64,v=true,zicboz=true"
before_script:
- *multiarch_before_script
- sed -i 's/march=native/march=rv64imfdvzicboz/g' ~/.config/pystencils/config.json
- sed -i s/g\+\+/clang++-15/g ~/.config/pystencils/config.json
minimal-conda: minimal-conda:
stage: pretest
extends: .every-commit
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/minimal_conda
before_script:
- pip install -e .
script:
- python quicktest.py
tags:
- docker
- cuda
minimal-sympy-master:
stage: test stage: test
except: extends: .every-commit
variables:
- $ENABLE_NIGHTLY_BUILDS
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/minimal_conda image: i10git.cs.fau.de:5005/pycodegen/pycodegen/minimal_conda
before_script:
- pip install -e .
script: script:
- python setup.py quicktest - python -m pip install --upgrade git+https://github.com/sympy/sympy.git
- python quicktest.py
allow_failure: true
tags: tags:
- docker - docker
- cuda
pycodegen-integration:
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full
stage: test
when: manual
allow_failure: true
script:
- git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@i10git.cs.fau.de/pycodegen/pycodegen.git
- cd pycodegen
- git submodule sync --recursive
- git submodule update --init --recursive
- git submodule foreach git fetch origin # compare the latest master version!
- git submodule foreach git reset --hard origin/master
- cd pystencils
- git remote add test $CI_REPOSITORY_URL
- git fetch test
- git reset --hard $CI_COMMIT_SHA
- cd ..
- pip install -e pystencils/
- pip install -e lbmpy/
- cmake --version
- ./install_walberla.sh
- export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- cd pystencils
- py.test -v -n $NUM_CORES --junitxml=report.xml .
- cd ../lbmpy
- py.test -v -n $NUM_CORES --junitxml=report.xml .
- cd ../walberla/build/
- make -j $NUM_CORES CodegenJacobiCPU CodegenJacobiGPU CodegenPoissonCPU CodegenPoissonGPU MicroBenchmarkGpuLbm LbCodeGenerationExample
- make -j $NUM_CORES multiphaseCPU multiphaseGPU FluctuatingMRT FlowAroundSphereCodeGen FieldLayoutAndVectorizationTest GeneratedOutflowBC
- cd apps/benchmarks/UniformGridGPU
- make -j $NUM_CORES
- cd ../UniformGridCPU
- make -j $NUM_CORES
tags:
- docker
- cuda11
- AVX
artifacts:
when: always
reports:
junit: pycodegen/*/report.xml
# -------------------- Scheduled Tasks --------------------------------------------------------------------------
# Nightly test against the latest (pre-release) version of SymPy published on PyPI
nightly-sympy:
stage: nightly
needs: []
extends: .scheduled
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/latest_python
before_script:
- pip install -e .
- pip install --upgrade --pre sympy
script:
- env
- pip list
- export NUM_CORES=$(nproc --all)
- mkdir -p ~/.config/matplotlib
- echo "backend:template" > ~/.config/matplotlib/matplotlibrc
- mkdir public
- pytest -v -n $NUM_CORES -m "not longrun" --junitxml=report.xml
tags:
- docker
- AVX
- cuda
artifacts:
when: always
reports:
junit: report.xml
# -------------------- Linter & Documentation -------------------------------------------------------------------------- # -------------------- Linter & Documentation --------------------------------------------------------------------------
flake8-lint: flake8-lint:
stage: test stage: pretest
except: extends: .every-commit
variables:
- $ENABLE_NIGHTLY_BUILDS
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full
script: script:
- flake8 pystencils - flake8 src/pystencils
tags: tags:
- docker - docker
- cuda
build-documentation: build-documentation:
stage: test stage: docs
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full extends: .every-commit
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/documentation
needs: []
before_script:
- pip install -e .
script: script:
- export PYTHONPATH=`pwd`
- mkdir html_doc - mkdir html_doc
- sphinx-build -b html doc html_doc
- sphinx-build -W -b html doc html_doc - sphinx-build -W -b html doc html_doc
tags: tags:
- docker - docker
- cuda
artifacts: artifacts:
paths: paths:
- html_doc - html_doc
...@@ -119,7 +347,9 @@ build-documentation: ...@@ -119,7 +347,9 @@ build-documentation:
pages: pages:
image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full image: i10git.cs.fau.de:5005/pycodegen/pycodegen/full
extends: .every-commit-master
stage: deploy stage: deploy
needs: ["tests-and-coverage", "build-documentation"]
script: script:
- ls -l - ls -l
- mv coverage_report html_doc - mv coverage_report html_doc
...@@ -129,5 +359,3 @@ pages: ...@@ -129,5 +359,3 @@ pages:
- public - public
tags: tags:
- docker - docker
only:
- master@pycodegen/pystencils
[settings]
line_length=100
balanced_wrapping=True
multi_line_output=4
known_third_party=sympy
Contributors:
-------------
- Martin Bauer <martin.bauer@fau.de>
- Markus Holzer <markus.holzer@fau.de>
- Stephan Seitz <stephan.seitz@fau.de>
- Michael Kuron <mkuron@icp.uni-stuttgart.de>
- Jan Hönig <jan.hoenig@fau.de>
- Julian Hammer <julian.hammer@fau.de>
- Nils Kohl <nils.kohl@fau.de>
- Frederik Hennig <frederik.hennig@fau.de>
- Dominik Ernst <dominik.ernst@fau.de>
- Christian Godenschwager <christian.godenschwager@fau.de>
- Dominik Thoennes <dominik.thoennes@fau.de>
# Change Log
## Unreleased
### Removed
* LLVM backend because it was not used much and not good integrated in pystencils.
* OpenCL backend because it was not used much and not good integrated in pystencils.
# Contributing
Contributions to pystencils are always welcome, and they are greatly appreciated!
A list of open problems can be found [here]( https://i10git.cs.fau.de/pycodegen/pystencils/-/issues).
Of course, it is also always appreciated to bring own ideas and problems to the community!
Please submit all contributions to the official [GitLab repository](https://i10git.cs.fau.de/pycodegen/pystencils) in the form of a Merge Request. Please do not submit git diffs or files containing the changes.
There also exists a GitHub repository, which is only a mirror to the GitLab repository. Contributions to the GitHub repository are not considered.
`pystencils` is an open-source python package under the license of AGPL3. Thus we consider the act of contributing to the code by submitting a Merge Request as the "Sign off" or agreement to the AGPL3 license.
You can contribute in many different ways:
## Types of Contributions
### Report Bugs
Report bugs at [https://i10git.cs.fau.de/pycodegen/pystencils/-/issues](https://i10git.cs.fau.de/pycodegen/pystencils/-/issues).
For pystencils, it is often necessary to provide the python and [SymPy](https://www.sympy.org/en/index.html) versions used and hardware information like the
processor architecture and the compiler version used to compile the generated kernels.
### Fix Issues
Look through the GitLab issues. Different tags are indicating the status of the issues.
The "bug" tag indicates problems with pystencils, while the "feature" tag shows ideas that should be added in the future.
### Write Documentation
The documentation of pystencils can be found [here](https://pycodegen.pages.i10git.cs.fau.de/pystencils/). Jupyter notebooks are used to provide an
interactive start to pystencils. It is always appreciated if new document notebooks are provided
since this helps others a lot.
## Get Started!
Ready to contribute? Here is how to set up `pystencils` for local development.
1. Fork the `pystencils` repo on GitLab.
2. Clone your fork locally:
```bash
$ git clone https://i10git.cs.fau.de/your-name/pystencils
```
3. Install your local copy into a virtualenv. It is also recommended to use anaconda or miniconda to manage the python environments.
```bash
$ mkvirtualenv pystencils
$ cd pystencils/
$ pip install -e .
```
4. Create a branch for local development:
```bash
$ git checkout -b name-of-your-bugfix-or-feature
```
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the
tests
```bash
$ flake8 pystencils
$ py.test -v -n $NUM_CORES -m "not longrun" .
```
To get all packages needed for development, a requirements list can be found [here](https://i10git.cs.fau.de/pycodegen/pycodegen/-/blob/master/conda_environment_dev.yml). This includes flake8 and pytest.
6. Commit your changes and push your branch to GitHub::
```bash
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
```
7. Submit a Merge Request on GitLab.
## Merge Request Guidelines
Before you submit a Merge Request, check that it meets these guidelines:
1. All functionality that is implemented through this Merge Request should be covered by unit tests. These are implemented in `pystencil_tests`
2. If the Merge Request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring.
3. If you have a maintainer status for `pystencils`, you can merge Merge Requests to the master branch. However, every Merge Request needs to be reviewed by another developer. Thus it is not allowed to merge a Merge Request, which is submitted by oneself.
## Tips
To run a subset of tests:
```bash
$ py.test my_test.py
```
\ No newline at end of file
include README.md include AUTHORS.txt
include COPYING.txt include CONTRIBUTING.md
include CHANGELOG.md
...@@ -2,15 +2,16 @@ pystencils ...@@ -2,15 +2,16 @@ pystencils
========== ==========
[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/mabau/pystencils/master?filepath=doc%2Fnotebooks) [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/mabau/pystencils/master?filepath=doc%2Fnotebooks)
[![Docs](https://img.shields.io/badge/read-the_docs-brightgreen.svg)](http://pycodegen.pages.walberla.net/pystencils) [![Docs](https://img.shields.io/badge/read-the_docs-brightgreen.svg)](https://pycodegen.pages.i10git.cs.fau.de/pystencils)
[![pypi-package](https://badge.fury.io/py/pystencils.svg)](https://badge.fury.io/py/pystencils)
[![pipeline status](https://i10git.cs.fau.de/pycodegen/pystencils/badges/master/pipeline.svg)](https://i10git.cs.fau.de/pycodegen/pystencils/commits/master) [![pipeline status](https://i10git.cs.fau.de/pycodegen/pystencils/badges/master/pipeline.svg)](https://i10git.cs.fau.de/pycodegen/pystencils/commits/master)
[![coverage report](https://i10git.cs.fau.de/pycodegen/pystencils/badges/master/coverage.svg)](http://pycodegen.pages.walberla.net/pystencils/coverage_report) [![coverage report](https://i10git.cs.fau.de/pycodegen/pystencils/badges/master/coverage.svg)](http://pycodegen.pages.i10git.cs.fau.de/pystencils/coverage_report)
Run blazingly fast stencil codes on numpy arrays. Run blazingly fast stencil codes on numpy arrays.
*pystencils* uses sympy to define stencil operations, that can be executed on numpy arrays. *pystencils* uses sympy to define stencil operations, that can be executed on numpy arrays.
Exploiting the stencil structure makes *pystencils* run faster than normal numpy code and even as Cython and numba, Exploiting the stencil structure makes *pystencils* run faster than normal numpy code and even as Cython and numba,
[as demonstrated in this notebook](http://pycodegen.pages.walberla.net/pystencils/notebooks/demo_benchmark.html). [as demonstrated in this notebook](https://pycodegen.pages.i10git.cs.fau.de/pystencils/notebooks/demo_benchmark.html).
Here is a code snippet that computes the average of neighboring cells: Here is a code snippet that computes the average of neighboring cells:
...@@ -20,7 +21,7 @@ import numpy as np ...@@ -20,7 +21,7 @@ import numpy as np
f, g = ps.fields("f, g : [2D]") f, g = ps.fields("f, g : [2D]")
stencil = ps.Assignment(g[0, 0], stencil = ps.Assignment(g[0, 0],
(f[1, 0] + f[-1, 0] + f[0, 1] + f[0, -1]) / 4) (f[1, 0] + f[-1, 0] + f[0, 1] + f[0, -1]) / 4)
kernel = ps.create_kernel(stencil).compile() kernel = ps.create_kernel(stencil).compile()
f_arr = np.random.rand(1000, 1000) f_arr = np.random.rand(1000, 1000)
...@@ -32,15 +33,15 @@ kernel(f=f_arr, g=g_arr) ...@@ -32,15 +33,15 @@ kernel(f=f_arr, g=g_arr)
It comes with automatic finite difference discretization for PDEs: It comes with automatic finite difference discretization for PDEs:
```python ```python
import pystencils as ps
import sympy as sp
c, v = ps.fields("c, v(2): [2D]") c, v = ps.fields("c, v(2): [2D]")
adv_diff_pde = ps.fd.transient(c) - ps.fd.diffusion(c, sp.symbols("D")) + ps.fd.advection(c, v) adv_diff_pde = ps.fd.transient(c) - ps.fd.diffusion(c, sp.symbols("D")) + ps.fd.advection(c, v)
discretize = ps.fd.Discretization2ndOrder(dx=1, dt=0.01) discretize = ps.fd.Discretization2ndOrder(dx=1, dt=0.01)
discretization = discretize(adv_diff_pde) discretization = discretize(adv_diff_pde)
``` ```
Look at the [documentation](http://pycodegen.pages.walberla.net/pystencils) to learn more.
Installation Installation
------------ ------------
...@@ -51,7 +52,7 @@ pip install pystencils[interactive] ...@@ -51,7 +52,7 @@ pip install pystencils[interactive]
Without `[interactive]` you get a minimal version with very little dependencies. Without `[interactive]` you get a minimal version with very little dependencies.
All options: All options:
- `gpu`: use this if an Nvidia GPU is available and CUDA is installed - `gpu`: use this if an NVIDIA or AMD GPU is available and CUDA or ROCm is installed
- `alltrafos`: pulls in additional dependencies for loop simplification e.g. libisl - `alltrafos`: pulls in additional dependencies for loop simplification e.g. libisl
- `bench_db`: functionality to store benchmark result in object databases - `bench_db`: functionality to store benchmark result in object databases
- `interactive`: installs dependencies to work in Jupyter including image I/O, plotting etc. - `interactive`: installs dependencies to work in Jupyter including image I/O, plotting etc.
...@@ -59,12 +60,28 @@ All options: ...@@ -59,12 +60,28 @@ All options:
Options can be combined e.g. Options can be combined e.g.
```bash ```bash
pip install pystencils[interactive,gpu,doc] pip install pystencils[interactive, gpu, doc]
``` ```
pystencils is also fully compatible with Windows machines. If working with visual studio and cupy makes sure to run example files first to ensure that cupy can find the compiler's executable.
Documentation Documentation
------------- -------------
Read the docs [here](http://pycodegen.pages.walberla.net/pystencils) and Read the docs [here](https://pycodegen.pages.i10git.cs.fau.de/pystencils) and
check out the Jupyter notebooks in `doc/notebooks`. check out the Jupyter notebooks in `doc/notebooks`. The **Changelog** of pystencils can be found [here](https://i10git.cs.fau.de/pycodegen/pystencils/-/blob/master/CHANGELOG.md).
Authors
-------
Many thanks go to the [contributors](https://i10git.cs.fau.de/pycodegen/pystencils/-/blob/master/AUTHORS.txt) of pystencils.
### Please cite us
If you use pystencils in a publication, please cite the following articles:
Overview:
- M. Bauer et al, Code Generation for Massively Parallel Phase-Field Simulations. Association for Computing Machinery, 2019. https://doi.org/10.1145/3295500.3356186
Performance Modelling:
- D. Ernst et al, Analytical performance estimation during code generation on modern GPUs. Journal of Parallel and Distributed Computing, 2023. https://doi.org/10.1016/j.jpdc.2022.11.003
...@@ -7,14 +7,14 @@ ...@@ -7,14 +7,14 @@
# conda env create -f conda_environment_user.yml # conda env create -f conda_environment_user.yml
# . activate pystencils # . activate pystencils
# #
# If you have CUDA installed and want to use your GPU, uncomment the last line to install pycuda # If you have CUDA or ROCm installed and want to use your GPU, uncomment the last line to install cupy
# #
# ---------------------------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------------------------
name: pystencils name: pystencils
dependencies: dependencies:
# Basic dependencies: # Basic dependencies:
- python >= 3.6 - python >= 3.8
- numpy - numpy
- sympy >= 1.1 - sympy >= 1.1
- appdirs # to find default cache directory on each platform - appdirs # to find default cache directory on each platform
...@@ -32,4 +32,4 @@ dependencies: ...@@ -32,4 +32,4 @@ dependencies:
- ipy_table # HTML tables for jupyter notebooks - ipy_table # HTML tables for jupyter notebooks
- pyevtk # VTK output for serial simulations - pyevtk # VTK output for serial simulations
- blitzdb # file-based No-SQL database to store simulation results - blitzdb # file-based No-SQL database to store simulation results
#- pycuda # add this if you have CUDA installed #- cupy # add this if you have CUDA or ROCm installed
import os import os
import pytest
import tempfile
import runpy import runpy
import sys import sys
import tempfile
import warnings
import nbformat
import pytest
from nbconvert import PythonExporter
from pystencils.boundaries.createindexlist import * # NOQA
# Trigger config file reading / creation once - to avoid race conditions when multiple instances are creating it # Trigger config file reading / creation once - to avoid race conditions when multiple instances are creating it
# at the same time # at the same time
from pystencils.cpu import cpujit from pystencils.cpu import cpujit
...@@ -14,12 +20,17 @@ try: ...@@ -14,12 +20,17 @@ try:
pyximport.install(language_level=3) pyximport.install(language_level=3)
except ImportError: except ImportError:
pass pass
from pystencils.boundaries.createindexlistcython import * # NOQA
SCRIPT_FOLDER = os.path.dirname(os.path.realpath(__file__)) SCRIPT_FOLDER = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.abspath('pystencils')) sys.path.insert(0, os.path.abspath('pystencils'))
# the Ubuntu pipeline uses an older version of pytest which uses deprecated functionality.
# This leads to many warinings in the test and coverage pipeline.
pytest_numeric_version = [int(x, 10) for x in pytest.__version__.split('.')]
pytest_numeric_version.reverse()
pytest_version = sum(x * (100 ** i) for i, x in enumerate(pytest_numeric_version))
def add_path_to_ignore(path): def add_path_to_ignore(path):
if not os.path.exists(path): if not os.path.exists(path):
...@@ -28,34 +39,49 @@ def add_path_to_ignore(path): ...@@ -28,34 +39,49 @@ def add_path_to_ignore(path):
collect_ignore += [os.path.join(SCRIPT_FOLDER, path, f) for f in os.listdir(os.path.join(SCRIPT_FOLDER, path))] collect_ignore += [os.path.join(SCRIPT_FOLDER, path, f) for f in os.listdir(os.path.join(SCRIPT_FOLDER, path))]
collect_ignore = [os.path.join(SCRIPT_FOLDER, "doc", "conf.py")] collect_ignore = [os.path.join(SCRIPT_FOLDER, "doc", "conf.py"),
add_path_to_ignore('pystencils_tests/benchmark') os.path.join(SCRIPT_FOLDER, "src", "pystencils", "opencl", "opencl.autoinit")]
add_path_to_ignore('tests/benchmark')
add_path_to_ignore('_local_tmp') add_path_to_ignore('_local_tmp')
try: try:
import pycuda import cupy
except ImportError: except ImportError:
collect_ignore += [os.path.join(SCRIPT_FOLDER, "pystencils/pystencils_tests/test_cudagpu.py")] collect_ignore += [os.path.join(SCRIPT_FOLDER, "tests/test_gpu.py")]
add_path_to_ignore('pystencils/gpucuda') add_path_to_ignore('src/pystencils/gpu')
try: try:
import llvmlite import waLBerla
except ImportError: except ImportError:
collect_ignore += [os.path.join(SCRIPT_FOLDER, 'pystencils_tests/backends/llvm.py')] collect_ignore += [os.path.join(SCRIPT_FOLDER, "tests/test_aligned_array.py"),
add_path_to_ignore('pystencils/llvm') os.path.join(SCRIPT_FOLDER, "tests/test_datahandling_parallel.py"),
os.path.join(SCRIPT_FOLDER, "doc/notebooks/03_tutorial_datahandling.ipynb"),
os.path.join(SCRIPT_FOLDER, "src/pystencils/datahandling/parallel_datahandling.py"),
os.path.join(SCRIPT_FOLDER, "tests/test_small_block_benchmark.ipynb")]
try: try:
import kerncraft import blitzdb
except ImportError: except ImportError:
collect_ignore += [os.path.join(SCRIPT_FOLDER, "pystencils_tests/test_kerncraft_coupling.py")] add_path_to_ignore('src/pystencils/runhelper')
add_path_to_ignore('pystencils/kerncraft_coupling') collect_ignore += [os.path.join(SCRIPT_FOLDER, "tests/test_parameterstudy.py")]
collect_ignore += [os.path.join(SCRIPT_FOLDER, "tests/test_json_serializer.py")]
try: try:
import blitzdb import islpy
except ImportError: except ImportError:
add_path_to_ignore('pystencils/runhelper') collect_ignore += [os.path.join(SCRIPT_FOLDER, "src/pystencils/integer_set_analysis.py")]
try:
import graphviz
except ImportError:
collect_ignore += [os.path.join(SCRIPT_FOLDER, "src/pystencils/backends/dot.py")]
collect_ignore += [os.path.join(SCRIPT_FOLDER, "doc/notebooks/01_tutorial_getting_started.ipynb")]
try:
import pyevtk
except ImportError:
collect_ignore += [os.path.join(SCRIPT_FOLDER, "src/pystencils/datahandling/vtk.py")]
collect_ignore += [os.path.join(SCRIPT_FOLDER, 'setup.py')] collect_ignore += [os.path.join(SCRIPT_FOLDER, 'setup.py')]
...@@ -65,10 +91,6 @@ for root, sub_dirs, files in os.walk('.'): ...@@ -65,10 +91,6 @@ for root, sub_dirs, files in os.walk('.'):
collect_ignore.append(f) collect_ignore.append(f)
import nbformat
from nbconvert import PythonExporter
class IPythonMockup: class IPythonMockup:
def run_line_magic(self, *args, **kwargs): def run_line_magic(self, *args, **kwargs):
pass pass
...@@ -89,6 +111,7 @@ class IPyNbTest(pytest.Item): ...@@ -89,6 +111,7 @@ class IPyNbTest(pytest.Item):
self.code = code self.code = code
self.add_marker('notebook') self.add_marker('notebook')
@pytest.mark.filterwarnings("ignore:IPython.core.inputsplitter is deprecated")
def runtest(self): def runtest(self):
global_dict = {'get_ipython': lambda: IPythonMockup(), global_dict = {'get_ipython': lambda: IPythonMockup(),
'is_test_run': True} 'is_test_run': True}
...@@ -114,10 +137,16 @@ class IPyNbFile(pytest.File): ...@@ -114,10 +137,16 @@ class IPyNbFile(pytest.File):
exporter.exclude_markdown = True exporter.exclude_markdown = True
exporter.exclude_input_prompt = True exporter.exclude_input_prompt = True
notebook_contents = self.fspath.open() notebook_contents = self.fspath.open(encoding='utf-8')
notebook = nbformat.read(notebook_contents, 4)
code, _ = exporter.from_notebook_node(notebook) with warnings.catch_warnings():
yield IPyNbTest(self.name, self, code) warnings.filterwarnings("ignore", "IPython.core.inputsplitter is deprecated")
notebook = nbformat.read(notebook_contents, 4)
code, _ = exporter.from_notebook_node(notebook)
if pytest_version >= 50403:
yield IPyNbTest.from_parent(name=self.name, parent=self, code=code)
else:
yield IPyNbTest(self.name, self, code)
def teardown(self): def teardown(self):
pass pass
...@@ -126,4 +155,7 @@ class IPyNbFile(pytest.File): ...@@ -126,4 +155,7 @@ class IPyNbFile(pytest.File):
def pytest_collect_file(path, parent): def pytest_collect_file(path, parent):
glob_exprs = ["*demo*.ipynb", "*tutorial*.ipynb", "test_*.ipynb"] glob_exprs = ["*demo*.ipynb", "*tutorial*.ipynb", "test_*.ipynb"]
if any(path.fnmatch(g) for g in glob_exprs): if any(path.fnmatch(g) for g in glob_exprs):
return IPyNbFile(path, parent) if pytest_version >= 50403:
return IPyNbFile.from_parent(fspath=path, parent=parent)
else:
return IPyNbFile(path, parent)
...@@ -4,10 +4,11 @@ ...@@ -4,10 +4,11 @@
import datetime import datetime
import sphinx_rtd_theme import sphinx_rtd_theme
import os import os
import re
import sys import sys
sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('.'))
from version_from_git import version_number_from_git import pystencils
extensions = [ extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.autodoc',
...@@ -25,11 +26,14 @@ templates_path = ['_templates'] ...@@ -25,11 +26,14 @@ templates_path = ['_templates']
source_suffix = '.rst' source_suffix = '.rst'
master_doc = 'index' master_doc = 'index'
copyright = '{}, Martin Bauer'.format(datetime.datetime.now().year) copyright = f'{datetime.datetime.now().year}, Martin Bauer, Markus Holzer, Frederik Hennig'
author = 'Martin Bauer' author = 'Martin Bauer, Markus Holzer, Frederik Hennig'
version = version_number_from_git() # The short X.Y version (including .devXXXX, rcX, b1 suffixes if present)
release = version_number_from_git() version = re.sub(r'(\d+\.\d+)\.\d+(.*)', r'\1\2', pystencils.__version__)
language = None version = re.sub(r'(\.dev\d+).*?$', r'\1', version)
# The full version, including alpha/beta/rc tags.
release = pystencils.__version__
language = 'en'
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '**.ipynb_checkpoints'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '**.ipynb_checkpoints']
default_role = 'any' default_role = 'any'
pygments_style = 'sphinx' pygments_style = 'sphinx'
...@@ -47,13 +51,14 @@ nbsphinx_execute = 'never' ...@@ -47,13 +51,14 @@ nbsphinx_execute = 'never'
nbsphinx_codecell_lexer = 'python3' nbsphinx_codecell_lexer = 'python3'
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('https://docs.python.org/3.6', None), intersphinx_mapping = {'python': ('https://docs.python.org/3.8', None),
'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None),
'matplotlib': ('https://matplotlib.org/', None), 'matplotlib': ('https://matplotlib.org/', None),
'sympy': ('https://docs.sympy.org/latest/', None), 'sympy': ('https://docs.sympy.org/latest/', None),
} }
autodoc_member_order = 'bysource' autodoc_member_order = 'bysource'
bibtex_bibfiles = ['sphinx/pystencils.bib']
project = 'pystencils' project = 'pystencils'
html_logo = "img/logo.png" html_logo = 'img/logo.png'
doc/img/github_repo_card.png

78.4 KiB

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="379.82614mm"
height="189.91307mm"
viewBox="0 0 1345.8407 672.92033"
id="svg2"
version="1.1"
inkscape:version="0.92.3 (2405546, 2018-03-11)"
sodipodi:docname="logo_large.svg"
inkscape:export-filename="/home/martin/code/pycodegen/pystencils/doc/img/github_repo_card.png"
inkscape:export-xdpi="85.599998"
inkscape:export-ydpi="85.599998">
<defs
id="defs4">
<inkscape:path-effect
effect="spiro"
id="path-effect4188"
is_visible="true" />
<inkscape:path-effect
effect="spiro"
id="path-effect4188-5"
is_visible="true" />
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4596">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4598" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4600" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4602" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4604" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4606" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4608">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4610" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4612" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4614" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4616" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4618" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4620">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4622" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4624" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4626" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4628" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4630" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4632">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4634" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4636" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4638" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4640" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4642" />
</filter>
<inkscape:path-effect
effect="spiro"
id="path-effect4188-7"
is_visible="true" />
<inkscape:path-effect
effect="spiro"
id="path-effect4188-5-6"
is_visible="true" />
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4596-6">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4598-6" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4600-9" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4602-1" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4604-4" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4606-3" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4620-1">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4622-1" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4624-4" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4626-8" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4628-5" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4630-7" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4632-1">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4634-9" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4636-8" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4638-7" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4640-6" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4642-5" />
</filter>
<filter
y="-0.25"
height="1.5"
inkscape:menu-tooltip="Darkens the edge with an inner blur and adds a flexible glow"
inkscape:menu="Shadows and Glows"
inkscape:label="Dark And Glow"
style="color-interpolation-filters:sRGB"
id="filter4608-0">
<feGaussianBlur
stdDeviation="5"
result="result6"
id="feGaussianBlur4610-2" />
<feComposite
result="result8"
in="SourceGraphic"
operator="atop"
in2="result6"
id="feComposite4612-5" />
<feComposite
result="result9"
operator="over"
in2="SourceAlpha"
in="result8"
id="feComposite4614-7" />
<feColorMatrix
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "
result="result10"
id="feColorMatrix4616-6" />
<feBlend
in="result10"
mode="normal"
in2="result6"
id="feBlend4618-9" />
</filter>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.70000001"
inkscape:cx="545.01294"
inkscape:cy="35.725386"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="3840"
inkscape:window-height="2061"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0">
<inkscape:grid
type="xygrid"
id="grid4176"
originx="267.20477"
originy="315.17846" />
</sodipodi:namedview>
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(267.20477,-694.6203)">
<text
xml:space="preserve"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:34.78659058px;line-height:125%;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, ';letter-spacing:0px;word-spacing:0px;fill:#252525;fill-opacity:1;stroke:none;stroke-width:4.34832382px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
x="159.99139"
y="964.43109"
id="text1392-1"
inkscape:export-xdpi="70.669998"
inkscape:export-ydpi="70.669998"><tspan
sodipodi:role="line"
id="tspan1390-1"
x="159.99139"
y="964.43109"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:156.53968811px;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, Bold';fill:#252525;fill-opacity:1;stroke-width:4.34832382px">pystencils</tspan></text>
<g
id="g9986"
transform="matrix(4.1201463,0,0,4.1201463,-399.75066,866.02979)"
inkscape:export-xdpi="70.669998"
inkscape:export-ydpi="70.669998">
<path
inkscape:connector-curvature="0"
inkscape:original-d="M 60.891002,27.333516 H 118.64865"
inkscape:path-effect="#path-effect4188-7"
id="path4186-6"
d="M 60.891002,27.333516 H 118.64865"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.78799796;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.70388345" />
<path
sodipodi:nodetypes="cc"
inkscape:connector-curvature="0"
inkscape:original-d="M 89.922623,-0.47572315 C 31.237244,132.88729 89.846228,36.88339 89.846228,56.13594"
inkscape:path-effect="#path-effect4188-5-6"
id="path4186-3-9"
d="M 89.922623,-0.47572315 89.846228,56.13594"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.78799796;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.70388345" />
<circle
transform="matrix(0.21391721,0,0,0.21391721,27.733834,-23.442344)"
r="34.345188"
cy="108.02044"
cx="291.42902"
id="path4136-76"
style="opacity:1;fill:#e69f00;fill-opacity:1;stroke:none;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter4596-6)" />
<circle
transform="matrix(0.21391721,0,0,0.21391721,27.733834,-23.442344)"
r="34.345188"
cy="365.43817"
cx="290.41885"
id="path4136-6-0"
style="opacity:1;fill:#0072b2;fill-opacity:1;stroke:none;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter4620-1)" />
<circle
transform="matrix(0.21391721,0,0,0.21391721,27.733834,-23.442344)"
r="34.345188"
cy="236.72931"
cx="422.24377"
id="path4136-3-9"
style="opacity:1;fill:#999999;fill-opacity:1;stroke:none;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter4632-1)" />
<circle
transform="matrix(0.21391721,0,0,0.21391721,27.733834,-23.442344)"
r="34.345188"
cy="236.72931"
cx="155.56349"
id="path4136-7-0"
style="opacity:1;fill:#009e73;fill-opacity:1;stroke:none;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter4608-0)" />
</g>
<text
xml:space="preserve"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:8.7668047px;line-height:125%;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, ';letter-spacing:0px;word-spacing:0px;fill:#252525;fill-opacity:0.70629368;stroke:none;stroke-width:1.09585059px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
x="229.96391"
y="1071.713"
id="text1392-1-3"
inkscape:export-xdpi="70.669998"
inkscape:export-ydpi="70.669998"><tspan
sodipodi:role="line"
id="tspan1390-1-6"
x="229.96391"
y="1071.713"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:62.0406723px;line-height:105.99999428%;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, Bold';fill:#252525;fill-opacity:0.70629368;stroke-width:1.09585059px">speed up stencil </tspan><tspan
sodipodi:role="line"
x="229.96391"
y="1137.4761"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:62.0406723px;line-height:105.99999428%;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, Bold';fill:#252525;fill-opacity:0.70629368;stroke-width:1.09585059px"
id="tspan109">computations on</tspan><tspan
sodipodi:role="line"
x="229.96391"
y="1203.2393"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:62.0406723px;line-height:105.99999428%;font-family:'Latin Modern Mono Light';-inkscape-font-specification:'Latin Modern Mono Light, Bold';fill:#252525;fill-opacity:0.70629368;stroke-width:1.09585059px"
id="tspan107">numpy arrays</tspan></text>
</g>
</svg>
...@@ -14,5 +14,6 @@ pystencils can help you to generate blazingly fast code for image processing, nu ...@@ -14,5 +14,6 @@ pystencils can help you to generate blazingly fast code for image processing, nu
.. image:: /img/pystencils_arch_block_diagram.svg .. image:: /img/pystencils_arch_block_diagram.svg
:height: 450px :height: 450px
:align: center
This source diff could not be displayed because it is too large. You can view the blob instead.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from pystencils.session import * from pystencils.session import *
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Tutorial 02: Basic Kernel generation with *pystencils* # Tutorial 02: Basic Kernel generation with *pystencils*
Now that you have an [overview of pystencils](01_tutorial_getting_started.ipynb), Now that you have an [overview of pystencils](01_tutorial_getting_started.ipynb),
this tutorial shows in more detail how to formulate, optimize and run stencil kernels. this tutorial shows in more detail how to formulate, optimize and run stencil kernels.
## 1) Kernel Definition ## 1) Kernel Definition
### a) Defining kernels with assignment lists and the `kernel` decorator ### a) Defining kernels with assignment lists and the `kernel` decorator
*pystencils* gets a symbolic formulation of the kernel. This can be either an `Assignment` or a sequence of `Assignment`s that follow a set of restrictions. *pystencils* gets a symbolic formulation of the kernel. This can be either an `Assignment` or a sequence of `Assignment`s that follow a set of restrictions.
Lets first create a kernel that consists of multiple assignments: Lets first create a kernel that consists of multiple assignments:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
src_arr = np.zeros([20, 30]) src_arr = np.zeros([20, 30])
dst_arr = np.zeros_like(src_arr) dst_arr = np.zeros_like(src_arr)
dst, src = ps.fields(dst=dst_arr, src=src_arr) dst, src = ps.fields(dst=dst_arr, src=src_arr)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grad_x, grad_y = sp.symbols("grad_x, grad_y") grad_x, grad_y = sp.symbols("grad_x, grad_y")
symbolic_description = [ symbolic_description = [
ps.Assignment(grad_x, (src[1, 0] - src[-1, 0]) / 2), ps.Assignment(grad_x, (src[1, 0] - src[-1, 0]) / 2),
ps.Assignment(grad_y, (src[0, 1] - src[0, -1]) / 2), ps.Assignment(grad_y, (src[0, 1] - src[0, -1]) / 2),
ps.Assignment(dst[0, 0], grad_x + grad_y), ps.Assignment(dst[0, 0], grad_x + grad_y),
] ]
kernel = ps.create_kernel(symbolic_description) kernel = ps.create_kernel(symbolic_description)
symbolic_description symbolic_description
``` ```
%% Output %% Output
$$\left [ grad_{x} \leftarrow \frac{{{src}_{E}}}{2} - \frac{{{src}_{W}}}{2}, \quad grad_{y} \leftarrow \frac{{{src}_{N}}}{2} - \frac{{{src}_{S}}}{2}, \quad {{dst}_{C}} \leftarrow grad_{x} + grad_{y}\right ]$$
$\displaystyle \left[ grad_{x} \leftarrow_{} \frac{{src}_{(1,0)}}{2} - \frac{{src}_{(-1,0)}}{2}, \ grad_{y} \leftarrow_{} \frac{{src}_{(0,1)}}{2} - \frac{{src}_{(0,-1)}}{2}, \ {dst}_{(0,0)} \leftarrow_{} grad_{x} + grad_{y}\right]$
⎡ src_E src_W src_N src_S ⎤ ⎡ src_E src_W src_N src_S ⎤
⎢gradₓ := ───── - ─────, grad_y := ───── - ─────, dst_C := gradₓ + grad_y⎥ ⎢gradₓ := ───── - ─────, grad_y := ───── - ─────, dst_C := gradₓ + grad_y⎥
⎣ 2 2 2 2 ⎦ ⎣ 2 2 2 2 ⎦
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We created subexpressions, using standard sympy symbols on the left hand side, to split the kernel into multiple assignments. Defining a kernel using a list of `Assignment`s is quite tedious and hard to read. We created subexpressions, using standard sympy symbols on the left hand side, to split the kernel into multiple assignments. Defining a kernel using a list of `Assignment`s is quite tedious and hard to read.
To simplify the formulation of a kernel, *pystencils* offers the `kernel` decorator, that transforms a normal Python function with `@=` assignments into an assignment list that can be passed to `create_kernel`. To simplify the formulation of a kernel, *pystencils* offers the `kernel` decorator, that transforms a normal Python function with `@=` assignments into an assignment list that can be passed to `create_kernel`.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
@ps.kernel @ps.kernel
def symbolic_description_using_function(): def symbolic_description_using_function():
grad_x @= (src[1, 0] - src[-1, 0]) / 2 grad_x @= (src[1, 0] - src[-1, 0]) / 2
grad_y @= (src[0, 1] - src[0, -1]) / 2 grad_y @= (src[0, 1] - src[0, -1]) / 2
dst[0, 0] @= grad_x + grad_y dst[0, 0] @= grad_x + grad_y
symbolic_description_using_function symbolic_description_using_function
``` ```
%% Output %% Output
$$\left [ grad_{x} \leftarrow \frac{{{src}_{E}}}{2} - \frac{{{src}_{W}}}{2}, \quad grad_{y} \leftarrow \frac{{{src}_{N}}}{2} - \frac{{{src}_{S}}}{2}, \quad {{dst}_{C}} \leftarrow grad_{x} + grad_{y}\right ]$$
$\displaystyle \left[ grad_{x} \leftarrow_{} \frac{{src}_{(1,0)}}{2} - \frac{{src}_{(-1,0)}}{2}, \ grad_{y} \leftarrow_{} \frac{{src}_{(0,1)}}{2} - \frac{{src}_{(0,-1)}}{2}, \ {dst}_{(0,0)} \leftarrow_{} grad_{x} + grad_{y}\right]$
⎡ src_E src_W src_N src_S ⎤ ⎡ src_E src_W src_N src_S ⎤
⎢gradₓ := ───── - ─────, grad_y := ───── - ─────, dst_C := gradₓ + grad_y⎥ ⎢gradₓ := ───── - ─────, grad_y := ───── - ─────, dst_C := gradₓ + grad_y⎥
⎣ 2 2 2 2 ⎦ ⎣ 2 2 2 2 ⎦
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The decorated function can contain any Python code, only the `@=` operator, and the ternary inline `if-else` operator have different meaning. The decorated function can contain any Python code, only the `@=` operator, and the ternary inline `if-else` operator have different meaning.
### b) Ternary 'if' with `Piecewise` ### b) Ternary 'if' with `Piecewise`
The ternary operator maps to `sympy.Piecewise` functions, that can be used to introduce branching into the kernel. Piecewise defined functions must give a value for every input, i.e. there must be a 'otherwise' clause in the end that is indicated by the condition `True`. Piecewise objects are standard sympy terms that can be integrated into bigger expressions: The ternary operator maps to `sympy.Piecewise` functions, that can be used to introduce branching into the kernel. Piecewise defined functions must give a value for every input, i.e. there must be a 'otherwise' clause in the end that is indicated by the condition `True`. Piecewise objects are standard sympy terms that can be integrated into bigger expressions:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sp.Piecewise((1.0, src[0,1] > 0), (0.0, True)) + src[1, 0] sp.Piecewise((1.0, src[0,1] > 0), (0.0, True)) + src[1, 0]
``` ```
%% Output %% Output
$${{src}_{E}} + \begin{cases} 1.0 & \text{for}\: {{src}_{N}} > 0 \\0.0 & \text{otherwise} \end{cases}$$
$\displaystyle {src}_{(1,0)} + \begin{cases} 1.0 & \text{for}\: {src}_{(0,1)} > 0 \\0.0 & \text{otherwise} \end{cases}$
⎛⎧1.0 for src_N > 0⎞ ⎛⎧1.0 for src_N > 0⎞
src_E + ⎜⎨ ⎟ src_E + ⎜⎨ ⎟
⎝⎩0.0 otherwise ⎠ ⎝⎩0.0 otherwise ⎠
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Piecewise objects are created by the `kernel` decorator for ternary if-else statements. Piecewise objects are created by the `kernel` decorator for ternary if-else statements.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
@ps.kernel @ps.kernel
def kernel_with_piecewise(): def kernel_with_piecewise():
grad_x @= (src[1, 0] - src[-1, 0]) / 2 if src[-1, 0] > 0 else 0.0 grad_x @= (src[1, 0] - src[-1, 0]) / 2 if src[-1, 0] > 0 else 0.0
kernel_with_piecewise kernel_with_piecewise
``` ```
%% Output %% Output
$$\left [ grad_{x} \leftarrow \begin{cases} \frac{{{src}_{E}}}{2} - \frac{{{src}_{W}}}{2} & \text{for}\: {{src}_{W}} > 0 \\0.0 & \text{otherwise} \end{cases}\right ]$$
$\displaystyle \left[ grad_{x} \leftarrow_{} \begin{cases} \frac{{src}_{(1,0)}}{2} - \frac{{src}_{(-1,0)}}{2} & \text{for}\: {src}_{(-1,0)} > 0 \\0.0 & \text{otherwise} \end{cases}\right]$
⎡ ⎧src_E src_W ⎤ ⎡ ⎧src_E src_W ⎤
⎢ ⎪───── - ───── for src_W > 0⎥ ⎢ ⎪───── - ───── for src_W > 0⎥
⎢gradₓ := ⎨ 2 2 ⎥ ⎢gradₓ := ⎨ 2 2 ⎥
⎢ ⎪ ⎥ ⎢ ⎪ ⎥
⎣ ⎩ 0.0 otherwise ⎦ ⎣ ⎩ 0.0 otherwise ⎦
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### c) Assignment level optimizations using `AssignmentCollection` ### c) Assignment level optimizations using `AssignmentCollection`
When the kernels get larger and more complex, it is helpful to organize the list of assignment into a more structured way. The `AssignmentCollection` offers optimizating transformation on a list of assignments. It holds two assignment lists, one for subexpressions and one for the main assignments. Main assignments are typically those that write to an array. When the kernels get larger and more complex, it is helpful to organize the list of assignment into a more structured way. The `AssignmentCollection` offers optimizating transformation on a list of assignments. It holds two assignment lists, one for subexpressions and one for the main assignments. Main assignments are typically those that write to an array.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
@ps.kernel @ps.kernel
def somewhat_longer_dummy_kernel(s): def somewhat_longer_dummy_kernel(s):
s.a @= src[0, 1] + src[-1, 0] s.a @= src[0, 1] + src[-1, 0]
s.b @= 2 * src[1, 0] + src[0, -1] s.b @= 2 * src[1, 0] + src[0, -1]
s.c @= src[0, 1] + 2 * src[1, 0] + src[-1, 0] + src[0, -1] - src[0,0] s.c @= src[0, 1] + 2 * src[1, 0] + src[-1, 0] + src[0, -1] - src[0,0]
dst[0, 0] @= s.a + s.b + s.c dst[0, 0] @= s.a + s.b + s.c
ac = ps.AssignmentCollection(main_assignments=somewhat_longer_dummy_kernel[-1:], ac = ps.AssignmentCollection(main_assignments=somewhat_longer_dummy_kernel[-1:],
subexpressions=somewhat_longer_dummy_kernel[:-1]) subexpressions=somewhat_longer_dummy_kernel[:-1])
ac ac
``` ```
%% Output %% Output
Equation Collection for dst_C AssignmentCollection: dst_C, <- f(src_C, src_W, src_S, src_N, src_E)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ac.operation_count ac.operation_count
``` ```
%% Output %% Output
{'adds': 8, 'muls': 2, 'divs': 0} {'adds': 8,
'muls': 2,
'divs': 0,
'sqrts': 0,
'fast_sqrts': 0,
'fast_inv_sqrts': 0,
'fast_div': 0}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The `pystencils.simp` submodule offers several functions to optimize a collection of assignments. The `pystencils.simp` submodule offers several functions to optimize a collection of assignments.
It also offers functionality to group optimization into strategies and evaluate them. It also offers functionality to group optimization into strategies and evaluate them.
In this example we reduce the number of operations by reusing existing subexpressions to get rid of two unnecessary floating point additions. For more information about assignment collections and simplifications see the [demo notebook](demo_assignment_collection.ipynb). In this example we reduce the number of operations by reusing existing subexpressions to get rid of two unnecessary floating point additions. For more information about assignment collections and simplifications see the [demo notebook](demo_assignment_collection.ipynb).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
opt_ac = ps.simp.subexpression_substitution_in_existing_subexpressions(ac) opt_ac = ps.simp.subexpression_substitution_in_existing_subexpressions(ac)
opt_ac opt_ac
``` ```
%% Output %% Output
Equation Collection for dst_C AssignmentCollection: dst_C, <- f(src_C, src_W, src_S, src_N, src_E)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
opt_ac.operation_count opt_ac.operation_count
``` ```
%% Output %% Output
{'adds': 6, 'muls': 1, 'divs': 0} {'adds': 6,
'muls': 1,
'divs': 0,
'sqrts': 0,
'fast_sqrts': 0,
'fast_inv_sqrts': 0,
'fast_div': 0}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### d) Ghost layers and iteration region ### d) Ghost layers and iteration region
When creating a kernel with neighbor accesses, *pystencils* automatically restricts the iteration region, such that all accesses are safe. When creating a kernel with neighbor accesses, *pystencils* automatically restricts the iteration region, such that all accesses are safe.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
kernel = ps.create_kernel(ps.Assignment(dst[0,0], src[2, 0] + src[-1, 0])) kernel = ps.create_kernel(ps.Assignment(dst[0,0], src[2, 0] + src[-1, 0]))
ps.show_code(kernel) ps.show_code(kernel)
``` ```
%% Output %% Output
FUNC_PREFIX void kernel(double * RESTRICT fd_dst, double * RESTRICT const fd_src)
{
for (int ctr_0 = 2; ctr_0 < 18; ctr_0 += 1)
{
double * RESTRICT fd_dst_C = 30*ctr_0 + fd_dst;
double * RESTRICT const fd_src_2E = 30*ctr_0 + fd_src + 60;
double * RESTRICT const fd_src_W = 30*ctr_0 + fd_src - 30;
for (int ctr_1 = 2; ctr_1 < 28; ctr_1 += 1)
{
fd_dst_C[ctr_1] = fd_src_2E[ctr_1] + fd_src_W[ctr_1];
}
}
}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
When no additional ghost layer information is given, *pystencils* looks at all neighboring field accesses and introduces the required number of ghost layers **for all directions**. In the example above the largest neighbor accesses was ``src[2, 0]``, so theoretically we would need 2 ghost layers only the the end of the x coordinate. When no additional ghost layer information is given, *pystencils* looks at all neighboring field accesses and introduces the required number of ghost layers **for all directions**. In the example above the largest neighbor accesses was ``src[2, 0]``, so theoretically we would need 2 ghost layers only the the end of the x coordinate.
By default *pystencils* introduces 2 ghost layers at all borders of the domain. The next cell shows how to change this behavior. Be careful with manual ghost layer specification, wrong values may lead to SEGFAULTs. By default *pystencils* introduces 2 ghost layers at all borders of the domain. The next cell shows how to change this behavior. Be careful with manual ghost layer specification, wrong values may lead to SEGFAULTs.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
gl_spec = [(0, 2), # 0 ghost layers at the left, 2 at the right border gl_spec = [(0, 2), # 0 ghost layers at the left, 2 at the right border
(1, 0)] # 1 ghost layer at the lower y, one at the upper y coordinate (1, 0)] # 1 ghost layer at the lower y, one at the upper y coordinate
kernel = ps.create_kernel(ps.Assignment(dst[0,0], src[2, 0] + src[-1, 0]), ghost_layers=gl_spec) kernel = ps.create_kernel(ps.Assignment(dst[0,0], src[2, 0] + src[-1, 0]), ghost_layers=gl_spec)
ps.show_code(kernel) ps.show_code(kernel)
``` ```
%% Output %% Output
FUNC_PREFIX void kernel(double * RESTRICT fd_dst, double * RESTRICT const fd_src)
{
for (int ctr_0 = 0; ctr_0 < 18; ctr_0 += 1)
{
double * RESTRICT fd_dst_C = 30*ctr_0 + fd_dst;
double * RESTRICT const fd_src_2E = 30*ctr_0 + fd_src + 60;
double * RESTRICT const fd_src_W = 30*ctr_0 + fd_src - 30;
for (int ctr_1 = 1; ctr_1 < 30; ctr_1 += 1)
{
fd_dst_C[ctr_1] = fd_src_2E[ctr_1] + fd_src_W[ctr_1];
}
}
}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 2 ) Restrictions ## 2 ) Restrictions
### a) Independence Restriction ### a) Independence Restriction
*pystencils* only works for kernels where each array element can be updated independently from all other elements. This restriction ensures that the kernels can be easily parallelized and also be run on the GPU. Trying to define kernels where the results depends on the iteration order, leads to a ValueError. *pystencils* only works for kernels where each array element can be updated independently from all other elements. This restriction ensures that the kernels can be easily parallelized and also be run on the GPU. Trying to define kernels where the results depends on the iteration order, leads to a ValueError.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
invalid_description = [ invalid_description = [
ps.Assignment(dst[1, 0], src[1, 0] + src[-1, 0]), ps.Assignment(dst[1, 0], src[1, 0] + src[-1, 0]),
ps.Assignment(dst[0, 0], src[1, 0] - src[-1, 0]), ps.Assignment(dst[0, 0], src[1, 0] - src[-1, 0]),
] ]
try: try:
invalid_kernel = ps.create_kernel(invalid_description) invalid_kernel = ps.create_kernel(invalid_description)
assert False, "Should never be executed" assert False, "Should never be executed"
except ValueError as e: except ValueError as e:
print(e) print(e)
``` ```
%% Output %% Output
Field dst is written at two different locations Field dst is written at two different locations
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The independence restriction makes sure that the kernel can be safely parallelized by checking the following conditions: If a field is modified inside the kernel, it may only be modified at a single spatial position. In that case the field may also only be read at this position. Fields that are not modified may be read at multiple neighboring positions. The independence restriction makes sure that the kernel can be safely parallelized by checking the following conditions: If a field is modified inside the kernel, it may only be modified at a single spatial position. In that case the field may also only be read at this position. Fields that are not modified may be read at multiple neighboring positions.
Specifically, this rule allows for in-place updates that don't access neighbors. Specifically, this rule allows for in-place updates that don't access neighbors.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
valid_kernel = ps.create_kernel(ps.Assignment(src[0,0], 2*src[0,0] + 42)) valid_kernel = ps.create_kernel(ps.Assignment(src[0,0], 2*src[0,0] + 42))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
If a field stores multiple values per cell, as in the next example, this restriction only applies for accesses with the same index. If a field stores multiple values per cell, as in the next example, this restriction only applies for accesses with the same index.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
v = ps.fields("v(2): double[2D]") v = ps.fields("v(2): double[2D]")
valid_kernel = ps.create_kernel([ps.Assignment(v[0,0](1), 2*v[0,0](1) + 42), valid_kernel = ps.create_kernel([ps.Assignment(v[0,0](1), 2*v[0,0](1) + 42),
ps.Assignment(v[0,1](0), 2*v[1,0](0) + 42)]) ps.Assignment(v[0,1](0), 2*v[0,1](0) + 42)])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### b) Static Single Assignment Form ### b) Static Single Assignment Form
All assignments that don't write to a field must be in SSA form All assignments that don't write to a field must be in SSA form
1. Each sympy symbol may only occur once as a left-hand-side (fields can be written multiple times) 1. Each sympy symbol may only occur once as a left-hand-side (fields can be written multiple times)
2. A symbol has to be defined before it is used. If it is never defined it is introduced as function parameter 2. A symbol has to be defined before it is used. If it is never defined it is introduced as function parameter
The next cell demonstrates the first SSA restriction: The next cell demonstrates the first SSA restriction:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
@ps.kernel @ps.kernel
def not_allowed(): def not_allowed():
a, b = sp.symbols("a b") a, b = sp.symbols("a b")
a @= src[0, 0] a @= src[0, 0]
b @= a + 3 b @= a + 3
a @= src[-1, 0] a @= src[-1, 0]
dst[0, 0] @= a + b dst[0, 0] @= a + b
try: try:
ps.create_kernel(not_allowed) ps.create_kernel(not_allowed)
assert False assert False
except ValueError as e: except ValueError as e:
print(e) print(e)
``` ```
%% Output %% Output
Assignments not in SSA form, multiple assignments to a Assignments not in SSA form, multiple assignments to a
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
However, for right hand sides that are Field.Accesses this is allowed: Also it is not allowed to write a field at the same location
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
@ps.kernel @ps.kernel
def allowed(): def not_allowed():
dst[0, 0] @= src[0, 1] + src[1, 0] dst[0, 0] @= src[0, 1] + src[1, 0]
dst[0, 0] @= 2 * dst[0, 0] dst[0, 0] @= 2 * dst[0, 0]
ps.create_kernel(allowed)
try:
ps.create_kernel(not_allowed)
assert False
except ValueError as e:
print(e)
``` ```
%% Output %% Output
KernelFunction kernel([<double * RESTRICT fd_dst>, <double * RESTRICT const fd_src>]) Field dst is written twice at the same location
%% Cell type:markdown id: tags:
This situation should be resolved by introducing temporary variables
%% Cell type:code id: tags:
``` python
tmp_var = sp.Symbol("a")
@ps.kernel
def allowed():
tmp_var @= src[0, 1] + src[1, 0]
dst[0, 0] @= 2 * tmp_var
ast = ps.create_kernel(allowed)
ps.show_code(ast)
```
%% Output
......
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import psutil
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot, cm from matplotlib import pyplot, cm
from pystencils.session import * from pystencils.session import *
from pystencils.boundaries import add_neumann_boundary, Neumann, Dirichlet, BoundaryHandling from pystencils.boundaries import add_neumann_boundary, Neumann, Dirichlet, BoundaryHandling
from pystencils.slicing import slice_from_direction from pystencils.slicing import slice_from_direction
import math import math
import time import time
%matplotlib inline %matplotlib inline
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Test to see if pycuda is installed which is needed to run calculations on the GPU Test to see if cupy is installed which is needed to run calculations on the GPU
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
try: try:
import pycuda import cupy
gpu = True
except ImportError: except ImportError:
pycuda = None gpu = False
print('No pycuda installed') cupy = None
print('No cupy installed')
if pycuda:
import pycuda.gpuarray as gpuarray
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Tutorial 03: Datahandling # Tutorial 03: Datahandling
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This is a tutorial about the `DataHandling` class of pystencils. This class is an abstraction layer to This is a tutorial about the `DataHandling` class of pystencils. This class is an abstraction layer to
- link numpy arrays to pystencils fields - link numpy arrays to pystencils fields
- handle CPU-GPU array transfer, such that one can write code that works on CPU and GPU - handle CPU-GPU array transfer, such that one can write code that works on CPU and GPU
- makes it possible to write MPI parallel simulations to run on distributed-memory clusters using the waLBerla library - makes it possible to write MPI parallel simulations to run on distributed-memory clusters using the waLBerla library
We will look at a small and easy example to demonstrate the usage of `DataHandling` objects. We will define an averaging kernel to every cell of an array, that writes the average of the neighbor cell values to the center. We will look at a small and easy example to demonstrate the usage of `DataHandling` objects. We will define an averaging kernel to every cell of an array, that writes the average of the neighbor cell values to the center.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 1. Manual ## 1. Manual
### 1.1. CPU kernels ### 1.1. CPU kernels
In this first part, we set up a scenario manually without a `DataHandling`. In the next sections we then repeat the same setup with the help of the data handling. In this first part, we set up a scenario manually without a `DataHandling`. In the next sections we then repeat the same setup with the help of the data handling.
One concept of *pystencils* that may be confusing at first, is the differences between pystencils fields and numpy arrays. Fields are used to describe the computation *symbolically* with sympy, while numpy arrays hold the actual values where the computation is executed on. One concept of *pystencils* that may be confusing at first, is the differences between pystencils fields and numpy arrays. Fields are used to describe the computation *symbolically* with sympy, while numpy arrays hold the actual values where the computation is executed on.
One option to create and execute a *pystencils* kernel is listed below. For reasons that become clear later we call this the **variable-field-size workflow**: One option to create and execute a *pystencils* kernel is listed below. For reasons that become clear later we call this the **variable-field-size workflow**:
1. define pystencils fields 1. define pystencils fields
2. use sympy and the pystencils fields to define an update rule, that describes what should be done on *every cell* 2. use sympy and the pystencils fields to define an update rule, that describes what should be done on *every cell*
3. compile the update rule to a real function, that can be called from Python. For each field that was referenced in the symbolic description the function expects a numpy array, passed as named parameter 3. compile the update rule to a real function, that can be called from Python. For each field that was referenced in the symbolic description the function expects a numpy array, passed as named parameter
4. create some numpy arrays with actual data 4. create some numpy arrays with actual data
5. call the kernel - usually many times 5. call the kernel - usually many times
Now, lets see how this actually looks in Python code: Now, lets see how this actually looks in Python code:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# 1. field definitions # 1. field definitions
src_field, dst_field = ps.fields("src, dst:[2D]") src_field, dst_field = ps.fields("src, dst:[2D]")
# 2. define update rule # 2. define update rule
update_rule = [ps.Assignment(lhs=dst_field[0, 0], update_rule = [ps.Assignment(lhs=dst_field[0, 0],
rhs=(src_field[1, 0] + src_field[-1, 0] + rhs=(src_field[1, 0] + src_field[-1, 0] +
src_field[0, 1] + src_field[0, -1]) / 4)] src_field[0, 1] + src_field[0, -1]) / 4)]
# 3. compile update rule to function # 3. compile update rule to function
kernel_function = ps.create_kernel(update_rule).compile() kernel_function = ps.create_kernel(update_rule).compile()
# 4. create numpy arrays and call kernel # 4. create numpy arrays and call kernel
src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30]) src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30])
# 5. call kernel # 5. call kernel
kernel_function(src=src_arr, dst=dst_arr) # names of arguments have to match names passed to ps.fields() kernel_function(src=src_arr, dst=dst_arr) # names of arguments have to match names passed to ps.fields()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This workflow separates the symbolic and the numeric stages very cleanly. The separation also makes it possible to stop after step 3, write the C-code to a file and call the kernel from a C program. Speaking of the C-Code - lets have a look at the generated sources: This workflow separates the symbolic and the numeric stages very cleanly. The separation also makes it possible to stop after step 3, write the C-code to a file and call the kernel from a C program. Speaking of the C-Code - lets have a look at the generated sources:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ps.show_code(kernel_function.ast) ps.show_code(kernel_function.ast)
``` ```
%% Output %% Output
FUNC_PREFIX void kernel(double * _data_dst, double * const _data_src, int64_t const _size_dst_0, int64_t const _size_dst_1, int64_t const _stride_dst_0, int64_t const _stride_dst_1, int64_t const _stride_src_0, int64_t const _stride_src_1)
{
for (int ctr_0 = 1; ctr_0 < _size_dst_0 - 1; ctr_0 += 1)
{
double * _data_dst_00 = _data_dst + _stride_dst_0*ctr_0;
double * const _data_src_01 = _data_src + _stride_src_0*ctr_0 + _stride_src_0;
double * const _data_src_00 = _data_src + _stride_src_0*ctr_0;
double * const _data_src_0m1 = _data_src + _stride_src_0*ctr_0 - _stride_src_0;
for (int ctr_1 = 1; ctr_1 < _size_dst_1 - 1; ctr_1 += 1)
{
_data_dst_00[_stride_dst_1*ctr_1] = 0.25*_data_src_00[_stride_src_1*ctr_1 + _stride_src_1] + 0.25*_data_src_00[_stride_src_1*ctr_1 - _stride_src_1] + 0.25*_data_src_01[_stride_src_1*ctr_1] + 0.25*_data_src_0m1[_stride_src_1*ctr_1];
}
}
}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Even if it looks very ugly and low-level :) lets look at this code in a bit more detail. The code is generated in a way that it works for different array sizes. The size of the array is passed in the `_size_dst_` variables that specifiy the shape of the array for each dimension. Also, the memory layout (linearization) of the array can be different. That means the array could be stored in row-major or column-major order - if we pass in the array strides correctly the kernel does the right thing. If you're not familiar with the concept of strides check out [this stackoverflow post](https://stackoverflow.com/questions/53097952/how-to-understand-numpy-strides-for-layman) or search in the numpy documentation for strides - C vs Fortran order. Even if it looks very ugly and low-level :) lets look at this code in a bit more detail. The code is generated in a way that it works for different array sizes. The size of the array is passed in the `_size_dst_` variables that specifiy the shape of the array for each dimension. Also, the memory layout (linearization) of the array can be different. That means the array could be stored in row-major or column-major order - if we pass in the array strides correctly the kernel does the right thing. If you're not familiar with the concept of strides check out [this stackoverflow post](https://stackoverflow.com/questions/53097952/how-to-understand-numpy-strides-for-layman) or search in the numpy documentation for strides - C vs Fortran order.
The goal of *pystencils* is to produce the fastest possible code. One technique to do this is to use all available information already on compile time and generate code that is highly adapted to the specific problem. In our case we already know the shape and strides of the arrays we want to apply the kernel to, so we can make use of this information. This idea leads to the **fixed-field-size workflow**. The main difference there is that we define the arrays first and therefore let *pystencils* know about the array shapes and strides, so that it can generate more specific code: The goal of *pystencils* is to produce the fastest possible code. One technique to do this is to use all available information already on compile time and generate code that is highly adapted to the specific problem. In our case we already know the shape and strides of the arrays we want to apply the kernel to, so we can make use of this information. This idea leads to the **fixed-field-size workflow**. The main difference there is that we define the arrays first and therefore let *pystencils* know about the array shapes and strides, so that it can generate more specific code:
1. create numpy arrays that hold your data 1. create numpy arrays that hold your data
2. define pystencils fields, this time telling pystencils already which arrays they correspond to, so that it knows about the size and strides 2. define pystencils fields, this time telling pystencils already which arrays they correspond to, so that it knows about the size and strides
in the other steps nothing has changed in the other steps nothing has changed
3. define the update rule 3. define the update rule
4. compile update rule to kernel 4. compile update rule to kernel
5. run the kernel 5. run the kernel
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# 1. create arrays first # 1. create arrays first
src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30]) src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30])
# 2. define symbolic fields - note the additional parameter that link an array to each field # 2. define symbolic fields - note the additional parameter that link an array to each field
src_field, dst_field = ps.fields("src, dst:[2D]", src=src_arr, dst=dst_arr) src_field, dst_field = ps.fields("src, dst:[2D]", src=src_arr, dst=dst_arr)
# 3. define update rule # 3. define update rule
update_rule = [ps.Assignment(lhs=dst_field[0, 0], update_rule = [ps.Assignment(lhs=dst_field[0, 0],
rhs=(src_field[1, 0] + src_field[-1, 0] + rhs=(src_field[1, 0] + src_field[-1, 0] +
src_field[0, 1] + src_field[0, -1]) / 4)] src_field[0, 1] + src_field[0, -1]) / 4)]
# 4. compile it # 4. compile it
kernel_function = ps.create_kernel(update_rule).compile() kernel_function = ps.create_kernel(update_rule).compile()
# 5. call kernel # 5. call kernel
kernel_function(src=src_arr, dst=dst_arr) # names of arguments have to match names passed to ps.fields() kernel_function(src=src_arr, dst=dst_arr) # names of arguments have to match names passed to ps.fields()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functionally, both variants are equivalent. We see the difference only when we look at the generated code Functionally, both variants are equivalent. We see the difference only when we look at the generated code
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ps.show_code(kernel_function.ast) ps.show_code(kernel_function.ast)
``` ```
%% Output %% Output
FUNC_PREFIX void kernel(double * _data_dst, double * const _data_src)
{
for (int ctr_0 = 1; ctr_0 < 29; ctr_0 += 1)
{
double * _data_dst_00 = _data_dst + 30*ctr_0;
double * const _data_src_01 = _data_src + 30*ctr_0 + 30;
double * const _data_src_00 = _data_src + 30*ctr_0;
double * const _data_src_0m1 = _data_src + 30*ctr_0 - 30;
for (int ctr_1 = 1; ctr_1 < 29; ctr_1 += 1)
{
_data_dst_00[ctr_1] = 0.25*_data_src_00[ctr_1 + 1] + 0.25*_data_src_00[ctr_1 - 1] + 0.25*_data_src_01[ctr_1] + 0.25*_data_src_0m1[ctr_1];
}
}
}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Compare this to the code above! It looks much simpler. The reason is that all index computations are already simplified since the exact field sizes and strides are known. This kernel now only works on arrays of the previously specified size. Compare this to the code above! It looks much simpler. The reason is that all index computations are already simplified since the exact field sizes and strides are known. This kernel now only works on arrays of the previously specified size.
Lets try what happens if we use a different array: Lets try what happens if we use a different array:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
src_arr2, dst_arr2 = np.random.rand(40, 40), np.zeros([40, 40]) src_arr2, dst_arr2 = np.random.rand(40, 40), np.zeros([40, 40])
try: try:
kernel_function(src=src_arr2, dst=dst_arr2) kernel_function(src=src_arr2, dst=dst_arr2)
except ValueError as e: except ValueError as e:
print(e) print(e)
``` ```
%% Output %% Output
Wrong shape of array dst. Expected (30, 30) Wrong shape of array dst. Expected (30, 30)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### 1.2. GPU simulations ### 1.2. GPU simulations
Let's now jump to a seemingly unrelated topic: running kernels on the GPU. Let's now jump to a seemingly unrelated topic: running kernels on the GPU.
When creating the kernel, an additional parameter `target='gpu'` has to be passed. Also, the compiled kernel cannot be called with numpy arrays directly, but has to be called with `pycuda.gpuarray`s instead. That means, we have to transfer our numpy array to GPU first. From this step we obtain a gpuarray, then we can run the kernel, hopefully multiple times so that the data transfer was worth the time. Finally we transfer the finished result back to CPU: When creating the kernel, an additional parameter `target=ps.Target.GPU` has to be passed. Also, the compiled kernel cannot be called with numpy arrays directly, but has to be called with `cupy.array`s instead. That means, we have to transfer our numpy array to GPU first. From this step we obtain a gpuarray, then we can run the kernel, hopefully multiple times so that the data transfer was worth the time. Finally we transfer the finished result back to CPU:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
if pycuda: if cupy:
kernel_function_gpu = ps.create_kernel(update_rule, target='gpu').compile() config = ps.CreateKernelConfig(target=ps.Target.GPU)
kernel_function_gpu = ps.create_kernel(update_rule, config=config).compile()
# transfer to GPU # transfer to GPU
src_arr_gpu = pycuda.gpuarray.to_gpu(src_arr) src_arr_gpu = cupy.asarray(src_arr)
dst_arr_gpu = pycuda.gpuarray.to_gpu(dst_arr) dst_arr_gpu = cupy.asarray(dst_arr)
# run kernel on GPU, this is done many times in real setups # run kernel on GPU, this is done many times in real setups
kernel_function_gpu(src=src_arr_gpu, dst=dst_arr_gpu) kernel_function_gpu(src=src_arr_gpu, dst=dst_arr_gpu)
# transfer result back to CPU # transfer result back to CPU
dst_arr_gpu.get(dst_arr) dst_arr = dst_arr_gpu.get()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### 1.3. Summary: manual way ### 1.3. Summary: manual way
- Don't confuse *pystencils* fields and *numpy* arrays - Don't confuse *pystencils* fields and *numpy* arrays
- fields are symbolic - fields are symbolic
- arrays are numeric - arrays are numeric
- Use the fixed-field-size workflow whenever possible, since code might be faster. Create arrays first, then create fields from arrays - Use the fixed-field-size workflow whenever possible, since code might be faster. Create arrays first, then create fields from arrays
- if we run GPU kernels, arrays have to transferred to the GPU first - if we run GPU kernels, arrays have to transferred to the GPU first
As demonstrated in the examples above we have to define 2 or 3 corresponding objects for each grid: As demonstrated in the examples above we have to define 2 or 3 corresponding objects for each grid:
- symbolic pystencils field - symbolic pystencils field
- numpy array on CPU - numpy array on CPU
- for GPU run also a pycuda.gpuarray to mirror the data on the GPU - for GPU use also cupy to mirror the data on the GPU
Managing these three objects manually is tedious and error-prone. We'll see in the next section how the data handling object takes care of this problem. Managing these three objects manually is tedious and error-prone. We'll see in the next section how the data handling object takes care of this problem.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 2. Introducing the data handling - serial version ## 2. Introducing the data handling - serial version
### 2.1. Example for CPU simulations ### 2.1. Example for CPU simulations
The data handling internally keeps a mapping between symbolic fields and numpy arrays. When we create a field, automatically a corresponding array is allocated as well. Optionally we can also allocate memory on the GPU for the array as well. Lets dive right in and see how our example looks like, when implemented with a data handling. The data handling internally keeps a mapping between symbolic fields and numpy arrays. When we create a field, automatically a corresponding array is allocated as well. Optionally we can also allocate memory on the GPU for the array as well. Lets dive right in and see how our example looks like, when implemented with a data handling.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh = ps.create_data_handling(domain_size=(30, 30)) dh = ps.create_data_handling(domain_size=(30, 30))
# fields are now created using the data handling # fields are now created using the data handling
src_field = dh.add_array('src', values_per_cell=1) src_field = dh.add_array('src', values_per_cell=1)
dst_field = dh.add_array('dst', values_per_cell=1) dst_field = dh.add_array('dst', values_per_cell=1)
# kernel is created just like before # kernel is created just like before
update_rule = [ps.Assignment(lhs=dst_field[0, 0], update_rule = [ps.Assignment(lhs=dst_field[0, 0],
rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)] rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]
kernel_function = ps.create_kernel(update_rule).compile() kernel_function = ps.create_kernel(update_rule).compile()
# have a look at the generated code - it uses # have a look at the generated code - it uses
# the fast version where array sizes are compiled-in # the fast version where array sizes are compiled-in
# ps.show_code(kernel_function.ast) # ps.show_code(kernel_function.ast)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The data handling has methods to create fields - but where are the corresponding arrays? The data handling has methods to create fields - but where are the corresponding arrays?
In the serial case you can access them as a member of the data handling, for example to initialize our 'src' array we can write In the serial case you can access them as a member of the data handling, for example to initialize our 'src' array we can write
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
src_arr = dh.cpu_arrays['src'] src_arr = dh.cpu_arrays['src']
src_arr.fill(0.0) src_arr.fill(0.0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This method is nice and easy, but you should not use it if you want your simulation to run on distributed-memory clusters. We'll see why in the last section. So it is good habit to not access the arrays directly but use the data handling to do so. We can, for example, initialize the array also with the following code: This method is nice and easy, but you should not use it if you want your simulation to run on distributed-memory clusters. We'll see why in the last section. So it is good habit to not access the arrays directly but use the data handling to do so. We can, for example, initialize the array also with the following code:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.fill('src', 0.0) dh.fill('src', 0.0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To run the kernels with the same code as before, we would also need the arrays. We could do that accessing the `cpu_arrays`: To run the kernels with the same code as before, we would also need the arrays. We could do that accessing the `cpu_arrays`:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
kernel_function(src=dh.cpu_arrays['src'], kernel_function(src=dh.cpu_arrays['src'],
dst=dh.cpu_arrays['dst']) dst=dh.cpu_arrays['dst'])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
but to be prepared for MPI parallel simulations, again a method of the data handling should be used for this. but to be prepared for MPI parallel simulations, again a method of the data handling should be used for this.
Besides, this method is also simpler to use - since it automatically detects which arrays a kernel uses and passes them in. Besides, this method is also simpler to use - since it automatically detects which arrays a kernel uses and passes them in.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.run_kernel(kernel_function) dh.run_kernel(kernel_function)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To access the data read-only instead of using `cpu_arrays` the gather function should be used. To access the data read-only instead of using `cpu_arrays` the gather function should be used.
This function gives you a read-only copy of the domain or part of the domain. This function gives you a read-only copy of the domain or part of the domain.
We will discuss this function later in more detail when we look at MPI parallel simulations. We will discuss this function later in more detail when we look at MPI parallel simulations.
For serial simulations keep in mind that modifying the resulting array does not change your original data! For serial simulations keep in mind that modifying the resulting array does not change your original data!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
read_only_copy = dh.gather_array('src', ps.make_slice[:, :], ghost_layers=False) read_only_copy = dh.gather_array('src', ps.make_slice[:, :], ghost_layers=False)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### 2.2. Example for GPU simulations ### 2.2. Example for GPU simulations
In this section we have a look at GPU simulations using the data handling. Only minimal changes are required. In this section we have a look at GPU simulations using the data handling. Only minimal changes are required.
When creating the data handling we can pass a 'default_target'. This means for every added field an array on the CPU and the GPU is allocated. This is a useful default, for more fine-grained control the `add_array` method also takes additional parameters controlling where the array should be allocated. When creating the data handling we can pass a 'default_target'. This means for every added field an array on the CPU and the GPU is allocated. This is a useful default, for more fine-grained control the `add_array` method also takes additional parameters controlling where the array should be allocated.
Additionally we also need to compile a GPU version of the kernel. Additionally we also need to compile a GPU version of the kernel.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh = ps.create_data_handling(domain_size=(30, 30), default_target='gpu') if gpu is False:
dh = ps.create_data_handling(domain_size=(30, 30), default_target=ps.Target.CPU)
else:
dh = ps.create_data_handling(domain_size=(30, 30), default_target=ps.Target.GPU)
# fields are now created using the data handling # fields are now created using the data handling
src_field = dh.add_array('src', values_per_cell=1) src_field = dh.add_array('src', values_per_cell=1)
dst_field = dh.add_array('dst', values_per_cell=1) dst_field = dh.add_array('dst', values_per_cell=1)
# kernel is created just like before # kernel is created just like before
update_rule = [ps.Assignment(lhs=dst_field[0, 0], update_rule = [ps.Assignment(lhs=dst_field[0, 0],
rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)] rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]
kernel_function = ps.create_kernel(update_rule, target=dh.default_target).compile() config = ps.CreateKernelConfig(target=dh.default_target)
kernel_function = ps.create_kernel(update_rule, config=config).compile()
dh.fill('src', 0.0) dh.fill('src', 0.0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The data handling provides function to transfer data between CPU and GPU The data handling provides function to transfer data between CPU and GPU
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.to_gpu('src') if gpu:
dh.to_gpu('src')
dh.run_kernel(kernel_function) dh.run_kernel(kernel_function)
dh.to_cpu('dst')
if gpu:
dh.to_cpu('dst')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
usually one wants to transfer all fields that have been allocated on CPU and GPU at the same time: usually one wants to transfer all fields that have been allocated on CPU and GPU at the same time:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.all_to_gpu() dh.all_to_gpu()
dh.run_kernel(kernel_function) dh.run_kernel(kernel_function)
dh.all_to_cpu() dh.all_to_cpu()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can always include the `all_to_*` functions in our code, since they do nothing if there are no arrays allocated on the GPU. Thus there is only a single point in the code where we can switch between CPU and GPU version: the `default_target` of the data handling. We can always include the `all_to_*` functions in our code, since they do nothing if there are no arrays allocated on the GPU. Thus there is only a single point in the code where we can switch between CPU and GPU version: the `default_target` of the data handling.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### 2.2 Ghost Layers and periodicity ### 2.2 Ghost Layers and periodicity
The data handling can also provide periodic boundary conditions. Therefor the domain is extended by one layer of cells, the so-called ghost layer or halo layer. The data handling can also provide periodic boundary conditions. Therefor the domain is extended by one layer of cells, the so-called ghost layer or halo layer.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Shape of domain ", dh.shape) print("Shape of domain ", dh.shape)
print("Direct access to arrays ", dh.cpu_arrays['src'].shape) print("Direct access to arrays ", dh.cpu_arrays['src'].shape)
print("Gather ", dh.gather_array('src', ghost_layers=True).shape) print("Gather ", dh.gather_array('src', ghost_layers=True).shape)
``` ```
%% Output %% Output
Shape of domain (30, 30) Shape of domain (30, 30)
Direct access to arrays (32, 32) Direct access to arrays (32, 32)
Gather (32, 32) Gather (32, 32)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
So the actual arrays are 2 cells larger than what you asked for. This additional layer is used to copy over the data from the other end of the array, such that for the stencil algorithm effectively the domain is periodic. This copying operation has to be started manually though: So the actual arrays are 2 cells larger than what you asked for. This additional layer is used to copy over the data from the other end of the array, such that for the stencil algorithm effectively the domain is periodic. This copying operation has to be started manually though:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh = ps.create_data_handling((4, 4), periodicity=(True, False)) dh = ps.create_data_handling((4, 4), periodicity=(True, False))
dh.add_array("src") dh.add_array("src")
# get copy function # get copy function
copy_fct = dh.synchronization_function(['src']) copy_fct = dh.synchronization_function(['src'])
dh.fill('src', 0.0, ghost_layers=True) dh.fill('src', 0.0, ghost_layers=True)
dh.fill('src', 3.0, ghost_layers=False) dh.fill('src', 3.0, ghost_layers=False)
before_sync = dh.gather_array('src', ghost_layers=True).copy() before_sync = dh.gather_array('src', ghost_layers=True).copy()
copy_fct() # copy over to get periodicity in x direction copy_fct() # copy over to get periodicity in x direction
after_sync = dh.gather_array('src', ghost_layers=True).copy() after_sync = dh.gather_array('src', ghost_layers=True).copy()
plt.subplot(1,2,1) plt.subplot(1,2,1)
plt.scalar_field(before_sync); plt.scalar_field(before_sync);
plt.title("Before") plt.title("Before")
plt.subplot(1,2,2) plt.subplot(1,2,2)
plt.scalar_field(after_sync); plt.scalar_field(after_sync);
plt.title("After"); plt.title("After");
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 3. Going (MPI) parallel - the parallel data handling ## 3. Going (MPI) parallel - the parallel data handling
### 3.1. Conceptual overview ### 3.1. Conceptual overview
To run MPI parallel simulations the waLBerla framework is used. waLBerla has to be compiled against your local MPI library and thus is a bit hard to install. We suggest to use the version shipped with conda for testing. For production, when you want to run on a cluster the best option is to build waLBerla yourself against the MPI library that is installed on your cluster. To run MPI parallel simulations the waLBerla framework is used. waLBerla has to be compiled against your local MPI library and thus is a bit hard to install. We suggest to use the version shipped with conda for testing. For production, when you want to run on a cluster the best option is to build waLBerla yourself against the MPI library that is installed on your cluster.
Now lets have a look on how to write code that runs MPI parallel. Now lets have a look on how to write code that runs MPI parallel.
Since the data is distributed, we don't have access to the full array any more but only to the part that is stored locally. The domain is split into so called blocks, where one process might get one (or sometimes multiple) blocks. To do anything with the local part of the data we iterate over the **local** blocks to get the contents as numpy arrays. The blocks returned in the loop differ from process to process. Since the data is distributed, we don't have access to the full array any more but only to the part that is stored locally. The domain is split into so called blocks, where one process might get one (or sometimes multiple) blocks. To do anything with the local part of the data we iterate over the **local** blocks to get the contents as numpy arrays. The blocks returned in the loop differ from process to process.
Copy the following snippet to a python file and run with multiple processes e.g.: Copy the following snippet to a python file and run with multiple processes e.g.:
``mpirun -np 4 myscript.py`` you will see that there are as many blocks as processes. ``mpirun -np 4 myscript.py`` you will see that there are as many blocks as processes.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh = ps.create_data_handling(domain_size=(30, 30), parallel=True) dh = ps.create_data_handling(domain_size=(30, 30), parallel=True)
field = dh.add_array('field') field = dh.add_array('field')
for block in dh.iterate(): for block in dh.iterate():
# offset is in global coordinates, where first inner cell has coordiante (0,0) # offset is in global coordinates, where first inner cell has coordiante (0,0)
# and ghost layers have negative coordinates # and ghost layers have negative coordinates
print(block.offset, block['field'].shape) print(block.offset, block['field'].shape)
# use offset to create a local array 'my_data' for the part of the domain # use offset to create a local array 'my_data' for the part of the domain
#np.copyto(block[field.name], my_data) #np.copyto(block[field.name], my_data)
``` ```
%% Output %% Output
(-1, -1) (32, 32) (-1, -1) (32, 32)
[0][PROGRESS]------(0.000 sec) Initializing SetupBlockForest:
[0] - AABB: [ <0,0,0>, <30,30,1> ]
[0] - forest size (root blocks / blocks on the initial grid): 1 x 1 x 1
[0] - periodicity: false x false x false
[0][PROGRESS]------(0.000 sec) Initializing SetupBlockForest: Allocating root blocks ...
[0][PROGRESS]------(0.000 sec) Initializing SetupBlockForest: Setting up neighborhood information for each block (with respect to periodicity) ...
[0][PROGRESS]------(0.000 sec) Initializing SetupBlockForest: Assigning workload, memory requirements, and SUIDs to blocks ...
[0][PROGRESS]------(0.000 sec) Initializing SetupBlockForest: finished!
[0] The following block structure has been created:
[0] - AABB: [ <0,0,0>, <30,30,1> ]
[0] - initial decomposition: 1 x 1 x 1 (= forest size)
[0] - periodicity: false x false x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 1 (-> block ID bytes = 1)
[0] - total number of blocks: 1
[0] - blocks have not yet been distributed to processes
[0][PROGRESS]------(0.000 sec) Balancing SetupBlockForest: Creating a process distribution for 1 process(es) ...
[0][PROGRESS]------(0.000 sec) Balancing SetupBlockForest: process distribution to 1 process(es) finished!
[0] - number of worker processes: 1
[0] - number of empty buffer processes: 0
[0] - buffer processes are inserted into the process network: no
[0] The resulting block structure looks like as follows:
[0] - AABB: [ <0,0,0>, <30,30,1> ]
[0] - initial decomposition: 1 x 1 x 1 (= forest size)
[0] - periodicity: false x false x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 1 (-> block ID bytes = 1)
[0] - total number of blocks: 1
[0] - number of processes: 1 (1 worker process(es) / 0 empty buffer process(es))
[0] - buffer processes are inserted into the process network: no
[0] - process ID bytes: 0
[0] - blocks/memory/workload per process:
[0] + blocks:
[0] - min = 1
[0] - max = 1
[0] - avg = 1
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + memory:
[0] - min = 1
[0] - max = 1
[0] - avg = 1
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + workload:
[0] - min = 1
[0] - max = 1
[0] - avg = 1
[0] - stdDev = 0
[0] - relStdDev = 0
[0][PROGRESS]------(0.000 sec) Adding block data ("cell bounding box")
[0][PROGRESS]------(0.000 sec) Adding block data ("field")
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To get some more interesting results here in the notebook we put multiple blocks onto our single notebook process. This makes not much sense for real simulations, but for testing and demonstration purposes this is useful. To get some more interesting results here in the notebook we put multiple blocks onto our single notebook process. This makes not much sense for real simulations, but for testing and demonstration purposes this is useful.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from waLBerla import createUniformBlockGrid from waLBerla import createUniformBlockGrid
from pystencils.datahandling import ParallelDataHandling from pystencils.datahandling import ParallelDataHandling
blocks = createUniformBlockGrid(blocks=(2,1,2), cellsPerBlock=(20, 10, 20), blocks = createUniformBlockGrid(blocks=(2,1,2), cellsPerBlock=(20, 10, 20),
oneBlockPerProcess=False, periodic=(1, 0, 0)) oneBlockPerProcess=False, periodic=(1, 0, 0))
dh = ParallelDataHandling(blocks) dh = ParallelDataHandling(blocks)
field = dh.add_array('field') field = dh.add_array('field')
for block in dh.iterate(): for block in dh.iterate():
print(block.offset, block['field'].shape) print(block.offset, block['field'].shape)
``` ```
%% Output %% Output
(-1, -1, -1) (22, 12, 22) (-1, -1, -1)[0][PROGRESS]------(0.025 sec) Initializing SetupBlockForest:
[0] - AABB: [ <0,0,0>, <40,10,40> ]
[0] - forest size (root blocks / blocks on the initial grid): 2 x 1 x 2
[0] - periodicity: true x false x false
(22, 12, 22)
(19, -1, -1) (22, 12, 22) (19, -1, -1) (22, 12, 22)
(-1, -1, 19) (22, 12, 22) (-1, -1, 19) (22, 12, 22)
(19, -1, 19) (22, 12, 22) (19, -1, 19) (22, 12, 22)
[0][PROGRESS]------(0.025 sec) Initializing SetupBlockForest: Allocating root blocks ...
[0][PROGRESS]------(0.025 sec) Initializing SetupBlockForest: Setting up neighborhood information for each block (with respect to periodicity) ...
[0][PROGRESS]------(0.025 sec) Initializing SetupBlockForest: Assigning workload, memory requirements, and SUIDs to blocks ...
[0][PROGRESS]------(0.025 sec) Initializing SetupBlockForest: finished!
[0] The following block structure has been created:
[0] - AABB: [ <0,0,0>, <40,10,40> ]
[0] - initial decomposition: 2 x 1 x 2 (= forest size)
[0] - periodicity: true x false x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 3 (-> block ID bytes = 1)
[0] - total number of blocks: 4
[0] - blocks have not yet been distributed to processes
[0][PROGRESS]------(0.025 sec) Balancing SetupBlockForest: Creating a process distribution for 1 process(es) ...
[0][PROGRESS]------(0.025 sec) Balancing SetupBlockForest: process distribution to 1 process(es) finished!
[0] - number of worker processes: 1
[0] - number of empty buffer processes: 0
[0] - buffer processes are inserted into the process network: no
[0] The resulting block structure looks like as follows:
[0] - AABB: [ <0,0,0>, <40,10,40> ]
[0] - initial decomposition: 2 x 1 x 2 (= forest size)
[0] - periodicity: true x false x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 3 (-> block ID bytes = 1)
[0] - total number of blocks: 4
[0] - number of processes: 1 (1 worker process(es) / 0 empty buffer process(es))
[0] - buffer processes are inserted into the process network: no
[0] - process ID bytes: 0
[0] - blocks/memory/workload per process:
[0] + blocks:
[0] - min = 4
[0] - max = 4
[0] - avg = 4
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + memory:
[0] - min = 4
[0] - max = 4
[0] - avg = 4
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + workload:
[0] - min = 4
[0] - max = 4
[0] - avg = 4
[0] - stdDev = 0
[0] - relStdDev = 0
[0][PROGRESS]------(0.025 sec) Adding block data ("cell bounding box")
[0][PROGRESS]------(0.026 sec) Adding block data ("field")
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we see that we have four blocks with (20, 10, 20) block each, and the global domain is (40, 10, 40) big. Now we see that we have four blocks with (20, 10, 20) block each, and the global domain is (40, 10, 40) big.
All subblock also have a ghost layer around them, which is used to synchronize with their neighboring blocks (over the network). For ghost layer synchronization the same `synchronization_function` is used that we used above for periodic boundaries, because copying between blocks and copying the ghost layer for periodicity uses the same mechanism. All subblock also have a ghost layer around them, which is used to synchronize with their neighboring blocks (over the network). For ghost layer synchronization the same `synchronization_function` is used that we used above for periodic boundaries, because copying between blocks and copying the ghost layer for periodicity uses the same mechanism.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.gather_array('field').shape dh.gather_array('field').shape
``` ```
%% Output %% Output
$$\left ( 40, \quad 10, \quad 40\right )$$ $\displaystyle \left( 40, \ 10, \ 40\right)$
(40, 10, 40) (40, 10, 40)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### 3.2. Parallel example ### 3.2. Parallel example
To illustrate this in more detail, lets run a simple kernel on a parallel domain. waLBerla can handle 3D domains only, so we choose a z-size of 1. To illustrate this in more detail, lets run a simple kernel on a parallel domain. waLBerla can handle 3D domains only, so we choose a z-size of 1.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
blocks = createUniformBlockGrid(blocks=(2,4,1), cellsPerBlock=(20, 10, 1), blocks = createUniformBlockGrid(blocks=(2,4,1), cellsPerBlock=(20, 10, 1),
oneBlockPerProcess=False, periodic=(1, 1, 0)) oneBlockPerProcess=False, periodic=(1, 1, 0))
dh = ParallelDataHandling(blocks, dim=2) dh = ParallelDataHandling(blocks, dim=2)
src_field = dh.add_array('src') src_field = dh.add_array('src')
dst_field = dh.add_array('dst') dst_field = dh.add_array('dst')
update_rule = [ps.Assignment(lhs=dst_field[0, 0 ], update_rule = [ps.Assignment(lhs=dst_field[0, 0 ],
rhs=(src_field[1, 0] + src_field[-1, 0] + rhs=(src_field[1, 0] + src_field[-1, 0] +
src_field[0, 1] + src_field[0, -1]) / 4)] src_field[0, 1] + src_field[0, -1]) / 4)]
# 3. compile update rule to function # 3. compile update rule to function
kernel_function = ps.create_kernel(update_rule).compile() kernel_function = ps.create_kernel(update_rule).compile()
``` ```
%% Output
[0][PROGRESS]------(0.119 sec) Initializing SetupBlockForest:
[0] - AABB: [ <0,0,0>, <40,40,1> ]
[0] - forest size (root blocks / blocks on the initial grid): 2 x 4 x 1
[0] - periodicity: true x true x false
[0][PROGRESS]------(0.119 sec) Initializing SetupBlockForest: Allocating root blocks ...
[0][PROGRESS]------(0.119 sec) Initializing SetupBlockForest: Setting up neighborhood information for each block (with respect to periodicity) ...
[0][PROGRESS]------(0.119 sec) Initializing SetupBlockForest: Assigning workload, memory requirements, and SUIDs to blocks ...
[0][PROGRESS]------(0.119 sec) Initializing SetupBlockForest: finished!
[0] The following block structure has been created:
[0] - AABB: [ <0,0,0>, <40,40,1> ]
[0] - initial decomposition: 2 x 4 x 1 (= forest size)
[0] - periodicity: true x true x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 4 (-> block ID bytes = 1)
[0] - total number of blocks: 8
[0] - blocks have not yet been distributed to processes
[0][PROGRESS]------(0.119 sec) Balancing SetupBlockForest: Creating a process distribution for 1 process(es) ...
[0][PROGRESS]------(0.119 sec) Balancing SetupBlockForest: process distribution to 1 process(es) finished!
[0] - number of worker processes: 1
[0] - number of empty buffer processes: 0
[0] - buffer processes are inserted into the process network: no
[0] The resulting block structure looks like as follows:
[0] - AABB: [ <0,0,0>, <40,40,1> ]
[0] - initial decomposition: 2 x 4 x 1 (= forest size)
[0] - periodicity: true x true x false
[0] - number of blocks discarded from the initial grid: 0 (= 0 %)
[0] - number of levels: 1
[0] - tree ID digits: 4 (-> block ID bytes = 1)
[0] - total number of blocks: 8
[0] - number of processes: 1 (1 worker process(es) / 0 empty buffer process(es))
[0] - buffer processes are inserted into the process network: no
[0] - process ID bytes: 0
[0] - blocks/memory/workload per process:
[0] + blocks:
[0] - min = 8
[0] - max = 8
[0] - avg = 8
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + memory:
[0] - min = 8
[0] - max = 8
[0] - avg = 8
[0] - stdDev = 0
[0] - relStdDev = 0
[0] + workload:
[0] - min = 8
[0] - max = 8
[0] - avg = 8
[0] - stdDev = 0
[0] - relStdDev = 0
[0][PROGRESS]------(0.119 sec) Adding block data ("cell bounding box")
[0][PROGRESS]------(0.119 sec) Adding block data ("src")
[0][PROGRESS]------(0.120 sec) Adding block data ("dst")
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now lets initialize the arrays. To do this we can get arrays (meshgrids) from the block with the coordinates of the local cells. We use this to initialize a circular shape. Now lets initialize the arrays. To do this we can get arrays (meshgrids) from the block with the coordinates of the local cells. We use this to initialize a circular shape.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dh.fill('src', 0.0) dh.fill('src', 0.0)
for block in dh.iterate(ghost_layers=False, inner_ghost_layers=False): for block in dh.iterate(ghost_layers=False, inner_ghost_layers=False):
x, y = block.midpoint_arrays x, y = block.midpoint_arrays
inside_sphere = (x -20)**2 + (y-25)**2 < 8 ** 2 inside_sphere = (x -20)**2 + (y-25)**2 < 8 ** 2
block['src'][inside_sphere] = 1.0 block['src'][inside_sphere] = 1.0
plt.scalar_field( dh.gather_array('src') ); plt.scalar_field( dh.gather_array('src') );
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we can run our compute kernel on this data as usual. We just have to make sure that the field is synchronized after every step, i.e. that the ghost layers are correctly updated. Now we can run our compute kernel on this data as usual. We just have to make sure that the field is synchronized after every step, i.e. that the ghost layers are correctly updated.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sync = dh.synchronization_function(['src']) sync = dh.synchronization_function(['src'])
for i in range(40): for i in range(40):
sync() sync()
dh.run_kernel(kernel_function) dh.run_kernel(kernel_function)
dh.swap('src', 'dst') dh.swap('src', 'dst')
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plt.scalar_field( dh.gather_array('src') ); plt.scalar_field( dh.gather_array('src') );
``` ```
%% Output %% Output
......
This source diff could not be displayed because it is too large. You can view the blob instead.