Commit 5ee8dda6 authored by Romain Casati's avatar Romain Casati
Browse files

Adding examples to show in gallery.

parent 84f18a97
......@@ -16,7 +16,7 @@ install-kernel: _install-kernel version
build: clean install-kernel
python3 setup.py build
for f in version custom api/ kernelspecs/ basthon/; do cp -r notebook/$$f build/lib/notebook/; done
for f in version custom api/ kernelspecs/ basthon/ examples/; do cp -r notebook/$$f build/lib/notebook/; done
mv build/lib/notebook/basthon/* build/lib/notebook/
archives:
......
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure(figsize=(6, 4))\nax = fig.gca(projection='3d')\nX = np.linspace(-10, 10, 101)\nY = np.linspace(-10, 10, 101)\nX, Y = np.meshgrid(X, Y)\nD = np.sqrt(X ** 2 + Y ** 2)\nZ = np.exp(-D/2) * np.cos(1.5 * D)\nax.plot_wireframe(X, Y, Z, rstride=2, cstride=2, linewidth=0.5)\n\nplt.show()","execution_count":1,"outputs":[{"output_type":"display_data","data":{"application/javascript":"element.append(window.mplBus.pop(0));"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import requests\nimport gzip\nimport json\n\n# loading data\nresponse = requests.get(\"https://sig.infobrisson.fr/france.continental-borders.json.gz\")\nfrance = json.loads(gzip.decompress(response.content).decode())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(france)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import proj4py\n\n# from WGS84 to Lambert93\n_proj = proj4py.proj4('EPSG:4326', 'EPSG:2154')\n\ndef projete(points, reverse=False):\n if isinstance(points[0], (int, float)):\n points = [points]\n func = _proj.inverse if reverse else _proj.forward\n res = [tuple(func(p)) for p in points]\n return res if len(res) != 1 else res[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"france_proj = projete(france)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\n\ndef center_of_mass(points):\n points = np.asarray(points)\n assert np.array_equal(points[0, :], points[-1, :])\n px, py = points[:, 0], points[:, 1]\n area = 0.5 * (np.dot(px[:-1], py[1:]) - np.dot(px[1:], py[:-1]))\n return tuple(np.dot(px[:-1] * py[1:] - px[1:] * py[:-1], points[1:, :] + points[:-1, :]) / (6 * area))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ncenter_proj = center_of_mass(france_proj)\ncenter = projete(center_proj, reverse=True)\nprint(\"Coordoonnée du centre de la France :\", center)\n\nplt.figure(figsize=(8, 8))\nplt.gca(aspect='equal')\n\nplt.plot(*np.asarray(france_proj).T)\nplt.plot(*center_proj, 'o')\n\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import folium\n\nm = folium.Map(location=center, zoom_start=15)\n\nfolium.Marker(center, popup='Centre de la France').add_to(m)\n\nm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"m.options['zoom'] = 5\n\nfolium.PolyLine(france, color='red', weight=3, opacity=0.7).add_to(m)\n\nm","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import turtle\n\n\ndef recursive_drawing_nested(func):\n def draw_func(length, depth):\n def forward(factor):\n draw_func(length * factor, depth - 1)\n if depth == 0:\n turtle.forward(length)\n else:\n func(forward)\n draw_func.mode = \"nested\"\n return draw_func\n\n\ndef recursive_drawing_extend(func):\n def draw_func(length, depth):\n def forward(factor):\n turtle.forward(length)\n draw_func(length * factor, depth - 1)\n turtle.penup()\n turtle.backward(length)\n turtle.pendown()\n if depth > 0:\n func(forward)\n draw_func.mode = \"extend\"\n return draw_func\n\n\ndef recursive_drawing(mode=\"nested\"):\n if mode == \"nested\":\n return recursive_drawing_nested\n elif mode == \"extend\":\n return recursive_drawing_extend\n\n\ndef draw(length, depth, recurssive_func):\n turtle.shape(\"turtle\")\n turtle.color(\"red\")\n turtle.speed(\"fastest\")\n\n if recurssive_func.mode == \"nested\":\n turtle.penup()\n turtle.backward(length / 2)\n turtle.pendown()\n\n recurssive_func(length, depth)\n\n turtle.done()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"@recursive_drawing(mode=\"nested\")\ndef von_koch(forward):\n forward(1/3)\n turtle.left(60)\n forward(1/3)\n turtle.right(120)\n forward(1/3)\n turtle.left(60)\n forward(1/3)\n\ndraw(600, 3, von_koch)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"@recursive_drawing(mode=\"extend\")\ndef tree(forward):\n turtle.left(30)\n forward(0.6)\n turtle.right(60)\n forward(0.6)\n turtle.left(30)\n\n# tronc\nturtle.color(\"red\")\nturtle.penup()\nturtle.left(90)\nturtle.backward(150)\nturtle.pendown()\nturtle.forward(150)\n\ndraw(100, 8, tree)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from js import document\n\nelement = document.getElementById(\"notebook-container\")\n\nelement.style.backgroundColor = \"red\"","execution_count":1,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Des easter eggs (fonctionalités cachées) de Python"},{"metadata":{},"cell_type":"markdown","source":"## Le plus simple 'hello world' du monde !"},{"metadata":{"trusted":true},"cell_type":"code","source":"import __hello__","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## L'esprit de Python"},{"metadata":{"trusted":true},"cell_type":"code","source":"import this","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Voir le code de [this.py](https://github.com/python/cpython/blob/master/Lib/this.py) pour un autre easter egg."},{"metadata":{"trusted":true},"cell_type":"code","source":"import micropip\nmicropip.install(\"antigravity\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import antigravity\n\n# une redirection vers xkcd !","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from __future__ import braces","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from math import pi\n\nhash(float(\"infinity\")), round(pi, 5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import folium\n\nm = folium.Map(location=[47.228382, 2.062796], zoom_start=17)\n\nm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"coords = [45.832622, 6.865175]\n\nm = folium.Map(location=coords, zoom_start=12, tiles='Stamen Terrain')\n\nfolium.Marker(coords, popup='<i>Mont Blanc</i>', tooltip=\"Cliquez !\").add_to(m)\n\nm.add_child(folium.LatLngPopup())\n\nm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import graphviz","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dot = \"\"\"digraph g {\n\nnode [shape = circle,\n style = filled,\n color = grey]\n\nnode [fillcolor = red]\na\n\nnode [fillcolor = green]\nb c d\n\nnode [fillcolor = orange]\n\nedge [color = grey]\na -> {b c d}\nb -> {e f g h i j}\nc -> {k l m n o p}\nd -> {q r s t u v}\n}\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"graphviz.from_string(dot)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for engine in ('dot', 'neato', 'twopi', 'circo'):\n display(graphviz.from_string(dot, engine=engine))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{},"cell_type":"markdown","source":"© Guillaume CONNAN"},{"metadata":{},"cell_type":"markdown","source":"## Listes chaînées"},{"metadata":{"trusted":true},"cell_type":"code","source":"from __future__ import annotations\nfrom typing import Generic, TypeVar, Optional\nimport random\n\nT = TypeVar(\"T\")\n\nclass Maillon(Generic[T]):\n\n def __init__(self: Maillon[T], val: T) -> None:\n self._val = val\n self._suiv: Optional[Maillon[T]] = None\n\n def get_val(self: Maillon[T]) -> T:\n return self._val \n\n def get_suiv(self: Maillon[T]) -> Optional[Maillon[T]]:\n return self._suiv\n\n def set_suiv(self: Maillon[T], m: Optional[Maillon[T]]) -> None:\n if m is None or (type(m._val) == type(self._val)):\n self._suiv = m\n else:\n raise TypeError \n\n def __repr__(self: Maillon[T]) -> str:\n return f\"[{self._val}]-->{None if self._suiv is None else self._suiv._val}\"\n\n\nclass ListeC(Generic[T]):\n\n def __init__(self: ListeC[T]) -> None:\n self._tete: Optional[Maillon[T]] = None\n\n def est_vide(self: ListeC[T]) -> bool:\n return self._tete is None\n\n def queue(self: ListeC[T]) -> ListeC[T]:\n qt: ListeC[T] = ListeC()\n if not self._tete is None:\n qt._tete = self._tete.get_suiv() \n return qt\n\n def insere_tete(self: ListeC[T], val: T) -> None:\n if self._tete is None:\n self._tete = Maillon(val)\n else:\n t = Maillon(val)\n t.set_suiv(self._tete)\n self._tete = t\n \n def __repr__(self: ListeC[T]) -> str:\n if self.est_vide():\n return \"Vide\"\n if self.queue().est_vide():\n return f\"Tete : {self._tete} --> Queue : Vide\"\n return f\"Tete : {self._tete.get_val()} --> Queue : {self.queue()._tete.get_val()} --> ?\" \n\n def __len__(self: ListeC[T]) -> int:\n if self.est_vide():\n print(\"Vide\")\n return 0\n else:\n print(f\"{self._tete}\")\n return 1 + self.queue().__len__()\n\n ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"m1 = Maillon(1)\nm2 = Maillon(2)\nm1.set_suiv(m2)\nm1, m2","execution_count":null,"outputs":[]},{"metadata":{"tags":[],"trusted":true},"cell_type":"code","source":"ls = ListeC()\nfor nb in random.choices(range(1000), k = 10):\n ls.insere_tete(nb)\nls","execution_count":null,"outputs":[]},{"metadata":{"tags":[],"trusted":true},"cell_type":"code","source":"len(ls)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Étudier et expliquer le code proposé. Créer les méthodes suivantes:\n\n1. `insere_fin` qui insere un élément à la fin d'une liste chaînée.\n2. `get_el` qui a pour paramètre un entier i et qui renvoie la valeur du i-ème maillon de la liste.\n3. `insere_entre` qui a pour paramètre un entier i et qui insère une valeur en i-ème position dans la liste.\n4. `map` qui a pour paramètre une fonction et qui renvoie la liste dont les éléments sont les images des éléments de la liste de départ dans le même ordre\n5. `renverse` qui renvoie la liste dans l'ordre inverse."},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python_defaultSpec_1601490066637","display_name":"Python 3.8.2 64-bit"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Utilisation de Markdown dans Basthon-Notebook"},{"metadata":{},"cell_type":"markdown","source":"## Un titre de second niveau"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"La syntaxe markdown est utilisable dans des cellules de type _Markdown_ :\n\n - [un exemple de lien](https://basthon.fr)\n - un équation : $e^{i \\pi} + 1 = 0$\n - un tableau :\n \n| Syntax | Description |\n| ----------- | ----------- |\n| Header | Title |\n| Paragraph | Text |"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Récupération et traitement des données OSM de la France (niveau 4, régions)"},{"metadata":{},"cell_type":"markdown","source":"Il semble que le contour continental de la France ne soit pas directement disponible. On récupère donc les régions séparément. Les données présentées ci-dessous sont issus [d'OpenStreetMap © les contributeurs d’OpenStreetMap](https://www.openstreetmap.org/copyright)."},{"metadata":{},"cell_type":"markdown","source":"## Récuération de la liste des régions"},{"metadata":{"trusted":true},"cell_type":"code","source":"import requests\nimport json\n\n# on cherche toutes les régions de France\n\noverpass_url = \"https://overpass-api.de/api/interpreter\"\noverpass_query = \"\"\"\n[out:json];\narea[name=\"France\"][boundary];\n rel(area)[boundary][admin_level=4];\n map_to_area;\n foreach->.d(\n (.d;);out;\n );\n\"\"\"\nresponse = requests.get(overpass_url, params={'data': overpass_query})\ndata = response.json()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sorted([e['tags']['name'] for e in data['elements']])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# on ne garde que les plus pertinentes\nregions = [\n 'Auvergne-Rhône-Alpes',\n 'Bourgogne-Franche-Comté',\n 'Bretagne',\n 'Centre-Val de Loire',\n 'Corse',\n 'Grand Est',\n 'Guadeloupe',\n 'Guyane',\n 'Hauts-de-France',\n 'La Réunion',\n 'Martinique',\n 'Mayotte',\n 'Normandie',\n 'Nouvelle-Aquitaine',\n 'Occitanie',\n 'Pays de la Loire',\n \"Provence-Alpes-Côte d'Azur\",\n 'Île-de-France']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Récupérations des données régionales de contour"},{"metadata":{"trusted":true},"cell_type":"code","source":"import gzip\n\n# données géométriques au format JSON\nfor r in regions:\n overpass_query = \"\"\"\n[out:json];\nrelation[boundary=administrative][admin_level=4][name=\"{}\"];\nout geom;\n\"\"\".format(r)\n response = requests.get(overpass_url, params={'data': overpass_query})\n with gzip.open(\"{}.geom.json.gz\".format(r), 'w') as f:\n f.write(response.content)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Traitement pour retrouver un contour ordonné"},{"metadata":{"trusted":true},"cell_type":"code","source":"def contours(region=None, ways=None):\n # l'ordre des chemins n'est pas assuré mais on peut le retrouver :\n # https://gis.stackexchange.com/questions/119728/how-do-you-get-the-nodes-of-an-area-in-overpass-api-in-the-right-order\n if region is not None:\n data = json.load(gzip.open(\"{}.geom.json.gz\".format(region)))\n ways = [[(p['lat'], p['lon']) for p in m['geometry']]\n for e in data['elements'] for m in e['members']\n if m['type'] == 'way' and m['role'] == 'outer']\n else:\n assert ways is not None\n \n # on construit le dico des chemins indicés par le premier point\n # (les chemins sont ajoutés dans les deux sens)\n res = {}\n for way in ways: \n start, end = way[0], way[-1]\n\n if start in res:\n way = res[start][::-1] + way[1:]\n del res[start]\n if way[0] != way[-1] and end in res:\n way = way + res[end][1:]\n del res[end]\n res[way[0]] = way\n res[way[-1]] = way[::-1]\n\n for k, c in res.items():\n assert c[0] == c[-1], len(c)\n\n return sorted(res.values(), key=lambda x: len(x), reverse=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for r in regions:\n json.dump(contours(r), gzip.open(\"{}.borders.json.gz\".format(r), 'wt'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Extraction des données continentales"},{"metadata":{"trusted":true},"cell_type":"code","source":"for r in regions:\n data = json.load(gzip.open(\"{}.borders.json.gz\".format(r)))[0]\n json.dump(data, gzip.open(\"{}.continental-borders.json.gz\".format(r), 'wt'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Représentation en Lambert93 pour vérifier"},{"metadata":{"trusted":true},"cell_type":"code","source":"import proj4py\n\n# from WGS84 to Lambert93\n_proj = proj4py.proj4('EPSG:4326', 'EPSG:2154')\n\ndef projete(points, reverse=False):\n if isinstance(points[0], (int, float)):\n points = [points]\n func = _proj.inverse if reverse else _proj.forward\n res = [tuple(func(p)) for p in points]\n return res if len(res) != 1 else res[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.figure(figsize=(8, 8))\nplt.gca(aspect='equal')\nfor r in regions:\n if r in {\"La Réunion\", \"Guadeloupe\", \"Guyane\", \"Martinique\", \"Mayotte\"}: continue\n c = json.load(gzip.open(\"{}.continental-borders.json.gz\".format(r)))\n pts = np.asarray(projete(c))\n plt.plot(pts[:, 0], pts[:, 1])\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Construction du contour de la France"},{"metadata":{"trusted":true},"cell_type":"code","source":"def union(region_list):\n # suppression des chemins qui apparaissent en double\n ways = {}\n for r in region_list:\n data = json.load(gzip.open(\"{}.geom.json.gz\".format(r)))\n for e in data['elements']:\n for m in e['members']:\n if m['type'] != 'way' or m['role'] != 'outer':\n continue\n ref = m['ref']\n if ref in ways:\n del ways[ref]\n else:\n ways[ref] = [(p['lat'], p['lon']) for p in m['geometry']]\n return contours(ways=ways.values())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"france = union(regions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(8, 8))\nplt.gca(aspect='equal')\npts = np.asarray(projete(france[0]))\nplt.plot(pts[:, 0], pts[:, 1])\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.3"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import requests\nfrom io import StringIO\n\n# données INSEE : https://www.insee.fr/fr/statistiques/4767258\nresponse = requests.get(\"https://data.infobrisson.fr/classement_prenoms_filles_2019.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\n\ndf = pd.read_csv(StringIO(response.decode()), sep=';')\n\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"response = requests.get(\"https://data.infobrisson.fr/classement_prenoms_garcons_2019.csv\")\n\ndf = pd.read_csv(StringIO(response.decode()), sep=';')\n\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.3"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Import d'un module depuis Pypi"},{"metadata":{"trusted":true},"cell_type":"code","source":"import micropip\n\nmicropip.install(\"emoji\")","execution_count":1,"outputs":[{"output_type":"execute_result","execution_count":1,"data":{"text/plain":"[object Promise]"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"from emoji import emojize\nemojize(\":thumbs_up:\")","execution_count":2,"outputs":[{"output_type":"execute_result","execution_count":2,"data":{"text/plain":"'👍'"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"emojize(\":snake:\")","execution_count":3,"outputs":[{"output_type":"execute_result","execution_count":3,"data":{"text/plain":"'🐍'"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(emojize(\"J':red_heart: Basthon !\"))","execution_count":4,"outputs":[{"output_type":"stream","text":"J'❤ Basthon !\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>\n# License: BSD 3 clause\n\n# Standard scientific Python imports\nimport matplotlib.pyplot as plt\n\n# Import datasets, classifiers and performance metrics\nfrom sklearn import datasets, svm, metrics\nfrom sklearn.model_selection import train_test_split\n\n# The digits dataset\ndigits = datasets.load_digits()\n\n# The data that we are interested in is made of 8x8 images of digits, let's\n# have a look at the first 4 images, stored in the `images` attribute of the\n# dataset. If we were working from image files, we could load them using\n# matplotlib.pyplot.imread. Note that each image must have the same size. For these\n# images, we know which digit they represent: it is given in the 'target' of\n# the dataset.\n_, axes = plt.subplots(2, 4)\nimages_and_labels = list(zip(digits.images, digits.target))\nfor ax, (image, label) in zip(axes[0, :], images_and_labels[:4]):\n ax.set_axis_off()\n ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n ax.set_title('Training: %i' % label)\n\n# To apply a classifier on this data, we need to flatten the image, to\n# turn the data in a (samples, feature) matrix:\nn_samples = len(digits.images)\ndata = digits.images.reshape((n_samples, -1))\n\n# Create a classifier: a support vector classifier\nclassifier = svm.SVC(gamma=0.001)\n\n# Split data into train and test subsets\nX_train, X_test, y_train, y_test = train_test_split(\n data, digits.target, test_size=0.5, shuffle=False)\n\n# We learn the digits on the first half of the digits\nclassifier.fit(X_train, y_train)\n\n# Now predict the value of the digit on the second half:\npredicted = classifier.predict(X_test)\n\nimages_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))\nfor ax, (image, prediction) in zip(axes[1, :], images_and_predictions[:4]):\n ax.set_axis_off()\n ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n ax.set_title('Prediction: %i' % prediction)\n\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(y_test, predicted)))\nprint(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(predicted, y_test))\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from sympy import *","execution_count":1,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = Symbol(\"x\")\nsol = solve(x ** 2 + x + 1)\npretty_print(sol)","execution_count":2,"outputs":[{"output_type":"display_data","data":{"text/latex":"$$\\left [ - \\frac{1}{2} - \\frac{\\sqrt{3} i}{2}, \\quad - \\frac{1}{2} + \\frac{\\sqrt{3} i}{2}\\right ]$$"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"area_gaussian = Integral(exp(-x ** 2), (x, -oo, oo))\npretty_print(area_gaussian, \"=\", area_gaussian.doit())","execution_count":3,"outputs":[{"output_type":"display_data","data":{"text/latex":"$$\\int_{-\\infty}^{\\infty} e^{- x^{2}}\\, dx = \\sqrt{\\pi}$$"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"n = Symbol(\"n\")\npretty_print(summation(1 / n ** 2, (n, 1, oo)))","execution_count":4,"outputs":[{"output_type":"display_data","data":{"text/latex":"$$\\frac{\\pi^{2}}{6}$$"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import image\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = image.imread(\"sandbox.png\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\nplt.imshow(img)\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = 1 - img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\nplt.imshow(img)\nplt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[{"output_type":"display_data","data":{"application/javascript":"element.append(window.mplBus.pop(0));"},"metadata":{}}]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Bezier(object):\n \"\"\"\n Une courbe de Bézier de degré n > 0 en dimension d > 1.\n \"\"\"\n def __init__(self, control_points):\n \"\"\"\n control_points.shape == (n + 1, d)\n \"\"\"\n self._points = np.asarray(control_points)\n\n def __call__(self, t):\n \"\"\"\n Position de la courbe à la valeur t.\n \"\"\"\n return self.de_casteljau(t)\n\n def de_casteljau(self, t):\n \"\"\"\n Position de la courbe à la valeur t.\n \"\"\"\n t = np.asarray(t)\n points = self._points[..., np.newaxis]\n while points.shape[0] > 1:\n points = points[1:, ...] * t + points[:-1, ...] * (1 - t)\n res = points[0].T\n # single value evaluation\n if not t.shape:\n res = res[0]\n return res\n \n def control_points(self):\n return self._points","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import turtle\n\ndef directed_goto(x, y):\n turtle.setheading(turtle.towards(x, y))\n turtle.goto(x, y)\n\ndef draw_curve(curve, npoints=50):\n t = np.linspace(0, 1, npoints)\n points = curve(t)\n p0 = points[0]\n turtle.penup()\n directed_goto(*p0)\n turtle.pendown()\n for p in points[1:]:\n directed_goto(*p)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"turtle.color(\"#366f9e\")\nturtle.shape(\"turtle\")\nturtle.speed(\"fast\")\nturtle.width(3)\n\nb = Bezier([(-200, -200), (500, 200), (-500, 200), (200, -200)])\ndraw_curve(b)\n\nturtle.done()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class BSpline(object):\n \"\"\"\n Une spline de Bézier.\n \"\"\"\n def __init__(self, control_points, degree=3):\n self._curves = [Bezier(control_points[i:i + degree + 1])\n for i in range(0, len(control_points) - 1, degree)]\n\n def npieces(self):\n return len(self._curves)\n\n def _eval_at(self, t):\n # t should be of type float\n if t >= 1:\n return self._curves[-1]._points[-1]\n t *= self.npieces()\n index = int(t)\n return self._curves[index](t - index)\n\n def __call__(self, t):\n t = np.asarray(t)\n if not t.shape:\n return self._eval_at(t)\n return np.array([self._eval_at(x) for x in t])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bas = 18 * (np.asarray(\n [(0.0, 0.0), (0.5, 0.0), (6.0, 15.0), (3.0, 15.0),\n (0.0, 15.0), (1.5, 0.0), (2.5, 0.0),\n (3.5, 0.0), (3.0, 4.0), (4.0, 4.0),\n (5.0, 4.0), (5.0, 4.0), (5.0, 4.0),\n (5.0, 4.0), (5.0, 0.0), (5.5, 0.0),\n (6.0, 0.0), (6.5, 1.5), (6.5, 1.5),\n (6.5, 1.5), (6.0, 4.0), (8.0, 4.0),\n (10.0, 4.0), (10.0, 0.0), (8.0, 0.0),\n (6.0, 0.0), (6.0, 4.0), (8.0, 4.0),\n (10.0, 4.0), (9.5, 0.0), (10.0, 0.0),\n (10.5, 0.0), (14.0, 4.0), (13.0, 4.0),\n (12.0, 4.0), (14.5, 1.0), (14.0, 0.5),\n (13.5, 0.0), (11.5, 0.0), (11.5, 0.5),\n (11.5, 1.0), (14.0, 0.0), (14.5, 0.0)]) - (17, 5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"curve_bas = BSpline(bas)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"thon = bas[-1] + 18 * np.asarray(\n [(0.0, 0.0), (1.5, 0.0), (2.0, 10.0), (2.0, 10.0),\n (2.0, 10.0), (1.5, 7.0), (2.0, 7.0),\n (2.5, 7.0), (3.5, 7.0), (3.5, 7.0),\n (3.5, 7.0), (2.5, 7.0), (2.0, 7.0),\n (1.5, 7.0), (1.5, 0.0), (3.5, 0.0),\n (5.5, 0.0), (10.5, 15.0), (7.0, 15.0),\n (3.5, 15.0), (6.0, 0.5), (6.0, 0.0),\n (6.0, -0.5), (5.0, 4.0), (7.0, 4.0),\n (9.0, 4.0), (7.5, 0.0), (9.0, 0.0),\n (10.5, 0.0), (13.0, 0.0), (13.0, 2.0),\n (13.0, 4.0), (12.0, 4.0), (11.5, 4.0),\n (11.0, 4.0), (9.5, 3.5), (9.5, 2.0),\n (9.5, 0.5), (10.0, 0.0), (11.0, 0.0),\n (12.0, 0.0), (14.0, 1.5), (12.5, 3.5),\n (11.0, 5.5), (11.5, 1.5), (12.5, 2.5),\n (13.5, 3.5), (14.0, 4.0), (15.0, 4.0),\n (16.0, 4.0), (15.5, 0.0), (15.5, 0.0),\n (15.5, 0.0), (15.5, 4.0), (17.0, 4.0),\n (18.5, 4.0), (17.5, 0.0), (19.0, 0.0)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"curve_thon = BSpline(thon)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"turtle.shape(\"turtle\")\nturtle.speed(\"normal\")\nturtle.width(5)\n\nturtle.color(\"#366f9e\")\ndraw_curve(curve_bas, 300)\nturtle.color(\"#ffc938\")\ndraw_curve(curve_thon, 400)\n\nturtle.done()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"}},"nbformat":4,"nbformat_minor":2}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment