### Download ShakeMap Grid Data Example (Python) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md This example demonstrates how to download ShakeMap grid.xml files for a specific geographical region and time frame using the libcomcat library. It utilizes bounding box coordinates, start and end times for the search. ```python getproduct shakemap "grid.xml" -d /home/user/newzealand -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 ``` -------------------------------- ### Retrieve Finite-Fault Input Files Example (Python) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md This example shows how to retrieve .inp files for the finite-fault product using libcomcat. It specifies bounding box coordinates, a date range, and a magnitude range to filter the search results. ```python getproduct finite-fault .inp -d ~/tmp/chile -b -76.509 -49.804 -67.72 -17.427 -s 2007-01-01 -e 2016-05-01 -m 6.5 9.9 ``` -------------------------------- ### Retrieve Moment Rate Function Files Example (Python) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md This example demonstrates retrieving .mr files for the finite-fault product with libcomcat. Similar to retrieving .inp files, it uses bounding box coordinates, a date range, and a magnitude range for filtering. ```python getproduct finite-fault .mr -d ~/tmp/chile -b -76.509 -49.804 -67.72 -17.427 -s 2007-01-01 -e 2016-05-01 -m 6.5 9.9 ``` -------------------------------- ### Download Scenario Shakemap Intensity Files Example (Python) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md This example illustrates how to download SCENARIO shakemap intensity.jpg files from the USGS Scenario server using libcomcat. It specifies bounding box coordinates for Northern California, a date range, magnitude range, and uses the --scenario flag. ```python %(prog)s shakemap-scenario intensity.jpg -b -123 -119 35 40 -s 2013-10-01 -e 2013-10-30 -m 0.0 9.9 --scenario -d ~/tmp/scenario ``` -------------------------------- ### Get event history with web output Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID and prints the HTML tables to standard output. Requires an event ID. ```bash geteventhist ci38572791 --web ``` -------------------------------- ### Get event history for a specific product type Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID, but limits the output to only a specified product type. Requires an event ID. ```bash geteventhist ci38572791 -p shakemap ``` -------------------------------- ### GET /event/{id}/products Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Retrieves specific product information associated with an earthquake event, supporting version and source filtering. ```APIDOC ## GET /event/{id}/products ### Description Retrieves Product objects for an event. Users can filter by product type, source network, and specific versioning logic. ### Method GET ### Endpoint /event/{id}/products ### Parameters #### Query Parameters - **type** (string) - Required - The product type (e.g., 'shakemap', 'phase-data'). - **source** (string) - Optional - The source network (default: 'preferred', options: 'all', 'us', 'ak', etc.). - **version** (string) - Optional - Version criteria (default: 'preferred', options: 'first', 'last', 'all'). ### Request Example `ci3144585.getProducts('phase-data', source='all', version='first')` ### Response #### Success Response (200) - **contents** (list) - List of files included in the product. - **source** (string) - The contributing source. - **version** (string) - Derived version number. #### Response Example [ { "source": "us", "version": "1", "update_time": "2014-11-07 00:54:47" } ] ``` -------------------------------- ### Retrieving and Inspecting Event Products in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb This Python code snippet shows how to use the `getProducts` method of a `DetailEvent` object to retrieve different versions and sources of a specific product (e.g., 'phase-data'). It demonstrates fetching the preferred product, all sources, and specific versions, and also how to get the number of available versions for a product. ```python ## Get 'preferred' phase-data product for the 'preferred' source preferred_product = ci3144585.getProducts('phase-data') print('Preferred product: %s\nThis always returns one product.' % preferred_product) ## Get 'preferred' phase-data product for 'all' sources all_product = ci3144585.getProducts('phase-data', source='all') print('Preferred version with all sources returns %s products: %s\n' % (len(all_product), all_product)) ## Get 'last' phase-data product for 'all' sources last_product = ci3144585.getProducts('phase-data', source='us', version='first') print('Last version with us sources returns %s products: %s\n' % (len(last_product), last_product)) ## Get the number of versions of the phase-data product num_versions = ci3144585.getNumVersions('phase-data') print('There are %s versions.' % num_versions) ``` -------------------------------- ### Interact with SummaryEvent Object Methods in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Illustrates the usage of several methods available on a SummaryEvent object. It shows how to check for the existence of specific products ('shakemap') and properties ('station'), retrieve the event's detail URL, get the corresponding DetailEvent object, and convert the event's properties to a dictionary. ```python ## Check for product product = earthquake.hasProduct('shakemap') print('Includes "shakemap" as a product: %s' % product) ## Check for property prop = earthquake.hasProperty('station') print('Includes "station" as a property: %s' % prop) ## Get URL url = earthquake.getDetailURL() print('Event URL: %s' % url) ## Get DetailEvent detail = earthquake.getDetailEvent() print('DetailEvent: %s' % detail) ## Get dictionary event_dict = earthquake.toDict() print('Event Dictionary: %s' % event_dict) ``` -------------------------------- ### GET /phases Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Dataframes.ipynb Retrieves a dataframe containing phase arrival data for an earthquake event. ```APIDOC ## GET /phases ### Description Provides detailed phase arrival information, including residuals, weights, and station/agency data. ### Method GET ### Endpoint get_phase_dataframe(detail, catalog) ### Parameters #### Request Body - **detail** (DetailEvent) - Required - The event object. - **catalog** (string) - Optional - Source catalog (default: 'preferred'). ### Response #### Success Response (200) - **Dataframe** (pandas.DataFrame) - Contains Channel, Distance, Azimuth, Phase, Arrival Time, Status, Residual, Weight, and Agency columns. ``` -------------------------------- ### Get event history for a specific event ID to a directory (Excel) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID and saves the output to a specified directory in Excel format. Requires an event ID. ```bash geteventhist ci38572791 -d ./output_dir -f excel ``` -------------------------------- ### Get event history and split descriptions Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID and splits descriptions of single-product queries into separate columns. Outputs in default CSV format. Requires an event ID. ```bash geteventhist ci38572791 --split ``` -------------------------------- ### GET /events/{id}/products Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves detailed product-specific metadata, such as ShakeMap properties, for a specific earthquake event. ```APIDOC ## GET /events/{id}/products ### Description Fetches specific product data like ShakeMaps or PAGER reports associated with a unique event identifier. ### Method GET ### Parameters #### Path Parameters - **id** (string) - Required - The unique event identifier (e.g., 'us2000ar20'). ### Response #### Success Response (200) - **products** (list) - List of available products with associated properties (e.g., maxmmi, process-timestamp). ``` -------------------------------- ### Get event history for a specific event ID (CSV) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID. Outputs the summary in CSV format. Requires an event ID. ```bash geteventhist ci38572791 -f csv ``` -------------------------------- ### Count Matching Events with libcomcat Source: https://github.com/usgs/libcomcat/blob/master/docs/api.md Provides an example of using the `count` function from libcomcat to determine the number of earthquake events that match specific criteria. The input parameters for `count` are identical to those used by the `search` method. ```python from libcomcat.search import count # Count events matching certain criteria (criteria not specified in example) event_count = count() ``` -------------------------------- ### Get Phase Dataframe with Manual Picks Source: https://github.com/usgs/libcomcat/blob/master/notebooks/PhasesAndMagnitudes.ipynb Retrieves seismic phase arrival data for a given event and filters it to include only manual picks. It also cleans the 'Channel' column by removing '--'. ```python usframe = get_phase_dataframe(detail, catalog='us') usframe = usframe[usframe['Status'] == 'manual'] usframe['Channel'] = usframe['Channel'].str.replace('--','') # note that the line below merely prints the sorted dataframe, ``` -------------------------------- ### Load and Inspect DataFrame with Pandas Source: https://github.com/usgs/libcomcat/blob/master/notebooks/AssociatingCatalogues.ipynb This snippet demonstrates how to load a CSV file into a pandas DataFrame and then display the DataFrame. It assumes the 'pandas' library is installed and the 'datafile' variable contains the path to the CSV. The output is the DataFrame itself, showing its structure and initial rows. ```python import pandas as pd datafile = 'path/to/your/data.csv' # Replace with your actual file path dataframe = pd.read_csv(datafile) dataframe ``` -------------------------------- ### Get Pager Summaries with getpager Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md The `getpager` script summarizes estimated exposures and losses for seismic events. It saves this information to a specified spreadsheet file, with CSV as the default format. An option `--get-countries` is available to break out country-specific data. Dependencies include the libcomcat library. ```bash getpager events.csv ``` -------------------------------- ### Command Line Tools for Data Retrieval (Bash) Source: https://context7.com/usgs/libcomcat/llms.txt Provides a set of command-line utilities for quick access to earthquake data. These tools allow users to find event IDs, download catalogs in CSV format, retrieve magnitude and phase arrival data, get PAGER results, access event history, and download specific products like ShakeMaps. ```bash # Find event ID closest to time/location findid -e 2019-07-15T10:39:32 35.932 -117.715 # Get all nearby event IDs with expanded search window findid -e 2019-07-15T10:39:32 35.932 -117.715 -a -r 200 -w 120 -o events.csv # Download earthquake catalog as CSV getcsv -s 2020-01-01 -e 2020-12-31 -m 4.0 -o earthquakes_2020.csv # Get magnitude data for specific event getmags -i us2000ar20 -o magnitudes.csv # Get phase arrival data getphases -i us2000ar20 -o phases.csv # Download PAGER results getpager -i us2000ar20 -f excel -o pager_results.xlsx # Get event history with product updates geteventhist -i us2000ar20 -o history.csv # Download ShakeMap grid file getproduct -i us2000ar20 shakemap grid.xml -o shakemap_grid.xml ``` -------------------------------- ### Get event history excluding specific products Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Summarizes the history of event products for a given event ID, excluding specified products. Outputs in default CSV format. Requires an event ID. ```bash geteventhist ci38572791 --exclude-products dyfi ``` -------------------------------- ### Set Event Offset in libcomcat Search Source: https://github.com/usgs/libcomcat/blob/master/docs/api.md Illustrates how to use the `offset` parameter in the libcomcat search method to retrieve events starting from a specific position in the results. An offset of 2, for example, will return events starting from the second event found. ```python from libcomcat.search import search # Retrieve events starting from the second event second_event = search(offset=2) ``` -------------------------------- ### Download event info with preferred moment tensors (Excel) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads basic event information and expands the results to include preferred moment tensors. Outputs data in Excel format. ```bash getcsv nz.xlsx --get-moment-components preferred -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f excel ``` -------------------------------- ### Download event info with all moment tensors (Excel) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads basic event information and expands the results to include all available moment tensors. Outputs data in Excel format. ```bash getcsv nz.xlsx --get-moment-components all -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f excel ``` -------------------------------- ### Accessing Product Content and Metadata Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Demonstrates how to retrieve and inspect the list of available content files within a product object. ```python print('Shakemap Contents: %s' % product.contents) ``` -------------------------------- ### GET /event/{id} Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Retrieves comprehensive details for a specific earthquake event by its unique ID. ```APIDOC ## GET /event/{id} ### Description Fetches an earthquake event object based on the provided event ID. This object contains metadata, location data, and access to associated products. ### Method GET ### Endpoint /event/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique earthquake event identifier (e.g., 'ci3144585'). ### Request Example `get_event_by_id('ci3144585')` ### Response #### Success Response (200) - **id** (string) - Earthquake ID - **magnitude** (float) - Earthquake magnitude - **time** (datetime) - Event occurrence time - **products** (list) - List of available product types #### Response Example { "id": "ci3144585", "magnitude": 6.6, "location": "Northridge, California", "products": ["shakemap", "phase-data"] } ``` -------------------------------- ### Retrieving and Displaying Product Images Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Shows how to fetch raw byte data for a specific image file within a product and render it using Matplotlib and PIL. ```python img = product.getContentBytes('intensity.jpg')[0] image = Image.open(io.BytesIO(img)) plt.figure(figsize=(10, 12)) plt.imshow(np.asarray(image)) plt.show() ``` -------------------------------- ### GET /magnitude Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Dataframes.ipynb Retrieves a dataframe of amplitude, period, and magnitude data for a specific catalog and type. ```APIDOC ## GET /magnitude ### Description Organizes amplitude, period, and magnitude observations recorded at stations for a given earthquake catalog. ### Method GET ### Endpoint get_magnitude_data_frame(eventid, catalog, magtype) ### Parameters #### Request Body - **eventid** (string) - Required - The COMCAT event ID. - **catalog** (string) - Required - Source catalog (e.g., 'us', 'ak', 'preferred'). - **magtype** (string) - Required - Magnitude type (e.g., 'mb', 'ml'). ### Response #### Success Response (200) - **Dataframe** (pandas.DataFrame) - Contains Channel, Amplitude, Period, Status, Magnitude, and Weight columns. ``` -------------------------------- ### GET /pager Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Dataframes.ipynb Retrieves population exposure estimates for an earthquake event based on PAGER data. ```APIDOC ## GET /pager ### Description Organizes PAGER earthquake impact information, including total population exposure and exposure by country. ### Method GET ### Endpoint get_pager_data_frame(detail, get_losses, get_country_exposures, get_all_version) ### Parameters #### Request Body - **detail** (DetailEvent) - Required - The event object. - **get_losses** (bool) - Optional - Include predicted fatalities/monetary losses. - **get_country_exposures** (bool) - Optional - Include shaking exposures per country. - **get_all_version** (bool) - Optional - Fetch all PAGER product versions. ### Response #### Success Response (200) - **Dataframe** (pandas.DataFrame) - Contains id, location, time, latitude, depth, magnitude, country, pager_version, and MMI 1-10 intensity exposures. ``` -------------------------------- ### GET /history Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Dataframes.ipynb Retrieves a dataframe containing the history of products associated with a specific earthquake event. ```APIDOC ## GET /history ### Description Retrieves a dataframe tracking the record of products for an earthquake event over time. Include superseded events to view the full product history. ### Method GET ### Endpoint get_history_data_frame(detail, products) ### Parameters #### Request Body - **detail** (DetailEvent) - Required - The event object retrieved via ID. - **products** (list) - Optional - Specific ComCat products to include (e.g., ['dyfi', 'shakemap']). ### Response #### Success Response (200) - **Dataframe** (pandas.DataFrame) - Contains columns: Update Time, Product, Authoritative Event ID, Code, Associated, Product Source, Product Version, Elapsed (min), URL, Comment, Description. ``` -------------------------------- ### Download basic event info and moment tensors for New Zealand (CSV) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads basic event information (time, lat, lon, depth, magnitude) and moment tensor components for a specified geographic box and time range. Outputs data in CSV format. ```bash getcsv nz.csv -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f csv ``` -------------------------------- ### Accessing and Listing Product Properties in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb This Python snippet illustrates how to obtain a specific product (e.g., 'shakemap') from a `DetailEvent` object and then iterate through its properties. It shows how to access individual property values using dictionary-like access with the square bracket notation `product[prop]`. ```python product = ci3144585.getProducts('shakemap')[0] ## list the product properties for prop in product.properties: print('%s: %s' % (prop, product[prop])) ``` -------------------------------- ### Download event info with all magnitudes (CSV) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads event information including all magnitudes (source and type). Outputs data in CSV format. ```bash getcsv nz.csv --get-moment-components -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 --get-all-magnitudes -f csv ``` -------------------------------- ### GET /events/search Source: https://context7.com/usgs/libcomcat/llms.txt Searches for events based on complex criteria including PAGER alert levels, significance, and review status. ```APIDOC ## GET /events/search ### Description Retrieves a list of earthquake events based on advanced filtering options such as PAGER alerts or product availability. ### Method GET ### Parameters #### Query Parameters - **alertlevel** (string) - Optional - PAGER alert level (e.g., 'orange', 'red'). - **producttype** (string) - Optional - Required product (e.g., 'shakemap'). - **reviewstatus** (string) - Optional - The review status of the event. - **minsig** (int) - Optional - Minimum significance value. ### Request Example search(updatedafter=datetime(2024, 1, 1), minmagnitude=5.0, alertlevel='red') ### Response #### Success Response (200) - **events** (list) - A list of event objects containing metadata and location details. ``` -------------------------------- ### GET /events/count Source: https://context7.com/usgs/libcomcat/llms.txt Counts the number of earthquakes matching specified search criteria without retrieving the full event datasets. ```APIDOC ## GET /events/count ### Description Provides a count of events that satisfy the provided temporal, spatial, and magnitude filters. ### Method GET ### Parameters #### Query Parameters - **starttime** (datetime) - Required - The starting date/time for the search. - **endtime** (datetime) - Required - The ending date/time for the search. - **minmagnitude** (float) - Optional - Minimum earthquake magnitude. - **minlatitude/maxlatitude** (float) - Optional - Latitude boundaries. - **minlongitude/maxlongitude** (float) - Optional - Longitude boundaries. ### Request Example count(starttime=datetime(2020, 1, 1), endtime=datetime(2021, 1, 1), minmagnitude=3.0) ### Response #### Success Response (200) - **count** (int) - The number of events matching the criteria. ``` -------------------------------- ### Download event info with preferred focal angles (Excel) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads basic event information and expands the results to include preferred focal angles. Outputs data in Excel format. ```bash getcsv nz.xlsx --get-focal-angles preferred -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f excel ``` -------------------------------- ### Download event info with all focal angles (Excel) Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads basic event information and expands the results to include all available focal angles. Outputs data in Excel format. ```bash getcsv nz.xlsx --get-focal-angles all -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f excel ``` -------------------------------- ### Inspect DataFrame Columns and Rows Source: https://github.com/usgs/libcomcat/blob/master/notebooks/EventHistory.ipynb This snippet demonstrates how to inspect the contents of the downloaded DataFrame. `len(dataframe)` shows the total number of product entries, and `dataframe.head()` displays the first five rows and all columns. This is crucial for understanding the structure and initial data present in the DataFrame. ```python print(len(dataframe)) dataframe.head() ``` -------------------------------- ### Download events with fractional days using ISO 8601 Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Downloads events, supporting fractional days by using the ISO 8601 combined date time format. Covers the entire globe. ```bash getcsv tmp.csv -s 2015-01-01T00:00:00 -e 2015-01-01T01:15:00 -b -180 180 -90 90 ``` -------------------------------- ### Download Earthquake Product Files with Python Source: https://context7.com/usgs/libcomcat/llms.txt Accesses and saves associated products for a seismic event, such as ShakeMap grid XML files or QuakeML data. Supports both file-based saving and byte-stream retrieval. ```python from libcomcat.search import get_event_by_id # Get event and access its products detail = get_event_by_id('us2000ar20') # Download ShakeMap grid if detail.hasProduct('shakemap'): shakemap_products = detail.getProducts('shakemap', source='preferred') shakemap = shakemap_products[0] # Download grid.xml file url = shakemap.getContent('grid.xml', 'shakemap_grid.xml') print(f"Downloaded ShakeMap grid from: {url}") # Get content as bytes data, source_url = shakemap.getContentBytes('info.json') info_text = data.decode('utf-8') print(f"Info JSON content: {info_text[:200]}...") # Download origin QuakeML if detail.hasProduct('origin'): origin = detail.getProducts('origin', source='preferred')[0] origin.getContent('quakeml.xml', 'origin_quakeml.xml') print("Downloaded origin QuakeML") ``` -------------------------------- ### Search for Earthquake and Display SummaryEvent Properties in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb Demonstrates how to use the `search` method from libcomcat to find earthquake events based on geographic location and time. It then prints key properties of the first returned SummaryEvent object, such as ID, time, magnitude, and depth. ```python earthquake = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, orderby='magnitude', limit=1)[0] print("%s occurred on %s with a magnitude of %s and depth of %s" % (earthquake.id, earthquake.time, earthquake.magnitude, earthquake.depth)) ``` -------------------------------- ### Get Event History with geteventhist Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md The `geteventhist` command retrieves a summary spreadsheet of products for a given event. It supports various output formats like Excel and allows filtering by product type, exclusion of specific products, and splitting columns into separate files. Dependencies include the libcomcat library. ```bash geteventhist ci38457511 -d ~/tmp/ridgecrest -f excel ``` ```bash geteventhist ci38457511 -d ~/tmp/ridgecrest -f excel --exclude-products dyfi ``` ```bash geteventhist ci38457511 -d ~/tmp/ridgecrest -f excel --split ``` ```bash geteventhist ci38457511 -d ~/tmp/ridgecrest -f excel -p origin shakemap ``` ```bash geteventhist ci38457511 -d ~/tmp/ridgecrest -f excel -p origin shakemap --split ``` ```bash geteventhist ci38996632 -p origin --web --split > ~/test.html ``` -------------------------------- ### Search Earthquake Events by Magnitude in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Search.ipynb Demonstrates how to search for earthquake events within a specified bounding box and order them by magnitude using the `search` function. It then visualizes the magnitudes of the retrieved events. Requires `datetime` and `matplotlib.pyplot`. ```python from datetime import datetime import matplotlib.pyplot as plt from libcomcat.search import search box_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, orderby='magnitude') magnitude = [e.magnitude for e in box_events] fig, ax = plt.subplots(figsize=(8, 5)) # note we must use plt.subplots, not plt.subplot ax.plot(range(len(magnitude)), magnitude, '-.') ax.set_xlabel(r'Event Number', fontsize=14) ax.set_ylabel(r'Magnitude (M)', fontsize=14) ax.set_title('Events Ordered by Magnitude\nwithin the Bounding Box', fontsize=16) plt.show() ``` -------------------------------- ### Get Event Details and Magnitudes (Python) Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves detailed information for a specific earthquake event and extracts all available magnitude data. It processes the detail data into a pandas DataFrame and prints columns containing magnitude information, filtering out missing values. ```python from libcomcat.search import get_event_by_id, get_detail_data_frame import pandas as pd # Get detailed event detail = get_event_by_id('us2000ar20') # Extract all magnitudes df = get_detail_data_frame( [detail], get_all_magnitudes=True, get_tensors='none', get_focals='none' ) # Print all magnitude columns mag_cols = [col for col in df.columns if 'magnitude' in col.lower()] for col in mag_cols: if pd.notna(df[col].iloc[0]): print(f"{col}: {df[col].iloc[0]}") ``` -------------------------------- ### Get NEIC Magnitude DataFrame using Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/PhasesAndMagnitudes.ipynb Retrieves a pandas DataFrame containing NEIC magnitudes for seismic events. It requires a DetailEvent object, catalog type ('us'), and magnitude type ('ml'). The resulting DataFrame is then cleaned to remove '--' from the 'Channel' column and sorted by 'Channel'. ```python usmagframe = get_magnitude_data_frame(detail, 'us', 'ml') usmagframe['Channel'] = usmagframe['Channel'].str.replace('--','') usmagframe.sort_values('Channel') ``` -------------------------------- ### Initialize Notebook Environment and Imports Source: https://github.com/usgs/libcomcat/blob/master/notebooks/AssociatingCatalogues.ipynb Configures the Jupyter notebook for inline plotting and imports necessary standard and third-party libraries including pandas, numpy, and the libcomcat associate function. ```python %matplotlib inline from datetime import datetime import pandas as pd import numpy as np from libcomcat.dataframes import associate ``` -------------------------------- ### Retrieve Phase Arrival Data Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves phase arrival times and station information for a specific earthquake event. It utilizes `get_event_by_id` and `get_phase_dataframe` from libcomcat. The function takes an event ID as input and returns a DataFrame of phase arrivals, which can then be filtered, for example, to select P-wave arrivals. ```python from libcomcat.search import get_event_by_id from libcomcat.dataframes import get_phase_dataframe # Get event details detail = get_event_by_id('us2000ar20') # Extract phase arrivals try: phase_df = get_phase_dataframe(detail, catalog='preferred') print(f"Retrieved {len(phase_df)} phase arrivals") print(phase_df.head()) # Columns: Channel, Distance, Azimuth, Phase, Arrival Time, # Status, Residual, Weight, Agency # Filter for P-wave arrivals p_waves = phase_df[phase_df['Phase'].str.startswith('P')] print(f"P-wave arrivals: {len(p_waves)}") except Exception as e: print(f"No phase data available: {e}") ``` -------------------------------- ### Import Libraries for libcomcat Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Search.ipynb Imports necessary libraries for using libcomcat, including datetime for time-based searches, matplotlib.pyplot for plotting, and specific functions from libcomcat.search. ```python # stdlib imports from datetime import datetime # Third party imports import matplotlib.pyplot as plt # Local imports from libcomcat.search import count, get_event_by_id, search ``` -------------------------------- ### Accessing Event Products in Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Classes.ipynb This snippet demonstrates how to retrieve an earthquake event by its ID and then access and print its associated products using the libcomcat Python library. It highlights the use of the `get_event_by_id` function and accessing the `products` attribute of the event object. ```python ci3144585 = get_event_by_id('ci3144585'); print("The products in for the event, '%s', include: %s" % (ci3144585.id, ci3144585.products)) ``` -------------------------------- ### Get All Magnitude Types for an Event Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves all magnitude determinations from different sources for a specific earthquake event. This function uses `get_event_by_id` and `get_detail_data_frame`. The `get_detail_data_frame` function returns a DataFrame containing various magnitude types and their associated values, providing a comprehensive view of magnitude estimates for the event. ```python from libcomcat.search import get_event_by_id from libcomcat.dataframes import get_detail_data_frame # The code to demonstrate getting all magnitude types is not provided in the input text, but this is the function signature. # Example usage would involve calling get_event_by_id and then get_detail_data_frame. ``` -------------------------------- ### Get Regional Magnitude DataFrame using Python Source: https://github.com/usgs/libcomcat/blob/master/notebooks/PhasesAndMagnitudes.ipynb Retrieves a pandas DataFrame containing regional magnitudes for seismic events. Similar to the NEIC magnitude retrieval, this function requires a DetailEvent object, catalog type ('regional'), and magnitude type ('ml'). The 'Channel' column is cleaned, and the DataFrame is sorted by 'Channel'. ```python regmagframe = get_magnitude_data_frame(detail, regional, 'ml') regmagframe['Channel'] = regmagframe['Channel'].str.replace('--','') regmagframe.sort_values('Channel') ``` -------------------------------- ### Set up Matplotlib for Inline Plots Source: https://github.com/usgs/libcomcat/blob/master/notebooks/PhasesAndMagnitudes.ipynb Configures Matplotlib to display plots directly within the output of a script or notebook. ```python %matplotlib inline ``` -------------------------------- ### Get Earthquake Magnitude Information Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves station magnitude measurements for a given earthquake event using `get_event_by_id` and `get_magnitude_data_frame`. The function takes an event ID and optionally a catalog name. It returns a DataFrame of magnitude measurements which can be used to calculate average magnitudes of specific types, like local magnitude (ml). ```python from libcomcat.search import get_event_by_id from libcomcat.dataframes import get_magnitude_data_frame # Get event details detail = get_event_by_id('ci38457511') # Extract magnitude data try: mag_df = get_magnitude_data_frame(detail, catalog='preferred') print(f"Retrieved {len(mag_df)} magnitude measurements") print(mag_df.head()) # Columns: Channel, Type, Amplitude, Period, Status, # Magnitude, Weight, Distance, Azimuth # Calculate average local magnitude ml_mags = mag_df[mag_df['Type'] == 'ml'] if len(ml_mags) > 0: avg_ml = ml_mags['Magnitude'].mean() print(f"Average ML: {avg_ml:.2f}") except Exception as e: print(f"No magnitude data available: {e}") ``` -------------------------------- ### Define Constants for Earthquake Association Source: https://github.com/usgs/libcomcat/blob/master/notebooks/AssociatingCatalogues.ipynb Sets up the file path for the source catalogue and defines time constants in seconds to facilitate tolerance calculations during the association process. ```python datafile = '../tests/data/sample_catalogue.csv' DMINUTE = 60 DHOUR = 3600 DDAY = 86400 ``` -------------------------------- ### Get DYFI Intensity Data Source: https://context7.com/usgs/libcomcat/llms.txt Retrieves community intensity reports from the "Did You Feel It?" (DYFI) product for an earthquake event. It uses `get_event_by_id` and `get_dyfi_data_frame`. The function checks for the 'dyfi' product and can fetch data at a specified resolution (e.g., 'utm_1km'). The output DataFrame contains station information and intensity reports, allowing analysis of the highest reported intensities. ```python from libcomcat.search import get_event_by_id from libcomcat.dataframes import get_dyfi_data_frame # Get event with DYFI data detail = get_event_by_id('ci38457511') if detail.hasProduct('dyfi'): # Get DYFI data at 1km resolution (if available) dyfi_df = get_dyfi_data_frame(detail, dyfi_file='utm_1km') print(f"Retrieved {len(dyfi_df)} DYFI stations") print(dyfi_df.head()) # Columns: station, lat, lon, distance, intensity, nresp # Find highest intensity reports max_intensity = dyfi_df['intensity'].max() high_intensity = dyfi_df[dyfi_df['intensity'] >= max_intensity - 0.5] print(f"Maximum CDI: {max_intensity:.1f}") print(f"Locations with CDI >= {max_intensity - 0.5:.1f}:") print(high_intensity[['station', 'intensity', 'nresp']]) else: print("No DYFI product available") ``` -------------------------------- ### Import and Export Seismic Event DataFrames Source: https://github.com/usgs/libcomcat/blob/master/notebooks/ComparingMagnitudes.ipynb Handles the persistence of event data by reading from or writing to Excel spreadsheets to avoid lengthy re-downloads. ```python tablefile = './data/events.xlsx' if 'dataframe' not in vars(): dataframe = pd.read_excel(tablefile) else: dataframe.to_excel(tablefile, index=False) ``` -------------------------------- ### Download Event History DataFrame using ComCat ID Source: https://github.com/usgs/libcomcat/blob/master/notebooks/EventHistory.ipynb This function downloads a summary DataFrame of all products associated with a given ComCat ID. It uses `get_event_by_id` to fetch event details and `get_history_data_frame` to create the DataFrame. This is useful for analyzing the history of products for a specific earthquake event. ```python from libcomcat.dataframes import get_history_data_frame, split_history_frame, PRODUCTS from libcomcat.search import get_event_by_id history_event = get_event_by_id('ci38457511', includesuperseded=True) dataframe, event = get_history_data_frame(history_event) ``` -------------------------------- ### Import Necessary Libraries for libcomcat Source: https://github.com/usgs/libcomcat/blob/master/notebooks/PhasesAndMagnitudes.ipynb Imports essential libraries for data manipulation, seismic data processing, and plotting, including pandas, numpy, obspy, and custom libcomcat modules. ```python # Third party imports import matplotlib import matplotlib.pyplot as plt import numpy as np from obspy.io.quakeml.core import Unpickler import pandas as pd # Local imports from libcomcat.dataframes import get_phase_dataframe, get_magnitude_data_frame from libcomcat.search import get_event_by_id ``` -------------------------------- ### Search Earthquake Events by Location (Bounding Box) using libcomcat Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Search.ipynb Illustrates how to perform a bounding box search for earthquake events by specifying minimum and maximum latitude and longitude using the `search` function. It prints the number of events found within the specified geographical area. ```python box_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364) print("Bounding Box returned %s events" % len(box_events)) ``` -------------------------------- ### Generate Phase Dataframe Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Dataframes.ipynb Retrieves phase arrival data for a given event, organizing it into a DataFrame. This function requires a DetailEvent object and optionally accepts a source catalog. The output DataFrame includes channel, distance, azimuth, phase, arrival time, status, residual, weight, and agency information. ```python phase_event = get_event_by_id('us70005nie') phase_df = get_phase_dataframe(phase_event) display(HTML(phase_df.to_html())) ``` -------------------------------- ### Count events and max supported events in a query Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md Prints the number of events that would be returned from a query and the maximum number of events supported by a single ComCat query. Does not output event data to a file. ```bash getcsv tmp.csv -x --get-moment-components -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 ``` -------------------------------- ### Order Events by Magnitude or Time in libcomcat Source: https://github.com/usgs/libcomcat/blob/master/docs/api.md Shows how to order search results by magnitude or time using the `orderby` parameter in libcomcat. Results can be sorted in descending order by default (e.g., 'magnitude', 'time') or ascending order by appending '-asc' (e.g., 'magnitude-asc', 'time-asc'). ```python from libcomcat.search import search # Order events by magnitude (descending) magnitude_events = search(orderby='magnitude') # Order events by magnitude (ascending) magnitude_ascending_events = search(orderby='magnitude-asc') # Order events by time (descending) time_events = search(orderby='time') # Order events by time (ascending) time_ascending_events = search(orderby='time-asc') ``` -------------------------------- ### Visualize seismic event depth evolution by network Source: https://github.com/usgs/libcomcat/blob/master/notebooks/EventHistory.ipynb This script iterates through a DataFrame of seismic origins, plotting depth versus elapsed time. It dynamically maps unique network sources to distinct colors and creates a legend using custom circular patches. ```python fig = plt.figure(figsize=(12,8)) colors = ['r','b','g','k','m'] nets = origin_frame['Product Source'].unique().tolist() labels = {} for idx, row in origin_frame.iterrows(): netidx = nets.index(row['Product Source']) color = colors[netidx] line = plt.plot(row['Elapsed (min)'],row['Depth'], mfc=color,mec='k',marker='.', ms=24) if color not in labels: labels[color] = nets[netidx] patches = [] for color, network in labels.items(): tpatch = mpatches.Circle(xy=(0,0),color=color, label=network, ec='k') patches.append(tpatch) plt.legend(handles=patches); plt.title('Evolution of Network Depths'); plt.xlabel('Elapsed Time (min)'); ``` -------------------------------- ### Summarize Magnitudes with getmags Source: https://github.com/usgs/libcomcat/blob/master/docs/cli.md The `getmags` script summarizes epicenter and magnitude information, saving it to a specified file. It allows filtering by geographic bounds, time range, and magnitude range. The output format can be CSV, tab-delimited, or Excel. Dependencies include the libcomcat library. ```bash getmags nz.csv -b 163.213 -178.945 -48.980 -32.324 -s 2013-01-01 -e 2014-01-01 -f csv ``` ```bash getmags recent.csv 2015-01-01T00:00:00 -e 2015-01-01T01:15:00 ``` -------------------------------- ### Visualize seismic data using Matplotlib Source: https://github.com/usgs/libcomcat/blob/master/notebooks/ComparingMagnitudes.ipynb Configures and displays Matplotlib charts, including scatter plots, histograms, and axes customization. These snippets use the pyplot interface to visualize statistical relationships and distributions from seismic datasets. ```python plt.axes([minmag,maxmag,minmag,maxmag]); plt.axis('square'); plt.xlabel(reg_type, fontsize=14); plt.ylabel(us_type, fontsize=14); plt.text(minmag, maxmag, 'N=%i' % N, fontsize=14); sdate = stime.strftime('%b %d, %Y') edate = etime.strftime('%b %d, %Y') fmt = '%s vs. %s (%s to %s)' plt.title(fmt % (reg_type, us_type, sdate, edate), fontsize=16); ``` ```python fig = plt.figure(figsize=(8,6)); plt.hist(distances, bins=10); plt.xlabel('LD-US Location Distance', fontsize=14); xmin,xmax,ymin,ymax = plt.axis(); xpos = xmax - (xmax-xmin)/10 ypos = ymax - (ymax-ymin)/10 plt.text(xpos,ypos,'N=%i' % len(distances), fontsize=14); plt.title('LD vs US Locations', fontsize=16); ``` ```python plt.figure(figsize=(8,6)); regcol = 'ld-depth' uscol = 'us-depth' ddepth = locdf[uscol] - locdf[regcol] plt.plot(locdf['ld-ml'],ddepth,'b.'); plt.xlabel('ld-ml', fontsize=14); plt.ylabel('US depth - LD depth', fontsize=14); plt.title('Depth Difference vs LD-ML', fontsize=16); ``` -------------------------------- ### Python: Search Earthquakes by Magnitude, Alert Level, Significance, and CDI Source: https://github.com/usgs/libcomcat/blob/master/notebooks/Search.ipynb Demonstrates how to use the 'search' function in Python to filter earthquake events based on magnitude, alert level, significance, and Community Determined Intensity (CDI). It also includes plotting functionalities to visualize the search results and bounding box. Requires the 'comcat' library and 'matplotlib'. ```python from libcomcat import search from datetime import datetime import matplotlib.pyplot as plt # Example using the bounding box option and limited by magnitude and Intensity # Magnitude mag_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, minmagnitude=4, maxmagnitude=8) print("Magnitude returned %s events" % len(mag_events)) # Alert Level alert_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, alertlevel="green") print("Alert level returned %s events" % len(alert_events)) # Significance significance_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, minsig=10, maxsig=20) print("Significance returned %s events" % len(significance_events)) # CDI cdi_events = search(starttime=datetime(1994, 1, 17, 12, 30), endtime=datetime(1994, 1, 18, 12, 35), minlatitude=34.1, maxlatitude=34.3, minlongitude=-118.742, maxlongitude=-118.364, mincdi=5, maxcdi=7) print("CDI returned %s events" % len(cdi_events)) # Plotting (assuming event_lon and event_lat are defined elsewhere or extracted from events) # For demonstration, let's assume we have these lists from mag_events, significance_events # In a real scenario, you would extract these from the search results. event_lon = [e.longitude for e in mag_events] event_lat = [e.latitude for e in mag_events] fig, ax = plt.subplots(figsize=(8, 5)) # note we must use plt.subplots, not plt.subplot equake_scatter = ax.scatter(event_lon, event_lat, color='y', label="All Events") # Placeholder for 'All Events' bb = ax.plot([-118.742, -118.364, -118.364, -118.742, -118.742], [34.1, 34.1, 34.3, 34.3, 34.1], label='Bounding Box') circle1 = plt.Circle((-118.537, 34.213), 0.02, color='m', fill=False, label='Radius ($^o$)') # This circle is defined but not added to the plot mag_scatter = ax.scatter([e.longitude for e in mag_events], [e.latitude for e in mag_events], color='m', label='Magnitude: 4-9') sig_scatter = ax.scatter([e.longitude for e in significance_events], [e.latitude for e in significance_events], color='g', label='Significance: 10-20') ax.set_xlabel(r'Longitude ($^o$)', fontsize=14) ax.set_ylabel(r'Latitude ($^o$)', fontsize=14) ax.legend(handles=[bb[0], quake_scatter, mag_scatter, sig_scatter], fontsize=12, loc=4) ax.set_title('Searches Limited by Magnitude and Intensity', fontsize=16) plt.show() ```