Fichier d’origine (260 × 310 pixels, taille du fichier : 344 kio, type MIME : image/gif, en boucle, 144 trames, 10 s)

    Ce fichier et sa description proviennent de Wikimedia Commons.

    Description

     Cette image matricielle GIF a été créée avec Python.
    Description
    Français : Simulation d'une planche de Galton à 10 rangées : à chaque clou, une bille part à gauche ou à droite avec une probabilité ½, et les piles obtenues approchent la loi binomiale B(10, ½) (en pointillés).
    Date
    Source Travail personnel
    Auteur ou autrice Global Donald

    Conditions d’utilisation

    Moi, en tant que détenteur des droits d’auteur sur cette œuvre, je la publie sous la licence suivante :
    Creative Commons CC-Zero Ce fichier est dans le domaine public selon les termes de la licence Creative Commons CC0 1.0 Universel.
    La personne qui a associé une œuvre avec cet acte l’a placée dans le domaine public en renonçant mondialement à tous ses droits sur cette œuvre en vertu des lois relatives au droit d’auteur, ainsi qu’à tous les droits juridiques connexes et voisins qu’elle possédait sur l’œuvre, sans autre limite que celles imposées par la loi. Vous pouvez copier, modifier, distribuer et utiliser cette œuvre, y compris à des fins commerciales, sans qu’il soit nécessaire d’en demander la permission.

    Source code

    Python script used to generate this animation
    import numpy as np
    from PIL import Image, ImageDraw, ImageFont
     
    OUT = sys.argv[1] if len(sys.argv) > 1 else "Planche_de_Galton_animation.gif"
    SEED = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    W, H, S, DELAY = 260, 310, 4, 60
    ROWS = 10
    NB = ROWS + 1
    SP = 21.0                                   # peg spacing (= bin width)
    CX = W / 2
    Y_TOP, DY = 34.0, 13.0                      # first peg row, row spacing
    PEG_R, BALL_R = 1.9, 2.75
    FLOOR = 300.0
    BIN_TOP = Y_TOP + (ROWS - 1) * DY + 14
    FR_ROW = 2                                  # frames per row
     
    BG, PEG, WALL, BALL, BALL_NEW, CURVE, TXT, TXT2 = ((255, 255, 255), (84, 89, 93), (162, 169, 177),
                                                        (51, 102, 204), (32, 64, 140), (215, 51, 51),
                                                        (32, 33, 34), (114, 119, 125))
    F_SEMI = "/usr/share/fonts/opentype/inter/Inter-SemiBold.otf"
     
    # ----------------------------------------------------------------- simulation
    rng = np.random.default_rng(SEED)
    release = []
    f = 0
    for i in range(230):                        # release schedule: 1, then 2, then 3 balls per frame
        rate = 1 if f < 30 else (2 if f < 60 else 3)
        release.append(f + (i % rate) / rate)          # staggered within the frame
        if (i + 1) % rate == 0:
            f += 1
    release = np.array(release, float)
    N = len(release)
    steps = rng.integers(0, 2, (N, ROWS))       # 1 = right
    bins = steps.sum(1)
    T_FALL = ROWS * FR_ROW
    DROP = 5
     
     
    def bin_x(k):
        return CX + (k - ROWS / 2) * SP
     
     
    def peg_xy(r, j):
        return CX + (j - r / 2) * SP, Y_TOP + r * DY
     
     
    # landing order -> slot in its bin
    land = release + T_FALL + DROP
    slot = np.zeros(N, int)
    cnt = np.zeros(NB, int)
    for i in np.argsort(land, kind="stable"):
        slot[i] = cnt[bins[i]]
        cnt[bins[i]] += 1
    PER_ROW = 3
    ROW_H = BALL_R * 2 * 0.87
     
     
    def slot_xy(k, s):
        row, col = divmod(s, PER_ROW)
        dx = (col - 1) * BALL_R * 2.05 + (BALL_R if row % 2 else 0) * 0.0
        return bin_x(k) + dx, FLOOR - BALL_R - 0.5 - row * ROW_H
     
     
    def ball_pos(i, fr):
        """Position of ball i at frame fr, or None if not released / ('landed', xy)."""
        t = fr - release[i]
        if t < 0:
            return None
        if t >= T_FALL + DROP:
            return ("landed", slot_xy(bins[i], slot[i]))
        if t < T_FALL:
            r = int(t // FR_ROW)
            s = (t - r * FR_ROW) / FR_ROW
            k0 = steps[i, :r].sum()
            x0, y0 = peg_xy(r, k0)
            if r + 1 < ROWS:
                k1 = k0 + steps[i, r]
                x1, y1 = peg_xy(r + 1, k1)
            else:
                k1 = k0 + steps[i, r]
                x1, y1 = bin_x(k1), BIN_TOP
            x = x0 + (x1 - x0) * s
            y = y0 + (y1 - y0) * s - 5.0 * 4 * s * (1 - s)          # small hop over the peg
            return ("fly", (x, y - PEG_R - BALL_R))
        s = (t - T_FALL) / DROP                                    # free fall to the pile
        x, y1 = slot_xy(bins[i], slot[i])
        y = BIN_TOP - PEG_R - BALL_R + (y1 - BIN_TOP + PEG_R + BALL_R) * s * s
        return ("fly", (x, y))
     
     
    EXPECT = [N * comb(ROWS, k) / 2 ** ROWS for k in range(NB)]
     
     
    def render(fr, fade=1.0, curve=0.0):
        img = Image.new("RGB", (W * S, H * S), BG)
        d = ImageDraw.Draw(img)
     
        def P(x, y):
            return x * S, y * S
     
        def mix(c, a):
            return tuple(int(BG[j] + (c[j] - BG[j]) * a) for j in range(3))
     
        # funnel
        d.line([P(CX - 26, 10), P(CX - 5, Y_TOP - 10)], fill=PEG, width=round(1.2 * S))
        d.line([P(CX + 26, 10), P(CX + 5, Y_TOP - 10)], fill=PEG, width=round(1.2 * S))
        # pegs
        for r in range(ROWS):
            for j in range(r + 1):
                x, y = peg_xy(r, j)
                d.ellipse([P(x - PEG_R, y - PEG_R), P(x + PEG_R, y + PEG_R)], fill=PEG)
        # bin walls and floor
        for k in range(NB + 1):
            x = bin_x(k) - SP / 2
            d.line([P(x, BIN_TOP), P(x, FLOOR)], fill=WALL, width=S)
        d.line([P(bin_x(0) - SP / 2, FLOOR), P(bin_x(ROWS) + SP / 2, FLOOR)], fill=PEG, width=round(1.2 * S))
        # balls
        landed = 0
        for i in range(N):
            p = ball_pos(i, fr)
            if p is None:
                continue
            kind, (x, y) = p
            col = BALL if kind == "landed" else BALL_NEW
            if kind == "landed":
                landed += 1
            a = fade if kind == "landed" else (1.0 if fade > 0.99 else 0.0)
            if a <= 0:
                continue
            d.ellipse([P(x - BALL_R, y - BALL_R), P(x + BALL_R, y + BALL_R)], fill=mix(col, a))
        # expected binomial profile (pile top for each bin)
        if curve > 0:
            pts = []
            for k in range(NB):
                rows_k = EXPECT[k] / PER_ROW
                pts.append((bin_x(k), FLOOR - rows_k * ROW_H - BALL_R))
            xs = np.linspace(0, ROWS, 200)
            ys = np.interp(xs, np.arange(NB), [p[1] for p in pts])
            # smooth through the points with a cubic interpolation
            from scipy.interpolate import CubicSpline
            cs = CubicSpline(np.arange(NB), [p[1] for p in pts])
            line = [P(bin_x(xv), cs(xv)) for xv in xs]
            seg = 0
            for a_, b_ in zip(line[:-1], line[1:]):                # dashed
                if (seg // 3) % 2 == 0:
                    d.line([a_, b_], fill=mix(CURVE, curve), width=round(1.6 * S))
                seg += 1
        out = img.reduce(S)
        t = ImageDraw.Draw(out)
        t.text((10, 22), f"n = {landed}", font=ImageFont.truetype(F_SEMI, 12),
               fill=mix(TXT, max(fade, 0.0)), anchor="ls")
        return np.asarray(out)
     
     
    def timeline():
        last = int(np.ceil(land.max()))
        st = [(last, 1.0, 1.0)] * 25
        st += [(last, 1 - i / 5, 1 - i / 5) for i in range(1, 5)]
        st += [(-1, 1.0, 0.0)] * 4
        st += [(fr, 1.0, 0.0) for fr in range(0, last + 1)]
        st += [(last, 1.0, i / 5) for i in range(1, 6)]
        st += [(last, 1.0, 1.0)] * 3
        return [render(*s) for s in st]
     
     
    # ----------------------------------------------------------------- palette + GIF
    def nearest(cols, pal):
        dd = (cols ** 2).sum(1)[:, None] - 2 * cols @ pal.T + (pal ** 2).sum(1)[None]
        return dd.argmin(1)
     
     
    def kmeans(X, w, k, iters=40, seed=5):
        rg = np.random.default_rng(seed)
        C = [X[rg.choice(len(X), p=w / w.sum())]]
        d2 = ((X - C[0]) ** 2).sum(1)
        for _ in range(1, min(k, len(X))):
            p = w * d2
            C.append(X[rg.choice(len(X), p=p / p.sum())])
            d2 = np.minimum(d2, ((X - C[-1]) ** 2).sum(1))
        C = np.array(C)
        for _ in range(iters):
            lab = nearest(X, C)
            sw = np.bincount(lab, weights=w, minlength=len(C))
            ok = sw > 0
            for ch in range(3):
                C[ok, ch] = np.bincount(lab, weights=w * X[:, ch], minlength=len(C))[ok] / sw[ok]
        return C
     
     
    def ucols(arr):
        f_ = arr.reshape(-1, 3).astype(np.int64)
        key = (f_[:, 0] << 16) | (f_[:, 1] << 8) | f_[:, 2]
        uk, inv, cnt_ = np.unique(key, return_inverse=True, return_counts=True)
        return np.stack([(uk >> 16) & 255, (uk >> 8) & 255, uk & 255], -1).astype(np.float64), inv, cnt_
     
     
    def main():
        raw = timeline()
        frames, durations = [], []
        for fr in raw:
            if frames and np.array_equal(fr, frames[-1]):
                durations[-1] += DELAY
            else:
                frames.append(fr)
                durations.append(DELAY)
        cols, _, cn = ucols(np.concatenate([fr.reshape(-1, 3) for fr in frames]))
        fixed = np.array([BG, PEG, WALL, BALL, BALL_NEW, CURVE, TXT], np.float64)
        pal = np.clip(np.rint(np.vstack([fixed, kmeans(cols, np.sqrt(cn), 255 - len(fixed))])), 0, 255)
        pal_list = [int(v) for v in pal.flatten()] + [0, 0, 0] * (256 - len(pal))
        ims, prev, err = [], None, []
        for fr in frames:
            c, inv, _ = ucols(fr)
            ind = nearest(c, pal)[inv.ravel()].reshape(H, W).astype(np.uint8)
            q = pal[ind].astype(np.uint8)
            err.append(np.abs(q.astype(int) - fr.astype(int)).mean())
            out = ind if prev is None else np.where((q == prev).all(-1), 255, ind).astype(np.uint8)
            prev = q
            im = Image.fromarray(out, "P")
            im.putpalette(pal_list)
            ims.append(im)
        ims[0].save(OUT, save_all=True, append_images=ims[1:], duration=durations, loop=0,
                    transparency=255, disposal=1, optimize=False)
        print(f"{OUT}: {os.path.getsize(OUT) / 1e6:.2f} MB, {W}x{H}, {len(frames)} frames, "
              f"{sum(durations) / 1000:.1f} s, {W * H * len(frames) / 1e6:.2f} MP, err {np.mean(err):.2f}, "
              f"N={N}, bins={np.bincount(bins, minlength=NB).tolist()}")
     
     
    if __name__ == "__main__":
        main()
    

    Légendes

    Simulation d'une planche de Galton à 10 rangées : à chaque clou, une bille part à gauche ou à droite avec une probabilité ½, et les piles obtenues approchent la loi binomiale B(10, ½) (en pointillés).

    Éléments décrits dans ce fichier

    dépeint

    image/gif

    Historique du fichier

    Cliquer sur une date et heure pour voir le fichier tel qu'il était à ce moment-là.

    Date et heureVignetteDimensionsUtilisateurCommentaire
    actuel25 octobre 2026 à 01:38Vignette pour la version du 25 octobre 2026 à 01:38260 × 310 (344 kio)Global DonaldUploaded own work with UploadWizard

    La page suivante utilise ce fichier :