API documentations

acc.core module

Preprocessing and correlation

acc.core._fill_array(data, mask=None, fill_value=None)[source]

Mask numpy array and/or fill array value without demasking.

Additionally set fill_value to value. If data is not a MaskedArray and mask is None returns silently data.

  • mask – apply mask to array
  • fill_value – fill value

find the start and end time of a specific stream.

Return starttime, endtime:
acc.core._run_abs_mean(tr, time_length=5, filter=(0.01, 1), corners=4, zerophase=True, waterlevel=1e-08)[source]

running absolute mean normalization

  • tr – trace to be normalized
  • time_length (float) – time length to be smoothed, default 5 sec
  • filter (tuple) – bandpass frequency band, default (0.01, 1) Hz
  • corners (int) – corners default 4
  • zerophase (bool) – default True
  • waterlevel (float) – waterlevel to safe guard division

data after temporal normalization

acc.core.remove_response(trace, resp_path, pre_filt=(0.01, 0.02, 8, 9), output='VEL', format='XML')[source]

Romove instrumental response

  • trace
  • resp_path
  • pre_filt
  • output
  • format


currently only support XML DATALESS RESP format.

acc.core.rotation(stream, method='NE->RT', acc_type='event')[source]


  • stream – obspy stream to be rotated
  • method – “NE->RT” or “ZNE->LQT”
  • acc_type – “event”, “noise”
Return stream:

obspy stream after rotation.


The keywords component_azimuth and component_inclination must be given in the stats. Currently, only acc_type=”event” are well debugged. The input 3-component data should be in the roughly same periods or time window.

acc.core.spectral_whitening(tr, smooth=None, filter=None, waterlevel=1e-08, corners=2, zerophase=True)[source]

Apply spectral whitening to data

Data is divided by its smoothed (Default: None) amplitude spectrum.

  • tr – trace to manipulate
  • smooth – length of smoothing window in Hz (default None -> no smoothing)
  • filter – filter spectrum with bandpass after whitening (tuple with min and max frequency) (default None -> no filter)
  • waterlevel – waterlevel relative to mean of spectrum
  • mask_again – weather to mask array after this operation again and set the corresponding data to 0
  • corners – parameters parsing to filter,
  • zerophase – parameters parsing to filter

whitened data

acc.core.time_norm(tr, method, time_length=5, filter=(0.01, 1), corners=2, zerophase=True, waterlevel=1e-08)[source]

Calculate normalized data, see e.g. Bensen et al. (2007, GJI)

  • tr – Trace to manipulate
  • method (str) –

    1bit: reduce data to +1 if >0 and -1 if <0

    run_abs_mean: running absolute mean normalization

  • time_length (float) – time length to be smoothed, default 5 sec
  • filter (tuple) – bandpass frequency band, default (0.01, 1) Hz
  • corners (int) – corners default 2
  • zerophase (bool) – default True
  • waterlevel (float) – waterlevel to safe guard division

normalized data

acc.io module

I/O modules

acc.io._acc_read(file, outpath, acc_type, phase, force=True, tt_model='ak135', depth_unit='km')[source]

Read seismic data.

  • file – file name to be read
  • outpath – where to save the data
  • acc_type – event or noise
  • phase – if acc_type=’event’, then calculate the traveltime of the phase
  • force – force to overwrite when file exists if force is True
  • tt_model – 1-d theoretical model, e.g., ak135 used to calculate traveltime of a specific phase
  • depth_unit – unit of depth, general one is km, but in some cases it could be m.

acc.io._get_event_data(tr, tt_model, phase, acc_type, depth_unit='km')[source]

Update a sac trace to a obspy trace and update trace header, and calculate theoretical traveltime of a specific model and phase

  • tr
  • tt_model
  • phase
  • acc_type
  • depth_unit


The input trace should be read from sac-formatted files.

depth_unit is not used. if depth>1000 then unit should be meter, since no events deeper than 700 km on the earth.


Get event id from a sac-formatted trace.

Return str event_id:
 event id

