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…

      'layer2':f"Layer 2 uses the pinned release pairing {l2.get('release_pairing')} and contains {l2['profile_count']} literature-anchored stage-specific prior profiles with 1,000 independent prior-scenario draws per endpoint; it is not a fitted dynamic GRN/ODE or held-out validated differentiation predictor. Arm 1B constitutive EEF1A1 drives antisense CD47 and inducible sense 5xISRE drives HLA-E. Computed Arm 1A/1B Hour-0 CD47 is {f(arm1a.get('hour0_basal_cd47_molecules_per_cell'),0)}/{f(cd47,0)} molecules/cell; Arm 1B/WT is {f(ratio,8)}x. Resting Arm 1B HLA-E is {f(arm1b.get('hour0_resting_unstimulated_hlae_molecules_per_cell'),0)} and IFNg24h HLA-E {f(arm1b.get('ifng_24h_induced_hlae_molecules_per_cell'),0)}; the resting endpoint is {resting_relation} the assumed 15,000 threshold. Exact edited beta/alpha/delta/iEC density is unmeasured, with a preregistered Stage-0 acceptance target for Hour-0 density. TYK2-KO Stage-6 prior is {f(stage6,3)} versus {f(wt6,3)} WT ({f(change,1)}%); this is distinct from the transcript-level endpoint. {CANDIDATE}; anti-silencing function requires head-to-head lineage qualification against the published CBX3-side fragment. The local 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. Scenario-B P2A profiles are unsupported provisional comparators; the exact 2A-free Scenario-B donor/prediction remains unavailable.",
      'layer3':STRUCTURE1+' '+STRUCTURE2+' The 21-residue linker-2 path includes unresolved HLA-E Gly1 between the 20-aa (G4S)4 linker and HLA-E Ser2 N; 73.50 A contour, 0.4234 extension, 9.901 pN are coarse WLC quantities. The 3CDG reference-crystal Arg107 C-alpha distance is 17.02 A, nearest-heavy-atom distance 14.82 A; neither is a measured engineered Gly107 geometry. Foldseek is a cached-hit replay with missing historical database/tool/date provenance, not a reproducible original search. 8H4X was superseded by 8ZCR (Yan, Zhou et al., 2024, Acta Crystallogr F 80:286-293; DOI:10.1107/S2053230X24009439; PMID:39382088). Exact-product function remains unresolved.',
      'layer4':f"Layer 4 is a conditional model, not validated graft survival. The physical source lamina half-width fraction is {f(l4['geometry'].get('selected_source_lamina_half_width_fraction'),2)}; its continuous central volume is derived from that same geometry and control-volume overlap at every mesh. Nominal minimum slab oxygen is {f(lead.get('min_slab_po2_across_14_days_mmhg'),2)} mmHg at {f(lead.get('time_of_min_slab_po2_hours'),0)} h. The {f(lead.get('min_120um_cluster_core_po2_mmhg'),2)}-mmHg homogenized fixed-surface Dirichlet core is an upper-bound screen; operative uniform-supply / conservative gel-only two-zone cores are {f(shell.get('two_zone_fv_uniform_supply_120um_core_po2_mmhg'),2)}/{f(shell.get('two_zone_fv_gel_only_supply_120um_core_po2_mmhg'),2)} mmHg. Physical supply topology remains a Stage-2 assay gate; mesh error is evaluated on unrounded values, with NUMERICALLY_UNRESOLVED whenever an uncertainty interval straddles the threshold. 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: {reference_ode_text}. {challenge_text} Nominal modeled peak peroxide is {f(lead.get('max_interstitial_h2o2_uM'),3)} uM and maximum pH {f(lead.get('max_interstitial_ph'),3)}.",
      'layer5':f"Layer 5 is an illustrative assigned-rule population simulator, not a clinical forecast. Personalized analytic expectation is {f(p.get('global_analytic_expected_5yr_survival_personalized_compiled_pct'),4)}%, standardized Plan A analytic {f(p.get('global_analytic_expected_5yr_survival_standardized_plan_a_pct'),4)}%; sampled personalized {f(p.get('global_5yr_survival_personalized_dna_compiled_openislet_pct'),2)}%. Analytic ancestry gap is {f(s.get('analytic_max_ancestry_disparity_gap_personalized_pct',p.get('analytic_max_ancestry_disparity_gap_personalized_pct_v80_065')),2)} percentage points; sampled gap {f(s.get('sampled_max_ancestry_disparity_gap_personalized_pct',p.get('max_ancestry_disparity_gap_personalized_pct')),2)} points, with finite sample/seed scope. Genome-wide off-target enumeration is NOT_ENUMERATED and coding-hit count is null; assigned illustrative three-mismatch panel scores are not exhaustive genome/exome scans or empirical HiFi-SpCas9 specificity. Variant identity is source-verified dbSNP interval identity; rare-variant screening frequencies are explicit assumed priors, with gnomAD row-level AC/AN validation pending. Manufacturing yield is null/NOT_MEASURED; exp(-lambda_K*max(0,K-4))*gamma_B**B is a dimensionless engineering utility discount. The executable optional TYK2 design is PEmax+epegRNA. CGBE remains an unimplemented contingency requiring an engineered SpG/SpRY-compatible PAM, editing-window/bystander ledger and separate validation; no CGBE guide is qualified here.",
      'design':f"HIP-Core executes all {len(l1['protocol'].get('runs',[]))} coded rows, including all 11 repeat/bridge/lead rows, across 25 distinct genotypes. The quoted covariance/power applies to 108 independent run-nested clones or 75 shared-genotype clones; 61-clone power is UNEVALUATED with null SE/MDE. Current factor sums are {list(l1['protocol'].get('column_sums_across_36_runs_by_factor',{}).values())}; +1 counts are {list(l1['protocol'].get('plus_one_counts_across_36_runs_by_factor',{}).values())}."
    }


