API Reference

Models

Data models for earthquake data.

class seismoalert.models.Earthquake(id, time, latitude, longitude, depth, magnitude, place, url)[source]

Represents a single earthquake event.

Parameters:
id

Unique event identifier from USGS.

time

Event timestamp (UTC).

latitude

Epicenter latitude in degrees.

longitude

Epicenter longitude in degrees.

depth

Hypocentral depth in kilometers.

magnitude

Event magnitude.

place

Human-readable location description.

url

USGS event detail URL.

id: str
time: datetime
latitude: float
longitude: float
depth: float
magnitude: float
place: str
url: str
classmethod from_geojson_feature(feature)[source]

Create an Earthquake from a USGS GeoJSON feature.

Parameters:

feature (dict) – A single GeoJSON feature dict from USGS API response.

Return type:

Earthquake

Returns:

An Earthquake instance.

class seismoalert.models.EarthquakeCatalog(earthquakes=<factory>)[source]

A collection of earthquake events with filtering and sorting helpers.

Parameters:

earthquakes (list[Earthquake])

earthquakes

List of Earthquake objects.

earthquakes: list[Earthquake]
classmethod from_geojson(geojson)[source]

Parse a USGS GeoJSON response into an EarthquakeCatalog.

Parameters:

geojson (dict) – Full GeoJSON FeatureCollection from the USGS API.

Return type:

EarthquakeCatalog

Returns:

An EarthquakeCatalog containing all parsed events.

filter_by_magnitude(min_mag=None, max_mag=None)[source]

Return a new catalog filtered by magnitude range.

Parameters:
  • min_mag (float | None) – Minimum magnitude (inclusive).

  • max_mag (float | None) – Maximum magnitude (inclusive).

Return type:

EarthquakeCatalog

Returns:

Filtered EarthquakeCatalog.

filter_by_depth(min_depth=None, max_depth=None)[source]

Return a new catalog filtered by depth range.

Parameters:
  • min_depth (float | None) – Minimum depth in km (inclusive).

  • max_depth (float | None) – Maximum depth in km (inclusive).

Return type:

EarthquakeCatalog

Returns:

Filtered EarthquakeCatalog.

sort_by_time(reverse=False)[source]

Return a new catalog sorted by event time.

Parameters:

reverse (bool) – If True, sort newest first.

Return type:

EarthquakeCatalog

Returns:

Sorted EarthquakeCatalog.

sort_by_magnitude(reverse=True)[source]

Return a new catalog sorted by magnitude.

Parameters:

reverse (bool) – If True (default), sort largest first.

Return type:

EarthquakeCatalog

Returns:

Sorted EarthquakeCatalog.

property magnitudes: list[float]

List of all magnitudes in the catalog.

property max_magnitude: float | None

Maximum magnitude in the catalog, or None if empty.

Client

USGS Earthquake API client.

exception seismoalert.client.USGSClientError[source]

Raised when the USGS API returns an error.

class seismoalert.client.USGSClient(base_url='https://earthquake.usgs.gov/fdsnws/event/1/query', timeout=30, max_retries=3)[source]

Client for the USGS Earthquake Hazards Program API.

Parameters:
  • base_url (str) – API endpoint URL.

  • timeout (int) – Request timeout in seconds.

  • max_retries (int) – Number of retries on transient failures.

fetch_earthquakes(starttime=None, endtime=None, min_magnitude=None, max_magnitude=None, min_depth=None, max_depth=None, limit=1000)[source]

Fetch earthquake data from the USGS API.

Parameters:
  • starttime (datetime | None) – Start of time window (defaults to 24 hours ago).

  • endtime (datetime | None) – End of time window (defaults to now).

  • min_magnitude (float | None) – Minimum magnitude filter.

  • max_magnitude (float | None) – Maximum magnitude filter.

  • min_depth (float | None) – Minimum depth in km.

  • max_depth (float | None) – Maximum depth in km.

  • limit (int) – Maximum number of events to return.

Return type:

EarthquakeCatalog

Returns:

EarthquakeCatalog with fetched events.

Raises:

USGSClientError – If the API returns an error response.

Analyzer

Statistical analysis of earthquake catalogs.

class seismoalert.analyzer.GutenbergRichterResult(a_value, b_value, mc)[source]

Result of a Gutenberg-Richter law fit.

