Devlog #95 – Applied Science Batch: 12 New Simulations Across 11 Categories

This batch is about breadth, not spectacle. Twelve new simulations — each in English and Ukrainian — lift several categories that were running thin: relativity, optics, machine learning, climate, perception, game math, gamedev, combinatorics, civil engineering, medtech, and agronomy. From the gravitational redshift of light leaving a black hole to the soil-water bucket model behind a farmer’s irrigation schedule, this is applied science you can poke at in a browser tab.

12 simulations across 11 categories

An applied-science batch, bilingual from day one

Every simulation in this batch ships with full English and Ukrainian copy, the same equations, and the same interactive controls. The goal was to deepen categories that had only one or two entries — civil engineering, medtech, agronomy, perception — so the library is broad as well as deep. The site now stands at 650 simulations.

650
Total simulations
12
New this batch
11
Categories touched
95
Devlog #

New Simulations

🔴

Gravitational Redshift relativity

Schwarzschild redshift of light climbing out of a gravity well. Five bodies from Earth to a black hole, an animated photon whose wavelength shifts toward red, and the Pound–Rebka experiment (z ≈ 2.46×10−¹&sup5;).

🌈

Diffraction Grating optics

N-slit interference intensity with the principal-maximum and sinc-envelope structure, the grating equation, monochromatic vs white light, resolving power R = mN, and 6 presets.

🌲

Random Forest machine-learning

Bootstrap aggregating plus random feature subsets of decision trees. Watch a single overfitting tree versus a 50-tree ensemble, Gini impurity splits, out-of-bag error, and the smoothed decision boundary.

🌊

El Niño (ENSO) climate

The delayed-oscillator model of the El Niño–Southern Oscillation: a tilting Pacific thermocline, the Oceanic Niño Index threshold of ±0.5°C, and the irregular 2–7 year cycle.

👁️

Gestalt Grouping perception

Six grouping principles in action: proximity, similarity, closure (Kanizsa triangle), continuity, common fate, and figure–ground (Rubin’s vase).

🎲

Dice Probability game-math

The sum-of-dice distribution as a convolution converging to a Gaussian (central limit theorem), the law of large numbers, mean and variance formulas, and real casino odds.

🏰

Procedural Dungeon gamedev

Three classic generation algorithms: BSP partitioning, random rooms joined by a spanning-tree corridor graph, and cellular-automata caves — all driven by a seeded linear congruential generator.

🔢

Catalan Numbers combinatorics

The Catalan sequence and five of its bijections: balanced parentheses, Dyck paths, binary trees, polygon triangulations, and non-crossing chords, with the ratio Cₙ₊₁/Cₙ → 4.

🧱

Retaining Wall civil-engineering

Rankine active earth pressure, the resultant thrust acting at H/3, factors of safety against overturning and sliding, base eccentricity, and an animated failure mode.

🩸

Haemodialysis medtech

Countercurrent urea clearance, single-pool kinetics, the Kt/V adequacy target, and the urea reduction ratio — the maths behind a dialysis prescription.

🌱

Photosynthesis agronomy

The light-response curve with compensation and saturation points, Blackman’s law of limiting factors, dark respiration, and C3 vs C4 presets.

💧

Irrigation & Soil Water agronomy

The soil-water balance, field capacity and wilting point, the management-allowed depletion trigger, crop evapotranspiration ET = ET₀·Kc, and deficit irrigation.

Gravitational Redshift: Light Climbing Out of a Well

When a photon climbs away from a massive body, it loses energy — not by slowing down (light never does) but by stretching its wavelength. This gravitational redshift is a direct consequence of general relativity and time dilation: clocks deeper in a gravitational well run slow, so a wave emitted there is measured to have a lower frequency when received higher up.

For a non-rotating spherical mass, the Schwarzschild metric gives the exact ratio between the received and emitted frequency in terms of the Schwarzschild radius and the radial positions of emitter and receiver. The simulation lets you choose from five bodies — Earth, the Sun, a white dwarf, a neutron star, and a black hole — and animates a single photon climbing outward, its colour drifting from blue toward red as the wavelength shift is mapped to an RGB value.

