Collection d’examples#

Automatisation#

  1. Clone many folders in one row

  2. Collect email addresses from mails in an inbox folder)

Clone many folders in one row

eleves = "project1;project2;..."
root = r"destination"

for el in eleves.split(";"):
    cl = el.lower().replace(".","-")
    fold = os.path.join(root, el)
    if not os.path.exists(fold):
        print("clone", el)
        url = "https://<gitlab>/<group>/{0}.git".format(cl)
        git_clone(  fold, url,user=user,password=password, init=False,fLOG=print)

(entrée originale : git_helper.py:docstring of ensae_teaching_cs.automation_students.git_helper.git_clone, line 32)

Collect email addresses from mails in an inbox folder)

from ensae_teaching_cs.automation_students import grab_addresses
from pymmails import MailBoxImap

user = "xavier.dupre"
pwd = "***"
server = "imap.gmail.com"
mailfolder = ["ensae/ENSAE_2016", "ensae/ensae_interro_2015"]
date = "1-Dec-2015"

box = MailBoxImap(user, pwd, server, ssl=True, fLOG=fLOG)
box.login()
emails = grab_addresses(box, mailfolder, date, fLOG=fLOG)
box.logout()

(entrée originale : mail_helper.py:docstring of ensae_teaching_cs.automation_students.mail_helper.grab_addresses, line 13)

Computer Science, Machine Learning#

  1. algorithme de Arrow-Hurwicz

  2. opérations avec numpy.matrix

  3. solver.cp de cvxopt

algorithme de Arrow-Hurwicz

On résoud le problème suivant avec l’algorithme de Arrow-Hurwicz.

\left\{ \begin{array}{l} \min_{x,y} \left \{ x^2 + y^2 - xy + y \right \}  \\
sous \; contrainte \; x + 2y = 1 \end{array}\right.

Qui s’implémente à l’aide de la fonction suivante :

import random
from ensae_teaching_cs.td_1a.optimisation_contrainte import Arrow_Hurwicz

def f_df(X) :
    x,y = X
    f = x**2 + y**2 - x*y + y
    d = [ x*2 - y, y*2 - x + 1  ]
    return f, d

def contrainte(X) :
    x,y = X
    f = x+2*y-1
    d = [ 1,2]
    return f, d

X0  = [ random.random(),random.random() ]
p0  = random.random()
sol = Arrow_Hurwicz(f_df, contrainte, X0, p0, do_print=False)

(entrée originale : optimisation_contrainte.py:docstring of ensae_teaching_cs.td_1a.optimisation_contrainte.exercice_particulier2, line 1)

opérations avec numpy.matrix

Voici quelques écritures classiques avec le module numpy.

import numpy as np
mat = np.matrix ( [[1,2],[3,4]] ) # crée une matrice 2*2
s   = mat.shape           # égale à (nombre de lignes, nombre de colonnes)
l   = mat [0,:]           # retourne la première ligne
c   = mat [:,0]           # retourne la première colonne
iv  = mat.I               # inverse la matrice
mat [:,0] = mat [:,1]     # la première ligne est égale à la seconde
o   = np.ones ( (10,10) ) # crée un matrice de 1 10x10
d   = np.diag (mat)       # extrait la diagonale d'une matrice
dd  = np.matrix (d)       # transforme d en matrice
t   = mat.transpose ()    # obtient la transposée
e   = mat [0,0]           # obtient de première élément
k   = mat * mat           # produit matriciel
k   = mat @ mat           # produit matriciel à partir de Python 3.5
m   = mat * 4             # multiplie la matrice par 4
mx  = np.max (mat [0,:])  # obtient le maximum de la première ligne
s   = np.sum (mat [0,:])  # somme de la première ligne


mat = np.diagflat(np.ones((1,4)))
print(mat)  # matrice diagonale
t   =  mat == 0
print(t)    # matrice de booléens
mat [ mat == 0 ] = 4
print(mat)  # ...
print(iv)   # ...

(entrée originale : numpys.py:docstring of ensae_teaching_cs.td_1a.numpys.numpy_matrix2list, line 6)

solver.cp de cvxopt

On résoud le problème suivant avec cvxopt :

\left\{ \begin{array}{l} \min_{x,y} \left \{ x^2 + y^2 - xy + y \right \}
\\ sous \; contrainte \; x + 2y = 1 \end{array}\right.

Qui s’implémente à l’aide de la fonction suivante :

def f_df_H(x=None,z=None) :
    if x is None :
        # cas 1
        x0 = matrix ( [[ random.random(), random.random() ]])
        return 0,x0
    f = x[0]**2 + x[1]**2 - x[0]*x[1] + x[1]
    d = matrix ( [ x[0]*2 - x[1], x[1]*2 - x[0] + 1 ] ).T
    h = matrix ( [ [ 2.0, -1.0], [-1.0, 2.0] ])
    if z is None:
        # cas 2
        return  f, d
    else :
        # cas 3
        return f, d, h

solvers.options['show_progress'] = False
A = matrix([ [ 1.0, 2.0 ] ]).trans()
b = matrix ( [[ 1.0] ] )
sol = solvers.cp ( f_df_H, A = A, b = b)

(entrée originale : optimisation_contrainte.py:docstring of ensae_teaching_cs.td_1a.optimisation_contrainte.exercice_particulier1, line 1)

  1. Enregistrer plusieurs DataFrame dans un seul fichier Excel ?

Enregistrer plusieurs DataFrame dans un seul fichier Excel ?

Le code suivant enregistre deux DataFrame dans un seul fichier Excel.

import pandas
writer = pandas.ExcelWriter('example.xlsx')
df1.to_excel(writer, 'Data 0')
df2.to_excel(writer, 'Data 1')
write.save()

Ou en utilisant cette fonction :

dfs2excel( { 'Data 0':df1, 'Data 1':df2 }, "example.xlsx" )

(entrée originale : serialization.py:docstring of ensae_teaching_cs.td_2a.serialization.dfs2excel, line 7)

Geek#

  1. Convertir le notebook en cours au format HTML

Convertir le notebook en cours au format HTML

C’est l’objet du notebook 2A.soft - Convert a notebook into a document.

(entrée originale : faq_jupyter.py:docstring of ensae_teaching_cs.faq.faq_jupyter.jupyter_convert_notebooks, line 1)