diff --git a/.github/workflows/myst-to-pages.yml b/.github/workflows/myst-to-pages.yml new file mode 100644 index 0000000..aa011df --- /dev/null +++ b/.github/workflows/myst-to-pages.yml @@ -0,0 +1,80 @@ +# NOTE THAT in addition to this file, you need to check on github.com +# - enable github pages (select deploy from a branch) +# - go to the Settings -> Environments tab +# then select the 'github-pages' environment +# and make sure the branch of interest (here main) is allowed in the 'Branch protection rules' area +# - also for using a self-hosted runner, make sure you have set it up properly +# github.com/$ORGA -> Settings -> Actions -> Runner groups -> Default Group -> Allow public repositories + +name: Deploy MyST to GitHub Pages + +on: + # Allows manual trigger + workflow_dispatch: + push: + branches: + - main + + +# the following sets permissions of the GITHUB_TOKEN +# to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +# this is no longer needed as we serve from hostnames +# in our own domain info-mines.paris +# env: +# BASE_URL: /${{ github.event.repository.name }} + + +jobs: + build-and-deploy: + runs-on: self-hosted + container: + image: dockerhub.pl.sophia.inria.fr/python-nodejs:latest + # this is so we can use source + defaults: + run: + shell: bash + steps: + - name: Checkout repository + uses: actions/checkout@v5 + - name: "Python venv & requirements.txt" + run: | + python3 -m venv venv + source venv/bin/activate + if [ -f requirements.txt ]; then + pip install -r requirements.txt + fi + - name: Install MyST Markdown + run: | + source venv/bin/activate + npm install mystmd thebe-core thebe thebe-lite + - name: Setup Graphviz + uses: ts-graphviz/setup-graphviz@v2 + - name: Build HTML Assets + run: | + source venv/bin/activate + cd notebooks + npx myst build --execute --html --execute-parallel 1 + - name: Setup Pages + uses: actions/configure-pages@v5 + - name: Upload artifact + uses: actions/upload-pages-artifact@v4 + with: + path: './notebooks/_build/html' + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} diff --git a/.nbhosting/Dockerfile b/.nbhosting/Dockerfile deleted file mode 100644 index 50e2156..0000000 --- a/.nbhosting/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -# -------- -# using scipy, it's kinda big but that should not be a problem -# base-notebook lacks at least numpy, widgets, so... -FROM nbhosting/minimal-notebook - -# NOTE -# we cannot use jupyter nbextension enable/disable -# because we provide our own nbconfig/notebook.json -# and that is where is stored the enabled/disabled extensions -RUN true \ - && pip install jupyterlab notebook jupytext jupyterlab-myst \ - && pip install jupyterlab-courselevels \ - && pip install nbautoeval ipythontutor \ - && pip install numpy pandas matplotlib ipywidgets ipympl \ - && pip install folium \ - && apt-get install -y graphviz && pip install graphviz \ - && true diff --git a/.nbhosting/nbhosting.yaml b/.nbhosting/nbhosting.yaml deleted file mode 100644 index fd2ee7d..0000000 --- a/.nbhosting/nbhosting.yaml +++ /dev/null @@ -1,93 +0,0 @@ -# you may want to redefine locally either -# - the list of tracks as tracks-filter -# - and the list of builds as builds-filter -# typically -# tracks-filter: [ python ] -# builds-filter: [ python ] -# or -# tracks-filter: [ data-science ] -# builds-filter: [ data-science ] - -# we define 2 tracks - python and data-science -# each corresponding to one jupyter-book -tracks: -- description: Python - activités - id: python - name: Python - sections: - - name: exercices basiques - notebooks: - - notebooks/exos/basic/EXO-ipsplit-nb - - notebooks/exos/basic/EXO-skimlist-readme-nb - - notebooks/exos/basic/EXO-invoice-nb - - notebooks/exos/basic/README-agenda-nb - - notebooks/exos/basic/README-adnpercents-nb - - notebooks/exos/basic/EXO-files-sortby-nb - - notebooks/exos/basic/EXO-randomdate-readme-nb - - notebooks/exos/basic/EXO-wordcounts-readme-nb - - name: howtos - notebooks: - - notebooks/howtos/encodings/HOWTO-encodings-nb - - notebooks/howtos/requests/HOWTO-requests-nb - - notebooks/howtos/adnwalk/HOWTO-adnwalk-nb - - notebooks/howtos/subprocesses/HOWTO-subprocesses-nb - - name: TPs basiques - notebooks: - - notebooks/tps/files-formats/README-files-formats-nb - - notebooks/tps/watson/README-watson-nb - - notebooks/tps/parse-people/README-parse-people-nb - - notebooks/tps/indexing-structs/README-indexing-structs-nb - - notebooks/tps/queens/README-queens-nb - - name: TPs classes - notebooks: - - notebooks/tps/students-grades/README* - - notebooks/tps/auctions/README* - - notebooks/tps/unicode-boxes/README* - - notebooks/tps/expressions-lang/README* - - name: TPs graphes - notebooks: - - notebooks/tps/graph-bfs-dfs/README* - - notebooks/tps/graph-shortest-path/README* - - notebooks/tps/metro/README-metro-nb - - notebooks/tps/pagerank-thrones/README* - - notebooks/tps/puzzle8/README-* - - name: TPs visu & games - notebooks: - - notebooks/tps/snake/README* - - notebooks/tps/boids/README* - - notebooks/tps/chatbot/README* - - notebooks/tps/redis/README* - - notebooks/tps/motus/README* - - notebooks/tps/dobble/README* - - name: lecture de code - notebooks: - - notebooks/reading/snake/snake - - name: avancés - notebooks: - - notebooks/exos/advanced/EXO-attributes-proxy-nb - - notebooks/exos/advanced/EXO-attributes-dynprop-nb - - name: sample code - notebooks: - - notebooks/samples/* - - name: WIP - notebooks: - - notebooks/tps/subprocesses-howto - - notebooks/tps/webscraper-wip/README* -builds: -- id: python - name: Python - description: exos on core Python - external_url: https://flotpython-exos-python.readthedocs.io/ -# directory: . -# script: | -# pip install jupyter-book -# jupyter-book build --toc jb/python/_toc.yml --config jb/_config.yml . -- id: data-science - name: Data Science - description: exos on numpy, pandas, dataviz - external_url: https://flotpython-exos-ds.readthedocs.io/ -# directory: . -# script: | -# pip install jupyter-book -# pip install sphinx-exercise -# jupyter-book build --toc jb/ds/_toc.yml --config jb/_config.yml . diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..74c9c28 --- /dev/null +++ b/LICENSE @@ -0,0 +1,6 @@ +Copyright (c) Thierry Parmentelat + +This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike +4.0 International License. To view a copy of this license, visit +http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative +Commons, PO Box 1866, Mountain View, CA 94042, USA. diff --git a/README.md b/README.md index 6502a25..2c5228f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ a collection of exercises, TPs and miscell pedagogical material for practising programing in Python. -published as a Jupyter book at - +[![Published](https://img.shields.io/badge/Published-Website-green)](https://python-exos.info-mines.paris) diff --git a/jupytext.toml b/jupytext.toml new file mode 100644 index 0000000..cebaef5 --- /dev/null +++ b/jupytext.toml @@ -0,0 +1,4 @@ + +cell_metadata_filter = """all,-hidden,-heading_collapsed,-run_control,-trusted,-editable,-slideshow""" +# use the jupytext config exclusively for exclusions +notebook_metadata_filter = """all, -jupytext.cell_metadata_filter, -jupytext.notebook_metadata_filter, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version,-language_info.version, -language_info.codemirror_mode,-language_info.file_extension, -language_info.mimetype, -toc, -rise, -version""" diff --git a/notebooks/Makefile b/notebooks/Makefile index 74b1747..d311c46 100644 --- a/notebooks/Makefile +++ b/notebooks/Makefile @@ -9,10 +9,9 @@ all: toc style prune artefacts book -include Makefile.book -include Makefile.style +include Makefile.book2 +include Makefile.style2 include Makefile.prune -include Makefile.toc # specific to exos include Makefile.artefacts diff --git a/notebooks/Makefile.book b/notebooks/Makefile.book deleted file mode 100644 index 8f6c07c..0000000 --- a/notebooks/Makefile.book +++ /dev/null @@ -1,7 +0,0 @@ -book: - jupyter-book build . - -book-clean: - rm -rf _build - -.PHONY: book book-clean diff --git a/notebooks/Makefile.book2 b/notebooks/Makefile.book2 new file mode 100644 index 0000000..0289f7c --- /dev/null +++ b/notebooks/Makefile.book2 @@ -0,0 +1,12 @@ +# in development, use myst start + +book: + npx myst build --execute --html + +book-dev: + npx myst start --execute + +book-clean: + rm -rf _build + +.PHONY: book book-dev book-clean diff --git a/notebooks/Makefile.style b/notebooks/Makefile.style deleted file mode 100644 index f46fa94..0000000 --- a/notebooks/Makefile.style +++ /dev/null @@ -1,33 +0,0 @@ -########## STYLE -# we keep 2 style files: -# -# _static/style_common.css: a common file for all projects -# _static/style_local.css: additions specific to this project -# -# jupyter-book: -# will automatically inject both into the resulting html -# jupyterlab: -# this makefile produces a single _static/style.html file -# which contains both sources -# this needs to be included in each notebook in a ') > $@ - -style-clean: - rm -f _static/style.html - -.PHONY: style style-clean diff --git a/notebooks/Makefile.style2 b/notebooks/Makefile.style2 new file mode 100644 index 0000000..4048c20 --- /dev/null +++ b/notebooks/Makefile.style2 @@ -0,0 +1,20 @@ +########## STYLE +# we keep 2 style files: +# +# _static/style_jb2.css: a common file for all projects +# _static/style_local.css: additions specific to this project +# +# this way we can keep the common style file in sync between all projects +# using byte-comparison tools +# +# (it is recommended to create an empty _static/style_local.css +# file if needed, to avoid errors in the build process) + + +style: _static/style.css + +_static/style.css: _static/style_jb2.css _static/style_local.css + (echo '/* autogenerated, DO NOT EDIT ME ! - edit style_jb2.css or style_local.css instead */'; \ + cat $^ ) > $@ + +.PHONY: style diff --git a/notebooks/Makefile.toc b/notebooks/Makefile.toc deleted file mode 100644 index a5fedb6..0000000 --- a/notebooks/Makefile.toc +++ /dev/null @@ -1,11 +0,0 @@ -# update the jb toc from nbhosting -toc: ../.nbhosting/nbhosting.yaml - -ifeq ($(TOCDIR),) -TOCDIR = notebooks -endif - -# update nbhosting tracks from jupyter book toc -# need to prefix notebooks path with 'notebooks/' -../.nbhosting/nbhosting.yaml: _toc.yml - $$HOME/git/nbhosting/scripts/jb-to-nbh-toc.py -p '$(TOCDIR)' $< $@ diff --git a/notebooks/README.md b/notebooks/README.md index 3d11025..8813997 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -1,5 +1,12 @@ # flotpython exos: pure Python +[![Published](https://img.shields.io/badge/Published-Website-green)](https://python-exos.info-mines.paris) +[![MyST Build Status](https://img.shields.io/github/actions/workflow/status/flotpython/exos-python/myst-to-pages.yml?branch=main&label=MyST%20Build%20Status)](https://github.com/flotpython/exos-python/actions/workflows/myst-to-pages.yml) +[![GitHub Repo](https://img.shields.io/badge/GitHub-Repository-blue?logo=github)](https://github.com/flotpython/exos-python) + + +[![License: CC BY-NC-ND](https://img.shields.io/badge/License-CC%20BY--NC--ND-lightgrey.svg)](https://creativecommons.org/licenses/by-nc-nd/4.0/) *Thierry Parmentelat* + this repo contains exercises and TPs that [complement the Python MOOC](https://www.fun-mooc.fr/en/cours/python-3-des-fondamentaux-aux-concepts-avances-du-langage/) excluded are the auto-corrected exercises mentioned in the MOOC @@ -19,9 +26,7 @@ expected to have acquired the skills for installing and managing a decent software stack (typically bash + vscode + python + ipython + jupyter) the fact that most of the material is written as a notebook is mostly a convenience, both for authoring (outputs are up-to-date), and of course in cases -where the starting material is a notebook itself -if you can really not install anything on your laptop, you can in last resort -use [the emergency resources at the bottom of this page](label-lite-tools) +where the starting material is a notebook itself ## contents @@ -49,59 +54,6 @@ distinction between notebooks and pure Python or pure markdown ## note on autoreload in ipython or notebooks if you use IPython or Jupyter on your laptop, make sure to read - + it's in French, but gives you the recipe to get IPython and the notebooks to play along if you're doing module development (otherwise you'll be bitten by the caching of modules) - -(label-lite-tools)= -## last resort computing resources - -if you really cannot install anything on your laptop, you can use this instead -this is a best effort, not everything works exactly like on a laptop - -you should first check whether you can effectively save your work; in -particular, keep in mind that the only place where your work is likely to be -saved is .. in the brower itself; so for example using another browser, or *a -fortiori* another computer, will likely make you lose your work - -### a browser-based JupyterLab - -`````{admonition} browser-hosted Jupyter Lab -:class: seealso dropdown - -````{div} -```{jupyterlite} -:kernel: python -:theme: JupyterLab Light -:width: 100% -:height: 90vh -:prompt: click to start a JuptyerLab -:prompt_color: pink - -# please be patient ... -print("welcome to Python in the browser") - -``` -```` -````` - -### a browser-based REPL - -`````{admonition} browser-hosted IPython console -:class: seealso dropdown - -````{div} -```{replite} -:kernel: python -:theme: JupyterLab Light -:width: 100% -:height: 90vh -:prompt: click to start a console -:prompt_color: yellow - -# please be patient ... -print("welcome to Python in the browser") - -``` -```` -````` diff --git a/notebooks/_config.yml b/notebooks/_config.yml deleted file mode 100755 index b2f7bab..0000000 --- a/notebooks/_config.yml +++ /dev/null @@ -1,83 +0,0 @@ -# Jupyter Book settings - -title: Python Exercices -author: Thierry Parmentelat -# this is tweaked by a sed command in ds/.readthedocs.yaml -logo: media/logo-exos-python.svg - -# we want the corriges to build as well -# only_build_toc_files: true - -exclude_patterns: - # consider only filenames that start with an uppercase - # there is something fishy here: - # if we don't put the extension part, it will exclude things like ds-exos/numpy - # with everything below; so we make sure to target only files and not directories - # also this turns out to suppress too much content, like e.g. stuff in _static - # and possibly other things that we don't want to exclude - # so we don't exclude these, can still be helpful for incremental runs though - # - "**/[a-z]*.[a-z]*" - # convenience for authors - but DO NOT exclude .teacher - # so the corrections can be built - - "**/teacher/*" - # generic exclusions - - "**/trash/**/*" - - "**/wip/*" - - "**/.ipynb_checkpoints/*" - - "**/.pytest_cache/*" - -execute: - execute_notebooks: cache - exclude_patterns: - # consider only filenames that start with an uppercase - - "[a-z]**/[a-z]*" - - "**/.teacher/[a-z]*" - timeout: 60 - -parse: - myst_enable_extensions: - - html_image # for raw tags in markdown - - dollarmath # for mathjax - - strikethrough - -sphinx: - config: - nb_custom_formats: - .py: - - jupytext.reads - - fmt: py:percent - html_theme_options: - repository_url: https://github.com/flotpython/exos - repository_branch: main - path_to_docs: . - use_issues_button: yes - use_repository_button: yes - use_download_button: yes - home_page_in_toc: false - toc_title: "TOC" - - html_favicon: media/flotpython-favicon.svg - html_show_copyright: false - html_extra_path: - - media - # would be needed if we were to expose contents to jupyterlite - # - lite - html_static_path: - - _static - html_js_files: - - my-book.js - jupyterlite_dir: . - # required as of 2024 May to get %matplotlib ipympl - # to show up (at all, not even interactive) in the book output - nb_ipywidgets_js: - # Load RequireJS, used by the IPywidgets for dependency management - "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js": - "integrity": "sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" - "crossorigin": "anonymous" - # Load IPywidgets bundle for embedding. - "https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@*/dist/embed-amd.js": - "data-jupyter-widgets-cdn": "https://cdn.jsdelivr.net/npm/" - "crossorigin": "anonymous" - - extra_extensions: - - jupyterlite_sphinx diff --git a/notebooks/_static/my-book.js b/notebooks/_static/my-book.js deleted file mode 100644 index 4baf1ae..0000000 --- a/notebooks/_static/my-book.js +++ /dev/null @@ -1,73 +0,0 @@ -// standard JS additions for our jupyter books - -// expose to the console -const cheatCorrige = () => { - // open a corrige file which is located under - // the .teacher folder with an extra "corrige-" suffix - // e.g. "my-book-nb.html" -> ".teacher/my-book-nb-corrige.html" - const currentLocation = window.location.href - let newLocation - if (currentLocation.includes("-corrige")) - // undo: go back to the student version - newLocation = currentLocation.replace( - /(.*)\/\.teacher\/([A-Za-z0-9_-]+)-corrige-nb\.html/gm, - "$1/$2-nb.html" - ) - else - newLocation = currentLocation.replace( - /(.*)\/([A-Za-z0-9_-]+)-nb\.html/gm, - "$1/.teacher/$2-corrige-nb.html" - ) - if (newLocation === currentLocation) { - console.log("from my-book.js: no corrige file found") - return - } - window.location.href = newLocation -} - -// run the following code when the page is loaded -window.addEventListener('load', - () => { - - const urlTocEntriesOpenInNewTab = () => { - console.log("from my-book.js: url-typed toc entries open in a separate tab") - document.querySelectorAll("nav a.reference.external") - .forEach(node => node.target = "_blank") - } - - // define a keyboard shortcut to open the corrige file - // want to be able to communicate the use of Ctrl-Shift-? - // very surprisingly, it is incredibly hard to catch a keyboard shortcut - // properly i.e. regardless of the keyboard layout - // given that keypress is deprecated, we are left with keydown - // as beforeinput does not even trigger in our case (not changing the dom) - // it turns out that neither the key nor code properties are reliable - // across qwerty / azerty / layouts - I haven't tried dvorak - // so here's the trade off that I came up with: - // the 'key' property seems to always refer to the lowercase character - // on a qwerty I have / being the lowercase and ? the uppercase - // on an azerty I have , being the lowercase and ? the uppercase - // on a qwerty linux, ? is the lowercase and / the uppercase - const lowercases = { '/': true, ',': true, '?': true } - const cheatCorrigeShortcut = () => { - console.log("from my-book.js: define corrige magic shortcut") - document.addEventListener("keydown", (event) => { - // console.log("keydown", event) - if (event.key in lowercases && event.ctrlKey && event.shiftKey) { - cheatCorrige() - } - }) - } - - // inject class corrige when relevant - const outlineCorrige = () => { - if (window.location.href.includes("corrige")) { - document.body.classList.add("corrige") - } - } - - // our setup - urlTocEntriesOpenInNewTab() - outlineCorrige() - cheatCorrigeShortcut() - }) diff --git a/notebooks/_static/style.css b/notebooks/_static/style.css new file mode 100644 index 0000000..00483ad --- /dev/null +++ b/notebooks/_static/style.css @@ -0,0 +1,317 @@ +/* autogenerated, DO NOT EDIT ME ! - edit style_jb2.css or style_local.css instead */ +/* + * for jupyter-book 2 aka mystmd + * with myst.yml: template: book-theme + * trying to improve the rendering of jupyter notebooks + * particularly wrt spacing around lists and paragraphs + * as well as other miscellanous tweaks + */ + +/* ---------- the left hand side toc */ + +.primary-scrollbar { + + div.w-full { + + &[data-state='open'] { + border: 1px solid var(--jp-border-color0); + border-radius: 8px; + padding-top: 0px; + } + + div.block { + &::before { + content: '≡ '; + } + } + } + + a.p-2 { + padding: 0.08em 1em; + + &.active { + &::before { + content: '⌘ '; + } + } + } +} + +/* ---------- space around lists */ + +/* a paragraph that is just above a list should not have a bottom margin + * thanks SO + * https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector + */ +main { + p:has(+ :is(ol, ul)) { + margin-bottom: 0px !important; + } + + p+ :is(ol, ul) { + margin-top: 0px !important; + } + + li>ul { + margin-top: 0px !important; + } +} + +.article :where(ul ul, ul ol, ol ul, ol ol):not(:where([class~=not-prose], [class~=not-prose] *)) { + margin-bottom: 0.25em; +} + +/* ---------- code */ + +:root { + --myst-code-border-radius: 0.5rem; + --myst-code-border-width: 0.8px; +} + +/* cell inputs */ +html.light { + --myst-input-background-color: rgb(243, 244, 245); + --myst-input-border-color: rgb(209, 213, 218); + --myst-input-left-color: rgb(0, 128, 0); + --myst-input-left-width: 4px; +} + +html.dark { + --myst-input-background-color: rgb(41, 49, 61); + --myst-input-border-color: rgb(206, 214, 221); + --myst-input-left-color: rgb(0, 128, 0); + --myst-input-left-width: 4px; +} + + +.relative.group\/block>.relative.group:has(>pre) { + border-radius: var(--myst-code-border-radius); + border-width: var(--myst-code-border-width); + border-color: var(--myst-input-border-color); + background-color: var(--myst-input-background-color); + border-left-width: var(--myst-input-left-width); + border-left-color: var(--myst-input-left-color); +} + + +/* cell outputs */ +html.light { + --myst-output-background-color: rgb(248, 255, 248); + --myst-output-border-color: blue; + --myst-output-empty-border-color: red; +} + +html.dark { + --myst-output-background-color: rgb(6, 75, 6); + --myst-output-border-color: rgb(35, 182, 211); + --myst-output-empty-border-color: rgb(128, 0, 0); +} + +html article main .relative.group[data-mdast-node-id] { + &:empty { + &::before { + content: ' ∅ no output ∅ '; + } + font-size: xx-small; + padding: 0px 1em; + + border-color: var(--myst-output-empty-border-color); + margin-bottom: 1rem; + } + + border-radius: var(--myst-code-border-radius); + margin-top: 0px; + padding: 0.25em 1em; + border-width: var(--myst-code-border-width); + border-color: var(--myst-output-border-color); + background-color: var(--myst-output-background-color); + + &>div { + border: 0px solid #00000000 !important; + background-color: #00000000 !important; + + &>code { + border: 0px solid #00000000 !important; + } + } +} +html article main .relative.group:has(+[data-mdast-node-id]) { + margin-bottom: 0.7em; +} + +/* code blocks */ +html.light { + --myst-block-background-color: rgb(243, 244, 245); + --myst-block-border-color: rgb(209, 213, 218); + --myst-block-left-color: rgb(0, 0, 128); + --myst-block-left-width: 2px; +} + +html.dark { + --myst-block-background-color: rgb(41, 49, 61); + --myst-block-border-color: rgb(72, 86, 107); + --myst-block-left-color: rgb(0, 0, 128); + --myst-block-left-width: 2px; +} + +html body article main div.group.relative:has(>pre>code) { + padding: .1rem .25rem !important; + border-radius: var(--myst-code-border-radius); + background-color: var(--myst-block-background-color); + border-width: var(--myst-code-border-width); + border-color: var(--myst-block-border-color); + border-left-width: var(--myst-block-left-width); + border-left-color: var(--myst-block-left-color); + + &>pre.hljs.block { + background-color: #00000000 !important; + } +} + +/* inline code : use same style as blocks */ +p>code { + background-color: var(--myst-block-background-color); + border-width: var(--myst-code-border-width); + border-color: var(--myst-block-border-color); + padding: 0.1rem 0.20rem; + margin-left: 0.20rem; + margin-right: 0.20rem; + border-radius: 3px; +} + +/* ---------- use page width more effectively */ +@media (min-width: 1536px) { + html { + .article-grid, .xl\:article-grid { + grid-template-columns: + /* [screen-start] .5rem [screen-inset-start] 1fr [page-start] 3rem [page-inset-start] minmax(4rem, 9rem) [body-outset-start] 3rem [body-start gutter-left-start] 1rem [body-inset-start] minmax(8ch, 10ch) [middle-start] minmax(8ch, 10ch) [gutter-left-end] minmax(8ch, 10ch) minmax(8ch, 10ch) [gutter-right-start] minmax(8ch, 10ch) [middle-end] minmax(8ch, 10ch) [body-inset-end] 1rem [body-end gutter-right-end] 3rem [body-outset-end] minmax(5rem, 13rem) [page-inset-end] 3rem [page-end] 1fr [screen-inset-end] .5rem [screen-end]; */ + [screen-start] .5rem + [screen-inset-start] 1fr + [page-start] 3rem + [page-inset-start] minmax(4rem, 9rem) + [body-outset-start] 3rem + [body-start gutter-left-start] 1rem + [body-inset-start] minmax(8ch, 10ch) + [middle-start] minmax(8ch, 10ch) + [gutter-left-end] minmax(8ch, 10ch) + /* this is the one we increase from minmax(8ch, 10ch)*/ + 10fr + [gutter-right-start] minmax(8ch, 10ch) + [middle-end] minmax(8ch, 10ch) + [body-inset-end] 1rem + [body-end gutter-right-end] 3rem + [body-outset-end] minmax(5rem, 13rem) + [page-inset-end] 3rem + [page-end] 1fr + [screen-inset-end] .5rem + [screen-end] !important; + } + } +} + +.full-width { + grid-column: body / page; +} + +/* here's the settings for the medium size screens + * it's hard to do much better, + * ideally the right had side toc could take a little less space +*/ +/* @media (min-width: 1024px) and (max-width: 1535px) { + html { + .article-grid, .xl\:article-grid { + grid-template-columns: + [screen-start] .25rem [screen-inset-start page-start] 1rem [page-inset-start body-outset-start] 1fr [body-start gutter-left-start] 1rem [body-inset-start] minmax(8ch,10ch) [middle-start] minmax(8ch,10ch) [gutter-left-end] minmax(8ch,10ch) minmax(8ch,10ch) [gutter-right-start] minmax(8ch,10ch) [middle-end] minmax(8ch,10ch) [body-inset-end] 1rem [body-end gutter-right-end] 3rem [body-outset-end] minmax(5rem,13rem) [page-inset-end] 3rem [page-end] 1fr [screen-inset-end] .25rem [screen-end] + } + } +} */ + + +/* ---------- tables */ +html.light { + --myst-table-background-color-header: #f8f8f8; + --myst-table-bottom-color-header: rgb(90, 175, 211); + --myst-table-background-color-even: #fbfbfb; + --myst-table-background-color-odd: #fdfdfd; +} + +html.dark { + --myst-table-background-color-header: #080808; + --myst-table-bottom-color-header: rgb(11, 128, 137); + --myst-table-background-color-even: #020202; + --myst-table-background-color-odd: #040404; +} + +article main table { + thead, tfoot { + tr { + background-color: var(--myst-table-background-color-header); + } + } + tbody { + th { + background-color: var(--myst-table-background-color-header); + padding:0.65rem; + font-size: larger; + border-bottom-color: var(--myst-table-bottom-color-header); + border-bottom-width: 2px; + } + tr:nth-child(even) { + background-color: var(--myst-table-background-color-even); + } + + tr:nth-child(odd) { + background-color: var(--myst-table-background-color-odd) + } + } +} + +/* space before admonitions */ +/* :is(.bd-container, .myst) div.admonition>.admonition-title+* { + margin-top: 0px !important; +} + */ + +/* standard admonition classes */ +.admonition-smaller { + font-size: smaller; + line-height: 1.2; +} + +.admonition-small { + font-size: small; + line-height: 1.2; +} + +.admonition-x-small { + font-size: x-small; + line-height: 1.2; +} + +/* slight gradient for corriges */ +.corrige { + background-image: radial-gradient(circle at top left, #d1effa, #e2f9cd); +} + +html[data-theme='dark'] .corrige { + background-image: radial-gradient(circle at top left, #0e3852, #0c5517); +} + +/* our exercises often do +1. the thing to do + +```{code-cell} ipython3 +# your code +``` + +it would be better if we could indent the code cell but if we do, we lose the overall cell structure +as the code cell is then part of the list item, in markdown, and is no longer deemed a code cell by jupyter +*/ + +*+div.group\/block>div.myst-code { + margin-top: 0.3em; +} + +*:has(+div.group\/block>div.myst-code) { + margin-bottom: 0.3em; +} diff --git a/notebooks/_static/style_common.css b/notebooks/_static/style_common.css deleted file mode 100644 index 12b9e57..0000000 --- a/notebooks/_static/style_common.css +++ /dev/null @@ -1,132 +0,0 @@ -/* - * trying to improve the rendering of jupyter notebooks - * particularly wrt spacing around lists and paragraphs - * as well as other miscellanous tweaks - * - * .bd-container targets jupyter-book output - * .myst targets jupyter-lab rendering - */ - -/* use more horizontal space when available - * this is otherwise arbitrarily set to 88rem - */ - -@media (min-width: 960px) { - .bd-page-width { - max-width: initial !important; - } - - /* but keep the upper-left logo to grow too much */ - .navbar-brand.logo>img { - max-width: 250px; - max-height: 170px; - } -} - -/* make the right-hand-side index background transparent */ -#bd-toc-nav { - background-color: rgb(0 0 0 / 0); -} - - -/* not too much space between paragraphs */ -:is(.bd-container, .myst) :is(p, ul) { - margin-bottom: 0.5em !important; - margin-top: 0.5em !important; -} - -.myst :where(:is(p, ul)):not(:where([class~=not-prose], [class~=not-prose] *)) { - margin-bottom: 0.5em !important; - margin-top: 0.5em !important; -} - - -/* not too much space around lists */ -:is(.bd-container, .myst) *+ :is(ol, ul), -/* a paragraph that is just above a list should not have a bottom margin - * thanks SO - * https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector - */ -:is(.bd-container, .myst) p:has(+ :is(ol, ul)) { - margin-bottom: initial !important; -} - -:is(.bd-container, .myst) li>ul { - margin-top: 0.1em !important; -} - - -/* execution output cells */ -div.cell div.cell_output .output pre { - background-color: #f8fff8 !important; - border: 0.3px solid blue !important; -} - -html[data-theme='dark'] div.cell div.cell_output .output pre { - background-color: #064b06 !important; -} - -div.prompt.input_prompt, div.prompt.output_prompt { - opacity: 0.6; -} - -/* jupyterlab-myst and tables */ -:is(.bd-container, .myst) table td { - padding: initial !important; -} - -:is(.bd-container, .myst) table tbody tr:nth-child(odd) { - background-color: #fdfdfd; -} - -:is(.bd-container, .myst) table tbody tr:nth-child(even) { - background-color: #fbfbfb; -} - -:is(.bd-container, .myst) table :is(thead, tfoot) tr { - background-color: #f8f8f8; -} - -html[data-theme='dark'] { - & :is(.bd-container, .myst) table tbody tr:nth-child(odd) { - background-color: #020202; - } - - & :is(.bd-container, .myst) table tbody tr:nth-child(even) { - background-color: #040404; - } - - & :is(.bd-container, .myst) table :is(thead, tfoot) tr { - background-color: #080808; - } -} - -/* space before admonitions */ -:is(.bd-container, .myst) div.admonition>.admonition-title+* { - margin-top: 0px !important; -} - -/* standard admonition classes */ -.admonition-smaller { - font-size: smaller; - line-height: 1.2; -} - -.admonition-small { - font-size: small; - line-height: 1.2; -} - -.admonition-x-small { - font-size: x-small; - line-height: 1.2; -} - -/* slight gradient for corriges */ -.corrige { - background-image: radial-gradient(circle at top left, #d1effa, #e2f9cd); -} - -html[data-theme='dark'] .corrige { - background-image: radial-gradient(circle at top left, #0e3852, #0c5517); -} diff --git a/notebooks/_static/style_jb2.css b/notebooks/_static/style_jb2.css new file mode 100644 index 0000000..0ab567a --- /dev/null +++ b/notebooks/_static/style_jb2.css @@ -0,0 +1,316 @@ +/* + * for jupyter-book 2 aka mystmd + * with myst.yml: template: book-theme + * trying to improve the rendering of jupyter notebooks + * particularly wrt spacing around lists and paragraphs + * as well as other miscellanous tweaks + */ + +/* ---------- the left hand side toc */ + +.primary-scrollbar { + + div.w-full { + + &[data-state='open'] { + border: 1px solid var(--jp-border-color0); + border-radius: 8px; + padding-top: 0px; + } + + div.block { + &::before { + content: '≡ '; + } + } + } + + a.p-2 { + padding: 0.08em 1em; + + &.active { + &::before { + content: '⌘ '; + } + } + } +} + +/* ---------- space around lists */ + +/* a paragraph that is just above a list should not have a bottom margin + * thanks SO + * https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector + */ +main { + p:has(+ :is(ol, ul)) { + margin-bottom: 0px !important; + } + + p+ :is(ol, ul) { + margin-top: 0px !important; + } + + li>ul { + margin-top: 0px !important; + } +} + +.article :where(ul ul, ul ol, ol ul, ol ol):not(:where([class~=not-prose], [class~=not-prose] *)) { + margin-bottom: 0.25em; +} + +/* ---------- code */ + +:root { + --myst-code-border-radius: 0.5rem; + --myst-code-border-width: 0.8px; +} + +/* cell inputs */ +html.light { + --myst-input-background-color: rgb(243, 244, 245); + --myst-input-border-color: rgb(209, 213, 218); + --myst-input-left-color: rgb(0, 128, 0); + --myst-input-left-width: 4px; +} + +html.dark { + --myst-input-background-color: rgb(41, 49, 61); + --myst-input-border-color: rgb(206, 214, 221); + --myst-input-left-color: rgb(0, 128, 0); + --myst-input-left-width: 4px; +} + + +.relative.group\/block>.relative.group:has(>pre) { + border-radius: var(--myst-code-border-radius); + border-width: var(--myst-code-border-width); + border-color: var(--myst-input-border-color); + background-color: var(--myst-input-background-color); + border-left-width: var(--myst-input-left-width); + border-left-color: var(--myst-input-left-color); +} + + +/* cell outputs */ +html.light { + --myst-output-background-color: rgb(248, 255, 248); + --myst-output-border-color: blue; + --myst-output-empty-border-color: red; +} + +html.dark { + --myst-output-background-color: rgb(6, 75, 6); + --myst-output-border-color: rgb(35, 182, 211); + --myst-output-empty-border-color: rgb(128, 0, 0); +} + +html article main .relative.group[data-mdast-node-id] { + &:empty { + &::before { + content: ' ∅ no output ∅ '; + } + font-size: xx-small; + padding: 0px 1em; + + border-color: var(--myst-output-empty-border-color); + margin-bottom: 1rem; + } + + border-radius: var(--myst-code-border-radius); + margin-top: 0px; + padding: 0.25em 1em; + border-width: var(--myst-code-border-width); + border-color: var(--myst-output-border-color); + background-color: var(--myst-output-background-color); + + &>div { + border: 0px solid #00000000 !important; + background-color: #00000000 !important; + + &>code { + border: 0px solid #00000000 !important; + } + } +} +html article main .relative.group:has(+[data-mdast-node-id]) { + margin-bottom: 0.7em; +} + +/* code blocks */ +html.light { + --myst-block-background-color: rgb(243, 244, 245); + --myst-block-border-color: rgb(209, 213, 218); + --myst-block-left-color: rgb(0, 0, 128); + --myst-block-left-width: 2px; +} + +html.dark { + --myst-block-background-color: rgb(41, 49, 61); + --myst-block-border-color: rgb(72, 86, 107); + --myst-block-left-color: rgb(0, 0, 128); + --myst-block-left-width: 2px; +} + +html body article main div.group.relative:has(>pre>code) { + padding: .1rem .25rem !important; + border-radius: var(--myst-code-border-radius); + background-color: var(--myst-block-background-color); + border-width: var(--myst-code-border-width); + border-color: var(--myst-block-border-color); + border-left-width: var(--myst-block-left-width); + border-left-color: var(--myst-block-left-color); + + &>pre.hljs.block { + background-color: #00000000 !important; + } +} + +/* inline code : use same style as blocks */ +p>code { + background-color: var(--myst-block-background-color); + border-width: var(--myst-code-border-width); + border-color: var(--myst-block-border-color); + padding: 0.1rem 0.20rem; + margin-left: 0.20rem; + margin-right: 0.20rem; + border-radius: 3px; +} + +/* ---------- use page width more effectively */ +@media (min-width: 1536px) { + html { + .article-grid, .xl\:article-grid { + grid-template-columns: + /* [screen-start] .5rem [screen-inset-start] 1fr [page-start] 3rem [page-inset-start] minmax(4rem, 9rem) [body-outset-start] 3rem [body-start gutter-left-start] 1rem [body-inset-start] minmax(8ch, 10ch) [middle-start] minmax(8ch, 10ch) [gutter-left-end] minmax(8ch, 10ch) minmax(8ch, 10ch) [gutter-right-start] minmax(8ch, 10ch) [middle-end] minmax(8ch, 10ch) [body-inset-end] 1rem [body-end gutter-right-end] 3rem [body-outset-end] minmax(5rem, 13rem) [page-inset-end] 3rem [page-end] 1fr [screen-inset-end] .5rem [screen-end]; */ + [screen-start] .5rem + [screen-inset-start] 1fr + [page-start] 3rem + [page-inset-start] minmax(4rem, 9rem) + [body-outset-start] 3rem + [body-start gutter-left-start] 1rem + [body-inset-start] minmax(8ch, 10ch) + [middle-start] minmax(8ch, 10ch) + [gutter-left-end] minmax(8ch, 10ch) + /* this is the one we increase from minmax(8ch, 10ch)*/ + 10fr + [gutter-right-start] minmax(8ch, 10ch) + [middle-end] minmax(8ch, 10ch) + [body-inset-end] 1rem + [body-end gutter-right-end] 3rem + [body-outset-end] minmax(5rem, 13rem) + [page-inset-end] 3rem + [page-end] 1fr + [screen-inset-end] .5rem + [screen-end] !important; + } + } +} + +.full-width { + grid-column: body / page; +} + +/* here's the settings for the medium size screens + * it's hard to do much better, + * ideally the right had side toc could take a little less space +*/ +/* @media (min-width: 1024px) and (max-width: 1535px) { + html { + .article-grid, .xl\:article-grid { + grid-template-columns: + [screen-start] .25rem [screen-inset-start page-start] 1rem [page-inset-start body-outset-start] 1fr [body-start gutter-left-start] 1rem [body-inset-start] minmax(8ch,10ch) [middle-start] minmax(8ch,10ch) [gutter-left-end] minmax(8ch,10ch) minmax(8ch,10ch) [gutter-right-start] minmax(8ch,10ch) [middle-end] minmax(8ch,10ch) [body-inset-end] 1rem [body-end gutter-right-end] 3rem [body-outset-end] minmax(5rem,13rem) [page-inset-end] 3rem [page-end] 1fr [screen-inset-end] .25rem [screen-end] + } + } +} */ + + +/* ---------- tables */ +html.light { + --myst-table-background-color-header: #f8f8f8; + --myst-table-bottom-color-header: rgb(90, 175, 211); + --myst-table-background-color-even: #fbfbfb; + --myst-table-background-color-odd: #fdfdfd; +} + +html.dark { + --myst-table-background-color-header: #080808; + --myst-table-bottom-color-header: rgb(11, 128, 137); + --myst-table-background-color-even: #020202; + --myst-table-background-color-odd: #040404; +} + +article main table { + thead, tfoot { + tr { + background-color: var(--myst-table-background-color-header); + } + } + tbody { + th { + background-color: var(--myst-table-background-color-header); + padding:0.65rem; + font-size: larger; + border-bottom-color: var(--myst-table-bottom-color-header); + border-bottom-width: 2px; + } + tr:nth-child(even) { + background-color: var(--myst-table-background-color-even); + } + + tr:nth-child(odd) { + background-color: var(--myst-table-background-color-odd) + } + } +} + +/* space before admonitions */ +/* :is(.bd-container, .myst) div.admonition>.admonition-title+* { + margin-top: 0px !important; +} + */ + +/* standard admonition classes */ +.admonition-smaller { + font-size: smaller; + line-height: 1.2; +} + +.admonition-small { + font-size: small; + line-height: 1.2; +} + +.admonition-x-small { + font-size: x-small; + line-height: 1.2; +} + +/* slight gradient for corriges */ +.corrige { + background-image: radial-gradient(circle at top left, #d1effa, #e2f9cd); +} + +html[data-theme='dark'] .corrige { + background-image: radial-gradient(circle at top left, #0e3852, #0c5517); +} + +/* our exercises often do +1. the thing to do + +```{code-cell} ipython3 +# your code +``` + +it would be better if we could indent the code cell but if we do, we lose the overall cell structure +as the code cell is then part of the list item, in markdown, and is no longer deemed a code cell by jupyter +*/ + +*+div.group\/block>div.myst-code { + margin-top: 0.3em; +} + +*:has(+div.group\/block>div.myst-code) { + margin-bottom: 0.3em; +} diff --git a/notebooks/_toc.yml b/notebooks/_toc.yml deleted file mode 100644 index 0c7cbb1..0000000 --- a/notebooks/_toc.yml +++ /dev/null @@ -1,89 +0,0 @@ -# this is the source for the table of contents -# of the flotpython-exos-python book -format: jb-book -root: README -parts: -- caption: exercices débutants - chapters: - # input, loop, int(), except - - file: exos/beginners/EXO-countdown-nb - # import, argparse - - file: exos/beginners/EXO-guess-nb - # slicing, conditional expression, return/break - - file: exos/beginners/EXO-palindrom-nb - # sorted - - file: exos/beginners/EXO-anagrams-nb - # counter, regexp - - file: exos/beginners/EXO-frequency-nb -- caption: exercices basiques - chapters: - # str, ints, binary computations - - file: exos/basic/EXO-ipsplit-nb - # lists, side effects - - file: exos/basic/EXO-skimlist-readme-nb - # strs and formatting - - file: exos/basic/EXO-invoice-nb - # dicts - - file: exos/basic/README-agenda-nb - # basic counts, requires dicts - - file: exos/basic/README-adnpercents-nb - # filesystem / pathlib - - file: exos/basic/EXO-files-sortby-nb - - file: exos/basic/EXO-randomdate-readme-nb - - file: exos/basic/EXO-wordcounts-readme-nb -- caption: howtos - chapters: - - file: howtos/encodings/HOWTO-encodings-nb - - file: howtos/requests/HOWTO-requests-nb - - file: howtos/adnwalk/HOWTO-adnwalk-nb - - glob: tps/graph-bfs-dfs/README* - - file: howtos/subprocesses/HOWTO-subprocesses-nb -- caption: TPs basiques - chapters: - # ascii, utf8, binary, as well as various file formats - # like pickle, json, yaml, csv - - file: tps/files-formats/README-files-formats-nb - - file: tps/watson/README-watson-nb - # using dicts for indexing and sets for creating groups - - file: tps/parse-people/README-parse-people-nb - # using dicts for structs and for indexing - - file: tps/indexing-structs/README-indexing-structs-nb - # itertools - - file: tps/queens/README-queens-nb -- caption: TPs classes - chapters: - - glob: tps/students-grades/README* - - glob: exos/basic/EXO-class-sort-hash-nb - - glob: tps/auctions/README* - - glob: tps/unicode-boxes/README* - - glob: tps/explang/README* -- caption: TPs graphes - chapters: - - glob: tps/graph-shortest-path/README* - - file: tps/metro/README-metro-nb - - glob: tps/pagerank-thrones/README* - - glob: tps/puzzle8/README-* -- caption: TPs visu & games - chapters: - - glob: tps/snake/README* - # unfinished business - # - "python-tps/flappybird-wip/README*.md" - - glob: tps/boids/README* - - glob: tps/chatbot/README* - - glob: tps/redis/README* - - glob: tps/motus/README* - - glob: tps/dobble/README* -- caption: lecture de code - chapters: - - file: reading/snake/snake -- caption: "avanc\xE9s" - chapters: - - file: exos/advanced/EXO-attributes-proxy-nb - - file: exos/advanced/EXO-attributes-dynprop-nb -- caption: sample code - chapters: - - glob: samples/* -- caption: WIP - chapters: - - file: tps/subprocesses-howto - - glob: tps/webscraper-wip/README* diff --git a/notebooks/exos/advanced/EXO-attributes-dynprop-nb.md b/notebooks/exos/advanced/EXO-attributes-dynprop-nb.md index 60ab454..306f796 100644 --- a/notebooks/exos/advanced/EXO-attributes-dynprop-nb.md +++ b/notebooks/exos/advanced/EXO-attributes-dynprop-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst diff --git a/notebooks/exos/advanced/EXO-attributes-proxy-nb.md b/notebooks/exos/advanced/EXO-attributes-proxy-nb.md index aef43ed..6868847 100644 --- a/notebooks/exos/advanced/EXO-attributes-proxy-nb.md +++ b/notebooks/exos/advanced/EXO-attributes-proxy-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst @@ -53,10 +49,6 @@ nbhosting: * ou lever l'exception AttributeError ```{code-cell} ipython3 ---- -slideshow: - slide_type: slide ---- class Echo: def __getattr__(self, attrname): if len(attrname) == 3: @@ -71,10 +63,6 @@ class Echo: ``` ```{code-cell} ipython3 ---- -slideshow: - slide_type: slide ---- echo = Echo() echo.foo() ``` @@ -90,8 +78,6 @@ except AttributeError as e: print("OOPS", e) ``` -+++ {"slideshow": {"slide_type": "slide"}} - # Deuxième partie +++ @@ -125,10 +111,6 @@ except AttributeError as e: ``` ```{code-cell} ipython3 ---- -slideshow: - slide_type: slide ---- class BlacklistEcho(Echo): def __init__(self, blacklist): super().__init__() @@ -140,10 +122,6 @@ class BlacklistEcho(Echo): ``` ```{code-cell} ipython3 ---- -slideshow: - slide_type: slide ---- blacklist = [ 'six', 'two', 'four'] echo2 = BlacklistEcho(blacklist) diff --git a/notebooks/exos/basic/EXO-randomdate-readme-nb.md b/notebooks/exos/basic/EXO-randomdate-readme-nb.md index 2f23fd9..60575f7 100644 --- a/notebooks/exos/basic/EXO-randomdate-readme-nb.md +++ b/notebooks/exos/basic/EXO-randomdate-readme-nb.md @@ -45,7 +45,7 @@ Dans le but de ## étape 1: générer une date -+++ {"slideshow": {"slide_type": "slide"}} ++++ ````{admonition} to do Écrivez une fonction qui se comporte comme `generate_random_date` @@ -69,8 +69,6 @@ generate_random_date() generate_random_date("10/02/2020", "31/12/2021") ``` -+++ {"tags": []} - ### indices +++ @@ -102,6 +100,7 @@ pour représenter : * les instants au cours du temps (dates, heures, ...): la classe `datetime` que, juste pour être compatibles avec la PEP008, on va importer sous le nom de `DateTime` + * les durées - i.e. la différence entre deux instants: la classe `timedelta` et idem ici on va l'appeler `TimeDelta`` @@ -233,6 +232,7 @@ sort_data("randomdate.txt", "randomdate-sorted.txt") * le **méthode** `list.sort()` qui copie une liste en place du coup si on essaye d'optimiser l'utilisation de la mémoire, on va choisir laquelle ? + * ces fonctions pour trier acceptent un paramètre `key=`, regardez bien comment ça marche ce truc-là * pas la peine d'essayer de finasser et de lire le fichier ligne par ligne, on n'a pas d'autre choix que de lire l'entrée en entier avant de trier diff --git a/notebooks/exos/beginners/EXO-anagrams-nb.md b/notebooks/exos/beginners/EXO-anagrams-nb.md index b12c0b0..95e186e 100644 --- a/notebooks/exos/beginners/EXO-anagrams-nb.md +++ b/notebooks/exos/beginners/EXO-anagrams-nb.md @@ -3,8 +3,6 @@ jupytext: text_representation: extension: .md format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python diff --git a/notebooks/exos/beginners/EXO-countdown-nb.md b/notebooks/exos/beginners/EXO-countdown-nb.md index 50f603a..24b6703 100644 --- a/notebooks/exos/beginners/EXO-countdown-nb.md +++ b/notebooks/exos/beginners/EXO-countdown-nb.md @@ -3,8 +3,6 @@ jupytext: text_representation: extension: .md format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python @@ -66,7 +64,6 @@ time.sleep(0.5) +++ - ### une version v0 un peu naïve ça fonctionne, mais on ne contrôle pas l'entrée de l'utilisateur: @@ -99,6 +96,7 @@ cette fois on continue de poser la question jusqu'à ce qu'on reçoive un entier * dans un premier temps on avait écrit la fonction `saisie_entier()` et le texte de la question était *cablé* à l'intérieur; mais dans un exercice suivant, on a voulu réutiliser cette fonction, d'où le paramètre + * il reste un défaut ici; pouvez-vous voir lequel ? ```{admonition} réponse :class: dropdown diff --git a/notebooks/exos/beginners/EXO-frequency-nb.md b/notebooks/exos/beginners/EXO-frequency-nb.md index a1ec952..2a79ad3 100644 --- a/notebooks/exos/beginners/EXO-frequency-nb.md +++ b/notebooks/exos/beginners/EXO-frequency-nb.md @@ -3,8 +3,6 @@ jupytext: text_representation: extension: .md format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python diff --git a/notebooks/exos/beginners/EXO-guess-nb.md b/notebooks/exos/beginners/EXO-guess-nb.md index c50dd53..49227b4 100644 --- a/notebooks/exos/beginners/EXO-guess-nb.md +++ b/notebooks/exos/beginners/EXO-guess-nb.md @@ -3,8 +3,6 @@ jupytext: text_representation: extension: .md format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python diff --git a/notebooks/exos/beginners/EXO-palindrom-nb.md b/notebooks/exos/beginners/EXO-palindrom-nb.md index a49edbd..4a53689 100644 --- a/notebooks/exos/beginners/EXO-palindrom-nb.md +++ b/notebooks/exos/beginners/EXO-palindrom-nb.md @@ -3,8 +3,6 @@ jupytext: text_representation: extension: .md format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python diff --git a/notebooks/howtos/adnwalk/HOWTO-adnwalk-nb.md b/notebooks/howtos/adnwalk/HOWTO-adnwalk-nb.md index d5c6164..d08bd67 100644 --- a/notebooks/howtos/adnwalk/HOWTO-adnwalk-nb.md +++ b/notebooks/howtos/adnwalk/HOWTO-adnwalk-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst @@ -127,6 +123,7 @@ moves['C'] ``` Ce qui signifie pour nous que lorsqu'on rencontre un `C`, il faut : + * faire `+1` en x, * et ne rien faire (ajouter `0`) en y. @@ -141,6 +138,7 @@ print("à ajouter en y: ", delta_y) ### Le parcours à proprement parler Nous avons à présent tous les éléments pour écrire une fonction, qui + * prend en entrée un fragment d'ADN codé comme une chaine de caractères contenant les 4 abbréviations, * et qui retourne deux listes, correspondant aux X et aux Y respectivement, des points du chemin. diff --git a/notebooks/howtos/encodings/HOWTO-encodings-nb.md b/notebooks/howtos/encodings/HOWTO-encodings-nb.md index f56d2f5..2929da3 100644 --- a/notebooks/howtos/encodings/HOWTO-encodings-nb.md +++ b/notebooks/howtos/encodings/HOWTO-encodings-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst diff --git a/notebooks/howtos/requests/HOWTO-requests-nb.md b/notebooks/howtos/requests/HOWTO-requests-nb.md index 9ea28c1..5da1e40 100644 --- a/notebooks/howtos/requests/HOWTO-requests-nb.md +++ b/notebooks/howtos/requests/HOWTO-requests-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst diff --git a/notebooks/howtos/subprocesses/HOWTO-subprocesses-nb.md b/notebooks/howtos/subprocesses/HOWTO-subprocesses-nb.md index 4cf7707..f7ed217 100644 --- a/notebooks/howtos/subprocesses/HOWTO-subprocesses-nb.md +++ b/notebooks/howtos/subprocesses/HOWTO-subprocesses-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst @@ -21,7 +17,7 @@ nbhosting: # gestion de sous-processus -un aperçu ultra-rapide de: comment faire pour lancer un autre processus depuis Python +un aperçu ultra-rapide de: comment faire pour lancer un autre processus depuis Python +++ diff --git a/notebooks/media/flotpython-favicon.svg b/notebooks/media/flotpython-favicon.svg index bd23046..69f653c 100644 --- a/notebooks/media/flotpython-favicon.svg +++ b/notebooks/media/flotpython-favicon.svg @@ -1 +1,62 @@ - \ No newline at end of file + + + + + + + + diff --git a/notebooks/media/flotpython-favicon.svg.ico b/notebooks/media/flotpython-favicon.svg.ico new file mode 100644 index 0000000..dcf57e6 Binary files /dev/null and b/notebooks/media/flotpython-favicon.svg.ico differ diff --git a/notebooks/myst-toc.yml b/notebooks/myst-toc.yml new file mode 100644 index 0000000..0189d1b --- /dev/null +++ b/notebooks/myst-toc.yml @@ -0,0 +1,111 @@ +version: 1 + +project: + toc: + + - file: README.md + + - title: exercices débutants + children: + # input, loop, int(), except + - file: exos/beginners/EXO-countdown-nb.md + # import, argparse + - file: exos/beginners/EXO-guess-nb.md + # slicing, conditional expression, return/break + - file: exos/beginners/EXO-palindrom-nb.md + # sorted + - file: exos/beginners/EXO-anagrams-nb.md + # counter, regexp + - file: exos/beginners/EXO-frequency-nb.md + + - title: exercices basiques + children: + # str, ints, binary computations + - file: exos/basic/EXO-ipsplit-nb.md + # lists, side effects + - file: exos/basic/EXO-skimlist-readme-nb.md + # strs and formatting + - file: exos/basic/EXO-invoice-nb.md + # dicts + - file: exos/basic/README-agenda-nb.md + # basic counts, requires dicts + - file: exos/basic/README-adnpercents-nb.md + # filesystem / pathlib + - file: exos/basic/EXO-files-sortby-nb.md + - file: exos/basic/EXO-randomdate-readme-nb.md + - file: exos/basic/EXO-wordcounts-readme-nb.md + + - title: howtos + children: + - file: howtos/encodings/HOWTO-encodings-nb.md + - file: howtos/requests/HOWTO-requests-nb.md + - file: howtos/adnwalk/HOWTO-adnwalk-nb.md + - pattern: tps/graph-bfs-dfs/README*-nb.md + - file: howtos/subprocesses/HOWTO-subprocesses-nb.md + + - title: TPs basiques + children: + # ascii, utf8, binary, as well as various file formats + # like pickle, json, yaml, csv + - file: tps/files-formats/README-files-formats-nb.md + - file: tps/watson/README-watson-nb.md + # using dicts for indexing and sets for creating groups + - file: tps/parse-people/README-parse-people-nb.md + # using dicts for structs and for indexing + - file: tps/indexing-structs/README-indexing-structs-nb.md + # itertools + - file: tps/queens/README-queens-nb.md + # lexer, parser, eval - a small expression language + - pattern: tps/*/.teacher/*-corrige-nb.md + hidden: true + + - title: TPs classes + children: + - pattern: tps/students-grades/README*-nb.md + - pattern: exos/basic/EXO-class-sort-hash-nb.md + - pattern: tps/auctions/README*-nb.md + - pattern: tps/unicode-boxes/README*-nb.md + - pattern: tps/explang/README*-nb.md + + - title: TPs graphes + children: + - pattern: tps/graph-shortest-path/README*-nb.md + - file: tps/metro/README-metro-nb.md + - pattern: tps/pagerank-thrones/README*-nb.md + - pattern: tps/puzzle8/README-*-nb.md + - file: tps/ants/README-ants-nb.md + + - title: TPs avancés + children: + - file: tps/explang2/README-explang2-nb.md + + - title: TPs visu & games + children: + - pattern: tps/snake/README*-nb.md + - pattern: tps/game-of-life/README*-nb.md + # unfinished business + # - "python-tps/flappybird-wip/README*.md" + - pattern: tps/boids/README*-nb.md + - pattern: tps/chatbot/README*-nb.md + - pattern: tps/redis/README*-nb.md + - pattern: tps/motus/README*-nb.md + - pattern: tps/dobble/README*-nb.md + hidden: true + + - title: lecture de code + children: + - file: reading/snake/snake-nb.md + + - title: "avancés" + children: + - file: exos/advanced/EXO-attributes-proxy-nb.md + - file: exos/advanced/EXO-attributes-dynprop-nb.md + + - title: sample code + children: + - pattern: samples/*-nb.md + + - title: WIP + children: + - file: tps/subprocesses-howto-nb.md + - pattern: tps/webscraper-wip/README*-nb.md diff --git a/notebooks/myst.yml b/notebooks/myst.yml new file mode 100644 index 0000000..22aa6b9 --- /dev/null +++ b/notebooks/myst.yml @@ -0,0 +1,52 @@ +# See docs at: https://mystmd.org/guide/frontmatter +version: 1 +project: + title: Python programmation exos + # I suspect the intention was maybe to use this for the title tooltip ? + # in any case as of now 2024 june the title is used for the tooltip too (a bit silly) + # and I can't see where this is used + description: "Python - various activities: exos, TPs and HOWTOs" + # this one causes additional buttons to be shown + # in the upper right area (close to the github button) + license: CC-BY-NC-SA-4.0 + # inserted under the title + authors: + - Thierry Parmentelat + github: https://github.com/flotpython/exos-python + keywords: + - Informatique + - Python + - numpy + - pandas + - matplotlib + - Jupyter + date: 2026-01-19 + jupyter: + lite: true + # bibliography: [] + plugins: + - https://raw.githubusercontent.com/choldgraf/myst-lightbox/main/src/index.mjs + +site: + #template: book-theme + template: https://github.com/flotpython/myst-theme/releases/download/custom/book-theme.zip + # used in the tab name + title: python-exos + # this would be for the horizontal header bar - not used here (yet) + # nav: [] + # actions: + # - title: Learn More + # url: https://mystmd.org/guide + domains: [] + options: + # workaround for https://github.com/jupyter-book/mystmd/issues/1985#issuecomment-3232330240 + # we have converted the svg to ico + favicon: media/flotpython-favicon.svg.ico + logo: media/logo-exos-python.svg + # very visible in the header + logo_text: "Python - exos" + style: "_static/style.css" + folders: true + +extends: + - myst-toc.yml diff --git a/notebooks/requirements-rtd.txt b/notebooks/requirements-rtd.txt deleted file mode 100644 index f2b7c88..0000000 --- a/notebooks/requirements-rtd.txt +++ /dev/null @@ -1,11 +0,0 @@ -# generic deps -sphinx -sphinx-rtd-theme -jupyter-book - -# -jupyterlite-pyodide-kernel -jupyterlite-sphinx >= 0.13 - -# toggable left sidebar -pydata-sphinx-theme<0.16 diff --git a/notebooks/tps/ants/.teacher/README-ants-corrige-nb.md b/notebooks/tps/ants/.teacher/README-ants-corrige-nb.md new file mode 100644 index 0000000..88ffd93 --- /dev/null +++ b/notebooks/tps/ants/.teacher/README-ants-corrige-nb.md @@ -0,0 +1,213 @@ +--- +jupytext: + formats: md:myst + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# ants: a genetic algorithm + ++++ {"tags": ["prune-cell"]} + +````{admonition} nothing to prune +:class: warning + +there are no difference - apart from this very cell - between the teacher and the student version, but the notebook is duplicated in .teacher for consistency +```` + ++++ {"editable": true, "slideshow": {"slide_type": ""}} + +```{admonition} grab the zip for starters + +{download}`you will need the zipfile that you can find here<./ARTEFACTS-ants.zip>` +``` + ++++ + +## problem statement + +our goal in this activity is to implement an optimization algorithm that is an example of a *genetic algorithm* +it turns out this algorithm can solve two equivalent problems + +### traveling salesman + +specifically, we consider a famous problem, which is of great importance for everything logistics, and is known as **the *"traveling salesman"* problem** +consider for example a truck that needs to deliver parcels in several locations +the problem is to find **the shortest path** (or more accurately, a reasonably short path) + +- that starts from the warehouse +- goes through all the locations +- and returns to the warehouse + +### ants colony problem + +the traveling salesman problem is in fact equivalent to the one known as the **the *"ants colony"* problem**, where the colony needs to find the best route from the ant hill and back, that goes through the spots where food has been found + +this latter metaphor is **a little more helpful** though in the context of the genetic algorithm, because the algorithm indeed mimicks the existence of several ants that concurrently walk the graph, and leave pheromons to keep track of the past + +```{admonition} not *the* shortest path +is has been shown that finding *the* shortest path is an NP-problem, so it's untractable +but as explained in the video, the genetic algorithm finds reasonable paths, in that they do not differ much from the optimal one +``` + ++++ + +## ACO: a super useful resource + +the YouTube video below gives a 20' introduction on the algorithm known as *Ants Colony Optimization (ACO)*, and explains essentially all the logic and formulas needed to implement it +```{iframe} https://www.youtube.com/embed/u7bQomllcJw?rel=0&controls=1 +``` +so it is a **highly recommended** resource to get started with the details of the algorithm + +```{admonition} not a video fan ? + +[I found this one helpful too, in a totally different style](https://perso.liris.cnrs.fr/christine.solnon/publications/cpaior.pdf) + +and there's plenty others around as well, google for 'ACO algorithm' ... +``` + ++++ + +## useful data + +in the zip file you will find: + ++++ + +### `data/*.csv` + +we provide a few datafiles in the `data/` folder, made from some graphs that appear in the video +these use a simple csv format that should be self explanatory (just forget the `radius` column) + +| name | timestamp in video | # nodes | +|-|-|-| +| data/video-50.csv | 1:17 | 50 | +| data/video-30.csv | 3:14 | 30 | +| data/video-04.csv | 8:57 | 4 | +| data/video-10.csv | 11:25 | 10 | +| data/video-06.csv | 14:54 | 6 | +| data/video-66.csv | 17:44 | 66 | + +plus for convenience some polygon-like shapes in `poly*.csv` + ++++ + +### `data/*.path` + +here we provide the results found by our own implementation; this in particular is used by the 'Cheat' button in `ui.py` - see below + ++++ + +## problem.py + +also provided in the zip, you can use `problem.py` like so: + +```{code-cell} ipython3 +from problem import Problem2D + +problem = Problem2D("data/video-06.csv") +``` + +```{code-cell} ipython3 +# how many nodes +len(problem) +``` + +```{code-cell} ipython3 +# to iterate over nodes + +for node in problem: + print(node) +``` + +```{code-cell} ipython3 +# or rather + +for index, node in enumerate(problem): + print(f"{index}-th node is {node}") +``` + +```{code-cell} ipython3 +# get distance between 2 nodes + +problem.distance(0, 2) +``` + +```{code-cell} ipython3 +# what it says + +problem.distance_along_path([0, 1, 2, 3, 0]) +``` + +#### displaying the graphs + ++++ + +we've also coded some display featured for your convenience + +1st off, **provided that you have `graphviz` installed** + +```{code-cell} ipython3 +# you can do display it with graphviz like this + +problem.to_graphviz() +``` + +```{code-cell} ipython3 +# or this if you prefer + +problem.to_graphviz(show_distances=False) +``` + +```{code-cell} ipython3 +# prune-cell +# sub-optimal for big graphs though +Problem2D("data/video-50.csv").to_graphviz(show_distances=False) +``` + +#### if you prefer plotly + +and there again, **provided that you have `plotly` installed** you could do + +```{code-cell} ipython3 +import plotly.io as pio + +# Try one of these depending on your setup: +pio.renderers.default = "notebook" # for classic Jupyter Notebook +``` + +```{code-cell} ipython3 +problem.to_plotly() +``` + +```{code-cell} ipython3 +# prune-cell + +Problem2D("data/video-50.csv").to_plotly(show_distances=False) +``` + +```{code-cell} ipython3 +# prune-cell + +p6 = Problem2D("data/video-06.csv") +p6.print_distances() +``` + +## `ui.py` + +might come in handy too, it is a simple `flet` UI that lets you visualize your work; you might consider + +- reading its code +- make sure your `solver.py` code fits the expected interface - or tweak `ui.py` according to your own interface +- run it with +```bash +flet run -d ui.py +``` +so that the UI will hot reload upon any change you make in `solver.py` diff --git a/notebooks/tps/ants/.teacher/data b/notebooks/tps/ants/.teacher/data new file mode 120000 index 0000000..eed2d0b --- /dev/null +++ b/notebooks/tps/ants/.teacher/data @@ -0,0 +1 @@ +../data/ \ No newline at end of file diff --git a/notebooks/tps/ants/.teacher/gridsearch.py b/notebooks/tps/ants/.teacher/gridsearch.py new file mode 100644 index 0000000..2e2923d --- /dev/null +++ b/notebooks/tps/ants/.teacher/gridsearch.py @@ -0,0 +1,95 @@ +""" +do a gridsearch on the solver meta-parameters +""" + +import math +from itertools import product + +from problem import Problem2D +from solver import Solver + +ITERATIONS = 10 + +# ALPHAS = [0.1, 0.5, 1, 2, 5] +ALPHAS = [1] +# BETAS = [0.1, 0.5, 1, 2, 5] +BETAS = [1] +# VAPORIZATIONS = [0.1, 0.5, 0.9] +VAPORIZATIONS = [0.64] +# PHERO_INITS = [0.1, 0.5, 1, 2, 5] +PHERO_INITS = [1] + +def use_default_parameters(): + global ALPHAS, BETAS, VAPORIZATIONS, PHERO_INITS + from solver import ALPHA, BETA, VAPORISATION, PHERO_INIT + ALPHAS = [ALPHA] + BETAS = [BETA] + VAPORIZATIONS = [VAPORISATION] + PHERO_INITS = [PHERO_INIT] + + +def gridsearch(filename, iterations): + p = Problem2D(filename) + best_distance = math.inf + best_path = None + best_params = None + + CUBE = (ALPHAS, BETAS, VAPORIZATIONS, PHERO_INITS) + nb_combinations = len(ALPHAS) * len(BETAS) * len(VAPORIZATIONS) * len(PHERO_INITS) + + for index, hyper_params in enumerate(product(*CUBE), 1): + (alpha, beta, vaporization, phero_init) = hyper_params + s = Solver(p, alpha=alpha, beta=beta, vaporisation=vaporization, + phero_init=phero_init) + path, distance = s.solve(iterations) + print( + f"{index}/{nb_combinations} " + f"alpha={alpha} beta={beta} vaporization={vaporization} phero_init={phero_init}" + f"path={path} distance={distance}") + if distance < best_distance: + best_distance = distance + best_path = path + best_params = hyper_params + + print(f"best path={best_path} distance={best_distance} with params={best_params}") + # save in .path file + # compute max euclidian diameter + max_diameter = max(p.distance(i, j) + for i, j in product(range(len(p)), repeat=2) if i != j) + for i in range(len(p)): + for j in range(i+1, len(p)): + d = p.distance(i, j) + if d > max_diameter: + max_diameter = d + cheated_filename = filename.replace(".csv", ".path") + with open(cheated_filename, "w") as f: + import json + print(f"saving best path to {cheated_filename}") + json.dump(dict( + path=best_path, + distance=best_distance, + params=best_params, + iterations=iterations, + diameter=max_diameter, + ), f) + +from argparse import ArgumentParser +def main(): + parser = ArgumentParser() + parser.add_argument("filenames", nargs="+",help="the problem filename (csv)") + parser.add_argument( + "-i", "--iterations", type=int, default=ITERATIONS, + help=f"number of iterations per run (default: {ITERATIONS})") + # useful only to recompute the .path files + parser.add_argument( + "-d", "--default-parameters", action="store_true", + help="use the default parameters from solver.py instead of the gridsearch") + + args = parser.parse_args() + if args.default_parameters: + use_default_parameters() + for filename in args.filenames: + gridsearch(filename, args.iterations) + +if __name__ == "__main__": + main() diff --git a/notebooks/tps/ants/.teacher/main.py b/notebooks/tps/ants/.teacher/main.py new file mode 100644 index 0000000..d6f2c5c --- /dev/null +++ b/notebooks/tps/ants/.teacher/main.py @@ -0,0 +1,11 @@ +from problem import Problem2D + +from solver import Solver + +def demo_solver(): + p = Problem2D("data/video-10.csv") + s = Solver(p) + path, distance = s.solve(20) + print("found path=", path, "distance=", p.distance_along_path(path)) + +demo_solver() \ No newline at end of file diff --git a/notebooks/tps/ants/.teacher/media b/notebooks/tps/ants/.teacher/media new file mode 120000 index 0000000..d803adf --- /dev/null +++ b/notebooks/tps/ants/.teacher/media @@ -0,0 +1 @@ +../media/ \ No newline at end of file diff --git a/notebooks/tps/ants/.teacher/problem.py b/notebooks/tps/ants/.teacher/problem.py new file mode 120000 index 0000000..267141b --- /dev/null +++ b/notebooks/tps/ants/.teacher/problem.py @@ -0,0 +1 @@ +../problem.py \ No newline at end of file diff --git a/notebooks/tps/ants/.teacher/solver.py b/notebooks/tps/ants/.teacher/solver.py new file mode 100644 index 0000000..0891a66 --- /dev/null +++ b/notebooks/tps/ants/.teacher/solver.py @@ -0,0 +1,212 @@ +""" +the core of the ants colony algorithm +""" + +import random +import numpy as np +# import itertools + +from problem import Problem + + +### meta parameters + +# the weights used in the probability of choosing the next vertex +# pheromone +ALPHA = 2. +# distance +BETA = 2. +# the ratio that remains after evaporation +VAPORISATION = 0.9 +# how much pheromones we start with +PHERO_INIT = 1. + +# the constant to compute the edges +# WARNING: not a parameter +# this will be set from problem in Solver.__init__() +DIST_WEIGHT = None + + +### debug +DEBUG = False +# DEBUG = True + +def debug(*args, **kwargs): + if not DEBUG: + return + # display large arrays properly + with np.printoptions(edgeitems=30, linewidth=100000, precision=5): + args2 = [] + for arg in args: + args2.append(arg if not isinstance(arg, np.ndarray) else repr(arg)) + print("DBG:", *args2, **kwargs) + + +class Pheromones: + """ + pheromones representation + links are symmetric, so we only store them once + coded as a triangular matrix, diagonal excluded + """ + + def __init__(self, problem: Problem): + self.problem = problem + n = len(problem) + # initialize to avoid division by zero + # see random.choices below + self.edges = PHERO_INIT*np.ones((n, n), dtype=float) + + def __len__(self): + n, _ = self.edges.shape + return n + + def __repr__(self): + return repr(self.edges) + + # use upper right triangle only + def __getitem__(self, idx2): + i, j = idx2 + if i == j: + raise ValueError("no self loop") + i, j = min(i, j), max(i, j) + return self.edges[i, j] + + def __setitem__(self, idx2, x): + i, j = idx2 + if i == j: + raise ValueError("no self loop") + i, j = min(i, j), max(i, j) + i, j = min(i, j), max(i, j) + self.edges[i, j] = x + + def copy(self): + clone = Pheromones(self.problem) + clone.edges = self.edges.copy() + return clone + + +class Ant: + def __init__(self, problem: Problem, pheromones: Pheromones, start_vertex: int): + """ + the incoming pheromones object is read only + """ + self.problem = problem + self.pheromones = pheromones + self.start_vertex = start_vertex + self.current_vertex = start_vertex + self.possible = set(range(len(self.pheromones))) - {self.current_vertex} + self.path = [start_vertex] + self.total = 0 + + def pick_next(self): + weights = [] + # just consider the non visited nodes + for i in self.possible: + # for each one, the probability is proportional to this amount + probability = ( + (self.pheromones[self.current_vertex, i]**ALPHA) + / (self.problem.distance(self.current_vertex, i)**BETA) + ) + weights.append(probability) + # pick the next vertex + # random.choices does the weight normalization for us, no need to divide + # there's one exception though: if all the weights are zero + # so for now we just ignore this case by starting with a pheromone of 1 + # debug(f"PICK current_vertex={self.current_vertex}") + # debug(f"PICK {candidates=}") + # debug(f"PICK distances=", [self.problem.distances[self.current_vertex, candidate] for candidate in candidates]) + # debug(f"PICK {weights=}") + next_vertex = random.choices(list(self.possible), weights=weights)[0] + # debug(f"PICK {next_vertex=}") + self.path.append(next_vertex) + self.possible.remove(next_vertex) + self.total += self.problem.distance(self.current_vertex, next_vertex) + self.current_vertex = next_vertex + + def walk(self): + # debug(f"{self.pheromones=}") + debug(f"walk from {self.current_vertex}") + while self.possible: + self.pick_next() + # go back to the start + self.path.append(self.path[0]) + self.total += self.problem.distance(self.current_vertex, self.path[0]) + return self.total + + +class Solver: + """ + the solver class + """ + def __init__( + self, problem: Problem, *, + alpha: float = ALPHA, beta: float = BETA, + vaporisation: float = VAPORISATION, + phero_init: float = PHERO_INIT, + ): + self.problem = problem + # set the meta parameters + global ALPHA, BETA, VAPORISATION, PHERO_INIT + ALPHA = alpha + BETA = beta + VAPORISATION = vaporisation + PHERO_INIT = phero_init + # global, but not a parameter + global DIST_WEIGHT + DIST_WEIGHT = problem.mean_distance() + self.pheromones = Pheromones(problem) + + Solution = tuple[list[int], float] + + def solve(self, nb_iterations) -> Solution: + """ + this is where you should write the algorithm + it should return a permutation of the indices in problem + """ + debug(10*'\n') + debug(f"epoch 0, self.pheromones=\n", self.pheromones) + for iteration in range(nb_iterations): + debug(f"\n\n{10*'='} iteration {iteration}") + + # create one ant per starting vertex and make it walk the graph + ants = [ Ant(self.problem, self.pheromones, start_vertex) + for start_vertex in range(len(self.problem)) + ] + for ant in ants: + ant.walk() + debug(f"ant {ant.start_vertex} has picked path {ant.path} with total distance {ant.total}") + + # update the pheromones + self.new_pheromones = self.pheromones.copy() + # update the edges + self.new_pheromones.edges *= VAPORISATION + + for ant in ants: + # # follow the ants path: we artificially add the starting vertex at the end + # full_path = list(itertools.chain(ant.path, [ant.path[0]])) + # so we can iterate over the pairs of vertices + # including the one that returns to the starting point + debug(f"pheromone contrib for ant #{ant.start_vertex}") + for i, j in zip(ant.path, ant.path[1:]): + debug(f"contrib {i=} {j=} before: {self.new_pheromones[i, j]:.5f}", end=' ') + self.new_pheromones[i, j] += DIST_WEIGHT / ant.total + debug(f"after: {self.new_pheromones[i, j]:.5f}") + # adopt the new pheromones + self.pheromones = self.new_pheromones + debug(f"after update, self.pheromones=\n", self.pheromones) + + # we're done with the iterations, let's return the best path + # it's not clear whether the result depends on the starting vertex + # for now we always start at 0 + best_path = [0] + remaining = set(range(len(self.problem))) - {best_path[0]} + while len(best_path) < len(self.problem): + best = 0 + for i in remaining: + if self.pheromones[best_path[-1], i] > best: + best = self.pheromones[best_path[-1], i] + best_candidate = i + best_path.append(best_candidate) + remaining.remove(best_candidate) + distance = self.problem.distance_along_path(best_path) + return best_path, distance diff --git a/notebooks/tps/ants/.teacher/ui.py b/notebooks/tps/ants/.teacher/ui.py new file mode 120000 index 0000000..0c3df0e --- /dev/null +++ b/notebooks/tps/ants/.teacher/ui.py @@ -0,0 +1 @@ +../ui.py \ No newline at end of file diff --git a/notebooks/tps/ants/ARTEFACTS b/notebooks/tps/ants/ARTEFACTS new file mode 100644 index 0000000..84dc5aa --- /dev/null +++ b/notebooks/tps/ants/ARTEFACTS @@ -0,0 +1,3 @@ +data/*.csv +problem.py +ui.py diff --git a/notebooks/tps/ants/ARTEFACTS-ants.zip b/notebooks/tps/ants/ARTEFACTS-ants.zip new file mode 100644 index 0000000..638e192 Binary files /dev/null and b/notebooks/tps/ants/ARTEFACTS-ants.zip differ diff --git a/notebooks/tps/ants/README-ants-nb.md b/notebooks/tps/ants/README-ants-nb.md new file mode 100644 index 0000000..27c81d2 --- /dev/null +++ b/notebooks/tps/ants/README-ants-nb.md @@ -0,0 +1,184 @@ +--- +jupytext: + formats: md:myst + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# ants: a genetic algorithm + ++++ + +```{admonition} grab the zip for starters + +{download}`you will need the zipfile that you can find here<./ARTEFACTS-ants.zip>` +``` + ++++ + +## problem statement + +our goal in this activity is to implement an optimization algorithm that is an example of a *genetic algorithm* +it turns out this algorithm can solve two equivalent problems + +### traveling salesman + +specifically, we consider a famous problem, which is of great importance for everything logistics, and is known as **the *"traveling salesman"* problem** +consider for example a truck that needs to deliver parcels in several locations +the problem is to find **the shortest path** (or more accurately, a reasonably short path) + +- that starts from the warehouse +- goes through all the locations +- and returns to the warehouse + +### ants colony problem + +the traveling salesman problem is in fact equivalent to the one known as the **the *"ants colony"* problem**, where the colony needs to find the best route from the ant hill and back, that goes through the spots where food has been found + +this latter metaphor is **a little more helpful** though in the context of the genetic algorithm, because the algorithm indeed mimicks the existence of several ants that concurrently walk the graph, and leave pheromons to keep track of the past + +```{admonition} not *the* shortest path +is has been shown that finding *the* shortest path is an NP-problem, so it's untractable +but as explained in the video, the genetic algorithm finds reasonable paths, in that they do not differ much from the optimal one +``` + ++++ + +## ACO: a super useful resource + +the YouTube video below gives a 20' introduction on the algorithm known as *Ants Colony Optimization (ACO)*, and explains essentially all the logic and formulas needed to implement it +```{iframe} https://www.youtube.com/embed/u7bQomllcJw?rel=0&controls=1 +``` +so it is a **highly recommended** resource to get started with the details of the algorithm + +```{admonition} not a video fan ? + +[I found this one helpful too, in a totally different style](https://perso.liris.cnrs.fr/christine.solnon/publications/cpaior.pdf) + +and there's plenty others around as well, google for 'ACO algorithm' ... +``` + ++++ + +## useful data + +in the zip file you will find: + ++++ + +### `data/*.csv` + +we provide a few datafiles in the `data/` folder, made from some graphs that appear in the video +these use a simple csv format that should be self explanatory (just forget the `radius` column) + +| name | timestamp in video | # nodes | +|-|-|-| +| data/video-50.csv | 1:17 | 50 | +| data/video-30.csv | 3:14 | 30 | +| data/video-04.csv | 8:57 | 4 | +| data/video-10.csv | 11:25 | 10 | +| data/video-06.csv | 14:54 | 6 | +| data/video-66.csv | 17:44 | 66 | + +plus for convenience some polygon-like shapes in `poly*.csv` + ++++ + +### `data/*.path` + +here we provide the results found by our own implementation; this in particular is used by the 'Cheat' button in `ui.py` - see below + ++++ + +## problem.py + +also provided in the zip, you can use `problem.py` like so: + +```{code-cell} +from problem import Problem2D + +problem = Problem2D("data/video-06.csv") +``` + +```{code-cell} +# how many nodes +len(problem) +``` + +```{code-cell} +# to iterate over nodes + +for node in problem: + print(node) +``` + +```{code-cell} +# or rather + +for index, node in enumerate(problem): + print(f"{index}-th node is {node}") +``` + +```{code-cell} +# get distance between 2 nodes + +problem.distance(0, 2) +``` + +```{code-cell} +# what it says + +problem.distance_along_path([0, 1, 2, 3, 0]) +``` + +#### displaying the graphs + ++++ + +we've also coded some display featured for your convenience + +1st off, **provided that you have `graphviz` installed** + +```{code-cell} +# you can do display it with graphviz like this + +problem.to_graphviz() +``` + +```{code-cell} +# or this if you prefer + +problem.to_graphviz(show_distances=False) +``` + +#### if you prefer plotly + +and there again, **provided that you have `plotly` installed** you could do + +```{code-cell} +import plotly.io as pio + +# Try one of these depending on your setup: +pio.renderers.default = "notebook" # for classic Jupyter Notebook +``` + +```{code-cell} +problem.to_plotly() +``` + +## `ui.py` + +might come in handy too, it is a simple `flet` UI that lets you visualize your work; you might consider + +- reading its code +- make sure your `solver.py` code fits the expected interface - or tweak `ui.py` according to your own interface +- run it with +```bash +flet run -d ui.py +``` +so that the UI will hot reload upon any change you make in `solver.py` diff --git a/notebooks/tps/ants/data/convert_image.py b/notebooks/tps/ants/data/convert_image.py new file mode 100644 index 0000000..2e64db6 --- /dev/null +++ b/notebooks/tps/ants/data/convert_image.py @@ -0,0 +1,64 @@ +""" +a utility to transform a screenshot into a csv file +""" + +from pathlib import Path +from argparse import ArgumentParser + +import numpy as np +import pandas as pd +# pip install opencv-python +import cv2 + +def convert_image(filename): + image_path = Path(filename) + csv_path = image_path.with_suffix(".csv") + + image = cv2.imread(image_path, cv2.IMREAD_COLOR) + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + blurred = cv2.GaussianBlur(gray, (9, 9), 2) + + circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1, minDist=20, + param1=50, param2=30, minRadius=10, maxRadius=50) + + + if circles is None: + print("no circle found") + return + rows = [] + circles = np.uint16(np.around(circles)) + for index, circle in enumerate(circles[0, :]): + # Extract circle coordinates (x, y) and radius + x, y, radius, *_ = circle + rows.append(dict(name=f"n{index}", x=x, y=y, radius=radius)) + df = pd.DataFrame(rows) + + # rescale to fit a [0, 600] range + min_x, max_x = df["x"].min(), df["x"].max() + min_y, max_y = df["y"].min(), df["y"].max() + + span_x, span_y = max_x - min_x, max_y - min_y + if span_x > span_y: + scale = 600 / span_x + else: + scale = 600 / span_y + + df["x"] = (df["x"] - min_x) * scale + df["y"] = (df["y"] - min_y) * scale + # back to integer + df['x'] = df['x'].astype(int) + df['y'] = df['y'].astype(int) + # add a margin + df["x"] += 50 + df["y"] += 50 + + df.to_csv(csv_path) + + print(f"output written in {csv_path}") + +if __name__ == '__main__': + parser = ArgumentParser(description="convert a screenshot into a csv file") + parser.add_argument("image", nargs='+', help="the image to convert") + args = parser.parse_args() + for filename in args.image: + convert_image(filename) diff --git a/notebooks/tps/ants/data/diamond.csv b/notebooks/tps/ants/data/diamond.csv new file mode 100644 index 0000000..c32f61a --- /dev/null +++ b/notebooks/tps/ants/data/diamond.csv @@ -0,0 +1,5 @@ +name,x,y +0,0,50 +1,85,0 +2,170,50 +3,85,100 \ No newline at end of file diff --git a/notebooks/tps/ants/data/diamond.path b/notebooks/tps/ants/data/diamond.path new file mode 100644 index 0000000..6b39565 --- /dev/null +++ b/notebooks/tps/ants/data/diamond.path @@ -0,0 +1 @@ +{"path": [0, 2, 1, 3], "distance": 467.2308292331602, "params": [1, 1, 0.64, 1, 0.01], "iterations": 10} \ No newline at end of file diff --git a/notebooks/tps/ants/data/poly-05.csv b/notebooks/tps/ants/data/poly-05.csv new file mode 100644 index 0000000..fb969be --- /dev/null +++ b/notebooks/tps/ants/data/poly-05.csv @@ -0,0 +1,6 @@ +x,y,name +300.0,290.0,p0 +537.7641290737884,207.0820393249937,p1 +446.9463130731183,72.91796067500631,p2 +153.05368692688174,72.9179606750063,p3 +62.23587092621159,207.08203932499367,p4 diff --git a/notebooks/tps/ants/data/poly-05.path b/notebooks/tps/ants/data/poly-05.path new file mode 100644 index 0000000..1545e94 --- /dev/null +++ b/notebooks/tps/ants/data/poly-05.path @@ -0,0 +1 @@ +{"path": [0, 4, 3, 2, 1], "distance": 1121.5321538673284, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 475.52825814757676} \ No newline at end of file diff --git a/notebooks/tps/ants/data/poly-08.csv b/notebooks/tps/ants/data/poly-08.csv new file mode 100644 index 0000000..33b0b3a --- /dev/null +++ b/notebooks/tps/ants/data/poly-08.csv @@ -0,0 +1,9 @@ +x,y,name +300.0,290.0,p0 +476.77669529663683,254.8528137423857,p1 +550.0,170.0,p2 +476.7766952966369,85.14718625761431,p3 +300.00000000000006,50.0,p4 +123.22330470336317,85.14718625761428,p5 +50.0,169.99999999999997,p6 +123.22330470336308,254.85281374238568,p7 diff --git a/notebooks/tps/ants/data/poly-08.path b/notebooks/tps/ants/data/poly-08.path new file mode 100644 index 0000000..24d3e1d --- /dev/null +++ b/notebooks/tps/ants/data/poly-08.path @@ -0,0 +1 @@ +{"path": [0, 7, 6, 5, 4, 3, 2, 1], "distance": 1169.2625386406319, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 500.0} \ No newline at end of file diff --git a/notebooks/tps/ants/data/poly-12.csv b/notebooks/tps/ants/data/poly-12.csv new file mode 100644 index 0000000..a9d9008 --- /dev/null +++ b/notebooks/tps/ants/data/poly-12.csv @@ -0,0 +1,13 @@ +x,y,name +300.0,290.0,p0 +425.0,273.92304845413264,p1 +516.5063509461097,230.0,p2 +550.0,170.0,p3 +516.5063509461097,110.00000000000003,p4 +425.0,66.07695154586736,p5 +300.00000000000006,50.0,p6 +175.00000000000006,66.07695154586735,p7 +83.49364905389041,109.99999999999994,p8 +50.0,169.99999999999997,p9 +83.49364905389035,230.0,p10 +174.9999999999999,273.92304845413264,p11 diff --git a/notebooks/tps/ants/data/poly-12.path b/notebooks/tps/ants/data/poly-12.path new file mode 100644 index 0000000..813b348 --- /dev/null +++ b/notebooks/tps/ants/data/poly-12.path @@ -0,0 +1 @@ +{"path": [0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], "distance": 1184.988476858752, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 500.0} \ No newline at end of file diff --git a/notebooks/tps/ants/data/polygon.py b/notebooks/tps/ants/data/polygon.py new file mode 100644 index 0000000..4a4d427 --- /dev/null +++ b/notebooks/tps/ants/data/polygon.py @@ -0,0 +1,36 @@ +import argparse +import json + +import numpy as np +import pandas as pd + +def polygon_as_df(n): + values = [ + dict( + x=300 + 250 * np.sin(2 * np.pi * i / n), + y=170 + 120 * np.cos(2 * np.pi * i / n), + name=f"p{i}", + ) + for i in range(n) + ] + return pd.DataFrame(values) + +def polygon_in_file(n): + df = polygon_as_df(n) + filename = f"data/poly{n}.csv" + df.to_csv(filename, index=False) + filename = f"data/poly{n}.path" + with open(filename, "w") as f: + json.dump(dict(path=list(range(n)), distance=0), f) + + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("dimensions", nargs='+', type=int) + args = parser.parse_args() + for n in args.dimensions: + polygon_in_file(n) + +if __name__ == '__main__': + main() diff --git a/notebooks/tps/ants/data/video-04.csv b/notebooks/tps/ants/data/video-04.csv new file mode 100644 index 0000000..9786911 --- /dev/null +++ b/notebooks/tps/ants/data/video-04.csv @@ -0,0 +1,5 @@ +,name,x,y,radius +,n0,0,100,20 +,n1,100,50,20 +,n2,200,100,20 +,n3,100,150,20 diff --git a/notebooks/tps/ants/data/video-04.path b/notebooks/tps/ants/data/video-04.path new file mode 100644 index 0000000..a98d39e --- /dev/null +++ b/notebooks/tps/ants/data/video-04.path @@ -0,0 +1 @@ +{"path": [0, 1, 2, 3], "distance": 447.21359549995793, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 200.0} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-06.csv b/notebooks/tps/ants/data/video-06.csv new file mode 100644 index 0000000..f66ebcf --- /dev/null +++ b/notebooks/tps/ants/data/video-06.csv @@ -0,0 +1,7 @@ +,name,x,y,radius +0,b,627,146,29 +1,a,50,142,29 +2, ,227,50,30 +3, ,106,255,30 +4, ,213,189,29 +5, ,125,83,31 diff --git a/notebooks/tps/ants/data/video-06.path b/notebooks/tps/ants/data/video-06.path new file mode 100644 index 0000000..b84e184 --- /dev/null +++ b/notebooks/tps/ants/data/video-06.path @@ -0,0 +1 @@ +{"path": [0, 4, 3, 1, 5, 2], "distance": 1282.049564637041, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 577.0138646514484} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-10.csv b/notebooks/tps/ants/data/video-10.csv new file mode 100644 index 0000000..f706b47 --- /dev/null +++ b/notebooks/tps/ants/data/video-10.csv @@ -0,0 +1,11 @@ +,name,x,y,radius +0,n0,299,260,32 +1,n1,58,119,32 +2,n2,504,301,32 +3,n3,650,371,32 +4,n4,306,50,30 +5,n5,563,501,22 +6,n6,580,126,22 +7,n7,360,494,22 +8,n8,137,466,22 +9,n9,50,301,21 diff --git a/notebooks/tps/ants/data/video-10.path b/notebooks/tps/ants/data/video-10.path new file mode 100644 index 0000000..bbe3b96 --- /dev/null +++ b/notebooks/tps/ants/data/video-10.path @@ -0,0 +1 @@ +{"path": [0, 4, 1, 9, 8, 7, 5, 3, 2, 6], "distance": 2084.560062275812, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 643.4034504103937} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-15.csv b/notebooks/tps/ants/data/video-15.csv new file mode 100644 index 0000000..830e917 --- /dev/null +++ b/notebooks/tps/ants/data/video-15.csv @@ -0,0 +1,16 @@ +,name,x,y,radius +0,n0,410,50,33 +1,n1,189,109,33 +2,n2,420,480,32 +3,n3,64,255,33 +4,n4,50,325,29 +5,n5,281,50,32 +6,n6,241,585,32 +7,n7,193,189,32 +8,n8,122,423,32 +9,n9,493,367,31 +10,n10,650,181,27 +11,n11,413,592,31 +12,n12,561,61,30 +13,n13,563,232,32 +14,n14,132,530,31 diff --git a/notebooks/tps/ants/data/video-15.path b/notebooks/tps/ants/data/video-15.path new file mode 100644 index 0000000..7658469 --- /dev/null +++ b/notebooks/tps/ants/data/video-15.path @@ -0,0 +1 @@ +{"path": [0, 5, 1, 7, 3, 4, 8, 14, 6, 11, 2, 9, 13, 10, 12], "distance": 1858.4526180630278, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 635.6115165728198} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-30.csv b/notebooks/tps/ants/data/video-30.csv new file mode 100644 index 0000000..622eaea --- /dev/null +++ b/notebooks/tps/ants/data/video-30.csv @@ -0,0 +1,31 @@ +,name,x,y,radius +0,n0,587,463,24 +1,n1,159,151,24 +2,n2,50,197,24 +3,n3,175,241,24 +4,n4,385,387,24 +5,n5,354,489,24 +6,n6,570,167,24 +7,n7,195,51,16 +8,n8,268,102,16 +9,n9,650,146,17 +10,n10,370,156,17 +11,n11,451,73,17 +12,n12,538,254,16 +13,n13,354,50,17 +14,n14,376,267,17 +15,n15,251,425,16 +16,n16,462,183,16 +17,n17,283,309,17 +18,n18,74,95,16 +19,n19,645,54,16 +20,n20,500,389,16 +21,n21,449,312,17 +22,n22,50,411,17 +23,n23,91,294,16 +24,n24,158,380,16 +25,n25,118,487,16 +26,n26,456,474,17 +27,n27,586,349,17 +28,n28,559,80,16 +29,n29,291,200,16 diff --git a/notebooks/tps/ants/data/video-30.path b/notebooks/tps/ants/data/video-30.path new file mode 100644 index 0000000..2c9034c --- /dev/null +++ b/notebooks/tps/ants/data/video-30.path @@ -0,0 +1 @@ +{"path": [0, 27, 20, 26, 5, 4, 21, 14, 17, 29, 10, 16, 12, 6, 9, 19, 28, 11, 13, 8, 7, 1, 3, 23, 2, 18, 22, 25, 15, 24], "distance": 3568.1356657530973, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 693.8832754865907} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-50.csv b/notebooks/tps/ants/data/video-50.csv new file mode 100644 index 0000000..5d5ec74 --- /dev/null +++ b/notebooks/tps/ants/data/video-50.csv @@ -0,0 +1,50 @@ +,name,x,y,radius +0,n0,645,134,16 +1,n1,253,199,17 +2,n2,620,78,16 +3,n3,405,179,17 +4,n4,236,100,16 +5,n5,385,251,16 +6,n6,434,314,16 +7,n7,551,50,17 +8,n8,50,217,16 +9,n9,475,181,17 +10,n10,581,369,17 +11,n11,650,247,16 +12,n12,85,360,16 +13,n13,483,230,17 +14,n14,57,289,16 +15,n15,516,372,16 +16,n16,476,57,16 +17,n17,74,70,16 +18,n18,646,197,16 +19,n19,219,149,16 +20,n20,268,64,10 +21,n21,269,324,16 +22,n22,315,254,16 +23,n23,396,116,16 +24,n24,437,377,16 +25,n25,573,205,16 +26,n26,218,260,10 +27,n27,167,374,16 +28,n28,338,318,16 +29,n29,644,300,11 +30,n30,631,344,10 +31,n31,298,126,17 +32,n32,329,181,11 +33,n33,187,208,10 +34,n34,557,265,10 +35,n35,367,64,10 +36,n36,56,135,16 +37,n37,512,300,16 +38,n38,388,355,11 +39,n39,129,144,10 +40,n40,436,248,11 +41,n41,563,131,10 +42,n42,483,114,10 +43,n43,128,274,11 +44,n44,175,317,10 +45,n45,112,213,10 +46,n46,586,314,10 +47,n47,173,69,11 +48,n48,330,379,16 diff --git a/notebooks/tps/ants/data/video-50.path b/notebooks/tps/ants/data/video-50.path new file mode 100644 index 0000000..a1590eb --- /dev/null +++ b/notebooks/tps/ants/data/video-50.path @@ -0,0 +1 @@ +{"path": [0, 2, 7, 16, 42, 41, 25, 34, 46, 10, 15, 37, 6, 24, 38, 48, 28, 21, 26, 33, 1, 19, 4, 20, 31, 32, 22, 5, 40, 13, 9, 3, 23, 35, 47, 17, 36, 39, 45, 8, 14, 12, 27, 44, 43, 30, 29, 11, 18], "distance": 3756.7944508145983, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 620.7455195166534} \ No newline at end of file diff --git a/notebooks/tps/ants/data/video-66.csv b/notebooks/tps/ants/data/video-66.csv new file mode 100644 index 0000000..4ea1b75 --- /dev/null +++ b/notebooks/tps/ants/data/video-66.csv @@ -0,0 +1,67 @@ +,name,x,y,radius +0,n0,650,69,16 +1,n1,362,323,16 +2,n2,279,141,16 +3,n3,386,382,16 +4,n4,587,61,16 +5,n5,633,300,16 +6,n6,344,72,16 +7,n7,147,237,16 +8,n8,336,369,16 +9,n9,141,66,16 +10,n10,524,80,16 +11,n11,235,118,16 +12,n12,285,82,16 +13,n13,538,369,16 +14,n14,580,329,16 +15,n15,361,201,16 +16,n16,587,122,16 +17,n17,473,50,16 +18,n18,151,172,16 +19,n19,403,157,16 +20,n20,626,368,16 +21,n21,234,63,16 +22,n22,139,109,16 +23,n23,421,63,10 +24,n24,75,330,11 +25,n25,343,236,11 +26,n26,462,167,11 +27,n27,633,228,11 +28,n28,230,171,10 +29,n29,465,232,16 +30,n30,201,212,11 +31,n31,310,295,11 +32,n32,204,368,10 +33,n33,513,260,11 +34,n34,58,183,10 +35,n35,90,119,10 +36,n36,64,63,11 +37,n37,228,296,10 +38,n38,442,293,10 +39,n39,69,251,10 +40,n40,108,284,16 +41,n41,413,208,13 +42,n42,155,312,11 +43,n43,245,244,11 +44,n44,470,371,11 +45,n45,181,134,10 +46,n46,647,145,10 +47,n47,576,267,10 +48,n48,148,359,10 +49,n49,412,343,10 +50,n50,337,164,11 +51,n51,448,108,10 +52,n52,50,371,11 +53,n53,280,200,11 +54,n54,387,269,11 +55,n55,511,316,10 +56,n56,280,382,10 +57,n57,185,271,10 +58,n58,264,343,10 +59,n59,524,198,10 +60,n60,525,130,10 +61,n61,576,188,10 +62,n62,96,376,10 +63,n63,106,198,10 +64,n64,354,116,10 +65,n65,586,378,12 diff --git a/notebooks/tps/ants/data/video-66.path b/notebooks/tps/ants/data/video-66.path new file mode 100644 index 0000000..a12bbac --- /dev/null +++ b/notebooks/tps/ants/data/video-66.path @@ -0,0 +1 @@ +{"path": [0, 4, 16, 60, 10, 17, 23, 51, 26, 19, 41, 29, 38, 54, 25, 15, 50, 64, 6, 12, 21, 11, 2, 53, 43, 37, 57, 42, 48, 32, 58, 56, 8, 3, 49, 44, 55, 33, 59, 61, 27, 46, 28, 30, 7, 35, 36, 9, 22, 45, 18, 63, 34, 39, 40, 24, 52, 62, 31, 1, 13, 65, 20, 5, 14, 47], "distance": 4580.2862280682375, "params": [2.0, 2.0, 0.9, 1.0], "iterations": 50, "diameter": 671.7172023999385} \ No newline at end of file diff --git a/notebooks/tps/ants/problem.py b/notebooks/tps/ants/problem.py new file mode 100644 index 0000000..453a89f --- /dev/null +++ b/notebooks/tps/ants/problem.py @@ -0,0 +1,214 @@ +""" +the basic bricks: how to model a problem + +- at its root, a problem is just + - an ordered collection of nodes (any Python object) + - a matrix with the distances between the nodes + remember that in general, the distance from node i to node j + may be different from node j to node i + +- a specific kind of problem is when the nodes are in an open 2D space + so in this case we can assume each node has a position (x, y) + and then infer the distances + +""" + +import math +import itertools +from dataclasses import dataclass + +import numpy as np +import pandas as pd + + +class Problem: + """ + in the most generic case, a problem is just a collection of nodes + with a distance matrix - which does not have to be symmetric btw + + the diagonal of the matrix is always 0, although this is not enforced + as the algorithm will never use it in fact + """ + def __init__(self, nodes: list, distances: np.ndarray): + self.nodes = nodes + self.distances = distances + # sanity check + if distances.shape != (len(nodes), len(nodes)): + raise ValueError("distances should be a square matrix") + + # make it iterable + def __iter__(self): + return iter(self.nodes) + def __len__(self): + return len(self.nodes) + def __getitem__(self, i): + return self.nodes[i] + + def distance(self, i, j): + return self.distances[i, j] + + def mean_distance(self): + """ + helper to get a feeling of the problem size + """ + n = len(self) + if n <= 1: + return 0 + total = sum(self.distance(i, j) + for i, j in itertools.product(range(n), repeat=2) if i != j) + return total / (n*(n-1)) + + def print_distances(self): + """ + helper to list all distances + probably useful on small problems only + """ + for i, n1 in enumerate(self): + print("==") + for j, n2 in enumerate(self): + if n1 != n2: + print(f"{n1.name} -> {n2.name} = {self.distance(i, j):.2f}") + + def distance_along_path(self, path): + """ + what the name says + """ + total = 0 + # we want to go back to the first node + # so we add the starting node at the end of the iteration + chain = list(itertools.chain(path, [path[0]])) + # so now we can iterate over the pairs of vertices + # the second argument of zip is shifted by one + # so we have the next vertex in the path + for i, j in zip(chain, chain[1:]): + total += self.distance(i, j) + return total + + +class Problem2D(Problem): + + # make it immutable and hashable + @dataclass(frozen=True) + class Node: + name: str + x: float + y: float + + def distance(self, other): + return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) + + + def __init__(self, filename): + """ + if filename is provided, will load from that csv file + that should have the following columns: + name,x,y + """ + nodes = list() + if filename is not None: + df = pd.read_csv(filename) + for _, row in df.iterrows(): + nodes.append(Problem2D.Node(row["name"], row["x"], row["y"])) + distances = np.zeros((len(nodes), len(nodes))) + for i, n1 in enumerate(nodes): + for j, n2 in enumerate(nodes): + distances[i, j] = n1.distance(n2) + + super().__init__(nodes, distances) + + + def to_graphviz(self, show_distances=True): + """ + Return a Graphviz object representing the problem. + Works directly in Jupyter (just evaluate the returned object). + """ + try: + from graphviz import Graph + except ImportError: + print("you need to install graphviz to use this function") + return None + + G = Graph() + # add nodes + for i, n in enumerate(self.nodes): + # use same coordinates as in the ui + G.node(str(i), label=n.name, pos=f"{n.x},{-n.y}!", shape="circle") + + # add edges + for i, _n1 in enumerate(self.nodes): + for j, _n2 in enumerate(self.nodes): + if j <= i: + continue # avoid duplicates + kwdargs = {} + if show_distances: + kwdargs["xlabel"] = f"{self.distances[i, j]:.2f}" + G.edge(str(i), str(j), **kwdargs) + + # important for Graphviz to use the pos= attribute + G.attr(overlap="false") + G.attr(splines="true") + G.attr(layout="neato") # neato respects pos + return G + + + + def to_plotly(self, show_distances=True, + node_size=12, node_label_font=14, edge_width=1): + """ + Display the problem as an interactive Plotly graph in Jupyter. + - Nodes are fixed at their (x, y) positions. + - Distances appear as hover text on edges (optional). + """ + try: + import plotly.graph_objects as go + except ImportError: + print("you need to install plotly to use this function") + return None + xs = [n.x for n in self.nodes] + ys = [n.y for n in self.nodes] + labels = [n.name for n in self.nodes] + n = len(self.nodes) + + # Build edges + edge_x, edge_y, edge_texts = [], [], [] + for i in range(n): + for j in range(i + 1, n): # undirected, no duplicates + x0, y0 = self.nodes[i].x, self.nodes[i].y + x1, y1 = self.nodes[j].x, self.nodes[j].y + edge_x += [x0, x1, None] + edge_y += [y0, y1, None] + if show_distances: + edge_texts.append(f"{self.distances[i, j]:.2f}") + else: + edge_texts.append(None) + + # Trace for edges + edge_trace = go.Scatter( + x=edge_x, y=edge_y, + mode="lines", + line=dict(width=edge_width, color="gray"), + hoverinfo="text" if show_distances else "none", + text=edge_texts + ) + + # Trace for nodes + node_trace = go.Scatter( + x=xs, y=ys, + mode="markers+text", + text=labels, + textposition="top center", + marker=dict(size=node_size, color="blue"), + textfont=dict(size=node_label_font), + hoverinfo="text" + ) + + fig = go.Figure([edge_trace, node_trace]) + fig.update_layout( + showlegend=False, + xaxis=dict(showgrid=False, zeroline=False, visible=False), + yaxis=dict(showgrid=False, zeroline=False, visible=False, scaleanchor="x", scaleratio=1), + width=600, height=600, + margin=dict(l=20, r=20, t=20, b=20) + ) + + return fig diff --git a/notebooks/tps/ants/solver.py b/notebooks/tps/ants/solver.py new file mode 100644 index 0000000..a7f0e5a --- /dev/null +++ b/notebooks/tps/ants/solver.py @@ -0,0 +1,21 @@ +""" +the core of the matter +""" + +from problem import Problem + +class Solver: + + def __init__(self, problem: Problem): + self.problem = problem + + + def solve(self, nb_iterations) -> list[int]: + """ + this is where you should write the algorithm + it should return a permutation of the indices in problem + """ + indices = list(range(len(self.problem))) + + import random + return random.shuffle(indices) diff --git a/notebooks/tps/ants/ui.py b/notebooks/tps/ants/ui.py new file mode 100644 index 0000000..566c3a8 --- /dev/null +++ b/notebooks/tps/ants/ui.py @@ -0,0 +1,239 @@ +# pylint: disable=missing-docstring + +import itertools +from pathlib import Path + +import flet as ft +import flet.canvas as cv + +from problem import Problem2D +from solver import Solver + +RIGHT_MARGIN, BOTTOM_MARGIN = 50, 250 +START_SIZE = 100 +INPUT_SIZE = 70 + +MIN_WIDTH, MIN_HEIGHT = 600, 300 + +class AntsUi(ft.Column): + + def __init__(self, page): + + # we need this so we can modify the app width / height + self.page = page + # the problem at hand + self.problem = None + self.filename = None + # the path to draw + self.solution = None + + # the UI + pick_files_dialog = ft.FilePicker(on_result=self.pick_files_callback) + load_button = ft.ElevatedButton( + "Load file", + on_click=lambda _: pick_files_dialog.pick_files( + allow_multiple=False + )) + + iteration_input = ft.TextField( + label="Iters", + # value="20", + value="1", + width=INPUT_SIZE, + on_submit=lambda e: self.solve(), + ) + alpha_input = ft.TextField( + label="Alpha", + value="1", + width=INPUT_SIZE, + on_submit=lambda e: self.solve(), + ) + beta_input = ft.TextField( + label="Beta", + value="1", + width=INPUT_SIZE, + on_submit=lambda e: self.solve(), + ) + solve_button = ft.ElevatedButton( + "Solve", + on_click=lambda e: self.solve(), + ) + cheat_button = ft.ElevatedButton( + "Cheat", + on_click=lambda e: self.cheat(), + ) + + distance_area = ft.TextField(label="Distance", disabled=True) + show_labels = ft.Checkbox( + "Show labels", + value=False, + # value=True, + on_change=lambda e: self.refresh(), + ) + message_area = ft.Text() + + header = ft.Column([ + ft.Row([load_button, pick_files_dialog, + iteration_input, alpha_input, beta_input, + solve_button, cheat_button, + show_labels], + alignment=ft.MainAxisAlignment.SPACE_EVENLY, + ), + distance_area, + message_area, + ]) + + canvas = cv.Canvas(expand=True) + + # this is a column and its children are: + super().__init__([header, canvas]) + + # keep references for further use in the other methods + self.iteration_input = iteration_input + self.alpha_input = alpha_input + self.beta_input = beta_input + self.solve_button = solve_button + self.distance_area = distance_area + self.show_labels = show_labels + self.message_area = message_area + self.canvas = canvas + + + def message(self, message): + self.message_area.value = message + self.message_area.update() + + def pick_files_callback(self, e: ft.FilePickerResultEvent): + match e.files: + case []: + print("empty selection") + return + case first, second, *_: + print("multiple selection not supported") + return + case [single]: + self.load_problem(single.path) + + def load_problem(self, filename): + self.problem = Problem2D(filename) + self.filename = filename + self.solution = None + self.distance_area.value = "" + self.refresh() + try: + short_name = Path(filename).name + except Exception: + short_name = filename + self.message(f"Loaded {len(self.problem)} nodes from {short_name}") + + def clear(self): + self.canvas.shapes = [] + # self.page.update() + + def refresh(self): + self.clear() + # draw the path first so it's behind the nodes + self.draw_path() + self.draw_problem() + try: + path, distance = self.solution + self.distance_area.value = f"{distance:.2f}" + except TypeError: + self.distance_area.value = "n/a" + # do not forget to update the view + self.page.update() + + def draw_problem(self): + # the pencil to use + paint = ft.Paint(style=ft.PaintingStyle.FILL, color=ft.Colors.RED) + text_style = ft.TextStyle(font_family="Arial", size=10, color=ft.Colors.GREEN) + + for index, n in enumerate(self.problem): + self.canvas.shapes.append( + cv.Circle(n.x, n.y, 5, paint)) + if self.show_labels.value: + self.canvas.shapes.append( + cv.Text(n.x+10, n.y - 10, n.name, style=text_style)) + else: + self.canvas.shapes.append( + cv.Text(n.x+10, n.y - 10, str(index), style=text_style)) + self.page.window.width = max(max(n.x for n in self.problem) + RIGHT_MARGIN, MIN_WIDTH) + self.page.window.height = max(max(n.y for n in self.problem) + BOTTOM_MARGIN, MIN_HEIGHT) + # self.page.update() + + def draw_path(self): + if not self.solution: + return + stroke_paint = ft.Paint( + stroke_width=1, style=ft.PaintingStyle.STROKE, color=ft.Colors.BLUE) + path, distance = self.solution + chain = list(itertools.chain(path, [path[0]])) + for i, j in zip(chain, chain[1:]): + n1, n2 = self.problem[i], self.problem[j] + self.canvas.shapes.append( + cv.Line(n1.x, n1.y, n2.x, n2.y, stroke_paint)) + # self.page.update() + + def solve(self): + if self.problem is None: + self.message("No problem loaded") + return + self.solve_button.enabled = False + self.iteration_input.enabled = False + self.update() + self.message("Solving...") + self.page.update() + solver = Solver(self.problem, + alpha=float(self.alpha_input.value), + beta=float(self.beta_input.value)) + try: + iterations = int(self.iteration_input.value) + except ValueError: + self.message("Invalid number of iterations") + self.solve_button.enabled = True + self.iteration_input.enabled = True + return + self.solution = solver.solve(iterations) + self.refresh() + self.solve_button.enabled = True + self.iteration_input.enabled = True + self.message("done !") + self.page.update() + + def cheat(self): + if self.problem is None: + self.message("No problem loaded") + return + if not self.filename: + self.message("No file loaded") + return + cheated_filename = self.filename.replace(".csv", ".path") + short_name = Path(cheated_filename).name + self.message(f"Cheating: loading path from {short_name}...") + path = [] + import json + with open(cheated_filename) as f: + cheat = json.load(f) + path = cheat["path"] + if len(path) != len(self.problem): + self.message(f"Invalid path length found in {cheated_filename}") + return + distance = self.problem.distance_along_path(path) + self.solution = path, distance + self.message(f"Displaying Cheated path from {short_name}") + self.refresh() + + +def main(page): + page.window.width = START_SIZE + RIGHT_MARGIN + page.window.height = START_SIZE + BOTTOM_MARGIN + page.window.top = 10 + page.window.left = 800 + ants_ui = AntsUi(page) + page.add(ants_ui) + # for convenience during development + ants_ui.load_problem("data/video-06.csv") + page.update() + # ants_ui.solve() + +ft.app(main) diff --git a/notebooks/tps/auctions/.teacher/README-auctions-corrige-nb.md b/notebooks/tps/auctions/.teacher/README-auctions-corrige-nb.md index 0a94c2f..9abaa04 100644 --- a/notebooks/tps/auctions/.teacher/README-auctions-corrige-nb.md +++ b/notebooks/tps/auctions/.teacher/README-auctions-corrige-nb.md @@ -13,8 +13,9 @@ language_info: name: python nbconvert_exporter: python pygments_lexer: ipython3 -nbhosting: - title: "TP: ventes aux ench\xE8res" +authors: + - "Daniel Garnier-Moiroux" + - "Thierry Parmentelat" --- # ventes aux enchères @@ -134,7 +135,7 @@ test_blind.py ... [1 1. Ouvrez tout le dossier dans VSCode 2. Choisissez sur la gauche l'onglet 'Testing', et configurez les tests Python pour utiliser `unittest` -```{image} images/vscode-test-configure.png +```{image} media/vscode-test-configure.png :align: center ``` @@ -142,12 +143,13 @@ et aux questions suivantes, répondez: * Q: `Select the directory containing the tests:` A: `. Root directory` + * Q: `Select the pattern to identify test files:` A: `test_*.py` (vous devez avoir des fichiers de ce genre, comme `test_blind.py`) 3. À ce stade vous devriez voir les testeurs, toujours dans l'onglet gauche `Testing` -```{image} images/vscode-test-explore.png +```{image} media/vscode-test-explore.png :align: center ``` diff --git a/notebooks/tps/auctions/.teacher/media b/notebooks/tps/auctions/.teacher/media new file mode 120000 index 0000000..d803adf --- /dev/null +++ b/notebooks/tps/auctions/.teacher/media @@ -0,0 +1 @@ +../media/ \ No newline at end of file diff --git a/notebooks/tps/auctions/ARTEFACTS b/notebooks/tps/auctions/ARTEFACTS index 89bb933..b1e2ccb 100644 --- a/notebooks/tps/auctions/ARTEFACTS +++ b/notebooks/tps/auctions/ARTEFACTS @@ -1,4 +1,3 @@ -LICENSE README-auctions-nb.md auction.py blind.py diff --git a/notebooks/tps/auctions/ARTEFACTS-auctions.zip b/notebooks/tps/auctions/ARTEFACTS-auctions.zip index e80ea0f..e30ffc9 100644 Binary files a/notebooks/tps/auctions/ARTEFACTS-auctions.zip and b/notebooks/tps/auctions/ARTEFACTS-auctions.zip differ diff --git a/notebooks/tps/auctions/README-auctions-nb.md b/notebooks/tps/auctions/README-auctions-nb.md index 1935f31..c12bc9d 100644 --- a/notebooks/tps/auctions/README-auctions-nb.md +++ b/notebooks/tps/auctions/README-auctions-nb.md @@ -1,4 +1,5 @@ --- +authors: [Daniel Garnier-Moiroux, Thierry Parmentelat] jupytext: encoding: '# -*- coding: utf-8 -*-' main_language: python @@ -13,8 +14,6 @@ language_info: name: python nbconvert_exporter: python pygments_lexer: ipython3 -nbhosting: - title: "TP: ventes aux ench\xE8res" --- # ventes aux enchères @@ -102,7 +101,7 @@ test_blind.py ... [1 1. Ouvrez tout le dossier dans VSCode 2. Choisissez sur la gauche l'onglet 'Testing', et configurez les tests Python pour utiliser `unittest` -```{image} images/vscode-test-configure.png +```{image} media/vscode-test-configure.png :align: center ``` @@ -110,12 +109,13 @@ et aux questions suivantes, répondez: * Q: `Select the directory containing the tests:` A: `. Root directory` + * Q: `Select the pattern to identify test files:` A: `test_*.py` (vous devez avoir des fichiers de ce genre, comme `test_blind.py`) 3. À ce stade vous devriez voir les testeurs, toujours dans l'onglet gauche `Testing` -```{image} images/vscode-test-explore.png +```{image} media/vscode-test-explore.png :align: center ``` diff --git a/notebooks/tps/auctions/images/vscode-test-configure.png b/notebooks/tps/auctions/media/vscode-test-configure.png similarity index 100% rename from notebooks/tps/auctions/images/vscode-test-configure.png rename to notebooks/tps/auctions/media/vscode-test-configure.png diff --git a/notebooks/tps/auctions/images/vscode-test-explore.png b/notebooks/tps/auctions/media/vscode-test-explore.png similarity index 100% rename from notebooks/tps/auctions/images/vscode-test-explore.png rename to notebooks/tps/auctions/media/vscode-test-explore.png diff --git a/notebooks/tps/boids/.teacher/README-boids-corrige-nb.md b/notebooks/tps/boids/.teacher/README-boids-corrige-nb.md index 8080bcc..a53164f 100644 --- a/notebooks/tps/boids/.teacher/README-boids-corrige-nb.md +++ b/notebooks/tps/boids/.teacher/README-boids-corrige-nb.md @@ -15,20 +15,15 @@ nbhosting: title: 'TP: les boids' --- -+++ {"tags": ["prune-cell"]} - # TP - les boids avec `arcade` -+++ - -Licence CC BY-NC-ND, Thierry Parmentelat - +++ {"tags": ["prune-cell"]} ````{admonition} nothing to prune :class: warning -there are no difference - apart from this very cell - between the teacher and the student version, but the notebook is duplicated in .teacher for consistency +there are no difference - apart from this very cell - between the teacher and the student version, +but the notebook is duplicated in `.teacher` for consistency ```` +++ @@ -37,12 +32,13 @@ there are no difference - apart from this very cell - between the teacher and th {download}`vous aurez besoin du zip qui se trouve ici<./ARTEFACTS-boids.zip>` ``` -+++ +--- ## c'est quoi les *boids* ? une simulation ludique où on tente de reproduire le comportement d'animaux en -groupes - typiquement oiseaux et poissons +groupes +typiquement nuée d'oiseaux ou banc de poissons ### intérêts @@ -51,12 +47,13 @@ c'est intéressant parce que * c'est une illustration du modèle de programmation "par acteurs" chaque entité dans l'univers adapte son comportement en fonction de ses voisins immédiats + * on y découvre [arcade, une autre bibliothèque de jeux pour Python](https://api.arcade.academy/en/latest/) et c'est intéressant pour nous car cette librairie se programme exclusivement **par spécialisation de classes** -+++ +--- ## introduction @@ -65,11 +62,12 @@ dans ce TP nous allons * découvrir (très superficiellement) la librairie `arcade` * et l'utiliser pour implémenter un début de simulation de *boids* -+++ +--- ### notre sujet -dans sa version originale chaque animal décide de sa trajectoire, **en fonction uniquement de ses voisins proches**, et cela en suivant trois règles: +dans sa version originale chaque animal décide de sa trajectoire, **en fonction +uniquement de ses voisins proches**, et cela en suivant trois règles: * séparation (typiquement pour éviter les obstacles) * alignement (tout le monde va, en gros, dans la même direction) @@ -80,223 +78,225 @@ c'est-à-dire ce qui permet aux boids d'éviter de heurter les autres boids, et les élèves rapides et/ou motivés pourront poursuivre jusqu'à réaliser une simulation complète s'ils le souhaitent -+++ +--- ### en vidéo voici d'abord une vidéo très courte pour vous montrer les différentes étapes du TP - +::::{admonition} arcade 3.x +:class: danger -l'enjeu principal ici est d'être exposé à ce style de **programmation par spécialisation de classes** -aussi ce chemin est uniquement **indicatif**, et surtout à destination des élèves qui en ressentiront le besoin -si vous vous sentez, vous pouvez très bien vous y prendre complètement autrement, -le contrat est rempli dès que vous avez: **des obstacles** fixes, et **des boids** qui évoluent **spontanément** en **évitant** les autres objets +comme la librairie `arcade` a récemment évolué vers la version 3.x, le code de +démarrage a été mis à jour en conséquence, et c'est pourquoi avec le code de +départ que je vous fournis **vous allez commencer directement à l'étape 2** de la +vidéo +:::: -+++ +::::{figure} +:align: center +```{iframe} https://www.youtube.com/embed/d4789cBD3Ek?rel=0&controls=1 +``` +penser à la lire en plein écran +:::: + +l'enjeu principal ici est d'être exposé à la **programmation par spécialisation de classes** +aussi ce chemin par étapes est uniquement **indicatif**, et surtout à +destination des élèves qui ressentent le besoin d'être guidés pas à pas +si vous vous sentez, vous pouvez très bien vous y prendre complètement autrement ! +le contrat est rempli dès que vous avez: **des obstacles** fixes, et **des +boids** qui évoluent **spontanément** en **évitant** les obstacles et les autres +boids + +--- -### contenu +### contenu du zip le zip contient -* le starter code dans `boids-01.py` +* le starter code dans `boids-02.py` * les figures dans le dossier `media/` -+++ +--- ## pas à pas -+++ - -### v01: starter code - -```python -""" -display a single object, inert, at (100, 100) -""" - -import arcade +### v02: starter code -BACKGROUND = arcade.color.ALMOND -IMAGE = "media/arrow-resized.png" +* dans le zip vous trouverez le code suivant; n'hésitez pas à le renommer dans + un fichier `boids.py` si vous préférez -class Window(arcade.Window): +::::{admonition} le code de départ +:class: dropdown - def __init__(self): - super().__init__(800, 800, "My first boid") - arcade.set_background_color(BACKGROUND) - self.boid = None +:::{literalinclude} boids-02.py +::: +:::: - def setup(self): - boid = arcade.Sprite(IMAGE) - boid.center_x = 100 - boid.center_y = 100 - self.boid = boid - - def on_draw(self): - arcade.start_render() - self.boid.draw() - - def on_update(self, delta_time): - self.boid.update() - -window = Window() -window.setup() -arcade.run() -``` - -* installez la librairie +* installez la librairie (comment fait-on déjà ?) * vérifiez que vous avez le fichier `media/arrow-resized.png` (il est dans le zip) -* copiez et lancez le code ci-dessus +* lancez le code ci-dessus vous devez voir un seul boid immobile, dans le coin en bas à gauche -+++ - -installez la librairie, copiez le code ci-dessus dans par exemple `boid.py`, et lancez-le -vous devez voir un seul boid dans le coin en bas à gauche, il est immobile - -+++ - -#### commentaire - -observez la différence de style de programmation par rapport à `pygame` -comment aurait-on écrit la même chose en `pygame` ? - -+++ - -#### l'implicite +::::{admonition} l'implicite dans ce code, on utilise - et ce n'est pas du tout explicite - le fait que * le module `arcade` vient avec une *mainloop* - `arcade.run()` - qui se charge de faire 'avancer' le jeu - par défaut à plusieurs dizaines de Hz + qui se charge de faire 'avancer' le jeu - par défaut à plusieurs dizaines de Hz - et cela même si avec cette version 01 on ne voit pas grand chose bouger ⏸️ + * cette mainloop va appeler les méthodes `on_draw()` et `on_update()` sur chaque instance de `Window` - c'est là que nous pouvons programmer la logique de notre "*jeu*" + +* notamment nous disons que pour mettre à jour le jeu (`on_update`), + on doit mettre à jour tous les objets qui sont dans la `SpriteList` + `self.boids`, ce que l'on fait par l'appel à `self.boids.update()` + * la classe `Sprite` permet d'ajouter des objets qui savent s'afficher - ici on a juste créé l'objet à partir d'un png, puis fixé `boid.center_x` et `boid.center_y` - + ici on a juste créé l'objet à partir d'une image `.png`, puis fixé + `boid.center_x` et `boid.center_y` + +:::{admonition} pour les forts +:class: dropdown warning pour les forts: dans le même registre, mais plus subtil: * il a suffi qu'on crée une instance de `Window` pour qu'elle soit prise en compte par cette boucle; comment c'est possible d'après vous ? +::: -+++ - -### v02: de la place pour plusieurs boids +:::: -on veut garder exactement le même comportement (un seul boid fixe pour l'instant) -mais on va modifier le code pour pouvoir (plus tard) en créer plusieurs +::::{admonition} vs pygame +:class: admonition-small -pour cela, on pourrait penser à utiliser une liste standard Python, -mais je vous invite à utiliser plutôt la classe `SpriteList` que fournit `arcade` +observez la différence de style de programmation par rapport à `pygame` +comment aurait-on écrit la même chose en `pygame` ? +:::: -+++ +::::{admonition} à faire pour aider le debug -#### debugging +partant de là, je vous recommande de: -en plus de ça, je vous recommande de: -* prévoir le cas du debug, par exemple avec une variable globale DEBUG +* prévoir le cas du debug, par exemple avec une variable globale `DEBUG` * et dans ce cas afficher un message à chaque fois que le boid est mis à jour (surtout pour mettre en évidence la *mainloop* à ce stade) -* et aussi de [regarder la méthode `set_update_rate()`](https://api.arcade.academy/en/latest/api/window.html?highlight=set_update_rate#arcade.Window.set_update_rate) + +* et aussi de [regarder la méthode + `set_update_rate()`](https://api.arcade.academy/en/2.6.1/api/window.html#arcade.Window.set_update_rate) pour ralentir la cadence, ce qui sera sûrement utile à un moment donné pour débugger + * pourquoi ne pas aussi imprimer un message pour voir à quel rythme sont faits les `draw()` et `update()` +:::: -+++ +--- ### v03: le boid avance -maintenant on va faire bouger notre objet, et lui donner un mouvement rectiligne +maintenant on va faire bouger notre objet, et lui donner un mouvement rectiligne -et pour ça on va cesser d'utiliser directement la classe `Sprite`, +et pour ça on va cesser d'utiliser directement la classe `Sprite`, et on va au contraire la **spécialiser** pour créer notre propre classe `Boid` (c-à-d que la classe `Boid` hérite de la classe `Sprite`) -#### à savoir +::::{admonition} à savoir * pour chaque cycle de la *mainloop*, l'objet `Window` utilise - * sa méthode `on_update()` pour mettre à jour l'état des objets - * et sa méthode `on_draw()` pour les redessiner - c'est pour cela que celle-ci commence par `start_render()` + * sa méthode `on_update()` pour mettre à jour l'état des objets (juste en mémoire) + * et sa méthode `on_draw()` pour les redessiner + c'est pour cela que celle-ci commence par `clear()` qui efface tout, et remet simplement le fond d'écran - * on peut donc **faire avancer le boid** simplement en **redéfinissant quelques méthodes** dans le code -* par défaut les deux méthodes (`draw()` et `update()`) se produisent à la même fréquence (60Hz), - mais avec `set_update_rate()` on ralentit uniquement `update()` - c'est pourquoi `on_update(time_delta)` reçoit le temps (en ms) - qui s'est écoulé depuis le dernier appel - -et aussi, mais moins crucial à ce stade: - -* on n'en a pas besoin tout de suite, mais dans la classe `Sprite` - il y a un attribut `angle` qui sert à dire de combien on veut tourner l'image -* et naturellement dans notre cas, on va vouloir que l'objet avance dans la direction de la flêche - (même si ce stade on ne peut pas encore faire tourner le boid) +* bref, le résultat c'est qu'on peut **faire avancer le boid** + simplement en **redéfinissant quelques méthodes** dans le code +* par défaut les deux méthodes (`draw()` et `update()`) se produisent à la même fréquence (60Hz), + et avec `set_update_rate()` on ralentit uniquement `update()` +* `on_update(time_delta)` reçoit le temps (en ms) qui s'est écoulé depuis le + dernier update(), c'est pratique pour faire des mouvements si on connaît la + vitesse de déplacement de l'objet +:::: + +::::{admonition} et aussi, mais moins crucial +:class: warning + +* on n'en a pas besoin tout de suite, mais dans la classe `Sprite`, il y a un + attribut `angle` qui sert à dire de combien on veut tourner l'image lors de + l'affichage +* et naturellement dans notre cas, on va vouloir que l'objet avance dans la + direction de la flêche (même si ce stade on ne peut pas encore faire tourner + le boid) * aussi il serait habile de considérer que la vitesse du boid est un de ses attributs (et non pas une constante) même si là encore on n'en a pas besoin tout de suite * pensez à exprimer les vitesses en pixels par seconde +:::: -+++ +--- ### v04: en circuit fermé -on va faire en sorte que le plateau devienne infini en le refermant sur lui-même -un objet sortant à gauche réapparait à droite, et idem dans tous les sens -ça peut valoir le coup de "sortir" la taille du jeu pour en faire des constantes - -et pour que ce soit plus facile à tester on va orienter le boid vers le coin en bas à gauche +* on va faire en sorte que le plateau devienne infini en le refermant sur lui-même +i.e. un objet sortant à gauche réapparait à droite, et idem dans tous les sens… +* ça peut valoir le coup de "sortir" la taille du jeu pour en faire des constantes +* et pour que ce soit plus facile à tester on va orienter le boid vers le coin en bas à gauche si vous vous y êtes bien pris pour le faire avancer, c'est juste une question de changer son `.angle` -+++ +--- ### v05: du bruit sur le cap faites en sorte que le trajet du boid ne soit plus strictement rectiligne en ajoutant à chaque pas un léger bruit sur la direction -+++ +--- ### v06: les touches `←` et `→` faites en sorte de pouvoir contrôler la direction du boid avec les touches du clavier -#### à savoir +::::{admonition} à savoir -* pour intercepter les événements clavier, vous pouvez définir dans la classe `Window` les méthodes -```python -def on_key_press(self, key, modifiers): - pass -def on_key_release(self, key, modifiers): - pass -``` -* la librairie expose par exemple la constante `arcade.key.LEFT` +* pour intercepter les événements clavier, vous pouvez définir dans la classe + `Window` les méthodes + ```python + def on_key_press(self, key, modifiers): + pass + def on_key_release(self, key, modifiers): + pass + ``` +* la librairie expose des constantes comme par exemple `arcade.key.LEFT` +:::: -#### attention +::::{admonition} *user-friendliness* -ceci est beaucoup plus facile à utiliser si le boid continue de tourner pendant **tout le temps où la touche est enfoncée** - plutôt que de devoir appuyer plein de fois sur la touche +soyez sympa avec vos utilisateurs: ceci est beaucoup plus facile à utiliser si +le boid continue de tourner pendant **tout le temps où la touche est enfoncée** - plutôt que +de devoir appuyer plein de fois sur la touche… +:::: -+++ +--- ### v07: ajouter un obstacle ajoutez un unique obstacle, immobile, par exemple au centre du jeu vous trouverez une image `media/obstacle-resized.png` pour le matérialiser -**2 options** +::::{admonition} 2 options + * on pourrait facilement s'en sortir avec juste la classe `Sprite` -* mais je vous demande, pour vous exercer à la spécialisation de classes, de créer une classe `Obstacle` +* mais je vous demande, pour vous exercer à la spécialisation de classes, de + créer une classe `Obstacle` +:::: -+++ +--- ### v08: créez une grille d'obstacles remplacez l'unique obstacle par une grille d'obstacles -mettez en 10 x 10, ils sont donc espacés de 80px +par exemple: mettez en 10 x 10, ils sont donc espacés de 80px -+++ +--- ### v09: détecter les voisins @@ -305,126 +305,146 @@ prenez 20 pixels comme rayon de détection pour ma part j'ai rendu le boid semi-transparent, en jouant sur l'attribut `alpha` des `Sprite` (255 = opaque, 0 = transparent) -+++ +::::{admonition} discussion -#### discussion +ici on a le choix d'utiliser -ici on a le choix d'utiliser * soit une variable globale (la liste de tous les obstacles) * ou de rajouter dans la classe `Boid` une liste d'obstacles quels sont les avantages et les inconvénients des 2 approches ? + * en termes de vitesse de programmation * en termes de réutilisabilité je vous recommande la deuxième option +:::: -+++ +--- ### v10: la règle de séparation implémentez la règle de séparation on peut la résumer comme ceci: -+++ - ```{image} media/separation.png :align: center +:width: 80% ``` -+++ +--- c'est-à-dire que quand on s'intéresse au boid b, on va -* ignorer tous les objets qui se trouvent plus loin qu'un certain rayon 'r' -* et pour tous ceux qui sont proches, par exemple o, on calcule un vecteur $\overrightarrow{\delta}$ qui va permettre d'écarter l'objet b de o - je n'ai pas trouvé de formule dans la littérature pour calculer $\overrightarrow{\delta}$, j'ai sorti de mon chapeau la formule suivante - $\overrightarrow{\delta} = \overrightarrow{ob} * \frac{1}{2}(1-\frac{d}{r})$ +* ignorer tous les objets (en rouge) qui se trouvent plus loin qu'un certain rayon 'r' +* et pour tous ceux qui sont proches (en vert), par exemple o, on calcule un + vecteur $\overrightarrow{\delta}$ qui va permettre d'écarter l'objet b de o - de façon à ce que: - * les objets sur le cercle ont une influence nulle, - * et si o est tout proche de b, il est repoussé à un rayon r/2 +je n'ai pas trouvé de formule dans la littérature pour calculer +$\overrightarrow{\delta}$, j'ai sorti de mon chapeau la formule suivante + +::::{math} +:align: center +\overrightarrow{\delta} = \overrightarrow{ob} \times \frac{1}{2}(1-\frac{d}{r}) +:::: -on fait la somme de tous ces vecteurs, et on l'ajoute au déplacement de b +de façon à ce que: -i.e. dans l'exemple de la figure, lorsqu'on traite le boid en b: -* on ignore les boids aux endroits en rouge -* et on fait la somme des 3 vecteurs (en vert) +* les objets sur le cercle ont une influence nulle, +* et si o est tout proche de b, il est repoussé à un rayon r/2 + +on fait la somme de tous ces vecteurs, et on l'ajoute au déplacement de b +i.e., dans l'exemple de la figure, lorsqu'on traite le boid en b: + +* on ignore les boids éloignés - en rouge +* et pour les 3 boids proches - en vert - on fait la somme des 3 vecteurs de + "repoussement" (en vert aussi) * qu'on ajoute naturellement au déplacement dû à la vitesse du boid -#### à noter +::::{admonition} à noter -dans cette version, en cas de collision, on se contente de modifier la position du boid, et pas son orientation; on arrangera ca plus tard +dans cette version, en cas de collision, on se contente de modifier la position +du boid, et pas son orientation; on arrangera ca plus tard +:::: -+++ +--- + +### v11: orienter correctement + +* dans cette version, on va essayer de répercuter les collisions sur l'orientation du boid +* et pour ça on va mettre à jour brutalement l'attribut `angle` +* à ce stade, on se base uniquement sur le mouvement qui est fait à l'instant t: +* pour être explicite, si on passe de *(x1, y1)* à *(x2, y2)*, on oriente + le boid pour s'aligner sur le vecteur *(x2-x1, y2-y1)* -### v11: on essaie d'orienter correctement +l'effet n'est pas forcément très réussi, vous devez voir l'orientation sauter brutalement d'un angle à un autre -dans cette version, on va essayer de répercuter les collisions sur l'orientation du boid -et pour ça on va mettre à jour brutalement l'attribut `angle` uniquement sur le mouvement qui est fait à l'instant t -i.e, pour être clair, que si on passe de (x1, y1) à (x2, y2), on oriente le boid pour s'aligner sur le vecteur (x2-x1, y2-y1) -l'effet n'est pas forcément très réussi, vous devez voir l'orientation sauter brutalement d'un angle un autre +::::{admonition} à savoir -**à savoir** voyez la fonction `math.atan2` qui est pratique ici +:::: -+++ +--- -### v12: on lisse les changements d'orientation +### v12: tourner plus doucement -comment pourrait-on obtenir quelque chose d'un peu plus élégant, en ce qui concerne les changements de direction ? +pour lisser les changements d'orientation: comment pourrait-on obtenir quelque +chose d'un peu plus élégant, en ce qui concerne les changements de direction ? -+++ +--- ### v13: les touches `↑` et `↓` -faire en sorte qu'on puisse contrôler aussi la vitesse avec les touches +faire en sorte qu'on puisse contrôler aussi la vitesse avec les touches `↑` et `↓` essayez le comportement de l'évitement d'obstacles à plusieurs vitesses -+++ +--- ### v14: plusieurs boids remplacez l'unique boid par un ensemble de 20 boids -sans changer la séparation, qui est calculée seulement à partir des obstacles +sans changer, pour l'instant, la séparation, qui est calculée seulement à partir des obstacles -+++ +--- -### v15: éviter les obstacles **et** les autres boids +### v15: éviter aussi les autres boids assurez-vous que la séparation permet d'éviter tous les objets (obstacles et boids) -+++ +--- ### en option... vous pouvez ensuite améliorer dans les directions suivantes : + * implémenter les deux autres règles (alignement et cohésion) * faire en sorte qu'on puisse interactivement ajouter/enlever des obstacles * faire des raccourcis clavier pour activer/désactiver les 3 règles, et le bruit * bien tenir compte de la vitesse de rafraichissement du jeu i.e., est-ce que la simulation continue de fonctionner si on ralentit la logique du jeu avec `Window.set_update_rate()` + * etc... pour information voici une synthèse des 3 règles, à vous de chercher pour préciser comment interpréter ces figures -+++ - ```{image} media/boids-rules.png :align: center ``` -+++ +--- ## pour aller plus loin -* pour plus de détails sur les boids, +* pour plus de détails sur les boids, voir [la page de Craig Reynolds](http://www.red3d.com/cwr/boids/), - l'auteur original, et [la page wikipedia](https://en.wikipedia.org/wiki/Boids) - -* je vous signale un tutoriel intéressant sur la librairie arcade: - https://realpython.com/arcade-python-game-framework/ - -* enfin d'autres vidéos qui peuvent vous inspirer également - - + l'auteur original +* et [la page wikipedia](https://en.wikipedia.org/wiki/Boids) +* je vous signale [un tutoriel intéressant sur la librairie arcade](https://realpython.com/arcade-python-game-framework/) assez long / exhaustif +* enfin d'autres vidéos qui peuvent vous inspirer également (parmi $10^n$ autres) : + + ::::{grid} 2 + ```{iframe} https://www.youtube.com/embed/QbUPfMXXQIY?rel=0&controls=1 + ``` + ```{iframe} https://www.youtube.com/embed/bqtqltqcQhw?rel=0&controls=1 + ``` + :::: diff --git a/notebooks/tps/boids/.teacher/boids-01.py b/notebooks/tps/boids/.teacher/boids-01.py deleted file mode 120000 index feb1317..0000000 --- a/notebooks/tps/boids/.teacher/boids-01.py +++ /dev/null @@ -1 +0,0 @@ -../boids-01.py \ No newline at end of file diff --git a/notebooks/tps/boids/.teacher/boids-02.py b/notebooks/tps/boids/.teacher/boids-02.py deleted file mode 100644 index 6cbb7d4..0000000 --- a/notebooks/tps/boids/.teacher/boids-02.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -Window has a self.boids instead of a self.boid -""" - -import arcade - -BACKGROUND = arcade.color.ALMOND -IMAGE = "media/arrow-resized.png" - -class Window(arcade.Window): - - def __init__(self): - super().__init__(800, 800, "My first boid") - arcade.set_background_color(BACKGROUND) - self.set_location(800, 100) - self.boids = None - - def setup(self): - boid = arcade.Sprite(IMAGE) - boid.center_x = 100 - boid.center_y = 100 - self.boids = arcade.SpriteList() - self.boids.append(boid) - - def on_draw(self): - arcade.start_render() - self.boids.draw() - - def on_update(self, delta_time): - self.boids.update() - -window = Window() -window.setup() -arcade.run() diff --git a/notebooks/tps/boids/.teacher/boids-02.py b/notebooks/tps/boids/.teacher/boids-02.py new file mode 120000 index 0000000..a8f8830 --- /dev/null +++ b/notebooks/tps/boids/.teacher/boids-02.py @@ -0,0 +1 @@ +../boids-02.py \ No newline at end of file diff --git a/notebooks/tps/boids/.teacher/boids-03.py b/notebooks/tps/boids/.teacher/boids-03.py index 67129d1..d07b891 100644 --- a/notebooks/tps/boids/.teacher/boids-03.py +++ b/notebooks/tps/boids/.teacher/boids-03.py @@ -17,7 +17,7 @@ def __init__(self): self.center_x, self.center_y = 100, 100 self.speed = 100 # in pixels / second - def on_update(self, delta_time): + def update(self, delta_time): self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) @@ -36,11 +36,11 @@ def setup(self): self.boids.append(boid) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) + self.boids.update() window = Window() window.setup() diff --git a/notebooks/tps/boids/.teacher/boids-04.py b/notebooks/tps/boids/.teacher/boids-04.py index dfbc0d7..c308bfd 100644 --- a/notebooks/tps/boids/.teacher/boids-04.py +++ b/notebooks/tps/boids/.teacher/boids-04.py @@ -17,12 +17,12 @@ class Boid(arcade.Sprite): def __init__(self): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second - def on_update(self, delta_time): - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + def update(self, delta_time): + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -42,11 +42,11 @@ def setup(self): self.boids.append(boid) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) + self.boids.update() window = Window() window.setup() diff --git a/notebooks/tps/boids/.teacher/boids-05.py b/notebooks/tps/boids/.teacher/boids-05.py index 8c3d71c..8242ba2 100644 --- a/notebooks/tps/boids/.teacher/boids-05.py +++ b/notebooks/tps/boids/.teacher/boids-05.py @@ -18,15 +18,14 @@ class Boid(arcade.Sprite): def __init__(self): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second - def on_update(self, delta_time): - self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + def update(self, delta_time): + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -46,11 +45,11 @@ def setup(self): self.boids.append(boid) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) + self.boids.update(delta_time) window = Window() window.setup() diff --git a/notebooks/tps/boids/.teacher/boids-06.py b/notebooks/tps/boids/.teacher/boids-06.py index 5e966cf..c1a0652 100644 --- a/notebooks/tps/boids/.teacher/boids-06.py +++ b/notebooks/tps/boids/.teacher/boids-06.py @@ -19,18 +19,18 @@ class Boid(arcade.Sprite): def __init__(self): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 - def on_update(self, delta_time): + def update(self, delta_time): self.angle += self.steer self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -57,11 +57,11 @@ def setup(self): self.boids.append(boid) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) + self.boids.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-07.py b/notebooks/tps/boids/.teacher/boids-07.py index bad8914..b8312bb 100644 --- a/notebooks/tps/boids/.teacher/boids-07.py +++ b/notebooks/tps/boids/.teacher/boids-07.py @@ -28,18 +28,18 @@ class Boid(arcade.Sprite): def __init__(self): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 - def on_update(self, delta_time): + def update(self, delta_time): self.angle += self.steer self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -69,13 +69,13 @@ def setup(self): self.obstacles.append(Obstacle(WIDTH//2, HEIGHT//2)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-08.py b/notebooks/tps/boids/.teacher/boids-08.py index e0578d9..57b4589 100644 --- a/notebooks/tps/boids/.teacher/boids-08.py +++ b/notebooks/tps/boids/.teacher/boids-08.py @@ -31,18 +31,18 @@ class Boid(arcade.Sprite): def __init__(self): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 - def on_update(self, delta_time): + def update(self, delta_time): self.angle += self.steer self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -76,13 +76,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-09.py b/notebooks/tps/boids/.teacher/boids-09.py index 24f91dd..c8f78b5 100644 --- a/notebooks/tps/boids/.teacher/boids-09.py +++ b/notebooks/tps/boids/.teacher/boids-09.py @@ -33,12 +33,12 @@ class Boid(arcade.Sprite): def __init__(self, obstacles): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.obstacles = obstacles - def on_update(self, delta_time): + def update(self, delta_time): for o in self.obstacles: if math.dist((self.center_x, self.center_y), @@ -52,8 +52,8 @@ def on_update(self, delta_time): self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) self.center_x %= WIDTH self.center_y %= HEIGHT @@ -87,13 +87,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-10.py b/notebooks/tps/boids/.teacher/boids-10.py index 6a6bc11..1035937 100644 --- a/notebooks/tps/boids/.teacher/boids-10.py +++ b/notebooks/tps/boids/.teacher/boids-10.py @@ -34,7 +34,7 @@ class Boid(arcade.Sprite): def __init__(self, obstacles): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.obstacles = obstacles @@ -57,14 +57,14 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): self.angle += self.steer self.angle += (1 - 2*random.random()) * NOISE_ANGLE - self.center_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - self.center_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + self.center_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + self.center_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() self.center_x += avoid_x @@ -102,13 +102,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-11.py b/notebooks/tps/boids/.teacher/boids-11.py index 4a9513d..eb81316 100644 --- a/notebooks/tps/boids/.teacher/boids-11.py +++ b/notebooks/tps/boids/.teacher/boids-11.py @@ -33,7 +33,7 @@ class Boid(arcade.Sprite): def __init__(self, obstacles): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.obstacles = obstacles @@ -56,11 +56,11 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): # convenience: do a atan2 but in degrees # and with args in the natural order X Y def angle_from_move(move_x, move_y): - return 180/math.pi*math.atan2(move_y, move_x) + return -180/math.pi*math.atan2(move_y, move_x) # accumulate the move move_x, move_y = 0., 0. @@ -69,8 +69,8 @@ def angle_from_move(move_x, move_y): self.angle += (1 - 2*random.random()) * NOISE_ANGLE # add our own speed - move_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - move_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + move_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + move_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() move_x += avoid_x @@ -116,13 +116,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-12.py b/notebooks/tps/boids/.teacher/boids-12.py index 453674e..4a33fdf 100644 --- a/notebooks/tps/boids/.teacher/boids-12.py +++ b/notebooks/tps/boids/.teacher/boids-12.py @@ -36,7 +36,7 @@ class Boid(arcade.Sprite): def __init__(self, obstacles): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.obstacles = obstacles @@ -59,11 +59,11 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): # convenience: do a atan2 but in degrees # and with args in the natural order X Y def angle_from_move(move_x, move_y): - return 180/math.pi*math.atan2(move_y, move_x) + return -180/math.pi*math.atan2(move_y, move_x) # accumulate the move move_x, move_y = 0., 0. @@ -72,8 +72,8 @@ def angle_from_move(move_x, move_y): self.angle += (1 - 2*random.random()) * NOISE_ANGLE # add our own speed - move_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - move_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + move_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + move_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() move_x += avoid_x @@ -122,13 +122,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-13.py b/notebooks/tps/boids/.teacher/boids-13.py index 363e312..43387a3 100644 --- a/notebooks/tps/boids/.teacher/boids-13.py +++ b/notebooks/tps/boids/.teacher/boids-13.py @@ -37,7 +37,7 @@ class Boid(arcade.Sprite): def __init__(self, obstacles): super().__init__(IMAGE) self.center_x, self.center_y = 100, 100 - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.acceleration = 1 @@ -61,11 +61,11 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): # convenience: do a atan2 but in degrees # and with args in the natural order X Y def angle_from_move(move_x, move_y): - return 180/math.pi*math.atan2(move_y, move_x) + return -180/math.pi*math.atan2(move_y, move_x) # accumulate the move move_x, move_y = 0., 0. @@ -75,8 +75,8 @@ def angle_from_move(move_x, move_y): self.angle += (1 - 2*random.random()) * NOISE_ANGLE # add our own speed - move_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - move_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + move_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + move_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() move_x += avoid_x @@ -132,13 +132,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-14.py b/notebooks/tps/boids/.teacher/boids-14.py index c0e9e22..7b392d8 100644 --- a/notebooks/tps/boids/.teacher/boids-14.py +++ b/notebooks/tps/boids/.teacher/boids-14.py @@ -43,7 +43,7 @@ def __init__(self, obstacles, x=None, y=None): super().__init__(IMAGE) self.center_x = x if x is not None else random.random()*WIDTH self.center_y = y if y is not None else random.random()*HEIGHT - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.acceleration = 1 @@ -67,11 +67,11 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): # convenience: do a atan2 but in degrees # and with args in the natural order X Y def angle_from_move(move_x, move_y): - return 180/math.pi*math.atan2(move_y, move_x) + return -180/math.pi*math.atan2(move_y, move_x) # accumulate the move move_x, move_y = 0., 0. @@ -81,8 +81,8 @@ def angle_from_move(move_x, move_y): self.angle += (1 - 2*random.random()) * NOISE_ANGLE # add our own speed - move_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - move_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + move_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + move_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() move_x += avoid_x @@ -138,13 +138,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids-15.py b/notebooks/tps/boids/.teacher/boids-15.py index 529d304..9b84dcd 100644 --- a/notebooks/tps/boids/.teacher/boids-15.py +++ b/notebooks/tps/boids/.teacher/boids-15.py @@ -41,7 +41,7 @@ def __init__(self, boids, obstacles, x=None, y=None): super().__init__(IMAGE) self.center_x = x if x is not None else random.random()*WIDTH self.center_y = y if y is not None else random.random()*HEIGHT - self.angle = -135 + self.angle = 135 self.speed = 100 # in pixels / second self.steer = 0 self.acceleration = 1 @@ -66,11 +66,11 @@ def avoid_move(self) -> tuple[float, float]: move_y += alpha*(self.center_y-o.center_y) return move_x, move_y - def on_update(self, delta_time): + def update(self, delta_time): # convenience: do a atan2 but in degrees # and with args in the natural order X Y def angle_from_move(move_x, move_y): - return 180/math.pi*math.atan2(move_y, move_x) + return -180/math.pi*math.atan2(move_y, move_x) # accumulate the move move_x, move_y = 0., 0. @@ -80,8 +80,8 @@ def angle_from_move(move_x, move_y): self.angle += (1 - 2*random.random()) * NOISE_ANGLE # add our own speed - move_x += self.speed * delta_time * math.cos(math.radians(self.angle)) - move_y += self.speed * delta_time * math.sin(math.radians(self.angle)) + move_x += self.speed * delta_time * math.cos(math.radians(-self.angle)) + move_y += self.speed * delta_time * math.sin(math.radians(-self.angle)) avoid_x, avoid_y = self.avoid_move() move_x += avoid_x @@ -137,13 +137,13 @@ def setup(self): self.obstacles.append(Obstacle(ox, oy)) def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): - self.boids.on_update(delta_time) - self.obstacles.on_update(delta_time) + self.boids.update(delta_time) + self.obstacles.update(delta_time) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: diff --git a/notebooks/tps/boids/.teacher/boids.py b/notebooks/tps/boids/.teacher/boids.py index 08a3324..b637805 100644 --- a/notebooks/tps/boids/.teacher/boids.py +++ b/notebooks/tps/boids/.teacher/boids.py @@ -93,8 +93,8 @@ def __init__(self, self.center_y = y if y is not None else random.random()*HEIGHT self.angle = angle if angle is not None else 360 * random.random() # the boid's speed, exposed to other boids for the alignment rule - self.move_x = BOID_SPEED*math.cos(math.radians(self.angle)) - self.move_y = BOID_SPEED*math.sin(math.radians(self.angle)) + self.move_x = BOID_SPEED*math.cos(math.radians(-self.angle)) + self.move_y = BOID_SPEED*math.sin(math.radians(-self.angle)) # a cache of the entities that are close-by # will be computed at each update self.close_flock = None @@ -224,7 +224,7 @@ def speed_limit(self, speed: Vector, limit) -> Vector: return speed * limit / norm - def update(self): + def update(self, delta_time): # compute the subset of the flock that is within CLOSE_RADIUS1 # using norm_1 which is less cpu-consuming # using a list instead of a set could probably cut it too @@ -247,7 +247,7 @@ def update(self): move = self.noised_speed(move) # align icon with actual move - self.angle = move.degrees() + self.angle = -move.degrees() if DEBUG: print(f"SUMMARY {self}: {move=} {self.angle=}") @@ -325,14 +325,14 @@ def remove_obstacles(self): self.obstacles = SpriteList() def on_draw(self): - arcade.start_render() + self.clear() self.boids.draw() self.obstacles.draw() def on_update(self, delta_time): if self.freeze: return - self.boids.update() + self.boids.update(delta_time) def display_current_settings(self): diff --git a/notebooks/tps/boids/ARTEFACTS b/notebooks/tps/boids/ARTEFACTS index e0acfc9..857cddc 100644 --- a/notebooks/tps/boids/ARTEFACTS +++ b/notebooks/tps/boids/ARTEFACTS @@ -1,3 +1,3 @@ README-boids-nb.md -boids-01.py +boids-02.py media/ diff --git a/notebooks/tps/boids/ARTEFACTS-boids.zip b/notebooks/tps/boids/ARTEFACTS-boids.zip index 3bfcc56..40f403c 100644 Binary files a/notebooks/tps/boids/ARTEFACTS-boids.zip and b/notebooks/tps/boids/ARTEFACTS-boids.zip differ diff --git a/notebooks/tps/boids/README-boids-nb.md b/notebooks/tps/boids/README-boids-nb.md index efe8c44..425087a 100644 --- a/notebooks/tps/boids/README-boids-nb.md +++ b/notebooks/tps/boids/README-boids-nb.md @@ -15,7 +15,7 @@ nbhosting: title: 'TP: les boids' --- -Licence CC BY-NC-ND, Thierry Parmentelat +# TP - les boids avec `arcade` +++ @@ -23,12 +23,13 @@ Licence CC BY-NC-ND, Thierry Parmentelat {download}`vous aurez besoin du zip qui se trouve ici<./ARTEFACTS-boids.zip>` ``` -+++ +--- ## c'est quoi les *boids* ? une simulation ludique où on tente de reproduire le comportement d'animaux en -groupes - typiquement oiseaux et poissons +groupes +typiquement nuée d'oiseaux ou banc de poissons ### intérêts @@ -37,12 +38,13 @@ c'est intéressant parce que * c'est une illustration du modèle de programmation "par acteurs" chaque entité dans l'univers adapte son comportement en fonction de ses voisins immédiats + * on y découvre [arcade, une autre bibliothèque de jeux pour Python](https://api.arcade.academy/en/latest/) et c'est intéressant pour nous car cette librairie se programme exclusivement **par spécialisation de classes** -+++ +--- ## introduction @@ -51,11 +53,12 @@ dans ce TP nous allons * découvrir (très superficiellement) la librairie `arcade` * et l'utiliser pour implémenter un début de simulation de *boids* -+++ +--- ### notre sujet -dans sa version originale chaque animal décide de sa trajectoire, **en fonction uniquement de ses voisins proches**, et cela en suivant trois règles: +dans sa version originale chaque animal décide de sa trajectoire, **en fonction +uniquement de ses voisins proches**, et cela en suivant trois règles: * séparation (typiquement pour éviter les obstacles) * alignement (tout le monde va, en gros, dans la même direction) @@ -66,223 +69,225 @@ c'est-à-dire ce qui permet aux boids d'éviter de heurter les autres boids, et les élèves rapides et/ou motivés pourront poursuivre jusqu'à réaliser une simulation complète s'ils le souhaitent -+++ +--- ### en vidéo voici d'abord une vidéo très courte pour vous montrer les différentes étapes du TP - +::::{admonition} arcade 3.x +:class: danger -l'enjeu principal ici est d'être exposé à ce style de **programmation par spécialisation de classes** -aussi ce chemin est uniquement **indicatif**, et surtout à destination des élèves qui en ressentiront le besoin -si vous vous sentez, vous pouvez très bien vous y prendre complètement autrement, -le contrat est rempli dès que vous avez: **des obstacles** fixes, et **des boids** qui évoluent **spontanément** en **évitant** les autres objets +comme la librairie `arcade` a récemment évolué vers la version 3.x, le code de +démarrage a été mis à jour en conséquence, et c'est pourquoi avec le code de +départ que je vous fournis **vous allez commencer directement à l'étape 2** de la +vidéo +:::: -+++ +::::{figure} +:align: center +```{iframe} https://www.youtube.com/embed/d4789cBD3Ek?rel=0&controls=1 +``` +penser à la lire en plein écran +:::: -### contenu +l'enjeu principal ici est d'être exposé à la **programmation par spécialisation de classes** +aussi ce chemin par étapes est uniquement **indicatif**, et surtout à +destination des élèves qui ressentent le besoin d'être guidés pas à pas +si vous vous sentez, vous pouvez très bien vous y prendre complètement autrement ! +le contrat est rempli dès que vous avez: **des obstacles** fixes, et **des +boids** qui évoluent **spontanément** en **évitant** les obstacles et les autres +boids + +--- + +### contenu du zip le zip contient -* le starter code dans `boids-01.py` +* le starter code dans `boids-02.py` * les figures dans le dossier `media/` -+++ +--- ## pas à pas -+++ - -### v01: starter code +### v02: starter code -```python -""" -display a single object, inert, at (100, 100) -""" +* dans le zip vous trouverez le code suivant; n'hésitez pas à le renommer dans + un fichier `boids.py` si vous préférez -import arcade +::::{admonition} le code de départ +:class: dropdown -BACKGROUND = arcade.color.ALMOND -IMAGE = "media/arrow-resized.png" +:::{literalinclude} boids-02.py +::: +:::: -class Window(arcade.Window): - - def __init__(self): - super().__init__(800, 800, "My first boid") - arcade.set_background_color(BACKGROUND) - self.boid = None - - def setup(self): - boid = arcade.Sprite(IMAGE) - boid.center_x = 100 - boid.center_y = 100 - self.boid = boid - - def on_draw(self): - arcade.start_render() - self.boid.draw() - - def on_update(self, delta_time): - self.boid.update() - -window = Window() -window.setup() -arcade.run() -``` - -* installez la librairie +* installez la librairie (comment fait-on déjà ?) * vérifiez que vous avez le fichier `media/arrow-resized.png` (il est dans le zip) -* copiez et lancez le code ci-dessus +* lancez le code ci-dessus vous devez voir un seul boid immobile, dans le coin en bas à gauche -+++ - -installez la librairie, copiez le code ci-dessus dans par exemple `boid.py`, et lancez-le -vous devez voir un seul boid dans le coin en bas à gauche, il est immobile - -+++ - -#### commentaire - -observez la différence de style de programmation par rapport à `pygame` -comment aurait-on écrit la même chose en `pygame` ? - -+++ - -#### l'implicite +::::{admonition} l'implicite dans ce code, on utilise - et ce n'est pas du tout explicite - le fait que * le module `arcade` vient avec une *mainloop* - `arcade.run()` - qui se charge de faire 'avancer' le jeu - par défaut à plusieurs dizaines de Hz + qui se charge de faire 'avancer' le jeu - par défaut à plusieurs dizaines de Hz - et cela même si avec cette version 01 on ne voit pas grand chose bouger ⏸️ + * cette mainloop va appeler les méthodes `on_draw()` et `on_update()` sur chaque instance de `Window` - c'est là que nous pouvons programmer la logique de notre "*jeu*" + +* notamment nous disons que pour mettre à jour le jeu (`on_update`), + on doit mettre à jour tous les objets qui sont dans la `SpriteList` + `self.boids`, ce que l'on fait par l'appel à `self.boids.update()` + * la classe `Sprite` permet d'ajouter des objets qui savent s'afficher - ici on a juste créé l'objet à partir d'un png, puis fixé `boid.center_x` et `boid.center_y` - + ici on a juste créé l'objet à partir d'une image `.png`, puis fixé + `boid.center_x` et `boid.center_y` + +:::{admonition} pour les forts +:class: dropdown warning pour les forts: dans le même registre, mais plus subtil: * il a suffi qu'on crée une instance de `Window` pour qu'elle soit prise en compte par cette boucle; comment c'est possible d'après vous ? +::: -+++ - -### v02: de la place pour plusieurs boids +:::: -on veut garder exactement le même comportement (un seul boid fixe pour l'instant) -mais on va modifier le code pour pouvoir (plus tard) en créer plusieurs +::::{admonition} vs pygame +:class: admonition-small -pour cela, on pourrait penser à utiliser une liste standard Python, -mais je vous invite à utiliser plutôt la classe `SpriteList` que fournit `arcade` +observez la différence de style de programmation par rapport à `pygame` +comment aurait-on écrit la même chose en `pygame` ? +:::: -+++ +::::{admonition} à faire pour aider le debug -#### debugging +partant de là, je vous recommande de: -en plus de ça, je vous recommande de: -* prévoir le cas du debug, par exemple avec une variable globale DEBUG +* prévoir le cas du debug, par exemple avec une variable globale `DEBUG` * et dans ce cas afficher un message à chaque fois que le boid est mis à jour (surtout pour mettre en évidence la *mainloop* à ce stade) -* et aussi de [regarder la méthode `set_update_rate()`](https://api.arcade.academy/en/latest/api/window.html?highlight=set_update_rate#arcade.Window.set_update_rate) + +* et aussi de [regarder la méthode + `set_update_rate()`](https://api.arcade.academy/en/2.6.1/api/window.html#arcade.Window.set_update_rate) pour ralentir la cadence, ce qui sera sûrement utile à un moment donné pour débugger + * pourquoi ne pas aussi imprimer un message pour voir à quel rythme sont faits les `draw()` et `update()` +:::: -+++ +--- ### v03: le boid avance -maintenant on va faire bouger notre objet, et lui donner un mouvement rectiligne +maintenant on va faire bouger notre objet, et lui donner un mouvement rectiligne -et pour ça on va cesser d'utiliser directement la classe `Sprite`, +et pour ça on va cesser d'utiliser directement la classe `Sprite`, et on va au contraire la **spécialiser** pour créer notre propre classe `Boid` (c-à-d que la classe `Boid` hérite de la classe `Sprite`) -#### à savoir +::::{admonition} à savoir * pour chaque cycle de la *mainloop*, l'objet `Window` utilise - * sa méthode `on_update()` pour mettre à jour l'état des objets - * et sa méthode `on_draw()` pour les redessiner - c'est pour cela que celle-ci commence par `start_render()` + * sa méthode `on_update()` pour mettre à jour l'état des objets (juste en mémoire) + * et sa méthode `on_draw()` pour les redessiner + c'est pour cela que celle-ci commence par `clear()` qui efface tout, et remet simplement le fond d'écran - * on peut donc **faire avancer le boid** simplement en **redéfinissant quelques méthodes** dans le code -* par défaut les deux méthodes (`draw()` et `update()`) se produisent à la même fréquence (60Hz), - mais avec `set_update_rate()` on ralentit uniquement `update()` - c'est pourquoi `on_update(time_delta)` reçoit le temps (en ms) - qui s'est écoulé depuis le dernier appel - -et aussi, mais moins crucial à ce stade: - -* on n'en a pas besoin tout de suite, mais dans la classe `Sprite` - il y a un attribut `angle` qui sert à dire de combien on veut tourner l'image -* et naturellement dans notre cas, on va vouloir que l'objet avance dans la direction de la flêche - (même si ce stade on ne peut pas encore faire tourner le boid) +* bref, le résultat c'est qu'on peut **faire avancer le boid** + simplement en **redéfinissant quelques méthodes** dans le code +* par défaut les deux méthodes (`draw()` et `update()`) se produisent à la même fréquence (60Hz), + et avec `set_update_rate()` on ralentit uniquement `update()` +* `on_update(time_delta)` reçoit le temps (en ms) qui s'est écoulé depuis le + dernier update(), c'est pratique pour faire des mouvements si on connaît la + vitesse de déplacement de l'objet +:::: + +::::{admonition} et aussi, mais moins crucial +:class: warning + +* on n'en a pas besoin tout de suite, mais dans la classe `Sprite`, il y a un + attribut `angle` qui sert à dire de combien on veut tourner l'image lors de + l'affichage +* et naturellement dans notre cas, on va vouloir que l'objet avance dans la + direction de la flêche (même si ce stade on ne peut pas encore faire tourner + le boid) * aussi il serait habile de considérer que la vitesse du boid est un de ses attributs (et non pas une constante) même si là encore on n'en a pas besoin tout de suite * pensez à exprimer les vitesses en pixels par seconde +:::: -+++ +--- ### v04: en circuit fermé -on va faire en sorte que le plateau devienne infini en le refermant sur lui-même -un objet sortant à gauche réapparait à droite, et idem dans tous les sens -ça peut valoir le coup de "sortir" la taille du jeu pour en faire des constantes - -et pour que ce soit plus facile à tester on va orienter le boid vers le coin en bas à gauche +* on va faire en sorte que le plateau devienne infini en le refermant sur lui-même +i.e. un objet sortant à gauche réapparait à droite, et idem dans tous les sens… +* ça peut valoir le coup de "sortir" la taille du jeu pour en faire des constantes +* et pour que ce soit plus facile à tester on va orienter le boid vers le coin en bas à gauche si vous vous y êtes bien pris pour le faire avancer, c'est juste une question de changer son `.angle` -+++ +--- ### v05: du bruit sur le cap faites en sorte que le trajet du boid ne soit plus strictement rectiligne en ajoutant à chaque pas un léger bruit sur la direction -+++ +--- ### v06: les touches `←` et `→` faites en sorte de pouvoir contrôler la direction du boid avec les touches du clavier -#### à savoir +::::{admonition} à savoir -* pour intercepter les événements clavier, vous pouvez définir dans la classe `Window` les méthodes -```python -def on_key_press(self, key, modifiers): - pass -def on_key_release(self, key, modifiers): - pass -``` -* la librairie expose par exemple la constante `arcade.key.LEFT` +* pour intercepter les événements clavier, vous pouvez définir dans la classe + `Window` les méthodes + ```python + def on_key_press(self, key, modifiers): + pass + def on_key_release(self, key, modifiers): + pass + ``` +* la librairie expose des constantes comme par exemple `arcade.key.LEFT` +:::: -#### attention +::::{admonition} *user-friendliness* -ceci est beaucoup plus facile à utiliser si le boid continue de tourner pendant **tout le temps où la touche est enfoncée** - plutôt que de devoir appuyer plein de fois sur la touche +soyez sympa avec vos utilisateurs: ceci est beaucoup plus facile à utiliser si +le boid continue de tourner pendant **tout le temps où la touche est enfoncée** - plutôt que +de devoir appuyer plein de fois sur la touche… +:::: -+++ +--- ### v07: ajouter un obstacle ajoutez un unique obstacle, immobile, par exemple au centre du jeu vous trouverez une image `media/obstacle-resized.png` pour le matérialiser -**2 options** +::::{admonition} 2 options + * on pourrait facilement s'en sortir avec juste la classe `Sprite` -* mais je vous demande, pour vous exercer à la spécialisation de classes, de créer une classe `Obstacle` +* mais je vous demande, pour vous exercer à la spécialisation de classes, de + créer une classe `Obstacle` +:::: -+++ +--- ### v08: créez une grille d'obstacles remplacez l'unique obstacle par une grille d'obstacles -mettez en 10 x 10, ils sont donc espacés de 80px +par exemple: mettez en 10 x 10, ils sont donc espacés de 80px -+++ +--- ### v09: détecter les voisins @@ -291,126 +296,146 @@ prenez 20 pixels comme rayon de détection pour ma part j'ai rendu le boid semi-transparent, en jouant sur l'attribut `alpha` des `Sprite` (255 = opaque, 0 = transparent) -+++ +::::{admonition} discussion -#### discussion +ici on a le choix d'utiliser -ici on a le choix d'utiliser * soit une variable globale (la liste de tous les obstacles) * ou de rajouter dans la classe `Boid` une liste d'obstacles quels sont les avantages et les inconvénients des 2 approches ? + * en termes de vitesse de programmation * en termes de réutilisabilité je vous recommande la deuxième option +:::: -+++ +--- ### v10: la règle de séparation implémentez la règle de séparation on peut la résumer comme ceci: -+++ - ```{image} media/separation.png :align: center +:width: 80% ``` -+++ +--- c'est-à-dire que quand on s'intéresse au boid b, on va -* ignorer tous les objets qui se trouvent plus loin qu'un certain rayon 'r' -* et pour tous ceux qui sont proches, par exemple o, on calcule un vecteur $\overrightarrow{\delta}$ qui va permettre d'écarter l'objet b de o - je n'ai pas trouvé de formule dans la littérature pour calculer $\overrightarrow{\delta}$, j'ai sorti de mon chapeau la formule suivante - $\overrightarrow{\delta} = \overrightarrow{ob} * \frac{1}{2}(1-\frac{d}{r})$ +* ignorer tous les objets (en rouge) qui se trouvent plus loin qu'un certain rayon 'r' +* et pour tous ceux qui sont proches (en vert), par exemple o, on calcule un + vecteur $\overrightarrow{\delta}$ qui va permettre d'écarter l'objet b de o - de façon à ce que: - * les objets sur le cercle ont une influence nulle, - * et si o est tout proche de b, il est repoussé à un rayon r/2 +je n'ai pas trouvé de formule dans la littérature pour calculer +$\overrightarrow{\delta}$, j'ai sorti de mon chapeau la formule suivante -on fait la somme de tous ces vecteurs, et on l'ajoute au déplacement de b +::::{math} +:align: center +\overrightarrow{\delta} = \overrightarrow{ob} \times \frac{1}{2}(1-\frac{d}{r}) +:::: + +de façon à ce que: + +* les objets sur le cercle ont une influence nulle, +* et si o est tout proche de b, il est repoussé à un rayon r/2 -i.e. dans l'exemple de la figure, lorsqu'on traite le boid en b: -* on ignore les boids aux endroits en rouge -* et on fait la somme des 3 vecteurs (en vert) +on fait la somme de tous ces vecteurs, et on l'ajoute au déplacement de b +i.e., dans l'exemple de la figure, lorsqu'on traite le boid en b: + +* on ignore les boids éloignés - en rouge +* et pour les 3 boids proches - en vert - on fait la somme des 3 vecteurs de + "repoussement" (en vert aussi) * qu'on ajoute naturellement au déplacement dû à la vitesse du boid -#### à noter +::::{admonition} à noter -dans cette version, en cas de collision, on se contente de modifier la position du boid, et pas son orientation; on arrangera ca plus tard +dans cette version, en cas de collision, on se contente de modifier la position +du boid, et pas son orientation; on arrangera ca plus tard +:::: -+++ +--- -### v11: on essaie d'orienter correctement +### v11: orienter correctement -dans cette version, on va essayer de répercuter les collisions sur l'orientation du boid -et pour ça on va mettre à jour brutalement l'attribut `angle` uniquement sur le mouvement qui est fait à l'instant t -i.e, pour être clair, que si on passe de (x1, y1) à (x2, y2), on oriente le boid pour s'aligner sur le vecteur (x2-x1, y2-y1) -l'effet n'est pas forcément très réussi, vous devez voir l'orientation sauter brutalement d'un angle un autre +* dans cette version, on va essayer de répercuter les collisions sur l'orientation du boid +* et pour ça on va mettre à jour brutalement l'attribut `angle` +* à ce stade, on se base uniquement sur le mouvement qui est fait à l'instant t: +* pour être explicite, si on passe de *(x1, y1)* à *(x2, y2)*, on oriente + le boid pour s'aligner sur le vecteur *(x2-x1, y2-y1)* + +l'effet n'est pas forcément très réussi, vous devez voir l'orientation sauter brutalement d'un angle à un autre + +::::{admonition} à savoir -**à savoir** voyez la fonction `math.atan2` qui est pratique ici +:::: -+++ +--- -### v12: on lisse les changements d'orientation +### v12: tourner plus doucement -comment pourrait-on obtenir quelque chose d'un peu plus élégant, en ce qui concerne les changements de direction ? +pour lisser les changements d'orientation: comment pourrait-on obtenir quelque +chose d'un peu plus élégant, en ce qui concerne les changements de direction ? -+++ +--- ### v13: les touches `↑` et `↓` -faire en sorte qu'on puisse contrôler aussi la vitesse avec les touches +faire en sorte qu'on puisse contrôler aussi la vitesse avec les touches `↑` et `↓` essayez le comportement de l'évitement d'obstacles à plusieurs vitesses -+++ +--- ### v14: plusieurs boids remplacez l'unique boid par un ensemble de 20 boids -sans changer la séparation, qui est calculée seulement à partir des obstacles +sans changer, pour l'instant, la séparation, qui est calculée seulement à partir des obstacles -+++ +--- -### v15: éviter les obstacles **et** les autres boids +### v15: éviter aussi les autres boids assurez-vous que la séparation permet d'éviter tous les objets (obstacles et boids) -+++ +--- ### en option... vous pouvez ensuite améliorer dans les directions suivantes : + * implémenter les deux autres règles (alignement et cohésion) * faire en sorte qu'on puisse interactivement ajouter/enlever des obstacles * faire des raccourcis clavier pour activer/désactiver les 3 règles, et le bruit * bien tenir compte de la vitesse de rafraichissement du jeu i.e., est-ce que la simulation continue de fonctionner si on ralentit la logique du jeu avec `Window.set_update_rate()` + * etc... pour information voici une synthèse des 3 règles, à vous de chercher pour préciser comment interpréter ces figures -+++ - ```{image} media/boids-rules.png :align: center ``` -+++ +--- ## pour aller plus loin -* pour plus de détails sur les boids, +* pour plus de détails sur les boids, voir [la page de Craig Reynolds](http://www.red3d.com/cwr/boids/), - l'auteur original, et [la page wikipedia](https://en.wikipedia.org/wiki/Boids) - -* je vous signale un tutoriel intéressant sur la librairie arcade: - https://realpython.com/arcade-python-game-framework/ - -* enfin d'autres vidéos qui peuvent vous inspirer également - - + l'auteur original +* et [la page wikipedia](https://en.wikipedia.org/wiki/Boids) +* je vous signale [un tutoriel intéressant sur la librairie arcade](https://realpython.com/arcade-python-game-framework/) assez long / exhaustif +* enfin d'autres vidéos qui peuvent vous inspirer également (parmi $10^n$ autres) : + + ::::{grid} 2 + ```{iframe} https://www.youtube.com/embed/QbUPfMXXQIY?rel=0&controls=1 + ``` + ```{iframe} https://www.youtube.com/embed/bqtqltqcQhw?rel=0&controls=1 + ``` + :::: diff --git a/notebooks/tps/boids/boids-01.py b/notebooks/tps/boids/boids-02.py similarity index 68% rename from notebooks/tps/boids/boids-01.py rename to notebooks/tps/boids/boids-02.py index a6695d5..05c2b7b 100644 --- a/notebooks/tps/boids/boids-01.py +++ b/notebooks/tps/boids/boids-02.py @@ -1,6 +1,8 @@ """ simplest possible starting code with one motionless boid display a single object, inert, at (100, 100) +with arcade-3.x this is the starter step, and +Window has a self.boids instead of a single self.boid """ import arcade @@ -14,20 +16,21 @@ def __init__(self): super().__init__(800, 800, "My first boid") arcade.set_background_color(BACKGROUND) self.set_location(800, 100) - self.boid = None + self.boids = None def setup(self): boid = arcade.Sprite(IMAGE) boid.center_x = 100 boid.center_y = 100 - self.boid = boid + self.boids = arcade.SpriteList() + self.boids.append(boid) def on_draw(self): - arcade.start_render() - self.boid.draw() + self.clear() + self.boids.draw() def on_update(self, delta_time): - self.boid.update() + self.boids.update() window = Window() window.setup() diff --git a/notebooks/tps/chatbot/.gitignore b/notebooks/tps/chatbot/.gitignore new file mode 100644 index 0000000..4c49bd7 --- /dev/null +++ b/notebooks/tps/chatbot/.gitignore @@ -0,0 +1 @@ +.env diff --git a/notebooks/tps/chatbot/.teacher/README-chatbot-corrige-nb.md b/notebooks/tps/chatbot/.teacher/README-chatbot-corrige-nb.md index 40ceb28..b1af162 100644 --- a/notebooks/tps/chatbot/.teacher/README-chatbot-corrige-nb.md +++ b/notebooks/tps/chatbot/.teacher/README-chatbot-corrige-nb.md @@ -3,16 +3,12 @@ jupytext: text_representation: extension: .md format_name: myst + format_version: 0.13 + jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 -language_info: - name: python - nbconvert_exporter: python - pygments_lexer: ipython3 -nbhosting: - title: 'TP: un chatbot' --- # TP - un chatbot avec `flet` @@ -53,7 +49,7 @@ on met à votre disposition **deux serveurs** `ollama`: - chacun des deux sait mettre en oeuvre plusieurs modèles d'IA (notamment `mistral`, mais pas que...) - l'un des deux ne possède qu'un CPU; du coup il est relativement lent mais on peut y accéder sans login/password - par contre l'autre possède un GPU, il est plus rapide pour notre application, mais le code pour s'en servir est un peu plus compliqué car il faut lui fournir un login/password -- les détails de ces deux serveurs sont dans le *starter code* +- les détails de ces deux serveurs sont dans le *starter code* (à part les login/password qui vous seront communiqués par un autre moyen) - pour les utiliser, essentiellement on `POST` une requête http au serveur avec le chemin `/api/generate` @@ -71,7 +67,7 @@ ce qu'on veut faire, c'est fabriquer une UI sommaire qui permet - de choisir le serveur, - de choisir le modèle, - et de poser ensuite des questions comme avec chatGPT -- enfin sur cette implémentation on a également un bouton qui permet d'enabler le *streaming* +- enfin sur cette implémentation on a également un bouton qui permet d'enabler le *streaming* l'idée consiste à afficher les résultats "au fur et à mesure" plutôt qu'en une seule fois à la fin de l'échange avec le serveur, on en reparlera... @@ -164,7 +160,7 @@ pour vous familiariser avec le modèle de lignes et colonnes de `flet`, **ajoute - et `flet.Text` - et à chaque fois les différents attributs disponibles pour contrôler le look et le comportement de l'UI -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ## v03: avec un peu de classe: `ChatbotApp` @@ -172,8 +168,12 @@ ceci est une étape **totalement optionnelle**, mais je vous recommande de **cr - on pourrait envisager par exemple que `ChatbotApp` hérite de `ft.Column` - de cette façon on se retrouverait avec un `main` qui ne fait plus que - ```{literalinclude} chatbot-03a.py - :start-after: show the code in the instructions + ```{code} python + def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) ``` Je vous propose de procéder en deux temps @@ -205,7 +205,9 @@ toujours pour éviter de finir avec un gros paquet de spaguettis, on va imaginer - la `Row` avec les différents réglages - et une instance de `History()` -`````{admonition} la logique de la classe History ++++ + +```{admonition} la logique de la classe History :class: tip pour fixer les idées, disons qu'à ce stade cette classe possède les méthodes @@ -219,7 +221,9 @@ l'idée est que l'objet `History` possède: et pour cela on utilisera `add_message(some_text)`, dont le job donc est d'insérer un objet `ft.Text` (non modifiable par l'utilisateur cette fois) **en avant-dernière position** - c'est-à-dire juste au dessus du prompt -````` +``` + ++++ pour être bien clair, à ce stade on ne fait pas encore usage du réseau pour quoi que ce soit, on veut juste mettre en place la structure de l'UI @@ -228,12 +232,12 @@ ici encore je vous conseille de procéder par petites étapes: - 4a: la trame de la classe `History` - 4b: faites en sorte que le fait de taper "Entrée" dans la zone de prompt fasse le même effet que le bouton "Send" -```{admonition} regardez la classe `TextField` +:::{admonition} regardez la classe `TextField` :class: tip pour le titre on utilise la classe `Text` qui est en *read-only*; pour la zone de prompt, il est préferable d'utiliser `TextField` qui est *editable* et qui offre plus de flexibilité -``` +::: +++ @@ -270,7 +274,7 @@ ce code peut s'exécuter par exemple directement dans ipython import requests import json -url = "http://ollama.pl.sophia.inria.fr:8080/api/generate" +url = "https://ollama.pl.sophia.inria.fr/api/generate" # c'est expliqué dans la doc ollama: l'API /api/generate # s'attend à ce qu'on lui passe ces deux paramètres: @@ -464,7 +468,58 @@ plutôt que de proposer une liste de modèles "en dur" comme dans le *starter co dans mon implémentation j'ai choisi de "cacher" ce résultat, pour ne pas redemander plusieurs fois cette liste à un même serveur (cette liste bouge très très peu...); mais c'est optionnel; par contre ce serait sympa pour les utilisateurs de conserver, lorsque c'est possible, le modèle choisi lorsqu'on change de serveur... -+++ +## v10 (optionnel): une classe `Server` + +dans cette version, je vous propose de **créer une classe `Server` abstraite**, +qui définit une API commune pour interagir avec un serveur d'IA; puis une classe +concrète **`OllamaServer`** qui hérite de `Server` et qui encapsule la logique +d'interaction avec l'API ollama - puisque pour l'instant nos deux serveurs +offrent la même API + +mais de cette façon dans le futur (étape suivante) on pourra plus simplement +ajouter le code pour interagir avec d'autres types de serveurs, qui implémentent +une API différente (par exemple `litellm` que nous avons aussi déployé à +l'Inria) + +c'est pourquoi dans cette v10, je vous propose de rester à fonctionnalités +constantes, mais de créer une classe `OllamaServer` qui hérite de +`Server` et qui implémente les méthodes suivantes: + +```python +class Server: + """ + an abstract server class + """ + def list_models(self) -> list[str]: + pass + def generate_blocking(self, prompt, model, streaming ) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model, streaming) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass +``` + +## v11 (optionnel): une autre API + +à présent que nous avons une classe `Server`, on va pouvoir **implémenter une autre classe** qui hérite de `Server`, par exemple `LitellmServer`, qui implémente la même API mais en s'appuyant sur le serveur `litellm-sam.inria.fr` + +l'API en question est documentée ici + (pour l'instant nécessite +un VPN) - et sans doute à plein d'autres endroits publics + +pour vous authentifier vous aurez également besoin d'une clé API - communiquée par un autre moyen + +le but du jeu consiste donc ici à +- implémenter une classe concrète `LitellmServer` qui hérite de `Server` et qui +implémente les mêmes méthodes que `OllamaServer`, mais en s'appuyant sur l'API +`litellm` +- ajouter une entrée dans le dictionnaire `SERVERS` pour pouvoir choisir ce + serveur dans l'interface ## plein d'améliorations possibles diff --git a/notebooks/tps/chatbot/.teacher/README-ollama.md b/notebooks/tps/chatbot/.teacher/README-ollama.md index 3fcacd8..8a57099 100644 --- a/notebooks/tps/chatbot/.teacher/README-ollama.md +++ b/notebooks/tps/chatbot/.teacher/README-ollama.md @@ -1,41 +1,8 @@ -# The CPU instance +# Redirect -## infra +everything related to Ollama is now in the **private** repo that goes with the +JavaScript version of this exercise. -runs in a container in stupeflip +as of this writing, but subject to year bumping: -## security - -runs on port 8080; no authentication - -## management - -to manage it, use the `ollama` command but that requires an environment variable to be set - -```bash -export OLLAMA_HOST=0.0.0.0:8080 -# then you can use the ollama command as usual -ollama list -ollama pull gemma2:2b -ollama pull mistral:7b -ollama pull deepseek-r1:7b -``` - -## testing - -Using `http` (from `pip install httpie`) you can reach both instances from the command line like so: - -```bash - -# the CPU -http http://ollama.pl.sophia.inria.fr:8080/api/generate model=mistral:7b prompt="Hey" - -# the GPU -http https://Bob:hiccup@ollama-sam.inria.fr/api/generate model=mistral:7b prompt="Hey" - -# in streaming mode: CPU -http -S http://ollama.pl.sophia.inria.fr:8080/api/generate model=mistral:7b prompt="Hey" stream:=true - -# in streaming mode: GPU -http -S https://Bob:hiccup@ollama-sam.inria.fr/api/generate model=mistral:7b prompt="Hey" stream:=true -``` +https://github.com/ue22-p25/frontend-chatbot-private.git diff --git a/notebooks/tps/chatbot/.teacher/chatbot-02.py b/notebooks/tps/chatbot/.teacher/chatbot-02.py index ef7540b..2653c6f 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-02.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-02.py @@ -4,22 +4,26 @@ and how to mix and match Rows and Columns """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-03a.py b/notebooks/tps/chatbot/.teacher/chatbot-03a.py index baa51bb..6601a0e 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-03a.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-03a.py @@ -5,22 +5,26 @@ it still won't do much, but it's more reusable this way """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-03b.py b/notebooks/tps/chatbot/.teacher/chatbot-03b.py index b168482..e55a102 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-03b.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-03b.py @@ -5,22 +5,26 @@ as attributes in the ChatbotApp instance """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-04a.py b/notebooks/tps/chatbot/.teacher/chatbot-04a.py index f1663b9..2b023fb 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-04a.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-04a.py @@ -2,22 +2,26 @@ introduce class History that will store the history of the chatbot """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-04b.py b/notebooks/tps/chatbot/.teacher/chatbot-04b.py index 843e06b..9fc73c3 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-04b.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-04b.py @@ -2,22 +2,26 @@ hitting return in the Send button triggers the callback as well """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-05a.py b/notebooks/tps/chatbot/.teacher/chatbot-05a.py index 4876a13..d8b9714 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-05a.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-05a.py @@ -4,23 +4,27 @@ """ # the library to actually send stuff to the network +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-05b.py b/notebooks/tps/chatbot/.teacher/chatbot-05b.py index f4e433c..9c46220 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-05b.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-05b.py @@ -3,23 +3,27 @@ """ # the library to actually send stuff to the network +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-06.py b/notebooks/tps/chatbot/.teacher/chatbot-06.py index b82a2e3..e761eaa 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-06.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-06.py @@ -6,24 +6,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-07a.py b/notebooks/tps/chatbot/.teacher/chatbot-07a.py index 2fbe8ac..1edbe0e 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-07a.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-07a.py @@ -3,24 +3,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-07b.py b/notebooks/tps/chatbot/.teacher/chatbot-07b.py index 155abf0..e6072db 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-07b.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-07b.py @@ -6,24 +6,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-07c.py b/notebooks/tps/chatbot/.teacher/chatbot-07c.py index 8557624..db3ddaf 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-07c.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-07c.py @@ -4,24 +4,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-08.py b/notebooks/tps/chatbot/.teacher/chatbot-08.py index c8e115d..8effe02 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-08.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-08.py @@ -3,24 +3,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-09.py b/notebooks/tps/chatbot/.teacher/chatbot-09.py index 53e8859..878b092 100644 --- a/notebooks/tps/chatbot/.teacher/chatbot-09.py +++ b/notebooks/tps/chatbot/.teacher/chatbot-09.py @@ -5,24 +5,27 @@ """ import json +import os +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import requests import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/chatbot/.teacher/chatbot-10.py b/notebooks/tps/chatbot/.teacher/chatbot-10.py new file mode 100644 index 0000000..b89b97a --- /dev/null +++ b/notebooks/tps/chatbot/.teacher/chatbot-10.py @@ -0,0 +1,319 @@ +""" +instead of using a hard-wired list of models, +we fetch the list of supported models at the server +at the api/tags endpoint using GET +""" + +import json +import os +from typing import Iterator + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv +import requests +import flet as ft + +load_dotenv() + +# in this version we create servers as INSTANCES of CLASSES +# so we can encapsulate the logic to interact with them +# +# rationale is to be able to talk with servers that implement other APIs +# e.g. litellm that has also been deployed and on more servers + +# we keep the idea of specifying our available servers as this dictionary +# but below we'll use this to create actual server INSTANCES + +SERVER_SPECS = { + 'GPU': { + "name": "GPU fast", + "url": "https://ollama-sam.inria.fr", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), + }, + 'CPU': { + "name": "CPU slow", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), + }, +} + +TITLE = "My first Chatbot 10" + +class Server: + """ + an abstract server class + """ + def list_model_names(self) -> list[str]: + pass + def generate_blocking(self, prompt, model) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass + + +class OllamaServer(Server): + """ + for servers that comply with ollama's API + """ + def __init__(self, name, url, username=None, password=None): + self.name = name + self.url = url + self.username = username + self.password = password + + def _authenticate_extra_args(self) -> dict: + auth_args = {} + if self.username is not None: + auth_args = { + 'auth': (self.username, self.password) + } + return auth_args + + def list_model_names(self): + url = f"{self.url}/api/tags" + auth_args = self._authenticate_extra_args() + answer = requests.get(url, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return [] + raw = answer.json() + return [model['name'] for model in raw['models']] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return result + for line in answer.text.split("\n"): + # splitting artefacts can be ignored + if not line: + continue + # there should be no exception, but just in case... + try: + data = json.loads(line) + # the last JSON chunk contains statistics and is not a message + if data['done']: + break + result.append(data['response']) + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + return result + + def generate_streaming(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, stream=True, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return + for line in answer.iter_lines(): + if not line: + continue + try: + data = json.loads(line) + if data['done']: + return + yield data['response'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +SERVERS = {} +for key, spec in SERVER_SPECS.items(): + SERVERS[key] = OllamaServer( + name=spec['name'], + url=spec['url'], + username=spec.get('username', None), + password=spec.get('password', None), + ) + +class History(ft.Column): + """ + the history is a column of text messages + where prompts and answers alternate + """ + + def __init__(self, app): + super().__init__( + [ft.TextField( + label="Type a message...", + on_submit=lambda event: app.send_request(event), + fill_color="lightgrey", + )], + scroll=ft.ScrollMode.AUTO, + auto_scroll=True, + expand=True, + ) + + # insert material - prompt or answer - to allow for different styles + def add_prompt(self, message): + self._add_entry(message, "prompt") + def add_answer(self, message): + self._add_entry(message, "answer") + def _add_entry(self, message, kind): + display = ft.Text(value=message) + display.color = "blue" if kind == "prompt" else "green" + display.size = 20 if kind == "prompt" else 16 + display.italic = kind == "prompt" + self.controls.insert(-1, display) + + # we always insert in the penultimate position + # given that the last item in controls is the prompt TextField + def add_chunk(self, chunk): + self.controls[-2].value += chunk + def current_prompt(self): + return self.controls[-1].value + + def enable_prompt(self): + self.controls[-1].disabled = False + def disable_prompt(self): + self.controls[-1].disabled = True + +class ChatbotApp(ft.Column): + + def __init__(self): + # we keep a cache of available models on each server + self.model_names_per_server = {} + + header = ft.Text(value=TITLE, size=40) + + self.streaming = ft.Checkbox(label="streaming", value=True) + # will be populated later + self.model = ft.Dropdown( + # options=[], + width=300, + ) + self.server = ft.Dropdown( + options=[ft.dropdown.Option(server) + for server in SERVER_SPECS.keys()], + value="GPU", + width=100, + on_change=lambda event: self.update_models(), + ) + + self.submit = ft.ElevatedButton("Send", on_click=self.send_request) + + self.history = History(self) + + row = ft.Row( + [self.streaming, self.model, self.server, self.submit], + alignment=ft.MainAxisAlignment.CENTER, + ) + super().__init__( + [header, row, self.history], + horizontal_alignment=ft.CrossAxisAlignment.CENTER, + expand=True, + ) + + # go fetch the relevant models for the selected server + # as explained below, at this point we are not yet in the page + # so we cannot yet call update() at this point + self.update_models(update=False) + + def fetch_models(self): + # already fetched ? + if self.server.value in self.model_names_per_server: + return + server_instance = SERVERS[self.server.value] + model_names = server_instance.list_model_names() + # for usability: sort the models alphabetically + model_names.sort() + self.model_names_per_server[self.server.value] = model_names + + def update_models(self, *, update=True): + # preserve current setting as far as possible + current_model = self.model.value + self.fetch_models() + available_models = self.model_names_per_server[self.server.value] + # replace the current options with the new ones + self.model.options = [ + ft.dropdown.Option(model) for model in self.model_names_per_server[self.server.value] + ] + # preserve setting if possible, otherwise pick first one + if current_model in available_models: + self.model.value = current_model + else: + # xxx somehow the first model on GPU - all-minilm:22m-l6-v2-fp16 + # returns an error saying the model does not support generate + # so, as a workaround, find the first model that does not start with all- + self.model.value = next( + model for model in available_models if not model.startswith("all-") + ) + # a subtle point here: because we call update_models in the constructor, + # and because at that time the app is not yet in the page + # we cannot call update() in that circumstance() + # BUT since this method is bound the the 'change' event on the server widget + # in that circumstance we need to update + if update: + self.update() + + def send_request(self, _event): + # disable the button to prevent double submission + self.submit.disabled = True + self.history.disable_prompt() + self.send_request_2(_event) + self.submit.disabled = False + self.history.enable_prompt() + self.update() + + + # send the prompt to the server and display the answer + def send_request_2(self, _event): + model = self.model.value + prompt = self.history.current_prompt() + server_instance = SERVERS[self.server.value] + + # record the question asked + self.history.add_prompt(prompt) + # create placeholder for the answer + self.history.add_answer("") + # update UI + self.update() + + # send the request + streaming = self.streaming.value + + print(f"Sending message to {server_instance.name}, {model=}, {streaming=}, {prompt=}") + + # streaming or non streaming + if not streaming: + # not streaming = blocking + answers = server_instance.generate_blocking(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + else: + # streaming version + answers = server_instance.generate_streaming(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + + +def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) + + +ft.app(target=main) diff --git a/notebooks/tps/chatbot/.teacher/chatbot-11.py b/notebooks/tps/chatbot/.teacher/chatbot-11.py new file mode 100644 index 0000000..6449c41 --- /dev/null +++ b/notebooks/tps/chatbot/.teacher/chatbot-11.py @@ -0,0 +1,423 @@ +""" +instead of using a hard-wired list of models, +we fetch the list of supported models at the server +at the api/tags endpoint using GET +""" + +import json +import os +from typing import Iterator + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD, LITELLM_KEY from .env +from dotenv import load_dotenv +import requests +import flet as ft + +load_dotenv() + +# in this version we create servers as INSTANCES of CLASSES +# so we can encapsulate the logic to interact with them +# +# rationale is to be able to talk with servers that implement other APIs +# e.g. litellm that has also been deployed and on more servers + +# we keep the idea of specifying our available servers as this dictionary +# but below we'll use this to create actual server INSTANCES + +SERVER_SPECS = { + 'GPU': { + "type": "ollama", + "name": "GPU fast", + "url": "https://ollama-sam.inria.fr", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), + }, + 'CPU': { + "type": "ollama", + "name": "CPU slow", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), + }, + 'LiteLLM': { + "type": "litellm", + "name": "LiteLLM (GPUs)", + "url": "https://litellm-sam.inria.fr", + "key": os.getenv("LITELLM_KEY"), + } +} + +TITLE = "My first Chatbot 11" + +class Server: + """ + an abstract server class + """ + def list_model_names(self) -> list[str]: + pass + def generate_blocking(self, prompt, model) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass + + +class OllamaServer(Server): + """ + for servers that comply with ollama's API + """ + def __init__(self, name, url, username=None, password=None): + self.name = name + self.url = url + self.username = username + self.password = password + + def _authenticate_extra_args(self) -> dict: + auth_args = {} + if self.username is not None: + auth_args = { + 'auth': (self.username, self.password) + } + return auth_args + + def list_model_names(self): + url = f"{self.url}/api/tags" + auth_args = self._authenticate_extra_args() + answer = requests.get(url, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return [] + raw = answer.json() + return [model['name'] for model in raw['models']] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return result + for line in answer.text.split("\n"): + # splitting artefacts can be ignored + if not line: + continue + # there should be no exception, but just in case... + try: + data = json.loads(line) + # the last JSON chunk contains statistics and is not a message + if data['done']: + break + result.append(data['response']) + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + return result + + def generate_streaming(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, stream=True, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return + for line in answer.iter_lines(): + if not line: + continue + try: + data = json.loads(line) + if data['done']: + return + yield data['response'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +class LitellmServer(Server): + """ + for servers that comply with LiteLLM's API + """ + def __init__(self, name, url, key): + self.name = name + self.url = url + self.key = key + + def _authenticate_headers(self) -> dict: + if not self.key: + return {} + return dict(headers={"X-API-KEY": self.key}) + + def list_model_names(self): + url = f"{self.url}/models" + extra_args = self._authenticate_headers() + req = requests.get(url, **extra_args) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return [] + raw = req.json() + return [ + chunk['id'] for chunk in raw['data'] + ] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + } + # print("sending POST to", url, "with payload", payload) + req = requests.post( + url, + json=payload, + **self._authenticate_headers() + ) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return [] + raw = req.json() + result = [] + if 'choices' in raw: + for choice in raw['choices']: + result.append(choice['text']) + return result + + + def generate_streaming(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + "stream": True, + } + # print("sending POST to", url, "with payload", payload) + req = requests.post( + url, + json=payload, + stream=True, + **self._authenticate_headers() + ) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return + for chunk in req.iter_lines(): + if not chunk: + continue + try: + chunk = chunk.decode('utf-8') + # remove extra 'data: ' prefix + if chunk.startswith("data: "): + chunk = chunk[6:] + data = json.loads(chunk) + if 'choices' in data: + for choice in data['choices']: + yield choice['text'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +SERVERS = {} +for key, spec in SERVER_SPECS.items(): + match spec['type']: + case 'ollama': + SERVERS[key] = OllamaServer( + name=spec['name'], + url=spec['url'], + username=spec.get('username', None), + password=spec.get('password', None), + ) + case 'litellm': + SERVERS[key] = LitellmServer( + name=spec['name'], + url=spec['url'], + key=spec['key'], + ) + + +class History(ft.Column): + """ + the history is a column of text messages + where prompts and answers alternate + """ + + def __init__(self, app): + super().__init__( + [ft.TextField( + label="Type a message...", + on_submit=lambda event: app.send_request(event), + fill_color="lightgrey", + )], + scroll=ft.ScrollMode.AUTO, + auto_scroll=True, + expand=True, + ) + + # insert material - prompt or answer - to allow for different styles + def add_prompt(self, message): + self._add_entry(message, "prompt") + def add_answer(self, message): + self._add_entry(message, "answer") + def _add_entry(self, message, kind): + display = ft.Text(value=message) + display.color = "blue" if kind == "prompt" else "green" + display.size = 20 if kind == "prompt" else 16 + display.italic = kind == "prompt" + self.controls.insert(-1, display) + + # we always insert in the penultimate position + # given that the last item in controls is the prompt TextField + def add_chunk(self, chunk): + self.controls[-2].value += chunk + def current_prompt(self): + return self.controls[-1].value + + def enable_prompt(self): + self.controls[-1].disabled = False + def disable_prompt(self): + self.controls[-1].disabled = True + +class ChatbotApp(ft.Column): + + def __init__(self): + # we keep a cache of available models on each server + self.model_names_per_server = {} + + header = ft.Text(value=TITLE, size=40) + + self.streaming = ft.Checkbox(label="streaming", value=True) + # will be populated later + self.model = ft.Dropdown( + # options=[], + width=300, + ) + self.server = ft.Dropdown( + options=[ft.dropdown.Option(server) + for server in SERVER_SPECS.keys()], + value="GPU", + width=100, + on_change=lambda event: self.update_models(), + ) + + self.submit = ft.ElevatedButton("Send", on_click=self.send_request) + + self.history = History(self) + + row = ft.Row( + [self.streaming, self.model, self.server, self.submit], + alignment=ft.MainAxisAlignment.CENTER, + ) + super().__init__( + [header, row, self.history], + horizontal_alignment=ft.CrossAxisAlignment.CENTER, + expand=True, + ) + + # go fetch the relevant models for the selected server + # as explained below, at this point we are not yet in the page + # so we cannot yet call update() at this point + self.update_models(update=False) + + def fetch_models(self): + # already fetched ? + # if empty, try again + if (self.server.value in self.model_names_per_server + and self.model_names_per_server[self.server.value]): + return + server_instance = SERVERS[self.server.value] + model_names = server_instance.list_model_names() + # for usability: sort the models alphabetically + model_names.sort() + self.model_names_per_server[self.server.value] = model_names + + def update_models(self, *, update=True): + # preserve current setting as far as possible + current_model = self.model.value + self.fetch_models() + available_models = self.model_names_per_server[self.server.value] + # replace the current options with the new ones + self.model.options = [ + ft.dropdown.Option(model) for model in self.model_names_per_server[self.server.value] + ] + # preserve setting if possible, otherwise pick first one + if current_model in available_models: + self.model.value = current_model + else: + # xxx somehow the first model on GPU - all-minilm:22m-l6-v2-fp16 + # returns an error saying the model does not support generate + # so, as a workaround, find the first model that does not start with all- + self.model.value = next( + model for model in available_models if not model.startswith("all-") + ) + # a subtle point here: because we call update_models in the constructor, + # and because at that time the app is not yet in the page + # we cannot call update() in that circumstance() + # BUT since this method is bound the the 'change' event on the server widget + # in that circumstance we need to update + if update: + self.update() + + def send_request(self, _event): + # disable the button to prevent double submission + self.submit.disabled = True + self.history.disable_prompt() + self.send_request_2(_event) + self.submit.disabled = False + self.history.enable_prompt() + self.update() + + + # send the prompt to the server and display the answer + def send_request_2(self, _event): + model = self.model.value + prompt = self.history.current_prompt() + server_instance = SERVERS[self.server.value] + + # record the question asked + self.history.add_prompt(prompt) + # create placeholder for the answer + self.history.add_answer("") + # update UI + self.update() + + # send the request + streaming = self.streaming.value + + print(f"Sending message to {server_instance.name}, {model=}, {streaming=}, {prompt=}") + + # streaming or non streaming + if not streaming: + # not streaming = blocking + answers = server_instance.generate_blocking(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + else: + # streaming version + answers = server_instance.generate_streaming(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + + +def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) + + +ft.app(target=main) diff --git a/notebooks/tps/chatbot/.teacher/chatbot-12.py b/notebooks/tps/chatbot/.teacher/chatbot-12.py new file mode 100644 index 0000000..58352da --- /dev/null +++ b/notebooks/tps/chatbot/.teacher/chatbot-12.py @@ -0,0 +1,433 @@ +""" +instead of using a hard-wired list of models, +we fetch the list of supported models at the server +at the api/tags endpoint using GET +""" + +import json +import os +from typing import Iterator + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD, LITELLM_KEY from .env +from dotenv import load_dotenv +import requests +import flet as ft + +load_dotenv() + +# in this version we create servers as INSTANCES of CLASSES +# so we can encapsulate the logic to interact with them +# +# rationale is to be able to talk with servers that implement other APIs +# e.g. litellm that has also been deployed and on more servers + +# we keep the idea of specifying our available servers as this dictionary +# but below we'll use this to create actual server INSTANCES + +SERVER_SPECS = { + 'GPU': { + "type": "ollama", + "name": "GPU fast", + "url": "https://ollama-sam.inria.fr", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), + }, + 'CPU': { + "type": "ollama", + "name": "CPU slow", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), + }, + 'LiteLLM': { + "type": "litellm", + "name": "LiteLLM (GPUs)", + "url": "https://litellm-sam.inria.fr", + "key": os.getenv("LITELLM_KEY"), + } +} + +TITLE = "My first Chatbot 12" + +class Server: + """ + an abstract server class + """ + def list_model_names(self) -> list[str]: + pass + def generate_blocking(self, prompt, model) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass + + +class OllamaServer(Server): + """ + for servers that comply with ollama's API + """ + def __init__(self, name, url, username=None, password=None): + self.name = name + self.url = url + self.username = username + self.password = password + + def _authenticate_extra_args(self) -> dict: + auth_args = {} + if self.username is not None: + auth_args = { + 'auth': (self.username, self.password) + } + return auth_args + + def list_model_names(self): + url = f"{self.url}/api/tags" + auth_args = self._authenticate_extra_args() + answer = requests.get(url, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return [] + raw = answer.json() + return [model['name'] for model in raw['models']] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return result + for line in answer.text.split("\n"): + # splitting artefacts can be ignored + if not line: + continue + # there should be no exception, but just in case... + try: + data = json.loads(line) + # the last JSON chunk contains statistics and is not a message + if data['done']: + break + result.append(data['response']) + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + return result + + def generate_streaming(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + answer = requests.post(url, json=payload, stream=True, **auth_args) + print(f"HTTP retcod on {url}:", answer.status_code) + if not (200 <= answer.status_code < 300): + print("not 2xx, aborting") + return + for line in answer.iter_lines(): + if not line: + continue + try: + data = json.loads(line) + if data['done']: + return + yield data['response'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +class LitellmServer(Server): + """ + for servers that comply with LiteLLM's API + """ + def __init__(self, name, url, key): + self.name = name + self.url = url + self.key = key + + def _authenticate_headers(self) -> dict: + if not self.key: + return {} + return dict(headers={"X-API-KEY": self.key}) + + def list_model_names(self): + url = f"{self.url}/models" + extra_args = self._authenticate_headers() + req = requests.get(url, **extra_args) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return [] + raw = req.json() + return [ + chunk['id'] for chunk in raw['data'] + ] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + } + # print("sending POST to", url, "with payload", payload) + req = requests.post( + url, + json=payload, + **self._authenticate_headers() + ) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return [] + raw = req.json() + result = [] + if 'choices' in raw: + for choice in raw['choices']: + result.append(choice['text']) + return result + + + def generate_streaming(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + "stream": True, + } + # print("sending POST to", url, "with payload", payload) + req = requests.post( + url, + json=payload, + stream=True, + **self._authenticate_headers() + ) + print(f"HTTP retcod on {url}:", req.status_code) + if not (200 <= req.status_code < 300): + print("not 2xx, aborting") + return + for chunk in req.iter_lines(): + if not chunk: + continue + try: + chunk = chunk.decode('utf-8') + # remove extra 'data: ' prefix + if chunk.startswith("data: "): + chunk = chunk[6:] + data = json.loads(chunk) + if 'choices' in data: + for choice in data['choices']: + yield choice['text'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +SERVERS = {} +for key, spec in SERVER_SPECS.items(): + match spec['type']: + case 'ollama': + SERVERS[key] = OllamaServer( + name=spec['name'], + url=spec['url'], + username=spec.get('username', None), + password=spec.get('password', None), + ) + case 'litellm': + SERVERS[key] = LitellmServer( + name=spec['name'], + url=spec['url'], + key=spec['key'], + ) + + +class History(ft.Column): + """ + the history is a column of text messages + where prompts and answers alternate + """ + + def __init__(self, app): + super().__init__( + [ft.TextField( + label="Type a message...", + on_submit=lambda event: app.send_request(event), + fill_color="lightgrey", + )], + scroll=ft.ScrollMode.AUTO, + auto_scroll=True, + expand=True, + ) + + # insert material - prompt or answer - to allow for different styles + def add_prompt(self, message): + self._add_entry(message, "prompt") + def add_answer(self, message): + self._add_entry(message, "answer") + def _add_entry(self, message, kind): + display = ft.Text(value=message) + display.color = "blue" if kind == "prompt" else "green" + display.size = 20 if kind == "prompt" else 16 + display.italic = kind == "prompt" + self.controls.insert(-1, display) + + # we always insert in the penultimate position + # given that the last item in controls is the prompt TextField + def add_chunk(self, chunk): + self.controls[-2].value += chunk + def current_prompt(self): + return self.controls[-1].value + + def enable_prompt(self): + self.controls[-1].disabled = False + def disable_prompt(self): + self.controls[-1].disabled = True + +class ChatbotApp(ft.Column): + + def __init__(self): + # we keep a cache of available models on each server + self.model_names_per_server = {} + + header = ft.Text(value=TITLE, size=40) + + self.streaming = ft.Checkbox(label="streaming", value=True) + # will be populated later + self.model = ft.Dropdown( + # options=[], + # width=300, + expand=True, + ) + self.server = ft.Dropdown( + options=[ft.dropdown.Option(server) + for server in SERVER_SPECS.keys()], + value="GPU", + width=100, + on_change=lambda event: self.update_models(), + ) + + self.submit = ft.ElevatedButton("Send", on_click=self.send_request) + + self.history = History(self) + + row = ft.Row( + [self.streaming, self.model, self.server, self.submit], + alignment=ft.MainAxisAlignment.CENTER, + ) + super().__init__( + [header, row, self.history], + horizontal_alignment=ft.CrossAxisAlignment.CENTER, + expand=True, + ) + + # go fetch the relevant models for the selected server + # as explained below, at this point we are not yet in the page + # so we cannot yet call update() at this point + self.update_models(update=False) + + def fetch_models(self): + # already fetched ? + # if empty, try again + if (self.server.value in self.model_names_per_server + and self.model_names_per_server[self.server.value]): + return + server_instance = SERVERS[self.server.value] + model_names = server_instance.list_model_names() + # for usability: sort the models alphabetically + model_names.sort() + self.model_names_per_server[self.server.value] = model_names + + def update_models(self, *, update=True): + # preserve current setting as far as possible + current_model = self.model.value + self.fetch_models() + available_models = self.model_names_per_server[self.server.value] + # replace the current options with the new ones + self.model.options = [ + ft.dropdown.Option(model) for model in self.model_names_per_server[self.server.value] + ] + # preserve setting if possible, otherwise pick first one + if current_model in available_models: + self.model.value = current_model + else: + # pick a mistral model by default + for model in available_models: + if model.startswith("mistral-"): + self.model.value = model + break + # otherwise, pick the first model that not a 'all-...' + # this is a workaround because somehow the first model on GPU + # namely - all-minilm:22m-l6-v2-fp16 + # returns an error saying the model does not support generate + else: + self.model.value = next( + model for model in available_models if not model.startswith("all-") + ) + # a subtle point here: because we call update_models in the constructor, + # and because at that time the app is not yet in the page + # we cannot call update() in that circumstance() + # BUT since this method is bound the the 'change' event on the server widget + # in that circumstance we need to update + if update: + self.update() + + def send_request(self, _event): + # disable the button to prevent double submission + self.submit.disabled = True + self.history.disable_prompt() + self.send_request_2(_event) + self.submit.disabled = False + self.history.enable_prompt() + self.update() + + + # send the prompt to the server and display the answer + def send_request_2(self, _event): + model = self.model.value + prompt = self.history.current_prompt() + server_instance = SERVERS[self.server.value] + + # record the question asked + self.history.add_prompt(prompt) + # create placeholder for the answer + self.history.add_answer("") + context = f"➡️ {server_instance.name} / {model}) ...\n" + self.history.add_chunk(context) + # update UI + self.update() + + # send the request + streaming = self.streaming.value + + print(f"Sending message to {server_instance.name}, {model=}, {streaming=}, {prompt=}") + + # streaming or non streaming + if not streaming: + # not streaming = blocking + answers = server_instance.generate_blocking(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + else: + # streaming version + answers = server_instance.generate_streaming(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + + +def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) + + +ft.app(target=main) diff --git a/notebooks/tps/chatbot/.teacher/chatbot-13.py b/notebooks/tps/chatbot/.teacher/chatbot-13.py new file mode 100644 index 0000000..0b9a50f --- /dev/null +++ b/notebooks/tps/chatbot/.teacher/chatbot-13.py @@ -0,0 +1,494 @@ +""" +better error reporting: +errors from requests are caught and displayed in a message area +between the title and the dialog +""" + +import json +import os +from datetime import datetime +from typing import Iterator + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD, LITELLM_KEY from .env +from dotenv import load_dotenv +import requests +import flet as ft + +load_dotenv() + +# in this version we create servers as INSTANCES of CLASSES +# so we can encapsulate the logic to interact with them +# +# rationale is to be able to talk with servers that implement other APIs +# e.g. litellm that has also been deployed and on more servers + +# we keep the idea of specifying our available servers as this dictionary +# but below we'll use this to create actual server INSTANCES + +DEFAULT_SERVER = "CPU" + +SERVER_SPECS = { + 'GPU': { + "type": "ollama", + "name": "GPU fast", + "url": "https://ollama-sam.inria.fr", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), + }, + 'CPU': { + "type": "ollama", + "name": "CPU slow", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), + }, + 'LiteLLM': { + "type": "litellm", + "name": "LiteLLM (GPUs)", + "url": "https://litellm-sam.inria.fr", + "key": os.getenv("LITELLM_KEY"), + } +} + +TITLE = "My first Chatbot 13" + + +class ServerError(Exception): + """raised when a server request fails""" + pass + + +class Server: + """ + an abstract server class + """ + def list_model_names(self) -> list[str]: + pass + def generate_blocking(self, prompt, model) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass + + +class OllamaServer(Server): + """ + for servers that comply with ollama's API + """ + def __init__(self, name, url, username=None, password=None): + self.name = name + self.url = url + self.username = username + self.password = password + + def _authenticate_extra_args(self) -> dict: + auth_args = {} + if self.username is not None: + auth_args = { + 'auth': (self.username, self.password) + } + return auth_args + + def list_model_names(self): + url = f"{self.url}/api/tags" + auth_args = self._authenticate_extra_args() + print(f"Fetching model names from {url} with auth_args={auth_args}") + try: + answer = requests.get(url, **auth_args) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= answer.status_code < 300): + raise ServerError( + f"HTTP {answer.status_code} on {url}\n{answer.text[:200]}") + raw = answer.json() + return [model['name'] for model in raw['models']] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + result = [] + + try: + answer = requests.post(url, json=payload, **auth_args) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= answer.status_code < 300): + raise ServerError( + f"HTTP {answer.status_code} on {url}\n{answer.text[:200]}") + for line in answer.text.split("\n"): + # splitting artefacts can be ignored + if not line: + continue + # there should be no exception, but just in case... + try: + data = json.loads(line) + # the last JSON chunk contains statistics and is not a message + if data['done']: + break + result.append(data['response']) + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + return result + + def generate_streaming(self, prompt, model): + url = f"{self.url}/api/generate" + auth_args = self._authenticate_extra_args() + payload = {'model': model, 'prompt': prompt} + + try: + answer = requests.post(url, json=payload, stream=True, **auth_args) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= answer.status_code < 300): + raise ServerError( + f"HTTP {answer.status_code} on {url}\n{answer.text[:200]}") + for line in answer.iter_lines(): + if not line: + continue + try: + data = json.loads(line) + if data['done']: + return + yield data['response'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +class LitellmServer(Server): + """ + for servers that comply with LiteLLM's API + """ + def __init__(self, name, url, key): + self.name = name + self.url = url + self.key = key + + def _authenticate_headers(self) -> dict: + if not self.key: + return {} + return dict(headers={"X-API-KEY": self.key}) + + def list_model_names(self): + url = f"{self.url}/models" + extra_args = self._authenticate_headers() + try: + req = requests.get(url, **extra_args) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= req.status_code < 300): + raise ServerError( + f"HTTP {req.status_code} on {url}\n{req.text[:200]}") + raw = req.json() + return [ + chunk['id'] for chunk in raw['data'] + ] + + def generate_blocking(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + } + try: + req = requests.post( + url, + json=payload, + **self._authenticate_headers() + ) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= req.status_code < 300): + raise ServerError( + f"HTTP {req.status_code} on {url}\n{req.text[:200]}") + raw = req.json() + result = [] + if 'choices' in raw: + for choice in raw['choices']: + result.append(choice['text']) + return result + + + def generate_streaming(self, prompt, model): + url = f"{self.url}/v1/completions" + payload = { + "model": model, + "prompt": prompt, + "stream": True, + } + try: + req = requests.post( + url, + json=payload, + stream=True, + **self._authenticate_headers() + ) + except requests.exceptions.RequestException as exc: + raise ServerError(f"cannot reach {url}: {exc}") from exc + if not (200 <= req.status_code < 300): + raise ServerError( + f"HTTP {req.status_code} on {url}\n{req.text[:200]}") + for chunk in req.iter_lines(): + if not chunk: + continue + try: + chunk = chunk.decode('utf-8') + # remove extra 'data: ' prefix + if chunk.startswith("data: "): + chunk = chunk[6:] + data = json.loads(chunk) + if 'choices' in data: + for choice in data['choices']: + yield choice['text'] + except Exception as e: + print(f"Exception {type(e)=}, {e=}") + + +SERVERS = {} +for key, spec in SERVER_SPECS.items(): + match spec['type']: + case 'ollama': + SERVERS[key] = OllamaServer( + name=spec['name'], + url=spec['url'], + username=spec.get('username', None), + password=spec.get('password', None), + ) + case 'litellm': + SERVERS[key] = LitellmServer( + name=spec['name'], + url=spec['url'], + key=spec['key'], + ) + + +class History(ft.Column): + """ + the history is a column of text messages + where prompts and answers alternate + """ + + def __init__(self, app): + super().__init__( + [ft.TextField( + label="Type a message...", + on_submit=lambda event: app.send_request(event), + fill_color="lightgrey", + )], + scroll=ft.ScrollMode.AUTO, + auto_scroll=True, + expand=True, + ) + + # insert material - prompt or answer - to allow for different styles + def add_prompt(self, message): + self._add_entry(message, "prompt") + def add_answer(self, message): + self._add_entry(message, "answer") + def _add_entry(self, message, kind): + display = ft.Text(value=message) + display.color = "blue" if kind == "prompt" else "green" + display.size = 20 if kind == "prompt" else 16 + display.italic = kind == "prompt" + self.controls.insert(-1, display) + + # we always insert in the penultimate position + # given that the last item in controls is the prompt TextField + def add_chunk(self, chunk): + self.controls[-2].value += chunk + def current_prompt(self): + return self.controls[-1].value + + def enable_prompt(self): + self.controls[-1].disabled = False + def disable_prompt(self): + self.controls[-1].disabled = True + +class ChatbotApp(ft.Column): + + def __init__(self): + # we keep a cache of available models on each server + self.model_names_per_server = {} + + header = ft.Text(value=TITLE, size=40) + + # a message area to display errors and status messages + # placed between the title and the controls + self.message_text = ft.Text(value="", color="grey", size=12) + self.message_area = ft.Container( + content=ft.Column( + [self.message_text], + scroll=ft.ScrollMode.AUTO, + auto_scroll=True, + ), + width=float("inf"), + height=60, + border=ft.border.all(1, "grey"), + border_radius=5, + padding=5, + ) + + self.streaming = ft.Checkbox(label="streaming", value=True) + # will be populated later + self.model = ft.Dropdown( + # options=[], + # width=300, + expand=True, + ) + self.server = ft.Dropdown( + options=[ft.dropdown.Option(server) + for server in SERVER_SPECS.keys()], + value=DEFAULT_SERVER, + width=100, + on_change=lambda event: self.update_models(), + ) + + self.submit = ft.ElevatedButton("Send", on_click=self.send_request) + + self.history = History(self) + + row = ft.Row( + [self.streaming, self.model, self.server, self.submit], + alignment=ft.MainAxisAlignment.CENTER, + ) + super().__init__( + [header, self.message_area, row, self.history], + horizontal_alignment=ft.CrossAxisAlignment.CENTER, + expand=True, + ) + + # go fetch the relevant models for the selected server + # as explained below, at this point we are not yet in the page + # so we cannot yet call update() at this point + # this is harmful when the default server is down or unreachable + # so let's turn off this auto-connect line + # self.update_models(update=False) + + def show_message(self, message): + """display a message in the message area""" + timestamp = datetime.now().strftime("%H:%M:%S") + line = f"{timestamp} {message}" + if self.message_text.value: + self.message_text.value += f"\n{line}" + else: + self.message_text.value = line + + def fetch_models(self): + # already fetched ? + # if empty, try again + if (self.server.value in self.model_names_per_server + and self.model_names_per_server[self.server.value]): + return + server_instance = SERVERS[self.server.value] + model_names = server_instance.list_model_names() + # for usability: sort the models alphabetically + model_names.sort() + self.model_names_per_server[self.server.value] = model_names + + def update_models(self, *, update=True): + # preserve current setting as far as possible + current_model = self.model.value + try: + self.fetch_models() + except (ServerError, requests.exceptions.RequestException) as exc: + self.show_message(f"fetching models: {exc}") + self.model_names_per_server[self.server.value] = [] + if update: + self.update() + return + available_models = self.model_names_per_server[self.server.value] + # replace the current options with the new ones + self.model.options = [ + ft.dropdown.Option(model) for model in available_models + ] + # preserve setting if possible, otherwise pick first one + if current_model in available_models: + self.model.value = current_model + else: + # pick a mistral model by default + for model in available_models: + if model.startswith("mistral-"): + self.model.value = model + break + # otherwise, pick the first model that not a 'all-...' + # this is a workaround because somehow the first model on GPU + # namely - all-minilm:22m-l6-v2-fp16 + # returns an error saying the model does not support generate + else: + self.model.value = next( + (model for model in available_models + if not model.startswith("all-")), + None, + ) + # a subtle point here: because we call update_models in the constructor, + # and because at that time the app is not yet in the page + # we cannot call update() in that circumstance() + # BUT since this method is bound the the 'change' event on the server widget + # in that circumstance we need to update + if update: + self.update() + + def send_request(self, _event): + # disable the button to prevent double submission + # self.submit.disabled = True + self.submit.style = ft.ButtonStyle(bgcolor="red") + self.history.disable_prompt() + self.send_request_2(_event) + # self.submit.disabled = False + self.submit.style = ft.ButtonStyle(bgcolor="green") + self.history.enable_prompt() + self.update() + + + # send the prompt to the server and display the answer + def send_request_2(self, _event): + model = self.model.value + prompt = self.history.current_prompt() + server_instance = SERVERS[self.server.value] + + # record the question asked + self.history.add_prompt(prompt) + # create placeholder for the answer + self.history.add_answer("") + context = f"➡️ {server_instance.name} / {model}) ...\n" + self.history.add_chunk(context) + # update UI + self.update() + + # send the request + streaming = self.streaming.value + + print(f"Sending message to {server_instance.name}, {model=}, {streaming=}, {prompt=}") + + try: + # streaming or non streaming + if not streaming: + # not streaming = blocking + answers = server_instance.generate_blocking(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + else: + # streaming version + answers = server_instance.generate_streaming(prompt, model) + for text in answers: + self.history.add_chunk(text) + self.update() + except (ServerError, requests.exceptions.RequestException) as exc: + self.show_message(f"send request: {exc}") + self.update() + + +def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) + + +ft.app(target=main) diff --git a/notebooks/tps/chatbot/README-chatbot-nb.md b/notebooks/tps/chatbot/README-chatbot-nb.md index 9c0b958..33bfc9f 100644 --- a/notebooks/tps/chatbot/README-chatbot-nb.md +++ b/notebooks/tps/chatbot/README-chatbot-nb.md @@ -7,12 +7,6 @@ kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 -language_info: - name: python - nbconvert_exporter: python - pygments_lexer: ipython3 -nbhosting: - title: 'TP: un chatbot' --- # TP - un chatbot avec `flet` @@ -39,7 +33,7 @@ on met à votre disposition **deux serveurs** `ollama`: - chacun des deux sait mettre en oeuvre plusieurs modèles d'IA (notamment `mistral`, mais pas que...) - l'un des deux ne possède qu'un CPU; du coup il est relativement lent mais on peut y accéder sans login/password - par contre l'autre possède un GPU, il est plus rapide pour notre application, mais le code pour s'en servir est un peu plus compliqué car il faut lui fournir un login/password -- les détails de ces deux serveurs sont dans le *starter code* +- les détails de ces deux serveurs sont dans le *starter code* (à part les login/password qui vous seront communiqués par un autre moyen) - pour les utiliser, essentiellement on `POST` une requête http au serveur avec le chemin `/api/generate` @@ -57,7 +51,7 @@ ce qu'on veut faire, c'est fabriquer une UI sommaire qui permet - de choisir le serveur, - de choisir le modèle, - et de poser ensuite des questions comme avec chatGPT -- enfin sur cette implémentation on a également un bouton qui permet d'enabler le *streaming* +- enfin sur cette implémentation on a également un bouton qui permet d'enabler le *streaming* l'idée consiste à afficher les résultats "au fur et à mesure" plutôt qu'en une seule fois à la fin de l'échange avec le serveur, on en reparlera... @@ -150,7 +144,7 @@ pour vous familiariser avec le modèle de lignes et colonnes de `flet`, **ajoute - et `flet.Text` - et à chaque fois les différents attributs disponibles pour contrôler le look et le comportement de l'UI -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ## v03: avec un peu de classe: `ChatbotApp` @@ -158,8 +152,12 @@ ceci est une étape **totalement optionnelle**, mais je vous recommande de **cr - on pourrait envisager par exemple que `ChatbotApp` hérite de `ft.Column` - de cette façon on se retrouverait avec un `main` qui ne fait plus que - ```{literalinclude} chatbot-03a.py - :start-after: show the code in the instructions + ```{code} python + def main(page: ft.Page): + page.title = TITLE + + chatbot = ChatbotApp() + page.add(chatbot) ``` Je vous propose de procéder en deux temps @@ -191,7 +189,9 @@ toujours pour éviter de finir avec un gros paquet de spaguettis, on va imaginer - la `Row` avec les différents réglages - et une instance de `History()` -`````{admonition} la logique de la classe History ++++ + +```{admonition} la logique de la classe History :class: tip pour fixer les idées, disons qu'à ce stade cette classe possède les méthodes @@ -205,7 +205,9 @@ l'idée est que l'objet `History` possède: et pour cela on utilisera `add_message(some_text)`, dont le job donc est d'insérer un objet `ft.Text` (non modifiable par l'utilisateur cette fois) **en avant-dernière position** - c'est-à-dire juste au dessus du prompt -````` +``` + ++++ pour être bien clair, à ce stade on ne fait pas encore usage du réseau pour quoi que ce soit, on veut juste mettre en place la structure de l'UI @@ -214,12 +216,12 @@ ici encore je vous conseille de procéder par petites étapes: - 4a: la trame de la classe `History` - 4b: faites en sorte que le fait de taper "Entrée" dans la zone de prompt fasse le même effet que le bouton "Send" -```{admonition} regardez la classe `TextField` +:::{admonition} regardez la classe `TextField` :class: tip pour le titre on utilise la classe `Text` qui est en *read-only*; pour la zone de prompt, il est préferable d'utiliser `TextField` qui est *editable* et qui offre plus de flexibilité -``` +::: +++ @@ -256,7 +258,7 @@ ce code peut s'exécuter par exemple directement dans ipython import requests import json -url = "http://ollama.pl.sophia.inria.fr:8080/api/generate" +url = "https://ollama.pl.sophia.inria.fr/api/generate" # c'est expliqué dans la doc ollama: l'API /api/generate # s'attend à ce qu'on lui passe ces deux paramètres: @@ -450,7 +452,58 @@ plutôt que de proposer une liste de modèles "en dur" comme dans le *starter co dans mon implémentation j'ai choisi de "cacher" ce résultat, pour ne pas redemander plusieurs fois cette liste à un même serveur (cette liste bouge très très peu...); mais c'est optionnel; par contre ce serait sympa pour les utilisateurs de conserver, lorsque c'est possible, le modèle choisi lorsqu'on change de serveur... -+++ +## v10 (optionnel): une classe `Server` + +dans cette version, je vous propose de **créer une classe `Server` abstraite**, +qui définit une API commune pour interagir avec un serveur d'IA; puis une classe +concrète **`OllamaServer`** qui hérite de `Server` et qui encapsule la logique +d'interaction avec l'API ollama - puisque pour l'instant nos deux serveurs +offrent la même API + +mais de cette façon dans le futur (étape suivante) on pourra plus simplement +ajouter le code pour interagir avec d'autres types de serveurs, qui implémentent +une API différente (par exemple `litellm` que nous avons aussi déployé à +l'Inria) + +c'est pourquoi dans cette v10, je vous propose de rester à fonctionnalités +constantes, mais de créer une classe `OllamaServer` qui hérite de +`Server` et qui implémente les méthodes suivantes: + +```python +class Server: + """ + an abstract server class + """ + def list_models(self) -> list[str]: + pass + def generate_blocking(self, prompt, model, streaming ) -> list[str]: + """ + non-streaming generation - returns a list of text chunks + """ + pass + def generate_streaming(self, prompt, model, streaming) -> Iterator[str]: + """ + streaming generation - yields text chunks + """ + pass +``` + +## v11 (optionnel): une autre API + +à présent que nous avons une classe `Server`, on va pouvoir **implémenter une autre classe** qui hérite de `Server`, par exemple `LitellmServer`, qui implémente la même API mais en s'appuyant sur le serveur `litellm-sam.inria.fr` + +l'API en question est documentée ici + (pour l'instant nécessite +un VPN) - et sans doute à plein d'autres endroits publics + +pour vous authentifier vous aurez également besoin d'une clé API - communiquée par un autre moyen + +le but du jeu consiste donc ici à +- implémenter une classe concrète `LitellmServer` qui hérite de `Server` et qui +implémente les mêmes méthodes que `OllamaServer`, mais en s'appuyant sur l'API +`litellm` +- ajouter une entrée dans le dictionnaire `SERVERS` pour pouvoir choisir ce + serveur dans l'interface ## plein d'améliorations possibles diff --git a/notebooks/tps/chatbot/chatbot-01.py b/notebooks/tps/chatbot/chatbot-01.py index 165a09e..db17650 100644 --- a/notebooks/tps/chatbot/chatbot-01.py +++ b/notebooks/tps/chatbot/chatbot-01.py @@ -7,22 +7,26 @@ """ +import os + +# reads GPU_USERNAME, GPU_PASSWORD, CPU_USERNAME, CPU_PASSWORD from .env +from dotenv import load_dotenv import flet as ft +load_dotenv() + SERVERS = { - # this one is fast because it has GPUs, - # but it requires a login / password 'GPU': { "name": "GPU fast", "url": "https://ollama-sam.inria.fr", - "username": "Bob", - "password": "hiccup", + "username": os.getenv("GPU_USERNAME"), + "password": os.getenv("GPU_PASSWORD"), }, - # this one is slow because it has no GPUs, - # but it does not require a login / password 'CPU': { "name": "CPU slow", - "url": "http://ollama.pl.sophia.inria.fr:8080", + "url": "https://ollama.pl.sophia.inria.fr", + "username": os.getenv("CPU_USERNAME"), + "password": os.getenv("CPU_PASSWORD"), }, } diff --git a/notebooks/tps/dobble/.teacher/README-dobble-corrige-nb.md b/notebooks/tps/dobble/.teacher/README-dobble-corrige-nb.md index e8add0b..c9a3131 100644 --- a/notebooks/tps/dobble/.teacher/README-dobble-corrige-nb.md +++ b/notebooks/tps/dobble/.teacher/README-dobble-corrige-nb.md @@ -52,6 +52,7 @@ Et ce qui est un peu étonnant, c'est que **pour tout couple de cartes** il y a L'idée ici consiste donc à rétro-concevoir le mécanisme de fabrication des cartes: On se fixe un nombre **N** de symboles par carte: + * quelle est la logique qui permet de construire un jeu de cartes qui vérifie la bonne propriété ? * combien de cartes peut-on construire ? * combien de symboles faut-il utiliser ? @@ -593,7 +594,7 @@ def draw_map(self, figsize=(8, 8)): ys([-0.5, self.expected()-0.5]), 'k-', linewidth=0.5) # save as svg, but in the media/ folder - output = path(self.filename.replace("data/", "media/")).with_suffix('.svg')) + output = Path(self.filename.replace("data/", "media/")).with_suffix('.svg') plt.savefig(output) Deck.draw_map = draw_map diff --git a/notebooks/tps/dobble/ARTEFACTS-dobble.zip b/notebooks/tps/dobble/ARTEFACTS-dobble.zip index e036cc6..078cc8e 100644 Binary files a/notebooks/tps/dobble/ARTEFACTS-dobble.zip and b/notebooks/tps/dobble/ARTEFACTS-dobble.zip differ diff --git a/notebooks/tps/dobble/README-dobble-nb.md b/notebooks/tps/dobble/README-dobble-nb.md index d4b099b..8066ea4 100644 --- a/notebooks/tps/dobble/README-dobble-nb.md +++ b/notebooks/tps/dobble/README-dobble-nb.md @@ -44,6 +44,7 @@ Et ce qui est un peu étonnant, c'est que **pour tout couple de cartes** il y a L'idée ici consiste donc à rétro-concevoir le mécanisme de fabrication des cartes: On se fixe un nombre **N** de symboles par carte: + * quelle est la logique qui permet de construire un jeu de cartes qui vérifie la bonne propriété ? * combien de cartes peut-on construire ? * combien de symboles faut-il utiliser ? diff --git a/notebooks/tps/explang/.teacher/README-explang-corrige-nb.md b/notebooks/tps/explang/.teacher/README-explang-corrige-nb.md index eb9d213..4968f5b 100644 --- a/notebooks/tps/explang/.teacher/README-explang-corrige-nb.md +++ b/notebooks/tps/explang/.teacher/README-explang-corrige-nb.md @@ -12,11 +12,10 @@ language_info: name: python nbconvert_exporter: python pygments_lexer: ipython3 -nbhosting: - title: 'TP: langage d''expressions' +short_title: OOP et langage d'expressions +title: un langage d'expressions implémenté en OOP --- -# un petit langage d'expressions +++ @@ -45,6 +44,7 @@ Traditionnellement (l'implémentation d')un langage est vu comme une suite d'op * analyse lexicale et syntaxique : on manipule le code sous forme de texte, pour le transformer en une structure de données qui soit plus adaptée à toute la série de calculs qu'on doit faire dans les parties suivantes, puis + * l'interprétation / compilation propremement dite. +++ @@ -107,6 +107,7 @@ et munis de ce vocabulaire on peut maintenant représenter a := 20 a + 1 ``` + * par l'arbre ``` Expressions( @@ -139,9 +140,11 @@ expression.eval() +++ Parmi ce qui est attendu: + * on s'efforcera de **factoriser au maximum le code**, et d'éviter dans toute la mesure du possible les répétitions fastidieuses c'est tout l'objectif de cet exercice, on veut produire un code maintenable (pas de répétition), et dans lequel on puisse facilement ajouter des *features* (nouveaux opérateurs notamment). + * on vous demande à la construction des objets de vérifier qu'on **appelle** le **constructeur** avec un **nombre d'arguments correct**, et de lancer une **exception `TypeError` sinon** (comme le fait Python lorsqu'on appelle une fonction avec un mauvais nombre d'arguments) voyez tout à la fin du notebook un tableau récapitulatif des nombres d'arguments @@ -211,46 +214,64 @@ from explangv1 import * et ensuite vous évaluez ces cellules pour tester votre code ```{code-cell} ipython3 +:tags: [raises-exception] + # should print 10 tree = Integer(10); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # -10 tree = Negative(Integer(10)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 30 tree = Plus(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 60 tree = Plus(Integer(10), Integer(20), Integer(30)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 24 tree = Multiply(Integer(2), Integer(3), Integer(4)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 0.5 tree = Divide(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 200 tree = Multiply(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 6000 tree = Multiply(Integer(10), Integer(20), Integer(30)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Multiply( Plus(Multiply(Integer(10), Integer(2)), Integer(30)), Multiply(Negative(Integer(4)), Integer(25))) @@ -259,6 +280,8 @@ assert tree.eval() == -5000 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Plus(Multiply(Integer(10), Integer(2)), Negative(Negative(Integer(30))), Minus(Integer(100), Integer(50))) @@ -267,6 +290,8 @@ assert tree.eval() == 100 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Multiply( Plus(Integer(30), Integer(40), Integer(50)), Minus(Integer(20), Integer(15))) @@ -275,6 +300,8 @@ assert tree.eval() == 600 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Negative( Plus(Float(10), Negative(Integer(20)))) @@ -282,11 +309,15 @@ assert tree.eval() == 10. ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Divide(Integer(10), Integer(4)) assert tree.eval() == 2.5 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # ces cellules devraient toutes afficher OK try: Plus() @@ -295,6 +326,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Divide() except TypeError: @@ -302,6 +335,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Negative(Integer(1), Integer(1)) except TypeError: @@ -309,6 +344,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # ces cellules devraient toutes afficher OK try: Multiply(Integer(1)) @@ -317,6 +354,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Plus(Integer(1)) except TypeError: @@ -324,6 +363,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Divide(Integer(10), Integer(20), Integer(30)) except TypeError: @@ -331,6 +372,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Negative(Integer(10), Integer(20)) except TypeError: @@ -356,6 +399,7 @@ dans laquelle `env` est un dictionnaire qui associe le nom d'une variable avec s +++ pour réaliser cette deuxième partie: + * dupliquez votre code de la v1, et modifiez le a minima pour que `eval` puisse s'appeler avec la bonne signature * ajoutez les 3 nouvelles classes * `Variable`: qui correspond à l'utilisation d'une variable dans une formule @@ -388,6 +432,8 @@ from explangv2 import * et si tout marche bien vous pouvez exécuter la suite sans erreur: ```{code-cell} ipython3 +:tags: [raises-exception] + program1 = Expressions( Assignment("a", Integer(10)), Assignment("b", Integer(20)), @@ -398,6 +444,8 @@ assert program1.eval({}) == 30 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + """ a = 2 + (b := 2) # env = {'a': 4, 'b': 2} b = a * b # env = {'a': 4, 'b': 8} diff --git a/notebooks/tps/explang/ARTEFACTS-explang.zip b/notebooks/tps/explang/ARTEFACTS-explang.zip index 89de4af..d0faa85 100644 Binary files a/notebooks/tps/explang/ARTEFACTS-explang.zip and b/notebooks/tps/explang/ARTEFACTS-explang.zip differ diff --git a/notebooks/tps/explang/README-explang-nb.md b/notebooks/tps/explang/README-explang-nb.md index b12998a..183b120 100644 --- a/notebooks/tps/explang/README-explang-nb.md +++ b/notebooks/tps/explang/README-explang-nb.md @@ -12,14 +12,10 @@ language_info: name: python nbconvert_exporter: python pygments_lexer: ipython3 -nbhosting: - title: 'TP: langage d''expressions' +short_title: OOP et langage d'expressions +title: un langage d'expressions implémenté en OOP --- -# un petit langage d'expressions - -+++ - Licence CC BY-NC-ND, Thierry Parmentelat +++ @@ -45,6 +41,7 @@ Traditionnellement (l'implémentation d')un langage est vu comme une suite d'op * analyse lexicale et syntaxique : on manipule le code sous forme de texte, pour le transformer en une structure de données qui soit plus adaptée à toute la série de calculs qu'on doit faire dans les parties suivantes, puis + * l'interprétation / compilation propremement dite. +++ @@ -107,6 +104,7 @@ et munis de ce vocabulaire on peut maintenant représenter a := 20 a + 1 ``` + * par l'arbre ``` Expressions( @@ -139,9 +137,11 @@ expression.eval() +++ Parmi ce qui est attendu: + * on s'efforcera de **factoriser au maximum le code**, et d'éviter dans toute la mesure du possible les répétitions fastidieuses c'est tout l'objectif de cet exercice, on veut produire un code maintenable (pas de répétition), et dans lequel on puisse facilement ajouter des *features* (nouveaux opérateurs notamment). + * on vous demande à la construction des objets de vérifier qu'on **appelle** le **constructeur** avec un **nombre d'arguments correct**, et de lancer une **exception `TypeError` sinon** (comme le fait Python lorsqu'on appelle une fonction avec un mauvais nombre d'arguments) voyez tout à la fin du notebook un tableau récapitulatif des nombres d'arguments @@ -203,46 +203,64 @@ class Divide: et ensuite vous évaluez ces cellules pour tester votre code ```{code-cell} ipython3 +:tags: [raises-exception] + # should print 10 tree = Integer(10); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # -10 tree = Negative(Integer(10)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 30 tree = Plus(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 60 tree = Plus(Integer(10), Integer(20), Integer(30)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 24 tree = Multiply(Integer(2), Integer(3), Integer(4)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 0.5 tree = Divide(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 200 tree = Multiply(Integer(10), Integer(20)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # 6000 tree = Multiply(Integer(10), Integer(20), Integer(30)); print(tree.eval()) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Multiply( Plus(Multiply(Integer(10), Integer(2)), Integer(30)), Multiply(Negative(Integer(4)), Integer(25))) @@ -251,6 +269,8 @@ assert tree.eval() == -5000 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Plus(Multiply(Integer(10), Integer(2)), Negative(Negative(Integer(30))), Minus(Integer(100), Integer(50))) @@ -259,6 +279,8 @@ assert tree.eval() == 100 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Multiply( Plus(Integer(30), Integer(40), Integer(50)), Minus(Integer(20), Integer(15))) @@ -267,6 +289,8 @@ assert tree.eval() == 600 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Negative( Plus(Float(10), Negative(Integer(20)))) @@ -274,11 +298,15 @@ assert tree.eval() == 10. ``` ```{code-cell} ipython3 +:tags: [raises-exception] + tree = Divide(Integer(10), Integer(4)) assert tree.eval() == 2.5 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # ces cellules devraient toutes afficher OK try: Plus() @@ -287,6 +315,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Divide() except TypeError: @@ -294,6 +324,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Negative(Integer(1), Integer(1)) except TypeError: @@ -301,6 +333,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # ces cellules devraient toutes afficher OK try: Multiply(Integer(1)) @@ -309,6 +343,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Plus(Integer(1)) except TypeError: @@ -316,6 +352,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Divide(Integer(10), Integer(20), Integer(30)) except TypeError: @@ -323,6 +361,8 @@ except TypeError: ``` ```{code-cell} ipython3 +:tags: [raises-exception] + try: Negative(Integer(10), Integer(20)) except TypeError: @@ -348,6 +388,7 @@ dans laquelle `env` est un dictionnaire qui associe le nom d'une variable avec s +++ pour réaliser cette deuxième partie: + * dupliquez votre code de la v1, et modifiez le a minima pour que `eval` puisse s'appeler avec la bonne signature * ajoutez les 3 nouvelles classes * `Variable`: qui correspond à l'utilisation d'une variable dans une formule @@ -375,6 +416,8 @@ class Expressions: et si tout marche bien vous pouvez exécuter la suite sans erreur: ```{code-cell} ipython3 +:tags: [raises-exception] + program1 = Expressions( Assignment("a", Integer(10)), Assignment("b", Integer(20)), @@ -385,6 +428,8 @@ assert program1.eval({}) == 30 ``` ```{code-cell} ipython3 +:tags: [raises-exception] + """ a = 2 + (b := 2) # env = {'a': 4, 'b': 2} b = a * b # env = {'a': 4, 'b': 8} diff --git a/notebooks/tps/explang2/.teacher/README-explang2-corrige-nb.md b/notebooks/tps/explang2/.teacher/README-explang2-corrige-nb.md new file mode 100644 index 0000000..ce0eb85 --- /dev/null +++ b/notebooks/tps/explang2/.teacher/README-explang2-corrige-nb.md @@ -0,0 +1,336 @@ +--- +jupytext: + encoding: '# -*- coding: utf-8 -*-' + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +language_info: + name: python + nbconvert_exporter: python + pygments_lexer: ipython3 +short_title: full expression lang +title: "a small expression language: lexer, parser, eval" +authors: + - Aurélien Noce + - Thierry Parmentelat +--- + + ++++ + +Licence CC BY-NC-ND, Thierry Parmentelat + ++++ + +```{admonition} about this TP +this is a sequel to the `explang` TP; there, we only wrote the +**evaluator**, using classes, starting from an AST that was already +built for us. + +here we tackle the **whole pipeline**, from a plain string down to a +value: + +* **lexer**: turn a string of source code into a stream of tokens +* **parser**: turn that stream of tokens into an AST (here, plain tuples) +* **eval**: compute the value of that AST + +and we do it with **plain functions** rather than classes; one day we +may merge the two exercises and revisit `eval` with an OOP approach on +top of this pipeline, but for now let's take it one step at a time. +``` + ++++ + +## the pipeline + +we're building a tiny calculator that only knows about integers and the +4 operators `+ - * /`, with parentheses for grouping. + +three stages, three files: + +| stage | file | signature | input | output | +|-------|-------------|--------------------|---------------------|---------------------------| +| lex | `lexer.py` | `tokenize(file)` | a file-like object | a generator of tokens (strings) | +| parse | `parser.py` | `parse(tokens)` | a list of tokens | an AST | +| eval | `eval.py` | `eval(ast)` | an AST | a number | + +an AST node is either + +* an `int` (a leaf), or +* a 3-tuple `(op, left, right)` where `op` is one of `"+" "-" "*" "/"` + and `left`, `right` are themselves AST nodes + +for example the expression `1 + 2 * 3` gets tokenized into + +```python +['1', '+', '2', '*', '3'] +``` + +then parsed into + +```python +('+', 1, ('*', 2, 3)) +``` + +and finally evaluates to `7` + ++++ + +## the lexer + +* **works on**: generators, string methods +* **the input**: any file-like object (an open file, or an `io.StringIO`) + that contains a simple arithmetic expression, e.g. + ``` + (1 + 2) * 30 + ``` +* **todo**: write a generator function + ```python + def tokenize(file): + ... + ``` + that reads through `file` and `yield`s the tokens one at a time, as + strings: + * a run of digits becomes one token, e.g. `"30"` + * each one of `+ - * / ( )` is its own token + * whitespace (including newlines) is simply skipped + +* **tip**: don't call `file.read(1)` in a loop (that's slow); instead + **iterate** over `file` - which naturally yields lines - and then + iterate over the characters of each line + +* **bonus**: also write a small convenience helper + ```python + def tokenize_string(string): + ... + ``` + that wraps `string` in an `io.StringIO` and returns the list of + tokens directly - handy for quick tests + +```{code-cell} ipython3 +def tokenize(file): + ... + +def tokenize_string(string): + ... +``` + +```{code-cell} ipython3 +# prune-cell + +from lexer import tokenize, tokenize_string +``` + +and then you can check your code with + +```{code-cell} ipython3 +:tags: [raises-exception] + +tokenize_string("1 + 2 * 3") +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert tokenize_string("1 + 2 * 3") == ['1', '+', '2', '*', '3'] +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert tokenize_string("(1 + 2) * 30") == ['(', '1', '+', '2', ')', '*', '30'] +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# whitespace, including newlines, is not significant +assert tokenize_string(" 12\n+\n 7 ") == ['12', '+', '7'] +``` + ++++ + +## the parser + +* **works on**: recursive-descent parsing, tuples + +now that we can turn a string into a stream of tokens, we need to turn +that stream into an AST. + +we use a classic **top-down (recursive-descent)** parser, with one +function per grammar rule; the grammar we implement is: + +``` +expr := term (("+"|"-") term)* +term := factor (("*"|"/") factor)* +factor := int | "(" expr ")" +``` + +* **todo**: write + ```python + def parse(tokens): + ... + ``` + that takes the **list** of tokens produced by the lexer, and returns + the AST + + you will probably want to write it as a set of mutually recursive + helper functions, all shaped like `tokens -> (ast, remaining_tokens)`: + + * `expr(tokens)` + * `term(tokens)` + * `factor(tokens)` + + `parse` itself just calls `expr` and makes sure there are no tokens + left over + +````{admonition} the trick + +the traditional way to write this code is to have a 'cascade' of functions calling one another, as illustrated below (go full-width if that helps) + +```{image} media/parse-stack-add-first.excalidraw.svg +``` + +with another input we'd see this instead: + +```{image} media/parse-stack-mul-first.excalidraw.svg +``` + +the "lower" a rule sits in the call stack, the higher its precedence; +that's why `factor` (which handles parentheses) sits below `term` +(which handles `*` `/`), which itself sits below `expr` (which handles +`+` `-`) + +```` + +And now it's your turn: + +```{code-cell} ipython3 +def parse(tokens): + ... +``` + +```{code-cell} ipython3 +# prune-cell + +from parser import parse +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +parse(tokenize_string("1 + 2 * 3")) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert parse(tokenize_string("1 + 2 * 3")) == ('+', 1, ('*', 2, 3)) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# parentheses change the shape of the tree, not just the value +assert parse(tokenize_string("(1 + 2) * 3")) == ('*', ('+', 1, 2), 3) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# left-associativity: a - b - c is (a - b) - c, not a - (b - c) +assert parse(tokenize_string("10 - 2 - 3")) == ('-', ('-', 10, 2), 3) +``` + ++++ + +## eval + +* **works on**: recursion, dict-as-a-switch + +* **todo**: write + ```python + def eval(ast): + ... + ``` + that computes the value described by `ast` + +```{code-cell} ipython3 +def eval(ast): + ... +``` + +```{code-cell} ipython3 +# prune-cell + +from eval import eval +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("1 + 2 * 3"))) == 7 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("(1 + 2) * 3"))) == 9 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("10 - 2 - 3"))) == 5 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("(30 + 40 + 50) * (20 - 15)"))) == 600 +``` + ++++ + +## putting it all together + +now that the 3 stages are in place, you can write a one-liner that goes +straight from source to value: + +```{code-cell} ipython3 +def run(string): + return eval(parse(tokenize_string(string))) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert run("2 * (3 + 4) - 5") == 9 +``` + ++++ + +## going further (optional) + +a few ways you could extend this toy language, if you want to keep going: + +* support **unary minus**, e.g. `-3 + 4` or `-(1 + 2)` +* support **floats**, not just integers +* raise a proper, informative exception (instead of an obscure crash) + when the input is malformed, e.g. `"1 +"` or `"(1 + 2"` +* replace the **list** of tokens with the **generator** returned by + `tokenize` directly - does `parse` still work if it can only look one + token ahead, and can't index or slice into it? + +```{admonition} modalities +Once you're happy with your code, put it in `lexer.py`, `parser.py` and +`eval.py`, and import it from the notebook with e.g. +`from lexer import tokenize, tokenize_string` so you can test it here. + +Don't forget to turn on **autoreload** so the notebook picks up your +edits without needing a kernel restart. +``` diff --git a/notebooks/tps/explang2/.teacher/eval.py b/notebooks/tps/explang2/.teacher/eval.py new file mode 100644 index 0000000..97d50b4 --- /dev/null +++ b/notebooks/tps/explang2/.teacher/eval.py @@ -0,0 +1,30 @@ +""" +Evaluator for the AST produced by parser.parse(). + +An AST node is either: +- an int (a leaf) +- a tuple (op, left, right) where op is one of "+", "-", "*", "/" + and left, right are themselves AST nodes + +### Example + + >>> from parser import parse + >>> eval(parse("1 + 2 * 3".split())) + 7 + >>> eval(parse("( 1 + 2 ) * 3".split())) + 9 +""" + +OPERATORS = { + "+": lambda a, b: a + b, + "-": lambda a, b: a - b, + "*": lambda a, b: a * b, + "/": lambda a, b: a / b, +} + + +def eval(ast): + if isinstance(ast, int): + return ast + op, left, right = ast + return OPERATORS[op](eval(left), eval(right)) diff --git a/notebooks/tps/explang2/.teacher/lexer.py b/notebooks/tps/explang2/.teacher/lexer.py new file mode 100644 index 0000000..7d0d464 --- /dev/null +++ b/notebooks/tps/explang2/.teacher/lexer.py @@ -0,0 +1,63 @@ +""" +Our lexer. + +It takes a file-like object (anything iterable that yields lines, e.g. +an io.StringIO or an open file) and returns a generator of tokens, +compatible with what parser.parse() expects: strings like +"12", "+", "-", "*", "/", "(", ")". + +### Example + + >>> import io + >>> list(tokenize(io.StringIO("1 + 2 * 3"))) + ['1', '+', '2', '*', '3'] + + >>> list(tokenize(io.StringIO("(1 + 2) * 30"))) + ['(', '1', '+', '2', ')', '*', '30'] + + >>> tokenize_string("1 + 2 * 3") + ['1', '+', '2', '*', '3'] +""" + +import io + + +def tokenize(file): + # iterate over the file (which yields lines) and then over each + # line's characters; faster than calling .read(1) in a loop + def chars(): + for line in file: + yield from line + + # digits of the number currently being read + digits = "" + + for c in chars(): + if c.isdigit(): + # accumulate; we don't know yet if the number is over + digits += c + continue + + # here the current character is not a digit + # so if we had a number in progress, it is now complete + if digits: + yield digits + digits = "" + + if c.isspace(): + continue + + if c in "+-*/()": + yield c + continue + + raise SyntaxError(f"unexpected character: {c!r}") + + # don't forget a number left in progress at end of file + if digits: + yield digits + + +def tokenize_string(string): + # convenience wrapper for quick tests / interactive use + return list(tokenize(io.StringIO(string))) diff --git a/notebooks/tps/explang2/.teacher/media b/notebooks/tps/explang2/.teacher/media new file mode 120000 index 0000000..d803adf --- /dev/null +++ b/notebooks/tps/explang2/.teacher/media @@ -0,0 +1 @@ +../media/ \ No newline at end of file diff --git a/notebooks/tps/explang2/.teacher/parser.py b/notebooks/tps/explang2/.teacher/parser.py new file mode 100644 index 0000000..f974bc9 --- /dev/null +++ b/notebooks/tps/explang2/.teacher/parser.py @@ -0,0 +1,89 @@ +""" +Our top-down parser. + +A small illustration of how parentheses affect evaluation order. + +Note the trick behind this style of writing: the "lower" you are in the +call stack, the higher your precedence! + +### Examples + + >>> parse("1 + 2 * 3".split()) + ('+', 1, ('*', 2, 3)) + + >>> parse("( 1 + 2 ) * 3".split()) + ('*', ('+', 1, 2), 3) +""" + + +def parse(tokens): + # here we unpack the result of expr() + # all the helper functions have the shape: tokens -> (ast, remaining_tokens) + # if we didn't consume everything this will blow up... but for an + # example like this, we don't care... + ast, rest = expr(tokens) + assert rest == [] + return ast + + +## +# expr := term (("+"|"-") term)* +## + +def expr(tokens): + left, rest = term(tokens) # the left-hand term + return expr_tail(left, rest) + + +# if we find a + or a - we parse the right-hand side +def expr_tail(left, tokens): + if tokens and tokens[0] in ("+", "-"): + op, *rest = tokens + right, rest = term(rest) + return expr_tail((op, left, right), rest) + # otherwise it's a noop + return left, tokens + + +## +# term := factor (("*"|"/") factor)* +## + +def term(tokens): + left, rest = factor(tokens) # the left-hand term + return term_tail(left, rest) + + +# same idea as above, with * and / this time +def term_tail(left, tokens): + if tokens and tokens[0] in ("*", "/"): + op, *rest = tokens + right, rest = factor(rest) + return term_tail((op, left, right), rest) + return left, tokens + + +## +# factor := int | "(" expr ")" +## + +def factor(tokens): + if not tokens: + raise SyntaxError("missing token") + + head, *rest = tokens + + # for an integer, return its value + if head.lstrip("-").isdigit(): + return int(head), rest + + # parentheses: first match the opening one + if head == "(": + # then any expression + e, rest = expr(rest) + # we should find a closing parenthesis, otherwise we blow up + if rest and rest[0] == ")": + return e, rest[1:] + raise SyntaxError("expected ')'") + + raise SyntaxError(f"unexpected or missing token: {tokens!r}") diff --git a/notebooks/tps/explang2/README-explang2-nb.md b/notebooks/tps/explang2/README-explang2-nb.md new file mode 100644 index 0000000..d0f3f75 --- /dev/null +++ b/notebooks/tps/explang2/README-explang2-nb.md @@ -0,0 +1,305 @@ +--- +authors: [Aurélien Noce, Thierry Parmentelat] +jupytext: + encoding: '# -*- coding: utf-8 -*-' + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +language_info: + name: python + nbconvert_exporter: python + pygments_lexer: ipython3 +short_title: full expression lang +title: 'a small expression language: lexer, parser, eval' +--- + +Licence CC BY-NC-ND, Thierry Parmentelat + ++++ + +```{admonition} about this TP +this is a sequel to the `explang` TP; there, we only wrote the +**evaluator**, using classes, starting from an AST that was already +built for us. + +here we tackle the **whole pipeline**, from a plain string down to a +value: + +* **lexer**: turn a string of source code into a stream of tokens +* **parser**: turn that stream of tokens into an AST (here, plain tuples) +* **eval**: compute the value of that AST + +and we do it with **plain functions** rather than classes; one day we +may merge the two exercises and revisit `eval` with an OOP approach on +top of this pipeline, but for now let's take it one step at a time. +``` + ++++ + +## the pipeline + +we're building a tiny calculator that only knows about integers and the +4 operators `+ - * /`, with parentheses for grouping. + +three stages, three files: + +| stage | file | signature | input | output | +|-------|-------------|--------------------|---------------------|---------------------------| +| lex | `lexer.py` | `tokenize(file)` | a file-like object | a generator of tokens (strings) | +| parse | `parser.py` | `parse(tokens)` | a list of tokens | an AST | +| eval | `eval.py` | `eval(ast)` | an AST | a number | + +an AST node is either + +* an `int` (a leaf), or +* a 3-tuple `(op, left, right)` where `op` is one of `"+" "-" "*" "/"` + and `left`, `right` are themselves AST nodes + +for example the expression `1 + 2 * 3` gets tokenized into + +```python +['1', '+', '2', '*', '3'] +``` + +then parsed into + +```python +('+', 1, ('*', 2, 3)) +``` + +and finally evaluates to `7` + ++++ + +## the lexer + +* **works on**: generators, string methods +* **the input**: any file-like object (an open file, or an `io.StringIO`) + that contains a simple arithmetic expression, e.g. + ``` + (1 + 2) * 30 + ``` +* **todo**: write a generator function + ```python + def tokenize(file): + ... + ``` + that reads through `file` and `yield`s the tokens one at a time, as + strings: + * a run of digits becomes one token, e.g. `"30"` + * each one of `+ - * / ( )` is its own token + * whitespace (including newlines) is simply skipped + +* **tip**: don't call `file.read(1)` in a loop (that's slow); instead + **iterate** over `file` - which naturally yields lines - and then + iterate over the characters of each line + +* **bonus**: also write a small convenience helper + ```python + def tokenize_string(string): + ... + ``` + that wraps `string` in an `io.StringIO` and returns the list of + tokens directly - handy for quick tests + +```{code-cell} ipython3 +def tokenize(file): + ... + +def tokenize_string(string): + ... +``` + +and then you can check your code with + +```{code-cell} ipython3 +:tags: [raises-exception] + +tokenize_string("1 + 2 * 3") +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert tokenize_string("1 + 2 * 3") == ['1', '+', '2', '*', '3'] +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert tokenize_string("(1 + 2) * 30") == ['(', '1', '+', '2', ')', '*', '30'] +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# whitespace, including newlines, is not significant +assert tokenize_string(" 12\n+\n 7 ") == ['12', '+', '7'] +``` + +## the parser + +* **works on**: recursive-descent parsing, tuples + +now that we can turn a string into a stream of tokens, we need to turn +that stream into an AST. + +we use a classic **top-down (recursive-descent)** parser, with one +function per grammar rule; the grammar we implement is: + +``` +expr := term (("+"|"-") term)* +term := factor (("*"|"/") factor)* +factor := int | "(" expr ")" +``` + +* **todo**: write + ```python + def parse(tokens): + ... + ``` + that takes the **list** of tokens produced by the lexer, and returns + the AST + + you will probably want to write it as a set of mutually recursive + helper functions, all shaped like `tokens -> (ast, remaining_tokens)`: + + * `expr(tokens)` + * `term(tokens)` + * `factor(tokens)` + + `parse` itself just calls `expr` and makes sure there are no tokens + left over + +````{admonition} the trick + +the traditional way to write this code is to have a 'cascade' of functions calling one another, as illustrated below (go full-width if that helps) + +```{image} media/parse-stack-add-first.excalidraw.svg +``` + +with another input we'd see this instead: + +```{image} media/parse-stack-mul-first.excalidraw.svg +``` + +the "lower" a rule sits in the call stack, the higher its precedence; +that's why `factor` (which handles parentheses) sits below `term` +(which handles `*` `/`), which itself sits below `expr` (which handles +`+` `-`) + +```` + +And now it's your turn: + +```{code-cell} ipython3 +def parse(tokens): + ... +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +parse(tokenize_string("1 + 2 * 3")) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert parse(tokenize_string("1 + 2 * 3")) == ('+', 1, ('*', 2, 3)) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# parentheses change the shape of the tree, not just the value +assert parse(tokenize_string("(1 + 2) * 3")) == ('*', ('+', 1, 2), 3) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +# left-associativity: a - b - c is (a - b) - c, not a - (b - c) +assert parse(tokenize_string("10 - 2 - 3")) == ('-', ('-', 10, 2), 3) +``` + +## eval + +* **works on**: recursion, dict-as-a-switch + +* **todo**: write + ```python + def eval(ast): + ... + ``` + that computes the value described by `ast` + +```{code-cell} ipython3 +def eval(ast): + ... +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("1 + 2 * 3"))) == 7 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("(1 + 2) * 3"))) == 9 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("10 - 2 - 3"))) == 5 +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert eval(parse(tokenize_string("(30 + 40 + 50) * (20 - 15)"))) == 600 +``` + +## putting it all together + +now that the 3 stages are in place, you can write a one-liner that goes +straight from source to value: + +```{code-cell} ipython3 +def run(string): + return eval(parse(tokenize_string(string))) +``` + +```{code-cell} ipython3 +:tags: [raises-exception] + +assert run("2 * (3 + 4) - 5") == 9 +``` + +## going further (optional) + +a few ways you could extend this toy language, if you want to keep going: + +* support **unary minus**, e.g. `-3 + 4` or `-(1 + 2)` +* support **floats**, not just integers +* raise a proper, informative exception (instead of an obscure crash) + when the input is malformed, e.g. `"1 +"` or `"(1 + 2"` +* replace the **list** of tokens with the **generator** returned by + `tokenize` directly - does `parse` still work if it can only look one + token ahead, and can't index or slice into it? + +```{admonition} modalities +Once you're happy with your code, put it in `lexer.py`, `parser.py` and +`eval.py`, and import it from the notebook with e.g. +`from lexer import tokenize, tokenize_string` so you can test it here. + +Don't forget to turn on **autoreload** so the notebook picks up your +edits without needing a kernel restart. +``` diff --git a/notebooks/tps/explang2/eval.py b/notebooks/tps/explang2/eval.py new file mode 120000 index 0000000..2058940 --- /dev/null +++ b/notebooks/tps/explang2/eval.py @@ -0,0 +1 @@ +.teacher/eval.py \ No newline at end of file diff --git a/notebooks/tps/explang2/lexer.py b/notebooks/tps/explang2/lexer.py new file mode 120000 index 0000000..965c4a0 --- /dev/null +++ b/notebooks/tps/explang2/lexer.py @@ -0,0 +1 @@ +.teacher/lexer.py \ No newline at end of file diff --git a/notebooks/tps/explang2/media/parse-stack-add-first.excalidraw.svg b/notebooks/tps/explang2/media/parse-stack-add-first.excalidraw.svg new file mode 100644 index 0000000..594a2ea --- /dev/null +++ b/notebooks/tps/explang2/media/parse-stack-add-first.excalidraw.svg @@ -0,0 +1,101 @@ +eyJ2ZXJzaW9uIjogIjEiLCAiZW5jb2RpbmciOiAiYnN0cmluZyIsICJjb21wcmVzc2VkIjogdHJ1ZSwgImVuY29kZWQiOiAieNrtXely4ki6fVx1MDAxNaJuxPT0TOHOfemJ+4PF7Da7WaYmXGJcdTAwMDFiXHUwMDE1XHUwMDEyi8DAREfcX/N/Ju5cdTAwMDPc/cH6SW5cblfZUF2Q8nS1XFzlUlU4woAsUsqjc/LLPN+Xf33j7ubmm1x1MDAxZiNvzG3PsMb9pXH/5m3kzcZcXK7Gjq0+QOrVylkve4ejRq47X/34w1x1MDAwZsOxO1p3r3rO7Ie5sZyZtmtahvvDwHLc+c5cdTAwMWQ5dtTcOqvow+/eXHRNy/SOWqmT/Pmvb8Z972S4Z/Zqu9nGpNV9XHUwMDFld1G6XHUwMDE0X0W9g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RXHUwMDBmu8b/kqJcdTAwMTC/XG5Z6UNZXFwgKVFCo5UkjKRcdTAwMWFBMYpe3Fx1MDAxY4O/bHPMhPY2tyY1sZOoNmKp/CzVXHUwMDEwt1x1MDAxNzlcdOPPMm66WOPo6NOvb9xEJMJcdTAwMWVKtaSEgFx1MDAxYTkxSkiwXHUwMDA2vrtiekBKdWzV2sNcdTAwMDSLllLZjX12f2hMSchKusQhijFcdTAwMTKS6Vx1MDAxM4eYXHUwMDAwXlxyLChevLJcdTAwMTX+sitbtapm9i413myT+Uyhs1x1MDAxZVx1MDAxNGrxW/NcIi2Rw7Tvr6ali2uvR59+fbSEJeBcdTAwMThcdTAwMTDhXHUwMDAzpczbyFxikmDzdVx1MDAwNqlhXHUwMDBmRHPzVbzWs93E6lYmeme3o1wiXHUwMDA0fJKWXGL4yEXy7dLSYU9cdTAwMWVvjlTvI+dQYo6I+Fx1MDAwMmpcdTAwMTbgL71mwaplxsu76LyZr1x1MDAxYvX7XHUwMDExXHUwMDAxq32ncZGZKFx1MDAxNJ+DmS46844+/fqYySu7LInUb5hcblx1MDAwNWSSc1x1MDAxOSwx7W/K6ya+XHUwMDFlyfmYXHUwMDE0bkS9OZG78tlZ8UOI+UtiYuBKhOOlh4VnTlU/YP3+UdCL9NRcdTAwMGb5MsyY+CswY7rzVouD6rgho+1RXHUwMDFjSaeVcPdcdTAwMTfZiX2eKaaLpfaOPv1cbtmJQco48zFuol7JYkBcdTAwMTBcdTAwMGaUnlJjuVx1MDAxYSRirM9Gm9lweTdGODY4R0/szCRTSE9PPlx0ICXyNrnTh+9CXHUwMDAxXHUwMDAzXHTKvozyiviLLa/oXbcxn1dddeWH52y4XHUwMDFj9983XHUwMDFiPfSeeu2ac09A37+8cfrmtW10rZObsFx1MDAxOZv38U9cdTAwMTDM4PDvzU9cdTAwMGZIM1x1MDAwZk/zTz/9P+gqXHReIn0= +Tracing parse("1 + 2 * 3".split()) — the call stack, snapshot by snapshot +explang2/.teacher/parser.py — tokens are shown as the remaining slice of the expression, e.g. "+ 2 * 3" +① call parse(tokens) + +parse +1 + 2 * 3 + +② descend intofactor for '1' + +parse +1 + 2 * 3 + +expr +1 + 2 * 3 + +term +1 + 2 * 3 + +factor +1 + 2 * 3 + +③ term→1; expr_tailsees '+', calls term + +parse +1 + 2 * 3 + +expr +1 + 2 * 3 + +expr_tail +left = 1tokens: + 2 * 3 + +term +2 * 3 + +④ descend intofactor for '2' + +parse +1 + 2 * 3 + +expr +1 + 2 * 3 + +expr_tail +left = 1tokens: + 2 * 3 + +term +2 * 3 + +factor +2 * 3 + +⑤ term_tail sees '*'MAX DEPTH: 6 frames + +parse +1 + 2 * 3 + +expr +1 + 2 * 3 + +expr_tail +left = 1tokens: + 2 * 3 + +term +2 * 3 + +term_tail +left = 2tokens: * 3 + +factor +3 + +⑥ unwind: factor→3,term_tail & term done;expr_tail builds '+' + +parse +1 + 2 * 3 + +expr +1 + 2 * 3 + +expr_tail +left = 1right = ('*', 2, 3) + +⑦ expr done;parse returns the AST + +parse +→ ('+', 1, ('*', 2, 3)) +functions: + +parse + +expr + +term + +factor + +expr_tail + +term_tail \ No newline at end of file diff --git a/notebooks/tps/explang2/media/parse-stack-mul-first.excalidraw.svg b/notebooks/tps/explang2/media/parse-stack-mul-first.excalidraw.svg new file mode 100644 index 0000000..7dfd31f --- /dev/null +++ b/notebooks/tps/explang2/media/parse-stack-mul-first.excalidraw.svg @@ -0,0 +1,99 @@ +eyJ2ZXJzaW9uIjogIjEiLCAiZW5jb2RpbmciOiAiYnN0cmluZyIsICJjb21wcmVzc2VkIjogdHJ1ZSwgImVuY29kZWQiOiAieNrtXdly20iW/Vx1MDAxNYbnwV3dRVXuS3XMg7iv4ipxaXcoSFx1MDAwMiTBXHUwMDA1JEFw7aiIfpr3mZhcdTAwMGaY/cP6SyZByVx1MDAxMukyiVQtkC3DXHUwMDBlO0RcdTAwMTBcdTAwMDJcdTAwMTLIk+fkzTx582/v3N3cfPdj5J257XUmluF0Nu++j7xbm87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MDEy01x1MDAxMC1QYjhcdTAwMWTkm52W3SlN3ebs1JJ7MihO0GeJiYErXHUwMDEx9pZcdTAwMWXnnSGknDDgn+vVS1x1MDAxNFxugu4tnTVm4q/AmCnuMkUjV1/cX8ezXHUwMDAzY1x1MDAxYdvzkVx1MDAxObtIT+y3XHUwMDE5Y1x1MDAwMj3VNZLn6On526+PniiFQFx1MDAxMZTwpSeMMFF9J1x1MDAxOezSrHLbvckvi/tYs9SqRnugylx1MDAxYePVOXpiZ4aYQno6XuFO+GFcdTAwMDWpbzSHXGLhkkFcdTAwMTJ4MPea9HRyfz168p67M5/XXFz15IdmNnAs47HY6KH21GfXnHtcdTAwMDL6+LE4M8yk3elOTl7C2jI3sc/wS//w591PXHUwMDBmSDNcdTAwMGaN+aef/lx1MDAxZsgoXT8ifQ== + +Tracing parse("1 * 2 + 3".split()) — the call stack, snapshot by snapshot +explang2/.teacher/parser.py — tokens are shown as the remaining slice of the expression, e.g. "+ 3" +① call parse(tokens) + +parse +1 * 2 + 3 + +② descend intofactor for '1' + +parse +1 * 2 + 3 + +expr +1 * 2 + 3 + +term +1 * 2 + 3 + +factor +1 * 2 + 3 + +③ term_tail sees '*'MAX DEPTH: 5 frames + +parse +1 * 2 + 3 + +expr +1 * 2 + 3 + +term +1 * 2 + 3 + +term_tail +left = 1tokens: * 2 + 3 + +factor +2 + 3 + +④ term_tail builds '*';expr_tail sees '+',calls term + +parse +1 * 2 + 3 + +expr +1 * 2 + 3 + +expr_tail +left = ('*', 1, 2)tokens: + 3 + +term +3 + +⑤ descend for '3'DEPTH 5 again + +parse +1 * 2 + 3 + +expr +1 * 2 + 3 + +expr_tail +left = ('*', 1, 2)tokens: + 3 + +term +3 + +factor +3 + +⑥ term done; expr_tailbuilds the '+' node + +parse +1 * 2 + 3 + +expr +1 * 2 + 3 + +expr_tail +left = ('*', 1, 2)right = 3 + +⑦ expr done;parse returns the AST + +parse +→ ('+', ('*', 1, 2), 3) +functions: + +parse + +expr + +term + +factor + +expr_tail + +term_tail \ No newline at end of file diff --git a/notebooks/tps/explang2/parser.py b/notebooks/tps/explang2/parser.py new file mode 120000 index 0000000..01e8a36 --- /dev/null +++ b/notebooks/tps/explang2/parser.py @@ -0,0 +1 @@ +.teacher/parser.py \ No newline at end of file diff --git a/notebooks/tps/files-formats/.teacher/README-files-formats-corrige-nb.md b/notebooks/tps/files-formats/.teacher/README-files-formats-corrige-nb.md index 5be6965..46650cb 100644 --- a/notebooks/tps/files-formats/.teacher/README-files-formats-corrige-nb.md +++ b/notebooks/tps/files-formats/.teacher/README-files-formats-corrige-nb.md @@ -58,13 +58,13 @@ there are no difference - apart from this very cell - between the teacher and th ## les fichiers et l'OS -c'est quoi l'OS ? +c'est quoi l'OS ? - votre code ne cause **jamais directement** au harware - mais toujours au travers d'**abstractions exposées par l'OS** - parmi lesquelles, entre autres, la **notion de "fichier"** -```{image} operating_system_placement.png +```{image} media/operating_system_placement.png :align: right :width: 250px ``` @@ -81,14 +81,14 @@ c'est quoi l'OS ? ## lire un fichier simple -(le fichier `hello.txt` fait partie du zip) +(le fichier `data/hello.txt` fait partie du zip) +++ ### ouverture d'un fichier ```{code-cell} ipython3 -f = open("hello.txt") +f = open("data/hello.txt") ``` - que se passe-t-il ? @@ -98,7 +98,7 @@ f = open("hello.txt") ```python # ça marche aussi; quelle différence ? - f = open("hello.txt", encoding="utf-8") + f = open("data/hello.txt", encoding="utf-8") ``` +++ @@ -107,7 +107,7 @@ f = open("hello.txt") - analyser les types des différents objets ```python - type("hello.txt") + type("data/hello.txt") type(f) ``` - avancer étape par étape @@ -135,7 +135,7 @@ l'idiome à **toujours utiliser** pour lire un fichier texte ```python # TOUJOURS lire ou écrire un fichier avec un with ! -with open("hello.txt") as f: +with open("data/hello.txt") as f: for line in f: print(line, end="") ``` @@ -155,7 +155,7 @@ une autre approche consisterait à utiliser `line.rstrip()` qui enlève l'évent je dis éventuel car la dernière ligne ne contient pas toujours ce fameux *newline*; le monde est compliqué parfois... **exercice**: dans *vs-code*, allez enlever le dernier *newline* (mettez vous à la fin du fichier et faites un *Delete*) -et refaites tourner les 3 lignes ci-dessus; vous pouvez aussi regarder ce que donne `cat hello.txt` dans le terminal. +et refaites tourner les 3 lignes ci-dessus; vous pouvez aussi regarder ce que donne `cat data/hello.txt` dans le terminal. ```` +++ @@ -169,7 +169,7 @@ on va regarder dans les yeux deux fichiers texte: ### ASCII - installez l'extension vscode *Hex Editor* -- regarder le contenu de `hello.txt` avec vs-code +- regarder le contenu de `data/hello.txt` avec vs-code - utilisez *clic droit* -> *Open With* -> *Hex Editor* - comparez avec @@ -177,7 +177,7 @@ on va regarder dans les yeux deux fichiers texte: ### Unicode -faites pareil avec `bonjour.txt` +faites pareil avec `data/bonjour.txt` - que constatez-vous ? - voyez aussi @@ -186,7 +186,7 @@ faites pareil avec `bonjour.txt` ## un fichier binaire -faites pareil avec `tiny.pickle` +faites pareil avec `data/tiny.pickle` - ouvrez-le "normalement" (pour l'instant sans utiliser la librairie `pickle`) @@ -230,7 +230,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* à faire: - lisez la documentation du module `pickle` -- essayez de lire le fichier `tiny.pickle` +- essayez de lire le fichier `data/tiny.pickle` - inspectez les types des objets dans la donnée +++ @@ -240,7 +240,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* - partez de ce que vous venez de lire - modifiez certaines des données - sauvegardez-les dans un nouveau fichier - `tiny-changed.pickle` + `data/tiny-changed.pickle` - et relisez-le pour vérifier que "ça marche" +++ @@ -249,7 +249,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* à vous de jouer -- on va refaire pareil à partir de `tiny.json` +- on va refaire pareil à partir de `data/tiny.json` - lisez-la doc et écrivez le code qui lit ce fichier - modifiez la donnée lue, et sauvez-la - est-ce qu'on peut y mettre un ensemble ? ou un tuple ? @@ -259,13 +259,13 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* ### encore un: yaml - trouvez la doc de `PyYAML` -- lisez le fichier `tiny.yaml` +- lisez le fichier `data/tiny.yaml` - comment peut-on comparer avec JSON ? ```{admonition} et avec annotations ? en option: par défaut le format YAML permet de stocker - comme JSON - les types communs aux autres langages, -i.e. booléens, nombres, chaines, listes et dictionnaires; il est possible aussi de stocker des types un peu moins communs comme le tuple et l'ensemble, au prix d'une gymnastique déjà un peu oins facile d'accès; arrivez-vous à lire le fichier `small-annotated.yaml` ? +i.e. booléens, nombres, chaines, listes et dictionnaires; il est possible aussi de stocker des types un peu moins communs comme le tuple et l'ensemble, au prix d'une gymnastique déjà un peu oins facile d'accès; arrivez-vous à lire le fichier `data/small-annotated.yaml` ? ça peut demander une plangée dans SO (stackoverflow)... ``` @@ -278,7 +278,7 @@ on recommence (c'est optionnel, si vous savez déjà lire un csv avec pandas)... - lisez la documentation du module `csv` google `python module csv` -- essayez de lire le fichier `pokemon.csv` +- essayez de lire le fichier `data/pokemon.csv` - sauriez-vous créer une dataframe ? - version facile: avec `pd.read_csv()` - un peu moins simple: sans utiliser `pd.read_csv()` @@ -295,10 +295,10 @@ pour cela, 2 armes +++ -### exercice: lisez `notes.txt` +### exercice: lisez `data/notes.txt` * sans importer de module additionnel, -* lisez le fichier `notes.txt` +* lisez le fichier `data/notes.txt` * créez et affichez un dictionnaire *nom élève* → note diff --git a/notebooks/tps/files-formats/.teacher/data b/notebooks/tps/files-formats/.teacher/data new file mode 120000 index 0000000..4909e06 --- /dev/null +++ b/notebooks/tps/files-formats/.teacher/data @@ -0,0 +1 @@ +../data \ No newline at end of file diff --git a/notebooks/tps/files-formats/.teacher/media b/notebooks/tps/files-formats/.teacher/media new file mode 120000 index 0000000..f47d0bb --- /dev/null +++ b/notebooks/tps/files-formats/.teacher/media @@ -0,0 +1 @@ +../media \ No newline at end of file diff --git a/notebooks/tps/files-formats/ARTEFACTS b/notebooks/tps/files-formats/ARTEFACTS index 7e2efcc..8f30213 100644 --- a/notebooks/tps/files-formats/ARTEFACTS +++ b/notebooks/tps/files-formats/ARTEFACTS @@ -1,7 +1,2 @@ README-files-format-nb.md -hello.txt -bonjour.txt -tiny.pickle -tiny.json -tiny.yaml -notes.txt +data/ diff --git a/notebooks/tps/files-formats/ARTEFACTS-files-formats.zip b/notebooks/tps/files-formats/ARTEFACTS-files-formats.zip index 972121e..2eb47cc 100644 Binary files a/notebooks/tps/files-formats/ARTEFACTS-files-formats.zip and b/notebooks/tps/files-formats/ARTEFACTS-files-formats.zip differ diff --git a/notebooks/tps/files-formats/README-files-formats-nb.md b/notebooks/tps/files-formats/README-files-formats-nb.md index 13d7779..9c28b7f 100644 --- a/notebooks/tps/files-formats/README-files-formats-nb.md +++ b/notebooks/tps/files-formats/README-files-formats-nb.md @@ -50,13 +50,13 @@ Licence CC BY-NC-ND, Thierry Parmentelat & Aurélien Noce ## les fichiers et l'OS -c'est quoi l'OS ? +c'est quoi l'OS ? - votre code ne cause **jamais directement** au harware - mais toujours au travers d'**abstractions exposées par l'OS** - parmi lesquelles, entre autres, la **notion de "fichier"** -```{image} operating_system_placement.png +```{image} media/operating_system_placement.png :align: right :width: 250px ``` @@ -73,14 +73,14 @@ c'est quoi l'OS ? ## lire un fichier simple -(le fichier `hello.txt` fait partie du zip) +(le fichier `data/hello.txt` fait partie du zip) +++ ### ouverture d'un fichier ```{code-cell} ipython3 -f = open("hello.txt") +f = open("data/hello.txt") ``` - que se passe-t-il ? @@ -90,7 +90,7 @@ f = open("hello.txt") ```python # ça marche aussi; quelle différence ? - f = open("hello.txt", encoding="utf-8") + f = open("data/hello.txt", encoding="utf-8") ``` +++ @@ -99,7 +99,7 @@ f = open("hello.txt") - analyser les types des différents objets ```python - type("hello.txt") + type("data/hello.txt") type(f) ``` - avancer étape par étape @@ -127,7 +127,7 @@ l'idiome à **toujours utiliser** pour lire un fichier texte ```python # TOUJOURS lire ou écrire un fichier avec un with ! -with open("hello.txt") as f: +with open("data/hello.txt") as f: for line in f: print(line, end="") ``` @@ -147,7 +147,7 @@ une autre approche consisterait à utiliser `line.rstrip()` qui enlève l'évent je dis éventuel car la dernière ligne ne contient pas toujours ce fameux *newline*; le monde est compliqué parfois... **exercice**: dans *vs-code*, allez enlever le dernier *newline* (mettez vous à la fin du fichier et faites un *Delete*) -et refaites tourner les 3 lignes ci-dessus; vous pouvez aussi regarder ce que donne `cat hello.txt` dans le terminal. +et refaites tourner les 3 lignes ci-dessus; vous pouvez aussi regarder ce que donne `cat data/hello.txt` dans le terminal. ```` +++ @@ -161,7 +161,7 @@ on va regarder dans les yeux deux fichiers texte: ### ASCII - installez l'extension vscode *Hex Editor* -- regarder le contenu de `hello.txt` avec vs-code +- regarder le contenu de `data/hello.txt` avec vs-code - utilisez *clic droit* -> *Open With* -> *Hex Editor* - comparez avec @@ -169,7 +169,7 @@ on va regarder dans les yeux deux fichiers texte: ### Unicode -faites pareil avec `bonjour.txt` +faites pareil avec `data/bonjour.txt` - que constatez-vous ? - voyez aussi @@ -178,7 +178,7 @@ faites pareil avec `bonjour.txt` ## un fichier binaire -faites pareil avec `tiny.pickle` +faites pareil avec `data/tiny.pickle` - ouvrez-le "normalement" (pour l'instant sans utiliser la librairie `pickle`) @@ -222,7 +222,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* à faire: - lisez la documentation du module `pickle` -- essayez de lire le fichier `tiny.pickle` +- essayez de lire le fichier `data/tiny.pickle` - inspectez les types des objets dans la donnée +++ @@ -232,7 +232,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* - partez de ce que vous venez de lire - modifiez certaines des données - sauvegardez-les dans un nouveau fichier - `tiny-changed.pickle` + `data/tiny-changed.pickle` - et relisez-le pour vérifier que "ça marche" +++ @@ -241,7 +241,7 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* à vous de jouer -- on va refaire pareil à partir de `tiny.json` +- on va refaire pareil à partir de `data/tiny.json` - lisez-la doc et écrivez le code qui lit ce fichier - modifiez la donnée lue, et sauvez-la - est-ce qu'on peut y mettre un ensemble ? ou un tuple ? @@ -251,13 +251,13 @@ dans `open(name, 'rb')` le `r` est pour *read* et le `b` pour *binary* ### encore un: yaml - trouvez la doc de `PyYAML` -- lisez le fichier `tiny.yaml` +- lisez le fichier `data/tiny.yaml` - comment peut-on comparer avec JSON ? ```{admonition} et avec annotations ? en option: par défaut le format YAML permet de stocker - comme JSON - les types communs aux autres langages, -i.e. booléens, nombres, chaines, listes et dictionnaires; il est possible aussi de stocker des types un peu moins communs comme le tuple et l'ensemble, au prix d'une gymnastique déjà un peu oins facile d'accès; arrivez-vous à lire le fichier `small-annotated.yaml` ? +i.e. booléens, nombres, chaines, listes et dictionnaires; il est possible aussi de stocker des types un peu moins communs comme le tuple et l'ensemble, au prix d'une gymnastique déjà un peu oins facile d'accès; arrivez-vous à lire le fichier `data/small-annotated.yaml` ? ça peut demander une plangée dans SO (stackoverflow)... ``` @@ -270,7 +270,7 @@ on recommence (c'est optionnel, si vous savez déjà lire un csv avec pandas)... - lisez la documentation du module `csv` google `python module csv` -- essayez de lire le fichier `pokemon.csv` +- essayez de lire le fichier `data/pokemon.csv` - sauriez-vous créer une dataframe ? - version facile: avec `pd.read_csv()` - un peu moins simple: sans utiliser `pd.read_csv()` @@ -287,10 +287,10 @@ pour cela, 2 armes +++ -### exercice: lisez `notes.txt` +### exercice: lisez `data/notes.txt` * sans importer de module additionnel, -* lisez le fichier `notes.txt` +* lisez le fichier `data/notes.txt` * créez et affichez un dictionnaire *nom élève* → note diff --git a/notebooks/tps/files-formats/bonjour.txt b/notebooks/tps/files-formats/data/bonjour.txt similarity index 100% rename from notebooks/tps/files-formats/bonjour.txt rename to notebooks/tps/files-formats/data/bonjour.txt diff --git a/notebooks/tps/files-formats/hello.txt b/notebooks/tps/files-formats/data/hello.txt similarity index 100% rename from notebooks/tps/files-formats/hello.txt rename to notebooks/tps/files-formats/data/hello.txt diff --git a/notebooks/tps/files-formats/notes.txt b/notebooks/tps/files-formats/data/notes.txt similarity index 100% rename from notebooks/tps/files-formats/notes.txt rename to notebooks/tps/files-formats/data/notes.txt diff --git a/notebooks/tps/files-formats/pokemon.csv b/notebooks/tps/files-formats/data/pokemon.csv similarity index 100% rename from notebooks/tps/files-formats/pokemon.csv rename to notebooks/tps/files-formats/data/pokemon.csv diff --git a/notebooks/tps/files-formats/small-annotated.yaml b/notebooks/tps/files-formats/data/small-annotated.yaml similarity index 100% rename from notebooks/tps/files-formats/small-annotated.yaml rename to notebooks/tps/files-formats/data/small-annotated.yaml diff --git a/notebooks/tps/files-formats/operating_system_placement.png b/notebooks/tps/files-formats/media/operating_system_placement.png similarity index 100% rename from notebooks/tps/files-formats/operating_system_placement.png rename to notebooks/tps/files-formats/media/operating_system_placement.png diff --git a/notebooks/tps/files-formats/mess-with-json.py b/notebooks/tps/files-formats/mess-with-json.py index bfd8799..3a32b5f 100644 --- a/notebooks/tps/files-formats/mess-with-json.py +++ b/notebooks/tps/files-formats/mess-with-json.py @@ -16,7 +16,7 @@ def read_sample(filename): with open(filename, 'r') as feed: return json.loads(feed.read()) -SAMPLE = "tiny.json" +SAMPLE = "data/tiny.json" def main(): write_sample(SAMPLE) diff --git a/notebooks/tps/files-formats/mess-with-pickle.py b/notebooks/tps/files-formats/mess-with-pickle.py index 8b85a98..54badd2 100644 --- a/notebooks/tps/files-formats/mess-with-pickle.py +++ b/notebooks/tps/files-formats/mess-with-pickle.py @@ -16,7 +16,7 @@ def read_sample(filename): with open(filename, 'rb') as feed: return pickle.loads(feed.read()) -SAMPLE = "tiny.pickle" +SAMPLE = "data/tiny.pickle" def main(): write_sample(SAMPLE) diff --git a/notebooks/tps/files-formats/mess-with-yaml.py b/notebooks/tps/files-formats/mess-with-yaml.py index 857bda2..d3f4915 100644 --- a/notebooks/tps/files-formats/mess-with-yaml.py +++ b/notebooks/tps/files-formats/mess-with-yaml.py @@ -19,7 +19,7 @@ def read_sample(filename): with open(filename, 'r') as feed: return yaml.load(feed, yaml.FullLoader) -SAMPLE = "tiny.yaml" +SAMPLE = "data/tiny.yaml" def main(): write_sample(SAMPLE) diff --git a/notebooks/tps/game-of-life/.teacher/README-game-of-life-corrige-nb.md b/notebooks/tps/game-of-life/.teacher/README-game-of-life-corrige-nb.md new file mode 100644 index 0000000..d6ed972 --- /dev/null +++ b/notebooks/tps/game-of-life/.teacher/README-game-of-life-corrige-nb.md @@ -0,0 +1,59 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# the game of life + ++++ + +## the rules + ++++ + +Conway's game of life is a simulation that observes the following rules +each cell has a total of 8 neighbours; depending on the number of cells alive among these 8: + +- Any live cell with fewer than two live neighbours dies, as if by underpopulation. +- Any live cell with two or three live neighbours lives on to the next generation. +- Any live cell with more than three live neighbours dies, as if by overpopulation. +- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. + +See https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for more details + ++++ + +## your mission + ++++ + +your job is fairly simple, you are to write a program that implements these; it could look like the following screenshot - but you are free to go for any other tooling / format / etc.. + ++++ + +```{image} media/game-of-life.gif +:align: center +:width: 60% +``` + ++++ + +## notes + +in no particular order + +### wrapping + +in the original definition, the screen is supposed infinite, and so as a means to better approach this on a finite screen, our implementation has the right end of the screen wrapped to the right; and same of course in the vertical direction + +### pygame + +this demo is implemented with `pygame` but that's not at all mandatory diff --git a/notebooks/tps/game-of-life/.teacher/game_of_life.py b/notebooks/tps/game-of-life/.teacher/game_of_life.py new file mode 100644 index 0000000..1cd814b --- /dev/null +++ b/notebooks/tps/game-of-life/.teacher/game_of_life.py @@ -0,0 +1,220 @@ +""" +Conway's Game of Life — interactive Python implementation using pygame. + +Requirements: pygame (`pip install pygame`). +""" + +import sys +import random +import pygame +from pygame.locals import ( + QUIT, KEYDOWN, K_ESCAPE, K_SPACE, K_c, K_r, K_n, K_UP, K_DOWN, K_SLASH, MOUSEBUTTONDOWN +) + +### Configuration +# in pixels +CELL_SIZE = 15 +# number of cells horizontally, and vertically +GRID_WIDTH, GRID_HEIGHT = 80, 60 +# in pixels +WINDOW_WIDTH, WINDOW_HEIGHT = CELL_SIZE * GRID_WIDTH, CELL_SIZE * GRID_HEIGHT +# colors in rgb +BG_COLOR = (10, 10, 10) +GRID_COLOR = (40, 40, 40) +CELL_COLOR = (200, 200, 200) +# frames per second for pygame +FPS = 60 + +# density of random grid +DENSITY = 0.15 + + +def create_grid(randomize=False): + """ + Return a GRID_HEIGHT x GRID_WIDTH grid of 0/1. + """ + grid = [ + [0 for _ in range(GRID_WIDTH)] + for _ in range(GRID_HEIGHT) + ] + if randomize: + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + # or grid[y][x] = 1 if random.random() < DENSITY else 0 + grid[y][x] = (random.random() < DENSITY) + return grid + + +def draw_surface(surface, grid): + surface.fill(BG_COLOR) + # Draw cells + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + if grid[y][x]: + rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE) + pygame.draw.rect(surface, CELL_COLOR, rect) + # Draw grid lines (optional — comment out for performance) + for x in range(0, WINDOW_WIDTH+1, CELL_SIZE): + pygame.draw.line(surface, GRID_COLOR, (x, 0), (x, WINDOW_HEIGHT)) + for y in range(0, WINDOW_HEIGHT+1, CELL_SIZE): + pygame.draw.line(surface, GRID_COLOR, (0, y), (WINDOW_WIDTH, y)) + + +def count_neighbors(grid, x, y): + """Count living neighbors for cell (x, y) with wrapping edges.""" + total = 0 + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + if dx == 0 and dy == 0: + continue + nx = (x + dx) % GRID_WIDTH + ny = (y + dy) % GRID_HEIGHT + total += grid[ny][nx] + return total + + +def step(grid): + """Compute one generation and return the new grid.""" + new = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)] + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + neighbors = count_neighbors(grid, x, y) + if grid[y][x] == 1: + # Any live cell with two or three live neighbours survives. + new[y][x] = 1 if neighbors in (2, 3) else 0 + else: + # Dead cell with exactly three live neighbours becomes a live cell. + new[y][x] = 1 if neighbors == 3 else 0 + return new + + +def toggle_cell(grid, mouse_pos): + mx, my = mouse_pos + x = mx // CELL_SIZE + y = my // CELL_SIZE + if 0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT: + grid[y][x] = 0 if grid[y][x] else 1 + + +def randomize_grid(grid, density=DENSITY): + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + grid[y][x] = (random.random() < density) + + +def draw_help(surface, font): + help_text = [ + "Conway's Game of Life — Help", + "", + "Controls:", + "Space — start/pause simulation", + "N — advance one step (when paused)", + "C — clear grid", + "R — randomize grid", + "Up/Down — change simulation speed", + "Left Click — toggle cell", + "Right Click — randomize small area", + "? — show this help", + "Esc — exit", + "", + "Press any key to close this help screen...", + ] + + + overlay = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT)) + overlay.set_alpha(230) + overlay.fill((20, 20, 20)) + surface.blit(overlay, (0, 0)) + + + y_offset = 60 + for line in help_text: + text = font.render(line, True, (240, 240, 240)) + rect = text.get_rect(center=(WINDOW_WIDTH // 2, y_offset)) + surface.blit(text, rect) + y_offset += 25 + + pygame.display.flip() + + # Wait until any key is pressed + waiting = True + while waiting: + for event in pygame.event.get(): + if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): + pygame.quit() + sys.exit() + elif event.type == KEYDOWN or event.type == MOUSEBUTTONDOWN: + waiting = False + +def main(): + pygame.init() + screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) + pygame.display.set_caption("Conway's Game of Life") + clock = pygame.time.Clock() + + font = pygame.font.SysFont(None, 20) + + grid = create_grid(False) + running = False + sim_speed = 10 # steps per second when running + step_timer = 0.0 + randomize_grid(grid) + draw_help(screen, font) + + while True: + dt = clock.tick(FPS) / 1000.0 + step_timer += dt + + for event in pygame.event.get(): + if event.type == QUIT: + pygame.quit() + sys.exit() + if event.type == KEYDOWN: + if event.key == K_ESCAPE: + pygame.quit() + sys.exit() + elif event.key == K_SPACE: + running = not running + elif event.key == K_c: + grid = create_grid(False) + elif event.key == K_r: + randomize_grid(grid) + elif event.key == K_n: + grid = step(grid) + elif event.key == K_UP: + sim_speed = min(sim_speed + 1, 60) + elif event.key == K_DOWN: + sim_speed = max(sim_speed - 1, 1) + elif event.key == K_SLASH: # '?' key + draw_help(screen, font) + elif event.type == MOUSEBUTTONDOWN: + if event.button == 1: # left click + toggle_cell(grid, event.pos) + elif event.button == 3: # right click -> randomize small neighborhood + mx, my = event.pos + cx = mx // CELL_SIZE + cy = my // CELL_SIZE + for dy in range(-1, 2): + for dx in range(-1, 2): + nx = (cx + dx) % GRID_WIDTH + ny = (cy + dy) % GRID_HEIGHT + grid[ny][nx] = 1 if random.random() < 0.8 else 0 + + # Update simulation + if running and step_timer >= 1.0 / sim_speed: + grid = step(grid) + step_timer = 0.0 + + # Draw + draw_surface(screen, grid) + + # HUD + status = f"Running: {running} Speed: {sim_speed} steps/s Cells alive: {sum(sum(row) for row in grid)}" + text = font.render(status, True, (180, 180, 180)) + screen.blit(text, (5, 5)) + + pygame.display.flip() + + +if __name__ == '__main__': + main() diff --git a/notebooks/tps/game-of-life/.teacher/game_of_life_arcade.py b/notebooks/tps/game-of-life/.teacher/game_of_life_arcade.py new file mode 100644 index 0000000..bbd75e0 --- /dev/null +++ b/notebooks/tps/game-of-life/.teacher/game_of_life_arcade.py @@ -0,0 +1,169 @@ +""" +Conway's Game of Life implemented with the Arcade library. + +Requirements: + pip install arcade + +Arcade provides a clean and modern API for educational visualization. +""" + +import arcade +import random + +CELL_SIZE = 15 +GRID_WIDTH = 80 +GRID_HEIGHT = 60 +WINDOW_WIDTH = CELL_SIZE * GRID_WIDTH +WINDOW_HEIGHT = CELL_SIZE * GRID_HEIGHT +FPS = 60 + +class GameOfLife(arcade.Window): + def __init__(self): + super().__init__( + WINDOW_WIDTH, WINDOW_HEIGHT, + "Conway's Game of Life", + update_rate=1/FPS, + # resizable=False, + # antialiasing=False, + # high_dpi=False, # 👈 this disables automatic Retina scaling + ) + arcade.set_background_color(arcade.color.BLACK) + + # Force consistent viewport and window size - avoid resolution being changed by OS scaling + self.set_viewport(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT) + self.set_size(WINDOW_WIDTH, WINDOW_HEIGHT) + + self.grid = self.create_grid() + self.running = False + self.sim_speed = 10 # steps per second + self.accumulator = 0.0 + self.show_help = False + + def create_grid(self, randomize=False): + grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)] + if randomize: + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + grid[y][x] = 1 if random.random() < 0.2 else 0 + return grid + + def count_neighbors(self, x, y): + total = 0 + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + if dx == 0 and dy == 0: + continue + nx = (x + dx) % GRID_WIDTH + ny = (y + dy) % GRID_HEIGHT + total += self.grid[ny][nx] + return total + + def step(self): + new_grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)] + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + neighbors = self.count_neighbors(x, y) + if self.grid[y][x] == 1: + new_grid[y][x] = 1 if neighbors in (2, 3) else 0 + else: + new_grid[y][x] = 1 if neighbors == 3 else 0 + self.grid = new_grid + + def randomize_grid(self): + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + self.grid[y][x] = 1 if random.random() < 0.2 else 0 + + def on_draw(self): + arcade.start_render() + if self.show_help: + self.draw_help() + return + + for y in range(GRID_HEIGHT): + for x in range(GRID_WIDTH): + if self.grid[y][x]: + arcade.draw_rectangle_filled( + x * CELL_SIZE + CELL_SIZE / 2, + y * CELL_SIZE + CELL_SIZE / 2, + CELL_SIZE - 1, + CELL_SIZE - 1, + arcade.color.LIGHT_GRAY, + ) + + text = f"Running: {self.running} | Speed: {self.sim_speed} steps/s | Alive: {sum(sum(r) for r in self.grid)}" + arcade.draw_text(text, 10, 10, arcade.color.WHITE, 12) + + def draw_help(self): + arcade.draw_lrtb_rectangle_filled(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, (20, 20, 20, 230)) + lines = [ + "Conway's Game of Life — Help", + "", + "Space — start/pause simulation", + "N — advance one step (when paused)", + "C — clear grid", + "R — randomize grid", + "Up/Down — change simulation speed", + "Left Click — toggle cell", + "? — show this help", + "Esc — exit", + "", + "Press any key to close help...", + ] + y = WINDOW_HEIGHT - 80 + for line in lines: + arcade.draw_text(line, WINDOW_WIDTH / 2, y, arcade.color.WHITE, 16, anchor_x="center") + y -= 25 + + def on_update(self, delta_time): + if self.show_help: + return + + if self.running: + self.accumulator += delta_time + if self.accumulator >= 1 / self.sim_speed: + self.step() + self.accumulator = 0 + + def on_mouse_press(self, x, y, button, modifiers): + if self.show_help: + self.show_help = False + return + + gx = int(x // CELL_SIZE) + gy = int(y // CELL_SIZE) + if 0 <= gx < GRID_WIDTH and 0 <= gy < GRID_HEIGHT: + self.grid[gy][gx] = 0 if self.grid[gy][gx] else 1 + + def on_key_press(self, key, modifiers): + import arcade.key as k + + if self.show_help: + self.show_help = False + return + + if key == k.ESCAPE: + arcade.close_window() + elif key == k.SPACE: + self.running = not self.running + elif key == k.C: + self.grid = self.create_grid(False) + elif key == k.R: + self.randomize_grid() + elif key == k.N: + self.step() + elif key == k.UP: + self.sim_speed = min(self.sim_speed + 1, 60) + elif key == k.DOWN: + self.sim_speed = max(self.sim_speed - 1, 1) + elif key == k.SLASH or key == k.QUESTION: + self.show_help = True + + +def main(): + GameOfLife() + arcade.run() + + +if __name__ == "__main__": + main() diff --git a/notebooks/tps/game-of-life/.teacher/media b/notebooks/tps/game-of-life/.teacher/media new file mode 120000 index 0000000..d803adf --- /dev/null +++ b/notebooks/tps/game-of-life/.teacher/media @@ -0,0 +1 @@ +../media/ \ No newline at end of file diff --git a/notebooks/tps/game-of-life/README-game-of-life-nb.md b/notebooks/tps/game-of-life/README-game-of-life-nb.md new file mode 100644 index 0000000..2bce098 --- /dev/null +++ b/notebooks/tps/game-of-life/README-game-of-life-nb.md @@ -0,0 +1,57 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# the game of life + ++++ + +## the rules + ++++ + +Conway's game of life is a simulation that observes the following rules +each cell has a total of 8 neighbours; depending on the number of cells alive among these 8: + +- Any live cell with fewer than two live neighbours dies, as if by underpopulation. +- Any live cell with two or three live neighbours lives on to the next generation. +- Any live cell with more than three live neighbours dies, as if by overpopulation. +- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. + +See https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for more details + ++++ + +## your mission + ++++ + +your job is fairly simple, you are to write a program that implements these; it could look like the following screenshot - but you are free to go for any other tooling / format / etc.. + ++++ + +```{image} media/game-of-life.gif +:align: center +:width: 60% +``` + ++++ + +## notes + +in no particular order + +### wrapping + +in the original definition, the screen is supposed infinite, and so as a means to better approach this on a finite screen, our implementation has the right end of the screen wrapped to the right; and same of course in the vertical direction + +### pygame + +this demo is implemented with `pygame` but that's not at all mandatory diff --git a/notebooks/tps/game-of-life/media/game-of-life.gif b/notebooks/tps/game-of-life/media/game-of-life.gif new file mode 100644 index 0000000..1a533f2 Binary files /dev/null and b/notebooks/tps/game-of-life/media/game-of-life.gif differ diff --git a/notebooks/tps/graph-shortest-path/.teacher/README-graph-shortest-path-corrige-nb.md b/notebooks/tps/graph-shortest-path/.teacher/README-graph-shortest-path-corrige-nb.md index b300cf8..74c8751 100644 --- a/notebooks/tps/graph-shortest-path/.teacher/README-graph-shortest-path-corrige-nb.md +++ b/notebooks/tps/graph-shortest-path/.teacher/README-graph-shortest-path-corrige-nb.md @@ -453,7 +453,6 @@ reach = parse_graph("data/reach.csv") ```{code-cell} ipython3 :cell_style: center -:tags: [] # pour le visualiser: # installer graphviz avec @@ -656,12 +655,14 @@ en français : * on localise toutes les arêtes qui lient un noeud visité à un noeud non visité * pour chacune de ces arêtes $s ― (w) → d$, on calcule la somme $marque(s) + w$ + * on sélectionne l'arête $s_0 ― (w_0) → d_0$ pour laquelle cette somme est la plus petite * on marque $d_0$ comme visité avec $marque(s_0) + w_0$ * on arrête la boucle lorsque, soit * on atteint la destination (ici $d_0 == f$) on a trouvé la distance la plus courte, qui est la marque de $f$ + * ou bien s'il n'y a plus d'arête qui satisfasse le critère ça signifie que $f$ n'est pas atteignable depuis $a$ @@ -877,6 +878,7 @@ shortest_distance(G2, 'v1', 'v6') #### avec quelques graphes denses c'est l'occasion de parler un peu de l'instruction `assert`: + * sa fonction est **de ne rien faire** si l'expression associée est `True` * par contre si elle est fausse, une exception `AssertionError` est levée @@ -901,8 +903,6 @@ GD4 = parse_graph("data/dense-4.csv") assert shortest_distance(GD4, "1x1", "4x4") == 8 ``` -+++ {"tags": []} - ## exo #5 : `shortest_path` comment pourriez-vous adapter cet algorithme pour retourner **aussi** le chemin par lequel il faut passer ? @@ -1017,7 +1017,7 @@ Aerys,Tyrion,5 ... ``` -+++ {"cell_style": "split", "tags": []} ++++ {"cell_style": "split"} ````{admonition} pour voir le début d'un fichier :class: dropdown tip @@ -1027,10 +1027,12 @@ Aerys,Tyrion,5 ```bash head -5 data/thrones.csv ``` + * ou depuis IPython ou un notbook, on ajoute un `!` pour dire que c'est un travail pour le terminal ```python !head -5 data/thrones.csv ``` + * enfin on peut aussi écrire un petit bout de code en Python sauriez-vous le faire ? on verra bientôt `enumerate()` qui peut s'avérer utile pour faire ça @@ -1150,6 +1152,7 @@ l'algorithme de plus court chemin que nous avons écrit jusqu'ici a surtout des l'intérêt est d'écrire un code qui s'écrit et se lit facilement par contre, le lecteur affuté aura remarqué la chose suivante : + * à chaque itération de la boucle, on **recalcule de zéro** la frontière entre les sommets explorés et les autres * or, d'un tour de boucle à l'autre, cette frontière **change très peu**, et uniquement autour du noeud que l'on vient d'explorer @@ -1167,8 +1170,10 @@ pour n=4: **exercice**: pour un entier $n$, écrire une fonction `planar(n)` qui construit un graphe: + * qui contient $n^2$ sommets chacun étiqueté par un couple $(i, j), i\in[1..n], j\in[1..n]$ + * où chaque sommet est connecté à ses voisins immédiats * $(i, j) \xrightarrow{i} (i+1, j)$ si $i) -* `first_names.txt` + +* `data/first-names.txt` (dérivé de ) ce qu'il faut faire: * fabriquez un jeu de données aléatoires contenant 10000 personnes avec la contrainte qu'il y ait en sortie **unicité du nom x prénom** + * pour les dates de naissance tirez au sort une date entre le 01/01/2000 et le 31/12/2004 -* rangez cela dans le fichier `data-big.txt` +* rangez cela dans le fichier `data/sample-big.txt` * vous devez produire ce fichier dans un temps de l'ordre de 50-100ms ```{code-cell} ipython3 @@ -148,7 +151,7 @@ def random_date(start, end): BEG = Date(year=2000, month=1, day=1) END = Date(year=2004, month=12, day=31) -with open("last_names.txt") as last, open("first_names.txt") as first: +with open("data/last-names.txt") as last, open("data/first-names.txt") as first: LAST_NAMES = [x for line in last for x in line.strip().split()] FIRST_NAMES = [x for line in first for x in line.strip().split()] @@ -173,7 +176,7 @@ def generate_data(filename, how_many): ```{code-cell} ipython3 %%timeit -generate_data("data-big.txt", 10_000) +generate_data("data/sample-big.txt", 10_000) ``` ```{code-cell} ipython3 @@ -184,8 +187,10 @@ generate_data("data-big.txt", 10_000) * utilisez `%%timeit` pour mesurer le temps moyen qu'il faut pour chercher une personne dans la liste à partir de son nom et prénom + * on prévoit ue notre code aura besoin de faire cette recherche plusieurs millions de fois; comment pourrait-on faire pour accélérer cette recherche ? + * écrivez le code qui va bien et mesurez le gain de performance pour la recherche ```{code-cell} ipython3 @@ -193,7 +198,7 @@ generate_data("data-big.txt", 10_000) ``` ```{code-cell} ipython3 -L = parse_text("data-big.txt") +L = parse_text("data/sample-big.txt") ``` ```{code-cell} ipython3 diff --git a/notebooks/tps/indexing-structs/.teacher/data b/notebooks/tps/indexing-structs/.teacher/data new file mode 120000 index 0000000..4909e06 --- /dev/null +++ b/notebooks/tps/indexing-structs/.teacher/data @@ -0,0 +1 @@ +../data \ No newline at end of file diff --git a/notebooks/tps/indexing-structs/ARTEFACTS b/notebooks/tps/indexing-structs/ARTEFACTS index 937a7a4..e3a20cc 100644 --- a/notebooks/tps/indexing-structs/ARTEFACTS +++ b/notebooks/tps/indexing-structs/ARTEFACTS @@ -1,4 +1,2 @@ README-indexing-structs-nb.md -last_names.txt -first_names.txt -data-small.txt +data/ diff --git a/notebooks/tps/indexing-structs/ARTEFACTS-indexing-structs.zip b/notebooks/tps/indexing-structs/ARTEFACTS-indexing-structs.zip index e40c100..33503bd 100644 Binary files a/notebooks/tps/indexing-structs/ARTEFACTS-indexing-structs.zip and b/notebooks/tps/indexing-structs/ARTEFACTS-indexing-structs.zip differ diff --git a/notebooks/tps/indexing-structs/README-indexing-structs-nb.md b/notebooks/tps/indexing-structs/README-indexing-structs-nb.md index 31e88d2..911d73f 100644 --- a/notebooks/tps/indexing-structs/README-indexing-structs-nb.md +++ b/notebooks/tps/indexing-structs/README-indexing-structs-nb.md @@ -30,6 +30,7 @@ pour faire cet exercice, {download}`commencez par télécharger le zip<./ARTEFAC +++ dans ce petit exercice on va utiliser + * le dict pour gérer des enregistrements (en C on dirait des *structs*) * le dict pour indexer un grand nombre de données pour accélérer les recherches * et l'ensemble pour détecter les collisions et calculer le nombre d'entrées uniques dans une collection @@ -41,8 +42,8 @@ car pour ce genre de choses, dans la vraie vie, on pourrait aussi utiliser une d ## parsing -on veut pouvoir lire des fichiers texte qui ressemblent à celui-ci (`data-small.txt`) -```{literalinclude} data-small.txt +on veut pouvoir lire des fichiers texte qui ressemblent à celui-ci (`data/sample-small.txt`) +```{literalinclude} data/sample-small.txt ``` on suppose dans tout ce TP qu'il y a **unicité du (nom x prénom)** @@ -59,17 +60,19 @@ i.e. on n'est pas confronté au cas où deux personnes ont le même nom et le m à partir des deux fichiers joints: -* `last_names.txt` +* `data/last-names.txt` (dérivé de ) -* `first_names.txt` + +* `data/first-names.txt` (dérivé de ) ce qu'il faut faire: * fabriquez un jeu de données aléatoires contenant 10000 personnes avec la contrainte qu'il y ait en sortie **unicité du nom x prénom** + * pour les dates de naissance tirez au sort une date entre le 01/01/2000 et le 31/12/2004 -* rangez cela dans le fichier `data-big.txt` +* rangez cela dans le fichier `data/sample-big.txt` * vous devez produire ce fichier dans un temps de l'ordre de 50-100ms +++ @@ -78,8 +81,10 @@ ce qu'il faut faire: * utilisez `%%timeit` pour mesurer le temps moyen qu'il faut pour chercher une personne dans la liste à partir de son nom et prénom + * on prévoit ue notre code aura besoin de faire cette recherche plusieurs millions de fois; comment pourrait-on faire pour accélérer cette recherche ? + * écrivez le code qui va bien et mesurez le gain de performance pour la recherche +++ diff --git a/notebooks/tps/indexing-structs/first_names.txt b/notebooks/tps/indexing-structs/data/first-names.txt similarity index 100% rename from notebooks/tps/indexing-structs/first_names.txt rename to notebooks/tps/indexing-structs/data/first-names.txt diff --git a/notebooks/tps/indexing-structs/last_names.txt b/notebooks/tps/indexing-structs/data/last-names.txt similarity index 100% rename from notebooks/tps/indexing-structs/last_names.txt rename to notebooks/tps/indexing-structs/data/last-names.txt diff --git a/notebooks/tps/indexing-structs/data-small.txt b/notebooks/tps/indexing-structs/data/sample-small.txt similarity index 100% rename from notebooks/tps/indexing-structs/data-small.txt rename to notebooks/tps/indexing-structs/data/sample-small.txt diff --git a/notebooks/tps/metro/.teacher/README-metro-corrige-nb.md b/notebooks/tps/metro/.teacher/README-metro-corrige-nb.md index 4585857..bde0112 100644 --- a/notebooks/tps/metro/.teacher/README-metro-corrige-nb.md +++ b/notebooks/tps/metro/.teacher/README-metro-corrige-nb.md @@ -17,15 +17,13 @@ nbhosting: title: "m\xE9tro parisien" --- -+++ {"slideshow": {"slide_type": ""}, "tags": []} - # le réseau du métro parisien +++ Licence CC BY-NC-ND, Thierry Parmentelat -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ```{admonition} commencez par télécharger le zip {download}`vous aurez besoin du zip qui se trouve ici<./ARTEFACTS-metro.zip>` @@ -97,6 +95,7 @@ hops.head() 1. dessiner le réseau sur une carte 1. s'en servir de support pour visualiser deux algorithmes de parcours de graphe + * DFS : *depth-first-search* * BFS : *breadth-first-search* @@ -105,6 +104,7 @@ hops.head() ### comment on se propose de le faire 1. construire une structure de données pour + * ranger le graphe, * pouvoir le parcourir rapidement/efficacement 2. afficher la carte avec la librairie `folium` @@ -204,6 +204,7 @@ c'est ce que nous visualiserons à la fin de ce TP +++ on va représenter le graphe avec plusieurs classes d'objet : + * `Station` : contient les détails de l'arrêt ; ici on n'a gardé, parmi tous les détails exposés par la RATP, que les coordonnées latitude et longitude, mais dans un exemple plus réaliste on pourrait avoir ici plein de détails... * `Node` : modélise un noeud (sommet) dans le graphe, et ses noeuds voisins ; * `Graph` : contient l'ensemble des noeuds du réseau. @@ -601,12 +602,16 @@ class Graph: maintenant on devrait pouvoir construire le graphe ```{code-cell} ipython3 +:tags: [raises-exception] + metro = build_graph(stations, hops) print(f"notre graphe a {len(metro)} stations et {metro.nb_edges()} liens") ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # exercice: calculer le nombre de lignes nb_lines = ... # prune-line-begin @@ -730,6 +735,8 @@ def build_map(metro, show_labels=True): à ce stade si votre code pour `Node` et `Graph` est correct vous pouvez voir ici la carte du réseau avec la station Chatelet numérotée `0` ```{code-cell} ipython3 +:tags: [raises-exception] + # on met au moins un label pour voir l'effet metro.find_node_from_station_id(chatelet_station_id).label = '0' diff --git a/notebooks/tps/metro/.teacher/labelicon.py b/notebooks/tps/metro/.teacher/labelicon.py new file mode 120000 index 0000000..52d20ca --- /dev/null +++ b/notebooks/tps/metro/.teacher/labelicon.py @@ -0,0 +1 @@ +../labelicon.py \ No newline at end of file diff --git a/notebooks/tps/metro/.teacher/nuancier.py b/notebooks/tps/metro/.teacher/nuancier.py new file mode 120000 index 0000000..b25cf17 --- /dev/null +++ b/notebooks/tps/metro/.teacher/nuancier.py @@ -0,0 +1 @@ +../nuancier.py \ No newline at end of file diff --git a/notebooks/tps/metro/ARTEFACTS-metro.zip b/notebooks/tps/metro/ARTEFACTS-metro.zip index a5249ab..1b7759c 100644 Binary files a/notebooks/tps/metro/ARTEFACTS-metro.zip and b/notebooks/tps/metro/ARTEFACTS-metro.zip differ diff --git a/notebooks/tps/metro/README-metro-nb.md b/notebooks/tps/metro/README-metro-nb.md index 3776443..620bcf6 100644 --- a/notebooks/tps/metro/README-metro-nb.md +++ b/notebooks/tps/metro/README-metro-nb.md @@ -17,15 +17,13 @@ nbhosting: title: "m\xE9tro parisien" --- -+++ {"slideshow": {"slide_type": ""}, "tags": []} - # le réseau du métro parisien +++ Licence CC BY-NC-ND, Thierry Parmentelat -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ```{admonition} commencez par télécharger le zip {download}`vous aurez besoin du zip qui se trouve ici<./ARTEFACTS-metro.zip>` @@ -97,6 +95,7 @@ hops.head() 1. dessiner le réseau sur une carte 1. s'en servir de support pour visualiser deux algorithmes de parcours de graphe + * DFS : *depth-first-search* * BFS : *breadth-first-search* @@ -105,6 +104,7 @@ hops.head() ### comment on se propose de le faire 1. construire une structure de données pour + * ranger le graphe, * pouvoir le parcourir rapidement/efficacement 2. afficher la carte avec la librairie `folium` @@ -179,6 +179,7 @@ c'est ce que nous visualiserons à la fin de ce TP +++ on va représenter le graphe avec plusieurs classes d'objet : + * `Station` : contient les détails de l'arrêt ; ici on n'a gardé, parmi tous les détails exposés par la RATP, que les coordonnées latitude et longitude, mais dans un exemple plus réaliste on pourrait avoir ici plein de détails... * `Node` : modélise un noeud (sommet) dans le graphe, et ses noeuds voisins ; * `Graph` : contient l'ensemble des noeuds du réseau. @@ -508,12 +509,16 @@ class Graph: maintenant on devrait pouvoir construire le graphe ```{code-cell} ipython3 +:tags: [raises-exception] + metro = build_graph(stations, hops) print(f"notre graphe a {len(metro)} stations et {metro.nb_edges()} liens") ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # exercice: calculer le nombre de lignes nb_lines = ... @@ -633,6 +638,8 @@ def build_map(metro, show_labels=True): à ce stade si votre code pour `Node` et `Graph` est correct vous pouvez voir ici la carte du réseau avec la station Chatelet numérotée `0` ```{code-cell} ipython3 +:tags: [raises-exception] + # on met au moins un label pour voir l'effet metro.find_node_from_station_id(chatelet_station_id).label = '0' diff --git a/notebooks/tps/motus/.teacher/README-motus-corrige-nb.md b/notebooks/tps/motus/.teacher/README-motus-corrige-nb.md index 7e5149c..b13f454 100644 --- a/notebooks/tps/motus/.teacher/README-motus-corrige-nb.md +++ b/notebooks/tps/motus/.teacher/README-motus-corrige-nb.md @@ -16,8 +16,6 @@ nbhosting: title: 'TP: le jeu de motus' --- -+++ {"tags": []} - # le jeu de motus +++ @@ -49,6 +47,7 @@ voici un exemple de session, le mot à deviner était `CITRON` ``` ici on a + * d'abord essayé `CASTOR`; la 'correction' nous a appris que * le mot commence par un `C`, * qu'il contient un `O` en 5-ème position, @@ -61,6 +60,7 @@ ici on a * etc... les codes de couleur sont donc + * rouge: lettre bien placée * jaune: lettre mal placée * bleu (ou blanc, selon les supports): lettre absente @@ -116,8 +116,6 @@ show_example("addition", "addendum") ``` ```{code-cell} ipython3 -:tags: [] - # prune-cell from motus import show_example @@ -142,6 +140,7 @@ print(Path("data/ods6.url").open().read()) ## étape 1: l'ordi anime le jeu dans un premier temps: + * lisez le module `motus.py` * utilisez le pour écrire un fichier `main.py` qui implémente un jeu dans lequel l'ordi se contente de vous faire jouer: * il demande un nombre de lettres diff --git a/notebooks/tps/motus/.teacher/motus.py b/notebooks/tps/motus/.teacher/motus.py new file mode 120000 index 0000000..0a489a3 --- /dev/null +++ b/notebooks/tps/motus/.teacher/motus.py @@ -0,0 +1 @@ +../motus.py \ No newline at end of file diff --git a/notebooks/tps/motus/ARTEFACTS-motus.zip b/notebooks/tps/motus/ARTEFACTS-motus.zip index 06bd0bd..73c69cc 100644 Binary files a/notebooks/tps/motus/ARTEFACTS-motus.zip and b/notebooks/tps/motus/ARTEFACTS-motus.zip differ diff --git a/notebooks/tps/motus/README-motus-nb.md b/notebooks/tps/motus/README-motus-nb.md index 28e2bde..d0f61a5 100644 --- a/notebooks/tps/motus/README-motus-nb.md +++ b/notebooks/tps/motus/README-motus-nb.md @@ -16,8 +16,6 @@ nbhosting: title: 'TP: le jeu de motus' --- -+++ {"tags": []} - # le jeu de motus +++ @@ -49,6 +47,7 @@ voici un exemple de session, le mot à deviner était `CITRON` ``` ici on a + * d'abord essayé `CASTOR`; la 'correction' nous a appris que * le mot commence par un `C`, * qu'il contient un `O` en 5-ème position, @@ -61,6 +60,7 @@ ici on a * etc... les codes de couleur sont donc + * rouge: lettre bien placée * jaune: lettre mal placée * bleu (ou blanc, selon les supports): lettre absente @@ -123,6 +123,7 @@ print(Path("data/ods6.url").open().read()) ## étape 1: l'ordi anime le jeu dans un premier temps: + * lisez le module `motus.py` * utilisez le pour écrire un fichier `main.py` qui implémente un jeu dans lequel l'ordi se contente de vous faire jouer: * il demande un nombre de lettres diff --git a/notebooks/tps/pagerank-thrones/.teacher/README-pagerank-thrones-corrige-nb.md b/notebooks/tps/pagerank-thrones/.teacher/README-pagerank-thrones-corrige-nb.md index 3dc6d0e..8a7d9e7 100644 --- a/notebooks/tps/pagerank-thrones/.teacher/README-pagerank-thrones-corrige-nb.md +++ b/notebooks/tps/pagerank-thrones/.teacher/README-pagerank-thrones-corrige-nb.md @@ -115,7 +115,7 @@ here are the steps that we will take to this end : 1. running the simulation **several times** with different lifespans - ranging from several hops to a few thousands - 2. we can experimentally check if we indeed obtain consistent results, i.e. constant results for all characters -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ***** @@ -208,7 +208,6 @@ one way to think about this problem is to create a class `RandomWalker`: * from all the above, it is easy to write the simulation * result is a dictionary with vertices as key, and as value the number of steps spent in that vertex during the simulation - +++ @@ -227,6 +226,10 @@ this radically different approach requires more care, but can then be drasticall ### data acquisition +```{code-cell} ipython3 +import pandas as pd +``` + ```{code-cell} ipython3 URL = "https://raw.githubusercontent.com/pupimvictor/NetworkOfThrones/master/stormofswords.csv" ``` @@ -239,8 +242,6 @@ URL = "https://raw.githubusercontent.com/pupimvictor/NetworkOfThrones/master/sto ```{code-cell} ipython3 # prune-cell -import pandas as pd - df = pd.read_csv(URL) df.head() ``` @@ -437,6 +438,8 @@ class PageRankWalker: if you've followed our interface, you can use the following code as-is ```{code-cell} ipython3 +:tags: [raises-exception] + # create a walker object from the graph obtained above walker = PageRankWalker(G) @@ -444,6 +447,7 @@ walker = PageRankWalker(G) ```{code-cell} ipython3 :cell_style: split +:tags: [raises-exception] STEPS = 1000 @@ -451,16 +455,22 @@ frequencies = walker.walk(STEPS) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # the sum of all values should be STEPS raincheck = sum(frequencies.values()) raincheck == STEPS ``` ```{code-cell} ipython3 +:tags: [raises-exception] + raincheck, STEPS ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # dicts are not so good at sorting # let's use a list instead @@ -530,6 +540,8 @@ def monte_carlo(url_or_filename, steps, damping=0.85): ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # show top winners with a 1000-steps simu for _ in range(5): print(f"{40*'-'}") @@ -537,6 +549,8 @@ for _ in range(5): ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # same with a tenfold simulation for _ in range(5): print(f"{40*'-'}") @@ -572,6 +586,8 @@ from graphviz import Digraph ``` ```{code-cell} ipython3 +:tags: [raises-exception] + gv = Digraph('Characters of the Thrones', filename='thrones-graphviz') for source, weighted_dict in G.items(): @@ -581,19 +597,18 @@ for source, weighted_dict in G.items(): ```{code-cell} ipython3 :cell_style: split +:tags: [raises-exception] gv.attr(rankdir='TB', size='12') gv ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # save as svg # https://graphviz.readthedocs.io/en/stable/formats.html#formats gv.format = 'svg' gv.render() ``` - -```{code-cell} ipython3 - -``` diff --git a/notebooks/tps/pagerank-thrones/README-pagerank-thrones-nb.md b/notebooks/tps/pagerank-thrones/README-pagerank-thrones-nb.md index 695e9d9..b50a115 100644 --- a/notebooks/tps/pagerank-thrones/README-pagerank-thrones-nb.md +++ b/notebooks/tps/pagerank-thrones/README-pagerank-thrones-nb.md @@ -115,7 +115,7 @@ here are the steps that we will take to this end : 1. running the simulation **several times** with different lifespans - ranging from several hops to a few thousands - 2. we can experimentally check if we indeed obtain consistent results, i.e. constant results for all characters -+++ {"slideshow": {"slide_type": ""}, "tags": []} ++++ ***** @@ -226,6 +226,10 @@ this radically different approach requires more care, but can then be drasticall ### data acquisition +```{code-cell} ipython3 +import pandas as pd +``` + ```{code-cell} ipython3 URL = "https://raw.githubusercontent.com/pupimvictor/NetworkOfThrones/master/stormofswords.csv" ``` @@ -301,6 +305,8 @@ class PageRankWalker: if you've followed our interface, you can use the following code as-is ```{code-cell} ipython3 +:tags: [raises-exception] + # create a walker object from the graph obtained above walker = PageRankWalker(G) @@ -308,6 +314,7 @@ walker = PageRankWalker(G) ```{code-cell} ipython3 :cell_style: split +:tags: [raises-exception] STEPS = 1000 @@ -315,16 +322,22 @@ frequencies = walker.walk(STEPS) ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # the sum of all values should be STEPS raincheck = sum(frequencies.values()) raincheck == STEPS ``` ```{code-cell} ipython3 +:tags: [raises-exception] + raincheck, STEPS ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # dicts are not so good at sorting # let's use a list instead @@ -394,6 +407,8 @@ def monte_carlo(url_or_filename, steps, damping=0.85): ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # show top winners with a 1000-steps simu for _ in range(5): print(f"{40*'-'}") @@ -401,6 +416,8 @@ for _ in range(5): ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # same with a tenfold simulation for _ in range(5): print(f"{40*'-'}") @@ -436,6 +453,8 @@ from graphviz import Digraph ``` ```{code-cell} ipython3 +:tags: [raises-exception] + gv = Digraph('Characters of the Thrones', filename='thrones-graphviz') for source, weighted_dict in G.items(): @@ -445,19 +464,18 @@ for source, weighted_dict in G.items(): ```{code-cell} ipython3 :cell_style: split +:tags: [raises-exception] gv.attr(rankdir='TB', size='12') gv ``` ```{code-cell} ipython3 +:tags: [raises-exception] + # save as svg # https://graphviz.readthedocs.io/en/stable/formats.html#formats gv.format = 'svg' gv.render() ``` - -```{code-cell} ipython3 - -``` diff --git a/notebooks/tps/parse-people/.teacher/README-parse-people-corrige-nb.md b/notebooks/tps/parse-people/.teacher/README-parse-people-corrige-nb.md index 4e14e2a..15e844f 100644 --- a/notebooks/tps/parse-people/.teacher/README-parse-people-corrige-nb.md +++ b/notebooks/tps/parse-people/.teacher/README-parse-people-corrige-nb.md @@ -46,6 +46,7 @@ This activity is about parsing text files, and building structures using builtin fields are separated by any number (but at least one) of spaces/tabs, like e.g. in file `people-simple-03` ```{literalinclude} people-simple-03 ``` + * **todo**: write a function for parsing this format; it should return a list of 4-tuples ```python def parse(filename) -> list[tuple[str, str, str, str]]: @@ -66,7 +67,7 @@ def parse(filename): result.append((first, last, email, phone)) return result -L = parse("data-simple-03"); L +L = parse("data/people-simple-03.txt"); L ``` ```{code-cell} ipython3 @@ -83,7 +84,7 @@ def parse_bis(filename): result.append(line.strip().split()) return result -parse_bis("data-simple-03") +parse_bis("data/people-simple-03.txt") ``` ```{code-cell} ipython3 @@ -97,7 +98,7 @@ def parse_ter(filename): with open(filename, encoding="utf-8") as f: return [line.strip().split() for line in f] -parse_ter("data-simple-03") +parse_ter("data/people-simple-03.txt") ``` ````{admonition} discussion @@ -122,6 +123,7 @@ discuss the pros and cons of each approach def index(list_of_tuples): ``` that builds and returns that data structure + * write a function ```python def initial(list_of_tuples): @@ -280,11 +282,13 @@ dataframe(L) where the part between `[]` is **optional**, i.e there can be **0 or more** groupnames mentioned on each student line; like e.g. from `people-groups-10`: ```{literalinclude} people-groups-10 ``` + * **todo** duplicate and tweak the `parse` function, so as to write ```python def group_parse(filename): ``` so it now returns a 2-tuple with + * the list of tuples as before * a dictionary of sets * the keys here will be the **group names**, @@ -311,7 +315,7 @@ def group_parse(filename): groups_by_name[group].add(person) return persons, groups_by_name -G = group_parse("data-groups-10"); G +G = group_parse("data/people-groups-10.txt"); G ``` ```{code-cell} ipython3 @@ -324,7 +328,7 @@ def group_parse_bis(filename) -> tuple[ ]: return group_parse(filename) -group_parse_bis("data-groups-10") +group_parse_bis("data/people-groups-10.txt") ``` ## regexps (optional) @@ -339,6 +343,7 @@ group_parse_bis("data-groups-10") def check_values(L: list[tuple]) -> None: ``` that expects as an input the output of `parse`, and that outlines ill-formed input + * **note** on ASCII *vs* Unicode input: * in a first approximation, use patterns like `a-z` to check for letters; * how does this behave with respect to names with accents and cedillas @@ -367,16 +372,16 @@ def _check_values(L, re_n, re_e, re_p): ```{code-cell} ipython3 # first rough approx. -re_names = re.compile("^[-_a-zA-Z]+$") -re_email = re.compile("^[-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+$") +re_names = re.compile(r"^[-_a-zA-Z]+$") +re_email = re.compile(r"^[-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+$") # we need to escape the + because otherwise it means repetition -re_phone = re.compile("^(0|\+33)[0-9]{9}$") +re_phone = re.compile(r"^(0|\+33)[0-9]{9}$") def check_values(L: list) -> None: return _check_values(L, re_names, re_email, re_phone) -L120 = group_parse("data-groups-120")[0] +L120 = group_parse("data/people-groups-120.txt")[0] check_values(L120) ``` @@ -384,8 +389,8 @@ check_values(L120) # using \w is tempting, but it will allow for _ # and we dont want that... -re_names_bis = re.compile("^[-_\w]+$") -re_email_bis = re.compile("^[-\w0-9.]+@[-\w0-9.]+$") +re_names_bis = re.compile(r"^[-_\w]+$") +re_email_bis = re.compile(r"^[-\w0-9.]+@[-\w0-9.]+$") def check_values_bis(L: list) -> None: return _check_values(L, re_names_bis, re_email_bis, re_phone) diff --git a/notebooks/tps/parse-people/.teacher/data b/notebooks/tps/parse-people/.teacher/data new file mode 120000 index 0000000..4909e06 --- /dev/null +++ b/notebooks/tps/parse-people/.teacher/data @@ -0,0 +1 @@ +../data \ No newline at end of file diff --git a/notebooks/tps/parse-people/ARTEFACTS b/notebooks/tps/parse-people/ARTEFACTS index a4141a8..8c915e0 100644 --- a/notebooks/tps/parse-people/ARTEFACTS +++ b/notebooks/tps/parse-people/ARTEFACTS @@ -1,5 +1,2 @@ README-parse-people-nb.md -people-simple-03 -people-simple-10 -people-groups-10 -people-groups-120 +data/ \ No newline at end of file diff --git a/notebooks/tps/parse-people/ARTEFACTS-parse-people.zip b/notebooks/tps/parse-people/ARTEFACTS-parse-people.zip index 0911a4c..f692079 100644 Binary files a/notebooks/tps/parse-people/ARTEFACTS-parse-people.zip and b/notebooks/tps/parse-people/ARTEFACTS-parse-people.zip differ diff --git a/notebooks/tps/parse-people/README-parse-people-nb.md b/notebooks/tps/parse-people/README-parse-people-nb.md index c71c656..b8d42a6 100644 --- a/notebooks/tps/parse-people/README-parse-people-nb.md +++ b/notebooks/tps/parse-people/README-parse-people-nb.md @@ -46,6 +46,7 @@ This activity is about parsing text files, and building structures using builtin fields are separated by any number (but at least one) of spaces/tabs, like e.g. in file `people-simple-03` ```{literalinclude} people-simple-03 ``` + * **todo**: write a function for parsing this format; it should return a list of 4-tuples ```python def parse(filename) -> list[tuple[str, str, str, str]]: @@ -76,6 +77,7 @@ discuss the pros and cons of each approach def index(list_of_tuples): ``` that builds and returns that data structure + * write a function ```python def initial(list_of_tuples): @@ -106,11 +108,13 @@ discuss the pros and cons of each approach where the part between `[]` is **optional**, i.e there can be **0 or more** groupnames mentioned on each student line; like e.g. from `people-groups-10`: ```{literalinclude} people-groups-10 ``` + * **todo** duplicate and tweak the `parse` function, so as to write ```python def group_parse(filename): ``` so it now returns a 2-tuple with + * the list of tuples as before * a dictionary of sets * the keys here will be the **group names**, @@ -130,6 +134,7 @@ discuss the pros and cons of each approach def check_values(L: list[tuple]) -> None: ``` that expects as an input the output of `parse`, and that outlines ill-formed input + * **note** on ASCII *vs* Unicode input: * in a first approximation, use patterns like `a-z` to check for letters; * how does this behave with respect to names with accents and cedillas diff --git a/notebooks/tps/parse-people/people-groups-10 b/notebooks/tps/parse-people/data/people-groups-10.txt similarity index 100% rename from notebooks/tps/parse-people/people-groups-10 rename to notebooks/tps/parse-people/data/people-groups-10.txt diff --git a/notebooks/tps/parse-people/people-groups-120 b/notebooks/tps/parse-people/data/people-groups-120.txt similarity index 100% rename from notebooks/tps/parse-people/people-groups-120 rename to notebooks/tps/parse-people/data/people-groups-120.txt diff --git a/notebooks/tps/parse-people/people-simple-03 b/notebooks/tps/parse-people/data/people-simple-03.txt similarity index 100% rename from notebooks/tps/parse-people/people-simple-03 rename to notebooks/tps/parse-people/data/people-simple-03.txt diff --git a/notebooks/tps/parse-people/people-simple-10 b/notebooks/tps/parse-people/data/people-simple-10.txt similarity index 100% rename from notebooks/tps/parse-people/people-simple-10 rename to notebooks/tps/parse-people/data/people-simple-10.txt diff --git a/notebooks/tps/puzzle8/.teacher/README-puzzle8-corrige-nb.md b/notebooks/tps/puzzle8/.teacher/README-puzzle8-corrige-nb.md index 476606b..b196b2c 100644 --- a/notebooks/tps/puzzle8/.teacher/README-puzzle8-corrige-nb.md +++ b/notebooks/tps/puzzle8/.teacher/README-puzzle8-corrige-nb.md @@ -208,7 +208,7 @@ so, note that if you choose to use you own class: - and to make it **sortable**, you can go with implementing only `__lt__` (stands for *lower than*) which is enough to describe order among instances of your class (for a deeper discussion, see also ) - **note** however that in my solution, I did not even had to resort to that, thanks to `dataclass`, [more on this in this section below](label-dataclass-in-queue) + **note** however that in my solution, I did not even had to resort to that, thanks to `dataclass`, [more on this in this section below](#label-dataclass-in-queue) ````{admonition} which is the cheapest ? diff --git a/notebooks/tps/puzzle8/README-puzzle8-nb.md b/notebooks/tps/puzzle8/README-puzzle8-nb.md index 55302d5..aa4bc2a 100644 --- a/notebooks/tps/puzzle8/README-puzzle8-nb.md +++ b/notebooks/tps/puzzle8/README-puzzle8-nb.md @@ -200,7 +200,7 @@ so, note that if you choose to use you own class: - and to make it **sortable**, you can go with implementing only `__lt__` (stands for *lower than*) which is enough to describe order among instances of your class (for a deeper discussion, see also ) - **note** however that in my solution, I did not even had to resort to that, thanks to `dataclass`, [more on this in this section below](label-dataclass-in-queue) + **note** however that in my solution, I did not even had to resort to that, thanks to `dataclass`, [more on this in this section below](#label-dataclass-in-queue) ````{admonition} which is the cheapest ? diff --git a/notebooks/tps/queens/.teacher/README-queens-corrige-nb.md b/notebooks/tps/queens/.teacher/README-queens-corrige-nb.md index 3f10820..8603e6b 100644 --- a/notebooks/tps/queens/.teacher/README-queens-corrige-nb.md +++ b/notebooks/tps/queens/.teacher/README-queens-corrige-nb.md @@ -89,7 +89,7 @@ il y a toutefois une précaution à prendre si vous travaillez comme ceci en effet l'import d'un module est **caché** par Python, ce qui fait que par défaut, les changements que vous faites dans fichier `rooks_and_queens.py` ne sont **plus rechargés après le premier import** pour vous installer confortablement, voyez ce lien: -https://ue12-p24-intro.readthedocs.io/en/main/1-01-installations-nb.html#configuration-de-l-autoreload +https://intro.info-mines.paris/1-1-installations/#-configuration-de-lautoreload ```` +++ @@ -256,8 +256,6 @@ for p in queens(6): draw_position(p) ``` -+++ {"tags": []} - ## fin de la partie obligatoire jusqu'ici c'est plutôt facile - ou court en tous cas; pour info ma correction tient en diff --git a/notebooks/tps/queens/ARTEFACTS-queens.zip b/notebooks/tps/queens/ARTEFACTS-queens.zip index b420731..364e32a 100644 Binary files a/notebooks/tps/queens/ARTEFACTS-queens.zip and b/notebooks/tps/queens/ARTEFACTS-queens.zip differ diff --git a/notebooks/tps/queens/README-queens-nb.md b/notebooks/tps/queens/README-queens-nb.md index b8d45d3..2f0545b 100644 --- a/notebooks/tps/queens/README-queens-nb.md +++ b/notebooks/tps/queens/README-queens-nb.md @@ -89,7 +89,7 @@ il y a toutefois une précaution à prendre si vous travaillez comme ceci en effet l'import d'un module est **caché** par Python, ce qui fait que par défaut, les changements que vous faites dans fichier `rooks_and_queens.py` ne sont **plus rechargés après le premier import** pour vous installer confortablement, voyez ce lien: -https://ue12-p24-intro.readthedocs.io/en/main/1-01-installations-nb.html#configuration-de-l-autoreload +https://intro.info-mines.paris/1-1-installations/#-configuration-de-lautoreload ```` +++ @@ -248,8 +248,6 @@ for p in queens(6): draw_position(p) ``` -+++ {"tags": []} - ## fin de la partie obligatoire jusqu'ici c'est plutôt facile - ou court en tous cas; pour info ma correction tient en diff --git a/notebooks/tps/redis/.teacher/README-redis-corrige-nb.md b/notebooks/tps/redis/.teacher/README-redis-corrige-nb.md index 4a493ee..9de5117 100644 --- a/notebooks/tps/redis/.teacher/README-redis-corrige-nb.md +++ b/notebooks/tps/redis/.teacher/README-redis-corrige-nb.md @@ -16,6 +16,7 @@ language_info: # multi-joueur avec redis ```{admonition} ATTENTION +:class: danger l'installation de redis sur Windows est **complexe** l'installation par conda n'installe **que la librairie Python**, et pas le serveur @@ -33,6 +34,7 @@ on se propose de réaliser un petit jeu multi joueur, et pour cela nous aurons b traditionnel, ici pas de SQL ni de stockage sur le disque; il existe bien sûr [une librairie Python](https://redis.readthedocs.io/en/latest/) pour communiquer avec redis depuis Python + * [pygame](www.pygame.org), et plus accessoirement pour le graphisme et autres interactions avec le jeu (qu'on a déjà vu avec le snake) @@ -59,6 +61,7 @@ théorie le choix entre * faire tourner tout le jeu, c'est-à-dire les deux joueurs, dans un seul process; mais ça impose de jouer tous les deux sur le même ordi, pas glop du tout + * du coup ça n'est pas une solution en général, donc c'est beaucoup mieux que **chaque joueur lance son propre process**, qui pourront même du coup tourner sur des ordinateurs différents pourvu qu'on s'y prenne correctement @@ -135,6 +138,7 @@ voici aussi à tout hasard d'autres options, selon votre système d'exploitation `````{tab-set} ````{tab-item} Windows + * autre option: memurai dont l'installation se charge de créer un service microsoft ```` @@ -144,6 +148,7 @@ autre option: `brew install redis` ```` ````{tab-item} Linux + * redhat/fedora: autre option: `dnf install redis` * debain/ubuntu: `apt install redis` ```` @@ -226,16 +231,20 @@ quelques suggestions dans ce sens: * il va vous falloir créer une instance du serveur redis (un `redis.Redis()`) dans le programme principal + * et passer cette instance à la classe `Player` * de façon à ce qu'elle puisse tenir le serveur redis au courant de toutes ses modifications de position et/ou de couleur (le raccourci clavier `c` permet de changer de couleur du joueur) + * une fois que c'est fait, il convient que le programme principal interroge le serveur pour connaitre la position des autres joueurs, avant de rafraichir l'affichage + * pour faire cela, une voie possible serait d'écrire une classe `Others` (dans un fichier `others.py`) dont le travail est d'interroger le serveur pour connaitre la position des autres joueurs + * ce qui donnerait un flux de données dans le genre de ceci ```{image} media/dataflow.excalidraw.svg @@ -327,6 +336,7 @@ en effet il est ultra fréquent que les ordinateurs soient derrière un routeur :class: seealso plus de détails ici + * * le RFC: ``` diff --git a/notebooks/tps/redis/ARTEFACTS-redis.zip b/notebooks/tps/redis/ARTEFACTS-redis.zip index d7a0c25..a3df284 100644 Binary files a/notebooks/tps/redis/ARTEFACTS-redis.zip and b/notebooks/tps/redis/ARTEFACTS-redis.zip differ diff --git a/notebooks/tps/redis/README-redis-nb.md b/notebooks/tps/redis/README-redis-nb.md index fc667e8..9de5117 100644 --- a/notebooks/tps/redis/README-redis-nb.md +++ b/notebooks/tps/redis/README-redis-nb.md @@ -15,6 +15,16 @@ language_info: # multi-joueur avec redis +```{admonition} ATTENTION +:class: danger + +l'installation de redis sur Windows est **complexe** +l'installation par conda n'installe **que la librairie Python**, et pas le serveur +la doc officielle indique de passer par WSL, ce qui est .. carrément *overkill* + +à déconseiller... +``` + {download}`vous aurez besoin du zip qui se trouve ici<./ARTEFACTS-redis.zip>` on se propose de réaliser un petit jeu multi joueur, et pour cela nous aurons besoin de @@ -24,6 +34,7 @@ on se propose de réaliser un petit jeu multi joueur, et pour cela nous aurons b traditionnel, ici pas de SQL ni de stockage sur le disque; il existe bien sûr [une librairie Python](https://redis.readthedocs.io/en/latest/) pour communiquer avec redis depuis Python + * [pygame](www.pygame.org), et plus accessoirement pour le graphisme et autres interactions avec le jeu (qu'on a déjà vu avec le snake) @@ -50,6 +61,7 @@ théorie le choix entre * faire tourner tout le jeu, c'est-à-dire les deux joueurs, dans un seul process; mais ça impose de jouer tous les deux sur le même ordi, pas glop du tout + * du coup ça n'est pas une solution en général, donc c'est beaucoup mieux que **chaque joueur lance son propre process**, qui pourront même du coup tourner sur des ordinateurs différents pourvu qu'on s'y prenne correctement @@ -126,6 +138,7 @@ voici aussi à tout hasard d'autres options, selon votre système d'exploitation `````{tab-set} ````{tab-item} Windows + * autre option: memurai dont l'installation se charge de créer un service microsoft ```` @@ -135,6 +148,7 @@ autre option: `brew install redis` ```` ````{tab-item} Linux + * redhat/fedora: autre option: `dnf install redis` * debain/ubuntu: `apt install redis` ```` @@ -217,16 +231,20 @@ quelques suggestions dans ce sens: * il va vous falloir créer une instance du serveur redis (un `redis.Redis()`) dans le programme principal + * et passer cette instance à la classe `Player` * de façon à ce qu'elle puisse tenir le serveur redis au courant de toutes ses modifications de position et/ou de couleur (le raccourci clavier `c` permet de changer de couleur du joueur) + * une fois que c'est fait, il convient que le programme principal interroge le serveur pour connaitre la position des autres joueurs, avant de rafraichir l'affichage + * pour faire cela, une voie possible serait d'écrire une classe `Others` (dans un fichier `others.py`) dont le travail est d'interroger le serveur pour connaitre la position des autres joueurs + * ce qui donnerait un flux de données dans le genre de ceci ```{image} media/dataflow.excalidraw.svg @@ -318,6 +336,7 @@ en effet il est ultra fréquent que les ordinateurs soient derrière un routeur :class: seealso plus de détails ici + * * le RFC: ``` diff --git a/notebooks/tps/snake/.teacher/README-snake-corrige-nb.md b/notebooks/tps/snake/.teacher/README-snake-corrige-nb.md index 3ce0802..7edf028 100644 --- a/notebooks/tps/snake/.teacher/README-snake-corrige-nb.md +++ b/notebooks/tps/snake/.teacher/README-snake-corrige-nb.md @@ -16,7 +16,7 @@ language_info: # Le snake -+++ {"tags": [], "slideshow": {"slide_type": ""}} ++++ Licence CC BY-NC-ND, Thierry Parmentelat & Aurélien Noce @@ -203,6 +203,7 @@ pour cela cliquer dans la bannière du bas la zone qui indique le Python courant depuis vs-code : - ouvrir la palette + * `⇧ ⌘ P` Shift-Command-P (mac) * `⇧ ⌃ P` Shift-Control-P (windows) - chercher la fonction *Toggle Terminal* diff --git a/notebooks/tps/snake/README-snake-nb.md b/notebooks/tps/snake/README-snake-nb.md index 3ce0802..7edf028 100644 --- a/notebooks/tps/snake/README-snake-nb.md +++ b/notebooks/tps/snake/README-snake-nb.md @@ -16,7 +16,7 @@ language_info: # Le snake -+++ {"tags": [], "slideshow": {"slide_type": ""}} ++++ Licence CC BY-NC-ND, Thierry Parmentelat & Aurélien Noce @@ -203,6 +203,7 @@ pour cela cliquer dans la bannière du bas la zone qui indique le Python courant depuis vs-code : - ouvrir la palette + * `⇧ ⌘ P` Shift-Command-P (mac) * `⇧ ⌃ P` Shift-Control-P (windows) - chercher la fonction *Toggle Terminal* diff --git a/notebooks/tps/students-grades/.teacher/README-students-corrige-nb.md b/notebooks/tps/students-grades/.teacher/README-students-corrige-nb.md index e4376cd..5f66d3d 100644 --- a/notebooks/tps/students-grades/.teacher/README-students-corrige-nb.md +++ b/notebooks/tps/students-grades/.teacher/README-students-corrige-nb.md @@ -17,15 +17,13 @@ nbhosting: title: TP - classes simples --- -+++ {"slideshow": {"slide_type": ""}, "tags": []} - # classes `Student` et `Class` +++ Licence CC BY-NC-ND, Thierry Parmentelat & Laurent Lacourt -+++ {"tags": [], "slideshow": {"slide_type": ""}} ++++ ````{admonition} pas besoin de zip pour faire ce TP, vous avez seulement besoin de cet énoncé en HTML @@ -41,6 +39,7 @@ pour faire ce TP, vous avez seulement besoin de cet énoncé en HTML ou encore `def foo(s: str) -> bool:` au lieu de simplement `def foo(s):` + * dans ce TP nous allons nous définir deux classes `Student` et `Class`. Comme vous l'avez vu en cours une classe est définie (entre autres) par une série d'attributs et de méthodes. Il faut voir les méthodes comme des fonctions écrites spécialement pour s'appliquer à une instance de la classe. Les méthodes sont des fonctions qui, vous avez l'habitude de voir maintenant, ont généralement `self` comme premier argument; cela permet une utilisation `instance.methode(autre, arguments)` Ainsi, lorsqu'il vous est demandé d'implémenter la méthode `add_grade(topic: str, grade: float)` à la classe `Student`, n'oubliez pas que cela se traduit dans votre cellule par quelque chose comme : ```python diff --git a/notebooks/tps/students-grades/README-students-nb.md b/notebooks/tps/students-grades/README-students-nb.md index 23a848f..2ed57dc 100644 --- a/notebooks/tps/students-grades/README-students-nb.md +++ b/notebooks/tps/students-grades/README-students-nb.md @@ -17,15 +17,13 @@ nbhosting: title: TP - classes simples --- -+++ {"slideshow": {"slide_type": ""}, "tags": []} - # classes `Student` et `Class` +++ Licence CC BY-NC-ND, Thierry Parmentelat & Laurent Lacourt -+++ {"tags": [], "slideshow": {"slide_type": ""}} ++++ ````{admonition} pas besoin de zip pour faire ce TP, vous avez seulement besoin de cet énoncé en HTML @@ -41,6 +39,7 @@ pour faire ce TP, vous avez seulement besoin de cet énoncé en HTML ou encore `def foo(s: str) -> bool:` au lieu de simplement `def foo(s):` + * dans ce TP nous allons nous définir deux classes `Student` et `Class`. Comme vous l'avez vu en cours une classe est définie (entre autres) par une série d'attributs et de méthodes. Il faut voir les méthodes comme des fonctions écrites spécialement pour s'appliquer à une instance de la classe. Les méthodes sont des fonctions qui, vous avez l'habitude de voir maintenant, ont généralement `self` comme premier argument; cela permet une utilisation `instance.methode(autre, arguments)` Ainsi, lorsqu'il vous est demandé d'implémenter la méthode `add_grade(topic: str, grade: float)` à la classe `Student`, n'oubliez pas que cela se traduit dans votre cellule par quelque chose comme : ```python diff --git a/notebooks/tps/unicode-boxes/.teacher/README-unicode-boxes-corrige-nb.md b/notebooks/tps/unicode-boxes/.teacher/README-unicode-boxes-corrige-nb.md index 9bec28e..5a4d753 100644 --- a/notebooks/tps/unicode-boxes/.teacher/README-unicode-boxes-corrige-nb.md +++ b/notebooks/tps/unicode-boxes/.teacher/README-unicode-boxes-corrige-nb.md @@ -196,10 +196,12 @@ print(b22) +++ a few suggestions about how to improve + * accept for the width and height: either an int (like before) or a **list of integers** so we can build **grids** instead of boxes ```python b = Grid(10, [2, 2]) ``` + * make it reconnectable ? needs some thinking though ;-) * etc... diff --git a/notebooks/tps/unicode-boxes/.teacher/boxes.py b/notebooks/tps/unicode-boxes/.teacher/boxes.py new file mode 120000 index 0000000..af4177e --- /dev/null +++ b/notebooks/tps/unicode-boxes/.teacher/boxes.py @@ -0,0 +1 @@ +../boxes.py \ No newline at end of file diff --git a/notebooks/tps/unicode-boxes/README-unicode-boxes-nb.md b/notebooks/tps/unicode-boxes/README-unicode-boxes-nb.md index 8a70235..de4a422 100644 --- a/notebooks/tps/unicode-boxes/README-unicode-boxes-nb.md +++ b/notebooks/tps/unicode-boxes/README-unicode-boxes-nb.md @@ -182,10 +182,12 @@ print(b22) +++ a few suggestions about how to improve + * accept for the width and height: either an int (like before) or a **list of integers** so we can build **grids** instead of boxes ```python b = Grid(10, [2, 2]) ``` + * make it reconnectable ? needs some thinking though ;-) * etc... diff --git a/notebooks/tps/watson/.teacher/README-watson-corrige-nb.md b/notebooks/tps/watson/.teacher/README-watson-corrige-nb.md index 1c280d9..2be8701 100644 --- a/notebooks/tps/watson/.teacher/README-watson-corrige-nb.md +++ b/notebooks/tps/watson/.teacher/README-watson-corrige-nb.md @@ -56,7 +56,7 @@ print(reponse) ### notebooks -si vous envisagez de faire ce TP dans un notebook, [assurez-vous de bien lire cette section](label-autoreload) +si vous envisagez de faire ce TP dans un notebook, [assurez-vous de bien lire cette section](#label-autoreload) +++ @@ -69,6 +69,7 @@ on veut écrire un programme qui * puis: * selon que la réponse contient **le mot `bien`** ou **le mot `mal`** on affiche un message positif ou négatif (par exemple `C'est super!` et `Ohhhh, c'est triste.`) + * si la phrase est vide par contre, on affiche `Tu n'es pas bavard.` * enfin si rien de tout cela, on affiche `Je ne comprends pas` * dans tous les cas après la première réponse le programme s'arrête @@ -223,6 +224,7 @@ C'est fini, au revoir ! +++ on décide de refactorer le code en créant des classes; par exemple + * une classe `Feeling` correspondant à chacun des deux ensembles de mots * une classe `Sentence` qui sera crée pour chaque réponse * une classe `Watson` qui est l'application elle-même @@ -248,6 +250,8 @@ une façon de faire la v7 ## etc.. c'est toujours améliorable... par exemple: + * on pourrait imaginer mettre les réponses aussi dans le fichier de config dans ce cas un autre format serait sans doute mieux adapté; que pensez-vous de yaml dans ce contexte ? + * ... diff --git a/notebooks/tps/watson/.teacher/media b/notebooks/tps/watson/.teacher/media new file mode 120000 index 0000000..f47d0bb --- /dev/null +++ b/notebooks/tps/watson/.teacher/media @@ -0,0 +1 @@ +../media \ No newline at end of file diff --git a/notebooks/tps/watson/.teacher/watson1.py b/notebooks/tps/watson/.teacher/watson1.py new file mode 120000 index 0000000..3b90098 --- /dev/null +++ b/notebooks/tps/watson/.teacher/watson1.py @@ -0,0 +1 @@ +../watson1.py \ No newline at end of file diff --git a/notebooks/tps/watson/.teacher/watson5.py b/notebooks/tps/watson/.teacher/watson5.py new file mode 120000 index 0000000..aa70bef --- /dev/null +++ b/notebooks/tps/watson/.teacher/watson5.py @@ -0,0 +1 @@ +../watson5.py \ No newline at end of file diff --git a/notebooks/tps/watson/.teacher/watson7.py b/notebooks/tps/watson/.teacher/watson7.py new file mode 120000 index 0000000..e6a70f4 --- /dev/null +++ b/notebooks/tps/watson/.teacher/watson7.py @@ -0,0 +1 @@ +../watson7.py \ No newline at end of file diff --git a/notebooks/tps/watson/ARTEFACTS-watson.zip b/notebooks/tps/watson/ARTEFACTS-watson.zip index 881854e..e66c98f 100644 Binary files a/notebooks/tps/watson/ARTEFACTS-watson.zip and b/notebooks/tps/watson/ARTEFACTS-watson.zip differ diff --git a/notebooks/tps/watson/README-watson-nb.md b/notebooks/tps/watson/README-watson-nb.md index 564ecf8..d84b8f8 100644 --- a/notebooks/tps/watson/README-watson-nb.md +++ b/notebooks/tps/watson/README-watson-nb.md @@ -48,7 +48,7 @@ print(reponse) ### notebooks -si vous envisagez de faire ce TP dans un notebook, [assurez-vous de bien lire cette section](label-autoreload) +si vous envisagez de faire ce TP dans un notebook, [assurez-vous de bien lire cette section](#label-autoreload) +++ @@ -61,6 +61,7 @@ on veut écrire un programme qui * puis: * selon que la réponse contient **le mot `bien`** ou **le mot `mal`** on affiche un message positif ou négatif (par exemple `C'est super!` et `Ohhhh, c'est triste.`) + * si la phrase est vide par contre, on affiche `Tu n'es pas bavard.` * enfin si rien de tout cela, on affiche `Je ne comprends pas` * dans tous les cas après la première réponse le programme s'arrête @@ -215,6 +216,7 @@ C'est fini, au revoir ! +++ on décide de refactorer le code en créant des classes; par exemple + * une classe `Feeling` correspondant à chacun des deux ensembles de mots * une classe `Sentence` qui sera crée pour chaque réponse * une classe `Watson` qui est l'application elle-même @@ -240,6 +242,8 @@ une façon de faire la v7 ## etc.. c'est toujours améliorable... par exemple: + * on pourrait imaginer mettre les réponses aussi dans le fichier de config dans ce cas un autre format serait sans doute mieux adapté; que pensez-vous de yaml dans ce contexte ? + * ... diff --git a/notebooks/tps/wip-flappybird/README-flappybird-nb.md b/notebooks/tps/wip-flappybird/README-flappybird-nb.md index ace6c93..870824f 100644 --- a/notebooks/tps/wip-flappybird/README-flappybird-nb.md +++ b/notebooks/tps/wip-flappybird/README-flappybird-nb.md @@ -1,10 +1,6 @@ --- jupytext: - cell_metadata_filter: all,-hidden,-heading_collapsed,-run_control,-trusted encoding: '# -*- coding: utf-8 -*-' - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst diff --git a/notebooks/tps/wip-webscraper/README-webscraper-nb.md b/notebooks/tps/wip-webscraper/README-webscraper-nb.md index b31f7a7..2803730 100644 --- a/notebooks/tps/wip-webscraper/README-webscraper-nb.md +++ b/notebooks/tps/wip-webscraper/README-webscraper-nb.md @@ -1,9 +1,5 @@ --- jupytext: - cell_metadata_filter: all, -hidden, -heading_collapsed, -run_control, -trusted - notebook_metadata_filter: all, -jupytext.text_representation.jupytext_version, -jupytext.text_representation.format_version, - -language_info.version, -language_info.codemirror_mode.version, -language_info.codemirror_mode, - -language_info.file_extension, -language_info.mimetype, -toc text_representation: extension: .md format_name: myst diff --git a/requirements.txt b/requirements.txt index f4280d3..aa5952c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -38,3 +38,6 @@ ruamel.yaml # for unicode boxes colorama +# for ants +graphviz +plotly