The G-R law states: log10(N) = a - b * M where N is the number of events >= magnitude M.

Parameters:
a_value

Productivity parameter (log10 of total event rate).

b_value

Slope of the frequency-magnitude distribution.

mc

Magnitude of completeness used for the fit.

a_value: float
b_value: float
mc: float
class seismoalert.analyzer.AnomalyPeriod(start_index, end_index, event_count, expected_count, sigma_deviation)[source]

Represents a detected anomalous seismicity period.

Parameters:
  • start_index (int)

  • end_index (int)

  • event_count (int)

  • expected_count (float)

  • sigma_deviation (float)

start_index

Start index in the time-sorted catalog.

end_index

End index in the time-sorted catalog.

event_count

Number of events in the window.

expected_count

Expected number of events based on the mean rate.

sigma_deviation

Number of standard deviations above the mean.

start_index: int
end_index: int
event_count: int
expected_count: float
sigma_deviation: float
seismoalert.analyzer.magnitude_of_completeness(catalog)[source]

Estimate the magnitude of completeness (Mc) using the max-curvature method.

The magnitude of completeness is the magnitude at which the frequency-magnitude distribution reaches its maximum, i.e., the most frequently occurring magnitude bin.

Parameters:

catalog (EarthquakeCatalog) – Earthquake catalog to analyze.

Return type:

float

Returns:

Estimated magnitude of completeness.

Raises:

ValueError – If catalog is empty.

seismoalert.analyzer.gutenberg_richter(catalog, mc=None)[source]

Fit the Gutenberg-Richter frequency-magnitude relation.

Uses the maximum likelihood estimate for b-value:

b = log10(e) / (M_mean - Mc)

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to analyze.

  • mc (float | None) – Magnitude of completeness. If None, estimated automatically.

Return type:

GutenbergRichterResult

Returns:

GutenbergRichterResult with a-value, b-value, and mc.

Raises:

ValueError – If catalog has insufficient data above Mc.

seismoalert.analyzer.interevent_times(catalog)[source]

Compute inter-event time intervals in seconds.

Parameters:

catalog (EarthquakeCatalog) – Earthquake catalog (will be sorted by time).

Return type:

ndarray

Returns:

Array of time differences in seconds between consecutive events.

Raises:

ValueError – If catalog has fewer than 2 events.

seismoalert.analyzer.detect_anomalies(catalog, window_days=7, threshold_sigma=2.0)[source]

Detect anomalous seismicity rate periods using a sliding window.

Compares event counts in each window to the overall mean rate. Windows with counts exceeding mean + threshold_sigma * std are flagged.

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to analyze.

  • window_days (int) – Sliding window size in days.

  • threshold_sigma (float) – Number of standard deviations for anomaly threshold.

Return type:

list[AnomalyPeriod]

Returns:

List of AnomalyPeriod objects for each detected anomaly.

seismoalert.analyzer.clustering_coefficient(catalog, radius_km=50.0, time_window_hours=72.0)[source]

Compute a spatio-temporal clustering coefficient.

Measures the fraction of event pairs that fall within a given spatial radius and time window.

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to analyze.

  • radius_km (float) – Spatial clustering radius in kilometers.

  • time_window_hours (float) – Temporal clustering window in hours.

Return type:

float

Returns:

Clustering coefficient between 0.0 and 1.0.

Alerts

Alert system for earthquake monitoring.

  1. Create rules

    ┌──────────────────────────────────────────┐ │ AlertRule(“Large Earthquake”, │ │ condition=large_earthquake_condition(6.0),│ │ template=”Max magnitude: M{max_mag}”) │ │ │ │ AlertRule(“High Rate”, │ │ condition=high_rate_condition(50), │ │ template=”{count} events detected”) │ └──────────────────────────────────────────┘

  2. Register with manager

    ┌──────────────────────────────────────────┐ │ AlertManager │ │ rules: [rule_1, rule_2] │ └──────────────────────────────────────────┘

  3. Evaluate against catalog

    ┌──────────────────────────────────────────┐ │ manager.evaluate(catalog) │ │ → rule_1: condition(catalog) → True │ │ → Alert(“Large Earthquake”, “M7.2”) │ │ → rule_2: condition(catalog) → False │ │ → None (skipped) │ └──────────────────────────────────────────┘

  4. Output: [Alert(“Large Earthquake”, “M7.2”)]

  5. Optionally send via stubs

    │ WebhookAlert.send(alert) → logs it EmailAlert.send(alert) → logs it

