From 7007938f952874cfcccfdf2ea05abffd12c4d9bb Mon Sep 17 00:00:00 2001 From: Eva Rifa Date: Thu, 1 Feb 2024 10:54:01 +0100 Subject: [PATCH 1/4] Add reticulate vignette --- RUserMeeting_scripts/reticulate_vignette.Rmd | 120 +++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 RUserMeeting_scripts/reticulate_vignette.Rmd diff --git a/RUserMeeting_scripts/reticulate_vignette.Rmd b/RUserMeeting_scripts/reticulate_vignette.Rmd new file mode 100644 index 0000000..4c938fd --- /dev/null +++ b/RUserMeeting_scripts/reticulate_vignette.Rmd @@ -0,0 +1,120 @@ +--- +author: "Eva Rifà" +date: "R User meeting 04/05/2023" +output: rmarkdown::html_vignette +vignette: > + %\VignetteEngine{knitr::knitr} + %\VignetteIndexEntry{Data Storage and Retrieval} + %\usepackage[utf8]{inputenc} +--- + +Package Reticulate +----------------------------------------- + +It is an R package that embeds a Python session within your R session. It calls Python from R being able to translate objects within both packages. + +**How to use reticulate? Different methods** + +1. Importing Python modules — The import() function can import any Python module and call it’s functions directly from R. +2. Sourcing Python scripts — The source_python() function can source a Python script the same way as source() an R script. +3. Python REPL — The repl_python() function creates an interactive Python console within R +4. Python in R Markdown — R chunks can access Python objects and vice-versa. + +### 1. Importing Python modules + +```t +# Import modules in a terminal +module load matplotlib/3.2.2-foss-2015a-Python-3.7.3 +module load Python/3.7.3-foss-2015a +module load R/4.1.2-foss-2015a-bare +``` + +```r +library(reticulate) +``` +```r +matplotlib <- import("matplotlib") + +# Generate some data +x <- c(1, 2, 3, 4, 5) +y <- c(2, 4, 6, 8, 10) + +# Create a scatter plot using matplotlib +plt <- matplotlib$pyplot +plt$scatter(x, y) +plt$xlabel("X") +plt$ylabel("Y") +plt$title("Scatter Plot") +plt$savefig(fname = "plot1.png") +``` + + +In the next example, we load the necessary modules in a terminal: +```t +# Import modules in a terminal +module load xarray/0.20.0-foss-2015a-Python-3.7.3 +# Other dependencies of xarray +module load netcdf4-python/1.5.3-foss-2015a-Python-3.7.3 +module load numpy/1.20.3-foss-2015a-Python-3.7.3 +``` +```r +library(reticulate) +# Example 2: Read Netcdf with xarray +xr <- import("xarray") + +obs_path <- "/esarchive/recon/ecmwf/erainterim/monthly_mean/tas_f6h/" +obs_file <- paste0(obs_path, "tas_201811.nc") + +obs <- xr$open_dataset(obs_file) + +obs +# +# Dimensions: (time: 1, lat: 256, lon: 512) +``` + +### 2. Sourcing Python scripts + +Here, we first need to save a python script: + +```py +import matplotlib.pyplot as plt +import numpy as np + +# Data for plotting +t = np.arange(0.0, 2.0, 0.01) +s = 1 + np.sin(2 * np.pi * t) +fig, ax = plt.subplots() +ax.plot(t, s) +ax.set(xlabel = 'time (s)', ylabel = 'x (m)', + title = 'Created with R') +ax.grid() +fig.savefig("plot2.png") +``` + +Then, we source it from an R session: +```r +library(reticulate) + +source_python("/esarchive/scratch/erifarov/rpackages/cstools-local/dev-xarray/test_reticulate_source.py") +``` + +### 3. Python REPL + +Inside an R session: +```r +library(reticulate) +repl_python() + +import matplotlib.pyplot as plt +import numpy as np + +# Data for plotting +t = np.arange(0.0, 2.0, 0.01) +s = 1 + np.sin(2 * np.pi * t) +fig, ax = plt.subplots() +ax.plot(t, s) +ax.set(xlabel = 'time (s)', ylabel = 'x (m)', + title = 'Created with R') +ax.grid() +fig.savefig("plot2.png") +``` \ No newline at end of file -- GitLab From 3824941cec4a48091cd3de741f0894d0aa40c236 Mon Sep 17 00:00:00 2001 From: Eva Rifa Date: Thu, 1 Feb 2024 14:40:47 +0100 Subject: [PATCH 2/4] Improve reticulate script --- .../reticulate_vignette.Rmd | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) rename {RUserMeeting_scripts => r_user_meeting_scripts}/reticulate_vignette.Rmd (65%) diff --git a/RUserMeeting_scripts/reticulate_vignette.Rmd b/r_user_meeting_scripts/reticulate_vignette.Rmd similarity index 65% rename from RUserMeeting_scripts/reticulate_vignette.Rmd rename to r_user_meeting_scripts/reticulate_vignette.Rmd index 4c938fd..e083b73 100644 --- a/RUserMeeting_scripts/reticulate_vignette.Rmd +++ b/r_user_meeting_scripts/reticulate_vignette.Rmd @@ -1,6 +1,6 @@ --- author: "Eva Rifà" -date: "R User meeting 04/05/2023" +date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteEngine{knitr::knitr} @@ -8,20 +8,25 @@ vignette: > %\usepackage[utf8]{inputenc} --- -Package Reticulate +Reticulate ----------------------------------------- -It is an R package that embeds a Python session within your R session. It calls Python from R being able to translate objects within both packages. +The reticulate package provides a comprehensive set of tools for interoperability between Python and R. -**How to use reticulate? Different methods** +Reticulate embeds a Python session within your R session. It calls Python from R being able to translate objects within both packages. All the information can be found in the package documentation: https://rstudio.github.io/reticulate/. + +> NOTE: This script was used as an Ice-Breaker of the R User Meeting held at BSC on 4/5/2023. -1. Importing Python modules — The import() function can import any Python module and call it’s functions directly from R. -2. Sourcing Python scripts — The source_python() function can source a Python script the same way as source() an R script. -3. Python REPL — The repl_python() function creates an interactive Python console within R -4. Python in R Markdown — R chunks can access Python objects and vice-versa. +**How to use reticulate? Different methods** +There are a variety of ways to integrate Python code into R: +1. Importing Python modules +2. Sourcing Python scripts +3. Python REPL ### 1. Importing Python modules +The import() function can import any Python module and call it’s functions directly from R. +#### Example I ```t # Import modules in a terminal module load matplotlib/3.2.2-foss-2015a-Python-3.7.3 @@ -47,7 +52,7 @@ plt$ylabel("Y") plt$title("Scatter Plot") plt$savefig(fname = "plot1.png") ``` - +#### Example II In the next example, we load the necessary modules in a terminal: ```t @@ -73,8 +78,7 @@ obs ``` ### 2. Sourcing Python scripts - -Here, we first need to save a python script: +The source_python() function can source a Python script the same way as source() an R script. Here, we first need to save a python script: ```py import matplotlib.pyplot as plt @@ -90,15 +94,17 @@ ax.set(xlabel = 'time (s)', ylabel = 'x (m)', ax.grid() fig.savefig("plot2.png") ``` +Then, we need to save the script. Let's call it ('test_reticulate_source.py'). Then, we source it from an R session: ```r library(reticulate) -source_python("/esarchive/scratch/erifarov/rpackages/cstools-local/dev-xarray/test_reticulate_source.py") +source_python("test_reticulate_source.py") ``` ### 3. Python REPL +The repl_python() function creates an interactive Python console within R. Objects you create within Python are available to your R session (and vice-versa). Inside an R session: ```r -- GitLab From ed7e6cda61c80bc5301b198ba8da57a7f752f8ca Mon Sep 17 00:00:00 2001 From: Eva Rifa Date: Thu, 1 Feb 2024 14:42:18 +0100 Subject: [PATCH 3/4] Add date --- r_user_meeting_scripts/reticulate_vignette.Rmd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r_user_meeting_scripts/reticulate_vignette.Rmd b/r_user_meeting_scripts/reticulate_vignette.Rmd index e083b73..3bc9cdc 100644 --- a/r_user_meeting_scripts/reticulate_vignette.Rmd +++ b/r_user_meeting_scripts/reticulate_vignette.Rmd @@ -1,6 +1,6 @@ --- author: "Eva Rifà" -date: "`r Sys.Date()`" +date: "01/02/2024" output: rmarkdown::html_vignette vignette: > %\VignetteEngine{knitr::knitr} -- GitLab From 4b5fc075c16e0695341006245b0debe443dfbc2a Mon Sep 17 00:00:00 2001 From: Eva Rifa Date: Thu, 1 Feb 2024 14:44:15 +0100 Subject: [PATCH 4/4] Few improvements --- r_user_meeting_scripts/reticulate_vignette.Rmd | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/r_user_meeting_scripts/reticulate_vignette.Rmd b/r_user_meeting_scripts/reticulate_vignette.Rmd index 3bc9cdc..f35b03b 100644 --- a/r_user_meeting_scripts/reticulate_vignette.Rmd +++ b/r_user_meeting_scripts/reticulate_vignette.Rmd @@ -17,11 +17,12 @@ Reticulate embeds a Python session within your R session. It calls Python from R > NOTE: This script was used as an Ice-Breaker of the R User Meeting held at BSC on 4/5/2023. -**How to use reticulate? Different methods** +**How to use reticulate?** There are a variety of ways to integrate Python code into R: 1. Importing Python modules 2. Sourcing Python scripts 3. Python REPL +4. Python in R Markdown (not shown in this file) ### 1. Importing Python modules The import() function can import any Python module and call it’s functions directly from R. -- GitLab