Get event id from a obspy trace. The obspy trace should have the event_time keyword.

Parameters:tr – a obspy trace
Return str event_id:
 event id in “%Y%m%d%H%M%S”, e.g., ‘20191019200909’
acc.io._get_noise_data(tr, acc_type)[source]

Get update sac-trace header to obspy trace header station_latitude etc.

  • tr
  • acc_type
Return tr:

Get trace id for noise type data. e.g., ‘starttime-endtime’

Parameters:tr – an obspy trace
Return str event_id:
 noise id

Get the origin time of an event trace in sac format.

Parameters:tr – A event trace
Return origin:origin time of an event


The trace should be sac formatted.


Get station id of a given trace.

Parameters:tr – trace
Return station_id:
 station id formatted as ‘{newwork}.{station}.{location}’.

Load parameters from the json formatted file

Parameters:jsonfile (str) – json file containing parameters
Return dict kwargs:
 dictionary containing parameters

Import data from external media

Parameters:jsonfile – parameter filename

acc.main module

acc.migration module

acc.migration._mig_1(path, model='ak135')[source]
acc.migration.mig_one_station(stream, model='ak135', earth_radius=6378137.0, depth_range=(0, 300, 1))[source]
acc.migration.migration_one_station_stack(stream, method='PWS', power=2, time_range=[8, 16], coeff=0.5)[source]

Stacking of migrated traces for one station. Currently not used.

  • stream
  • method – “PWS” for phase-weighted stacking and “linear” for linear stacking
  • power – used by “PWS” only. power=0 is linear stacking
  • time_range – if None do simple stacking (PWS or linear). if a list contains two elements then

it will select traces with high resemblance with the initial stacking to get final stacked trace. :param coeff: traces with correlation efficient higher than the value will be selected. :return: trace after stacking


The one more procedure is to improve signal-to-noise ratio. You may check the stats header corrstack. If the key equals zero, the stacking is the general ones, otherwise the correlated stacking are implemented. The value denotes the number of stacked traces.

acc.plotting module


acc.plotting._plot(amp, depth, stack, extent, dist_range, depth_range, savepath, profile_id, wclip=1, iclip=1, figsize=(5.2, 3), width_ratios=[0.6, 2])[source]
acc.plotting._plot_1station(stmig, latlon0, azimuth, bins, width, savepath, depth_range, **kwargs)[source]
acc.plotting._plot_stations(stmig, latlon0, azimuth, bins, width, savepath, depth_range, profile_id, **kwargs)[source]
acc.plotting.plot_acc_one_station(stream, fname=None, fig_width=7.0, trace_height=0.5, stack_height=0.5, scale=2, scale_stack=10, fillcolors=('red', 'blue'), info=(('back_azimuth', 'baz (°)', 'C0'), ('distance', 'dist (°)', 'C3')))[source]

Plot auto- or correlogram for one station. Reproduced from the rf package.

  • stream – stream to plot
  • fname – filename to save plot to. Can be None. In this case the figure is left open.
  • fig_width – width of figure in inches
  • trace_height – height of one trace in inches
  • stack_height – height of stack axes in inches
  • scale – scale for individual traces
  • fillcolors – fill colors for positive and negative wiggles
  • info – Plot one additional axes showing maximal two entries of the stats object. Each entry in this list is a list consisting of three entries: key, label and color. info can be None. In this case no additional axes is plotted.
acc.plotting.plot_ppoint(stream, fname='pp.pdf', depths=[30, 50, 80, 100, 150, 200])[source]
acc.plotting.write_netcdf4(pos, dep, data, file)[source]

acc.processing module

acc.processing._autocorrelation(tr, window=[-20, 70], filter=[0.5, 4], corners=2, zerophase=True)[source]

Autocorrelation for event type data.

  • tr
  • window
  • filter – A tuple or a list containing the lower and upper limit of filter.
  • corners
  • zerophase


filter after autocorrelation.

acc.processing._cal_event_snr(tr, signal=[-10, 10], noise=[-100, -50], waterlevel=1e-08)[source]

