Annotations

Open in marimo
WarningExperimental

Annotations are an experimental part of DASCore: the API and file formats may change in any minor release without a deprecation period. See what experimental means.

An AnnotationSet records where things are in your data: phase picks, a window around an event, a vehicle’s track, the outline of a noisy region. Annotations are written in coordinates (e.g., time and distance) rather than sample indices, so they stay valid when the data are decimated, trimmed, or re-chunked. They describe data but never hold it.

This tutorial annotates light-rail trains in a recording from Salt Lake City: it picks train passages, groups the picks into trains, measures their speeds, traces one train along the fiber, and then plots, queries, cuts, and saves the result.

The data

The example holds about 50 minutes of low-frequency DAS recorded under a street in Salt Lake City, decimated to 4 Hz, along 745 m of fiber. Light-rail trains show up every few minutes as strong bursts of strain rate:

import tempfile
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.signal import find_peaks

import dascore as dc

patch = dc.get_example_patch("UoU_lf_urban.hdf5")
_ax = patch.viz.waterfall(scale=0.1)

Picking train passages

Picks usually come from a picker or a spreadsheet as one table. Here a simple picker finds the moments when the strain rate anywhere on the fiber peaks, and notes where on the fiber that happened:

amplitude = np.abs(patch.data)
strongest = amplitude.max(axis=1)
peaks, _ = find_peaks(strongest, height=1e-5, distance=4 * 60)

picks = pd.DataFrame(
    {
        "time": patch.get_array("time")[peaks],
        "distance": patch.get_array("distance")[amplitude[peaks].argmax(axis=1)],
        "peak": strongest[peaks],
    }
)
picks.head()
time distance peak
0 2023-05-24 02:49:52.350844422 7145.033163 0.000057
1 2023-05-24 02:50:52.353646182 7639.990879 0.000081
2 2023-05-24 02:55:02.115308508 7194.038878 0.000083
3 2023-05-24 02:56:07.118343748 7639.990879 0.000085
4 2023-05-24 02:58:04.623830528 7635.090308 0.000010

AnnotationSet.from_patch turns the table into a set. It takes the dimensions from the patch and records which data the picks were made on. Columns other than the dimensions, such as peak, are yours and are kept as written.

pick_set = dc.AnnotationSet.from_patch(patch, picks)
pick_set
DASCore AnnotationSet 🏷
Dimensions (time, distance)
    *time: min: 2023-05-24T02:49:52.350844422 max: …03:36:42.232048508 <46.8 m> (value)
    *distance: min: 7135.232 max: 7644.891 <509.659> (value)
Contents
    annotations: 24
    features: 24 (groups: 24, paths: 0, polygons: 0)
    bases: 0
    annotation columns: time, distance, peak, feature_id
Attributes
    data_id: db90866432091e707379a150a6e8bc1e

Grouping picks into trains

Each train is picked twice: first near the west end of the fiber (around 7,150 m), then about a minute later near the east end (around 7,630 m). Rows that belong together share a feature_id, so pairing those picks turns them into trains. A few weaker signals near the east end have no partner; they stay as single picks.

is_west = picks["distance"] < 7400
is_second = (
    ~is_west
    & is_west.shift(fill_value=False)
    & (picks["time"].diff() < pd.Timedelta("90s"))
)
is_first = is_second.shift(-1, fill_value=False)
train_number = is_first.cumsum().astype(str)
grouped = picks.assign(feature_id=("train_" + train_number).where(is_first | is_second))

trains = dc.AnnotationSet.from_patch(patch, grouped)
trains.features
geometry id
0 None train_1
1 None train_2
2 None train_3
3 None train_4
4 None train_5
5 None train_6
6 None train_7
7 None train_8
8 None train_9
9 None train_10

You never write the features table yourself: naming a new feature_id creates the group.

How a set is organized

A set holds three tables:

  • annotations: one row per located thing. For each dimension a row states a single value (time), a half-open range (time_min, time_max), or nothing, in which case it spans that whole dimension.
  • features: what rows compose. A feature is a group (unordered, like the trains above), a path (vertices in order), or a polygon (rings of vertices). A row without a feature_id is a feature on its own.
  • bases: named curves, such as a straight line, that a path can be drawn from instead of listing its vertices.

So a row can be an instant across the whole fiber, a pick at one place, or a stretch of fiber at all times:

time distance distance_min distance_max feature_id reads as
03:10:00 an instant across the fiber
03:10:00 7630 train_5 a pick, part of train_5
7350 7420 a stretch of fiber at all times

Train speeds

bounds gives each feature’s extent. A train’s extent is how far and how long it traveled between its two picks, which gives its speed:

