OpenIslet

scripts/generate_release_manifest.py

Generate the Wave-0 / P0-8 Release & Provenance Manifest (`manifest.json`) and

script Release v0.8.0 gen-eb955f8266035aba 148 KB · 11 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/generate_release_manifest.py · SHA-256: 9b8e7a9ff4998368…

            "ceg_superseded_preprint_duplicates_total": layer1_ceg_atlas["summary"]["superseded_preprint_duplicates_in_ceg"],
            "ceg_arms_total": layer1_ceg_atlas["summary"]["experimental_and_control_arms_total"],
            "ceg_outcomes_total": layer1_ceg_atlas["summary"]["structured_outcomes_total"],
            "ceg_blueprint_links_total": layer1_ceg_atlas["summary"]["blueprint_links_total"],
            "ceg_effector_nodes_total": layer1_ceg_atlas["summary"]["biological_effector_nodes_total"],
            "extracted_thresholds_total": len(graph_data.get("regime_thresholds", [])),
            "extracted_failure_modes_total": len(
                graph_data.get("residual_failure_and_complementary_lever_pairs", [])
            ),
            "graveyard_entries_total": len(graveyard_data.get("graveyard_entries", [])),
            "graveyard_offgrid_guardrails_total": len(
                (graveyard_data.get("off_grid_molecular_dead_end_guardrails") or {}).get("guardrails") or []
            ),
            "graveyard_public_cards_total": len(graveyard_data.get("graveyard_entries", []))
            + len((graveyard_data.get("off_grid_molecular_dead_end_guardrails") or {}).get("guardrails") or []),
            "omics_gnomad_raw_files_total": len(gnomad_files),
            "candidate_stacks_evaluated": ranking_payload.get(
                "total_valid_combinatorial_stacks_evaluated", 0
            ),
            "graph_target_nodes": len(graph_data.get("target_gene_atlas", [])),
            "layer2_construct_cassettes_total": layer2_atlas["summary"]["construct_cassettes_synthesized_and_audited"],
            "layer2_perturbation_arms_simulated": layer2_atlas["summary"]["perturbation_profiles_total"],
            "layer2_alphagenome_avi_snvs_archived": None,
            "layer2_avi_predictions_available": False,
            "layer2_unverified_private_archive_rows": layer2_atlas["summary"]["archival_table_supplied_rows_private_quarantine"],
            "layer3_pdb_experimental_structures_verified": layer3_atlas["summary"]["total_experimental_pdb_structures_verified"],
            "layer3_alphafold_structures_verified": layer3_atlas["summary"]["total_alphafold_v6_models_verified"],
            "layer3_immune_synapse_complexes_verified": len(layer3_atlas["complexes"]),
            "layer4_pde_regimes_simulated": n_layer4_pde_regimes,
            "layer4_paracrine_ode_grafts_simulated": len(layer4_atlas["part_b_24h_trihormonal_paracrine_and_whole_body_metabolic_ode"]["graft_architectures_compared"]),
            "layer5_crispr_guides_compiled": layer5_atlas["summary"]["total_guides_compiled"],
            "layer5_virtual_patients_simulated": layer5_atlas["summary"]["total_virtual_patients_simulated"],
        },
        "artifacts": artifact_entries,
    }

    _require_generation_lease()
    write_documentation(ROOT, manifest_pin_count=len(artifact_entries), render=True,rollback_journal=_GENERATION_JOURNAL.get())
    for rel in artifact_entries:
        p = ROOT / rel
        artifact_entries[rel] = {"sha256": sha256_file(p), "bytes": p.stat().st_size}

    manifest_path = ROOT / "manifest.json"
    _require_generation_lease()
    _publish_generation_artifacts({manifest_path:(json.dumps(manifest,indent=2,ensure_ascii=False,allow_nan=False)+'\n').encode('utf-8')},ROOT/'.manifest-file-publication.lock')
    print(
        f"Wrote manifest.json and brief exports: {len(studies)} studies, {n_effects} atomic effects."
    )


# Explicit machine-verified open-license PMID allowlist; empty by default so all 563 studies enforce the <=240-char cap.
VERIFIED_OPEN_LICENSE_PMIDS: set[str] = set()