def facts_block(facts):
    n=narratives(facts); lines=[START,'','**Current executable facts (generated from on-disk artifacts; physical gates pending).**','',n['corpus'],'',n['layer1'],'',n['design'],'','| Construct | Donor bp | Packaged bp, including 2 x 145-bp ITRs |','| :--- | ---: | ---: |']
    for construct in facts['layer2']['constructs']:
        lines.append(f"| `{construct['construct_id']}` | {construct.get('total_length_bp')} | {construct.get('packaged_aav6_genome_with_2x145bp_itrs_bp')} |")
    promoter=facts['layer1'].get('audit_ledger',{}).get('native_eef1a1_promoter',{})
    lines += ['',f"Native EEF1A1 core: {promoter.get('length_bp')} bp, {promoter.get('cpg_dinucleotides')} CpG dinucleotides, {promoter.get('total_exact_or_rc_occurrences')} exact/RC donor occurrences; these are native CpG-containing promoter sequences.",'',f"Release manifest: `{facts['manifest_pin_count']:,}` pinned files. Machine facts: `data/extracted/documentation_facts_v0.8.0.json`. These facts supersede stale numeric summaries in explicitly historical rationale sections. Outward rankings remain unfrozen (`outward_rankings_frozen: false`); no exact product has passed physical qualification.",'',END]
    return '\n'.join(lines)


def _refine_table_cell(cell, key, current):
    """Update a bounded generated qualifier while retaining authored cell content."""
    start = '<!-- OPENISLET_CELL_' + key + '_START -->'
    end = '<!-- OPENISLET_CELL_' + key + '_END -->'
    note = start + ' Current generated scope: ' + current + ' ' + end
    _validate_markers(cell, start, end)
    if start in cell:
        return re.sub(re.escape(start) + r'.*?' + re.escape(end), lambda _m: note, cell)
    if current.strip() in cell:
        return cell
    # Earlier generated cells had no marker. If only numbers changed, update
    # those values in place rather than appending a second, contradictory copy.
    numeric_shape=lambda value: re.sub(r'(?<![A-Za-z])[-+]?\d+(?:[.,]\d+)*(?:[eE][-+]?\d+)?','#',value.strip())
    if numeric_shape(cell)==numeric_shape(current):
        return cell[:len(cell)-len(cell.lstrip())]+current.strip()+cell[len(cell.rstrip()):]
    return cell.rstrip() + '<br>' + note + ' '


def _score_cell(cell, value, floor=None):
    number = '`' + f(value, 4) + '`'
    if re.search(r'`[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)`', cell):
        cell = re.sub(r'`[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)`', lambda _m: number, cell, count=1)
    else:
        cell = ' **' + number + '** ' + cell.strip()
    if floor is not None:
        cell = re.sub(r'(Floor:\s*`)[0-9.]+(`)', lambda m: m.group(1) + f(floor,4) + m.group(2), cell)
    return cell