The classic terrestrial test is the Pound–Rebka experiment (1959), which measured the tiny redshift of gamma rays climbing a 22.5 m tower at Harvard — a fractional shift of only about 2.46×10−¹&sup5;, confirmed using the Mössbauer effect.

R_s   = 2GM / c^2                  (Schwarzschild radius)
f_recv / f_emit = sqrt(1 - R_s/r_emit) / sqrt(1 - R_s/r_recv)
z     = (lambda_recv - lambda_emit) / lambda_emit
Pound-Rebka:  z = gh/c^2 ≈ 2.46e-15  (h = 22.5 m)

Diffraction Grating: N-Slit Interference

A diffraction grating is a surface ruled with thousands of equally spaced slits or grooves per millimetre. Light passing through it interferes constructively only in specific directions, splitting white light into sharp spectral lines — the working principle of every laboratory spectrometer.

The intensity pattern is the product of two factors: a multi-slit interference term that sharpens dramatically as the number of slits N grows, and a single-slit sinc diffraction envelope that modulates the peak heights. Principal maxima appear wherever the path difference between adjacent slits is a whole number of wavelengths, given by the grating equation. The ability to separate two close wavelengths — the resolving power — scales with both the order m and the number of illuminated slits N.

The simulation offers monochromatic and white-light modes, six presets from a coarse 100 lines/mm grating to a fine 1200 lines/mm one, and a live read-out of the resolving power.

I(theta) = I0 * [ sin(N*delta/2) / (N*sin(delta/2)) ]^2 * sinc^2(beta)
delta    = (2*pi*d/lambda) * sin(theta)        (phase between slits)
d * (sin(theta_i) + sin(theta_m)) = m*lambda   (grating equation)
R        = lambda / d(lambda) = m*N            (resolving power)

Random Forest: Wisdom of Many Trees

A single decision tree is easy to interpret but prone to overfitting: grown deep enough, it will memorise the training data and produce a jagged, brittle decision boundary. A random forest tames this by training many trees on different bootstrap samples of the data, and at each split considering only a random subset of features. Averaging their votes cancels out the individual quirks.

Each split is chosen to maximise the reduction in Gini impurity — a measure of how mixed the class labels are in a node. Because each tree is trained on a bootstrap sample, roughly a third of the data is left out of each tree; those out-of-bag samples give an honest, cross-validation-free estimate of generalisation error.

The simulation contrasts a single deep tree, whose boundary clings to every outlier, with a 50-tree ensemble whose boundary is smooth and robust — a vivid demonstration of variance reduction through bagging.

Gini(node) = 1 - sum_k p_k^2          (impurity, p_k = class fraction)
Bootstrap: sample n points with replacement per tree
Feature bag: choose sqrt(p) features at each split
OOB error: predict each point using only trees that didn't see it
Vote: majority class over all trees

El Niño: The Delayed Oscillator

The El Niño–Southern Oscillation (ENSO) is the largest source of year-to-year climate variability on Earth. It arises from a coupled feedback between the tropical Pacific Ocean and the atmosphere above it: warm sea-surface temperatures weaken the trade winds, which flatten the thermocline, which warms the surface further — a positive feedback that would run away were it not for a delayed negative feedback carried by slow ocean waves crossing the basin.

The delayed-oscillator model captures this with a single equation: a local positive growth term, a delayed negative term representing waves that reflect off the western boundary and return after a time lag, and a cubic term that limits the amplitude. The result is a self-sustaining but irregular oscillation with a period of two to seven years.

The simulation tilts the Pacific thermocline in real time and tracks the Oceanic Niño Index, declaring an El Niño or La Niña event whenever the index crosses ±0.5°C for a sustained period.

dT/dt = a*T(t) - b*T(t - tau) - eps*T(t)^3
  a   : local coupled growth (Bjerknes feedback)
  b   : delayed wave feedback (negative)
  tau : ocean wave crossing/reflection delay
