Nlloc

Earthquake location tools using NonLinLoc.

Warning

The NonLinLoc (NLLoc) workflow in SeisMonitor is currently supported only on Ubuntu Linux systems. Other operating systems (Windows/macOS) are not officially tested and may fail due to system-level dependencies.

nlloc

class SeisMonitor.monitor.locator.nlloc.nlloc.NLLoc(core_path, agency, region, vel_model, stations, delta_in_km=2, kwargs_for_trans={}, kwargs_for_vel2grid={}, kwargs_for_grid2time={}, kwargs_for_time2loc={}, tmp_folder='/home/docs/checkouts/readthedocs.org/user_builds/seismonitor/checkouts/latest/docs/source', exhaustively=False, search_in_degrees=[], rm_attempts=False)[source]

Bases: object

NonLinLoc (NLLoc) seismic event locator.

This class provides an interface to the NonLinLoc algorithm for earthquake location using a 1D/3D velocity model and station geometry.

It wraps the full workflow including travel-time computation, grid building, and event location.

Args:

core_path: str

Path to the NonLinLoc installation directory.

agency: str

Agency name used in output event metadata.

region: list of float

Spatial search region defined as: [lon_min, lon_max, lat_min, lat_max, z_min, z_max]

Notes: - Longitude and latitude are in degrees - Depth (z) is in kilometers - Positive z corresponds to depth below sea level

vel_model: VelModel

Velocity model used for travel-time computation.

stations: Stations

Station metadata container.

delta_in_km: float, optional

Grid spacing in kilometers (default: 2).

kwargs_for_trans: dict, optional

Parameters for coordinate transformation.

kwargs_for_vel2grid: dict, optional

Parameters for Vel2Grid execution.

kwargs_for_grid2time: dict, optional

Parameters for Grid2Time execution.

kwargs_for_time2loc: dict, optional

Parameters for Time2Loc execution.

tmp_folder: str, optional

Directory used for temporary files and travel-time grids. Defaults to current working directory.

exhaustively: bool, optional

If True, performs multi-resolution grid search.

search_in_degrees: list, optional

Grid refinement levels in degrees (used when exhaustively=True).

rm_attempts: bool, optional

If True, removes intermediate attempt files after processing.

Attributes:

core_path: str

Path to the NonLinLoc core installation directory.

nlloc_paths: dict

Dictionary containing resolved executable paths for NLLoc components.

basic_inputs: LocatorBasicInputs

Container holding velocity model and station information used for location.

tmp_folder: str

Working directory used for temporary files and intermediate outputs.

Warning

  • Ensure that the region fully covers all stations, expected earthquake locations, and the velocity model extent. Pay special attention to the elevation range: 0 corresponds to sea level, negative values indicate below sea level, and positive values indicate above sea level.

  • The compute_travel_times method can be computationally expensive depending on grid resolution, spatial extent of the model, and number of stations. Large grids may also require significant memory and disk usage. Ensure adequate computational resources are available before execution.

compute_travel_times()[source]

Compute travel-time tables using the velocity model and station geometry.

This method runs the NLLoc workflow steps:

  • Vel2Grid: builds the velocity grid from the velocity model

  • Grid2Time: computes travel-time tables for all stations

The resulting travel-time grids are stored in self.tmp_folder.

Notes

This operation can be computationally expensive depending on:

  • Grid resolution

  • Spatial extent of the model

  • Number of stations

Large grids may also require significant memory and disk space.

Ensure adequate computational resources are available before execution.

Warning

This method may take a long time to complete for large domains or dense station networks.

locate(catalog, nlloc_out_folder, out_filename='locations.xml', out_format='SC3ML')[source]

Main location method with optional exhaustive search.

Parameters:
  • catalog (Union[Catalog, str]) – Input catalog or path

  • nlloc_out_folder (str) – Output directory

  • out_filename (str) – Output filename

  • out_format (str) – Output format

Return type:

Catalog

Returns:

Located event catalog

loc utils

Useful functions for earthquake location.

class SeisMonitor.monitor.locator.utils.LocatorBasicInputs(vel_model, stations)[source]