class seismoalert.alerts.Alert(rule_name, message)[source]

A triggered alert.

Parameters:
  • rule_name (str)

  • message (str)

rule_name

Name of the rule that triggered the alert.

message

Formatted alert message.

rule_name: str
message: str
class seismoalert.alerts.AlertRule(name, condition, message_template)[source]

A configurable alert rule.

Parameters:
name

Human-readable rule name.

condition

Callable that takes an EarthquakeCatalog and returns True if triggered.

message_template

Format string for the alert message. Receives the catalog as ‘catalog’.

name: str
condition: Callable[[EarthquakeCatalog], bool]
message_template: str
evaluate(catalog)[source]

Evaluate the rule against a catalog.

Parameters:

catalog (EarthquakeCatalog) – Earthquake catalog to check.

Return type:

Alert | None

Returns:

An Alert if the condition is met, None otherwise.

seismoalert.alerts.large_earthquake_condition(min_magnitude)[source]

Create a condition that triggers when any event exceeds a magnitude threshold.

Parameters:

min_magnitude (float) – Magnitude threshold.

Return type:

Callable[[EarthquakeCatalog], bool]

Returns:

Condition callable.

seismoalert.alerts.high_rate_condition(max_count)[source]

Create a condition that triggers when event count exceeds a threshold.

Parameters:

max_count (int) – Maximum event count before triggering.

Return type:

Callable[[EarthquakeCatalog], bool]

Returns:

Condition callable.

class seismoalert.alerts.AlertManager(rules=<factory>)[source]

Manages alert rules and evaluates them against earthquake catalogs.

Parameters:

rules (list[AlertRule])

rules

List of registered alert rules.

rules: list[AlertRule]
add_rule(rule)[source]

Register an alert rule.

Parameters:

rule (AlertRule) – AlertRule to add.

Return type:

None

evaluate(catalog)[source]

Evaluate all rules against a catalog.

Parameters:

catalog (EarthquakeCatalog) – Earthquake catalog to check.

Return type:

list[Alert]

Returns:

List of triggered Alert objects.

class seismoalert.alerts.WebhookAlert(webhook_url)[source]

Stub for sending alerts via webhook.

In a production system, this would POST to a webhook URL. Currently logs the payload for demonstration.

Parameters:

webhook_url (str) – Target URL for the webhook.

send(alert)[source]

Send an alert via webhook (stub).

Parameters:

alert (Alert) – The alert to send.

Return type:

None

class seismoalert.alerts.EmailAlert(recipient)[source]

Stub for sending alerts via email.

In a production system, this would send an actual email. Currently logs the email content for demonstration.

Parameters:

recipient (str) – Email recipient address.

send(alert)[source]

Send an alert via email (stub).

Parameters:

alert (Alert) – The alert to send.

Return type:

None

Visualizer

Visualization utilities for earthquake data.

seismoalert.visualizer.create_earthquake_map(catalog, output_path='earthquakes.html')[source]

Create an interactive Folium map of earthquake locations.

Each earthquake is represented as a circle marker with size proportional to magnitude and color indicating severity.

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to visualize.

  • output_path (str | Path) – Path for the output HTML file.

Return type:

Path

Returns:

Path to the saved HTML file.

seismoalert.visualizer.plot_magnitude_time(catalog, output_path='magnitude_time.png')[source]

Plot earthquake magnitude vs. time.

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to plot.

  • output_path (str | Path) – Path for the output image file.

Return type:

Path

Returns:

Path to the saved image file.

seismoalert.visualizer.plot_gutenberg_richter(catalog, a_value, b_value, output_path='gutenberg_richter.png', mc=None)[source]

Plot the Gutenberg-Richter frequency-magnitude distribution.

Shows observed cumulative event counts, the fitted G-R line, and optionally the magnitude of completeness (Mc).

Parameters:
  • catalog (EarthquakeCatalog) – Earthquake catalog to plot.

  • a_value (float) – G-R a-value (productivity).

  • b_value (float) – G-R b-value (slope).

  • output_path (str | Path) – Path for the output image file.

  • mc (float | None) – Magnitude of completeness. Drawn as a vertical dashed line if provided.

Return type:

Path

Returns:

Path to the saved image file.