ONI event:  |T| > 0.5 C sustained;  period ≈ 2-7 years

Gestalt Grouping: How the Eye Organises

Gestalt psychology, developed in early 20th-century Germany, holds that the visual system perceives whole, organised forms rather than isolated parts — “the whole is other than the sum of its parts.” A handful of grouping principles describe how scattered elements snap into coherent objects.

The simulation demonstrates six of them interactively. Proximity groups nearby dots into rows or columns; similarity groups by colour or shape; closure lets the mind complete an interrupted contour, famously producing the illusory Kanizsa triangle; continuity favours smooth, continuous lines; common fate binds elements that move together; and figure–ground organisation forces a choice between two readings, as in Rubin’s reversible vase–faces image.

Each principle has a toggle that lets you watch the same elements re-group as you change spacing, colour, motion, or contour completeness — a direct, manipulable window onto perceptual organisation.

Dice Probability: Convolution to the Bell Curve

Rolling a single fair die gives a flat, uniform distribution. Sum two dice and the distribution becomes triangular; sum many and it grows into the familiar bell curve. This is the central limit theorem made tangible: the distribution of a sum of independent identically distributed variables tends toward a Gaussian, regardless of the shape of the individual distribution.

Mechanically, the probability mass function of a sum of dice is the repeated convolution of the single-die distribution with itself. The simulation builds this PMF directly and overlays the limiting Gaussian, while a separate panel rolls thousands of times to show the running average settling onto the theoretical mean — the law of large numbers.

E[sum]   = n * (s + 1) / 2
Var[sum] = n * (s^2 - 1) / 12          (n dice, s sides each)
P_sum    = P_die * P_die * ... (n-fold convolution)
CLT:  standardised sum -> Normal(0,1) as n grows
LLN:  sample mean -> E[X] as rolls grow

Procedural Dungeon: Three Generators, One Seed

Procedural generation lets a game build endless, varied levels from a few lines of code and a random seed. The simulation implements three canonical dungeon generators side by side, all driven by the same seeded linear congruential generator so that any layout is exactly reproducible.

Binary space partitioning recursively splits the map into ever-smaller rectangles, then places a room inside each leaf and connects sibling rooms — producing tidy, architecturally believable dungeons. The random-rooms method scatters rectangles, discards overlaps, and joins the survivors with corridors derived from a minimum spanning tree, giving an organic warren. Cellular automata start from random noise and repeatedly apply a smoothing rule, carving cave systems with soft, natural walls.

LCG:  x = (a*x + c) mod m            (deterministic, seed-driven)
BSP:  split rect; recurse; room per leaf; connect siblings
Rooms+MST: place rects; reject overlaps; corridors via spanning tree
Caves: random fill p; repeat: cell = (neighbours_wall >= 5)

Catalan Numbers: One Sequence, Many Faces

The Catalan numbers 1, 1, 2, 5, 14, 42, 132… appear in an astonishing range of counting problems. The simulation shows five of them as live, manipulable bijections, making vivid the surprising fact that all are counted by the very same sequence.

The nth Catalan number counts the ways to balance n pairs of parentheses, the monotonic lattice paths that stay below the diagonal (Dyck paths), the shapes of binary trees with n internal nodes, the triangulations of a convex polygon, and the ways to draw non-crossing chords joining 2n points on a circle. Drag a slider for n and every panel re-enumerates in lockstep.

C_n = (2n)! / ((n+1)! * n!) = binom(2n, n) / (n + 1)
Recurrence:  C_{n+1} = sum_{i=0..n} C_i * C_{n-i}
Asymptotic ratio:  C_{n+1} / C_n -> 4  as n grows
n:    0 1 2 3 4  5   6
C_n:  1 1 2 5 14 42 132

Retaining Wall: Earth Pressure and Safety

A retaining wall holds back a mass of soil that would otherwise slump to its natural angle of repose. Designing one means quantifying the horizontal thrust the soil exerts and proving the wall will not tip over, slide forward, or overload the ground beneath it.

