Skip to content

Commit

Permalink
wip: update vrs/core models
Browse files Browse the repository at this point in the history
  • Loading branch information
korikuzma committed Dec 20, 2024
1 parent 9690f95 commit 4d51227
Show file tree
Hide file tree
Showing 5 changed files with 428 additions and 330 deletions.
4 changes: 2 additions & 2 deletions src/therapy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def custom_openapi() -> dict:
"Return merged strongest-match concept for query string " "provided by user."
)
merged_matches_summary = (
"Given query, provide merged normalized record as a " "Therapeutic Agent."
"Given query, provide merged normalized record as a Therapy Mappable Concept."
)
merged_response_descr = "A response to a validly-formed query."
normalize_q_descr = "Therapy to normalize."
Expand Down Expand Up @@ -148,7 +148,7 @@ def normalize(
:param q: therapy search term
:param bool infer_namespace: if True, try to infer namespace from query term.
:returns: JSON response with matching normalized record provided as a
Therapeutic Agent, and source metadata
Therapy Mappable Concept, and source metadata
"""
try:
response = query_handler.normalize(html.unescape(q), infer_namespace)
Expand Down
59 changes: 31 additions & 28 deletions src/therapy/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Any, TypeVar

from botocore.exceptions import ClientError
from ga4gh.core import domain_models, entity_models
from ga4gh.core.models import MappableConcept, ConceptMapping, Coding, code, Extension, Relation
from uvicorn.config import logger

from therapy import NAMESPACE_LUIS, PREFIX_LOOKUP, SOURCES
Expand Down Expand Up @@ -350,10 +350,10 @@ def _add_merged_meta(self, response: NormalizationService) -> NormalizationServi
:return: completed response object.
"""
sources_meta = {}
therapeutic_agent = response.therapeutic_agent
therapy = response.therapy
sources = [response.normalized_id.split(":")[0]] # type: ignore[union-attr]
if therapeutic_agent.mappings: # type: ignore[union-attr]
sources += [m.coding.system for m in therapeutic_agent.mappings] # type: ignore[union-attr]
if therapy.mappings: # type: ignore[union-attr]
sources += [m.coding.system for m in therapy.mappings] # type: ignore[union-attr]

for src in sources:
try:
Expand All @@ -377,42 +377,44 @@ def _record_order(self, record: dict) -> tuple[int, str]:
source_rank = SourcePriority[src]
return source_rank, record["concept_id"]

def _add_therapeutic_agent(
def _add_therapy(
self,
response: NormalizationService,
record: dict,
match_type: MatchType,
) -> NormalizationService:
"""Format received DB record as therapeutic agent and update response object.
"""Format received DB record as Mappable Concept and update response object.
:param NormalizationService response: in-progress response object
:param Dict record: record as stored in DB
:param str query: query string from user request
:param MatchType match_type: type of match achieved
:return: completed response object ready to return to user
"""
therapeutic_agent_obj = domain_models.TherapeuticAgent(
id=f"normalize.therapy.{record['concept_id']}", label=record.get("label")
therapy_obj = MappableConcept(
id=f"normalize.therapy.{record['concept_id']}",
conceptType="Therapy",
label=record.get("label")
)

source_ids = record.get("xrefs", []) + record.get("associated_with", [])
mappings = []
for source_id in source_ids:
system, code = source_id.split(":")
system, source_code = source_id.split(":")
mappings.append(
entity_models.ConceptMapping(
coding=entity_models.Coding(
code=entity_models.Code(code), system=system.lower()
ConceptMapping(
coding=Coding(
code=code(source_code), system=system.lower()
),
relation=entity_models.Relation.RELATED_MATCH,
relation=Relation.RELATED_MATCH,
)
)
if mappings:
therapeutic_agent_obj.mappings = mappings
therapy_obj.mappings = mappings

extensions = []
if "aliases" in record:
therapeutic_agent_obj.alternativeLabels = record["aliases"]
extensions.append(Extension(name="aliases", value=record["aliases"]))

extensions = []
if any(
filter(
lambda f: f in record,
Expand All @@ -435,49 +437,50 @@ def _add_therapeutic_agent(
indication = self._get_indication(ind_db)

if indication.normalized_disease_id:
system, code = indication.normalized_disease_id.split(":")
system, source_code = indication.normalized_disease_id.split(":")
mappings = [
entity_models.ConceptMapping(
coding=entity_models.Coding(
code=entity_models.Code(code), system=system.lower()
ConceptMapping(
coding=Coding(
code=code(source_code), system=system.lower()
),
relation=entity_models.Relation.RELATED_MATCH,
relation=Relation.RELATED_MATCH,
)
]
else:
mappings = []
ind_disease_obj = domain_models.Disease(
ind_disease_obj = MappableConcept(
id=indication.disease_id,
conceptType="Disease",
label=indication.disease_label,
mappings=mappings or None,
)

if indication.supplemental_info:
ind_disease_obj.extensions = [
entity_models.Extension(name=k, value=v)
Extension(name=k, value=v)
for k, v in indication.supplemental_info.items()
]
inds_list.append(ind_disease_obj.model_dump(exclude_none=True))
if inds_list:
approv_value["has_indication"] = inds_list

approv = entity_models.Extension(
approv = Extension(
name="regulatory_approval", value=approv_value
)
extensions.append(approv)

trade_names = record.get("trade_names")
if trade_names:
extensions.append(
entity_models.Extension(name="trade_names", value=trade_names)
Extension(name="trade_names", value=trade_names)
)

if extensions:
therapeutic_agent_obj.extensions = extensions
therapy_obj.extensions = extensions

response.match_type = match_type
response.normalized_id = record["concept_id"]
response.therapeutic_agent = therapeutic_agent_obj
response.therapy = therapy_obj
return self._add_merged_meta(response)

def _resolve_merge(
Expand Down Expand Up @@ -537,7 +540,7 @@ def normalize(self, query: str, infer: bool = True) -> NormalizationService:
response = NormalizationService(**self._prepare_normalized_response(query))

return self._perform_normalized_lookup(
response, query, infer, self._add_therapeutic_agent
response, query, infer, self._add_therapy
)

def _construct_drug_match(self, record: dict) -> Therapy:
Expand Down
8 changes: 4 additions & 4 deletions src/therapy/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from enum import Enum, IntEnum
from typing import Any, Literal

from ga4gh.core import domain_models
from ga4gh.core.models import MappableConcept
from pydantic import BaseModel, ConfigDict, StrictBool, constr

from therapy import __version__
Expand Down Expand Up @@ -485,7 +485,7 @@ class NormalizationService(BaseNormalizationService):
"""Response containing one or more merged records and source data."""

normalized_id: str | None = None
therapeutic_agent: domain_models.TherapeuticAgent | None = None
therapy: MappableConcept | None = None
source_meta_: dict[SourceName, SourceMeta] | None = None

model_config = ConfigDict(
Expand All @@ -495,8 +495,8 @@ class NormalizationService(BaseNormalizationService):
"warnings": None,
"match_type": 80,
"normalized_id": "rxcui:2555",
"therapeutic_agent": {
"type": "TherapeuticAgent",
"therapy": {
"type": "Therapy",
"id": "normalize.therapy.rxcui:2555",
"label": "cisplatin",
"mappings": [
Expand Down
Loading

0 comments on commit 4d51227

Please sign in to comment.