def _ranking_header(cells):
    patterns = {'pediatric':r'pediatric','adult':r'adult','composite':r'composite',
                'rank':r'grid\s*position|\brank\b','discount':r'mfg|manufacturing|engineering.*discount',
                'limiting':r'limiting|bottleneck','specification':r'specification'}
    matches = {key: [i for i,cell in enumerate(cells) if re.search(pattern,cell,re.I)] for key,pattern in patterns.items()}
    required = ('pediatric','adult')
    intent=any(re.search(r'index|score|composite|grid\s*position|architecture\s*id',cell,re.I) for cell in cells)
    if not intent: return None
    if any(matches[key] for key in required) and (any(len(matches[key]) != 1 for key in required) or len({matches[key][0] for key in required}) != 2 or len(matches['composite']) > 1):
        raise ValueError('Ranking table requires distinct, unique pediatric/adult columns and at most one composite column')
    mapping = {key: indices[0] if indices else None for key,indices in matches.items()}
    return mapping if all(mapping[key] is not None for key in ('pediatric','adult')) else None


def _validate_markers(text, start, end):
    if text.count(start) != text.count(end) or text.count(start) > 1 or (start in text and text.index(start) > text.index(end)):
        raise ValueError('Malformed or duplicate generated-document markers')


def _table_cells(line):
    # A pipe preceded by an even number of backslashes is a delimiter.
    cells=[];start=0;slashes=0
    for index,char in enumerate(line):
        if char=='|' and slashes%2==0:
            cells.append(line[start:index]);start=index+1
        slashes=slashes+1 if char=='\\' else 0
    cells.append(line[start:])
    return cells


def _protect_link_destinations(text, prefix):
    """Shield link destinations during prose substitutions without a parser dependency.

    Balanced parentheses and backslash escapes are retained byte-for-byte;
    reference definitions and autolinks are protected as complete literals.
    The surrounding authored label remains available to ordinary rendering.
    """
    protected = []
    def hold(value):
        key = f'{prefix}LINK_{len(protected)}\x00'
        protected.append((key, value))
        return key
    # A definition's destination and title may each begin on the next line.
    # Scan escapes and balanced destination parentheses before accepting it;
    # an ordinary following paragraph must remain available to rendering.
    definition = re.compile(r'^ {0,3}\[(?:\\[^\r\n]|[^\[\]\\\r\n])+\]:[ \t]*', re.M)
    def next_content(position):
        return position + len(re.match(r'[ \t]*(?:\r?\n[ \t]*)?', text[position:])[0])
    spans = []
    for match in definition.finditer(text):
        if spans and match.start() < spans[-1][1]:
            continue
        start = end = next_content(match.end())
        if end >= len(text):
            continue
        angle = text[end] == '<'
        if angle:
            end += 1
        depth = 0
        while end < len(text):
            char = text[end]
            if char == '\\' and end+1 < len(text):
                end += 2; continue
            if angle:
                if char == '>':
                    end += 1; break
                if char in '<\r\n':
                    break
            else:
                if char.isspace() or char in '<>':
                    break
                if char == '(':
                    depth += 1
                elif char == ')':
                    depth -= 1
                    if depth < 0: break
            end += 1
        if end == start or depth or (angle and text[end-1:end] != '>'):
            continue
        destination_end = end
        title_start = next_content(end)
        if title_start > end and text[title_start:title_start+1] in ('"', "'", '('):
            closing = ')' if text[title_start] == '(' else text[title_start]
            end = title_start+1
            while end < len(text):
                if text[end] == '\\' and end+1 < len(text):
                    end += 2; continue
                if text[end] == closing:
                    end += 1; break
                if text[end] == '\n' and re.match(r'[ \t]*\r?\n', text[end+1:]):
                    break
                end += 1
            if text[end-1:end] != closing:
                end = destination_end
        else:
            end = destination_end
        end += len(re.match(r'[ \t]*', text[end:])[0])
        if end < len(text) and text[end] not in '\r\n':
            # An invalid title on the next line does not invalidate an otherwise
            # complete destination on the preceding line.
            end = destination_end + len(re.match(r'[ \t]*', text[destination_end:])[0])
            if end < len(text) and text[end] not in '\r\n':
                continue
        spans.append((match.start(), end))
    for start, end in reversed(spans):
        text = text[:start] + hold(text[start:end]) + text[end:]
    # Preserve lexical HTML, including quoted attributes and comments. Managed
    # table delimiters remain visible to their existing scope-update parser.
    html = re.compile(r'''<!--.*?-->|<\?.*?\?>|<!\[CDATA\[.*?\]\]>|<![A-Z][^>]*>|</?[A-Za-z][A-Za-z0-9-]*(?:\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*/?>''', re.S)
    def hold_html(match):
        value = match[0]
        if re.fullmatch(r'<!-- OPENISLET_CELL_[A-Z0-9_]+_(?:START|END) -->', value):
            return value
        return hold(value)
    text = html.sub(hold_html, text)
    pieces = []; start = 0; i = 0
    while i < len(text)-1:
        if text[i:i+2] != '](':
            i += 1; continue
        end = i+2; depth = 1; angle = False; quoted = None
        while end < len(text) and depth:
            char = text[end]
            if char == '\\':
                end += 2; continue
            if quoted:
                if char == quoted: quoted = None
            elif char in ('"', "'") and (end == i+2 or text[end-1].isspace()): quoted = char
            elif char == '<': angle = True
            elif char == '>': angle = False
            elif not angle and char == '(': depth += 1
            elif not angle and char == ')': depth -= 1
            end += 1
        if depth:
            i += 2; continue
        pieces.append(text[start:i+1]); pieces.append(hold(text[i+1:end]))
        start = end; i = end
    pieces.append(text[start:])
    text = ''.join(pieces)
    text = re.sub(r'<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\n]*|[^<>\s]+@[^<>\s]+)>', lambda m: hold(m[0]), text)
    return text, protected


