### Start training PhaseNet model Source: https://ai4eps.github.io/PhaseNet Initiates training for the PhaseNet model using a pre-trained model. Specify training data, epochs, and batch size. Plotting is enabled for monitoring. ```python python phasenet/train.py --model_dir=model/190703-214543/ --train_dir=test_data/npz --train_list=test_data/npz.csv --plot_figure --epochs=10 --batch_size=10 ``` -------------------------------- ### Install Dependencies to Default Environment Source: https://ai4eps.github.io/PhaseNet Update the default Conda environment with the dependencies specified in env.yaml. ```bash conda env update -f=env.yaml -n base ``` -------------------------------- ### Get Phase Picks and Prediction Time Series from PhaseNet API Source: https://ai4eps.github.io/PhaseNet/example_fastapi Requests both phase picks and prediction probabilities (time series) from the PhaseNet API's /predict_prob endpoint. It then visualizes the Z-component waveform and the predicted P and S phase probabilities. ```python resp = requests.post(f'{PHASENET_API_URL}/predict_prob', json=req) print(resp) picks, preds = resp.json() preds = np.array(preds) print('Picks', picks) plt.figure() plt.subplot(211) plt.plot(data[:,-1], 'k', label="Z") plt.subplot(212) plt.plot(preds[0, :, 0, 1], label="P") plt.plot(preds[0, :, 0, 2], label="S") plt.legend() plt.show(); ``` -------------------------------- ### Predict with mseed format Source: https://ai4eps.github.io/PhaseNet Performs batch prediction on data in mseed format. Use --amplitude to get amplitude values. The batch size is set to 1 due to variable data lengths. ```python python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed.csv --data_dir=test_data/mseed --format=mseed --amplitude --response_xml=test_data/stations.xml --batch_size=1 --sampling_rate=100 ``` ```python python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed2.csv --data_dir=test_data/mseed --format=mseed --amplitude --response_xml=test_data/stations.xml --batch_size=1 --sampling_rate=100 ``` -------------------------------- ### Read Seismic Stream Source: https://ai4eps.github.io/PhaseNet/example_gradio Reads seismic waveform data into an ObsPy stream object and plots it. Ensure ObsPy is installed and data is accessible. ```python import obspy stream = obspy.read() stream.plot(); ``` -------------------------------- ### Download and Unzip Demo Data Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Navigate to the PhaseNet directory and download the test data zip file, then unzip it to prepare for batch prediction. ```bash cd PhaseNet wget https://github.com/wayneweiqiang/PhaseNet/releases/download/test_data/test_data.zip unzip test_data.zip ``` -------------------------------- ### Create and Activate 'phasenet' Environment for Mac ARM Source: https://ai4eps.github.io/PhaseNet For Mac ARM chips, create a Conda environment using env_mac.yaml and activate it. ```bash conda env create -f env_mac.yaml conda activate phasenet ``` -------------------------------- ### Create and Activate 'phasenet' Virtual Environment Source: https://ai4eps.github.io/PhaseNet Create a new Conda virtual environment named 'phasenet' and activate it. ```bash conda env create -f env.yaml conda activate phasenet ``` -------------------------------- ### Predict Phase Picks with PhaseNet Source: https://ai4eps.github.io/PhaseNet/example_gradio Initializes the Gradio client with the PhaseNet model and uses it to predict P/S-phase picks from the seismic data. Requires the Gradio client and the PhaseNet model to be accessible. ```python model = "ai4eps/phasenet" # model = "http://127.0.0.1:7860" client = Client(model, serialize=True) _, picks_csv, picks_json = client.predict(["data.mseed"], json.dumps(data.tolist()), json.dumps([data_id])) ``` -------------------------------- ### Import Libraries and Set Project Root Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Imports necessary libraries (pandas, json, os) and defines the project root directory for accessing results. ```python import pandas as pd import json import os PROJECT_ROOT = os.path.realpath(os.path.join(os.path.abspath(''), "..")) ``` -------------------------------- ### Load and Prepare Seismic Data with ObsPy Source: https://ai4eps.github.io/PhaseNet/example_fastapi Reads seismic data using ObsPy and prepares it for PhaseNet. It sorts the stream, asserts three components, extracts the waveform data, and formats metadata like station ID and timestamp. ```python import obspy stream = obspy.read() stream.plot(); ``` ```python ## Extract 3-component data stream = stream.sort() assert(len(stream) == 3) data = [] for trace in stream: data.append(trace.data) data = np.array(data).T assert(data.shape[-1] == 3) data_id = stream[0].get_id()[:-1] timestamp = stream[0].stats.starttime.datetime.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] ``` -------------------------------- ### Import Libraries Source: https://ai4eps.github.io/PhaseNet/example_gradio Imports necessary Python libraries for data handling, client interaction, and visualization. ```python from gradio_client import Client import obspy import numpy as np import json import pandas as pd import matplotlib.pyplot as plt import json ``` -------------------------------- ### Clone PhaseNet Repository Source: https://ai4eps.github.io/PhaseNet Clone the PhaseNet repository from GitHub to your local machine. ```bash git clone https://github.com/wayneweiqiang/PhaseNet.git cd PhaseNet ``` -------------------------------- ### Download Test Data Source: https://ai4eps.github.io/PhaseNet Downloads and unzips the test data required for prediction and training. ```bash wget https://github.com/wayneweiqiang/PhaseNet/releases/download/test_data/test_data.zip unzip test_data.zip ``` -------------------------------- ### Configure PhaseNet API URL Source: https://ai4eps.github.io/PhaseNet/example_fastapi Sets the URL for the PhaseNet API endpoint. Several options are commented out, with the active URL pointing to a hosted service. ```python # PHASENET_API_URL = "http://127.0.0.1:8000" # PHASENET_API_URL = "http://phasenet.quakeflow.com" ## gcp # PHASENET_API_URL = "http://test.quakeflow.com:8001" ## local machine PHASENET_API_URL = "https://ai4eps-eqnet.hf.space" # PHASENET_API_URL = "http://131.215.74.195:8001" ## local machine ``` -------------------------------- ### PhaseNet Predict Script Optional Arguments Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction This displays the available optional arguments for the `predict.py` script, including data input, model, output, and prediction parameters. ```bash usage: predict.py [-h] [--batch_size BATCH_SIZE] [--model_dir MODEL_DIR] [--data_dir DATA_DIR] [--data_list DATA_LIST] [--hdf5_file HDF5_FILE] [--hdf5_group HDF5_GROUP] [--result_dir RESULT_DIR] [--result_fname RESULT_FNAME] [--min_p_prob MIN_P_PROB] [--min_s_prob MIN_S_PROB] [--mpd MPD] [--amplitude] [--format FORMAT] [--s3_url S3_URL] [--stations STATIONS] [--plot_figure] [--save_prob] optional arguments: -h, --help show this help message and exit --batch_size BATCH_SIZE batch size --model_dir MODEL_DIR Checkpoint directory (default: None) --data_dir DATA_DIR Input file directory --data_list DATA_LIST Input csv file --hdf5_file HDF5_FILE Input hdf5 file --hdf5_group HDF5_GROUP data group name in hdf5 file --result_dir RESULT_DIR Output directory --result_fname RESULT_FNAME Output file --min_p_prob MIN_P_PROB Probability threshold for P pick --min_s_prob MIN_S_PROB Probability threshold for S pick --mpd MPD Minimum peak distance --amplitude if return amplitude value --format FORMAT input format --stations STATIONS seismic station info --plot_figure If plot figure for test --save_prob If save result for test ``` -------------------------------- ### Import Libraries for PhaseNet Source: https://ai4eps.github.io/PhaseNet/example_fastapi Imports necessary Python libraries for data manipulation, plotting, and API requests. Ensures the PhaseNet module is accessible. ```python import os, sys import numpy as np import matplotlib.pyplot as plt import obspy import requests sys.path.insert(0, os.path.abspath("../")) ``` -------------------------------- ### Visualize Waveforms and Picks Source: https://ai4eps.github.io/PhaseNet/example_gradio Generates plots for each seismic component, overlaying the waveform data with predicted P and S phase picks. The alpha value of the vertical lines represents the phase score. ```python fig, ax = plt.subplots(len(stream), 1, figsize=(10, 10)) for i, tr in enumerate(stream): ax[i].plot(tr.times(), tr.data, label=tr.stats.channel, c="k") for _, pick in picks.iterrows(): c = "blue" if pick["phase_type"] == "P" else "red" label = pick["phase_type"] if i == 0 else None ax[i].axvline((pick["phase_time"]-tr.stats.starttime.datetime).total_seconds(), c=c, label=label, alpha=pick["phase_score"]) ax[i].legend() ``` -------------------------------- ### Predict with seismic array format Source: https://ai4eps.github.io/PhaseNet Performs batch prediction on seismic array data, used by QuakeFlow. Requires station information. ```python python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed_array.csv --data_dir=test_data/mseed_array --stations=test_data/stations.json --format=mseed_array --amplitude ``` -------------------------------- ### Run Batch Prediction for mseed format Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Execute the PhaseNet prediction script for data in mseed format. Ensure the model and data paths are correctly specified. The `--plot_figure` argument can be removed for large datasets to improve performance. ```bash python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed.csv --data_dir=test_data/mseed --format=mseed --plot_figure ``` -------------------------------- ### Run Batch Prediction for seismic array (mseed_array format) Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Execute the PhaseNet prediction script for seismic array data in mseed_array format, specifying station information. The `--amplitude` flag is used for this format. The `--plot_figure` argument can be removed for large datasets to improve performance. ```bash python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed_array.csv --data_dir=test_data/mseed_array --stations=test_data/stations.json --format=mseed_array --amplitude ``` ```bash python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/mseed2.csv --data_dir=test_data/mseed --stations=test_data/stations.json --format=mseed_array --amplitude ``` -------------------------------- ### Predict P/S-Phase Picks using PhaseNet API Source: https://ai4eps.github.io/PhaseNet/example_fastapi Sends prepared seismic waveform data to the PhaseNet API's /predict endpoint to obtain P and S phase picks. It prints the HTTP response and the JSON response containing the picks. ```python req = {"id": [data_id], "timestamp": [timestamp], "vec": [data.tolist()]} resp = requests.post(f'{PHASENET_API_URL}/predict', json=req) print(resp) print('Picks', resp.json()) ``` -------------------------------- ### Run Batch Prediction for hdf5 format Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Execute the PhaseNet prediction script for data in hdf5 format. Ensure the model and data paths are correctly specified. The `--plot_figure` argument can be removed for large datasets to improve performance. ```bash python phasenet/predict.py --model=model/190703-214543 --hdf5_file=test_data/data.h5 --hdf5_group=data --format=hdf5 --plot_figure ``` -------------------------------- ### Predict with hdf5 format Source: https://ai4eps.github.io/PhaseNet Performs batch prediction on data in hdf5 format. Specify the hdf5 file and group name. ```python python phasenet/predict.py --model=model/190703-214543 --hdf5_file=test_data/data.h5 --hdf5_group=data --format=hdf5 ``` -------------------------------- ### Predict with sac format Source: https://ai4eps.github.io/PhaseNet Performs batch prediction on data in sac format. ```python python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/sac.csv --data_dir=test_data/sac --format=sac --batch_size=1 ``` -------------------------------- ### Read JSON Picks Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Loads seismic picks from a JSON file into a Python list of dictionaries. This format is often more structured for direct use. ```python with open(os.path.join(PROJECT_ROOT, "results/picks.json")) as fp: picks_json = json.load(fp) print(picks_json[1]) print(picks_json[0]) ``` -------------------------------- ### Run Batch Prediction for sac format Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Execute the PhaseNet prediction script for data in sac format. Ensure the model and data paths are correctly specified. The `--plot_figure` argument can be removed for large datasets to improve performance. ```bash python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/sac.csv --data_dir=test_data/sac --format=sac --plot_figure ``` -------------------------------- ### Write Stream to MSEED Source: https://ai4eps.github.io/PhaseNet/example_gradio Saves the seismic stream data to a MiniSEED file. This is useful for persistent storage or sharing. ```python stream.write("data.mseed", format="MSEED") ``` -------------------------------- ### Run Batch Prediction for numpy format Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Execute the PhaseNet prediction script for data in numpy format. Ensure the model and data paths are correctly specified. The `--plot_figure` argument can be removed for large datasets to improve performance. ```bash python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/npz.csv --data_dir=test_data/npz --format=numpy --plot_figure ``` -------------------------------- ### Read and Process CSV Picks Source: https://ai4eps.github.io/PhaseNet/example_batch_prediction Reads picks from a tab-separated CSV file and processes the index and probability columns, which are stored as strings representing lists. ```python picks_csv = pd.read_csv(os.path.join(PROJECT_ROOT, "results/picks.csv"), sep="\t") picks_csv.loc[:, 'p_idx'] = picks_csv["p_idx"].apply(lambda x: x.strip("[]").split(",")) picks_csv.loc[:, 'p_prob'] = picks_csv["p_prob"].apply(lambda x: x.strip("[]").split(",")) picks_csv.loc[:, 's_idx'] = picks_csv["s_idx"].apply(lambda x: x.strip("[]").split(",")) picks_csv.loc[:, 's_prob'] = picks_csv["s_prob"].apply(lambda x: x.strip("[]").split(",")) print(picks_csv.iloc[1]) print(picks_csv.iloc[0]) ``` -------------------------------- ### Predict with numpy format Source: https://ai4eps.github.io/PhaseNet Performs batch prediction on data in numpy format. ```python python phasenet/predict.py --model=model/190703-214543 --data_list=test_data/npz.csv --data_dir=test_data/npz --format=numpy ``` -------------------------------- ### Extract 3-Component Data Source: https://ai4eps.github.io/PhaseNet/example_gradio Sorts the seismic stream, asserts it contains exactly three components, and extracts the waveform data. It also prepares a data ID and timestamp. ```python stream = stream.sort() assert(len(stream) == 3) data = [] for trace in stream: data.append(trace.data) data = np.array(data).T assert(data.shape[-1] == 3) data_id = stream[0].get_id()[:-1] timestamp = stream[0].stats.starttime.datetime.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] ``` -------------------------------- ### Load Prediction Results Source: https://ai4eps.github.io/PhaseNet/example_gradio Parses the JSON output from the PhaseNet prediction into a pandas DataFrame for easier manipulation and analysis. ```python picks = pd.read_json(picks_json) # picks = pd.read_csv(csv, parse_dates=["phase_time"]) # print(picks) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.