OpenIslet

scripts/identify_and_stratify_corpus.py

Step 2: Deterministic Data Identification, Signal Tagging & Concentric Ring Stratification

script Release v0.8.0 gen-eb955f8266035aba 23 KB · 2 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/identify_and_stratify_corpus.py · SHA-256: b8d9431dd82a9f3f…

            ring = "Ring_4_Rodent_Tier4_and_Peripheral_Pool"

        ring_counts[ring] += 1

        if pmid in SUPERSEDED_PREPRINT_PMIDS:
            record_study_type = "Preprint_Superseded_By_Peer_Reviewed"
        elif pmid in CITATION_ONLY_NO_ABSTRACT_PMIDS:
            record_study_type = "Citation_Only_No_Abstract_Indexed"
        elif pmid in PROJECT_SUMMARY_PMIDS:
            record_study_type = "Project_Summary"
        elif pmid in REVIEW_PMIDS:
            record_study_type = "Review"
        elif pmid in CLINICAL_TRIAL_REPORT_PMIDS:
            record_study_type = "Clinical_Trial_Report"
        else:
            record_study_type = "Empirical_Experimental"

        entry = {
            "pmid": pmid,
            "pmcid": pmcid,
            "doi": rec.get("doi"),
            "pub_year": rec.get("pub_year"),
            "journal": rec.get("journal"),
            "first_author": rec.get("first_author"),
            "senior_author": rec.get("senior_author"),
            "title": rec.get("title"),
            "record_study_type": record_study_type,
            "is_active_empirical_study": record_study_type in ("Empirical_Experimental", "Clinical_Trial_Report"),
            "data_accessibility_class": access_class,
            "geo_gse_accessions": gse_list,
            "estimated_fidelity_tier": fidelity_tier,
            "matched_pillars": pillars,
            "core_subpillar_count": len(core_subpillars),
            "matched_beta1_targets": matched_targets,
            "quantitative_signal_count": quant_hits,
            "effect_modifier_signal_count": modifier_hits,
            "priority_ring": ring,
            "is_golden_seed": bool(is_seed or is_curated_frontier),
        }
        stratified_records.append(entry)
        if ring == "Ring_1_Platinum_MultiGate_Core":
            ring1_queue.append(entry)

    # Sort automated 532 Ring 1 studies first, followed by the 31 curated frontier/counter-evidence additions in canonical order
    auto_ring1_studies = [r for r in ring1_queue if r["pmid"] not in CURATED_FRONTIER_SET]
    curated_frontier_studies = [r for r in ring1_queue if r["pmid"] in CURATED_FRONTIER_SET]
    auto_ring1_studies.sort(
        key=lambda x: (
            x["is_golden_seed"],
            x["pmcid"] is not None,
            x["core_subpillar_count"],
            len(x["matched_beta1_targets"]),
            x["pub_year"] or 0,
        ),
        reverse=True,
    )
    curated_frontier_studies.sort(key=lambda x: CURATED_ORDER_INDEX.get(x["pmid"], 999))
    ring1_queue = auto_ring1_studies + curated_frontier_studies

    ring1_pmids = [r["pmid"] for r in ring1_queue]
    ring1_platinum_seed_pmids = [r["pmid"] for r in ring1_queue if r["is_golden_seed"]]
    ring1_study_type_counts = Counter(r["record_study_type"] for r in ring1_queue)
    non_superseded_count = sum(
        1 for r in ring1_queue if r["record_study_type"] != "Preprint_Superseded_By_Peer_Reviewed"
    )
    active_deduplicated_count = sum(
        1
        for r in ring1_queue
        if r["record_study_type"] not in (
            "Preprint_Superseded_By_Peer_Reviewed",
            "Project_Summary",
            "Citation_Only_No_Abstract_Indexed",
        )
    )
    active_empirical_count = sum(1 for r in ring1_queue if r["is_active_empirical_study"])

    out_ring1 = RAW_DIR / "ring1_platinum_queue.json"
    if out_ring1.exists():
        try:
            existing_q = json.loads(out_ring1.read_text(encoding="utf-8"))
            existing_pmids = [
                str(s["pmid"]) if isinstance(s, dict) else str(s)
                for s in existing_q.get("studies", [])
            ]
            missing_existing = sorted(set(existing_pmids) - set(ring1_pmids))
            if missing_existing:
                raise RuntimeError(
                    f"Refusing to overwrite ring1_platinum_queue.json: {len(missing_existing)} existing Ring-1 PMIDs "
                    f"would be dropped ({missing_existing[:5]}...)."
                )
        except json.JSONDecodeError:
            pass

    summary = {
        "generated_at": "2026-10-24",
        "total_pubmed_studies_indexed": len(stratified_records),
        "initial_pubmed_harvest_records": 6857,
        "targeted_blindspot_and_counterevidence_additions": len(stratified_records) - 6857,
        "automated_ring1_core_count": len(auto_ring1_studies),
        "curated_frontier_and_counterevidence_ring1_additions": len(curated_frontier_studies),
        "ring1_platinum_core_total": len(ring1_queue),
        "ring1_platinum_seed_and_frontier_count": len(ring1_platinum_seed_pmids),
        "ring1_superseded_preprint_twins_count": ring1_study_type_counts["Preprint_Superseded_By_Peer_Reviewed"],
        "ring1_non_superseded_studies_count": non_superseded_count,
        "ring1_active_deduplicated_studies_count": active_deduplicated_count,
        "ring1_non_empirical_project_summary_count": ring1_study_type_counts["Project_Summary"],
        "ring1_citation_only_no_abstract_count": ring1_study_type_counts["Citation_Only_No_Abstract_Indexed"],
        "ring1_non_empirical_review_count": ring1_study_type_counts["Review"],
        "ring1_active_empirical_studies_count": active_empirical_count,
        "ring1_study_type_breakdown": dict(ring1_study_type_counts),
        "abstract_availability_and_triage_mode_audit": {
            "triage_mode": "Title_MeSH_Keyword_Subpillar_Triage_With_Explicit_Fallback_OptIn",
            "allow_title_only_fallback": allow_title_only_fallback,
            "manifest_inline_abstract_count": manifest_abstract_count,
            "ring1_cached_dossier_abstract_count": dossier_abstract_count,
        },
        "data_accessibility_breakdown": dict(data_access_counts),
        "open_fulltext_pmc_xml_total": sum(1 for r in stratified_records if r["pmcid"] is not None),
        "open_fulltext_pmc_xml_pct": round(100.0 * sum(1 for r in stratified_records if r["pmcid"] is not None) / max(1, len(stratified_records)), 1),
        "biological_fidelity_tier_breakdown": dict(fidelity_counts),
        "concentric_priority_ring_breakdown": dict(ring_counts),
        "ring1_open_fulltext_count": sum(1 for r in ring1_queue if r["pmcid"] is not None),
        "target_gene_mention_breakdown": dict(target_gene_counts.most_common()),
        "initial_6857_harvest_stratification_snapshot": {
            "total_pubmed_studies_indexed": 6857,
            "concentric_priority_ring_breakdown": {
                "Ring_1_Platinum_MultiGate_Core": 532,
                "Ring_2_Human_SC_Islet_and_TargetGene_Core": 2174,
                "Ring_3_Human_Islet_Paracrine_HPAP_and_Engraftment_Core": 1631,
                "Ring_4_Rodent_Tier4_and_Peripheral_Pool": 2520,
            },
            "ring1_open_fulltext_count": 374,
        },
    }

    out_summary = RAW_DIR / "corpus_triage_and_rings.json"
    with open(out_summary, "w", encoding="utf-8") as f:
        json.dump(summary, f, indent=2, ensure_ascii=False)
        f.write("\n")

    with open(out_ring1, "w", encoding="utf-8") as f:
        json.dump(
            {
                "count": len(ring1_queue),
                "automated_ring1_core_count": len(auto_ring1_studies),
                "curated_frontier_and_counterevidence_additions_count": len(curated_frontier_studies),
                "total_ring1_studies": len(ring1_queue),
                "superseded_preprint_twins_count": ring1_study_type_counts["Preprint_Superseded_By_Peer_Reviewed"],
                "non_superseded_studies_count": non_superseded_count,
                "active_deduplicated_studies_count": active_deduplicated_count,
                "non_empirical_project_summary_count": ring1_study_type_counts["Project_Summary"],
                "citation_only_no_abstract_count": ring1_study_type_counts["Citation_Only_No_Abstract_Indexed"],
                "non_empirical_review_count": ring1_study_type_counts["Review"],
                "active_empirical_studies_count": active_empirical_count,
                "ring1_study_type_breakdown": dict(ring1_study_type_counts),
                "studies": ring1_queue,
            },
            f,
            indent=2,
            ensure_ascii=False,
        )
        f.write("\n")

    out_strat_manifest = RAW_DIR / "corpus_stratification_manifest.json"
    with open(out_strat_manifest, "w", encoding="utf-8") as f:
        json.dump(
            {
                "schema_version": "0.8.1",
                "total_deduplicated_pubmed_records_in_manifest": len(stratified_records),
                "initial_pubmed_harvest_records": 6857,
                "targeted_blindspot_and_counterevidence_additions": len(stratified_records) - 6857,
                "automated_ring1_core_count": len(auto_ring1_studies),
                "curated_frontier_and_counterevidence_ring1_additions": len(curated_frontier_studies),
                "ring1_platinum_core_count": len(ring1_queue),
                "ring1_platinum_seed_and_frontier_count": len(ring1_platinum_seed_pmids),
                "ring1_superseded_preprint_twins_count": ring1_study_type_counts["Preprint_Superseded_By_Peer_Reviewed"],
                "ring1_non_superseded_studies_count": non_superseded_count,
                "ring1_active_deduplicated_studies_count": active_deduplicated_count,
                "ring1_non_empirical_project_summary_count": ring1_study_type_counts["Project_Summary"],
                "ring1_citation_only_no_abstract_count": ring1_study_type_counts["Citation_Only_No_Abstract_Indexed"],
                "ring1_non_empirical_review_count": ring1_study_type_counts["Review"],
                "ring1_active_empirical_studies_count": active_empirical_count,
                "ring1_study_type_breakdown": dict(ring1_study_type_counts),
                "ring1_platinum_pmids": ring1_platinum_seed_pmids,
                "ring1_pmids": ring1_pmids,
                "ring1_platinum_is_strict_subset_of_ring1": set(ring1_platinum_seed_pmids).issubset(set(ring1_pmids)),
                "ring1_queue_path": "data/raw/ring1_platinum_queue.json",
                "notes": (
                    f"Computed corpus stratification: {len(stratified_records)} PubMed records; "
                    f"{len(ring1_queue)} Ring-1 bibliographic records; {non_superseded_count} non-superseded; "
                    f"{active_deduplicated_count} active deduplicated; {active_empirical_count} active empirical. "
                    f"Excluded project summaries: {ring1_study_type_counts['Project_Summary']}; "
                    f"citation-only (no abstract indexed): {ring1_study_type_counts['Citation_Only_No_Abstract_Indexed']}; "
                    f"reviews: {ring1_study_type_counts['Review']}; "
                    f"superseded preprints: {ring1_study_type_counts['Preprint_Superseded_By_Peer_Reviewed']}."
                ),
            },
            f,
            indent=2,
            ensure_ascii=False,
        )
        f.write("\n")

    out_all_stratified = RAW_DIR / "corpus_stratified_index.jsonl"
    with open(out_all_stratified, "w", encoding="utf-8") as f:
        for r in stratified_records:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    print("=== STEP 2: DATA IDENTIFICATION & RING STRATIFICATION SUMMARY ===")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Stratify PubMed corpus and emit Ring-1 Platinum queue.")
    parser.add_argument(
        "--allow-title-only",
        dest="allow_title_only",
        action="store_true",
        default=False,
        help="Explicitly allow title+MeSH+keyword+subpillar triage when inline manifest abstracts are absent; private dossier caches may still be required.",
    )
    parser.add_argument(
        "--strict-require-abstracts",
        dest="allow_title_only",
        action="store_false",
        help="Fail immediately if corpus_manifest_all_sources.jsonl contains 0 inline abstracts.",
    )
    args = parser.parse_args()
    main(allow_title_only_fallback=args.allow_title_only)