Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@ 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.
# 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}
```


Expand Down
14 changes: 14 additions & 0 deletions dhl_sdk/_utils.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
)
40 changes: 29 additions & 11 deletions dhl_sdk/db_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,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,
Expand Down Expand Up @@ -141,7 +141,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")

Expand Down Expand Up @@ -854,18 +854,26 @@ 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. With "id", spectra data is
keyed by the spectrum variable id instead of "spectra".

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:
Expand All @@ -878,13 +886,17 @@ def get_data(self, client: DataBaseClient) -> dict:

"""

return self._get_data_inner(client, self.variables, self.instances)
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(
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

Expand All @@ -896,11 +908,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:
Expand All @@ -913,6 +927,9 @@ def _get_data_inner(

"""

if key_by not in ("code", "id"):
raise ValueError(f"key_by must be 'code' or 'id', got '{key_by}'")

cache = {}
experiment_data = {}

Expand All @@ -923,12 +940,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)))
Expand All @@ -942,7 +959,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,
}
Expand Down
24 changes: 21 additions & 3 deletions dhl_sdk/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -73,22 +74,39 @@ 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. With "id",
spectra data is keyed by the spectrum variable id instead of "spectra".

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
"""

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(
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)

Expand Down
2 changes: 1 addition & 1 deletion dhl_sdk/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 <feedback@datahow.ch>"]
Expand Down
Loading
Loading