Skip to content

Commit de5ddfd

Browse files
authored
Adds Jupyter notebooks and MATLAB live scripts to the examples (#30)
* rearranged examples to make way for python * script for getting tutorials * fixed matlab images and made setup tutorial simpler * split tutorials folder into two * split tutorials folder into two * added livescripts to matlab examples * added nbsphinx to requirements and install pandoc in CI * removed python-rat data from repo * made notebooks part of build process * fix ci * added prolog to notebooks * matlab live scripts now have outputs * updated readme, fixed typo, added examples to header * update notebooks readme * tidied up header * complete rebase (whoops!) * review fixes
1 parent 11594fa commit de5ddfd

30 files changed

+474
-505
lines changed

.github/workflows/build_docs.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,17 @@ jobs:
2121
python-version: '3.11'
2222
- name: Build docs
2323
run: |
24+
# create an x11 display because otherwise MATLAB refuses to export live scripts...
25+
sudo apt install -y xvfb
26+
export DISPLAY=':99.0'
27+
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
28+
2429
wget https://github.com/RascalSoftware/RAT/releases/download/nightly/Linux.zip
2530
unzip Linux.zip -d API/
31+
32+
# we get pandoc from web as apt version is outdated
33+
wget https://github.com/jgm/pandoc/releases/download/3.6.2/pandoc-3.6.2-1-amd64.deb
34+
sudo apt install -y ./pandoc-3.6.2-1-amd64.deb
2635
python -m pip install --upgrade pip
2736
pip install matlabengine==24.1.*
2837
pip install -r requirements.txt

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,7 @@ source/_outputs/
1919

2020
# autogenerated documentation
2121
source/reference/python/RATapi.*
22+
source/python_examples/data/
23+
source/matlab_examples/*.html
24+
source/python_examples/notebooks/*
25+
!source/python_examples/notebooks/README.md

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ Download the appropriate version of RAT from the GitHub [release](https://github
1717
wget https://github.com/RascalSoftware/RAT/releases/download/nightly/Linux.zip
1818
unzip Linux.zip -d API/
1919

20+
You also must have `pandoc` installed to build the Python example Jupyter notebooks. See the installation instructions [here](https://pandoc.org/installing.html).
21+
2022

2123
To build the HTML docs, type the following into a terminal with access to the Python executable:
2224

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ sphinxcontrib-matlabdomain==0.18
33
pydata-sphinx-theme==0.15.2
44
sphinx_design==0.6.0
55
sphinx-copybutton==0.5.2
6+
jupyter==1.0.0
7+
nbsphinx==0.9.6
68
RATapi==0.0.0.dev4
79
autodoc_pydantic==2.2.0
810
enum-tools[sphinx]==0.12.0

source/conf.py

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,13 @@
77
# documentation root, use os.path.abspath to make it absolute, like shown here.
88
import os
99
import sys
10+
import shutil
1011
import datetime
12+
import zipfile
13+
from importlib import metadata
1114
from urllib.parse import urljoin
15+
from urllib.request import urlretrieve
16+
from pathlib import Path
1217
# -- Project information -----------------------------------------------------
1318
# Add any Sphinx extension module names here, as strings. They can be
1419
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@@ -33,17 +38,60 @@
3338
sys.path.insert(0, os.path.dirname(os.path.abspath("..")))
3439
from version import get_doc_version
3540
doc_version = get_doc_version()
36-
41+
3742
# -- General configuration ---------------------------------------------------
3843

3944
# add extensions path for snippets
4045
sys.path.append(os.path.abspath("./_ext"))
4146

42-
extensions = ['sphinxcontrib.matlab', 'sphinx.ext.napoleon', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinxcontrib.autodoc_pydantic', 'sphinx_design', 'sphinx_copybutton', 'snippets', 'enum_tools.autoenum']
47+
extensions = ['sphinxcontrib.matlab', 'sphinx.ext.napoleon', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinxcontrib.autodoc_pydantic', 'sphinx_design', 'sphinx_copybutton', 'snippets', 'enum_tools.autoenum', 'nbsphinx']
4348

4449
# Add any paths that contain templates here, relative to this directory.
4550
templates_path = ['_templates']
4651

52+
# -- Setup example files -----------------------------------------------------
53+
PYTHON_RAT_RELEASE = metadata.version("RATapi")
54+
55+
if not os.path.isdir("./python_examples/data"):
56+
zip_dir, headers = urlretrieve(f"https://github.com/RascalSoftware/python-RAT/archive/refs/tags/{PYTHON_RAT_RELEASE}.zip")
57+
with zipfile.ZipFile(zip_dir) as zf:
58+
zf.extractall()
59+
print("Copying Jupyter notebooks...")
60+
for directory in ['normal_reflectivity', 'domains', 'absorption']:
61+
for file in Path(f"./python-RAT-{PYTHON_RAT_RELEASE}/RATapi/examples/{directory}/").glob('*'):
62+
shutil.copy(file, "./python_examples/notebooks/")
63+
64+
shutil.copytree(f"./python-RAT-{PYTHON_RAT_RELEASE}/RATapi/examples/data", "./python_examples/data", dirs_exist_ok=True)
65+
66+
shutil.rmtree(f"./python-RAT-{PYTHON_RAT_RELEASE}")
67+
68+
if not os.path.isfile("./matlab_examples/standardLayersDSPCSheet.html"):
69+
try:
70+
from matlab.engine import start_matlab
71+
except ImportError:
72+
print("Could not copy MATLAB live scripts as MATLAB is not installed.")
73+
else:
74+
print("Starting MATLAB Engine...")
75+
eng = start_matlab()
76+
matlab_examples_path = Path("./matlab_examples").resolve()
77+
eng.eval("cd('../API'); addPaths;", nargout=0)
78+
for sheet in ['normalReflectivity/standardLayers/standardLayersDSPCSheet',
79+
'normalReflectivity/customLayers/customLayersDSPCSheet',
80+
'normalReflectivity/customXY/customXYDSPCSheet',
81+
'domains/standardLayers/domainsStandardLayersSheet',
82+
'domains/customLayers/domainsCustomLayersSheet',
83+
'domains/customXY/domainsCustomXYSheet',
84+
'miscellaneous/convertRascal1Project/convertRascal',
85+
'miscellaneous/alternativeLanguages/customModelLanguagesSheet',]:
86+
filename = Path(sheet).name
87+
folder = str(Path(sheet).parent)
88+
print(f"exporting {sheet}")
89+
eng.cd(f"examples/{folder}", nargout=0)
90+
eng.matlab.internal.liveeditor.executeAndSave(str(Path(f"../API/examples/{sheet}.mlx").resolve()), nargout=0)
91+
eng.export(f"{filename}.mlx", str(matlab_examples_path / f"{filename}.html"), nargout=0)
92+
eng.cd("../../../", nargout=0)
93+
94+
4795
# -- Options for HTML output -------------------------------------------------
4896
#set primary_domain = 'matlab'
4997
primary_domain = None
@@ -84,6 +132,30 @@
84132

85133
autodoc_typehints = "description"
86134

135+
nbsphinx_prolog = r"""
136+
{% set docname = 'doc/' + env.doc2path(env.docname, base=None)|string %}
137+
138+
.. raw:: html
139+
140+
<div class="admonition note">
141+
This page was generated from the notebook {{ env.docname.split('/')|last|e + '.ipynb' }} found in
142+
<a class="reference external" href="https://github.com/RascalSoftware/python-RAT/blob/"""+PYTHON_RAT_RELEASE+r"""/RATapi/examples/">the Python-RAT repository</a>.
143+
<a href="{{ env.docname.split('/')|last|e + '.ipynb' }}" class="reference download internal" download>Download notebook</a>.
144+
</div>
145+
146+
.. note::
147+
148+
To get the output project and results from this example in your Python session, run:
149+
150+
.. code-block:: python
151+
152+
from RATapi.examples import {{ env.docname.split('/')|last|e }}
153+
project, results = {{ env.docname.split('/')|last|e }}()
154+
155+
-------------------------------------------------------------------------------------
156+
157+
"""
158+
87159
### autodoc_pydantic settings
88160
# hide JSON schemas by default
89161
autodoc_pydantic_model_show_json = False

source/examples.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Examples
2+
========
3+
4+
Several examples are provided for RAT in both Python and MATLAB:
5+
6+
7+
Matlab
8+
------
9+
10+
.. toctree::
11+
:maxdepth: 3
12+
13+
matlab_examples/index
14+
15+
Python
16+
------
17+
18+
.. toctree::
19+
:maxdepth: 3
20+
21+
python_examples/index

source/examples/DSPC_custom_XY.rst

Lines changed: 0 additions & 79 deletions
This file was deleted.

source/examples/DSPC_custom_layers.rst

Lines changed: 0 additions & 67 deletions
This file was deleted.

source/examples/DSPC_standard_layers.rst

Lines changed: 0 additions & 55 deletions
This file was deleted.

0 commit comments

Comments
 (0)