Rankine’s theory gives the active earth-pressure coefficient as a function of the soil’s friction angle. The pressure grows linearly with depth, so its resultant thrust acts at one-third of the wall height from the base. The simulation computes factors of safety against overturning and sliding, the eccentricity of the resultant on the base, and plays an animated failure when a safety factor drops below its threshold.

K_a   = tan^2(45 - phi/2)              (Rankine active coefficient)
P_a   = 0.5 * K_a * gamma * H^2        (thrust, acting at H/3)
FS_overturning = M_resist / M_overturn   >= 2.0
FS_sliding     = (mu * N) / P_a          >= 1.5
e     = B/2 - (M_net / N)               (base eccentricity)

Haemodialysis: A Membrane for a Kidney

When kidneys fail, a dialysis machine takes over the job of clearing waste solutes from the blood. Blood and a clean dialysate fluid flow on opposite sides of a semipermeable membrane, and small molecules such as urea diffuse down their concentration gradient from blood to dialysate.

Running the two flows countercurrent — in opposite directions — keeps the concentration gradient high along the whole length of the membrane, maximising clearance. The simulation models the falling blood urea concentration with single-pool kinetics and reports the two clinical adequacy measures: the dimensionless Kt/V and the urea reduction ratio.

C(t)  = C0 * exp(-K * t / V)           (single-pool urea kinetics)
  K   : dialyser clearance (mL/min)
  V   : urea distribution volume
Kt/V  >= 1.2     (adequacy target per session)
URR   = (C0 - C_end) / C0 * 100%

Photosynthesis: The Light-Response Curve

The rate at which a leaf fixes carbon depends, among other things, on how much light it receives. At low light, the rate climbs almost linearly; as light intensifies, the rate saturates because the biochemical machinery cannot keep up. Below a certain light level — the compensation point — respiration outpaces photosynthesis and the leaf is a net carbon emitter.

The simulation models net assimilation with a non-rectangular hyperbola driven by the quantum yield and the light-saturated maximum rate, minus a constant dark-respiration term. It marks the compensation and saturation points and illustrates Blackman’s law of limiting factors — the idea that the slowest input caps the overall rate. C3 and C4 presets show why C4 plants, which concentrate CO₂ around their fixing enzyme, outperform C3 plants under bright, hot conditions.

A_net = (phi*I * A_max) / (phi*I + A_max) - R_d
  phi   : quantum yield (mol CO2 per mol photons)
  I     : photon flux;   A_max : light-saturated rate
  R_d   : dark respiration
Compensation point:  A_net = 0
Saturation point:    dA/dI ≈ 0  (Blackman limiting)

Irrigation: The Soil-Water Bucket

A field’s root zone behaves like a leaky bucket. Rain and irrigation fill it; crop transpiration, deep drainage, and runoff empty it. Sound irrigation scheduling means knowing how full the bucket is and refilling it before the crop runs short.

The bucket is bounded by two soil properties: field capacity, the water held after gravity drains the excess, and the wilting point, below which roots can no longer extract water. The plant-available water lies between them, and a management-allowed depletion fraction sets the trigger for the next irrigation. Crop water demand is the reference evapotranspiration scaled by a crop coefficient; the simulation also explores deficit irrigation, where deliberately under-watering saves water at a modest yield cost.

delta_S = P + I - ET - D - R           (soil-water balance)
  P,I : precipitation, irrigation;  D,R : drainage, runoff
ET    = ET0 * Kc                       (crop evapotranspiration)
TAW   = (FC - WP) * root_depth         (total available water)
Trigger irrigation when depletion >= MAD * TAW

Up Next

That wraps the applied-science batch — 12 simulations, 11 categories, all bilingual, bringing the library to 650. With civil engineering, medtech, and agronomy now better represented, the next batch will return to the physics and pure-maths backbone while we keep filling perception and game-math gaps. Browse everything in the blog archive.

← Devlog #94: Wave 73 All posts →