OpenIslet

scripts/render_documentation.py

Render current scientific facts from artifacts while retaining design rationale.

script Release v0.8.0 gen-eb955f8266035aba 63 KB · 4 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/render_documentation.py · SHA-256: f458f2ce4138aab1…

                # The enclosing list/quote ended, even without a fence closer.
                closed=True;break
            i+=1
            if closing.fullmatch(inner):closed=True;break
        key=literal_key(len(fences))
        fences.append((key,''.join(lines[start:i]).rstrip('\n')))
        if not closed:unclosed_key=key
        held.append(key+'\n')
    text=''.join(held)
    _validate_markers(text,START,END)
    _validate_markers(text,'<!-- OPENISLET_CURRENT_LAYER_SCOPE -->','<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->')
    n=narratives(facts)
    text=re.sub(re.escape(START)+r'.*?'+re.escape(END)+r'\n*','',text,flags=re.S)
    text=re.sub(r'<!-- OPENISLET_CURRENT_LAYER_SCOPE -->.*?<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->\s*','',text,flags=re.S)
    text,protected_links=_protect_link_destinations(text,literal_prefix)
    replacements={
      'WAVE-0 PUBLICATION & RANKING FREEZE (Active':'WAVE-0 PRIOR-ANCHORED PUBLICATION (outward_rankings_frozen: false; physical assay gates pending',
      'while guaranteeing Hour-0 density':'with a preregistered Stage-0 acceptance target for Hour-0 density',
      'GSG-tPT2A':'GSG-P2A',
      '2A-free design preventing':'proposed 2A-free topology (exact donor and benefit unresolved), intended to reduce',
      '100% native Phe19 N-terminus':'predicted native Phe19 N-terminus; processing requires direct qualification',
      'including `Ile22`':'including the unresolved HLA-E Gly1 between the 20-aa (G4S)4 linker and HLA-E Ser2 N',
      '§ 356k(e)` governs review actions on the designation request':'§ 356k(e)` concerns actions to expedite development and review of an application using a designated platform; requests and determinations are governed by § 356k(c)-(d)',
      'Pan-Allelic `SIRPα` Proof':'Reference SIRPA V1/V2 sequence and geometry comparison; pan-allelic protection unverified',
      'Pan-Allelic SIRPa Proof':'Reference SIRPA V1/V2 sequence and geometry comparison; pan-allelic protection unverified',
      '1` `Asp101` insertion in `V2`':'1` `Asp101` insertion in `V1` (4CMM), relative to V2 (2JJS)',
      '[14, 20, 22, 24, 27, 45, 65, 66, 70, 77, 79, 100]':'[14, 20, 22, 24, 27, 45, 65, 66, 70, 77, 79, 101] (2JJS/V2 numbering)',
      'not CpG-free':'CpG-containing', 'CpG-free':'CpG-containing candidate; anti-silencing pending',
      'To guarantee zero false negatives':'To benchmark retrieval rather than guarantee zero false negatives',
      'live NCBI `dbSNP`/`ClinVar`/`gnomAD v4.1` polymorphism audit':'source-verified dbSNP/ClinVar interval identities plus explicitly assumed rare-variant screening priors; gnomAD row-level frequency validation pending',
      'v113 / GENCODE v46':'112 / GENCODE v46',
      'canonical Ensembl v113':'pinned Ensembl/GENCODE (current versions in documentation_facts_v0.8.0.json)',
      'source-adjudicated':'source-bound heuristic', 'Source-adjudicated':'Source-bound heuristic',
      'MVDGTLLLL':'MSRSVALAVLALLSLSGLEA (20 aa encoded B2M signal; processing qualification pending)',
    }
    for old,new in replacements.items(): text=text.replace(old,new)
    # Never consume code-span delimiters while replacing an alias. Earlier
    # permissive backtick matching left valid inline code with an open span.
    text=re.sub(r'(?:minimal[ *]+)?455[ *]*bp[ *]*(?:minimal[ *]+|core[ *]+)?(?:[\[(]or[^\])]+[\])][ *]*)?CBX3-A2UCOE(?:\s+core)?',CANDIDATE+' (legacy CBX3-A2UCOE alias; anti-silencing function pending)',text)
    text=text.replace('AAVS1-[455bp CBX3-A2UCOE]','AAVS1-[HNRNPA2B1-proximal 455bp candidate; legacy CBX3-A2UCOE]')
    text=text.replace('mPGK \\| EEF1A1-core -> HLA-E','EEF1A1-core \\| Syn_5xISRE_minP -> HLA-E')
    text=text.replace('mPGK | EEF1A1-core -> HLA-E','EEF1A1-core | Syn_5xISRE_minP -> HLA-E')
    output=[]
    ranking_columns=None
    source_lines=text.splitlines()
    table_width=None
    for row_index,line in enumerate(source_lines):
        original=line
        if line.startswith('|'):
            next_line=source_lines[row_index+1] if row_index+1 < len(source_lines) else ''
            if next_line.startswith('|') and re.fullmatch(r'[| :\-\t]+',next_line):
                header_cells=_table_cells(line)
                ranking_columns=_ranking_header(header_cells)
                table_width=len(header_cells)
        else: ranking_columns=None;table_width=None
        # Current count assertions must follow regenerated records, including
        # review reclassification; do not freeze values from a prior audit.
        for label, key in [('total arms', 'arms'), ('arms', 'arms'), ('atomic effects', 'atomic_effects'), ('atomic quantitative & qualitative effects', 'atomic_effects')]:
            if label == 'arms' and any(tok in line for tok in ('Mode-B', 'islet1_locus1_s10_modeb_comparators', 'ASTAR_4143', 'ARM1B_3974')):
                continue
            line=re.sub(r'`[\d,]+`(?= '+label+r'\b)', '`'+f"{facts['corpus'][key]:,}"+'`', line)
        line=re.sub(r'`[\d,]+ / [\d,]+ = 100\.0%`(?= exact)', '`'+f"{facts['corpus']['atomic_effects']:,} / {facts['corpus']['atomic_effects']:,} = 100.0%"+'`', line)
        if 'single-field substring match' in line and 'effects' in line:
            line=re.sub(r'`[\d,]+ / [\d,]+`', '`'+f"{facts['corpus']['atomic_effects']:,} / {facts['corpus']['atomic_effects']:,}"+'`', line)
        strict_empirical=facts['corpus'].get('ring1_corpus_count_reconciliation',{}).get('strict_active_peer_reviewed_empirical_studies_total')
        if strict_empirical is not None:
            line=re.sub(r'`[\d,]+`(?= strict peer-reviewed empirical)', '`'+str(strict_empirical)+'`', line)
        if ('PD-L1' in line or 'Phe19' in line) and '100%' in line and ('cleav' in line or 'N-termin' in line):
            line=line.replace('100%', 'predicted (direct processing qualification pending)')
        if ('HNRNPA2B1' in line or '455' in line or 'AAVS1' in line) and ('iCasp9' in line or 'suicide switch' in line):
            line=line.replace('and tested with', 'and proposed for testing with').replace('insulated by', 'proposed insulation using')
        # Refresh generated labels too: idempotence must not freeze a prior
        # artifact snapshot when the scientific source objects change.
        if line.startswith('- **Validated Ring-1 records:**'):
            line='- **Validated Ring-1 records:** '+n['corpus']+' Private dossier caches are excluded from public redistribution.'
        elif line.lstrip().startswith('- Current corpus:'):
            line=re.match(r'^\s*',line).group(0)+'- '+n['corpus']
        elif line.lstrip().startswith('- **Heuristic extraction labels:**'):
            line='  - **Heuristic extraction labels:** '+n['corpus']
        elif line.startswith('> 1. **Prior-anchored scenario outputs:**'):
            line='> 1. **Prior-anchored scenario outputs:** '+n['layer1']
        elif line.startswith('> **Estimand & prior sensitivity:**'):
            line='> **Estimand & prior sensitivity:** '+n['layer1']
        elif line.startswith('  - Layer 4 is a conditional model'):
            line='  - '+n['layer4']+' Shrinking-core sensitivity: '+n['shrinking_core']+'. Current chemistry extrema are listed in the atlas.'
        elif line.startswith('  - Low-glucose challenge reference-ODE minima:'):
            line='  - '+n['challenge']+' Reference fixed-functional-beta-IEQ ODE curves have pde_coupling_applied=false and cannot inherit a PDE-derived full-product verdict; matched PDE/ODE states are identified separately. Reference ODE outputs: '+n['reference_ode']+'.'
        elif line.startswith('  - Layer 5 is an illustrative assigned-rule population simulator'):
            line='  - '+n['layer5']
        # Replace entire stale assertions, preserving the surrounding document's structure.
        if ('**Layer 1' in line or '1. **Layer 1' in line) and len(line)>400: line='1. **Layer 1:** '+n['corpus']+' '+n['layer1']
        elif ('**Layer 2' in line or '2. **Layer 2' in line) and len(line)>500: line='2. **Layer 2:** '+n['layer2']+' '+CHS4+'. '+P2A+'. '+DELIVERY
        elif ('**Layer 3' in line or '3. **Layer 3' in line) and len(line)>500: line='3. **Layer 3:** '+n['layer3']
        elif ('**Layer 4' in line or '4. **Layer 4' in line) and len(line)>500: line='4. **Layer 4:** '+n['layer4']
        elif ('**Layer 5' in line or '5. **Layer 5' in line) and len(line)>500: line='5. **Layer 5:** '+n['layer5']
        elif '**Estimand & Prior-Dominance Note:**' in line or ('99.' in line and ('variance decomposition' in line or 'structural prior variance' in line)): line='> **Estimand & prior sensitivity:** '+n['layer1']
        elif line.startswith('> 1. **Prior-Anchored Scenario Outputs'): line='> 1. **Prior-anchored scenario outputs:** '+n['layer1']
        elif '**Structural Compatibility Screen for `GY-008`' in line: line='  - '+STRUCTURE1
        elif '**Structural Compatibility Screen for `GY-003`' in line: line='  - '+STRUCTURE2
        elif line.startswith('  - Across the 336-hour'): line='  - '+n['layer4']+' Shrinking-core sensitivity: '+n['shrinking_core']+'. Current chemistry extrema are listed in the atlas.'
        elif line.startswith('  - Executes `compile_personalized_patient_blueprint`'): line='  - '+n['layer5']
        elif ('3,118' in line or '3118' in line) and ('3,092' in line or '26` rows are primary' in line or 'unresolved-origin' in line or 'quarantined in the private cache' in line): line='  - The 3,118-row AVI table is quarantined in the private cache: end-to-end batch generation provenance for the full 3,118-row table is incomplete (as a whole it is not a certified model scan), a limited 28 Oct 2026 live re-run against alphagenome v0.10.0 verified 59/59 sampled rows (9 candidate edits plus 50 random rows), AlphaGenome non-commercial output terms conflict with CC-BY-4.0 public redistribution, and zero AlphaGenome outputs are shipped publicly or used as active ranking weights or insertion-safety certifications. Ensembl release 112 / GENCODE v46 selected transcript identities and coordinates are read from the pinned raw models.'
        elif ('1,000' in line or '1000' in line) and ('credible' in line or 'GRN' in line) and len(line)>200 and not line.startswith('- **Stage 0→7 prior-scenario plane:**'): line='  - '+n['layer2']
        if 'EEF1A1' in line and re.search(r'`?20`?\s+(?:native\s+)?CpG',line):
            count=facts['layer1'].get('audit_ledger',{}).get('native_eef1a1_promoter',{}).get('cpg_dinucleotides')
            line=re.sub(r'`?20`?\s+(native\s+)?CpG(?:\s+dinucleotides|s)?',lambda m: f"`{count}` {m.group(1) or ''}CpG dinucleotides",line)
        if ('`44` adjudicated' in line and 'independently' not in line) or ('false positives' in line and ('`0` false positives' in line or '0` false positives' in line or '39` strict true' in line)) or ('44/44' in line and 'penalt' in line):
            if line.startswith('|') and not line.startswith('| **Stage 0**'):
                cells=_table_cells(line)
                if len(cells)>=5:
                    cells[2]=_refine_table_cell(cells[2],'HEURISTIC_COUNT',str(facts['corpus']['heuristic_penalty_effects'])+' heuristic penalty flags; independent accuracy unmeasured')
                    cells[3]=_refine_table_cell(cells[3],'HEURISTIC_SCOPE','Rule-based null/clause/subject negative controls are regression checks, not an independently adjudicated sensitivity or false-positive estimate.')
                    line='|'.join(cells)
            else: line='  - **Heuristic extraction labels:** '+n['corpus']
        if line.startswith(('- **Stage 0→7 Perturbation Trajectory Plane:**','- **Stage 0→7 prior-scenario plane:**')):
            line='- **Stage 0→7 prior-scenario plane:** '+n['layer2']
        if '3,092' in line and ('effects' in line or 'Atomic Effects' in line): line=line.replace('3,092',f"{facts['corpus']['atomic_effects']:,}")
        if '561` active' in line: line=line.replace('561` active',str(facts['corpus'].get('active_deduplicated_studies_count'))+'` active')
        if '233/233' in line: line=line.replace('233/233',str(facts['corpus']['raw_edit_entries'])+'/'+str(facts['corpus']['raw_edit_entries']))
        if '312` gene tokens' in line: line=line.replace('312` gene tokens',str(facts['corpus'].get('expanded_gene_occurrences'))+'` expanded gene occurrences')
        if line.startswith('| **Prior-Constant & Auxiliary'):
            cells=_table_cells(line);cells[2]=_refine_table_cell(cells[2],'PRIOR_VALUES',n['layer1']);cells[3]=_refine_table_cell(cells[3],'PRIOR_SCOPE','All active registry ranges and source/omics channels are replayed; independent source validity remains a separate question.');line='|'.join(cells)
        if '7` functional LRR pairs' in line: line=line.replace('7` functional LRR pairs',str(facts['corpus'].get('source_bound_functional_intervention_lrr_pairs_count', 4))+'` functional intervention LRR pairs ('+str(facts['corpus']['total_numeric_lrr_effects'])+'` total typed numeric LRR effects)')
        if line.startswith('  - Holding peripheral systemic insulin-action'):
            line='  - '+n['challenge']+' Reference fixed-functional-beta-IEQ ODE curves have pde_coupling_applied=false and cannot inherit a PDE-derived full-product verdict; matched PDE/ODE states are identified separately. Reference ODE outputs: '+n['reference_ode']+'.'
        if 'RNLS' in line and ('poor dynamic GSIS' in line or 'Fig. 6' in line or 'GSIS/OCR tradeoff' in line):
            if line.startswith('| **`GRAVEYARD_004`'):
                cells=_table_cells(line)
                cells[-2]=_refine_table_cell(cells[-2],'RNLS_SCOPE',RNLS)
                line='|'.join(cells)
            elif line.startswith('|'):
                cells=_table_cells(line)
                cells=[(' '+RNLS+' ') if ('poor dynamic GSIS' in cell or ('MacDonald' in cell and '39988068' in cell)) else cell for cell in cells]
                line='|'.join(cells)
            else:
                prefix='> 3. ' if line.startswith('> 3.') else re.match(r'^\s*',line).group(0)+'- '
                line=prefix+'**RNLS precaution:** '+RNLS
        if 'Worm-Like Chain (`WLC`)' in line:
            line=re.sub(r'`HLA-E\*01:03 Gly107` sits.*$', 'The 3CDG reference crystal Arg107 C-alpha is 17.02 A from the receptor; nearest-heavy-atom clearance is 14.82 A. Engineered Gly107 geometry is unmeasured; stability and surface-density values are working priors.',line)
        if line.startswith(('- **Multi-Repository Discovery Manifest','- **PubMed Discovery Manifest')):
            discovery=facts['discovery_manifest']
            line=f"- **PubMed Discovery Manifest (`data/raw/corpus_manifest_all_sources.jsonl`):** {discovery['jsonl_rows']:,} JSONL rows / {discovery['unique_pubmed_pmids']:,} unique PubMed PMIDs, with {discovery['inline_abstract_strings']} inline abstract strings. Separate preprint, patent, GEO and ClinicalTrials.gov inventories are retained in their own raw files and are not additive components of this PMID manifest."
        if line.startswith('| **Raw Corpus Manifest'):
            discovery=facts['discovery_manifest'];cells=_table_cells(line)
            cells[2]=_refine_table_cell(cells[2],'DISCOVERY_COUNT',f"{discovery['jsonl_rows']:,} JSONL rows / {discovery['unique_pubmed_pmids']:,} unique PubMed PMIDs")
            cells[3]=_refine_table_cell(cells[3],'DISCOVERY_SCOPE','PubMed records only; separate preprint/patent/GEO/trial files are independent inventories, not additional rows in this manifest.')
            line='|'.join(cells)
        if line.startswith('All extraction, graph-construction, and combinatorial scenario pipelines'):
            line=f"All extraction, graph-construction and scenario pipelines are hash-pinned in [`manifest.json`](manifest.json) (`{facts['manifest_pin_count']:,}` pinned files). Private research dossiers remain excluded from public bundles; the rights-aware exporter applies the <=240-character / <25%-abstract policy and preserves source/license qualification. Counts by scientific scope are generated above rather than inferred by adding separate inventories."
        if line.startswith('| **Stage 0**'):
            cells=_table_cells(line)
            if len(cells)>=5:
                cells[3]=_refine_table_cell(cells[3],'STAGE0',n['corpus']+' Stage-0 construct, density, differentiation and immune/GSIS acceptance experiments remain preregistered pending.')
                line='|'.join(cells)
        if line.lstrip().startswith('- **`594` experimental') or ('genetic edit entries' in line and '233' in line):
            line='  - '+n['corpus']
        if ('3,092' in line or '3092' in line) and 'atomic' in line and 'effect' in line:
            line='  - Current extracted effects: '+str(facts['corpus']['atomic_effects'])+'; source identifier, digest, typed numeric role and direct character slice are verified together. Inequality P values retain relation/bound with exact p_value=null.'
        if 'schema-validated primary study records' in line:
            line='- **Validated Ring-1 records:** '+n['corpus']+' Private dossier caches are excluded from public redistribution.'
        if '217-bp' in line and 'U78775.1' in line and not line.startswith('Current cHS4'):
            if 'LOCUS4_' in line:
                loc4=next((c for c in facts['layer2']['constructs'] if c['construct_id'].startswith('LOCUS4')), {})
                line='  4. **Locus 4:** '+str(loc4.get('total_length_bp'))+' bp donor / '+str(loc4.get('packaged_aav6_genome_with_2x145bp_itrs_bp'))+' bp including ITRs; '+CHS4+'; '+CANDIDATE+'; 230-bp native EEF1A1 core, iCasp9 and polyA. Exact sequence and source intervals are in the construct ledger.'
            else:
                line='  - **Current cHS4 source:** '+CHS4+'. The earlier 217-bp U78775.1 match is historical.'
        if line.startswith('  - **Pass 1') or line.startswith('  - **Pass 2'):
            line=line.split(' All specificity figures')[0]
            line += ' All specificity figures on this line are assigned illustrative three-mismatch panel scores, not an exhaustive genome/exome scan or HiFi-SpCas9 empirical specificity estimate; genome-wide enumeration is NOT_ENUMERATED.'
        if filename=='README.md' and line.lstrip().startswith('- **Locus 1:**'):