deriva-ml 1.17.10__py3-none-any.whl → 1.17.11__py3-none-any.whl
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.
- deriva_ml/__init__.py +43 -1
- deriva_ml/asset/__init__.py +17 -0
- deriva_ml/asset/asset.py +357 -0
- deriva_ml/asset/aux_classes.py +100 -0
- deriva_ml/bump_version.py +254 -11
- deriva_ml/catalog/__init__.py +21 -0
- deriva_ml/catalog/clone.py +1199 -0
- deriva_ml/catalog/localize.py +426 -0
- deriva_ml/core/__init__.py +29 -0
- deriva_ml/core/base.py +817 -1067
- deriva_ml/core/config.py +169 -21
- deriva_ml/core/constants.py +120 -19
- deriva_ml/core/definitions.py +123 -13
- deriva_ml/core/enums.py +47 -73
- deriva_ml/core/ermrest.py +226 -193
- deriva_ml/core/exceptions.py +297 -14
- deriva_ml/core/filespec.py +99 -28
- deriva_ml/core/logging_config.py +225 -0
- deriva_ml/core/mixins/__init__.py +42 -0
- deriva_ml/core/mixins/annotation.py +915 -0
- deriva_ml/core/mixins/asset.py +384 -0
- deriva_ml/core/mixins/dataset.py +237 -0
- deriva_ml/core/mixins/execution.py +408 -0
- deriva_ml/core/mixins/feature.py +365 -0
- deriva_ml/core/mixins/file.py +263 -0
- deriva_ml/core/mixins/path_builder.py +145 -0
- deriva_ml/core/mixins/rid_resolution.py +204 -0
- deriva_ml/core/mixins/vocabulary.py +400 -0
- deriva_ml/core/mixins/workflow.py +322 -0
- deriva_ml/core/validation.py +389 -0
- deriva_ml/dataset/__init__.py +2 -1
- deriva_ml/dataset/aux_classes.py +20 -4
- deriva_ml/dataset/catalog_graph.py +575 -0
- deriva_ml/dataset/dataset.py +1242 -1008
- deriva_ml/dataset/dataset_bag.py +1311 -182
- deriva_ml/dataset/history.py +27 -14
- deriva_ml/dataset/upload.py +225 -38
- deriva_ml/demo_catalog.py +126 -110
- deriva_ml/execution/__init__.py +46 -2
- deriva_ml/execution/base_config.py +639 -0
- deriva_ml/execution/execution.py +543 -242
- deriva_ml/execution/execution_configuration.py +26 -11
- deriva_ml/execution/execution_record.py +592 -0
- deriva_ml/execution/find_caller.py +298 -0
- deriva_ml/execution/model_protocol.py +175 -0
- deriva_ml/execution/multirun_config.py +153 -0
- deriva_ml/execution/runner.py +595 -0
- deriva_ml/execution/workflow.py +223 -34
- deriva_ml/experiment/__init__.py +8 -0
- deriva_ml/experiment/experiment.py +411 -0
- deriva_ml/feature.py +6 -1
- deriva_ml/install_kernel.py +143 -6
- deriva_ml/interfaces.py +862 -0
- deriva_ml/model/__init__.py +99 -0
- deriva_ml/model/annotations.py +1278 -0
- deriva_ml/model/catalog.py +286 -60
- deriva_ml/model/database.py +144 -649
- deriva_ml/model/deriva_ml_database.py +308 -0
- deriva_ml/model/handles.py +14 -0
- deriva_ml/run_model.py +319 -0
- deriva_ml/run_notebook.py +507 -38
- deriva_ml/schema/__init__.py +18 -2
- deriva_ml/schema/annotations.py +62 -33
- deriva_ml/schema/create_schema.py +169 -69
- deriva_ml/schema/validation.py +601 -0
- {deriva_ml-1.17.10.dist-info → deriva_ml-1.17.11.dist-info}/METADATA +4 -4
- deriva_ml-1.17.11.dist-info/RECORD +77 -0
- {deriva_ml-1.17.10.dist-info → deriva_ml-1.17.11.dist-info}/WHEEL +1 -1
- {deriva_ml-1.17.10.dist-info → deriva_ml-1.17.11.dist-info}/entry_points.txt +1 -0
- deriva_ml/protocols/dataset.py +0 -19
- deriva_ml/test.py +0 -94
- deriva_ml-1.17.10.dist-info/RECORD +0 -45
- {deriva_ml-1.17.10.dist-info → deriva_ml-1.17.11.dist-info}/licenses/LICENSE +0 -0
- {deriva_ml-1.17.10.dist-info → deriva_ml-1.17.11.dist-info}/top_level.txt +0 -0
deriva_ml/core/base.py
CHANGED
|
@@ -14,56 +14,53 @@ Typical usage example:
|
|
|
14
14
|
from __future__ import annotations # noqa: I001
|
|
15
15
|
|
|
16
16
|
# Standard library imports
|
|
17
|
-
from collections import defaultdict
|
|
18
17
|
import logging
|
|
19
18
|
from datetime import datetime
|
|
20
|
-
from itertools import chain
|
|
21
19
|
from pathlib import Path
|
|
22
|
-
from typing import Dict,
|
|
20
|
+
from typing import Dict, List, cast, TYPE_CHECKING, Any
|
|
23
21
|
from typing_extensions import Self
|
|
24
|
-
from urllib.parse import urlsplit
|
|
25
|
-
|
|
26
22
|
|
|
27
23
|
# Third-party imports
|
|
28
24
|
import requests
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
Status,
|
|
51
|
-
TableDefinition,
|
|
52
|
-
VocabularyTerm,
|
|
53
|
-
)
|
|
25
|
+
|
|
26
|
+
# Deriva imports - use importlib to avoid shadowing by local 'deriva.py' files
|
|
27
|
+
import importlib
|
|
28
|
+
_deriva_core = importlib.import_module("deriva.core")
|
|
29
|
+
_deriva_server = importlib.import_module("deriva.core.deriva_server")
|
|
30
|
+
_ermrest_catalog = importlib.import_module("deriva.core.ermrest_catalog")
|
|
31
|
+
_ermrest_model = importlib.import_module("deriva.core.ermrest_model")
|
|
32
|
+
_core_utils = importlib.import_module("deriva.core.utils.core_utils")
|
|
33
|
+
_globus_auth_utils = importlib.import_module("deriva.core.utils.globus_auth_utils")
|
|
34
|
+
|
|
35
|
+
DEFAULT_SESSION_CONFIG = _deriva_core.DEFAULT_SESSION_CONFIG
|
|
36
|
+
get_credential = _deriva_core.get_credential
|
|
37
|
+
urlquote = _deriva_core.urlquote
|
|
38
|
+
DerivaServer = _deriva_server.DerivaServer
|
|
39
|
+
ErmrestCatalog = _ermrest_catalog.ErmrestCatalog
|
|
40
|
+
ErmrestSnapshot = _ermrest_catalog.ErmrestSnapshot
|
|
41
|
+
Table = _ermrest_model.Table
|
|
42
|
+
DEFAULT_LOGGER_OVERRIDES = _core_utils.DEFAULT_LOGGER_OVERRIDES
|
|
43
|
+
deriva_tags = _core_utils.tag
|
|
44
|
+
GlobusNativeLogin = _globus_auth_utils.GlobusNativeLogin
|
|
45
|
+
|
|
54
46
|
from deriva_ml.core.config import DerivaMLConfig
|
|
55
|
-
from deriva_ml.core.
|
|
56
|
-
from deriva_ml.
|
|
57
|
-
from deriva_ml.
|
|
58
|
-
from deriva_ml.dataset.
|
|
59
|
-
from deriva_ml.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
47
|
+
from deriva_ml.core.definitions import ML_SCHEMA, RID, Status, TableDefinition, VocabularyTableDef
|
|
48
|
+
from deriva_ml.core.exceptions import DerivaMLException
|
|
49
|
+
from deriva_ml.core.logging_config import apply_logger_overrides, configure_logging
|
|
50
|
+
from deriva_ml.dataset.upload import bulk_upload_configuration
|
|
51
|
+
from deriva_ml.interfaces import DerivaMLCatalog
|
|
52
|
+
from deriva_ml.core.mixins import (
|
|
53
|
+
AnnotationMixin,
|
|
54
|
+
VocabularyMixin,
|
|
55
|
+
RidResolutionMixin,
|
|
56
|
+
PathBuilderMixin,
|
|
57
|
+
WorkflowMixin,
|
|
58
|
+
FeatureMixin,
|
|
59
|
+
DatasetMixin,
|
|
60
|
+
AssetMixin,
|
|
61
|
+
ExecutionMixin,
|
|
62
|
+
FileMixin,
|
|
63
|
+
)
|
|
67
64
|
|
|
68
65
|
# Optional debug imports
|
|
69
66
|
try:
|
|
@@ -75,12 +72,25 @@ except ImportError: # Graceful fallback if IceCream isn't installed.
|
|
|
75
72
|
|
|
76
73
|
if TYPE_CHECKING:
|
|
77
74
|
from deriva_ml.execution.execution import Execution
|
|
75
|
+
from deriva_ml.model.catalog import DerivaModel
|
|
78
76
|
|
|
79
77
|
# Stop pycharm from complaining about undefined references.
|
|
80
78
|
ml: DerivaML
|
|
81
79
|
|
|
82
80
|
|
|
83
|
-
class DerivaML(
|
|
81
|
+
class DerivaML(
|
|
82
|
+
PathBuilderMixin,
|
|
83
|
+
RidResolutionMixin,
|
|
84
|
+
VocabularyMixin,
|
|
85
|
+
WorkflowMixin,
|
|
86
|
+
FeatureMixin,
|
|
87
|
+
DatasetMixin,
|
|
88
|
+
AssetMixin,
|
|
89
|
+
ExecutionMixin,
|
|
90
|
+
FileMixin,
|
|
91
|
+
AnnotationMixin,
|
|
92
|
+
DerivaMLCatalog,
|
|
93
|
+
):
|
|
84
94
|
"""Core class for machine learning operations on a Deriva catalog.
|
|
85
95
|
|
|
86
96
|
This class provides core functionality for managing ML workflows, features, and datasets in a Deriva catalog.
|
|
@@ -105,26 +115,79 @@ class DerivaML(Dataset):
|
|
|
105
115
|
>>> ml.add_term('vocabulary_table', 'new_term', description='Description of term')
|
|
106
116
|
"""
|
|
107
117
|
|
|
118
|
+
# Class-level type annotations for DerivaMLCatalog protocol compliance
|
|
119
|
+
ml_schema: str
|
|
120
|
+
domain_schemas: frozenset[str]
|
|
121
|
+
default_schema: str | None
|
|
122
|
+
model: DerivaModel
|
|
123
|
+
cache_dir: Path
|
|
124
|
+
working_dir: Path
|
|
125
|
+
catalog: ErmrestCatalog | ErmrestSnapshot
|
|
126
|
+
catalog_id: str | int
|
|
127
|
+
|
|
108
128
|
@classmethod
|
|
109
129
|
def instantiate(cls, config: DerivaMLConfig) -> Self:
|
|
130
|
+
"""Create a DerivaML instance from a configuration object.
|
|
131
|
+
|
|
132
|
+
This method is the preferred way to instantiate DerivaML when using hydra-zen
|
|
133
|
+
for configuration management. It accepts a DerivaMLConfig (Pydantic model) and
|
|
134
|
+
unpacks it to create the instance.
|
|
135
|
+
|
|
136
|
+
This pattern allows hydra-zen's `instantiate()` to work with DerivaML:
|
|
137
|
+
|
|
138
|
+
Example with hydra-zen:
|
|
139
|
+
>>> from hydra_zen import builds, instantiate
|
|
140
|
+
>>> from deriva_ml import DerivaML
|
|
141
|
+
>>> from deriva_ml.core.config import DerivaMLConfig
|
|
142
|
+
>>>
|
|
143
|
+
>>> # Create a structured config using hydra-zen
|
|
144
|
+
>>> DerivaMLConf = builds(DerivaMLConfig, populate_full_signature=True)
|
|
145
|
+
>>>
|
|
146
|
+
>>> # Configure for your environment
|
|
147
|
+
>>> conf = DerivaMLConf(
|
|
148
|
+
... hostname='deriva.example.org',
|
|
149
|
+
... catalog_id='42',
|
|
150
|
+
... domain_schema='my_domain',
|
|
151
|
+
... )
|
|
152
|
+
>>>
|
|
153
|
+
>>> # Instantiate the config to get a DerivaMLConfig object
|
|
154
|
+
>>> config = instantiate(conf)
|
|
155
|
+
>>>
|
|
156
|
+
>>> # Create the DerivaML instance
|
|
157
|
+
>>> ml = DerivaML.instantiate(config)
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
config: A DerivaMLConfig object containing all configuration parameters.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
A new DerivaML instance configured according to the config object.
|
|
164
|
+
|
|
165
|
+
Note:
|
|
166
|
+
The DerivaMLConfig class integrates with Hydra's configuration system
|
|
167
|
+
and registers custom resolvers for computing working directories.
|
|
168
|
+
See `deriva_ml.core.config` for details on configuration options.
|
|
169
|
+
"""
|
|
110
170
|
return cls(**config.model_dump())
|
|
111
171
|
|
|
112
172
|
def __init__(
|
|
113
173
|
self,
|
|
114
174
|
hostname: str,
|
|
115
175
|
catalog_id: str | int,
|
|
116
|
-
|
|
176
|
+
domain_schemas: set[str] | None = None,
|
|
177
|
+
default_schema: str | None = None,
|
|
117
178
|
project_name: str | None = None,
|
|
118
179
|
cache_dir: str | Path | None = None,
|
|
119
180
|
working_dir: str | Path | None = None,
|
|
120
181
|
hydra_runtime_output_dir: str | Path | None = None,
|
|
121
182
|
ml_schema: str = ML_SCHEMA,
|
|
122
|
-
logging_level=logging.WARNING,
|
|
123
|
-
deriva_logging_level=logging.WARNING,
|
|
124
|
-
credential=None,
|
|
125
|
-
|
|
183
|
+
logging_level: int = logging.WARNING,
|
|
184
|
+
deriva_logging_level: int = logging.WARNING,
|
|
185
|
+
credential: dict | None = None,
|
|
186
|
+
s3_bucket: str | None = None,
|
|
187
|
+
use_minid: bool | None = None,
|
|
126
188
|
check_auth: bool = True,
|
|
127
|
-
|
|
189
|
+
clean_execution_dir: bool = True,
|
|
190
|
+
) -> None:
|
|
128
191
|
"""Initializes a DerivaML instance.
|
|
129
192
|
|
|
130
193
|
This method will connect to a catalog and initialize local configuration for the ML execution.
|
|
@@ -133,17 +196,28 @@ class DerivaML(Dataset):
|
|
|
133
196
|
Args:
|
|
134
197
|
hostname: Hostname of the Deriva server.
|
|
135
198
|
catalog_id: Catalog ID. Either an identifier or a catalog name.
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
199
|
+
domain_schemas: Optional set of domain schema names. If None, auto-detects all
|
|
200
|
+
non-system schemas. Use this when working with catalogs that have multiple
|
|
201
|
+
user-defined schemas.
|
|
202
|
+
default_schema: The default schema for table creation operations. If None and
|
|
203
|
+
there is exactly one domain schema, that schema is used. If there are multiple
|
|
204
|
+
domain schemas, this must be specified for table creation to work without
|
|
205
|
+
explicit schema parameters.
|
|
139
206
|
ml_schema: Schema name for ML schema. Used if you have a non-standard configuration of deriva-ml.
|
|
140
|
-
project_name: Project name. Defaults to name of
|
|
207
|
+
project_name: Project name. Defaults to name of default_schema.
|
|
141
208
|
cache_dir: Directory path for caching data downloaded from the Deriva server as bdbag. If not provided,
|
|
142
209
|
will default to working_dir.
|
|
143
210
|
working_dir: Directory path for storing data used by or generated by any computations. If no value is
|
|
144
211
|
provided, will default to ${HOME}/deriva_ml
|
|
145
|
-
|
|
212
|
+
s3_bucket: S3 bucket URL for dataset bag storage (e.g., 's3://my-bucket'). If provided,
|
|
213
|
+
enables MINID creation and S3 upload for dataset exports. If None, MINID functionality
|
|
214
|
+
is disabled regardless of use_minid setting.
|
|
215
|
+
use_minid: Use the MINID service when downloading dataset bags. Only effective when
|
|
216
|
+
s3_bucket is configured. If None (default), automatically set to True when s3_bucket
|
|
217
|
+
is provided, False otherwise.
|
|
146
218
|
check_auth: Check if the user has access to the catalog.
|
|
219
|
+
clean_execution_dir: Whether to automatically clean up execution working directories
|
|
220
|
+
after successful upload. Defaults to True. Set to False to retain local copies.
|
|
147
221
|
"""
|
|
148
222
|
# Get or use provided credentials for server access
|
|
149
223
|
self.credential = credential or get_credential(hostname)
|
|
@@ -164,32 +238,46 @@ class DerivaML(Dataset):
|
|
|
164
238
|
"Please check your credentials and make sure you have logged in."
|
|
165
239
|
)
|
|
166
240
|
self.catalog = server.connect_ermrest(catalog_id)
|
|
167
|
-
|
|
241
|
+
# Import here to avoid circular imports
|
|
242
|
+
from deriva_ml.model.catalog import DerivaModel
|
|
243
|
+
self.model = DerivaModel(
|
|
244
|
+
self.catalog.getCatalogModel(),
|
|
245
|
+
ml_schema=ml_schema,
|
|
246
|
+
domain_schemas=domain_schemas,
|
|
247
|
+
default_schema=default_schema,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
# Store S3 bucket configuration and resolve use_minid
|
|
251
|
+
self.s3_bucket = s3_bucket
|
|
252
|
+
if use_minid is None:
|
|
253
|
+
# Auto mode: enable MINID if s3_bucket is configured
|
|
254
|
+
self.use_minid = s3_bucket is not None
|
|
255
|
+
elif use_minid and s3_bucket is None:
|
|
256
|
+
# User requested MINID but no S3 bucket configured - disable MINID
|
|
257
|
+
self.use_minid = False
|
|
258
|
+
else:
|
|
259
|
+
self.use_minid = use_minid
|
|
168
260
|
|
|
169
261
|
# Set up working and cache directories
|
|
170
|
-
self.working_dir = DerivaMLConfig.compute_workdir(working_dir)
|
|
262
|
+
self.working_dir = DerivaMLConfig.compute_workdir(working_dir, catalog_id)
|
|
171
263
|
self.working_dir.mkdir(parents=True, exist_ok=True)
|
|
172
264
|
self.hydra_runtime_output_dir = hydra_runtime_output_dir
|
|
173
265
|
|
|
174
266
|
self.cache_dir = Path(cache_dir) if cache_dir else self.working_dir / "cache"
|
|
175
267
|
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
176
268
|
|
|
177
|
-
#
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
269
|
+
# Set up logging using centralized configuration
|
|
270
|
+
# This configures deriva_ml, Hydra, and deriva-py loggers without
|
|
271
|
+
# affecting the root logger or calling basicConfig()
|
|
272
|
+
self._logger = configure_logging(
|
|
273
|
+
level=logging_level,
|
|
274
|
+
deriva_level=deriva_logging_level,
|
|
275
|
+
)
|
|
183
276
|
self._logging_level = logging_level
|
|
184
277
|
self._deriva_logging_level = deriva_logging_level
|
|
185
278
|
|
|
186
|
-
#
|
|
187
|
-
|
|
188
|
-
# allow for reconfiguration of module-specific logging levels
|
|
189
|
-
[logging.getLogger(name).setLevel(level) for name, level in logger_config.items()]
|
|
190
|
-
logging.getLogger("root").setLevel(deriva_logging_level)
|
|
191
|
-
logging.getLogger("bagit").setLevel(deriva_logging_level)
|
|
192
|
-
logging.getLogger("bdbag").setLevel(deriva_logging_level)
|
|
279
|
+
# Apply deriva's default logger overrides for fine-grained control
|
|
280
|
+
apply_logger_overrides(DEFAULT_LOGGER_OVERRIDES)
|
|
193
281
|
|
|
194
282
|
# Store instance configuration
|
|
195
283
|
self.host_name = hostname
|
|
@@ -197,22 +285,14 @@ class DerivaML(Dataset):
|
|
|
197
285
|
self.ml_schema = ml_schema
|
|
198
286
|
self.configuration = None
|
|
199
287
|
self._execution: Execution | None = None
|
|
200
|
-
self.
|
|
201
|
-
self.
|
|
288
|
+
self.domain_schemas = self.model.domain_schemas
|
|
289
|
+
self.default_schema = self.model.default_schema
|
|
290
|
+
self.project_name = project_name or self.default_schema or "deriva-ml"
|
|
202
291
|
self.start_time = datetime.now()
|
|
203
292
|
self.status = Status.pending.value
|
|
293
|
+
self.clean_execution_dir = clean_execution_dir
|
|
204
294
|
|
|
205
|
-
|
|
206
|
-
logging.basicConfig(
|
|
207
|
-
level=logging_level,
|
|
208
|
-
format="%(asctime)s - %(name)s.%(levelname)s - %(message)s",
|
|
209
|
-
)
|
|
210
|
-
|
|
211
|
-
# Set Deriva library logging level
|
|
212
|
-
deriva_logger = logging.getLogger("deriva")
|
|
213
|
-
deriva_logger.setLevel(logging_level)
|
|
214
|
-
|
|
215
|
-
def __del__(self):
|
|
295
|
+
def __del__(self) -> None:
|
|
216
296
|
"""Cleanup method to handle incomplete executions."""
|
|
217
297
|
try:
|
|
218
298
|
# Mark execution as aborted if not completed
|
|
@@ -222,7 +302,7 @@ class DerivaML(Dataset):
|
|
|
222
302
|
pass
|
|
223
303
|
|
|
224
304
|
@staticmethod
|
|
225
|
-
def _get_session_config():
|
|
305
|
+
def _get_session_config() -> dict:
|
|
226
306
|
"""Returns customized HTTP session configuration.
|
|
227
307
|
|
|
228
308
|
Configures retry behavior and connection settings for HTTP requests to the Deriva server. Settings include:
|
|
@@ -254,58 +334,23 @@ class DerivaML(Dataset):
|
|
|
254
334
|
)
|
|
255
335
|
return session_config
|
|
256
336
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
"""Returns catalog path builder for queries.
|
|
337
|
+
def is_snapshot(self) -> bool:
|
|
338
|
+
return hasattr(self.catalog, "_snaptime")
|
|
260
339
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
>>> results = path.entities().fetch()
|
|
270
|
-
"""
|
|
271
|
-
return self.catalog.getPathBuilder()
|
|
340
|
+
def catalog_snapshot(self, version_snapshot: str) -> Self:
|
|
341
|
+
"""Returns a DerivaML instance for a specific snapshot of the catalog."""
|
|
342
|
+
return DerivaML(
|
|
343
|
+
self.host_name,
|
|
344
|
+
version_snapshot,
|
|
345
|
+
logging_level=self._logging_level,
|
|
346
|
+
deriva_logging_level=self._deriva_logging_level,
|
|
347
|
+
)
|
|
272
348
|
|
|
273
349
|
@property
|
|
274
|
-
def
|
|
275
|
-
""
|
|
276
|
-
|
|
277
|
-
Provides a convenient way to access tables and construct queries within the domain-specific schema.
|
|
278
|
-
|
|
279
|
-
Returns:
|
|
280
|
-
datapath._CatalogWrapper: Path builder object scoped to the domain schema.
|
|
281
|
-
|
|
282
|
-
Example:
|
|
283
|
-
>>> domain = ml.domain_path
|
|
284
|
-
>>> results = domain.my_table.entities().fetch()
|
|
285
|
-
"""
|
|
286
|
-
return self.pathBuilder.schemas[self.domain_schema]
|
|
287
|
-
|
|
288
|
-
def table_path(self, table: str | Table) -> Path:
|
|
289
|
-
"""Returns a local filesystem path for table CSV files.
|
|
350
|
+
def _dataset_table(self) -> Table:
|
|
351
|
+
return self.model.schemas[self.model.ml_schema].tables["Dataset"]
|
|
290
352
|
|
|
291
|
-
|
|
292
|
-
The path follows the project's directory structure conventions.
|
|
293
|
-
|
|
294
|
-
Args:
|
|
295
|
-
table: Name of the table or Table object to get the path for.
|
|
296
|
-
|
|
297
|
-
Returns:
|
|
298
|
-
Path: Filesystem path where the CSV file should be placed.
|
|
299
|
-
|
|
300
|
-
Example:
|
|
301
|
-
>>> path = ml.table_path("experiment_results")
|
|
302
|
-
>>> df.to_csv(path) # Save data for upload
|
|
303
|
-
"""
|
|
304
|
-
return table_path(
|
|
305
|
-
self.working_dir,
|
|
306
|
-
schema=self.domain_schema,
|
|
307
|
-
table=self.model.name_to_table(table).name,
|
|
308
|
-
)
|
|
353
|
+
# pathBuilder, domain_path, table_path moved to PathBuilderMixin
|
|
309
354
|
|
|
310
355
|
def download_dir(self, cached: bool = False) -> Path:
|
|
311
356
|
"""Returns the appropriate download directory.
|
|
@@ -384,27 +429,37 @@ class DerivaML(Dataset):
|
|
|
384
429
|
uri = self.cite(cast(str, table))
|
|
385
430
|
return f"{uri}/{urlquote(table_obj.schema.name)}:{urlquote(table_obj.name)}"
|
|
386
431
|
|
|
387
|
-
def cite(self, entity: Dict[str, Any] | str) -> str:
|
|
388
|
-
"""Generates
|
|
432
|
+
def cite(self, entity: Dict[str, Any] | str, current: bool = False) -> str:
|
|
433
|
+
"""Generates citation URL for an entity.
|
|
389
434
|
|
|
390
|
-
Creates a
|
|
391
|
-
the catalog snapshot time to ensure version stability
|
|
435
|
+
Creates a URL that can be used to reference a specific entity in the catalog.
|
|
436
|
+
By default, includes the catalog snapshot time to ensure version stability
|
|
437
|
+
(permanent citation). With current=True, returns a URL to the current state.
|
|
392
438
|
|
|
393
439
|
Args:
|
|
394
440
|
entity: Either a RID string or a dictionary containing entity data with a 'RID' key.
|
|
441
|
+
current: If True, return URL to current catalog state (no snapshot).
|
|
442
|
+
If False (default), return permanent citation URL with snapshot time.
|
|
395
443
|
|
|
396
444
|
Returns:
|
|
397
|
-
str:
|
|
445
|
+
str: Citation URL. Format depends on `current` parameter:
|
|
446
|
+
- current=False: https://{host}/id/{catalog}/{rid}@{snapshot_time}
|
|
447
|
+
- current=True: https://{host}/id/{catalog}/{rid}
|
|
398
448
|
|
|
399
449
|
Raises:
|
|
400
450
|
DerivaMLException: If an entity doesn't exist or lacks a RID.
|
|
401
451
|
|
|
402
452
|
Examples:
|
|
403
|
-
|
|
453
|
+
Permanent citation (default):
|
|
404
454
|
>>> url = ml.cite("1-abc123")
|
|
405
455
|
>>> print(url)
|
|
406
456
|
'https://deriva.org/id/1/1-abc123@2024-01-01T12:00:00'
|
|
407
457
|
|
|
458
|
+
Current catalog URL:
|
|
459
|
+
>>> url = ml.cite("1-abc123", current=True)
|
|
460
|
+
>>> print(url)
|
|
461
|
+
'https://deriva.org/id/1/1-abc123'
|
|
462
|
+
|
|
408
463
|
Using a dictionary:
|
|
409
464
|
>>> url = ml.cite({"RID": "1-abc123"})
|
|
410
465
|
"""
|
|
@@ -413,9 +468,12 @@ class DerivaML(Dataset):
|
|
|
413
468
|
return entity
|
|
414
469
|
|
|
415
470
|
try:
|
|
416
|
-
# Resolve RID and create citation URL
|
|
471
|
+
# Resolve RID and create citation URL
|
|
417
472
|
self.resolve_rid(rid := entity if isinstance(entity, str) else entity["RID"])
|
|
418
|
-
|
|
473
|
+
base_url = f"https://{self.host_name}/id/{self.catalog_id}/{rid}"
|
|
474
|
+
if current:
|
|
475
|
+
return base_url
|
|
476
|
+
return f"{base_url}@{self.catalog.latest_snapshot().snaptime}"
|
|
419
477
|
except KeyError as e:
|
|
420
478
|
raise DerivaMLException(f"Entity {e} does not have RID column")
|
|
421
479
|
except DerivaMLException as _e:
|
|
@@ -439,59 +497,247 @@ class DerivaML(Dataset):
|
|
|
439
497
|
... print(f"{user['Full_Name']} ({user['ID']})")
|
|
440
498
|
"""
|
|
441
499
|
# Get the user table path and fetch basic user info
|
|
442
|
-
user_path = self.pathBuilder.public.ERMrest_Client.path
|
|
500
|
+
user_path = self.pathBuilder().public.ERMrest_Client.path
|
|
443
501
|
return [{"ID": u["ID"], "Full_Name": u["Full_Name"]} for u in user_path.entities().fetch()]
|
|
444
502
|
|
|
445
|
-
|
|
446
|
-
"""Resolves RID to catalog location.
|
|
503
|
+
# resolve_rid, retrieve_rid moved to RidResolutionMixin
|
|
447
504
|
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
""
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
505
|
+
def apply_catalog_annotations(
|
|
506
|
+
self,
|
|
507
|
+
navbar_brand_text: str = "ML Data Browser",
|
|
508
|
+
head_title: str = "Catalog ML",
|
|
509
|
+
) -> None:
|
|
510
|
+
"""Apply catalog-level annotations including the navigation bar and display settings.
|
|
511
|
+
|
|
512
|
+
This method configures the Chaise web interface for the catalog. Chaise is Deriva's
|
|
513
|
+
web-based data browser that provides a user-friendly interface for exploring and
|
|
514
|
+
managing catalog data. This method sets up annotations that control how Chaise
|
|
515
|
+
displays and organizes the catalog.
|
|
516
|
+
|
|
517
|
+
**Navigation Bar Structure**:
|
|
518
|
+
The method creates a navigation bar with the following menus:
|
|
519
|
+
- **User Info**: Links to Users, Groups, and RID Lease tables
|
|
520
|
+
- **Deriva-ML**: Core ML tables (Workflow, Execution, Dataset, Dataset_Version, etc.)
|
|
521
|
+
- **WWW**: Web content tables (Page, File)
|
|
522
|
+
- **{Domain Schema}**: All domain-specific tables (excludes vocabularies and associations)
|
|
523
|
+
- **Vocabulary**: All controlled vocabulary tables from both ML and domain schemas
|
|
524
|
+
- **Assets**: All asset tables from both ML and domain schemas
|
|
525
|
+
- **Features**: All feature tables with entries named "TableName:FeatureName"
|
|
526
|
+
- **Catalog Registry**: Link to the ermrest registry
|
|
527
|
+
- **Documentation**: Links to ML notebook instructions and Deriva-ML docs
|
|
528
|
+
|
|
529
|
+
**Display Settings**:
|
|
530
|
+
- Underscores in table/column names displayed as spaces
|
|
531
|
+
- System columns (RID) shown in compact and entry views
|
|
532
|
+
- Default table set to Dataset
|
|
533
|
+
- Faceting and record deletion enabled
|
|
534
|
+
- Export configurations available to all users
|
|
535
|
+
|
|
536
|
+
**Bulk Upload Configuration**:
|
|
537
|
+
Configures upload patterns for asset tables, enabling drag-and-drop file uploads
|
|
538
|
+
through the Chaise interface.
|
|
539
|
+
|
|
540
|
+
Call this after creating the domain schema and all tables to initialize the catalog's
|
|
541
|
+
web interface. The navigation menus are dynamically built based on the current schema
|
|
542
|
+
structure, automatically organizing tables into appropriate categories.
|
|
479
543
|
|
|
480
544
|
Args:
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
Returns:
|
|
484
|
-
dict[str, Any]: Dictionary containing all column values for the entity.
|
|
485
|
-
|
|
486
|
-
Raises:
|
|
487
|
-
DerivaMLException: If the RID doesn't exist in the catalog.
|
|
545
|
+
navbar_brand_text: Text displayed in the navigation bar brand area.
|
|
546
|
+
head_title: Title displayed in the browser tab.
|
|
488
547
|
|
|
489
548
|
Example:
|
|
490
|
-
>>>
|
|
491
|
-
>>>
|
|
549
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
550
|
+
>>> # After creating domain schema and tables...
|
|
551
|
+
>>> ml.apply_catalog_annotations()
|
|
552
|
+
>>> # Or with custom branding:
|
|
553
|
+
>>> ml.apply_catalog_annotations("My Project Browser", "My ML Project")
|
|
492
554
|
"""
|
|
493
|
-
|
|
494
|
-
|
|
555
|
+
catalog_id = self.model.catalog.catalog_id
|
|
556
|
+
ml_schema = self.ml_schema
|
|
557
|
+
|
|
558
|
+
# Build domain schema menu items (one menu per domain schema)
|
|
559
|
+
domain_schema_menus = []
|
|
560
|
+
for domain_schema in sorted(self.domain_schemas):
|
|
561
|
+
if domain_schema not in self.model.schemas:
|
|
562
|
+
continue
|
|
563
|
+
domain_schema_menus.append({
|
|
564
|
+
"name": domain_schema,
|
|
565
|
+
"children": [
|
|
566
|
+
{
|
|
567
|
+
"name": tname,
|
|
568
|
+
"url": f"/chaise/recordset/#{catalog_id}/{domain_schema}:{tname}",
|
|
569
|
+
}
|
|
570
|
+
for tname in self.model.schemas[domain_schema].tables
|
|
571
|
+
# Don't include controlled vocabularies, association tables, or feature tables.
|
|
572
|
+
if not (
|
|
573
|
+
self.model.is_vocabulary(tname)
|
|
574
|
+
or self.model.is_association(tname, pure=False, max_arity=3)
|
|
575
|
+
)
|
|
576
|
+
],
|
|
577
|
+
})
|
|
578
|
+
|
|
579
|
+
# Build vocabulary menu items (ML schema + all domain schemas)
|
|
580
|
+
vocab_children = [{"name": f"{ml_schema} Vocabularies", "header": True}]
|
|
581
|
+
vocab_children.extend([
|
|
582
|
+
{
|
|
583
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:{tname}",
|
|
584
|
+
"name": tname,
|
|
585
|
+
}
|
|
586
|
+
for tname in self.model.schemas[ml_schema].tables
|
|
587
|
+
if self.model.is_vocabulary(tname)
|
|
588
|
+
])
|
|
589
|
+
for domain_schema in sorted(self.domain_schemas):
|
|
590
|
+
if domain_schema not in self.model.schemas:
|
|
591
|
+
continue
|
|
592
|
+
vocab_children.append({"name": f"{domain_schema} Vocabularies", "header": True})
|
|
593
|
+
vocab_children.extend([
|
|
594
|
+
{
|
|
595
|
+
"url": f"/chaise/recordset/#{catalog_id}/{domain_schema}:{tname}",
|
|
596
|
+
"name": tname,
|
|
597
|
+
}
|
|
598
|
+
for tname in self.model.schemas[domain_schema].tables
|
|
599
|
+
if self.model.is_vocabulary(tname)
|
|
600
|
+
])
|
|
601
|
+
|
|
602
|
+
# Build asset menu items (ML schema + all domain schemas)
|
|
603
|
+
asset_children = [
|
|
604
|
+
{
|
|
605
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:{tname}",
|
|
606
|
+
"name": tname,
|
|
607
|
+
}
|
|
608
|
+
for tname in self.model.schemas[ml_schema].tables
|
|
609
|
+
if self.model.is_asset(tname)
|
|
610
|
+
]
|
|
611
|
+
for domain_schema in sorted(self.domain_schemas):
|
|
612
|
+
if domain_schema not in self.model.schemas:
|
|
613
|
+
continue
|
|
614
|
+
asset_children.extend([
|
|
615
|
+
{
|
|
616
|
+
"url": f"/chaise/recordset/#{catalog_id}/{domain_schema}:{tname}",
|
|
617
|
+
"name": tname,
|
|
618
|
+
}
|
|
619
|
+
for tname in self.model.schemas[domain_schema].tables
|
|
620
|
+
if self.model.is_asset(tname)
|
|
621
|
+
])
|
|
622
|
+
|
|
623
|
+
catalog_annotation = {
|
|
624
|
+
deriva_tags.display: {"name_style": {"underline_space": True}},
|
|
625
|
+
deriva_tags.chaise_config: {
|
|
626
|
+
"headTitle": head_title,
|
|
627
|
+
"navbarBrandText": navbar_brand_text,
|
|
628
|
+
"systemColumnsDisplayEntry": ["RID"],
|
|
629
|
+
"systemColumnsDisplayCompact": ["RID"],
|
|
630
|
+
"defaultTable": {"table": "Dataset", "schema": "deriva-ml"},
|
|
631
|
+
"deleteRecord": True,
|
|
632
|
+
"showFaceting": True,
|
|
633
|
+
"shareCiteAcls": True,
|
|
634
|
+
"exportConfigsSubmenu": {"acls": {"show": ["*"], "enable": ["*"]}},
|
|
635
|
+
"resolverImplicitCatalog": False,
|
|
636
|
+
"navbarMenu": {
|
|
637
|
+
"newTab": False,
|
|
638
|
+
"children": [
|
|
639
|
+
{
|
|
640
|
+
"name": "User Info",
|
|
641
|
+
"children": [
|
|
642
|
+
{
|
|
643
|
+
"url": f"/chaise/recordset/#{catalog_id}/public:ERMrest_Client",
|
|
644
|
+
"name": "Users",
|
|
645
|
+
},
|
|
646
|
+
{
|
|
647
|
+
"url": f"/chaise/recordset/#{catalog_id}/public:ERMrest_Group",
|
|
648
|
+
"name": "Groups",
|
|
649
|
+
},
|
|
650
|
+
{
|
|
651
|
+
"url": f"/chaise/recordset/#{catalog_id}/public:ERMrest_RID_Lease",
|
|
652
|
+
"name": "ERMrest RID Lease",
|
|
653
|
+
},
|
|
654
|
+
],
|
|
655
|
+
},
|
|
656
|
+
{ # All the primary tables in deriva-ml schema.
|
|
657
|
+
"name": "Deriva-ML",
|
|
658
|
+
"children": [
|
|
659
|
+
{
|
|
660
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Workflow",
|
|
661
|
+
"name": "Workflow",
|
|
662
|
+
},
|
|
663
|
+
{
|
|
664
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Execution",
|
|
665
|
+
"name": "Execution",
|
|
666
|
+
},
|
|
667
|
+
{
|
|
668
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Execution_Metadata",
|
|
669
|
+
"name": "Execution Metadata",
|
|
670
|
+
},
|
|
671
|
+
{
|
|
672
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Execution_Asset",
|
|
673
|
+
"name": "Execution Asset",
|
|
674
|
+
},
|
|
675
|
+
{
|
|
676
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Dataset",
|
|
677
|
+
"name": "Dataset",
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
"url": f"/chaise/recordset/#{catalog_id}/{ml_schema}:Dataset_Version",
|
|
681
|
+
"name": "Dataset Version",
|
|
682
|
+
},
|
|
683
|
+
],
|
|
684
|
+
},
|
|
685
|
+
{ # WWW schema tables.
|
|
686
|
+
"name": "WWW",
|
|
687
|
+
"children": [
|
|
688
|
+
{
|
|
689
|
+
"url": f"/chaise/recordset/#{catalog_id}/WWW:Page",
|
|
690
|
+
"name": "Page",
|
|
691
|
+
},
|
|
692
|
+
{
|
|
693
|
+
"url": f"/chaise/recordset/#{catalog_id}/WWW:File",
|
|
694
|
+
"name": "File",
|
|
695
|
+
},
|
|
696
|
+
],
|
|
697
|
+
},
|
|
698
|
+
*domain_schema_menus, # One menu per domain schema
|
|
699
|
+
{ # Vocabulary menu with all controlled vocabularies.
|
|
700
|
+
"name": "Vocabulary",
|
|
701
|
+
"children": vocab_children,
|
|
702
|
+
},
|
|
703
|
+
{ # List of all asset tables.
|
|
704
|
+
"name": "Assets",
|
|
705
|
+
"children": asset_children,
|
|
706
|
+
},
|
|
707
|
+
{ # List of all feature tables in the catalog.
|
|
708
|
+
"name": "Features",
|
|
709
|
+
"children": [
|
|
710
|
+
{
|
|
711
|
+
"url": f"/chaise/recordset/#{catalog_id}/{f.feature_table.schema.name}:{f.feature_table.name}",
|
|
712
|
+
"name": f"{f.target_table.name}:{f.feature_name}",
|
|
713
|
+
}
|
|
714
|
+
for f in self.model.find_features()
|
|
715
|
+
],
|
|
716
|
+
},
|
|
717
|
+
{
|
|
718
|
+
"url": "/chaise/recordset/#0/ermrest:registry@sort(RID)",
|
|
719
|
+
"name": "Catalog Registry",
|
|
720
|
+
},
|
|
721
|
+
{
|
|
722
|
+
"name": "Documentation",
|
|
723
|
+
"children": [
|
|
724
|
+
{
|
|
725
|
+
"url": "https://github.com/informatics-isi-edu/deriva-ml/blob/main/docs/ml_workflow_instruction.md",
|
|
726
|
+
"name": "ML Notebook Instruction",
|
|
727
|
+
},
|
|
728
|
+
{
|
|
729
|
+
"url": "https://informatics-isi-edu.github.io/deriva-ml/",
|
|
730
|
+
"name": "Deriva-ML Documentation",
|
|
731
|
+
},
|
|
732
|
+
],
|
|
733
|
+
},
|
|
734
|
+
],
|
|
735
|
+
},
|
|
736
|
+
},
|
|
737
|
+
deriva_tags.bulk_upload: bulk_upload_configuration(model=self.model),
|
|
738
|
+
}
|
|
739
|
+
self.model.annotations.update(catalog_annotation)
|
|
740
|
+
self.model.apply()
|
|
495
741
|
|
|
496
742
|
def add_page(self, title: str, content: str) -> None:
|
|
497
743
|
"""Adds page to web interface.
|
|
@@ -513,9 +759,15 @@ class DerivaML(Dataset):
|
|
|
513
759
|
... )
|
|
514
760
|
"""
|
|
515
761
|
# Insert page into www tables with title and content
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
762
|
+
# Use default schema or first domain schema for www tables
|
|
763
|
+
schema = self.default_schema or (sorted(self.domain_schemas)[0] if self.domain_schemas else None)
|
|
764
|
+
if schema is None:
|
|
765
|
+
raise DerivaMLException("No domain schema available for adding pages")
|
|
766
|
+
self.pathBuilder().www.tables[schema].insert([{"Title": title, "Content": content}])
|
|
767
|
+
|
|
768
|
+
def create_vocabulary(
|
|
769
|
+
self, vocab_name: str, comment: str = "", schema: str | None = None, update_navbar: bool = True
|
|
770
|
+
) -> Table:
|
|
519
771
|
"""Creates a controlled vocabulary table.
|
|
520
772
|
|
|
521
773
|
A controlled vocabulary table maintains a list of standardized terms and their definitions. Each term can have
|
|
@@ -525,6 +777,9 @@ class DerivaML(Dataset):
|
|
|
525
777
|
vocab_name: Name for the new vocabulary table. Must be a valid SQL identifier.
|
|
526
778
|
comment: Description of the vocabulary's purpose and usage. Defaults to empty string.
|
|
527
779
|
schema: Schema name to create the table in. If None, uses domain_schema.
|
|
780
|
+
update_navbar: If True (default), automatically updates the navigation bar to include
|
|
781
|
+
the new vocabulary table. Set to False during batch table creation to avoid
|
|
782
|
+
redundant updates, then call apply_catalog_annotations() once at the end.
|
|
528
783
|
|
|
529
784
|
Returns:
|
|
530
785
|
Table: ERMRest table object representing the newly created vocabulary table.
|
|
@@ -540,988 +795,483 @@ class DerivaML(Dataset):
|
|
|
540
795
|
... comment="Standard tissue classifications",
|
|
541
796
|
... schema="bio_schema"
|
|
542
797
|
... )
|
|
798
|
+
|
|
799
|
+
Create multiple vocabularies without updating navbar until the end:
|
|
800
|
+
|
|
801
|
+
>>> ml.create_vocabulary("Species", update_navbar=False)
|
|
802
|
+
>>> ml.create_vocabulary("Tissue_Type", update_navbar=False)
|
|
803
|
+
>>> ml.apply_catalog_annotations() # Update navbar once
|
|
543
804
|
"""
|
|
544
|
-
# Use
|
|
545
|
-
schema = schema or self.
|
|
805
|
+
# Use default schema if none specified
|
|
806
|
+
schema = schema or self.model._require_default_schema()
|
|
546
807
|
|
|
547
808
|
# Create and return vocabulary table with RID-based URI pattern
|
|
548
809
|
try:
|
|
549
810
|
vocab_table = self.model.schemas[schema].create_table(
|
|
550
|
-
|
|
811
|
+
VocabularyTableDef(
|
|
812
|
+
name=vocab_name,
|
|
813
|
+
curie_template=f"{self.project_name}:{{RID}}",
|
|
814
|
+
comment=comment,
|
|
815
|
+
)
|
|
551
816
|
)
|
|
552
817
|
except ValueError:
|
|
553
818
|
raise DerivaMLException(f"Table {vocab_name} already exist")
|
|
554
|
-
return vocab_table
|
|
555
|
-
|
|
556
|
-
def create_table(self, table: TableDefinition) -> Table:
|
|
557
|
-
"""Creates a new table in the catalog.
|
|
558
|
-
|
|
559
|
-
Creates a table using the provided TableDefinition object, which specifies the table structure including
|
|
560
|
-
columns, keys, and foreign key relationships.
|
|
561
|
-
|
|
562
|
-
Args:
|
|
563
|
-
table: A TableDefinition object containing the complete specification of the table to create.
|
|
564
|
-
|
|
565
|
-
Returns:
|
|
566
|
-
Table: The newly created ERMRest table object.
|
|
567
|
-
|
|
568
|
-
Raises:
|
|
569
|
-
DerivaMLException: If table creation fails or the definition is invalid.
|
|
570
|
-
|
|
571
|
-
Example:
|
|
572
|
-
|
|
573
|
-
>>> table_def = TableDefinition(
|
|
574
|
-
... name="experiments",
|
|
575
|
-
... column_definitions=[
|
|
576
|
-
... ColumnDefinition(name="name", type=BuiltinTypes.text),
|
|
577
|
-
... ColumnDefinition(name="date", type=BuiltinTypes.date)
|
|
578
|
-
... ]
|
|
579
|
-
... )
|
|
580
|
-
>>> new_table = ml.create_table(table_def)
|
|
581
|
-
"""
|
|
582
|
-
# Create table in domain schema using provided definition
|
|
583
|
-
return self.model.schemas[self.domain_schema].create_table(table.model_dump())
|
|
584
|
-
|
|
585
|
-
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
|
|
586
|
-
def create_asset(
|
|
587
|
-
self,
|
|
588
|
-
asset_name: str,
|
|
589
|
-
column_defs: Iterable[ColumnDefinition] | None = None,
|
|
590
|
-
fkey_defs: Iterable[ColumnDefinition] | None = None,
|
|
591
|
-
referenced_tables: Iterable[Table] | None = None,
|
|
592
|
-
comment: str = "",
|
|
593
|
-
schema: str | None = None,
|
|
594
|
-
) -> Table:
|
|
595
|
-
"""Creates an asset table.
|
|
596
|
-
|
|
597
|
-
Args:
|
|
598
|
-
asset_name: Name of the asset table.
|
|
599
|
-
column_defs: Iterable of ColumnDefinition objects to provide additional metadata for asset.
|
|
600
|
-
fkey_defs: Iterable of ForeignKeyDefinition objects to provide additional metadata for asset.
|
|
601
|
-
referenced_tables: Iterable of Table objects to which asset should provide foreign-key references to.
|
|
602
|
-
comment: Description of the asset table. (Default value = '')
|
|
603
|
-
schema: Schema in which to create the asset table. Defaults to domain_schema.
|
|
604
|
-
|
|
605
|
-
Returns:
|
|
606
|
-
Table object for the asset table.
|
|
607
|
-
"""
|
|
608
|
-
# Initialize empty collections if None provided
|
|
609
|
-
column_defs = column_defs or []
|
|
610
|
-
fkey_defs = fkey_defs or []
|
|
611
|
-
referenced_tables = referenced_tables or []
|
|
612
|
-
schema = schema or self.domain_schema
|
|
613
|
-
|
|
614
|
-
# Add an asset type to vocabulary
|
|
615
|
-
self.add_term(MLVocab.asset_type, asset_name, description=f"A {asset_name} asset")
|
|
616
|
-
|
|
617
|
-
# Create the main asset table
|
|
618
|
-
asset_table = self.model.schemas[schema].create_table(
|
|
619
|
-
Table.define_asset(
|
|
620
|
-
schema,
|
|
621
|
-
asset_name,
|
|
622
|
-
column_defs=[c.model_dump() for c in column_defs],
|
|
623
|
-
fkey_defs=[fk.model_dump() for fk in fkey_defs],
|
|
624
|
-
comment=comment,
|
|
625
|
-
)
|
|
626
|
-
)
|
|
627
819
|
|
|
628
|
-
#
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
[
|
|
632
|
-
(asset_table.name, asset_table),
|
|
633
|
-
("Asset_Type", self.model.name_to_table("Asset_Type")),
|
|
634
|
-
]
|
|
635
|
-
)
|
|
636
|
-
)
|
|
637
|
-
|
|
638
|
-
# Create references to other tables if specified
|
|
639
|
-
for t in referenced_tables:
|
|
640
|
-
asset_table.create_reference(self.model.name_to_table(t))
|
|
641
|
-
|
|
642
|
-
# Create an association table for tracking execution
|
|
643
|
-
atable = self.model.schemas[self.domain_schema].create_table(
|
|
644
|
-
Table.define_association(
|
|
645
|
-
[
|
|
646
|
-
(asset_name, asset_table),
|
|
647
|
-
(
|
|
648
|
-
"Execution",
|
|
649
|
-
self.model.schemas[self.ml_schema].tables["Execution"],
|
|
650
|
-
),
|
|
651
|
-
]
|
|
652
|
-
)
|
|
653
|
-
)
|
|
654
|
-
atable.create_reference(self.model.name_to_table("Asset_Role"))
|
|
820
|
+
# Update navbar to include the new vocabulary table
|
|
821
|
+
if update_navbar:
|
|
822
|
+
self.apply_catalog_annotations()
|
|
655
823
|
|
|
656
|
-
|
|
657
|
-
asset_annotation(asset_table)
|
|
658
|
-
return asset_table
|
|
824
|
+
return vocab_table
|
|
659
825
|
|
|
660
|
-
def
|
|
661
|
-
"""
|
|
826
|
+
def create_table(self, table: TableDefinition, schema: str | None = None, update_navbar: bool = True) -> Table:
|
|
827
|
+
"""Creates a new table in the domain schema.
|
|
662
828
|
|
|
663
|
-
|
|
829
|
+
Creates a table using the provided TableDefinition object, which specifies the table structure
|
|
830
|
+
including columns, keys, and foreign key relationships. The table is created in the domain
|
|
831
|
+
schema associated with this DerivaML instance.
|
|
664
832
|
|
|
665
|
-
|
|
666
|
-
|
|
833
|
+
**Required Classes**:
|
|
834
|
+
Import the following classes from deriva_ml to define tables:
|
|
667
835
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
836
|
+
- ``TableDefinition``: Defines the complete table structure
|
|
837
|
+
- ``ColumnDefinition``: Defines individual columns with types and constraints
|
|
838
|
+
- ``KeyDefinition``: Defines unique key constraints (optional)
|
|
839
|
+
- ``ForeignKeyDefinition``: Defines foreign key relationships to other tables (optional)
|
|
840
|
+
- ``BuiltinTypes``: Enum of available column data types
|
|
673
841
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
>>> for asset in assets:
|
|
680
|
-
... print(f"{asset['RID']}: {asset['Type']}")
|
|
681
|
-
"""
|
|
682
|
-
# Validate and get asset table reference
|
|
683
|
-
asset_table = self.model.name_to_table(asset_table)
|
|
684
|
-
if not self.model.is_asset(asset_table):
|
|
685
|
-
raise DerivaMLException(f"Table {asset_table.name} is not an asset")
|
|
686
|
-
|
|
687
|
-
# Get path builders for asset and type tables
|
|
688
|
-
pb = self._model.catalog.getPathBuilder()
|
|
689
|
-
asset_path = pb.schemas[asset_table.schema.name].tables[asset_table.name]
|
|
690
|
-
(
|
|
691
|
-
asset_type_table,
|
|
692
|
-
_,
|
|
693
|
-
_,
|
|
694
|
-
) = self._model.find_association(asset_table, MLVocab.asset_type)
|
|
695
|
-
type_path = pb.schemas[asset_type_table.schema.name].tables[asset_type_table.name]
|
|
696
|
-
|
|
697
|
-
# Build a list of assets with their types
|
|
698
|
-
assets = []
|
|
699
|
-
for asset in asset_path.entities().fetch():
|
|
700
|
-
# Get associated asset types for each asset
|
|
701
|
-
asset_types = (
|
|
702
|
-
type_path.filter(type_path.columns[asset_table.name] == asset["RID"])
|
|
703
|
-
.attributes(type_path.Asset_Type)
|
|
704
|
-
.fetch()
|
|
705
|
-
)
|
|
706
|
-
# Combine asset data with its types
|
|
707
|
-
assets.append(
|
|
708
|
-
asset | {MLVocab.asset_type.value: [asset_type[MLVocab.asset_type.value] for asset_type in asset_types]}
|
|
709
|
-
)
|
|
710
|
-
return assets
|
|
711
|
-
|
|
712
|
-
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
|
|
713
|
-
def create_feature(
|
|
714
|
-
self,
|
|
715
|
-
target_table: Table | str,
|
|
716
|
-
feature_name: str,
|
|
717
|
-
terms: list[Table | str] | None = None,
|
|
718
|
-
assets: list[Table | str] | None = None,
|
|
719
|
-
metadata: list[ColumnDefinition | Table | Key | str] | None = None,
|
|
720
|
-
optional: list[str] | None = None,
|
|
721
|
-
comment: str = "",
|
|
722
|
-
) -> type[FeatureRecord]:
|
|
723
|
-
"""Creates a new feature definition.
|
|
724
|
-
|
|
725
|
-
A feature represents a measurable property or characteristic that can be associated with records in the target
|
|
726
|
-
table. Features can include vocabulary terms, asset references, and additional metadata.
|
|
842
|
+
**Available Column Types** (BuiltinTypes enum):
|
|
843
|
+
``text``, ``int2``, ``int4``, ``int8``, ``float4``, ``float8``, ``boolean``,
|
|
844
|
+
``date``, ``timestamp``, ``timestamptz``, ``json``, ``jsonb``, ``markdown``,
|
|
845
|
+
``ermrest_uri``, ``ermrest_rid``, ``ermrest_rcb``, ``ermrest_rmb``,
|
|
846
|
+
``ermrest_rct``, ``ermrest_rmt``
|
|
727
847
|
|
|
728
848
|
Args:
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
metadata: Optional columns, tables, or keys to include in a feature definition.
|
|
734
|
-
optional: Column names that are not required when creating feature instances.
|
|
735
|
-
comment: Description of the feature's purpose and usage.
|
|
849
|
+
table: A TableDefinition object containing the complete specification of the table to create.
|
|
850
|
+
update_navbar: If True (default), automatically updates the navigation bar to include
|
|
851
|
+
the new table. Set to False during batch table creation to avoid redundant updates,
|
|
852
|
+
then call apply_catalog_annotations() once at the end.
|
|
736
853
|
|
|
737
854
|
Returns:
|
|
738
|
-
|
|
855
|
+
Table: The newly created ERMRest table object.
|
|
739
856
|
|
|
740
857
|
Raises:
|
|
741
|
-
DerivaMLException: If
|
|
858
|
+
DerivaMLException: If table creation fails or the definition is invalid.
|
|
742
859
|
|
|
743
860
|
Examples:
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
...
|
|
750
|
-
...
|
|
861
|
+
**Simple table with basic columns**:
|
|
862
|
+
|
|
863
|
+
>>> from deriva_ml import TableDefinition, ColumnDefinition, BuiltinTypes
|
|
864
|
+
>>>
|
|
865
|
+
>>> table_def = TableDefinition(
|
|
866
|
+
... name="Experiment",
|
|
867
|
+
... column_defs=[
|
|
868
|
+
... ColumnDefinition(name="Name", type=BuiltinTypes.text, nullok=False),
|
|
869
|
+
... ColumnDefinition(name="Date", type=BuiltinTypes.date),
|
|
870
|
+
... ColumnDefinition(name="Description", type=BuiltinTypes.markdown),
|
|
871
|
+
... ColumnDefinition(name="Score", type=BuiltinTypes.float4),
|
|
872
|
+
... ],
|
|
873
|
+
... comment="Records of experimental runs"
|
|
751
874
|
... )
|
|
752
|
-
|
|
753
|
-
# Initialize empty collections if None provided
|
|
754
|
-
terms = terms or []
|
|
755
|
-
assets = assets or []
|
|
756
|
-
metadata = metadata or []
|
|
757
|
-
optional = optional or []
|
|
758
|
-
|
|
759
|
-
def normalize_metadata(m: Key | Table | ColumnDefinition | str):
|
|
760
|
-
"""Helper function to normalize metadata references."""
|
|
761
|
-
if isinstance(m, str):
|
|
762
|
-
return self.model.name_to_table(m)
|
|
763
|
-
elif isinstance(m, ColumnDefinition):
|
|
764
|
-
return m.model_dump()
|
|
765
|
-
else:
|
|
766
|
-
return m
|
|
767
|
-
|
|
768
|
-
# Validate asset and term tables
|
|
769
|
-
if not all(map(self.model.is_asset, assets)):
|
|
770
|
-
raise DerivaMLException("Invalid create_feature asset table.")
|
|
771
|
-
if not all(map(self.model.is_vocabulary, terms)):
|
|
772
|
-
raise DerivaMLException("Invalid create_feature asset table.")
|
|
773
|
-
|
|
774
|
-
# Get references to required tables
|
|
775
|
-
target_table = self.model.name_to_table(target_table)
|
|
776
|
-
execution = self.model.schemas[self.ml_schema].tables["Execution"]
|
|
777
|
-
feature_name_table = self.model.schemas[self.ml_schema].tables["Feature_Name"]
|
|
778
|
-
|
|
779
|
-
# Add feature name to vocabulary
|
|
780
|
-
feature_name_term = self.add_term("Feature_Name", feature_name, description=comment)
|
|
781
|
-
atable_name = f"Execution_{target_table.name}_{feature_name_term.name}"
|
|
782
|
-
# Create an association table implementing the feature
|
|
783
|
-
atable = self.model.schemas[self.domain_schema].create_table(
|
|
784
|
-
target_table.define_association(
|
|
785
|
-
table_name=atable_name,
|
|
786
|
-
associates=[execution, target_table, feature_name_table],
|
|
787
|
-
metadata=[normalize_metadata(m) for m in chain(assets, terms, metadata)],
|
|
788
|
-
comment=comment,
|
|
789
|
-
)
|
|
790
|
-
)
|
|
791
|
-
# Configure optional columns and default feature name
|
|
792
|
-
for c in optional:
|
|
793
|
-
atable.columns[c].alter(nullok=True)
|
|
794
|
-
atable.columns["Feature_Name"].alter(default=feature_name_term.name)
|
|
795
|
-
|
|
796
|
-
# Return feature record class for creating instances
|
|
797
|
-
return self.feature_record_class(target_table, feature_name)
|
|
798
|
-
|
|
799
|
-
def feature_record_class(self, table: str | Table, feature_name: str) -> type[FeatureRecord]:
|
|
800
|
-
"""Returns a pydantic model class for feature records.
|
|
801
|
-
|
|
802
|
-
Creates a typed interface for creating new instances of the specified feature. The returned class includes
|
|
803
|
-
validation and type checking based on the feature's definition.
|
|
804
|
-
|
|
805
|
-
Args:
|
|
806
|
-
table: The table containing the feature, either as name or Table object.
|
|
807
|
-
feature_name: Name of the feature to create a record class for.
|
|
808
|
-
|
|
809
|
-
Returns:
|
|
810
|
-
type[FeatureRecord]: A pydantic model class for creating validated feature records.
|
|
811
|
-
|
|
812
|
-
Raises:
|
|
813
|
-
DerivaMLException: If the feature doesn't exist or the table is invalid.
|
|
875
|
+
>>> experiment_table = ml.create_table(table_def)
|
|
814
876
|
|
|
815
|
-
|
|
816
|
-
>>> ExpressionFeature = ml.feature_record_class("samples", "expression_level")
|
|
817
|
-
>>> feature = ExpressionFeature(value="high", confidence=0.95)
|
|
818
|
-
"""
|
|
819
|
-
# Look up a feature and return its record class
|
|
820
|
-
return self.lookup_feature(table, feature_name).feature_record_class()
|
|
877
|
+
**Table with foreign key to another table**:
|
|
821
878
|
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
879
|
+
>>> from deriva_ml import (
|
|
880
|
+
... TableDefinition, ColumnDefinition, ForeignKeyDefinition, BuiltinTypes
|
|
881
|
+
... )
|
|
882
|
+
>>>
|
|
883
|
+
>>> # Create a Sample table that references Subject
|
|
884
|
+
>>> sample_def = TableDefinition(
|
|
885
|
+
... name="Sample",
|
|
886
|
+
... column_defs=[
|
|
887
|
+
... ColumnDefinition(name="Name", type=BuiltinTypes.text, nullok=False),
|
|
888
|
+
... ColumnDefinition(name="Subject", type=BuiltinTypes.text, nullok=False),
|
|
889
|
+
... ColumnDefinition(name="Collection_Date", type=BuiltinTypes.date),
|
|
890
|
+
... ],
|
|
891
|
+
... fkey_defs=[
|
|
892
|
+
... ForeignKeyDefinition(
|
|
893
|
+
... colnames=["Subject"],
|
|
894
|
+
... pk_sname=ml.default_schema, # Schema of referenced table
|
|
895
|
+
... pk_tname="Subject", # Name of referenced table
|
|
896
|
+
... pk_colnames=["RID"], # Column(s) in referenced table
|
|
897
|
+
... on_delete="CASCADE", # Delete samples when subject deleted
|
|
898
|
+
... )
|
|
899
|
+
... ],
|
|
900
|
+
... comment="Biological samples collected from subjects"
|
|
901
|
+
... )
|
|
902
|
+
>>> sample_table = ml.create_table(sample_def)
|
|
827
903
|
|
|
828
|
-
|
|
829
|
-
table: The table containing the feature, either as name or Table object.
|
|
830
|
-
feature_name: Name of the feature to delete.
|
|
904
|
+
**Table with unique key constraint**:
|
|
831
905
|
|
|
832
|
-
|
|
833
|
-
|
|
906
|
+
>>> from deriva_ml import (
|
|
907
|
+
... TableDefinition, ColumnDefinition, KeyDefinition, BuiltinTypes
|
|
908
|
+
... )
|
|
909
|
+
>>>
|
|
910
|
+
>>> protocol_def = TableDefinition(
|
|
911
|
+
... name="Protocol",
|
|
912
|
+
... column_defs=[
|
|
913
|
+
... ColumnDefinition(name="Name", type=BuiltinTypes.text, nullok=False),
|
|
914
|
+
... ColumnDefinition(name="Version", type=BuiltinTypes.text, nullok=False),
|
|
915
|
+
... ColumnDefinition(name="Description", type=BuiltinTypes.markdown),
|
|
916
|
+
... ],
|
|
917
|
+
... key_defs=[
|
|
918
|
+
... KeyDefinition(
|
|
919
|
+
... colnames=["Name", "Version"],
|
|
920
|
+
... constraint_names=[["myschema", "Protocol_Name_Version_key"]],
|
|
921
|
+
... comment="Each protocol name+version must be unique"
|
|
922
|
+
... )
|
|
923
|
+
... ],
|
|
924
|
+
... comment="Experimental protocols with versioning"
|
|
925
|
+
... )
|
|
926
|
+
>>> protocol_table = ml.create_table(protocol_def)
|
|
834
927
|
|
|
835
|
-
|
|
836
|
-
DerivaMLException: If deletion fails due to constraints or permissions.
|
|
928
|
+
**Batch creation without navbar updates**:
|
|
837
929
|
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
930
|
+
>>> ml.create_table(table1_def, update_navbar=False)
|
|
931
|
+
>>> ml.create_table(table2_def, update_navbar=False)
|
|
932
|
+
>>> ml.create_table(table3_def, update_navbar=False)
|
|
933
|
+
>>> ml.apply_catalog_annotations() # Update navbar once at the end
|
|
841
934
|
"""
|
|
842
|
-
#
|
|
843
|
-
|
|
844
|
-
try:
|
|
845
|
-
# Find and delete the feature's implementation table
|
|
846
|
-
feature = next(f for f in self.model.find_features(table) if f.feature_name == feature_name)
|
|
847
|
-
feature.feature_table.drop()
|
|
848
|
-
return True
|
|
849
|
-
except StopIteration:
|
|
850
|
-
return False
|
|
935
|
+
# Use default schema if none specified
|
|
936
|
+
schema = schema or self.model._require_default_schema()
|
|
851
937
|
|
|
852
|
-
|
|
853
|
-
|
|
938
|
+
# Create table in domain schema using provided definition
|
|
939
|
+
# Handle both TableDefinition (dataclass with to_dict) and plain dicts
|
|
940
|
+
table_dict = table.to_dict() if hasattr(table, 'to_dict') else table
|
|
941
|
+
new_table = self.model.schemas[schema].create_table(table_dict)
|
|
854
942
|
|
|
855
|
-
|
|
856
|
-
|
|
943
|
+
# Update navbar to include the new table
|
|
944
|
+
if update_navbar:
|
|
945
|
+
self.apply_catalog_annotations()
|
|
857
946
|
|
|
858
|
-
|
|
859
|
-
table: The table containing the feature, either as name or Table object.
|
|
860
|
-
feature_name: Name of the feature to look up.
|
|
947
|
+
return new_table
|
|
861
948
|
|
|
862
|
-
|
|
863
|
-
|
|
949
|
+
# =========================================================================
|
|
950
|
+
# Cache and Directory Management
|
|
951
|
+
# =========================================================================
|
|
864
952
|
|
|
865
|
-
|
|
866
|
-
|
|
953
|
+
def clear_cache(self, older_than_days: int | None = None) -> dict[str, int]:
|
|
954
|
+
"""Clear the dataset cache directory.
|
|
867
955
|
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
>>> print(feature.feature_name)
|
|
871
|
-
'expression_level'
|
|
872
|
-
"""
|
|
873
|
-
return self.model.lookup_feature(table, feature_name)
|
|
874
|
-
|
|
875
|
-
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
|
|
876
|
-
def list_feature_values(self, table: Table | str, feature_name: str) -> datapath._ResultSet:
|
|
877
|
-
"""Retrieves all values for a feature.
|
|
878
|
-
|
|
879
|
-
Returns all instances of the specified feature that have been created, including their associated
|
|
880
|
-
metadata and references.
|
|
956
|
+
Removes cached dataset bags from the cache directory. Can optionally filter
|
|
957
|
+
by age to only remove old cache entries.
|
|
881
958
|
|
|
882
959
|
Args:
|
|
883
|
-
|
|
884
|
-
|
|
960
|
+
older_than_days: If provided, only remove cache entries older than this
|
|
961
|
+
many days. If None, removes all cache entries.
|
|
885
962
|
|
|
886
963
|
Returns:
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
964
|
+
dict with keys:
|
|
965
|
+
- 'files_removed': Number of files removed
|
|
966
|
+
- 'dirs_removed': Number of directories removed
|
|
967
|
+
- 'bytes_freed': Total bytes freed
|
|
968
|
+
- 'errors': Number of removal errors
|
|
891
969
|
|
|
892
970
|
Example:
|
|
893
|
-
>>>
|
|
894
|
-
>>>
|
|
895
|
-
|
|
971
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
972
|
+
>>> # Clear all cache
|
|
973
|
+
>>> result = ml.clear_cache()
|
|
974
|
+
>>> print(f"Freed {result['bytes_freed'] / 1e6:.1f} MB")
|
|
975
|
+
>>>
|
|
976
|
+
>>> # Clear cache older than 7 days
|
|
977
|
+
>>> result = ml.clear_cache(older_than_days=7)
|
|
896
978
|
"""
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
feature = self.lookup_feature(table, feature_name)
|
|
900
|
-
|
|
901
|
-
# Build and execute query for feature values
|
|
902
|
-
pb = self.catalog.getPathBuilder()
|
|
903
|
-
return pb.schemas[feature.feature_table.schema.name].tables[feature.feature_table.name].entities().fetch()
|
|
979
|
+
import shutil
|
|
980
|
+
import time
|
|
904
981
|
|
|
905
|
-
|
|
906
|
-
def add_term(
|
|
907
|
-
self,
|
|
908
|
-
table: str | Table,
|
|
909
|
-
term_name: str,
|
|
910
|
-
description: str,
|
|
911
|
-
synonyms: list[str] | None = None,
|
|
912
|
-
exists_ok: bool = True,
|
|
913
|
-
) -> VocabularyTerm:
|
|
914
|
-
"""Adds a term to a vocabulary table.
|
|
982
|
+
stats = {'files_removed': 0, 'dirs_removed': 0, 'bytes_freed': 0, 'errors': 0}
|
|
915
983
|
|
|
916
|
-
|
|
917
|
-
|
|
984
|
+
if not self.cache_dir.exists():
|
|
985
|
+
return stats
|
|
918
986
|
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
description: Explanation of term's meaning and usage.
|
|
923
|
-
synonyms: Alternative names for the term.
|
|
924
|
-
exists_ok: If True, return the existing term if found. If False, raise error.
|
|
925
|
-
|
|
926
|
-
Returns:
|
|
927
|
-
VocabularyTerm: Object representing the created or existing term.
|
|
928
|
-
|
|
929
|
-
Raises:
|
|
930
|
-
DerivaMLException: If a term exists and exists_ok=False, or if the table is not a vocabulary table.
|
|
931
|
-
|
|
932
|
-
Examples:
|
|
933
|
-
Add a new tissue type:
|
|
934
|
-
>>> term = ml.add_term(
|
|
935
|
-
... table="tissue_types",
|
|
936
|
-
... term_name="epithelial",
|
|
937
|
-
... description="Epithelial tissue type",
|
|
938
|
-
... synonyms=["epithelium"]
|
|
939
|
-
... )
|
|
940
|
-
|
|
941
|
-
Attempt to add an existing term:
|
|
942
|
-
>>> term = ml.add_term("tissue_types", "epithelial", "...", exists_ok=True)
|
|
943
|
-
"""
|
|
944
|
-
# Initialize an empty synonyms list if None
|
|
945
|
-
synonyms = synonyms or []
|
|
946
|
-
|
|
947
|
-
# Get table reference and validate if it is a vocabulary table
|
|
948
|
-
table = self.model.name_to_table(table)
|
|
949
|
-
pb = self.catalog.getPathBuilder()
|
|
950
|
-
if not (self.model.is_vocabulary(table)):
|
|
951
|
-
raise DerivaMLTableTypeError("vocabulary", table.name)
|
|
952
|
-
|
|
953
|
-
# Get schema and table names for path building
|
|
954
|
-
schema_name = table.schema.name
|
|
955
|
-
table_name = table.name
|
|
987
|
+
cutoff_time = None
|
|
988
|
+
if older_than_days is not None:
|
|
989
|
+
cutoff_time = time.time() - (older_than_days * 24 * 60 * 60)
|
|
956
990
|
|
|
957
991
|
try:
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
term_name: Name or synonym of the term to find.
|
|
992
|
+
for entry in self.cache_dir.iterdir():
|
|
993
|
+
try:
|
|
994
|
+
# Check age if filtering
|
|
995
|
+
if cutoff_time is not None:
|
|
996
|
+
entry_mtime = entry.stat().st_mtime
|
|
997
|
+
if entry_mtime > cutoff_time:
|
|
998
|
+
continue # Skip recent entries
|
|
999
|
+
|
|
1000
|
+
# Calculate size before removal
|
|
1001
|
+
if entry.is_dir():
|
|
1002
|
+
entry_size = sum(f.stat().st_size for f in entry.rglob('*') if f.is_file())
|
|
1003
|
+
shutil.rmtree(entry)
|
|
1004
|
+
stats['dirs_removed'] += 1
|
|
1005
|
+
else:
|
|
1006
|
+
entry_size = entry.stat().st_size
|
|
1007
|
+
entry.unlink()
|
|
1008
|
+
stats['files_removed'] += 1
|
|
1009
|
+
|
|
1010
|
+
stats['bytes_freed'] += entry_size
|
|
1011
|
+
except (OSError, PermissionError) as e:
|
|
1012
|
+
self._logger.warning(f"Failed to remove cache entry {entry}: {e}")
|
|
1013
|
+
stats['errors'] += 1
|
|
1014
|
+
|
|
1015
|
+
except OSError as e:
|
|
1016
|
+
self._logger.error(f"Failed to iterate cache directory: {e}")
|
|
1017
|
+
stats['errors'] += 1
|
|
1018
|
+
|
|
1019
|
+
return stats
|
|
1020
|
+
|
|
1021
|
+
def get_cache_size(self) -> dict[str, int | float]:
|
|
1022
|
+
"""Get the current size of the cache directory.
|
|
990
1023
|
|
|
991
1024
|
Returns:
|
|
992
|
-
|
|
1025
|
+
dict with keys:
|
|
1026
|
+
- 'total_bytes': Total size in bytes
|
|
1027
|
+
- 'total_mb': Total size in megabytes
|
|
1028
|
+
- 'file_count': Number of files
|
|
1029
|
+
- 'dir_count': Number of directories
|
|
993
1030
|
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
Look up by primary name:
|
|
999
|
-
>>> term = ml.lookup_term("tissue_types", "epithelial")
|
|
1000
|
-
>>> print(term.description)
|
|
1001
|
-
|
|
1002
|
-
Look up by synonym:
|
|
1003
|
-
>>> term = ml.lookup_term("tissue_types", "epithelium")
|
|
1031
|
+
Example:
|
|
1032
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
1033
|
+
>>> size = ml.get_cache_size()
|
|
1034
|
+
>>> print(f"Cache size: {size['total_mb']:.1f} MB ({size['file_count']} files)")
|
|
1004
1035
|
"""
|
|
1005
|
-
|
|
1006
|
-
vocab_table = self.model.name_to_table(table)
|
|
1007
|
-
if not self.model.is_vocabulary(vocab_table):
|
|
1008
|
-
raise DerivaMLException(f"The table {table} is not a controlled vocabulary")
|
|
1036
|
+
stats = {'total_bytes': 0, 'total_mb': 0.0, 'file_count': 0, 'dir_count': 0}
|
|
1009
1037
|
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
schema_path = self.catalog.getPathBuilder().schemas[schema_name]
|
|
1038
|
+
if not self.cache_dir.exists():
|
|
1039
|
+
return stats
|
|
1013
1040
|
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1041
|
+
for entry in self.cache_dir.rglob('*'):
|
|
1042
|
+
if entry.is_file():
|
|
1043
|
+
stats['total_bytes'] += entry.stat().st_size
|
|
1044
|
+
stats['file_count'] += 1
|
|
1045
|
+
elif entry.is_dir():
|
|
1046
|
+
stats['dir_count'] += 1
|
|
1018
1047
|
|
|
1019
|
-
|
|
1020
|
-
|
|
1048
|
+
stats['total_mb'] = stats['total_bytes'] / (1024 * 1024)
|
|
1049
|
+
return stats
|
|
1021
1050
|
|
|
1022
|
-
def
|
|
1023
|
-
"""
|
|
1051
|
+
def list_execution_dirs(self) -> list[dict[str, any]]:
|
|
1052
|
+
"""List execution working directories.
|
|
1024
1053
|
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
Args:
|
|
1028
|
-
table: Vocabulary table to list terms from (name or Table object).
|
|
1054
|
+
Returns information about each execution directory in the working directory,
|
|
1055
|
+
useful for identifying orphaned or incomplete execution outputs.
|
|
1029
1056
|
|
|
1030
1057
|
Returns:
|
|
1031
|
-
|
|
1058
|
+
List of dicts, each containing:
|
|
1059
|
+
- 'execution_rid': The execution RID (directory name)
|
|
1060
|
+
- 'path': Full path to the directory
|
|
1061
|
+
- 'size_bytes': Total size in bytes
|
|
1062
|
+
- 'size_mb': Total size in megabytes
|
|
1063
|
+
- 'modified': Last modification time (datetime)
|
|
1064
|
+
- 'file_count': Number of files
|
|
1032
1065
|
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
>>> for term in terms:
|
|
1039
|
-
... print(f"{term.name}: {term.description}")
|
|
1040
|
-
... if term.synonyms:
|
|
1041
|
-
... print(f" Synonyms: {', '.join(term.synonyms)}")
|
|
1066
|
+
Example:
|
|
1067
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
1068
|
+
>>> dirs = ml.list_execution_dirs()
|
|
1069
|
+
>>> for d in dirs:
|
|
1070
|
+
... print(f"{d['execution_rid']}: {d['size_mb']:.1f} MB")
|
|
1042
1071
|
"""
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
table = self.model.name_to_table(table.value if isinstance(table, MLVocab) else table)
|
|
1072
|
+
from datetime import datetime
|
|
1073
|
+
from deriva_ml.dataset.upload import upload_root
|
|
1046
1074
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
raise DerivaMLException(f"The table {table} is not a controlled vocabulary")
|
|
1075
|
+
results = []
|
|
1076
|
+
exec_root = upload_root(self.working_dir) / "execution"
|
|
1050
1077
|
|
|
1051
|
-
|
|
1052
|
-
|
|
1078
|
+
if not exec_root.exists():
|
|
1079
|
+
return results
|
|
1053
1080
|
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
) -> DatasetBag:
|
|
1060
|
-
"""Downloads a dataset to the local filesystem and creates a MINID if needed.
|
|
1081
|
+
for entry in exec_root.iterdir():
|
|
1082
|
+
if entry.is_dir():
|
|
1083
|
+
size_bytes = sum(f.stat().st_size for f in entry.rglob('*') if f.is_file())
|
|
1084
|
+
file_count = sum(1 for f in entry.rglob('*') if f.is_file())
|
|
1085
|
+
mtime = datetime.fromtimestamp(entry.stat().st_mtime)
|
|
1061
1086
|
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1087
|
+
results.append({
|
|
1088
|
+
'execution_rid': entry.name,
|
|
1089
|
+
'path': str(entry),
|
|
1090
|
+
'size_bytes': size_bytes,
|
|
1091
|
+
'size_mb': size_bytes / (1024 * 1024),
|
|
1092
|
+
'modified': mtime,
|
|
1093
|
+
'file_count': file_count,
|
|
1094
|
+
})
|
|
1065
1095
|
|
|
1066
|
-
|
|
1067
|
-
dataset: Specification of the dataset to download, including version and materialization options.
|
|
1068
|
-
execution_rid: Optional execution RID to associate the download with.
|
|
1069
|
-
|
|
1070
|
-
Returns:
|
|
1071
|
-
DatasetBag: Object containing:
|
|
1072
|
-
- path: Local filesystem path to downloaded dataset
|
|
1073
|
-
- rid: Dataset's Resource Identifier
|
|
1074
|
-
- minid: Dataset's Minimal Viable Identifier
|
|
1096
|
+
return sorted(results, key=lambda x: x['modified'], reverse=True)
|
|
1075
1097
|
|
|
1076
|
-
|
|
1077
|
-
Download with default options:
|
|
1078
|
-
>>> spec = DatasetSpec(rid="1-abc123")
|
|
1079
|
-
>>> bag = ml.download_dataset_bag(dataset=spec)
|
|
1080
|
-
>>> print(f"Downloaded to {bag.path}")
|
|
1081
|
-
|
|
1082
|
-
Download with execution tracking:
|
|
1083
|
-
>>> bag = ml.download_dataset_bag(
|
|
1084
|
-
... dataset=DatasetSpec(rid="1-abc123", materialize=True),
|
|
1085
|
-
... execution_rid="1-xyz789"
|
|
1086
|
-
... )
|
|
1087
|
-
"""
|
|
1088
|
-
if not self._is_dataset_rid(dataset.rid):
|
|
1089
|
-
raise DerivaMLTableTypeError("Dataset", dataset.rid)
|
|
1090
|
-
return self._download_dataset_bag(
|
|
1091
|
-
dataset=dataset,
|
|
1092
|
-
execution_rid=execution_rid,
|
|
1093
|
-
snapshot_catalog=DerivaML(
|
|
1094
|
-
self.host_name,
|
|
1095
|
-
self._version_snapshot(dataset),
|
|
1096
|
-
logging_level=self._logging_level,
|
|
1097
|
-
deriva_logging_level=self._deriva_logging_level,
|
|
1098
|
-
),
|
|
1099
|
-
)
|
|
1100
|
-
|
|
1101
|
-
def _update_status(self, new_status: Status, status_detail: str, execution_rid: RID):
|
|
1102
|
-
"""Update the status of an execution in the catalog.
|
|
1103
|
-
|
|
1104
|
-
Args:
|
|
1105
|
-
new_status: New status.
|
|
1106
|
-
status_detail: Details of the status.
|
|
1107
|
-
execution_rid: Resource Identifier (RID) of the execution.
|
|
1108
|
-
new_status: Status:
|
|
1109
|
-
status_detail: str:
|
|
1110
|
-
execution_rid: RID:
|
|
1111
|
-
|
|
1112
|
-
Returns:
|
|
1113
|
-
|
|
1114
|
-
"""
|
|
1115
|
-
self.status = new_status.value
|
|
1116
|
-
self.pathBuilder.schemas[self.ml_schema].Execution.update(
|
|
1117
|
-
[
|
|
1118
|
-
{
|
|
1119
|
-
"RID": execution_rid,
|
|
1120
|
-
"Status": self.status,
|
|
1121
|
-
"Status_Detail": status_detail,
|
|
1122
|
-
}
|
|
1123
|
-
]
|
|
1124
|
-
)
|
|
1125
|
-
|
|
1126
|
-
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
|
|
1127
|
-
def add_files(
|
|
1098
|
+
def clean_execution_dirs(
|
|
1128
1099
|
self,
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
) -> RID:
|
|
1134
|
-
"""Adds files to the catalog with their metadata.
|
|
1100
|
+
older_than_days: int | None = None,
|
|
1101
|
+
exclude_rids: list[str] | None = None,
|
|
1102
|
+
) -> dict[str, int]:
|
|
1103
|
+
"""Clean up execution working directories.
|
|
1135
1104
|
|
|
1136
|
-
|
|
1137
|
-
|
|
1105
|
+
Removes execution output directories from the local working directory.
|
|
1106
|
+
Use this to free up disk space from completed or orphaned executions.
|
|
1138
1107
|
|
|
1139
1108
|
Args:
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
execution_rid: Optional execution RID to associate files with.
|
|
1109
|
+
older_than_days: If provided, only remove directories older than this
|
|
1110
|
+
many days. If None, removes all execution directories (except excluded).
|
|
1111
|
+
exclude_rids: List of execution RIDs to preserve (never remove).
|
|
1144
1112
|
|
|
1145
1113
|
Returns:
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
Examples:
|
|
1152
|
-
Add a single file type:
|
|
1153
|
-
>>> files = [FileSpec(url="path/to/file.txt", md5="abc123", length=1000)]
|
|
1154
|
-
>>> rids = ml.add_files(files, file_types="text")
|
|
1155
|
-
|
|
1156
|
-
Add multiple file types:
|
|
1157
|
-
>>> rids = ml.add_files(
|
|
1158
|
-
... files=[FileSpec(url="image.png", md5="def456", length=2000)],
|
|
1159
|
-
... file_types=["image", "png"],
|
|
1160
|
-
... execution_rid="1-xyz789"
|
|
1161
|
-
... )
|
|
1162
|
-
"""
|
|
1163
|
-
if execution_rid and self.resolve_rid(execution_rid).table.name != "Execution":
|
|
1164
|
-
raise DerivaMLTableTypeError("Execution", execution_rid)
|
|
1165
|
-
|
|
1166
|
-
filespec_list = list(files)
|
|
1114
|
+
dict with keys:
|
|
1115
|
+
- 'dirs_removed': Number of directories removed
|
|
1116
|
+
- 'bytes_freed': Total bytes freed
|
|
1117
|
+
- 'errors': Number of removal errors
|
|
1167
1118
|
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
# Now make sure that all of the file types and dataset_types in the spec list are defined.
|
|
1177
|
-
if spec_types - defined_types:
|
|
1178
|
-
raise DerivaMLInvalidTerm(MLVocab.asset_type.name, f"{spec_types - defined_types}")
|
|
1179
|
-
|
|
1180
|
-
# Normalize dataset_types, make sure FIle type is included.
|
|
1181
|
-
if isinstance(dataset_types, list):
|
|
1182
|
-
dataset_types = ["File"] + dataset_types if "File" not in dataset_types else dataset_types
|
|
1183
|
-
else:
|
|
1184
|
-
dataset_types = ["File", dataset_types] if dataset_types else ["File"]
|
|
1185
|
-
for ds_type in dataset_types:
|
|
1186
|
-
self.lookup_term(MLVocab.dataset_type, ds_type)
|
|
1187
|
-
|
|
1188
|
-
# Add files to the file table, and collect up the resulting entries by directory name.
|
|
1189
|
-
pb = self._model.catalog.getPathBuilder()
|
|
1190
|
-
file_records = list(
|
|
1191
|
-
pb.schemas[self.ml_schema].tables["File"].insert([f.model_dump(by_alias=True) for f in filespec_list])
|
|
1192
|
-
)
|
|
1193
|
-
|
|
1194
|
-
# Get the name of the association table between file_table and file_type and add file_type records
|
|
1195
|
-
atable = self.model.find_association(MLTable.file, MLVocab.asset_type)[0].name
|
|
1196
|
-
# Need to get a link between file record and file_types.
|
|
1197
|
-
type_map = {
|
|
1198
|
-
file_spec.md5: file_spec.file_types + ([] if "File" in file_spec.file_types else [])
|
|
1199
|
-
for file_spec in filespec_list
|
|
1200
|
-
}
|
|
1201
|
-
file_type_records = [
|
|
1202
|
-
{MLVocab.asset_type.value: file_type, "File": file_record["RID"]}
|
|
1203
|
-
for file_record in file_records
|
|
1204
|
-
for file_type in type_map[file_record["MD5"]]
|
|
1205
|
-
]
|
|
1206
|
-
pb.schemas[self._ml_schema].tables[atable].insert(file_type_records)
|
|
1207
|
-
|
|
1208
|
-
if execution_rid:
|
|
1209
|
-
# Get the name of the association table between file_table and execution.
|
|
1210
|
-
pb.schemas[self._ml_schema].File_Execution.insert(
|
|
1211
|
-
[
|
|
1212
|
-
{"File": file_record["RID"], "Execution": execution_rid, "Asset_Role": "Output"}
|
|
1213
|
-
for file_record in file_records
|
|
1214
|
-
]
|
|
1215
|
-
)
|
|
1216
|
-
|
|
1217
|
-
# Now create datasets to capture the original directory structure of the files.
|
|
1218
|
-
dir_rid_map = defaultdict(list)
|
|
1219
|
-
for e in file_records:
|
|
1220
|
-
dir_rid_map[Path(urlsplit(e["URL"]).path).parent].append(e["RID"])
|
|
1221
|
-
|
|
1222
|
-
nested_datasets = []
|
|
1223
|
-
path_length = 0
|
|
1224
|
-
dataset = None
|
|
1225
|
-
# Start with the longest path so we get subdirectories first.
|
|
1226
|
-
for p, rids in sorted(dir_rid_map.items(), key=lambda kv: len(kv[0].parts), reverse=True):
|
|
1227
|
-
dataset = self.create_dataset(
|
|
1228
|
-
dataset_types=dataset_types, execution_rid=execution_rid, description=description
|
|
1229
|
-
)
|
|
1230
|
-
members = rids
|
|
1231
|
-
if len(p.parts) < path_length:
|
|
1232
|
-
# Going up one level in directory, so Create nested dataset
|
|
1233
|
-
members = nested_datasets + rids
|
|
1234
|
-
nested_datasets = []
|
|
1235
|
-
self.add_dataset_members(dataset_rid=dataset, members=members, execution_rid=execution_rid)
|
|
1236
|
-
nested_datasets.append(dataset)
|
|
1237
|
-
path_length = len(p.parts)
|
|
1238
|
-
|
|
1239
|
-
return dataset
|
|
1240
|
-
|
|
1241
|
-
def list_files(self, file_types: list[str] | None = None) -> list[dict[str, Any]]:
|
|
1242
|
-
"""Lists files in the catalog with their metadata.
|
|
1243
|
-
|
|
1244
|
-
Returns a list of files with their metadata including URL, MD5 hash, length, description,
|
|
1245
|
-
and associated file types. Files can be optionally filtered by type.
|
|
1246
|
-
|
|
1247
|
-
Args:
|
|
1248
|
-
file_types: Filter results to only include these file types.
|
|
1249
|
-
|
|
1250
|
-
Returns:
|
|
1251
|
-
list[dict[str, Any]]: List of file records, each containing:
|
|
1252
|
-
- RID: Resource identifier
|
|
1253
|
-
- URL: File location
|
|
1254
|
-
- MD5: File hash
|
|
1255
|
-
- Length: File size
|
|
1256
|
-
- Description: File description
|
|
1257
|
-
- File_Types: List of associated file types
|
|
1258
|
-
|
|
1259
|
-
Examples:
|
|
1260
|
-
List all files:
|
|
1261
|
-
>>> files = ml.list_files()
|
|
1262
|
-
>>> for f in files:
|
|
1263
|
-
... print(f"{f['RID']}: {f['URL']}")
|
|
1264
|
-
|
|
1265
|
-
Filter by file type:
|
|
1266
|
-
>>> image_files = ml.list_files(["image", "png"])
|
|
1119
|
+
Example:
|
|
1120
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
1121
|
+
>>> # Clean all execution dirs older than 30 days
|
|
1122
|
+
>>> result = ml.clean_execution_dirs(older_than_days=30)
|
|
1123
|
+
>>> print(f"Freed {result['bytes_freed'] / 1e9:.2f} GB")
|
|
1124
|
+
>>>
|
|
1125
|
+
>>> # Clean all except specific executions
|
|
1126
|
+
>>> result = ml.clean_execution_dirs(exclude_rids=['1-ABC', '1-DEF'])
|
|
1267
1127
|
"""
|
|
1128
|
+
import shutil
|
|
1129
|
+
import time
|
|
1130
|
+
from deriva_ml.dataset.upload import upload_root
|
|
1268
1131
|
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
file = ml_path.File
|
|
1272
|
-
asset_type = ml_path.tables[asset_type_atable.name]
|
|
1273
|
-
|
|
1274
|
-
path = file.path
|
|
1275
|
-
path = path.link(asset_type.alias("AT"), on=file.RID == asset_type.columns[file_fk], join_type="left")
|
|
1276
|
-
if file_types:
|
|
1277
|
-
path = path.filter(asset_type.columns[asset_type_fk] == datapath.Any(*file_types))
|
|
1278
|
-
path = path.attributes(
|
|
1279
|
-
path.File.RID,
|
|
1280
|
-
path.File.URL,
|
|
1281
|
-
path.File.MD5,
|
|
1282
|
-
path.File.Length,
|
|
1283
|
-
path.File.Description,
|
|
1284
|
-
path.AT.columns[asset_type_fk],
|
|
1285
|
-
)
|
|
1132
|
+
stats = {'dirs_removed': 0, 'bytes_freed': 0, 'errors': 0}
|
|
1133
|
+
exclude_rids = set(exclude_rids or [])
|
|
1286
1134
|
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
if ft := f.get("Asset_Type"): # assign-and-test in one go
|
|
1291
|
-
entry["File_Types"].append(ft)
|
|
1135
|
+
exec_root = upload_root(self.working_dir) / "execution"
|
|
1136
|
+
if not exec_root.exists():
|
|
1137
|
+
return stats
|
|
1292
1138
|
|
|
1293
|
-
|
|
1294
|
-
|
|
1139
|
+
cutoff_time = None
|
|
1140
|
+
if older_than_days is not None:
|
|
1141
|
+
cutoff_time = time.time() - (older_than_days * 24 * 60 * 60)
|
|
1295
1142
|
|
|
1296
|
-
|
|
1297
|
-
|
|
1143
|
+
for entry in exec_root.iterdir():
|
|
1144
|
+
if not entry.is_dir():
|
|
1145
|
+
continue
|
|
1298
1146
|
|
|
1299
|
-
|
|
1300
|
-
|
|
1147
|
+
# Skip excluded RIDs
|
|
1148
|
+
if entry.name in exclude_rids:
|
|
1149
|
+
continue
|
|
1301
1150
|
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
- description: Workflow description
|
|
1309
|
-
- rid: Resource identifier
|
|
1310
|
-
- checksum: Source code checksum
|
|
1311
|
-
|
|
1312
|
-
Examples:
|
|
1313
|
-
>>> workflows = ml.list_workflows()
|
|
1314
|
-
>>> for w in workflows:
|
|
1315
|
-
print(f"{w.name} (v{w.version}): {w.description}")
|
|
1316
|
-
print(f" Source: {w.url}")
|
|
1317
|
-
"""
|
|
1318
|
-
# Get a workflow table path and fetch all workflows
|
|
1319
|
-
workflow_path = self.pathBuilder.schemas[self.ml_schema].Workflow
|
|
1320
|
-
return [
|
|
1321
|
-
Workflow(
|
|
1322
|
-
name=w["Name"],
|
|
1323
|
-
url=w["URL"],
|
|
1324
|
-
workflow_type=w["Workflow_Type"],
|
|
1325
|
-
version=w["Version"],
|
|
1326
|
-
description=w["Description"],
|
|
1327
|
-
rid=w["RID"],
|
|
1328
|
-
checksum=w["Checksum"],
|
|
1329
|
-
)
|
|
1330
|
-
for w in workflow_path.entities().fetch()
|
|
1331
|
-
]
|
|
1151
|
+
try:
|
|
1152
|
+
# Check age if filtering
|
|
1153
|
+
if cutoff_time is not None:
|
|
1154
|
+
entry_mtime = entry.stat().st_mtime
|
|
1155
|
+
if entry_mtime > cutoff_time:
|
|
1156
|
+
continue
|
|
1332
1157
|
|
|
1333
|
-
|
|
1334
|
-
|
|
1158
|
+
# Calculate size before removal
|
|
1159
|
+
entry_size = sum(f.stat().st_size for f in entry.rglob('*') if f.is_file())
|
|
1160
|
+
shutil.rmtree(entry)
|
|
1161
|
+
stats['dirs_removed'] += 1
|
|
1162
|
+
stats['bytes_freed'] += entry_size
|
|
1335
1163
|
|
|
1336
|
-
|
|
1337
|
-
|
|
1164
|
+
except (OSError, PermissionError) as e:
|
|
1165
|
+
self._logger.warning(f"Failed to remove execution dir {entry}: {e}")
|
|
1166
|
+
stats['errors'] += 1
|
|
1338
1167
|
|
|
1339
|
-
|
|
1168
|
+
return stats
|
|
1340
1169
|
|
|
1341
|
-
|
|
1342
|
-
|
|
1170
|
+
def get_storage_summary(self) -> dict[str, any]:
|
|
1171
|
+
"""Get a summary of local storage usage.
|
|
1343
1172
|
|
|
1344
1173
|
Returns:
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
... url="https://github.com/org/repo/workflows/gene_analysis.py",
|
|
1354
|
-
... workflow_type="python_script",
|
|
1355
|
-
... version="1.0.0",
|
|
1356
|
-
... description="Analyzes gene expression patterns"
|
|
1357
|
-
... )
|
|
1358
|
-
>>> workflow_rid = ml.add_workflow(workflow)
|
|
1359
|
-
"""
|
|
1360
|
-
# Check if a workflow already exists by URL
|
|
1361
|
-
if workflow_rid := self.lookup_workflow(workflow.checksum or workflow.url):
|
|
1362
|
-
return workflow_rid
|
|
1363
|
-
|
|
1364
|
-
# Get an ML schema path for the workflow table
|
|
1365
|
-
ml_schema_path = self.pathBuilder.schemas[self.ml_schema]
|
|
1366
|
-
|
|
1367
|
-
try:
|
|
1368
|
-
# Create a workflow record
|
|
1369
|
-
workflow_record = {
|
|
1370
|
-
"URL": workflow.url,
|
|
1371
|
-
"Name": workflow.name,
|
|
1372
|
-
"Description": workflow.description,
|
|
1373
|
-
"Checksum": workflow.checksum,
|
|
1374
|
-
"Version": workflow.version,
|
|
1375
|
-
MLVocab.workflow_type: self.lookup_term(MLVocab.workflow_type, workflow.workflow_type).name,
|
|
1376
|
-
}
|
|
1377
|
-
# Insert a workflow and get its RID
|
|
1378
|
-
workflow_rid = ml_schema_path.Workflow.insert([workflow_record])[0]["RID"]
|
|
1379
|
-
except Exception as e:
|
|
1380
|
-
error = format_exception(e)
|
|
1381
|
-
raise DerivaMLException(f"Failed to insert workflow. Error: {error}")
|
|
1382
|
-
return workflow_rid
|
|
1383
|
-
|
|
1384
|
-
def lookup_workflow(self, url_or_checksum: str) -> RID | None:
|
|
1385
|
-
"""Finds a workflow by URL.
|
|
1386
|
-
|
|
1387
|
-
Args:
|
|
1388
|
-
url_or_checksum: URL or checksum of the workflow.
|
|
1389
|
-
Returns:
|
|
1390
|
-
RID: Resource Identifier of the workflow if found, None otherwise.
|
|
1174
|
+
dict with keys:
|
|
1175
|
+
- 'working_dir': Path to working directory
|
|
1176
|
+
- 'cache_dir': Path to cache directory
|
|
1177
|
+
- 'cache_size_mb': Cache size in MB
|
|
1178
|
+
- 'cache_file_count': Number of files in cache
|
|
1179
|
+
- 'execution_dir_count': Number of execution directories
|
|
1180
|
+
- 'execution_size_mb': Total size of execution directories in MB
|
|
1181
|
+
- 'total_size_mb': Combined size in MB
|
|
1391
1182
|
|
|
1392
1183
|
Example:
|
|
1393
|
-
>>>
|
|
1394
|
-
>>>
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
workflow_path = self.pathBuilder.schemas[self.ml_schema].Workflow
|
|
1399
|
-
try:
|
|
1400
|
-
# Search for workflow by URL
|
|
1401
|
-
url_column = workflow_path.URL
|
|
1402
|
-
checksum_column = workflow_path.Checksum
|
|
1403
|
-
return list(
|
|
1404
|
-
workflow_path.path.filter(
|
|
1405
|
-
(url_column == url_or_checksum) | (checksum_column == url_or_checksum)
|
|
1406
|
-
).entities()
|
|
1407
|
-
)[0]["RID"]
|
|
1408
|
-
except IndexError:
|
|
1409
|
-
return None
|
|
1410
|
-
|
|
1411
|
-
def create_workflow(self, name: str, workflow_type: str, description: str = "") -> Workflow:
|
|
1412
|
-
"""Creates a new workflow definition.
|
|
1413
|
-
|
|
1414
|
-
Creates a Workflow object that represents a computational process or analysis pipeline. The workflow type
|
|
1415
|
-
must be a term from the controlled vocabulary. This method is typically used to define new analysis
|
|
1416
|
-
workflows before execution.
|
|
1417
|
-
|
|
1418
|
-
Args:
|
|
1419
|
-
name: Name of the workflow.
|
|
1420
|
-
workflow_type: Type of workflow (must exist in workflow_type vocabulary).
|
|
1421
|
-
description: Description of what the workflow does.
|
|
1422
|
-
|
|
1423
|
-
Returns:
|
|
1424
|
-
Workflow: New workflow object ready for registration.
|
|
1425
|
-
|
|
1426
|
-
Raises:
|
|
1427
|
-
DerivaMLException: If workflow_type is not in the vocabulary.
|
|
1428
|
-
|
|
1429
|
-
Examples:
|
|
1430
|
-
>>> workflow = ml.create_workflow(
|
|
1431
|
-
... name="RNA Analysis",
|
|
1432
|
-
... workflow_type="python_notebook",
|
|
1433
|
-
... description="RNA sequence analysis pipeline"
|
|
1434
|
-
... )
|
|
1435
|
-
>>> rid = ml.add_workflow(workflow)
|
|
1436
|
-
"""
|
|
1437
|
-
# Validate workflow type exists in vocabulary
|
|
1438
|
-
self.lookup_term(MLVocab.workflow_type, workflow_type)
|
|
1439
|
-
|
|
1440
|
-
# Create and return a new workflow object
|
|
1441
|
-
return Workflow(name=name, workflow_type=workflow_type, description=description)
|
|
1442
|
-
|
|
1443
|
-
def create_execution(
|
|
1444
|
-
self, configuration: ExecutionConfiguration, workflow: Workflow | RID | None = None, dry_run: bool = False
|
|
1445
|
-
) -> "Execution":
|
|
1446
|
-
"""Creates an execution environment.
|
|
1447
|
-
|
|
1448
|
-
Given an execution configuration, initialize the local compute environment to prepare for executing an
|
|
1449
|
-
ML or analytic routine. This routine has a number of side effects.
|
|
1450
|
-
|
|
1451
|
-
1. The datasets specified in the configuration are downloaded and placed in the cache-dir. If a version is
|
|
1452
|
-
not specified in the configuration, then a new minor version number is created for the dataset and downloaded.
|
|
1453
|
-
|
|
1454
|
-
2. If any execution assets are provided in the configuration, they are downloaded
|
|
1455
|
-
and placed in the working directory.
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
Args:
|
|
1459
|
-
configuration: ExecutionConfiguration:
|
|
1460
|
-
workflow: Workflow object representing the workflow to execute if not present in the ExecutionConfiguration.
|
|
1461
|
-
dry_run: Do not create an execution record or upload results.
|
|
1462
|
-
|
|
1463
|
-
Returns:
|
|
1464
|
-
An execution object.
|
|
1184
|
+
>>> ml = DerivaML('deriva.example.org', 'my_catalog')
|
|
1185
|
+
>>> summary = ml.get_storage_summary()
|
|
1186
|
+
>>> print(f"Total storage: {summary['total_size_mb']:.1f} MB")
|
|
1187
|
+
>>> print(f" Cache: {summary['cache_size_mb']:.1f} MB")
|
|
1188
|
+
>>> print(f" Executions: {summary['execution_size_mb']:.1f} MB")
|
|
1465
1189
|
"""
|
|
1466
|
-
|
|
1467
|
-
|
|
1190
|
+
cache_stats = self.get_cache_size()
|
|
1191
|
+
exec_dirs = self.list_execution_dirs()
|
|
1192
|
+
|
|
1193
|
+
exec_size_mb = sum(d['size_mb'] for d in exec_dirs)
|
|
1194
|
+
|
|
1195
|
+
return {
|
|
1196
|
+
'working_dir': str(self.working_dir),
|
|
1197
|
+
'cache_dir': str(self.cache_dir),
|
|
1198
|
+
'cache_size_mb': cache_stats['total_mb'],
|
|
1199
|
+
'cache_file_count': cache_stats['file_count'],
|
|
1200
|
+
'execution_dir_count': len(exec_dirs),
|
|
1201
|
+
'execution_size_mb': exec_size_mb,
|
|
1202
|
+
'total_size_mb': cache_stats['total_mb'] + exec_size_mb,
|
|
1203
|
+
}
|
|
1468
1204
|
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1205
|
+
# =========================================================================
|
|
1206
|
+
# Schema Validation
|
|
1207
|
+
# =========================================================================
|
|
1472
1208
|
|
|
1473
|
-
def
|
|
1474
|
-
"""
|
|
1209
|
+
def validate_schema(self, strict: bool = False) -> "SchemaValidationReport":
|
|
1210
|
+
"""Validate that the catalog's ML schema matches the expected structure.
|
|
1475
1211
|
|
|
1476
|
-
|
|
1477
|
-
|
|
1212
|
+
This method inspects the catalog schema and verifies that it contains all
|
|
1213
|
+
the required tables, columns, vocabulary terms, and relationships that are
|
|
1214
|
+
created by the ML schema initialization routines in create_schema.py.
|
|
1478
1215
|
|
|
1479
|
-
|
|
1480
|
-
|
|
1216
|
+
The validation checks:
|
|
1217
|
+
- All required ML tables exist (Dataset, Execution, Workflow, etc.)
|
|
1218
|
+
- All required columns exist with correct types
|
|
1219
|
+
- All required vocabulary tables exist (Asset_Type, Dataset_Type, etc.)
|
|
1220
|
+
- All required vocabulary terms are initialized
|
|
1221
|
+
- All association tables exist for relationships
|
|
1481
1222
|
|
|
1482
|
-
|
|
1483
|
-
in the
|
|
1223
|
+
In strict mode, the validator also reports errors for:
|
|
1224
|
+
- Extra tables not in the expected schema
|
|
1225
|
+
- Extra columns not in the expected table definitions
|
|
1484
1226
|
|
|
1485
1227
|
Args:
|
|
1486
|
-
|
|
1228
|
+
strict: If True, extra tables and columns are reported as errors.
|
|
1229
|
+
If False (default), they are reported as informational items.
|
|
1230
|
+
Use strict=True to verify a clean ML catalog matches exactly.
|
|
1231
|
+
Use strict=False to validate a catalog that may have domain extensions.
|
|
1487
1232
|
|
|
1488
1233
|
Returns:
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1234
|
+
SchemaValidationReport with validation results. Key attributes:
|
|
1235
|
+
- is_valid: True if no errors were found
|
|
1236
|
+
- errors: List of error-level issues
|
|
1237
|
+
- warnings: List of warning-level issues
|
|
1238
|
+
- info: List of informational items
|
|
1239
|
+
- to_text(): Human-readable report
|
|
1240
|
+
- to_dict(): JSON-serializable dictionary
|
|
1493
1241
|
|
|
1494
1242
|
Example:
|
|
1495
|
-
>>>
|
|
1243
|
+
>>> ml = DerivaML('localhost', 'my_catalog')
|
|
1244
|
+
>>> report = ml.validate_schema(strict=False)
|
|
1245
|
+
>>> if report.is_valid:
|
|
1246
|
+
... print("Schema is valid!")
|
|
1247
|
+
... else:
|
|
1248
|
+
... print(report.to_text())
|
|
1249
|
+
|
|
1250
|
+
>>> # Strict validation for a fresh ML catalog
|
|
1251
|
+
>>> report = ml.validate_schema(strict=True)
|
|
1252
|
+
>>> print(f"Found {len(report.errors)} errors, {len(report.warnings)} warnings")
|
|
1253
|
+
|
|
1254
|
+
>>> # Get report as dictionary for JSON/logging
|
|
1255
|
+
>>> import json
|
|
1256
|
+
>>> print(json.dumps(report.to_dict(), indent=2))
|
|
1257
|
+
|
|
1258
|
+
Note:
|
|
1259
|
+
This method validates the ML schema (typically 'deriva-ml'), not the
|
|
1260
|
+
domain schema. Domain-specific tables and columns are not checked
|
|
1261
|
+
unless they are part of the ML schema itself.
|
|
1262
|
+
|
|
1263
|
+
See Also:
|
|
1264
|
+
- deriva_ml.schema.validation.SchemaValidationReport
|
|
1265
|
+
- deriva_ml.schema.validation.validate_ml_schema
|
|
1496
1266
|
"""
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
# If no RID provided, try to find single execution in working directory
|
|
1501
|
-
if not execution_rid:
|
|
1502
|
-
e_rids = execution_rids(self.working_dir)
|
|
1503
|
-
if len(e_rids) != 1:
|
|
1504
|
-
raise DerivaMLException(f"Multiple execution RIDs were found {e_rids}.")
|
|
1505
|
-
execution_rid = e_rids[0]
|
|
1506
|
-
|
|
1507
|
-
# Try to load configuration from a file
|
|
1508
|
-
cfile = asset_file_path(
|
|
1509
|
-
prefix=self.working_dir,
|
|
1510
|
-
exec_rid=execution_rid,
|
|
1511
|
-
file_name="configuration.json",
|
|
1512
|
-
asset_table=self.model.name_to_table("Execution_Metadata"),
|
|
1513
|
-
metadata={},
|
|
1514
|
-
)
|
|
1267
|
+
from deriva_ml.schema.validation import SchemaValidationReport, validate_ml_schema
|
|
1268
|
+
return validate_ml_schema(self, strict=strict)
|
|
1515
1269
|
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
description=execution["Description"],
|
|
1524
|
-
)
|
|
1270
|
+
# Methods moved to mixins:
|
|
1271
|
+
# - create_asset, list_assets -> AssetMixin
|
|
1272
|
+
# - create_feature, feature_record_class, delete_feature, lookup_feature, list_feature_values -> FeatureMixin
|
|
1273
|
+
# - find_datasets, create_dataset, lookup_dataset, delete_dataset, list_dataset_element_types,
|
|
1274
|
+
# add_dataset_element_type, download_dataset_bag -> DatasetMixin
|
|
1275
|
+
# - _update_status, create_execution, restore_execution -> ExecutionMixin
|
|
1276
|
+
# - add_files, list_files, _bootstrap_versions, _synchronize_dataset_versions, _set_version_snapshot -> FileMixin
|
|
1525
1277
|
|
|
1526
|
-
# Create and return an execution instance
|
|
1527
|
-
return Execution(configuration, self, reload=execution_rid)
|