- [[#22-making-sure-jupyter-allows-you-to-use-r][2.2 Making sure Jupyter allows you to use R]]
- [[#23-additional-tips][2.3 Additional tips]]
* 1 Jupyter tips and tricks
The following [[https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/][webpage]] lists several Jupyter tricks (in particular, it
illustrates many =IPython magic= commands) that should improve your
efficiency (note that this blog post is about two years old so some of
the tricks may have been integrated in the default behavior of Jupyter
now).
** 1.1 Creating or importing a notebook
Using the Jupyter environment we deployed for this MOOC will allow to
easily access any file from your default GitLab project. There are
situations however where you may want to play with other notebooks.
- Adding a brand new notebook in a given directory :: Simply follow
the following steps:
1. From the menu: =File -> Open=. You're now in the Jupyter file manager.
2. Navigate to the directory where you want your notebook to be created.
3. Then from the top right button: =New -> Notebook: Python 3=.
4. Give your notebook a name from the menu: =File -> Rename=.
N.B.: If you create a file by doing ~File -> New Notebook ->
Python 3~, the new notebook will be created in the current
directory. Moving it afterward is possible but a bit cumbersome
(you'll have to go through the Jupyter file manager by following
the menu =File -> Open=, then select it, =Shut= it =down=, and =Move=
and/or =Rename=).
- Importing an already existing notebook :: If your notebook is
already in your GitLab project, then simply synchronize by using
the =Git pull= button and use the =File -> Open= menu. Otherwise,
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
else's repository to re-execute it.
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
notebook]], click on =Open raw= (a small =</>= within a document icon)
and save (=Ctrl-S= on most browsers) the content (a long Json text
file).
2. Open the Jupyter file manager from the menu =File -> Open= and
navigate to the directory where you want to upload your notebook.
3. Then from the top right button, =Upload= the previously downloaded
notebook and confirm the upload.
4. Open the freshly uploaded notebook through the Jupyter file
manager.
** 1.2 Running R and Python in the same notebook
=rpy2= package allows to use both languages in the same notebook by:
1. Loading =rpy2=:
* Table des matières :TOC:
- [[#1-jupyter-trucs-et-astuces][1 Jupyter: Trucs et astuces]]
- [[#11-création-ou-import-dun-notebook][1.1 Création ou import d'un notebook]]
- [[#12-exécuter-du-code-r-et-du-code-python-dans-le-même-notebook][1.2 Exécuter du code R et du code Python dans le même notebook]]
- [[#13-autres-langages-que-python-et-r][1.3 Autres langages que Python et R]]
- [[#2-installation-et-configuration-de-jupyter-sur-votre-ordinateur][2 Installation et configuration de Jupyter sur votre ordinateur]]
- [[#21-installation-de-jupyter][2.1 Installation de Jupyter]]
- [[#22-sassurer-que-jupyter-vous-permet-dutiliser-r][2.2 S'assurer que Jupyter vous permet d'utiliser R]]
Cette [[https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/][page web]] (en anglais) recense un certain nombre d'astuces
relatives à l'utilisation de Jupyter (et en particulier des
illustrations des nombreuses commandes magiques =IPython magic=) et
susceptibles d'améliorer votre efficacité (notez bien que ce billet a
plus de deux ans que Jupyter évoluant très rapidement, certaines de
ces astuces ou de ces modules complémentaires font maintenant partie
du comportement par défaut des versions les plus récentes de Jupyter).
** 1.1 Création ou import d'un notebook
L'environnement Jupyter que nous avons déployé dans le cadre de ce
MOOC vous permettra d'accéder très simplement à tout fichier (et en
particulier les notebooks des différents exercices que nous avons
créés pour vous) de votre projet gitlab par défaut. Il y a néanmoins
des situations où vous pouvez vouloir utiliser d'autres notebooks que
ceux du MOOC.
- Créer un notebook tout neuf dans un répertoire donné ::
1. À partir du menu: =File -> Open=. Ceci vous permet d'accéder au
gestionnaire de fichiers de Jupyter.
2. Naviguez jusque dans le répertoire dans lequel vous souhaitez
créer votre notebook.
3. Utilisez le bouton en haut à droite: =New -> Notebook: Python 3=.
4. Donnez un nom à votre notebook à partir du menu: =File -> Rename=.
N.B.: Si vous créez un notebook à partir du menu ~File -> New
Notebook -> Python 3~, il sera créé dans le répertoire courant. Le
déplacer après coup et un peu pénible. Il vous faudra aller dans
le gestionnaire de fichiers de Jupyter (menu =File -> Open=),
sélectionner le notebook, l'arrêter (=Shut =down=), puis le déplacer
(=Move=) et/ou le renommer (=Rename=).
- Importer un notebook déja existant :: Si le notebook qui vous
intéresse est déjà dans votre projet GitLab, il vous suffit de
synchroniser la copie de votre Jupyter à l'aide du bouton =Git
pull= et d'utiliser le menu =File -> Open=. Dans le cas contraire,
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
quelqu'un d'autre, procédez de la façon suivante:
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
hébergé sur un gitLab]], cliquez sur =Open raw= (l'icone avec
un petit =</>= ) et sauvegardez (=Ctrl-S= sur la plupart des
navigateurs) son contenu (un long fichier texte au format JSON).
2. Ouvrez le gestionnaire de fichiers de Jupyter via le menu =File ->
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
%load_ext rpy2.ipython
#+end_src
2. Using the =%R= Ipython magic:
2. Utilisez la (nouvellement activée) commande magique =%R=:
#+begin_src python :results output :exports both
%%R
summary(cars)
#+end_src
Python objects can then even be passed to R as follows (assuming =df=
is a pandas dataframe):
Les objets Python peuvent même être passé à R de la façon suivante
(ici, on suppose que =df= est une dataframe pandas):
#+begin_src python :results output :exports both
%%R -i df
plot(df)
#+end_src
Note that this =%%R= notation indicates that R should be used for the whole cell but
an other possibility is to use =%R= to have a single line of R within a
python cell.
** 1.3 Other languages
Jupyter is not limited to Pytyhon and R. Many other languages are available:
[[https://github.com/jupyter/jupyter/wiki/Jupyter-kernels][https://github.com/jupyter/jupyter/wiki/Jupyter-kernels]], including
non-free languages like SAS, Mathematica, Matlab... Note that the maturity of these kernels differs widely.
None of these other languages have been deployed in the context of our
MOOC but you may want to read the next sections to learn how
to set up your own Jupyter on your computer and benefit from these extensions.
Since the question was asked several times, if you really need to stay
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
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]]).
Since proprietary software such as SAS cannot easily be inspected, we discourage its use as it hinders reproducibility by
essence. But perfection does not exist anyway and using Jupyter
literate programming approach allied with systematic control version
and environment control will certainly help anyway.
* 2 Installing and configuring Jupyter on your computer
In this section, we explain how to set up a Jupyter environment on
your own computer similar to the one deployed for this MOOC.
Note that Jupyter notebooks are only a small part of the picture and
that Jupyter is now part of a bigger project: [[https://blog.jupyter.org/jupyterlab-is-ready-for-users-5a6f039b8906][JupyterLab]], which allows
you to mix various components (including notebooks) in your
browser. In the context of this MOOC, our time frame was too short to
benefit from JupyterLab which was still under active development. You may, however, prefer JupyterLab when doing an installation on your own computer.
** 2.1 Installing Jupyter
Follow these instructions if you wish to have a Jupyter environment on
your own computer similar to the one we set up for this MOOC.
First, download and install the [[https://conda.io/miniconda.html][latest version of Miniconda]]. We use
Miniconda version =4.5.4= and Python version =3.6= on our server.
Miniconda is a light version of Anaconda, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science.
Then download the [[https://gist.github.com/brospars/4671d9013f0d99e1c961482dab533c57][mooc_rr environment file]] and create the environment using conda:
Cette notation =%%R= indique à Python et à Jupyter et que le langage R
doit être utilisé pour évaluer l'ensemble de la cellule. En interne,
python (=rpy2=) maintient une session R, lui passe le code de la cellule
et récupère le résultat. Jupyter fait alors le nécessaire pour
l'afficher correctement. Il est également possible d'utiliser =%R= pour
avoir une seule ligne de R au sein d'une cellule python.
** 1.3 Autres langages que Python et R
Jupyter tire son nom des langages Julia, Python, et R. Il ne se limite
donc pas aux langages Python et R. De nombreux autres langages de
programmation sont disponibles:
[[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,
Matlab... Notez que la maturité de ces noyaux est très variables.
Nous n'avons déployé aucun de ces autres langages dans le cadre du
MOOC mais nous vous invitons à lire les sections suivantes pour
apprendre à déployer votre propre instance de jupyter et activer
certaines de ses extensions.
Puisque la question est posée de façon récurrente, si vous avez besoin
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
avec la bibliothèque [[https://sassoftware.github.io/saspy/][Python SASPy]] (des explications détaillés sont
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.
*** • Interaction avec GitLab et GitHub
Pour rendre vous simplifier la vie, nous avons rajouté des boutons
=pull/push= dans Jupyter qui vous permettent de synchroniser vos
modifications avec GitLab. Ce développement spécifique pour ce MOOC
s'est inspiré d'une [[https://github.com/Lab41/sunny-side-up][preuve de concept]] précédente mais est vraiment /ad
hoc/. Indépendemment et à peu près au même moment, une autre personne a
développé un [[https://github.com/sat28/githubcommit][Plugin Jupyter assez générique permettant de se
synchroniser avec Gitlab ou Github]]. Si cette fonctionnalité vous
intéresse, c'est donc une piste intéressante à explorer. Sinon,
souvenez vous qu'il est très simple d'insérer une cellule shell dans
Jupyter et dans laquelle vous pouvez facilement insérer des commandes
git. C'est la façon dont nous travaillons en pratique la majorité du
temps.
Ceci étant dit, vous avez certainement remarqué que Jupyter conserve
une trace parfaite de l'ordre dans lequel les cellules ont été
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
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.