12. Individual Phase Week 3 — Earthquake Sources, Rendering & CPU Pinning ========================================================================= Overview -------- Three strands this week: the Okada earthquake source becomes usable end-to-end (click a subduction zone, pick a magnitude, get a physical seafloor displacement), the renderer stays smooth at every zoom level, and ``tsunami_lab_viz`` is pinned so the visualization keeps one fixed CPU core while OpenMP gets a dedicated, undisturbed set of worker threads — one per performance core — for maximum solver throughput. GUI-Thread CPU Pinning ----------------------- Thread architecture of ``tsunami_lab_viz`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``tsunami_lab_viz`` runs three kinds of threads in one process: the GUI/render loop (main thread), a background ``SolverThread`` that drives ``WavePropagation2d::timeStep`` in a loop, and — for the duration of each ``timeStep`` call — the OpenMP worker pool spawned by its parallel regions (see :doc:`09_parallelization`). Only the GUI thread never enters an OpenMP parallel region. The ``SolverThread`` *does*: the first time it hits a parallel construct, libgomp treats it as the team's master thread and, if ``OMP_PROC_BIND`` is set, pins it to the first entry of ``OMP_PLACES`` — so it is automatically covered by the OpenMP placement below. The GUI thread is the only one left unpinned, and since a busy GUI thread on the same core as an OpenMP worker causes visible stutter and steals cycles from the solver, it is pinned explicitly via ``pthread_setaffinity_np`` in ``tsunami_lab::util::pinThreadToCore()`` (``src/util/CpuAffinity.cpp``), called at the very start of ``main()`` in ``src/main_viz.cpp``. This pinning is opt-in through the ``TSUNAMI_VIZ_CORE`` environment variable (a logical CPU id) so it has no effect unless requested, and is a no-op on non-Linux platforms: .. code-block:: bash TSUNAMI_VIZ_CORE=0 ./build/tsunami_lab_viz Running on different machines: ``scripts/viz_pinning_env.sh`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Which logical CPU id to reserve, and which ids to hand to OpenMP, depends on the machine's core topology (see below) — the concrete numbers used above (``TSUNAMI_VIZ_CORE=0``, cores 1–11 for OpenMP) only apply to the 12-core machine they were measured on. Rather than re-deriving them by hand on every new machine, ``scripts/viz_pinning_env.sh`` detects the topology and computes them automatically: .. code-block:: bash # option 1: detect + run in one step scripts/viz_pinning_env.sh ./build/tsunami_lab_viz # option 2: export into the current shell, then run manually eval "$(scripts/viz_pinning_env.sh)" ./build/tsunami_lab_viz On **Linux** it distinguishes the same two cases described below: on a hybrid CPU it reads ``/sys/devices/cpu_core/cpus`` / ``cpu_atom/cpus`` and reserves an E-core for the GUI while giving OpenMP all P-cores; otherwise it groups logical CPUs by physical core via ``lscpu -p=CPU,CORE,ONLINE``, reserves one physical core for the GUI and gives OpenMP one thread per remaining physical core (leaving SMT siblings idle). If ``lscpu`` isn't installed, or only one physical core is found, it leaves the pinning variables unset rather than guessing. On **macOS** there is no user-space hard CPU-affinity API — no ``pthread_setaffinity_np`` equivalent, and libomp doesn't honour ``OMP_PLACES`` there — so ``pinThreadToCore()`` is a no-op by design (see above) and the script does not set ``TSUNAMI_VIZ_CORE``/``OMP_PLACES``/ ``OMP_PROC_BIND`` at all. It still tunes ``OMP_NUM_THREADS`` via ``sysctl``: on Apple Silicon it uses ``hw.perflevel0.physicalcpu`` (the performance-core count, ``hw.perflevel1.physicalcpu`` efficiency cores excluded); on Intel Macs / unknown topologies it uses ``hw.physicalcpu - 1``, reserving one core for the GUI *by count only* — the OS scheduler, not the app, decides which physical core actually runs it. It always prints what it detected to stderr, so the chosen cores/counts stay visible even when redirected into ``eval``. Finding which cores to use (manual / how the script decides) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The goal is to reserve **one fixed core for the GUI thread** and let **OpenMP use as many threads as there are performance cores**, without the two competing for the same physical core. Which cores count as "performance" depends on the CPU: * **Hybrid CPUs with P-cores/E-cores** (Intel Alder Lake and newer): the kernel exposes the split directly: .. code-block:: bash cat /sys/devices/cpu_core/cpus # performance (P) cores cat /sys/devices/cpu_atom/cpus # efficiency (E) cores Pin the GUI thread to one E-core (it doesn't need P-core performance) and give OpenMP the P-core list. * **Homogeneous CPUs with SMT/Hyper-Threading** (e.g. AMD Ryzen, most Intel desktop/server chips without E-cores): there are no "performance cores" in the hybrid sense — the relevant distinction is *physical core* vs. *SMT sibling*. For a compute-bound kernel like the wave solver, running one OpenMP thread per **physical** core beats using both SMT siblings (the siblings share execution units, so the second one adds little throughput but doubles synchronisation overhead). List the physical-core groups with: .. code-block:: bash lscpu -e=CPU,CORE,ONLINE Two logical CPUs with the same ``CORE`` value are SMT siblings of the same physical core; pick one per group for OpenMP and leave the rest — including one full physical core reserved for the GUI thread — out of the OpenMP set. Example on a 12-core/24-thread machine (CPUs 0–11 and 12–23 are SMT sibling pairs, i.e. CPU *n* and *n+12* share a physical core): reserve physical core 0 (logical CPUs 0 and 12) for the GUI and give OpenMP one thread per remaining physical core (1–11, i.e. logical CPUs 1–11): .. code-block:: bash TSUNAMI_VIZ_CORE=0 \ OMP_NUM_THREADS=11 OMP_PROC_BIND=close \ OMP_PLACES="{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}" \ ./build/tsunami_lab_viz * **Multi-socket / NUMA machines** (see the Grace benchmarks in :doc:`09_parallelization`): also keep the OpenMP set within a single NUMA node (``numactl -H`` or ``lscpu`` show the node boundaries) — crossing sockets is far more costly than losing one core to the GUI. Note that ``OMP_PLACES`` only affects OpenMP threads (including the ``SolverThread`` once it enters a parallel region); it does not touch the GUI thread, which is why ``TSUNAMI_VIZ_CORE`` is needed in addition to the existing ``OMP_*`` variables. Wrapping the whole process in ``taskset`` instead is *not* equivalent — it would also confine the OpenMP threads to the same restricted set and remove the separation. Solver Vectorization & Dry-Cell CFL Fix ---------------------------------------- Follow-up performance work on ``WavePropagation2d`` / ``FWave`` (measured on an Apple M4, ``DamBreak2d`` with 1000x1000 cells): - ``FWave::netUpdates`` rewritten branch-free (wet/dry handling and wave accumulation via selects, same semantics incl. NaN cases) and force-inlined. - X-sweep decoupled through per-thread edge buffers: net updates are stored per edge, then applied in a second elementwise loop. This removes the read-write overlap on cell ``ix+1`` between consecutive edges — together with ``__restrict`` pointers all sweep loops now auto-vectorize (NEON, verified with ``-Rpass=loop-vectorize``). - Memory passes fused: the copy pass now lives inside the X-sweep, the NaN/negativity clamp inside the black Y-phase (5 grid passes → 3). - ``OMP_SCHEDULE`` fallback is now platform-dependent: ``guided`` on Apple Silicon (with ``static`` the slowest E-core gates every barrier; guided lets E-cores contribute), ``static`` elsewhere (NUMA first-touch). Result: 10.9 → 5.0 ns per cell and iteration single-threaded, 3.6 → 1.15 ns with 10 threads (~3x). Separately, the visualization's time-scale factor collapsed (x90 → x7) once the wave reached a coast: drying cells (``0 < h <= c_dryTolerance``) keep their leftover momentum frozen (the solver masks their updates), and ``SolverThread::maxWaveSpeed()`` counted them via ``u = hu/h`` with a tiny ``h``, shrinking dt for the rest of the run. Fixed twofold: ``maxWaveSpeed`` skips cells the solver treats as dry, and the clamp phase of ``timeStep`` flushes ``hu``/``hv`` in dry cells. Regression tests: ``[WaveProp2dDryFlush]``, ``[DryCFL]``. Earthquake Source: Okada End-to-End ------------------------------------ The ``GaussianDisplacement`` placeholder is replaced by the Okada dislocation model researched in :doc:`11_individual_week2`: - ``displacement/OkadaDisplacement`` implements the 1985 half-space solution for the vertical component ``u_z``, with unit tests against known analytic cases; the horizontal components ``u_x``/``u_y`` were added afterwards and validated against the reference ``okada85.m``. - ``io/Slab2Reader`` reads the global Slab2 NetCDF depth/dip/strike rasters and downloads them on first run. ``displacement/OkadaFactory`` combines them with the Wells & Coppersmith (1994) scaling relations (``displacement/WellsCoppersmith.h``) so a click position plus a moment magnitude fully determine the fault; a click outside any modelled slab samples *NaN* and is rejected. - With ``u_x``/``u_y`` available, the **Tanioka–Satake** correction is applied in both the region preview and the live simulation: horizontal motion of a sloping seafloor contributes :math:`u_z^{\text{eff}} = u_z + u_x \partial_x b + u_y \partial_y b`, which matters most on the steep slab-facing flank of the trench. Robustness fixes that fell out of running real Okada sources over GEBCO bathymetry: ``FWave`` now treats cells at or below ``c_dryTolerance`` as dry instead of testing ``h <= 0`` (vanishingly thin wet cells blew up :math:`u = hu/h`), ``WavePropagation2d`` resets non-finite cells to dry, the live GEBCO setup floors the initial water depth at the dry tolerance, and ``SolverThread`` re-derives its CFL-stable scaling every step instead of once from the still initial state — wave speeds that only grow later (shoaling, run-up) previously broke the CFL bound. Rendering & Interaction ------------------------ - **Mesh LOD + frustum culling** (``visualization/Lod.h``): the terrain and water meshes are drawn at a distance-dependent resolution and off-screen blocks are skipped, keeping the frame rate stable from globe to street-level zoom. A follow-up fixed blocks being culled at grazing camera angles. - **MSAA** raised to 4x and then 8x: the dense mesh (up to 1200² cells) collapses into sub-pixel triangles when zoomed out, which flickered as white speckles without multisampling. - **Coastal seabed artifacts:** dry cells are no longer discarded from the water mesh, so it doubles as a gap-free water sheet; while simulating, the terrain is drawn in two passes (land writes depth and occludes the water, seabed is colour-only) so no bare shallow seabed shows through. - **Slab2 on the globe:** depth-graded subduction zones with hover info and click-to-suggest region, plus the slab-depth legend folded into the shared bottom-right legend panel. - **Displacement on click in a worker thread** instead of behind a button, so the GUI stays responsive while the field is built. - **Historical scenarios** (``visualization/Scenario.h``, ``displacement/SubductionScaling.h``): selectable real events that preset region, epicentre and magnitude. - Smaller UI/CI work: non-Latin-1 glyphs replaced and panels widened with text wrapping; GitHub Pages deployment without a separate branch. Individual Contributions ------------------------- - **Yannik Köllmann:** ``tsunami_lab::util::pinThreadToCore()`` GUI-thread pinning via ``TSUNAMI_VIZ_CORE``; branchless/vectorized FWave kernel, fused sweep passes and dry-cell CFL fix (see above); wrote this chapter. - **Jan Vogt:** mesh LOD and frustum culling incl. the grazing-angle fix; MSAA; coastal seabed/water-sheet fix; Slab2 overlay on the globe with hover info and click-to-suggest region; shared legend panel; displacement built in a worker thread on click; historical scenarios; UI text fixes and the single-branch Pages deployment. - **Mika Brückner:** Okada displacement model (``u_z`` and ``u_x``/``u_y``) with unit tests and ``okada85.m`` validation; Slab2 NetCDF reader with first-run download; ``OkadaFactory`` + Wells & Coppersmith fault scaling; click-and-magnitude quake input with subduction overlay in the region view; Tanioka–Satake correction; dry-tolerance and CFL-scaling stability fixes.