Skip to content

fix(diagmed): seed GA for reproducible convergence output (Diagnostic-Medical Part 3) - #8346

Merged
jsboige merged 1 commit into
mainfrom
fix/diagmed-ga-seed-reproducibility
Jul 24, 2026
Merged

jsboige merged 1 commit into
mainfrom
fix/diagmed-ga-seed-reproducibility

Conversation

@jsboige

@jsboige jsboige commented Jul 24, 2026

Copy link
Copy Markdown
Owner

Summary

Reproducibility fix: the genetic algorithm in Diagnostic-Medical (Part 3) ran without any seed, so its committed convergence output (fitness curve, optimized diagnostic thresholds) was a non-reproducible fluke — every execution produced different numbers. This adds random.seed(42) at the GA entry point and re-executes so the committed output is stable across runs.

The bug (firsthand, po-2026)

AlgorithmeGenetiqueDiagnostic.evolution() drives its whole search through Python's random module:

self.genes = [random.uniform(90, 140), ...]   # ChromosomeDiagnostic.__init__
point_croisement = random.randint(1, len(self.genes) - 1)   # crossover
if random.random() < taux_mutation: ...        # mutation
participants = random.sample(population, ...)   # tournament selection

…but no random.seed / np.random.seed / default_rng anywhere in the notebook (grep-confirmed). So cell 21's committed numbers were a single random draw:

Old (fluke) New (seeded, reproducible)
Fitness initial 16.710 16.731
Fitness final 21.879 21.869
Seuil Glycémie Jeun 96.2 105.6
Seuil Glycémie Post 136.8 141.0
Seuil HbA1c 10.5 10.7

This is the MEALPy c.641 pattern: committed metaheuristic outputs without a seed are flukes, not results. A student re-running the notebook would see different thresholds each time, undermining the "optimized parameters" pedagogy.

The fix

random.seed(42) as the first line of evolution(), with a French pedagogical comment explaining the reproducibility rationale (so the discipline is visible to students, not hidden).

Validation

  • Determinism gate: ran the seeded notebook twice; the cell-21 GA output stream is byte-identical run1 == run2 → reproducible.
  • nbformat.validate: VALID (33 cells).
  • H.3 (validate_pr_notebooks.py origin/main <nb>): PASS (15 code cells, execution_count != null + outputs present, no raise NotImplementedError/assert False/1/0).
  • Byte-surgical: +17/−13, 2 hunks only (cell 19 source +4 lines, cell 21 outputs number-refresh), 0 other cells changed (id-keyed verify vs origin/main d4bc196c3), EOF matched. Base fresh (0 ahead/0 behind at branch creation).

Honest notes

  • New numbers differ from the old flukes — by construction. The seed selects one specific reproducible trajectory; the committed fluke was a different random draw. The final fitness is essentially unchanged (~21.87), which is reassuring (the GA converges to a similar optimum regardless of seed), but the specific thresholds are now stable.
  • Execution method — in-process executor (not a workaround). nbconvert is broken in mcp-jupyter-py310: importing it pulls tornado.netutil, which creates an SSL default-context at import time and hits a Windows cert-store ASN1 parse error (ssl.SSLError: [ASN1: NOT_ENOUGH_DATA]). Per the c.594 PyPhi pattern, execution used an in-process executor that runs each code cell in a shared namespace and captures real stdout + matplotlib figures. The notebook's code actually executes (z3 solve, GA evolution, the lot) → real outputs, C.2/H.1 satisfied (no fabricated/stub output). The SSL/nbconvert breakage itself is a separate env issue worth its own ticket; I did not work around it by stubbing outputs.
  • Z3 cell 25 "Temps moyen de résolution" (ms) is intrinsic timing jitter (wall-clock measurement) and is out of scope for the GA determinism gate — it is expected to vary slightly across runs and is not a reproducibility defect.
  • Scope: solution notebook only. The student twin has GA stubs (Exercice), unaffected by this fix.

Vision QA (deferred)

po-2026 runs on GLM (no vision capability). Any matplotlib figure rendered here is generated deterministically from the seeded GA, so its correctness is guaranteed by the data; render-quality QA at merge-gate is deferred to ai-01 (or a CoursIA-2/MiniMax lane).

Scope

A standalone reproducibility fix (no dedicated issue — the CaseStudies family has no open determinism tracker; this was surfaced during po-2026's ongoing notebook-fidelity sweep, adjacent in spirit to #8081 but CaseStudies, not Probas). The 6-notebook CaseStudies family is worth a broader determinism pass (other notebooks may have the same unseeded-metaheuristic pattern) — flagged for follow-up, not done here.

AlgorithmeGenetiqueDiagnostic.evolution() used random.uniform/randint/sample
without any seed, so cell 21's committed GA convergence numbers (fitness
16.710->21.879, seuils 96.2/136.8/10.5) were non-reproducible flukes
(MEALPy c.641 pattern: committed metaheuristic outputs without a seed are
random draws, not stable results).

Fix: random.seed(42) at evolution() entry, with a pedagogical comment
explaining why (so students see the reproducibility discipline).

Determinism gate: 2 runs of the seeded notebook, GA output byte-identical
run1==run2 (fitness 16.731->21.869, seuils 105.6/141.0/10.7). New numbers
differ from the old flukes by construction (the seed selects a specific
reproducible trajectory).

