markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The function defines a number of parameters that will change the signal, but using the default parameters the function outputs a Curve like this: | fm_modulation() | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
HoloMaps
The HoloMap is the first container type we will start working with, because it is often the starting point of a parameter exploration. HoloMaps allow exploring a parameter space sampled at specific, discrete values, and can easily be created using a dictionary comprehension. When declaring a HoloMap, just ensu... | carrier_frequencies = [10, 20, 110, 220, 330]
modulation_frequencies = [110, 220, 330]
hmap = hv.HoloMap({(fc, fm): fm_modulation(fc, fm) for fc in carrier_frequencies
for fm in modulation_frequencies}, kdims=['fc', 'fm'])
hmap | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Note how the keys in our HoloMap map on to two automatically generated sliders. HoloViews supports two types of widgets by default: numeric sliders, or a dropdown selection menu for all non-numeric types. These sliders appear because a HoloMap can display only a single Element at one time, and the user must thus select... | # Exercise: Try changing the function below to return an ``Area`` or ``Scatter`` element,
# in the same way `fm_modulation` returned a ``Curve`` element.
def fm_modulation2(f_carrier=220, f_mod=110, mod_index=1, length=0.1, sampleRate=3000):
x = np.arange(0,length, 1.0/sampleRate)
y = np.sin(2*np.pi*f_carrier*x... | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Apart from their simplicity and generality, one of the key features of HoloMaps is that they can be exported to a static HTML file, GIF, or video, because every combination of the sliders (parameter values) has been pre-computed already. This very convenient feature of pre-computation becomes a liability for very larg... | %%opts Curve (color='red')
dmap = hv.DynamicMap(fm_modulation, kdims=['f_carrier', 'f_mod', 'mod_index'])
dmap = dmap.redim.range(f_carrier=((10, 110)), f_mod=(10, 110), mod_index=(0.1, 2))
dmap
# Exercise: Declare a DynamicMap using the function from the previous exercise and name it ``exercise_dmap``
# Exercise (O... | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Faceting parameter spaces
Casting
HoloMaps and DynamicMaps let you explore a multidimensional parameter space by looking at one point in that space at a time, which is often but not always sufficient. If you want to see more data at once, you can facet the HoloMap to put some data points side by side or overlaid to fac... | %%opts Curve [width=150]
hv.GridSpace(hmap).opts()
# Exercise: Try casting your ``exercise_hmap`` HoloMap from the first exercise to an ``NdLayout`` or
# ``NdOverlay``, guessing from the name what the resulting organization will be before testing it.
| notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Faceting with methods
Using the .overlay, .grid and .layout methods we can facet multi-dimensional data by a specific dimension: | hmap.overlay('fm') | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Using these methods with a DynamicMap requires special attention, because a dynamic map can return an infinite number of different values along its dimensions, unlike a HoloMap. Obviously, HoloViews could not comply with such a request, but these methods are perfectly legal with DynamicMap if you also define which spec... | %%opts Curve [width=150]
dmap.redim.values(f_mod=[10, 20, 30], f_carrier=[10, 20, 30]).overlay('f_mod').grid('f_carrier').opts()
# Exercise: Facet the ``exercise_dmap`` DynamicMap using ``.overlay`` and ``.grid``
# Hint: Use the .redim.values method to set discrete values for ``f_mod`` and ``f_carrier`` dimensions
| notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Optional
Slicing and indexing
HoloMaps and other containers also allow you to easily index or select by key, allowing you to:
select a specific key: obj[10, 110]
select a slice: obj[10, 200:]
select multiple values: obj[[10, 110], 110] | %%opts Curve [width=300]
hmap[10, 110] + hmap[10, 200:].overlay() + hmap[[10, 110], 110].overlay() | notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
You can do the same using the select method: | (hmap.select(fc=10, fm=110) +
hmap.select(fc=10, fm=(200, None)).overlay() +
hmap.select(fc=[10, 110], fm=110).overlay())
# Exercise: Try selecting two carrier frequencies and two modulation frequencies on the ``exercise_hmap``
| notebooks/03-exploration-with-containers.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Now we set up all simulation parameters. | # Lennard-Jones parameters
LJ_SIGMA = 1
LJ_EPSILON = 1
LJ_CUT = 2**(1. / 6.) * LJ_SIGMA
# Particles
N_PART = 1200
# Area fraction of the mono-layer
PHI = 0.1
# Dipolar interaction parameter lambda = mu_0 m^2 /(4 pi sigma^3 KT)
DIP_LAMBDA = 4
# Temperature
KT = 1.0
# Friction coefficient
GAMMA = 1.0
# Time step
TI... | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Note that we declared a <tt>lj_cut</tt>. This will be used as the cut-off radius of the Lennard-Jones potential to obtain a purely repulsive WCA potential.
Now we set up the system. The length of the simulation box is calculated using the desired area fraction and the area all particles occupy. Then we create the ESPRe... | # System setup
# BOX_SIZE = ...
print("Box size", BOX_SIZE)
# Note that the dipolar P3M and dipolar layer correction need a cubic
# simulation box for technical reasons.
system = espressomd.System(box_l=(BOX_SIZE, BOX_SIZE, BOX_SIZE))
system.time_step = TIME_STEP | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Now we set up the interaction between the particles as a non-bonded interaction and use the Lennard-Jones potential as the interaction potential. Here we use the above mentioned cut-off radius to get a purely repulsive interaction. | # Lennard-Jones interaction
system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA, cutoff=LJ_CUT, shift="auto") | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Now we generate random positions and orientations of the particles and their dipole moments.
Hint:
It should be noted that we seed the random number generator of numpy. Thus the initial configuration of our system is the same every time this script will be executed. You can change it to another one to simulate with a ... | # Random dipole moments
# ...
# dip = ...
# Random positions in the monolayer
pos = BOX_SIZE * np.hstack((np.random.random((N_PART, 2)), np.zeros((N_PART, 1)))) | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Now we add the particles with their positions and orientations to our system. Thereby we activate all degrees of freedom for the orientation of the dipole moments. As we want a two dimensional system we only allow the particles to translate in $x$- and $y$-direction and not in $z$-direction by using the <tt>fix</tt> ar... | # Add particles
system.part.add(pos=pos, rotation=N_PART * [(1, 1, 1)], dip=dip, fix=N_PART * [(0, 0, 1)]) | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Be aware that we do not set the magnitude of the magnetic dipole moments to the particles. As in our case all particles have the same dipole moment it is possible to rewrite the dipole-dipole interaction potential to
\begin{equation}
u_{\text{DD}}(\vec{r}{ij}, \vec{\mu}_i, \vec{\mu}_j) = \gamma \mu^2 \left(\frac{\... | # Set integrator to steepest descent method
system.integrator.set_steepest_descent(
f_max=0, gamma=0.1, max_displacement=0.05) | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Exercise:
Perform a steepest descent energy minimization.
Track the relative energy change $E_{\text{rel}}$ per minimization loop (where the integrator is run for 10 steps) and terminate once $E_{\text{rel}} \le 0.05$, i.e. when there is less than a 5% difference in the relative energy change in between iterations.
```... | # Switch to velocity Verlet integrator
system.integrator.set_vv()
system.thermostat.set_langevin(kT=KT, gamma=GAMMA, seed=1) | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
To calculate the dipole-dipole interaction we use the Dipolar P3M method (see Ref. <a href='#[1]'>[1]</a>) which is based on the Ewald summation. By default the boundary conditions of the system are set to conducting which means the dielectric constant is set to infinity for the surrounding medium. As we want to simula... | # Setup dipolar P3M and dipolar layer correction
dp3m = DipolarP3M(accuracy=5E-4, prefactor=DIP_LAMBDA * LJ_SIGMA**3 * KT)
dlc = DLC(maxPWerror=1E-4, gap_size=BOX_SIZE - LJ_SIGMA)
system.actors.add(dp3m)
system.actors.add(dlc)
# tune verlet list skin
system.cell_system.tune_skin(min_skin=0.4, max_skin=2., tol=0.2, int... | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Now we equilibrate the dipole-dipole interaction for some time | # Equilibrate
print("Equilibration...")
EQUIL_ROUNDS = 20
EQUIL_STEPS = 1000
for i in range(EQUIL_ROUNDS):
system.integrator.run(EQUIL_STEPS)
print(
f"progress: {(i + 1) * 100. / EQUIL_ROUNDS}%, dipolar energy: {system.analysis.energy()['dipolar']}",
end="\r")
print("\nEquilibration done") | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Sampling
The system will be sampled over 100 loops. | LOOPS = 100 | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
As the system is two dimensional, we can simply do a scatter plot to get a visual representation of a system state. To get a better insight of how a ferrofluid system develops during time we will create a video of the development of our system during the sampling. If you only want to sample the system simply go to Samp... | import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tempfile import NamedTemporaryFile
import base64
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasa... | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Exercise:
In the following an animation loop is defined, however it is incomplete.
Extend the code such that in every loop the system is integrated for 100 steps.
Afterwards x_data and y_data have to be populated by the folded $x$- and $y$- positions of the particles.
(You may copy and paste the incomplete code templat... | fig, ax = plt.subplots(figsize=(10, 10))
part, = ax.plot([], [], 'o')
animation.FuncAnimation(fig, run, frames=LOOPS, blit=True, interval=0, repeat=False, init_func=init) | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Cluster analysis
To quantify the number of clusters and their respective sizes, we now want to perform a cluster analysis.
For that we can use ESPREsSo's cluster analysis class.
Exercise:
Setup a cluster analysis object (ClusterStructure class) and assign its instance to the variable cluster_structure.
As criterion for... | n_clusters = []
cluster_sizes = [] | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Sampling without animation
The following code just samples the system and does a cluster analysis every <tt>loops</tt> (100 by default) simulation steps.
Exercise:
Write an integration loop which runs a cluster analysis on the system, saving the number of clusters n_clusters and the size distribution cluster_sizes.
Tak... | import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
plt.xlim(0, BOX_SIZE)
plt.ylim(0, BOX_SIZE)
plt.xlabel('x-position', fontsize=20)
plt.ylabel('y-position', fontsize=20)
plt.plot(system.part[:].pos_folded[:, 0], system.part[:].pos_folded[:, 1], 'o')
plt.show() | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
In the plot chain-like and ring-like clusters should be visible. Some of them are connected via Y- or X-links to each other. Also some monomers should be present.
Cluster distribution
After having sampled our system we now can calculate estimators for the expectation value of the cluster sizes and their distribution.
E... | plt.figure(figsize=(10, 10))
plt.grid()
plt.xticks(range(0, 20))
plt.plot(size_dist[1][:-2], size_dist[0][:-1] / float(LOOPS))
plt.xlabel('size of clusters', fontsize=20)
plt.ylabel('distribution', fontsize=20)
plt.show() | doc/tutorials/ferrofluid/ferrofluid_part1.ipynb | fweik/espresso | gpl-3.0 |
Arbres binaires de recherche
Exercice 1 : ABR
Définition du type Abr et exemples de valeurs
Comme au TP1 et TP2, plutôt que d'utiliser des classes, je préfère utiliser des dictionnaires avec une seule clé et une seule valeur pour représenter des structures arborescentes.
La valeur est ici None s'il n'y a rien à stocker... | Leaf = {"Leaf": None}
def Node(k: int, v: str, l: dict, r: dict) -> dict:
""" Crée un arbre binaire avec un noeud de clé k, de valeur v, de fils gauche l et de fils droit r."""
return {"Node": (k, v, l, r)} | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On peut aussi utiliser une approche objet, et définir une classe.
L'avantage sera un accès plus rapide aux différentes valeurs stockées : arbre.l donne le fils gauche. | class NodeClass():
def __init__(self, k: int, v: str, l, r):
self.k = k
self.v = v
self.l = l
self.r = r | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Note sur le typage en Python
En Python, avec le module typing, on peut définir des alias de types (non récursifs), comme en OCaml.
On peut ensuite ajouter indications de typage, à des définitions de variables ou de fonctions. | from typing import Dict, List, Any, Union, Tuple
Abr = Dict[str, Union[str, Tuple[int, str, Any, Any]]] | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exemples d'arbres binaires | exemple_arbre_binaire1: Abr = Node(1, "a", Leaf, Leaf)
print(exemple_arbre_binaire1)
exemple_arbre_binaire2: Abr = Node(2, "b", exemple_arbre_binaire1, Leaf)
print(exemple_arbre_binaire2)
exemple_arbre_binaire3: Abr = Node(3, "c", exemple_arbre_binaire1, exemple_arbre_binaire2)
print(exemple_arbre_binaire3) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Pour afficher joliment des structures arborescentes on peut utiliser pprint.pprint : | from pprint import pprint
pprint(exemple_arbre_binaire2)
pprint(exemple_arbre_binaire3) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
En OCaml on pouvait définir un type récursif comme cela (observez comment abr intervient dans la définition de anode qui intervient dans la définition de abr...), mais en Python ce n'est pas possible.
```ocaml
type 'a abr =
| Leaf
| Node of 'a anode
and 'b anode = {
key : int;
value : 'b;
left : ... | def nb_keys(a: Abr) -> int:
""" Calcule le nombre de clés d'un arbre binaire a."""
# on simule "match a with ..." avec des if/elif/else
if "Leaf" in a: # simule | Leaf ->
return 0
elif "Node" in a:
_, _, l, r = a["Node"]
return 1 + nb_keys(l) + nb_keys(r)
else: # ce cas n'a... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
En OCaml, l'avantage du pattern matching est qu'il nous prévient si le test n'est pas exhaustif.
En Python, on ne peut pas avoir ce genre d'aide.
ocaml
let rec nb_keys (a : 'a abr) : int =
match a with
(* si on oublie le cas de base : | Leaf -> 0 *)
| Node n -> 1 + nb_keys n.left + nb_keys n.right
;;
... | print("L'arbre binaire suivant :")
pprint(exemple_arbre_binaire1)
print("contient", nb_keys(exemple_arbre_binaire1), "clés.")
print("L'arbre binaire suivant :")
pprint(exemple_arbre_binaire2)
print("contient", nb_keys(exemple_arbre_binaire2), "clés.")
print("L'arbre binaire suivant :")
pprint(exemple_arbre_binaire3)
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Extraire une liste des clés
Bonus : on peut extraire une liste des clés, très facilement : | def list_keys(a: Abr) -> List[str]:
""" Extraire la liste des clés d'un arbre binaire a (parcours en profondeur)."""
# on simule "match a with ..." avec des if/elif/else
if "Leaf" in a: # simule | Leaf ->
return []
elif "Node" in a:
v, k, l, r = a["Node"]
return [k] + list_keys(... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 2 : trouve | def trouve(a: Abr, x: int) -> Union[int, None]:
# Optional[int] is equivalent to Union[int]
if "Leaf" in a:
return None
elif "Node" in a:
k, v, l, r = a["Node"]
if k == x: # on a trouvé la valeur v associée à la clé k = x
return v
elif x < k:
# on ch... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exemple de recherche qui ne fonctionne pas (sans renvoyer d'erreur, juste un None) : | print("En cherchant la clé 42 dans l'arbre binaire suivant")
pprint(exemple_arbre_binaire3)
print("on trouve la valeur associée =", trouve(exemple_arbre_binaire3, 42)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Si on veut que la recherche échoue si la clé cherchée n'est pas présente, on peut changer le code et écrire : | def trouve_avec_erreur(a: Abr, x: int) -> int: # notez que le type de retour est juste un entier désormais
if "Leaf" in a:
raise ValueError("Incapable de trouver {} dans l'arbre binaire {}".format(x, a))
elif "Node" in a:
k, _, l, r = a["Node"]
if k == x: # on a trouvé la valeur v ass... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La traceback (affichage de l'erreur) nous montre même les appels récursifs qui ont menés à l'erreur. (ici, deux appels récursifs sur le fils droit, puisque 42 était plus grand que les deux clés successives 3 et 2).
Exercice 3 : insertion | def insertion(a: Abr, k: int, v: str) -> Abr:
if "Leaf" in a: # a arbre vide, on crée un noeud ayant deux fils vides
return Node(k, v, Leaf, Leaf)
elif "Node" in a:
ka, va, l, r = a["Node"]
if k == ka: # on ne change pas les fils
return Node(k, v, l, r) # change va -> v
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Quelques tests : | pprint(insertion(insertion(Leaf, 2, "deux"), 1, "un"))
print("Valeur trouvée pour la clé 1 =", trouve(insertion(insertion(Leaf, 2, "deux"), 1, "un"), 1))
pprint(insertion(insertion(Leaf, 2, "deux"), 1, "un"))
print("Valeur trouvée pour la clé 2 =", trouve(insertion(insertion(Leaf, 2, "deux"), 1, "un"), 2))
pprint(ins... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 4 : suppression
minimum a renvoie le couple (key, value) de l'arbre a avec key minimal dans a.
Lance une exception si a est vide. | def minimum(a: Abr) -> Tuple[int, str]:
if "Leaf" in a:
raise ValueError("Arbre vide")
elif "Node" in a:
k, v, l, r = a["Node"]
if "Leaf" in l: # sous-arbre gauche vide : le minimum est le noeud actuel
return (k, v)
else: # sinon, le minimum de l'arbre actuel est à c... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On pourrait être plus élégant que ces tests "Leaf" in a et "Node" in a, et utiliser deux fonctions is_leaf(a) et is_node(a). Cela permettrait de cacher un peu plus les détails d'implémentations. | def is_leaf(a: Abr) -> bool:
return "Leaf" in a # ou Leaf == a
def is_node(a: Abr) -> bool:
return "Node" in a
minimum(insertion (insertion(Leaf, 1, "un"), 2, "deux"))
minimum(insertion (insertion(Leaf, 2, "deux"), 1, "un")) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La suppression se fait dans le cas où la clé x est trouvée : | def suppression(a: Abr, x: int) -> Abr:
if "Leaf" in a: # rien à supprimer
return Leaf
elif "Node" in a:
k, v, l, r = a["Node"]
if k == x: # trouvé
if "Leaf" in r: # sous-arbre droit vide : on renvoie le sous-arbre gauche
return l
else:
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Deux exemples : | print(trouve (suppression (insertion (insertion(Leaf, 2, "deux"), 1, "un"), 1), 1))
print(trouve (suppression (insertion (insertion(Leaf, 2, "deux"), 1, "un"), 1), 2)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 5 : fusion
decoupe a k sépare l'arbre a en deux arbres (a1, a2) tels que l'union des clés-valeurs de a1 et a2 est égale à l'ensemble des clés-valeurs de a (privé de l'association liée à k si elle était présente dans a).
Les clés de a1 sont < à k.
Les clés de a2 sont > à k. | def decoupe(a: Abr, x: int) -> Tuple[Abr, Abr]:
"""
[decoupe a k] sépare l'arbre [a] en deux arbres [(a1, a2)]
tels que l'union des clés-valeurs de [a1] et [a2] est égale à
l'ensemble des clés-valeurs de [a] (privé de l'association
liée à [k] si elle était présente dans [a]).
Les clés de [a1] sont < ... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Et maintenant la fusion n'est pas très difficile : | def fusion(a1: Abr, a2: Abr) -> Abr:
""" Fusionne les deux arbres binaires de recherche a1 et a2.
Convention : si une clé est présente dans les deux arbres, nous gardons celle de [a1]
"""
if "Leaf" in a1: # rien à supprimer
return a2
elif "Node" in a1:
k, v, l, r = a1["Node"]
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 6
Avantages et les inconvénients des ABR
Discussions durant la séance...
Autres structures de données (clef, valeur)
Les tables de hashage
autres idées ? envoyez moi un mail : lilian.besson at ens-rennes.fr ou ouvrez un ticket sur GitHub
Tas binaire min (ou max)
Un tas binaire est un arbre binaire dans le... | E = {"E": None}
T = lambda rang, v, l, r: {"T": (rang, v, l, r)}
TasBinaire = Union[
Dict[str, None], # pour E = {"E": None}
Dict[str, Tuple[int, str, dict, dict]] # pour T = {"T" : (k, v, l, r)}
# ici si on pouvait écrire des types récursifs, il faudrait écrire
# Dict[str, Tuple[int, str, TasBinaire... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La première primitive est la création d'un tas avec la clé x, et deux sous-tas a et b.
Le rang est minimisé. | def make(x: int, a: TasBinaire, b: TasBinaire) -> TasBinaire:
""" Créer un tas binaire de clé x avec deux sous-tas a et b, minimisant le rang."""
ra = rank(a)
rb = rank(b)
if ra >= rb:
return T(rb + 1, x, a, b)
else:
return T(ra + 1, x, b, a) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exemples de tas binaires | tas1 = make(10, E, E)
pprint(tas1)
tas2 = make(120, tas1, E)
pprint(tas2)
tas3 = make(150, tas2, E)
pprint(tas3) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On peut vérifier si un tas est vide, ou créer le tas vide. | empty: TasBinaire = E
def is_empty(a: TasBinaire) -> bool:
""" Teste si le tas binaire a est vide ou non."""
if "E" in a:
return True
else:
return False
# plus rapidement
def is_empty(a: TasBinaire) -> bool:
return "E" in a
is_empty(E)
is_empty(tas1), is_empty(tas2), is_empty(tas3) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La fusion est assez naturelle : on procède par récurrence, en joignant deux tas et en continuant la fusion pour les tas plus petits.
On garde la plus petite clé à la racine, pour conserver la propriété tournoi. | def merge(h1: TasBinaire, h2: TasBinaire) -> TasBinaire:
""" Fusionne les deux tas binaires h1 et h2."""
if "E" in h1:
return h2
elif "E" in h2:
return h1
else:
r1, x, a1, b1 = h1["T"]
r2, y, a2, b2 = h2["T"]
if x <= y:
return make(x, a1, merge(b1, h2)... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On peut désormais créer les tas précédemment définis correctement, pour qu'ils soient bien équilibrés : | tas1 = make(10, E, E)
pprint(tas1)
tas2 = merge(tas1, make(120, E, E))
pprint(tas2)
tas3 = merge(make(150, E, E), tas2)
pprint(tas3)
print("Fusion du tas vide et du tas1 suivant")
pprint(tas1)
pprint(merge(E, tas1))
print("Fusion de tas1 et tas2 suivants")
pprint(tas1)
pprint(tas2)
pprint(merge(tas1, tas2))
print(... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On voit que les fusions respectent bien la propriété du tas binaire.
L'insertion correspond à la fusion d'un tas avec une seule clé et du tas courant : | def insert(x: int, h: TasBinaire) -> TasBinaire:
""" Solution naive pour insérer une nouvelle valeur x dans le tas binaire h."""
return merge(T(1, x, E, E), h)
# return merge(make(x, E, E), h) # équivalent | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La lecture de la plus petite clé est triviale : | class Empty(Exception):
pass
def mini(a: TasBinaire) -> int:
""" Calcule le minimum du tas binaire a (première valeur)."""
if "E" in a:
raise Empty
else:
_, x, _, _ = a["T"]
return x | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Et l'extraction n'est pas compliquée : il suffit de fusionner les deux sous-tas, ce qui va produire un tas tournoi avec les clés restantes. | def extract_min(a: TasBinaire) -> Tuple[int, TasBinaire]:
""" Extraie le minimum et renvoie un tas binaire sans cette valeur."""
if "E" in a:
raise Empty
else:
_, x, a, b = a["T"]
return (x, merge(a, b)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Et maintenant pour le tri par tas :
On crée un tas vide,
Dans lequel on insère les valeurs du tableau à trier, une par une,
Puis on déconstruit le tas en extrayant le minimum, un par un, et en les stockant dans un tableau,
Le tableau obtenu est trié dans l'ordre croissant. | def triParTas(a: List[int]) -> List[int]:
""" Tri par tas"""
n = len(a)
tas = E # tas vide
for i in range(n):
tas = insert(a[i], tas)
a2 = [-1] * n # aussi [-1 for i in range(n)]
for i in range(n):
m, t = extract_min(tas)
a2[i] = m
tas = t
return a2 | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Complexité :
L'étape 1. est en $\mathcal{O}(1)$,
L'étape 2. est en $\mathcal{O}(\log n)$ pour chacune des $n$ valeurs,
L'étape 3. est aussi en $\mathcal{O}(\log n)$ pour chacune des $n$ valeurs,
$\implies$ L'algorithme de tri par tas est en $\mathcal{O}(n \log n)$ en temps et en $\mathcal{O}(n)$ en mémoire externe.
U... | triParTas([])
triParTas([10, 3, 4, 1, 2, 7, 8, 5, 9, 6]) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Quelques essais numériques rapides | def isSorted(tableau: List) -> bool:
return tableau == sorted(tableau)
import numpy as np
def randomTableau(n: int) -> List[int]:
return list(np.random.randint(-n*10, n*10, n))
%time isSorted(triParTas([10, 3, 4, 1, 2, 7, 8, 5, 9, 6]*100))
%time isSorted(triParTas(randomTableau(10*100)))
%time isSorted(tri... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On observe que la fonction implémentée a une complexité sur-linéaire, et sous-quadratique. En affichant plus de valeurs, on pourrait reconnaître un profil pseudo-linéaire (ie, $\Theta(n \log(n))$). | import numpy as np
import timeit
valeurs_n = np.logspace(2, 6, num=30, dtype=int)
temps = []
for n in valeurs_n:
code = "triParTas(randomTableau({}))".format(n)
essais = 100 if n < 1e4 else 10
print("- Chronométrons le code", code)
temps_n = timeit.timeit(
code,
number=essais, globals=gl... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Cette première courbe semble linéaire, ou quasi-linéaire.
Pour vérifier que le temps de calcul a vraiment un profil ressemblant à une courbe $cst * n * \log(n)$, une méthode rapide et simple est la suivante :
on affiche $f(n) / n$ (ici en <span style="color: red;">rouge o-</span>), en espérant que son profil ressemble... | plt.figure(figsize=(10, 7))
plt.plot(valeurs_n[15:], np.array(temps[15:]) / valeurs_n[15:], "ro-", label="Temps de calcul / n")
cst = temps[-1] / valeurs_n[-1]
cst = cst / np.log(valeurs_n[-1])
plt.plot(valeurs_n[15:], np.log(valeurs_n[15:]) * cst, "b+:", label="cst * log(n)")
plt.xlabel("Taille n du tableau à trier")
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Là on constate que la courbe $f(n) / n$ ressemble bien à un logarithme.
Bien sûr, tout cela est juste expérimental pour de petites valeurs, cela ne suffit PAS DU TOUT à prouver que $f(n) = \Theta(n \log(n))$.
Exercice 7 : arbre tournoi
Ici je donne une autre implémentation, généralement celle présentée dans les ouvra... | Arbre = List[int]
class ArbreTournoi():
def __init__(self, n: int, a: Arbre):
self.n = n
self.a = a | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Par exemple, l'arbre suivant s'écrit comme suit : | arbre_test = ArbreTournoi(7, [1,2,3,4,5,6,7])
arbre_test2 = ArbreTournoi(6, [2,1,3,4,5,6,-1, -1])
def capacite(an: ArbreTournoi) -> int:
""" Capacité d'un arbre tournoi, taille du tableau a (nb max de valeurs)."""
return len(an.a)
def nb_element(an: ArbreTournoi) -> int:
""" Nombre d'éléments d'un arbre ... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Une et deux descentes à droite, par exemple : | droite(arbre_test, 0)
i, _ = droite(arbre_test, 0)
droite(arbre_test, i) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On parcourt les sous-arbres pour trouver le minimum : | def min_sous_arbre(an: ArbreTournoi, i: int) -> int:
ag = a_gauche(an, i)
ad = a_droite(an, i)
if not ag and not ad:
return float("+inf")
elif ag and not ad:
g, vg = gauche(an, i)
return min(vg, min_sous_arbre(an, g))
elif not ag and ad:
d, vd = droite(an, i)
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Et enfin la solution pour la fonction testant si un arbre binaire est un tas tournoi, qui doit être récursive et descendre dans les deux sous-arbres gauche et droite tant qu'ils existent : | def est_tournoi(an: ArbreTournoi) -> bool:
def depuis(i: int) -> bool:
r, vr = noeud(an, i)
min_v = min_sous_arbre(an, i)
res = vr < min_v
if res and a_gauche(an, i):
g, vg = gauche(an, i)
res = depuis(g)
if res and a_droite(an, i):
d, vd =... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 8 : parent, fils_gauche et fils_droit | def parent(an: ArbreTournoi, i: int) -> Tuple[int, int]:
return noeud(an, ((i - 1) // 2))
print("arbre_test: n = {}, a = {}".format(arbre_test.n, arbre_test.a))
print(noeud(arbre_test, 1))
print(parent(arbre_test, 1))
print(noeud(arbre_test, 2))
print(parent(arbre_test, 2))
print(noeud(arbre_test, 4))
print(pare... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 9 : echange | def echange(a: List[Any], i: int, j: int) -> None:
a[i], a[j] = a[j], a[i] # very Pythonic
"""
vi, vj = a[i], a[j]
a[i] = vj
a[j] = vi
"""
"""
tmp = a[i]
a[i] = a[j]
a[j] = tmp
""" | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 10 : insertion
Si besoin, en insérant un élément dans un tableau déjà plein, on doit doubler sa capacité. Ce n'est pas compliqué : d'abord on double le tableau, puis on fait l'insertion normale. | def double_capacite(an: ArbreTournoi) -> ArbreTournoi:
c = capacite(an)
a2 = [-1] * (2*c) # [-1 for _ in range(2*c)]
for i in range(an.n):
a2[i] = an.a[i]
return ArbreTournoi(an.n, a2) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
L'opération élémentaire s'appelle une "percolation haute" : pour rétablir si nécessaire la propriété d'ordre du tas binaire : tant que x n'est pas la racine de l'arbre et que x est strictement inférieur (tas min) à son père on échange les positions entre x et son père. | def percolation_haute(an: ArbreTournoi, i: int) -> None:
p, _ = parent(an, i)
while valeur(an, p) > valeur(an, i):
echange(an.a, i, p)
i = p
p, _ = parent(an, i) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Maintenant, l'insertion a proprement dite : | def insertion(an: ArbreTournoi, x: int) -> ArbreTournoi:
n, c = an.n, capacite(an)
if n == c:
an2 = double_capacite(an)
return insertion(an2, x)
else:
an2 = ArbreTournoi(n + 1, an.a[:]) # tableau[:] fait une copie
an2.a[n] = x # ajoute la valeur x à la fin
percolatio... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 11 : creation
La sémantique de cette fonction est de créer un tas min à partir d'un tableau de valeur. | def creation(a: List[int]) -> ArbreTournoi:
n = len(a)
a_vide = [-1] * n
an = ArbreTournoi(0, a_vide)
for i in range(n):
an = insertion(an, a[i])
return an
arbre_test3 = creation([20, 1, 3, 5, 7])
print("arbre_test3: n = {}, a = {}".format(arbre_test3.n, arbre_test3.a)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Notez que cet arbre est bien tournoi, mais n'est pas trié. | print("Est tournoi ?", est_tournoi(arbre_test3))
print("Est trié ?", arbre_test3.a == sorted(arbre_test3.a)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 12 : diminue_clef
On peut augmenter ou diminuer la priorité (la clé) d'un nœud mais il faut ensuite satisfaire la contrainte d'ordre. Si l'on augmente la clé on fera donc une percolation-haute à partir de notre nœud et si l'on diminue la clé on fera un percolation-basse.
Faites le vous-même.
Exercice 13 : ex... | def indice_min_fils(an: ArbreTournoi, i: int) -> int:
g = i
d = i
if a_gauche(an, i):
g, _ = gauche(an, i)
if a_droite(an, i):
d, _ = droite(an, i)
if valeur(an, g) < valeur(an, d):
return g
else:
return d | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La percolation basse n'est pas trop compliquée : | def percolation_basse(an: ArbreTournoi, i: int) -> None:
f = indice_min_fils(an, i)
while valeur(an, f) < valeur(an, i):
echange(an.a, i, f)
i = f
f = indice_min_fils(an, i) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Enfin l'extraction du minimum est facile. | def extraire_min(an: ArbreTournoi) -> Tuple[int, ArbreTournoi]:
an2 = ArbreTournoi(an.n, an.a[:]) # copie !
if a_gauche(an2, 0):
m = an2.a[0] # racine
an2.n = an2.n - 1 # on enlève un élément
echange(an2.a, 0, an2.n) # on place la racine à la fin, à un endroit désormais inutilisé
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Et pour un exemple : | a = creation([20, 1, 3, 5, 7])
print("a: n = {}, a = {}".format(a.n, a.a))
m, a = extraire_min(a) # m = 1
print("m = {}, et a: n = {}, a = {}".format(m, a.n, a.a))
m, a = extraire_min(a) # m = 3
print("m = {}, et a: n = {}, a = {}".format(m, a.n, a.a))
m, a = extraire_min(a) # m = 5
print("m = {}, et a: n = {}, a... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Remarquez comment le redimensionement du tableau n'arrive qu'à la fin.
Exercice 14 : tri par tas
La meilleure façon de vérifier notre implémentation est d'implémenter le tri par tas :
on construit un tas depuis la liste de valeur,
on extrait le minimum successivement. | def triParTas2(a: List[int]) -> List[int]:
n = len(a)
avide = [-1] * n
an = creation(a) # tas contenant les valeurs de a, bien placées
for i in range(n):
m, an2 = extraire_min(an)
avide[i] = m # minimum du tas an, placé en ième position
an = an2 # nouveau tas avec une vale... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Union-Find
Exercice 15 : Union-Find avec tableaux
Version simple avec des tableaux simples. | Representant = Union[None, int]
# Representant = Optional[int]
UnionFind = List[Representant] | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
En OCaml, on pourrait écrire ces types :
ocaml
type representant = Aucun | Element of int;; (* [int option] pourrait suffire *)
type unionfind = representant array;; | def create_uf(n: int) -> UnionFind:
return [None] * n
def makeset(uf: UnionFind, i: int) -> None:
if len(uf) < i:
uf = uf + [None] * (i - len(uf))
if uf[i] is None:
uf[i] = i
else:
raise ValueError("makeset avec uf = {} et i = {} : impossible d'ajouter i car déja présent".format... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
L'union est assez rapide aussi : | def union(uf: UnionFind, i: int, j: int) -> None:
n = len(uf)
if uf[i] is None or uf[j] is None:
raise ValueErrorrror("Élement i = {} ou j = {} absent de l'UnionFind uf = {}".format(i, j, uf))
for k in range(n):
# tous les éléments dont le représentant est j vont avoir comme représentant i
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La recherche est aussi très facile, il suffit de donner la valeur stockée en case i : | def find(uf: UnionFind, i: int) -> int:
if uf[i] is None:
raise ValueError("Élement i = {} absent de l'UnionFind uf = {}".format(i, uf))
else:
return uf[i] | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Tests : | uf_test = create_uf(6)
print("UnionFind uf vide = {}".format(uf_test))
for i in range(0, 5+1):
makeset(uf_test, i)
print("UnionFind uf rempli par i=0..5 = {}".format(uf_test))
print("find(uf_test, 5) =", find(uf_test, 5))
union(uf_test, 0, 1)
print("Union de 0 et 1 dans uf, désormais uf = {}".format(uf_test))
un... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 16 : Union-Find avec forêts
Version avancée avec des forêts. | aucun = False
racine = True
Position = Union[bool, int]
# malheureusement, Python va calculer ce type comme étant int,
# et n'affichera pas ça comme Position ou Union[bool, int],
# car bool est un sous type de int
UnionFindForest = List[Position] | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Créer une union-find vide revient à créer un tableau avec chaque élément n'ayant pas de représentant, donc valant aucun. | def create_uf(n: int) -> UnionFindForest:
return [aucun] * n | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Rajouter un singleton ${i}$ dans l'union-find revient à mettre la case i du tableau à racine : | def makeset(uf: UnionFindForest, i: int) -> None:
if uf[i] == aucun:
uf[i] = racine # i devient son propre représentant
else:
raise ValueError("Élément i = {} déjà présent dans l'UnionFindForest uf = {}".format(i, uf)) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
La recherche est un peu plus compliquée et on propose une première optimisation, qui va servir à "aplatir" la forêt. | def find(uf: UnionFindForest, i: int) -> int:
uf_i = uf[i]
if uf[i] == aucun:
raise ValueError("Élément i = {} absent de l'UnionFindForest uf = {}".format(i, uf))
elif uf[i] == racine: # i est son propre représentant
return i
else:
j = uf[i] # représentant courant de i
... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Pour l'union, on fait ici le choix arbitraire de préférer la racine de i, on devrait préférer celle de l'arbre le plus petit pour "écraser" la forêt. Cf. [Papadimitriou] ou [Cormen] (ou Wikipédia). | def union(uf: UnionFindForest, i: int, j: int) -> None:
if uf[i] == aucun or uf[j] == aucun:
raise ValueError("Élément i = {} ou j = {} absent de l'UnionFindForest uf = {}".format(i, j, uf))
else:
r_i = find(uf, i)
uf[r_i] = j
# c'est un des choix possibles, on peut faire l'inver... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
On vérfie avec le même test que pour la première implémentation : | uf_test = create_uf(6)
print("UnionFindForest uf vide = {}".format(uf_test))
for i in range(0, 5+1):
makeset(uf_test, i)
print("UnionFindForest uf rempli par i=0..5 = {}".format(uf_test))
print("find(uf_test, 5) =", find(uf_test, 5))
union(uf_test, 0, 1)
print("Union de 0 et 1 dans uf, désormais uf = {}".format(u... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Exercice 17 : Bonus & discussions
En classe.
Je recommande aussi la lecture de ce document (en anglais), si tout ça vous intéresse et si vous envisagez d'en faire un développement. Ce document contient notamment une analyse bien propre de la complexité amortie de l'opération Find pour l'algorithme optimisé, qui donne u... | from typing import Optional
Sommet = int
Poids = int
AreteMatrix = Optional[Poids]
GrapheMatrix = List[List[AreteMatrix]]
Destination = Tuple[Sommet, Poids]
GrapheList = List[List[Destination]] # liste d'adjacence
def taille_GrapheMatrix(g: GrapheMatrix) -> int:
n = len(g)
assert all([ len(g[i]) == n for i i... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Il est facile d'obtenir la liste d'arête, représentées comme un triplet (i, j, p) si l'arête $i \arrow j$ de poids $p$ est présente dans le graphe.
Par exemple avec les graphes représentés par listes d'adjancences : | Arete = Tuple[Sommet, Sommet, Poids]
def liste_aretes_GrapheList(g: GrapheList) -> List[Arete]:
n = taille_GrapheList(g)
resultat = [
(i, j, p)
for i in range(n)
for (j, p) in g[i]
]
return resultat
graphe_test: GrapheList = [
[(1, 11), (2, 2), (3, 1)],
[(2, 7)],
[]... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
L'algorithme de Kruskal a besoin de trier les arêtes selon leur poids, par ordre croissant, et cela se fait facilement avec le fonction sorted de la libraire standard, à laquelle on donne un argument (optionnel) key qui est (ici) une fonction extrayant le poids p du triplet (i, j, p). | aretes = liste_aretes_GrapheList(graphe_test)
sorted(aretes,
key = lambda a: a[2]
) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Algorithme de Kruskal
Je ne redonne pas d'explications ici, allez voir Wikipédia ou un livre d'algorithmique de référence ([Cormen] ou [Beauquier, Berstel, Chrétienne] par exemple).
Voir aussi cette visualisation, et cette autre implémentation en Python (donnée pour le cours d'ALGO1 en L3SIF en 2019).
"L'algorithme de... | def kruskal(g: GrapheList) -> List[Arete]:
aretes = liste_aretes_GrapheList(g)
aretes = sorted(aretes,
key = lambda a: a[2]
)
n = taille_GrapheList(g)
uf = create_uf(n)
for i in range(n):
makeset(uf, i)
# uf contient chaque sommet dans des singletons
resultat = [] # list... | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Cet algorithme donne bien un arbre couvrant, il faudrait vérifier sa minimalité. | graphe_test
kruskal(graphe_test) | agreg/TP_Programmation_2017-18/TP3__Python.ipynb | Naereen/notebooks | mit |
Evaluation des modèles pour l'extraction supercritique
L'extraction supercritique est de plus en plus utilisée afin de retirer des matières organiques de différents liquides ou matrices solides. Cela est dû au fait que les fluides supercritiques ont des avantages non négligeables par rapport aux autres solvants, ils on... | import numpy as np
from scipy import integrate
from matplotlib.pylab import * | Modelo de impregnacion/modelo2/Activité 10_Viernes2-checkpoint.ipynb | pysg/pyther | mit |
Ejemplo 2 funciona | import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
def vdp1(t, y):
return np.array([y[1], (1 - y[0]**2)*y[1] - y[0]])
t0, t1 = 0, 20 # start and end
t = np.linspace(t0, t1, 100) # the points of evaluation of solution
y0 = [2, 0] # initial value
y = np.... | Modelo de impregnacion/modelo2/Activité 10_Viernes2-checkpoint.ipynb | pysg/pyther | mit |
Fonction
Modelo Reverchon
Mathematical Modeling of Supercritical Extraction of Sage Oil | P = 9 #MPa
T = 323 # K
Q = 8.83 #g/min
e = 0.4
rho = 285 #kg/m3
miu = 2.31e-5 # Pa*s
dp = 0.75e-3 # m
Dl = 0.24e-5 #m2/s
De = 8.48e-12 # m2/s
Di = 6e-13
u = 0.455e-3 #m/s
kf = 1.91e-5 #m/s
de = 0.06 # m
W = 0.160 # kg
kp = 0.2
r = 0.31 #m
n = 10
V = 12
#C = kp * qE
C = 0.1
qE = C / kp
Cn = 0.05
Cm = 0.02
t = np.l... | Modelo de impregnacion/modelo2/Activité 10_Viernes2-checkpoint.ipynb | pysg/pyther | mit |
Trabajo futuro
Realizar modificaciones de los parametros para observar cómo afectan al comportamiento del modelo.
Realizar un ejemplo de optimización de parámetros utilizando el modelo de Reverchon.
Referencias
[1] E. Reverchon, Mathematical modelling of supercritical extraction of sage oil, AIChE J. 42 (1996) 1765–1... |
#Datos experimentales
x_data = np.linspace(0,9,10)
y_data = np.array([0.000,0.416,0.489,0.595,0.506,0.493,0.458,0.394,0.335,0.309])
def f(y, t, k):
""" sistema de ecuaciones diferenciales ordinarias """
return (-k[0]*y[0], k[0]*y[0]-k[1]*y[1], k[1]*y[1])
def my_ls_func(x,teta):
f2 = lambda y, t: f(y, t... | Modelo de impregnacion/modelo2/Activité 10_Viernes2-checkpoint.ipynb | pysg/pyther | mit |
Let's search for galaxies with M$\star$ > 3 $\times$ 10$^{11}$ M$\odot$.
To specify our search parameter, M$_\star$, we must know the database table and name of the parameter. In this case, MaNGA uses the NASA-Sloan Atlas (NSA) for target selection so we will use the Sersic profile determination for stellar mass, which... | myquery1 = 'nsa.sersic_mass > 3e11'
# or
myquery1 = 'nsa.sersic_logmass > 11.47'
q1 = Query(searchfilter=myquery1)
r1 = q1.run() | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
Running the query produces a Results object (r1): | # show results
r1.results | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
We will learn how to use the features of our Results object a little bit later, but first let's revise our search to see how more complex search queries work.
Multiple Search Criteria
Let's add to our search to find only galaxies with a redshift less than 0.1.
Redshift is the z parameter and is also in the nsa table, s... | myquery2 = 'nsa.sersic_mass > 3e11 AND nsa.z < 0.1'
q2 = Query(searchfilter=myquery2)
r2 = q2.run()
r2.results | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
Compound Search Statements
We were hoping for a few more than 3 galaxies, so let's try to increase our search by broadening the criteria to also include galaxies with 127 fiber IFUs and a b/a ratio of at least 0.95.
To find 127 fiber IFUs, we'll use the name parameter of the ifu table, which means the full search param... | myquery3 = '(nsa.sersic_mass > 3e11 AND nsa.z < 0.1) OR (ifu.name=127* AND nsa.ba90 >= 0.95)'
q3 = Query(searchfilter=myquery3)
r3 = q3.run()
r3.results | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
Design Your Own Search
OK, now it's your turn to try designing a search.
Exercise: Write a search filter that will find galaxies with a redshift less than 0.02 that were observed with the 1901 IFU? | # Enter your search here | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
You should get 8 results:
[NamedTuple(mangaid='1-22438', plate=7992, name='1901', z=0.016383046284318),
NamedTuple(mangaid='1-113520', plate=7815, name='1901', z=0.0167652331292629),
NamedTuple(mangaid='1-113698', plate=8618, name='1901', z=0.0167444702237844),
NamedTuple(mangaid='1-134004', plate=8486, name='1901',... | # You might have to do an svn update to get this to work (otherwise try the next cell)
q = Query()
q.get_available_params()
# try this if the previous cell didn't return a list of parameters
from marvin.api.api import Interaction
from pprint import pprint
url = config.urlmap['api']['getparams']['url']
ii = Interaction... | docs/sphinx/jupyter/my-first-query.ipynb | bretthandrews/marvin | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.