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…

"""Render current scientific facts from artifacts while retaining design rationale.

No numeric value in this module is a surrogate assay result. Historical details
remain in their source documents; the generated block identifies current scope.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import math
import os
import stat

START = '<!-- OPENISLET_GENERATED_FACTS_START -->'
END = '<!-- OPENISLET_GENERATED_FACTS_END -->'
RENDER_EXEMPT_DOCS = frozenset({
    'README.md',
    'PROJECT-DECISIONS-LOG.md',
    'OPENISLET-2026-2030-MASTER-TIMELINE.md',
    'SERPINB9-REDOX-AND-SWITCH-QUALIFICATION-NOTE.md',
    'CD47-DENSITY-CEILING-AND-HYPOXIC-TSP1-QUALIFICATION-NOTE.md',
    'TNFA-IFNG-INTRINSIC-APOPTOSIS-QUALIFICATION-NOTE.md',
    'PREDIFF-HYPOXIA-PRIMING-QUALIFICATION-NOTE.md',
    'GATE-34-V090-HYGIENE-SAFECELL-MINIFH-ORTHOGONALITY-PROTOCOL.md',
    'GATE-35-ROUTE4-OMENTUM-AND-EXVIVO-REST-PROTOCOL.md',
    'GATE-36-FOUNDRY-V2-SHIELD-INVVAX-INSL82I-CUFFV2-PROTOCOL.md',
    'GATE-37-ARMZ-ENSC-ISLETSORT-V2-AND-2P24-PORTFOLIO-PROTOCOL.md',
    'GATE-38-FIVE-TRANSGENE-JOINT-COVERAGE-AND-DEPENDENCE-PROTOCOL.md',
    'GATE-39-CUFF-HUMORAL-STRATUM-COVERAGE-AND-OMISSION-PROTOCOL.md',
    'GATE-40-PIRFENIDONE-LOCAL-ANTIFBR-H4-PROTOCOL.md',
    'GATE-41-DEUCRAVACITINIB-LOCAL-TYK2-IBMIR-NK-PROTOCOL.md',
    'GATE-42-GY032-CHANNEL-C-BYSTANDER-SCREEN-PROTOCOL.md',
    'GATE-43-CELLGEMMA-WARN-GUARDRAILS-AND-PILOTS-PROTOCOL.md',
    'IIP_DRAFT_A_PIRFENIDONE_LOCAL_ANTIFBR_IEC_H4.md',
    'IIP_DRAFT_B_DEUCRAVACITINIB_LOCAL_TYK2_IBMIR_NK.md',
    'IIP_DRAFT_C_BBC3_PMAIP1_JAK2_H3_CHANNEL_C_BYSTANDER.md',
    'IIP_DRAFT_D_CELLGEMMA_BLUEPRINT_GUARDRAILS_AND_HIPCORE_AUDIT.md',
})
CANDIDATE = 'HNRNPA2B1-proximal 455-bp CpG-core candidate (GRCh38 chr7:26200580-26201034)'
RNLS = ('MacDonald 2025 (PMID:39988068 Fig. 6) reports poor dynamic GSIS in both WT and RNLS-KO iPSC-beta aggregates. '
        'Higher basal OCR in KO motivates a precautionary metabolic penalty, not a demonstrated knockout-specific GSIS decrement; '
        'the exact-product dynamic-perifusion comparison is pending.')
DELIVERY = ('Shy 2023 (PMID:36008610) supports a nonviral ssDNA/dsDNA editing strategy in its tested cell context. '
            'Exact 4,880-bp hPSC donor delivery, ceDNA and mammalian bridge-recombinase transfer are experimental delivery options requiring Stage-0 qualification.')
STATUTE = ('Section 356k(e) concerns actions to expedite development and review of an application using a designated platform; '
           'designation requests and determinations are governed by sections 356k(c)-(d). Section 356k(f) concerns leveraging data, '
           'subject to the same-sponsor or granted right-of-reference conditions. This is a citation correction, not a finding of product eligibility or approval. '
           '[Official statute](https://www.govinfo.gov/link/uscode/21/356k).')
CHS4 = ('engineered 250-bp cHS4-derived variant: 235-bp exact contiguous match at insert 3..237 to U78775.2 positions 10..244, '
        'with 2 bp before and 13 bp after that block; the alignment ledger discloses adjacent native T245 omission and native/adapted tail classification. '
        'Those 15 outside-block bases are not all established synthetic adapters; insulation requires bench qualification')
P2A = 'single 22-aa GSG-P2A element (21-aa upstream stub plus downstream Pro; legacy tPT2A alias)'
STRUCTURE1 = ('Reference-geometry compatibility screen: 3CDG is a CD94/NKG2A complex. P8-Phe8 contributes 24 heavy-atom contacts to shared CD94 and 0 to NKG2A in copy 1, and 21/0 in copy 2. '
              'Removing Phe ring atoms is an atom-truncation diagnostic, not a relaxed Val8 model. This structure cannot discriminate NKG2A from NKG2C. '
              'Receptor-specific K_D values are working soluble-ectodomain reference priors; direct SPR and HCMV+ NKG2C+ NK-donor assays remain preregistered.')
STRUCTURE2 = ('Reference SIRPA V1/V2 sequence and geometry comparison; pan-allelic protection is unverified. '
              'Asp101 is inserted in SIRPA V1 (4CMM) relative to V2 (2JJS). Soluble crystal CD47 carries C33G/Cys15-to-Gly; engineered CD47 retains WT Cys15. '
              'Reference soluble-C15G structures place CD47 Val115 about 30.93 A from the nearest SIRPA atom. '
              'This coarse anchor-distance screen does not model membrane orientation, the engineered WT-Cys15/GPI stalk or V8; binding, membrane and phagocytosis assays remain pending.')


def _safe_location(path):
    for parent in [path.absolute(), *path.absolute().parents]:
        if parent.is_symlink():
            raise ValueError('Documentation paths and ancestors may not be symbolic links')


def _read_regular(path):
    _safe_location(path)
    info=path.lstat()
    if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
        raise ValueError('Documentation inputs must be single-link regular files')
    fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
    try:
        opened=os.fstat(fd)
        if (opened.st_dev,opened.st_ino)!=(info.st_dev,info.st_ino):
            raise ValueError('Documentation input changed identity while opening')
        with os.fdopen(fd,'rb',closefd=False) as stream:data=stream.read()
        after=os.fstat(fd)
        if (after.st_size,after.st_mtime_ns,after.st_ctime_ns)!=(len(data),opened.st_mtime_ns,opened.st_ctime_ns):
            raise ValueError('Documentation input changed while reading')
        return data
    finally:os.close(fd)


def read_json(root, relative, default=None):
    path = root / relative
    return json.loads(_read_regular(path)) if path.exists() else ({} if default is None else default)


def strip_trajectories(value):
    if isinstance(value, dict):
        return {k: strip_trajectories(v) for k,v in value.items() if not any(t in k for t in ('trajectory', 'hourly_grid', 'sampled_hourly'))}
    if isinstance(value, list): return [strip_trajectories(v) for v in value]
    return value


def derive_facts(root: Path, manifest_pin_count: int) -> dict:
    source_bytes={}
    def load(relative, default=None):
        key=Path(relative).as_posix();path=root/key
        if not path.exists():return {} if default is None else default
        if key not in source_bytes:source_bytes[key]=_read_regular(path)
        return json.loads(source_bytes[key])
    discovery_path=root/'data/raw/corpus_manifest_all_sources.jsonl'
    discovery_key=discovery_path.relative_to(root).as_posix()
    source_bytes[discovery_key]=_read_regular(discovery_path)
    discovery_rows=[json.loads(line) for line in source_bytes[discovery_key].decode('utf-8').splitlines() if line.strip()]
    discovery={'jsonl_rows':len(discovery_rows),'unique_pubmed_pmids':len({str(row['pmid']) for row in discovery_rows if row.get('pmid')}),'inline_abstract_strings':sum(bool(row.get('abstract')) for row in discovery_rows),'scope':'PubMed PMID records only; patent, preprint, GEO and trial inventories are separate source files, not additive components of this JSONL.'}
    paths = {'graph':'data/extracted/cross_study_discovery_graph.json',
             'rankings':'data/extracted/islet1_candidate_stack_rankings.json',
             'protocol':'data/protocols/hip_core_fractional_factorial_v0.6.2.json',
             'layer2':'data/extracted/layer2_regulatory_and_perturbation_atlas.json',
             'layer3':'data/extracted/layer3_structural_verification_atlas.json',
             'layer4':'data/extracted/layer4_tissue_and_metabolic_twin_atlas.json',
             'layer5':'data/extracted/layer5_personalized_patient_and_crispr_atlas.json'}
    data = {name:load(path) for name,path in paths.items()}
    studies=[load(p.relative_to(root)) for p in sorted((root/'data/extracted').glob('*.json')) if p.stem.isdigit()]
    selected_gencode_models=load('data/raw/layer2_genomic_and_jaspar_reference.json').get('gencode_v46_transcript_models_pinned',{})
    raw_edits=[edit for study in studies for arm in study.get('arms',[]) for edit in arm.get('gate2_3_4_genetic_and_epitope_edits',[])]
    ledger=data['rankings'].get('layer1_ultracode_audit_reconciliation_ledger',{})
    stage=data['layer2'].get('stage0_to_stage7_perturbation_plane',{})
    profiles=stage.get('perturbation_profiles',[])
    construct=data['layer2'].get('construct_sequence_and_grammar_verification',{})
    pde=data['layer4'].get('part_a_336h_spatial_reaction_diffusion_pouch_pde',{})
    regimes=pde.get('regimes_simulated',[])
    lead=next((r for r in regimes if r.get('regime_id')=='LEAD_CENTRAL_LAMINA_PDMS_CAO2_F045_PLUS_CATALASE'),{})
    ode=data['layer4'].get('part_b_24h_trihormonal_paracrine_and_whole_body_metabolic_ode',{})
    patient=data['layer5'].get('part_b_personalized_patient_compiler_and_10k_population_trial',{})
    return {'schema_version':'0.8.0','epistemic_status':'GENERATED_COMPUTATIONAL_FACTS_PHYSICAL_QUALIFICATION_PENDING',
            'manifest_pin_count':manifest_pin_count,'discovery_manifest':discovery,
            'source_sha256':{path:hashlib.sha256(data).hexdigest() for path,data in source_bytes.items()},
            'corpus':{'studies':len(studies),'arms':sum(len(s.get('arms',[])) for s in studies),
                      'reference_control_arms':sum(bool(a.get('is_reference_control')) for s in studies for a in s.get('arms',[])),
                      'atomic_effects':sum(len(s.get('atomic_effects',[])) for s in studies),
                      'raw_edit_entries':len(raw_edits),'total_numeric_lrr_effects':sum(isinstance(e.get('log_response_ratio_or_smd'),(int,float)) for st in studies for e in st.get('atomic_effects',[])),'expanded_gene_occurrences':ledger.get('source_counts',{}).get('expanded_edit_gene_occurrences'),
                      'heuristic_penalty_effects':sum(bool(e.get('secretome_or_differentiation_penalty_observed')) for s in studies for e in s.get('atomic_effects',[])),
                      **data['graph'].get('corpus_epistemic_and_fidelity_diagnostics',{})},
            'layer1':{'audit_ledger':ledger,'ranked_architectures':data['rankings'].get('ranked_candidate_architectures',[]),
                      'sensitivity':data['rankings'].get('direct_output_logit_sensitivity_and_variance_decomposition',{}),
                      'protocol':strip_trajectories(data['protocol'])},
            'layer2':{'summary':data['layer2'].get('summary',{}),'release_pairing':data['layer2'].get('ensembl_gencode_release_pairing'),
                      'constructs':construct.get('constructs',[]),'selected_gencode_models':selected_gencode_models,'regulatory_audits':construct.get('regulatory_element_audits',{}),
                      'profile_count':len(profiles),'profiles':profiles,'kinetics':stage.get('hour0_hlae_inducible_vs_constitutive_kinetics_note',{}),
                      'model_type':stage.get('model_type')},
            'layer3':{'summary':data['layer3'].get('summary',{}),'complexes':data['layer3'].get('complexes',[])},
            'layer4':{'summary':data['layer4'].get('summary',{}),'lead':strip_trajectories(lead),
                      'geometry':data['layer4'].get('part_a_exact_oxygen_boundary_value_and_volume_algebra',{}),
                      'shrinking_core':strip_trajectories(pde.get('shrinking_core_coupled_bvp_safety_comparison_ultracode_v80_09',{})),
                      'grid_convergence':strip_trajectories(pde.get('spatial_grid_convergence_51_101_201_401_preastra_a094',{})),
                      'joint_vascular_iip_0002':strip_trajectories(pde.get('joint_vascular_timing_and_exchange_sensitivity_iip_0002',{})),
                      'challenge':ode.get('low_glucose_challenge_below_4p2mM_oat1_verification_ultracode_v80_15',{}),
                      'reference_architectures':strip_trajectories(ode.get('graft_architectures_compared',[])),
                      'matched_pde_ode':strip_trajectories(ode.get('matched_pde_ode_qualification_scenarios',[]))},
            'layer5':{'summary':data['layer5'].get('summary',{}),'patient':strip_trajectories(patient)}}


def f(value, digits=2):
    if isinstance(value, bool) or (isinstance(value, (int, float)) and not math.isfinite(value)):
        raise ValueError('Rendered numeric facts must be finite numbers, never booleans')
    return 'unavailable' if value is None else f'{value:,.{digits}f}' if isinstance(value,(int,float)) else str(value)


def narratives(facts):
    c=facts['corpus']; l1=facts['layer1']; l2=facts['layer2']; l4=facts['layer4']; l5=facts['layer5']
    a=l1.get('audit_ledger',{}); registry=a.get('registry',{}); search=a.get('search',{})
    vd=l1['sensitivity'].get('uniform_grid_pooled_pediatric_gate_logit_variance_decomposition',{})
    structural_share=vd.get('structural_share_of_component_variance_sum')
    structural_percent=100*structural_share if type(structural_share) in (int,float) else structural_share
    profiles={p['genotype_id']:p for p in l2['profiles']}
    wt=profiles.get('WT_UNEDITED_CONTROL',{}); arm1a=profiles.get('SCENARIO_A_ARM_1A_BICISTRONIC_P2A_COMPARATOR',{}); arm1b=profiles.get('SCENARIO_A_ARM_1B_UNIVERSAL_LEAN_4LOCUS',{})
    cd47=arm1b.get('hour0_basal_cd47_molecules_per_cell'); wt_cd47=wt.get('hour0_basal_cd47_molecules_per_cell')
    resting_hlae=arm1b.get('hour0_resting_unstimulated_hlae_molecules_per_cell')
    resting_relation='unavailable relative to' if resting_hlae is None else ('below' if resting_hlae < 15000 else 'at or above')
    ratio=cd47/wt_cd47 if cd47 is not None and wt_cd47 else None
    stage6=next((p.get('stage6_neurog3_ep_fraction') for p in l2['profiles'] if 'TYK2' in p.get('genotype_id','') and 'KO' in p.get('genotype_id','')),None)
    wt6=wt.get('stage6_neurog3_ep_fraction'); change=(stage6/wt6-1)*100 if stage6 is not None and wt6 else None
    shell=l4['lead'].get('wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001',{})
    p=l5['patient']; s=l5['summary']; lead=l4['lead']
    shrinking=l4['shrinking_core'].get('coupled_shrinking_core_regimes',[])
    shrink_text='; '.join(str(row.get('scenario_id',row.get('regime_id','shrinking-core scenario')))+': '+f(row.get('min_slab_po2_across_14_days_mmhg'),2)+' mmHg at '+f(row.get('time_of_min_slab_po2_hours'),0)+' h' for row in shrinking)
    challenge=l4['challenge']
    reference_ode_text='; '.join(str(row.get('graft_id'))+': minimum '+f(row.get('min_glucose_mM'),2)+' mM / insulin shutoff t50 '+f(row.get('insulin_secretion_shutoff_half_time_min'),2)+' min' for row in l4['reference_architectures'])
    challenge_text='Low-glucose challenge reference-ODE minima: lead '+f(challenge.get('low_glucose_challenge_lead_with_lt_4p2mM_clamp_min_glucose_0p25min_mM'),4)+', composite-reflex OAT1 '+f(challenge.get('low_glucose_challenge_oat1_without_lt_4p2mM_clamp_min_glucose_0p25min_mM'),4)+', pure-beta-clamp OAT1A '+f(challenge.get('low_glucose_challenge_oat1a_beta_clamp_only_min_glucose_0p25min_mM'),4)+' mM; these share the specified prior kinetic constants and are not measured clinical protection.'
    return {
      'reference_ode':reference_ode_text,
      'challenge':challenge_text,
      'shrinking_core':shrink_text,
      'corpus':f"Current corpus: {c['studies']:,} studies, {c.get('active_deduplicated_studies_count','unavailable')} active deduplicated, {c.get('active_empirical_studies_count','unavailable')} active empirical, {c.get('ring1_corpus_count_reconciliation',{}).get('strict_active_peer_reviewed_empirical_studies_total','unavailable')} strict peer-reviewed empirical; {c['atomic_effects']:,} effects, {c['arms']} arms, {c['reference_control_arms']} reference controls, {c['raw_edit_entries']} edit entries and {c.get('expanded_gene_occurrences')} expanded gene occurrences under the ranker expander. Direction/penalty labels are rule-based heuristics; {c['heuristic_penalty_effects']} flagged penalties are not an independently adjudicated accuracy dataset.",
      'layer1':f"Layer 1 evaluates {f(search.get('all_stacks'),0)} prior-anchored stacks ({f(search.get('feasible_stacks'),0)} feasible, {f(search.get('top_tier_stacks'),0)} code-defined top tier). Registry: {f(registry.get('source_literal_offset_terms'),0)} source terms / {f(registry.get('net_gate_offset_entries'),0)} net offsets / {f(registry.get('auxiliary_scalar_leaves'),0)} auxiliary scalar leaves / {f(registry.get('engineering_priors'),0)} engineering priors. Structural share of component variance is {f(structural_percent,4)}% from unrounded latent logits. Current auxiliary non-stack utility-target profiles with typed numeric LRR evidence: {f(a.get('profile_counts',{}).get('candidate_target_profiles_with_typed_numeric_lrr'),0)} (0 evaluated Islet-1 stack targets with new typed numeric LRR changes; the shrinkage branch is checked separately against an actual HNF1A-KO source contrast when zero). Seeded direct and shared-parameter Monte Carlo are exploratory sensitivity simulations with finite-draw Wilson intervals and rank quantiles, not clinical probabilities or fitted posterior intervals. CHK-12 recomputes and compares the complete current replay.",