Bases: object

Container for basic inputs required by seismic location algorithms.

This class groups the minimum required components for a locator, including a velocity model and station metadata.

Parameters:
  • vel_model (VelModel) – Velocity model used for travel-time calculations.

  • stations (Stations) – Station metadata container.

vel_model

Stored velocity model.

Type:

VelModel

stations

Stored station inventory.

Type:

Stations

class SeisMonitor.monitor.locator.utils.Stations(stations)[source]

Bases: object

Container for seismic station metadata.

This class standardizes station information from different sources such as pandas DataFrames or ObsPy inventories, and provides utilities for exporting to seismic location formats (e.g. NonLinLoc).

Expected station table format

The internal DataFrame is expected to contain at least:

Column

Description

station

Station code

latitude

Station latitude (degrees)

longitude

Station longitude (degrees)

elevation

Elevation (meters)

type stations:

param stations:

Station data source. Can be:

  • pandas DataFrame with station metadata

  • ObsPy Inventory object

  • path or other format supported by resp2df

type stations:

pandas.DataFrame or str or Inventory

to_nlloc(out)[source]

Export velocity model in NonLinLoc (NLLoc) layer format.

This method writes the velocity model into a format compatible with NonLinLoc, where each row represents a layered 1D velocity structure.

If S-wave velocity (Vs) is not provided, it can be computed from Vp using the vp_vs_ratio parameter.

Output format

Each line follows the NLLoc “LAYER” specification:

LAYER depth Vp_top Vp_grad Vs_top Vs_grad rho_top rho_grad

where gradients are assumed to be zero (constant velocity per layer).

type out:

param out:

Output file path where the velocity model will be written.

type out:

str

Notes

  • Depth is expected in kilometers.

  • Velocities are in km/s.

  • Density is in g/cm³.

  • Vs is computed as Vp / vp_vs_ratio if compute_vs=True.

  • Gradients are currently set to zero (constant layers).

Example output line

LAYER   10.00   6.06   0.00   3.46   0.00   2.60   0.00

class SeisMonitor.monitor.locator.utils.VelModel(vel_path, model_name=None, vp_vs_ratio=1.78, compute_vs=True)[source]

Bases: object

Velocity model container for seismic travel-time and wave propagation calculations.

The model is typically loaded from a CSV file or a pandas DataFrame containing a 1D depth-dependent velocity structure.

Expected data format

The input velocity model must contain the following columns:

Column

Description

depth

Depth in km (positive downward)

vp

P-wave velocity (km/s)

vs

S-wave velocity (km/s)

rho

Density (g/cm³)

Example (Texas model):

depth,vp,vs,rho
-1,3.500,2.000,2.6
0,4.405,2.517,2.6
2,5.525,3.157,2.6
6,5.917,3.381,2.6
10,6.061,3.463,2.6
type vel_path:

param vel_path:

Path to a CSV file containing the velocity model, or a DataFrame already loaded in memory.

type vel_path:

str or pandas.DataFrame

type model_name:

param model_name:

Name identifier for the velocity model.

type model_name:

str, optional

type vp_vs_ratio:

param vp_vs_ratio:

Ratio used to compute S-wave velocity (Vs) if it is missing.

type vp_vs_ratio:

float, default=1.78

type compute_vs:

param compute_vs:

If True, compute Vs from Vp using vp_vs_ratio when Vs is not provided.

type compute_vs:

bool, default=True

vel

Loaded velocity model with columns: depth, vp, vs, rho.

Type:

pandas.DataFrame

model_name

Name of the velocity model.

Type:

str

vp_vs_ratio

Vp/Vs ratio used for conversion.

Type:

float

compute_vs

Flag indicating whether Vs is computed from Vp.

Type:

bool

Notes

If vel_path is a DataFrame, it is used directly without copying.

to_nlloc(out)[source]

Write velocity model in NonLinLoc format.

Parameters:

out (str) – Output file path

SeisMonitor.monitor.locator.utils.changing_picks_info(ev, ref_picks)[source]

Update event picks with information from reference picks.