extent = trains.bounds().dropna(subset=["feature_id"])
seconds = (extent["time_max"] - extent["time_min"]).dt.total_seconds()
extent.assign(speed=(extent["distance_max"] - extent["distance_min"]) / seconds)
feature_id annotation kind time_min time_max distance_min distance_max speed
0 train_1 <NA> group 2023-05-24 02:49:52.350844422 2023-05-24 02:50:52.353646182 7145.033163 7639.990879 8.248910
1 train_2 <NA> group 2023-05-24 02:55:02.115308508 2023-05-24 02:56:07.118343748 7194.038878 7639.990879 6.860480
2 train_3 <NA> group 2023-05-24 02:59:14.627099248 2023-05-24 03:00:17.130017748 7194.038878 7620.388593 6.821277
3 train_4 <NA> group 2023-05-24 03:05:28.644563552 2023-05-24 03:06:30.397447030 7145.033163 7610.587450 7.538989
4 train_5 <NA> group 2023-05-24 03:09:54.906996362 2023-05-24 03:10:55.909844818 7198.939449 7644.891450 7.310347
5 train_6 <NA> group 2023-05-24 03:15:59.674028728 2023-05-24 03:17:01.176900532 7189.138306 7620.388593 7.011872
6 train_7 <NA> group 2023-05-24 03:20:23.686356472 2023-05-24 03:21:24.189181580 7135.232020 7615.488022 7.937745
7 train_8 <NA> group 2023-05-24 03:24:23.697563512 2023-05-24 03:25:24.200388620 7198.939449 7644.891450 7.370763
8 train_9 <NA> group 2023-05-24 03:31:27.967374290 2023-05-24 03:32:28.220187724 7194.038878 7620.388593 7.076013
9 train_10 <NA> group 2023-05-24 03:35:38.729083312 2023-05-24 03:36:42.232048508 7135.232020 7644.891450 8.025758

The trains move at about 7 to 8 m/s, roughly 25 to 30 km/h.

Tracing a train

add_path adds a path through its vertices. To trace train_8, take the time its signal peaks on each channel it reaches. An array keyword gives one value per vertex, and a scalar keyword, such as vehicle, describes the whole path. Builder methods like this return a new set.

train_8 = extent.set_index("feature_id").loc["train_8"]
passage = patch.select(
    time=(train_8.time_min - pd.Timedelta("20s"), train_8.time_max + pd.Timedelta("20s"))
)
passage_amplitude = np.abs(passage.data)
reached = passage_amplitude.max(axis=0) > 5e-6
track_time = passage.get_array("time")[passage_amplitude.argmax(axis=0)][reached][::6]
track_distance = passage.get_array("distance")[reached][::6]

traced = trains.add_path(
    "train_8_track", time=track_time, distance=track_distance, vehicle="light rail"
)

Marking a quiet window

add_polygon outlines a region. Give the outer ring first and any holes after it; each ring closes on its own. A box with no trains in it, across the whole fiber, marks a window to estimate noise from:

quiet_start = pd.Timestamp("2023-05-24T03:02:30")
quiet_end = pd.Timestamp("2023-05-24T03:04:30")
fiber_start, fiber_end = patch.get_array("distance")[[0, -1]]
quiet = {
    "time": [quiet_start, quiet_end, quiet_end, quiet_start],
    "distance": [fiber_start, fiber_start, fiber_end, fiber_end],
}
ann = traced.add_polygon("quiet", rings=[quiet], note="noise window")
ann
DASCore AnnotationSet 🏷
Dimensions (time, distance)
    *time: min: 2023-05-24T02:49:52.350844422 max: …03:36:42.232048508 <46.8 m> (value)
    *distance: min: 7002.917 max: 7747.803 <744.887> (value)
Contents
    annotations: 41
    features: 16 (groups: 14, paths: 1, polygons: 1)
    bases: 0
    annotation columns: time, distance, peak, feature_id, seq, part, ring
    feature columns: geometry, id, vehicle, note
Attributes
    data_id: db90866432091e707379a150a6e8bc1e

Seeing your annotations

AnnotationSet.viz.plot draws a set over a waterfall. Picks are markers, paths are lines, polygons are filled shapes, and a row spanning a dimension is a line or band across it:

_ax = patch.viz.waterfall(scale=0.1)
_ax = ann.viz.plot(ax=_ax)

Zooming in on the traced train shows the path following its leading edge. overlapping, given a patch, keeps only the features within it:

_ax = passage.viz.waterfall(scale=0.1)
_ax = ann.overlapping(passage).viz.plot(ax=_ax)

Pass color to color by a column, and palette to fix the colors of chosen values.

Finding annotations