def render_text(text, facts, filename):
    # Fenced examples and diagrams are authored literals, not replacement inputs.
    fences=[];unclosed_key=None
    literal_prefix='\x00OPENISLET_LITERAL_FENCE_'
    while literal_prefix in text:
        literal_prefix = literal_prefix + '_'
    def literal_key(index):return f'{literal_prefix}{index}\x00'
    lines=text.splitlines(keepends=True); held=[]; i=0
    while i < len(lines):
        # Also shield fenced blocks inside block quotes and ordinary indented
        # code. Conservative shielding retains authored literals byte-for-byte.
        prefix=re.match(r'^(?: {0,3}>[ \t]?| {0,3}(?:[-+*]|[0-9]{1,9}[.)])[ \t]+)*',lines[i]).group(0)
        candidate=lines[i][len(prefix):]
        match=re.match(r'^ {0,3}(`{3,}|~{3,})([^\n]*)',candidate)
        raw_html=re.match(r'^ {0,3}<(script|pre|style|textarea)(?:\s|>|$)',candidate,re.I)
        if raw_html:
            start=i;closing_html=re.compile(r'</'+raw_html[1]+r'\s*>',re.I)
            while i<len(lines):
                line=lines[i];i+=1
                if closing_html.search(line):break
            key=literal_key(len(fences))
            fences.append((key,''.join(lines[start:i]).rstrip('\n')));held.append(key+'\n')
            if not closing_html.search(line):unclosed_key=key
            continue
        if not match and candidate.strip() and (candidate.startswith('    ') or candidate.startswith('\t')):
            start=i;i+=1
            while i<len(lines) and (not lines[i].strip() or re.sub(r'^(?: {0,3}>[ \t]?)*','',lines[i]).startswith(('    ','\t'))):i+=1
            # Separator blank lines belong to surrounding Markdown. Keeping
            # them outside the literal avoids consuming one on each re-render.
            while i>start+1 and not lines[i-1].strip():i-=1
            key=literal_key(len(fences))
            fences.append((key,''.join(lines[start:i]).rstrip('\n')));held.append(key+'\n')
            continue
        if not match or (match.group(1)[0]=='`' and '`' in match.group(2)):
            held.append(lines[i]); i+=1; continue
        fence=match.group(1); start=i; i+=1
        closed=False
        # Container order matters: '- >' continues as '  >', whereas '> -'
        # continues as '>  '. Stripping all quotes first conflates those forms.
        containers=[]
        for item in re.finditer(r' {0,3}>[ \t]?| {0,3}(?:[-+*]|[0-9]{1,9}[.)])[ \t]+',prefix):
            containers.append(('quote' if '>' in item[0] else 'list',len(item[0].expandtabs(4))))
        closing=re.compile(r'^ {0,3}'+re.escape(fence[0])+'{'+str(len(fence))+r',}[ \t]*(?:\r?\n)?$')
        while i<len(lines):
            inner=lines[i]
            for kind,width in containers:
                if kind=='quote':
                    quote=re.match(r'^ {0,3}>[ \t]?',inner)
                    if quote is None:
                        inner=None;break
                    inner=inner[len(quote[0]):]
                else:
                    expanded=inner.expandtabs(4)
                    if inner.strip() and not expanded.startswith(' '*width):
                        inner=None;break
                    inner=expanded[width:]
            if inner is None: