pysmo.tools.cache
On-disk waveform caching: fetch a station and window once, replay it later.
FetchCache is the main entry point. Built
from a fetch function and a parser, it behaves as a callable
(station, starttime, endtime) -> Seismogram. The first call for a given
station and window downloads and stores the raw response; later calls for
the same station and window read it back from the file, with no network
access. Its call signature is
SeismogramFetcher, so it can also
be a PysmoProject's fetch_seismogram.
BlobCache is the storage layer underneath:
a keyed store of byte blobs in a single SQLite file, compressed, with an
optional size cap. FetchCache uses it for raw fetch responses;
TransformCache uses it for
transformed seismograms. Use it directly to cache anything else that is
costly to produce and reduces to bytes.
Portable on disk
A cache file is an ordinary SQLite database: one table, each row a zlib-compressed entry. A SQLite client and zlib are all it takes to read the contents back, in any language.
Examples:
Fetch a window of SAC data once, then replay it from disk on the next
run. FetchCache is paired here with
fetch_sac and
SAC.from_zip.
>>> import pandas as pd
>>> from pysmo import MiniStation, Seismogram
>>> from pysmo.classes import SAC
>>> from pysmo.tools.cache import FetchCache
>>> from pysmo.tools.web import fetch_sac
>>>
>>> def parse_sac_seismogram_zip(raw: bytes) -> Seismogram:
... return SAC.from_zip(raw).seismogram
...
>>> station = MiniStation(
... name="ANMO", network="IU", location="00", channel="LHZ",
... latitude=34.945981, longitude=-106.457133,
... )
>>> starttime = pd.Timestamp("2010-02-27T06:44:00Z")
>>> endtime = pd.Timestamp("2010-02-27T06:54:00Z")
>>>
>>> cache = FetchCache(
... path="waveform_cache.sqlite3", fetch_raw=fetch_sac, parse=parse_sac_seismogram_zip
... )
>>> seismogram = cache(station, starttime, endtime) # miss: fetches and stores
>>> seismogram_again = cache(station, starttime, endtime) # hit: no fetch
>>> seismogram_again.data.shape == seismogram.data.shape
True
>>>
Type Aliases:
| Name | Description |
|---|---|
RawParser |
A callable that parses raw fetch bytes into a |
Classes:
| Name | Description |
|---|---|
BlobCache |
A keyed store of byte blobs in a single SQLite file. |
FetchCache |
A waveform cache: fetch a station and window once, re-parse it from a file. |
RawFetcher |
A callable that returns the raw bytes for a station and time window. |
RawParser
RawParser = Callable[[bytes], Seismogram]
A callable that parses raw fetch bytes into a Seismogram.
For example SAC.from_zip or
MSeed.from_bytes. Must match the format
the RawFetcher it is paired with returns.
BlobCache
A keyed store of byte blobs in a single SQLite file.
get takes a string key and a
callback. On a hit it returns the stored blob; on a miss it calls the
callback, stores what it returns (compressed), and returns that. Keys and
values are arbitrary bytes; the cache interprets neither.
Pass max_bytes to cap the total stored size; once it is exceeded the
oldest entries are removed until the cache fits again.
Local disk only
The SQLite file must be on local disk and used by one process at a time. WAL mode and concurrent access over a network filesystem are unsupported and can corrupt the file.
Examples:
>>> from pathlib import Path
>>> import tempfile
>>> from pysmo.tools.cache import BlobCache
>>>
>>> tmp = Path(tempfile.mkdtemp())
>>> cache = BlobCache(path=tmp / "blobs.sqlite3", encoding_version=1)
>>> calls = []
>>> def produce() -> bytes:
... calls.append(1)
... return b"payload"
...
>>> cache.get("some-key", produce)
b'payload'
>>> cache.get("some-key", produce) # hit: produce not called again
b'payload'
>>> len(calls)
1
>>>
Methods:
| Name | Description |
|---|---|
__attrs_post_init__ |
Fail fast if |
__del__ |
Close the connection when the cache is garbage collected. |
__getstate__ |
Drop the live connection and lock for pickling. |
__setstate__ |
Restore the fields and create a fresh lock. |
close |
Close the database connection. |
get |
Return the blob stored under |
Attributes:
| Name | Type | Description |
|---|---|---|
encoding_version |
PositiveInt
|
Layout version for the file, recorded on creation and checked on open. |
max_bytes |
PositiveInt | None
|
Cap on the total compressed size of stored blobs, in bytes. |
path |
Path
|
Path to the SQLite file. |
wal |
bool
|
Enable SQLite WAL mode (local disk only). |
Source code in src/pysmo/tools/cache.py
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 | |
encoding_version
instance-attribute
encoding_version: PositiveInt
Layout version for the file, recorded on creation and checked on open.
Opening a file that was written with a different value raises
ValueError. Each cache built on BlobCache passes its own constant.
max_bytes
class-attribute
instance-attribute
max_bytes: PositiveInt | None = field(
default=None,
validator=validators.optional(validators.gt(0)),
)
Cap on the total compressed size of stored blobs, in bytes.
When a new entry pushes the total past the cap, the oldest entries are
removed until it fits again. A single entry larger than the cap is stored
and kept anyway, so it is never re-produced on every call. None (the
default) means no cap. The file on disk is somewhat larger than
max_bytes because of SQLite's own page and index overhead.
path
class-attribute
instance-attribute
Path to the SQLite file.
Created on first use; its parent directory must already exist.
__attrs_post_init__
Fail fast if path's parent directory doesn't exist.
__del__
__getstate__
__setstate__
close
Close the database connection.
Optional: the connection is also closed when the cache is garbage collected. Call this to release the handle sooner.
Source code in src/pysmo/tools/cache.py
get
Return the blob stored under key, producing and storing it on a miss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The cache key. |
required |
produce
|
Callable[[], bytes]
|
Called only on a miss. Must return |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
The blob: read from the file on a hit, from |
Source code in src/pysmo/tools/cache.py
FetchCache
A waveform cache: fetch a station and window once, re-parse it from a file.
Call it as (station, starttime, endtime) -> Seismogram. On the first
call for a given station and window it runs fetch_raw, stores the raw
response, and returns parse of it; later calls for the same station and
window read the stored bytes and return parse of those, without
fetching. parse therefore runs on every call, and the file holds the
unparsed response, which any other tool can read. For a project that
should also skip the transform on a hit, see
TransformCache.
Any format works, as long as fetch_raw and parse agree (e.g.
fetch_sac with
SAC.from_zip). While a window stays
cached it is replayed byte-for-byte; an entry evicted under a finite
max_bytes is fetched again on next access.
The call signature is
SeismogramFetcher, so an
instance also serves as a
PysmoProject's fetch_seismogram.
A database written by pysmo's earlier SqliteArchiveFetcher is read
as-is, without migration.
Methods:
| Name | Description |
|---|---|
__attrs_post_init__ |
Build the inner store (which also checks |
__call__ |
Return the |
__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 |
|---|---|---|
fetch_raw |
RawFetcher
|
Fetches the raw response for a station and time window. |
max_bytes |
PositiveInt | None
|
Cap on the total stored size in bytes; see |
parse |
RawParser
|
Parses a raw response into a |
path |
Path
|
Path to the SQLite file. |
wal |
bool
|
Enable SQLite WAL mode (local disk only). |
Source code in src/pysmo/tools/cache.py
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 | |
fetch_raw
instance-attribute
fetch_raw: RawFetcher
Fetches the raw response for a station and time window.
max_bytes
class-attribute
instance-attribute
max_bytes: PositiveInt | None = field(
default=None,
validator=validators.optional(validators.gt(0)),
)
Cap on the total stored size in bytes; see
BlobCache.max_bytes. None
(the default) means no cap, so a cached window is never evicted and
re-fetched.
parse
instance-attribute
parse: RawParser
Parses a raw response into a Seismogram. Runs on every call.
path
class-attribute
instance-attribute
Path to the SQLite file.
Created on first use; its parent directory must already exist.
__attrs_post_init__
__call__
__call__(
station: Station,
starttime: Timestamp,
endtime: Timestamp,
) -> Seismogram
Return the Seismogram for station and window, from cache when possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station
|
Station
|
Station to fetch data for. |
required |
starttime
|
Timestamp
|
Start of the requested window (UTC). |
required |
endtime
|
Timestamp
|
End of the requested window (UTC). |
required |
Returns:
| Type | Description |
|---|---|
Seismogram
|
The parsed seismogram: from the file on a hit, freshly fetched |
Seismogram
|
and stored on a miss. |
Source code in src/pysmo/tools/cache.py
__getstate__
Drop the inner store; it is rebuilt from the plain fields on unpickling.
__setstate__
RawFetcher
Bases: Protocol
A callable that returns the raw bytes for a station and time window.
Called with keyword arguments only, matching pysmo's fetch functions
(fetch_sac,
fetch_mseed,
fetch_geocsvseismogram),
which can be passed straight in as FetchCache.fetch_raw.
Methods:
| Name | Description |
|---|---|
__call__ |
Fetch raw bytes for |