pysmo.tools.project
On-demand fetching and preparation of waveforms for stations and events.
A PysmoProject describes a pipeline that
fetches waveforms for a list of stations and prepares them for further
processing. The time window for each station is either derived from an event
or set explicitly. A project holds no waveform data itself, only its entries
and the functions that carry out each stage of the pipeline. There are three
stages, each with a default that can be replaced.
Stage 1: Fetch window resolution
Projects are built from a list of
ProjectEntry objects. Each entry holds
a station, plus an event, an explicit window (starttime/endtime), or
both. The event is optional: an entry without one just needs an explicit
window. The first stage resolves each entry to an absolute fetch window, a WindowResult:
- An entry with an explicit window uses it as-is, even if it also has an event.
- Otherwise the project's
windowresolver derives the window from the entry's event. The default,PhaseWindow, predicts the arrival of a seismic phase (P by default) at the station and returns the span[arrival + pre_pick, arrival + post_pick].
flowchart LR
Entry(["`**ProjectEntry**`"])
Explicit{"`Explicit
window?`"}
Window["`**window**
default: **PhaseWindow**`"]
Result(["`**WindowResult**`"])
Entry --> Explicit
Explicit -->|Yes| Result
Explicit -->|No| Window --> Result
Custom window resolvers
The window resolver holds the project's windowing policy: given an
event and a station, it decides which stretch of time to fetch.
PhaseWindow places it around a predicted phase arrival. A custom
WindowResolver can apply any
other rule, such as a fixed span after the origin time, or a window
around arrival times taken from an existing set of picks.
Stage 2: Seismogram fetch
The second stage downloads the raw waveform for the entry's station over the
resolved window, using the project's fetch_seismogram. The default fetches
miniSEED from the EarthScope FDSN dataselect service via
MSeed.fetch, and goes to the network on every
fetch. A checksum of the first waveform fetched for an entry is recorded on
ProjectEntry.checksum, so a
later fetch that returns different data is reported.
flowchart LR
Station(["`**ProjectEntry.station**`"])
Window(["`**WindowResult**`"])
Fetch["`**fetch_seismogram**
default: **MSeed.fetch**`"]
Raw(["`**Seismogram**`"])
Station --> Fetch
Window --> Fetch
Fetch --> Raw
Adding a cache
Data in a live archive can change between fetches. Caching the miniSEED
downloads on disk with a FetchCache
ensures every session of a project works with the same data (see
"Caching downloads" below). A custom
SeismogramFetcher is
typically only needed for a different data centre or a local archive.
Stage 3: Seismogram transformation
The third stage prepares the downloaded seismogram for downstream processing,
using the project's seismogram_transform, e.g. removing the instrument
response, detrending, and resampling. The transform also determines the
seismogram type the project returns. Alongside the seismogram, the
transform receives a FetchContext
with the entry, the window used for the fetch, and the reference from
stage 1, and it may make its own fetches, such as instrument response
metadata. The default copies the raw waveform into a
MiniSeismogram without any processing. The result
is kept in memory, so each entry is fetched and transformed only once for as
long as the project's settings stay unchanged.
flowchart LR
Raw(["`**Seismogram**`"])
Context(["`**FetchContext**`"])
Transform["`**seismogram_transform**
default: → **MiniSeismogram**`"]
Result(["`**TSeismogram**`"])
Raw --> Transform
Context --> Transform
Transform --> Result
Caching transformed data
Wrapping the transform in a
TransformCache stores its output
on disk, so later sessions skip the processing and the transform's own
fetches (see "Caching transformed seismograms" below). The waveform
itself is still fetched by fetch_seismogram.
Basic example
This example builds a project with a single entry, resolves its fetch window, and fetches the seismogram, with no stage customised. The entry pairs IU.ANMO with the 2010-02-27 Maule, Chile M8.8 earthquake:
>>> import pandas as pd
>>> from pysmo import MiniEvent, MiniStation
>>> from pysmo.tools.project import ProjectEntry, PysmoProject
>>>
>>> station_anmo = MiniStation(
... name="ANMO", network="IU", location="00", channel="LHZ",
... latitude=34.945981, longitude=-106.457133,
... )
>>> event_maule = MiniEvent(
... latitude=-36.122, longitude=-72.898, depth=22900.0,
... time=pd.Timestamp("2010-02-27T06:34:11.53Z"),
... )
>>> entry = ProjectEntry(station=station_anmo, event=event_maule)
>>> project = PysmoProject(entries=[entry])
>>>
Discovery methods only inspect entries and fetch no data:
>>> len(project.stations)
1
>>> project.events_for(station_anmo)
[MiniEvent(time=Timestamp('2010-02-27 06:34:11.530000+0000', tz='UTC'),
latitude=-36.122, longitude=-72.898, depth=22900.0)]
>>>
The entry has an event and no explicit window, so stage 1 calls the default
PhaseWindow, which places the window around the predicted P arrival. This
fetches no data either.
>>> window = project.window(entry)
>>> window.reference.floor("s")
Timestamp('2010-02-27 06:46:06+0000', tz='UTC')
>>> window.endtime - window.starttime
Timedelta('0 days 00:10:00')
>>>
Fetching the seismogram runs stages 2 and 3: the default
fetch_seismogram downloads miniSEED from EarthScope, and the default
seismogram_transform returns it unprocessed as a MiniSeismogram:
>>> seismogram = project.seismogram(station_anmo, event_maule)
>>> type(seismogram).__name__
'MiniSeismogram'
>>>
Building entries
A project may cover too many stations and events to write each
ProjectEntry by hand. build_entries
creates the entries from lists of stations and events: it pairs every
station with every event and keeps the pairs an optional filter function
accepts. Its inputs are plain lists of stations and events. In the example
below, they are parsed from a station inventory and an event catalogue, then
narrowed with list comprehensions. The project is generic over the event and
station types it is built from, so project.events / project.stations
return those concrete types, not the bare Event /
Station protocols.
example_catalogue.xml
<?xml version="1.0"?>
<q:quakeml xmlns="http://quakeml.org/xmlns/bed/1.2"
xmlns:q="http://quakeml.org/xmlns/quakeml/1.2">
<eventParameters publicID="smi:example/catalogue">
<event publicID="smi:example/maule">
<description><text>Maule, Chile</text></description>
<origin publicID="smi:example/maule/origin">
<time><value>2010-02-27T06:34:11.53Z</value></time>
<latitude><value>-36.122</value></latitude>
<longitude><value>-72.898</value></longitude>
<depth><value>22900</value></depth>
</origin>
<magnitude publicID="smi:example/maule/magnitude">
<mag><value>8.8</value></mag>
<type>Mw</type>
</magnitude>
<type>earthquake</type>
</event>
</eventParameters>
</q:quakeml>
example_inventory.xml
<?xml version="1.0"?>
<FDSNStationXML xmlns="http://www.fdsn.org/xml/station/1">
<Network code="IU">
<Station code="ANMO" startDate="1989-01-01T00:00:00">
<Latitude>34.945981</Latitude>
<Longitude>-106.457133</Longitude>
<Channel code="BHZ" locationCode="00" startDate="2008-06-30T20:00:00"
endDate="2011-02-18T19:11:00">
<Latitude>34.945981</Latitude>
<Longitude>-106.457133</Longitude>
</Channel>
</Station>
</Network>
</FDSNStationXML>
>>> from pathlib import Path
>>> from pysmo import Event, Station
>>> from pysmo.classes import QuakeML, StationXML, resolve_epochs
>>> from pysmo.tools.azdist import haversine
>>> from pysmo.tools.project import build_entries
>>>
>>> events = QuakeML.all_from_bytes(Path("example_catalogue.xml").read_bytes())
>>> strong = [e for e in events if (e.magnitude or 0) >= 8.0]
>>> inventory = StationXML.all_from_bytes(Path("example_inventory.xml").read_bytes())
>>> bhz = [e for e in inventory if e.channel == "BHZ"]
>>> stations = resolve_epochs(bhz, strong[0].time)
>>> len(strong), len(stations)
(1, 1)
>>>
>>> def teleseismic_p(station: Station, event: Event) -> bool:
... return haversine(event, station) <= 95.0
>>> entries = build_entries(stations, strong, teleseismic_p)
>>> project_from_catalogue = PysmoProject(entries=entries)
>>> [type(e).__name__ for e in project_from_catalogue.events]
['QuakeML']
>>> [type(s).__name__ for s in project_from_catalogue.stations]
['StationXML']
>>>
entries grows later without rebuilding, via a plain extend, since the
in-memory cache is keyed by entry content, not list position:
>>> project_from_catalogue.entries.extend(
... build_entries(stations, strong, teleseismic_p)
... )
>>> len(project_from_catalogue.entries)
2
>>>
Customising the pipeline
Fetch window
A window not tied to an event is set explicitly on the entry. The window
resolver is then not used:
>>> fixed_window_project = PysmoProject(
... entries=[
... ProjectEntry(
... station=station_anmo,
... starttime="2010-02-27T05:00:00Z",
... endtime="2010-02-27T06:00:00Z",
... )
... ],
... )
>>> fixed_window_project.events
[]
>>> fixed_window_project.events_for(station_anmo)
[None]
>>>
For windows derived from an event, the settings of PhaseWindow select the
phase, the span around its predicted arrival, and the travel-time model used
for the prediction. This example predicts arrivals with the ak135 model
instead of the default iasp91:
>>> from functools import partial
>>> from pysmo.tools.project import PhaseWindow
>>> from pysmo.tools.traveltime import travel_times
>>>
>>> project_ak135 = PysmoProject(
... entries=[entry],
... window=PhaseWindow(travel_time_backend=partial(travel_times, model="ak135")),
... )
>>> arrivals = project_ak135.window.travel_time_backend(
... depth=event_maule.depth, distance=60.0, phases=["P"]
... )
>>> round(arrivals["P"].total_seconds(), 1)
604.7
>>>
Caching downloads
A FetchCache as fetch_seismogram stores
each downloaded waveform on disk, so a station/window already fetched once
is read back locally on a later run, rather than re-fetched. Here it wraps
the same miniSEED download the default uses:
>>> from pysmo import Seismogram
>>> from pysmo.classes import MSeed
>>> from pysmo.tools.cache import FetchCache
>>> from pysmo.tools.web import fetch_mseed
>>>
>>> def parse_mseed(raw: bytes) -> Seismogram:
... return MSeed.from_bytes(raw)
...
>>> waveform_cache = FetchCache(
... path="waveform_cache.sqlite3", fetch_raw=fetch_mseed, parse=parse_mseed
... )
>>> download_cached_project = PysmoProject(
... entries=[entry], fetch_seismogram=waveform_cache
... )
>>> one = download_cached_project.seismogram(station_anmo, event_maule) # miss: fetched and stored
>>> download_cached_project.clear_cache()
>>> one_again = download_cached_project.seismogram(station_anmo, event_maule) # hit: read from disk
>>>
Seismogram transform
This example prepares the data for ICCS, which
expects seismograms of type
MiniIccsSeismogram (or another
implementation of the IccsSeismogram type) with the instrument response
already removed. The seismogram_transform removes the response, then
converts the result into a MiniIccsSeismogram, using context.reference
(the predicted arrival) as the initial pick. It's a callable attrs class
rather than a plain function so pre_filt is configurable per instance:
>>> from attrs import define
>>> from pysmo import Seismogram
>>> from pysmo.functions import clone_to_mini
>>> from pysmo.tools.iccs import ICCS, MiniIccsSeismogram
>>> from pysmo.tools.project import FetchContext
>>> from pysmo.tools.signal import remove_response
>>>
>>> @define(kw_only=True)
... class ToMiniIccsSeismogramWithResponseRemoved:
... pre_filt: tuple[float, float, float, float]
...
... def __call__(
... self, seismogram: Seismogram, context: FetchContext[Station, Event]
... ) -> MiniIccsSeismogram:
... response = StationXML.fetch(
... station=context.entry.station, time=context.starttime
... ).response
... corrected = clone_to_mini(
... MiniIccsSeismogram, seismogram, update={"t0": context.reference}
... )
... remove_response(corrected, response, pre_filt=self.pre_filt)
... return corrected
...
>>> to_mini_iccs_seismogram = ToMiniIccsSeismogramWithResponseRemoved(
... # Teleseismic P on IU.ANMO's LHZ (1 Hz) channel: comfortably above
... # the instrument's own corner and below the 0.5 Hz Nyquist.
... pre_filt=(0.01, 0.02, 0.2, 0.3),
... )
>>> iccs_project = PysmoProject(
... entries=[entry],
... seismogram_transform=to_mini_iccs_seismogram,
... )
>>>
Fetching a seismogram now downloads the waveform with the default
fetch_seismogram, and the instrument response with the transform's own
fetch; the result goes straight into ICCS:
>>> one = iccs_project.seismogram(station_anmo, event_maule)
>>> isinstance(one, MiniIccsSeismogram)
True
>>> iccs = ICCS(seismograms=iccs_project.seismograms_for(event_maule))
>>> len(iccs.seismograms)
1
>>>
Caching transformed seismograms
A TransformCache wrapping
seismogram_transform stores the transformed seismogram on disk. On a hit,
the transform is not run at all, so any processing and any fetches the
transform makes itself are skipped. The waveform is still fetched by
fetch_seismogram. Here it wraps a transform that detrends the data:
>>> from pysmo import MiniSeismogram, Seismogram
>>> from pysmo.functions import clone_to_mini, detrend
>>> from pysmo.tools.project import FetchContext, TransformCache
>>>
>>> def detrended(seismogram: Seismogram, context: FetchContext) -> MiniSeismogram:
... mini = clone_to_mini(MiniSeismogram, seismogram)
... detrend(mini)
... return mini
...
>>> transform_cache = TransformCache(path="transform_cache.sqlite3", transform=detrended)
>>> transform_cached_project = PysmoProject(
... entries=[entry], seismogram_transform=transform_cache
... )
>>> one = transform_cached_project.seismogram(station_anmo, event_maule) # miss: transformed and stored
>>> transform_cached_project.clear_cache()
>>> one_again = transform_cached_project.seismogram(station_anmo, event_maule) # hit: read from disk
>>> isinstance(one_again, MiniSeismogram)
True
>>>
Saving project state
The state of a project is saved with pickle. It consists of the
entries (including their checksums), which window, fetch_seismogram,
and seismogram_transform are used along with their configuration, and an
optional name that labels the project. Neither waveform data nor the
in-memory cache are saved. Nor is the code behind the callables: loading a
saved project requires the same code to be importable.
window, fetch_seismogram, and seismogram_transform must each be a
top-level function in an importable module, a functools.partial of
one, or an instance of a callable attrs class with only picklable fields;
not a lambda or closure. A callable that needs its own configuration (e.g.
filter corner frequencies) should be an attrs class. Its fields are saved with it, and they are what
resolution_context_digest uses to fingerprint window and
seismogram_transform (see "Identifying entries and changes" below). PhaseWindow is
one such class.
Unpickling runs arbitrary code, so a saved project is safe to load only when it was produced locally or comes from a trusted source. The version check on load detects a file written in an incompatible format; it is not a security check, and runs after the file has already been unpickled. Sharing a project with someone else therefore means sharing the Python code that builds it, not the pickle file.
Identifying entries and changes
Entries, project settings, and fetched waveforms each have an identifying string. These allow a seismogram to be referred to outside the project, and changes to the project or the archive data to be detected:
entry.identityidentifies an entry by its station, event, and explicit window. It is computed without fetching anything. Passing it toproject.get(identity)fetches and transforms that entry, also on a project whose entries have never been fetched.project.resolution_context_digestidentifies the settings that decide what a fetch returns:windowandseismogram_transform. It changes when either of them does, before anything is fetched. Reassigningfetch_seismogramdoes not change it.entry.checksumidentifies the waveform fetched for an entry, and only exists after the first fetch. A later fetch with a different checksum means the archive data have changed (see stage 2).
An entry built from the same station and event has the same identity, and
no checksum until it is fetched. Changing the window resolver changes the
digest:
>>> from pysmo.tools.project import PhaseWindow
>>>
>>> same_entry = ProjectEntry(station=station_anmo, event=event_maule)
>>> same_entry.identity == entry.identity
True
>>> same_entry.identity[:3]
'v1:'
>>> same_entry.checksum is None
True
>>>
>>> identified_project = PysmoProject(entries=[same_entry])
>>> digest = identified_project.resolution_context_digest
>>> identified_project.window = PhaseWindow(phase="S")
>>> identified_project.resolution_context_digest == digest
False
>>>
-
API reference
toolsprojectPysmoProjectseismogram_transform
Type Aliases:
| Name | Description |
|---|---|
SeismogramFetcher |
Download a seismogram for a station and absolute time window. |
SeismogramTransform |
Convert a freshly downloaded seismogram into the project's target type. |
WindowResolver |
Resolve an entry's absolute fetch window. |
Classes:
| Name | Description |
|---|---|
FetchContext |
Context passed to |
PhaseWindow |
Resolve a fetch window from an entry's event and a predicted phase arrival. |
ProjectEntry |
One station/event selection within a |
PysmoProject |
Declares station/event data to fetch on demand and transform into |
TransformCache |
Caches a |
UnknownEntryIdentity |
Raised when an entry with the requested identity is not found in the project. |
WindowResult |
The absolute fetch window resolved for one entry. |
Functions:
| Name | Description |
|---|---|
build_entries |
Build project entries from a filtered cross product of stations and events. |
callable_identity |
A stable, picklable identity string for a callable. |
entry_identity |
The entry's stable identity, computed from its natural key without I/O. |
entry_identity_components |
The normalised natural key of an entry as a nested dict, before hashing. |
resolution_context_digest |
Digest over the project parameters that determine fetched content. |
SeismogramFetcher
SeismogramFetcher = Callable[
[Station, Timestamp, Timestamp], Seismogram
]
Download a seismogram for a station and absolute time window.
Called with a Station and the resolved
starttime/endtime, and returns a Seismogram.
"Always fresh" by contract: PysmoProject
keeps its own in-memory cache, so a fetcher normally hits the network every
time rather than consulting a cache of its own. A
FetchCache can take its place for a
reproducible on-disk cache instead. Must be picklable: a top-level function,
or an attrs instance with only picklable fields; not a lambda or closure.
SeismogramTransform
SeismogramTransform = Callable[
[Seismogram, FetchContext[TStation, TEvent]],
TSeismogram,
]
Convert a freshly downloaded seismogram into the project's target type.
Called with the downloaded Seismogram and a
FetchContext carrying the originating
entry and this fetch's resolved window. The one place ordinary data
preparation (response removal, detrending, resampling) belongs, and free to
issue its own additional fetches (e.g. instrument response metadata via
StationXML.fetch). Must be picklable: a
top-level function, or an attrs instance with only picklable fields; not a
lambda or closure. Wrapping it in a
TransformCache caches its output
(and those additional fetches) on disk.
WindowResolver
WindowResolver = Callable[
[ProjectEntry[TStation, TEvent]], WindowResult
]
Resolve an entry's absolute fetch window.
Called with a single ProjectEntry and
returns a WindowResult. Its
reference is the timestamp the window is placed around, if there is one,
and is passed to seismogram_transform via
FetchContext. Raises ValueError when
no window can be resolved (no predicted arrival for the station/event
geometry, or a required event missing).
Only ever called for entries without an explicit starttime/endtime
pair: PysmoProject resolves that case
itself before consulting the resolver, so a custom resolver never has to
reimplement it. PhaseWindow is the
default. Must be picklable: a top-level function, or an attrs instance with
only picklable fields; not a lambda or closure. The same applies to
fetch_seismogram and seismogram_transform.
PysmoProject caches on
entry.identity, which
quantises event coordinates (~11 m) and depth (100 m); a resolver that
returns materially different windows for entries closer than that shares one
cache slot between them. The default PhaseWindow is unaffected: the
sub-quantum change in a teleseismic arrival time is far below one sample.
FetchContext
Context passed to seismogram_transform with the downloaded seismogram.
Bundles the originating ProjectEntry
with what this specific fetch resolved but that doesn't belong on
ProjectEntry itself. Recomputed fresh on every fetch, never persisted
(unlike entry.checksum, which is deliberately pinned).
Note the deliberate naming overlap with entry.starttime/entry.endtime:
those are the entry's possibly-None explicit override (see
ProjectEntry), while
starttime/endtime here are always-populated and reflect the window
that was actually used: identical to the entry's own when an explicit
override was given, resolved by the project's window otherwise. A
transform wanting "the window this fetch actually covered" should read
context.starttime/context.endtime, not
context.entry.starttime/context.entry.endtime.
-
API reference
toolsprojectTransformCache__call__
Attributes:
| Name | Type | Description |
|---|---|---|
endtime |
Timestamp
|
Absolute end of the window actually used for this fetch. |
entry |
ProjectEntry[TStation, TEvent]
|
The entry this seismogram was fetched for. |
reference |
Timestamp | None
|
Timestamp the window was placed around (a predicted phase arrival for |
starttime |
Timestamp
|
Absolute start of the window actually used for this fetch. |
Source code in src/pysmo/tools/project/_types.py
endtime
instance-attribute
endtime: Timestamp
Absolute end of the window actually used for this fetch.
entry
instance-attribute
entry: ProjectEntry[TStation, TEvent]
The entry this seismogram was fetched for.
reference
instance-attribute
reference: Timestamp | None
Timestamp the window was placed around (a predicted phase arrival for
the default window), or None if entry.starttime/entry.endtime
were used directly.
starttime
instance-attribute
starttime: Timestamp
Absolute start of the window actually used for this fetch.
PhaseWindow
Resolve a fetch window from an entry's event and a predicted phase arrival.
The default WindowResolver for
PysmoProject: predicts the phase
arrival for the station/event geometry with travel_time_backend, then
returns the window [arrival + pre_pick, arrival + post_pick].
Frozen and picklable by value (given a picklable travel_time_backend),
so it travels with a pickled PysmoProject.
-
API reference
tools
-
API reference
toolsprojectPysmoProjectwindow
Methods:
| Name | Description |
|---|---|
__call__ |
Resolve the window for |
Attributes:
| Name | Type | Description |
|---|---|---|
phase |
str
|
Seismic phase the window is placed around. |
post_pick |
PositiveTimedelta
|
Offset from the predicted arrival to the window end. Must be positive. |
pre_pick |
NonPositiveTimedelta
|
Offset from the predicted arrival to the window start; zero or negative. |
travel_time_backend |
TravelTimeBackend
|
Predicts the phase arrival the window is built around. |
Source code in src/pysmo/tools/project/_phasewindow.py
phase
class-attribute
instance-attribute
Seismic phase the window is placed around.
With the default travel_time_backend this must be one of the phases in
Phase; any other name raises when a
window is resolved. A custom backend may accept a wider set.
post_pick
class-attribute
instance-attribute
post_pick: PositiveTimedelta = field(
default=pd.Timedelta(minutes=8),
converter=to_timedelta,
validator=[
validators.instance_of(pd.Timedelta),
validators.gt(pd.Timedelta(0)),
],
)
Offset from the predicted arrival to the window end. Must be positive.
pre_pick
class-attribute
instance-attribute
pre_pick: NonPositiveTimedelta = field(
default=pd.Timedelta(minutes=-2),
converter=to_timedelta,
validator=[
validators.instance_of(pd.Timedelta),
validators.le(pd.Timedelta(0)),
],
)
Offset from the predicted arrival to the window start; zero or negative.
travel_time_backend
class-attribute
instance-attribute
travel_time_backend: TravelTimeBackend = field(
default=builtin_backend
)
Predicts the phase arrival the window is built around.
Defaults to pysmo's built-in solver,
travel_times. Any callable of
the same shape
(TravelTimeBackend) can
take its place, for another velocity model, a phase the built-in solver
does not cover, or arrival times from an external source. Must be
picklable: a top-level function, a functools.partial of one, or an
attrs instance with only picklable fields; not a lambda or closure.
__call__
__call__(entry: ProjectEntry[TS, TE]) -> WindowResult
Resolve the window for entry.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/pysmo/tools/project/_phasewindow.py
ProjectEntry
One station/event selection within a PysmoProject.
Pairs a station with either an event (for a phase-arrival-relative
window, resolved at fetch time) or an explicit absolute time window, or
both; an explicit window always takes precedence over one derived from
event. See
PysmoProject for how the window is
actually resolved.
At least one of (event, an explicit starttime/endtime pair) is
required; a lone starttime or endtime, or a starttime at or after
endtime, raises ValueError at construction.
Generic over the station and event types it was built with, so a
PysmoProject built from a list of
entries keeps those concrete types (e.g. project.events comes back as
list[QuakeML], not list[Event]). An event-less entry leaves TEvent
at its default, Event. A list mixing event-bearing and
event-less entries has no single inferred element type, so annotate it
(list[ProjectEntry[MyStation, MyEvent]]) or reach for
build_entries, which produces a
homogeneous list.
-
API reference
toolsprojectPhaseWindow__call__
Methods:
| Name | Description |
|---|---|
__attrs_post_init__ |
Reject a half-specified, reversed, or (event-less) absent window. |
Attributes:
| Name | Type | Description |
|---|---|---|
checksum |
str | None
|
Checksum of the fetched seismogram, set on first fetch; |
endtime |
Timestamp | None
|
Explicit end of the fetch window (UTC). |
event |
TEvent | None
|
Event for deriving a phase-arrival-relative window (if no explicit times). |
identity |
str
|
Stable identity string for this entry, computed without fetching. |
identity_components |
dict[str, Any]
|
This entry's normalised natural key as a nested dict, before hashing. |
starttime |
Timestamp | None
|
Explicit start of the fetch window (UTC). |
station |
TStation
|
Station to fetch waveform data for. |
Source code in src/pysmo/tools/project/_entry.py
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 | |
checksum
class-attribute
instance-attribute
Checksum of the fetched seismogram, set on first fetch; None until then.
A mismatch on a later fetch means the underlying archive data changed
since this entry was first fetched; see
PysmoProject.on_checksum_mismatch
for how that is reported. Deliberately mutated by
PysmoProject as a side effect of
fetching, so it is captured the next time the containing project is
pickled; this is what makes it a durable reproducibility pin rather
than a one-session-only check.
Because this field is mutated in place, a ProjectEntry shared across
two different PysmoProject instances (e.g. reused deliberately in an
iterative workflow, or accidentally via a shared entries list) has its
checksum set/checked by whichever project fetches it first; the
entry doesn't belong to one project. Sharing entries across projects is
fine; sharing them without being aware their checksum state is joint,
not per-project, is the surprise to avoid.
endtime
class-attribute
instance-attribute
endtime: Timestamp | None = field(
default=None,
converter=converters.optional(to_utc_timestamp),
on_setattr=setters.convert,
)
Explicit end of the fetch window (UTC).
Overrides event when set together with starttime.
event
class-attribute
instance-attribute
Event for deriving a phase-arrival-relative window (if no explicit times).
identity
property
identity: str
Stable identity string for this entry, computed without fetching.
Derived from the natural key: 'v1:' and a sha256 hexdigest. Persisting
it and passing it to
PysmoProject.get retrieves
the entry's seismogram later.
Examples:
>>> import pandas as pd
>>> from pysmo import MiniEvent, MiniStation
>>> from pysmo.tools.project import ProjectEntry
>>> station = MiniStation(
... name="ANMO",
... network="IU",
... location="00",
... channel="BHZ",
... latitude=34.9459,
... longitude=-106.4571,
... )
>>> event = MiniEvent(
... latitude=-36.122,
... longitude=-72.898,
... depth=22900.0,
... time=pd.Timestamp("2010-02-27T06:34:11.53Z"),
... )
>>> entry = ProjectEntry(station=station, event=event)
>>> entry.identity.startswith("v1:")
True
>>> len(entry.identity)
67
identity_components
property
This entry's normalised natural key as a nested dict, before hashing.
Examples:
>>> import pandas as pd
>>> from pysmo import MiniEvent, MiniStation
>>> from pysmo.tools.project import ProjectEntry
>>> station = MiniStation(
... name="ANMO",
... network="IU",
... location="00",
... channel="BHZ",
... latitude=34.9459,
... longitude=-106.4571,
... )
>>> event = MiniEvent(
... latitude=-36.122,
... longitude=-72.898,
... depth=22900.0,
... time=pd.Timestamp("2010-02-27T06:34:11.53Z"),
... )
>>> entry = ProjectEntry(station=station, event=event)
>>> components = entry.identity_components
>>> components["schema"]
'v1'
>>> components["station"]["name"]
'ANMO'
starttime
class-attribute
instance-attribute
starttime: Timestamp | None = field(
default=None,
converter=converters.optional(to_utc_timestamp),
on_setattr=setters.convert,
)
Explicit start of the fetch window (UTC).
Overrides event when set together with endtime.
__attrs_post_init__
Reject a half-specified, reversed, or (event-less) absent window.
Source code in src/pysmo/tools/project/_entry.py
PysmoProject
Declares station/event data to fetch on demand and transform into TSeismogram.
A PysmoProject holds a flat list of
ProjectEntry objects plus three
pluggable callables: window resolves each entry's fetch window,
fetch_seismogram downloads the trace, and seismogram_transform turns
it into the caller's target type TSeismogram. No waveform data are
stored on the instance between calls beyond an in-memory cache of
already-fetched-and-transformed results.
An optional name can label the project for identification by tools
that hold more than one project. It is free-text and carries no
semantics: it is not a key, does not affect cache invalidation, and is
not part of resolution_context_digest or any entry identity.
Generic over the station and event types of its entries (matching
ProjectEntry's parameter order)
and the return type of seismogram_transform, all three inferred at
construction: TStation / TEvent from entries (build them with
build_entries from a list of, say,
StationXML and QuakeML, and project.stations / project.events
come back as list[StationXML] / list[QuakeML]), TSeismogram from
seismogram_transform's return type, defaulting to
MiniSeismogram when the default transform is
used.
See the module documentation for a worked example.
Persistence
A PysmoProject travels as a pickle. The in-memory cache and lock
are dropped during pickling and reconstructed on unpickling. An
optional name is preserved across pickles; unpickling a project
serialised without a name defaults it to None.
Unpickling executes code, so a project file is safe to load only when its origin is known and trusted (see the module documentation). The format-version check on load reports an incompatible pickle; it is not a security boundary and runs after unpickling. There is no cross-version migration: a pickle from an earlier state format must be rebuilt from its source.
Thread-safety
The in-memory fetch cache is safe to touch from multiple threads
calling seismogram,
seismograms_for,
or fetch_all on the
same instance concurrently. This does not parallelise fetching
itself, though: fetch_seismogram is called outside the lock, so
two threads racing the same not-yet-cached entry both still fetch
before one result wins and is cached.
Reassigning window (or any other cache-affecting field) on one
thread while another is mid-fetch is also safe: the in-flight fetch
still returns a result, it just isn't cached (the next call
recomputes it with the current parameters).
Methods:
| Name | Description |
|---|---|
__getstate__ |
Drop the fetch cache and lock, neither of which can survive pickling. |
__setstate__ |
Restore state without firing |
clear_cache |
Clear the in-memory fetch cache. |
events_for |
Events available for one station, in first-seen order. |
fetch_all |
Fetch every entry in the project. |
get |
Fetch (or return from cache) the result for an entry by its identity. |
seismogram |
Fetch (or return from cache) the result for one station/event combination. |
seismograms_for |
All seismograms for one event, e.g. ready for |
stations_for |
Stations available for one event, in first-seen order. |
Attributes:
| Name | Type | Description |
|---|---|---|
entries |
list[ProjectEntry[TStation, TEvent]]
|
Station/event/window selections making up this project. |
events |
list[TEvent]
|
Distinct events across all entries, excluding event-less entries. |
fetch_seismogram |
SeismogramFetcher
|
Download a seismogram for a station and absolute time window. |
name |
str | None
|
Optional free-text label for this project. |
on_checksum_mismatch |
Literal['warn', 'raise', 'ignore']
|
Behaviour when a fetched seismogram's checksum no longer matches the |
resolution_context_digest |
str
|
Digest over the project parameters that determine fetched content. |
seismogram_transform |
SeismogramTransform[TStation, TEvent, TSeismogram]
|
Convert a freshly downloaded seismogram into the target type |
stations |
list[TStation]
|
Distinct stations across all entries, in first-seen order. |
window |
WindowResolver[TStation, TEvent]
|
Resolve an entry's fetch window when it carries no explicit one. |
Source code in src/pysmo/tools/project/_project.py
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 575 576 577 578 579 580 581 | |
entries
class-attribute
instance-attribute
entries: list[ProjectEntry[TStation, TEvent]] = field(
factory=list,
on_setattr=setters.pipe(
setters.convert, _on_setattr_clear_cache
),
)
Station/event/window selections making up this project.
Build them with
build_entries; grow the project
later with project.entries.extend(build_entries(...)) (a plain
in-place mutation; call
clear_cache afterwards
only to free memory, never for correctness, since the fetch cache is
keyed by entry content).
-
API reference
toolsprojectPysmoProjectclear_cache
events
property
events: list[TEvent]
Distinct events across all entries, excluding event-less entries.
In first-seen order; compares with ==, same caveat as stations.
fetch_seismogram
class-attribute
instance-attribute
fetch_seismogram: SeismogramFetcher = field(
default=_default_fetch_seismogram,
on_setattr=setters.pipe(
setters.convert, _on_setattr_clear_cache
),
)
Download a seismogram for a station and absolute time window.
Any SeismogramFetcher (see
there for the call contract). Defaults to a private helper wrapping
MSeed.fetch, which goes to the network on
every call.
Data in a live archive can change between fetches. A
FetchCache stores each fetched waveform
on disk, so later sessions work with the same data, as long as its
max_bytes stays at the default (unlimited). A finite max_bytes evicts
old waveforms, which are then fetched again. Fetches made by
seismogram_transform itself are not covered; see
TransformCache for those.
-
API reference
toolsprojectPysmoProjectclear_cache
name
class-attribute
instance-attribute
name: str | None = field(
default=None,
validator=validators.optional(
validators.instance_of(str)
),
)
Optional free-text label for this project.
Useful for identification by downstream tools that hold multiple
projects. This is purely a label, not a key: no uniqueness is enforced,
renaming does not invalidate the fetch cache, and it is not part of
resolution_context_digest
or any entry identity.
on_checksum_mismatch
class-attribute
instance-attribute
on_checksum_mismatch: Literal["warn", "raise", "ignore"] = (
field(
default="warn",
validator=validators.in_(
("warn", "raise", "ignore")
),
)
)
Behaviour when a fetched seismogram's checksum no longer matches the
one recorded on entry.checksum from its first fetch.
"warn" (default) emits a UserWarning and still returns the new data;
"raise" raises ValueError instead of returning anything, for a
pipeline that should hard-stop on detected drift; "ignore" returns the
new data with no signal at all. In every case entry.checksum keeps the
value from the first fetch; it is never overwritten by a mismatching
value, so a mismatch is reported (or not) consistently on every
subsequent fetch, not just the first time it's noticed.
Deliberately not part of cache invalidation: changing this policy only affects how a future mismatch is handled, it doesn't change what data was fetched or would be re-fetched, so nothing about previously cached results becomes stale when it changes.
-
API reference
toolsprojectProjectEntrychecksum
resolution_context_digest
property
resolution_context_digest: str
Digest over the project parameters that determine fetched content.
Covers window and seismogram_transform. Reassigning
fetch_seismogram (e.g. to an on-disk fetch cache) leaves the
digest unchanged.
Examples:
>>> from pysmo.tools.project import PysmoProject
>>> project = PysmoProject()
>>> project.resolution_context_digest.startswith("rc2:")
True
>>> len(project.resolution_context_digest)
68
seismogram_transform
class-attribute
instance-attribute
seismogram_transform: SeismogramTransform[
TStation, TEvent, TSeismogram
] = field(
default=_seismogram_to_mini_seismogram,
on_setattr=setters.pipe(
setters.convert, _on_setattr_clear_cache
),
)
Convert a freshly downloaded seismogram into the target type TSeismogram.
Any SeismogramTransform (see
there for the call contract). Defaults to returning the raw trace as a
MiniSeismogram, with no processing: a custom
transform is where response removal, detrending and resampling belong,
and it may issue its own additional fetches, as the
module documentation's example does for instrument
response metadata. A callable attrs class with only picklable fields is
the way to give the transform its own configuration.
-
API reference
toolsprojectPysmoProjectclear_cache
stations
property
stations: list[TStation]
Distinct stations across all entries, in first-seen order.
A plain @property, not @cached_property: recomputed on each
access, same as
ICCS.cc_seismograms's
precedent for a no-arg derived list view in this codebase. Compares
with == (attrs-generated equality, not identity or hashing;
Station is not hashable).
window
class-attribute
instance-attribute
window: WindowResolver[TStation, TEvent] = field(
default=PhaseWindow(),
on_setattr=setters.pipe(
setters.convert, _on_setattr_clear_cache
),
)
Resolve an entry's fetch window when it carries no explicit one.
Any WindowResolver (see there for
the call contract). Defaults to
PhaseWindow, which places the window
around a predicted phase arrival. An entry with an explicit
starttime/endtime bypasses this entirely, so a custom resolver only
ever handles the event-derived case.
-
API reference
toolsprojectPysmoProjectclear_cache
__getstate__
Drop the fetch cache and lock, neither of which can survive pickling.
Source code in src/pysmo/tools/project/_project.py
__setstate__
Restore state without firing on_setattr hooks, then make a fresh lock.
Source code in src/pysmo/tools/project/_project.py
clear_cache
Clear the in-memory fetch cache.
Cleared automatically whenever
entries,
window,
seismogram_transform,
or
fetch_seismogram
is reassigned.
Call this manually after any in-place mutation of
entries (e.g. append,
remove, or index assignment), which isn't observable by
on_setattr and therefore doesn't clear the cache automatically.
The same applies to mutating a configuration field inside window,
seismogram_transform, or fetch_seismogram rather than reassigning
the whole callable; a frozen=True attrs callable (as
PhaseWindow is) rules that out.
-
API reference
toolsprojectPysmoProjectentries
Source code in src/pysmo/tools/project/_project.py
events_for
events_for(station: TStation) -> list[TEvent | None]
Events available for one station, in first-seen order.
None appears in the result if station has an event-less entry; an
event-less selection is a first-class member of this list, not a
special case to check for separately.
Source code in src/pysmo/tools/project/_project.py
fetch_all
fetch_all() -> list[TSeismogram]
Fetch every entry in the project.
With the default, always-fresh fetch_seismogram, this just warms
_cache for the session. With a cache-backed fetch_seismogram
(e.g. FetchCache), this is what
actually populates the on-disk cache: a single, explicit "get
everything this project needs onto disk" call, rather
than relying on incidental use of seismogram/seismograms_for to
cover every entry eventually.
Returns:
| Type | Description |
|---|---|
list[TSeismogram]
|
One transformed result per entry, in |
-
API reference
toolsprojectPysmoProject
Source code in src/pysmo/tools/project/_project.py
get
Fetch (or return from cache) the result for an entry by its identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity
|
str
|
An |
required |
Returns:
| Type | Description |
|---|---|
TSeismogram
|
The transformed result for the matching entry. |
Raises:
| Type | Description |
|---|---|
UnknownEntryIdentity
|
If no entry matches this identity. |
ValueError
|
If more than one entry matches: an authoring mistake, surfaced rather than silently resolved by picking one. |
Examples:
>>> import pandas as pd
>>> from pysmo import MiniEvent, MiniSeismogram, MiniStation, Station
>>> from pysmo.tools.project import ProjectEntry, PysmoProject
>>> def fake_fetch(station: Station, t0: pd.Timestamp, t1: pd.Timestamp):
... return MiniSeismogram(
... begin_time=t0, delta=pd.Timedelta(seconds=1), data=[1.0, 2.0]
... )
>>> station = MiniStation(
... name="ANMO",
... network="IU",
... location="00",
... channel="BHZ",
... latitude=34.9459,
... longitude=-106.4571,
... )
>>> entry = ProjectEntry(
... station=station,
... starttime=pd.Timestamp("2020-01-01T00:00:00Z"),
... endtime=pd.Timestamp("2020-01-01T00:10:00Z"),
... )
>>> project = PysmoProject(entries=[entry], fetch_seismogram=fake_fetch)
>>> seis = project.get(entry.identity)
>>> len(seis.data)
2
Source code in src/pysmo/tools/project/_project.py
seismogram
seismogram(
station: TStation,
event: TEvent | None = None,
*,
_stacklevel: int = 3
) -> TSeismogram
Fetch (or return from cache) the result for one station/event combination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station
|
TStation
|
Station to fetch. |
required |
event
|
TEvent | None
|
Event to fetch for, or |
None
|
Returns:
| Type | Description |
|---|---|
TSeismogram
|
The transformed result for the matching entry. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no entry matches this station/event combination. |
ValueError
|
If more than one entry matches: an authoring mistake (e.g. the same station/event added twice with different explicit windows), surfaced rather than silently resolved by picking one. |
Source code in src/pysmo/tools/project/_project.py
seismograms_for
seismograms_for(event: TEvent) -> list[TSeismogram]
All seismograms for one event, e.g. ready for ICCS(seismograms=...).
Built from
stations_for and
seismogram, not an
independent filter over entries.
Typed to require an Event, unlike stations_for/events_for
(which both treat None as first-class), deliberately: this
method exists for the event-based bulk-fetch use case (ICCS),
which has no equivalent "all event-less entries" workflow to
support. [seismogram(s, None) for s in stations_for(None)]
already covers that case directly if it's ever needed.
-
API reference
toolsprojectPysmoProject
Source code in src/pysmo/tools/project/_project.py
stations_for
stations_for(event: TEvent | None) -> list[TStation]
Stations available for one event, in first-seen order.
Pass None for stations with an event-less entry.
-
API reference
toolsprojectPysmoProjectseismograms_for
Source code in src/pysmo/tools/project/_project.py
TransformCache
Caches a seismogram_transform's output, and its secondary fetches, on disk.
A SeismogramTransform for
PysmoProject that wraps another
transform. On a miss it runs the wrapped transform and stores its result
as a seismogram_to_json document
in a BlobCache; on a hit it reconstructs
the result from JSON without running the transform at all, which also
skips whatever additional fetches (instrument response metadata, say) the
transform issues on its own. That second effect is usually the reason to
reach for this: a FetchCache pins the
waveform but says nothing about a transform's own network calls.
The cache key folds in every part of the fetch the wrapped transform can
observe: the entry's identity, the resolved window and its reference
time, the wrapped transform's configuration
(callable_identity), and a
seismogram_checksum of the
transform's input seismogram. A change to any of them mints a new key with
no explicit purge; an evicted or drifted input drains naturally. Every
call hashes the input seismogram to build the key, a hit included.
Only value-object attrs seismograms round-trip:
MiniSeismogram,
MiniIccsSeismogram,
GeoCsvSeismogram, and any user type
whose fields are primitives, collections, nested attrs, or the three
leaf types seismogram_to_json handles. A transform returning anything
else (a
SacSeismogram live view, a type with an unhookable field) raises
TypeError at store time, naming
clone_to_mini.
Examples:
>>> import pandas as pd
>>> from pathlib import Path
>>> import tempfile
>>> from pysmo import MiniEvent, MiniSeismogram, MiniStation, Seismogram
>>> from pysmo.functions import clone_to_mini
>>> from pysmo.tools.project import FetchContext, ProjectEntry
>>> from pysmo.tools.project import TransformCache
>>>
>>> calls = []
>>> def double(seismogram: Seismogram, context: FetchContext) -> MiniSeismogram:
... calls.append(1)
... return clone_to_mini(MiniSeismogram, seismogram)
...
>>> station = MiniStation(
... name="ANMO", network="IU", location="00", channel="BHZ",
... latitude=34.9, longitude=-106.5,
... )
>>> event = MiniEvent(
... latitude=-36.1, longitude=-72.9, depth=22900.0,
... time=pd.Timestamp("2010-02-27T06:34:11Z"),
... )
>>> entry = ProjectEntry(station=station, event=event)
>>> context = FetchContext(
... entry=entry,
... starttime=pd.Timestamp("2010-02-27T06:40:00Z"),
... endtime=pd.Timestamp("2010-02-27T06:50:00Z"),
... reference=pd.Timestamp("2010-02-27T06:44:00Z"),
... )
>>> raw = MiniSeismogram(
... begin_time=pd.Timestamp("2010-02-27T06:40:00Z"),
... delta=pd.Timedelta(seconds=1), data=[1.0, 2.0, 3.0],
... )
>>>
>>> cache = TransformCache(
... path=Path(tempfile.mkdtemp()) / "transform.sqlite3", transform=double
... )
>>> first = cache(raw, context) # miss: runs the wrapped transform
>>> second = cache(raw, context) # hit: reconstructed from JSON
>>> len(calls)
1
>>> second.data.tolist()
[1.0, 2.0, 3.0]
>>>
Methods:
| Name | Description |
|---|---|
__attrs_post_init__ |
Build the inner store (which also checks |
__call__ |
Return the transformed result for this fetch, from cache when possible. |
__getstate__ |
Drop the inner store; it is rebuilt from the plain fields on unpickling. |
__setstate__ |
Restore the plain fields, then rebuild the inner store. |
close |
Close the inner store's connection, if one is open. |
Attributes:
| Name | Type | Description |
|---|---|---|
max_bytes |
PositiveInt | None
|
Maximum total size of compressed data stored, in bytes; |
path |
Path
|
Location of the SQLite database file. |
transform |
SeismogramTransform[TStation, TEvent, TSeismogram]
|
The wrapped transform, run only on a cache miss. |
trusted_modules |
tuple[str, ...]
|
Top-level packages a cached result's type may be imported from when it |
verify |
bool
|
Re-decode each freshly stored result and compare it to the transform's |
wal |
bool
|
Enable WAL mode (local disk only; see |
Source code in src/pysmo/tools/project/_transformcache.py
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 | |
max_bytes
class-attribute
instance-attribute
max_bytes: PositiveInt | None = field(
default=None,
validator=validators.optional(validators.gt(0)),
metadata={"identity": False},
)
Maximum total size of compressed data stored, in bytes; None for
unlimited. See BlobCache.max_bytes.
path
class-attribute
instance-attribute
Location of the SQLite database file.
The file itself is created on first use; its parent directory must
already exist, checked at construction time. Not part of the wrapper's
callable_identity: moving the
cache file does not change what a call returns.
transform
instance-attribute
transform: SeismogramTransform[
TStation, TEvent, TSeismogram
]
The wrapped transform, run only on a cache miss.
Must be picklable: a top-level function, or an attrs instance with only
picklable fields; not a lambda or closure. PysmoProject places the same
constraint on seismogram_transform itself.
trusted_modules
class-attribute
instance-attribute
Top-level packages a cached result's type may be imported from when it
is rebuilt on a hit. The pysmo value objects
(MiniSeismogram and friends) are covered by the
default; widen it only if the wrapped transform returns a value object
defined outside pysmo, in the caller's own package.
verify
class-attribute
instance-attribute
verify: bool = True
Re-decode each freshly stored result and compare it to the transform's
output, raising TypeError on any mismatch.
Catches a round trip that silently loses information on a rich TSeismogram
(e.g. a non-primitive value in MiniIccsSeismogram.extra). Best left on
unless the transform output is known to be a plain
MiniSeismogram.
wal
class-attribute
instance-attribute
Enable WAL mode (local disk only; see
BlobCache).
__attrs_post_init__
__call__
__call__(
seismogram: Seismogram,
context: FetchContext[TStation, TEvent],
) -> TSeismogram
Return the transformed result for this fetch, from cache when possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seismogram
|
Seismogram
|
The freshly fetched trace, the wrapped transform's input. |
required |
context
|
FetchContext[TStation, TEvent]
|
The originating entry and this fetch's resolved window. |
required |
Returns:
| Type | Description |
|---|---|
TSeismogram
|
The wrapped transform's result: reconstructed from JSON on a hit, |
TSeismogram
|
freshly computed (and then stored) on a miss. |
Source code in src/pysmo/tools/project/_transformcache.py
__getstate__
Drop the inner store; it is rebuilt from the plain fields on unpickling.
__setstate__
Restore the plain fields, then rebuild the inner store.
UnknownEntryIdentity
Bases: KeyError
Raised when an entry with the requested identity is not found in the project.
Subclasses KeyError, which
PysmoProject.seismogram
also raises for an unknown station/event pair, so one except KeyError
(or except LookupError) catches both lookups.
-
API reference
toolsprojectPysmoProjectget
Source code in src/pysmo/tools/project/_identity.py
WindowResult
The absolute fetch window resolved for one entry.
Returned by a WindowResolver.
starttime must be strictly before endtime, checked at construction so
a buggy resolver fails here rather than at the remote fetch.
-
API reference
toolsprojectPhaseWindow__call__
Methods:
| Name | Description |
|---|---|
__attrs_post_init__ |
Reject a reversed or zero-length window. |
Attributes:
| Name | Type | Description |
|---|---|---|
endtime |
Timestamp
|
Absolute end of the window. |
reference |
Timestamp | None
|
Timestamp the window was placed around (a predicted phase arrival for |
starttime |
Timestamp
|
Absolute start of the window. |
Source code in src/pysmo/tools/project/_types.py
reference
instance-attribute
reference: Timestamp | None
Timestamp the window was placed around (a predicted phase arrival for
PhaseWindow), or None when the
window came from an entry's explicit starttime/endtime.
__attrs_post_init__
Reject a reversed or zero-length window.
Source code in src/pysmo/tools/project/_types.py
build_entries
build_entries(
stations: Iterable[TStation],
events: Iterable[TEvent],
predicate: (
Callable[[TStation, TEvent], bool] | None
) = None,
) -> list[ProjectEntry[TStation, TEvent]]
Build project entries from a filtered cross product of stations and events.
One ProjectEntry per (station,
event) pair for which predicate returns True, or every pair if
predicate is None. stations and events are expected to be
already narrowed to the working set; this function pairs, it does not
narrow or transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stations
|
Iterable[TStation]
|
The stations to pair, already narrowed. |
required |
events
|
Iterable[TEvent]
|
The events to pair, already narrowed. |
required |
predicate
|
Callable[[TStation, TEvent], bool] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
list[ProjectEntry[TStation, TEvent]]
|
One |
Source code in src/pysmo/tools/project/_entry.py
callable_identity
A stable, picklable identity string for a callable.
Supports:
- Top-level functions in importable modules.
functools.partialwrapping a supported callable.attrsinstances with picklable fields. A field carryingmetadata={"identity": False}is left out of the digest, for configuration that does not change what the callable returns (a wrapping cache's storage path, for instance).
Raises TypeError for closures, lambdas, bound methods, classes, and other
objects.
-
API reference
toolsprojectTransformCachepath
Source code in src/pysmo/tools/project/_identity.py
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 | |
entry_identity
entry_identity(entry: _IdentityEntry) -> str
The entry's stable identity, computed from its natural key without I/O.
The string is 'v1:' followed by a sha256 hexdigest.
Source code in src/pysmo/tools/project/_identity.py
entry_identity_components
The normalised natural key of an entry as a nested dict, before hashing.
Top-level keys are schema, station, event, and window; event and
window are None when absent.
Source code in src/pysmo/tools/project/_identity.py
resolution_context_digest
resolution_context_digest(project: _IdentityProject) -> str
Digest over the project parameters that determine fetched content.
Covers window and seismogram_transform. Reassigning fetch_seismogram
(e.g. to an offline archive cache) leaves the digest unchanged.