Calculation of SNR for event data.

  • tr
  • signal
  • noise
  • waterlevel

acc.processing._crosscorrelation(tr1, tr2, window=[-20, 70], filter=[0.5, 4], corners=2, zerophase=True)[source]

cross-correlation for event type data.

  • tr1
  • tr2
  • window
  • filter
  • corners
  • zerophase

acc.processing._proc(tr, sampling_rate=10)[source]

Basic processing including downsampling, detrend, and demean.

  • tr – raw trace
  • sampling_rate
Return tr:

trace after processing

acc.processing._proc_event_Z(file, **kwargs)[source]

Processing a single component Z including downsampling, detrend, demean, remove instrumental response, selection of data by SNR>threshold, spectral whitening, temporal normalization and auto-correlation.

For event type data.

  • file
  • kwargs

acc.processing._proc_event_full(st, **kwargs)[source]

processings including

  • st
  • kwargs

acc.processing._proc_event_rst(st, **kwargs)[source]

processing including rotation, spectral whitening and temporal normalization. and cross-correlation.

  • st
  • kwargs

1 if processing successfully.


rst is short as Rotation Spectral whitening and Temporal normalization.

acc.processing._proc_noise_Z(file, **kwargs)[source]

Internal functions of calculate z-comp autocorrelation for noise data.

  • file
  • kwargs

acc.processing._rot(st, method='NE->RT')[source]


  • st
  • method – “NE->RT”, “ZNE->LQT”.


the code can handle ‘Z12’, ‘123’, ‘ZNE’. It requires trace header of component_azimuth and component_inclination. if method == “NE->RT”, then the two components rotation will be applied. But while the components are “123” or “Z12”, they are rotated to “ZNE” first.

acc.processing._select_data_event(tr, dist_range=[30, 90], magnitude=[5.0, 9.0], snr_threshold=2.0, signal=[-10, 10], noise=[-100, -50], waterlevel=1e-08)[source]
acc.processing._simple_proc(st, sampling_rate=10, njobs=1)[source]

A parallel version of _proc, i.e., Basic processing including downsampling, detrend, and demean.

  • st – an obspy stream
  • sampling_rate – expected sampling rate
  • njobs – number of jobs or CPU to use
Return st:

stream after processing

acc.processing._sliding_autocorrelation(tr, length=3600, overlap=1800, filter=[0.5, 4], corners=2, zerophase=True)[source]

Sliding autocorrelation for noise data.

  • tr
  • length
  • overlap
  • filter
  • corners
  • zerophase


processing vertical component of event data


Parallel processing of noise autocorrelation.


acc.profile module

acc.profile._find_box(latlon, boxes, crs=None)[source]

Return the box which encloses the coordinates.

acc.profile._find_box_cartesian(latlon, boxes)[source]

Return the box which encloses the coordinates.

acc.profile._get_box(latlon0, azimuth, length, width=2000, offset=0)[source]

Create a single box.

acc.profile._get_box_cartesian(latlon0, azimuth, length, width=2000, offset=0)[source]

Create a single box.

acc.profile.df_depth(depth, dfmig, boxes, depths, pos_dist, a, b)[source]
acc.profile.direct_geodetic(latlon, azi, dist)[source]

Solve direct geodetic problem with geographiclib.

  • latlon (tuple) – coordinates of first point
  • azi – azimuth of direction
  • dist – distance in km

coordinates (lat, lon) of second point on a WGS84 globe

acc.profile.get_profile_boxes(latlon0, azimuth, bins, width=2000)[source]

Create 2D boxes for usage in profile() function.

  • latlon0 (tuple) – coordinates of starting point of profile
  • azimuth – azimuth of profile direction
  • bins (tuple) – Edges of the distance bins in km (e.g. (0, 10, 20, 30))
  • width – width of the boxes in km (default: large)

List of box dicts. Each box has the entries ‘poly’ (shapely polygon with lonlat corners), ‘length’ (length in km), ‘pos’ (midpoint of box in km from starting coordinates), ‘latlon’ (midpoint of box as coordinates)

