diff --git a/CHANGELOG.md b/CHANGELOG.md index f824c12..8acd0ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver - canoP studio in English or in French: a FR/EN switch in the top bar, saved in the settings. New installations start in English; studios set up before keep French. +- Tutorial of canoP studio in the documentation: the build, a run of the blast example, and a + convergence campaign with a new initial condition in Python and its analysis. ## 0.1.0 - 2026-11-27 diff --git a/docs/_static/canop.css b/docs/_static/canop.css index 703be46..abda1b6 100644 --- a/docs/_static/canop.css +++ b/docs/_static/canop.css @@ -3,3 +3,7 @@ .sidebar-logo { max-width: 85%; } table.docutils td, table.docutils th { vertical-align: top; } table.canop-params td:first-child { white-space: nowrap; } +/* tutorial: the screenshot of a panel beside its explanation, below it on narrow screens */ +img.tuto-side { float: left; margin: 0.3em 1.5em 1em 0; } +@media (max-width: 60em) { img.tuto-side { float: none; display: block; margin: 0 auto 1em; } } +article h2, article h3 { clear: both; } diff --git a/docs/index.md b/docs/index.md index 64fb4d8..6ae1e09 100644 --- a/docs/index.md +++ b/docs/index.md @@ -36,6 +36,13 @@ getting-started/installation getting-started/running ``` +```{toctree} +:caption: Tutorial +:maxdepth: 2 + +tutorial/index +``` + ```{toctree} :caption: User guide :maxdepth: 2 diff --git a/docs/tutorial/build.md b/docs/tutorial/build.md new file mode 100644 index 0000000..069b692 --- /dev/null +++ b/docs/tutorial/build.md @@ -0,0 +1,93 @@ + + +# 1. Build canoP + +The left panel of canoP studio holds its settings, in two parts: **Code and build** (what is built, +with which environment, and where) and **Execution** (how the runs are launched). This page goes +through their choices, then builds canoP once. + +## The Code and build panel + +```{image} images/build-code-panel.webp +:alt: The Code and build panel of canoP studio +:width: 300px +:class: tuto-side +``` + +**canoP sources** is the clone the studio runs from. **Build directory** is empty by default: +`/_build`. Each variant (Kokkos backend and architectures) has its own directory: the OpenMP +build in `_build`, a Cuda build for an A100 in `_build_cuda_ampere80`, so that switching the backend +keeps both builds. + +**Dimension** chooses the executable, `canoP_2d` or `canoP_3d`; a build compiles the one chosen. The +model (`onephase`, `twophase5eq`, `twophase7eq`) is not chosen here but in the input file +(`simulation.model`): the physics is written in Python and compiled at run time, so a new model, +initial condition or flux needs no new build of canoP. + +**Kokkos backend**: OpenMP for the CPUs, Cuda for NVIDIA GPUs. **CPU architecture** (and, for Cuda, +the architecture of the GPU of the runs, e.g. `AMPERE80` for an A100) is passed to Kokkos; *none* +leaves the choice to the compiler. + +**Environment (modules…)** are the shell lines run before the build and before each run: they load +a C++17 compiler, CMake, MPI, HDF5 and a Python 3.11 or later. **CMake options** are added to the +configuration. Both, and the Slurm options of the runs, belong to the backend: switching from +OpenMP to Cuda shows those of Cuda, and back. The studio sets the backend and architectures of Kokkos +itself and removes them from the CMake options. + +**Build on**: *this node* runs the build on the node of the studio (the login node); *a compute +node* submits a Slurm job of one task with **Build jobs** cores, with the **Slurm options of the +build**. +A Cuda build needs no GPU. On a shared login node, prefer the compute node. + +**Configure** runs CMake only; **Build** configures when needed and compiles; **Empty the build +directory** deletes the build of this variant (CMake configuration included). **Executable** shows +the executable once it exists. + +## The first build + +Click **Build**. With *a compute node*, the studio submits the job and the top bar shows +`build: pending`, then `build: running`; a message tells when it ends. The first build of a clone +takes longer than the next ones: canoP builds its own Kokkos (shared library), pykokkos-base and +pykokkos, and, when the Python of the environment lacks numpy, h5py or pybind11 3.1.0, makes its +Python environment `/.local/python` with pip, which needs access to the internet +from the node of the build. On a cluster, the first build took about ten minutes on 8 cores of a +compute node; the next builds only compile what changed. + +The **Log** tab, **Build**, follows the log while it is written; the menu also gives the logs of +the previous builds, and **Search** finds a word or a regular expression in the log: + +```{image} images/build-log.webp +:alt: The log of the build in the Log tab +:width: 100% +``` + +When a build fails, the error is in this log: an environment line to fix (a module that does not +exist), a missing dependency found by CMake, or an error of the compiler. + +## The Execution panel + +```{image} images/build-execution-panel.webp +:alt: The Execution panel of canoP studio, with the launcher sbatch +:width: 300px +:class: tuto-side +``` + +**Launcher**: *direct* runs canoP on the node of the studio, for short runs; *mpirun* runs it +there with MPI (`mpirun -np`); *srun* starts it through Slurm and waits for its allocation; *sbatch* +submits a Slurm job with the **Slurm options of the runs** of the backend, which runs canoP with +`srun`. The panel then lists the partitions of the cluster (`sinfo`), with their time limit and +nodes. + +**MPI processes** × **OpenMP threads** are the cores of a run; 0 threads leaves `OMP_NUM_THREADS` +unset, so that OpenMP takes every core it sees: with *direct* on a login node, set a few threads. +**Extra arguments** are added to the command line of canoP. + +**Safeguards of the campaigns run by an agent**: an AI agent that drives the studio through its MCP +tools (Claude Code, for example) cannot submit more runs, nodes, cores, GPUs or core-hours than +these limits without asking you; only you can change them. + +Next: {doc}`run`. diff --git a/docs/tutorial/campaign.md b/docs/tutorial/campaign.md new file mode 100644 index 0000000..96c4dae --- /dev/null +++ b/docs/tutorial/campaign.md @@ -0,0 +1,198 @@ + + +# 3. A convergence campaign + +This page measures the order of convergence of the scheme of canoP. A new initial condition, written +in Python, gives a smooth problem with a known solution: a sine wave of density advected at uniform +velocity in a periodic domain. A campaign runs it on uniform meshes of 32² to 512² cells, and its +`analysis.py` plots the error against the number of cells. + +## The input file + +The base of the campaign is the input file of the editor. In the **Run** tab, start from the blast +example and change it as below (or paste it in the text of the ini file): + +```{literalinclude} files/convergence.ini +:language: ini +``` + +Compared with the blast example: + +- `physics.initial_condition = sine`, the new initial condition, with its parameters in `[sine]`; +- `simulation.time_order = 2` (SSP Runge-Kutta 2): with the forward Euler scheme, the error in time, + of order 1 at a fixed CFL number, would hide the order 2 in space; +- `amr.epsilon_refine = -1` and `amr.epsilon_coarsen = -1`: the refinement indicator lies in + [0, 1], so every block is refined up to `amr.max_refine` and none is coarsened, which gives a + uniform mesh of 2max_refine cells per direction; +- `simulation.tmax = 1` with the velocity (1, 1): the wave crosses the periodic domain once in each + direction and is back at its initial position; +- `hyperbolic_flux = hllc` and fewer outputs (`io.save_count = 5`). + +## The campaign + +In the **Campaign** tab, **New campaign** takes the input file of the editor as its base. Give it a +name and one line per parameter to vary, `section.key = v1, v2, ...`; the campaign has one run per +combination of the values (here 5): + +```{image} images/campaign-new.webp +:alt: The dialog of a new campaign, with the sweep of amr.max_refine +:width: 640px +``` + +A campaign is a directory `_campaigns//`: a signac project with one directory per run +(`workspace//`), its own copy of the physics of canoP (`physics/`, in a git repository: each launch +commits it and records the commit in the runs) and its analysis (`analysis.py`). Its runs are +*prepared*: nothing runs before they are launched. + +```{image} images/campaign-prepared.webp +:alt: The five prepared runs of the campaign +:width: 100% +``` + +## A new initial condition + +An initial condition is a file of `physics//initial_conditions/`; its name is the value of +`physics.initial_condition`. The campaign uses its own copy of the physics: add the file to +`_campaigns/convergence/physics/onephase/initial_conditions/sine.py`, for example in the editor of VS +Code: + +```{literalinclude} files/sine.py +:language: python +``` + +The file has two parts: + +- `params(dim)` runs in plain Python when the run starts: it reads the parameters of the input file + (`get_real`, `get_int`, `get_string` with a section, a key and a default) and returns them by name. + The docstring describes them: canoP studio shows it under the mouse, as on the previous page. +- `initial_state` is a pykokkos function (`@pk.function`), translated into C++ and compiled for the + CPU or the GPU. It receives the centre of a cell (`z = 0` in 2D), the parameters (`ip.m0`, ...), + the domain (`domain[0:3]`: lower corner, `domain[3:6]`: lengths) and the dimension, and returns + the primitive state `Prim(m, P, T, vx, vy, vz)` of the cell. + +Select a run of the campaign, **View** loads it in the editor, and **Initial condition** checks the +new file at once: it compiles the kernels of the initial condition and shows the result. + +```{image} images/campaign-initial-condition.webp +:alt: The sine wave on the uniform mesh of the coarsest run +:width: 100% +``` + +## What pykokkos accepts + +A pykokkos function is not Python: it is translated into C++, with a subset of Python. These rules +were checked by compiling variants of `sine.py`: + +| In `initial_state` | Result | +|---|---| +| a new variable without annotation, `s2 = sx * sy` | refused by the C++ compiler, at the line: `'s2' was not declared in this scope`; write `s2: float = sx * sy` | +| `max(a, b)` of Python | refused: `undefined symbol max used`; use `pk.fmax` (and `pk.fmin` for a minimum) | +| `np.sin(x)` of numpy | refused: `undefined symbol np used`; use the functions of pykokkos: `pk.sin`, `pk.exp`, `pk.sqrt`, `pk.atan2`, ... | +| a constant of the module, `SHIFT = 0.5` | refused: `undefined symbol SHIFT used`; make it a parameter in `params`, or write the value | +| `a if c else b` | refused: `Not supported for translation`; write an `if` statement | +| a list, `[0.5, 0.25][0]` | refused, without the line: `AttributeError: 'List' object has no attribute 'id'` | +| `math.pi`, `abs(x)`, `x ** 2` | accepted | +| `1 / 2`, `ip.n / 2` with an integer parameter | accepted, a real division as in Python (0.5) | + +Other points to keep in mind: + +- **Every initial condition of the model is compiled together.** An error in `sine.py` stops every + run of the model that uses this physics, whatever its initial condition: here, the runs of this + campaign only, since it has its own copy of the physics. +- **Errors point to the line of the file of the physics**, for the translation by pykokkos and for + the C++ compiler. On a GPU, nvcc gives no column: check a new file on the CPU first. +- **A change compiles again** the kernels that contain the file, about 10 s each, at the next run or + initial condition. +- **The parameters are numbers.** `params` may compute anything in Python, but returns integers or + reals, with names that do not depend on the input file. + +## The runs + +The runs of a campaign are Slurm jobs, one per run. The **Launcher** of the **Execution** panel must +be *sbatch* (see {doc}`build`), and its settings apply to every run: here 1 MPI process of 16 OpenMP +threads, with the `#SBATCH` lines of the panel (a partition, a time limit of one hour, one node). +**Launch the prepared runs (5)** asks for a confirmation: + +```{image} images/campaign-launch.webp +:alt: The confirmation of the launch of the five runs +:width: 520px +``` + +At the launch, the studio: + +1. commits the physics of the campaign if it changed (here the new `sine.py`) in the git repository + of the campaign; +2. copies that commit into each run (`canoP_physics/`) and writes the commits of canoP and of the + physics at the top of its input file (lines `# [canoP studio]`): each run keeps the code and the + physics it ran with; +3. submits the runs with signac-flow (`python project.py submit -o run` in the directory of the + campaign), then commits the launch. + +The table follows the runs: *queued*, *running*, then *finished*, with their outputs and the +time reached. Depending on the limits of the partition, the runs run at the same time or one after +the other. A click on a run gives its details: its Slurm job, the versions of canoP and of the physics +it ran with, its parameters, and its metrics, read from its log by the campaign (`project.py`) once +it is finished. + +```{image} images/campaign-finished.webp +:alt: The five finished runs of the campaign, with their durations and metrics +:width: 100% +``` + +## The analysis + +The **Analysis** tab draws a metric of the finished runs against a parameter of the campaign. Choose +the campaign, `amr.max_refine` as the parameter (x) and `elapsed_s`, the duration of each run, as the +metric (y). The other metrics (`n_outputs`, `t_final`, `mcups`) are read from the logs by the +campaign itself (`project.py`) when its runs finish. + +Here the durations are 7, 7, 45, 68 and 473 s. The smallest runs spend their time mostly in the start +of canoP and in the outputs. From 256² to 512², the duration is multiplied by 7, close to 8, the work +of one more level in 2D: 4 times more cells, and twice more time steps, since the time step follows +the size of the cells. + +The panel on the right belongs to the campaign: it is drawn by its file `analysis.py`, made from a +template when the campaign is created. Replace that file with the analysis of the convergence, +`_campaigns/convergence/analysis.py`: + +```{literalinclude} files/analysis.py +:language: python +``` + +The studio calls three functions of this file, and loads it again as soon as it is saved: + +- `analyse(points, x, y)` receives the points of the graph, `[(x, y, run), ...]` for the finished + runs, where `run` is the start of the id of the run (8 characters, as in the table), and returns a + result made of numbers, strings, lists and dictionaries, which the page keeps as `an_result`. Here + it does not use x and y: for each run it finds its directory (`_run_dir`), reads its last output + (`workspace//sine_iter*.xmf`, with the XDMF reader of VTK), compares the density with the exact + solution, the initial wave moved by (vx, vy) t, and computes the L1 error and the observed order + between two successive levels, log(ecoarse / efine) / log(nfine / + ncoarse). +- `draw(ax, points, result, x, y)` may add to the matplotlib graph of the tab (nothing here). +- `panel(app)` builds the panel with the widgets of trame and Vuetify (`app.v3`, `app.html`), bound + to `an_result`: the log-log plot of the error, drawn as an image by `analyse`, and the table of the + errors and orders. + +The file runs in the studio, with its Python (numpy, matplotlib and VTK are there): keep it fast, as +here with the errors kept from one call to the next as long as the outputs do not change. + +```{image} images/campaign-analysis.webp +:alt: The Analysis tab: duration of the runs against amr.max_refine, and the convergence of the L1 error +:width: 100% +``` + +The L1 error goes from 1.1 × 10-2 on 32² cells to 9.0 × 10-5 on 512² cells, and +the observed order rises from 1.69 (32² to 64²) to 1.83 (256² to 512²). It is below 2 because the +minmod limiter flattens the slopes at the extrema of the wave, where the reconstruction is only of +order 1; these regions shrink as the mesh is refined, and the order approaches 2. + +The campaign of this page, as it ran (its git repository: physics, input files, analysis, metrics), +is in [canoPdev/tutorial](https://github.com/canoPdev/tutorial), with its results on the +[wiki](https://github.com/canoPdev/tutorial/wiki). Its README tells how to run it again. + +Next: back to {doc}`index`. diff --git a/docs/tutorial/files/analysis.py b/docs/tutorial/files/analysis.py new file mode 100644 index 0000000..7892cea --- /dev/null +++ b/docs/tutorial/files/analysis.py @@ -0,0 +1,156 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Analysis of a convergence campaign: L1 error of the density versus amr.max_refine. + +The runs advect the sine wave of physics/onephase/initial_conditions/sine.py in a periodic domain, +on a uniform mesh. analyse() reads the last output of each run, compares its density with the exact +solution (the initial wave moved by (vx, vy) t) and gives the L1 error and the observed order between +successive levels; panel() shows them, with the error versus the number of cells. The graph of the +tab shows the metric chosen in it versus the chosen parameter (e.g. the time of each run). +""" +import base64 +import configparser +import glob +import io +import math +import os +import re + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +_errors = {} # (output, modification time) -> (error, cells per direction) + + +def _ini(run_dir): + """Input file of a run, as a ConfigParser.""" + ini = configparser.ConfigParser(comment_prefixes=("#", ";"), inline_comment_prefixes=(";",), strict=False) + for path in sorted(glob.glob(os.path.join(run_dir, "*.ini"))): + ini.read(path, encoding="utf-8") + return ini + + +def _last_output(run_dir): + """Last output (XDMF file) of a run, or None.""" + steps = sorted(glob.glob(os.path.join(run_dir, "*_iter*.xmf"))) + return steps[-1] if steps else None + + +def _cells(path): + """Density, cell centres, cell areas and time of an output.""" + # pylint: disable=import-outside-toplevel (VTK is only needed here) + from vtkmodules.util.numpy_support import vtk_to_numpy + from vtkmodules.vtkFiltersParallel import vtkMergeBlocks + from vtkmodules.vtkIOXdmf2 import vtkXdmfReader + + reader = vtkXdmfReader() + reader.SetFileName(path) + reader.Update() + grid = reader.GetOutputDataObject(0) + if grid.IsA("vtkCompositeDataSet"): + merge = vtkMergeBlocks() + merge.SetInputData(grid) + merge.Update() + grid = merge.GetOutput() + points = vtk_to_numpy(grid.GetPoints().GetData()).astype(float) + corners = points[vtk_to_numpy(grid.GetCells().GetConnectivityArray()).reshape(-1, 4)] # quads, 2D + centres = corners.mean(axis=1) + sizes = corners.max(axis=1) - corners.min(axis=1) + density = vtk_to_numpy(grid.GetCellData().GetArray("m")) + with open(path, encoding="utf-8") as fd: + time = float(re.search(r']*Value="([^"]+)"', fd.read()).group(1)) + return density, centres, sizes[:, 0] * sizes[:, 1], time, points + + +def l1_error(run_dir): + """L1 error of the density of the last output of a run, and its number of cells per direction.""" + path = _last_output(run_dir) + if path is None: + return None + key = (path, os.path.getmtime(path)) + if key not in _errors: + ini = _ini(run_dir) + sine = ini["sine"] if ini.has_section("sine") else {} + + def value(name, default): + return float(sine.get(name, default)) + + density, centres, areas, time, points = _cells(path) + lower, length = points.min(axis=0), points.max(axis=0) - points.min(axis=0) + x = (centres[:, 0] - lower[0] - value("vx", 1.0) * time) / length[0] + y = (centres[:, 1] - lower[1] - value("vy", 1.0) * time) / length[1] + exact = value("m0", 1.0) + value("amplitude", 0.2) * np.sin(2 * math.pi * x) * np.sin(2 * math.pi * y) + error = float(np.sum(np.abs(density - exact) * areas) / np.sum(areas)) + _errors[key] = (error, round(length[0] / math.sqrt(areas.mean()))) + return _errors[key] + + +def _run_dir(run): + """Directory of a run, from the start of its id (the studio gives its first 8 characters).""" + found = glob.glob(os.path.join(HERE, "workspace", glob.escape(run) + "*")) + return found[0] if len(found) == 1 else None + + +def analyse(points, x, y): + """L1 error of each run, sorted by number of cells, with the observed order between neighbours.""" + rows = [] + for _, _, run in points: + run_dir = _run_dir(run) + found = l1_error(run_dir) if run_dir else None + if found: + rows.append({"run": run[:8], "cells": found[1], "error": found[0]}) + rows.sort(key=lambda r: r["cells"]) + for coarse, fine in zip(rows, rows[1:]): + fine["order"] = math.log(coarse["error"] / fine["error"]) / math.log(fine["cells"] / coarse["cells"]) + return {"rows": rows, "plot": _plot(rows) if len(rows) > 1 else None} + + +def _plot(rows): + """Log-log plot of the error versus the number of cells per direction, as a PNG data URL.""" + import matplotlib # pylint: disable=import-outside-toplevel + + matplotlib.use("Agg") + import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel + from matplotlib.ticker import NullLocator # pylint: disable=import-outside-toplevel + + n = np.array([r["cells"] for r in rows], dtype=float) + e = np.array([r["error"] for r in rows]) + fig, ax = plt.subplots(figsize=(4.6, 3.4), dpi=100) + ax.loglog(n, e, "o-", label="L1 error of the density") + ax.loglog(n, e[0] * (n[0] / n) ** 2, "--", color="grey", label="order 2") + ax.set_xticks(n, labels=["%d" % v for v in n]) # the meshes of the runs, not the powers of 10 + ax.xaxis.set_minor_locator(NullLocator()) + ax.set_xlabel("cells per direction") + ax.set_ylabel("L1 error") + ax.grid(True, which="both", alpha=0.3) + ax.legend(fontsize=8) + fig.tight_layout() + buf = io.BytesIO() + fig.savefig(buf, format="png") + plt.close(fig) + return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() + + +def draw(ax, points, result, x, y): + """Nothing to add to the graph of the tab.""" + + +def panel(app): + """The convergence plot and the table of the errors and orders.""" + v3, html = app.v3, app.html + html.Div("No finished run yet.", v_if="!an_result || !an_result.rows.length", + classes="text-caption text-medium-emphasis pa-2") + with html.Div(v_if="an_result && an_result.rows.length"): + html.Img(src=("an_result.plot",), v_if="an_result.plot", style="width: 100%") + with v3.VTable(density="compact"): + with html.Thead(): + with html.Tr(): + for title in ("run", "cells", "L1 error", "order"): + html.Th(title) + with html.Tbody(): + with html.Tr(v_for="r in an_result.rows", key="r.run"): + html.Td("{{ r.run }}", classes="mono") + html.Td("{{ r.cells }}²") + html.Td("{{ r.error.toExponential(3) }}") + html.Td("{{ r.order === undefined ? '' : r.order.toFixed(2) }}") diff --git a/docs/tutorial/files/convergence.ini b/docs/tutorial/files/convergence.ini new file mode 100644 index 0000000..75552b5 --- /dev/null +++ b/docs/tutorial/files/convergence.ini @@ -0,0 +1,70 @@ +[simulation] +; model: a directory of physics/ +model = onephase +; final time: the wave crosses the periodic domain once in x and in y +tmax = 1.0 +; CFL number +cfl = 0.4 +; order in space: 1, or 2 (MUSCL reconstruction) +space_order = 2 +; order in time: 2 (SSP Runge-Kutta 2), so that the error in time does not limit the order +time_order = 2 +; slope limiter of the MUSCL reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 1 +periodic_y = 1 +periodic_z = 1 +; trees of the brick per direction +ntree_x = 1 +ntree_y = 1 +ntree_z = 1 +; length of a tree +ltree = 1 +; cells of a block per direction (a power of 2, at least 4); cubic cells: by = bz = bx +bx = 4 +by = 4 +bz = 4 +; levels of the cells (2^level cells per tree and direction): the campaign varies max_refine +min_refine = 3 +max_refine = 5 +; uniform mesh at max_refine: every block is refined (the indicator, in [0, 1], exceeds -1) +; and none is coarsened +epsilon_refine = -1 +epsilon_coarsen = -1 + +[io] +; prefix of the output files +output_prefix = sine +; number of outputs over the run +save_count = 5 +; derived fields written with the conservative variables +write_variables = P, V + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = sine +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = reflective +; refinement criterion: refine_conditions/.py +refine_condition = m_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = hllc +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = none +; instantaneous relaxation: relaxations/.py, or none +relaxation = none +; source term: sources/.py, or none +source = none + +[sine] +; mean density and amplitude of the wave +m0 = 1.0 +amplitude = 0.2 +; pressure +P0 = 1.0 +; velocity: after tmax = 1, the wave is back at its initial position +vx = 1.0 +vy = 1.0 diff --git a/docs/tutorial/files/sine.py b/docs/tutorial/files/sine.py new file mode 100644 index 0000000..f7b2971 --- /dev/null +++ b/docs/tutorial/files/sine.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""sine: a sine wave of density advected at uniform velocity and pressure, for convergence studies. + +``m = m0 + amplitude sin(2 pi x / L_x) sin(2 pi y / L_y)`` (``x`` and ``y`` from the lower corner +of the domain), pressure ``P0`` and velocity ``(vx, vy)`` everywhere. In a periodic domain, the +solution of the Euler equations is this wave moved by ``(vx, vy) t``. Parameters (section +``[sine]``): + +- ``m0``, ``amplitude``: mean density and amplitude of the wave; +- ``P0``: pressure; +- ``vx``, ``vy``: velocity. +""" +import math + +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("sine", "m0", 1.0) + res["amplitude"] = get_real("sine", "amplitude", 0.2) + res["P0"] = get_real("sine", "P0", 1.0) + res["vx"] = get_real("sine", "vx", 1.0) + res["vy"] = get_real("sine", "vy", 1.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + sx: float = pk.sin(2.0 * math.pi * (x - domain[0]) / domain[3]) + sy: float = pk.sin(2.0 * math.pi * (y - domain[1]) / domain[4]) + q.m = ip.m0 + ip.amplitude * sx * sy + q.P = ip.P0 + q.vx = ip.vx + q.vy = ip.vy + return q diff --git a/docs/tutorial/images/build-code-panel.webp b/docs/tutorial/images/build-code-panel.webp new file mode 100644 index 0000000..e509552 Binary files /dev/null and b/docs/tutorial/images/build-code-panel.webp differ diff --git a/docs/tutorial/images/build-execution-panel.webp b/docs/tutorial/images/build-execution-panel.webp new file mode 100644 index 0000000..e0f65d4 Binary files /dev/null and b/docs/tutorial/images/build-execution-panel.webp differ diff --git a/docs/tutorial/images/build-log.webp b/docs/tutorial/images/build-log.webp new file mode 100644 index 0000000..a8956be Binary files /dev/null and b/docs/tutorial/images/build-log.webp differ diff --git a/docs/tutorial/images/campaign-analysis.webp b/docs/tutorial/images/campaign-analysis.webp new file mode 100644 index 0000000..f5a6cde Binary files /dev/null and b/docs/tutorial/images/campaign-analysis.webp differ diff --git a/docs/tutorial/images/campaign-finished.webp b/docs/tutorial/images/campaign-finished.webp new file mode 100644 index 0000000..0ae9892 Binary files /dev/null and b/docs/tutorial/images/campaign-finished.webp differ diff --git a/docs/tutorial/images/campaign-initial-condition.webp b/docs/tutorial/images/campaign-initial-condition.webp new file mode 100644 index 0000000..dc4d19f Binary files /dev/null and b/docs/tutorial/images/campaign-initial-condition.webp differ diff --git a/docs/tutorial/images/campaign-launch.webp b/docs/tutorial/images/campaign-launch.webp new file mode 100644 index 0000000..c1221f4 Binary files /dev/null and b/docs/tutorial/images/campaign-launch.webp differ diff --git a/docs/tutorial/images/campaign-new.webp b/docs/tutorial/images/campaign-new.webp new file mode 100644 index 0000000..7d15ef8 Binary files /dev/null and b/docs/tutorial/images/campaign-new.webp differ diff --git a/docs/tutorial/images/campaign-prepared.webp b/docs/tutorial/images/campaign-prepared.webp new file mode 100644 index 0000000..92a88af Binary files /dev/null and b/docs/tutorial/images/campaign-prepared.webp differ diff --git a/docs/tutorial/images/run-campaign.webp b/docs/tutorial/images/run-campaign.webp new file mode 100644 index 0000000..ca00e4e Binary files /dev/null and b/docs/tutorial/images/run-campaign.webp differ diff --git a/docs/tutorial/images/run-example.webp b/docs/tutorial/images/run-example.webp new file mode 100644 index 0000000..b2057dd Binary files /dev/null and b/docs/tutorial/images/run-example.webp differ diff --git a/docs/tutorial/images/run-initial-condition.webp b/docs/tutorial/images/run-initial-condition.webp new file mode 100644 index 0000000..d02b8ec Binary files /dev/null and b/docs/tutorial/images/run-initial-condition.webp differ diff --git a/docs/tutorial/images/run-key-help.webp b/docs/tutorial/images/run-key-help.webp new file mode 100644 index 0000000..a821987 Binary files /dev/null and b/docs/tutorial/images/run-key-help.webp differ diff --git a/docs/tutorial/images/run-log.webp b/docs/tutorial/images/run-log.webp new file mode 100644 index 0000000..a49c4fa Binary files /dev/null and b/docs/tutorial/images/run-log.webp differ diff --git a/docs/tutorial/images/run-view.webp b/docs/tutorial/images/run-view.webp new file mode 100644 index 0000000..eb07fd4 Binary files /dev/null and b/docs/tutorial/images/run-view.webp differ diff --git a/docs/tutorial/index.md b/docs/tutorial/index.md new file mode 100644 index 0000000..84c73b5 --- /dev/null +++ b/docs/tutorial/index.md @@ -0,0 +1,30 @@ + + +# Tutorial: canoP studio + +This tutorial runs canoP from canoP studio, from the build to a convergence study: + +1. {doc}`build`: the settings of the build and of the runs, and a first build of canoP; +2. {doc}`run`: a run outside campaigns, from its initial condition to its results; +3. {doc}`campaign`: a new initial condition written in Python and a campaign that measures the order + of convergence of the scheme. + +It assumes that canoP studio is installed and open (see {doc}`../getting-started/installation`): +on a cluster, in VS Code in the browser (code-server) on a login node, the canoP icon of the left +bar starts the studio. Its interface is in English or in French: the FR/EN switch of the top bar. + +The screenshots come from a cluster with Slurm; paths and environment modules are shown with neutral +values (`~/canoP`, `module load gcc cmake ...`). They are taken by `docs/tutorial/screenshots.py` +from a running studio, to be redone when the interface changes. + +```{toctree} +:maxdepth: 1 + +build +run +campaign +``` diff --git a/docs/tutorial/run.md b/docs/tutorial/run.md new file mode 100644 index 0000000..8496fdc --- /dev/null +++ b/docs/tutorial/run.md @@ -0,0 +1,101 @@ + + +# 2. A run outside campaigns + +This page runs the blast example of the single-phase model: a disc of high pressure in a gas at +rest, on an adaptive mesh. The run belongs to the campaign `hors-campagne`, which holds the runs +made outside parameter studies. + +## The input file + +In the **Run** tab, choose `settings/settings_onephase_blast.ini` in **Examples provided with the +code**. The editor shows the input file twice: by section on the left, as text on the right; a change +on one side is written to the other when the field is left. + +```{image} images/run-example.webp +:alt: The blast example in the editor of the Run tab +:width: 100% +``` + +Each key shows its value and its type; **×** removes it from the file. **Filter the parameters** +keeps the keys whose name contains a text, and **Show the defaults of the code** adds the keys that +the file does not set, with the default value of the code. Under the mouse, a key gives its +description, its type, its default value and the files of the code or of the physics that read it: + +```{image} images/run-key-help.webp +:alt: The description of the key blast.radius under the mouse +:width: 544px +``` + +A key that canoP never reads is flagged, which usually means a typo. **Rescan the code** reads the +keys again after a change of the physics. + +## Into a campaign + +The status line reads *No run*: an example is a base, not a run. **Load into the campaign** (here +`hors-campagne`) makes a run of it, a directory `_campaigns/hors-campagne/workspace//` with its +own copy of the input file. From then on, the editor edits that copy, and **Run** relaunches the +same run in place. The fields under the status line override, for this run only, the number of +processes and threads and, with Slurm, the nodes, the time and the partition (empty: the value of +the Execution panel, shown in grey). + +## The initial condition + +**Initial condition** runs canoP without any time step (`simulation.nstepmax = 0`): it builds the +initial condition, refined level by level up to `amr.max_refine`, and writes it. It is shown in the +**View** tab as soon as it is written; the box **Mesh** shows the blocks of the adaptive mesh, finer +around the disc: + +```{image} images/run-initial-condition.webp +:alt: The initial condition of the blast example, with its adaptive mesh +:width: 100% +``` + +This is the quickest way to check a new initial condition or new refinement settings before a run. +The first time a model runs, pykokkos compiles its kernels (about 10 s each, a line +`pykokkos: ... compiled` in the log for each); they are kept in `/pykokkos_cache` for the next +runs. + +## The run + +**Run** launches canoP with the launcher of the Execution panel; the chip next to the buttons shows +`run: running`, then `run: finished`. The **Log** tab, **Simulation**, follows the log of canoP while it is written: +the time steps, the outputs, and at the end the conservation of the integrals, the histogram of the +levels of the mesh and the timings: + +```{image} images/run-log.webp +:alt: The end of the log of the run +:width: 100% +``` + +The **View** tab follows the outputs while the run writes them (**Follow the run**). **Field** and +**Colormap** choose what is drawn, **Auto range** fits the colours to the values of each output (or +type the bounds in the legend), **Velocity** draws arrows of the velocity, and the slider at the +bottom goes through the outputs (▶ plays them). In 3D, the view shows a slice along an axis or the +outer surface. + +```{image} images/run-view.webp +:alt: The density at the end of the run, with the mesh +:width: 100% +``` + +The view and the derived fields of a run are Python files of its directory, `canoP_view.py` and +`canoP_fields.py`, reloaded when they are saved: see {doc}`../user-guide/studio`. + +## The run in its campaign + +The **Campaign** tab lists the runs of `hors-campagne`. A click on a run gives its directory, its +outputs, the versions of canoP and of the physics it ran with (the physics of the campaign is a git +repository, copied into `canoP_physics/` of the run at each launch), its parameters and its metrics. +**View** shows it in the Run, Log and View tabs; **Delete** removes it. + +```{image} images/run-campaign.webp +:alt: The run in the table of the campaign hors-campagne, with its details +:width: 100% +``` + +Next: {doc}`campaign`. diff --git a/docs/tutorial/screenshots.py b/docs/tutorial/screenshots.py new file mode 100644 index 0000000..ad7750f --- /dev/null +++ b/docs/tutorial/screenshots.py @@ -0,0 +1,371 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Screenshots of the tutorial of canoP studio (docs/tutorial/images/), taken with Playwright. + + python docs/tutorial/screenshots.py --clone --port [build] [run] [campaign] + +Page 3 (campaign) submits the 5 runs of the convergence campaign to Slurm, with the sbatch launcher +and 16 OpenMP threads per run, and waits for them (about 10 minutes on 16 cores). + +canoP studio must run, in English, from the canoP clone (its settings, key and build in that +clone) on this machine at http://localhost:. The script drives the page as a user would and +saves the images at twice the resolution of the page, as WebP, in docs/tutorial/images/. + +Before each capture the page shows neutral values: the path of the clone becomes ``~/canoP``, the +user name ``user``, the host ``login``, the paths of the software of the cluster ``/opt/...`` and +the environment modules a generic line. Only what the browser shows is changed, not the studio. + +Needs the Python packages playwright (with its Chromium: ``python -m playwright install chromium``) +and pillow. On a cluster login node, unset DISPLAY (with X11 forwarding Chromium disables WebGL, +which the view of the results needs); Chromium may also need libraries of the distribution that the +node lacks (libgbm): extract them from the packages of the distribution and add them to +LD_LIBRARY_PATH. +""" +import argparse +import glob +import io +import os +import re +import socket +import time + +from PIL import Image +from playwright.sync_api import sync_playwright + +HERE = os.path.dirname(os.path.abspath(__file__)) +GENERIC_ENV = "module load gcc cmake openmpi hdf5 python\nexport CC=gcc CXX=g++" + +NEUTRAL_JS = """([pairs, env]) => { + const subst = (s) => { for (const [re, to] of pairs) s = s.replace(new RegExp(re, 'g'), to); return s; }; + const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + const t = subst(n.nodeValue); + if (t !== n.nodeValue) n.nodeValue = t; + } + for (const e of document.querySelectorAll('input, textarea')) { + const label = (e.closest('.v-input') || e).innerText || ''; + if (e.tagName === 'TEXTAREA' && /environment/i.test(label)) e.value = env; + else if (e.value) e.value = subst(e.value); + if (e.placeholder) e.placeholder = subst(e.placeholder); + } + for (const e of document.querySelectorAll('[title]')) e.title = subst(e.title); +}""" + + +class Shots: + """A page of the studio and the captures of its tutorial.""" + + def __init__(self, page, clone, out, quality): + self.pg, self.clone, self.out, self.quality = page, clone, out, quality + user = os.environ.get("USER") or os.path.basename(os.path.expanduser("~")) + clones = sorted({clone, os.path.realpath(clone), re.sub(r"^/gpfs", "", os.path.realpath(clone))}, + key=len, reverse=True) + self.pairs = [(re.escape(c), "~/canoP") for c in clones] + self.pairs += [(r"/gpfs/softs/spack[^/]*/opt/spack/[^/]+/([A-Za-z0-9_.+-]+?)-[a-z0-9]{32}", "/opt/$1"), + (re.escape(socket.gethostname()), "login"), (r"\b%s\b" % re.escape(user), "user")] + + def neutral(self): + """Show neutral paths, names and modules in the page.""" + self.pg.evaluate(NEUTRAL_JS, [self.pairs, GENERIC_ENV]) + + def save(self, name, locator=None, clip=None): + """Capture the page (or an element, or a region) as docs/tutorial/images/.webp.""" + self.pg.evaluate("() => document.activeElement && document.activeElement.blur()") + self.pg.wait_for_timeout(800) + self.neutral() + png = locator.screenshot() if locator is not None else self.pg.screenshot(clip=clip) + image = Image.open(io.BytesIO(png)).convert("RGB") + path = os.path.join(self.out, name + ".webp") + image.save(path, "WEBP", quality=self.quality, method=6) + print("%-32s %5d x %4d %6.1f kB" % (name, image.width, image.height, os.path.getsize(path) / 1e3)) + + # -- page elements --------------------------------------------------------------------------- + + def panel(self, title): + return self.pg.locator(".v-expansion-panel").filter( + has=self.pg.locator(".v-expansion-panel-title", has_text=re.compile(r"^\s*" + title))).first + + def open_panels(self, *titles): + """Open the panels of the settings named in titles, close the others.""" + for title in ("Code and build", "Execution"): + panel = self.panel(title) + if ("v-expansion-panel--active" in (panel.get_attribute("class") or "")) != (title in titles): + panel.locator(".v-expansion-panel-title").click() + self.pg.wait_for_timeout(1000) + + def tab(self, name): + self.pg.locator(".v-tabs .v-tab", has_text=re.compile(r"^\s*%s\s*$" % name, re.I)).first.click() + self.pg.wait_for_timeout(1500) + + def select(self, label, item): + """Choose `item` in the menu labelled `label`.""" + self.pg.locator(".v-input:visible", has_text=label).first.locator(".v-field").click() + self.pg.wait_for_timeout(800) + self.pg.locator(".v-overlay--active .v-list-item", has_text=item).first.click() + self.pg.wait_for_timeout(1500) + + +def page_build(s): + """Tutorial page 1: the settings of the build and of the execution, and the build log.""" + s.pg.set_viewport_size({"width": 1600, "height": 1300}) + s.open_panels("Code and build") + s.save("build-code-panel", locator=s.panel("Code and build")) + s.open_panels("Execution") + launcher = s.pg.locator(".v-input", has_text="Launcher").first.locator(".v-select__selection").inner_text() + s.select("Launcher", "sbatch") + s.save("build-execution-panel", locator=s.panel("Execution")) + s.select("Launcher", launcher.strip()) + # narrow, so that the image is shown at about its size in the documentation + s.pg.set_viewport_size({"width": 1320, "height": 560}) + s.tab("Log") + s.pg.get_by_role("button", name="Build", exact=True).first.click() + s.pg.wait_for_timeout(3000) + s.save("build-log", clip={"x": 380, "y": 48, "width": 940, "height": 492}) + + +def wait_file(pattern, text, timeout=1800): + """Wait until a file matching `pattern` contains `text`; return its path.""" + start = time.time() + while time.time() - start < timeout: + for path in glob.glob(pattern): + with open(path, encoding="utf-8", errors="replace") as fd: + if text in fd.read(): + return path + time.sleep(5) + raise TimeoutError("no %s with %r after %d s" % (pattern, text, timeout)) + + +CONTENT = {"x": 380, "y": 48, "width": 1220, "height": 912} # tabs and tab content, viewport 1600 x 960 + + +def union(*boxes, margin=12): + """Region covering the bounding boxes, with a margin.""" + x0 = min(b["x"] for b in boxes) - margin + y0 = min(b["y"] for b in boxes) - margin + x1 = max(b["x"] + b["width"] for b in boxes) + margin + y1 = max(b["y"] + b["height"] for b in boxes) + margin + return {"x": max(x0, 0), "y": max(y0, 0), "width": x1 - max(x0, 0), "height": y1 - max(y0, 0)} + + +def page_run_input(s): + """Tutorial page 2, first part: the blast example in the editor and the description of a key.""" + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.open_panels() + s.tab("Run") + # another example first, so that the blast example is loaded again even if it is already chosen + s.select("Examples provided with the code", "onephase_gresho") + s.select("Examples provided with the code", "onephase_blast") + s.pg.wait_for_timeout(3000) + s.save("run-example", clip=CONTENT) + # the description of a key, under the mouse + blast = s.panel(r"\[blast\]") + if "v-expansion-panel--active" not in (blast.get_attribute("class") or ""): + blast.locator(".v-expansion-panel-title").click() + s.pg.wait_for_timeout(1500) + key = blast.get_by_text("radius", exact=True).first + key.hover() + s.pg.wait_for_timeout(1500) + tip = s.pg.locator(".v-overlay__content:visible").last + s.save("run-key-help", clip=union(tip.bounding_box(), key.bounding_box())) + s.pg.mouse.move(5, 5) + + +def page_run_results(s): + """Tutorial page 2, second part: initial condition, run, log, view and table of the campaign.""" + runs = os.path.join(s.clone, "_campaigns", "hors-campagne", "workspace", "*") + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.tab("Run") + s.pg.get_by_role("button", name="Load into the campaign").click() + s.pg.wait_for_timeout(4000) + s.pg.get_by_role("button", name="Initial condition").click() + wait_file(os.path.join(runs, "condition_initiale", "canoP.log"), "Kalypsso timings") + s.pg.wait_for_timeout(8000) + s.tab("View") + s.pg.get_by_label("Mesh").check() + s.pg.wait_for_timeout(3000) + s.save("run-initial-condition", clip=CONTENT) + s.pg.get_by_label("Mesh").uncheck() + s.tab("Run") + s.pg.get_by_role("button", name="Run", exact=True).click() + wait_file(os.path.join(runs, "canoP.log"), "Mcell-updates/s") + s.pg.wait_for_timeout(8000) + s.pg.set_viewport_size({"width": 1320, "height": 560}) + s.tab("Log") + s.pg.get_by_role("button", name="Simulation", exact=True).first.click() + s.pg.wait_for_timeout(3000) + s.save("run-log", clip={"x": 380, "y": 48, "width": 940, "height": 492}) + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.tab("View") + s.pg.get_by_label("Mesh").check() + s.pg.wait_for_timeout(3000) + s.save("run-view", clip=CONTENT) + s.pg.get_by_label("Mesh").uncheck() + page_run_campaign(s) + + +def page_run_campaign(s): + """Tutorial page 2, end: the run in the table of the campaign hors-campagne, with its details.""" + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.tab("Campaign") + s.select("Campaign", "hors-campagne") + for _ in range(60): # the table follows the state of the runs every few seconds + if s.pg.locator("tbody tr", has_text="finished").count(): + break + s.pg.wait_for_timeout(5000) + for _ in range(24): # the metrics are computed in the background once the run is finished + s.pg.locator("tbody tr", has_text="finished").first.get_by_text("settings_onephase_blast").click() + s.pg.wait_for_timeout(5000) + if s.pg.get_by_text(re.compile(r"^\s*Metrics")).count(): + break + s.save("run-campaign", clip=CONTENT) + + +FILES = os.path.join(HERE, "files") +CAMPAIGN = "convergence" +SWEEP = "amr.max_refine = 5, 6, 7, 8, 9" + + +def page_campaign_table(s, name="campaign-prepared"): + """The table of the campaign convergence.""" + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.tab("Campaign") + s.select("Campaign", CAMPAIGN) + s.pg.wait_for_timeout(3000) + if name: + s.save(name, clip=CONTENT) + + +def page_campaign_prepare(s): + """Tutorial page 3, first part: the base input file, the campaign, its physics and analysis, a check.""" + import shutil # pylint: disable=import-outside-toplevel + + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.open_panels() + s.tab("Run") + s.select("Examples provided with the code", "onephase_blast") + with open(os.path.join(FILES, "convergence.ini"), encoding="utf-8") as fd: + s.pg.get_by_label("Text of the ini file").fill(fd.read()) + s.pg.keyboard.press("Tab") + s.pg.wait_for_timeout(3000) + s.tab("Campaign") + s.pg.get_by_role("button", name="New campaign").click() + s.pg.wait_for_timeout(1500) + s.pg.get_by_label("Name (letters, digits, - and _)").fill(CAMPAIGN) + s.pg.get_by_label("Parameters to vary").fill(SWEEP) + s.pg.wait_for_timeout(2000) + dialog = s.pg.locator(".v-overlay--active .v-card").first + s.save("campaign-new", locator=dialog) + s.pg.get_by_role("button", name="Create").click() + dialog.wait_for(state="hidden", timeout=300000) # the campaign is made: signac project, git, physics + s.pg.wait_for_timeout(3000) + # the physics and the analysis of the campaign: files of its directory + root = os.path.join(s.clone, "_campaigns", CAMPAIGN) + shutil.copy(os.path.join(FILES, "sine.py"), os.path.join(root, "physics", "onephase", "initial_conditions")) + shutil.copy(os.path.join(FILES, "analysis.py"), root) + page_campaign_table(s, "campaign-prepared") + # check the initial condition of the coarsest run + s.pg.locator("tbody tr").first.click() + s.pg.wait_for_timeout(2000) + s.pg.get_by_role("button", name="View").first.click() + s.pg.wait_for_timeout(3000) + s.tab("Run") + s.pg.get_by_role("button", name="Initial condition").click() + wait_file(os.path.join(root, "workspace", "*", "condition_initiale", "canoP.log"), "Kalypsso timings") + s.pg.wait_for_timeout(8000) + s.tab("View") + s.pg.get_by_label("Mesh").check() + s.pg.wait_for_timeout(3000) + s.save("campaign-initial-condition", clip=CONTENT) + s.pg.get_by_label("Mesh").uncheck() + + +def page_campaign_launch(s, threads=16): + """Tutorial page 3, second part: the launch of the prepared runs with sbatch, and the finished table.""" + s.pg.set_viewport_size({"width": 1600, "height": 960}) + # a campaign is launched with sbatch: one run per Slurm job, here 1 process of `threads` threads + s.open_panels("Execution") + s.select("Launcher", "sbatch") + s.pg.get_by_label("OpenMP threads").fill(str(threads)) + s.pg.keyboard.press("Tab") + s.pg.wait_for_timeout(2000) + s.open_panels() + page_campaign_table(s, None) + s.pg.get_by_role("button", name=re.compile(r"Launch the prepared runs")).click() + s.pg.wait_for_timeout(1500) + dialog = s.pg.locator(".v-overlay--active .v-card").first + s.save("campaign-launch", locator=dialog) + dialog.get_by_role("button", name="Run", exact=True).click() + dialog.wait_for(state="hidden", timeout=300000) + page_campaign_finished(s) + + +def page_campaign_finished(s): + """The table of the campaign once its runs are finished.""" + page_campaign_table(s, None) + rows = s.pg.locator(".v-table").first.locator("tbody tr") # the runs, not the details of a run + for _ in range(720): # the table follows the state of the runs every few seconds + if rows.count() and rows.filter(has_text="finished").count() == rows.count(): + break + s.pg.wait_for_timeout(5000) + s.pg.wait_for_timeout(30000) # the metrics of the last run + page_campaign_table(s, "campaign-finished") + + +def page_campaign_analysis(s): + """Tutorial page 3, end: the Analysis tab, with the graph of the tab and the panel of analysis.py.""" + s.pg.set_viewport_size({"width": 1600, "height": 960}) + s.tab("Analysis") + s.select("Campaign", CAMPAIGN) + s.select("Parameter (x)", "amr.max_refine") + s.select("Metric (y)", "elapsed_s") + s.pg.wait_for_timeout(8000) # analyse() reads the last output of each run + s.save("campaign-analysis", clip=CONTENT) + + +def page_run(s): + """Tutorial page 2: a run outside campaigns (blast example): input file, initial condition, run, results.""" + page_run_input(s) + page_run_results(s) + + +def page_campaign(s): + """Tutorial page 3: the campaign, its initial condition, the launch of its runs (sbatch) and the analysis.""" + page_campaign_prepare(s) + page_campaign_launch(s) + page_campaign_analysis(s) + + +PAGES = {"build": page_build, "run": page_run, "campaign": page_campaign} +# parts of the pages, to take some captures again +PARTS = {"run-input": page_run_input, "run-campaign": page_run_campaign, "campaign-prepare": page_campaign_prepare, + "campaign-table": page_campaign_table, "campaign-launch": page_campaign_launch, + "campaign-finished": page_campaign_finished, "campaign-analysis": page_campaign_analysis} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--clone", required=True, help="canoP clone the studio runs from") + parser.add_argument("--port", type=int, required=True, help="port of the studio on this machine") + parser.add_argument("--out", default=os.path.join(HERE, "images"), help="directory of the images") + parser.add_argument("--quality", type=int, default=82, help="WebP quality (100: best)") + parser.add_argument("pages", nargs="*", default=list(PAGES), choices=list(PAGES) + list(PARTS), + help="pages of the tutorial (%s, default: all, in this order) or parts of them (%s)" + % (", ".join(PAGES), ", ".join(PARTS))) + args = parser.parse_args() + with open(os.path.join(args.clone, ".local", "canop-studio", "auth_key"), encoding="utf-8") as fd: + key = fd.read().strip() + os.makedirs(args.out, exist_ok=True) + with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page(viewport={"width": 1600, "height": 1000}, device_scale_factor=2) + page.goto("http://localhost:%d/index.html?secret=%s" % (args.port, key), wait_until="networkidle") + page.wait_for_timeout(4000) + shots = Shots(page, args.clone, args.out, args.quality) + for name in args.pages: + dict(PAGES, **PARTS)[name](shots) + browser.close() + + +if __name__ == "__main__": + main()