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.

Parameters:
  • mask – apply mask to array
  • fill_value – fill value
acc.core._find_start_end_time(stream)[source]

find the start and end time of a specific stream.

Parameters: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

Parameters:
  • 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
Returns:

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

Parameters:
  • trace
  • resp_path
  • pre_filt
  • output
  • format
Returns:

Note

currently only support XML DATALESS RESP format.

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

Rotatation.

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

obspy stream after rotation.

Note

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.

Parameters:
  • 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
Returns:

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)

Parameters:
  • 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
Returns:

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.

Parameters:
  • 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.
Returns:

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

Parameters:
  • tr
  • tt_model
  • phase
  • acc_type
  • depth_unit
Returns:

Note

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.

acc.io._get_event_id(tr)[source]

Get event id from a sac-formatted trace.

Parameters:tr
Return str event_id:
 event id
acc.io._get_event_id_tr(tr)[source]

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.

Parameters:
  • tr
  • acc_type
Return tr:
acc.io._get_noise_id(tr)[source]

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

Parameters:tr – an obspy trace
Return str event_id:
 noise id
acc.io._get_sac_origin(tr)[source]

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

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

Note

The trace should be sac formatted.

acc.io._get_station_id(tr)[source]

Get station id of a given trace.

Parameters:tr – trace
Return station_id:
 station id formatted as ‘{newwork}.{station}.{location}’.
acc.io._load_json(jsonfile)[source]

Load parameters from the json formatted file

Parameters:jsonfile (str) – json file containing parameters
Return dict kwargs:
 dictionary containing parameters
acc.io.import_data(jsonfile)[source]

Import data from external media

Parameters:jsonfile – parameter filename
Returns:

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_1station(jsonfile)[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.

Parameters:
  • 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

Note

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

Plottings

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.

Parameters:
  • 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.plot_profile(jsonfile)[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.

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

Note

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.

Parameters:
  • tr
  • signal
  • noise
  • waterlevel
Returns:

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

cross-correlation for event type data.

Parameters:
  • tr1
  • tr2
  • window
  • filter
  • corners
  • zerophase
Returns:

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

Basic processing including downsampling, detrend, and demean.

Parameters:
  • 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.

Parameters:
  • file
  • kwargs
Returns:

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

processings including

Parameters:
  • st
  • kwargs
Returns:

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

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

Parameters:
  • st
  • kwargs
Returns:

1 if processing successfully.

Note

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.

Parameters:
  • file
  • kwargs
Returns:

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

rotation.

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

Note

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.

Parameters:
  • 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.

Parameters:
  • tr
  • length
  • overlap
  • filter
  • corners
  • zerophase
Returns:

acc.processing.processing_event_Z(jsonfile)[source]

processing vertical component of event data

Parameters:jsonfile
Returns:
acc.processing.processing_event_full(jsonfile)[source]
acc.processing.processing_noise_Z(jsonfile)[source]

Parallel processing of noise autocorrelation.

Parameters:jsonfile
Returns:

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.

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

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.

Parameters:
  • 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)
Returns:

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.internal_profile(tr)[source]
acc.profile.profile(stream, boxes, crs=None)[source]

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

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

profile stream

acc.stack module

stacking

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.stack.stack(jsonfile)[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.

Parameters:
  • 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.
__class__

alias of builtins.type

__delattr__

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>})
__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

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

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

__init_subclass__()

This method is called when a class is subclassed.

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

__iter__()[source]
__le__

Return self<=value.

__len__()[source]
__lt__

Return self<value.

__module__ = 'acc.util'
__ne__

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__weakref__

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

Parameters:
  • 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.

Parameters:
  • 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