import re as _re

VALID_REDACTION_MARKER_RE = _re.compile(
    r"^\[REDACTED_(?:NON_OA|CONSERVATIVE)_EXCERPT: see PMID:\d{7,8}"
    r"(?: span=[A-Za-z0-9_.\[\]:|-]+)?"
    r"(?: field=[A-Za-z0-9_]+)?"
    r"(?: mod=[A-Za-z0-9_,-]+)?"
    r"(?: genes=[A-Za-z0-9_,-]+)?"
    r"(?: pert=(?:GOF_OE|KO_LOF|BOTH|NONE))?"
    r" quote_sha256=[0-9a-f]{64}\]$"
)


def _validate_public_redaction_token(text: str, *, expected_pmid: str | None = None, source_quote: str | None = None, expected_field: str | None = None) -> bool:
    import importlib.util
    helper_path = Path(__file__).parent / "public_excerpt_policy.py"
    # Loaded once per exporter module, including isolated fixture checkouts.
    global _REDACTION_HELPER
    if _REDACTION_HELPER is None:
        spec = importlib.util.spec_from_file_location("openislet_public_excerpt_policy", helper_path)
        helper = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(helper)
        _REDACTION_HELPER = helper
    snapshot = _PUBLIC_POLICY_SNAPSHOT.get()
    helper = snapshot['helper'] if snapshot is not None else _REDACTION_HELPER
    return helper.validate_token(text, expected_pmid=expected_pmid, source_quote=source_quote, expected_field=expected_field)


_REDACTION_HELPER = None


def _public_redaction_field(name: str) -> str:
    _validate_public_redaction_token("")
    snapshot = _PUBLIC_POLICY_SNAPSHOT.get()
    return (snapshot['helper'] if snapshot is not None else _REDACTION_HELPER).safe_field(name)


def _redaction_prefix_for_pmid(pmid: str) -> str:
    _validate_public_redaction_token("")
    snapshot = _PUBLIC_POLICY_SNAPSHOT.get()
    helper = snapshot['helper'] if snapshot is not None else _REDACTION_HELPER
    fn = getattr(helper, "redaction_token_prefix_for_pmid", None)
    return fn(str(pmid)) if fn is not None else "[REDACTED_NON_OA_EXCERPT:"


def _has_redaction_prefix(text: object) -> bool:
    return isinstance(text, str) and ("[REDACTED_NON_OA_EXCERPT:" in text or "[REDACTED_CONSERVATIVE_EXCERPT:" in text)


def _is_authentic_redaction_marker(text: str) -> bool:
    """Compatibility name for bounded opaque syntax, not source acquisition proof."""
    return _validate_public_redaction_token(text)


_PUBLIC_SCHEMA_METADATA_CACHE = {}


def _is_bounded_public_metadata(value,field,*,bibliographic=False):
    _validate_public_redaction_token("")
    snapshot=_PUBLIC_POLICY_SNAPSHOT.get()
    helper=snapshot['helper'] if snapshot is not None else _REDACTION_HELPER
    return helper.is_bounded_metadata(value,field,bibliographic=bibliographic)


