code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for par in parameters:
if par['station'] == tr.stats.station and \
par['channel'] == tr.stats.channel:
parameter = par
break
else:
msg = 'No parameters set for station ' + str(tr.stats.station)
warnings.warn(msg)
return []
triggers = [... | def _channel_loop(tr, parameters, max_trigger_length=60,
despike=False, debug=0) | Internal loop for parellel processing.
:type tr: obspy.core.trace
:param tr: Trace to look for triggers in.
:type parameters: list
:param parameters: List of TriggerParameter class for trace.
:type max_trigger_length: float
:type despike: bool
:type debug: int
:return: trigger
:rty... | 2.961379 | 2.951972 | 1.003186 |
header = ' '.join(['# User:', getpass.getuser(),
'\n# Creation date:', str(UTCDateTime()),
'\n# EQcorrscan version:',
str(eqcorrscan.__version__),
'\n\n\n'])
if append:
f = op... | def write(self, filename, append=True) | Write the parameters to a file as a human-readable series of dicts.
:type filename: str
:param filename: File to write to
:type append: bool
:param append: Append to already existing file or over-write. | 3.917006 | 4.43483 | 0.883237 |
# append any extension suffix defined by Python for current platform
ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
# in principle "EXT_SUFFIX" is what we want.
# "SO" seems to be deprecated on newer python
# but: older python seems to have empty "EXT_SUFFIX", so we fall back
if not ex... | def _get_lib_name(lib) | Helper function to get an architecture and Python version specific library
filename. | 6.183836 | 6.336478 | 0.975911 |
# our custom defined part of the extension file name
libname = _get_lib_name(name)
libdir = os.path.join(os.path.dirname(__file__), 'lib')
libpath = os.path.join(libdir, libname)
static_fftw = os.path.join(libdir, 'libfftw3-3.dll')
static_fftwf = os.path.join(libdir, 'libfftw3f-3.dll')
... | def _load_cdll(name) | Helper function to load a shared library built during installation
with ctypes.
:type name: str
:param name: Name of the library to load (e.g. 'mseed').
:rtype: :class:`ctypes.CDLL` | 2.632973 | 2.666358 | 0.987479 |
event = Event()
event.origins.append(Origin())
event.creation_info = CreationInfo(author='EQcorrscan',
creation_time=UTCDateTime())
event.comments.append(Comment(text='cross_net'))
samp_rate = stream[0].stats.sampling_rate
if not env:
if debug ... | def cross_net(stream, env=False, debug=0, master=False) | Generate picks using a simple envelope cross-correlation.
Picks are made for each channel based on optimal moveout defined by
maximum cross-correlation with master trace. Master trace will be the
first trace in the stream if not set. Requires good inter-station
coherance.
:type stream: obspy.cor... | 3.491728 | 3.040715 | 1.148325 |
cccoh = 0.0
kchan = 0
array_xcorr = get_array_xcorr(xcorr_func)
for tr in st1:
tr2 = st2.select(station=tr.stats.station,
channel=tr.stats.channel)
if len(tr2) > 0 and tr.stats.sampling_rate != \
tr2[0].stats.sampling_rate:
warnin... | def cross_chan_coherence(st1, st2, allow_shift=False, shift_len=0.2, i=0,
xcorr_func='time_domain') | Calculate cross-channel coherency.
Determine the cross-channel coherency between two streams of multichannel
seismic data.
:type st1: obspy.core.stream.Stream
:param st1: Stream one
:type st2: obspy.core.stream.Stream
:param st2: Stream two
:type allow_shift: bool
:param allow_shift:
... | 2.931979 | 2.802345 | 1.046259 |
# Initialize square matrix
dist_mat = np.array([np.array([0.0] * len(stream_list))] *
len(stream_list))
for i, master in enumerate(stream_list):
# Start a parallel processing pool
pool = Pool(processes=cores)
# Parallel processing
results = [pool.... | def distance_matrix(stream_list, allow_shift=False, shift_len=0, cores=1) | Compute distance matrix for waveforms based on cross-correlations.
Function to compute the distance matrix for all templates - will give
distance as 1-abs(cccoh), e.g. a well correlated pair of templates will
have small distances, and an equally well correlated reverse image will
have the same distance... | 2.91057 | 2.916325 | 0.998026 |
if cores == 'all':
num_cores = cpu_count()
else:
num_cores = cores
# Extract only the Streams from stream_list
stream_list = [x[0] for x in template_list]
# Compute the distance matrix
if debug >= 1:
print('Computing the distance matrix using %i cores' % num_cores)
... | def cluster(template_list, show=True, corr_thresh=0.3, allow_shift=False,
shift_len=0, save_corrmat=False, cores='all', debug=1) | Cluster template waveforms based on average correlations.
Function to take a set of templates and cluster them, will return groups
as lists of streams. Clustering is done by computing the cross-channel
correlation sum of each stream in stream_list with every other stream in
the list. :mod:`scipy.clus... | 2.803987 | 2.629186 | 1.066485 |
groups = []
group_delays = []
group_chans = []
# Sort templates by number of channels
stream_list = [(st, len(st)) for st in stream_list]
stream_list.sort(key=lambda tup: tup[1])
stream_list = [st[0] for st in stream_list]
for i, st in enumerate(stream_list):
msg = ' '.join(... | def group_delays(stream_list) | Group template waveforms according to their arrival times (delays).
:type stream_list: list
:param stream_list:
List of :class:`obspy.core.stream.Stream` waveforms you want to group.
:returns:
list of List of :class:`obspy.core.stream.Stream` where each initial
list is a group with... | 2.52735 | 2.531971 | 0.998175 |
warnings.warn('Depreciated, use svd instead.')
return svd(stream_list=stream_list, full=full) | def SVD(stream_list, full=False) | Depreciated. Use svd. | 4.516455 | 3.391134 | 1.331842 |
# Convert templates into ndarrays for each channel
# First find all unique channels:
stachans = list(set([(tr.stats.station, tr.stats.channel)
for st in stream_list for tr in st]))
stachans.sort()
# Initialize a list for the output matrices, one matrix per-channel
s... | def svd(stream_list, full=False) | Compute the SVD of a number of templates.
Returns the singular vectors and singular values of the templates.
:type stream_list: List of :class: obspy.Stream
:param stream_list: List of the templates to be analysed
:type full: bool
:param full: Whether to compute the full input vector matrix or not... | 3.261587 | 2.972681 | 1.097187 |
warnings.warn('Depreciated, use empirical_svd instead.')
return empirical_svd(stream_list=stream_list, linear=linear) | def empirical_SVD(stream_list, linear=True) | Depreciated. Use empirical_svd. | 3.916652 | 2.659775 | 1.47255 |
# Run a check to ensure all traces are the same length
stachans = list(set([(tr.stats.station, tr.stats.channel)
for st in stream_list for tr in st]))
for stachan in stachans:
lengths = []
for st in stream_list:
lengths.append(len(st.select(station=s... | def empirical_svd(stream_list, linear=True) | Empirical subspace detector generation function.
Takes a list of templates and computes the stack as the first order
subspace detector, and the differential of this as the second order
subspace detector following the empirical subspace method of
`Barrett & Beroza, 2014 - SRL
<http://srl.geosciencew... | 2.990481 | 2.845811 | 1.050836 |
warnings.warn('Depreciated, use svd_to_stream instead.')
return svd_to_stream(uvectors=uvectors, stachans=stachans, k=k,
sampling_rate=sampling_rate) | def SVD_2_stream(uvectors, stachans, k, sampling_rate) | Depreciated. Use svd_to_stream | 2.710472 | 2.146448 | 1.262771 |
svstreams = []
for i in range(k):
svstream = []
for j, stachan in enumerate(stachans):
if len(uvectors[j]) <= k:
warnings.warn('Too few traces at %s for a %02d dimensional '
'subspace. Detector streams will not include '
... | def svd_to_stream(uvectors, stachans, k, sampling_rate) | Convert the singular vectors output by SVD to streams.
One stream will be generated for each singular vector level,
for all channels. Useful for plotting, and aiding seismologists thinking
of waveforms!
:type svectors: list
:param svectors: List of :class:`numpy.ndarray` Singular vectors
:typ... | 3.733058 | 3.592065 | 1.039251 |
stack = stacking.linstack([Stream(tr) for tr in trace_list])[0]
output = np.array([False] * len(trace_list))
group1 = []
array_xcorr = get_array_xcorr()
for i, tr in enumerate(trace_list):
if array_xcorr(
np.array([tr.data]), stack.data, [0])[0][0][0] > 0.6:
... | def corr_cluster(trace_list, thresh=0.9) | Group traces based on correlations above threshold with the stack.
Will run twice, once with a lower threshold to remove large outliers that
would negatively affect the stack, then again with your threshold.
:type trace_list: list
:param trace_list:
List of :class:`obspy.core.stream.Trace` to ... | 3.135994 | 2.96287 | 1.058431 |
# Initialize square matrix
dist_mat = np.array([np.array([0.0] * len(catalog))] *
len(catalog))
# Calculate distance vector for each event
for i, master in enumerate(catalog):
mast_list = []
if master.preferred_origin():
master_ori = master.prefer... | def dist_mat_km(catalog) | Compute the distance matrix for all a catalog using epicentral separation.
Will give physical distance in kilometers.
:type catalog: obspy.core.event.Catalog
:param catalog: Catalog for which to compute the distance matrix
:returns: distance matrix
:rtype: :class:`numpy.ndarray` | 2.521543 | 2.398174 | 1.051443 |
# Compute the distance matrix and linkage
dist_mat = dist_mat_km(catalog)
dist_vec = squareform(dist_mat)
Z = linkage(dist_vec, method='average')
# Cluster the linkage using the given threshold as the cutoff
indices = fcluster(Z, t=d_thresh, criterion='distance')
group_ids = list(set(i... | def space_cluster(catalog, d_thresh, show=True) | Cluster a catalog by distance only.
Will compute the matrix of physical distances between events and utilize
the :mod:`scipy.clustering.hierarchy` module to perform the clustering.
:type catalog: obspy.core.event.Catalog
:param catalog: Catalog of events to clustered
:type d_thresh: float
:par... | 3.894737 | 4.043371 | 0.96324 |
initial_spatial_groups = space_cluster(catalog=catalog, d_thresh=d_thresh,
show=False)
# Need initial_spatial_groups to be lists at the moment
initial_spatial_lists = []
for group in initial_spatial_groups:
initial_spatial_lists.append(list(group))... | def space_time_cluster(catalog, t_thresh, d_thresh) | Cluster detections in space and time.
Use to separate repeaters from other events. Clusters by distance
first, then removes events in those groups that are at different times.
:type catalog: obspy.core.event.Catalog
:param catalog: Catalog of events to clustered
:type t_thresh: float
:param t... | 5.31775 | 5.328691 | 0.997947 |
from eqcorrscan.core.match_filter import read_detections
warnings.warn('Legacy function, please use '
'eqcorrscan.core.match_filter.Party.rethreshold.')
old_detections = read_detections(path)
old_thresh = float(old_thresh)
new_thresh = float(new_thresh)
# Be nice, ensure t... | def re_thresh_csv(path, old_thresh, new_thresh, chan_thresh) | Remove detections by changing the threshold.
Can only be done to remove detection by increasing threshold,
threshold lowering will have no effect.
:type path: str
:param path: Path to the .csv detection file
:type old_thresh: float
:param old_thresh: Old threshold MAD multiplier
:type new_... | 4.49917 | 3.912668 | 1.149898 |
# All parallel processing happens on a per-trace basis, we shouldn't create
# more workers than there are traces
n_cores = kwargs.get('cores', cpu_count())
if n_cores is None:
n_cores = cpu_count()
if n_cores > traces:
n_cores = traces
pool = Pool(n_cores)
yield pool
... | def pool_boy(Pool, traces, **kwargs) | A context manager for handling the setup and cleanup of a pool object.
:param Pool: any Class (not instance) that implements the multiprocessing
Pool interface
:param traces: The number of traces to process
:type traces: int | 3.804327 | 3.893357 | 0.977133 |
def multithread(templates, stream, *args, **kwargs):
with pool_boy(ThreadPool, len(stream), **kwargs) as pool:
return _pool_normxcorr(templates, stream, pool=pool, func=func)
return multithread | def _general_multithread(func) | return the general multithreading function using func | 10.137948 | 10.231739 | 0.990833 |
valid_methods = set(list(XCOR_ARRAY_METHODS) + list(XCORR_STREAM_METHODS))
cache = {}
def register(register_str):
if register_str not in valid_methods:
msg = 'register_name must be in %s' % valid_methods
raise ValueError(msg)
def _register(func):
... | def register_array_xcorr(name, func=None, is_default=False) | Decorator for registering correlation functions.
Each function must have the same interface as numpy_normxcorr, which is
*f(templates, stream, pads, *args, **kwargs)* any number of specific kwargs
can be used.
Register_normxcorr can be used as a decorator (with or without arguments)
or as a callab... | 4.262079 | 4.313893 | 0.987989 |
# get the function or register callable
if callable(name_or_func):
func = register_array_xcorr(name_or_func)
else:
func = XCOR_FUNCS[name_or_func or 'default']
assert callable(func), 'func is not callable'
# ensure func has the added methods
if not hasattr(func, 'registered'... | def _get_registerd_func(name_or_func) | get a xcorr function from a str or callable. | 5.251747 | 4.53302 | 1.158553 |
import bottleneck
from scipy.signal.signaltools import _centered
# Generate a template mask
used_chans = ~np.isnan(templates).any(axis=1)
# Currently have to use float64 as bottleneck runs into issues with other
# types: https://github.com/kwgoodman/bottleneck/issues/164
stream = strea... | def numpy_normxcorr(templates, stream, pads, *args, **kwargs) | Compute the normalized cross-correlation using numpy and bottleneck.
:param templates: 2D Array of templates
:type templates: np.ndarray
:param stream: 1D array of continuous data
:type stream: np.ndarray
:param pads: List of ints of pad lengths in the same order as templates
:type pads: list
... | 3.406945 | 3.306499 | 1.030378 |
used_chans = ~np.isnan(templates).any(axis=1)
utilslib = _load_cdll('libutils')
argtypes = [
np.ctypeslib.ndpointer(dtype=np.float32, ndim=1,
flags=native_str('C_CONTIGUOUS')),
ctypes.c_int, ctypes.c_int,
np.ctypeslib.ndpointer(dtype=np.float32, ... | def time_multi_normxcorr(templates, stream, pads, threaded=False, *args,
**kwargs) | Compute cross-correlations in the time-domain using C routine.
:param templates: 2D Array of templates
:type templates: np.ndarray
:param stream: 1D array of continuous data
:type stream: np.ndarray
:param pads: List of ints of pad lengths in the same order as templates
:type pads: list
:pa... | 2.358121 | 2.302719 | 1.02406 |
no_chans = np.zeros(len(templates))
chans = [[] for _ in range(len(templates))]
array_dict_tuple = _get_array_dicts(templates, stream)
stream_dict, template_dict, pad_dict, seed_ids = array_dict_tuple
cccsums = np.zeros([len(templates),
len(stream[0]) - len(templates[0][... | def _time_threaded_normxcorr(templates, stream, *args, **kwargs) | Use the threaded time-domain routine for concurrency
:type templates: list
:param templates:
A list of templates, where each one should be an obspy.Stream object
containing multiple traces of seismic data and the relevant header
information.
:type stream: obspy.core.stream.Stream
... | 3.972523 | 3.926237 | 1.011789 |
# number of threads:
# default to using inner threads
# if `cores` or `cores_outer` passed in then use that
# else if OMP_NUM_THREADS set use that
# otherwise use all available
num_cores_inner = kwargs.get('cores')
num_cores_outer = kwargs.get('cores_outer')
if num_cores_inn... | def _fftw_stream_xcorr(templates, stream, *args, **kwargs) | Apply fftw normxcorr routine concurrently.
:type templates: list
:param templates:
A list of templates, where each one should be an obspy.Stream object
containing multiple traces of seismic data and the relevant header
information.
:type stream: obspy.core.stream.Stream
:param s... | 3.391607 | 3.280921 | 1.033736 |
func = _get_registerd_func(name_or_func)
concur = concurrency or 'stream_xcorr'
if not hasattr(func, concur):
msg = '%s does not support concurrency %s' % (func.__name__, concur)
raise ValueError(msg)
return getattr(func, concur) | def get_stream_xcorr(name_or_func=None, concurrency=None) | Return a function for performing normalized cross correlation on lists of
streams.
:param name_or_func:
Either a name of a registered function or a callable that implements
the standard array_normxcorr signature.
:param concurrency:
Optional concurrency strategy, options are below.
... | 3.425162 | 4.821966 | 0.710325 |
# Do some reshaping
# init empty structures for data storage
template_dict = {}
stream_dict = {}
pad_dict = {}
t_starts = []
stream.sort(['network', 'station', 'location', 'channel'])
for template in templates:
template.sort(['network', 'station', 'location', 'channel'])
... | def _get_array_dicts(templates, stream, copy_streams=True) | prepare templates and stream, return dicts | 3.681725 | 3.599962 | 1.022712 |
num_cores = cpu_count()
if debug >= 1:
data_in = tr.copy()
# Note - might be worth finding spikes in filtered data
filt = tr.copy()
filt.detrend('linear')
try:
filt.filter('bandpass', freqmin=10.0,
freqmax=(tr.stats.sampling_rate / 2) - 1)
except Exce... | def median_filter(tr, multiplier=10, windowlength=0.5,
interp_len=0.05, debug=0) | Filter out spikes in data above a multiple of MAD of the data.
Currently only has the ability to replaces spikes with linear
interpolation. In the future we would aim to fill the gap with something
more appropriate. Works in-place on data.
:type tr: obspy.core.trace.Trace
:param tr: trace to des... | 3.016892 | 3.001506 | 1.005126 |
MAD = np.median(np.abs(window))
thresh = multiplier * MAD
if debug >= 2:
print('Threshold for window is: ' + str(thresh) +
'\nMedian is: ' + str(MAD) +
'\nMax is: ' + str(np.max(window)))
peaks = find_peaks2_short(arr=window,
thresh=... | def _median_window(window, window_start, multiplier, starttime, sampling_rate,
debug=0) | Internal function to aid parallel processing
:type window: numpy.ndarry
:param window: Data to look for peaks in.
:type window_start: int
:param window_start: Index of window start point in larger array, used \
for peak indexing.
:type multiplier: float
:param multiplier: Multiple of MA... | 3.870142 | 3.844437 | 1.006686 |
start_loc = peak_loc - int(0.5 * interp_len)
end_loc = peak_loc + int(0.5 * interp_len)
if start_loc < 0:
start_loc = 0
if end_loc > len(data) - 1:
end_loc = len(data) - 1
fill = np.linspace(data[start_loc], data[end_loc], end_loc - start_loc)
data[start_loc:end_loc] = fill
... | def _interp_gap(data, peak_loc, interp_len) | Internal function for filling gap with linear interpolation
:type data: numpy.ndarray
:param data: data to remove peak in
:type peak_loc: int
:param peak_loc: peak location position
:type interp_len: int
:param interp_len: window to interpolate
:returns: Trace works in-place
:rtype: :c... | 1.693366 | 1.835836 | 0.922395 |
data_in = tr.copy()
_interp_len = int(tr.stats.sampling_rate * interp_len)
if _interp_len < len(template.data):
warnings.warn('Interp_len is less than the length of the template,'
'will used the length of the template!')
_interp_len = len(template.data)
if isin... | def template_remove(tr, template, cc_thresh, windowlength,
interp_len, debug=0) | Looks for instances of template in the trace and removes the matches.
:type tr: obspy.core.trace.Trace
:param tr: Trace to remove spikes from.
:type template: osbpy.core.trace.Trace
:param template: Spike template to look for in data.
:type cc_thresh: float
:param cc_thresh: Cross-correlation t... | 3.672642 | 3.672482 | 1.000044 |
wavfiles = glob.glob(path_name + os.sep + '*')
out_files = [_check_data(wavfile, station, channel, debug=debug)
for wavfile in wavfiles]
out_files = list(set(out_files))
return out_files | def _get_station_file(path_name, station, channel, debug=0) | Helper function to find the correct file.
:type path_name: str
:param path_name: Path to files to check.
:type station: str
:type channel: str
:returns: list of filenames, str | 4.01808 | 4.718683 | 0.851526 |
if debug > 1:
print('Checking ' + wavfile)
st = read(wavfile, headonly=True)
for tr in st:
if tr.stats.station == station and tr.stats.channel == channel:
return wavfile | def _check_data(wavfile, station, channel, debug=0) | Inner loop for parallel checks.
:type wavfile: str
:param wavfile: Wavefile path name to look in.
:type station: str
:param station: Channel name to check for
:type channel: str
:param channel: Channel name to check for
:type debug: int
:param debug: Debug level, if > 1, will output wha... | 3.361378 | 4.679367 | 0.71834 |
available_stations = []
if arc_type.lower() == 'day_vols':
wavefiles = glob.glob(os.path.join(archive, day.strftime('Y%Y'),
day.strftime('R%j.01'), '*'))
for wavefile in wavefiles:
header = read(wavefile, headonly=True)
avai... | def _check_available_data(archive, arc_type, day) | Function to check what stations are available in the archive for a given \
day.
:type archive: str
:param archive: The archive source
:type arc_type: str
:param arc_type: The type of archive, can be:
:type day: datetime.date
:param day: Date to retrieve data for
:returns: list of tuple... | 2.892231 | 2.783625 | 1.039016 |
if os.name == 'nt':
f = io.open(logfile, 'rb')
else:
f = io.open(logfile, 'rb')
phase_err = []
lock = []
# Extract all the phase errors
for line_binary in f:
try:
line = line_binary.decode("utf8", "ignore")
except UnicodeDecodeError:
w... | def rt_time_log(logfile, startdate) | Open and read reftek raw log-file.
Function to open and read a log-file as written by a RefTek RT130
datalogger. The information within is then scanned for timing errors
above the threshold.
:type logfile: str
:param logfile: The logfile to look in
:type startdate: datetime.date
:param sta... | 2.814603 | 2.735601 | 1.028879 |
if os.name == 'nt':
f = open(logfile, 'rb')
else:
f = open(logfile, 'rb')
locations = []
for line_binary in f:
try:
line = line_binary.decode("utf8", "ignore")
except UnicodeDecodeError:
warnings.warn('Cannot decode line, skipping')
... | def rt_location_log(logfile) | Extract location information from a RefTek raw log-file.
Function to read a specific RefTek RT130 log-file and find all location
information.
:type logfile: str
:param logfile: The logfile to look in
:returns: list of tuples of lat, lon, elevation in decimal degrees and km.
:rtype: list | 2.40992 | 2.369858 | 1.016905 |
time_err = []
for stamp in phase_err:
if abs(stamp[1]) > time_thresh:
time_err.append(stamp[0])
return time_err | def flag_time_err(phase_err, time_thresh=0.02) | Find large time errors in list.
Scan through a list of tuples of time stamps and phase errors
and return a list of time stamps with timing errors above a threshold.
.. note::
This becomes important for networks cross-correlations, where
if timing information is uncertain at one site, the r... | 2.791145 | 3.406636 | 0.819326 |
log_files = glob.glob(directory + '/*/0/000000000_00000000')
print('I have ' + str(len(log_files)) + ' log files to scan')
total_phase_errs = []
for i, log_file in enumerate(log_files):
startdate = dt.datetime.strptime(log_file.split('/')[-4][0:7],
'... | def check_all_logs(directory, time_thresh) | Check all the log-files in a directory tree for timing errors.
:type directory: str
:param directory: Directory to search within
:type time_thresh: float
:param time_thresh: Time threshold in seconds
:returns: List of :class:`datetime.datetime` for which error timing is
above threshold, e.... | 3.482264 | 3.56853 | 0.975826 |
num = round(num, dp)
num = '{0:.{1}f}'.format(num, dp)
return num | def _cc_round(num, dp) | Convenience function to take a float and round it to dp padding with zeros
to return a string
:type num: float
:param num: Number to round
:type dp: int
:param dp: Number of decimal places to round to.
:returns: str
>>> print(_cc_round(0.25364, 2))
0.25 | 2.810066 | 5.459241 | 0.514736 |
if str(W1) in [' ', '']:
W1 = 1
elif str(W1) in ['-9', '9', '9.0', '-9.0']:
W1 = 0
elif float(W1) < 0:
warnings.warn('Negative weight found, setting to zero')
W1 = 0
else:
W1 = 1 - (int(W1) / 4.0)
if str(W2) in [' ', '']:
W2 = 1
elif str(W2) ... | def _av_weight(W1, W2) | Function to convert from two seisan weights (0-4) to one hypoDD \
weight(0-1).
:type W1: str
:param W1: Seisan input weight (0-4)
:type W2: str
:param W2: Seisan input weight (0-4)
:returns: str
.. rubric:: Example
>>> print(_av_weight(1, 4))
0.3750
>>> print(_av_weight(0, 0))... | 2.150215 | 2.088986 | 1.02931 |
stalist = []
f = open(path + '/STATION0.HYP', 'r')
for line in f:
if line[1:6].strip() in stations:
station = line[1:6].strip()
lat = line[6:14] # Format is either ddmm.mmS/N or ddmm(.)mmmS/N
if lat[-1] == 'S':
NS = -1
else:
... | def readSTATION0(path, stations) | Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tuples of station, lat, long, elevation
:rtyp... | 2.353655 | 2.22848 | 1.056171 |
event_list = []
sort_list = [(readheader(sfile).origins[0].time, sfile)
for sfile in sfile_list]
sort_list.sort(key=lambda tup: tup[0])
sfile_list = [sfile[1] for sfile in sort_list]
catalog = Catalog()
for i, sfile in enumerate(sfile_list):
event_list.append((i, sf... | def sfiles_to_event(sfile_list) | Write an event.dat file from a list of Seisan events
:type sfile_list: list
:param sfile_list: List of s-files to sort and put into the database
:returns: List of tuples of event ID (int) and Sfile name | 3.381266 | 3.845315 | 0.879321 |
f = open('event.dat', 'w')
for i, event in enumerate(catalog):
try:
evinfo = event.origins[0]
except IndexError:
raise IOError('No origin')
try:
Mag_1 = event.magnitudes[0].mag
except IndexError:
Mag_1 = 0.0
try:
... | def write_event(catalog) | Write obspy.core.event.Catalog to a hypoDD format event.dat file.
:type catalog: obspy.core.event.Catalog
:param catalog: A catalog of obspy events. | 2.587059 | 2.493788 | 1.037401 |
ph_catalog = Catalog()
f = open(ph_file, 'r')
# Topline of each event is marked by # in position 0
for line in f:
if line[0] == '#':
if 'event_text' not in locals():
event_text = {'header': line.rstrip(),
'picks': []}
els... | def read_phase(ph_file) | Read hypoDD phase files into Obspy catalog class.
:type ph_file: str
:param ph_file: Phase file to read event info from.
:returns: Catalog of events from file.
:rtype: :class:`obspy.core.event.Catalog`
>>> from obspy.core.event.catalog import Catalog
>>> # Get the path to the test data
>>... | 3.44852 | 3.544159 | 0.973015 |
ph_event = Event()
# Extract info from header line
# YR, MO, DY, HR, MN, SC, LAT, LON, DEP, MAG, EH, EZ, RMS, ID
header = event_text['header'].split()
ph_event.origins.append(Origin())
ph_event.origins[0].time =\
UTCDateTime(year=int(header[1]), month=int(header[2]),
... | def _phase_to_event(event_text) | Function to convert the text for one event in hypoDD phase format to \
event object.
:type event_text: dict
:param event_text: dict of two elements, header and picks, header is a \
str, picks is a list of str.
:returns: obspy.core.event.Event | 2.464255 | 2.359681 | 1.044317 |
new_template = stack.copy()
# Copy the data before we trim it to keep the stack safe
# Get the earliest time in the template as this is when the detection is
# taken.
mintime = min([tr.stats.starttime for tr in template])
# Generate a list of tuples of (station, channel, delay) with delay i... | def extract_from_stack(stack, template, length, pre_pick, pre_pad,
Z_include=False, pre_processed=True, samp_rate=None,
lowcut=None, highcut=None, filt_order=3) | Extract a multiplexed template from a stack of detections.
Function to extract a new template from a stack of previous detections.
Requires the stack, the template used to make the detections for the \
stack, and we need to know if the stack has been pre-processed.
:type stack: obspy.core.stream.Strea... | 3.352485 | 3.161157 | 1.060525 |
st = Stream()
catalog = Catalog(sorted(catalog, key=lambda e: e.origins[0].time))
all_waveform_info = []
for event in catalog:
for pick in event.picks:
if not pick.waveform_id:
debug_print(
"Pick not associated with waveforms, will not use:"
... | def _download_from_client(client, client_type, catalog, data_pad, process_len,
available_stations=[], all_channels=False, debug=0) | Internal function to handle downloading from either seishub or fdsn client | 3.300844 | 3.258643 | 1.012951 |
# case for catalog only containing one event
if len(catalog) == 1:
return [catalog]
sub_catalogs = []
# Sort catalog by date
catalog.events = sorted(
catalog.events,
key=lambda e: (e.preferred_origin() or e.origins[0]).time)
sub_catalog = Catalog([catalog[0]])
fo... | def _group_events(catalog, process_len, template_length, data_pad) | Internal function to group events into sub-catalogs based on process_len.
:param catalog: Catalog to groups into sub-catalogs
:type catalog: obspy.core.event.Catalog
:param process_len: Length in seconds that data will be processed in
:type process_len: int
:return: List of catalogs
:rtype: li... | 2.772466 | 2.595255 | 1.068283 |
EQcorrscanDeprecationWarning(
"Function is depreciated and will be removed soon. Use "
"template_gen.template_gen instead.")
temp_list = template_gen(
method="from_meta_file", process=False, meta_file=catalog, st=st,
lowcut=None, highcut=None, samp_rate=st[0].stats.sampling_... | def multi_template_gen(catalog, st, length, swin='all', prepick=0.05,
all_horiz=False, delayed=True, plot=False, debug=0,
return_event=False, min_snr=None) | Generate multiple templates from one stream of data.
Thin wrapper around _template_gen to generate multiple templates from
one stream of continuous data. Takes processed (filtered and resampled)
seismic data!
:type catalog: obspy.core.event.Catalog
:param catalog: Events to extract templates for
... | 4.594208 | 3.788029 | 1.212823 |
tic = time.time()
out = func(*args, **kwargs)
toc = time.time()
print('%s took %0.2f seconds' % (name, toc - tic))
return out | def time_func(func, name, *args, **kwargs) | call a func with args and kwargs, print name of func and how
long it took. | 2.032978 | 2.159219 | 0.941534 |
if flength and 2.5 * sp < flength and 100 < flength:
additional_length = flength
elif 2.5 * sp < 100.0:
additional_length = 100
else:
additional_length = 2.5 * sp
synth = np.zeros(int(sp + 10 + additional_length))
# Make the array begin 10 samples before the P
# and ... | def seis_sim(sp, amp_ratio=1.5, flength=False, phaseout='all') | Generate a simulated seismogram from a given S-P time.
Will generate spikes separated by a given S-P time, which are then
convolved with a decaying sine function. The P-phase is simulated by a
positive spike of value 1, the S-arrival is simulated by a decaying
boxcar of maximum amplitude 1.5. These a... | 4.362291 | 4.167744 | 1.046679 |
# Convert SP to samples
sp = int(sp * samp_rate)
# Scan through a range of amplitude ratios
synthetics = [Stream(Trace(seis_sim(sp, a))) for a in amp_range]
for st in synthetics:
for tr in st:
tr.stats.station = 'SYNTH'
tr.stats.channel = 'SH1'
tr.sta... | def SVD_sim(sp, lowcut, highcut, samp_rate,
amp_range=np.arange(-10, 10, 0.01)) | Generate basis vectors of a set of simulated seismograms.
Inputs should have a range of S-P amplitude ratios, in theory to simulate \
a range of focal mechanisms.
:type sp: int
:param sp: S-P time in seconds - will be converted to samples according \
to samp_rate.
:type lowcut: float
:... | 6.845634 | 6.334908 | 1.080621 |
stack = streams[np.argmax([len(stream) for stream in streams])].copy()
if normalize:
for tr in stack:
tr.data = tr.data / np.sqrt(np.mean(np.square(tr.data)))
tr.data = np.nan_to_num(tr.data)
for i in range(1, len(streams)):
for tr in stack:
matchtr =... | def linstack(streams, normalize=True) | Compute the linear stack of a series of seismic streams of \
multiplexed data.
:type streams: list
:param streams: List of streams to stack
:type normalize: bool
:param normalize: Normalize traces before stacking, normalizes by the RMS \
amplitude.
:returns: stacked data
:rtype: :c... | 2.433461 | 2.365436 | 1.028758 |
# First get the linear stack which we will weight by the phase stack
Linstack = linstack(streams)
# Compute the instantaneous phase
instaphases = []
print("Computing instantaneous phase")
for stream in streams:
instaphase = stream.copy()
for tr in instaphase:
ana... | def PWS_stack(streams, weight=2, normalize=True) | Compute the phase weighted stack of a series of streams.
.. note:: It is recommended to align the traces before stacking.
:type streams: list
:param streams: List of :class:`obspy.core.stream.Stream` to stack.
:type weight: float
:param weight: Exponent to the phase stack used for weighting.
:... | 4.380882 | 4.097278 | 1.069218 |
from eqcorrscan.core.match_filter import normxcorr2
from eqcorrscan.utils.plotting import xcorr_plot
traces = deepcopy(trace_list)
if not master:
# Use trace with largest MAD amplitude as master
master = traces[0]
MAD_master = np.median(np.abs(master.data))
for i in ... | def align_traces(trace_list, shift_len, master=False, positive=False,
plot=False) | Align traces relative to each other based on their cross-correlation value.
Uses the :func:`eqcorrscan.core.match_filter.normxcorr2` function to find
the optimum shift to align traces relative to a master event. Either uses
a given master to align traces, or uses the trace with the highest MAD
amplitu... | 2.815433 | 2.271615 | 1.239397 |
dir_name = tempfile.mkdtemp()
yield dir_name
if os.path.exists(dir_name):
shutil.rmtree(dir_name) | def temporary_directory() | make a temporary directory, yeild its name, cleanup on exit | 2.259888 | 2.013845 | 1.122176 |
td = t1 - t2
return (td.seconds + td.days * 24 * 3600) * 10 ** 6 + td.microseconds | def _total_microsec(t1, t2) | Calculate difference between two datetime stamps in microseconds.
:type t1: :class: `datetime.datetime`
:type t2: :class: `datetime.datetime`
:return: int
.. rubric:: Example
>>> print(_total_microsec(UTCDateTime(2013, 1, 1).datetime,
... UTCDateTime(2014, 1, 1).datetime... | 2.612566 | 3.747576 | 0.697135 |
return t.name == family_file.split(os.sep)[-1].split('_detections.csv')[0] | def _templates_match(t, family_file) | Return True if a tribe matches a family file path.
:type t: Tribe
:type family_file: str
:return: bool | 6.497457 | 7.91984 | 0.820403 |
master = template_group[0]
processed_streams = []
kwargs = {
'filt_order': master.filt_order,
'highcut': master.highcut, 'lowcut': master.lowcut,
'samp_rate': master.samp_rate, 'debug': debug,
'parallel': parallel, 'num_cores': cores}
# Processing always needs to be ... | def _group_process(template_group, parallel, debug, cores, stream, daylong,
ignore_length, overlap) | Process data into chunks based on template processing length.
Templates in template_group must all have the same processing parameters.
:type template_group: list
:param template_group: List of Templates.
:type parallel: bool
:param parallel: Whether to use parallel processing or not
:type deb... | 3.741087 | 3.476016 | 1.076257 |
templates = []
if compressed:
arc = tarfile.open(dirname, "r:*")
members = arc.getmembers()
_parfile = [member for member in members
if member.name.split(os.sep)[-1] ==
'template_parameters.csv']
if len(_parfile) == 0:
arc.... | def _par_read(dirname, compressed=True) | Internal write function to read a formatted parameter file.
:type dirname: str
:param dirname: Directory to read the parameter file from.
:type compressed: bool
:param compressed: Whether the directory is compressed or not. | 2.217981 | 2.292312 | 0.967574 |
return not _resolved(os.path.join(base, path)).startswith(base) | def _badpath(path, base) | joinpath will ignore base if path is absolute. | 8.251704 | 8.826242 | 0.934906 |
tip = _resolved(os.path.join(base, os.path.dirname(info.name)))
return _badpath(info.linkname, base=tip) | def _badlink(info, base) | Links are interpreted relative to the directory containing the link | 8.837752 | 7.882366 | 1.121206 |
base = _resolved(".")
for finfo in members:
if _badpath(finfo.name, base):
print(finfo.name, "is blocked (illegal path)")
elif finfo.issym() and _badlink(finfo, base):
print(finfo.name, "is blocked: Hard link to", finfo.linkname)
elif finfo.islnk() and _badl... | def _safemembers(members) | Check members of a tar archive for safety.
Ensure that they do not contain paths or links outside of where we
need them - this would only happen if the archive wasn't made by
eqcorrscan.
:type members: :class:`tarfile.TarFile`
:param members: an open tarfile. | 3.787751 | 3.636386 | 1.041625 |
with open(filename, 'w') as f:
for detection in family.detections:
det_str = ''
for key in detection.__dict__.keys():
if key == 'event' and detection.__dict__[key] is not None:
value = str(detection.event.resource_id)
elif key ... | def _write_family(family, filename) | Write a family to a csv file.
:type family: :class:`eqcorrscan.core.match_filter.Family`
:param family: Family to write to file
:type filename: str
:param filename: File to write to. | 3.094858 | 3.273602 | 0.945398 |
detections = []
with open(fname, 'r') as f:
for line in f:
det_dict = {}
gen_event = False
for key_pair in line.rstrip().split(';'):
key = key_pair.split(': ')[0].strip()
value = key_pair.split(': ')[-1].strip()
if ... | def _read_family(fname, all_cat, template) | Internal function to read csv family files.
:type fname: str
:param fname: Filename
:return: list of Detection | 2.761684 | 2.780448 | 0.993251 |
party = Party()
party.read(filename=fname, read_detection_catalog=read_detection_catalog)
return party | def read_party(fname=None, read_detection_catalog=True) | Read detections and metadata from a tar archive.
:type fname: str
:param fname:
Filename to read from, if this contains a single Family, then will
return a party of length = 1
:type read_detection_catalog: bool
:param read_detection_catalog:
Whether to read the detection catalog... | 3.191903 | 6.218693 | 0.513276 |
f = open(fname, 'r')
detections = []
for index, line in enumerate(f):
if index == 0:
continue # Skip header
if line.rstrip().split('; ')[0] == 'Template name':
continue # Skip any repeated headers
detection = line.rstrip().split('; ')
detection[... | def read_detections(fname) | Read detections from a file to a list of Detection objects.
:type fname: str
:param fname: File to read from, must be a file written to by \
Detection.write.
:returns: list of :class:`eqcorrscan.core.match_filter.Detection`
:rtype: list
.. note::
:class:`eqcorrscan.core.match_filt... | 3.106145 | 3.278067 | 0.947554 |
catalog = get_catalog(detections)
catalog.write(filename=fname, format=format) | def write_catalog(detections, fname, format="QUAKEML") | Write events contained within detections to a catalog file.
:type detections: list
:param detections: list of eqcorrscan.core.match_filter.Detection
:type fname: str
:param fname: Name of the file to write to
:type format: str
:param format: File format to use, see obspy.core.event.Catalog.writ... | 3.616799 | 5.36451 | 0.674209 |
catalog = Catalog()
for detection in detections:
if detection.event:
catalog.append(detection.event)
return catalog | def get_catalog(detections) | Generate an :class:`obspy.core.event.Catalog` from list of \
:class:`Detection`'s.
:type detections: list
:param detections: list of :class:`eqcorrscan.core.match_filter.Detection`
:returns: Catalog of detected events.
:rtype: :class:`obspy.core.event.Catalog`
.. warning::
Will only w... | 4.278502 | 5.117218 | 0.836099 |
streams = []
for detection in detections:
cut_stream = Stream()
for pick in detection.event.picks:
tr = stream.select(station=pick.waveform_id.station_code,
channel=pick.waveform_id.channel_code)
if len(tr) == 0:
print('... | def extract_from_stream(stream, detections, pad=5.0, length=30.0) | Extract waveforms for a list of detections from a stream.
:type stream: obspy.core.stream.Stream
:param stream: Stream containing the detections.
:type detections: list
:param detections: list of eqcorrscan.core.match_filter.detection
:type pad: float
:param pad: Pre-detection extract time in s... | 3.156357 | 2.826022 | 1.11689 |
array_xcorr = get_array_xcorr()
# Check that we have been passed numpy arrays
if type(template) != np.ndarray or type(image) != np.ndarray:
print('You have not provided numpy arrays, I will not convert them')
return 'NaN'
if len(template) > len(image):
ccc = array_xcorr(
... | def normxcorr2(template, image) | Thin wrapper to eqcorrscan.utils.correlate functions.
:type template: numpy.ndarray
:param template: Template array
:type image: numpy.ndarray
:param image:
Image to scan the template through. The order of these
matters, if you put the template after the image you will get a
re... | 3.447913 | 3.925 | 0.878449 |
return [fam for fam in self.families
if fam.template.name == template_name][0] | def select(self, template_name) | Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family | 6.010529 | 7.792624 | 0.77131 |
self.families.sort(key=lambda x: x.template.name)
return self | def sort(self) | Sort the families by template name.
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='b')),
... Family(template=Template(name='a'))])
>>> party[0]
Family of 0 detections from template b
>>> party.sort()[0]
Fa... | 9.859632 | 6.735915 | 1.46374 |
if dates is None:
raise MatchFilterError('Need a list defining a date range')
new_party = Party()
for fam in self.families:
new_fam = Family(
template=fam.template,
detections=[det for det in fam if
date... | def filter(self, dates=None, min_dets=1) | Return a new Party filtered according to conditions.
Return a new Party with only detections within a date range and
only families with a minimum number of detections.
:type dates: list of obspy.core.UTCDateTime objects
:param dates: A start and end date for the new Party
:type... | 4.477838 | 3.868263 | 1.157584 |
all_dets = []
if dates:
new_party = self.filter(dates=dates, min_dets=min_dets)
for fam in new_party.families:
all_dets.extend(fam.detections)
else:
for fam in self.families:
all_dets.extend(fam.detections)
fig ... | def plot(self, plot_grouped=False, dates=None, min_dets=1, rate=False,
**kwargs) | Plot the cumulative detections in time.
:type plot_grouped: bool
:param plot_grouped:
Whether to plot all families together (plot_grouped=True), or each
as a separate line.
:type dates: list
:param dates: list of obspy.core.UTCDateTime objects bounding the
... | 2.879286 | 2.817469 | 1.021941 |
for family in self.families:
rethresh_detections = []
for d in family.detections:
if new_threshold_type == 'MAD' and d.threshold_type == 'MAD':
new_thresh = (d.threshold /
d.threshold_input) * new_threshold
... | def rethreshold(self, new_threshold, new_threshold_type='MAD') | Remove detections from the Party that are below a new threshold.
.. Note:: threshold can only be set higher.
.. Warning::
Works in place on Party.
:type new_threshold: float
:param new_threshold: New threshold level
:type new_threshold_type: str
:param new_... | 2.950644 | 2.753905 | 1.07144 |
all_detections = []
for fam in self.families:
all_detections.extend(fam.detections)
if timing == 'detect':
if metric == 'avg_cor':
detect_info = [(d.detect_time, d.detect_val / d.no_chans)
for d in all_detections]
... | def decluster(self, trig_int, timing='detect', metric='avg_cor') | De-cluster a Party of detections by enforcing a detection separation.
De-clustering occurs between events detected by different (or the same)
templates. If multiple detections occur within trig_int then the
preferred detection will be determined by the metric argument. This
can be eithe... | 2.55256 | 2.39832 | 1.064312 |
if catalog_format not in CAT_EXT_MAP.keys():
raise TypeError("{0} is not supported".format(catalog_format))
if format.lower() == 'csv':
if os.path.isfile(filename):
raise MatchFilterError(
'Will not overwrite existing file: %s' % filen... | def write(self, filename, format='tar', write_detection_catalog=True,
catalog_format="QUAKEML", debug=0) | Write Family out, select output format.
:type format: str
:param format:
One of either 'tar', 'csv', or any obspy supported
catalog output. See note below on formats
:type filename: str
:param filename: Path to write file to.
:type debug: int
:par... | 3.332225 | 3.405083 | 0.978603 |
tribe = Tribe()
families = []
if filename is None:
# If there is no filename given, then read the example.
filename = os.path.join(os.path.dirname(__file__),
'..', 'tests', 'test_data',
'test... | def read(self, filename=None, read_detection_catalog=True) | Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_detection_catalog:
Whether to read the detection catalog or not, if Fa... | 3.522471 | 3.44208 | 1.023355 |
catalog = Catalog()
for fam in self.families:
if len(fam.catalog) != 0:
catalog.events.extend(fam.catalog.events)
return catalog | def get_catalog(self) | Get an obspy catalog object from the party.
:returns: :class:`obspy.core.event.Catalog`
.. rubric:: Example
>>> party = Party().read()
>>> cat = party.get_catalog()
>>> print(len(cat))
4 | 5.457133 | 7.959255 | 0.685634 |
declustered = Party()
for family in self.families:
fam = Family(family.template)
for d in family.detections:
if d.no_chans > min_chans:
fam.detections.append(d)
declustered.families.append(fam)
self.families = declu... | def min_chans(self, min_chans) | Remove detections with fewer channels used than min_chans
:type min_chans: int
:param min_chans: Minimum number of channels to allow a detection.
:return: Party
.. Note:: Works in place on Party.
.. rubric:: Example
>>> party = Party().read()
>>> print(len(par... | 4.317537 | 3.923143 | 1.10053 |
_detections = []
[_detections.append(d) for d in self.detections
if not _detections.count(d)]
self.detections = _detections
return self | def _uniq(self) | Get list of unique detections.
Works in place.
.. rubric:: Example
>>> family = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0),
... no_chans=8, detect_val=4.2, threshold=1.2,
... | 4.361703 | 5.852768 | 0.745238 |
self.detections = sorted(self.detections, key=lambda d: d.detect_time)
return self | def sort(self) | Sort by detection time.
.. rubric:: Example
>>> family = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0) + 200,
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeo... | 5.400536 | 5.612342 | 0.962261 |
cumulative_detections(
detections=self.detections, plot_grouped=plot_grouped) | def plot(self, plot_grouped=False) | Plot the cumulative number of detections in time.
.. rubric:: Example
>>> family = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0) + 200,
... no_chans=8, detect_val=4.2, threshold=1.2,
... | 10.20871 | 12.431818 | 0.821176 |
Party(families=[self]).write(filename=filename, format=format)
return | def write(self, filename, format='tar') | Write Family out, select output format.
:type format: str
:param format:
One of either 'tar', 'csv', or any obspy supported
catalog output.
:type filename: str
:param filename: Path to write file to.
.. Note:: csv format will write out detection objects,... | 20.677668 | 51.957973 | 0.397969 |
return Party(families=[self]).lag_calc(
stream=stream, pre_processed=pre_processed, shift_len=shift_len,
min_cc=min_cc, horizontal_chans=horizontal_chans,
vertical_chans=vertical_chans, cores=cores,
interpolate=interpolate, plot=plot, parallel=parallel,
... | def lag_calc(self, stream, pre_processed, shift_len=0.2, min_cc=0.4,
horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'],
cores=1, interpolate=False, plot=False, parallel=True,
process_cores=None, debug=0) | Compute picks based on cross-correlation alignment.
:type stream: obspy.core.stream.Stream
:param stream:
All the data needed to cut from - can be a gappy Stream.
:type pre_processed: bool
:param pre_processed:
Whether the stream has been pre-processed or not to ... | 2.009759 | 2.427363 | 0.82796 |
for key in self.__dict__.keys():
if key in ['name', 'st', 'prepick', 'event', 'template_info']:
continue
if not self.__dict__[key] == other.__dict__[key]:
return False
return True | def same_processing(self, other) | Check is the templates are processed the same.
.. rubric:: Example
>>> template_a = Template(
... name='a', st=read(), lowcut=2.0, highcut=8.0, samp_rate=100,
... filt_order=4, process_length=3600, prepick=0.5)
>>> template_b = template_a.copy()
>>> template_a.s... | 4.845606 | 3.850281 | 1.258507 |
if format == 'tar':
Tribe(templates=[self]).write(filename=filename)
else:
self.st.write(filename, format=format)
return self | def write(self, filename, format='tar') | Write template.
:type filename: str
:param filename:
Filename to write to, if it already exists it will be opened and
appended to, otherwise it will be created.
:type format: str
:param format:
Format to write to, either 'tar' (to retain metadata), or... | 8.243391 | 15.535327 | 0.530622 |
tribe = Tribe()
tribe.read(filename=filename)
if len(tribe) > 1:
raise IOError('Multiple templates in file')
for key in self.__dict__.keys():
self.__dict__[key] = tribe[0].__dict__[key]
return self | def read(self, filename) | Read template from tar format with metadata.
:type filename: str
:param filename: Filename to read template from.
.. rubric:: Example
>>> template_a = Template(
... name='a', st=read(), lowcut=2.0, highcut=8.0, samp_rate=100,
... filt_order=4, process_length=36... | 4.142946 | 4.735505 | 0.874869 |
if method in ['from_meta_file', 'from_seishub', 'from_client',
'multi_template_gen']:
raise NotImplementedError('Method is not supported, '
'use Tribe.construct instead.')
streams, events, process_lengths = template_gen.tem... | def construct(self, method, name, lowcut, highcut, samp_rate, filt_order,
prepick, **kwargs) | Construct a template using a given method.
:param method:
Method to make the template,
see :mod:`eqcorrscan.core.template_gen` for possible methods.
:type method: str
:type name: str
:param name: Name for the template
:type lowcut: float
:param lo... | 4.136262 | 2.850527 | 1.451052 |
self.templates = sorted(self.templates, key=lambda x: x.name)
return self | def sort(self) | Sort the tribe, sorts by template name.
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... Template(name='a')])
>>> tribe.sort()
Tribe of 3 templates
>>> tribe[0] # doctest: +NORMALIZE_WHITESPACE
... | 5.278604 | 7.622087 | 0.69254 |
return [t for t in self.templates if t.name == template_name][0] | def select(self, template_name) | Select a particular template from the tribe.
:type template_name: str
:param template_name: Template name to look-up
:return: Template
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... Template(name='a... | 3.771569 | 9.57455 | 0.393916 |
self.templates = [t for t in self.templates if t != template]
return self | def remove(self, template) | Remove a template from the tribe.
:type template: :class:`eqcorrscan.core.match_filter.Template`
:param template: Template to remove from tribe
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... Template(name='... | 3.843171 | 8.893993 | 0.432109 |
if catalog_format not in CAT_EXT_MAP.keys():
raise TypeError("{0} is not supported".format(catalog_format))
if not os.path.isdir(filename):
os.makedirs(filename)
self._par_write(filename)
tribe_cat = Catalog()
for t in self.templates:
... | def write(self, filename, compress=True, catalog_format="QUAKEML") | Write the tribe to a file using tar archive formatting.
:type filename: str
:param filename:
Filename to write to, if it exists it will be appended to.
:type compress: bool
:param compress:
Whether to compress the tar archive or not, if False then will
... | 2.976739 | 2.920478 | 1.019264 |
filename = dirname + '/' + 'template_parameters.csv'
with open(filename, 'w') as parfile:
for template in self.templates:
for key in template.__dict__.keys():
if key not in ['st', 'event']:
parfile.write(key + ': ' +
... | def _par_write(self, dirname) | Internal write function to write a formatted parameter file.
:type dirname: str
:param dirname: Directory to write the parameter file to. | 3.662132 | 4.12549 | 0.887684 |
with tarfile.open(filename, "r:*") as arc:
temp_dir = tempfile.mkdtemp()
arc.extractall(path=temp_dir, members=_safemembers(arc))
tribe_dir = glob.glob(temp_dir + os.sep + '*')[0]
self._read_from_folder(dirname=tribe_dir)
shutil.rmtree(temp_dir)
... | def read(self, filename) | Read a tribe of templates from a tar formatted file.
:type filename: str
:param filename: File to read templates from.
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c', st=read())])
>>> tribe.write('test_tribe')
Tribe of 1 templates
>>> tribe_... | 4.373862 | 4.779487 | 0.915132 |
templates = _par_read(dirname=dirname, compressed=False)
t_files = glob.glob(dirname + os.sep + '*.ms')
tribe_cat_file = glob.glob(os.path.join(dirname, "tribe_cat.*"))
if len(tribe_cat_file) != 0:
tribe_cat = read_events(tribe_cat_file[0])
else:
... | def _read_from_folder(self, dirname) | Internal folder reader.
:type dirname: str
:param dirname: Folder to read from. | 3.775856 | 3.886342 | 0.971571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.