metaseed-brapi 0.78.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ # Python
2
+ __pycache__/
3
+
4
+ # Generated version file (hatch-vcs)
5
+ src/metaseed/_version.py
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+ .Python
10
+ build/
11
+ develop-eggs/
12
+ dist/
13
+ downloads/
14
+ eggs/
15
+ .eggs/
16
+ lib/
17
+ lib64/
18
+ parts/
19
+ sdist/
20
+ var/
21
+ wheels/
22
+ *.egg-info/
23
+ .installed.cfg
24
+ *.egg
25
+
26
+ # Virtual environments
27
+ .venv/
28
+ venv/
29
+ ENV/
30
+
31
+ # UV
32
+ .uv/
33
+ # uv.lock is committed for reproducible dev/CI builds and Dependabot scanning.
34
+
35
+ # Testing
36
+ .pytest_cache/
37
+ .coverage
38
+ htmlcov/
39
+ .tox/
40
+ .nox/
41
+
42
+ # IDE
43
+ .idea/
44
+ .vscode/
45
+ *.swp
46
+ *.swo
47
+ *~
48
+
49
+ # Jupyter
50
+ .ipynb_checkpoints/
51
+
52
+ # Documentation
53
+ site/
54
+
55
+ # OS
56
+ .DS_Store
57
+ Thumbs.db
58
+
59
+ # Environment
60
+ .env
61
+ .env.local
62
+ *.local
63
+
64
+ # Logs
65
+ *.log
66
+
67
+ # Type checking
68
+ .mypy_cache/
69
+ .pytype/
70
+ docs/REVIEW.md
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.5
2
+ Name: metaseed-brapi
3
+ Version: 0.78.0
4
+ Summary: The BrAPI v2: import trials and studies from a BrAPI server into the MIAPPE profile, and export BrAPI JSON, for metaseed
5
+ Project-URL: Homepage, https://sorenwacker.github.io/metaseed/
6
+ Project-URL: Repository, https://github.com/sorenwacker/metaseed
7
+ Author: Sören Wacker
8
+ License: MIT
9
+ Keywords: brapi,fair-data,metadata
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: httpx<1,>=0.27
16
+ Requires-Dist: metaseed-profiles==0.78.0
17
+ Requires-Dist: metaseed==0.78.0
18
+ Description-Content-Type: text/markdown
19
+
20
+ # metaseed-brapi
21
+
22
+ The BrAPI adapter for [metaseed](https://pypi.org/project/metaseed/): import trials and studies from a BrAPI server into the MIAPPE profile, and export BrAPI JSON. Install it through metaseed's extra:
23
+
24
+ ```bash
25
+ pip install 'metaseed[brapi]'
26
+ ```
27
+
28
+ It is imported as `metaseed.brapi`, requires `metaseed` at its own version, and is described in [Integration Adapters](https://sorenwacker.github.io/metaseed/architecture/integration-adapters/) and [ADR 007](https://sorenwacker.github.io/metaseed/architecture/decisions/007-profiles-and-adapters-are-plugins/).
@@ -0,0 +1,9 @@
1
+ # metaseed-brapi
2
+
3
+ The BrAPI adapter for [metaseed](https://pypi.org/project/metaseed/): import trials and studies from a BrAPI server into the MIAPPE profile, and export BrAPI JSON. Install it through metaseed's extra:
4
+
5
+ ```bash
6
+ pip install 'metaseed[brapi]'
7
+ ```
8
+
9
+ It is imported as `metaseed.brapi`, requires `metaseed` at its own version, and is described in [Integration Adapters](https://sorenwacker.github.io/metaseed/architecture/integration-adapters/) and [ADR 007](https://sorenwacker.github.io/metaseed/architecture/decisions/007-profiles-and-adapters-are-plugins/).
@@ -0,0 +1,24 @@
1
+ """Pin a plugin's metaseed dependencies to its own version at build time (ADR 007).
2
+
3
+ Every distribution under ``packages/`` carries this same file; a test keeps
4
+ the copies identical.
5
+ """
6
+
7
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
8
+
9
+
10
+ class PinToRelease(MetadataHookInterface):
11
+ """Set the dependencies from ``[tool.hatch.metadata.hooks.custom]``.
12
+
13
+ ``pinned`` names the distributions required at exactly the version this
14
+ build carries (``metaseed`` when omitted); ``dependencies`` lists the others,
15
+ each bounded below its next major version.
16
+ """
17
+
18
+ def update(self, metadata: dict) -> None:
19
+ """Write ``dependencies`` from the version hatch-vcs derived from the tag."""
20
+ version = metadata["version"]
21
+ pinned = self.config.get("pinned", ["metaseed"])
22
+ metadata["dependencies"] = [f"{name}=={version}" for name in pinned] + list(
23
+ self.config.get("dependencies", [])
24
+ )
@@ -0,0 +1,50 @@
1
+ [project]
2
+ name = "metaseed-brapi"
3
+ # The version comes from the repository's v* tag, shared with metaseed; the
4
+ # dependencies are written by hatch_build.py, which pins metaseed to that same
5
+ # version (ADR 007).
6
+ dynamic = ["version", "dependencies"]
7
+ description = "The BrAPI v2: import trials and studies from a BrAPI server into the MIAPPE profile, and export BrAPI JSON, for metaseed"
8
+ readme = "README.md"
9
+ requires-python = ">=3.11"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Sören Wacker" }]
12
+ keywords = ["metadata", "fair-data", "brapi"]
13
+ classifiers = [
14
+ "Intended Audience :: Science/Research",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://sorenwacker.github.io/metaseed/"
22
+ Repository = "https://github.com/sorenwacker/metaseed"
23
+
24
+ [build-system]
25
+ requires = ["hatchling", "hatch-vcs"]
26
+ build-backend = "hatchling.build"
27
+
28
+ [tool.hatch.version]
29
+ source = "vcs"
30
+
31
+ [tool.hatch.version.raw-options]
32
+ root = "../.."
33
+ local_scheme = "no-local-version"
34
+
35
+ [tool.hatch.metadata.hooks.custom]
36
+ pinned = ["metaseed", "metaseed-profiles"]
37
+ dependencies = ["httpx>=0.27,<1"]
38
+
39
+ # The package keeps its import path, metaseed.brapi: this distribution installs
40
+ # metaseed/brapi/ and no metaseed/__init__.py of its own.
41
+ [tool.hatch.build.targets.wheel]
42
+ only-include = ["src/metaseed/brapi"]
43
+ sources = ["src"]
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ only-include = ["src/metaseed/brapi", "README.md", "pyproject.toml", "hatch_build.py"]
47
+
48
+ [tool.uv.sources]
49
+ metaseed = { workspace = true }
50
+ metaseed-profiles = { workspace = true }
@@ -0,0 +1,249 @@
1
+ """BrAPI (Breeding API) importer.
2
+
3
+ Fetches plant-breeding metadata from any [BrAPI](https://brapi.org) v2 server and
4
+ maps it into a ``miappe``-profile dataset. Data files are referenced via their
5
+ URLs, never downloaded. The address names what to import: the server's base
6
+ URL for every study it holds, a trial's address for that trial's studies, or a
7
+ study's address for that one study.
8
+
9
+ >>> from metaseed.brapi import import_brapi
10
+ >>> base = "https://test-server.brapi.org/brapi/v2"
11
+ >>> client = import_brapi(base) # needs metaseed[brapi]
12
+ >>> trial = import_brapi(f"{base}/trials/trial1")
13
+ >>> client.validate()
14
+
15
+ ``build_dataset`` (the pure mapper) is importable without the ``metaseed[brapi]``
16
+ extra; ``import_brapi`` needs ``httpx``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+ from typing import TYPE_CHECKING, Any
23
+
24
+ from metaseed.brapi.export import to_brapi
25
+ from metaseed.brapi.mapper import build_dataset
26
+ from metaseed.provenance import creators_from, imported_now, normalize_license
27
+
28
+ if TYPE_CHECKING:
29
+ from metaseed.api.client import MetaseedClient
30
+ from metaseed.brapi.client import BrapiClient
31
+
32
+ __all__ = ["BrapiAddress", "build_dataset", "import_brapi", "parse_address", "to_brapi"]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class BrapiAddress:
37
+ """What a BrAPI address names: the server, or one trial or study on it."""
38
+
39
+ base_url: str
40
+ trial_db_id: str | None = None
41
+ study_db_id: str | None = None
42
+
43
+
44
+ def parse_address(address: str) -> BrapiAddress:
45
+ """Read a server base URL, a trial's address or a study's address.
46
+
47
+ A trial's address is ``<base>/trials/<trialDbId>`` and a study's
48
+ ``<base>/studies/<studyDbId>``, with the identifier as the server spells
49
+ it in a URL. Any other resource below the base URL is refused: given a
50
+ trial's address, the importer used to append ``/studies`` to it, and a
51
+ server that ignored the extra segments answered with every study it held.
52
+
53
+ Raises:
54
+ ValueError: For an address naming anything but the server, a trial or
55
+ a study, with the base URL to enter instead.
56
+ """
57
+ from urllib.parse import urlsplit, urlunsplit
58
+
59
+ parts = urlsplit(address)
60
+ segments = [segment for segment in parts.path.split("/") if segment]
61
+ for index, segment in enumerate(segments):
62
+ if segment.lower() not in _RESOURCES:
63
+ continue
64
+ base = urlunsplit(
65
+ (parts.scheme, parts.netloc, "/" + "/".join(segments[:index]), "", "")
66
+ )
67
+ record = segments[index + 1] if len(segments) > index + 1 else None
68
+ if segment.lower() == "trials" and record and len(segments) == index + 2:
69
+ return BrapiAddress(base, trial_db_id=record)
70
+ if segment.lower() == "studies" and record and len(segments) == index + 2:
71
+ return BrapiAddress(base, study_db_id=record)
72
+ raise ValueError(
73
+ f"'{address}' is not an address the import takes: enter the server's "
74
+ f"base URL, which ends in /brapi/v2 ({base}), a trial's address "
75
+ f"({base}/trials/<trialDbId>) or a study's ({base}/studies/<studyDbId>)."
76
+ )
77
+ return BrapiAddress(address.rstrip("/"))
78
+
79
+
80
+ def _study_variables(client: BrapiClient, study_id: str) -> list[dict[str, Any]]:
81
+ """The variable definitions one study uses, each naming that study.
82
+
83
+ A server without the ``variables`` endpoint gives none, and each variable
84
+ stays as its observations name it.
85
+ """
86
+ from metaseed.brapi.client import BrapiEndpointError
87
+
88
+ try:
89
+ found = client.variables(study_id)
90
+ except BrapiEndpointError:
91
+ return []
92
+ return [{**variable, "studyDbIds": [study_id]} for variable in found]
93
+
94
+
95
+ #: BrAPI resources an address may name below the base URL.
96
+ _RESOURCES = frozenset(
97
+ {"trials", "studies", "germplasm", "observationunits", "observations", "programs"}
98
+ )
99
+
100
+
101
+ def import_brapi(
102
+ address: str,
103
+ *,
104
+ study_db_id: str | None = None,
105
+ token: str | None = None,
106
+ client: BrapiClient | None = None,
107
+ version: str = "1.2",
108
+ ) -> MetaseedClient:
109
+ """Import a BrAPI v2 server, trial or study into a ``miappe``-profile dataset.
110
+
111
+ Args:
112
+ address: The server's base URL (e.g.
113
+ ``https://test-server.brapi.org/brapi/v2``), which imports every
114
+ study the server exposes; a trial's address
115
+ (``<base>/trials/<trialDbId>``), which imports that trial's
116
+ studies; or a study's address (``<base>/studies/<studyDbId>``).
117
+ study_db_id: Optional ``studyDbId`` to restrict a server import to one
118
+ study, kept for callers that hold the identifier rather than the
119
+ address.
120
+ token: Optional bearer token for authenticated servers.
121
+ client: Optional pre-configured
122
+ :class:`~metaseed.brapi.client.BrapiClient`.
123
+ version: ``miappe`` profile version.
124
+
125
+ Returns:
126
+ A :class:`~metaseed.api.client.MetaseedClient` holding the imported
127
+ Investigations, Studies, BiologicalMaterials, ObservationUnits,
128
+ ObservedVariables, and DataFile references. Call
129
+ :meth:`~metaseed.api.client.MetaseedClient.validate` to report gaps.
130
+
131
+ Raises:
132
+ ValueError: If the address names anything but a server, a trial or a
133
+ study.
134
+ """
135
+ from metaseed.brapi.client import BrapiClient, BrapiEndpointError
136
+
137
+ where = parse_address(address)
138
+ client = client or BrapiClient(where.base_url, token=token)
139
+
140
+ if where.trial_db_id is not None:
141
+ listed = client.trial(where.trial_db_id).get("studies") or []
142
+ studies = [
143
+ client.study(entry["studyDbId"])
144
+ for entry in listed
145
+ if isinstance(entry, dict) and entry.get("studyDbId")
146
+ ]
147
+ elif where.study_db_id is not None:
148
+ studies = [client.study(where.study_db_id)]
149
+ else:
150
+ studies = client.studies()
151
+ if study_db_id is not None:
152
+ studies = [s for s in studies if s.get("studyDbId") == study_db_id]
153
+ study_ids = [s["studyDbId"] for s in studies if s.get("studyDbId")]
154
+ scoped = where.trial_db_id is not None or where.study_db_id is not None
155
+
156
+ observation_units: list[dict[str, Any]] = []
157
+ observations: list[dict[str, Any]] = []
158
+ germplasm: list[dict[str, Any]] = []
159
+ seen_germplasm: set[str] = set()
160
+ variables: list[dict[str, Any]] = []
161
+ for study_id in study_ids:
162
+ units = client.observation_units(study_id)
163
+ observation_units.extend(units)
164
+ # Asked for the study first, which is a few requests where the server
165
+ # honours the filter (FAIDARE does). Not every server does: the BrAPI
166
+ # reference server answers with nothing, which once imported a dataset
167
+ # with no measurements at all; and FAIDARE answers 500 past its
168
+ # 20,000th record of one study. Then one request per unit we already
169
+ # have, which never reaches that deep, and a measurement a server
170
+ # lists under more than one unit is imported once.
171
+ seen_observations: set[str] = set()
172
+ try:
173
+ found = client.observations_for_study(study_id)
174
+ except BrapiEndpointError:
175
+ found = []
176
+ if not found:
177
+ found = [
178
+ observation
179
+ for unit in units
180
+ if unit.get("observationUnitDbId")
181
+ for observation in client.observations_for_unit(
182
+ unit["observationUnitDbId"]
183
+ )
184
+ ]
185
+ for observation in found:
186
+ raw_key = observation.get("observationDbId")
187
+ if raw_key is not None:
188
+ # A server may send the id as a number; compare as text.
189
+ key = str(raw_key)
190
+ if key in seen_observations:
191
+ continue
192
+ seen_observations.add(key)
193
+ observations.append(observation)
194
+ variables.extend(_study_variables(client, study_id))
195
+ if scoped:
196
+ # The germplasm of these studies, not of the whole server; a study
197
+ # may share accessions with the one before it.
198
+ for item in client.germplasm(study_id):
199
+ key = str(item.get("germplasmDbId") or "")
200
+ if key and key in seen_germplasm:
201
+ continue
202
+ seen_germplasm.add(key)
203
+ # Fetched for this study: a server that leaves out
204
+ # ``studyDbIds`` still told us which study it belongs to.
205
+ if not item.get("studyDbIds"):
206
+ item = {**item, "studyDbIds": [study_id]}
207
+ germplasm.append(item)
208
+
209
+ if not scoped:
210
+ germplasm = client.germplasm()
211
+
212
+ dataset = build_dataset(
213
+ studies,
214
+ observation_units,
215
+ observations,
216
+ germplasm,
217
+ variables=variables,
218
+ version=version,
219
+ )
220
+ # A BrAPI server can be run by anyone, so there are no repository terms to
221
+ # fall back on: the license is the studies' own, when they share one.
222
+ dataset.origin = imported_now(
223
+ "BrAPI",
224
+ address,
225
+ record_url=address,
226
+ stated_license=shared_license(studies),
227
+ repository_terms=None,
228
+ creators=creators_from(
229
+ [
230
+ (contact.get("name") or "", contact.get("orcid") or "")
231
+ for study in studies
232
+ for contact in study.get("contacts") or []
233
+ ]
234
+ ),
235
+ )
236
+ return dataset
237
+
238
+
239
+ def shared_license(studies: list[dict[str, Any]]) -> str | None:
240
+ """The license every study names, or ``None`` when they do not all name the same one.
241
+
242
+ One dataset-level license cannot state terms the imported studies do not
243
+ share, so a study naming none, or a different one, leaves the import
244
+ without a license.
245
+ """
246
+ licenses = {normalize_license(study.get("license")) for study in studies}
247
+ if len(licenses) != 1:
248
+ return None
249
+ return licenses.pop()
@@ -0,0 +1,270 @@
1
+ """HTTP client for a BrAPI v2 server.
2
+
3
+ Fetches plant-breeding metadata from any server implementing the
4
+ [Breeding API](https://brapi.org) v2. The base URL is configurable (BrAPI is a
5
+ standard, not a single endpoint) and an optional bearer token authenticates
6
+ against protected servers. Requires ``httpx`` (the ``metaseed[brapi]`` extra).
7
+ An ``httpx.Client`` can be injected for hermetic testing.
8
+
9
+ BrAPI wraps every payload as ``{"metadata": ..., "result": {"data": [...]}}``;
10
+ each method returns the ``result.data`` list.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from json import JSONDecodeError
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ try:
20
+ import httpx
21
+ except (
22
+ ModuleNotFoundError
23
+ ) as exc: # pragma: no cover - exercised only without the extra
24
+ raise ModuleNotFoundError(
25
+ "BrAPI import requires httpx. Install with: pip install 'metaseed[brapi]'"
26
+ ) from exc
27
+
28
+ from metaseed._http import request_json
29
+
30
+ if TYPE_CHECKING:
31
+ from collections.abc import Mapping
32
+
33
+ USER_AGENT = "metaseed (+https://github.com/sorenwacker/metaseed)"
34
+
35
+
36
+ class BrapiEndpointError(RuntimeError):
37
+ """A URL did not answer as a BrAPI v2 server.
38
+
39
+ Raised in place of the raw transport error, because the underlying failures
40
+ name nothing: a base URL missing its ``/brapi/v2`` suffix surfaces as a bare
41
+ ``404``, and a server returning an HTML error page surfaces as
42
+ ``JSONDecodeError: Expecting value: line 1 column 1``. Users reported being
43
+ unable to get any endpoint working, with these as the only diagnostics.
44
+ """
45
+
46
+
47
+ def _not_a_brapi_endpoint(
48
+ base_url: str, url: str, exc: Exception
49
+ ) -> BrapiEndpointError:
50
+ """Turn a transport failure into a message naming the likely mistake."""
51
+ status = getattr(getattr(exc, "response", None), "status_code", None)
52
+
53
+ if isinstance(exc, JSONDecodeError):
54
+ detail = (
55
+ f"{url} did not return JSON. It is probably a web page rather than "
56
+ "a BrAPI endpoint"
57
+ )
58
+ elif status == 404:
59
+ detail = f"{url} does not exist (404)"
60
+ elif status in (401, 403):
61
+ detail = (
62
+ f"{url} requires authentication ({status}). Pass a bearer token for "
63
+ "this server"
64
+ )
65
+ else:
66
+ detail = f"{url} failed: {exc}"
67
+
68
+ hint = ""
69
+ if not base_url.rstrip("/").endswith("brapi/v2"):
70
+ hint = (
71
+ " The base URL must be the BrAPI v2 root, which usually ends in "
72
+ f"/brapi/v2 - '{base_url}' does not."
73
+ )
74
+ return BrapiEndpointError(f"{detail}.{hint}")
75
+
76
+
77
+ #: A request is tried this many times on a transport error (a dropped
78
+ #: connection, a name that did not resolve), with a pause that doubles
79
+ #: between tries. A trial is thousands of requests over half an hour; one
80
+ #: hiccup must not throw them away.
81
+ ATTEMPTS = 3
82
+ RETRY_PAUSE_SECONDS = 2.0
83
+
84
+ #: Records asked for per page. Servers default to ten (FAIDARE among them),
85
+ #: which made a study of 1737 observation units 174 requests.
86
+ PAGE_SIZE = 1000
87
+
88
+
89
+ class BrapiClient:
90
+ """Minimal client for the BrAPI v2 endpoints metaseed imports."""
91
+
92
+ def __init__(
93
+ self,
94
+ base_url: str,
95
+ *,
96
+ token: str | None = None,
97
+ timeout: float = 30.0,
98
+ http_client: httpx.Client | None = None,
99
+ ) -> None:
100
+ """Initialize the client.
101
+
102
+ Args:
103
+ base_url: BrAPI v2 base URL (e.g.
104
+ ``https://test-server.brapi.org/brapi/v2``).
105
+ token: Optional bearer token for authenticated servers. When given,
106
+ an ``Authorization: Bearer <token>`` header is sent.
107
+ timeout: Per-request timeout in seconds.
108
+ http_client: Optional pre-configured ``httpx.Client`` (e.g. with a
109
+ mock transport for tests). When omitted, a request is issued
110
+ directly via ``httpx``.
111
+ """
112
+ self._base_url = base_url.rstrip("/")
113
+ self._token = token
114
+ self._timeout = timeout
115
+ self._client = http_client
116
+
117
+ def studies(self) -> list[dict[str, Any]]:
118
+ """Return BrAPI ``studies`` objects."""
119
+ return self._get("studies")
120
+
121
+ def trial(self, trial_db_id: str) -> dict[str, Any]:
122
+ """Return one BrAPI ``trial`` object, with the studies it lists.
123
+
124
+ Args:
125
+ trial_db_id: The ``trialDbId``, as the server spells it in a URL.
126
+ """
127
+ return self._get_one(f"trials/{trial_db_id}")
128
+
129
+ def study(self, study_db_id: str) -> dict[str, Any]:
130
+ """Return one BrAPI ``study`` object.
131
+
132
+ Args:
133
+ study_db_id: The ``studyDbId``, as the server spells it in a URL.
134
+ """
135
+ return self._get_one(f"studies/{study_db_id}")
136
+
137
+ def observation_units(self, study_db_id: str) -> list[dict[str, Any]]:
138
+ """Return BrAPI ``observationunits`` objects for a study.
139
+
140
+ Args:
141
+ study_db_id: The ``studyDbId`` to filter observation units by.
142
+ """
143
+ return self._get("observationunits", {"studyDbId": study_db_id})
144
+
145
+ def observations_for_study(self, study_db_id: str) -> list[dict[str, Any]]:
146
+ """Return BrAPI ``observations`` objects of a study, where the server filters.
147
+
148
+ Not every server honours ``studyDbId`` on ``/observations``: the
149
+ reference server answers with nothing. An empty answer is the caller's
150
+ cue to ask per observation unit instead.
151
+
152
+ Args:
153
+ study_db_id: The ``studyDbId`` to filter by.
154
+ """
155
+ return self._get("observations", {"studyDbId": study_db_id})
156
+
157
+ def observations_for_unit(
158
+ self, observation_unit_db_id: str
159
+ ) -> list[dict[str, Any]]:
160
+ """Return BrAPI ``observations`` objects for one observation unit.
161
+
162
+ An observation belongs to an observation unit, and filtering by unit is
163
+ honoured where filtering by study is not, so this is the reliable way to
164
+ collect a study's measurements: one request per unit already fetched.
165
+
166
+ Args:
167
+ observation_unit_db_id: The ``observationUnitDbId`` to filter by.
168
+ """
169
+ return self._get(
170
+ "observations", {"observationUnitDbId": observation_unit_db_id}
171
+ )
172
+
173
+ def germplasm(self, study_db_id: str | None = None) -> list[dict[str, Any]]:
174
+ """Return BrAPI ``germplasm`` objects, those of one study when asked.
175
+
176
+ Args:
177
+ study_db_id: Restrict to the germplasm of this study. A server
178
+ holding thousands of accessions is not read whole for one
179
+ trial.
180
+ """
181
+ return self._get(
182
+ "germplasm", {"studyDbId": study_db_id} if study_db_id else None
183
+ )
184
+
185
+ def variables(self, study_db_id: str) -> list[dict[str, Any]]:
186
+ """Return the BrAPI ``variables`` one study uses, with trait, method and scale.
187
+
188
+ Observations name a variable only; its definition, which MIAPPE needs
189
+ for the method and scale, is here.
190
+ """
191
+ return self._get("variables", {"studyDbId": study_db_id})
192
+
193
+ def _get_one(self, path: str) -> dict[str, Any]:
194
+ """Issue one GET for a single record and return its ``result``.
195
+
196
+ A single-record endpoint carries the object in ``result`` itself, where
197
+ a list endpoint carries a page in ``result.data``.
198
+ """
199
+ url = f"{self._base_url}/{path}"
200
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
201
+ if self._token:
202
+ headers["Authorization"] = f"Bearer {self._token}"
203
+ try:
204
+ body = self._request(url, None, headers)
205
+ except (httpx.HTTPStatusError, JSONDecodeError) as exc:
206
+ raise _not_a_brapi_endpoint(self._base_url, url, exc) from exc
207
+ result = body.get("result") if isinstance(body, dict) else None
208
+ return result if isinstance(result, dict) else {}
209
+
210
+ def _request(
211
+ self, url: str, params: Mapping[str, str] | None, headers: dict[str, str]
212
+ ) -> Any:
213
+ """One GET, tried again after a transport error; the last error is raised."""
214
+ for attempt in range(1, ATTEMPTS + 1):
215
+ try:
216
+ return request_json(
217
+ url,
218
+ params=params,
219
+ headers=headers,
220
+ timeout=self._timeout,
221
+ http_client=self._client,
222
+ )
223
+ except httpx.TransportError:
224
+ if attempt == ATTEMPTS:
225
+ raise
226
+ time.sleep(RETRY_PAUSE_SECONDS * 2 ** (attempt - 1))
227
+ raise AssertionError("unreachable")
228
+
229
+ def _get(
230
+ self, path: str, params: Mapping[str, str] | None = None
231
+ ) -> list[dict[str, Any]]:
232
+ """Issue GET requests and return all ``result.data`` records.
233
+
234
+ BrAPI paginates: each response carries ``metadata.pagination.totalPages``
235
+ and one page of ``result.data``. This follows the pages so a server with
236
+ more records than one page is not silently truncated.
237
+
238
+ Args:
239
+ path: Endpoint path appended to the base URL.
240
+ params: Optional query parameters.
241
+
242
+ Returns:
243
+ The concatenated ``result.data`` records across all pages.
244
+ """
245
+ url = f"{self._base_url}/{path}"
246
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
247
+ if self._token:
248
+ headers["Authorization"] = f"Bearer {self._token}"
249
+
250
+ collected: list[dict[str, Any]] = []
251
+ page = 0
252
+ while True:
253
+ query = {**(params or {}), "pageSize": str(PAGE_SIZE), "page": str(page)}
254
+ try:
255
+ body = self._request(url, query, headers)
256
+ except (httpx.HTTPStatusError, JSONDecodeError) as exc:
257
+ raise _not_a_brapi_endpoint(self._base_url, url, exc) from exc
258
+ if not isinstance(body, dict):
259
+ break
260
+ data = (body.get("result") or {}).get("data")
261
+ if isinstance(data, list):
262
+ collected.extend(d for d in data if isinstance(d, dict))
263
+ pagination = (body.get("metadata") or {}).get("pagination") or {}
264
+ total_pages = pagination.get("totalPages")
265
+ if not isinstance(total_pages, int) or page + 1 >= total_pages or not data:
266
+ break
267
+ page += 1
268
+ if page >= 10_000: # safety net
269
+ break
270
+ return collected
@@ -0,0 +1,155 @@
1
+ """Export a ``miappe``-profile dataset to BrAPI v2 JSON objects.
2
+
3
+ Produces the BrAPI v2 request bodies a BrAPI server accepts (``trials``,
4
+ ``studies``, ``observationUnits``, ``germplasm``) from a metaseed dataset bound
5
+ to the ``miappe`` profile. Pure and dependency-free (stdlib only); it never
6
+ contacts a server. Data files are *referenced* via study ``dataLinks``, never
7
+ uploaded.
8
+
9
+ This is the round-trip partner of :func:`metaseed.brapi.build_dataset`: it
10
+ inverts the mapper, turning Investigations back into trials, Studies into
11
+ studies, ObservationUnits into observation units, and BiologicalMaterials into
12
+ germplasm. Entity ``unique_id`` values become the corresponding BrAPI ``DbId``,
13
+ so parent references survive the round trip.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from metaseed.mapping import clean as _clean
21
+
22
+ if TYPE_CHECKING:
23
+ from metaseed.api.client import MetaseedClient
24
+
25
+
26
+ def _trial(investigation: dict[str, Any]) -> dict[str, Any]:
27
+ """Build a BrAPI ``trial`` from a miappe Investigation."""
28
+ trial_id = investigation.get("unique_id")
29
+ return _clean(
30
+ {
31
+ "trialDbId": trial_id,
32
+ "trialName": investigation.get("title") or trial_id,
33
+ "trialDescription": investigation.get("description"),
34
+ }
35
+ )
36
+
37
+
38
+ def _study(study: dict[str, Any]) -> dict[str, Any]:
39
+ """Build a BrAPI ``study`` from a miappe Study."""
40
+ study_id = study.get("unique_id")
41
+ design = _clean(
42
+ {
43
+ "PUI": study.get("experimental_design_type"),
44
+ "description": study.get("experimental_design_description"),
45
+ }
46
+ )
47
+ facility = _clean({"description": study.get("growth_facility_type")})
48
+ return _clean(
49
+ {
50
+ "studyDbId": study_id,
51
+ "studyName": study.get("title") or study_id,
52
+ "trialDbId": study.get("investigation_id"),
53
+ "studyDescription": study.get("description"),
54
+ "startDate": study.get("start_date"),
55
+ "endDate": study.get("end_date"),
56
+ "locationName": study.get("experimental_site_name"),
57
+ "experimentalDesign": design,
58
+ "growthFacility": facility,
59
+ "documentationURL": study.get("map_of_experimental_design"),
60
+ }
61
+ )
62
+
63
+
64
+ def _observation_unit(unit: dict[str, Any]) -> dict[str, Any]:
65
+ """Build a BrAPI ``observationUnit`` from a miappe ObservationUnit."""
66
+ level = _clean(
67
+ {
68
+ "levelName": unit.get("observation_level")
69
+ or unit.get("observation_unit_type"),
70
+ "levelCode": unit.get("observation_level_code"),
71
+ }
72
+ )
73
+ # BrAPI v2: block/replicate are expressed via observationLevelRelationships.
74
+ relationships = []
75
+ if unit.get("observation_unit_block"):
76
+ relationships.append(
77
+ {"levelName": "block", "levelCode": str(unit["observation_unit_block"])}
78
+ )
79
+ if unit.get("observation_unit_replicate"):
80
+ relationships.append(
81
+ {"levelName": "rep", "levelCode": str(unit["observation_unit_replicate"])}
82
+ )
83
+ position = _clean(
84
+ {
85
+ "positionCoordinateX": unit.get("observation_unit_x_ref"),
86
+ "positionCoordinateXType": unit.get("spatial_distribution_type"),
87
+ "positionCoordinateY": unit.get("observation_unit_y_ref"),
88
+ "entryType": unit.get("entry_type"),
89
+ }
90
+ )
91
+ # BrAPI v2 nests the level inside the position object.
92
+ if level:
93
+ position["observationLevel"] = level
94
+ if relationships:
95
+ position["observationLevelRelationships"] = relationships
96
+ return _clean(
97
+ {
98
+ "observationUnitDbId": unit.get("unique_id"),
99
+ "studyDbId": unit.get("study_id"),
100
+ "germplasmDbId": unit.get("biological_material_id"),
101
+ "observationUnitPosition": position,
102
+ }
103
+ )
104
+
105
+
106
+ def _germplasm(material: dict[str, Any]) -> dict[str, Any]:
107
+ """Build a BrAPI ``germplasm`` from a miappe BiologicalMaterial."""
108
+ germplasm_id = material.get("unique_id")
109
+ study_id = material.get("study_id")
110
+ return _clean(
111
+ {
112
+ "germplasmDbId": germplasm_id,
113
+ "germplasmName": material.get("biological_material_description")
114
+ or germplasm_id,
115
+ "genus": material.get("genus"),
116
+ "species": material.get("species"),
117
+ "subtaxa": material.get("infraspecific_name"),
118
+ "accessionNumber": material.get("accession_number"),
119
+ "instituteCode": material.get("material_source_institute_code"),
120
+ "instituteName": material.get("material_source_institute_name"),
121
+ "studyDbIds": [study_id] if study_id else [],
122
+ }
123
+ )
124
+
125
+
126
+ def to_brapi(client: MetaseedClient) -> dict[str, list[dict[str, Any]]]:
127
+ """Render a ``miappe``-profile dataset as BrAPI v2 JSON objects.
128
+
129
+ Args:
130
+ client: A MetaseedClient bound to the ``miappe`` profile.
131
+
132
+ Returns:
133
+ Mapping of BrAPI collection name to the list of v2 objects (the POST
134
+ request bodies a BrAPI server accepts), e.g.
135
+ ``{"trials": [...], "studies": [...], "observationUnits": [...],
136
+ "germplasm": [...]}``. Only non-empty collections are included.
137
+ """
138
+ entities = client.serialize()["entities"]
139
+ by_type: dict[str, list[dict[str, Any]]] = {}
140
+ for entity in entities:
141
+ by_type.setdefault(entity["_type"], []).append(entity)
142
+
143
+ builders: dict[str, tuple[str, Any]] = {
144
+ "Investigation": ("trials", _trial),
145
+ "Study": ("studies", _study),
146
+ "ObservationUnit": ("observationUnits", _observation_unit),
147
+ "BiologicalMaterial": ("germplasm", _germplasm),
148
+ }
149
+
150
+ result: dict[str, list[dict[str, Any]]] = {}
151
+ for entity_type, (collection, build) in builders.items():
152
+ objects = [build(e) for e in by_type.get(entity_type, [])]
153
+ if objects:
154
+ result[collection] = objects
155
+ return result
@@ -0,0 +1,484 @@
1
+ """Map BrAPI v2 objects into a ``miappe``-profile dataset.
2
+
3
+ Pure and network-free: it takes already-fetched BrAPI objects (as returned by a
4
+ BrAPI v2 server under ``result.data``) and builds a
5
+ :class:`~metaseed.api.client.MetaseedClient` bound to the ``miappe`` profile.
6
+ Data files are *referenced* (BrAPI ``dataLinks`` become ``DataFile`` entities
7
+ holding their URLs), never downloaded.
8
+
9
+ BrAPI ``DbId`` values are used as each entity's ``unique_id`` (the identifier the
10
+ ``*_id`` reference fields resolve against), so studies, observation units,
11
+ biological materials, and observed variables auto-link to their parents.
12
+ Entities are created with ``skip_validation`` — an import should not fail on a
13
+ record that omits a field; call :meth:`MetaseedClient.validate` to report gaps.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from metaseed.mapping import clean as _clean
21
+
22
+ if TYPE_CHECKING:
23
+ from metaseed.api.client import MetaseedClient
24
+
25
+
26
+ def build_dataset(
27
+ studies: list[dict[str, Any]],
28
+ observation_units: list[dict[str, Any]],
29
+ observations: list[dict[str, Any]],
30
+ germplasm: list[dict[str, Any]],
31
+ *,
32
+ variables: list[dict[str, Any]] | None = None,
33
+ version: str = "1.2",
34
+ ) -> MetaseedClient:
35
+ """Build a ``miappe``-profile dataset from BrAPI v2 objects.
36
+
37
+ Args:
38
+ studies: BrAPI ``studies`` objects (one per study).
39
+ observation_units: BrAPI ``observationunits`` objects.
40
+ observations: BrAPI ``observations`` objects.
41
+ germplasm: BrAPI ``germplasm`` objects.
42
+ variables: BrAPI ``variables`` objects, each naming its studies in
43
+ ``studyDbIds``. A variable an observation references but this list
44
+ lacks is created from the observation, with its name only.
45
+ version: ``miappe`` profile version.
46
+
47
+ Returns:
48
+ A MetaseedClient holding Investigations and their Studies,
49
+ BiologicalMaterials, ObservationUnits, ObservedVariables, and DataFile
50
+ references. Empty if every input list is empty.
51
+ """
52
+ from metaseed import MetaseedClient
53
+
54
+ client = MetaseedClient("miappe", version)
55
+
56
+ default_study_id = studies[0].get("studyDbId") if studies else None
57
+
58
+ study_ids = [s["studyDbId"] for s in studies if s.get("studyDbId")]
59
+ _add_investigations_and_studies(client, studies)
60
+ _add_contacts(client, studies)
61
+ _add_germplasm(client, germplasm, default_study_id, study_ids)
62
+ unit_nodes = _add_observation_units(client, observation_units)
63
+ _add_treatments(client, observation_units, unit_nodes)
64
+ defined = _add_variables(client, variables or [], default_study_id)
65
+ _add_observed_variables(client, observations, default_study_id, defined)
66
+ _add_data_files(client, studies)
67
+
68
+ return client
69
+
70
+
71
+ #: MIAPPE's entry types and growth facility types, as the profile's
72
+ #: vocabulary rules spell them. BrAPI servers return what their database
73
+ #: holds: Breedbase an entry type in capitals, FAIDARE a facility as a list
74
+ #: of CO_715 descriptions ("field environment condition, greenhouse").
75
+ ENTRY_TYPES = ("test", "check", "filler")
76
+ GROWTH_FACILITY_TYPES = (
77
+ "field",
78
+ "greenhouse",
79
+ "glasshouse",
80
+ "growth chamber",
81
+ "phytotron",
82
+ "open top chamber",
83
+ )
84
+
85
+
86
+ def _entry_type(value: Any) -> Any:
87
+ """The entry type in MIAPPE's spelling where it is one, else as sent."""
88
+ if isinstance(value, str) and value.strip().lower() in ENTRY_TYPES:
89
+ return value.strip().lower()
90
+ return value
91
+
92
+
93
+ def _growth_facility_type(value: Any) -> Any:
94
+ """The MIAPPE facility type a server's description names, else as sent.
95
+
96
+ An exact match wins; otherwise the first vocabulary term the description
97
+ contains, in the description's own order, so "field environment
98
+ condition, greenhouse" reads as a field.
99
+ """
100
+ if not isinstance(value, str):
101
+ return value
102
+ text = value.strip().lower()
103
+ if text in GROWTH_FACILITY_TYPES:
104
+ return text
105
+ found = [(text.find(term), term) for term in GROWTH_FACILITY_TYPES if term in text]
106
+ return min(found)[1] if found else value
107
+
108
+
109
+ def _trial_id(study: dict[str, Any]) -> str | None:
110
+ """Return the Investigation id for a study (its trial, else itself)."""
111
+ return study.get("trialDbId") or study.get("studyDbId")
112
+
113
+
114
+ def _add_investigations_and_studies(
115
+ client: MetaseedClient, studies: list[dict[str, Any]]
116
+ ) -> None:
117
+ """Create one Investigation per distinct BrAPI trial, then each Study."""
118
+ seen_trials: set[str] = set()
119
+ for study in studies:
120
+ trial_id = _trial_id(study)
121
+ if trial_id and trial_id not in seen_trials:
122
+ seen_trials.add(trial_id)
123
+ client.create_entity(
124
+ "Investigation",
125
+ _clean(
126
+ {
127
+ "unique_id": trial_id,
128
+ "title": study.get("trialName") or trial_id,
129
+ }
130
+ ),
131
+ skip_validation=True,
132
+ )
133
+
134
+ for study in studies:
135
+ study_id = study.get("studyDbId")
136
+ if not study_id:
137
+ continue
138
+ design = study.get("experimentalDesign") or {}
139
+ client.create_entity(
140
+ "Study",
141
+ _clean(
142
+ {
143
+ "unique_id": study_id,
144
+ "investigation_id": _trial_id(study),
145
+ "title": study.get("studyName") or study_id,
146
+ "description": study.get("studyDescription"),
147
+ "start_date": study.get("startDate"),
148
+ "end_date": study.get("endDate"),
149
+ "experimental_site_name": study.get("locationName"),
150
+ "experimental_design_type": design.get("PUI"),
151
+ "experimental_design_description": design.get("description"),
152
+ "growth_facility_type": _growth_facility_type(
153
+ (study.get("growthFacility") or {}).get("description")
154
+ ),
155
+ "map_of_experimental_design": study.get("documentationURL"),
156
+ }
157
+ ),
158
+ skip_validation=True,
159
+ )
160
+
161
+
162
+ def _add_contacts(client: MetaseedClient, studies: list[dict[str, Any]]) -> None:
163
+ """Create a Person under each Study for each of its BrAPI ``contacts``."""
164
+ for study in studies:
165
+ study_id = study.get("studyDbId")
166
+ for contact in study.get("contacts") or []:
167
+ if not isinstance(contact, dict) or not contact.get("name"):
168
+ continue
169
+ client.create_entity(
170
+ "Person",
171
+ _clean(
172
+ {
173
+ "study_id": study_id,
174
+ "name": contact.get("name"),
175
+ "email": contact.get("email"),
176
+ "institution": contact.get("instituteName"),
177
+ "role": contact.get("type"),
178
+ "orcid": contact.get("orcid"),
179
+ }
180
+ ),
181
+ skip_validation=True,
182
+ )
183
+
184
+
185
+ def _add_germplasm(
186
+ client: MetaseedClient,
187
+ germplasm: list[dict[str, Any]],
188
+ default_study_id: str | None,
189
+ imported_study_ids: list[str],
190
+ ) -> None:
191
+ """Create a BiologicalMaterial per BrAPI germplasm object and study.
192
+
193
+ MIAPPE places a biological material in a study, and its identifier need
194
+ only be unique there, so germplasm a server lists under several imported
195
+ studies becomes one BiologicalMaterial in each. It was placed in the first
196
+ of them only, and the other studies' units named a material they lacked.
197
+ """
198
+ for item in germplasm:
199
+ germplasm_id = item.get("germplasmDbId")
200
+ if not germplasm_id:
201
+ continue
202
+ listed = [s for s in item.get("studyDbIds") or [] if s in imported_study_ids]
203
+ for study_id in listed or [default_study_id]:
204
+ _add_biological_material(client, item, germplasm_id, study_id)
205
+
206
+
207
+ def _add_biological_material(
208
+ client: MetaseedClient,
209
+ item: dict[str, Any],
210
+ germplasm_id: str,
211
+ study_id: str | None,
212
+ ) -> None:
213
+ """Create one BiologicalMaterial for a germplasm object in one study."""
214
+ client.create_entity(
215
+ "BiologicalMaterial",
216
+ _clean(
217
+ {
218
+ "unique_id": germplasm_id,
219
+ "study_id": study_id,
220
+ "organism": item.get("species"),
221
+ "genus": item.get("genus"),
222
+ "species": item.get("species"),
223
+ "infraspecific_name": item.get("subtaxa"),
224
+ "accession_number": item.get("accessionNumber"),
225
+ "biological_material_description": item.get("germplasmName"),
226
+ "material_source_institute_code": item.get("instituteCode"),
227
+ "material_source_institute_name": item.get("instituteName"),
228
+ }
229
+ ),
230
+ skip_validation=True,
231
+ )
232
+
233
+
234
+ def _add_observation_units(
235
+ client: MetaseedClient, observation_units: list[dict[str, Any]]
236
+ ) -> dict[str, str]:
237
+ """Create an ObservationUnit per BrAPI observation unit.
238
+
239
+ Returns:
240
+ The node id of each unit, by its ``observationUnitDbId``.
241
+ """
242
+ nodes: dict[str, str] = {}
243
+ for unit in observation_units:
244
+ unit_id = unit.get("observationUnitDbId")
245
+ if not unit_id:
246
+ continue
247
+ position = unit.get("observationUnitPosition") or {}
248
+ # In BrAPI v2 the observationLevel object is nested inside the position,
249
+ # and block/replicate are expressed via observationLevelRelationships.
250
+ level = _level(position.get("observationLevel"))
251
+ nodes[unit_id] = client.create_entity(
252
+ "ObservationUnit",
253
+ _clean(
254
+ {
255
+ "unique_id": unit_id,
256
+ "study_id": unit.get("studyDbId"),
257
+ "biological_material_id": unit.get("germplasmDbId"),
258
+ "observation_unit_type": level.get("levelName"),
259
+ "observation_level": level.get("levelName"),
260
+ "observation_level_code": level.get("levelCode"),
261
+ "spatial_distribution_type": position.get(
262
+ "positionCoordinateXType"
263
+ ),
264
+ "observation_unit_x_ref": position.get("positionCoordinateX"),
265
+ "observation_unit_y_ref": position.get("positionCoordinateY"),
266
+ "observation_unit_block": _level_code(position, ("block",)),
267
+ "observation_unit_replicate": _level_code(
268
+ position, ("rep", "replicate")
269
+ ),
270
+ "entry_type": _entry_type(position.get("entryType")),
271
+ }
272
+ ),
273
+ skip_validation=True,
274
+ ).id
275
+ return nodes
276
+
277
+
278
+ def _token(text: str) -> str:
279
+ """``text`` as an identifier: MIAPPE's ``unique_id`` takes no whitespace."""
280
+ return "_".join(str(text).split())
281
+
282
+
283
+ def _add_treatments(
284
+ client: MetaseedClient,
285
+ observation_units: list[dict[str, Any]],
286
+ unit_nodes: dict[str, str],
287
+ ) -> None:
288
+ """Create a Factor per study and treatment, and its value on each unit.
289
+
290
+ BrAPI lists a unit's ``treatments`` as ``{factor, modality}`` pairs; MIAPPE
291
+ names the factor once in its Study and gives each unit a FactorValue.
292
+ """
293
+ factors: set[tuple[str, str]] = set()
294
+ for unit in observation_units:
295
+ unit_id = unit.get("observationUnitDbId")
296
+ study_id = unit.get("studyDbId")
297
+ node_id = unit_nodes.get(str(unit_id))
298
+ for treatment in unit.get("treatments") or []:
299
+ factor = treatment.get("factor") if isinstance(treatment, dict) else None
300
+ if not factor or not study_id or node_id is None:
301
+ continue
302
+ factor_id = _token(factor)
303
+ if (study_id, factor_id) not in factors:
304
+ factors.add((study_id, factor_id))
305
+ client.create_entity(
306
+ "Factor",
307
+ {"unique_id": factor_id, "study_id": study_id, "name": factor},
308
+ skip_validation=True,
309
+ )
310
+ client.create_entity(
311
+ "FactorValue",
312
+ _clean(
313
+ {
314
+ "unique_id": f"{_token(str(unit_id))}-{factor_id}",
315
+ "factor_id": factor_id,
316
+ "value": treatment.get("modality"),
317
+ }
318
+ ),
319
+ parent_id=node_id,
320
+ skip_validation=True,
321
+ )
322
+
323
+
324
+ def _add_variables(
325
+ client: MetaseedClient,
326
+ variables: list[dict[str, Any]],
327
+ default_study_id: str | None,
328
+ ) -> set[tuple[str | None, str]]:
329
+ """Create an ObservedVariable per BrAPI variable and study, with its
330
+ trait, method and scale.
331
+
332
+ Returns:
333
+ The (study, variable id) pairs created, so observations do not create
334
+ them again with their name only.
335
+ """
336
+ created: set[tuple[str | None, str]] = set()
337
+ for variable in variables:
338
+ variable_id = variable.get("observationVariableDbId")
339
+ if not variable_id:
340
+ continue
341
+ trait = variable.get("trait") or {}
342
+ method = variable.get("method") or {}
343
+ scale = variable.get("scale") or {}
344
+ for study_id in variable.get("studyDbIds") or [default_study_id]:
345
+ if (study_id, variable_id) in created:
346
+ continue
347
+ created.add((study_id, variable_id))
348
+ client.create_entity(
349
+ "ObservedVariable",
350
+ _clean(
351
+ {
352
+ "unique_id": variable_id,
353
+ "study_id": study_id,
354
+ "name": variable.get("observationVariableName"),
355
+ "trait": trait.get("traitName")
356
+ or variable.get("observationVariableName"),
357
+ "trait_description": trait.get("traitDescription"),
358
+ "trait_accession_number": trait.get("traitPUI"),
359
+ "method": method.get("methodName"),
360
+ "method_description": method.get("description"),
361
+ "method_accession_number": method.get("methodPUI"),
362
+ "scale": scale.get("scaleName"),
363
+ "scale_accession_number": scale.get("scalePUI"),
364
+ }
365
+ ),
366
+ skip_validation=True,
367
+ )
368
+ return created
369
+
370
+
371
+ def _level(level: Any) -> dict[str, Any]:
372
+ """The unit's level as ``levelName`` and ``levelCode``, however the server put it.
373
+
374
+ BrAPI names the level (``plot``) in ``levelName`` and numbers it in
375
+ ``levelCode``. FAIDARE puts the number in ``levelName`` and the path of
376
+ level names in ``levelOrder`` (``REPLICATE>BLOCK>PLOT``), whose last
377
+ segment is the level; a unit at the top of its hierarchy has a one-level
378
+ order (``PLANT``), which is the level itself.
379
+ """
380
+ if not isinstance(level, dict):
381
+ return {}
382
+ order = level.get("levelOrder")
383
+ name = level.get("levelName")
384
+ if (
385
+ isinstance(order, str)
386
+ and order.strip()
387
+ and not order.strip().isdigit()
388
+ and (name is None or str(name).isdigit())
389
+ ):
390
+ return {"levelName": order.rsplit(">", 1)[-1].lower(), "levelCode": name}
391
+ return level
392
+
393
+
394
+ def _relationships(position: dict[str, Any]) -> list[tuple[str, str | None]]:
395
+ """``(level name, code)`` per relationship, from objects or FAIDARE's strings.
396
+
397
+ BrAPI lists objects with ``levelName`` and ``levelCode``. FAIDARE lists
398
+ strings, one per unit, of the form
399
+ ``REPLICATE>BLOCK>PLOT:223977,REPLICATE>BLOCK:5,REPLICATE:2``: a level path
400
+ and its code per comma, the level being the path's last segment.
401
+ """
402
+ found: list[tuple[str, str | None]] = []
403
+ for rel in position.get("observationLevelRelationships") or []:
404
+ if isinstance(rel, dict):
405
+ code = rel.get("levelCode")
406
+ found.append(
407
+ (
408
+ str(rel.get("levelName", "")).lower(),
409
+ str(code) if code is not None else None,
410
+ )
411
+ )
412
+ elif isinstance(rel, str):
413
+ for piece in rel.split(","):
414
+ path, _, code = piece.strip().rpartition(":")
415
+ if path:
416
+ found.append((path.rsplit(">", 1)[-1].lower(), code or None))
417
+ return found
418
+
419
+
420
+ def _level_code(position: dict[str, Any], level_names: tuple[str, ...]) -> str | None:
421
+ """Return the levelCode for a named level from observationLevelRelationships."""
422
+ for name, code in _relationships(position):
423
+ if name in level_names:
424
+ return code
425
+ return None
426
+
427
+
428
+ def _add_observed_variables(
429
+ client: MetaseedClient,
430
+ observations: list[dict[str, Any]],
431
+ default_study_id: str | None,
432
+ defined: set[tuple[str | None, str]],
433
+ ) -> None:
434
+ """Create one ObservedVariable per distinct variable referenced, unless
435
+ the server's ``variables`` already defined it for that study.
436
+
437
+ BrAPI ``observations`` carry measured values, for which MIAPPE 1.2 has no
438
+ dedicated entity; they are reduced to the distinct ObservedVariable
439
+ definitions they reference.
440
+ """
441
+ seen: set[str] = set()
442
+ for obs in observations:
443
+ variable_id = obs.get("observationVariableDbId")
444
+ if not variable_id or variable_id in seen:
445
+ continue
446
+ seen.add(variable_id)
447
+ if (obs.get("studyDbId") or default_study_id, variable_id) in defined:
448
+ continue
449
+ client.create_entity(
450
+ "ObservedVariable",
451
+ _clean(
452
+ {
453
+ "unique_id": variable_id,
454
+ "study_id": obs.get("studyDbId") or default_study_id,
455
+ "name": obs.get("observationVariableName"),
456
+ "trait": obs.get("observationVariableName"),
457
+ }
458
+ ),
459
+ skip_validation=True,
460
+ )
461
+
462
+
463
+ def _add_data_files(client: MetaseedClient, studies: list[dict[str, Any]]) -> None:
464
+ """Reference each study's BrAPI ``dataLinks`` as a DataFile entity."""
465
+ for study in studies:
466
+ study_id = study.get("studyDbId")
467
+ for link in study.get("dataLinks") or []:
468
+ url = link.get("url")
469
+ if not url:
470
+ continue
471
+ client.create_entity(
472
+ "DataFile",
473
+ _clean(
474
+ {
475
+ "unique_id": url.rsplit("/", 1)[-1] or url,
476
+ "study_id": study_id,
477
+ "name": link.get("name") or url.rsplit("/", 1)[-1],
478
+ "link": url,
479
+ "description": link.get("description"),
480
+ "file_type": link.get("type"),
481
+ }
482
+ ),
483
+ skip_validation=True,
484
+ )