API Reference

This is the official API documentation for the sgsim package. Only public classes and functions are listed here.

class sgsim.GroundMotion(npts, dt, ac, vel, disp, tag=None)[source]

Bases: DomainConfig

Ground motion data container

Parameters:
  • npts (int) – Number of time points in the record.

  • dt (float) – Time step interval in seconds.

  • ac (ndarray) – Acceleration time series.

  • vel (ndarray) – Velocity time series.

  • disp (ndarray) – Displacement time series.

  • tag (str, optional) – Identifier for the ground motion record.

property ce

Cumulative energy of acceleration time series.

Returns:

Cumulative energy array.

Return type:

ndarray

property energy_slicer

Slice indices for cumulative energy range.

Returns:

Index slice for energy-based trimming.

Return type:

slice

property fas

Fourier amplitude spectrum of acceleration.

Returns:

Fourier amplitude spectrum.

Return type:

ndarray

filter(bandpass_freqs: tuple[float, float])[source]

Apply bandpass filter to ground motion.

Parameters:

bandpass_freqs (tuple of float) – Lower and upper cutoff frequencies (Hz) as (f_low, f_high).

Returns:

Modified GroundMotion instance for method chaining.

Return type:

self

classmethod load_from(source: str, tag=None, **kwargs)[source]

Load ground motion from file or array.

Parameters:
  • source (str) – Data source format: ‘NGA’, ‘ESM’, ‘COL’, ‘RAW’, ‘COR’, or ‘Array’.

  • tag (str, optional) – Record identifier.

  • **kwargs

    Source-specific arguments:

    For file sources: file, filename, zip_file, skiprows, scale For ‘Array’ source: dt (float), ac (ndarray)

Returns:

Loaded ground motion instance.

Return type:

GroundMotion

Examples

>>> gm = GroundMotion.load_from('NGA', file='record.AT2')
>>> gm = GroundMotion.load_from('Array', dt=0.01, ac=acc_array)
property mle_ac

Mean local extrema of acceleration.

Returns:

Average of local peak values.

Return type:

float

property mle_disp

Mean local extrema of displacement.

Returns:

Average of local peak values.

Return type:

float

property mle_vel

Mean local extrema of velocity.

Returns:

Average of local peak values.

Return type:

float

property mzc_ac

Mean zero-crossing of acceleration.

Returns:

Zero-crossings per unit time.

Return type:

float

property mzc_disp

Mean zero-crossing of displacement.

Returns:

Zero-crossings per unit time.

Return type:

float

property mzc_vel

Mean zero-crossing of velocity.

Returns:

Zero-crossings per unit time.

Return type:

float

property pga

Peak ground acceleration.

Returns:

Maximum absolute acceleration value.

Return type:

float

property pgd

Peak ground displacement.

Returns:

Maximum absolute displacement value.

Return type:

float

property pgv

Peak ground velocity.

Returns:

Maximum absolute velocity value.

Return type:

float

property pmnm_ac

Positive-minima and negative-maxima of acceleration.

Returns:

Ratio of peak to mean absolute value.

Return type:

float

property pmnm_disp

Positive-minima and negative-maxima of displacement.

Returns:

Ratio of peak to mean absolute value.

Return type:

float

property pmnm_vel

Positive-minima and negative-maxima of velocity.

Returns:

Ratio of peak to mean absolute value.

Return type:

float

resample(dt: float)[source]

Resample ground motion to new time step.

Parameters:

dt (float) – Target time step in seconds.

Returns:

Modified GroundMotion instance for method chaining.

Return type:

self

property sa

Spectral acceleration response.

Returns:

Sa values at periods defined by tp.

Return type:

ndarray

property sd

Spectral displacement response.

Returns:

Sd values at periods defined by tp.

Return type:

ndarray

smooth_fas(window: int = 9)[source]

Smoothed Fourier amplitude spectrum.

Parameters:

window (int, optional) – Moving average window size. Default is 9.

Returns:

Smoothed Fourier amplitude spectrum.

Return type:

ndarray

property spectra[source]

Response spectra at 5% damping.

Returns:

Array of shape (3, n_periods) with [Sd, Sv, Sa].

Return type:

ndarray

property sv

Spectral velocity response.

Returns:

Sv values at periods defined by tp.

Return type:

ndarray

to_csv(filename: str, features: list[str])[source]

Export selected features to CSV.

Parameters:
  • filename (str) – Output CSV file path.

  • features (list of str) – List of feature names to export.

trim(method: str, value: tuple[float, float] | int | slice)[source]

Trim ground motion time series.

Parameters:
  • method ({'energy', 'npts', 'slice'}) – Trimming approach. ‘energy’ trims by cumulative energy fraction, ‘npts’ keeps first N points, ‘slice’ applies custom indexing.

  • value (tuple of float, int, or slice) – Trim parameters. For ‘energy’: (start, end) fractions (e.g., 0.05, 0.95). For ‘npts’: number of points. For ‘slice’: slice object.

Returns:

Modified GroundMotion instance for method chaining.

Return type:

self

Examples

>>> motion.trim('energy', (0.05, 0.95))
>>> motion.trim('npts', 1000)
>>> motion.trim('slice', slice(100, 500))
class sgsim.ModelPlot(model, simulated_motion, real_motion)[source]

Bases: object

This class allows to

plot various simulation results and comparison with a target motion

property errors
property goodness_of_fits
plot_ac_ce(config=None)[source]