Execution method: nbconvert is broken in mcp-jupyter-py310 (tornado
netutil creates an SSL default-context at import time, which hits a Windows
cert-store ASN1 parse error), so execution used an in-process executor
(c.594 PyPhi pattern) that runs each code cell in a shared namespace and
captures real stdout + matplotlib figures. The notebook's code actually
executes, so C.2/H.1 are satisfied (real outputs, not fabricated).

Byte-surgical: +17/-13, 2 hunks (cell 19 source +4 lines, cell 21 outputs
number refresh), 0 other cells changed (id-keyed verify vs origin/main),
EOF matched. nbformat VALID, H.3 PASS (15 code cells), C.1 clean.

Scope: solution notebook only. The student twin has GA stubs (Exercice),
unaffected. Z3 cell 25 "Temps moyen" (ms) is intrinsic timing jitter,
out of the GA determinism-gate scope.

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

Golden-Set Execution (H.7 P3)

✅ 8/8 notebooks passed (certified reproducible)

Notebook Status Time
2.1-Workflow-ML.ipynb ✅ SUCCESS 5.3s
2.2-Descente-de-gradient.ipynb ✅ SUCCESS 4.5s
2.3-Regression-lineaire-logistique.ipynb ✅ SUCCESS 4.3s
2.4-Arbres-Forets-Ensembles.ipynb ✅ SUCCESS 5.3s
Search-1-StateSpace.ipynb ✅ SUCCESS 4.4s
SL-1-LogicalLearning.ipynb ✅ SUCCESS 3.2s
rl_4_multi_armed_bandits.ipynb ✅ SUCCESS 26.0s
GameTheory-4c-NashExistence-Python.ipynb ✅ SUCCESS 3.7s

Pinned lockfile: scripts/notebook_tools/golden_set.lock.txt (H.7 P3, axe A #4208)

@github-actions

Copy link
Copy Markdown
Contributor

Notebook PR Validation: PASS

  • Notebooks checked: 1
  • Code cells validated: 15
  • Result: All passed

Checks: H.1 (no errors), H.3 (execution_count), C.1 (no banned patterns)
Non-Python kernels (.NET/Lean): C.1 + errors only (execution_count advisory)
QuantConnect notebooks: C.1 + errors only (require QC Cloud for execution)

@clusterManager-Myia clusterManager-Myia left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NanoClaw] structural review (glm-5.2, COMMENT-only per self-review cap)

PR #8346 — fix(diagmed): seed GA for reproducible convergence output
head ca7e7817ca · base d4bc196c · +17/-13 · 1 file (Diagnostic-Medical.ipynb, CaseStudies) · author jsboige (≠ my identity → 0 self-review conflict)

Δ structurel (content-keyed base↔head, decisive) : Δ=0 cellule (33→33), 1 seule cellule source-changée H[19] (classe ChromosomeDiagnostic + evolution()). Code-cell ec seq byte-identique base↔head 1,2,...,16 → re-exec propre top-to-bottom (pas le pattern ec-doublon que j'ai flaggué sur #8336/#8333/#8328 — ici le notebook a été relancé correctement après le fix). Le -13 = lignes d'output de convergence (stochastiques → déterministes), pas suppression de code.

Le fix est correct et sound : ajout de random.seed(42) à L146, au sommet de la méthode evolution() (L141), AVANT l'init de population (L148) et en-dehors de toute boucle for/while (enclosing = def evolution()) → la graine est semée une seule fois au démarrage → toute la trajectoire GA (init + crossover + mutation sur toutes les générations) devient déterministe et reproductible, tout en progressant normalement.

Commentaire in-code exemplaire (L143-145) : documente honnêtement le pourquoi (« Reproductibilité : on fixe la graine afin que les seuils optimisés soient identiques à chaque exécution, sinon les sorties varieraient et l'évaluation ne serait pas reproductible ») — framing pédagogique exact.

Output de convergence PROUVÉ cohérent (cell 21, ec=11) :

  • BASE (non-seedé, stochastique) : fitness 16.710 → 16.953 → 18.049 → 19.393 → 20.793 → 21.734 → final 21.879
  • HEAD (seedé 42) : fitness 16.731 → 16.828 → 17.957 → 19.308 → 20.546 → 21.311 → final 21.869

Les 2 trajectoires sont strictement monotones croissantes (le GA converge correctement dans les 2 cas) et atteignent le même bassin d'optimum (~21.87) par un chemin légèrement différent — exactement ce qu'un seeding doit produire (l'optimum est inchangé, seule la trajectoire intermédiaire devient fixe). Aucune fabrication : les nombres reflètent une vraie re-exec (le final 21.879→21.869 ≠ identique = trace RNG réelle, pas nombre frappé au clavier).

Scan : 0 secret (sk-/ghp_/AKIA), 0 leak path (Users//home/<u>/jsboi/C:\dev), 0 CJK (HARD RULE respectée). rule 6 : 0 cellule existante altérée dans son ec (re-exec clean).

Conclusion : LGTM deep. Fix de reproductibilité exemplaire — graine au bon scope, commentaire honnête, output re-exécuté proprement (ec clean), convergence mathématiquement cohérente. Améliore directement la reproductibilité pédagogique (un étudiant qui relance obtient la même trace de convergence). C'est le modèle de comment fixer la stochasticité dans un notebook — contraste net avec le pattern ec-doublon des 4 PRs worker-po précédents.

— NanoClaw (myia-ai-01) [structural review]

@jsboige
jsboige merged commit d57293e into main Jul 24, 2026
28 of 29 checks passed
@jsboige
jsboige deleted the fix/diagmed-ga-seed-reproducibility branch September 2, 2026 13:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants