{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Twelve findings from one knee MRI\n\nEach study in this competition is a set of MRI series acquired in one session, and the\ntask is to give it twelve probabilities: anterior cruciate and medial collateral\nligament injury, medial and lateral meniscal tear, osteoarthritis in each of the three\ncompartments, joint effusion, synovitis, Baker's cyst, bone contusion, and fracture.\n\nThis notebook builds a study-level predictor from first principles. The order of the\nsections is the order in which the decisions constrain each other: what the score\nrewards decides how predictions should be combined, where the targets come from decides\nwhat can be trained, and what the scanner recorded decides what the encoder should be\nshown.\n","metadata":{}},{"cell_type":"markdown","source":"## 1. What the score rewards\n\nThe score is the unweighted mean of twelve per-label ROC AUCs:\n\n$$\\text{Score} \\;=\\; \\frac{1}{12}\\sum_{i=0}^{11} \\mathrm{AUC}_i .$$\n\nThree consequences follow directly, and each one removes a design choice.\n\n**Only order matters.** $\\mathrm{AUC}_i$ is invariant under any strictly increasing map\nof the scores for label $i$. Calibration is therefore worth nothing, and a fixed\nthreshold is worth nothing. It also fixes how to combine models: averaging raw\nprobabilities lets whichever model happens to be most confident dominate, whereas\naveraging *ranks* combines the only information the metric reads. Every combination\nbelow is a rank mean.\n\n**Every label costs the same.** Write $M$ for the mean AUC a good model could reach.\nA label left at chance contributes $0.5$ instead of roughly $M$, so it forfeits\n\n$$\\frac{M - 0.5}{12}$$\n\nof the final score no matter how well the other eleven do. At $M = 0.85$ that is\n$0.029$ — larger than the gap between neighbouring places in a mature competition.\nRare findings deserve *more* attention than common ones, not less, because a rare\nfinding is where a model most easily ends up at chance.\n\n**Prevalence drifts are survivable, thresholds are not.** AUC is, in expectation,\ninvariant to the positive rate. The competition states that prevalence is not guaranteed\nto match across the training, public and final sets, which would be fatal for any\naccuracy-like metric and for anything tuned to a threshold. It is not fatal here,\nprovided nothing in the pipeline depends on a cutoff. Nothing below does.\n","metadata":{}},{"cell_type":"markdown","source":"## 2. Where the targets come from\n\nOnly a small subset of the training studies carry the twelve per-condition labels. Every\ntraining study carries the original radiology report, and the data description invites\nderiving labels from it.\n\nThe decisive structural fact is in the schemas rather than in the prose: `train.csv` has\na `Report` column and `test.csv` does not. Text is available when fitting and absent when\npredicting. That rules out a fusion model with a text branch — at inference it would have\nnothing to read — and leaves three admissible uses of the reports:\n\n1. turn them into training targets, then fit a pure imaging model;\n2. use them as an auxiliary training signal, distilled into the image encoder and dropped\n   at inference;\n3. use them to weight studies by how confidently their labels could be read.\n\nThis notebook takes the first and the third. A multilingual rule extractor reads each\nreport clause by clause, deciding for each finding whether the clause asserts it, negates\nit, or hedges it, and emits a score together with a confidence. The confidence becomes a\nsample weight, so a study whose report says nothing about synovitis pulls on the\nsynovitis head far less than one that names it.\n\nTwo details matter more than the extractor's internals.\n\n**Reports are graded, annotations are thresholded.** The reporting radiologist and the\nannotator do not share a threshold. A report that says *small joint effusion* may sit\nagainst a negative annotation, because the annotator marked only effusions they judged\nsignificant. A rule of the form *term present $\\Rightarrow$ positive* is therefore wrong\nby construction. Grading the mention — trace, unqualified, marked — is right, and costs\nnothing, because §1 established that only the order of the scores is read.\n\n**Derived labels are not independent across studies.** A report shared verbatim by\nseveral studies yields one target vector for all of them. That has to be respected when\nsplitting; §7 does.\n","metadata":{}},{"cell_type":"markdown","source":"### Reading a report in nine languages\n\nThe extractor is the first model in this pipeline, so it is built here rather than\nattached as a file. It runs over a few megabytes of text in seconds, and keeping it in\nline means the targets can never be a stale copy of what the current rules would produce.\n\n**Script settles itself; language does not.** Greek and Cyrillic are decided by Unicode\nalone. The Latin-script remainder is scored by stopword counts across the candidate\nlanguages and the winner must beat the runner-up by a margin; what fails that test stays\n`unknown` rather than being guessed. The tempting shortcut — a cascade of substring tests,\n`'the '` for English, `'la '` for French — fails badly here, because `la` is as common in\nSpanish as in French and whichever test runs first swallows both.\n\n**Normalise, then segment, then scope.** Case, diacritics and separators are folded first,\nwhich also repairs a codepoint problem: many Greek reports spell mu with the MICRO SIGN\nU+00B5 rather than U+03BC, and NFKD maps one onto the other. Text is then split into\nclauses, with a heading line attached to the value beneath it, because a report that reads\n`Fractures :` and then `Aucune.` states one thing across two lines and any method that\nsplits them reads a negation as a positive.\n\n**Assertion, negation, hedge.** Within a clause the extractor asks which of three things\nthe sentence is doing. Negation is not an edge case: for several findings most mentions\nare negative, since a report lists what was checked and found intact. Explicit normality\ncounts as negation — *ligamentos cruzados y colaterales dentro de límites normales* is\nevidence of absence, not absence of evidence — except where a tear or a high grade is\nnamed in the same breath.\n\n**Stems, not phrases.** Four targets need an anatomy word and a pathology word together,\nand a lexicon of complete phrases cannot survive morphology: Turkish suffixes possessives\nonto the noun, Croatian and Greek decline it. Matching a stem and then requiring a side\nqualifier within a character window handles inflection without enumerating it, and a\ncharacter window rather than a token window handles word order, which puts the side\nadjective before the noun in English and after it in Greek.\n\n**Grade, do not threshold.** §1 established that only the order of the scores is read, and\n§2 that the annotator's threshold is stricter than the reporting radiologist's. Together\nthose say a mention should be scored by its emphasis — trace, unqualified, marked — and\nnever binarised. Each target also carries a confidence, which becomes the sample weight:\nsilence on a finding is weak evidence, and it should pull on the model weakly.\n\n### How an extractor like this is validated\n\nThis is the part that decides whether any of the above is worth trusting, and it is\nharder than writing the rules, because the obvious measurement is the one that cannot\ncarry the weight.\n\n**The dangerous failure is silent.** A rule that never fires does not raise an error; it\nemits a negative. A lexicon that is complete in English and thin in Greek therefore does\nnot look broken — it looks like a corpus where Greek patients have fewer findings. Worse,\nthe error is not random: language tracks the reporting institution, which tracks the\nscanner and the population, so a gap in one language is a systematic bias aligned with a\nsite rather than noise that averages out.\n\n**Gauge one: agreement, on the annotated subset.** For each target, compare the extracted\nscore against the per-condition annotation and read the AUC. This measures the right\nthing, and it is nearly useless for tuning, because that subset is small. The\nHanley–McNeil approximation for the standard error of an AUC $A$ with $n_p$ positives and\n$n_n$ negatives is\n\n$$\n\\mathrm{SE}(A)=\\sqrt{\\frac{A(1-A)+(n_p-1)(Q_1-A^{2})+(n_n-1)(Q_2-A^{2})}{n_p\\,n_n}},\n\\qquad\nQ_1=\\frac{A}{2-A},\\quad Q_2=\\frac{2A^{2}}{1+A}.\n$$\n\nPut a plausible $A\\approx0.8$ and a rare finding — a handful of positives among a few\ndozen studies — into that expression and the standard error lands near $0.09$, so the 95%\ninterval spans roughly $\\pm0.17$. Competitions are decided by differences an order of\nmagnitude smaller. Choosing between two lexicons on this number is choosing by coin flip,\nand it will feel like signal every time.\n\n**Gauge two: coverage, on the whole corpus.** For each (study, target) pair, record\nwhether any rule fired at all — assertion, negation or hedge. The *silence rate* is the\nfraction where none did. It needs no labels, so it runs on every report rather than on the\nannotated handful, and broken down by language and target it points straight at the\nmissing vocabulary. A common finding that is silent in one language and not another is a\nlexicon gap. A rare finding that is silent nearly everywhere is simply rare, and silence\nthere is correct.\n\nThe two gauges answer different questions and neither substitutes for the other:\n\n| | measures | sample | can decide |\n|---|---|---|---|\n| agreement | is a fired rule *right* | small | whether a target's labels are usable at all |\n| silence rate | does a rule *fire* | whole corpus | which language and which finding to work on next |\n\n**The loop.** Read actual reports in each language before writing any pattern — the\nvocabulary comes from the corpus, not from a translation of the English list. Write rules,\nthen measure both gauges. Then open the disagreements individually and ask what the\nextractor saw, because the aggregate says a target is weak while a handful of cases says\n*why*: a threshold mismatch, a missing negator, a morphological form the lexicon cannot\nreach. Fix, re-measure, and prefer changes that improve coverage on the large gauge over\nchanges that improve agreement on the small one — the first is signal, the second is\nmostly sampling noise.\n","metadata":{}},{"cell_type":"code","source":"from __future__ import annotations\n\nimport re\nimport unicodedata\n\nTARGETS = [\n    \"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\",\n    \"Medial OA\", \"Lateral OA\", \"PF OA\", \"Effusion\",\n    \"Synovitis\", \"Baker's\", \"Contusion\", \"Fracture\",\n]\n\n\n# Turkish dotted/dotless i must be folded before casefolding, otherwise \"İZLENMEZ\"\n# and \"izlenmez\" diverge. ß and the Croatian/Serbian d-with-stroke likewise.\n_PRE = str.maketrans({\n    \"ı\": \"i\", \"İ\": \"i\", \"I\": \"i\", \"ß\": \"ss\", \"đ\": \"d\", \"Đ\": \"d\",\n    \"ø\": \"o\", \"Ø\": \"o\", \"æ\": \"ae\", \"Æ\": \"ae\",\n})\n\n\ndef normalize(text: str) -> str:\n    \"\"\"Fold case, diacritics and separators; keep Greek and Cyrillic letters.\n\n    NFKD decomposition strips Latin accents and Greek tonos alike (ά -> α), which is what\n    we want: reports are inconsistent about accents. It also maps the MICRO SIGN U+00B5\n    to a real mu, which matters because most Greek reports here use the wrong codepoint.\n    \"\"\"\n    if not isinstance(text, str):\n        return \"\"\n    text = text.translate(_PRE).lower()\n    text = unicodedata.normalize(\"NFKD\", text)\n    text = \"\".join(ch for ch in text if not unicodedata.combining(ch))\n    text = text.replace(\"­\", \"\")                    # soft hyphen\n    text = re.sub(r\"[_\\-/\\\\]+\", \" \", text)\n    text = re.sub(r\"[ \\t]+\", \" \", text)\n    return text\n\n\n_SENT_SPLIT = re.compile(r\"(?<=[.;!?])\\s+|\\n+\")\n\n\ndef clauses(text: str):\n    \"\"\"Split into clauses, then attach `header:` lines to the value that follows.\n\n    A report line reading `Fractures :` followed by `Aucune.` is one statement. Splitting\n    on punctuation alone separates the anatomy from its negation and flips the label.\n    \"\"\"\n    norm = normalize(text)\n    raw = [c.strip() for c in _SENT_SPLIT.split(norm) if c and c.strip()]\n\n    merged = []\n    for i, c in enumerate(raw):\n        # A fragment ending in a colon is a heading for the next fragment. Structured\n        # English reports write long ones - \"lateral compartment (meniscus, collateral\n        # ligament complex, cartilage):\" is eight words - so the cap is generous, and\n        # the heading is kept as its own clause too in case it carries the finding.\n        if c.endswith(\":\") and len(c.split()) <= 14 and i + 1 < len(raw):\n            merged.append(c + \" \" + raw[i + 1])\n        merged.append(c)\n    # Comma-separated enumerations inside a long clause hide separate assertions.\n    out = []\n    for c in merged:\n        out.append(c)\n        if len(c.split()) > 25:\n            out.extend(p.strip() for p in c.split(\",\") if len(p.split()) > 2)\n    return out\n\n\ndef _rx(*alts: str) -> re.Pattern:\n    return re.compile(\"|\".join(alts))\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.554457Z","iopub.execute_input":"2026-08-10T17:35:04.555124Z","iopub.status.idle":"2026-08-10T17:35:04.56789Z","shell.execute_reply.started":"2026-08-10T17:35:04.55509Z","shell.execute_reply":"2026-08-10T17:35:04.567285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NEGATION = _rx(\n    # en\n    r\"\\bno\\b\", r\"\\bnot\\b\", r\"\\bwithout\\b\", r\"\\bnegative for\\b\", r\"\\babsence\\b\",\n    r\"\\bno evidence\\b\", r\"\\bunremarkable\\b\", r\"\\bfree of\\b\",\n    # es\n    r\"\\bsin\\b\", r\"\\bno hay\\b\", r\"\\bausencia\\b\", r\"\\bausentes?\\b\",\n    # fr\n    r\"\\bpas de\\b\", r\"\\bsans\\b\", r\"\\baucune?\\b\", r\"\\babsence\\b\",\n    # nl\n    r\"\\bgeen\\b\", r\"\\bzonder\\b\", r\"\\bniet\\b\",\n    # de\n    r\"\\bkeine?\\b\", r\"\\bohne\\b\", r\"\\bnicht\\b\",\n    # tr\n    r\"\\byok\\b\", r\"\\byoktur\\b\", r\"izlenmemekte\", r\"saptanmadi\", r\"\\bdegil\\b\",\n    r\"gozlenmemekte\", r\"mevcut degil\", r\"eslik etmiyor\", r\"\\bizlenmedi\\b\",\n    # hr / sr / bs\n    r\"\\bnema\\b\", r\"\\bbez\\b\", r\"\\bnisu\\b\", r\"\\bnije\\b\",\n    # el (accents already stripped)\n    r\"\\bδεν\\b\", r\"\\bχωρις\\b\", r\"ουδεν\",\n    # bg / ru\n    r\"\\bбез\\b\", r\"\\bне\\b\", r\"липсва\", r\"\\bняма\\b\",\n)\n\nNORMALITY = _rx(\n    r\"\\bnormal\", r\"\\bintact\\b\", r\"\\bpreserved\\b\", r\"\\bwithin normal limits\\b\",\n    r\"limites normales\", r\"\\bconservad\", r\"\\bintegr\", r\"\\bnormales\\b\",\n    r\"\\bdoga(l|ll)\\b\", r\"korunmus\", r\"\\bnormaldir\\b\", r\"olagan\",\n    r\"\\buredn\", r\"\\bocuvan\", r\"\\bodrzan\", r\"\\bintakt\",\n    r\"φυσιολογικ\", r\"ακεραι\",\n    r\"unauffallig\", r\"regelrecht\", r\"\\bintakt\\b\",\n    r\"нормал\", r\"запазен\", r\"съхранен\", r\"\\bбез особености\\b\",\n    r\"\\bgaaf\\b\", r\"\\bnormaal\\b\",\n)\n\nUNCERTAIN = _rx(\n    r\"\\bpossible\\b\", r\"\\bprobable\\b\", r\"\\bsuspicious\\b\", r\"\\bsuspected\\b\",\n    r\"cannot (be )?exclude\", r\"\\bmay\\b\", r\"\\bquestionable\\b\", r\"\\bequivocal\\b\",\n    r\"\\bposible\\b\", r\"sin criterios categoricos\", r\"\\bdudos\",\n    r\"\\bmuhtemel\\b\", r\"\\bolasi\\b\", r\"\\bsupheli\\b\", r\"\\bizlenim\",\n    r\"\\bmoguce\\b\", r\"\\bvjerojatno\\b\", r\"\\bsumnja\\b\",\n    r\"πιθαν\", r\"υποπτ\",\n    r\"\\bmoglich\", r\"\\bverdachtig\", r\"\\bfraglich\", r\"\\bV\\.a\\.\\b\",\n    r\"\\bвъзможно\\b\", r\"\\bвероятно\\b\", r\"суспект\",\n    r\"\\bmogelijk\\b\", r\"\\bverdacht\\b\",\n)\n\n# Pathology vocabulary shared by the paired rules.\nTEAR = _rx(\n    r\"\\btear\", r\"\\btorn\\b\", r\"\\brupture\", r\"\\bdisruption\\b\", r\"discontinuit\",\n    r\"\\bavuls\",\n    r\"\\brotura\\b\", r\"\\broturas\\b\", r\"\\bruptura\", r\"\\bdesgarro\", r\"\\broto\\b\",\n    r\"\\bdechirure\", r\"\\bdechire\",\n    r\"\\bscheur\", r\"\\bruptuur\", r\"gescheurd\",\n    r\"\\briss\\b\", r\"einriss\", r\"\\bruptur\", r\"zerreiss\", r\"\\blasion\",\n    r\"\\byirtik\", r\"\\byirtig\", r\"\\bkopma\\b\", r\"butunluk kaybi\", r\"\\brupturu\\b\",\n    r\"\\bpuknuce\", r\"\\bruptur\", r\"\\bprekid\\b\", r\"\\bpukotin\",\n    r\"ρηξη\", r\"ρηξις\", r\"ρηγμα\",\n    r\"руптура\", r\"разкъсв\", r\"разрив\", r\"скъсв\",\n)\n\nDEGEN = _rx(\n    r\"degenerat\", r\"\\bmucoid\\b\", r\"\\bmyxoid\\b\", r\"\\bfray\", r\"\\bfissur\",\n    r\"dejeneratif\", r\"\\bmukoid\\b\", r\"degenerativn\", r\"εκφυλιστ\", r\"дегенерат\",\n    r\"\\bmuco ?ide\\b\", r\"aufgefasert\",\n)\n\nINJURY = _rx(\n    r\"\\binjur\", r\"\\bsprain\", r\"\\blesion\", r\"\\blasion\", r\"\\bedema\\b\", r\"\\boedema\\b\",\n    r\"\\bodem\\b\", r\"\\bedem\\b\", r\"\\bοιδημα\", r\"\\bодем\", r\"\\bедем\", r\"\\bstrain\\b\",\n    r\"\\bhigh signal\\b\", r\"\\bsignal alteration\\b\", r\"\\bhiperintens\", r\"\\bhyperintens\",\n    r\"\\bthicken\", r\"\\bzadebljanje\\b\", r\"\\bverdikking\\b\", r\"\\bdistenzij\",\n    r\"\\blaksite\\b\", r\"\\blaxity\\b\", r\"\\bpartial\\b\", r\"\\bparcijaln\", r\"\\bparcial\",\n    r\"\\bpartiel\", r\"\\bpartiell\",\n)\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.569478Z","iopub.execute_input":"2026-08-10T17:35:04.569784Z","iopub.status.idle":"2026-08-10T17:35:04.589115Z","shell.execute_reply.started":"2026-08-10T17:35:04.569721Z","shell.execute_reply":"2026-08-10T17:35:04.588501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ANAT = {\n    \"ACL\": _rx(\n        r\"anterior cruciate\", r\"\\bacl\\b\",\n        r\"cruzado anterior\", r\"\\blca\\b\",\n        r\"croise anterieur\",\n        r\"voorste kruisband\", r\"\\bvkb\\b\",\n        r\"vorderes kreuzband\", r\"vorderen kreuzband\", r\"vordere kreuzband\",\n        r\"on capraz\", r\"\\bocb\\b\",\n        r\"prednji krizni\", r\"prednjeg krizn\",\n        r\"προσθι[οα][^ ]* χιαστ\", r\"προσθιου χιαστου\", r\"χιαστο[^ ]* συνδεσμ\",\n        r\"предна кръстна\", r\"предната кръстна\",\n        # Plural, unqualified: reports routinely clear both cruciates in one clause\n        # (\"Ligamentos cruzados y colaterales dentro de limites normales\"). Without\n        # this, Spanish ACL was silent on 88% of its reports and Dutch on 70%.\n        r\"cruciate ligaments\", r\"ligamentos cruzados\", r\"ligaments croises\",\n        r\"kruisbanden\", r\"kreuzbander\", r\"capraz baglar\", r\"krizn[a-z]* ligament[a-z]*\",\n        r\"χιαστοι συνδεσμ\", r\"χιαστων συνδεσμ\", r\"кръстните връзки\", r\"кръстни връзки\",\n    ),\n    \"MCL\": _rx(\n        r\"medial collateral\", r\"\\bmcl\\b\", r\"tibial collateral\",\n        r\"colateral medial\", r\"colateral interno\", r\"\\blcm\\b\",\n        r\"collateral medial\", r\"collateral interne\",\n        r\"mediale collaterale\", r\"binnenband\",\n        r\"innenband\", r\"mediales? kollateral\",\n        r\"\\bic yan bag\", r\"medial kollateral\", r\"\\biyb\\b\",\n        r\"medijalni kolateraln\", r\"medijalnog kolateraln\",\n        r\"εσω πλαγι\", r\"εσωτερικο πλαγι\",\n        r\"медиален колатерал\", r\"вътрешна странична\",\n        # Same plural pattern as the cruciates.\n        # \"Ligamentos cruzados y colaterales\" separates the noun from its adjective, so\n        # the adjective has to stand alone as a cue.\n        r\"\\bcolaterales\\b\", r\"\\bcollateraux\\b\", r\"\\bcollateralen\\b\", r\"\\bkolateralni\\b\",\n        r\"collateral ligaments\", r\"ligamentos colaterales\", r\"ligaments collateraux\",\n        r\"collaterale banden\", r\"kollateralbander\", r\"seitenbander\", r\"yan baglar\",\n        r\"kolateraln[a-z]* ligament[a-z]*\", r\"πλαγιοι συνδεσμ\", r\"πλαγιων συνδεσμ\",\n        r\"колатерални връзки\", r\"страничните връзки\",\n    ),\n    \"Medial Meniscus\": _rx(\n        r\"medial meniscus\", r\"\\bmm\\b(?= tear)\", r\"medial menisc\",\n        r\"menisco medial\", r\"menisco interno\",\n        r\"menisque medial\", r\"menisque interne\",\n        r\"mediale meniscus\", r\"binnenmeniscus\",\n        r\"innenmeniskus\", r\"medialen? meniskus\", r\"innenmeniskushinterhorn\",\n        r\"medyal menisk\", r\"\\bic menisk\",\n        r\"medijalni meniskus\", r\"medijalnog meniskusa\", r\"medijalnom meniskusu\",\n        r\"εσω μηνισκ\", r\"μηνισκ[^ ]* του εσω\", r\"εσω διαμερισμα[^.]{0,40}μηνισκ\",\n        r\"медиалния менискус\", r\"медиален менискус\", r\"вътрешния менискус\",\n    ),\n    \"Lateral Meniscus\": _rx(\n        r\"lateral meniscus\", r\"lateral menisc\",\n        r\"menisco lateral\", r\"menisco externo\",\n        r\"menisque lateral\", r\"menisque externe\",\n        r\"laterale meniscus\", r\"buitenmeniscus\",\n        r\"aussenmeniskus\", r\"lateralen? meniskus\",\n        r\"lateral menisk\", r\"\\bdis menisk\",\n        r\"lateralni meniskus\", r\"lateralnog meniskusa\", r\"lateralnom meniskusu\",\n        r\"εξω μηνισκ\", r\"μηνισκ[^ ]* του εξω\", r\"εξω διαμερισμα[^.]{0,40}μηνισκ\",\n        r\"латералния менискус\", r\"латерален менискус\", r\"външния менискус\",\n    ),\n}\n\n# Osteoarthritis is rarely written as \"osteoarthritis\". It is written as cartilage loss,\n# chondropathy grade, joint space narrowing, or osteophytes - scoped to a compartment.\nOA_EVIDENCE = _rx(\n    r\"osteoarthrit\", r\"\\barthros\", r\"\\bgonarthros\", r\"\\bosteoarthros\",\n    r\"chondropath\", r\"chondromalac\", r\"condropat\", r\"condromalac\",\n    r\"cartilage loss\", r\"cartilage thinning\", r\"chondral (loss|defect|ulcer|thinning)\",\n    r\"osteophyt\", r\"osteofit\", r\"osteofyt\", r\"osteofito\", r\"osteophyten\",\n    r\"joint space narrowing\", r\"pinzamiento articular\",\n    r\"kikirdak kayb\", r\"kikirdak incelme\", r\"kondropati\", r\"kondral\",\n    r\"kraakbeen(lijden|verlies)\", r\"gonartrose\", r\"artrose\",\n    r\"knorpel(verlust|schaden|defekt)\", r\"arthrose\", r\"gonarthrose\",\n    r\"hrskavic\", r\"hondromalac\", r\"artroz\", r\"osteoartrit\",\n    r\"χονδρ[^ ]*παθ\", r\"αρθριτ\", r\"αρθρωσ\", r\"οστεοφυτ\",\n    r\"αρθρικου χονδρου\", r\"εξαλειψη του αρθρικου χονδρου\",\n    r\"артроз\", r\"хондропат\", r\"остеофит\", r\"хрущял[^.]{0,30}(изтън|увред|дефект)\",\n    r\"ulcera[s]? condral\", r\"cartilago[^.]{0,25}(perdida|adelgaz)\",\n    r\"icrs grade\", r\"outerbridge\",\n)\n\nCOMPARTMENT = {\n    \"Medial OA\": _rx(\n        r\"medial (femorotibial|tibiofemoral|compartment)\",\n        r\"compartimento femorotibial medial\", r\"femorotibial interno\",\n        r\"mediaal femorotibiaal\", r\"mediale femorotibial\",\n        r\"medial femorotibial\", r\"medialen kompartiment\", r\"innere[sn]? kompartiment\",\n        r\"medyal femorotibial\", r\"ic kompartman\", r\"medyal kompartman\",\n        r\"medijaln[^ ]* (femorotibi|odjelj|kompartm)\",\n        r\"εσω διαμερισμα\", r\"εσω κνημιαι\", r\"εσω μηριαι\",\n        r\"медиалн[^ ]* (компартм|отдел|тибиал|феморотиб)\",\n        r\"medial (femoral|tibial) (condyle|plateau)\", r\"condilo femoral medial\",\n        r\"medialen? (femurkondyl|tibiaplateau)\", r\"mediale femorale condyl\",\n    ),\n    \"Lateral OA\": _rx(\n        r\"lateral (femorotibial|tibiofemoral|compartment)\",\n        r\"compartimento femorotibial lateral\", r\"femorotibial externo\",\n        r\"lateraal femorotibiaal\", r\"laterale femorotibial\",\n        r\"lateral femorotibial\", r\"lateralen kompartiment\", r\"aussere[sn]? kompartiment\",\n        r\"lateral femorotibial\", r\"dis kompartman\", r\"lateral kompartman\",\n        r\"lateraln[^ ]* (femorotibi|odjelj|kompartm)\",\n        r\"εξω διαμερισμα\", r\"εξω κνημιαι\", r\"εξω μηριαι\",\n        r\"латералн[^ ]* (компартм|отдел|тибиал|феморотиб)\",\n        r\"lateral (femoral|tibial) (condyle|plateau)\", r\"condilo femoral lateral\",\n        r\"lateralen? (femurkondyl|tibiaplateau)\", r\"laterale femorale condyl\",\n    ),\n    \"PF OA\": _rx(\n        r\"patellofemoral\", r\"femoropatellar\", r\"femoropatelar\", r\"patelofemoral\",\n        r\"retropatellar\", r\"retrorotulian\", r\"\\btrochlea\", r\"\\btroclea\", r\"\\btroklea\",\n        r\"\\bpatella\\b\", r\"\\bpatellar\\b\", r\"\\brotulian\", r\"\\brotula\\b\", r\"\\bpatele\\b\",\n        r\"\\bpatellae?\\b\", r\"patellofemoraal\", r\"femoropatellair\",\n        r\"επιγονατιδ\", r\"μηροεπιγονατιδ\", r\"τροχιλ\",\n        r\"пател\", r\"феморопател\", r\"тролх\",\n        r\"anterior compartment\", r\"compartimento anterior\", r\"prednj[^ ]* odjeljk\",\n    ),\n}\n\n# Self-declaring findings: the term itself is the finding.\nDIRECT = {\n    \"Effusion\": _rx(\n        r\"\\beffusion\", r\"joint fluid\", r\"intra ?articular fluid\", r\"\\bhydrops\\b\",\n        r\"derrame articular\", r\"\\bderrame\\b\", r\"liquido articular\",\n        r\"epanchement\",\n        r\"gewrichtsvocht\", r\"\\bvocht\\b\", r\"\\bhydrops\\b\", r\"gewrichtseffusie\",\n        r\"gelenkerguss\", r\"\\berguss\\b\", r\"gelenksergu\",\n        # \"diz eklemi ici sivi miktari ... artmis\" and \"eklem icerisinde yaygin sivi\n        # artisi\" both occur; the noun takes a possessive suffix, so `eklem ` alone\n        # misses. Match the stem plus any suffix.\n        r\"eklem\\w* ic\\w* sivi\", r\"efuzyon\", r\"eklem sivisi\",\n        r\"sivi (miktari|artisi|birikimi)\", r\"sivi artis\", r\"\\bsivi\\b[^.]{0,25}artmis\",\n        r\"\\bizljev\", r\"\\bizliv\", r\"zglobn[^ ]* tekucin\", r\"\\bhidrops\\b\",\n        r\"αρθρικ[^ ]* υγρ\", r\"υγρου ενδαρθρικα\", r\"ενδαρθρικ[^ ]* υγρ\", r\"ποσοτητα υγρου\",\n        r\"ενδαρθρικ\", r\"αρθρικη συλλογη\", r\"υγρο στην αρθρωση\", r\"υγρου στην αρθρωση\",\n        r\"ставен излив\", r\"излив\", r\"ставна течност\", r\"синовиална течност\",\n    ),\n    \"Synovitis\": _rx(\n        r\"synovit\", r\"sinovit\", r\"synovial (thickening|proliferation|hypertroph)\",\n        r\"synovitis\", r\"synoviale? (verdikking|proliferatie)\",\n        r\"synovialitis\", r\"synovialis(verdickung|proliferation)\",\n        r\"sinovijalitis\", r\"sinovitis\", r\"zadebljanje sinovij\",\n        r\"υμενιτιδα\", r\"συνοβιτιδα\", r\"υμενικ[^ ]* υπερτροφ\", r\"αρθρικου υμεν\",\n        r\"синовит\", r\"синовиал[^ ]* (задебел|пролифер)\",\n        r\"verdikkingen van (het )?synovium\", r\"pannus\",\n    ),\n    \"Baker's\": _rx(\n        r\"baker\", r\"popliteal cyst\", r\"quiste popliteo\", r\"quistes popliteos\",\n        r\"kyste poplite\", r\"popliteale? cyst\", r\"poplitealzyste\", r\"bakerzyste\",\n        r\"popliteal kist\", r\"\\bbakerova\\b\", r\"poplitealn[^ ]* cist\",\n        r\"κυστη baker\", r\"πολυχωρη συνοβιακη κυστη\", r\"κυστη του baker\",\n        r\"киста на бейкър\", r\"бейкърова киста\", r\"поплитеална киста\",\n        r\"gastrocnemio ?semimembranos\", r\"gastrocnemius semimembranosus burs\",\n    ),\n    \"Contusion\": _rx(\n        r\"\\bcontusion\", r\"bone bruise\", r\"bone marrow (o?edema|contusion)\",\n        r\"\\bkontuz\", r\"medular bone o?edema\", r\"marrow o?edema\",\n        r\"contusion osea\", r\"edema oseo\", r\"edema de medula osea\",\n        r\"oedeme osseux\", r\"contusion osseuse\",\n        r\"botcontusie\", r\"botoedeem\", r\"beenmergoedeem\", r\"botmergoedeem\",\n        r\"knochenmarkodem\", r\"knochenodem\", r\"kontusion\", r\"bone bruise\",\n        r\"kemik kontuzyonu\", r\"kemik iligi odemi\", r\"kemik odemi\",\n        r\"kostani edem\", r\"edem kosti\", r\"kontuzij\",\n        r\"οστεομυελικ[^ ]* οιδημα\", r\"οστικο οιδημα\", r\"μυελικο οιδημα\",\n        r\"костномозъчен едем\", r\"костен едем\", r\"контузионен\",\n    ),\n    \"Fracture\": _rx(\n        r\"\\bfractur\", r\"\\bfract\\b\",\n        r\"\\bfractura\", r\"\\bfracturas\\b\",\n        r\"\\bfractuur\", r\"\\bbreuk\\b\",\n        r\"\\bfraktur\", r\"\\bbruch\\b\",\n        r\"\\bkirik\\b\", r\"\\bkirigi\\b\", r\"\\bkirik\\b\",\n        r\"\\bfraktur\", r\"\\bprijelom\", r\"impresijsk[^ ]* fraktur\",\n        r\"καταγμα\", r\"καταγματ\",\n        r\"фрактур\", r\"счупван\", r\"фисур\",\n        r\"insufficiency fracture\", r\"stress fracture\", r\"avulsion fracture\",\n        r\"subchondral fracture\", r\"subkondral kiri\",\n    ),\n}\n\n# Terms that look like a finding but are not the finding being scored.\nDECOY = {\n    \"Fracture\": _rx(r\"no fracture\", r\"microfractur\", r\"\\bfracture (risk|prophyla)\"),\n    \"Baker's\": _rx(r\"meniscal cyst\", r\"quiste meniscal\", r\"ganglion\"),\n}\n\nPAIRED = {\"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\"}\nOA_TARGETS = {\"Medial OA\", \"Lateral OA\", \"PF OA\"}\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.815813Z","iopub.execute_input":"2026-08-10T17:35:04.816268Z","iopub.status.idle":"2026-08-10T17:35:04.900251Z","shell.execute_reply.started":"2026-08-10T17:35:04.816229Z","shell.execute_reply":"2026-08-10T17:35:04.899545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"STEM_MENISCUS = _rx(r\"menisc\\w*\", r\"menisk\\w*\", r\"μηνισκ\\w*\", r\"мениск\\w*\")\nSTEM_CRUCIATE = _rx(r\"cruciate\", r\"cruzado\", r\"croise\", r\"kruisband\", r\"kreuzband\",\n                    r\"capraz bag\\w*\", r\"krizn\\w*\", r\"χιαστ\\w*\", r\"кръстн\\w*\",\n                    r\"\\bacl\\b\", r\"\\bpcl\\b\", r\"\\blca\\b\", r\"\\blcp\\b\", r\"\\bvkb\\b\",\n                    r\"\\bhkb\\b\", r\"\\bocb\\b\", r\"\\bacb\\b\")\nSTEM_COLLATERAL = _rx(r\"collateral\\w*\", r\"colateral\\w*\", r\"kollateral\\w*\",\n                      r\"collaterale\\w*\", r\"kolateraln\\w*\", r\"yan bag\\w*\",\n                      r\"πλαγι\\w*\", r\"колатерал\\w*\", r\"странич\\w*\",\n                      r\"innenband\\w*\", r\"aussenband\\w*\", r\"binnenband\\w*\",\n                      r\"\\bmcl\\b\", r\"\\blcl\\b\", r\"\\blcm\\b\", r\"\\biyb\\b\")\n\nSIDE_MEDIAL = _rx(r\"\\bmedial\\w*\", r\"\\bmedyal\\w*\", r\"\\bmedijaln\\w*\", r\"\\bmediaal\\w*\",\n                  r\"\\bmediale\\w*\", r\"\\binterno\\w*\", r\"\\binterne\\w*\", r\"\\binnen\\w*\",\n                  r\"\\bic\\b\", r\"\\bunutarnj\\w*\", r\"\\bεσω\\w*\", r\"\\bεσωτερικ\\w*\",\n                  r\"\\bмедиал\\w*\", r\"\\bвътреш\\w*\", r\"\\btibial collateral\\b\",\n                  r\"\\bbinnen\\w*\", r\"\\bmediaal\\b\")\nSIDE_LATERAL = _rx(r\"\\blateral\\w*\", r\"\\bexterno\\w*\", r\"\\bexterne\\w*\", r\"\\bdis\\b\",\n                   r\"\\blateraln\\w*\", r\"\\baussen\\w*\", r\"\\bbuiten\\w*\", r\"\\bεξω\\w*\",\n                   r\"\\bεξωτερικ\\w*\", r\"\\bлатерал\\w*\", r\"\\bвъншн\\w*\",\n                   r\"\\bfibular collateral\\b\", r\"\\bvanjsk\\w*\")\nSIDE_ANTERIOR = _rx(r\"\\banterior\\w*\", r\"\\bant\\b\", r\"\\bon\\b\", r\"\\bprednj\\w*\",\n                    r\"\\bvorder\\w*\", r\"\\bvoorste\\b\", r\"\\bπροσθι\\w*\", r\"\\bпредн\\w*\",\n                    r\"\\banteriyor\\w*\", r\"\\bavant\\b\", r\"\\bant[eé]rieur\\w*\")\n\n# Fracture is the target whose stem varies most across the corpus.\nSTEM_FRACTURE = _rx(r\"fractur\\w*\", r\"fraktur\\w*\", r\"fractuur\\w*\", r\"\\bfract\\b\",\n                    r\"kiri[kgğ]\\w*\", r\"prijelom\\w*\", r\"lom kosti\", r\"\\bbreuk\\w*\",\n                    r\"\\bbruch\\w*\", r\"καταγμα\\w*\", r\"καταγματ\\w*\", r\"фрактур\\w*\",\n                    # NOT a bare `fissur\\w*`: \"fisuras condrales\" and \"full thickness\n                    # fissures in the articular cartilage\" describe cartilage, not bone.\n                    # The stem has to be anchored to a bone word to mean a fracture.\n                    r\"счупван\\w*\", r\"fisur\\w* (osea|oseas|kost)\", r\"fissur\\w* kost\")\n\nSTEM_OA_COMPARTMENT = _rx(r\"compartment\\w*\", r\"compartimento\\w*\", r\"compartiment\\w*\",\n                          r\"kompartman\\w*\", r\"kompartiment\\w*\", r\"odjelj\\w*\",\n                          r\"διαμερισμα\\w*\", r\"компартм\\w*\", r\"\\bотдел\\w*\",\n                          r\"femorotibial\\w*\", r\"femorotibiaal\\w*\", r\"tibiofemoral\\w*\",\n                          r\"femoro tibial\\w*\", r\"κνημιαι\\w*\", r\"μηριαι\\w*\",\n                          r\"femoral condyl\\w*\", r\"tibial plateau\\w*\",\n                          r\"condilo femoral\", r\"platillo tibial\", r\"tibiaplateau\\w*\",\n                          r\"femurkondyl\\w*\", r\"femoralne? kondil\\w*\",\n                          r\"tibijaln\\w* plato\", r\"femoral kondil\\w*\",\n                          r\"tibia plato\", r\"tibyal plato\")\n\n\ndef _near(clause: str, stem_rx: re.Pattern, qual_rx: re.Pattern, window: int = 55):\n    \"\"\"True if a stem match has a qualifier within `window` characters either side.\n\n    Character windows rather than token windows, because word order differs: English\n    puts the side before the noun, Greek and Bulgarian often after, and Turkish\n    attaches it as a separate preceding adjective.\n    \"\"\"\n    for m in stem_rx.finditer(clause):\n        lo = max(0, m.start() - window)\n        hi = min(len(clause), m.end() + window)\n        if qual_rx.search(clause[lo:hi]):\n            return True\n    return False\n\n\n# concept -> (stem, side) pairs used in addition to the phrase lexicons above\nSTEM_RULES = {\n    \"ACL\": (STEM_CRUCIATE, SIDE_ANTERIOR),\n    \"MCL\": (STEM_COLLATERAL, SIDE_MEDIAL),\n    \"Medial Meniscus\": (STEM_MENISCUS, SIDE_MEDIAL),\n    \"Lateral Meniscus\": (STEM_MENISCUS, SIDE_LATERAL),\n    \"Medial OA\": (STEM_OA_COMPARTMENT, SIDE_MEDIAL),\n    \"Lateral OA\": (STEM_OA_COMPARTMENT, SIDE_LATERAL),\n}\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.903324Z","iopub.execute_input":"2026-08-10T17:35:04.903899Z","iopub.status.idle":"2026-08-10T17:35:04.920679Z","shell.execute_reply.started":"2026-08-10T17:35:04.903869Z","shell.execute_reply":"2026-08-10T17:35:04.920061Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SEV_LOW = _rx(\n    r\"\\bsmall\\b\", r\"\\bminimal\\b\", r\"\\btrace\\b\", r\"\\bmild\\b\", r\"\\bslight\\b\",\n    r\"\\btiny\\b\", r\"\\bscant\\b\", r\"\\bmimimal\\b\", r\"\\bdiscrete\\b\", r\"\\bfocal\\b\",\n    r\"\\bleve\\b\", r\"\\bminim\", r\"\\bpeque\", r\"\\bligero\\b\", r\"\\bescaso\\b\", r\"\\bdiscreto\\b\",\n    r\"\\bhafif\\b\", r\"\\bminimal\\b\", r\"\\baz miktarda\\b\", r\"\\bsilik\\b\",\n    r\"\\bmanja\\b\", r\"\\bmanji\\b\", r\"\\bblago\\b\", r\"\\bdiskretn\", r\"\\bmalo\\b\",\n    r\"\\bgering\", r\"\\bdiskret\", r\"\\bkleine?r?\\b\", r\"\\bwenig\\b\", r\"\\bzarte?\\b\",\n    r\"\\bbeperkte?\\b\", r\"\\bgeringe\\b\", r\"\\bweinig\\b\", r\"\\blichte?\\b\",\n    r\"\\bηπι\", r\"\\bμικρ\", r\"\\bελαχιστ\",\n    r\"\\bминимал\", r\"\\bлек\", r\"\\bмалк\", r\"\\bнеголям\",\n)\n\nSEV_HIGH = _rx(\n    r\"\\blarge\\b\", r\"\\bmarked\\b\", r\"\\bmassive\\b\", r\"\\bsevere\\b\", r\"\\bextensive\\b\",\n    r\"\\bmoderate\\b\", r\"\\bgross\\b\", r\"\\bsignificant\\b\", r\"\\babundant\\b\", r\"\\btense\\b\",\n    r\"\\bmoderad\", r\"\\bimportante\\b\", r\"\\bsevera?\\b\", r\"\\bmarcad\", r\"\\bcuantios\",\n    r\"\\bbelirgin\\b\", r\"\\byaygin\\b\", r\"\\bileri\\b\", r\"\\bciddi\\b\", r\"\\bbol\\b\",\n    r\"\\bopsezan\\b\", r\"\\bveliki\\b\", r\"\\bizrazit\", r\"\\bznacajn\", r\"\\bumjeren\",\n    r\"\\bausgepragt\", r\"\\bdeutlich\", r\"\\bmassiv\", r\"\\bmassig\", r\"\\bgross\",\n    r\"\\buitgebreid\", r\"\\bgevorderd\", r\"\\bveel\\b\", r\"\\bmatige?\\b\",\n    r\"\\bμετρι\", r\"\\bμεγαλ\", r\"\\bεκτεταμεν\", r\"\\bευμεγεθ\", r\"\\bσοβαρ\",\n    r\"\\bголям\", r\"\\bизразен\", r\"\\bзначим\", r\"\\bумерен\", r\"\\bобилен\",\n)\n\n# OA is often asserted for the whole joint rather than per compartment\n# (\"tricompartmental osteoarthritis\", \"gonarthrose\", \"incipient OA of all three\n# compartments\"). Those statements are evidence for all three OA targets.\nGLOBAL_OA = _rx(\n    r\"tri ?compartment\", r\"all three compartment\", r\"global(ised)? (oa|osteoarthrit)\",\n    r\"\\bgonarthros\", r\"\\bgonartros\", r\"\\bgonarthrose\", r\"\\bgonartrose\",\n    r\"osteoarthritis of the knee\", r\"artrosis (de |)(la )?rodilla\", r\"knee osteoarthrit\",\n    r\"\\bdiz osteoartrit\", r\"\\bgonartroz\", r\"artroza koljena\",\n    r\"οστεοαρθριτιδα\", r\"αρθριτιδα του γονατος\",\n    r\"артроза на колянната\", r\"гонартроз\",\n    r\"degenerative joint disease\", r\"\\bdjd\\b\",\n)\n\n# A bare \"bone marrow oedema\" is not a contusion when it sits under a cartilage\n# defect: subchondral oedema beneath a worn compartment is reactive degenerative signal,\n# and reading it as a bruise turns every osteoarthritic knee into a trauma case.\nDEGENERATIVE_MARROW = _rx(\n    r\"subchondral\", r\"subcondral\", r\"subkondral\", r\"supkondraln\", r\"subchondraln\",\n    r\"υποχονδρι\", r\"субхондрал\", r\"subchondrale?\",\n    r\"\\bcyst\", r\"\\bquist\", r\"\\bzyste\\b\", r\"\\bcistic\", r\"reactive\", r\"reactivo\",\n)\n\nTRAUMA = _rx(\n    r\"\\bbruise\\b\", r\"\\bcontusion\", r\"\\bkontuz\", r\"\\bcontusion osea\\b\",\n    r\"\\btrauma\", r\"\\bimpaction\\b\", r\"\\bpivot shift\\b\", r\"\\bkissing\\b\",\n    r\"\\bacute\\b\", r\"\\bagudo\\b\", r\"\\bakut\", r\"\\bpivot kaymasi\\b\",\n    r\"\\bcontusion osseuse\\b\", r\"\\bbone bruise\\b\", r\"\\bbotcontusie\\b\",\n    r\"\\bконтузион\", r\"\\bμωλωπ\", r\"\\bkontuzij\",\n)\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.921606Z","iopub.execute_input":"2026-08-10T17:35:04.922106Z","iopub.status.idle":"2026-08-10T17:35:04.936525Z","shell.execute_reply.started":"2026-08-10T17:35:04.922083Z","shell.execute_reply":"2026-08-10T17:35:04.935783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def _polarity(clause: str, anchor_end: int) -> str:\n    \"\"\"Classify one clause as positive, negative or uncertain for a matched term.\n\n    Scope is the whole clause. Clause segmentation already keeps statements short, and\n    a window in characters mis-scopes badly across languages with different word orders -\n    Turkish puts its negator at the end of the sentence, English at the front.\n    \"\"\"\n    if UNCERTAIN.search(clause):\n        return \"uncertain\"\n    if NEGATION.search(clause):\n        return \"negative\"\n    if NORMALITY.search(clause):\n        # \"meniscus normal\" negates; \"normal ... but tear\" does not.\n        if TEAR.search(clause) or re.search(r\"\\bgrade [34]\\b\", clause):\n            return \"positive\"\n        return \"negative\"\n    return \"positive\"\n\n\nclass _Matcher:\n    \"\"\"Phrase lexicon first, stem+side proximity as the fallback.\n\n    Exposes `.search` so it drops into the same slot as a compiled pattern.\n    \"\"\"\n\n    def __init__(self, phrase_rx, stem=None, side=None, window=55):\n        self.phrase_rx = phrase_rx\n        self.stem = stem\n        self.side = side\n        self.window = window\n\n    def search(self, clause):\n        m = self.phrase_rx.search(clause)\n        if m is not None:\n            return m\n        if self.stem is not None and _near(clause, self.stem, self.side, self.window):\n            return self.stem.search(clause)\n        return None\n\n\nANAT_MATCH = {\n    tgt: _Matcher(ANAT[tgt], *STEM_RULES[tgt]) for tgt in PAIRED\n}\nCOMPARTMENT_MATCH = {\n    \"Medial OA\": _Matcher(COMPARTMENT[\"Medial OA\"], *STEM_RULES[\"Medial OA\"]),\n    \"Lateral OA\": _Matcher(COMPARTMENT[\"Lateral OA\"], *STEM_RULES[\"Lateral OA\"]),\n    \"PF OA\": _Matcher(COMPARTMENT[\"PF OA\"]),\n}\nDIRECT_MATCH = {\n    tgt: _Matcher(_rx(rx.pattern, STEM_FRACTURE.pattern) if tgt == \"Fracture\" else rx)\n    for tgt, rx in DIRECT.items()\n}\n\n\ndef _severity(clause: str) -> float:\n    \"\"\"Weight one positive mention by how emphatic the sentence is.\n\n    Ordered, not calibrated. A \"moderate effusion\" must outrank a \"trace effusion\" and\n    both must outrank silence; the absolute numbers do not matter to AUC.\n    \"\"\"\n    high = SEV_HIGH.search(clause) is not None\n    low = SEV_LOW.search(clause) is not None\n    if high and not low:\n        return 1.0\n    if low and not high:\n        return 0.45\n    return 0.75                       # unqualified mention\n\n\ndef _score_clauses(cls, anat_rx, path_rx=None, decoy_rx=None, context_penalty=None,\n                   context_bonus=None):\n    \"\"\"Accumulate graded evidence over clauses for one target.\n\n    Returns (score, confidence, n_pos, n_neg). Positives are graded by severity and by\n    optional context regexes; negatives only matter when nothing positive was found,\n    because reports assert normality for every structure they check.\n    \"\"\"\n    n_pos = n_neg = n_unc = 0\n    best = 0.0\n    for c in cls:\n        m = anat_rx.search(c)\n        if not m:\n            continue\n        if decoy_rx is not None and decoy_rx.search(c):\n            continue\n        if path_rx is not None and not path_rx.search(c):\n            if NORMALITY.search(c) and not NEGATION.search(c):\n                n_neg += 1\n            continue\n        pol = _polarity(c, m.end())\n        if pol == \"positive\":\n            n_pos += 1\n            w = _severity(c)\n            if context_penalty is not None and context_penalty.search(c):\n                w *= 0.45\n            if context_bonus is not None and context_bonus.search(c):\n                w = min(1.0, w * 1.35)\n            best = max(best, w)\n        elif pol == \"negative\":\n            n_neg += 1\n        else:\n            n_unc += 1\n            best = max(best, 0.30)\n\n    if n_pos or n_unc:\n        # 0.52 .. 0.95, ordered by the strongest single mention, nudged by repetition.\n        score = min(0.95, 0.50 + 0.42 * best + 0.03 * min(n_pos, 3))\n        conf = min(1.0, 0.55 + 0.15 * n_pos)\n    elif n_neg:\n        score = max(0.04, 0.20 - 0.04 * n_neg)\n        conf = min(0.9, 0.45 + 0.12 * n_neg)\n    else:\n        score, conf = 0.28, 0.05          # silence sits above asserted-negative\n    return score, conf, n_pos, n_neg\n\n\ndef extract(report: str) -> dict:\n    \"\"\"Extract twelve (score, confidence) pairs from one report.\"\"\"\n    cls = clauses(report)\n    out = {}\n    path_paired = _rx(TEAR.pattern, DEGEN.pattern, INJURY.pattern)\n\n    for tgt in TARGETS:\n        if tgt in PAIRED:\n            s, c, npos, nneg = _score_clauses(cls, ANAT_MATCH[tgt], path_paired)\n        elif tgt in OA_TARGETS:\n            s, c, npos, nneg = _score_clauses(cls, COMPARTMENT_MATCH[tgt], OA_EVIDENCE)\n        elif tgt == \"Contusion\":\n            # Reactive subchondral oedema under a cartilage defect is osteoarthritis,\n            # not a bruise. Explicit trauma wording pushes the other way.\n            s, c, npos, nneg = _score_clauses(cls, DIRECT_MATCH[tgt], None, DECOY.get(tgt),\n                                              context_penalty=DEGENERATIVE_MARROW,\n                                              context_bonus=TRAUMA)\n        else:\n            s, c, npos, nneg = _score_clauses(cls, DIRECT_MATCH[tgt], None, DECOY.get(tgt))\n        out[tgt] = s\n        out[tgt + \"__conf\"] = c\n        out[tgt + \"__npos\"] = npos\n        out[tgt + \"__nneg\"] = nneg\n\n    # --- cross-target corrections ------------------------------------------ #\n    # A whole-joint osteoarthritis statement is evidence for every compartment that was\n    # not separately assessed. Without this, \"incipient OA of all three compartments\"\n    # scores zero on all three OA targets.\n    g_hits = [c for c in cls if GLOBAL_OA.search(c) and _polarity(c, 0) == \"positive\"]\n    if g_hits:\n        gscore = 0.50 + 0.42 * max(_severity(c) for c in g_hits)\n        for tgt in OA_TARGETS:\n            if out[tgt + \"__npos\"] == 0 and out[tgt + \"__nneg\"] == 0:\n                out[tgt] = max(out[tgt], gscore * 0.92)\n                out[tgt + \"__conf\"] = max(out[tgt + \"__conf\"], 0.4)\n\n    # Synovitis is frequently visible on the images and absent from the text, so silence\n    # is weak evidence of absence here in a way it is not for other findings. Effusion is\n    # its most reliable textual proxy - the two share a mechanism - so a silent synovitis\n    # inherits a fraction of the effusion evidence instead of falling to the floor.\n    if out[\"Synovitis__npos\"] == 0 and out[\"Synovitis__nneg\"] == 0:\n        out[\"Synovitis\"] = max(out[\"Synovitis\"], 0.28 + 0.45 * (out[\"Effusion\"] - 0.28))\n\n    return out\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.937495Z","iopub.execute_input":"2026-08-10T17:35:04.938322Z","iopub.status.idle":"2026-08-10T17:35:04.961036Z","shell.execute_reply.started":"2026-08-10T17:35:04.938289Z","shell.execute_reply":"2026-08-10T17:35:04.960241Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Reading the acquisition\n\n`train_series.csv` describes each series with an anatomical plane and two binary flags,\n`Fluid_Sensitive` and `Fat_Suppression`. They name two physically independent properties.\n\n*Fluid sensitivity* is a property of the **contrast weighting**, set by repetition time\n$T_R$ and echo time $T_E$. Long $T_R$ suppresses $T_1$ contrast and long $T_E$ builds\n$T_2$ contrast, giving the familiar three regimes:\n\n$$\n\\text{weighting} \\;=\\;\n\\begin{cases}\nT_1 & T_R \\lesssim 800\\ \\text{ms}\\\\\nT_2 & T_R \\gtrsim 800\\ \\text{ms},\\ T_E \\gtrsim 60\\ \\text{ms}\\\\\n\\text{PD} & T_R \\gtrsim 800\\ \\text{ms},\\ T_E \\lesssim 60\\ \\text{ms}\n\\end{cases}\n$$\n\nFluid is bright on $T_2$ and intermediate on proton density; on $T_1$ it is dark. Gradient\necho breaks the rule — its $T_R$ is short by design — so it is kept separate rather than\ncalled $T_1$.\n\n*Fat suppression* is a **preparation** applied on top of any weighting: a chemically\nselective pulse, an inversion (STIR), or water excitation. It is what makes marrow oedema\nconspicuous, because without it the bright fat signal hides it.\n\nThe two are orthogonal, and both are recoverable from the header independently of the\nprovided columns: $T_R$ and $T_E$ give the weighting, and `SeriesDescription`,\n`SequenceName` and `ScanOptions` name the suppression. Two cautions when reading those\nstrings, both of which silently invert the answer if missed:\n\n- underscore is a word character, so a token test for `we` (water excitation) never fires\n  inside `t2_de3d_we_tra`. Separators must be normalised to spaces first.\n- `ScanOptions` must be matched as exact tokens. One vendor writes `SAT_GEMS` for\n  *spatial* saturation, so a substring test for `SAT` marks non-fat-suppressed series as\n  suppressed.\n\n### Which sequences to show the model\n\nA knee is read in three planes because the structures run in different directions:\ncruciate ligaments obliquely, best seen sagittally; collateral ligaments and the meniscal\nbody coronally; patellar cartilage and the retinacula axially. Crossing plane with the two\nacquisition axes gives the slots below, chosen so that each of the twelve findings has at\nleast one sequence that shows it well.\n\n| slot | plane | weighting | fat sat | what it carries |\n|---|---|---|---|---|\n| `SAG_FLUID_FS` | sagittal | PD / T2 | yes | meniscal tears, marrow oedema, effusion |\n| `COR_FLUID_FS` | coronal | PD / T2 | yes | collateral ligaments, meniscal body, oedema |\n| `AX_FLUID_FS` | axial | PD / T2 | yes | patellofemoral joint, synovium, effusion |\n| `SAG_FLUID_NOFS` | sagittal | PD / T2 | no | meniscal morphology at high contrast-to-noise |\n| `COR_T1` | coronal | T1 | no | marrow architecture, cartilage and bone outline |\n| `SAG_T1` | sagittal | T1 | no | anatomy, chronic change |\n\nA study rarely has all six; a per-slot presence mask carries the absences into the head,\nwhich §6 uses.\n","metadata":{}},{"cell_type":"code","source":"from __future__ import annotations\n\nimport os\n\nfor _v in (\"OMP_NUM_THREADS\", \"OPENBLAS_NUM_THREADS\", \"MKL_NUM_THREADS\"):\n    os.environ.setdefault(_v, \"4\")\n\nimport gc\nimport re\nimport time\nimport traceback\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# The label extractor is defined in the cells above when this runs as a notebook. As a\n# plain script it is imported from the package source, so the two paths share one\n# definition rather than keeping a copy each.\nif \"extract\" not in dir():\n    import sys\n    for _p in (\"src\", \"../src\", \"../../src\"):\n        if (Path(_p) / \"report_labeler.py\").is_file():\n            sys.path.insert(0, _p)\n            break\n    from report_labeler import extract  # noqa: F401\n\nT0 = time.time()\nSEED = 2026\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\n\nTARGETS = [\"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\", \"Medial OA\",\n           \"Lateral OA\", \"PF OA\", \"Effusion\", \"Synovitis\", \"Baker's\",\n           \"Contusion\", \"Fracture\"]\n\n# (0020,0032) ImagePositionPatient, (0020,0037) ImageOrientationPatient, (0020,0013) InstanceNumber\nORDER_TAGS     = [(0x0020, 0x0032), (0x0020, 0x0037), (0x0020, 0x0013)]\nORDER_THREADS  = 32\nORDER_BUDGET_S = 2400.0\nORDER_CACHE    = os.environ.get(\"RSNA_ORDER_CACHE\") or None\nIMG = 224                  # encoder input, matches DINOv2's patch-14 grid at 16x16\nCROP_MM = 160.0            # physical extent of the centre crop; a knee FOV is 140-180\nN_SLICE = 3                # slices per slot, stacked as the three input channels\nHDR_THREADS = 16\nPIX_THREADS = 12\nFEAT_BATCH = 64\nTIME_BUDGET = 8.0 * 3600\n\n# Six slots: three planes crossed with the acquisition axes. The fat-suppressed\n# fluid-sensitive series exist for nearly every study; the T1 and the non-suppressed\n# fluid-sensitive series are scarcer, which is what the presence mask is for.\nSLOTS_RECOVERED = [\n    (\"SAG_FLUID_FS\", \"Sagittal\", True, True),\n    (\"COR_FLUID_FS\", \"Coronal\", True, True),\n    (\"AX_FLUID_FS\", \"Axial\", True, True),\n    (\"SAG_FLUID_NOFS\", \"Sagittal\", True, False),\n    (\"COR_T1\", \"Coronal\", False, False),\n    (\"SAG_T1\", \"Sagittal\", False, False),\n]\n\n# The alternative: plane x the provided flag, ignoring the recovered weighting. Kept as\n# a switch so the choice of slot definition can be varied while everything else is held\n# fixed. Under this scheme a `Struct` slot mixes T1 series with non-fat-suppressed PD/T2\n# series, which carry very different tissue contrast.\nSLOTS_PUBLIC = [\n    (\"SAG_FLUID\", \"Sagittal\", None, True),\n    (\"COR_FLUID\", \"Coronal\", None, True),\n    (\"AX_FLUID\", \"Axial\", None, True),\n    (\"SAG_STRUCT\", \"Sagittal\", None, False),\n    (\"COR_STRUCT\", \"Coronal\", None, False),\n    (\"AX_STRUCT\", \"Axial\", None, False),\n]\n\nSLOT_SCHEME = os.environ.get(\"SLOT_SCHEME\", \"recovered\")\nSLOTS = SLOTS_PUBLIC if SLOT_SCHEME == \"public\" else SLOTS_RECOVERED\nN_SLOT = len(SLOTS)\n\n\nREAD_N = 27                # slices read per slot-series; every config subsets this\nREAD_SIZE = 322            # read resolution; configs downsample from here\n\n\ndef slice_groups(n_slices, read_n=None):\n    \"\"\"Split `n_slices` evenly spread positions into consecutive triples.\n\n    A group becomes one three-channel encoder input, and the groups' features are\n    averaged. Spreading first and grouping second keeps each group spanning a\n    proportional chunk of the stack, so a configuration with more groups samples the\n    joint more finely rather than merely repeating the middle of it.\n    \"\"\"\n    read_n = READ_N if read_n is None else read_n\n    idx = np.unique(np.round(np.linspace(0, read_n - 1, n_slices)).astype(int))\n    while len(idx) < n_slices:                       # duplicates only if read_n is small\n        idx = np.append(idx, idx[-1])\n    return [list(map(int, idx[i:i + 3])) for i in range(0, n_slices, 3)]\n\n\nCONFIGS = [\n    {\"name\": \"S224x9\", \"enc\": \"small\", \"img\": 224, \"groups\": slice_groups(9)},\n    {\"name\": \"S224x18\", \"enc\": \"small\", \"img\": 224, \"groups\": slice_groups(18)},\n    {\"name\": \"S224x27\", \"enc\": \"small\", \"img\": 224, \"groups\": slice_groups(27)},\n    {\"name\": \"S322x9\", \"enc\": \"small\", \"img\": 322, \"groups\": slice_groups(9)},\n]\n\nFATSAT_OPTS = {\"FS\", \"FATSAT\", \"FAT_SAT\", \"FSAT\"}\n_SEP = re.compile(r\"[_\\-.]\")\n_FATSAT_RX = re.compile(r\"\\bfs\\b|fatsat|fat sat|\\bstir\\b|\\bspair\\b|\\bspir\\b|\\bwe\\b|\"\n                        r\"water excit|\\btirm\\b|\\bsting\\b|\\bfatsup\\b\")\n_T1_RX = re.compile(r\"\\bt1\\b|\\bt1w\\b\")\n_T2_RX = re.compile(r\"\\bt2\\b|\\bt2w\\b\")\n_PD_RX = re.compile(r\"\\bpd\\b|\\bpdw\\b|proton|\\bdp\\b|dens\")\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:04.962878Z","iopub.execute_input":"2026-08-10T17:35:04.96319Z","iopub.status.idle":"2026-08-10T17:35:10.672353Z","shell.execute_reply.started":"2026-08-10T17:35:04.963169Z","shell.execute_reply":"2026-08-10T17:35:10.671791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def log(msg):\n    print(f\"[{time.time() - T0:7.1f}s] {msg}\", flush=True)\n\n\ndef find_root():\n    for c in [Path(\"/kaggle/input/competitions/rsna-knee-abnormality-detection\"),\n              Path(\"/kaggle/input/rsna-knee-abnormality-detection\"),\n              Path(\"data\"), Path(\".\")]:\n        if (c / \"test.csv\").is_file() and (c / \"test_series\").is_dir():\n            return c\n    # last resort: two-level scan, because the mount is nested one deeper than usual\n    for depth1 in sorted(p for p in Path(\"/kaggle/input\").iterdir() if p.is_dir()):\n        for cand in [depth1] + sorted(p for p in depth1.iterdir() if p.is_dir()):\n            if (cand / \"test.csv\").is_file():\n                return cand\n    raise FileNotFoundError(\"competition mount not found\")\n\n\ndef find_dinov2(variant=\"small\"):\n    \"\"\"Locate a mounted DINOv2 checkpoint directory by variant name.\"\"\"\n    base = Path(\"/kaggle/input\")\n    if not base.is_dir():\n        return None\n    hits = []\n    for root, dirs, files in os.walk(base):\n        dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n        if \"config.json\" in files and \"dinov2\" in root.lower():\n            hits.append(Path(root))\n    for h in hits:\n        if variant in str(h).lower():\n            return h\n    return hits[0] if hits else None\n\n\nROOT = find_root()\nlog(f\"input root: {ROOT}\")\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.673248Z","iopub.execute_input":"2026-08-10T17:35:10.673654Z","iopub.status.idle":"2026-08-10T17:35:10.683174Z","shell.execute_reply.started":"2026-08-10T17:35:10.673629Z","shell.execute_reply":"2026-08-10T17:35:10.682431Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"HDR_TAGS = [\"SeriesDescription\", \"SequenceName\", \"ScanOptions\", \"ScanningSequence\",\n            \"RepetitionTime\", \"EchoTime\", \"Laterality\", \"PixelSpacing\", \"Rows\",\n            \"Columns\", \"RescaleSlope\", \"RescaleIntercept\"]\n\n\ndef probe(item):\n    split, study, series, path = item\n    row = {\"split\": split, \"StudyInstanceUID\": study, \"SeriesInstanceUID\": series,\n           \"dir\": path}\n    try:\n        files = sorted(e.name for e in os.scandir(path) if e.name.endswith(\".dcm\"))\n        row[\"files\"] = files\n        row[\"n_slices\"] = len(files)\n        if not files:\n            return row\n        ds = pydicom.dcmread(os.path.join(path, files[len(files) // 2]),\n                             stop_before_pixels=True, force=True)\n        for t in HDR_TAGS:\n            v = getattr(ds, t, None)\n            if v is None:\n                row[t] = None\n            elif isinstance(v, (list, tuple)) or type(v).__name__ == \"MultiValue\":\n                row[t] = \"|\".join(str(x) for x in v)\n            else:\n                row[t] = str(v)\n    except Exception as exc:\n        row[\"err\"] = str(exc)[:120]\n    return row\n\n\ndef walk(split):\n    base = ROOT / split\n    items = []\n    if not base.is_dir():\n        return pd.DataFrame()\n    for study in os.scandir(base):\n        if study.is_dir():\n            for series in os.scandir(study.path):\n                if series.is_dir():\n                    items.append((split, study.name, series.name, series.path))\n    with ThreadPoolExecutor(max_workers=HDR_THREADS) as pool:\n        rows = list(pool.map(probe, items))\n    return pd.DataFrame(rows)\n\n\ndef annotate(df):\n    \"\"\"Recover fat suppression and pulse-sequence weighting from the header.\"\"\"\n    desc = (df[\"SeriesDescription\"].fillna(\"\") + \" \" + df[\"SequenceName\"].fillna(\"\"))\n    desc = desc.str.lower().str.replace(_SEP, \" \", regex=True)\n\n    opts = df[\"ScanOptions\"].fillna(\"\").str.upper().str.split(\"|\")\n    # GE writes SAT_GEMS for spatial saturation, so ScanOptions must be matched as\n    # exact tokens; a substring test on \"SAT\" fires on non-fat-sat series.\n    opts_fs = opts.apply(lambda ts: any(t.strip() in FATSAT_OPTS for t in ts))\n    df[\"fatsat\"] = desc.str.contains(_FATSAT_RX) | opts_fs\n\n    tr = pd.to_numeric(df[\"RepetitionTime\"], errors=\"coerce\")\n    te = pd.to_numeric(df[\"EchoTime\"], errors=\"coerce\")\n    gre = df[\"ScanningSequence\"].fillna(\"\").str.upper().str.contains(\"GR\")\n    t1, t2, pdw = desc.str.contains(_T1_RX), desc.str.contains(_T2_RX), desc.str.contains(_PD_RX)\n\n    df[\"weight\"] = np.where(t1 & ~t2 & ~pdw, \"T1\",\n                     np.where(t2 & ~pdw, \"T2\",\n                       np.where(pdw, \"PD\",\n                         np.where(gre, \"GRE\",\n                           np.where(tr < 800, \"T1\",\n                             np.where(te > 60, \"T2\",\n                               np.where(tr >= 800, \"PD\", \"UNK\")))))))\n    df[\"fluid\"] = np.isin(df[\"weight\"], [\"PD\", \"T2\"])\n    df[\"px\"] = pd.to_numeric(\n        df[\"PixelSpacing\"].fillna(\"\").str.split(\"|\").str[0].replace(\"\", np.nan),\n        errors=\"coerce\")\n    return df\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.684697Z","iopub.execute_input":"2026-08-10T17:35:10.685372Z","iopub.status.idle":"2026-08-10T17:35:10.699205Z","shell.execute_reply.started":"2026-08-10T17:35:10.685349Z","shell.execute_reply":"2026-08-10T17:35:10.698529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def pick_slots(series_df, plane_map):\n    \"\"\"One series per slot per study.\n\n    Ties are broken toward the stack with the most slices: a thicker stack samples the\n    joint more densely, and the three-slice sampler below benefits from the margin.\n    \"\"\"\n    series_df = series_df.copy()\n    series_df[\"plane\"] = series_df[\"SeriesInstanceUID\"].map(plane_map)\n    out = {}\n    for study, g in series_df.groupby(\"StudyInstanceUID\"):\n        chosen = {}\n        for name, plane, fluid, fs in SLOTS:\n            sel = (g[\"plane\"] == plane) & (g[\"fatsat\"] == fs)\n            # fluid=None means \"do not condition on weighting\" - the public scheme,\n            # where the single provided flag stands in for both axes at once.\n            if fluid is not None:\n                sel &= (g[\"fluid\"] == fluid)\n            cand = g[sel]\n            if len(cand) == 0 and fluid is False:\n                # T1 slots are the scarcest; fall back to any non-fat-sat, non-fluid\n                # series in the plane before giving up on the slot entirely.\n                cand = g[(g[\"plane\"] == plane) & (~g[\"fatsat\"])]\n            if len(cand):\n                chosen[name] = cand.sort_values(\"n_slices\", ascending=False).iloc[0]\n        out[study] = chosen\n    return out\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.700106Z","iopub.execute_input":"2026-08-10T17:35:10.700396Z","iopub.status.idle":"2026-08-10T17:35:10.713533Z","shell.execute_reply.started":"2026-08-10T17:35:10.700366Z","shell.execute_reply":"2026-08-10T17:35:10.713061Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Sampling at a fixed physical scale\n\nA DICOM slice of $N \\times N$ pixels with spacing $s$ mm/pixel covers $N s$ millimetres of\nanatomy. Both $N$ and $s$ vary widely across this corpus, so a fixed-pixel resize —\n\"make everything $224 \\times 224$\" — hands the encoder images whose physical scale differs\nby a factor of about three. A meniscus then occupies a different number of pixels in\ndifferent studies for no anatomical reason, and the network has to spend capacity undoing\na nuisance transform it was handed for free.\n\nCrop to a constant physical extent $L$ before resizing. Taking the centre\n\n$$n \\;=\\; \\Big\\lfloor \\frac{L}{s} \\Big\\rceil \\quad\\text{pixels}$$\n\nand resampling that to $P \\times P$ leaves an effective scale of\n\n$$s_{\\text{eff}} \\;=\\; \\frac{L}{P}\\ \\ \\text{mm/pixel}$$\n\nwhich no longer depends on the acquisition. With $L = 160$ mm — a knee fits comfortably\ninside that — and $P = 224$, every study reaches the encoder at $0.71$ mm/pixel.\n\n**Intensity needs the same treatment for the same reason.** MR has no absolute scale: the\nsame tissue takes a different number on a different sequence, coil or day, so there is no\nHounsfield-unit equivalent to anchor to. Normalising each series to its own 1st and 99th\npercentile — over the whole volume, not per slice, so slices keep their relative contrast\n— removes an offset that would otherwise track the acquisition site. Percentiles rather\nthan min and max, because one bright vessel would otherwise compress everything else.\n\nSlices are taken from the central 60% of each stack. The outer slices of a knee series\nmostly lie outside the joint, and sampling them spends read bandwidth on soft tissue.\n","metadata":{}},{"cell_type":"code","source":"def order_slices(rec):\n    \"\"\"Return this series' files sorted along the through-plane axis.\n\n    n = r_x x r_y  (slice normal from ImageOrientationPatient)\n    k = p . n      (signed through-plane coordinate, monotonic along the stack)\n    \"\"\"\n    files, d = rec[\"files\"], rec[\"dir\"]\n    keyed = []\n    for f in files:\n        ds, k = None, None\n        try:\n            ds = pydicom.dcmread(os.path.join(d, f), force=True,\n                                 stop_before_pixels=True, specific_tags=ORDER_TAGS)\n            iop = np.asarray(ds.ImageOrientationPatient, dtype=float)\n            ipp = np.asarray(ds.ImagePositionPatient, dtype=float)\n            k = float(np.dot(ipp, np.cross(iop[:3], iop[3:])))\n        except Exception:\n            try:\n                k = float(ds.InstanceNumber) if ds is not None else None\n            except Exception:\n                k = None\n        keyed.append((k, f))\n    if any(k is None for k, _ in keyed):\n        # No usable geometry: keep arbitrary order. Worse than sorting, better than\n        # dropping the series — and it gets counted rather than swallowed.\n        return files, False\n    return [f for _, f in sorted(keyed, key=lambda t: t[0])], True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.715765Z","iopub.execute_input":"2026-08-10T17:35:10.716425Z","iopub.status.idle":"2026-08-10T17:35:10.729108Z","shell.execute_reply.started":"2026-08-10T17:35:10.716402Z","shell.execute_reply":"2026-08-10T17:35:10.728343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def read_slot(rec, n_slice=None, out_size=None):\n    \"\"\"`n_slice` physically spread slices from one series, at `out_size` pixels.\n\n    Returns float32 [n_slice, out, out] normalised per-series to its 1st-99th\n    percentile. Percentiles rather than min/max because MR intensity has no absolute\n    scale and a single bright vessel would otherwise compress the whole dynamic range.\n\n    Reading is the expensive half of this pipeline, so the caller reads once at the\n    largest configuration it needs and derives the smaller ones from the returned buffer\n    rather than re-reading.\n    \"\"\"\n    n_slice = N_SLICE if n_slice is None else n_slice\n    out_size = IMG if out_size is None else out_size\n    files, d, px = rec.get(\"ordered\") or rec[\"files\"], rec[\"dir\"], rec[\"px\"]\n    n = len(files)\n    if n == 0:\n        return None\n    # Spread the samples over the central 60% of the stack: the outer slices of a knee\n    # series are mostly soft tissue outside the joint.\n    lo, hi = int(0.20 * (n - 1)), int(0.80 * (n - 1))\n    idx = np.unique(np.linspace(lo, hi, n_slice).astype(int)) if hi > lo else np.array([n // 2])\n    while len(idx) < n_slice:\n        idx = np.append(idx, idx[-1])\n\n    planes = []\n    for i in idx[:n_slice]:\n        try:\n            ds = pydicom.dcmread(os.path.join(d, files[int(i)]), force=True)\n            a = ds.pixel_array.astype(np.float32)\n            sl = float(getattr(ds, \"RescaleSlope\", 1) or 1)\n            ic = float(getattr(ds, \"RescaleIntercept\", 0) or 0)\n            a = a * sl + ic\n        except Exception:\n            a = np.zeros((out_size, out_size), dtype=np.float32)\n        planes.append(a)\n\n    shp = planes[0].shape\n    planes = [p if p.shape == shp else np.zeros(shp, np.float32) for p in planes]\n    vol = np.stack(planes)\n\n    # constant physical extent, then resize: PixelSpacing varies 3.4x across the corpus\n    if px and np.isfinite(px) and px > 0:\n        want = int(round(CROP_MM / px))\n        h, w = shp\n        if 16 < want < min(h, w):\n            cy, cx = h // 2, w // 2\n            half = want // 2\n            vol = vol[:, max(0, cy - half):cy + half, max(0, cx - half):cx + half]\n\n    lo_v, hi_v = np.percentile(vol, [1, 99])\n    vol = np.clip((vol - lo_v) / max(hi_v - lo_v, 1e-6), 0, 1)\n\n    t = torch.from_numpy(np.ascontiguousarray(vol)).unsqueeze(0)\n    t = F.interpolate(t, size=(out_size, out_size), mode=\"bilinear\", align_corners=False)\n    # uint8, not float32. These buffers queue up between the reader threads and the\n    # encoder, and at this size a float32 slot-series is several megabytes. Intensity is\n    # already normalised into [0, 1] here, so eight bits cost nothing that a bilinear\n    # resize has not already cost, and the queue is a quarter the size.\n    n_uniq = int(len(np.unique(idx[:n_slice])))\n    return (t.squeeze(0) * 255).round().clamp(0, 255).to(torch.uint8), n_uniq","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.729893Z","iopub.execute_input":"2026-08-10T17:35:10.730139Z","iopub.status.idle":"2026-08-10T17:35:10.743117Z","shell.execute_reply.started":"2026-08-10T17:35:10.730093Z","shell.execute_reply":"2026-08-10T17:35:10.742397Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5. Normalising left and right\n\nFour of the twelve targets — the two menisci and the medial and lateral tibiofemoral\ncompartments — are medial/lateral pairs. Medial and lateral are defined relative to the\nbody's midline, so which side of the *image* they fall on depends on which knee was\nscanned. Unless that is normalised, those four labels are being asked to learn from an\naxis the model cannot observe.\n\nThe correction is not the same in every plane, because the mirror acts on a different\nimage axis:\n\n- **Coronal and axial.** The medial-lateral direction lies in the image plane, so a left\n  knee is the horizontal mirror of a right knee. Flipping the last axis maps one onto the\n  other.\n- **Sagittal.** The medial-lateral direction is the *slice* axis; each individual slice is\n  unchanged by mirroring. What differs is the order in which the stack traverses the\n  joint, so the slice order is reversed rather than the pixels flipped.\n\n`Laterality` is present in the header for some studies and absent for others. Where it is\nabsent the volume is left alone: a wrong flip is worse than no flip, and the presence mask\nlets the head learn how much to trust each slot.\n","metadata":{}},{"cell_type":"code","source":"def normalise_laterality(img, plane, lat):\n    \"\"\"Map every knee onto a left-knee convention.\n\n    Coronal and axial views mirror under a horizontal flip. Sagittal stacks are not\n    mirror images of each other - the slice order runs medial-to-lateral in opposite\n    directions - so the channel order is reversed instead.\n    \"\"\"\n    if lat != \"R\":\n        return img\n    if plane in (\"Coronal\", \"Axial\"):\n        return torch.flip(img, dims=[-1])\n    return torch.flip(img, dims=[0])\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.744008Z","iopub.execute_input":"2026-08-10T17:35:10.744592Z","iopub.status.idle":"2026-08-10T17:35:10.758005Z","shell.execute_reply.started":"2026-08-10T17:35:10.744562Z","shell.execute_reply":"2026-08-10T17:35:10.757321Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 6. Aggregating slots into twelve decisions\n\nEach study arrives as up to six slot embeddings $x_s \\in \\mathbb{R}^{d}$ with a presence\nmask $m_s \\in \\{0,1\\}$. Pooling them identically would discard the reason the protocol has\nthree planes at all: each finding is read on particular sequences, and a mean over slots\ndilutes the one that carries the evidence with five that do not.\n\nProject each slot and add a learned slot identity,\n\n$$h_s \\;=\\; \\phi(x_s) + e_s, \\qquad h_s \\in \\mathbb{R}^{H},$$\n\ngive every diagnosis $o$ its own query $q_o \\in \\mathbb{R}^{H}$, and let it attend over\nthe slots, with absent slots masked out of the softmax:\n\n$$\n\\alpha_{o,s} \\;=\\; \\frac{\\exp\\!\\big(\\langle h_s, q_o\\rangle / \\sqrt{H}\\big)\\, m_s}\n{\\sum_{s'} \\exp\\!\\big(\\langle h_{s'}, q_o\\rangle / \\sqrt{H}\\big)\\, m_{s'}},\n\\qquad\nc_o \\;=\\; \\sum_s \\alpha_{o,s}\\, h_s ,\n$$\n\n$$\\ell_o \\;=\\; \\langle c_o, w_o \\rangle + b_o .$$\n\nThe masked softmax renormalises over whatever the study actually contains, so a missing\naxial series shifts a diagnosis's attention onto the sequences that are present instead of\nfeeding it a zero vector.\n\nThe encoder is a frozen self-supervised vision transformer; each slot is represented by\nits class token concatenated with the mean of its patch tokens. Freezing is a deliberate\nchoice at this label budget: the derived targets carry extraction noise, and fine-tuning a\nfull backbone against noisy targets fits the noise. Only the head above is trained, and\nthe loss is a per-label binary cross-entropy weighted by the per-study, per-label\nconfidence from §2.\n","metadata":{}},{"cell_type":"code","source":"class Encoder:\n    def __init__(self, variant=\"small\"):\n        p = find_dinov2(variant)\n        self.variant = variant\n        self.ok = p is not None\n        self.dev = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        if not self.ok:\n            log(f\"WARNING: DINOv2 '{variant}' not found; falling back to pooled pixels\")\n            self.dim = 256\n            return\n        from transformers import AutoModel\n        self.model = AutoModel.from_pretrained(str(p)).eval()\n        self.dim = self.model.config.hidden_size * 2\n\n        # The scheduled accelerator is not always the one the metadata asked for, and the\n        # shipped torch build does not compile kernels for every compute capability. When\n        # it does not, the first CUDA op raises `no kernel image is available for\n        # execution on the device`. Probe with a dummy forward and fall back to CPU rather\n        # than losing the whole session to it.\n        self._place(self.dev)\n        try:\n            with torch.no_grad():\n                self.model(pixel_values=torch.zeros(1, 3, IMG, IMG, device=self.dev))\n        except Exception as exc:\n            log(f\"GPU unusable ({type(exc).__name__}: {str(exc)[:90]}); falling back to CPU\")\n            self.dev = torch.device(\"cpu\")\n            self._place(self.dev)\n        log(f\"DINOv2 '{variant}' from {p}, dim {self.dim}, device {self.dev}\")\n\n    def _place(self, dev):\n        self.model = self.model.to(dev)\n        self.mean = torch.tensor([0.485, 0.456, 0.406], device=dev).view(1, 3, 1, 1)\n        self.std = torch.tensor([0.229, 0.224, 0.225], device=dev).view(1, 3, 1, 1)\n\n    @torch.no_grad()\n    def __call__(self, batch):\n        x = batch.to(self.dev, non_blocking=True)\n        if not self.ok:\n            return F.adaptive_avg_pool2d(x, 16).flatten(1)[:, :self.dim].float().cpu()\n        x = (x - self.mean) / self.std\n        with torch.autocast(\"cuda\", enabled=self.dev.type == \"cuda\"):\n            out = self.model(pixel_values=x).last_hidden_state\n        return torch.cat([out[:, 0], out[:, 1:].mean(1)], dim=1).float().cpu()\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.758799Z","iopub.execute_input":"2026-08-10T17:35:10.759034Z","iopub.status.idle":"2026-08-10T17:35:10.772025Z","shell.execute_reply.started":"2026-08-10T17:35:10.759014Z","shell.execute_reply":"2026-08-10T17:35:10.771242Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 8. Sizing the work\n\nThe cost is dominated by reading, not by arithmetic. A study holds several series and each\nseries holds tens of slices, so a study is on the order of a hundred and fifty files.\nReading every slice of every study is hundreds of thousands of decodes.\n\nThe slot design is what makes a much smaller number sufficient: it is a statement about\nwhich series carry the twelve findings, so restricting attention to `N_SLOT` series per\nstudy is a modelling decision rather than a shortcut. Within a chosen series, coverage of\nthe joint is a free parameter. Slices are read at `READ_N` positions spread over the\ncentral part of the stack and grouped into consecutive triples; each triple is one\nthree-channel encoder input, and a configuration's features are the mean over its groups.\nMore groups sample the joint more finely at a proportional cost, so this is the axis worth\nmeasuring rather than guessing.\n\n### What the configurations vary\n\nA frozen encoder offers three ways to spend more compute, and they are not equivalent:\n\n| axis | what it changes | what it cannot fix |\n|---|---|---|\n| **coverage** — more slice groups | *which anatomy is seen at all* | nothing about how it is seen |\n| **resolution** — larger input | how finely the seen anatomy is resolved | anatomy outside the sampled slices |\n| **capacity** — larger backbone | how the seen pixels are described | either of the above |\n\nOnly the first changes the *information* reaching the head; the other two change its\ndescription. A tear a few slices away from every sampled position is invisible at any\nresolution and to any backbone, which is an argument for looking at coverage first. It is\nan argument, not a result, so the configurations below vary coverage across a range and\nhold one resolution probe fixed against it to test whether the two interact.\n\nComparing them is only meaningful if nothing else moves, so all configurations share one\nread pass and differ solely in which slices they take and at what size.\n\nTwo implementation consequences follow, both of which are about the queue between the\nreading threads and the encoder rather than about either one alone:\n\n- buffers crossing that queue are held as `uint8`. Intensity has already been normalised\n  into $[0,1]$, so eight bits cost nothing a bilinear resize has not already cost, and the\n  buffer is a quarter the size.\n- reads are issued in bounded chunks. Submitting every job at once lets the readers run\n  arbitrarily far ahead of the encoder, and the completed results accumulate.\n\nA valid submission file is written before any of this begins and overwritten once real\npredictions exist, so the run always leaves a scoreable file behind.\n","metadata":{}},{"cell_type":"code","source":"def build_features(slot_map, plane_map, lat_map, tag):\n    \"\"\"Encode every (study, slot, group) triple under every configuration in CONFIGS.\n\n    Returns {config_name: (features, mask)} with features shaped\n    [n_studies, N_SLOT, n_groups, dim] and mask [n_studies, N_SLOT, n_groups].\n    \"\"\"\n    studies = sorted(slot_map)\n    sidx = {s: i for i, s in enumerate(studies)}\n    store = {c[\"name\"]: (np.zeros((len(studies), N_SLOT, len(c[\"groups\"]),\n                                   ENCODERS[c[\"enc\"]].dim), np.float16),\n                         np.zeros((len(studies), N_SLOT, len(c[\"groups\"])), np.float32))\n             for c in CONFIGS}\n\n    jobs = []\n    for st in studies:\n        for k, (name, plane, _, _) in enumerate(SLOTS):\n            rec = slot_map[st].get(name)\n            if rec is not None:\n                jobs.append((st, k, plane, rec))\n    log(f\"{tag}: {len(studies)} studies, {len(jobs)} slot-series, {len(CONFIGS)} configs\")\n    # Ordering first, as its own pass. It opens one header per slice of every chosen\n    # series — far more file opens than the decode that follows — and on a network\n    # mount that is latency, not work, so it gets its own wider pool.\n    t_ord = time.time()\n    n_hdr = sum(len(j[3][\"files\"]) for j in jobs)\n    log(f\"{tag}: ordering {len(jobs)} slot-series ({n_hdr} slice headers)\")\n    ok = done_o = 0\n    seen, todo = {}, jobs\n    \n    if ORDER_CACHE and Path(ORDER_CACHE).is_file():\n        try:\n            seen = json.loads(Path(ORDER_CACHE).read_text())\n        except (OSError, ValueError):\n            seen = {}\n        hit = 0\n        for _, _, _, rec in jobs:\n            e = seen.get(rec[\"SeriesInstanceUID\"])\n            if e and len(e[\"files\"]) == len(rec[\"files\"]):   # validate by file count\n                rec[\"ordered\"] = e[\"files\"]\n                ok += int(e[\"good\"])\n                hit += 1\n        todo = [j for j in jobs if \"ordered\" not in j[3]]\n        log(f\"{tag}: {hit} slot-series from cache, {len(todo)} to read\")\n    \n    CHUNK_O = 1024\n    with ThreadPoolExecutor(max_workers=ORDER_THREADS) as pool:\n        for c0 in range(0, len(todo), CHUNK_O):\n            block = todo[c0:c0 + CHUNK_O]\n            for (_, _, _, rec), (of, good) in zip(\n                    block, pool.map(lambda j: order_slices(j[3]), block)):\n                rec[\"ordered\"] = of\n                ok += int(good)\n                done_o += 1\n                if ORDER_CACHE:\n                    seen[rec[\"SeriesInstanceUID\"]] = {\"files\": of, \"good\": bool(good)}\n            budget = min(ORDER_BUDGET_S,\n                         max(60.0, (TIME_BUDGET - (time.time() - T0)) * 0.35))\n            if time.time() - t_ord > budget:\n                log(f\"{tag}: ordering budget spent at {done_o}/{len(todo)}; rest keep file order\")\n                break\n    \n    if ORDER_CACHE and done_o:\n        tmp = Path(ORDER_CACHE).with_suffix(\".tmp\")\n        tmp.write_text(json.dumps(seen))\n        tmp.replace(Path(ORDER_CACHE))\n    log(f\"{tag}: ordered {ok}/{len(jobs)} by geometry \"\n        f\"({len(jobs) - ok} kept arbitrary) in {time.time() - t_ord:.0f}s\")\n    buf_vol, buf_key = [], []\n\n    def flush():\n        if not buf_vol:\n            return\n        vols = torch.stack(buf_vol).float().div_(255.0)   # B, READ_N, READ_SIZE, READ_SIZE\n        for c in CONFIGS:\n            enc = ENCODERS[c[\"enc\"]]\n            feats, mask = store[c[\"name\"]]\n            for g, grp in enumerate(c[\"groups\"]):\n                x = vols[:, grp]                          # B, 3, S, S\n                if c[\"img\"] != READ_SIZE:\n                    x = F.interpolate(x, size=(c[\"img\"], c[\"img\"]), mode=\"bilinear\",\n                                      align_corners=False)\n                out = enc(x).numpy()\n                for (i, kk, nu), v in zip(buf_key, out):\n                    feats[i, kk, g] = v\n                    mask[i, kk, g] = 1.0 if min(grp) < nu else 0.0\n        buf_vol.clear()\n        buf_key.clear()\n\n    CHUNK = 512\n    done = 0\n    stop = False\n    with ThreadPoolExecutor(max_workers=PIX_THREADS) as pool:\n        for c0 in range(0, len(jobs), CHUNK):\n            block = jobs[c0:c0 + CHUNK]\n            for (st, k, plane, rec), res in zip(\n                    block, pool.map(lambda j: read_slot(j[3], READ_N, READ_SIZE), block)):\n                done += 1\n                if res is None:\n                    continue\n                vol, n_uniq = res\n                vol = normalise_laterality(vol, plane, lat_map.get(st))\n                buf_vol.append(vol)\n                buf_key.append((sidx[st], k, n_uniq))\n                if len(buf_vol) >= FEAT_BATCH:\n                    flush()\n            if done % 4096 < CHUNK:\n                log(f\"  {tag} {done}/{len(jobs)}\")\n            if time.time() - T0 > TIME_BUDGET:\n                log(f\"  {tag}: time budget hit, stopping encode early\")\n                stop = True\n            if stop:\n                break\n    flush()\n    gc.collect()\n    return studies, store","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.773031Z","iopub.execute_input":"2026-08-10T17:35:10.773513Z","iopub.status.idle":"2026-08-10T17:35:10.802595Z","shell.execute_reply.started":"2026-08-10T17:35:10.77349Z","shell.execute_reply":"2026-08-10T17:35:10.802005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Head(nn.Module):\n    def __init__(self, dim, n_slot, n_group, n_out, hidden=256, p=0.2):\n        super().__init__()\n        self.proj = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU())\n        self.slot_emb  = nn.Parameter(torch.randn(n_slot, hidden) * 0.02)\n        self.group_emb = nn.Parameter(torch.randn(n_group, hidden) * 0.02)\n        self.query = nn.Parameter(torch.randn(n_out, hidden) * 0.02)\n        self.drop  = nn.Dropout(p)\n        self.out   = nn.Linear(hidden, n_out)\n        self.hidden, self.n_slot, self.n_group = hidden, n_slot, n_group\n\n    def forward(self, x, mask):                     # x: B, S*G, D   mask: B, S*G\n        pos = (self.slot_emb.repeat_interleave(self.n_group, 0)\n               + self.group_emb.repeat(self.n_slot, 1))        # S*G, H\n        h = self.proj(x) + pos\n        att = torch.einsum(\"bth,oh->bot\", h, self.query) / self.hidden ** 0.5\n        att = att.masked_fill(mask.unsqueeze(1) < 0.5, -1e4).softmax(-1)\n        ctx = self.drop(torch.einsum(\"bot,bth->boh\", att, h))\n        return (ctx * self.out.weight.unsqueeze(0)).sum(-1) + self.out.bias","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.803639Z","iopub.execute_input":"2026-08-10T17:35:10.803939Z","iopub.status.idle":"2026-08-10T17:35:10.818766Z","shell.execute_reply.started":"2026-08-10T17:35:10.803908Z","shell.execute_reply":"2026-08-10T17:35:10.818063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_head(Xtr, Mtr, Ytr, Wtr, Xva=None, Mva=None, epochs=26, seed=0):\n    torch.manual_seed(seed)\n    dev = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    n_group = Xtr.shape[1] // N_SLOT\n    model = Head(Xtr.shape[-1], N_SLOT, n_group, len(TARGETS)).to(dev)\n    opt = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-2)\n    sched = torch.optim.lr_scheduler.OneCycleLR(opt, 2e-3, total_steps=epochs * 20)\n\n    xt = torch.tensor(Xtr, device=dev)\n    mt = torch.tensor(Mtr, device=dev)\n    yt = torch.tensor(Ytr, device=dev)\n    wt = torch.tensor(Wtr, device=dev)\n    n = len(xt)\n    for _ in range(epochs):\n        model.train()\n        perm = torch.randperm(n, device=dev)\n        for b in range(20):\n            idx = perm[b * (n // 20):(b + 1) * (n // 20)]\n            if len(idx) < 8:\n                continue\n            logit = model(xt[idx], mt[idx])\n            loss = (F.binary_cross_entropy_with_logits(logit, yt[idx], reduction=\"none\")\n                    * wt[idx]).mean()\n            opt.zero_grad()\n            loss.backward()\n            opt.step()\n            sched.step()\n    model.eval()\n    with torch.no_grad():\n        pv = None\n        if Xva is not None:\n            pv = torch.sigmoid(model(torch.tensor(Xva, device=dev),\n                                     torch.tensor(Mva, device=dev))).cpu().numpy()\n    return model, pv\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.81971Z","iopub.execute_input":"2026-08-10T17:35:10.820021Z","iopub.status.idle":"2026-08-10T17:35:10.832606Z","shell.execute_reply.started":"2026-08-10T17:35:10.819999Z","shell.execute_reply":"2026-08-10T17:35:10.832036Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 7. Validating without fooling yourself\n\nTwo leaks are specific to this setup, and both inflate a validation number without\nimproving anything.\n\n**Shared reports.** Some reports are byte-identical across studies — a template read for\nan unremarkable knee. Every study in such a group receives the same derived target vector.\nSplit the group across folds and the model is scored on a target whose source it has\nalready been trained on. Folds are therefore assigned by a hash of the report text, which\nkeeps every duplicate group whole inside one fold.\n\n**Two references, two meanings.** Out-of-fold performance is reported twice: against the\nderived targets, which covers every training study and measures whether the imaging model\nlearned what the text says; and against the studies with per-condition annotations, which\nis far smaller and measures agreement with a reading of the *images*. The second is the\none that resembles the test set. The first is the one with enough positives per label to\ndistinguish a real difference from noise.\n\n### Choosing what to submit\n\nHaving two references makes selection a decision rather than a lookup, and the obvious\nrule — take the best on the larger reference — is wrong. The two measure different things,\nso a candidate that gains on one while losing on the other has not been shown to be\nbetter; it has been shown to be different. Ranking candidates by\n\n$$\\text{rank}(c) \\;=\\; \\min\\big(\\mathrm{AUC}^{\\text{derived}}_c,\\ \\mathrm{AUC}^{\\text{annot}}_c\\big)$$\n\nrefuses that trade: a candidate is only preferred if its *weaker* evidence is stronger than\neverything else's weaker evidence.\n\nThe same rule decides whether to ensemble at all. A rank mean over configurations is\nincluded as one more candidate rather than assumed to win. An ensemble inherits the\nweaknesses of its members, so one member that is poor against the annotations can drag the\nmean below a single configuration that is good against both — and averaging is a habit,\nnot a law.\n","metadata":{}},{"cell_type":"code","source":"def write_benchmark_submission():\n    \"\"\"Write the 0.5 benchmark file immediately.\n\n    A submission that never writes scores nothing at all, which is strictly worse than\n    scoring badly. The try/except around main() covers exceptions, but a kill for memory\n    is a SIGKILL and never reaches it. So a valid file exists from the first second and\n    is overwritten only once real predictions are ready.\n    \"\"\"\n    t = pd.read_csv(ROOT / \"test.csv\")\n    for c in TARGETS:\n        t[c] = 0.5\n    t.to_csv(\"submission.csv\", index=False)\n\n\ndef main():\n    write_benchmark_submission()\n    test_df = pd.read_csv(ROOT / \"test.csv\")\n    test_series = pd.read_csv(ROOT / \"test_series.csv\")\n    train_df = pd.read_csv(ROOT / \"train.csv\")\n    train_series = pd.read_csv(ROOT / \"train_series.csv\")\n    log(f\"train {train_df.shape} test {test_df.shape}\")\n\n    plane_map = dict(zip(\n        pd.concat([train_series, test_series])[\"SeriesInstanceUID\"],\n        pd.concat([train_series, test_series])[\"Anatomical_Plane\"]))\n\n    log(\"header pass: test\")\n    hte = annotate(walk(\"test_series\"))\n    log(f\"  {len(hte)} test series\")\n    log(\"header pass: train\")\n    htr = annotate(walk(\"train_series\"))\n    log(f\"  {len(htr)} train series\")\n\n    def lat_of(h):\n        \"\"\"Study -> 'L' / 'R' / None. The tag is present on 50% of studies and is\n        sometimes an empty string rather than absent, which is not the same as NaN.\"\"\"\n        d = {}\n        for st, g in h.groupby(\"StudyInstanceUID\"):\n            v = [str(x).strip().upper() for x in g[\"Laterality\"].dropna()]\n            v = [x[0] for x in v if x and x[0] in (\"L\", \"R\")]\n            d[st] = v[0] if v else None\n        return d\n\n    slots_te, slots_tr = pick_slots(hte, plane_map), pick_slots(htr, plane_map)\n    cov = pd.Series([len(v) for v in slots_tr.values()]).describe()\n    log(f\"train slots per study: mean {cov['mean']:.2f} min {cov['min']:.0f} max {cov['max']:.0f}\")\n\n    global ENCODERS\n    ENCODERS = {v: Encoder(v) for v in sorted({c[\"enc\"] for c in CONFIGS})}\n\n    st_tr, store_tr = build_features(slots_tr, plane_map, lat_of(htr), \"train\")\n    st_te, store_te = build_features(slots_te, plane_map, lat_of(hte), \"test\")\n\n    # ---- targets ---------------------------------------------------------- #\n    # Targets are derived here rather than attached as a file. The extractor is pure\n    # text over a few megabytes of reports, so running it inline costs seconds against a\n    # run measured in tens of minutes, and it removes the one way this pipeline could\n    # silently go stale: a change to the extractor that never reaches a frozen copy of\n    # its output.\n    t_lab = time.time()\n    lab = pd.DataFrame([extract(r) for r in train_df[\"Report\"].fillna(\"\")])\n    lab[\"StudyInstanceUID\"] = train_df[\"StudyInstanceUID\"].values\n    lab = lab.set_index(\"StudyInstanceUID\")\n    log(f\"derived labels for {len(lab)} studies in {time.time() - t_lab:.1f}s\")\n\n    gold = train_df.set_index(\"StudyInstanceUID\")[TARGETS]\n    gold = gold[gold.notna().all(axis=1)]\n\n    Y = np.zeros((len(st_tr), len(TARGETS)), np.float32)\n    W = np.zeros_like(Y)\n    for i, st in enumerate(st_tr):\n        if st in gold.index:\n            Y[i] = gold.loc[st].values\n            W[i] = 3.0                        # radiologist reads outrank derived labels\n        elif st in lab.index:\n            r = lab.loc[st]\n            Y[i] = r[TARGETS].values\n            W[i] = 0.25 + 0.75 * r[[t + \"__conf\" for t in TARGETS]].values\n    keep = W.sum(1) > 0\n    log(f\"supervised studies: {keep.sum()} of {len(st_tr)} (gold {len(gold)})\")\n\n    # ---- grouped OOF ------------------------------------------------------ #\n    # Group on report text: 177 studies share a byte-identical report, and the derived\n    # target vector for those is literally the same object. Splitting a duplicate group\n    # scores the model on a target whose source it has already seen.\n    import hashlib\n    rep = train_df.set_index(\"StudyInstanceUID\")[\"Report\"].fillna(\"\")\n    n_fold = int(min(5, max(2, keep.sum() // 4)))\n    grp = np.array([int(hashlib.md5(rep.get(s, s).encode()).hexdigest()[:8], 16) % n_fold\n                    for s in st_tr])\n\n    from sklearn.metrics import roc_auc_score\n    yb = (Y > 0.5).astype(int)\n    gi = np.array([i for i, s in enumerate(st_tr) if s in gold.index])\n    gold_y = gold.loc[[st_tr[i] for i in gi]].values.astype(int) if len(gi) else None\n\n    def score(oof):\n        d = [roc_auc_score(yb[keep, j], oof[keep, j]) if len(set(yb[keep, j])) > 1\n             else np.nan for j in range(len(TARGETS))]\n        g = [roc_auc_score(gold_y[:, j], oof[gi, j]) if gold_y is not None\n             and len(set(gold_y[:, j])) > 1 else np.nan for j in range(len(TARGETS))]\n        return np.nanmean(d), np.nanmean(g), d\n\n    results, oofs, test_preds = {}, {}, {}\n    for c in CONFIGS:\n        Xtr, Mtr = to_tokens(*store_tr[c[\"name\"]])\n        Xte, Mte = to_tokens(*store_te[c[\"name\"]])\n        oof = np.zeros_like(Y)\n        for f in range(n_fold):\n            tr_i = np.where(keep & (grp != f))[0]\n            va_i = np.where(grp == f)[0]\n            if len(tr_i) < 8 or len(va_i) == 0:\n                continue\n            _, pv = train_head(Xtr[tr_i], Mtr[tr_i], Y[tr_i], W[tr_i],\n                               Xtr[va_i], Mtr[va_i], seed=f)\n            oof[va_i] = pv\n        md, mg, per = score(oof)\n        results[c[\"name\"]] = (md, mg, per)\n        oofs[c[\"name\"]] = oof\n        log(f\"CONFIG {c['name']:8s}  derived {md:.4f}   gold58 {mg:.4f}\")\n\n        tr_i = np.where(keep)[0]\n        pr = []\n        for s in range(3):\n            _, pt = train_head(Xtr[tr_i], Mtr[tr_i], Y[tr_i], W[tr_i], Xte, Mte,\n                               seed=100 + s)\n            # rank-average across seeds and configs: AUC reads order only, so ranks are\n            # the right space to combine in and they make the configs commensurable.\n            pr.append(pd.DataFrame(pt).rank(pct=True).values)\n        test_preds[c[\"name\"]] = np.mean(pr, axis=0)\n        gc.collect()\n\n    log(\"---- per-target OOF (vs report-derived) ----\")\n    hdr = \"  \" + \"target\".ljust(18) + \"\".join(c[\"name\"].rjust(9) for c in CONFIGS)\n    log(hdr)\n    for j, t in enumerate(TARGETS):\n        log(\"  \" + t.ljust(18) + \"\".join(f\"{results[c['name']][2][j]:9.4f}\" for c in CONFIGS))\n    log(\"  \" + \"MACRO\".ljust(18) + \"\".join(f\"{results[c['name']][0]:9.4f}\" for c in CONFIGS))\n    log(\"  \" + \"GOLD58\".ljust(18) + \"\".join(f\"{results[c['name']][1]:9.4f}\" for c in CONFIGS))\n\n    ens_oof = np.mean([pd.DataFrame(oofs[c[\"name\"]]).rank(pct=True).values\n                       for c in CONFIGS], axis=0)\n    ed, eg, _ = score(ens_oof)\n    log(f\"ENSEMBLE(rank-mean of {len(CONFIGS)})  derived {ed:.4f}   gold58 {eg:.4f}\")\n\n    # Selection has to read both references, not just the larger one. They measure\n    # different things - agreement with what the reports say, and agreement with a\n    # reading of the images - and a candidate that wins one while losing the other has\n    # not been shown to be better. So: rank candidates by the worse of their two scores,\n    # which refuses to trade a real loss on one reference for a gain on the other, and\n    # only take the ensemble when it is the winner under that rule. Ensembling is a\n    # habit, not a law; an ensemble containing a weak member inherits its weakness.\n    def worst_of(md, mg):\n        return md if not np.isfinite(mg) else min(md, mg)\n\n    cands = {c[\"name\"]: (results[c[\"name\"]][0], results[c[\"name\"]][1]) for c in CONFIGS}\n    cands[\"ENSEMBLE\"] = (ed, eg)\n    pick = max(cands, key=lambda k: worst_of(*cands[k]))\n    P = (np.mean([test_preds[c[\"name\"]] for c in CONFIGS], axis=0)\n         if pick == \"ENSEMBLE\" else test_preds[pick])\n    log(f\"submitting {pick}: derived {cands[pick][0]:.4f}, gold {cands[pick][1]:.4f} \"\n        f\"(ranked on the worse of the two)\")\n\n    sub = pd.DataFrame(P, columns=TARGETS)\n    sub.insert(0, \"StudyInstanceUID\", st_te)\n    sub = test_df[[\"StudyInstanceUID\"]].merge(sub, on=\"StudyInstanceUID\", how=\"left\")\n    sub[TARGETS] = sub[TARGETS].fillna(0.5)\n    sub.to_csv(\"submission.csv\", index=False)\n    log(f\"submission.csv {sub.shape}; nulls {int(sub[TARGETS].isna().sum().sum())}\")\n    print(sub.head().to_string())\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.833562Z","iopub.execute_input":"2026-08-10T17:35:10.833934Z","iopub.status.idle":"2026-08-10T17:35:10.86011Z","shell.execute_reply.started":"2026-08-10T17:35:10.833898Z","shell.execute_reply":"2026-08-10T17:35:10.859444Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TOKEN_MODE = \"groups\"     # \"groups\" or \"mean\"\n\ndef to_tokens(feats, mask, mode=TOKEN_MODE):\n    N, S, G, D = feats.shape\n    if mode == \"mean\":                                   # reproduces the old behaviour\n        w = mask[..., None]\n        f = (feats.astype(np.float32) * w).sum(2) / np.maximum(w.sum(2), 1e-6)\n        return f, (mask.max(2) > 0).astype(np.float32)\n    return feats.reshape(N, S * G, D).astype(np.float32), mask.reshape(N, S * G)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:35:10.861136Z","iopub.execute_input":"2026-08-10T17:35:10.861461Z","iopub.status.idle":"2026-08-10T17:35:10.876888Z","shell.execute_reply.started":"2026-08-10T17:35:10.861427Z","shell.execute_reply":"2026-08-10T17:35:10.876134Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # ==========================================================\n# # SMOKE TEST - geometric slice ordering, 20 studies\n# # ==========================================================\n# import random\n# from scipy.stats import spearmanr\n\n# _both = pd.concat([pd.read_csv(ROOT / \"train_series.csv\"),\n#                    pd.read_csv(ROOT / \"test_series.csv\")])\n# plane_map = dict(zip(_both[\"SeriesInstanceUID\"], _both[\"Anatomical_Plane\"]))\n\n# t0 = time.time()\n# htr   = annotate(walk(\"train_series\"))\n# slots = pick_slots(htr, plane_map)\n# print(f\"header pass + slot pick: {time.time()-t0:.0f}s, {len(slots)} studies\")\n\n# sample = random.Random(0).sample(sorted(slots), 20)\n# jobs   = [(st, name, rec) for st in sample for name, rec in slots[st].items()]\n# n_hdr  = sum(len(r[\"files\"]) for _, _, r in jobs)\n# print(f\"{len(jobs)} slot-series, {n_hdr} slice headers\\n\")\n\n\n# def _probe(d, f):\n#     \"\"\"Recompute the through-plane coordinate and InstanceNumber for one file.\"\"\"\n#     k = inum = None\n#     try:\n#         ds   = pydicom.dcmread(os.path.join(d, f), force=True,\n#                                stop_before_pixels=True, specific_tags=ORDER_TAGS)\n#         iop  = np.asarray(ds.ImageOrientationPatient, dtype=float)\n#         ipp  = np.asarray(ds.ImagePositionPatient, dtype=float)\n#         k    = float(np.dot(ipp, np.cross(iop[:3], iop[3:])))\n#         inum = float(ds.InstanceNumber)\n#     except Exception:\n#         pass\n#     return k, inum\n\n\n# t1, n_good, rows = time.time(), 0, []\n# for st, name, rec in jobs:\n#     files, good = order_slices(rec)\n#     n_good += int(good)\n\n#     if not good:\n#         ds = pydicom.dcmread(os.path.join(rec[\"dir\"], rec[\"files\"][0]), force=True,\n#                              stop_before_pixels=True, specific_tags=ORDER_TAGS)\n#         miss = [t for t in (\"ImagePositionPatient\", \"ImageOrientationPatient\",\n#                             \"InstanceNumber\") if getattr(ds, t, None) is None]\n#         print(f\"  NO GEOMETRY  {name:16s} n={len(rec['files']):3d}  missing={miss}\")\n#         rows.append((name, len(rec[\"files\"]), np.nan, np.nan, np.nan, False))\n#         continue\n\n#     ks, ins = zip(*[_probe(rec[\"dir\"], f) for f in files])\n#     ks = np.asarray(ks, float)\n#     dk = np.diff(ks)\n\n#     old      = {f: i for i, f in enumerate(rec[\"files\"])}\n#     rho_file = spearmanr(range(len(files)), [old[f] for f in files]).correlation\n#     jitter   = float(np.std(dk) / max(abs(np.mean(dk)), 1e-9)) if len(dk) else np.nan\n#     rho_inum = (abs(spearmanr(ks, np.asarray(ins, float)).correlation)\n#                 if all(v is not None for v in ins) else np.nan)\n#     rows.append((name, len(files), rho_file, jitter, rho_inum, True))\n\n# dt  = time.time() - t1\n# rep = pd.DataFrame(rows, columns=[\"slot\", \"n\", \"rho_vs_filename\",\n#                                   \"spacing_jitter\", \"abs_rho_vs_InstNum\", \"geom\"])\n# print(\"\\n\" + rep.to_string(index=False))\n\n# rate = n_hdr / max(dt, 1e-9)\n# print(f\"\\nordered {n_good}/{len(jobs)} by geometry ({len(jobs)-n_good} arbitrary) in {dt:.1f}s\")\n# print(f\"{rate:.0f} headers/s  ->  23089 slot-series (~693k headers) \"\n#       f\"= {693000/rate/60:.0f} min for the full train pass\")\n# print(f\"median |rho vs filename|   {rep.rho_vs_filename.abs().median():.3f}   want ~0.0\")\n# print(f\"median spacing jitter      {rep.spacing_jitter.median():.3f}   want < 0.05\")\n# print(f\"median |rho vs InstNum|    {rep.abs_rho_vs_InstNum.median():.3f}   want ~1.0\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:40:56.64182Z","iopub.execute_input":"2026-08-10T17:40:56.642581Z","iopub.status.idle":"2026-08-10T17:42:45.566603Z","shell.execute_reply.started":"2026-08-10T17:40:56.642552Z","shell.execute_reply":"2026-08-10T17:42:45.565936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for st in sample:\n#     seen = {}\n#     for name, rec in slots[st].items():\n#         seen.setdefault(rec[\"SeriesInstanceUID\"], []).append(name)\n#     dup = {k: v for k, v in seen.items() if len(v) > 1}\n#     if dup:\n#         print(st, dup)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-10T17:49:29.038425Z","iopub.execute_input":"2026-08-10T17:49:29.039191Z","iopub.status.idle":"2026-08-10T17:49:29.044959Z","shell.execute_reply.started":"2026-08-10T17:49:29.039162Z","shell.execute_reply":"2026-08-10T17:49:29.044Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"try:\n    main()\nexcept Exception:\n    traceback.print_exc()\n    # A submission that fails to write scores nothing at all, so fall back to the\n    # benchmark file rather than dying.\n    t = pd.read_csv(find_root() / \"test.csv\")\n    for c in TARGETS:\n        t[c] = 0.5\n    t.to_csv(\"submission.csv\", index=False)\n    print(\"wrote fallback submission.csv\")\nlog(\"done\")\n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2026-08-07T04:33:21.543768Z","iopub.execute_input":"2026-08-07T04:33:21.544043Z","iopub.status.idle":"2026-08-07T04:40:47.092766Z","shell.execute_reply.started":"2026-08-07T04:33:21.544014Z","shell.execute_reply":"2026-08-07T04:40:47.091736Z"}},"outputs":[],"execution_count":null}]}