import tempfile
from pathlib import Path
import dascore as dc
from dascore.examples import inventory_patch_pair, write_tunnel_inventory
from dascore.exceptions import PatchError
patch, inventory = inventory_patch_pair()Inventory
This page covers an experimental part of DASCore: its API and file formats may change in any minor release without a deprecation period. See what experimental means.
A DASDAE inventory describes the observing system behind a fiber archive: the optical path, interrogator settings, deployment geometry, coupling, and labels. It plays the role StationXML plays for point sensors while leaving the data files unchanged.
Patches join to the inventory through acquisition_key (network.fiber_array.location.acquisition) and time. The result is metadata: patch attributes, coordinates along the fiber, and names available for selection and grouping.
The model
The diagram compares concepts with StationXML; it is not a containment diagram. In DASCore, acquisitions and optical paths are sibling collections on a fiber array. There is no Location model: a Channel carries a location_code, and a station holds its channels directly.
An Inventory contains Network objects. A network may hold conventional stations and FiberArray objects. Each fiber array holds:
Acquisitionobjects, which describe an interrogator stream and map acquisition distance onto an optical path.OpticalPathobjects, which describe what the light travelled through.
Shared objects such as interrogators, cables, enclosures, and measurements live under Inventory.resources. Other objects refer to them by resource_id; model constructors also accept the object itself. The inventory reference shows which file holds each object and how they refer to one another.
An optical path has four independent tracks along optical distance. Think of optical distance as a ruler laid along the fiber and of each track as a separate table of notes against it:
optical_components: fiber segments, splices, connectors, amplifiers, and terminators. These tile the complete path and define its extent. A fiber segment’sbuffer_typeis one oftight_buffered,semi_tight,loose_tube,ribbon,bare, orother, and empty when not stated.geometry: measured quantities along the fiber, including coordinates named by the inventory’s coordinate reference system.coupling: how each interval of cable meets its surroundings.labels: interval names such as borehole, drift, or zone.
Geometry, coupling, and labels may cover only part of the path. Missing coverage means “not stated,” not that the fiber or channel is absent.
Acquisitions and optical paths may have time-bounded epochs, so hardware or geometry can change while the fiber array keeps its identity. Resolving a patch therefore uses both its acquisition key and time.
Track semantics
Tracks use three shapes:
| shape | tracks | coverage | overlap | value outside coverage |
|---|---|---|---|---|
| tiling | optical_components |
complete | none | — |
| function | geometry columns, coupling, labels with values | partial | none | "" or NaN |
| membership | labels without values | partial | allowed | False |
Every label names its group, the coordinate it becomes. A label with an empty value states membership; one with a value defines an interval coordinate. Literal true and false values are refused, since an empty value already means membership. A group holds only text, only numbers, or only membership. Numeric groups use NaN outside coverage, so they project as floating-point coordinates.
OpticalPath.select takes a label group as a keyword, so path.select(section="coil") returns the part of the path where section is coil, with all its tracks; pass True for a membership group. A path is one contiguous range, so a value stated in several separate places raises an error naming them, and adding distance= narrows the selection to one.
Intervals are half-open, [start, end), so adjacent rows tile without overlap; projection still includes the final channel of a covered run.
Geometry columns, label groups, and typed tracks become coordinates. Label group names cannot use structural names, track names, recognized coordinate labels, or a track field’s short name such as buffer_type; see RESERVED_GROUP_NAMES in dascore.core.inventory. Geometry columns may use coordinate labels—that is how a segment states an axis—but cannot use the other reserved names or share a name with a label group.
Inspecting and visualizing
The examples use an inventory and patch that resolve together:
Inventory.get_names separates scalar attributes from per-channel coordinates:
names = inventory.get_names()
assert "gauge_length" in names.attrs
assert {"zone", "noisy", "coupling"} <= set(names.coords)This lists what the inventory can contribute; on a partially covered path, some channels get a blank value.
Inventory.viz.path aligns acquisitions, components, coupling, labels, and geometry along optical distance:
inventory.viz.path(show=True);
Use tracks= to select lanes and columns= to select geometry columns. Inventory.viz.map plots geometry in space, while Inventory.viz.timeline plots acquisition and path epochs through time.
Using an inventory with a spool
Spool.attach_inventory stores a reference to an inventory without changing patches or loading data. conform_to_inventory uses the attached inventory; enrich uses it too, or attaches one it is given.
spool = dc.spool(patch).attach_inventory(inventory)
assert "gauge_length" not in dict(spool[0].attrs)Once attached, inventory coordinates can drive selection and expansion:
northern = spool.select(zone="north")
zones = spool.expand_by("zone")
assert set(zones.get_contents()["zone"]) == {"north", "south"}A label group is a key and its values are the options, like a column of a table; groups do not nest. In the tunnel inventory, section says what kind of installation a stretch of fiber is in and borehole says which hole, so one selection combines them:
tunnel_root = Path(tempfile.mkdtemp()) / "tunnel"
write_tunnel_inventory(tunnel_root)
tunnel_patch = dc.get_example_patch(
"random_das", acquisition_key="XT.TUN1.00.DAS", time_min="2024-06-01", shape=(1776, 20)
)
tunnel_spool = dc.spool(tunnel_patch).attach_inventory(dc.inventory(tunnel_root))
hole_2 = tunnel_spool.select(section="borehole", borehole=2)
assert hole_2[0].get_coord("distance").min() == 1650Selection trims channels, and a patch with no matching channels drops out silently. unselect removes the matching channels instead, so it can cut one patch into several pieces:
quiet = spool.unselect(noisy=True)
assert len(quiet) == 2Selection and expansion judge whole patches, so they also drop a patch that no single inventory context describes: one straddling an acquisition or optical-path change, reaching outside every optical-path epoch, or not described at all. Each call warns once with the number dropped; unselect keeps them. To select within such patches, conform the spool first. Selecting on an inventory-backed attribute such as gauge_length behaves the same, unless the patch states it in its own header.
Attaching a replacement inventory clears enrichment configured from the old one.
Supplying the acquisition key
Only acquisition_key and time decide which acquisition and optical path describe a patch. Readers never derive the key from a file’s own metadata (a DASDAE file keeps one the patch had when written), so supply it: set the attribute, pass acquisition_key to Patch.enrich, or store files under a folder named acquisition_key=<key>, which the spool index reads as an attribute; see path attributes.
keyless = patch.update_attrs(acquisition_key="")
assert keyless.enrich(inventory, acquisition_key="DAS.R2D1..RAW").attrs.gauge_length == 10.0
hive_root = Path(tempfile.mkdtemp())
keyed_folder = hive_root / "acquisition_key=DAS.R2D1..RAW"
keyed_folder.mkdir()
keyless.io.write(keyed_folder / "patch.h5", "DASDAE")
hive_spool = dc.spool(hive_root).update().attach_inventory(inventory)
assert hive_spool.enrich()[0].attrs.gauge_length == 10.0Enriching patches
Spool.enrich copies resolved metadata as patches are loaded. Acquisition and interrogator facts become attributes; optical-path facts become per-channel coordinates.
enriched = spool.enrich()[0]
assert enriched.attrs.gauge_length == 10.0
assert "zone" in enriched.coords.coord_map
assert set(enriched.get_array("coupling")) == {"trench", ""}The acquisition’s distance_map places channels on the optical path. Compatible distance units are converted; incompatible axes raise. With two or more control points, channels outside the map’s range are not placed. With one, the map extends both ways: by spatial_interval per channel on the channel axis (which therefore needs spatial_interval), or one meter per meter on the acquisition_distance axis. Channels not placed, or placed beyond the path’s ends, get NaN (or empty text) from its tracks without a warning, as is normal when an interrogator records past the end of the fiber. An unresolved patch is returned unchanged with a warning, so enrichment never silently removes data.
By default, scalar acquisition and interrogator.* fields become attributes, and geometry, coupling, labels, and the fiber’s buffer_type (when any segment states one) become coordinates. Channels on segments that state no buffer type get an empty value and are not matched by select(buffer_type=...). Position coordinates take the names the inventory’s coordinate reference system declares, such as easting, northing, and elevation, or x, y, and z under the default CRS; either spelling can be requested. Four fields are left out unless requested: data_type and data_units, because processing may have changed the data, and sample_rate and spatial_interval, which the patch coordinates already state.
Unset attributes are always filled. When a patch attribute conflicts with the inventory, conflict decides: raise (default), since a conflict usually means the patch resolved to the wrong acquisition; keep_first keeps the patch value, keep_last uses the inventory, and drop removes both.
stale = patch.update_attrs(gauge_length=99.0)
try:
stale.enrich(inventory)
except PatchError as err:
print(err)
assert stale.enrich(inventory, conflict="keep_first").attrs.gauge_length == 99.0
assert stale.enrich(inventory, conflict="keep_last").attrs.gauge_length == 10.0
assert stale.enrich(inventory, conflict="drop").attrs.get("gauge_length") is NoneThe patch's 'gauge_length' is 99.0 but the inventory says 10.0. A disagreement here usually means the acquisition_key resolved to the wrong place.
Interrogator fields are not match keys: interrogator.name, interrogator.instrument_type, and the other interrogator.* fields are copied like any attribute. Several readers (TDMS, Silixa H5, DASVader, OptoDAS, and Febus, for example) set interrogator.name, often to the recording computer’s host name, so an inventory whose Interrogator.name says something else raises under the default policy. A blank value on either side never conflicts, so leave name empty in the inventory unless it matches what the files report:
from_host = patch.update_attrs(**{"interrogator.name": "host-7"})
# This inventory's interrogator states no name, so the file's stands.
assert from_host.enrich(inventory).attrs.get("interrogator.name") == "host-7"Patch.enrich does the same for one patch, but raises on an unresolved patch.
Conforming a spool
Spool.conform_to_inventory resolves every row now, splits patches at optical-path changes, and by default raises on unresolved patches. Because it can remove, split, or reject data, it runs only when asked; attaching and enriching never change the spool’s length.
stranger = dc.get_example_patch("random_das", acquisition_key="XX.NOPE..RAW")
mixed = dc.spool([patch, stranger]).attach_inventory(inventory)
conformed = mixed.conform_to_inventory(on_unresolved="ignore")
assert len(conformed) == 1
assert conformed[0].attrs.acquisition_key == "DAS.R2D1..RAW"Splitting keeps every sample exactly once. A patch with any sample outside every acquisition epoch, or outside every optical-path epoch at its location, is unresolved as a whole rather than cut; an acquisition whose location never has an optical path is exempt. Use on_unresolved="warn" or "ignore" when an inventory covers only part of an archive.
A patch straddling an acquisition change raises, since one patch cannot carry two acquisition configurations; select the time on each side of the change instead.
Inventory files beside data
A spool opened on a directory attaches an inventory stored there as .inventory/, .inventory.yaml, .inventory.yml, or .inventory.json:
data_path = Path(tempfile.mkdtemp()) / "archive"
data_path.mkdir()
patch.io.write(data_path / "patch.h5", "DASDAE")
inventory.io.to_yaml(data_path / ".inventory.yaml")
carrying = dc.spool(data_path).update()
assert carrying.enrich()[0].attrs.gauge_length == 10.0The spool finds the file when it opens but parses it only for an inventory-backed operation, such as selecting on an inventory coordinate, then caches it; len, sorting, chunking, loading patches, and selecting on indexed names do not parse it. After editing the file, call attach_inventory() with no argument to reread it.
Two .inventory spellings in one directory are refused as ambiguous. inventory.yaml, without the dot, is not a companion file; it is the envelope of the authoring directory.
Serializing
Inventory.io.to_yaml writes the single-file form. dc.inventory reads a directory, YAML, JSON, a model, or serialized text.
text = inventory.io.to_yaml()
assert dc.inventory(text) == inventory
json_path = data_path / "inventory.json"
json_path.write_text(inventory.model_dump_json())
assert dc.inventory(json_path) == inventoryInvalid documents raise InvalidInventoryError.