select filters by column values. A value matches exactly, a list matches any of its values, and a tuple is an inclusive range:

strong = ann.select(peak=(5e-5, None))
strong.annotations[["time", "distance", "peak", "feature_id"]]
time distance peak feature_id
0 2023-05-24 02:49:52.350844422 7145.033163 0.000057 train_1
1 2023-05-24 02:50:52.353646182 7639.990879 0.000081 train_1
2 2023-05-24 02:55:02.115308508 7194.038878 0.000083 train_2
3 2023-05-24 02:56:07.118343748 7639.990879 0.000085 train_2
4 2023-05-24 03:00:17.130017748 7620.388593 0.000086 train_3
5 2023-05-24 03:05:28.644563552 7145.033163 0.000055 train_4
6 2023-05-24 03:06:30.397447030 7610.587450 0.000085 train_4
7 2023-05-24 03:09:54.906996362 7198.939449 0.000056 train_5
8 2023-05-24 03:10:55.909844818 7644.891450 0.000085 train_5
9 2023-05-24 03:15:59.674028728 7189.138306 0.000061 train_6
10 2023-05-24 03:17:01.176900532 7620.388593 0.000092 train_6
11 2023-05-24 03:21:24.189181580 7615.488022 0.000080 train_7
12 2023-05-24 03:24:23.697563512 7198.939449 0.000084 train_8
13 2023-05-24 03:31:27.967374290 7194.038878 0.000060 train_9
14 2023-05-24 03:32:28.220187724 7620.388593 0.000073 train_9
15 2023-05-24 03:35:38.729083312 7135.232020 0.000055 train_10
16 2023-05-24 03:36:42.232048508 7644.891450 0.000069 train_10

overlapping also takes ranges, and keeps or drops each feature whole:

first_ten_minutes = ann.overlapping(
    time=(patch.get_coord("time").min(), pd.Timestamp("2023-05-24T02:56"))
)
[x.id for x in first_ten_minutes]
['train_1', 'train_2']

Cutting data around trains

Spool.cut returns one patch per feature, cut to its bounds and merged across the files it crosses. A pad of (before, after) widens the cut, here by 20 seconds on each side:

spool = dc.spool([patch])
train_ids = list(trains.features["id"])
cut = spool.cut(trains.select(feature_id=train_ids), time=("-20s", "20s"))
cut.get_contents()[["feature_id", "time_min", "time_max"]]
feature_id time_min time_max
0 train_1 2023-05-24 02:49:32.599922176 2023-05-24 02:51:12.104568428
1 train_2 2023-05-24 02:54:42.364386262 2023-05-24 02:56:26.869265994
2 train_3 2023-05-24 02:58:54.876177002 2023-05-24 03:00:36.880939994
3 train_4 2023-05-24 03:05:08.893641306 2023-05-24 03:06:50.148369276
4 train_5 2023-05-24 03:09:35.156074116 2023-05-24 03:11:15.660767064
5 train_6 2023-05-24 03:15:39.923106482 2023-05-24 03:17:20.927822778
6 train_7 2023-05-24 03:20:03.935434226 2023-05-24 03:21:43.940103826
7 train_8 2023-05-24 03:24:03.946641266 2023-05-24 03:25:43.951310866
8 train_9 2023-05-24 03:31:08.216452044 2023-05-24 03:32:47.971109970
9 train_10 2023-05-24 03:35:18.978161066 2023-05-24 03:37:01.982970754

Each cut patch states its feature_id, so you can join the results back to the set.

Editing

update changes a feature’s or annotation’s columns, remove drops one, and merge combines sets in the same dimensions, such as hand and automatic picks:

edited = ann.update(feature="train_8", note="traced").remove(feature="quiet")

Saving and sharing

A set of picks alone saves as a single table. CSV is easy to share but does not record the dimensions or which data the picks were made on, so state the dimensions again when reading. io.to_parquet keeps both (it needs pyarrow).

folder = Path(tempfile.mkdtemp())
csv_path = folder / "picks.csv"
pick_set.io.to_csv(csv_path)
from_csv = dc.annotations(csv_path, dims=patch.dims)

A set with features or bases saves as a directory, and dc.annotations reads it back:

directory = edited.io.save(folder / "trains")
assert dc.annotations(directory) == edited

To read a CSV written by another tool, name its columns as above (time, or time_min and time_max, for each dimension) and read it with dc.annotations(path, dims=("time", "distance")). Reading it with plain pandas instead turns identifiers such as 001 into numbers and NA into missing values.

Ranges and edges

Three interval rules meet in annotations: a row’s _min/_max range is half-open, a select tuple includes both ends, and overlapping given a patch includes the patch’s last sample.