pyshake package¶
Submodules¶
pyshake.catalog module¶
Catalog module.
- pyshake.catalog.alert_accuracy(reports, references, MMIcountry='Costa Rica', Mtypes='Mfd, MVS', Mmin=5.5, Lmin=0.8, Dmin=0.1, MMImin=4, ipm=<class 'pyshake.gm.gmm'>, stationmin=2, final=False)[source]¶
Evaluates the accuracy of earthquake reports by comparing their alert parameters (from the event first solution over alerting criteria) with the corresponding reference values based on the input reference catalog of seismic event source parameters.
The alert parameters (maximal shaking intensity, MMI) are inferred from the source parameters and the alerting parameters (Mmin, Lmin, MMImin, MMIcountry, ipm, and Mtypes) provided as options.
- Parameters:
reports (
dict) – A dictionary of EEW reports with reference solutions as provided bypyshake.catalog.matchreports().references (
pandas.DataFrame) – The reference catalog of seismic events as provided bypyshake.catalog.getref()to find events missing from reports.MMIcountry (
str) – The country for which the maximal Modified Mercalli Intensity (MMI) is calculated.Mtypes (
str) – The comma-separated list of types of magnitudes that are considered for alerting in the event reports.Mmin (
float, optional) – The minimum magnitude threshold for an earthquake event to be considered in the analysis.Lmin (
float, optional) – The minimum likelihood value for a seismic event reports to be considered in the analysis.stationmin (
int, optional) – The minimum number of station magnitude contributions for a seismic event reports to be considered in the analysis.Dmin (
float, optional) – The minimum allowable difference in longitude and latitude values when comparing locations.MMImin (
float, optional) – The minimum value of the Modified Mercalli Intensity (MMI) that an earthquake must reach to be considered in the evaluation.ipm (
pyshake.gm.gmm, optional) – A prediction model to calculate the shaking intensity of a seismic event based on the country distance and magnitude of the event. Seepyshake.gm.final (
bool, optional) – If True, only the final event solutions are considered for the analysis.
- Returns:
Four dictionaries with magnitude type keys include EEW and reference source parameters of Tp (true positives), Fp (false positives), Fn (false negatives), and bounds.
- Return type:
- pyshake.catalog.chronology(reports=None, references=None, TFpn=None, ax=None, title=None, subtitle=False, cmaps={'MVS': 'winter', 'Mfd': 'autumn', 'None': None}, colorbar=True, rightside=False, cax=None, legendsize=True, lax=None, xml=True, arrivalrank=4, arrivalF=False, legendsizenum=4, legend_marker_size=70, legend_marker_alpha=0.6666666666666666, hlegend_line_length=1, annotation=None, alphathreshold=70, eventlines=True, **options)[source]¶
Run
pyshake.catalog.alert_accuracy()(supporting all its related parameters) and generate a chronology plot.- Parameters:
reports (
dict) – A dictionary of EEW reports with reference solutions as provided bypyshake.catalog.matchreports().references (
pandas.DataFrame) – The reference catalog of seismic events as provided bypyshake.catalog.getref()to find events missing from reports.TFpn (
tuple, optional) – Pre-computer event classification as provided bypyshake.catalog.alert_accuracy(), making table output faster.
- Returns:
The table of false events that can be viewed with
print()ordisplay().- Return type:
matplotlib.DataFrame
- pyshake.catalog.eew_report2dict(files='.seiscomp/EEW_reports/*txt')[source]¶
Reads earthquake early warning (EEW) report files from a specified file-path pattern, and returns a dictionary of the extracted information. It supports the following formats:
Tdiff |Type|Mag.|Lat. |Lon. |Depth |origin time (UTC) |Lik.|Or.|Ma.|Str.|Len. |Author |Creation t. |Tdiff(current o.) ------------------------------------------------------------------------------------------------------------------------------------------ 80.60| MVS|3.42| 15.00| -92.89| 5.00|2019-09-24T20:21:01.06Z|0.99| 8| 4| | |scvsmag@s|2019-09-24T20:22:21.66Z| 80.60 Mag.|Lat. |Lon. |tdiff |Depth |creation time (UTC) |origin time (UTC) |likeh.|#st.(org.) |#st.(mag.) ------------------------------------------------------------------------------------------------------------------ 5.15| 10.31| -86.27| 47.14| 10.00|2017-03-17T10:32:56.1282Z|2017-03-17T10:32:08.9848Z| 0.30| 19| 7
- Parameters:
files (
str) – A string that represents the file path pattern for the EEW report files to be processed.- Returns:
A dictionary where the keys are event identifiers (from file paths of EEW report files from the specified file path pattern), and the values are dictionaries representing the contents of the EEW reports.
- Return type:
- pyshake.catalog.errors(reports=None, references=None, TFpn=None, ax=None, title=None, subtitle=False, cmaps={'MVS': 'winter', 'Mfd': 'autumn'}, colorbar=True, rightside=False, cax=None, legendsize=True, lax=None, final=False, **options)[source]¶
Run
pyshake.catalog.alert_accuracy()(supporting all its related parameters) and generate a location and magnitude error histogram.- Parameters:
reports (
dict) – A dictionary of EEW reports with reference solutions as provided bypyshake.catalog.matchreports().references (
pandas.DataFrame) – The reference catalog of seismic events as provided bypyshake.catalog.getref()to find events missing from reports.TFpn (
tuple, optional) – Pre-computer event classification as provided bypyshake.catalog.alert_accuracy(), making table output faster.
- Returns:
The table of false events that can be viewed with
print()ordisplay().- Return type:
matplotlib.DataFrame
- pyshake.catalog.event_eew_mag(events, MMIcountry='Costa Rica', Mtypes='Mfd, MVS', Mmin=5.5, Lmin=0.8, MMImin=4, ipm=<class 'pyshake.gm.gmm'>, debug=False)[source]¶
Evaluates alert parameters (from the event first solution over alerting criteria) on the input catalog of seismic event source parameters.
The alert parameters (maximal shaking intensity, MMI) are inferred from the source parameters and the alerting parameters (Mmin, Lmin, MMImin, MMIcountry, ipm, and Mtypes) provided as options.
- Parameters:
events (
obspy.core.event.Catalog) – The reference catalog of seismic events.MMIcountry (
str) – The country for which the maximal Modified Mercalli Intensity (MMI) is calculated.Mtypes (
str) – The comma-separated list of types of magnitudes that are considered for alerting in the event reports.Mmin (
float, optional) – The minimum magnitude threshold for an earthquake event to be considered in the analysis.Lmin (
float, optional) – The minimum likelihood value for a seismic event reports to be considered in the analysis.Dmin (
float, optional) – The minimum allowable difference in longitude and latitude values when comparing locations.MMImin (
float, optional) – The minimum value of the Modified Mercalli Intensity (MMI) that an earthquake must reach to be considered in the evaluation.ipm (
pyshake.gm.gmm, optional) – A prediction model to calculate the shaking intensity of a seismic event based on the country distance and magnitude of the event. Seepyshake.gm.
- Returns:
First event magnitudes exceeding the alert thresholds.
- Return type:
- pyshake.catalog.get_eventindex(url, method='pandas', **opt)[source]¶
Rapid event index list from FDSN web service. Uses the event FDSN web-service, returns the list of events.
from pyshake.catalog import get_eventindex get_eventindex('http://eida.ethz.ch', limit=100)
- Parameters:
url – The fdsnws base url (e.g. ‘http://eida.ethz.ch’).
method – ‘pandas’ or ‘obspy’ defines whether the event list should returned as a
pandas.DataFrameor aobspy.core.event.Catalog.
Note
Any additional keyword arguments will be passed to the web-service as additional arguments. Passing any non-default parameters that the web-service does not support will raise an error.
- Returns:
The list of events.
- Return type:
pandas.DataFrameorobspy.core.event.Catalog
- pyshake.catalog.getref(reports, url='USGS', kind='us', dt=240, dla=1.5, dlo=1.5, f=None, names=[], sep=',')[source]¶
Retrieves earthquake event data based on the input EEW report time-period and area, and returns the corresponding earthquake catalog.
- Parameters:
reports (
dict) – A dictionary of EEW reports as provided bypyshake.catalog.eew_report2dict()orpyshake.catalog.reportfilter().url (
str, optional) – The source FDSN web service URL for retrieving reference earthquake reports (seeobspy.clients.fdsn).kind (
str, optional) – The type of web service to use for retrieving earthquake data. The following are implemented: sc (SeisComP implementation of FDSN web service), or us (USGS implementation of FDSN web service)dt (
float, optional) – The time window in seconds that is added before and after the event origin times for querying seismic events FDSN web service.dla (
float, optional) – The latitude range in degrees that is added and subtracted to the event latitudes for querying seismic events FDSN web service.dlo (
float, optional) – The latitude range in degrees that is added and subtracted to the event latitudes for querying seismic events FDSN web service.
- Returns:
A reference catalog of seismic events covering the time-period and the area of the input catalog.
- Return type:
- pyshake.catalog.map(reports, references, TFpn=None, rightside=True, top=False, title=None, fig=None, ax=None, figsize=(8, 8), legendsize=True, legendsizenum=4, legendloc=None, legendfaults=True, subtitle=False, colorbar=True, bg=True, **options)[source]¶
Run
pyshake.catalog.alert_accuracy()(supporting all its related parameters) and generate the map of results, including legends and title with specified options.- Parameters:
reports (
dict) – A dictionary of EEW reports with reference solutions as provided bypyshake.catalog.matchreports().references (
pandas.DataFrame) – The reference catalog of seismic events as provided bypyshake.catalog.getref()to find events missing from reports.TFpn (
tuple, optional) – Pre-computer event classification as provided bypyshake.catalog.alert_accuracy(), making table output faster.rightside (
bool, optional) – Determines whether the legend should be displayed on the right side of the plot or not (left side).title (
str, optional) – Provide a descriptive title for the map.fig (
matplotlib.figure.Figure, optional) – Specify the figure object where the map will be plotted.ax (
matplotlib.axes.Axes, optional) – Specify the axe object where the map will be plotted.figsize (
tuple, optional) – Specify the size of the figure (width, height) that will be created for the plot. Seematplotlib.figure.Figure.legendsize (
bool, optional) – Whether the legend should include the event size scale.legendfaults (
bool, optional) – Whether the legend should include the fault types.
- Returns:
The matplotlib axis where the plots have been created
- Return type:
- pyshake.catalog.matchreports(reports, cat, maxhypocentraldist=150, maxtimediff=100, v=4.4)[source]¶
Compares earthquake reports with a reference catalog using event sources parameters to find matching events within the specified maximum hypocentral distance and origin time difference.
- Parameters:
reports (
dict) – A dictionary of EEW reports as provided bypyshake.catalog.eew_report2dict()orpyshake.catalog.reportfilter().cat – The reference catalog of seismic event as provided by
pyshake.catalog.getref()maxhypocentraldist (
float, optional) – The maximum hypocentral distance in kilometers allowed between two seismic events to be considered as possibly matching.maxtimediff (
float, optional) – The maximum time difference in seconds allowed between the origin times of two seismic events to be considered as possibly matching.v (
float, optional) – The average seismic velocity used in the calculation of reduced event distance based on their origin time difference.
- Type:
- Returns:
The dictionary of EEW reports updated with the reference source parameters from the matching reference seismic events.
- Return type:
- pyshake.catalog.reportfilter(reports, countrycodes='ni', dthresh=1.4)[source]¶
Filters out reports based on specified country codes and distance threshold, removing duplicate locations and empty reports.
- Parameters:
reports (
dict) – A dictionary of EEW reports as provided bypyshake.catalog.eew_report2dict().countrycodes (
str, optional) – A string that specifies the country code or codes to filter the reports by. By default, it is set to ‘ni’, which represents the country code for Nicaragua.dthresh (
float, optional) – The distance threshold (in degrees) used to determine if a given (latitude and longitude) point is close enough to the specified country to be kept.
- Returns:
A filtered version of the input reports dictionary based on the specified criteria.
- Return type:
- pyshake.catalog.table(reports=None, references=None, TFpn=None, **options)[source]¶
Run
pyshake.catalog.alert_accuracy()(supporting all its related parameters) and generate a table of false events.- Parameters:
reports (
dict) – A dictionary of EEW reports with reference solutions as provided bypyshake.catalog.matchreports().references (
pandas.DataFrame) – The reference catalog of seismic events as provided bypyshake.catalog.getref()to find events missing from reports.TFpn (
tuple, optional) – Pre-computer event classification as provided bypyshake.catalog.alert_accuracy(), making table output faster.
- Returns:
The matplotlib axis where the plots have been created
- Return type:
pyshake.event module¶
Event module.
- pyshake.event.leadtimegrid(inventory, declust=0.01, min_station_number=4, target=[-90.535278, 14.613333], depth=5, dlat=0.1, dlon=0.1, dmax=3, flat_latency={'*': 3, 'GT*': 5, 'GT-altac.*': 1.0, 'GT-rsn2.*': 1.0, 'SV*': 2, 'SV.*.00.HN*': 1.0}, resampling=1, kmtodeg=111.19492664455873, Vp=5.5, ttt={'p': <scipy.interpolate._interpolate.interp1d object>, 's': <scipy.interpolate._interpolate.interp1d object>})[source]¶
Calculates the EEW delays for a grid of event locations based on station coordinates and other parameters.
- Parameters:
inventory (
obspy.core.inventory.inventory.Inventory) – The instrument metadata inventory, which contains information about the seismic stations in the networkdeclust – The declust parameter is the clustering distance in degrees. It determines the maximum distance between two stations for them to be considered part of the same cluster. Stations within the clustering distance will be grouped together and only one station from each cluster will be used in the calculations
min_station_number – The min_station_number parameter is the minimum number of required stations for the calculation. It specifies the minimum number of stations that need to detect an earthquake in order for the calculation to be performed. If the number of stations that detect the earthquake is less than min_station_number, the calculation will, defaults to 4 (optional)
target – The target parameter is the coordinates of the target location where you want to calculate the EEW delays. In this case, the target location is set to Guatemala City with latitude -90.535278 and longitude 14.613333
depth – The depth parameter represents the depth of the earthquake events in kilometers, defaults to 5 (optional)
dlat – The parameter dlat represents the latitude increment used to create a grid of latitude values. It determines the spacing between adjacent latitude values in the grid
dlon – The parameter dlon represents the longitude increment used to create a grid of longitude values. It determines the spacing between adjacent longitude values in the grid
dmax – The parameter dmax represents the maximum distance in degrees from the network that will be considered for calculating the EEW delays, defaults to 3 (optional)
flat_latency – The flat_latency parameter is a dictionary that specifies the flat latency values for different station names or patterns. The keys in the dictionary are station names or patterns, and the values are the corresponding flat latency values. The flat latency is the delay in seconds that is added to the EEW delay for
resampling – The resampling parameter determines the resampling factor for the EEW delays. It controls the spacing between the grid points in the output EEW delays. A value of 1 means no resampling, while a value greater than 1 will result in a coarser grid with larger spacing between, defaults to 1 (optional)
kmtodeg – The parameter “kmtodeg” is a conversion factor used to convert distances in kilometers to degrees. It is calculated as 2 times the product of the Earth’s radius (6371 km) and pi divided by 360. This conversion factor is used in the calculations of distances between stations and source grid nodes
Vp – Vp is the P-wave velocity, which is the speed at which P-waves travel through the Earth’s crust. It is used to calculate the travel time of seismic waves from the event location to the target location
ttt – The parameter ttt is an object of the tttinterp class, which is used for interpolating travel times.
- Return type:
function- Returns:
three values: longitudes, latitudes, and EEW delays.
- Return type:
- pyshake.event.leadtimes(inventory, catalog, target, declust=0.01, min_station_number=4, mtodeg=111194.92664455873, model='iasp91', debug=False)[source]¶
Compute Earthquake Early Warning (EEW) lead times.
Each EEW lead time is defined for a given seismic event and EEW target. It is assumed as the delay between the arrival of the P-wave at the 4th closest station to the event and the arrival of the S-wave at the EEW target. However, in practice, EEW is required before the shaking at the EEW target exceeds the threshold for damage, which can be different from the S-wave arrival.
from obspy.clients.fdsn.client import Client inv = Client('ETH').get_stations(level='channel') cat = Client('ETH').get_events(limit=1,orderby='magnitude',maxdepth=10000) from pyshake.event import leadtime leadtimes(inv, cat, target=[8.54690,47.37850])
- Parameters:
inventory (
obspy.core.inventory.inventory.Inventory) – The instrument metadata inventory.catalog (
obspy.core.event.Catalog) – The seismic event catalog.target (
listoffloat) – The EEW target coordinates (longitude, latitude).declust (
float) – Clustering threshold in degrees for station coordinates. Default is 0.01 degrees.min_station_number (
int) – Minimum number of required stations. Default is 4.mtodeg (
float) – Conversion factor from kilometers to degrees. Default is calculated based on Earth’s radius.model (
str) – Time travel tables used for P-wave and S-wave travel times. Default is provided.debug (
bool) – A boolean flag to enable/disable debug output. The default value is False.
- Returns:
EEW lead time (in seconds) for each event in the catalog.
- Return type:
numpy.ndarray
pyshake.gm module¶
Ground motion model module.
pyshake.plotting module¶
Plotting utility module.
- pyshake.plotting.bmap(bounds=[-89, -83, 8, 14], figsize=(5, 5), rightside=True, top=False, fig=None, ax=None, legendfaults=True, bg=True, label_style={'path_effects': [<matplotlib.patheffects.withStroke object>], 'size': 'small'})[source]¶
- pyshake.plotting.mapcities(bmap, cities={'Guatemala City': [14.62778, -90.5152], 'Managua': [12.12801, -86.29536], 'San Jose': [9.94456, -84.11525], 'San Salvador': [13.70178, -89.21693]}, optcities={'color': 'k', 'fontsize': 'x-small', 'zorder': 9999999999}, optcitydot={'markeredgecolor': 'w', 'markeredgewidth': 0.8, 'markerfacecolor': 'none', 'zorder': 9999999999}, **opt)[source]¶
- pyshake.plotting.mapfaults(ax, url='https://raw.githubusercontent.com/GEMScienceTools/gem-global-active-faults/master/geojson/gem_active_faults_harmonized.geojson', fallback_label='Active faults', linestyle_str=[(0, (3, 1, 1, 1, 1, 1)), ':', '-.', '--'], legendfaults=True, **opt)[source]¶
pyshake.util module¶
Misc utility module.
- pyshake.util.eventcountrydistance(countryname, events, res=1, defaultdepth=5, defaultepd=2, quickndirty=False)[source]¶
Compute the distance from given hypocenter(s) to given country.
In case the hypocenter is within the country, the output distance is taken from hypocenter depth (default to 5 km).
from obspy.clients.fdsn.client import Client cat = Client('ETH').get_events(limit=1,orderby='magnitude',maxdepth=10000) from pyshake.util import eventcountrydistance events = [[ e.preferred_origin().longitude, e.preferred_origin().latitude, e.preferred_origin().depth/1000 ] for e in cat] countrydists = eventcountrydistance(country, events)
- pyshake.util.eventdistance(la, lo, de, refla, reflo, refde, v=1, meters=800)[source]¶
The function eventdistance calculates the distance between two geographical coordinates, taking into account the depth of the locations if provided.
- Parameters:
la – Latitude of the first location.
la –
floatlo – Longitude of the first location.
lo –
floatde – Depth of the first location (set to None if unknown).
de –
floatrefla – Latitude of the second location.
refla –
floatreflo – Longitude of the second location.
reflo –
floatrefde – Depth of the second location (set to None if unknown).
refde –
floatv – Divider of the horizontal distance output in case depth is unknown.
v –
floatmeters – If the absolute value of the depth (de or refde) is greater than this threshold, the function assumes that the depth is in kilometers instead of meters.
meters –
float
- Returns:
The distance in kilometers between the two geographical coordinates.
- Return type:
- pyshake.util.haversine(lon1, lat1, lon2, lat2, r=6371)[source]¶
Calculate the great circle distance between two points on the earth (specified in decimal degrees)
- pyshake.util.inv2coord(inventory, declust=0.01, flat_latency={'*': 0})[source]¶
Returns the list of stations latitudes and longitudes, omiting old stations being too close to another one
- pyshake.util.isincountries(la, lo, countrycodes, dthresh=1.4)[source]¶
The function isincountries checks if a given latitude and longitude pair is within a specified distance threshold of any country in a list of ISO2 country codes. The function uses the geopip library to determine the country code for the given coordinates
- Parameters:
- Returns:
The function will return True if the coordinates are within any of the specified countries, and False otherwise.
- Return type:
- pyshake.util.polygonthreshold(polygon, countryname='Switzerland', minintensity=4, mineventdepth=1, minepicentraldistance=1, groundmotionmodel=<class 'pyshake.gm.gmm'>, quickndirty=False, **kwargs)[source]¶
The function polygonthreshold calculates the minimum magnitude of an earthquake required to reach a given shaking intensity level anywhere inside a given country.
from pyshake.util import polygonthreshold # a polygon over Zurich polygon=[(8,47), (9,47), (9,47.5), (8,47.5)] # the minimum magnitude to reach MMI 3 in Switzerland # from any event in the polygon over Zurich # `s = 0` : No amplification polygonthreshold(polygon, countryname = 'Switzerland', minintensity = 3, s = 0) # 0.97 # the minimum magnitude to reach MMI 3 in Italy # from any event in the polygon over Zurich # `s = 1` : An amplification of 1 intensity unit polygonthreshold(polygon, countryname = 'Italy', minintensity = 3, s = 1) # 3.99
- Parameters:
polygon (
listofliste.g., [[lo1,la1],[lo2,la2]].) – The polygon parameter is a set of coordinates that define the shape of the polygon. It is used to determine if the event intersects with the specified countrycountryname (
str) – The name of the country where the intensity is evaluated. The default value is ‘Switzerland’, defaults to Switzerland (optional)minintensity (
float) – The minimum intensity threshold for the polygon. Any earthquake with an intensity below this threshold will not be considered, defaults to 4 (optional)mineventdepth (
float) – The mineventdepth parameter represents the depth of the event in kilometers. It is used to calculate the distance between the event and the polygon, defaults to 1 (optional)minepicentraldistance (
float) – The parameter “minepicentraldistance” represents the minimum epicentral distance in kilometers. It is used in the calculation of the distance between the event and the country, defaults to 1 (optional)groundmotionmodel (
pyshake.gm.gmm) – The groundmotionmodel parameter is a function that calculates the intensity of ground motion given the distance and magnitude of an earthquake. In this code, it is set to gmm.gm, which is a reference to a default ground motion model function by Allen et al. (2012)quickndirty (
bool) – The parameter “quickndirty” is a boolean flag that determines whether a quick and dirty calculation should be used for the distance calculation if the event is outside the specified country. If set to True, the shapely distance between the event and the country will be used, which can be very incorrect, defaults to False (optional)
- Returns:
the minimum magnitude of an earthquake that would produce a ground motion intensity greater than or equal to the specified minimum intensity, given the parameters and inputs provided.
- Return type:
- pyshake.util.ssh_event(sshuserhost='user@host', dbplugin='dbmysql', db='localhost/seiscomp3', opt='-fma', seiscomp='', eventid=None, minlatitude=-90, maxlatitude=90, minlongitude=-180, maxlongitude=180, minmagnitude=0, maxmagnitude=10, mintime=UTCDateTime(2026, 4, 8, 6, 15, 33, 107209), maxtime=UTCDateTime(2026, 4, 8, 7, 15, 33, 107225))[source]¶
- pyshake.util.tttinterp(model='iasp91', depth=5, ttt={'p': <scipy.interpolate._interpolate.interp1d object>, 's': <scipy.interpolate._interpolate.interp1d object>}, dmax=3)[source]¶
Return the dict of interpolants for p and s-phase travel times modeling at any distance such as: time = ttt[phases](dist)