Data Layer¶
This page covers the MongoDB document model, the datatypes system for format dispatch, and the repository JSON pipeline that loads data into projects.
MongoDB Document Model¶
Hera stores all metadata in MongoDB using a single base model (Metadata) with three subtypes. Each document represents a pointer to data — the actual data lives on disk (or inline for small values).
Measurements : "manages" Simulations_Collection ..> Simulations : "manages" Cache_Collection ..> Cache : "manages"
-->
--> Measurements : "manages"
Simulations_Collection ..> Simulations : "manages"
Cache_Collection ..> Cache : "manages"
Document Fields¶
| Field | Type | Description |
|---|---|---|
projectName |
str |
The project this document belongs to |
_cls |
str |
Discriminator: "Metadata.Measurements", "Metadata.Simulations", or "Metadata.Cache" |
type |
str |
Application-defined type tag (e.g., "ToolkitDataSource", "Experiment_rawData") |
resource |
str |
Path to the data file on disk, or inline value for small data |
dataFormat |
str |
One of the datatypes constants (see below) |
desc |
dict |
Free-form metadata dictionary — toolkit name, version, parameters, etc. |
Collection Architecture¶
Each collection type wraps a MongoEngine document class and provides the standard CRUD interface:
GetMeas --> GetDoc DelMeas --> DelDoc AddDoc --> MetadataCol GetDoc --> MetadataCol DelDoc --> MetadataCol
-->
--> GetMeas --> GetDoc
DelMeas --> DelDoc
AddDoc --> MetadataCol
GetDoc --> MetadataCol
DelDoc --> MetadataCol
Three Parallel APIs
The Project class exposes identical method sets for all three collection types: addMeasurementsDocument / addSimulationsDocument / addCacheDocument, and similarly for get and delete. Under the hood, each delegates to its own Collection instance which filters by the _cls discriminator.
The datatypes System¶
Source: hera/datalayer/datahandler.py (class datatypes)
The datatypes class defines all supported data format constants and provides the dispatch logic to read and write data in each format.
Supported Formats¶
subgraph DynamicFormats ["Dynamic"] direction LR CLASS["CLASS\nClass\npydoc.locate + instantiate"] end
-->
--> subgraph DynamicFormats ["Dynamic"]
direction LR
CLASS["CLASS\nClass\npydoc.locate + instantiate"]
end
| Constant | Value | Description |
|---|---|---|
STRING |
"string" |
Plain text / path string |
CSV_PANDAS |
"csv_pandas" |
CSV file read via pandas |
HDF |
"HDF" |
HDF5 file |
NETCDF_XARRAY |
"netcdf_xarray" |
NetCDF file read via xarray |
ZARR_XARRAY |
"zarr_xarray" |
Zarr archive read via xarray |
JSON_DICT |
"JSON_dict" |
JSON file parsed to dict |
JSON_PANDAS |
"JSON_pandas" |
JSON file read via pandas |
JSON_GEOPANDAS |
"JSON_geopandas" |
GeoJSON file read via geopandas |
GEOPANDAS |
"geopandas" |
Shapefile / GeoPackage read via geopandas |
GEOTIFF |
"geotiff" |
GeoTIFF raster read via rasterio |
PARQUET |
"parquet" |
Parquet file read via dask/pandas |
IMAGE |
"image" |
Image file read via matplotlib |
PICKLE |
"pickle" |
Python pickle file |
DICT |
"dict" |
Inline dictionary (stored in resource) |
NUMPY_ARRAY |
"numpy_array" |
NumPy .npy/.npz file |
NUMPY_DICT_ARRAY |
"numpy_dict_array" |
Dict of NumPy arrays |
CLASS |
"Class" |
Dynamic Python class (imported at runtime) |
Format Dispatch Flow¶
When document.getData() is called, the system resolves the handler based on dataFormat:
LoadClass --> Return ReadPickle --> Return ReadTiff --> Return ReadImg --> Return ReturnString --> Return
-->
--> LoadClass --> Return
ReadPickle --> Return
ReadTiff --> Return
ReadImg --> Return
ReturnString --> Return
Auto-Detection
The datatypes.getDataFormatName(data) static method can auto-detect the format from a Python object (DataFrame -> "parquet", xarray.Dataset -> "netcdf_xarray", dict -> "JSON_dict", etc.). This is used by Project.saveData() to automatically choose the right format and file extension.
Repository JSON Structure¶
A repository JSON is the standard way to declare and load data into a Hera project. It maps toolkit names to their configuration, datasources, and documents.
Format¶
{
"<ToolkitName>": {
"Config": {
"key1": "value1",
"key2": "value2"
},
"Datasource": {
"<datasource_name>": {
"isRelativePath": "True",
"item": {
"resource": "relative/path/to/data.parquet",
"dataFormat": "parquet",
"version": [0, 0, 1],
"desc": { ... }
}
}
},
"Measurements": {
"<measurement_name>": {
"isRelativePath": "True",
"item": {
"resource": "relative/path/to/file.shp",
"dataFormat": "geopandas",
"type": "SomeType",
"desc": { ... }
}
}
}
}
}
Loading Pipeline¶
DT->>Toolkit: Call named functionwith parameters end end end
DT-->>User: Loading complete
-->
-->DT->>Toolkit: Call named function<br/>with parameters
end
end
end
DT-->>User: Loading complete
-->
-->
Path Resolution¶
Each item in the repository JSON has an isRelativePath flag:
"True"— Theresourcepath is relative to the JSON file's directory. The loader prependsbasedirto make it absolute."False"— Theresourceis already an absolute path and is used as-is.
String Booleans
The isRelativePath field accepts both string "True"/"False" and Python booleans true/false. The loader checks for both forms. Always be explicit to avoid ambiguity.
Static Loading (No MongoDB)¶
For testing or lightweight scripts, dataToolkit provides two static methods that work without MongoDB:
from hera.utils.data.toolkit import dataToolkit
# Load and resolve all paths in one call
repo = dataToolkit.loadRepositoryFromPath("/path/to/repository.json")
# Or resolve paths on an already-parsed dict
resolved = dataToolkit.resolveDataSourcePaths(repo_dict, basedir="/data/root")
These methods perform a deep copy of the JSON and resolve all relative resource paths to absolute, but do not insert anything into MongoDB.
ToolkitDataSource Documents¶
When a datasource is registered via abstractToolkit.addDataSource(), it creates a special document:
{
"projectName": "MY_PROJECT",
"_cls": "Metadata.Measurements",
"type": "ToolkitDataSource",
"resource": "/data/meteorology/YAVNEEL.parquet",
"dataFormat": "parquet",
"desc": {
"toolkit": "MeteoLowFreq",
"datasourceName": "YAVNEEL",
"version": [0, 0, 1]
}
}
Querying Datasources
The abstractToolkit methods always filter by type="ToolkitDataSource" and toolkit=self.toolkitName. This ensures that each toolkit only sees its own datasources, even though all documents share the same MongoDB collection.
Version Resolution¶
When getDataSourceDocument(name) is called without a version:
s" --> PickMax["Sort by version\ntuple and pick\nhighest version"]
PickMax --> ReturnDoc
QueryDefault --> ReturnDoc
-->
-->s" --> PickMax["Sort by version\ntuple and pick\nhighest version"]
PickMax --> ReturnDoc
QueryDefault --> ReturnDoc
-->
-->
addDataSource Swimlane¶
The full call chain when a toolkit registers a new data source — from the toolkit API down through the data layer to MongoDB:
add[Type]Document Swimlane¶
The call chain for adding documents to each collection (Measurements, Simulations, Cache). All three follow the same pattern — only the collection class differs:
loadData Swimlane (HighFreqToolKit)¶
The complete flow for ingesting raw sensor data — from parsing through to data source registration:
Connection Management (document/__init__.py)¶
How connections are established¶
When hera is imported, the document/__init__.py module automatically connects to all databases defined in ~/.pyhera/config.json:
# Runs at import time (bottom of document/__init__.py)
for user in getDBNamesFromJSON():
createDBConnection(
connectionName=user,
mongoConfig=getMongoConfigFromJson(connectionName=user)
)
Dynamic class creation¶
MongoDB document classes are created dynamically at runtime using Python's type() builtin. This allows each database connection to have its own set of MongoEngine document classes with the correct db_alias:
# Creates a new class: Metadata(DynamicDocument, MetadataFrame)
new_Metadata = type('Metadata', (DynamicDocument, MetadataFrame), {
'meta': {
'db_alias': f'{dbName}-alias', # binds to specific DB
'allow_inheritance': True, # enables Measurements/Simulations/Cache subtypes
'auto_create_indexes': True,
'indexes': ['projectName'] # index for fast project queries
}
})
# Subtypes inherit from the dynamic Metadata class
new_Measurements = type('Measurements', (new_Metadata,), {})
new_Simulations = type('Simulations', (new_Metadata,), {})
new_Cache = type('Cache', (new_Metadata,), {})
The dbObjects registry¶
All connections and document classes are stored in a module-level dictionary:
dbObjects = {
"connectionName1": {
"connection": <mongoengine connection>,
"Metadata": <dynamic Metadata class>,
"Measurements": <dynamic Measurements class>,
"Simulations": <dynamic Simulations class>,
"Cache": <dynamic Cache class>,
},
"connectionName2": { ... },
}
getDBObject(objectName, connectionName) retrieves a class from this registry. Collections use it to get their MongoEngine document class:
# Inside AbstractCollection.__init__:
self._metadataCol = getDBObject('Metadata', connectionName)
# or for typed collections:
self._metadataCol = getDBObject('Measurements', connectionName)
Multi-database support¶
Each connection name maps to a separate MongoDB database. This enables: - Different projects on different servers - Shared "public" databases alongside local ones - Parallel connections with different aliases
MetadataFrame (document/metadataDocument.py)¶
getData() dispatch¶
MetadataFrame.getData() is the bridge between metadata and actual data:
def getData(self, **kwargs):
storeParametersDict = self.desc.get("storeParameters", {})
storeParametersDict.update(kwargs)
return getHandler(self.dataFormat).getData(
resource=self.resource, desc=self.desc, **storeParametersDict
)
- Reads
storeParametersfrom the document'sdesc— these were saved when the data was written (e.g.,usePandas=Truefor parquet) - Merges with any kwargs passed by the caller
- Calls
getHandler(dataFormat)to find the rightDataHandler_*class - Delegates to the handler's
getData(resource, desc, **params)
nonDBMetadataFrame¶
A wrapper for data that isn't stored in MongoDB. Used by saveData when saveMode=NOSAVE and by createNewArea when data is computed in memory:
class nonDBMetadataFrame:
def __init__(self, data, projectName=None, type=None, ...):
self._data = data # the actual Python object
def getData(self, **kwargs):
return self._data # just returns the object, no handler dispatch
DataHandler Pattern (datahandler.py)¶
How handlers work¶
Each DataHandler_* class is a static utility with two methods:
class DataHandler_parquet:
@staticmethod
def saveData(resource, fileName, **kwargs):
# Save the data object to disk
resource.to_parquet(fileName, **kwargs)
return {"usePandas": True} # store parameters returned to caller
@staticmethod
def getData(resource, desc={}, usePandas=False, **kwargs):
# Load data from disk
df = dask.dataframe.read_parquet(resource, **kwargs)
if usePandas:
df = df.compute()
return df
Key pattern:
- saveData writes to disk and returns a dict of store parameters — these are saved in desc.storeParameters so getData can reproduce the exact same load behavior
- getData reads from disk using resource (file path) and desc for metadata
Handler dispatch¶
def getHandler(objectType):
handlerName = f"DataHandler_{objectType}"
return getattr(datahandler_module, handlerName)
objectType is the dataFormat string (e.g., "parquet" → DataHandler_parquet).
Auto-detection¶
When saving data with Project.saveData(), the format is auto-detected:
datatypes.typeDatatypeMap = {
"pandas.core.frame.DataFrame": {"typeName": "parquet", "ext": "parquet"},
"geopandas.geodataframe.GeoDataFrame": {"typeName": "geopandas", "ext": "gpkg"},
"xarray.core.dataarray.DataArray": {"typeName": "zarr_xarray", "ext": "zarr"},
"numpy.ndarray": {"typeName": "numpy_array", "ext": "npy"},
"dict": {"typeName": "pickle", "ext": "pckle"},
# ...
}
datatypes.getDataFormatName(obj) looks up the fully-qualified class name in this map and returns the format string.
Adding a new handler¶
-
Create a class
DataHandler_myformatindatahandler.py: -
Add a constant to
datatypes: -
Optionally add to
typeDatatypeMapfor auto-detection:
Function Caching (autocache.py)¶
How @cacheFunction works¶
The cacheFunction decorator caches function return values in the project database:
@cacheFunction(returnFormat=datatypes.PARQUET, projectName="MY_PROJECT")
def expensive_computation(x, y):
# ... long computation ...
return result_df
Cache lookup flow¶
1. Function called with (args, kwargs)
↓
2. Bind args to function signature → dict of all parameters
↓
3. Convert to JSON (ConfigurationToJSON) with standardized MKS units
↓
4. Serialize non-BSON values to base64 text
↓
5. Add function's fully-qualified name
↓
6. Query Cache collection: type="functionCacheData" + all serialized params
↓
7a. Cache HIT → doc.getData() → return
7b. Cache MISS → execute function → saveData → create cache document → return
Argument serialization¶
Each function argument is checked for BSON compatibility:
for key, value in call_info.items():
serializable = BSON.encode({'test': value}) # try BSON
if serializable:
call_info_serialized[key] = (True, value) # store as-is
else:
call_info_serialized[key] = (False, base64(pickle(value))) # serialize
This handles complex objects (numpy arrays, custom classes) that MongoDB can't store natively.
Unit standardization¶
Arguments with physical units (pint Quantities or Unum) are converted to MKS before querying. This means 5 * ureg.km and 5000 * ureg.m produce the same cache key — the cache is unit-aware.
API Reference¶
hera.datalayer.datahandler.datatypes
¶
Registry of supported data format constants and dispatch logic for data handlers.
Each constant (e.g. STRING, PARQUET, HDF) identifies a data format.
Use getHandler(formatName) to retrieve the corresponding DataHandler_* class,
or getDataFormatName(obj) to auto-detect the format from a Python object.
Source code in hera/datalayer/datahandler.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
STRING = 'string'
class-attribute
instance-attribute
¶
CSV_PANDAS = 'csv_pandas'
class-attribute
instance-attribute
¶
NETCDF_XARRAY = 'netcdf_xarray'
class-attribute
instance-attribute
¶
JSON_DICT = 'JSON_dict'
class-attribute
instance-attribute
¶
GEOPANDAS = 'geopandas'
class-attribute
instance-attribute
¶
PARQUET = 'parquet'
class-attribute
instance-attribute
¶
CLASS = 'Class'
class-attribute
instance-attribute
¶
hera.utils.data.toolkit.dataToolkit
¶
Bases: abstractToolkit
Toolkit for managing data repositories (replacing the old hera-data).
It is initialized only with the DEFAULT project.
The structure of a datasource file is:
{
"<toolkit name>": {
"<datasource name>": {
"resource": "<location of datasource>",
"dataFormat": "<type of data source>",
"desc": {
... metadata ...
}
},
...
},
...
}
Source code in hera/utils/data/toolkit.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 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 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
addRepository(repositoryName, repositoryPath, overwrite=False)
¶
Register a repository JSON file as a data source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repositoryName
|
str
|
The name to register the repository under. |
required |
repositoryPath
|
str
|
Path to the repository JSON file. |
required |
overwrite
|
bool
|
If True, overwrite an existing repository with the same name. |
False
|
Source code in hera/utils/data/toolkit.py
getRepository(repositoryName)
¶
Load and return a repository's JSON content by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repositoryName
|
str
|
The name of the registered repository. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
The parsed repository JSON. |
Source code in hera/utils/data/toolkit.py
loadAllDatasourcesInRepositoryJSONToProject(projectName: str, repositoryJSON: dict, basedir: str = '', overwrite: bool = False, auto_register_missing: bool = True)
¶
Iterate through the repository JSON and for each toolkit: - Try to get an instance via ToolkitHome.getToolkit. - If missing and auto_register_missing=True, attempt auto-register ONLY if there is a clear classpath hint in the JSON (Registry.classpath or Registry.cls). - After we have a valid instance, dispatch to the appropriate handler per section.
Source code in hera/utils/data/toolkit.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
resolveDataSourcePaths(repositoryJSON, basedir='')
staticmethod
¶
Walk a repository JSON dict and resolve every resource field to an
absolute path, respecting the isRelativePath flag on each entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repositoryJSON
|
dict
|
The parsed repository JSON (toolkit-name -> section dict). |
required |
basedir
|
str
|
The base directory against which relative paths are resolved. Typically the directory that contains the repository JSON file. |
''
|
Returns:
| Type | Description |
|---|---|
dict
|
A deep copy of |
Source code in hera/utils/data/toolkit.py
loadRepositoryFromPath(json_path)
staticmethod
¶
Read a repository JSON file directly from disk, resolve all relative
resource paths to absolute paths based on the JSON file's directory,
and return the resulting dict.
This allows tests (and lightweight scripts) to work with repository
data without going through addRepository + MongoDB storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_path
|
str
|
Path to the repository JSON file. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
The repository dict with all resource paths resolved to absolute. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If json_path does not exist. |