code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from eqcorrscan.utils import clustering tribes = [] func = getattr(clustering, method) if method in ['space_cluster', 'space_time_cluster']: cat = Catalog([t.event for t in self.templates]) groups = func(cat, **kwargs) for group in groups: ...
def cluster(self, method, **kwargs)
Cluster the tribe. Cluster templates within a tribe: returns multiple tribes each of which could be stacked. :type method: str :param method: Method of stacking, see :mod:`eqcorrscan.utils.clustering` :return: List of tribes. .. rubric:: Example
5.727488
3.887985
1.473125
templates, catalog, process_lengths = template_gen.template_gen( method=method, lowcut=lowcut, highcut=highcut, filt_order=filt_order, samp_rate=samp_rate, prepick=prepick, return_event=True, save_progress=save_progress, **kwargs) for template, event, process...
def construct(self, method, lowcut, highcut, samp_rate, filt_order, prepick, save_progress=False, **kwargs)
Generate a Tribe of Templates. See :mod:`eqcorrscan.core.template_gen` for available methods. :param method: Method of Tribe generation. :param kwargs: Arguments for the given method. :type lowcut: float :param lowcut: Low cut (Hz), if set to None will not apply a l...
4.354722
4.032381
1.079938
mode = 'w' if append and os.path.isfile(fname): mode = 'a' header = '; '.join(['Template name', 'Detection time (UTC)', 'Number of channels', 'Channel list', 'Detection value', 'Threshold', '...
def write(self, fname, append=True)
Write detection to csv formatted file. Will append if append==True and file exists :type fname: str :param fname: Full path to file to open and write to. :type append: bool :param append: Set to true to append to an existing file, if True \ and file doesn't exist, w...
3.338042
3.491107
0.956156
if template is not None and template.name != self.template_name: print("Template names do not match: {0}: {1}".format( template.name, self.template_name)) return # Detect time must be valid QuakeML uri within resource_id. # This will write a forma...
def _calculate_event(self, template=None, template_st=None)
Calculate an event for this detection using a given template. :type template: Template :param template: The template that made this detection :type template_st: `obspy.core.stream.Stream` :param template_st: Template stream, used to calculate pick times, not needed if ...
4.091574
3.811225
1.073559
# We want to download some QuakeML files from the New Zealand GeoNet # network, GeoNet currently doesn't support FDSN event queries, so we # have to work around to download quakeml from their quakeml.geonet site. client = Client(network_code) # We want to download a few events from an earthqua...
def mktemplates(network_code='GEONET', publicIDs=['2016p008122', '2016p008353', '2016p008155', '2016p008194'], plot=True)
Functional wrapper to make templates
6.997546
7.036327
0.994488
# Locate the slowness file information gridfiles = [] stations_out = [] for station in stations: gridfiles += (glob.glob(path + '*.' + phase + '.' + station + '.time.csv')) if glob.glob(path + '*.' + phase + '.' + station + '*.csv'): stations_out +=...
def _read_tt(path, stations, phase, phaseout='S', ps_ratio=1.68, lags_switch=True)
Read in .csv files of slowness generated from Grid2Time. Converts these data to a useful format here. It should be noted that this can read either P or S travel-time grids, not both at the moment. :type path: str :param path: The path to the .csv Grid2Time outputs :type stations: list :pa...
3.281991
3.008185
1.09102
resamp_nodes = [] resamp_lags = [] # Cut the volume for i, node in enumerate(nodes): # If the node is within the volume range, keep it if mindepth < float(node[2]) < maxdepth and\ corners.contains_point(node[0:2]): resamp_nodes.append(node) ...
def _resample_grid(stations, nodes, lags, mindepth, maxdepth, corners)
Resample the lagtime grid to a given volume. For use if the grid from Grid2Time is too large or you want to run a faster, downsampled scan. :type stations: list :param stations: List of station names from in the form where stations[i] refers to nodes[i][:] and lags[i][:] :type node...
4.566091
4.157295
1.098332
netdif = abs((lags.T - lags.T[0]).sum(axis=1).reshape(1, len(nodes))) \ > threshold for i in range(len(nodes)): _netdif = abs((lags.T - lags.T[i]).sum(axis=1).reshape(1, len(nodes)))\ > threshold netdif = np.concatenate((netdif, _netdif), axis=0) ...
def _rm_similarlags(stations, nodes, lags, threshold)
Remove nodes that have a very similar network moveout to another node. This function will, for each node, calculate the difference in lagtime at each station at every node, then sum these for each node to get a cumulative difference in network moveout. This will result in an array of arrays with zeros...
2.709805
2.725359
0.994293
cum_net_resp = np.load('tmp' + str(instance) + '/node_' + str(node_lis[0]) + '.npy')[0] os.remove('tmp' + str(instance) + '/node_' + str(node_lis[0]) + '.npy') indices = np.ones(len(cum_net_resp)) * node_lis[0] for i in node_lis[1:]: node_energy = np.load('tmp' + ...
def _cum_net_resp(node_lis, instance=0)
Compute the cumulative network response by reading saved energy .npy files. :type node_lis: numpy.ndarray :param node_lis: List of nodes (ints) to read from :type instance: int :param instance: Instance flag for parallel workflows, defaults to 0. :returns: cumulative network response :rtype: n...
2.331495
2.385843
0.977221
cum_net_resp = np.nan_to_num(cum_net_resp) # Force no NaNs if np.isnan(cum_net_resp).any(): raise ValueError("Nans present") print('Mean of data is: ' + str(np.median(cum_net_resp))) print('RMS of data is: ' + str(np.sqrt(np.mean(np.square(cum_net_resp))))) print('MAD of data is: ' + s...
def _find_detections(cum_net_resp, nodes, threshold, thresh_type, samp_rate, realstations, length)
Find detections within the cumulative network response. :type cum_net_resp: numpy.ndarray :param cum_net_resp: Array of cumulative network response for nodes :type nodes: list :param nodes: Nodes associated with the source of energy in the \ cum_net_resp :type threshold: float :param th...
2.939744
2.804686
1.048154
stream = stream_in.copy() # Copy the data before we remove stations # First check that all channels in stream have data of the same length maxlen = np.max([len(tr.data) for tr in stream]) if maxlen == 0: warnings.warn('template without data') return 0.0, len(stream) if not stat...
def coherence(stream_in, stations=['all'], clip=False)
Determine the average network coherence of a given template or detection. You will want your stream to contain only signal as noise will reduce the coherence (assuming it is incoherent random noise). :type stream_in: obspy.core.stream.Stream :param stream_in: The stream of seismic data you want to cal...
2.741144
2.703576
1.013896
min_fftlen = int(stream[0][0].data.shape[0] + detector.data[0].shape[0] - Nc) fftlen = scipy.fftpack.next_fast_len(min_fftlen) mplen = stream[0][0].data.shape[0] ulen = detector.data[0].shape[0] num_st_fd = [np.fft.rfft(tr.data, n=fftlen) for tr in stream[0...
def _do_ffts(detector, stream, Nc)
Perform ffts on data, detector and denominator boxcar :type detector: eqcorrscan.core.subspace.Detector :param detector: Detector object for doing detecting :type stream: list of obspy.core.stream.Stream :param stream: List of streams processed according to detector :type Nc: int :param Nc: Num...
4.001939
3.603515
1.110565
num_cor = np.multiply(det_freq, data_freq) # Numerator convolution den_cor = np.multiply(w, data_freq_sq) # Denominator convolution # Do inverse fft # First and last Nt - 1 samples are invalid; clip them off num_ifft = np.real(np.fft.irfft(num_cor))[:, ulen-1:mplen:Nc] denominator = np.re...
def _det_stat_freq(det_freq, data_freq_sq, data_freq, w, Nc, ulen, mplen)
Compute detection statistic in the frequency domain :type det_freq: numpy.ndarray :param det_freq: detector in freq domain :type data_freq_sq: numpy.ndarray :param data_freq_sq: squared data in freq domain :type data_freq: numpy.ndarray :param data_freq: data in freq domain :type w: numpy.n...
5.750855
6.114059
0.940595
stack = stream[0].data for tr in stream[1:]: stack = np.dstack(np.array([stack, tr.data])) multiplex = stack.reshape(stack.size, ) return multiplex
def multi(stream)
Internal multiplexer for multiplex_detect. :type stream: obspy.core.stream.Stream :param stream: Stream to multiplex :return: trace of multiplexed data :rtype: obspy.core.trace.Trace .. Note: Requires all channels to be the same length. Maps a standard multiplexed stream of seismic data to a...
6.276159
5.423364
1.157245
from multiprocessing import Pool, cpu_count # First check that detector parameters are the same parameters = [] detections = [] for detector in detectors: parameter = (detector.lowcut, detector.highcut, detector.filt_order, detector.sampling_rate, ...
def subspace_detect(detectors, stream, threshold, trig_int, moveout=0, min_trig=1, parallel=True, num_cores=None)
Conduct subspace detection with chosen detectors. :type detectors: list :param detectors: list of :class:`eqcorrscan.core.subspace.Detector` to be used for detection. :type stream: obspy.core.stream.Stream :param stream: Stream to detect within. :type threshold: float :param thr...
2.410128
2.42211
0.995053
self.lowcut = lowcut self.highcut = highcut self.filt_order = filt_order self.sampling_rate = sampling_rate self.name = name self.multiplex = multiplex # Pre-process data p_streams, stachans = _subspace_process( streams=copy.deepcopy(s...
def construct(self, streams, lowcut, highcut, filt_order, sampling_rate, multiplex, name, align, shift_len=0, reject=0.3, no_missed=True, plot=False)
Construct a subspace detector from a list of streams, full rank. Subspace detector will be full-rank, further functions can be used \ to select the desired dimensions. :type streams: list :param streams: List of :class:`obspy.core.stream.Stream` to be used to generate ...
3.489916
3.444882
1.013073
# Take leftmost 'dimension' input basis vectors for i, channel in enumerate(self.u): if self.v[i].shape[1] < dimension: raise IndexError('Channel is max dimension %s' % self.v[i].shape[1]) self.data[i] = channel[:, 0:dimen...
def partition(self, dimension)
Partition subspace into desired dimension. :type dimension: int :param dimension: Maximum dimension to use.
7.245292
7.296092
0.993037
if show: return subspace_fc_plot(detector=self, stachans=stachans, size=size, show=show) percent_capture = 0 if np.isinf(self.dimension): return 100 for channel in self.sigma: fc = np.sum(channel[0:self.dime...
def energy_capture(self, stachans='all', size=(10, 7), show=False)
Calculate the average percentage energy capture for this subspace. :return: Percentage energy capture :rtype: float
5.242532
4.823985
1.086764
return _detect(detector=self, st=st, threshold=threshold, trig_int=trig_int, moveout=moveout, min_trig=min_trig, process=process, extract_detections=extract_detections, debug=debug, cores=cores)
def detect(self, st, threshold, trig_int, moveout=0, min_trig=0, process=True, extract_detections=False, cores=1, debug=0)
Detect within continuous data using the subspace method. :type st: obspy.core.stream.Stream :param st: Un-processed stream to detect within using the subspace detector. :type threshold: float :param threshold: Threshold value for detections between 0-1 :type trig_int...
1.907498
2.437174
0.782668
f = h5py.File(filename, "w") # Must store eqcorrscan version number, username would be useful too. data_group = f.create_group(name="data") for i, data in enumerate(self.data): dset = data_group.create_dataset(name="data_" + str(i), ...
def write(self, filename)
Write detector to a file - uses HDF5 file format. Meta-data are stored alongside numpy data arrays. See h5py.org for \ details of the methods. :type filename: str :param filename: Filename to save the detector to.
2.10069
2.099559
1.000539
f = h5py.File(filename, "r") self.data = [] for i in range(f['data'].attrs['length']): self.data.append(f['data']['data_' + str(i)].value) self.u = [] for i in range(f['u'].attrs['length']): self.u.append(f['u']['u_' + str(i)].value) self....
def read(self, filename)
Read detector from a file, must be HDF5 format. Reads a Detector object from an HDF5 file, usually created by \ eqcorrscan. :type filename: str :param filename: Filename to save the detector to.
1.966662
2.056052
0.956523
return subspace_detector_plot(detector=self, stachans=stachans, size=size, show=show)
def plot(self, stachans='all', size=(10, 7), show=True)
Plot the output basis vectors for the detector at the given dimension. Corresponds to the first n horizontal vectors of the V matrix. :type stachans: list :param stachans: list of tuples of station, channel pairs to plot. :type stachans: list :param stachans: List of tuples of ...
6.802861
3.848461
1.767683
lines = open(os.path.join(*path), 'r').readlines()[2:] return [s.strip() for s in lines if s.strip() != '']
def export_symbols(*path)
Required for windows systems - functions defined in libutils.def.
3.707255
3.67806
1.007937
R = 6371.009 # Radius of the Earth in km dlat = np.radians(abs(loc1[0] - loc2[0])) dlong = np.radians(abs(loc1[1] - loc2[1])) ddepth = abs(loc1[2] - loc2[2]) mean_lat = np.radians((loc1[0] + loc2[0]) / 2) dist = R * np.sqrt(dlat ** 2 + (np.cos(mean_lat) * dlong) ** 2) dist = np.sqrt(di...
def dist_calc(loc1, loc2)
Function to calculate the distance in km between two points. Uses the flat Earth approximation. Better things are available for this, like `gdal <http://www.gdal.org/>`_. :type loc1: tuple :param loc1: Tuple of lat, lon, depth (in decimal degrees and km) :type loc2: tuple :param loc2: Tuple of...
2.016729
2.142003
0.941516
counts = Counter(magnitudes) df = np.zeros(len(counts)) mag_steps = np.zeros(len(counts)) grad = np.zeros(len(counts) - 1) grad_points = grad.copy() for i, magnitude in enumerate(sorted(counts.keys(), reverse=True)): mag_steps[i] = magnitude if i > 0: df[i] = cou...
def calc_max_curv(magnitudes, plotvar=False)
Calculate the magnitude of completeness using the maximum curvature method. :type magnitudes: list :param magnitudes: List of magnitudes from which to compute the maximum curvature which will give an estimate of the magnitude of completeness given the assumption of a power-law scaling. ...
1.83405
1.88606
0.972424
# Note Wood anderson sensitivity is 2080 as per Uhrhammer & Collins 1990 PAZ_WA = {'poles': [-6.283 + 4.7124j, -6.283 - 4.7124j], 'zeros': [0 + 0j], 'gain': 1.0, 'sensitivity': 2080} if velocity: PAZ_WA['zeros'] = [0 + 0j, 0 + 0j] # De-trend data trace.detrend('simple') ...
def _sim_WA(trace, PAZ, seedresp, water_level, velocity=False)
Remove the instrument response from a trace and simulate a Wood-Anderson. Returns a de-meaned, de-trended, Wood Anderson simulated trace in its place. Works in-place on data and will destroy your original data, copy the trace before giving it to this function! :type trace: obspy.core.trace.Trace ...
3.462025
3.127048
1.107123
turning_points = [] # A list of tuples of (amplitude, sample) for i in range(1, len(data) - 1): if (data[i] < data[i - 1] and data[i] < data[i + 1]) or\ (data[i] > data[i - 1] and data[i] > data[i + 1]): turning_points.append((data[i], i)) if len(turning_points) >= 1: ...
def _max_p2t(data, delta)
Finds the maximum peak-to-trough amplitude and period. Originally designed to be used to calculate magnitudes (by \ taking half of the peak-to-trough amplitude as the peak amplitude). :type data: numpy.ndarray :param data: waveform trace to find the peak-to-trough in. :type delta: float :param ...
2.101549
2.031645
1.034407
with open(gsefile, 'r') as f: # First line should start with CAL2 header = f.readline() if not header[0:4] == 'CAL2': raise IOError('Unknown format for GSE file, only coded for CAL2') station = header.split()[1] channel = header.split()[2] sensor = he...
def _GSE2_PAZ_read(gsefile)
Read the instrument response information from a GSE Poles and Zeros file. Formatted for files generated by the SEISAN program RESP. Format must be CAL2, not coded for any other format at the moment, contact the authors to add others in. :type gsefile: string :param gsefile: Path to GSE file ...
3.002113
2.791595
1.075411
possible_respfiles = glob.glob(directory + os.path.sep + 'RESP.' + network + '.' + station + '.*.' + channel) # GeoNet RESP naming possible_respfiles += glob.glob(directory + os.path.sep + 'RESP.' + n...
def _find_resp(station, channel, network, time, delta, directory)
Helper function to find the response information. Works for a given station and channel at a given time and return a dictionary of poles and zeros, gain and sensitivity. :type station: str :param station: Station name (as in the response files) :type channel: str :param channel: Channel name (...
4.232015
4.322282
0.979116
a, b = itertools.tee(iterable) next(b, None) if sys.version_info.major == 2: return itertools.izip(a, b) else: return zip(a, b)
def _pairwise(iterable)
Wrapper on itertools for SVD_magnitude.
2.112878
2.212131
0.955132
print('Depreciated, use svd_moments instead') return svd_moments(u=U, s=s, v=V, stachans=stachans, event_list=event_list, n_svs=n_SVs)
def SVD_moments(U, s, V, stachans, event_list, n_SVs=4)
Depreciated.
2.616929
2.244124
1.166125
cat_out = catalog.copy() if mindepth is not None: for event in cat_out: try: origin = _get_origin(event) except IOError: continue if origin.depth < mindepth * 1000: cat_out.events.remove(event) if maxdepth is no...
def spatial_clip(catalog, corners, mindepth=None, maxdepth=None)
Clip the catalog to a spatial box, can be irregular. Can only be irregular in 2D, depth must be between bounds. :type catalog: :class:`obspy.core.catalog.Catalog` :param catalog: Catalog to clip. :type corners: :class:`matplotlib.path.Path` :param corners: Corners to clip the catalog to :type ...
1.893922
1.923494
0.984626
if event.preferred_origin() is not None: origin = event.preferred_origin() elif len(event.origins) > 0: origin = event.origins[0] else: raise IndexError('No origin set, cannot constrain') return origin
def _get_origin(event)
Get the origin of an event. :type event: :class:`obspy.core.event.Event` :param event: Event to get the origin of. :return: :class:`obspy.core.event.Origin`
3.614987
3.8118
0.948367
try: import ConfigParser except ImportError: import configparser as ConfigParser import ast f = open(infile, 'r') print('Reading parameters with the following header:') for line in f: if line[0] == '#': print(line.rstrip('\n').lstrip('\n')) f.close() ...
def read_parameters(infile='../parameters/EQcorrscan_parameters.txt')
Read the default parameters from file. :type infile: str :param infile: Full path to parameter file. :returns: parameters read from file. :rtype: :class:`eqcorrscan.utils.parameters.EQcorrscanParameters`
2.303109
2.300641
1.001073
outpath = os.sep.join(outfile.split(os.sep)[0:-1]) if len(outpath) > 0 and not os.path.isdir(outpath): msg = ' '.join([os.path.join(outfile.split(os.sep)[0:-1]), 'does not exist, check path.']) raise IOError(msg) # Make sure that the u...
def write(self, outfile='../parameters/EQcorrscan_parameters.txt', overwrite=False)
Function to write the parameters to a file - user readable. :type outfile: str :param outfile: Full path to filename to store parameters in. :type overwrite: bool :param overwrite: Whether to overwrite the old file or not.
3.190906
3.238972
0.98516
if len(np.nonzero(tr.data)[0]) < 0.5 * len(tr.data): qual = False else: qual = True return qual
def _check_daylong(tr)
Check the data quality of the daylong file. Check to see that the day isn't just zeros, with large steps, if it is then the resampling will hate it. :type tr: obspy.core.trace.Trace :param tr: Trace to check if the data are daylong. :return quality (simply good or bad) :rtype: bool .. ru...
5.027489
5.027179
1.000062
start_in, end_in = (tr.stats.starttime, tr.stats.endtime) for gap in gaps: stream = Stream() if gap['starttime'] > tr.stats.starttime: stream += tr.slice(tr.stats.starttime, gap['starttime']).copy() if gap['endtime'] < tr.stats.endtime: # Note this can happen...
def _zero_pad_gaps(tr, gaps, fill_gaps=True)
Replace padded parts of trace with zeros. Will cut around gaps, detrend, then pad the gaps with zeros. :type tr: :class:`osbpy.core.stream.Trace` :param tr: A trace that has had the gaps padded :param gaps: List of dict of start-time and end-time as UTCDateTime objects :type gaps: list :retur...
3.107205
3.11458
0.997632
tr = tr.split() gaps = tr.get_gaps() tr = tr.detrend().merge(fill_value=0)[0] gaps = [{'starttime': gap[4], 'endtime': gap[5]} for gap in gaps] return gaps, tr
def _fill_gaps(tr)
Interpolate through gaps and work-out where gaps are. :param tr: Gappy trace (e.g. tr.data is np.ma.MaskedArray) :type tr: `obspy.core.stream.Trace` :return: gaps, trace, where gaps is a list of dict
6.360559
4.801918
1.324587
''' if number != 1 ''' if number > 1: ''' repeat the test few times ''' for time in range(3): ''' Draw a RANDOM number in range of number ( Z_number ) ''' randomNumber = random.randint(2, number - 1) ''' Test if a^(n-1) = 1 mod n ''' if pow(r...
def is_prime(number)
Function to test primality of a number. Function lifted from online resource: http://www.codeproject.com/Articles/691200/Primality-test-algorithms-Prime-test-The-fastest-w This function is distributed under a separate licence: This article, along with any associated source code and files, is \ ...
5.655096
6.203468
0.911602
peaks = [] if not parallel: for sub_arr, arr_thresh in zip(arr, thresh): peaks.append(find_peaks2_short( arr=sub_arr, thresh=arr_thresh, trig_int=trig_int, debug=debug, starttime=starttime, samp_rate=samp_rate, full_peaks=full_peaks)) ...
def multi_find_peaks(arr, thresh, trig_int, debug=0, starttime=False, samp_rate=1.0, parallel=True, full_peaks=False, cores=None)
Wrapper for find-peaks for multiple arrays. :type arr: numpy.ndarray :param arr: 2-D numpy array is required :type thresh: list :param thresh: The threshold below which will be considered noise and peaks will not be found in. One threshold per array. :type trig_int: int :param t...
2.708576
2.781443
0.973802
utilslib = _load_cdll('libutils') length = np.int32(len(peaks)) utilslib.find_peaks.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float32, shape=(length,), flags=native_str('C_CONTIGUOUS')), np.ctypeslib.ndpointer(dtype=np.float32, shape=(length,), ...
def decluster(peaks, index, trig_int)
Decluster peaks based on an enforced minimum separation. :type peaks: np.array :param peaks: array of peak values :type index: np.ndarray :param index: locations of peaks :type trig_int: int :param trig_int: Minimum trigger interval in samples :return: list of tuples of (value, sample)
2.632705
2.699325
0.97532
triggers = [] for stachan, _peaks in zip(stachans, peaks): for peak in _peaks: trigger = (peak[1], peak[0], '.'.join(stachan)) triggers.append(trigger) coincidence_triggers = [] for i, master in enumerate(triggers): slaves = triggers[i + 1:] coinciden...
def coin_trig(peaks, stachans, samp_rate, moveout, min_trig, trig_int)
Find network coincidence triggers within peaks of detection statistics. Useful for finding network detections from sets of detections on individual stations. :type peaks: list :param peaks: List of lists of tuples of (peak, index) for each \ station-channel. Index should be in samples. :t...
2.688596
2.732068
0.984088
fig.suptitle(title) if show: fig.show() if save: fig.savefig(savefile) print("Saved figure to {0}".format(savefile)) if return_fig: return fig return None
def _finalise_figure(fig, **kwargs): # pragma: no cover title = kwargs.get("title") or None show = kwargs.get("show") or False save = kwargs.get("save") or False savefile = kwargs.get("savefile") or "EQcorrscan_figure.png" return_fig = kwargs.get("return_figure") or False if title
Internal function to wrap up a figure. Possible arguments: :type title: str :type show: bool :type save: bool :type savefile: str :type return_figure: bool
3.02811
3.310484
0.914703
trout = tr.copy() # Don't do it inplace on data x = np.arange(len(tr.data)) y = tr.data chunksize = int(round(tr.stats.sampling_rate / samp_rate)) # Wrap the array into a 2D array of chunks, truncating the last chunk if # chunksize isn't an even divisor of the total size. # (This part...
def chunk_data(tr, samp_rate, state='mean')
Downsample data for plotting. Computes the maximum of data within chunks, useful for plotting waveforms or cccsums, large datasets that would otherwise exceed the complexity allowed, and overflow. :type tr: obspy.core.trace.Trace :param tr: Trace to be chunked :type samp_rate: float :param...
3.324647
3.022612
1.099925
import matplotlib.pyplot as plt if cc is None or shift is None: if not isinstance(cc_vec, np.ndarray): print('Given cc: %s and shift: %s' % (cc, shift)) raise IOError('Must provide either cc_vec, or cc and shift') shift = np.abs(cc_vec).argmax() cc = cc_vec[s...
def xcorr_plot(template, image, shift=None, cc=None, cc_vec=None, **kwargs)
Plot a template overlying an image aligned by correlation. :type template: numpy.ndarray :param template: Short template image :type image: numpy.ndarray :param image: Long master image :type shift: int :param shift: Shift to apply to template relative to image, in samples :type cc: float ...
2.851632
3.109034
0.917208
import matplotlib.pyplot as plt if len(cccsum) != len(trace.data): print('cccsum is: ' + str(len(cccsum)) + ' trace is: ' + str(len(trace.data))) msg = ' '.join(['cccsum and trace must have the', 'same number of data points']) raise ValueError(m...
def triple_plot(cccsum, cccsum_hist, trace, threshold, **kwargs)
Plot a seismogram, correlogram and histogram. :type cccsum: numpy.ndarray :param cccsum: Array of the cross-channel cross-correlation sum :type cccsum_hist: numpy.ndarray :param cccsum_hist: cccsum for histogram plotting, can be the same as \ cccsum but included if cccsum is just an envelope. ...
2.509887
2.53681
0.989387
import matplotlib.pyplot as plt npts = len(data) t = np.arange(npts, dtype=np.float32) / (samp_rate * 3600) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(t, data, 'k') ax1.scatter(peaks[0][1] / (samp_rate * 3600), abs(peaks[0][0]), color='r', label='Peaks') ...
def peaks_plot(data, starttime, samp_rate, peaks=[(0, 0)], **kwargs)
Plot peaks to check that the peak finding routine is running correctly. Used in debugging for the EQcorrscan module. :type data: numpy.array :param data: Numpy array of the data within which peaks have been found :type starttime: obspy.core.utcdatetime.UTCDateTime :param starttime: Start time for ...
2.434054
2.475772
0.983149
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 import matplotlib.pyplot as plt lats = [] longs = [] depths = [] for node in nodes: lats.append(float(node[0])) longs.append(float(node[1])) depths.append(float(node[2])) fig = plt.figure() ax = fig.add_su...
def threeD_gridplot(nodes, **kwargs)
Plot in a series of grid points in 3D. :type nodes: list :param nodes: List of tuples of the form (lat, long, depth) :returns: :class:`matplotlib.figure.Figure` .. rubric:: Example >>> from eqcorrscan.utils.plotting import threeD_gridplot >>> nodes = [(-43.5, 170.4, 4), (-43.3, 170.8, 12), (...
1.828829
1.809131
1.010888
import matplotlib.pyplot as plt from eqcorrscan.core.match_filter import normxcorr2 n_axes = len(traces) if stack in ['linstack', 'PWS']: n_axes += 1 fig, axes = plt.subplots(n_axes, 1, sharex=True, figsize=size) if len(traces) > 1: axes = axes.ravel() traces = [(trace, ...
def multi_trace_plot(traces, corr=True, stack='linstack', size=(7, 12), **kwargs)
Plot multiple traces (usually from the same station) on the same plot. Differs somewhat to obspy's stream.plot in that only relative time within traces is worried about, it will not merge traces together. :type traces: list :param traces: List of obspy.core.Trace :type corr: bool :param corr: ...
2.695117
2.589256
1.040885
import matplotlib.pyplot as plt info = [(times[i], mags[i]) for i in range(len(times))] info.sort(key=lambda tup: tup[0]) times = [x[0] for x in info] mags = [x[1] for x in info] # Make two subplots next to each other of time before and time after fig, axes = plt.subplots(1, 2, sharey=T...
def interev_mag(times, mags, size=(10.5, 7.5), **kwargs)
Plot inter-event times against magnitude. :type times: list :param times: list of the detection times, must be sorted the same as mags :type mags: list :param mags: list of magnitudes :type size: tuple :param size: Size of figure in inches. :returns: :class:`matplotlib.figure.Figure` ...
2.032732
2.040387
0.996248
nodes = [] for ev in catalog: nodes.append((ev.preferred_origin().latitude, ev.preferred_origin().longitude, ev.preferred_origin().depth / 1000)) # Will plot borehole instruments at elevation - depth if provided all_stas = [] for net in invent...
def obspy_3d_plot(inventory, catalog, size=(10.5, 7.5), **kwargs)
Plot obspy Inventory and obspy Catalog classes in three dimensions. :type inventory: obspy.core.inventory.inventory.Inventory :param inventory: Obspy inventory class containing station metadata :type catalog: obspy.core.event.catalog.Catalog :param catalog: Obspy catalog class containing event metadata...
3.672297
3.918009
0.937287
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D stalats, stalongs, staelevs = zip(*stations) evlats, evlongs, evdepths = zip(*nodes) # Cope with +/-180 latitudes... _evlongs = [] for evlong in evlongs: if evlong < 0: evlong = float(evlong) ...
def threeD_seismplot(stations, nodes, size=(10.5, 7.5), **kwargs)
Plot seismicity and stations in a 3D, movable, zoomable space. Uses matplotlibs Axes3D package. :type stations: list :param stations: list of one tuple per station of (lat, long, elevation), \ with up positive. :type nodes: list :param nodes: list of one tuple per event of (lat, long, dept...
2.212297
2.147864
1.029999
import matplotlib.pyplot as plt # Work out how many traces we can plot n_traces = 0 for tr in signal: try: noise.select(id=tr.id)[0] except IndexError: # pragma: no cover continue n_traces += 1 fig, axes = plt.subplots(n_traces, 2, sharex=True)...
def noise_plot(signal, noise, normalise=False, **kwargs)
Plot signal and noise fourier transforms and the difference. :type signal: `obspy.core.stream.Stream` :param signal: Stream of "signal" window :type noise: `obspy.core.stream.Stream` :param noise: Stream of the "noise" window. :type normalise: bool :param normalise: Whether to normalise the dat...
1.967307
1.927018
1.020907
import matplotlib.pyplot as plt figures = [] for sval, stachan in zip(svalues, stachans): print(stachan) plot_traces = [SVStream.select(station=stachan[0], channel=stachan[1])[0] for SVStream in svstreams] fig, axes =...
def svd_plot(svstreams, svalues, stachans, **kwargs)
Plot singular vectors from the :mod:`eqcorrscan.utils.clustering` routines. One plot for each channel. :type svstreams: list :param svstreams: See :func:`eqcorrscan.utils.clustering.svd_to_stream` - these should be ordered by power, e.g. first singular vector in the first stream. :type...
2.764703
2.660056
1.03934
import matplotlib.pyplot as plt if isinstance(traces, Stream): traces.sort(['station', 'channel']) if not fig: fig = plt.figure() for i, tr in enumerate(traces): if i == 0: ax = fig.add_subplot(len(traces), 1, i + 1) else: ax = fig.add_subplot...
def spec_trace(traces, cmap=None, wlen=0.4, log=False, trc='k', tralpha=0.9, size=(10, 13), fig=None, **kwargs)
Plots seismic data with spectrogram behind. Takes a stream or list of traces and plots the trace with the spectra beneath it. :type traces: list :param traces: Traces to be plotted, can be a single :class:`obspy.core.stream.Stream`, or a list of :class:`obspy.core.trace.Trace`. :ty...
2.019948
2.079573
0.971328
import matplotlib.pyplot as plt if not axes: fig = plt.figure(figsize=size) ax1 = fig.add_subplot(111) else: ax1 = axes trace.spectrogram(wlen=wlen, log=log, show=False, cmap=cmap, axes=ax1) fig = plt.gcf() ax2 = ax1.twinx() y = trace.data x = np.linspace(0, ...
def _spec_trace(trace, cmap=None, wlen=0.4, log=False, trc='k', tralpha=0.9, size=(10, 2.5), axes=None, title=None)
Function to plot a trace over that traces spectrogram. Uses obspys spectrogram routine. :type trace: obspy.core.trace.Trace :param trace: trace to plot :type cmap: str :param cmap: [Matplotlib colormap](http://matplotlib.org/examples/color/ colormaps_reference.html) :type wlen: float ...
2.114182
2.053187
1.029708
import matplotlib.pyplot as plt if stachans == 'all' and not detector.multiplex: stachans = detector.stachans elif detector.multiplex: stachans = [('multi', ' ')] if np.isinf(detector.dimension): msg = ' '.join(['Infinite subspace dimension. Only plotting as many', ...
def subspace_detector_plot(detector, stachans, size, **kwargs)
Plotting for the subspace detector class. Plot the output basis vectors for the detector at the given dimension. Corresponds to the first n horizontal vectors of the V matrix. :type detector: :class:`eqcorrscan.core.subspace.Detector` :type stachans: list :param stachans: list of tuples of statio...
3.180212
3.070689
1.035667
def _match_filter_plot(stream, cccsum, template_names, rawthresh, plotdir, plot_format, i): # pragma: no cover import matplotlib.pyplot as plt plt.ioff() stream_plot = copy.deepcopy(stream[0]) # Downsample for plotting stream_plot = _plotting_decimation(stream_plot, 10e5...
Plotting function for match_filter. :param stream: Stream to plot :param cccsum: Cross-correlation sum to plot :param template_names: Template names used :param rawthresh: Threshold level :param plotdir: Location to save plots :param plot_format: Output plot type (e.g. png, svg, eps, pdf...) ...
null
null
null
trace_len = trace.stats.npts while trace_len > max_len: trace.decimate(decimation_step) trace_len = trace.stats.npts return trace
def _plotting_decimation(trace, max_len=10e5, decimation_step=4)
Decimate data until required length reached. :type trace: obspy.core.stream.Trace :param trace: Trace to decimate type max_len: int :param max_len: Maximum length in samples :type decimation_step: int :param decimation_step: Decimation factor to use for each step. :return: obspy.core.strea...
2.58325
3.415365
0.756361
for fig in doctree.traverse(condition=nodes.figure): if 'thumbnail' in fig['classes']: continue for img in fig.traverse(condition=nodes.image): img['classes'].append('img-responsive')
def make_images_responsive(app, doctree)
Add Bootstrap img-responsive class to images.
4.553406
4.132237
1.101923
log = logging.getLogger('ciu') request = requests.get("https://raw.githubusercontent.com/brettcannon/" "caniusepython3/master/caniusepython3/overrides.json") if request.status_code == 200: log.info("Overrides loaded from GitHub and cached") overrides = request...
def _manual_overrides(_cache_date=None)
Read the overrides file. An attempt is made to read the file as it currently stands on GitHub, and then only if that fails is the included file used.
4.202333
3.661725
1.147638
log = logging.getLogger("ciu") log.info("Checking {} ...".format(project_name)) request = requests.get("https://pypi.org/pypi/{}/json".format(project_name)) if request.status_code >= 400: log = logging.getLogger("ciu") log.warning("problem fetching {}, assuming ported ({})".format( ...
def supports_py3(project_name)
Check with PyPI if a project supports Python 3.
3.55022
3.325585
1.067547
dependencies = [] dependencies.extend(projects_.projects_from_requirements(requirements_paths)) dependencies.extend(projects_.projects_from_metadata(metadata)) dependencies.extend(projects) manual_overrides = pypi.manual_overrides() for dependency in dependencies: if dependency in...
def check(requirements_paths=[], metadata=[], projects=[])
Return True if all of the specified dependencies have been ported to Python 3. The requirements_paths argument takes a sequence of file paths to requirements files. The 'metadata' argument takes a sequence of strings representing metadata. The 'projects' argument takes a sequence of project names. ...
5.608242
5.325543
1.053084
description = ('Determine if a set of project dependencies will work with ' 'Python 3') parser = argparse.ArgumentParser(description=description) req_help = 'path(s) to a pip requirements file (e.g. requirements.txt)' parser.add_argument('--requirements', '-r', nargs='+', default...
def projects_from_cli(args)
Take arguments through the CLI can create a list of specified projects.
2.829976
2.857818
0.990258
if not blockers: encoding = getattr(sys.stdout, 'encoding', '') if encoding: encoding = encoding.lower() if encoding == 'utf-8': # party hat flair = "\U0001F389 " else: flair = '' return [flair + 'You have ...
def message(blockers)
Create a sequence of key messages based on what is blocking.
3.856477
3.864621
0.997893
pprinted = [] for blocker in sorted(blockers, key=lambda x: tuple(reversed(x))): buf = [blocker[0]] if len(blocker) > 1: buf.append(' (which is blocking ') buf.append(', which is blocking '.join(blocker[1:])) buf.append(')') pprinted.append(''.joi...
def pprint_blockers(blockers)
Pretty print blockers into a sequence of strings. Results will be sorted by top-level project name. This means that if a project is blocking another project then the dependent project will be what is used in the sorting, not the project at the bottom of the dependency graph.
3.102303
2.826969
1.097395
log = logging.getLogger('ciu') log.info('{0} top-level projects to check'.format(len(projects))) print('Finding and checking dependencies ...') blockers = dependencies.blockers(projects) print('') for line in message(blockers): print(line) print('') for line in pprint_bloc...
def check(projects)
Check the specified projects for Python 3 compatibility.
6.599981
6.382237
1.034117
blockers = set(reasons.keys()) - set(reasons.values()) paths = set() for blocker in blockers: path = [blocker] parent = reasons[blocker] while parent: if parent in path: raise CircularDependencyError(dict(parent=parent, ...
def reasons_to_paths(reasons)
Calculate the dependency paths to the reasons of the blockers. Paths will be in reverse-dependency order (i.e. parent projects are in ascending order).
2.606675
2.372238
1.098825
log = logging.getLogger('ciu') log.info('Locating dependencies for {}'.format(project_name)) located = distlib.locators.locate(project_name, prereleases=True) if not located: log.warning('{0} not found'.format(project_name)) return None return {packaging.utils.canonicalize_name(...
def dependencies(project_name)
Get the dependencies for a project.
6.500982
6.563947
0.990407
log = logging.getLogger('ciu') valid_reqs = [] for requirements_path in requirements: with io.open(requirements_path) as file: requirements_text = file.read() # Drop line continuations. requirements_text = re.sub(r"\\s*", "", requirements_text) # Drop comment...
def projects_from_requirements(requirements)
Extract the project dependencies from a Requirements specification.
3.357564
3.290751
1.020303
projects = [] for data in metadata: meta = distlib.metadata.Metadata(fileobj=io.StringIO(data)) projects.extend(pypi.just_name(project) for project in meta.run_requires) return frozenset(map(packaging.utils.canonicalize_name, projects))
def projects_from_metadata(metadata)
Extract the project dependencies from a metadata spec.
6.194633
5.62488
1.101292
if grayscale is None: grayscale = GRAYSCALE_DEFAULT confidence = float(confidence) needleImage = _load_cv2(needleImage, grayscale) needleHeight, needleWidth = needleImage.shape[:2] haystackImage = _load_cv2(haystackImage, grayscale) if region: haystackImage = haystackImag...
def _locateAll_opencv(needleImage, haystackImage, grayscale=None, limit=10000, region=None, step=1, confidence=0.999)
faster but more memory-intensive than pure python step 2 skips every other row and column = ~3x faster but prone to miss; to compensate, the algorithm automatically reduces the confidence threshold by 5% (which helps but will not avoid all misses). limitations: - OpenCV...
3.474484
3.429243
1.013193
start = time.time() while True: try: screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here. retVal = locate(image, screenshotIm, **kwargs) try: screenshot...
def locateOnScreen(image, minSearchTime=0, **kwargs)
minSearchTime - amount of time in seconds to repeat taking screenshots and trying to locate a match. The default of 0 performs a single search.
6.606282
6.625762
0.99706
raw_details = self._requestDetails(ip_address) raw_details['country_name'] = self.countries.get(raw_details.get('country')) raw_details['ip_address'] = ipaddress.ip_address(raw_details.get('ip')) raw_details['latitude'], raw_details['longitude'] = self._read_coords(raw_details.g...
def getDetails(self, ip_address=None)
Get details for specified IP address as a Details object.
3.211161
2.976893
1.078695
if ip_address not in self.cache: url = self.API_URL if ip_address: url += '/' + ip_address response = requests.get(url, headers=self._get_headers(), **self.request_options) if response.status_code == 429: raise RequestQuot...
def _requestDetails(self, ip_address=None)
Get IP address data by sending request to IPinfo API.
2.551976
2.448221
1.04238
headers = { 'user-agent': 'IPinfoClient/Python{version}/1.0'.format(version=sys.version_info[0]), 'accept': 'application/json' } if self.access_token: headers['authorization'] = 'Bearer {}'.format(self.access_token) return headers
def _get_headers(self)
Built headers for request to IPinfo API.
3.677362
2.741659
1.341291
if not countries_file: countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT) with open(countries_file) as f: countries_json = f.read() return json.loads(countries_json)
def _read_country_names(self, countries_file=None)
Read list of countries from specified country file or default file.
2.526591
2.205381
1.145648
if not self.has_section(section): return False if not self.has_option(section, option): return False if ConfigParser.get(self, section, option) == self._secure_placeholder: return True return False
def is_secure_option(self, section, option)
Test an option to see if it is secured or not. :param section: section id :type section: string :param option: option name :type option: string :rtype: boolean otherwise.
2.738115
2.929443
0.934688
items = [] for k, v in ConfigParser.items(self, section): if self.is_secure_option(section, k): v = self.get(section, k) if v == '!!False!!': v = False items.append((k, v)) return items
def items(self, section)
Get all items for a section. Subclassed, to ensure secure items come back with the unencrypted data. :param section: section id :type section: string
3.608242
3.964122
0.910225
return [x for x in self.items(section) if self.is_secure_option(section, x[0])]
def secure_items(self, section)
Like items() but only return secure items. :param section: section id :type section: string
4.536427
6.592966
0.688071
if not value: value = '!!False!!' if self.is_secure_option(section, option): self.set_secure(section, option, value) else: ConfigParser.set(self, section, option, value)
def set(self, section, option, value)
Set an option value. Knows how to set options properly marked as secure.
3.986539
3.343507
1.192322
if self.keyring_available: s_option = "%s%s" % (section, option) self._unsaved[s_option] = ('set', value) value = self._secure_placeholder ConfigParser.set(self, section, option, value)
def set_secure(self, section, option, value)
Set an option and mark it as secure. Any subsequent uses of 'set' or 'get' will also now know that this option is secure as well.
5.566339
5.599273
0.994118
if self.is_secure_option(section, option) and self.keyring_available: s_option = "%s%s" % (section, option) if self._unsaved.get(s_option, [''])[0] == 'set': res = self._unsaved[s_option][1] else: res = keyring.get_password(self.keyrin...
def get(self, section, option, *args)
Get option value from section. If an option is secure, populates the plain text.
3.283937
3.155586
1.040674
if self.is_secure_option(section, option) and self.keyring_available: s_option = "%s%s" % (section, option) self._unsaved[s_option] = ('delete', None) ConfigParser.remove_option(self, section, option)
def remove_option(self, section, option)
Removes the option from ConfigParser as well as the secure storage backend
5.061491
4.33823
1.166718
ConfigParser.write(self, *args) if self.keyring_available: for key, thing in self._unsaved.items(): action = thing[0] value = thing[1] if action == 'set': keyring.set_password(self.keyring_name, key, value) ...
def write(self, *args)
See ConfigParser.write(). Also writes secure items to keystore.
2.930012
2.770543
1.057559
if self.parser.has_section(id): return self._section_to_account(id) return None
def account(self, id)
Get :py:class:`ofxclient.Account` by section id
5.548723
4.782842
1.160131
serialized = account.serialize() section_items = flatten_dict(serialized) section_id = section_items['local_id'] if not self.parser.has_section(section_id): self.parser.add_section(section_id) for key in sorted(section_items): self.parser.set(se...
def add_account(self, account)
Add Account to config (does not save)
3.684846
3.600353
1.023468
for key in self.secured_field_names: value = self.parser.get(id, key) self.parser.set_secure(id, key, value) return self
def encrypt_account(self, id)
Make sure that certain fields are encrypted.
5.672447
4.88822
1.160432
for key in self.secured_field_names: if not self.parser.is_secure_option(id, key): return False return True
def is_encrypted_account(self, id)
Are all fields for the account id encrypted?
7.868612
5.937199
1.325307
if self.parser.has_section(id): self.parser.remove_section(id) return True return False
def remove_account(self, id)
Add Account from config (does not save)
3.758677
3.08306
1.219138
with open(self.file_name, 'w') as fp: self.parser.write(fp) return self
def save(self)
Save changes to config file
4.709911
4.22405
1.115023
client_args = {'ofx_version': str(ofx_version)} if 'ofx.discovercard.com' in bank_info['url']: # Discover needs no User-Agent and no Accept headers client_args['user_agent'] = False client_args['accept'] = False if 'www.accountonline.com' in bank_info['url']: # Citi need...
def client_args_for_bank(bank_info, ofx_version)
Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome ban...
4.188964
4.343592
0.964401
return hashlib.sha256(("%s%s" % ( self.id, self.username)).encode()).hexdigest()
def local_id(self)
Locally generated unique account identifier. :rtype: string
5.483054
6.427457
0.853067
u = self.username p = self.password if username and password: u = username p = password client = self.client() query = client.authenticated_query(username=u, password=p) res = client.post(query) ofx = BeautifulSoup(res, 'lxml') ...
def authenticate(self, username=None, password=None)
Test the authentication credentials Raises a ``ValueError`` if there is a problem authenticating with the human readable reason given by the institution. :param username: optional username (use self.username by default) :type username: string or None :param password: optional p...
4.117438
4.060611
1.013995
from ofxclient.account import Account client = self.client() query = client.account_list_query() resp = client.post(query) resp_handle = StringIO(resp) if IS_PYTHON_2: parsed = OfxParser.parse(resp_handle) else: parsed = OfxParser...
def accounts(self)
Ask the bank for the known :py:class:`ofxclient.Account` list. :rtype: list of :py:class:`ofxclient.Account` objects
5.133127
5.062311
1.013989
return { 'id': self.id, 'org': self.org, 'url': self.url, 'broker_id': self.broker_id, 'username': self.username, 'password': self.password, 'description': self.description, 'client_args': self.client().init...
def serialize(self)
Serialize predictably for use in configuration storage. Output looks like this:: { 'local_id': 'unique local identifier', 'id': 'FI Id', 'org': 'FI Org', 'url': 'FI OFX Endpoint Url', 'broker_id': 'FI Broker Id...
3.664181
1.89707
1.931495
return Institution( id=raw['id'], org=raw['org'], url=raw['url'], broker_id=raw.get('broker_id', ''), username=raw['username'], password=raw['password'], description=raw.get('description', None), client_args...
def deserialize(raw)
Instantiate :py:class:`ofxclient.Institution` from dictionary :param raw: serialized ``Institution`` :param type: dict per :py:method:`~Institution.serialize` :rtype: subclass of :py:class:`ofxclient.Institution`
3.535197
3.31451
1.066582
return hashlib.sha256(("%s%s" % ( self.institution.local_id(), self.number)).encode()).hexdigest()
def local_id(self)
Locally generated unique account identifier. :rtype: string
6.14431
7.368673
0.833842
days_ago = datetime.datetime.now() - datetime.timedelta(days=days) as_of = time.strftime("%Y%m%d", days_ago.timetuple()) query = self._download_query(as_of=as_of) response = self.institution.client().post(query) return StringIO(response)
def download(self, days=60)
Downloaded OFX response for the given time range :param days: Number of days to look back at :type days: integer :rtype: :py:class:`StringIO`
4.17875
3.699454
1.129559
if IS_PYTHON_2: return OfxParser.parse( self.download(days=days) ) else: return OfxParser.parse( BytesIO(self.download(days=days).read().encode()) )
def download_parsed(self, days=60)
Downloaded OFX response parsed by :py:meth:`OfxParser.parse` :param days: Number of days to look back at :type days: integer :rtype: :py:class:`ofxparser.Ofx`
5.280279
3.831855
1.377995