Comparing the cumulative energy and energy distribution of the record, model, and simulations

plot_ce(config=None)[source]

Cumulative energy plot of the record and simulations

plot_fas(log_scale=True, config=None)[source]

FAS plot of the record and simulations

plot_feature(feature='mzc', model_plot=True, sim_plot=False, config=None)[source]

Comparing the indicated error of the record, model, and simulations mzc, mle, pmnm

plot_motions(id1, id2, config=None)[source]

plot ground motion time histories of acceleration, velocity, and displacement in a 3 by 3 grid

plot_spectra(spectrum='sa', log_scale=True, config=None)[source]

Plot the specified type of spectrum (sa, sv, or sd) of the record and simulations

show_metrics(metric_type, save_path=None)[source]

Print metrics with optional saving.

class sgsim.StochasticModel(npts: int, dt: float, modulating: ParametricFunction, upper_frequency: ParametricFunction, upper_damping: ParametricFunction, lower_frequency: ParametricFunction, lower_damping: ParametricFunction)[source]

Bases: ModelConfig

Stochastic ground motion simulation model.

This class provides methods to simulate ground motions using calibrated stochastic parameters, save/load model configurations, and generate model summaries.

npts

Number of time points in the simulation.

Type:

int

dt

Time step of the simulation.

Type:

float

modulating

Time-varying modulating function.

Type:

ParametricFunction

upper_frequency

Upper frequency parameter function.

Type:

ParametricFunction

upper_damping

Upper damping parameter function.

Type:

ParametricFunction

lower_frequency

Lower frequency parameter function.

Type:

ParametricFunction

lower_damping

Lower damping parameter function.

Type:

ParametricFunction

See also

ModelConfig

Base configuration class

GroundMotion

Ground motion container class

fit(component: str, motion: GroundMotion, fit_range: tuple = (0.01, 0.99), initial_guess=None, bounds=None, method='L-BFGS-B')[source]

Fit stochastic model parameters to match target motion.

This method acts as a wrapper around the calibration logic defined in the optimization module.

Parameters:
  • component (str) – Component to fit (‘modulating’, ‘frequency’, or ‘damping’).

  • motion (GroundMotion) – The target ground motion.

  • initial_guess (array-like, optional) – Initial parameter values. If None, uses defaults.

  • bounds (list of tuples, optional) – Parameter bounds as [(min1, max1), (min2, max2), …]. If None, uses defaults.

  • method (str, optional) – Optimization method. Default is ‘L-BFGS-B’.

Returns:

result – Optimization result with success status, final parameters, etc.

Return type:

OptimizeResult

classmethod load_from(filename)[source]

Construct a stochastic model from a JSON file.

Loads a previously saved stochastic model configuration from a JSON file and reconstructs the complete model with all parametric functions and their calibrated parameters.

Parameters:

filename (str) – Path to JSON file containing model data (e.g., ‘model.json’). The file should have been created using the summary method with a filename argument.

Returns:

An instance of StochasticModel initialized from the file with all parametric functions and parameters restored.

Return type:

StochasticModel

Raises:
  • FileNotFoundError – If the specified file does not exist.

  • json.JSONDecodeError – If the file is not valid JSON.

  • AttributeError – If the parametric function types specified in the file are not found in the parametric_functions module.

See also

summary

Save a model to JSON file

Examples

>>> # Save a model
>>> model = StochasticModel(npts=1000, dt=0.01, ...)
>>> model.summary('my_model.json')
>>> # Load it back
>>> loaded_model = StochasticModel.load_from('my_model.json')
>>> loaded_model.npts
1000

Notes

The method performs the following steps: 1. Loads JSON data from file 2. Creates a model instance with function types 3. Restores all parameter values by calling each function

simulate(n, seed=None)[source]

Simulate ground motions using the calibrated stochastic model.

Parameters:
  • n (int) – Number of simulations to generate.

  • seed (int, optional) – Random seed for reproducibility. If None, the random number generator is not seeded.

Returns:

An instance of GroundMotion containing the simulated ground motions with acceleration, velocity, and displacement time series.

Return type:

GroundMotion

Notes

The simulation process involves: 1. Generating white noise samples 2. Computing Fourier series with stochastic model parameters 3. Applying inverse FFT to obtain time-domain signals 4. Integrating in frequency domain for velocity and displacement

Examples

>>> model = StochasticModel(npts=1000, dt=0.01, ...)
>>> gm = model.simulate(n=100, seed=42)
>>> gm.acceleration.shape
(100, 1000)
summary(filename=None)[source]

Print model parameters and optionally save to JSON file.

Displays a formatted summary of the stochastic model configuration including time step, number of points, and all parametric functions. Optionally saves the complete model configuration to a JSON file for later reconstruction.

Parameters:

filename (str, optional) – Path to JSON file for saving model data (e.g., ‘model.json’). If None, only prints to console without saving.

Returns:

self – The StochasticModel instance for method chaining.

Return type:

StochasticModel

See also

load_from

Load a model from JSON file

Notes

The saved JSON file contains: - Time discretization parameters (npts, dt) - Function types for all parametric components - Parameter values for each function

A stochastic model can be reconstructed from the saved file using the load_from class method.

Examples

>>> model = StochasticModel(npts=1000, dt=0.01, ...)
>>> model.summary()  # Print only
>>> model.summary('my_model.json')  # Print and save