Commit 34361997 authored by Jochen Schulz's avatar Jochen Schulz
Browse files

fix performance

parent 1b40a41a
Pipeline #224843 failed with stage
in 13 minutes and 40 seconds
......@@ -25,6 +25,6 @@ launch_buttons:
execute:
execute_notebooks : cache # Whether to execute notebooks at build time. Must be one of ("auto", "force", "cache", "off")
cache : "_build/.jupyter_cache/" # A path to the jupyter cache that will be used to store execution artifacs. Defaults to `_build/.jupyter_cache/`
exclude_patterns : ["README.md", "*.ipynb", "parallelisierung_lecture.md", "parallelisierung_exercise.md", "performance_lecture.md", "performance_exercise.md", "streams_lecture.md"] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time)
exclude_patterns : ["README.md", "*.ipynb", "parallelisierung_lecture.md", "parallelisierung_exercise.md", "streams_lecture.md"] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time)
stderr_output: show
timeout: 240
......@@ -25,6 +25,6 @@ launch_buttons:
execute:
execute_notebooks : cache # Whether to execute notebooks at build time. Must be one of ("auto", "force", "cache", "off")
cache : "_build/.jupyter_cache/" # A path to the jupyter cache that will be used to store execution artifacs. Defaults to `_build/.jupyter_cache/`
exclude_patterns : ["README.md", "*.ipynb", "parallelisierung_lecture.md", "parallelisierung_exercise.md", "performance_lecture.md", "performance_exercise.md", "streams_lecture.md"] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time)
exclude_patterns : ["README.md", "*.ipynb", "parallelisierung_lecture.md", "parallelisierung_exercise.md"] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time)
stderr_output: show
timeout: 240
......@@ -560,6 +560,17 @@ MarkupSafe = ">=2.0"
[package.extras]
i18n = ["Babel (>=2.7)"]
[[package]]
name = "json5"
version = "0.9.6"
description = "A Python implementation of the JSON5 data format."
category = "main"
optional = false
python-versions = "*"
[package.extras]
dev = ["hypothesis"]
[[package]]
name = "jsonschema"
version = "3.2.0"
......@@ -756,6 +767,49 @@ nbconvert = ">=5.5"
nbformat = "*"
Sphinx = ">=2"
[[package]]
name = "jupyterlab"
version = "3.1.9"
description = "JupyterLab computational environment"
category = "main"
optional = false
python-versions = ">=3.6"
[package.dependencies]
ipython = "*"
jinja2 = ">=2.1"
jupyter-core = "*"
jupyter-server = ">=1.4,<2.0"
jupyterlab-server = ">=2.3,<3.0"
nbclassic = ">=0.2,<1.0"
packaging = "*"
tornado = ">=6.1.0"
[package.extras]
test = ["coverage", "pytest (>=6.0)", "pytest-cov", "pytest-console-scripts", "pytest-check-links (>=0.5)", "jupyterlab-server[test] (>=2.2,<3.0)", "requests", "requests-cache", "virtualenv", "check-manifest"]
ui-tests = ["build"]
[[package]]
name = "jupyterlab-server"
version = "2.7.2"
description = "A set of server components for JupyterLab and JupyterLab like applications ."
category = "main"
optional = false
python-versions = ">=3.6"
[package.dependencies]
babel = "*"
entrypoints = ">=0.2.2"
jinja2 = ">=2.10"
json5 = "*"
jsonschema = ">=3.0.1"
jupyter-server = ">=1.4,<2.0"
packaging = "*"
requests = "*"
[package.extras]
test = ["codecov", "ipykernel", "pytest (>=5.3.2)", "pytest-cov", "jupyter-server", "openapi-core (>=0.14.0,<0.15.0)", "pytest-console-scripts", "strict-rfc3339", "ruamel.yaml", "wheel"]
[[package]]
name = "jupyterlab-widgets"
version = "1.0.0"
......@@ -801,6 +855,22 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
[package.dependencies]
six = ">=1.4.1"
[[package]]
name = "line-profiler"
version = "3.3.0"
description = "Line-by-line profiler."
category = "main"
optional = false
python-versions = "*"
[package.dependencies]
IPython = {version = ">=0.13", markers = "python_version >= \"3.7\""}
[package.extras]
all = ["cython", "cmake", "coverage[toml] (>=5.3)", "ninja", "pytest-cov (>=2.10.1)", "pytest (>=4.6.11)", "scikit-build", "ubelt (>=0.8.7)", "IPython (>=0.13,<7.17.0)", "IPython (>=0.13)"]
build = ["cython", "cmake", "ninja", "scikit-build"]
tests = ["coverage[toml] (>=5.3)", "pytest-cov (>=2.10.1)", "pytest (>=4.6.11)", "ubelt (>=0.8.7)"]
[[package]]
name = "linkify-it-py"
version = "1.0.1"
......@@ -991,6 +1061,21 @@ linkify = ["linkify-it-py (>=1.0,<2.0)"]
rtd = ["ipython", "sphinx-book-theme (>=0.1.0,<0.2.0)", "sphinx-panels (>=0.5.2,<0.6.0)", "sphinxcontrib-bibtex (>=2.1,<3.0)"]
testing = ["beautifulsoup4", "coverage", "docutils (>=0.17.0,<0.18.0)", "pytest (>=3.6,<4)", "pytest-cov", "pytest-regressions"]
[[package]]
name = "nbclassic"
version = "0.3.1"
description = "Jupyter Notebook as a Jupyter Server Extension."
category = "main"
optional = false
python-versions = ">=3.6"
[package.dependencies]
jupyter-server = ">=1.8,<2.0"
notebook = "<7"
[package.extras]
test = ["pytest", "pytest-tornasync", "pytest-console-scripts"]
[[package]]
name = "nbclient"
version = "0.5.3"
......@@ -2142,7 +2227,7 @@ testing = ["pytest (>=4.6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytes
[metadata]
lock-version = "1.1"
python-versions = ">=3.9,<3.10"
content-hash = "db632ffad1fc047057f3b419008f5d9db77e3f1fd2b7df8d9e23164c025f1fd3"
content-hash = "554ab2bcdc17a2fe41b8a402527122563ce80b30c61f4e94db72ae0831c67c5e"
[metadata.files]
alabaster = [
......@@ -2478,6 +2563,10 @@ jinja2 = [
{file = "Jinja2-3.0.1-py3-none-any.whl", hash = "sha256:1f06f2da51e7b56b8f238affdd6b4e2c61e39598a378cc49345bc1bd42a978a4"},
{file = "Jinja2-3.0.1.tar.gz", hash = "sha256:703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4"},
]
json5 = [
{file = "json5-0.9.6-py2.py3-none-any.whl", hash = "sha256:823e510eb355949bed817e1f3e2d682455dc6af9daf6066d5698d6a2ca4481c2"},
{file = "json5-0.9.6.tar.gz", hash = "sha256:9175ad1bc248e22bb8d95a8e8d765958bf0008fef2fe8abab5bc04e0f1ac8302"},
]
jsonschema = [
{file = "jsonschema-3.2.0-py2.py3-none-any.whl", hash = "sha256:4e5b3cf8216f577bee9ce139cbe72eca3ea4f292ec60928ff24758ce626cd163"},
{file = "jsonschema-3.2.0.tar.gz", hash = "sha256:c8a85b28d377cc7737e46e2d9f2b4f44ee3c0e1deac6bf46ddefc7187d30797a"},
......@@ -2519,6 +2608,14 @@ jupyter-sphinx = [
{file = "jupyter_sphinx-0.3.2-py3-none-any.whl", hash = "sha256:301e36d0fb3007bb5802f6b65b60c24990eb99c983332a2ab6eecff385207dc9"},
{file = "jupyter_sphinx-0.3.2.tar.gz", hash = "sha256:37fc9408385c45326ac79ca0452fbd7ae2bf0e97842d626d2844d4830e30aaf2"},
]
jupyterlab = [
{file = "jupyterlab-3.1.9-py3-none-any.whl", hash = "sha256:370545a6a33eb50db3f60bdd5e46ca690b2a7fb09145a5df0fc00dd0a40d06d2"},
{file = "jupyterlab-3.1.9.tar.gz", hash = "sha256:007e42f833e59fd36872d459e45be243d899edbd0e4a98d21388632e4e0d8af7"},
]
jupyterlab-server = [
{file = "jupyterlab_server-2.7.2-py3-none-any.whl", hash = "sha256:4832cb513f969087019dc913e59a430325670a69f2693733e8f1e16a1773be85"},
{file = "jupyterlab_server-2.7.2.tar.gz", hash = "sha256:c6c9ae5796ed60c65bccd84503cbd44b9e35b046b8265f24db3cc4d61631fc0d"},
]
jupyterlab-widgets = [
{file = "jupyterlab_widgets-1.0.0-py3-none-any.whl", hash = "sha256:caeaf3e6103180e654e7d8d2b81b7d645e59e432487c1d35a41d6d3ee56b3fef"},
{file = "jupyterlab_widgets-1.0.0.tar.gz", hash = "sha256:5c1a29a84d3069208cb506b10609175b249b6486d6b1cbae8fcde2a11584fb78"},
......@@ -2565,6 +2662,49 @@ latexcodec = [
{file = "latexcodec-2.0.1-py2.py3-none-any.whl", hash = "sha256:c277a193638dc7683c4c30f6684e3db728a06efb0dc9cf346db8bd0aa6c5d271"},
{file = "latexcodec-2.0.1.tar.gz", hash = "sha256:2aa2551c373261cefe2ad3a8953a6d6533e68238d180eb4bb91d7964adb3fe9a"},
]
line-profiler = [
{file = "line_profiler-3.3.0-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:2ac36ea20afc34d0f36300236baff447598bdee7143fb55aa2fcde72dfbfd8df"},
{file = "line_profiler-3.3.0-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:aa220334ee3d7dcb4f307064233b8d3455e0158e16a4389ad3ca57f9b2630373"},
{file = "line_profiler-3.3.0-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:fc47db8b6b1da5c769cf4af0e8841f29e6d9b581df293188be4ed49793eb176c"},
{file = "line_profiler-3.3.0-cp35-cp35m-manylinux2010_i686.whl", hash = "sha256:6b406cc1c93429ef761fe0cfa2aab3f6c341e736879e14578bb67c8e65801e35"},
{file = "line_profiler-3.3.0-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:d39b709a49c1cff1936afc7f5987e44fa0bd57d4018597d44baa3652fab05d3d"},
{file = "line_profiler-3.3.0-cp35-cp35m-manylinux2014_aarch64.whl", hash = "sha256:09d90ab8412df2b7e38561882d51ea5bd98215746df044dd651922e0dac27a8f"},
{file = "line_profiler-3.3.0-cp35-cp35m-win32.whl", hash = "sha256:2c8e0e8c2dd1f3a37c7eee9aa5178baf9ca3c3e2fbd4b497fb828f05e51e40c5"},
{file = "line_profiler-3.3.0-cp35-cp35m-win_amd64.whl", hash = "sha256:881570ff4523b1fec33716638aeade4eb151cf45c2ee1ae8783f1882605f4901"},
{file = "line_profiler-3.3.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:2b910d0cb75c242ec3a7849a1a9ec267f05968e42e6ad8366b76acbc0a13140b"},
{file = "line_profiler-3.3.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:f04d6180aa65abedca61f64bd0d4508769fbd755c9dc72153b55172dd0a94135"},
{file = "line_profiler-3.3.0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:bf30edb986ad21889a8844eb2917178f83adc08f4af0d79cab165bf90dc9a94f"},
{file = "line_profiler-3.3.0-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:946af02e5e2f39ebb433e08c544fcd62e74e3ff3ad05270848421f01e496fba6"},
{file = "line_profiler-3.3.0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:7f931cf6e89a48e33575956799397b277c3b479c7d8976ab7ec0d9f236cec96d"},
{file = "line_profiler-3.3.0-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:6e1aa3047b208369aaf40444d744a62ce08b60893419bf770e6ea8ae9efdd58f"},
{file = "line_profiler-3.3.0-cp36-cp36m-win32.whl", hash = "sha256:de7d7f9c3579c07d9d22caaf50a0e2232d1998d8fba7e97f9fba5ce1500d0ccc"},
{file = "line_profiler-3.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:120fda083250396982da428f72394bc95eebd43f2439b6d0f9df2c07a3cad9d8"},
{file = "line_profiler-3.3.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:46fcc9473a7fcd27297ec172e9f4e9975dfd688c6ab13fbc201f1d0b01617034"},
{file = "line_profiler-3.3.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:51415de78640627fd8ca95988ee496013f45099bdfde6021a267da2df39cd770"},
{file = "line_profiler-3.3.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:b2cc81e91b1556b0922cf7e5f8c3af163c82e989384f38d8352527d9ebe5cc71"},
{file = "line_profiler-3.3.0-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:3ac6991b4a24558dc24cb4fdd259fbd49ebe0a60873f2e227ed5f880284abc5f"},
{file = "line_profiler-3.3.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:3f4ceb262ae1bd64909d773cc0f3b9e7cd58f83eb6ded71bba52d3fd98028311"},
{file = "line_profiler-3.3.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:834afb47113a36e658ef94243ebb905b8d7c6d6e35811cc74cff0d2c35d63a07"},
{file = "line_profiler-3.3.0-cp37-cp37m-win32.whl", hash = "sha256:4e21f1e9c56faeca4c92d5f9c1113576a5ebbb1f855de0a0a322274d6086d222"},
{file = "line_profiler-3.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:ce9d1db1f8f24527c0893414a3cbbd72d492e81e9befab23387505fc7845501a"},
{file = "line_profiler-3.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9628b5450707390aa188bb499e1dde1147d3b7e3671bf7cf43344c5bbd89d749"},
{file = "line_profiler-3.3.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:02382a5e537902cb7af934c7f1e30710ef28b6081b3d24a0c610ac0869418b92"},
{file = "line_profiler-3.3.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:d9d0377b24869a205676047cb7659a350d466d423d7784d5a9490c8cd981fc0b"},
{file = "line_profiler-3.3.0-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:cbe05dcf635be9d91599dc5dcbbf4fe805ad19eb661f465a7c2cc2f65081a89b"},
{file = "line_profiler-3.3.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:7c75fc1286b71cb1147ffedb8c8bff7a258333bbcc03e75fad39321211926a8f"},
{file = "line_profiler-3.3.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:62a3030e3060ea63d2af08c9ae23e69a33ac2f6b3084e7fc34b8bb93b311fd75"},
{file = "line_profiler-3.3.0-cp38-cp38-win32.whl", hash = "sha256:6c235dd6cdeeacb9764a6e95d788ee3db9b772389beb4738f4df3a0bdd90ebf5"},
{file = "line_profiler-3.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:11eb4efcb431f449afeb701345e97b168c9668d628c6381a8139ddd6b3f8ff2a"},
{file = "line_profiler-3.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:91403fc8096ff43de81eca4105e1d827199bc2e577a8904987d10f35b5232175"},
{file = "line_profiler-3.3.0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:783bc84a49241f8902e2766a8b4708b235ac7f4667cb106db5b5368f3b69c4d9"},
{file = "line_profiler-3.3.0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:2e66ab84027f368031a1fab08e1f9002bf39f689680990086c5b4b25b594ffa3"},
{file = "line_profiler-3.3.0-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:463718de882bce16c467458db9b98e5e0d0457a35849bb96e66990e4e2a9765b"},
{file = "line_profiler-3.3.0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:c59b33741374989ffe57249d079fd852c33cc354fa9e6652a372dedc7d941edc"},
{file = "line_profiler-3.3.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:8b927dd2e22eb50b55f2f46bdadafb856ad0f3290c09aaa810100baaed63af63"},
{file = "line_profiler-3.3.0-cp39-cp39-win32.whl", hash = "sha256:c16772530005f4bccf81976f8dd0299832cfb5ab7997b564b8ec56f0d014f013"},
{file = "line_profiler-3.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:8a2e551dc71a277518eaaf7e885e4ec399047f1ac92275d601e6e771c026e7e9"},
{file = "line_profiler-3.3.0.tar.gz", hash = "sha256:8bd8353e9403b226def4438dbfdb57cafefb24488e49a6039cc63906c0bc8836"},
]
linkify-it-py = [
{file = "linkify-it-py-1.0.1.tar.gz", hash = "sha256:90b632ee516bf523c007ee96aa14ffc7efe1ca4074a80b0df366d66922d6d087"},
{file = "linkify_it_py-1.0.1-py3-none-any.whl", hash = "sha256:29ba044d36f0ff938730a8167b7341a7caffc3e11666f9009996af6b82b61dfc"},
......@@ -2715,6 +2855,10 @@ myst-parser = [
{file = "myst-parser-0.13.7.tar.gz", hash = "sha256:e4bc99e43e19f70d22e528de8e7cce59f7e8e7c4c34dcba203de92de7a7c7c85"},
{file = "myst_parser-0.13.7-py3-none-any.whl", hash = "sha256:260355b4da8e8865fe080b0638d7f1ab1791dc4bed02a7a48630b6bad4249219"},
]
nbclassic = [
{file = "nbclassic-0.3.1-py3-none-any.whl", hash = "sha256:a7437c90a0bffcce172a4540cc53e140ea5987280c87c31a0cfa6e5d315eb907"},
{file = "nbclassic-0.3.1.tar.gz", hash = "sha256:f920f8d09849bea7950e1017ff3bd101763a8d68f565a51ce053572e65aa7947"},
]
nbclient = [
{file = "nbclient-0.5.3-py3-none-any.whl", hash = "sha256:e79437364a2376892b3f46bedbf9b444e5396cfb1bc366a472c37b48e9551500"},
{file = "nbclient-0.5.3.tar.gz", hash = "sha256:db17271330c68c8c88d46d72349e24c147bb6f34ec82d8481a8f025c4d26589c"},
......
......@@ -22,6 +22,8 @@ dask = "^2021.7.2"
distributed = "^2021.7.2"
numba = "^0.53.1"
bokeh = "^2.3.3"
line-profiler = "^3.3.0"
jupyterlab = "^3.1.9"
[tool.poetry.dev-dependencies]
......
......@@ -3,8 +3,10 @@ jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.10.3
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
---
......@@ -13,16 +15,18 @@ kernelspec:
Wir kennen das...
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
a = [1, 2, 3]
a[3]
```
Hier wurde eine **Exception** ausgelöst, die den aufgetretenen Fehler repräsentiert. Die Exception hat hier die Klasse `IndexError`, es handelt sich also um einen Indizierungs-Fehler.
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
def function_with_error():
print('Start')
print(1 / 0)
......@@ -65,12 +69,13 @@ Weder `except` noch `finally` muss verwendet werden, allerdings mindestens eins
- Allerdings: die Befehle im `finally`-Block werden *in jedem Fall* ausgeführt, egal ob ein Fehler ausgelöst wurde oder nicht oder ob der Fehler behandelt wurde oder nicht.
```{code-cell}
```{code-cell} ipython3
a = [1, 2, 3]
try:
print(a[3])
print(a)
except IndexError as e:
print('Error occured: {}'.format(str(e)))
print('Error occured: {}'.format(str(e)))
```
### Propagation von Exceptions
......@@ -81,7 +86,7 @@ Ungewöhnlich dabei ist, dass die Verschachtelung der `try`-`except`-Blöcke nic
#### Beispiel (etwas künstlich...)
```{code-cell}
```{code-cell} ipython3
def eval_string(s):
"""Zerlegt einen String der Form 'x op y', wobei
x und y Darstellungen von Integern sind und op +, -,
......@@ -123,20 +128,21 @@ Die Fehler werden im Folgenden immer in `eval_string` ausgelöst, aber an unters
- Ungültige Eingabe: `eval_string` wird beendet, `eval_list` behandelt den Fehler.
```{code-cell}
```{code-cell} ipython3
print(sum_of_list(['1 + 2', 'drei * vier', '5 / 6', '7-8']))
```
- Division durch 0: `eval_string` und `eval_list` werden beendet, `sum_of_list` behandelt den Fehler.
```{code-cell}
```{code-cell} ipython3
print(sum_of_list(['1 / 0']))
```
- Eingabe ist kein String: der Fehler wird nicht behandelt, alle Funktionen werden beendet, die Notebook-Zelle wird beendet. Jupyter behandelt den Fehler implizit. Ein eigenständiges Programm würde hier abbrechen.
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
print(sum_of_list([12, 13, 14]))
print('Fertig.')
```
......@@ -180,8 +186,9 @@ Eine Exception wird mit `raise` ausgelöst. Das Exception-Objekt muss eine Insta
Wie genau die Exception-Instanzen erzeugt werden, hängt von der konkreten Klasse ab. Meist nehmen sie allerdings ein einzelnes String-Argument als Fehlermeldung.
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
raise ValueError('Illegal input')
```
......@@ -195,8 +202,9 @@ raise
ohne Argument verwenden. In diesem Fall wird die aktuelle Exception neu ausgelöst und propagiert weiter. Das ist nützlich, wenn man auf die Exception reagieren will, aber nicht letztenendes entscheiden kann, ob der Fehler ignoriert werden soll. In diesem Fall muss ggf. darüberliegender Code ebenfalls auf die Exception reagieren.
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
try:
raise ValueError('Something went wrong')
except:
......@@ -214,20 +222,22 @@ Exceptions werden oft ausgelöst, wenn bestimmte Bedingungen nicht erfüllt sind
`assert` überprüft die `<Bedingung>`. Wird diese zu einem *falschen* Wert ausgewertet, wird eine `AssertionError`-Exception ausgelöst, optional mit der gegebenen Fehlermeldung.
```{code-cell}
```{code-cell} ipython3
def first_element(lst):
assert isinstance(lst, list), 'wrong type argument'
assert lst, 'list is empty'
return lst[0]
```
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
first_element(123)
```
```{code-cell}
:tags: ["raises-exception"]
```{code-cell} ipython3
:tags: [raises-exception]
first_element([])
```
......
......@@ -3,15 +3,17 @@ jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.10.3
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
---
# Interpolation
```{code-cell}
```{code-cell} ipython3
import numpy as np
import scipy.linalg as spl
import scipy.interpolate as spi
......@@ -65,7 +67,7 @@ erzeugt die Vandermonde-Matrix mit `m` Spalten (d.h. mit Ordnung `n = m-1`) für
Interpolation von $y_k = (1 + x_k^2)^{-1}$ mit `x = linspace(-5, 5, 13)`.
```{code-cell}
```{code-cell} ipython3
interp_x = np.linspace(-5, 5, 13)
interp_y = 1 / (1 + interp_x**2)
......@@ -93,7 +95,7 @@ Die Koeffizienten sind umgekehrt über das Attribut `.coeffs` verfügbar.
**Beispiel: Plot des Interpolationspolynoms**
```{code-cell}
```{code-cell} ipython3
# Hilfsfunktion zum Plotten
import holoviews as hv
......@@ -109,7 +111,7 @@ def plot_with_points(f, label=None):
)).relabel(label)
```
```{code-cell}
```{code-cell} ipython3
P = np.poly1d(p)
print('P(4.5) = {}'.format(P(4.5)))
plot_with_points(P, 'Polynom-Interpolation')
......@@ -117,7 +119,7 @@ plot_with_points(P, 'Polynom-Interpolation')
**Beispiel: Polynomdivision**
```{code-cell}
```{code-cell} ipython3
# Polynom mit 3 Nullstellen
P1 = np.poly1d([-1, 1, 2], True)
......@@ -143,12 +145,12 @@ Für komplexere Polynom-Algebra sollte man allerdings eher SymPy verwenden.
numpy.roots(poly)
```
```{code-cell}
```{code-cell} ipython3
rs = np.roots(P)
print(rs)
```
```{code-cell}
```{code-cell} ipython3
max(abs(P(rs)))
```
......@@ -165,7 +167,7 @@ scipy.interpolate.KroghInterpolator(x, y)
Beide liefern ein Objekt zurück, das sich wie eine Funktion zum Auswerten an beliebigen Punkten nutzen lässt.
```{code-cell}
```{code-cell} ipython3
P = spi.BarycentricInterpolator(interp_x, interp_y)
print('P(4.5) = {}'.format(P(4.5)))
```
......@@ -197,7 +199,7 @@ Möglichkeiten für `kind`:
Höhere Ordnungen führen nicht zwangsläufig zu besseren Ergebnissen.
```{code-cell}
```{code-cell} ipython3
hv.Layout([
plot_with_points(spi.interp1d(interp_x, interp_y, kind=kind), label=str(kind))
for kind in ['nearest', 'linear', 'quadratic', 'cubic', 5, 7]
......@@ -224,7 +226,7 @@ erfüllen.
**Beispiel: Fitting eines Polynoms vom Grad $n = 6$**
```{code-cell}
```{code-cell} ipython3
V = np.vander(interp_x, 7)
P = np.poly1d(spl.solve(V.T @ V, V.T @ interp_y))
......@@ -241,7 +243,7 @@ numpy.polyfit(x, y, n)
Das Resultat ist ein Koeffizienten-Array, aus dem man mit `poly1d` ein Polynom-Objekt erzeugen kann.
```{code-cell}
```{code-cell} ipython3
P = np.poly1d(np.polyfit(interp_x, interp_y, 6))
plot_with_points(P, 'Polynom-Fit')
......@@ -258,12 +260,12 @@ scipy.interpolate.UnivariateSpline(x, y, s=None)
- `x, y`: wie gehabt die Datenpunkte, die bekannt sind
- `s`: Glättungsfaktor (*smoothing factor*); steuert, wieviele Punkte für die Splineinterpolation genutzt werden. Kleiner bedeutet mehr Punkte.
```{code-cell}
```{code-cell} ipython3
f = spi.UnivariateSpline(interp_x, interp_y)
plot_with_points(f, 'Spline-Fit')
```
```{code-cell}
```{code-cell} ipython3
f = spi.UnivariateSpline(interp_x, interp_y, s=0.2)
plot_with_points(f, 'Spline-Fit')
```
......@@ -299,7 +301,7 @@ Allgemeiner funktionieren auch Daten in `d` Dimensionen, wenn `points` und `xi`
Für die `'linear'`- und `'cubic'`-Methoden kann nur auf die *konvexe Hülle* der gegebenen `points` interpoliert werden. An anderen Punkten von `xi` wird `NaN` zurückgegeben. Für den Umgang damit kann die Funktion `numpy.isnan` nützlich sein (s.u.).
```{code-cell}
```{code-cell} ipython3
def f(x, y):
return np.cos(4*np.pi*x) * np.sin(4*np.pi*y)
......@@ -311,7 +313,7 @@ values = f(*points.T)
X, Y = np.ogrid[0:1:50j, 0:1:50j]
```
```{code-cell}
```{code-cell} ipython3
hv.Layout((
hv.Image((X.ravel(), Y.ravel(), f(X, Y).T)),
hv.Scatter(
......@@ -323,7 +325,7 @@ hv.Layout((
))
```
```{code-cell}
```{code-cell} ipython3
# (n, 2)-Array mit den Koordinaten aller Punkte
xfull, yfull = np.broadcast_arrays(X, Y)
xi = np.stack((xfull.ravel(), yfull.ravel()), axis=1)
......@@ -339,7 +341,7 @@ hv.Layout(gr).cols(2)
Umgang mit `NaN`, z.B. Fortsetzen als 0 auf Außenbereich:
```{code-cell}
```{code-cell} ipython3
p[np.isnan(p)] = 0
hv.Image((X.ravel(), Y.ravel(), p.T))
```
......@@ -350,26 +352,26 @@ Arrays können auch durch sogenannte **Boolsche Masken** indiziert werden, d.h.
Das ist besonders nützlich in Verbindung mit Vergleichsoperatoren, deren Resultat Bool-Arrays sind (s.o.).
```{code-cell}
```{code-cell} ipython3
a = np.arange(25).reshape((5, 5))
a % 2 == 0
```
```{code-cell}
```{code-cell} ipython3
b = a[a % 2 == 0]
b
```
Masken können auch auf der linken Seite einer Zuweisung verwendet werden.
```{code-cell}
```{code-cell} ipython3
a[a % 2 == 0] = -1
a
```
Darüber hinaus können Masken auch nur entlang einer einzelnen Achse eingesetzt werden.
```{code-cell}
```{code-cell} ipython3
a = np.arange(25).reshape((5, 5))
mask = np.array([True, True, False, True, False])
......@@ -387,8 +389,13 @@ array_object.any(axis=None)
Das `axis`-Argument funktioniert wie bei anderen Reduktionen (`sum`, `mean`, etc).
```{code-cell}
```{code-cell} ipython3
a = np.arange(25).reshape(5, 5)
print(a)
print(a <= 2)
(a <= 2).any(axis=0)
```
```{code-cell} ipython3
```
......@@ -3,8 +3,10 @@ jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.10.3
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
---
......@@ -12,7 +14,7 @@ kernelspec:
(nichtlinear)=
# Nichtlineare Gleichungen
```{code-cell}
```{code-cell} ipython3
import numpy as np
import scipy as sp
import scipy.optimize as spopt
......@@ -55,7 +57,7 @@ Die Rückgabe der Funktion enthält mehrere Attribute:
$x \cdot e^x - 1 = 0$
```{code-cell}
```{code-cell} ipython3
def f(x):
return x * np.exp(x) - 1
......@@ -63,7 +65,7 @@ res = spopt.root(f, [1])
res
```
```{code-cell}
```{code-cell} ipython3
%output size=150
x = np.linspace(-0.5, 1.5, 100)
......@@ -76,7 +78,7 @@ $\begin{cases} x^2 \cdot y = 2 \\ x \cdot y^2 = 1 \end{cases}$
Hier wollen wir auch die Jacobi-Matrix benutzen. Wir haben vor ein paar Vorlesungen `SymPy` kennengelernt, wodurch wir Ableitungen symbolisch ausrechnen können. Das nutzen wir nun. Insbesondere bei komplexeren Funktionen/Gleichungen wollen wir die Jacobi-Matrix nicht mehr selbst ausrechnen.
```{code-cell}
```{code-cell} ipython3
x, y = sy.symbols('x, y')
fsym = sy.Matrix([x**2 * y - 2, x * y**2 - 1])
dfsym = fsym.jacobian((x, y))
......@@ -85,7 +87,7 @@ dfsym
Die symbolische Funktion und die Jacobi-Matrix sind so noch nicht für die numerischen Algorithmen auf effiziente Weite nutzbar. Wir müssen sie wieder mit lambdify zu numerisch auswertbaren Funktionen konvertieren. Der 2. Schritt zur Transformation der Argumente und Rückgabewerte ist nötig, damit sie zu den Anforderungen von `root` passen.
```{code-cell}
```{code-cell} ipython3
f_l = sy.lambdify([x, y], fsym)
F = lambda x: f_l(x[0], x[1]).ravel()
......@@ -95,14 +97,14 @@ DF = lambda x: df_l(x[0], x[1])
Nun können wir diese Funktion mit symbolisch differenzierter Jacobi-Matrix in unserem Algorithmus nutzen:
```{code-cell}
```{code-cell} ipython3
res = spopt.root(F, np.array([1, 1]), jac=DF)
res
```
Zur visuellen Kontrolle plotten wir die Norm von `f`.
```{code-cell}
```{code-cell} ipython3
%%output size=150
X, Y = np.mgrid[-1:2:100j, -1:2:100j]
......@@ -146,7 +148,7 @@ scipy.optimize.minimize(func, x0, method=None, jac=None, hess=None, bounds=None,
- `bounds`: Grenzen für die Werte
- `constraints`: Nebenbedingungen. Schauen wir uns hier erstmal nicht weiter an.
```{code-cell}
```{code-cell} ipython3
res2 = spopt.minimize(lambda x: normf(x[0], x[1])**2, np.array([1, 1]))
res2
```
......@@ -173,7 +175,7 @@ $$