The following [[https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/][webpage]] lists several Jupyter tricks (in particular, it
Cette [[https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/][page web]] (en anglais) recense un certain nombre d'astuces
illustrates many =IPython magic= commands) that should improve your
relatives à l'utilisation de Jupyter (et en particulier des
efficiency (note that this blog post is about two years old so some of
illustrations des nombreuses commandes magiques =IPython magic=) et
the tricks may have been integrated in the default behavior of Jupyter
susceptibles d'améliorer votre efficacité (notez bien que ce billet a
now).
plus de deux ans que Jupyter évoluant très rapidement, certaines de
** 1.1 Creating or importing a notebook
ces astuces ou de ces modules complémentaires font maintenant partie
Using the Jupyter environment we deployed for this MOOC will allow to
du comportement par défaut des versions les plus récentes de Jupyter).
easily access any file from your default GitLab project. There are
** 1.1 Création ou import d'un notebook
situations however where you may want to play with other notebooks.
L'environnement Jupyter que nous avons déployé dans le cadre de ce
- Adding a brand new notebook in a given directory :: Simply follow
MOOC vous permettra d'accéder très simplement à tout fichier (et en
the following steps:
particulier les notebooks des différents exercices que nous avons
1. From the menu: =File -> Open=. You're now in the Jupyter file manager.
créés pour vous) de votre projet gitlab par défaut. Il y a néanmoins
2. Navigate to the directory where you want your notebook to be created.
des situations où vous pouvez vouloir utiliser d'autres notebooks que
3. Then from the top right button: =New -> Notebook: Python 3=.
ceux du MOOC.
4. Give your notebook a name from the menu: =File -> Rename=.
- Créer un notebook tout neuf dans un répertoire donné ::
1. À partir du menu: =File -> Open=. Ceci vous permet d'accéder au
N.B.: If you create a file by doing ~File -> New Notebook ->
gestionnaire de fichiers de Jupyter.
Python 3~, the new notebook will be created in the current
2. Naviguez jusque dans le répertoire dans lequel vous souhaitez
directory. Moving it afterward is possible but a bit cumbersome
créer votre notebook.
(you'll have to go through the Jupyter file manager by following
3. Utilisez le bouton en haut à droite: =New -> Notebook: Python 3=.
the menu =File -> Open=, then select it, =Shut= it =down=, and =Move=
4. Donnez un nom à votre notebook à partir du menu: =File -> Rename=.
and/or =Rename=).
- Importing an already existing notebook :: If your notebook is
N.B.: Si vous créez un notebook à partir du menu ~File -> New
already in your GitLab project, then simply synchronize by using
Notebook -> Python 3~, il sera créé dans le répertoire courant. Le
the =Git pull= button and use the =File -> Open= menu. Otherwise,
déplacer après coup et un peu pénible. Il vous faudra aller dans
imagine, you want to import the [[https://app-learninglab.inria.fr/gitlab/moocrr-session1/moocrr-reproducibility-study/blob/master/src/Python3/challenger.ipynb][following notebook]] from someone
le gestionnaire de fichiers de Jupyter (menu =File -> Open=),
else's repository to re-execute it.
sélectionner le notebook, l'arrêter (=Shut =down=), puis le déplacer
1. Download the file on your computer. E.g., for this [[https://app-learninglab.inria.fr/gitlab/moocrr-session1/moocrr-reproducibility-study/blob/master/src/Python3/challenger.ipynb][GitLab hosted
(=Move=) et/ou le renommer (=Rename=).
notebook]], click on =Open raw= (a small =</>= within a document icon)
- Importer un notebook déja existant :: Si le notebook qui vous
and save (=Ctrl-S= on most browsers) the content (a long Json text
intéresse est déjà dans votre projet GitLab, il vous suffit de
file).
synchroniser la copie de votre Jupyter à l'aide du bouton =Git
2. Open the Jupyter file manager from the menu =File -> Open= and
pull= et d'utiliser le menu =File -> Open=. Dans le cas contraire,
navigate to the directory where you want to upload your notebook.
par exemple si souhaitez importer cet [[https://app-learninglab.inria.fr/gitlab/moocrr-session1/moocrr-reproducibility-study/blob/master/src/Python3/challenger.ipynb][autre notebook]] rédigé par
3. Then from the top right button, =Upload= the previously downloaded
quelqu'un d'autre, procédez de la façon suivante:
notebook and confirm the upload.
1. Télé-chargez le fichier sur votre répertoire. Pour ce [[https://app-learninglab.inria.fr/gitlab/moocrr-session1/moocrr-reproducibility-study/blob/master/src/Python3/challenger.ipynb][Notebook
4. Open the freshly uploaded notebook through the Jupyter file
hébergé sur un gitLab]], cliquez sur =Open raw= (l'icone avec
manager.
un petit =</>= ) et sauvegardez (=Ctrl-S= sur la plupart des
** 1.2 Running R and Python in the same notebook
navigateurs) son contenu (un long fichier texte au format JSON).
=rpy2= package allows to use both languages in the same notebook by:
2. Ouvrez le gestionnaire de fichiers de Jupyter via le menu =File ->
1. Loading =rpy2=:
Open= et naviguez jusqu'au répertoire où vous souhaitez déposer
votre notebook.
3. Utilisez le bouton en haut à droite =Upload= pour transférer le
document de votre ordinateur vers le serveur Jupyter et confirmez
l'upload.
4. Vous pouvez maintenant ouvrir le notebook fraîchement récupéré
à l'aide du navigateur de fichiers de Jupyter et réexécuter le
code correspondant.
** 1.2 Exécuter du code R et du code Python dans le même notebook
C'était impossible avec les premières versions de Jupyter mais c'est
désormais très facile grâce à la bibliothèque python =rpy2=. Il vous
faut tout d'abord ouvrir un notebook python.
1. Chargez la bibliothèque =rpy2=. Le =%load_ext= est une commande magique
jupyter qui charge cette bibliothèque et vous donne accès à de
nouvelles commandes magiques.
#+begin_src python :results output :exports both
#+begin_src python :results output :exports both
%load_ext rpy2.ipython
%load_ext rpy2.ipython
#+end_src
#+end_src
2. Using the =%R= Ipython magic:
2. Utilisez la (nouvellement activée) commande magique =%R=:
#+begin_src python :results output :exports both
#+begin_src python :results output :exports both
%%R
%%R
summary(cars)
summary(cars)
#+end_src
#+end_src
Python objects can then even be passed to R as follows (assuming =df=
Les objets Python peuvent même être passé à R de la façon suivante
is a pandas dataframe):
(ici, on suppose que =df= est une dataframe pandas):
#+begin_src python :results output :exports both
#+begin_src python :results output :exports both
%%R -i df
%%R -i df
plot(df)
plot(df)
#+end_src
#+end_src
Note that this =%%R= notation indicates that R should be used for the whole cell but
Cette notation =%%R= indique à Python et à Jupyter et que le langage R
an other possibility is to use =%R= to have a single line of R within a
doit être utilisé pour évaluer l'ensemble de la cellule. En interne,
python cell.
python (=rpy2=) maintient une session R, lui passe le code de la cellule
** 1.3 Other languages
et récupère le résultat. Jupyter fait alors le nécessaire pour
Jupyter is not limited to Pytyhon and R. Many other languages are available:
l'afficher correctement. Il est également possible d'utiliser =%R= pour
[[https://github.com/jupyter/jupyter/wiki/Jupyter-kernels][https://github.com/jupyter/jupyter/wiki/Jupyter-kernels]], including
avoir une seule ligne de R au sein d'une cellule python.
non-free languages like SAS, Mathematica, Matlab... Note that the maturity of these kernels differs widely.
** 1.3 Autres langages que Python et R
Jupyter tire son nom des langages Julia, Python, et R. Il ne se limite
None of these other languages have been deployed in the context of our
donc pas aux langages Python et R. De nombreux autres langages de
MOOC but you may want to read the next sections to learn how
programmation sont disponibles:
to set up your own Jupyter on your computer and benefit from these extensions.
[[https://github.com/jupyter/jupyter/wiki/Jupyter-kernels][https://github.com/jupyter/jupyter/wiki/Jupyter-kernels]], et en
particulier des langages non libres comme SAS, Mathematica,
Since the question was asked several times, if you really need to stay
Matlab... Notez que la maturité de ces noyaux est très variables.
with SAS, you should know that SAS can be used within Jupyter using
either the [[https://sassoftware.github.io/sas_kernel/][Python SASKernel]] or the [[https://sassoftware.github.io/saspy/][Python SASPy]] package (step by step
Nous n'avons déployé aucun de ces autres langages dans le cadre du
explanations about this are given [[https://gitlab.inria.fr/learninglab/mooc-rr/mooc-rr-ressources/blob/master/documents/tuto_jupyter_windows/tuto_jupyter_windows.md][here]]).
MOOC mais nous vous invitons à lire les sections suivantes pour
apprendre à déployer votre propre instance de jupyter et activer
Since proprietary software such as SAS cannot easily be inspected, we discourage its use as it hinders reproducibility by
certaines de ses extensions.
essence. But perfection does not exist anyway and using Jupyter
literate programming approach allied with systematic control version
Puisque la question est posée de façon récurrente, si vous avez besoin
and environment control will certainly help anyway.
d'utiliser le langage SAS plutôt que le langage R, il y a deux façons
d'utiliser SAS avec Jupyter: soit avec le noyau [[https://sassoftware.github.io/sas_kernel/][Python SASKernel]], soit
* 2 Installing and configuring Jupyter on your computer
avec la bibliothèque [[https://sassoftware.github.io/saspy/][Python SASPy]] (des explications détaillés sont
In this section, we explain how to set up a Jupyter environment on
your own computer similar to the one deployed for this MOOC.
Malgré la qualité et la stabilité de ce langage, SAS n'en reste pas
Note that Jupyter notebooks are only a small part of the picture and
moins un langage propriétaire, ce qui rend l'inspection de ses
that Jupyter is now part of a bigger project: [[https://blog.jupyter.org/jupyterlab-is-ready-for-users-5a6f039b8906][JupyterLab]], which allows
procédures très difficile et limite la réutilisation des procédures
you to mix various components (including notebooks) in your
produites par d'autres chercheurs. Nous le déconseillons donc dans un
browser. In the context of this MOOC, our time frame was too short to
objectif de recherche reproductible mais il faut aussi savoir ne pas
benefit from JupyterLab which was still under active development. You may, however, prefer JupyterLab when doing an installation on your own computer.
être dogmatique. La perfection n'existe pas ;) et, même en utilisant
SAS, l'utilisation de la programmation lettrée de Jupyter et d'un
** 2.1 Installing Jupyter
contrôle de version (avec gitlab) et d'environnement (avec docker par
Follow these instructions if you wish to have a Jupyter environment on
exemple) se révélera très certainement précieux.
your own computer similar to the one we set up for this MOOC.
* 2 Installation et configuration de Jupyter sur votre ordinateur
Dans cette section, nous expliquons comment installer, sur votre
First, download and install the [[https://conda.io/miniconda.html][latest version of Miniconda]]. We use
ordinateur, un environnement Jupyter similaire à celui que nous avons
Miniconda version =4.5.4= and Python version =3.6= on our server.
déployé pour ce MOOC.
Miniconda is a light version of Anaconda, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science.
Notez que les notebooks Jupyter ne constituent qu'une petite partie de
l'écosystème et que Jupyter fait maintenant partie d'un projet plus
Then download the [[https://gist.github.com/brospars/4671d9013f0d99e1c961482dab533c57][mooc_rr environment file]] and create the environment using conda:
large, [[https://blog.jupyter.org/jupyterlab-is-ready-for-users-5a6f039b8906][JupyterLab]], qui permet d'assembler différents composants (dont
les notebooks) dans votre navigateur. Dans le cadre de ce MOOC, nous
avons manqué de temps pour bénéficier de tout JupyterLab qui était
toujours en développement actif. À l'heure actuelle, vous pouvez
cependant avoir intérêt à installer tout JupyterLab sur votre ordinateur.
** 2.1 Installation de Jupyter
Ces instructions permettent d'obtenir sur votre ordinateur un
environnement Jupyter similaire à celui que nous avons déployé dans le
cadre du MOOC.
Téléchargez et installez la [[https://conda.io/miniconda.html][dernière version de Miniconda]]. Sur notre
serveur, nous utilisons la version =4.5.4= de Miniconda et la version
=3.6= de Python.
Miniconda est une version légère d'Anaconda, une suite logicielle
incluant Python, Jupyter, R ainsi que les bibliothèques les plus
couramment utilisées en calcul scientifique et en science des données.
Téléchargez ensuite le [[https://gist.github.com/brospars/4671d9013f0d99e1c961482dab533c57][fichier d'environnement =mooc_rr= ]] et déployez
votre environnement à l'aide de conda:
#+begin_src shell :results output :exports both
#+begin_src shell :results output :exports both
conda env create -f environment.yml
conda env create -f environment.yml
...
@@ -125,95 +159,105 @@ source activate mooc_rr
...
@@ -125,95 +159,105 @@ source activate mooc_rr
# Linux, MacOS and Windows: launch the notebook
# Linux, MacOS and Windows: launch the notebook
jupyter notebook
jupyter notebook
#+end_src
#+end_src
** 2.2 Making sure Jupyter allows you to use R
** 2.2 S'assurer que Jupyter vous permet d'utiliser R
The environment described in the last section should include R, but if
Si vous avez installé l'environnement de la façon décrite dans la
you proceeded otherwise and only have Python available in Jupyter, you
section précédente, vous devriez déjà avoir R à votre disposition et
may want to read the following section.
vous n'avez donc rien à faire. Mais si vous avez procédé différemment
exécutées en incrémentant leur "indice". C'est une très bonne
propriété d'un point de vue reproductibilité mais il se peut, selon
For those who use [[https://blog.jupyter.org/jupyterlab-is-ready-for-users-5a6f039b8906][JupyterLab]] rather than the plain Jupyter, a specific [[https://github.com/jupyterlab/jupyterlab-git][JupyterLab git plugin]] has been developed to offer a nice version control experience.
votre usage, que cela s'avère peu pratique du point de vue du suivi de
version. Certaines personnes ont donc développé des [[https://gist.github.com/pbugnion/ea2797393033b54674af][git hooks
spécifiques]] permettant d'ignorer ces numéros lorsque l'on committe des
notebooks Jupyter. Il y au une longue discussion à ce sujet sur
[[https://stackoverflow.com/questions/18734739/using-ipython-notebooks-under-version-control][StackOverflow]] qui détaille différentes options.
Enfin, pour ceux qui utilisent [[https://blog.jupyter.org/jupyterlab-is-ready-for-users-5a6f039b8906][JupyterLab]] plutôt que le Jupyter de
base, un [[https://github.com/jupyterlab/jupyterlab-git][plugin git pour JupyterLab]] a été développé et offre des
fonctionnalités de suivi de version dignes d'un IDE classique.