def _is_fixed_public_schema_metadata(value: str, field: str = "") -> bool:
    """Recognize finite schema codes only in their documented metadata fields.

    Free-text fields never gain an exemption merely by equalling a code from
    another property. Explicit aliases below are typed copies in conditioning
    contexts and graph projections, not arbitrary prose exemptions.
    """
    if not isinstance(value, str):
        return False
    # These fields carry bounded machine identity, not source prose. Arm IDs
    # are the deterministic identifiers minted by this exporter itself.
    identifiers = {
        'arm_id': r'pmid[1-9][0-9]{0,8}_arm[1-9][0-9]{0,5}',
        'focal_arm_id': r'pmid[1-9][0-9]{0,8}_arm[1-9][0-9]{0,5}',
        'comparator_arm_id': r'pmid[1-9][0-9]{0,8}_arm[1-9][0-9]{0,5}',
        'cohort_id': r'pmid[1-9][0-9]{0,8}_cohort[1-9][0-9]{0,3}',
        'dossier_sha256': r'[0-9a-f]{64}',
        'quote_source_dossier_pmid': r'[1-9][0-9]{0,8}',
        'superseded_by_pmid': r'[1-9][0-9]{0,8}',
        'reconciled_from_superseded_preprint_pmid': r'[1-9][0-9]{0,8}',
        'subordinate_followup_to_pmid': r'[1-9][0-9]{0,8}',
        'bibliographic_volume_issue_pages': r'[0-9]{1,5}\([0-9A-Za-z-]{1,12}\):[0-9A-Za-z-]{1,24}',
    }
    if field in identifiers and _re.fullmatch(identifiers[field], value):
        return True
    snapshot = _PUBLIC_POLICY_SNAPSHOT.get()
    schema_bytes = snapshot['schema'] if snapshot is not None else _regular_file_bytes(ROOT, 'schemas/extraction_schema_v0.2.json')
    cache_key = hashlib.sha256(schema_bytes).digest()
    if cache_key not in _PUBLIC_SCHEMA_METADATA_CACHE:
        schema = json.loads(schema_bytes)
        by_field: dict[str, set[str]] = {}
        def collect(node, current_field=""):
            if isinstance(node, dict):
                by_field.setdefault(current_field, set()).update(v for v in node.get("enum", []) if isinstance(v, str))
                for key, child in node.items():
                    if key == "properties":
                        for name, prop in child.items(): collect(prop, name)
                    else: collect(child, current_field)
            elif isinstance(node, list):
                for child in node: collect(child, current_field)
        collect(schema)
        aliases = {
            "Z1_developmental_stage_and_timing": ("canonical_differentiation_stage_evaluated",),
            "Z2_genetic_background_and_allelic_dose": ("cell_source_class",),
            "Z3_immune_effector_and_stressor_pathway": ("outcome_domain", "challenge_type"),
            "Z6_microenvironment_oxygen_and_vascular_niche": ("transplant_site",),
            "Z7_promoter_and_epigenetic_context": ("promoter_or_locus_context",),
            "Z8_species_age_and_sex_context": ("max_biological_fidelity_tier",),
            "endpoint_name": ("outcome_domain",), "outcome_Y": ("outcome_domain",),
            "primary_gate_perturbed": ("functional_gate",),
            "secondary_gate_affected": ("functional_gate",),
            "functional_gates": ("functional_gate",),
            "hop1_relation": ("causal_relation",), "hop2_relation": ("causal_relation",),
            "study_arm_cell_source_classes": ("cell_source_class",),
            "study_arm_differentiation_stages": ("canonical_differentiation_stage_evaluated",),
        }
        for alias, origins in aliases.items():
            for origin in origins: by_field.setdefault(alias, set()).update(by_field.get(origin, set()))
        for name in ("systemic_immunosuppression_regimen", "encapsulation_or_biomaterial", "co_transplanted_cells_or_oxygen_source"):
            by_field.setdefault(name, set()).add("None")
        for name in ("measurement_unit", "units"):
            by_field.setdefault(name, set()).update((
                "%", "%_relative_decrease", "days", "fold_change_ratio",
                "functional_SP_variants_out_of_16", "genetic_correlation_rg",
                "h", "hours", "mM", "mg/dL", "mg/dl", "mm", "mmHg",
                "molecules_per_cell", "months", "nM", "ng/mL", "nm",
                "nmol/L", "nmol/L per min", "nmol/min/100 islets",
                "pg/mL", "pmol", "pmol/mL", "qualitative_statement",
                "quarantined_ambiguous_numeric",
                "quarantined_approximate_or_bounded_fold_change",
                "quarantined_mismatched_units",
                "quarantined_unbound_numeric_operand",
                "quarantined_unsupported_numeric_notation",
                "quarantined_unsupported_unit",
                "reported_units", "scc/h", "ug/mL", "week", "weeks",
                "\u00b5M", "\u00b5m", "\u03bcM", "\u03bcm",
                "fold_change_early_apoptotic_index", "fold_change_multi_comparator",
                "ng_per_mL_per_1e6_cells", "pct_pa_alleles_ddpcr",
                "percent_ddpcr_insertion_fraction", "percent_descriptive",
                "preclinical_xenograft_tumor_volume_suppression",
                "qualitative_ablation", "qualitative_gel_assembly_feasibility",
                "viability_index",
                "earliest_IAb_proportion", "gsea_nes", "median_survival_mo",
                "molar_excess_fold_for_50pct_inhibition", "pct_incidence",
                "pct_positive", "pct_reduction_at_1p0mM_vs_ctrl",
                "pct_reduction_vs_ctrl", "ROC_AUC", "hazard_ratio",
                "percent_discontinuation_teae", "percent_undiagnosed_end_of_followup",
                "qualitative_pvalue",
            ))
        by_field.setdefault("cell_line_id", set()).update((
            "EndoC-\u03b2H1", "EndoC-\u03b2H3", "H1", "H9", "HUES8",
            "WA01", "H1/WA01", "WA01/H1", "CyT49", "MEL1", "MIN6",
            "INS-1", "INS-1E", "NIT-1", "WTC11", "HEL24.3", "HEL46.11",
            "TkDN4-M", "UP421", "HEK293T",
            "Jurkat (clonal LV-hTMPK-F105Y)", "K562 (LV-hTMPK-F105Y)", "K562 (nontransduced)",
            "Primary human CD3+ T cells (n=4 paired healthy donors; activated CD3/CD28/CD2 + IL-2)",
            "Primary human CD3+ T cells (n=4 paired healthy donors; resting IL-7/IL-15)",
            "beta-iPLC line 2 (FS-beta-iPLC clone#81; triple-transgenic mouse)",
            "beta-iPLC line 2 (parental triple-transgenic mouse; no Cdk1-HSV-TK edit)",
        ))
        by_field.setdefault("comparator_X0", set()).add(
            "Control / comparator condition (see structured arm definitions)"
        )
        # Closed typed species enums emitted by build_cross_study_graph.py edge context
        # projections (strictly key-bound: free-text fields and non-enum prose never match).
        by_field.setdefault("target_cell_species", set()).update((
            "Human", "Rodent_or_Murine", "NHP", "Human_and_Rodent_Mixed_Context", "Unspecified",
        ))
        by_field.setdefault("host_recipient_species", set()).update((
            "Rodent_or_Murine", "NHP", "InVitro_or_Same_As_Target",
        ))
        by_field.setdefault("immune_effector_species", set()).update((
            "Human", "Rodent_or_Murine", "Unspecified_or_Abiotic",
        ))
        by_field.setdefault("reagent_species", set()).update((
            "Human", "Unspecified",
        ))
        span_pattern = schema["properties"]["atomic_effects"]["items"]["properties"]["source_span"]["pattern"]
        if len(_PUBLIC_SCHEMA_METADATA_CACHE) >= 16:
            _PUBLIC_SCHEMA_METADATA_CACHE.pop(next(iter(_PUBLIC_SCHEMA_METADATA_CACHE)))
        _PUBLIC_SCHEMA_METADATA_CACHE[cache_key] = ({k: frozenset(v) for k, v in by_field.items()}, _re.compile(span_pattern))
    by_field, span_pattern = _PUBLIC_SCHEMA_METADATA_CACHE[cache_key]
    if field == "gene_symbol_hgnc":
        _validate_public_redaction_token("")
        helper=snapshot['helper'] if snapshot is not None else _REDACTION_HELPER
        if value in helper.GENES or value in {"HLA-B_HLA-C_HLA-A24", "IL10_TGFB1_IL2_N88D", "JAK1_JAK2", "MULTI_LOCUS_SAFE_HARBOR"}:
            return True
    if field == "ensembl_gene_id" and _re.fullmatch(r"ENS(?:MUS)?G[0-9]{11}", value) is not None:
        return True
    if field == "source_figure_or_table" and len(value) <= 80:
        if _re.fullmatch(
            r"(?:Abstract|Title|Results|Methods|Discussion|Table|Tables|Fig\.?|Figs\.?|Figure|Figures|Extended Data|Supplementary|Supp\.?|SI Appendix|Section|Sec\.?|Panel|para|and|or|&|,|;|\(|\)|-|/|\u00a7|NCT\d{8}|[Ss]?[0-9]+(?:\.[0-9]+)?[A-Za-z]?|[IVX]+|\s)+",
            value,