From fa5a0b43cff1c2a5ba101efdfbf577f0d8983944 Mon Sep 17 00:00:00 2001 From: Tiago Mateus Date: Wed, 18 Nov 2026 10:27:18 +0000 Subject: [PATCH 1/4] fix(experiments): return every variable when codes are shared Variable codes are only unique within a variable group, so an experiment can hold e.g. a Z and a W variable both coded "Volume". get_data keyed the result by code and skipped any variable whose file column matched a key already stored, so one of the two series was silently dropped. - Add key_by="id" to Experiment.get_data and Dataset.get_data to key the result by variable id, which is always unique. - Keep key_by="code" as the default and warn when codes are shared. - Skip duplicates by the result key instead of comparing the file column against variable codes. --- README.md | 5 ++ dhl_sdk/db_entities.py | 42 +++++++++++--- dhl_sdk/entities.py | 19 ++++++- tests/test_db_client.py | 118 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 172 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 9f8ab11..9f64f68 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,11 @@ experiment = next(experiments) # Once you find your experiment of interest, you can download the data of that experiment by referencing your `client` experiment_data = experiment.get_data(client) + +# Variable codes are only unique within a variable group, so an experiment can have e.g. a "Volume" Z Variable +# and a "Volume" W Variable. Key the data by variable id to get both, and map ids back to code and group if needed. +experiment_data = experiment.get_data(client, key_by="id") +labels = {v.id: (v.code, v.group.name) for v in experiment.variables} ``` diff --git a/dhl_sdk/db_entities.py b/dhl_sdk/db_entities.py index fb6b284..3028b50 100644 --- a/dhl_sdk/db_entities.py +++ b/dhl_sdk/db_entities.py @@ -15,6 +15,7 @@ import copy import csv +import warnings from abc import ABC, abstractmethod from enum import Enum from io import StringIO @@ -854,18 +855,25 @@ def validate_import(self, client: Client) -> bool: return True - def get_data(self, client: DataBaseClient) -> dict: + def get_data( + self, client: DataBaseClient, key_by: Literal["code", "id"] = "code" + ) -> dict: """Get experiment data from the API Parameters ---------- client : DataBaseClient Client to use to get the data, i.e., DataHowLabClient + key_by : Literal["code", "id"], optional + Key the result by variable code or by variable id, by default "code". + Variable codes are only unique within a variable group, so when two + variables of the experiment share a code, only the first is returned + with "code". Use "id" to get every variable. Returns ------- Dictionary with the data where: - key: variable code + key: variable code or variable id, depending on `key_by` value: a dictionary with the data for the variable, with "timestamps" and "values" keys Example: @@ -878,13 +886,14 @@ def get_data(self, client: DataBaseClient) -> dict: """ - return self._get_data_inner(client, self.variables, self.instances) + return self._get_data_inner(client, self.variables, self.instances, key_by) def _get_data_inner( self, client: DataBaseClient, variables: list[Variable], instances: list[UnresolvedInstance], + key_by: Literal["code", "id"] = "code", ) -> dict: """Internal method to get experiment data from the API given the instances source @@ -896,11 +905,13 @@ def _get_data_inner( list of Variables, giving the source for the data instances: list[UnresolvedInstance] list of UnresolvedInstances, giving the source for the data + key_by : Literal["code", "id"], optional + Key the result by variable code or by variable id, by default "code" Returns ------- Dictionary with the data where: - key: variable code + key: variable code or variable id, depending on `key_by` value: a dictionary with the data for the variable, with "timestamps" and "values" keys Example: @@ -913,6 +924,18 @@ def _get_data_inner( """ + if key_by not in ("code", "id"): + raise ValueError(f"key_by must be 'code' or 'id', got '{key_by}'") + + codes = [variable.code for variable in variables] + shared_codes = sorted({code for code in codes if codes.count(code) > 1}) + if key_by == "code" and shared_codes: + warnings.warn( + f"Experiment '{self.name}' has several variables with the code(s) " + f"{shared_codes}. Only the first variable with each code is returned. " + "Use key_by='id' to get all of them." + ) + cache = {} experiment_data = {} @@ -923,12 +946,12 @@ def _get_data_inner( else: response = cache[instance.fileId] - if instance.column in experiment_data: - continue - if response.headers["content-type"] == "application/json": + key = variable.code if key_by == "code" else variable.id + if key in experiment_data: + continue data = response.json() - experiment_data[variable.code] = data["timeseries"][instance.column] + experiment_data[key] = data["timeseries"][instance.column] elif response.headers["content-type"] == "text/csv": csv_data = list(csv.reader(StringIO(response.text))) @@ -942,7 +965,8 @@ def _get_data_inner( raise InvalidVariantException() data_rows = [row[1:] for row in csv_data] - experiment_data["spectra"] = { + key = "spectra" if key_by == "code" else variable.id + experiment_data[key] = { spectra_ids: ids, "values": data_rows, } diff --git a/dhl_sdk/entities.py b/dhl_sdk/entities.py index eca30dc..ee90c31 100644 --- a/dhl_sdk/entities.py +++ b/dhl_sdk/entities.py @@ -73,13 +73,23 @@ def __init__(self, **data): self._client = data["client"] # pylint: disable=protected-access - def get_data(self, client: DataBaseClient) -> list[dict]: + def get_data( + self, client: DataBaseClient, key_by: Literal["code", "id"] = "code" + ) -> list[dict]: """Get the data from the experiments + Parameters: + ----------- + client: DataBaseClient + Client to use to get the data, i.e., DataHowLabClient + key_by: Literal["code", "id"], optional + Key each experiment's data by variable code or by variable id, + by default "code". Use "id" when variables share a code. + Returns: -------- list[dict]: List with the experiment data organized by: - key: variable code + key: variable code or variable id, depending on `key_by` value: dictionary with 2 keys: - "values": list with the values - "timestamps": list with the timestamps for each value @@ -88,7 +98,10 @@ def get_data(self, client: DataBaseClient) -> list[dict]: run_data = [] for i, experiment in enumerate(self.experiments): data = experiment._get_data_inner( - client=client, variables=self.variables, instances=self.instances[i] + client=client, + variables=self.variables, + instances=self.instances[i], + key_by=key_by, ) run_data.append(data) diff --git a/tests/test_db_client.py b/tests/test_db_client.py index fc4095f..641a172 100644 --- a/tests/test_db_client.py +++ b/tests/test_db_client.py @@ -8,6 +8,7 @@ from dhl_sdk.client import DataHowLabClient from dhl_sdk.crud import Result from dhl_sdk.db_entities import ( + UnresolvedInstance, Experiment, File, FlowVariableReference, @@ -691,3 +692,120 @@ def test_experiment_request_body(self): }, }, ) + + +class TestExperimentGetData(unittest.TestCase): + def setUp(self): + self.volume_z = Variable.new( + code="Volume", + name="Initial volume", + description="", + variable_group="Z Variables", + variable_type=VariableNumeric(), + measurement_unit="mL", + ) + self.volume_z.id = "volume-z-id" + + self.volume_w = Variable.new( + code="Volume", + name="Volume", + description="", + variable_group="W Variables", + variable_type=VariableNumeric(), + measurement_unit="mL", + ) + self.volume_w.id = "volume-w-id" + + self.glucose = Variable.new( + code="Glc", + name="Glucose", + description="", + variable_group="X Variables", + variable_type=VariableNumeric(), + measurement_unit="g/L", + ) + self.glucose.id = "glc-id" + + product = Product.new("prod", "product 1", "product description") + product.id = "prod-id" + + self.experiment = Experiment( + name="exp", + description="", + product=product, + variables=[self.volume_z, self.volume_w, self.glucose], + instances=[ + {"column": "BRvol", "fileId": "file-1"}, + {"column": "Volume", "fileId": "file-1"}, + {"column": "Glc", "fileId": "file-1"}, + ], + ) + + timeseries = { + "BRvol": {"timestamps": [0], "values": [209.1]}, + "Volume": {"timestamps": [0, 1, 2], "values": [209.1, 200.4, 197.5]}, + "Glc": {"timestamps": [0, 1], "values": [5.0, 4.2]}, + } + self.download = patch.object( + File, + "download", + return_value=Mock( + headers={"content-type": "application/json"}, + json=lambda: {"timeseries": timeseries}, + ), + ).start() + self.addCleanup(patch.stopall) + self.client = Mock() + + def test_key_by_id_returns_every_variable(self): + data = self.experiment.get_data(self.client, key_by="id") + + self.assertEqual( + data, + { + "volume-z-id": {"timestamps": [0], "values": [209.1]}, + "volume-w-id": { + "timestamps": [0, 1, 2], + "values": [209.1, 200.4, 197.5], + }, + "glc-id": {"timestamps": [0, 1], "values": [5.0, 4.2]}, + }, + ) + self.download.assert_called_once() + + def test_key_by_code_keeps_first_shared_code_and_warns(self): + with self.assertWarnsRegex(UserWarning, r"\['Volume'\].*key_by='id'"): + data = self.experiment.get_data(self.client) + + self.assertEqual( + data, + { + "Volume": {"timestamps": [0], "values": [209.1]}, + "Glc": {"timestamps": [0, 1], "values": [5.0, 4.2]}, + }, + ) + + def test_key_by_code_returns_variable_whose_column_matches_another_code(self): + experiment = self.experiment.model_copy( + update={ + "variables": [self.glucose, self.volume_w], + "instances": [ + UnresolvedInstance(column="BRvol", fileId="file-1"), + UnresolvedInstance(column="Glc", fileId="file-1"), + ], + } + ) + + data = experiment.get_data(self.client) + + self.assertEqual( + data, + { + "Glc": {"timestamps": [0], "values": [209.1]}, + "Volume": {"timestamps": [0, 1], "values": [5.0, 4.2]}, + }, + ) + + def test_invalid_key_by_raises(self): + with self.assertRaises(ValueError): + self.experiment.get_data(self.client, key_by="name") From 987b7b4801dfe367d88c452e6b182e6de93fc6e6 Mon Sep 17 00:00:00 2001 From: Tiago Mateus Date: Wed, 18 Nov 2026 10:39:34 +0000 Subject: [PATCH 2/4] fix(variables): accept flow references without a measurement id lab-db stores measurementId on a flow reference as optional, and references that only point to a feed concentration exist. The SDK required it, so get_variables() failed with a ValidationError as soon as it reached such a variable. Make measurement_id optional when reading variables. Creating a new flow variable through the SDK still requires it: the import validator already rejects references without one, and a test now pins that. --- dhl_sdk/db_entities.py | 2 +- dhl_sdk/validators.py | 2 +- tests/test_db_client.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/dhl_sdk/db_entities.py b/dhl_sdk/db_entities.py index 3028b50..2368f4a 100644 --- a/dhl_sdk/db_entities.py +++ b/dhl_sdk/db_entities.py @@ -142,7 +142,7 @@ class FlowVariableReference(BaseModel): fraction_id: ID of fraction """ - measurement_id: str = Field(alias="measurementId") + measurement_id: Optional[str] = Field(default=None, alias="measurementId") concentration_id: Optional[str] = Field(default=None, alias="concentrationId") fraction_id: Optional[str] = Field(default=None, alias="fractionId") diff --git a/dhl_sdk/validators.py b/dhl_sdk/validators.py index 6547d12..37196b4 100644 --- a/dhl_sdk/validators.py +++ b/dhl_sdk/validators.py @@ -46,7 +46,7 @@ class Group(Protocol): class FlowReferences(Protocol): - measurement_id: str + measurement_id: Optional[str] concentration_id: Optional[str] fraction_id: Optional[str] diff --git a/tests/test_db_client.py b/tests/test_db_client.py index 641a172..69f5a63 100644 --- a/tests/test_db_client.py +++ b/tests/test_db_client.py @@ -416,6 +416,42 @@ def test_variable_request_flows(self): }, ) + def test_flow_variable_from_api_without_measurement_reference(self): + var = Variable( + id="feed-id", + code="FEED1", + name="Feed 1", + variant="flow", + flow={ + "type": "bolus", + "references": [ + {"measurementId": "meas-id-111"}, + {"concentrationId": "conc-id-222"}, + ], + }, + ) + + references = var.variant_details.references + self.assertEqual(references[0].measurement_id, "meas-id-111") + self.assertIsNone(references[1].measurement_id) + self.assertEqual(references[1].concentration_id, "conc-id-222") + + def test_new_flow_variable_without_measurement_reference_fails_validation(self): + var = Variable.new( + code="FEED1", + name="Feed 1", + description="description", + variable_group="Feeds/Flows", + variable_type=VariableFlow(type="bolus", references=[{}]), + measurement_unit="n", + ) + client = Mock() + client.get.return_value = Mock(headers={"x-total-count": "0"}) + + with patch.object(var._validator, "is_imported", return_value=False): + with self.assertRaisesRegex(ImportValidationException, "measurement_id"): + var._validator.validate(var, client) + class TestVariableRequests(unittest.TestCase): def setUp(self): From a605e4dd9d9b7929577122a9ae5c25a7ffe104f1 Mon Sep 17 00:00:00 2001 From: Tiago Mateus Date: Wed, 18 Nov 2026 10:45:06 +0000 Subject: [PATCH 3/4] chore(release): bump version to 0.3.5 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 29f8028..037102a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "datahowlab-sdk" -version = "0.3.3" +version = "0.3.5" description = "The DataHowLab SDK for Python" license = "Apache-2.0" authors = ["DataHow "] From 464e274a467d8cf08b3785e9b361cb7d173d3b2f Mon Sep 17 00:00:00 2001 From: Tiago Mateus Date: Thu, 19 Nov 2026 08:19:50 +0000 Subject: [PATCH 4/4] fix(experiments): warn once per get_data call and document the spectra key Review follow-up. - Dataset.get_data() warned once per experiment about the same shared codes, and the warning pointed at the SDK instead of the caller. The check now runs once in each public get_data() and passes stacklevel. - With key_by="id", spectra data is keyed by the spectrum variable id instead of "spectra". Say so in both docstrings and the README, and cover both modes with a text/csv response. --- README.md | 1 + dhl_sdk/_utils.py | 14 ++++++++ dhl_sdk/db_entities.py | 18 ++++------ dhl_sdk/entities.py | 7 +++- tests/test_db_client.py | 74 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 9f64f68..1bc5c8a 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ experiment_data = experiment.get_data(client) # Variable codes are only unique within a variable group, so an experiment can have e.g. a "Volume" Z Variable # and a "Volume" W Variable. Key the data by variable id to get both, and map ids back to code and group if needed. +# With key_by="id", spectra data is keyed by the spectrum variable id instead of "spectra". experiment_data = experiment.get_data(client, key_by="id") labels = {v.id: (v.code, v.group.name) for v in experiment.variables} ``` diff --git a/dhl_sdk/_utils.py b/dhl_sdk/_utils.py index 958332f..016ac42 100644 --- a/dhl_sdk/_utils.py +++ b/dhl_sdk/_utils.py @@ -1,5 +1,6 @@ """This module contains generic utility functions used in the SDK""" +import warnings from enum import Enum import urllib.parse as urlparse from datetime import datetime @@ -200,3 +201,16 @@ def is_date_in_format(date_string, date_format): return True except ValueError: return False + + +def warn_on_shared_codes(variables: list, owner: str) -> None: + """Warn that only the first variable of each shared code is returned when keyed by code""" + codes = [variable.code for variable in variables] + shared_codes = sorted({code for code in codes if codes.count(code) > 1}) + if shared_codes: + warnings.warn( + f"{owner} has several variables with the code(s) {shared_codes}. " + "Only the first variable with each code is returned. " + "Use key_by='id' to get all of them.", + stacklevel=3, + ) diff --git a/dhl_sdk/db_entities.py b/dhl_sdk/db_entities.py index 2368f4a..315f92e 100644 --- a/dhl_sdk/db_entities.py +++ b/dhl_sdk/db_entities.py @@ -15,7 +15,6 @@ import copy import csv -import warnings from abc import ABC, abstractmethod from enum import Enum from io import StringIO @@ -34,7 +33,7 @@ VARIABLES_URL, ) -from dhl_sdk._utils import VariableGroupCodes +from dhl_sdk._utils import VariableGroupCodes, warn_on_shared_codes from dhl_sdk.crud import Client, CRUDClient, DataBaseClient from dhl_sdk.exceptions import ( ImportValidationException, @@ -868,7 +867,8 @@ def get_data( Key the result by variable code or by variable id, by default "code". Variable codes are only unique within a variable group, so when two variables of the experiment share a code, only the first is returned - with "code". Use "id" to get every variable. + with "code". Use "id" to get every variable. With "id", spectra data is + keyed by the spectrum variable id instead of "spectra". Returns ------- @@ -886,6 +886,9 @@ def get_data( """ + if key_by == "code": + warn_on_shared_codes(self.variables, f"Experiment '{self.name}'") + return self._get_data_inner(client, self.variables, self.instances, key_by) def _get_data_inner( @@ -927,15 +930,6 @@ def _get_data_inner( if key_by not in ("code", "id"): raise ValueError(f"key_by must be 'code' or 'id', got '{key_by}'") - codes = [variable.code for variable in variables] - shared_codes = sorted({code for code in codes if codes.count(code) > 1}) - if key_by == "code" and shared_codes: - warnings.warn( - f"Experiment '{self.name}' has several variables with the code(s) " - f"{shared_codes}. Only the first variable with each code is returned. " - "Use key_by='id' to get all of them." - ) - cache = {} experiment_data = {} diff --git a/dhl_sdk/entities.py b/dhl_sdk/entities.py index ee90c31..7eeb72b 100644 --- a/dhl_sdk/entities.py +++ b/dhl_sdk/entities.py @@ -46,6 +46,7 @@ Predictions, PredictionResponse, get_id_list, + warn_on_shared_codes, ) from dhl_sdk.crud import Client, CRUDClient, DataBaseClient, Result from dhl_sdk.db_entities import Experiment, Variable, UnresolvedInstance @@ -84,7 +85,8 @@ def get_data( Client to use to get the data, i.e., DataHowLabClient key_by: Literal["code", "id"], optional Key each experiment's data by variable code or by variable id, - by default "code". Use "id" when variables share a code. + by default "code". Use "id" when variables share a code. With "id", + spectra data is keyed by the spectrum variable id instead of "spectra". Returns: -------- @@ -95,6 +97,9 @@ def get_data( - "timestamps": list with the timestamps for each value """ + if key_by == "code": + warn_on_shared_codes(self.variables, f"Dataset '{self.name}'") + run_data = [] for i, experiment in enumerate(self.experiments): data = experiment._get_data_inner( diff --git a/tests/test_db_client.py b/tests/test_db_client.py index 69f5a63..38d6ce0 100644 --- a/tests/test_db_client.py +++ b/tests/test_db_client.py @@ -1,5 +1,6 @@ # pylint: disable=missing-docstring import unittest +import warnings from unittest.mock import Mock, call, patch from pydantic import ValidationError @@ -19,6 +20,7 @@ VariableLogical, VariableNumeric, ) +from dhl_sdk.entities import Dataset from dhl_sdk.exceptions import ImportValidationException, NewEntityException from dhl_sdk.validators import ExperimentFileValidator @@ -845,3 +847,75 @@ def test_key_by_code_returns_variable_whose_column_matches_another_code(self): def test_invalid_key_by_raises(self): with self.assertRaises(ValueError): self.experiment.get_data(self.client, key_by="name") + + def test_shared_code_warning_points_at_the_caller(self): + with self.assertWarns(UserWarning) as caught: + self.experiment.get_data(self.client) + + self.assertEqual(caught.filename, __file__) + + def test_dataset_warns_once_for_shared_codes(self): + dataset = Dataset( + id="dataset-id", + name="dataset", + description="", + variables=self.experiment.variables, + experiments=[self.experiment, self.experiment], + instances=[self.experiment.instances, self.experiment.instances], + client=self.client, + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + data = dataset.get_data(self.client) + + self.assertEqual(len(data), 2) + self.assertEqual(len(caught), 1) + self.assertIn("Dataset 'dataset'", str(caught[0].message)) + self.assertEqual(caught[0].filename, __file__) + + +class TestExperimentGetSpectraData(unittest.TestCase): + def setUp(self): + spectrum = Variable( + id="spectrum-id", + code="Spectrum", + name="Spectrum", + variant="spectrum", + spectrum={"xAxis": {"dimension": 2}}, + ) + product = Product.new("prod", "product 1", "product description") + product.id = "prod-id" + + self.experiment = Experiment( + name="exp", + description="", + product=product, + variables=[spectrum], + instances=[{"column": "1", "fileId": "spectra-file"}], + ) + + patch.object( + File, + "download", + return_value=Mock( + headers={"content-type": "text/csv"}, text="10,0.1,0.2\n20,0.3,0.4" + ), + ).start() + self.addCleanup(patch.stopall) + self.client = Mock() + self.spectra = { + "timestamps": ["10", "20"], + "values": [["0.1", "0.2"], ["0.3", "0.4"]], + } + + def test_key_by_code_keys_spectra_as_spectra(self): + self.assertEqual( + self.experiment.get_data(self.client), {"spectra": self.spectra} + ) + + def test_key_by_id_keys_spectra_by_variable_id(self): + self.assertEqual( + self.experiment.get_data(self.client, key_by="id"), + {"spectrum-id": self.spectra}, + )