acc.profile.profile(stream, boxes, crs=None)[source]

Stack traces in stream by piercing point coordinates in defined boxes.

  • stream – stream with pre-calculated piercing point coordinates
  • boxes – boxes created with get_profile_boxes()
  • crs – cartopy projection (default: AzimuthalEquidistant)

profile stream

acc.stack module


acc.stack._bootstrap(st, normalize=True, **kwargs)[source]
acc.stack._gen_random_number(low=0, high=100, n_iter=100, percentage=0.9, seed=59)[source]
acc.stack._stack(path, **kwargs)[source]
acc.stack.linear_stack(stream, normalize=True)[source]
acc.stack.pws_stack(stream, power=2, normalize=True)[source]

acc.util module

Utility functions and classes for Auto and Cross Correlogram calculation.

class acc.util.IterMultipleComponents(stream, key=None, number_components=None)[source]

Bases: object

Return iterable to iterate over associated components of a stream.

  • stream – Stream with different, possibly many traces. It is split into substreams with the same seed id (only last character i.e. component may vary)
  • key (str or None) – Additionally, the stream is grouped by the values of the given stats entry to differentiate between e.g. different events (for example key=’starttime’, key=’onset’)
  • number_components (int, tuple of ints or None) – Only iterate through substreams with matching number of components.

alias of builtins.type


Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'acc.util', '__doc__': "\n Return iterable to iterate over associated components of a stream.\n\n :param stream: Stream with different, possibly many traces. It is\n split into substreams with the same seed id (only last character\n i.e. component may vary)\n :type key: str or None\n :param key: Additionally, the stream is grouped by the values of\n the given stats entry to differentiate between e.g. different events\n (for example key='starttime', key='onset')\n :type number_components: int, tuple of ints or None\n :param number_components: Only iterate through substreams with\n matching number of components.\n ", '__init__': <function IterMultipleComponents.__init__>, '__len__': <function IterMultipleComponents.__len__>, '__iter__': <function IterMultipleComponents.__iter__>, '__dict__': <attribute '__dict__' of 'IterMultipleComponents' objects>, '__weakref__': <attribute '__weakref__' of 'IterMultipleComponents' objects>})

Default dir() implementation.


Return self==value.


Default object formatter.


Return self>=value.


Return getattr(self, name).


Return self>value.


Return hash(self).

__init__(stream, key=None, number_components=None)[source]

Initialize self. See help(type(self)) for accurate signature.


This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.


Return self<=value.


Return self<value.

__module__ = 'acc.util'

Return self!=value.


Create and return a new object. See help(type) for accurate signature.


Helper for pickle.


Helper for pickle.


Return repr(self).


Implement setattr(self, name, value).


Size of object in memory, in bytes.


Return str(self).


Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).


list of weak references to the object (if defined)

acc.util.iter_time(tr, length=3600, overlap=1800)[source]
acc.util.pkl2sac1(directory, suffix='pkl', fmt='SAC')[source]

Convert file from Pickle format with suffix of pkl to SAC format

  • directory – the directory contains files to be converted.
  • suffix – in this case, it should be “pkl”.
  • fmt – the target format to be converted. Support SAC, MSEED.

Example: /the/path/hello.pkl to /the/path_SAC/hello.sac

acc.util.smooth(x, window_len=None, window='flat', method='zeros')[source]

Smooth the data using a window with requested size.

This method is based on the convolution of a scaled window with the signal.

  • x – the input signal (numpy array)
  • window_len – the dimension of the smoothing window; should be an odd integer
  • window – the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’ flat window will produce a moving average smoothing.
  • method

    handling of border effects

    ’zeros’: zero padding on both ends (len(smooth(x)) = len(x))

    ’reflect’: pad reflected signal on both ends (same)

    ’clip’: pad signal on both ends with the last valid value (same)

    None: no handling of border effects (len(smooth(x)) = len(x) - len(window_len) + 1)

Module contents