Parameters:
  • ev (obspy.core.event.Event) – Event object to modify

  • ref_picks (dict) – Dictionary of reference picks with station_phase_time keys

Returns:

Modified event with updated picks and arrivals

Return type:

obspy.core.event.Event

SeisMonitor.monitor.locator.utils.filter_arrivals_by_distance(events, distance, min_P_phases=3, min_S_phases=2)[source]

Filter events based on arrival distance and minimum phase counts.

Parameters:
  • events (list) – List of event objects

  • distance (float) – Maximum distance for arrivals in degrees

  • min_P_phases (int) – Minimum number of P phases required

  • min_S_phases (int) – Minimum number of S phases required

Returns:

Filtered list of events meeting criteria

Return type:

list

SeisMonitor.monitor.locator.utils.get_bad_and_good_events(reloc_catalog)[source]

Separate events based on arrival azimuth uniformity.

Parameters:

reloc_catalog (obspy.core.event.Catalog) – Relocated event catalog

Returns:

(good_events, bad_events) where good_events have varying azimuths

and bad_events have uniform azimuths

Return type:

tuple

SeisMonitor.monitor.locator.utils.get_picks(catalog)[source]

Extract picks from a catalog into a dictionary.

Parameters:

catalog (obspy.core.event.Catalog) – Catalog containing events with picks

Returns:

Dictionary of picks keyed by station_phase_time strings

Return type:

dict

SeisMonitor.monitor.locator.utils.resp2df(resp)[source]

Convert station response inventory to DataFrame.

Parameters:

resp (Union[str, Inventory]) – Path to RESP file or Inventory object

Returns:

DataFrame with columns:

network, station, latitude, longitude, elevation

Return type:

pandas.DataFrame

nlloc utils

Useful functions for earthquake location using NonLinLoc.

class SeisMonitor.monitor.locator.nlloc.utils.GenericControlStatement(trans, control=[1, 54321])[source]

Bases: object

Class for generating generic control statements for NonLinLoc.

get_msg()[source]

Generate formatted control statement string.

Returns:

Formatted control statement

Return type:

str

class SeisMonitor.monitor.locator.nlloc.utils.Grid2Time(station_path, grid_folder_out, time_folder_out, phase='P', mode=['GRID3D', 'ANGLES_YES'], plfd=[0.001, 0])[source]

Bases: object

Class for generating travel time grid statements for NonLinLoc.

get_msg()[source]

Generate formatted travel time grid statement string.

Returns:

Formatted travel time grid statement

Return type:

str

class SeisMonitor.monitor.locator.nlloc.utils.NLLocControlFile(generic_control, vel2grid, grid2time, time2loc)[source]

Bases: object

Class for generating complete NonLinLoc control file.

get_msg(vel2grid=True, grid2time=True, time2loc=True)[source]

Generate complete control file message.

Parameters:
  • vel2grid (bool) – Include velocity grid section (default: True)

  • grid2time (bool) – Include travel time grid section (default: True)

  • time2loc (bool) – Include location section (default: True)

Returns:

Complete control file content

Return type:

str

write(out, vel2grid=True, grid2time=True, time2loc=True)[source]

Write control file to disk.

Parameters:
  • out (str) – Output file path

  • vel2grid (bool) – Include velocity grid section (default: True)

  • grid2time (bool) – Include travel time grid section (default: True)

  • time2loc (bool) – Include location section (default: True)

class SeisMonitor.monitor.locator.nlloc.utils.Time2Loc(catalog, grid, time_folder_out, loc_folder_out, meth=['GAU_ANALYTIC', 9999, 4, -1, -1, 1.78, 6], search=['OCT', 37, 58, 7, 0.01, 100000, 10000], sig='SeisMonitor', com='Comment', gau=[0.2, 0.0], gau2=[0.05, 0.05, 2.0], p_phaseid=['P', 'P', 'p', 'PN', 'PG', 'Pn', 'Pg'], s_phaseid=['S', 'S', 's', 'SN', 'SG', 'Sn', 'Sg'], qual2err=[0.1, 0.5, 1.0, 2.0, 99999.9], phstat=[9999.0, -1, 9999.0, 1.0, 1.0, 9999.0, -9999.0, 9999.0], angles=['ANGLES_YES', 5], hypout=['SAVE_NLLOC_ALL', 'SAVE_NLLOC_SUM', 'SAVE_HYPO71_SUM'], mag=['ML_HB', 1.0, 1.11, 0.00189])[source]

