|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +construct_pathfinder_constrained.py |
| 4 | +
|
| 5 | +Build a Pathfinder-style TRAPI query_graph with a single intermediate category constraint: |
| 6 | +
|
| 7 | + nodes: exactly two (both pinned) → {"ids": ["CURIE"]} |
| 8 | + paths: single p0 with predicates=["biolink:related_to"] and |
| 9 | + constraints:[{"intermediate_categories":[<ONE biolink:Class>]}] |
| 10 | +
|
| 11 | +Priority for ONE intermediate class: |
| 12 | + 1) state['intermediate_category'] (string) |
| 13 | + 2) first usable from state['intermediate_hints'] (list[str]) |
| 14 | + 3) regex hint from the NL query (e.g., "via genes", "through diseases", "contain a drug") |
| 15 | + 4) fallback to state['generic_types'] (but skip ChemicalEntity unless query mentions drug/chemical/compound) |
| 16 | +
|
| 17 | +All candidates are canonicalized via biolink_utils.canonicalize_class(). |
| 18 | +""" |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import logging |
| 22 | +import re |
| 23 | +from typing import Dict, Any, List, Optional, Tuple |
| 24 | + |
| 25 | +from ..state_types import TRAPIState |
| 26 | +from ..utils.biolink_utils import canonicalize_class |
| 27 | + |
| 28 | +logger = logging.getLogger(__name__) |
| 29 | +REQ_PRED = "biolink:related_to" |
| 30 | + |
| 31 | + |
| 32 | +# ── helpers ─────────────────────────────────────────────────────────────────── |
| 33 | + |
| 34 | +def _unique(seq: List[str]) -> List[str]: |
| 35 | + seen, out = set(), [] |
| 36 | + for x in seq or []: |
| 37 | + if x and x not in seen: |
| 38 | + out.append(x) |
| 39 | + seen.add(x) |
| 40 | + return out |
| 41 | + |
| 42 | + |
| 43 | +def _pick_two_pinned(nodes: Dict[str, Dict[str, Any]]) -> List[Tuple[str, str]]: |
| 44 | + """Return up to 2 (node_id, CURIE) pairs for pinned nodes.""" |
| 45 | + seen, out = set(), [] |
| 46 | + for nid, meta in (nodes or {}).items(): |
| 47 | + curie = meta.get("id") |
| 48 | + if curie and curie not in seen: |
| 49 | + out.append((nid, curie)) |
| 50 | + seen.add(curie) |
| 51 | + if len(out) == 2: |
| 52 | + break |
| 53 | + return out |
| 54 | + |
| 55 | + |
| 56 | +# Single-class, deterministic regex hints. The FIRST match wins. |
| 57 | +_HINT_ORDER: List[Tuple[str, str]] = [ |
| 58 | + # genes / proteins |
| 59 | + (r"\b(?:via|through)\s+(?:the\s+)?genes?\b", "Gene"), |
| 60 | + (r"\b(?:via|through)\s+(?:the\s+)?proteins?\b", "Protein"), |
| 61 | + # diseases |
| 62 | + (r"\b(?:via|through)\s+(?:the\s+)?diseases?\b", "Disease"), |
| 63 | + # drug / chemical |
| 64 | + (r"\bcontain(?:s|ing)?\s+(?:a\s+)?drug\b", "Drug"), |
| 65 | + (r"\b(?:via|through)\s+(?:a\s+)?drug\b", "Drug"), |
| 66 | + (r"\b(?:via|through)\s+(?:a\s+)?chemicals?\b", "ChemicalEntity"), |
| 67 | + (r"\b(?:via|through)\s+(?:a\s+)?compounds?\b", "ChemicalEntity"), |
| 68 | + # pathway / phenotype / anatomy |
| 69 | + (r"\b(?:via|through)\s+(?:the\s+)?pathways?\b", "Pathway"), |
| 70 | + (r"\b(?:via|through)\s+(?:the\s+)?phenotypes?\b", "PhenotypicFeature"), |
| 71 | + (r"\b(?:via|through)\s+(?:the\s+)?tissues?\b", "AnatomicalEntity"), |
| 72 | + (r"\b(?:via|through)\s+anatom(?:y|ical(?:\s+entity)?)\b", "AnatomicalEntity"), |
| 73 | +] |
| 74 | + |
| 75 | + |
| 76 | +def _query_hint_category(query: str) -> Optional[str]: |
| 77 | + q = (query or "").lower() |
| 78 | + for pat, raw in _HINT_ORDER: |
| 79 | + if re.search(pat, q, flags=re.I): |
| 80 | + cat = canonicalize_class(raw) |
| 81 | + if cat: |
| 82 | + return cat |
| 83 | + return None |
| 84 | + |
| 85 | + |
| 86 | +def _pick_single_intermediate(state: TRAPIState) -> Optional[str]: |
| 87 | + """ |
| 88 | + Choose exactly ONE intermediate Biolink category. |
| 89 | + """ |
| 90 | + # 1) explicit single choice (e.g., from UI) |
| 91 | + ui_raw = (state.get("intermediate_category") or "").strip() |
| 92 | + if ui_raw: |
| 93 | + cat = canonicalize_class(ui_raw) |
| 94 | + if cat: |
| 95 | + return cat |
| 96 | + |
| 97 | + # 2) optional list of hints (first usable) |
| 98 | + for raw in _unique(state.get("intermediate_hints", []) or []): |
| 99 | + cat = canonicalize_class(raw) |
| 100 | + if cat: |
| 101 | + return cat |
| 102 | + |
| 103 | + # 3) regex hint from query |
| 104 | + cat = _query_hint_category(state.get("query", "")) |
| 105 | + if cat: |
| 106 | + return cat |
| 107 | + |
| 108 | + # 4) fallback from generic_types, but avoid ChemicalEntity unless query mentions drug/chemical/compound |
| 109 | + generics = _unique(state.get("generic_types", []) or []) |
| 110 | + ql = (state.get("query") or "").lower() |
| 111 | + allow_chem = bool(re.search(r"\b(drug|chemical|compound)s?\b", ql)) |
| 112 | + |
| 113 | + # Preferred order for informative constraints |
| 114 | + preferred = [ |
| 115 | + "biolink:Gene", |
| 116 | + "biolink:Protein", |
| 117 | + "biolink:Disease", |
| 118 | + "biolink:Pathway", |
| 119 | + "biolink:PhenotypicFeature", |
| 120 | + "biolink:AnatomicalEntity", |
| 121 | + "biolink:Drug", |
| 122 | + "biolink:ChemicalEntity", |
| 123 | + ] |
| 124 | + |
| 125 | + for want in preferred: |
| 126 | + if want in generics and (want != "biolink:ChemicalEntity" or allow_chem): |
| 127 | + return want |
| 128 | + |
| 129 | + # Last-ditch: first canonicalizable thing |
| 130 | + for raw in generics: |
| 131 | + cat = canonicalize_class(raw) |
| 132 | + if cat: |
| 133 | + return cat |
| 134 | + |
| 135 | + return None |
| 136 | + |
| 137 | + |
| 138 | +# ── node ────────────────────────────────────────────────────────────────────── |
| 139 | + |
| 140 | +def node(state: TRAPIState) -> TRAPIState: |
| 141 | + """ |
| 142 | + nodes: |
| 143 | + n0: pinned CURIE |
| 144 | + n1: pinned CURIE |
| 145 | + paths: |
| 146 | + p0: subject=n0, object=n1, predicates=[biolink:related_to], |
| 147 | + constraints=[{'intermediate_categories':[<ONE class>]}] (only if chosen) |
| 148 | + """ |
| 149 | + src_nodes: Dict[str, Dict[str, Any]] = state.get("nodes", {}) or {} |
| 150 | + pinned = _pick_two_pinned(src_nodes) |
| 151 | + if len(pinned) < 2: |
| 152 | + logger.warning("Pathfinder-constrained needs 2 pinned nodes; found %d", len(pinned)) |
| 153 | + |
| 154 | + # Re-key as n0/n1 |
| 155 | + qg_nodes: Dict[str, Dict[str, Any]] = {} |
| 156 | + for i, (_, curie) in enumerate(pinned[:2]): |
| 157 | + qg_nodes[f"n{i}"] = {"ids": [curie]} |
| 158 | + |
| 159 | + p0: Dict[str, Any] = { |
| 160 | + "subject": "n0", |
| 161 | + "object": "n1", |
| 162 | + "predicates": [REQ_PRED], |
| 163 | + } |
| 164 | + |
| 165 | + picked = _pick_single_intermediate(state) |
| 166 | + if picked: |
| 167 | + p0["constraints"] = [{"intermediate_categories": [picked]}] |
| 168 | + logger.info("Added intermediate_categories constraint: %s", [picked]) |
| 169 | + else: |
| 170 | + logger.info("No intermediate category found; emitting unconstrained path.") |
| 171 | + |
| 172 | + state["output_json"] = { |
| 173 | + "message": { |
| 174 | + "query_graph": { |
| 175 | + "nodes": qg_nodes, |
| 176 | + "paths": {"p0": p0}, |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + return state |
0 commit comments