Metrics API
Metrics modules calculate observed and synthetic waveform values, transform those values into residuals and scores, plan file-based metric runs, and plot metric diagnostics.
Package Entry Point
Ground-motion metric and residual calculations.
Metrics Package Overview
This package exposes metric calculation, plotting, and workflow helpers without
eagerly importing heavy waveform dependencies. Import calculation functions from
spatial_vtk.metrics for convenience, or import focused submodules such as
spatial_vtk.metrics.plot when you only need figures.
Metrics Package Examples
- Import a calculation helper only when you need it:
from spatial_vtk.metrics import compute_metrics_pair
Calculate
Amplitude summary calculations for waveform metrics.
Calculation Amplitudes Overview
This module provides small reusable amplitude calculations used by metric workflows, QC summaries, and downstream diagnostics.
Calculation Amplitudes Examples
- Compute observed/synthetic amplitude ratios:
ratios = calculate_amplitude_ratios(obs, syn, dt=0.02)
- spatial_vtk.metrics.calculate.amplitudes.calculate_amplitude_ratios(obs_data: Any, syn_data: Any, dt: float | None = None) dict[str, float]
Compute paired amplitude-ratio summaries for one waveform pair.
- Parameters:
obs_data (Any) – Observed samples or trace-like object.
syn_data (Any) – Synthetic samples or trace-like object.
dt (float | None, optional) – Optional sample spacing in seconds. This is accepted for a consistent waveform-helper API, but amplitudes do not depend on
dt.obs_data – Required function argument.
syn_data – Required function argument.
dt – Optional function argument. Defaults to
None.
- Returns:
Peak and RMS amplitudes for both traces plus observed/synthetic ratios.
- Return type:
dict[str, float]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.amplitudes.coerce_series_and_dt(series_or_trace: Any, dt: float | None = None) tuple[ndarray, float]
Convert an array-like or trace-like object to samples and sample spacing.
- Parameters:
series_or_trace (Any) – Numeric samples or an ObsPy-like trace with
dataandstats.dt (float | None, optional) – Optional sample spacing in seconds. If omitted for trace-like objects,
stats.deltaorstats.sampling_rateis used.series_or_trace – Required function argument.
dt – Optional function argument. Defaults to
None.
- Returns:
One-dimensional sample array and resolved positive sample spacing.
- Return type:
tuple[numpy.ndarray, float]
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.calculate.amplitudes.compute_paired_station_event_maxima(observed: Any, synthetic: Any, dt: float | None = None) dict[str, float]
Compute paired maxima and amplitude ratios for one waveform pair.
- Parameters:
observed (Any) – Observed waveform samples or trace-like object.
synthetic (Any) – Synthetic waveform samples or trace-like object.
dt (float | None, optional) – Optional sample spacing in seconds.
observed – Required function argument.
synthetic – Required function argument.
dt – Optional function argument. Defaults to
None.
- Returns:
Combined maxima and amplitude-ratio summary for the pair.
- Return type:
dict[str, float]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.amplitudes.compute_station_event_maxima(trace: Any, dt: float | None = None) dict[str, float]
Compute peak and RMS amplitudes for one waveform.
- Parameters:
trace (Any) – Waveform samples or trace-like object.
dt (float | None, optional) – Optional sample spacing in seconds.
trace – Required function argument.
dt – Optional function argument. Defaults to
None.
- Returns:
max_amplitudeandrms_amplitudefor the waveform.- Return type:
dict[str, float]
- Returns:
Return value produced by the function.
- Return type:
dict
Arrival-pick catalog helpers.
Raised when the default PhaseNet picker cannot be found.
- spatial_vtk.metrics.calculate.arrival_picks.find_phasenet_command(explicit_command: str | None = None) str | None
Find the configured PhaseNet command.
- Parameters:
explicit_command (str | None, optional) – Optional user-supplied command or executable path.
explicit_command – Optional function argument. Defaults to
None.
- Returns:
Command text when PhaseNet appears available; otherwise
None.- Return type:
str or None
- Returns:
Return value produced by the function.
- Return type:
str | None
- spatial_vtk.metrics.calculate.arrival_picks.load_arrival_pick_catalog(path: str | Path) DataFrame
Load one arrival-pick catalog from CSV or Parquet.
- Parameters:
path (str | pathlib.Path) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.arrival_picks.normalize_pick_catalog(df: DataFrame, *, default_method: str = 'phasenet') DataFrame
Return a pick table with the public required pick-catalog columns.
- Parameters:
df (pandas.DataFrame) – Required function argument.
default_method (str, optional) – Optional function argument. Defaults to
'phasenet'.
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.arrival_picks.require_phasenet(explicit_command: str | None = None) str
Return a PhaseNet command or raise a clear availability error.
- Parameters:
explicit_command (str | None, optional) – Optional function argument. Defaults to
None.- Returns:
Return value produced by the function.
- Return type:
str
- spatial_vtk.metrics.calculate.arrival_picks.resolve_arrival_picker(picker: str | None = None, *, phasenet_command: str | None = None, allow_catalog_only: bool = False) str
Resolve the arrival-picking backend.
- Parameters:
picker (str | None, optional) – Picker selector.
Nonedefaults to"phasenet".phasenet_command (str | None, optional) – Optional explicit PhaseNet command.
allow_catalog_only (bool, optional) – Whether
picker="catalog"is allowed for workflows that load existing picks instead of creating new picks.picker – Optional function argument. Defaults to
None.phasenet_command – Optional function argument. Defaults to
None.allow_catalog_only – Optional function argument. Defaults to
False.
- Returns:
Resolved picker command or
"catalog".- Return type:
str
- Returns:
Return value produced by the function.
- Return type:
str
- spatial_vtk.metrics.calculate.arrival_picks.write_arrival_pick_catalog(df: DataFrame, path: str | Path, *, overwrite: bool = False) Path
Write one normalized pick catalog to CSV or Parquet.
- Parameters:
df (pandas.DataFrame) – Required function argument.
path (str | pathlib.Path) – Required function argument.
overwrite (bool, optional) – Optional function argument. Defaults to
False.
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
Frequency-band configuration helpers for metric calculations.
- spatial_vtk.metrics.calculate.bands.bands_from_list(edges: Iterable[float], *, label_format: str = '{low:.3g}-{high:.3g}Hz') dict[str, tuple[float, float]]
Build adjacent frequency bands from ordered frequency edges.
- Parameters:
edges (collections.abc.Iterable) – Ordered frequency edges in Hz.
label_format (str, optional) – Format string with
lowandhighfields.edges – Required function argument.
label_format – Optional function argument. Defaults to
'{low:.3g}-{high:.3g}Hz'.
- Returns:
Mapping from generated band labels to adjacent frequency tuples.
- Return type:
dict
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.bands.bands_from_logspace(min_freq: float, max_freq: float, n_bands: int, *, label_format: str = '{low:.3g}-{high:.3g}Hz') dict[str, tuple[float, float]]
Build logarithmically spaced frequency bands.
- Parameters:
min_freq (float) – Frequency range in Hz.
max_freq (float) – Frequency range in Hz.
n_bands (int) – Number of adjacent bands to create.
label_format (str, optional) – Format string with
lowandhighfields.min_freq – Required function argument.
max_freq – Required function argument.
n_bands – Required function argument.
label_format – Optional function argument. Defaults to
'{low:.3g}-{high:.3g}Hz'.
- Returns:
Mapping from generated band labels to frequency tuples.
- Return type:
dict
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.bands.dbg(message: str) None
Print a debug message when module-level debugging is enabled.
- Parameters:
message (str) – Message to print.
message – Required function argument.
- Returns:
This function only writes to standard output when debugging is enabled.
- Return type:
None
- Returns:
Return value produced by the function.
- Return type:
None
- spatial_vtk.metrics.calculate.bands.set_bands(bands: Mapping[str, tuple[float, float]]) None
Replace the active metric passbands.
- Parameters:
bands (collections.abc.Mapping) – Mapping from band label to
(low_hz, high_hz)frequency tuple.bands – Required function argument.
- Returns:
Updates the module-level
BANDSmapping in place.- Return type:
None
- Returns:
Return value produced by the function.
- Return type:
None
- spatial_vtk.metrics.calculate.bands.set_target_fs(fs: float) None
Set the target sampling rate used by waveform helpers.
- Parameters:
fs (float) – Sampling rate in Hz.
fs – Required function argument.
- Returns:
Updates the module-level
TARGET_FSvalue.- Return type:
None
- Returns:
Return value produced by the function.
- Return type:
None
Batch wrappers around the public GOF metric kernel.
- spatial_vtk.metrics.calculate.batch.calculate_metric_pair(observed: Any, synthetic: Any, *, dt: float, metadata: dict[str, Any] | None = None, which: Iterable[str] | None = None, **kwargs) dict[str, Any]
Compute metrics for one observed/synthetic pair and attach metadata.
- Parameters:
observed (Any) – One-dimensional waveform samples.
synthetic (Any) – One-dimensional waveform samples.
dt (float) – Sample spacing in seconds.
metadata (dict[str, Any] | None, optional) – Optional metadata copied into the output row.
which (collections.abc.Iterable[str] | None, optional) – Optional metric keys to compute.
**kwargs – Forwarded to
compute_metrics_pair().observed – Required function argument.
synthetic – Required function argument.
dt – Required function argument.
metadata – Optional function argument. Defaults to
None.which – Optional function argument. Defaults to
None.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Metadata plus metric outputs.
- Return type:
dict
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.batch.calculate_metrics_for_pairs(pairs: Sequence[Any], *, which: Iterable[str] | None = None, dt: float | None = None, **kwargs) DataFrame
Compute GOF metrics for a batch of observed/synthetic pairs.
- Parameters:
pairs (collections.abc.Sequence) – Sequence of mappings with
observed,synthetic, anddtfields, or tuples shaped like(observed, synthetic, dt).which (collections.abc.Iterable[str] | None, optional) – Optional metric keys to compute.
dt (float | None, optional) – Optional fallback sample spacing in seconds.
**kwargs – Forwarded to
spatial_vtk.metrics.calculate.gof.compute_metrics_pair().pairs – Required function argument.
which – Optional function argument. Defaults to
None.dt – Optional function argument. Defaults to
None.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
One row per pair, preserving mapping metadata columns.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
Metric residual and metadata enrichment helpers.
- spatial_vtk.metrics.calculate.enrich.add_path_geometry_columns(df: DataFrame, *, event_lat_col: str = 'event_lat', event_lon_col: str = 'event_lon', station_lat_col: str = 'sta_lat', station_lon_col: str = 'sta_lon') DataFrame
Add source-station distance, azimuth, and backazimuth columns.
- Parameters:
df (pandas.DataFrame) – Table with event and station coordinates.
event_lat_col (str, optional) – Coordinate column names.
event_lon_col (str, optional) – Coordinate column names.
station_lat_col (str, optional) – Coordinate column names.
station_lon_col (str, optional) – Coordinate column names.
df – Required function argument.
event_lat_col – Optional function argument. Defaults to
'event_lat'.event_lon_col – Optional function argument. Defaults to
'event_lon'.station_lat_col – Optional function argument. Defaults to
'sta_lat'.station_lon_col – Optional function argument. Defaults to
'sta_lon'.
- Returns:
Copy with
distance_km,azimuth_deg, andbackazimuth_degwhen coordinates are available.- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.enrich.enrich_metric_table(metrics_df: DataFrame, *, events: DataFrame | str | Path | None = None, stations: DataFrame | str | Path | None = None, event_key: str = 'event_id', station_key: str = 'station', residual_column: str | None = None, score_column: str | None = None) DataFrame
Attach event and station metadata to a metric table.
- Parameters:
metrics_df (pandas.DataFrame) – Metric table in wide or long form.
events (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables or CSV paths.
stations (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables or CSV paths.
event_key (str, optional) – Join columns.
station_key (str, optional) – Join columns.
residual_column (str | None, optional) – Optional transform column to expose as canonical
residual.score_column (str | None, optional) – Optional GOF column to expose as canonical
score.metrics_df – Required function argument.
events – Optional function argument. Defaults to
None.stations – Optional function argument. Defaults to
None.event_key – Optional function argument. Defaults to
'event_id'.station_key – Optional function argument. Defaults to
'station'.residual_column – Optional function argument. Defaults to
None.score_column – Optional function argument. Defaults to
None.
- Returns:
Enriched long metric table.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.enrich.prepare_metric_residual_table(df: DataFrame, *, residual_mode: str = 'logratio', residual_column: str | None = None, score_column: str | None = None, ensure_distance: bool = True) DataFrame
Normalize a wide metric table into long residual form.
- Parameters:
df (pandas.DataFrame) – Wide table with
*_obs/*_synmetric columns or an already-long table withmetricandresidual.residual_mode (str, optional) –
"logratio"or"diff"when converting wide tables.residual_column (str | None, optional) – Optional transform column to expose as canonical
residualfor downstream spatial and dashboard functions.score_column (str | None, optional) – Optional GOF column to expose as canonical
score.ensure_distance (bool, optional) – Whether to add distance and azimuth columns when event/station coordinates are available.
df – Required function argument.
residual_mode – Optional function argument. Defaults to
'logratio'.residual_column – Optional function argument. Defaults to
None.score_column – Optional function argument. Defaults to
None.ensure_distance – Optional function argument. Defaults to
True.
- Returns:
Long metric table using the public dashboard/spatial column contract.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
Goodness-of-fit metrics for observed and synthetic trace pairs.
The module implements the legacy C1-C13 metric bundle while exposing newer metric names elsewhere in the public package. It includes duration, intensity, amplitude, spectral, delay, correlation, and cumulative absolute velocity calculations.
Implementation notes
C5-C7 use the same Gaussian score kernel as C3 and C4.
C8 uses a Newmark average-acceleration SDOF solver and returns PSA.
C9 compares native FFT amplitudes over the requested frequency range.
C1 and C2 compare 5-95 percent duration lengths.
C11 uses a Gaussian penalty on absolute lag divided by lag cap.
C12 is the aligned cross-correlation score at the optimal lag.
C13 is CAV integrated over each trace’s 5-95 percent energy-duration window.
Velocity and displacement metrics use frequency-domain integration.
Inputs are expected to be preprocessed for the period band of interest and to use consistent physical units.
GOF Calculation Examples
- Compute one metrics bundle for aligned traces:
from spatial_vtk.metrics.calculate.gof import compute_metrics_pair
- spatial_vtk.metrics.calculate.gof.CAV(trace, dt: float, *, window: tuple[float, float] | None = None) float
Calculate cumulative absolute velocity for one acceleration trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
window (tuple[float, float] | None, optional) – Optional
(start_s, end_s)integration window. If omitted, the full trace is used.trace – Required function argument.
dt – Required function argument.
window – Optional function argument. Defaults to
None.
- Returns:
Integral of absolute acceleration.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.FAS(trace, dt: float, *, periods: Iterable[float] | None = None, frequencies: Iterable[float] | None = None, use_hann: bool = True) ndarray | tuple[ndarray, ndarray]
Calculate Fourier amplitude spectra on a requested period/frequency grid.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
periods (Optional, optional) – Optional periods in seconds. Returned values are interpolated at
1 / period.frequencies (Optional, optional) – Optional frequencies in Hz. Ignored when
periodsis supplied.use_hann (bool, optional) – Whether to apply a Hann window before the FFT.
trace – Required function argument.
dt – Required function argument.
periods – Optional function argument. Defaults to
None.frequencies – Optional function argument. Defaults to
None.use_hann – Optional function argument. Defaults to
True.
- Returns:
Interpolated amplitudes aligned with the requested grid. If neither
periodsnorfrequenciesis supplied, returns the native(frequency_hz, amplitude)arrays.- Return type:
numpy.ndarray or tuple[numpy.ndarray, numpy.ndarray]
- Returns:
Return value produced by the function.
- Return type:
numpy.ndarray | tuple[numpy.ndarray, numpy.ndarray]
- spatial_vtk.metrics.calculate.gof.PGA(trace, *, edge_frac: float = 0.01) float
Calculate peak ground acceleration.
- Parameters:
trace (Any) – Acceleration samples.
edge_frac (float, optional) – Fraction of samples trimmed from each edge before measuring the peak.
trace – Required function argument.
edge_frac – Optional function argument. Defaults to
0.01.
- Returns:
Peak absolute acceleration.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.PGD(trace, dt: float, *, fmin: float | None = None, edge_frac: float = 0.01) float
Calculate peak ground displacement from an acceleration trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
fmin (Optional, optional) – Optional low-frequency cutoff for integration.
edge_frac (float, optional) – Fraction of samples trimmed from each edge before measuring the peak.
trace – Required function argument.
dt – Required function argument.
fmin – Optional function argument. Defaults to
None.edge_frac – Optional function argument. Defaults to
0.01.
- Returns:
Peak absolute displacement.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.PGV(trace, dt: float, *, fmin: float | None = None, edge_frac: float = 0.01) float
Calculate peak ground velocity from an acceleration trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
fmin (Optional, optional) – Optional low-frequency cutoff for integration.
edge_frac (float, optional) – Fraction of samples trimmed from each edge before measuring the peak.
trace – Required function argument.
dt – Required function argument.
fmin – Optional function argument. Defaults to
None.edge_frac – Optional function argument. Defaults to
0.01.
- Returns:
Peak absolute velocity.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.PSA(trace, dt: float, periods: Iterable[float], *, damping: float = 0.05) ndarray
Calculate pseudo-spectral acceleration at requested periods.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
periods (Iterable) – Spectral periods in seconds.
damping (float, optional) – Damping ratio used by the Newmark SDOF solver.
trace – Required function argument.
dt – Required function argument.
periods – Required function argument.
damping – Optional function argument. Defaults to
0.05.
- Returns:
PSA values aligned with
periods.- Return type:
numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
numpy.ndarray
- spatial_vtk.metrics.calculate.gof.arias_duration(trace, dt: float) float
Calculate 5-95 percent Arias duration for one acceleration trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
trace – Required function argument.
dt – Required function argument.
- Returns:
Duration between 5 and 95 percent cumulative Arias intensity.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.arias_intensity(trace, dt: float) float
Calculate Arias intensity for one acceleration trace.
- Parameters:
trace (Any) – Acceleration samples with units consistent with
g = 981 cm/s^2.dt (float) – Sample spacing in seconds.
trace – Required function argument.
dt – Required function argument.
- Returns:
Arias intensity integrated over the trace.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.compute_C9(a1, a2, dt: float, fmin: float | None = None, fmax: float | None = None, compute_scores=True) Tuple[float, float, float]
Mean Anderson score over one-sided, properly scaled FAS bins in [fmin, fmax].
- Parameters:
a1 (Any) – Required function argument.
a2 (Any) – Required function argument.
dt (float) – Required function argument.
fmin (Optional, optional) – Optional function argument. Defaults to
None.fmax (Optional, optional) – Optional function argument. Defaults to
None.compute_scores (Any, optional) – Optional function argument. Defaults to
True.
- Returns:
Return value produced by the function.
- Return type:
Tuple
- spatial_vtk.metrics.calculate.gof.compute_arias(acc1, acc2, dt, compute_scores=True) Tuple[Tuple[float, float, float], Tuple[float, float, float]]
C1 Arias 5-95% duration and C3 total Arias intensity.
- Parameters:
acc1 (Any) – Required function argument.
acc2 (Any) – Required function argument.
dt (Any) – Required function argument.
compute_scores (Any, optional) – Optional function argument. Defaults to
True.
- Returns:
Return value produced by the function.
- Return type:
Tuple
- spatial_vtk.metrics.calculate.gof.compute_arrival_phase_metrics(acc_obs, acc_syn, dt: float, obs_pick_s: float, syn_pick_s: float, phase: str, *, obs_valid_mask=None, syn_valid_mask=None, lag_cap_s: float | None = None, window_before_s: float = 1.0, window_after_s: float = 2.0, obs_probability: float = nan, syn_probability: float = nan) dict[str, float | str]
Compute arrival-aware phase delay and aligned-correlation metrics.
Inputs:
acc_obs/acc_syn: full filtered observed and synthetic acceleration traces.
dt: sample spacing in seconds.
obs_pick_s/syn_pick_s: relative P or S pick times in seconds.
phase: phase label used in reason strings.
obs_valid_mask/syn_valid_mask: optional filter-validity masks.
lag_cap_s: lag scale for the Gaussian C11 score.
window_before_s/window_after_s: retained for API compatibility; C12 now uses the phase delay to align and correlate the whole valid waveform.
obs_probability/syn_probability: optional pick probabilities.
Outputs:
dictionary with
lag_s,score,correlation,confidence,status, andreasonfields. Status isokonly when both picks are inside valid trace regions and the whole-waveform shifted overlap can be correlated.
- Parameters:
acc_obs (Any) – Required function argument.
acc_syn (Any) – Required function argument.
dt (float) – Required function argument.
obs_pick_s (float) – Required function argument.
syn_pick_s (float) – Required function argument.
phase (str) – Required function argument.
obs_valid_mask (Any, optional) – Optional function argument. Defaults to
None.syn_valid_mask (Any, optional) – Optional function argument. Defaults to
None.lag_cap_s (Optional, optional) – Optional function argument. Defaults to
None.window_before_s (float, optional) – Optional function argument. Defaults to
1.0.window_after_s (float, optional) – Optional function argument. Defaults to
2.0.obs_probability (float, optional) – Optional function argument. Defaults to
nan.syn_probability (float, optional) – Optional function argument. Defaults to
nan.
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.gof.compute_cross_correlation_zero_lag(acc1, acc2) float
C10: zero-lag normalized cross-correlation value.
- Parameters:
acc1 (Any) – Required function argument.
acc2 (Any) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.compute_duration(vel1, vel2, dt, compute_scores=True) Tuple[Tuple[float, float, float], Tuple[float, float, float]]
C2 energy 5-95% duration and C4 energy integral.
- Parameters:
vel1 (Any) – Required function argument.
vel2 (Any) – Required function argument.
dt (Any) – Required function argument.
compute_scores (Any, optional) – Optional function argument. Defaults to
True.
- Returns:
Return value produced by the function.
- Return type:
Tuple
- spatial_vtk.metrics.calculate.gof.compute_metrics_pair(acc_data, acc_syn, dt: float, which: Iterable[str] | None = None, rs_freqs=array([0.1, 0.11253356, 0.12663802, 0.14251027, 0.16037187, 0.18047218, 0.20309176, 0.22854639, 0.25719138, 0.28942661, 0.32570207, 0.36652412, 0.41246264, 0.46415888, 0.52233451, 0.58780161, 0.66147406, 0.7443803, 0.83767764, 0.94266846, 1.06081836, 1.19377664, 1.34339933, 1.51177507, 1.70125428, 1.91448198, 2.15443469, 2.42446202, 2.72833338, 3.07029063, 3.45510729, 3.88815518, 4.37547938, 4.92388263, 5.54102033, 6.23550734, 7.01703829, 7.89652287, 8.88623816, 10.]), fmax_for_lag: float | None = None, scoring_function: str = 'decay', compute_scores: bool = True, override_lag_s: float | None = None, fmin: float | None = None, fmax: float | None = None, obs_valid_mask=None, syn_valid_mask=None, arrival_picks=None, arrival_window_before_s: float = 1.0, arrival_window_after_s: float = 2.0) Dict[str, float]
Computes requested metrics; if which is None, returns all plus RMS helpers. NOTE: Inputs should already be bandpassed as desired. Arrival-aware C12P/C12S metrics use P/S picks to derive a delay, then correlate the whole valid waveform after applying that delay. The arrival_window_* arguments are retained for API compatibility and are not used by the current whole-waveform C12P/C12S definition.
- Parameters:
acc_data (Any) – Required function argument.
acc_syn (Any) – Required function argument.
dt (float) – Required function argument.
which (Optional, optional) – Optional function argument. Defaults to
None.rs_freqs (Any, optional) – Optional function argument. Defaults to
array([ 0.1 , 0.11253356, 0.12663802, 0.14251027, 0.16037187, 0.18047218, 0.20309176, 0.22854639, 0.25719138, 0.28942661, 0.32570207, 0.36652412, 0.41246264, 0.46415888, 0.52233451, 0.58780161, 0.66147406, 0.7443803 , 0.83767764, 0.94266846, 1.06081836, 1.19377664, 1.34339933, 1.51177507, 1.70125428, 1.91448198, 2.15443469, 2.42446202, 2.72833338, 3.07029063, 3.45510729, 3.88815518, 4.37547938, 4.92388263, 5.54102033, 6.23550734, 7.01703829, 7.89652287, 8.88623816, 10. ]).fmax_for_lag (Optional, optional) – Optional function argument. Defaults to
None.scoring_function (str, optional) – Optional function argument. Defaults to
'decay'.compute_scores (bool, optional) – Optional function argument. Defaults to
True.override_lag_s (Optional, optional) – Optional function argument. Defaults to
None.fmin (Optional, optional) – Optional function argument. Defaults to
None.fmax (Optional, optional) – Optional function argument. Defaults to
None.obs_valid_mask (Any, optional) – Optional function argument. Defaults to
None.syn_valid_mask (Any, optional) – Optional function argument. Defaults to
None.arrival_picks (Any, optional) – Optional function argument. Defaults to
None.arrival_window_before_s (float, optional) – Optional function argument. Defaults to
1.0.arrival_window_after_s (float, optional) – Optional function argument. Defaults to
2.0.
- Returns:
Return value produced by the function.
- Return type:
Dict
- spatial_vtk.metrics.calculate.gof.compute_phase_metrics(a1, a2, dt, lag_cap_s=None, override_lag_s: float | None = None)
Compute delay and aligned-correlation scores for a trace pair.
C11 is a Gaussian score based on absolute lag divided by the lag cap. C12 is
10 * max(r_peak, 0), wherer_peakis the peak correlation coefficient at the optimal lag.- Parameters:
a1 (Any) – Required function argument.
a2 (Any) – Required function argument.
dt (Any) – Required function argument.
lag_cap_s (Any, optional) – Optional function argument. Defaults to
None.override_lag_s (Optional, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
Any
- spatial_vtk.metrics.calculate.gof.delay_corrected_cc(observed, synthetic, dt: float, *, delay_s: float | None = None, max_lag_s: float | None = None) float
Calculate correlation after applying the travel-time delay.
- Parameters:
observed (Any) – Observed waveform samples.
synthetic (Any) – Synthetic waveform samples.
dt (float) – Sample spacing in seconds.
delay_s (Optional, optional) – Optional precomputed delay. When omitted, the delay is estimated with
traveltime_delay().max_lag_s (Optional, optional) – Optional maximum lag used when estimating
delay_s.observed – Required function argument.
synthetic – Required function argument.
dt – Required function argument.
delay_s – Optional function argument. Defaults to
None.max_lag_s – Optional function argument. Defaults to
None.
- Returns:
Zero-lag correlation coefficient after delay correction.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.energy_duration(trace, dt: float, *, fmin: float | None = None) float
Calculate 5-95 percent velocity-energy duration for one trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
fmin (Optional, optional) – Optional low-frequency cutoff for frequency-domain integration.
trace – Required function argument.
dt – Required function argument.
fmin – Optional function argument. Defaults to
None.
- Returns:
Duration between 5 and 95 percent cumulative velocity energy.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.energy_intensity(trace, dt: float, *, fmin: float | None = None) float
Calculate the velocity-energy integral for one acceleration trace.
- Parameters:
trace (Any) – Acceleration samples.
dt (float) – Sample spacing in seconds.
fmin (Optional, optional) – Optional low-frequency cutoff for frequency-domain integration.
trace – Required function argument.
dt – Required function argument.
fmin – Optional function argument. Defaults to
None.
- Returns:
Integral of squared velocity over the trace.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.get_xcorr_full_func(a1, a2)
Computes the full normalized cross-correlation function for two signals. Returns (lags_in_samples, correlation_coefficients).
- Parameters:
a1 (Any) – Required function argument.
a2 (Any) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
Any
- spatial_vtk.metrics.calculate.gof.original_cc(observed, synthetic) float
Calculate the original zero-lag observed/synthetic correlation.
- Parameters:
observed (Any) – Observed waveform samples.
synthetic (Any) – Synthetic waveform samples.
observed – Required function argument.
synthetic – Required function argument.
- Returns:
Zero-lag normalized correlation coefficient.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.gof.set_scoring_function(name: str)
Sets the active scoring function for the module for the current process.
- Parameters:
name (str) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
Any
- spatial_vtk.metrics.calculate.gof.traveltime_delay(observed, synthetic, dt: float, *, max_lag_s: float | None = None) float
Return the delay that maximizes observed/synthetic cross-correlation.
- Parameters:
observed (Any) – Observed acceleration samples.
synthetic (Any) – Synthetic acceleration samples.
dt (float) – Sample spacing in seconds.
max_lag_s (Optional, optional) – Optional maximum absolute lag searched in seconds.
observed – Required function argument.
synthetic – Required function argument.
dt – Required function argument.
max_lag_s – Optional function argument. Defaults to
None.
- Returns:
Delay in seconds to apply to the synthetic trace. Positive values mean the synthetic trace is shifted earlier to align with the observed trace.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
PhaseNet adapter for broadband arrival picking.
Calculation Phasenet Adapter Overview
This module prepares station-level broadband waveform inputs for PhaseNet, runs a configured PhaseNet command, and converts PhaseNet picks into the public Spatial-VTK arrival-pick catalog schema.
Calculation Phasenet Adapter Examples
- Build a pick catalog from preloaded waveform groups:
build_phasenet_arrival_pick_catalog(groups, phasenet_command="python -m phasenet.predict", output_catalog="picks.csv", work_dir="phasenet_work")
- class spatial_vtk.metrics.calculate.phasenet_adapter.PhaseNetInputRecord(file_name: str, event_id: str, station: str, waveform_source: str, components: tuple[str, ...], sampling_rate: float, time_anchor: str = '', relative_time_origin: str = '', broadband: bool = True)
Describe one generated PhaseNet input file.
- Parameters:
file_name (str) – File name relative to the PhaseNet data directory.
event_id – Catalog identifiers for the input waveform.
station – Catalog identifiers for the input waveform.
waveform_source – Catalog identifiers for the input waveform.
components (tuple[str, ...]) – Components present in the generated three-channel input.
sampling_rate (float) – Sampling rate resolved from trace metadata.
time_anchor (str) – Absolute waveform start time when available.
relative_time_origin (str) – Absolute origin used to compute catalog-relative pick seconds.
broadband (bool) – Whether the input came from broadband traces.
- Returns:
Immutable metadata record used to normalize PhaseNet picks.
- Return type:
- spatial_vtk.metrics.calculate.phasenet_adapter.build_arg_parser() ArgumentParser
Build the module-level CLI parser.
- Returns:
Return value produced by the function.
- Return type:
argparse.ArgumentParser
- spatial_vtk.metrics.calculate.phasenet_adapter.build_phasenet_arrival_pick_catalog(groups: Iterable[Mapping[str, object]], *, phasenet_command: str | None = None, output_catalog: str | Path, work_dir: str | Path, model_dir: str | Path | None = None, model_version: str = '', min_p_prob: float = 0.0, min_s_prob: float = 0.0, overwrite: bool = False) Path
Prepare inputs, run PhaseNet, and write a pick catalog.
- Parameters:
groups (Iterable) – Required function argument.
phasenet_command (str | None, optional) – Optional function argument. Defaults to
None.output_catalog (str | pathlib.Path) – Required function argument.
work_dir (str | pathlib.Path) – Required function argument.
model_dir (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.model_version (str, optional) – Optional function argument. Defaults to
''.min_p_prob (float, optional) – Optional function argument. Defaults to
0.0.min_s_prob (float, optional) – Optional function argument. Defaults to
0.0.overwrite (bool, optional) – Optional function argument. Defaults to
False.
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
- spatial_vtk.metrics.calculate.phasenet_adapter.main(argv: Sequence[str] | None = None) int
Run the PhaseNet normalization CLI wrapper.
- Parameters:
argv (Optional, optional) – Optional function argument. Defaults to
None.- Returns:
Return value produced by the function.
- Return type:
int
- spatial_vtk.metrics.calculate.phasenet_adapter.normalize_phasenet_output(phasenet_csv: str | Path, records: Iterable[PhaseNetInputRecord], *, model_version: str = '', min_p_prob: float = 0.0, min_s_prob: float = 0.0) DataFrame
Convert PhaseNet picks into station-level Spatial-VTK catalog rows.
- Parameters:
phasenet_csv (str | pathlib.Path) – Required function argument.
records (Iterable) – Required function argument.
model_version (str, optional) – Optional function argument. Defaults to
''.min_p_prob (float, optional) – Optional function argument. Defaults to
0.0.min_s_prob (float, optional) – Optional function argument. Defaults to
0.0.
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.phasenet_adapter.prepare_phasenet_numpy_inputs(groups: Iterable[Mapping[str, object]], data_dir: str | Path, *, overwrite: bool = False) list[PhaseNetInputRecord]
Prepare full-broadband NumPy inputs for PhaseNet.
- Parameters:
groups (Iterable) – Required function argument.
data_dir (str | pathlib.Path) – Required function argument.
overwrite (bool, optional) – Optional function argument. Defaults to
False.
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.calculate.phasenet_adapter.run_phasenet(data_dir: str | Path, *, result_dir: str | Path, phasenet_command: str | None = None, model_dir: str | Path | None = None, sampling_rate: float, min_p_prob: float = 0.0, min_s_prob: float = 0.0) Path
Run PhaseNet for one sampling-rate group.
- Parameters:
data_dir (str | pathlib.Path) – PhaseNet input and output directories.
result_dir (str | pathlib.Path) – PhaseNet input and output directories.
phasenet_command (str | None, optional) – Explicit command. Defaults to the configured PhaseNet command.
model_dir (str | pathlib.Path | None, optional) – Optional PhaseNet model directory.
sampling_rate (float) – Trace sampling rate in Hz.
min_p_prob (float, optional) – PhaseNet probability thresholds.
min_s_prob (float, optional) – PhaseNet probability thresholds.
data_dir – Required function argument.
result_dir – Required function argument.
phasenet_command – Optional function argument. Defaults to
None.model_dir – Optional function argument. Defaults to
None.sampling_rate – Required function argument.
min_p_prob – Optional function argument. Defaults to
0.0.min_s_prob – Optional function argument. Defaults to
0.0.
- Returns:
Path to PhaseNet’s pick CSV.
- Return type:
pathlib.Path
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
- spatial_vtk.metrics.calculate.phasenet_adapter.write_phasenet_data_list(records: Sequence[PhaseNetInputRecord], data_dir: str | Path) Path
Write PhaseNet
data_list.csvfor generated inputs.- Parameters:
records (Sequence) – Required function argument.
data_dir (str | pathlib.Path) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
Public metric row builders.
Calculation Records Overview
This module defines the standardized long metric row shape used by the public metrics workflow. It keeps scalar and period-specific rows consistent across Python, CLI, and notebooks.
Calculation Records Examples
- Build one long metric row:
row = build_metric_value_row(metric_group="amplitude", metric="PGA", value_obs=1.2, value_syn=1.0)
- class spatial_vtk.metrics.calculate.records.MetricValueRow(metric_group: str, metric: str, value_obs: float = nan, value_syn: float = nan, period_s: float | None = None, context: dict[str, ~typing.Any] = <factory>, qc: dict[str, ~typing.Any] = <factory>, transforms: tuple[str, ...] = ('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof'))
Container for one long metric row.
- Parameters:
metric_group (str) – Public metric family such as
amplitudeorspectral.metric (str) – Public metric name such as
PGAorPSA.value_obs (float) – Observed metric value, if available.
value_syn (float) – Synthetic metric value, if available.
period_s (float | None) – Spectral period in seconds for period-specific rows.
context (dict[str, Any]) – Optional event/station/model/passband metadata.
qc (dict[str, Any]) – Optional QC provenance fields.
transforms (tuple[str, ...]) – Requested observed/synthetic transforms.
- Returns:
Immutable row object that can be converted to a dictionary.
- Return type:
- to_dict() dict[str, Any]
Return this metric row as a flat dictionary.
- Parameters:
self – Metric row instance.
- Returns:
Standardized long metric row.
- Return type:
dict[str, Any]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.records.build_metric_value_row(*, metric_group: str, metric: str, value_obs: float = nan, value_syn: float = nan, period_s: float | None = None, transforms: tuple[str, ...] = ('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof'), **metadata: Any) dict[str, Any]
Build one standardized long metric row.
- Parameters:
metric_group (str) – Public metric family.
metric (str) – Public metric name.
value_obs (float, optional) – Observed metric value.
value_syn (float, optional) – Synthetic metric value.
period_s (float | None, optional) – Optional period for spectral metrics.
transforms (tuple, optional) – Requested comparison transforms.
metadata (Any) – Additional context or QC columns.
metric_group – Required function argument.
metric – Required function argument.
value_obs – Optional function argument. Defaults to
nan.value_syn – Optional function argument. Defaults to
nan.period_s – Optional function argument. Defaults to
None.transforms – Optional function argument. Defaults to
('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof').metadata – Additional keyword arguments passed to the function.
- Returns:
Standardized long metric row.
- Return type:
dict[str, Any]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.records.build_spectral_metric_rows(*, metric: str, periods_s, values_obs=None, values_syn=None, transforms: tuple[str, ...] = ('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof'), **metadata: Any) list[dict[str, Any]]
Build one long metric row per spectral period.
- Parameters:
metric (str) – Spectral metric name, usually
PSAorFAS.periods_s (Any) – Period grid in seconds.
values_obs (Any, optional) – Observed values aligned with
periods_s.values_syn (Any, optional) – Synthetic values aligned with
periods_s.transforms (tuple, optional) – Requested comparison transforms.
metadata (Any) – Context or QC columns copied to every row.
metric – Required function argument.
periods_s – Required function argument.
values_obs – Optional function argument. Defaults to
None.values_syn – Optional function argument. Defaults to
None.transforms – Optional function argument. Defaults to
('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof').metadata – Additional keyword arguments passed to the function.
- Returns:
Standardized long spectral rows.
- Return type:
list[dict[str, Any]]
- Returns:
Return value produced by the function.
- Return type:
list
Period-domain spectrum calculations for metric diagnostics.
Calculation Spectra Overview
This module contains reusable spectrum helpers for workflows that need period-axis amplitude spectra or spectrogram data without rendering figures.
Calculation Spectra Examples
- Compute a period spectrum:
periods, amplitudes = compute_amplitude_spectrum_vs_period(trace, dt=0.02)
- spatial_vtk.metrics.calculate.spectra.compute_amplitude_spectrum_vs_period(trace: Any, dt: float | None = None) tuple[ndarray, ndarray]
Convert one waveform into a period-axis amplitude spectrum.
- Parameters:
trace (Any) – Waveform samples or trace-like object.
dt (float | None, optional) – Optional sample spacing in seconds.
trace – Required function argument.
dt – Optional function argument. Defaults to
None.
- Returns:
Period values in seconds and corresponding one-sided FFT amplitudes, sorted from short to long period.
- Return type:
tuple[numpy.ndarray, numpy.ndarray]
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.calculate.spectra.compute_period_spectrogram(trace: Any, dt: float | None = None, nfft: int = 256, noverlap: int = 192) tuple[ndarray, ndarray, ndarray]
Compute a period-axis spectrogram for one waveform.
- Parameters:
trace (Any) – Waveform samples or trace-like object.
dt (float | None, optional) – Optional sample spacing in seconds.
nfft (int, optional) – Spectrogram window and overlap in samples.
noverlap (int, optional) – Spectrogram window and overlap in samples.
trace – Required function argument.
dt – Optional function argument. Defaults to
None.nfft – Optional function argument. Defaults to
256.noverlap – Optional function argument. Defaults to
192.
- Returns:
Period array, time-bin array, and power matrix sorted from short to long period.
- Return type:
tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.calculate.spectra.interpolate_period_spectrum(periods: Sequence[float], amplitudes: Sequence[float], target_periods: Sequence[float]) ndarray
Interpolate amplitudes onto requested periods.
- Parameters:
periods (collections.abc.Sequence) – Source period axis in seconds.
amplitudes (collections.abc.Sequence) – Source amplitudes aligned to
periods.target_periods (collections.abc.Sequence) – Requested target periods in seconds.
periods – Required function argument.
amplitudes – Required function argument.
target_periods – Required function argument.
- Returns:
Interpolated amplitudes aligned with
target_periods.- Return type:
numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
numpy.ndarray
- spatial_vtk.metrics.calculate.spectra.subset_period_range(periods: Sequence[float], amplitudes: Sequence[float], min_period: float | None = None, max_period: float | None = None) tuple[ndarray, ndarray]
Filter a period spectrum to one inclusive period range.
- Parameters:
periods (collections.abc.Sequence) – Period axis in seconds.
amplitudes (collections.abc.Sequence) – Spectrum amplitudes aligned to
periods.min_period (float | None, optional) – Optional inclusive period limits.
max_period (float | None, optional) – Optional inclusive period limits.
periods – Required function argument.
amplitudes – Required function argument.
min_period – Optional function argument. Defaults to
None.max_period – Optional function argument. Defaults to
None.
- Returns:
Filtered period and amplitude arrays.
- Return type:
tuple[numpy.ndarray, numpy.ndarray]
- Returns:
Return value produced by the function.
- Return type:
tuple
Non-figure summary tables for metric outputs.
Calculation Summaries Overview
This module contains calculation-only summary helpers used by metrics workflows, dashboards, and spatial analysis. It does not render figures or write files.
Calculation Summaries Examples
- Summarize score columns by station and passband:
summary = summarize_metric_scores(metrics_df)
- spatial_vtk.metrics.calculate.summaries.binned_numeric_midpoints(series: Series | Sequence[float], step: float) tuple[ndarray, ndarray] | tuple[None, None]
Return bin edges and midpoint labels for one numeric series.
- Parameters:
series (pandas.Series | collections.abc.Sequence[float]) – Numeric values.
step (float) – Bin width.
series – Required function argument.
step – Required function argument.
- Returns:
Bin edges and labels, or
(None, None)for empty input.- Return type:
tuple[numpy.ndarray, numpy.ndarray] or tuple[None, None]
- Returns:
Return value produced by the function.
- Return type:
tuple[numpy.ndarray, numpy.ndarray] | tuple[None, None]
- spatial_vtk.metrics.calculate.summaries.build_station_residual_table(df: DataFrame, metric_stem: str, *, log_base: str = 'log2') tuple[DataFrame, str] | tuple[None, None]
Build one station-mean residual table for a metric stem.
- Parameters:
df (pandas.DataFrame) – Wide metric table with station coordinates and metric columns.
metric_stem (str) – Metric stem such as
C5orPSA_T3.0.log_base (str, optional) – Residual mode passed to
metric_residual_series().df – Required function argument.
metric_stem – Required function argument.
log_base – Optional function argument. Defaults to
'log2'.
- Returns:
Station-mean residual table and residual column name, or
(None, None)when required columns are unavailable.- Return type:
tuple[pandas.DataFrame, str] or tuple[None, None]
- Returns:
Return value produced by the function.
- Return type:
tuple[pandas.DataFrame, str] | tuple[None, None]
- spatial_vtk.metrics.calculate.summaries.metric_residual_series(df: DataFrame, metric_stem: str, *, log_base: str = 'log2') Series | None
Return finite observed/synthetic residuals for one metric stem.
- Parameters:
df (pandas.DataFrame) – Wide metric table.
metric_stem (str) – Metric stem such as
C5orPSA_T3.0.log_base (str, optional) – Residual mode:
log2,ln,log10, ordiff.df – Required function argument.
metric_stem – Required function argument.
log_base – Optional function argument. Defaults to
'log2'.
- Returns:
Residual series aligned to
dforNonewhen required columns are unavailable.- Return type:
pandas.Series or None
- Returns:
Return value produced by the function.
- Return type:
pandas.Series | None
- spatial_vtk.metrics.calculate.summaries.metric_stems_by_family(df: DataFrame, family: str) list[str]
Return residual-capable metric stems for a broad metric family.
- Parameters:
df (pandas.DataFrame) – Wide metric table.
family (str) – Family token. Supported values include
c,legacy,psa,spectral, andnamed.df – Required function argument.
family – Required function argument.
- Returns:
Sorted metric stems in the requested family.
- Return type:
list[str]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.calculate.summaries.residual_metric_stems(df: DataFrame, *, include_named: bool = True) list[str]
Return metric stems that have observed and synthetic value columns.
- Parameters:
df (pandas.DataFrame) – Wide metric table.
include_named (bool, optional) – Whether to include non-
C_imetric stems such asPSA_T1.0.df – Required function argument.
include_named – Optional function argument. Defaults to
True.
- Returns:
Sorted metric stems with both
*_obsand*_syncolumns.- Return type:
list[str]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.calculate.summaries.score_metric_stems(df: DataFrame) list[str]
Return metric stems that have score columns.
- Parameters:
df (pandas.DataFrame) – Wide metric table.
df – Required function argument.
- Returns:
Sorted metric stems with
*_scorecolumns.- Return type:
list[str]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.calculate.summaries.station_mean_table(df: DataFrame, *, value_columns: Sequence[str]) DataFrame
Aggregate metric values to one row per station.
- Parameters:
df (pandas.DataFrame) – Metric table with station coordinates.
value_columns (collections.abc.Sequence) – Numeric columns to average.
df – Required function argument.
value_columns – Required function argument.
- Returns:
Station-mean table with normalized
station,station_lon, andstation_latcolumns.- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.summaries.summarize_long_metric_table(df: DataFrame, *, value_col: str = 'log2_residual', group_cols: Sequence[str] = ('model', 'station', 'passband', 'metric')) DataFrame
Summarize a public long metric table.
- Parameters:
df (pandas.DataFrame) – Long metric table with a metric value or transform column.
value_col (str, optional) – Numeric value column to summarize.
group_cols (collections.abc.Sequence, optional) – Grouping columns to use when present.
df – Required function argument.
value_col – Optional function argument. Defaults to
'log2_residual'.group_cols – Optional function argument. Defaults to
('model', 'station', 'passband', 'metric').
- Returns:
Summary table with mean, median, standard deviation, and count.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.calculate.summaries.summarize_metric_scores(df: DataFrame, *, group_cols: Sequence[str] | None = None, score_columns: Sequence[str] | None = None) DataFrame
Summarize metric score columns by model/station/passband groups.
- Parameters:
df (pandas.DataFrame) – Wide metric table.
group_cols (collections.abc.Sequence[str] | None, optional) – Optional explicit grouping columns. Missing columns are ignored.
score_columns (collections.abc.Sequence[str] | None, optional) – Optional score columns. By default, all
*_scorecolumns are used.df – Required function argument.
group_cols – Optional function argument. Defaults to
None.score_columns – Optional function argument. Defaults to
None.
- Returns:
Summary table with mean, median, standard deviation, and count for each score column.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
Observed/synthetic metric comparison transforms.
Calculation Transforms Overview
This module separates metric values from comparison methods. Metric functions measure one observed or synthetic trace; transforms compare the two values.
Calculation Transforms Examples
- Compare one PGA pair:
compare_metric_values(120.0, 100.0, transforms=["log2_residual"])
- spatial_vtk.metrics.calculate.transforms.anderson_2004_gof(observed_value: float, synthetic_value: float) float
Return the Anderson-style GOF score used by legacy C metrics.
- Parameters:
observed_value (float) – Observed positive metric value.
synthetic_value (float) – Synthetic positive metric value.
observed_value – Required function argument.
synthetic_value – Required function argument.
- Returns:
Score on a 0-10 scale, where 10 is a perfect match.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.transforms.compare_metric_values(observed_value: float, synthetic_value: float, *, transforms: Iterable[str] = ('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof')) dict[str, float]
Apply requested observed/synthetic comparison transforms.
- Parameters:
observed_value (float) – Observed metric value.
synthetic_value (float) – Synthetic metric value.
transforms (collections.abc.Iterable, optional) – Transform names to calculate.
observed_value – Required function argument.
synthetic_value – Required function argument.
transforms – Optional function argument. Defaults to
('residual', 'log2_residual', 'ln_residual', 'anderson_2004_gof', 'olsen_mayhew_gof').
- Returns:
Mapping from transform name to calculated value.
- Return type:
dict[str, float]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.calculate.transforms.ln_residual(observed_value: float, synthetic_value: float) float
Return the natural-log observed/synthetic residual.
- Parameters:
observed_value (float) – Observed positive metric value.
synthetic_value (float) – Synthetic positive metric value.
observed_value – Required function argument.
synthetic_value – Required function argument.
- Returns:
ln(observed_value / synthetic_value)or NaN for non-positive values.- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.transforms.log2_residual(observed_value: float, synthetic_value: float) float
Return the base-2 logarithmic observed/synthetic residual.
- Parameters:
observed_value (float) – Observed positive metric value.
synthetic_value (float) – Synthetic positive metric value.
observed_value – Required function argument.
synthetic_value – Required function argument.
- Returns:
log2(observed_value / synthetic_value)or NaN for non-positive values.- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.transforms.olsen_mayhew_gof(observed_value: float, synthetic_value: float) float
Return the Olsen-Mayhew broadband GOF scalar score.
- Parameters:
observed_value (float) – Observed positive scalar metric value.
synthetic_value (float) – Synthetic positive scalar metric value.
observed_value – Required function argument.
synthetic_value – Required function argument.
- Returns:
Score on a 0-100 scale from Olsen and Mayhew’s complementary error-function normalized residual.
- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
- spatial_vtk.metrics.calculate.transforms.residual(observed_value: float, synthetic_value: float) float
Return the arithmetic observed-minus-synthetic residual.
- Parameters:
observed_value (float) – Observed metric value.
synthetic_value (float) – Synthetic metric value.
observed_value – Required function argument.
synthetic_value – Required function argument.
- Returns:
observed_value - synthetic_valueor NaN when either value is not finite.- Return type:
float
- Returns:
Return value produced by the function.
- Return type:
float
Waveform processing helpers used by metric calculations.
- class spatial_vtk.metrics.calculate.waveforms.BandpassResult(data: ndarray, dt: float, valid_mask: ndarray, low_hz: float, high_hz: float)
Filtered waveform data plus validity metadata.
- spatial_vtk.metrics.calculate.waveforms.align_streams(observed_stream, synthetic_stream)
Trim two ObsPy streams to their common time window.
- Parameters:
observed_stream (Any) – ObsPy
Streamobjects or stream-like objects withcopy,trim, and tracestats.starttime/endtimeattributes.synthetic_stream (Any) – ObsPy
Streamobjects or stream-like objects withcopy,trim, and tracestats.starttime/endtimeattributes.observed_stream – Required function argument.
synthetic_stream – Required function argument.
- Returns:
Trimmed observed and synthetic streams.
- Return type:
tuple
- Returns:
Return value produced by the function.
- Return type:
Any
- spatial_vtk.metrics.calculate.waveforms.amplitude_spectrum(data: ndarray, dt: float) tuple[ndarray, ndarray]
Compute a one-sided amplitude spectrum.
- Parameters:
data (numpy.ndarray) – One-dimensional waveform samples.
dt (float) – Sample interval in seconds.
data – Required function argument.
dt – Required function argument.
- Returns:
Frequencies in Hz and corresponding one-sided amplitudes.
- Return type:
tuple of numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.calculate.waveforms.apply_filter_validity_mask(data: ndarray, valid_mask: ndarray) ndarray
Replace samples outside a validity mask with NaN.
- Parameters:
data (numpy.ndarray) – One-dimensional samples.
valid_mask (numpy.ndarray) – Boolean mask with the same length as
data.data – Required function argument.
valid_mask – Required function argument.
- Returns:
Copy of data with invalid samples set to NaN.
- Return type:
numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
numpy.ndarray
- spatial_vtk.metrics.calculate.waveforms.bandpass_with_metadata(data: ndarray, dt: float, low_hz: float, high_hz: float, *, order: int = 4, taper_fraction: float = 0.05) BandpassResult
Bandpass filter a waveform and mark samples safe for comparison.
- Parameters:
data (numpy.ndarray) – One-dimensional waveform samples.
dt (float) – Sample interval in seconds.
low_hz (float) – Bandpass corner frequencies in Hz.
high_hz (float) – Bandpass corner frequencies in Hz.
order (int, optional) – Butterworth filter order.
taper_fraction (float, optional) – Fraction of the trace length masked at each edge after filtering.
data – Required function argument.
dt – Required function argument.
low_hz – Required function argument.
high_hz – Required function argument.
order – Optional function argument. Defaults to
4.taper_fraction – Optional function argument. Defaults to
0.05.
- Returns:
Filtered data and a boolean validity mask.
- Return type:
- Returns:
Return value produced by the function.
- Return type:
- spatial_vtk.metrics.calculate.waveforms.lowpass_waveform(data: ndarray, dt: float, cutoff_hz: float | None, *, order: int = 4) ndarray
Lowpass filter one waveform when a cutoff is configured.
- Parameters:
data (numpy.ndarray) – One-dimensional waveform samples.
dt (float) – Sample interval in seconds.
cutoff_hz (float | None) – Lowpass cutoff in Hz.
Noneor non-positive values leave the data unchanged.order (int, optional) – Butterworth filter order.
data – Required function argument.
dt – Required function argument.
cutoff_hz – Required function argument.
order – Optional function argument. Defaults to
4.
- Returns:
Filtered samples, or a finite copy of the original samples when no cutoff is configured.
- Return type:
numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
numpy.ndarray
- spatial_vtk.metrics.calculate.waveforms.trim_bandpassed_pair_to_common_valid(observed: BandpassResult, synthetic: BandpassResult) tuple[ndarray, ndarray, ndarray]
Trim two filtered waveforms to their common valid samples.
- Parameters:
observed (spatial_vtk.metrics.calculate.waveforms.BandpassResult) – Filtered waveform results with matching sample intervals.
synthetic (spatial_vtk.metrics.calculate.waveforms.BandpassResult) – Filtered waveform results with matching sample intervals.
observed – Required function argument.
synthetic – Required function argument.
- Returns:
Observed samples, synthetic samples, and the common validity mask.
- Return type:
tuple of numpy.ndarray
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.calculate.waveforms.trim_to_valid_window(data: ndarray, valid_mask: ndarray) tuple[ndarray, slice]
Trim data to the first and last valid sample in a mask.
- Parameters:
data (numpy.ndarray) – One-dimensional samples.
valid_mask (numpy.ndarray) – Boolean validity mask.
data – Required function argument.
valid_mask – Required function argument.
- Returns:
Trimmed data and the slice used to trim it.
- Return type:
tuple
- Returns:
Return value produced by the function.
- Return type:
tuple
Workflow
Metric workflow manifests and batch execution.
Workflow Execution Overview
This module writes resumable metric task manifests, runs individual batches, and merges batch outputs.
Workflow Execution Examples
- Write a manifest and run the first batch:
manifest = write_task_manifest(tasks, "metrics_manifest.json", output_dir="metric_batches")run_manifest_batch(manifest, batch_index=0)
- class spatial_vtk.metrics.workflow.execution.MetricWorkflowManifest(manifest_path: Path, tasks: tuple[MetricWorkflowTask, ...], batches: tuple[dict[str, Any], ...], qc_table: str = '')
Metric workflow manifest payload.
- Parameters:
manifest_path (pathlib.Path) – Path to the JSON manifest.
tasks (tuple[spatial_vtk.metrics.workflow.tasks.MetricWorkflowTask, ...]) – Planned metric tasks.
batches (tuple[dict[str, Any], ...]) – Batch dictionaries with task indices and output paths.
qc_table (str) – Optional QC table path.
- Returns:
Immutable manifest object.
- Return type:
- spatial_vtk.metrics.workflow.execution.build_arg_parser() ArgumentParser
Build the batch-execution CLI parser.
- Returns:
Return value produced by the function.
- Return type:
argparse.ArgumentParser
- spatial_vtk.metrics.workflow.execution.chunk_tasks(tasks: list[MetricWorkflowTask], *, chunk_size: int) list[list[MetricWorkflowTask]]
Split tasks into fixed-size chunks.
- Parameters:
tasks (list) – Workflow tasks.
chunk_size (int) – Maximum tasks per chunk.
tasks – Required function argument.
chunk_size – Required function argument.
- Returns:
Chunked tasks.
- Return type:
list[list[MetricWorkflowTask]]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.workflow.execution.main(argv: list[str] | None = None) int
Run one manifest batch from CLI arguments.
- Parameters:
argv (list[str] | None, optional) – Optional function argument. Defaults to
None.- Returns:
Return value produced by the function.
- Return type:
int
- spatial_vtk.metrics.workflow.execution.merge_batch_outputs(manifest: MetricWorkflowManifest | str | Path, output_path: str | Path, *, require_all: bool = True) Path
Merge batch outputs from a manifest into one metric table.
- Parameters:
manifest (spatial_vtk.metrics.workflow.execution.MetricWorkflowManifest | str | pathlib.Path) – Manifest object or path.
output_path (str | pathlib.Path) – Destination merged table.
require_all (bool, optional) – Whether every planned batch output must exist.
manifest – Required function argument.
output_path – Required function argument.
require_all – Optional function argument. Defaults to
True.
- Returns:
Written merged output path.
- Return type:
pathlib.Path
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
- spatial_vtk.metrics.workflow.execution.read_task_manifest(path: str | Path) MetricWorkflowManifest
Read a metric task manifest.
- Parameters:
path (str | pathlib.Path) – Manifest JSON path.
path – Required function argument.
- Returns:
Parsed manifest object.
- Return type:
- Returns:
Return value produced by the function.
- Return type:
spatial_vtk.metrics.workflow.execution.MetricWorkflowManifest
- spatial_vtk.metrics.workflow.execution.run_manifest_batch(manifest: MetricWorkflowManifest | str | Path, *, batch_index: int, overwrite: bool = False) Path
Run one batch from a metric task manifest.
- Parameters:
manifest (spatial_vtk.metrics.workflow.execution.MetricWorkflowManifest | str | pathlib.Path) – Manifest object or path.
batch_index (int) – Batch index to run.
overwrite (bool, optional) – Whether to replace an existing batch output.
manifest – Required function argument.
batch_index – Required function argument.
overwrite – Optional function argument. Defaults to
False.
- Returns:
Batch output path.
- Return type:
pathlib.Path
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
- spatial_vtk.metrics.workflow.execution.write_task_manifest(tasks: list[MetricWorkflowTask], manifest_path: str | Path, *, output_dir: str | Path, batch_size: int = 100, qc_table: str | Path | None = None, output_suffix: str = '.csv') MetricWorkflowManifest
Write a metric task manifest.
- Parameters:
tasks (list) – Planned metric tasks.
manifest_path (str | pathlib.Path) – Destination JSON manifest.
output_dir (str | pathlib.Path) – Directory for per-batch metric outputs.
batch_size (int, optional) – Maximum tasks per batch.
qc_table (str | pathlib.Path | None, optional) – Optional QC table path copied into the manifest.
output_suffix (str, optional) – Output suffix for batch tables, usually
.csvor.parquet.tasks – Required function argument.
manifest_path – Required function argument.
output_dir – Required function argument.
batch_size – Optional function argument. Defaults to
100.qc_table – Optional function argument. Defaults to
None.output_suffix – Optional function argument. Defaults to
'.csv'.
- Returns:
Written manifest object.
- Return type:
- Returns:
Return value produced by the function.
- Return type:
spatial_vtk.metrics.workflow.execution.MetricWorkflowManifest
Downstream output helpers for metric workflow rows.
Workflow Outputs Overview
This module turns file-based metric workflow rows into the standardized tables used by enrichment, spatial analysis, maps, dashboards, and tutorial notebooks.
Workflow Outputs Examples
- Prepare downstream tables:
tables = prepare_metric_workflow_outputs(metric_rows, events=events, stations=stations)- Write standard downstream files:
paths = write_metric_outputs(metric_rows, "outputs/metrics", events=events, stations=stations)
- spatial_vtk.metrics.workflow.outputs.prepare_metric_workflow_outputs(metric_rows: DataFrame | str | Path, *, events: DataFrame | str | Path | None = None, stations: DataFrame | str | Path | None = None, residual_column: str | None = None, score_column: str | None = None, distance_bin_km: float = 10.0, azimuth_bin_deg: float = 30.0, dashboard_distance_bin_km: float = 10.0, dashboard_azimuth_bin_deg: float = 10.0) dict[str, DataFrame | dict[str, DataFrame]]
Prepare metric workflow rows for downstream package modules.
- Parameters:
metric_rows (pandas.DataFrame | str | pathlib.Path) – Metric workflow output table or path.
events (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables joined before spatial/dashboard preparation.
stations (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables joined before spatial/dashboard preparation.
residual_column (str | None, optional) – Optional transform column exposed as canonical
residual. When omitted, workflow rows preferlog2_residualif noresidualcolumn exists.score_column (str | None, optional) – Optional GOF column exposed as canonical
score.distance_bin_km (float, optional) – Binning used for path-summary output.
azimuth_bin_deg (float, optional) – Binning used for path-summary output.
dashboard_distance_bin_km (float, optional) – Binning used for dashboard path summaries.
dashboard_azimuth_bin_deg (float, optional) – Binning used for dashboard path summaries.
metric_rows – Required function argument.
events – Optional function argument. Defaults to
None.stations – Optional function argument. Defaults to
None.residual_column – Optional function argument. Defaults to
None.score_column – Optional function argument. Defaults to
None.distance_bin_km – Optional function argument. Defaults to
10.0.azimuth_bin_deg – Optional function argument. Defaults to
30.0.dashboard_distance_bin_km – Optional function argument. Defaults to
10.0.dashboard_azimuth_bin_deg – Optional function argument. Defaults to
10.0.
- Returns:
Tables keyed as
metrics_long,path_table,path_summary,dashboard_metrics, anddashboard_summaries.- Return type:
dict
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.workflow.outputs.write_metric_outputs(metric_rows: DataFrame | str | Path, output_dir: str | Path | None = None, *, events: DataFrame | str | Path | None = None, stations: DataFrame | str | Path | None = None, residual_column: str | None = None, score_column: str | None = None, table_format: str = 'parquet', dashboard_partitioned: bool = False, distance_bin_km: float = 10.0, azimuth_bin_deg: float = 30.0, dashboard_distance_bin_km: float = 10.0, dashboard_azimuth_bin_deg: float = 10.0) dict[str, Path]
Write standard downstream outputs from metric workflow rows.
- Parameters:
metric_rows (pandas.DataFrame | str | pathlib.Path) – Metric workflow output table or path.
output_dir (str | pathlib.Path | None, optional) – Directory where standard outputs are written. When omitted,
outputs.tablesfrom the active config is used.events (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables joined before output.
stations (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional metadata tables joined before output.
residual_column (str | None, optional) – Optional transform column exposed as canonical
residual.score_column (str | None, optional) – Optional GOF column exposed as canonical
score.table_format (str, optional) –
"parquet"or"csv"for tabular outputs.dashboard_partitioned (bool, optional) – Whether the dashboard metric dataset should be partitioned by model, band, and metric.
distance_bin_km (float, optional) – Binning used for path-summary output.
azimuth_bin_deg (float, optional) – Binning used for path-summary output.
dashboard_distance_bin_km (float, optional) – Binning used for dashboard path summaries.
dashboard_azimuth_bin_deg (float, optional) – Binning used for dashboard path summaries.
metric_rows – Required function argument.
output_dir – Optional function argument. Defaults to
None.events – Optional function argument. Defaults to
None.stations – Optional function argument. Defaults to
None.residual_column – Optional function argument. Defaults to
None.score_column – Optional function argument. Defaults to
None.table_format – Optional function argument. Defaults to
'parquet'.dashboard_partitioned – Optional function argument. Defaults to
False.distance_bin_km – Optional function argument. Defaults to
10.0.azimuth_bin_deg – Optional function argument. Defaults to
30.0.dashboard_distance_bin_km – Optional function argument. Defaults to
10.0.dashboard_azimuth_bin_deg – Optional function argument. Defaults to
10.0.
- Returns:
Written paths keyed by artifact name.
- Return type:
dict[str, pathlib.Path]
- Returns:
Return value produced by the function.
- Return type:
dict
Run metric workflow tasks.
Workflow Run Overview
This module executes file-based metric tasks and writes standardized long metric tables. It keeps calculation logic separate from manifest chunking and SLURM script generation.
Workflow Run Examples
- Run planned tasks:
rows = run_metric_tasks(tasks, qc_table=qc_inventory)
- spatial_vtk.metrics.workflow.run.build_arg_parser() ArgumentParser
Build a CLI parser for direct task-table execution.
- Returns:
Return value produced by the function.
- Return type:
argparse.ArgumentParser
- spatial_vtk.metrics.workflow.run.calculate_task_rows(task: MetricWorkflowTask, *, qc_lookup: dict[tuple[str, str, str, str, str, str, str], dict[str, Any]] | None = None, waveform_cache: dict[str, Any] | None = None) list[dict[str, Any]]
Calculate all metric rows for one workflow task.
- Parameters:
task (spatial_vtk.metrics.workflow.tasks.MetricWorkflowTask) – Workflow task.
qc_lookup (dict[tuple[str, str, str, str, str, str, str], dict[str, Any]] | None, optional) – Optional normalized QC lookup.
waveform_cache (dict[str, Any] | None, optional) – Optional cache of loaded waveform files reused across tasks.
task – Required function argument.
qc_lookup – Optional function argument. Defaults to
None.waveform_cache – Optional function argument. Defaults to
None.
- Returns:
Long metric rows.
- Return type:
list[dict[str, object]]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.workflow.run.main(argv: list[str] | None = None) int
Run metric tasks from a task table.
- Parameters:
argv (list[str] | None, optional) – Optional function argument. Defaults to
None.- Returns:
Return value produced by the function.
- Return type:
int
- spatial_vtk.metrics.workflow.run.run_metric_tasks(tasks: list[MetricWorkflowTask], *, qc_table: DataFrame | str | Path | None = None) DataFrame
Run metric workflow tasks and return a long metric table.
- Parameters:
tasks (list) – Metric workflow tasks.
qc_table (pandas.DataFrame | str | pathlib.Path | None, optional) – Optional side-specific QC inventory.
tasks – Required function argument.
qc_table – Optional function argument. Defaults to
None.
- Returns:
Long metric table.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.workflow.run.write_metric_rows(df: DataFrame, path: str | Path) Path
Write metric rows to CSV or Parquet based on file suffix.
- Parameters:
df (pandas.DataFrame) – Metric dataframe.
path (str | pathlib.Path) – Output path.
.parquetand.pquse Parquet; all other suffixes use CSV.df – Required function argument.
path – Required function argument.
- Returns:
Written output path.
- Return type:
pathlib.Path
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
Generic SLURM support for metric workflow batches.
Workflow SLURM Overview
This module writes portable SLURM array scripts for metric workflow manifests.
It does not submit jobs unless a caller explicitly runs sbatch outside this
module.
Workflow SLURM Examples
- Write a script from config settings:
write_metrics_slurm_script("manifest.json", "run_metrics.slurm", settings)
- spatial_vtk.metrics.workflow.slurm.build_arg_parser() ArgumentParser
Build the SLURM script CLI parser.
- Parameters:
None
- Returns:
Parser for script-writing arguments.
- Return type:
argparse.ArgumentParser
- Returns:
Return value produced by the function.
- Return type:
argparse.ArgumentParser
- spatial_vtk.metrics.workflow.slurm.main(argv: list[str] | None = None) int
Write a SLURM script from CLI arguments.
- Parameters:
argv (list[str] | None, optional) – Optional argument list.
argv – Optional function argument. Defaults to
None.
- Returns:
Process exit code.
- Return type:
int
- Returns:
Return value produced by the function.
- Return type:
int
- spatial_vtk.metrics.workflow.slurm.slurm_settings_from_config(config: SpatialVTKConfig, *, section: str = 'metrics.slurm') SlurmSettings
Read SLURM settings from a public config object.
- Parameters:
config (spatial_vtk.config.runtime.SpatialVTKConfig) – Loaded Spatial-VTK config.
section (str, optional) – Dotted section key.
metrics.slurmis checked first, then top-levelslurmas a fallback.config – Required function argument.
section – Optional function argument. Defaults to
'metrics.slurm'.
- Returns:
Normalized SLURM settings.
- Return type:
- Returns:
Return value produced by the function.
- Return type:
- spatial_vtk.metrics.workflow.slurm.submit_metrics_slurm_job(manifest_path: str | Path, script_path: str | Path, settings: SlurmSettings)
Write and submit a SLURM array script for a metric workflow manifest.
- Parameters:
manifest_path (str | pathlib.Path) – Required function argument.
script_path (str | pathlib.Path) – Required function argument.
settings (spatial_vtk.config.compute.SlurmSettings) – Required function argument.
- Returns:
Return value produced by the function.
- Return type:
Any
- spatial_vtk.metrics.workflow.slurm.write_metrics_slurm_script(manifest_path: str | Path, script_path: str | Path, settings: SlurmSettings) Path
Write a SLURM array script for a metric workflow manifest.
- Parameters:
manifest_path (str | pathlib.Path) – Metric workflow manifest JSON.
script_path (str | pathlib.Path) – Destination shell script.
settings (spatial_vtk.config.compute.SlurmSettings) – User-provided SLURM settings.
manifest_path – Required function argument.
script_path – Required function argument.
settings – Required function argument.
- Returns:
Written script path.
- Return type:
pathlib.Path
- Returns:
Return value produced by the function.
- Return type:
pathlib.Path
Metric workflow task planning.
Workflow Tasks Overview
This module converts normalized observed/synthetic waveform inventories into explicit metric tasks that can be executed locally, in batches, or through a generic SLURM array job.
Workflow Tasks Examples
- Build tasks from inventories:
tasks = plan_metric_tasks(obs_inventory, syn_inventory, plan=metric_plan)
- class spatial_vtk.metrics.workflow.tasks.MetricWorkflowTask(task_id: str, event_id: str, station: str, component: str, model: str = '', passband: str = '', obs_waveform_path: str = '', syn_waveform_path: str = '', dt: float = nan, period_min_s: float | None = None, period_max_s: float | None = None, metrics: tuple[str, ...] = ('PGA',), transforms: tuple[str, ...] = ('log2_residual',), output_mode: str = 'full', spectral_periods_s: tuple[float, ...] = (), synthetic_max_frequency_hz: float | None = None, waveform_lowpass_hz: float | None = None, waveform_resample_hz: float | None = None, waveform_filter_order: int | None = None, spectral_relative_amplitude_threshold: float = 0.25, spectral_min_cycles_in_record: float = 3.0, disable_spectral_relative_amplitude_qc: bool = False, use_qc: bool = True)
One file-based metric calculation task.
- Parameters:
task_id (str) – Stable task identifier.
event_id – Calculation identity fields.
station – Calculation identity fields.
component – Calculation identity fields.
model – Calculation identity fields.
passband – Calculation identity fields.
obs_waveform_path – Optional observed and synthetic waveform paths.
syn_waveform_path – Optional observed and synthetic waveform paths.
dt (float) – Sample spacing in seconds.
period_min_s – Optional passband bounds in period seconds.
period_max_s – Optional passband bounds in period seconds.
metrics (tuple[str, ...]) – Metric names to calculate.
transforms (tuple[str, ...]) – Requested observed/synthetic transforms.
output_mode (str) –
observed,synthetic,residual,gof, orfull.spectral_periods_s (tuple[float, ...]) – Requested PSA/FAS periods.
synthetic_max_frequency_hz (float | None) – Optional maximum valid synthetic frequency.
waveform_lowpass_hz (float | None) – Optional project-configured lowpass cutoff applied before passband filtering and metric calculations.
waveform_resample_hz (float | None) – Optional target sample rate applied before passband filtering and metric calculations.
use_qc (bool) – Whether QC lookup rows should gate side values and comparisons.
- Returns:
Immutable workflow task.
- Return type:
- classmethod from_dict(payload: dict[str, Any]) MetricWorkflowTask
Build one task from a serialized dictionary.
- Parameters:
payload (dict) – Serialized task payload.
payload – Required function argument.
- Returns:
Reconstructed task.
- Return type:
- Returns:
Return value produced by the function.
- Return type:
- to_dict() dict[str, Any]
Return this task as a JSON/CSV-safe dictionary.
- Parameters:
self – Workflow task.
- Returns:
Serialized task payload.
- Return type:
dict[str, object]
- Returns:
Return value produced by the function.
- Return type:
dict
- spatial_vtk.metrics.workflow.tasks.metric_group_for(metric: str) str
Return the public metric group for one metric name.
- Parameters:
metric (str) – Public metric name or legacy C-code.
metric – Required function argument.
- Returns:
Metric group name.
- Return type:
str
- Returns:
Return value produced by the function.
- Return type:
str
- spatial_vtk.metrics.workflow.tasks.plan_metric_tasks(observed_inventory: DataFrame | str | Path | None, synthetic_inventory: DataFrame | str | Path | None = None, *, plan: MetricPlan, use_qc: bool = True, spectral_relative_amplitude_threshold: float = 0.25, spectral_min_cycles_in_record: float = 3.0, disable_spectral_relative_amplitude_qc: bool = False) list[MetricWorkflowTask]
Plan metric workflow tasks from observed/synthetic inventories.
- Parameters:
observed_inventory (pandas.DataFrame | str | pathlib.Path | None) – Observed waveform inventory or path. Required unless
plan.output_mode == "synthetic".synthetic_inventory (pandas.DataFrame | str | pathlib.Path | None, optional) – Synthetic waveform inventory or path. Required for pair modes and synthetic-only mode.
plan (spatial_vtk.io.plans.MetricPlan) – Resolved metric plan.
use_qc (bool, optional) – Whether tasks should honor QC tables during execution.
spectral_relative_amplitude_threshold (float, optional) – Relative amplitude threshold copied into each task for spectral QC.
spectral_min_cycles_in_record (float, optional) – Minimum usable cycles copied into each task for spectral QC.
disable_spectral_relative_amplitude_qc (bool, optional) – Whether each task should skip relative-amplitude spectral QC.
observed_inventory – Required function argument.
synthetic_inventory – Optional function argument. Defaults to
None.plan – Required function argument.
use_qc – Optional function argument. Defaults to
True.spectral_relative_amplitude_threshold – Optional function argument. Defaults to
0.25.spectral_min_cycles_in_record – Optional function argument. Defaults to
3.0.disable_spectral_relative_amplitude_qc – Optional function argument. Defaults to
False.
- Returns:
Planned workflow tasks.
- Return type:
list[MetricWorkflowTask]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.workflow.tasks.resolve_metric_names(metrics: tuple[str, ...] | list[str] | None, groups: tuple[str, ...] | list[str] | None = None) tuple[str, ...]
Resolve public metric names from metric or group selections.
- Parameters:
metrics (tuple[str, ...] | list[str] | None) – Explicit metric names, legacy C-codes, or
all.groups (tuple[str, ...] | list[str] | None, optional) – Metric groups used when explicit metrics are omitted.
metrics – Required function argument.
groups – Optional function argument. Defaults to
None.
- Returns:
Public metric names.
- Return type:
tuple[str, …]
- Returns:
Return value produced by the function.
- Return type:
tuple
- spatial_vtk.metrics.workflow.tasks.summarize_metric_tasks(tasks: list[MetricWorkflowTask] | DataFrame | str | Path, *, seconds_per_task: float = 60.0, memory_gb_per_task: float = 2.0, cpus_per_task: int = 1, parallel_tasks: int | None = None) DataFrame
Summarize metric task count and approximate resource needs.
- Parameters:
tasks (list[spatial_vtk.metrics.workflow.tasks.MetricWorkflowTask] | pandas.DataFrame | str | pathlib.Path) – Metric task list, serialized task dataframe, or task table path.
seconds_per_task (float, optional) – Approximate runtime for one task in seconds.
memory_gb_per_task (float, optional) – Approximate memory required by one task in GB.
cpus_per_task (int, optional) – CPU cores requested per task.
parallel_tasks (int | None, optional) – Optional number of tasks expected to run at the same time.
tasks – Required function argument.
seconds_per_task – Optional function argument. Defaults to
60.0.memory_gb_per_task – Optional function argument. Defaults to
2.0.cpus_per_task – Optional function argument. Defaults to
1.parallel_tasks – Optional function argument. Defaults to
None.
- Returns:
Compact estimate table with human-readable values and notes.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
- spatial_vtk.metrics.workflow.tasks.tasks_from_frame(table: DataFrame | str | Path) list[MetricWorkflowTask]
Read tasks from a dataframe or CSV/parquet path.
- Parameters:
table (pandas.DataFrame | str | pathlib.Path) – Serialized task table.
table – Required function argument.
- Returns:
Reconstructed tasks.
- Return type:
list[MetricWorkflowTask]
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.workflow.tasks.tasks_to_frame(tasks: list[MetricWorkflowTask]) DataFrame
Convert tasks to a dataframe.
- Parameters:
tasks (list) – Workflow tasks.
tasks – Required function argument.
- Returns:
Serialized task table.
- Return type:
pandas.DataFrame
- Returns:
Return value produced by the function.
- Return type:
pandas.DataFrame
Plotting
Example metric plots for deterministic observed/synthetic trace pairs.
- class spatial_vtk.metrics.plot.example_metric_plots.SyntheticMetricPair(name: str, observed: ndarray, synthetic: ndarray, dt: float)
One deterministic trace-pair scenario used to explain metric behavior.
- spatial_vtk.metrics.plot.example_metric_plots.build_example_metric_summary() list[dict[str, object]]
Compute C-metric summaries for the deterministic example pairs.
- Returns:
Return value produced by the function.
- Return type:
list
- spatial_vtk.metrics.plot.example_metric_plots.plot_example_metric_pairs(output_path: str | Path | None = None, *, scenarios: list[str] | None = None, showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None) Figure
Plot deterministic trace pairs and a small metric-score summary.
- Parameters:
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.scenarios (list[str] | None, optional) – Optional function argument. Defaults to
None.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.example_metric_plots.synthetic_metric_pairs() list[SyntheticMetricPair]
Build deterministic example trace pairs for metric demonstrations.
- Returns:
Return value produced by the function.
- Return type:
list
Model comparison and heatmap figures.
- spatial_vtk.metrics.plot.model_comparison.plot_band_score_distribution(df: DataFrame, output_path: str | Path | None = None, *, band_col: str = 'band', score_col: str = 'score', model_col: str = 'model', metric_col: str = 'metric', color_col: str | None = 'metric', title: str = 'Band Score Distribution', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None) Figure
Plot score distributions grouped by period band.
Inputs are a long metric table with one score column and a period-band column. The output is a Matplotlib figure with adjacent colored boxplots inside each passband group, plus visual separators between passbands.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.band_col (str, optional) – Optional function argument. Defaults to
'band'.score_col (str, optional) – Optional function argument. Defaults to
'score'.model_col (str, optional) – Optional function argument. Defaults to
'model'.metric_col (str, optional) – Optional function argument. Defaults to
'metric'.color_col (str | None, optional) – Optional function argument. Defaults to
'metric'.title (str, optional) – Optional function argument. Defaults to
'Band Score Distribution'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.model_comparison.plot_model_metric_heatmap(summary_df: DataFrame, output_path: str | Path | None = None, *, model_col: str = 'model', metric_col: str = 'metric', value_col: str = 'med_resid', title: str = 'Model-Metric Heatmap', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None) Figure
Plot model-by-metric summary values as a heatmap.
- Parameters:
summary_df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.model_col (str, optional) – Optional function argument. Defaults to
'model'.metric_col (str, optional) – Optional function argument. Defaults to
'metric'.value_col (str, optional) – Optional function argument. Defaults to
'med_resid'.title (str, optional) – Optional function argument. Defaults to
'Model-Metric Heatmap'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.model_comparison.plot_winner_heatmap(summary_df: DataFrame, output_path: str | Path | None = None, *, row_col: str = 'metric', col_col: str = 'band', winner_col: str = 'winner', title: str = 'Winning Model Heatmap', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None) Figure
Plot categorical winner labels by metric and band.
- Parameters:
summary_df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.row_col (str, optional) – Optional function argument. Defaults to
'metric'.col_col (str, optional) – Optional function argument. Defaults to
'band'.winner_col (str, optional) – Optional function argument. Defaults to
'winner'.title (str, optional) – Optional function argument. Defaults to
'Winning Model Heatmap'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
Period-domain metric plotting helpers.
- spatial_vtk.metrics.plot.periods.plot_period_spectra(spectra_df: DataFrame, output_path: str | Path | None = None, *, period_col: str = 'period_s', amplitude_col: str = 'amplitude', group_col: str | None = 'series', title: str = 'Period Spectra', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None, spatial_selection: FigureSpatialSelection | dict[str, object] | None = None, **spatial_kwargs: object) Figure
Plot period spectra from a long spectra table.
- Parameters:
spectra_df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.period_col (str, optional) – Optional function argument. Defaults to
'period_s'.amplitude_col (str, optional) – Optional function argument. Defaults to
'amplitude'.group_col (str | None, optional) – Optional function argument. Defaults to
'series'.title (str, optional) – Optional function argument. Defaults to
'Period Spectra'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.spatial_selection (spatial_vtk.visualize.selection.FigureSpatialSelection | dict[str, object] | None, optional) – Optional function argument. Defaults to
None.spatial_kwargs (object) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.periods.plot_period_spectrogram(spectrogram_df: DataFrame, output_path: str | Path | None = None, *, time_col: str = 'time_s', period_col: str = 'period_s', value_col: str = 'amplitude', title: str = 'Period Spectrogram', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None) Figure
Plot a time-period spectrogram from a long table.
- Parameters:
spectrogram_df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.time_col (str, optional) – Optional function argument. Defaults to
'time_s'.period_col (str, optional) – Optional function argument. Defaults to
'period_s'.value_col (str, optional) – Optional function argument. Defaults to
'amplitude'.title (str, optional) – Optional function argument. Defaults to
'Period Spectrogram'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.periods.plot_psa_period_curve(df: DataFrame, output_path: str | Path | None = None, *, metric: str | None = 'PSA', metric_col: str = 'metric', period_col: str = 'period_s', value_col: str = 'residual', group_col: str | None = 'model', title: str = 'PSA Period Response', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None, spatial_selection: FigureSpatialSelection | dict[str, object] | None = None, **spatial_kwargs: object) Figure
Plot PSA residuals or scores against oscillator period.
- Parameters:
df (pandas.DataFrame) – Long metric table. If
metricandmetric_colare available, the table is filtered before plotting.output_path (str | pathlib.Path | None, optional) – Optional destination for the figure.
outpath (str | pathlib.Path | None, optional) – Optional destination for the figure.
metric (str | None, optional) – Metric name and column used to select PSA rows. Set
metric=Noneto plot an already-filtered table.metric_col (str, optional) – Metric name and column used to select PSA rows. Set
metric=Noneto plot an already-filtered table.period_col (str, optional) – Columns used for period, plotted value, and optional grouping.
value_col (str, optional) – Columns used for period, plotted value, and optional grouping.
group_col (str | None, optional) – Columns used for period, plotted value, and optional grouping.
title (str, optional) – Figure title.
showfig (bool | None, optional) – Notebook/display and file-write controls.
savefig (bool | None, optional) – Notebook/display and file-write controls.
df – Required function argument.
output_path – Optional function argument. Defaults to
None.metric – Optional function argument. Defaults to
'PSA'.metric_col – Optional function argument. Defaults to
'metric'.period_col – Optional function argument. Defaults to
'period_s'.value_col – Optional function argument. Defaults to
'residual'.group_col – Optional function argument. Defaults to
'model'.title – Optional function argument. Defaults to
'PSA Period Response'.showfig – Optional function argument. Defaults to
None.savefig – Optional function argument. Defaults to
None.outpath – Optional function argument. Defaults to
None.spatial_selection (spatial_vtk.visualize.selection.FigureSpatialSelection | dict[str, object] | None, optional) – Optional function argument. Defaults to
None.spatial_kwargs (object) – Additional keyword arguments passed to the function.
- Returns:
The finished figure.
- Return type:
matplotlib.figure.Figure
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
Site-term metric diagnostic figures.
- spatial_vtk.metrics.plot.site_terms.plot_geology_boxplot(df: DataFrame, output_path: str | Path | None = None, *, geology_col: str = 'geology_class', value_col: str = 'residual', title: str = 'Metric Response by Geology', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None, spatial_selection: FigureSpatialSelection | dict[str, object] | None = None, **spatial_kwargs: object) Figure
Plot metric residuals or scores by geology class.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.geology_col (str, optional) – Optional function argument. Defaults to
'geology_class'.value_col (str, optional) – Optional function argument. Defaults to
'residual'.title (str, optional) – Optional function argument. Defaults to
'Metric Response by Geology'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.spatial_selection (spatial_vtk.visualize.selection.FigureSpatialSelection | dict[str, object] | None, optional) – Optional function argument. Defaults to
None.spatial_kwargs (object) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.site_terms.plot_vs30_scatter(df: DataFrame, output_path: str | Path | None = None, *, vs30_col: str = 'Vs30', value_col: str = 'residual', **kwargs) Figure
Plot metric residuals or scores against Vs30.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.vs30_col (str, optional) – Optional function argument. Defaults to
'Vs30'.value_col (str, optional) – Optional function argument. Defaults to
'residual'.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
Metric trend plotting helpers.
- spatial_vtk.metrics.plot.trends.plot_metric_trend(df: DataFrame, output_path: str | Path | None = None, *, x_col: str, y_col: str = 'residual', metric_col: str = 'metric', group_col: str | None = 'model', title: str | None = None, showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None, output_key: str | None = None, connect_points: bool = True, fit_method: object = None, fit: object = None, lowess_frac: float = 0.65, spatial_selection: FigureSpatialSelection | dict[str, object] | None = None, **spatial_kwargs: object) Figure
Plot metric values or residuals against one numeric variable.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.x_col (str) – Required function argument.
y_col (str, optional) – Optional function argument. Defaults to
'residual'.metric_col (str, optional) – Optional function argument. Defaults to
'metric'.group_col (str | None, optional) – Optional function argument. Defaults to
'model'.title (str | None, optional) – Optional function argument. Defaults to
None.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.output_key (str | None, optional) – Optional function argument. Defaults to
None.connect_points (bool, optional) – Optional function argument. Defaults to
True.fit_method (object, optional) – Optional function argument. Defaults to
None.fit (object, optional) – Optional function argument. Defaults to
None.lowess_frac (float, optional) – Optional function argument. Defaults to
0.65.spatial_selection (spatial_vtk.visualize.selection.FigureSpatialSelection | dict[str, object] | None, optional) – Optional function argument. Defaults to
None.spatial_kwargs (object) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.trends.plot_phase_delay_vs_distance(df: DataFrame, output_path: str | Path | None = None, *, delay_col: str = 'value', distance_col: str = 'distance_km', **kwargs) Figure
Plot phase or travel-time delay against source-station distance.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.delay_col (str, optional) – Optional function argument. Defaults to
'value'.distance_col (str, optional) – Optional function argument. Defaults to
'distance_km'.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.trends.plot_residuals_vs_depth(df: DataFrame, output_path: str | Path | None = None, **kwargs) Figure
Plot residuals against event depth.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.trends.plot_residuals_vs_distance(df: DataFrame, output_path: str | Path | None = None, **kwargs) Figure
Plot residuals against source-station distance.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.trends.plot_residuals_vs_distance_and_depth(df: DataFrame, output_path: str | Path | None = None, *, distance_col: str = 'distance_km', depth_col: str = 'depth_km', residual_col: str = 'residual', metric_col: str = 'metric', group_col: str | None = 'metric', title: str = 'Residuals vs Distance and Depth', showfig: bool | None = None, savefig: bool | None = None, outpath: str | Path | None = None, fit_method: object = None, fit: object = None, lowess_frac: float = 0.65, spatial_selection: FigureSpatialSelection | dict[str, object] | None = None, **spatial_kwargs: object) Figure
Plot residual trends against distance and depth in one figure.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.distance_col (str, optional) – Optional function argument. Defaults to
'distance_km'.depth_col (str, optional) – Optional function argument. Defaults to
'depth_km'.residual_col (str, optional) – Optional function argument. Defaults to
'residual'.metric_col (str, optional) – Optional function argument. Defaults to
'metric'.group_col (str | None, optional) – Optional function argument. Defaults to
'metric'.title (str, optional) – Optional function argument. Defaults to
'Residuals vs Distance and Depth'.showfig (bool | None, optional) – Optional function argument. Defaults to
None.savefig (bool | None, optional) – Optional function argument. Defaults to
None.outpath (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.fit_method (object, optional) – Optional function argument. Defaults to
None.fit (object, optional) – Optional function argument. Defaults to
None.lowess_frac (float, optional) – Optional function argument. Defaults to
0.65.spatial_selection (spatial_vtk.visualize.selection.FigureSpatialSelection | dict[str, object] | None, optional) – Optional function argument. Defaults to
None.spatial_kwargs (object) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure
- spatial_vtk.metrics.plot.trends.plot_score_trends(df: DataFrame, output_path: str | Path | None = None, *, x_col: str = 'distance_km', score_col: str = 'score', **kwargs) Figure
Plot GOF scores against one numeric variable.
- Parameters:
df (pandas.DataFrame) – Required function argument.
output_path (str | pathlib.Path | None, optional) – Optional function argument. Defaults to
None.x_col (str, optional) – Optional function argument. Defaults to
'distance_km'.score_col (str, optional) – Optional function argument. Defaults to
'score'.kwargs (Any) – Additional keyword arguments passed to the function.
- Returns:
Return value produced by the function.
- Return type:
matplotlib.figure.Figure