Bases: object

Class for generating location statements for NonLinLoc.

get_msg()[source]

Generate formatted location statement string.

Returns:

Formatted location statement

Return type:

str

class SeisMonitor.monitor.locator.nlloc.utils.Vel2Grid(vel_path, grid_folder_out, grid, p_phase='P', s_phase='S')[source]

Bases: object

Class for generating velocity grid statements for NonLinLoc.

get_msg()[source]

Generate formatted velocity grid statement string.

Returns:

Formatted velocity grid statement

Return type:

str

SeisMonitor.monitor.locator.nlloc.utils.apt_install(pkgs)[source]

Install packages using apt-get with sudo privileges.

Parameters:

pkgs (list) – List of package names to install

SeisMonitor.monitor.locator.nlloc.utils.download_nlloc(nlloc_path, forced=False)[source]

Download and compile NonLinLoc from Git repository.

Parameters:
  • nlloc_path (str) – Destination path for NonLinLoc

  • forced (bool) – Force re-download even if exists (default: False)

Returns:

True if already installed and not forced

Return type:

bool

SeisMonitor.monitor.locator.nlloc.utils.get_nlloc_folders(core_path)[source]

Generate dictionary of NonLinLoc folder paths.

Parameters:

core_path (str) – Base path to NonLinLoc core directory

Returns:

Dictionary containing all relevant NonLinLoc paths

Return type:

dict

SeisMonitor.monitor.locator.nlloc.utils.join_args(args)[source]

Convert list of arguments to space-separated string.

Parameters:

args (list) – List of arguments

Returns:

Space-separated string of arguments

Return type:

str

SeisMonitor.monitor.locator.nlloc.utils.resp2df(resp)[source]

Convert RESP file to DataFrame with station information.

Parameters:

resp (str) – Path to RESP file

Returns:

DataFrame with network, station, lat, lon, elevation

Return type:

pd.DataFrame

SeisMonitor.monitor.locator.nlloc.utils.run_nlloc(nlloc_paths, p_control_file_path, s_control_file_path)[source]

Execute NonLinLoc processing steps using system commands.

Parameters:
  • nlloc_paths (dict) – Dictionary of NonLinLoc executable paths

  • p_control_file_path (str) – Path to P-wave control file

  • s_control_file_path (str) – Path to S-wave control file

SeisMonitor.monitor.locator.nlloc.utils.testing_nlloc_core_path(nlloc_core_path)[source]

Validate existence of essential NonLinLoc directories.

Parameters:

nlloc_core_path (str) – Path to NonLinLoc core directory

Returns:

Validated paths dictionary

Return type:

dict

Raises:

Exception – If mandatory paths are missing

SeisMonitor.monitor.locator.nlloc.utils.write_1d_vel_model(vel_path, out, compute_vs=True, vp_vs_ratio=1.78)[source]

Write 1D velocity model file from CSV data.

Parameters:
  • vel_path (str) – Path to input velocity CSV file

  • out (str) – Output file path

  • compute_vs (bool) – Calculate Vs from Vp if True (default: True)

  • vp_vs_ratio (float) – Vp/Vs ratio for Vs calculation (default: 1.78)

SeisMonitor.monitor.locator.nlloc.utils.write_pref_origin_removing_phaselocinfo(catalog)[source]

Process seismic catalog to keep only preferred origins.

Parameters:

catalog (obspy.Catalog) – Input seismic catalog

Returns:

Modified catalog with cleaned origins

Return type:

obspy.Catalog

SeisMonitor.monitor.locator.nlloc.utils.write_station_file(sta_path, out)[source]

Write station file from RESP data.

Parameters:
  • sta_path (str) – Path to RESP file

  • out (str) – Output file path