Skip to content
Merged
94 changes: 87 additions & 7 deletions nmdc_runtime/site/repair/database_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ def __init__(
:param study_id: NMDC study ID for which the missing records need to be added.
:param gold_nmdc_instrument_map_df: A dataframe originally stored as a TSV mapping file in the
NMDC schema repo, which maps GOLD instrument IDs to IDs of NMDC instrument_set records.
:param include_field_site_info: Whether to include field research site information when
translating GOLD data. When True, the GoldStudyTranslator will create
`nmdc:FieldResearchSite` records and associate them with biosamples. Defaults to False.
:param enable_biosample_filtering: Whether to filter biosamples based on their
`sequencingStrategy` (only keeping "Metagenome" or "Metatranscriptome") and associated
project `projectStatus`. When False, all biosamples are included regardless of sequencing
strategy or project status. Defaults to True.
"""

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to main logic being added in this PR. I just noticed that these params were missing documentation in the docstring so added them here.

self.runtime_api_user_client = runtime_api_user_client
self.runtime_api_site_client = runtime_api_site_client
Expand Down Expand Up @@ -84,7 +91,18 @@ class which is responsible for making data_generation_set records.

all_gold_biosamples = []
all_gold_projects = []
existing_gold_project_ids = set()
for biosample in biosample_set:
# Check for existing DataGeneration records linked to this biosample
# using the /nmdcschema/linked_instances endpoint, which is more
# efficient than fetching all DataGeneration records for the study.
linked_data_generations = self.runtime_api_user_client.get_linked_data_generation_records_for_biosample(
biosample["id"]
)
for dg in linked_data_generations:
for gold_id in dg.get("gold_sequencing_project_identifiers", []):
existing_gold_project_ids.add(gold_id.replace("gold:", ""))

gold_biosample_identifiers = biosample.get("gold_biosample_identifiers")
if gold_biosample_identifiers:
for gold_biosample_id in gold_biosample_identifiers:
Expand All @@ -108,6 +126,24 @@ class which is responsible for making data_generation_set records.
filtered_biosamples = gold_study_translator.biosamples
filtered_projects = gold_study_translator.projects

# Filter out GOLD projects that already have DataGeneration records in the database
filtered_projects = [
project
for project in filtered_projects
if project["projectGoldId"] not in existing_gold_project_ids
]

# Deduplicate projects by projectGoldId — the same GOLD project can appear multiple
# times in all_gold_projects when a biosample has multiple gold_biosample_identifiers
# or when multiple NMDC biosamples share the same GOLD biosample.
seen_project_ids = set()
filtered_projects = [
project
for project in filtered_projects
if project["projectGoldId"] not in seen_project_ids
and not seen_project_ids.add(project["projectGoldId"])
]

gold_project_ids = [project["projectGoldId"] for project in filtered_projects]
nmdc_nucleotide_sequencing_ids = self.runtime_api_site_client.mint_id(
"nmdc:NucleotideSequencing", len(gold_project_ids)
Expand All @@ -116,19 +152,50 @@ class which is responsible for making data_generation_set records.
zip(gold_project_ids, nmdc_nucleotide_sequencing_ids)
)

gold_to_nmdc_biosample_ids = {}

# Build a map from GOLD biosample ID → has_input ID for DataGeneration records
# by traversing the Pooling → LibraryPreparation chain. If a Pooling process
# exists for the biosample, use the ProcessedSample output of LibraryPreparation
# (if present) or of Pooling directly. If no Pooling exists, fall back to the
# biosample itself. Only one API call is made per unique GOLD biosample ID since
# multiple NMDC biosamples can share the same GOLD biosample ID when pooled.
gold_biosample_to_has_input_id = {}
seen_gold_biosample_ids = set()
for biosample in biosample_set:
gold_ids = biosample.get("gold_biosample_identifiers", [])
for gold_id in gold_ids:
gold_id_stripped = gold_id.replace("gold:", "")
gold_to_nmdc_biosample_ids[gold_id_stripped] = biosample["id"]
if gold_id_stripped in seen_gold_biosample_ids:
continue
seen_gold_biosample_ids.add(gold_id_stripped)

pooling_records = (
self.runtime_api_user_client.get_linked_pooling_for_biosample(
biosample["id"]
)
)
if pooling_records:
pooling_output_id = pooling_records[0]["has_output"][0]
lib_prep_records = self.runtime_api_user_client.get_linked_library_preparation_for_processed_sample(
pooling_output_id
)
if lib_prep_records:
has_input_id = lib_prep_records[0]["has_output"][0]
else:
has_input_id = pooling_output_id
else:
has_input_id = biosample["id"]

gold_biosample_to_has_input_id[gold_id_stripped] = has_input_id

provenance_metadata = gold_study_translator._get_provenance_metadata(
source_system_of_record=nmdc.SourceSystemEnum.GOLD.text,
)

database.data_generation_set = []
# Similar to the logic in GoldStudyTranslator, the number of nmdc:NucleotideSequencing records
# created is based on the number of GOLD sequencing projects
for project in filtered_projects:
# map the projectGoldId to the NMDC biosample ID
# map the projectGoldId to the has_input ID (ProcessedSample or Biosample)
biosample_gold_id = next(
(
biosample["biosampleGoldId"]
Expand All @@ -142,19 +209,27 @@ class which is responsible for making data_generation_set records.
)

if biosample_gold_id:
nmdc_biosample_id = gold_to_nmdc_biosample_ids.get(biosample_gold_id)
if nmdc_biosample_id:
has_input_id = gold_biosample_to_has_input_id.get(biosample_gold_id)
if has_input_id:
database.data_generation_set.append(
gold_study_translator._translate_nucleotide_sequencing(
project,
nmdc_nucleotide_sequencing_id=gold_project_to_nmdc_nucleotide_sequencing_ids[
project["projectGoldId"]
],
nmdc_biosample_id=nmdc_biosample_id,
nmdc_biosample_id=has_input_id,
nmdc_study_id=self.study_id,
provenance_metadata=provenance_metadata,
)
)

database.data_generation_set = [
record
for record in database.data_generation_set
if str(record.processing_institution)
== nmdc.ProcessingInstitutionEnum.JGI.text
]

return database

def generate_biosample_set_from_gold_api_for_study(self) -> nmdc.Database:
Expand Down Expand Up @@ -235,6 +310,10 @@ def generate_biosample_set_from_gold_api_for_study(self) -> nmdc.Database:
).json()
gold_to_nmdc_biosample_ids = dict(zip(gold_biosample_ids, nmdc_biosample_ids))

provenance_metadata = gold_study_translator._get_provenance_metadata(
source_system_of_record=nmdc.SourceSystemEnum.GOLD.text,
)

database.biosample_set = [
gold_study_translator._translate_biosample(
biosample,
Expand All @@ -243,6 +322,7 @@ def generate_biosample_set_from_gold_api_for_study(self) -> nmdc.Database:
],
nmdc_study_id=self.study_id,
nmdc_field_site_id=None,
provenance_metadata=provenance_metadata,
)
for biosample in translated_biosamples
]
Expand Down
66 changes: 66 additions & 0 deletions nmdc_runtime/site/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,72 @@ def get_biosamples_for_study(self, study_id: str):
response.raise_for_status()
return response.json()["resources"]

def get_linked_data_generation_records_for_biosample(self, biosample_id: str):
"""Fetch DataGeneration records linked to a given biosample using the
/nmdcschema/linked_instances endpoint.

Note: This method was added for use by the DatabaseUpdater class
(nmdc_runtime.site.repair.database_updater) to check for existing
DataGeneration records before creating new ones.

:param biosample_id: NMDC biosample ID (e.g. "nmdc:bsm-11-abc123").
:return: List of hydrated DataGeneration records linked to the biosample.
"""
response = self.request(
"GET",
"/nmdcschema/linked_instances",
{
"ids": biosample_id,
"types": "nmdc:DataGeneration",
"hydrate": True,
"max_page_size": 9999,
},
)
response.raise_for_status()
return response.json()["resources"]

def get_linked_pooling_for_biosample(self, biosample_id: str):
"""Fetch Pooling records linked to a given biosample using the
/nmdcschema/linked_instances endpoint.

:param biosample_id: NMDC biosample ID (e.g. "nmdc:bsm-11-abc123").
:return: List of hydrated Pooling records linked to the biosample.
"""
response = self.request(
"GET",
"/nmdcschema/linked_instances",
{
"ids": biosample_id,
"types": "nmdc:Pooling",
"hydrate": True,
"max_page_size": 9999,
},
)
response.raise_for_status()
return response.json()["resources"]

def get_linked_library_preparation_for_processed_sample(
self, processed_sample_id: str
):
"""Fetch LibraryPreparation records linked to a given processed sample
using the /nmdcschema/linked_instances endpoint.

:param processed_sample_id: NMDC processed sample ID.
:return: List of hydrated LibraryPreparation records linked to the processed sample.
"""
response = self.request(
"GET",
"/nmdcschema/linked_instances",
{
"ids": processed_sample_id,
"types": "nmdc:LibraryPreparation",
"hydrate": True,
"max_page_size": 9999,
},
)
response.raise_for_status()
return response.json()["resources"]

def get_data_generation_records_for_study(self, study_id: str):
# TODO: same as above, we are using a large max_page_size to avoid pagination.
response = self.request(
Expand Down
9 changes: 9 additions & 0 deletions tests/test_data/test_database_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from unittest.mock import MagicMock, patch

from nmdc_schema import nmdc

from nmdc_runtime.site.repair.database_updater import DatabaseUpdater


Expand Down Expand Up @@ -61,6 +63,12 @@ def test_generate_data_generation_set_records_from_gold_api_for_study(
}
]

# No existing DataGeneration records linked to this biosample
mock_runtime_api_user_client.get_linked_data_generation_records_for_biosample.return_value = (
[]
)
mock_runtime_api_user_client.get_linked_pooling_for_biosample.return_value = []

mock_gold_api_client.fetch_biosample_by_biosample_id.return_value = [
{
"biosampleGoldId": "Gb0150488",
Expand Down Expand Up @@ -90,6 +98,7 @@ def test_generate_data_generation_set_records_from_gold_api_for_study(
MockGoldStudyTranslator.return_value._translate_nucleotide_sequencing.return_value = MagicMock(
id="nmdc:dgns-00-12345678",
biosample_id="nmdc:bsm-11-q59jb831",
processing_institution=nmdc.ProcessingInstitutionEnum.JGI.text,
)
mint_id_mock = MagicMock()
mint_id_mock.json.return_value = test_minter("nmdc:NucleotideSequencing", 1)
Expand Down
Loading