text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(array, cutoff): """ Compute the logarithm of an array with a cutoff on the small values """
arr = numpy.copy(array) arr[arr < cutoff] = cutoff return numpy.log(arr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose_arrays(a1, a2, firstfield='etag'): """ Compose composite arrays by generating an extended datatype containing all the fields. The two arrays must hav...
assert len(a1) == len(a2), (len(a1), len(a2)) if a1.dtype.names is None and len(a1.shape) == 1: # the first array is not composite, but it is one-dimensional a1 = numpy.array(a1, numpy.dtype([(firstfield, a1.dtype)])) fields1 = [(f, a1.dtype.fields[f][0]) for f in a1.dtype.names] if a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_script(upgrade, conn, dry_run=True, debug=True): """ An utility to debug upgrade scripts written in Python :param upgrade: upgrade procedure :param con...
conn = WrappedConnection(conn, debug=debug) try: upgrade(conn) except Exception: conn.rollback() raise else: if dry_run: conn.rollback() else: conn.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_sql_script(conn, fname): """ Apply the given SQL script to the database :param conn: a DB API 2 connection :param fname: full path to the creation scri...
sql = open(fname).read() try: # we cannot use conn.executescript which is non transactional for query in sql.split('\n\n'): conn.execute(query) except Exception: logging.error('Error executing %s' % fname) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade_db(conn, pkg_name='openquake.server.db.schema.upgrades', skip_versions=()): """ Upgrade a database by running several scripts in a single transaction...
upgrader = UpgradeManager.instance(conn, pkg_name) t0 = time.time() # run the upgrade scripts try: versions_applied = upgrader.upgrade(conn, skip_versions) except: conn.rollback() raise else: conn.commit() dt = time.time() - t0 logging.info('Upgrade compl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, templ, *args): """ A simple utility to run SQL queries. :param templ: a query or query template :param args: the arguments (or the empty tuple) :re...
curs = self._conn.cursor() query = curs.mogrify(templ, args) if self.debug: print(query) curs.execute(query) return curs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_versioning(self, conn): """ Create the version table into an already populated database and insert the base script. :param conn: a DB API 2 connectio...
logging.info('Creating the versioning table %s', self.version_table) conn.executescript(CREATE_VERSIONING % self.version_table) self._insert_script(self.read_scripts()[0], conn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self, conn): """ Create the version table and run the base script on an empty database. :param conn: a DB API 2 connection """
base = self.read_scripts()[0]['fname'] logging.info('Creating the initial schema from %s', base) apply_sql_script(conn, os.path.join(self.upgrade_dir, base)) self.install_versioning(conn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def upgrade(self, conn, skip_versions=()): ''' Upgrade the database from the current version to the maximum version in the upgrade scripts. :param conn: a DBAPI 2 connection :param skip_versions: the versions to skip ''' db_versions = self.get_db_versions(conn) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_db_versions(self, conn): """ Get all the versions stored in the database as a set. :param conn: a DB API 2 connection """
curs = conn.cursor() query = 'select version from {}'.format(self.version_table) try: curs.execute(query) return set(version for version, in curs.fetchall()) except: raise VersioningNotInstalled('Run oq engine --upgrade-db')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_scripts(self, minversion=None, maxversion=None, skip_versions=()): """ Extract the upgrade scripts from a directory as a list of dictionaries, ordered b...
scripts = [] versions = {} # a script is unique per version for scriptname in sorted(os.listdir(self.upgrade_dir)): match = self.parse_script_name(scriptname) if match: version = match['version'] if version in skip_versions: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_upgrade_scripts(self): """ Extract the OpenQuake upgrade scripts from the links in the GitHub page """
link_pattern = '>\s*{0}\s*<'.format(self.pattern[1:-1]) page = urllib.request.urlopen(self.upgrades_url).read() for mo in re.finditer(link_pattern, page): scriptname = mo.group(0)[1:-1].strip() yield self.parse_script_name(scriptname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def average_azimuth(self): """ Calculate and return weighted average azimuth of all line's segments in decimal degrees. Uses formula from http://en.wikipedia.org...
if len(self.points) == 2: return self.points[0].azimuth(self.points[1]) lons = numpy.array([point.longitude for point in self.points]) lats = numpy.array([point.latitude for point in self.points]) azimuths = geodetic.azimuth(lons[:-1], lats[:-1], lons[1:], lats[1:]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(self, section_length): """ Resample this line into sections. The first point in the resampled line corresponds to the first point in the original li...
if len(self.points) < 2: return Line(self.points) resampled_points = [] # 1. Resample the first section. 2. Loop over the remaining points # in the line and resample the remaining sections. # 3. Extend the list with the resampled points, except the first one ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_length(self): """ Calculate and return the length of the line as a sum of lengths of all its segments. :returns: Total length in km. """
length = 0 for i, point in enumerate(self.points): if i != 0: length += point.distance(self.points[i - 1]) return length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample_to_num_points(self, num_points): """ Resample the line to a specified number of points. :param num_points: Integer number of points the resulting li...
assert len(self.points) > 1, "can not resample the line of one point" section_length = self.get_length() / (num_points - 1) resampled_points = [self.points[0]] segment = 0 acc_length = 0 last_segment_length = 0 for i in range(num_points - 1): tot_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cena_tau(imt, mag, params): """ Returns the inter-event standard deviation, tau, for the CENA case """
if imt.name == "PGV": C = params["PGV"] else: C = params["SA"] if mag > 6.5: return C["tau3"] elif (mag > 5.5) and (mag <= 6.5): return ITPL(mag, C["tau3"], C["tau2"], 5.5, 1.0) elif (mag > 5.0) and (mag <= 5.5): return ITPL(mag, C["tau2"], C["tau1"], 5.0, 0....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tau_at_quantile(mean, stddev, quantile): """ Returns the value of tau at a given quantile in the form of a dictionary organised by intensity measure """
tau_model = {} for imt in mean: tau_model[imt] = {} for key in mean[imt]: if quantile is None: tau_model[imt][key] = mean[imt][key] else: tau_model[imt][key] = _at_percentile(mean[imt][key], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_stddevs(self, mag, imt, stddev_types, num_sites): """ Returns the standard deviations for either the ergodic or non-ergodic models """
tau = self._get_tau(imt, mag) phi = self._get_phi(imt, mag) sigma = np.sqrt(tau ** 2. + phi ** 2.) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_stddevs(self, mag, imt, stddev_types, num_sites): """ Returns the total standard deviation """
stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: sigma = self._get_total_sigma(imt, mag) stddevs.append(sigma + np.zeros(num_sites)) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_sigma_at_quantile(self, sigma_quantile): """ Calculates the total standard deviation at the specified quantile """
# Mean mean is found in self.TAU. Get the variance in tau tau_std = TAU_SETUP[self.tau_model]["STD"] # Mean phiss is found in self.PHI_SS. Get the variance in phi phi_std = deepcopy(self.PHI_SS.sa_coeffs) phi_std.update(self.PHI_SS.non_sa_coeffs) for key in phi_std: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_tau_vector(self, tau_mean, tau_std, imt_list): """ Gets the vector of mean and variance of tau values corresponding to the specific model and returns th...
self.magnitude_limits = MAG_LIMS_KEYS[self.tau_model]["mag"] self.tau_keys = MAG_LIMS_KEYS[self.tau_model]["keys"] t_bar = {} t_std = {} for imt in imt_list: t_bar[imt] = [] t_std[imt] = [] for mag, key in zip(self.magnitude_limits, self.tau_k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_phi_vector(self, phi_mean, phi_std, imt_list): """ Gets the vector of mean and variance of phi values corresponding to the specific model and returns th...
p_bar = {} p_std = {} for imt in imt_list: p_bar[imt] = [] p_std[imt] = [] for mag in self.magnitude_limits: phi_ss_mean = get_phi_ss(imt, mag, phi_mean) phi_ss_std = get_phi_ss(imt, mag, phi_std) if self.ergod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_total_sigma(self, imt, mag): """ Returns the estimated total standard deviation for a given intensity measure type and magnitude """
C = self.SIGMA[imt] if mag <= self.magnitude_limits[0]: # The CENA constant model is always returned here return C[self.tau_keys[0]] elif mag > self.magnitude_limits[-1]: return C[self.tau_keys[-1]] else: # Needs interpolation ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hcurves_and_means(dstore): """ Extract hcurves from the datastore and compute their means. :returns: curves_by_rlz, mean_curves """
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() getter = getters.PmapGetter(dstore, rlzs_assoc) pmaps = getter.get_pmaps() return dict(zip(getter.rlzs, pmaps)), dstore['hcurves/mean']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_mean(self, C, mag, rhypo, hypo_depth, mean, idx): """ Compute mean value according to equations 10 and 11 page 226. """
mean[idx] = (C['C1'] + C['C2'] * mag + C['C3'] * np.log(rhypo[idx] + C['C4'] * np.exp(C['C5'] * mag)) + C['C6'] * hypo_depth)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_std(self, C, stddevs, idx): """ Compute total standard deviation, see tables 3 and 4, pages 227 and 228. """
for stddev in stddevs: stddev[idx] += C['sigma']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_config(config): '''Check config file inputs and overwrite bad values with the defaults''' essential_keys = ['number_earthquakes'] for key in essential_keys: if key not in config: raise ValueError('For Kijko Nonparametric Gaussian the key %s ' 'need...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_exponential_spaced_values(mmin, mmax, number_samples): ''' Function to return a set of exponentially spaced values between mmin and mmax :param float mmin: Minimum value :param float mmax: Maximum value :param float number_samples: Number of exponentially spaced...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbcmd(action, *args): """ A dispatcher to the database server. :param action: database action to perform :param args: arguments """
global sock if sock is None: sock = zeromq.Socket( 'tcp://%s:%s' % (config.dbserver.host, DBSERVER_PORT), zeromq.zmq.REQ, 'connect').__enter__() # the socket will be closed when the calculation ends res = sock.send((action,) + args) if isinstance(res, parallel.Re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_log_record(self, record): """ Massage a log record before emitting it. Intended to be used by the custom log handlers defined in this module. """
if not hasattr(record, 'hostname'): record.hostname = '-' if not hasattr(record, 'job_id'): record.job_id = self.job_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(job_id, log_level='info', log_file=None): """ Context manager adding and removing log handlers. :param job_id: ID of the current job :param log_level:...
handlers = [LogDatabaseHandler(job_id)] # log on db always if log_file is None: # add a StreamHandler if not already there if not any(h for h in logging.root.handlers if isinstance(h, logging.StreamHandler)): handlers.append(LogStreamHandler(job_id)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_median_area(self, mag, rake): """ The values are a function of magnitude. """
# strike slip length = 10.0 ** (-2.57 + 0.62 * mag) seis_wid = 20.0 # estimate area based on length if length < seis_wid: return length ** 2. else: return length * seis_wid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct_surface(lons, lats, upper_depth, lower_depth): """ Utility method that constructs and return a simple fault surface with top edge specified by `lo...
depths = np.array([ np.zeros_like(lons) + upper_depth, np.zeros_like(lats) + lower_depth ]) mesh = RectangularMesh( np.tile(lons, (2, 1)), np.tile(lats, (2, 1)), depths ) return SimpleFaultSurface(mesh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_min_distance_to_sub_trench(lons, lats): """ Compute and return minimum distance between subduction trench and points specified by 'lon' and 'lat' The me...
trench = _construct_surface(SUB_TRENCH_LONS, SUB_TRENCH_LATS, 0., 10.) sites = Mesh(lons, lats, None) return np.abs(trench.get_rx_distance(sites))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_min_distance_to_volcanic_front(lons, lats): """ Compute and return minimum distance between volcanic front and points specified by 'lon' and 'lat'. Dist...
vf = _construct_surface(VOLCANIC_FRONT_LONS, VOLCANIC_FRONT_LATS, 0., 10.) sites = Mesh(lons, lats, None) return vf.get_rx_distance(sites)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_subduction_trench_correction(mean, x_tr, H, rrup, imt): """ Implement equation for subduction trench correction as described in equation 3.5.2-1, page...
if imt.name == 'PGV': V1 = 10 ** ((-4.021e-5 * x_tr + 9.905e-3) * (H - 30)) V2 = np.maximum(1., (10 ** (-0.012)) * ((rrup / 300.) ** 2.064)) corr = V2 if H > 30: corr *= V1 else: V2 = np.maximum(1., (10 ** (+0.13)) * ((rrup / 300.) ** 3.2)) corr = V2 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_volcanic_front_correction(mean, x_vf, H, imt): """ Implement equation for volcanic front correction as described in equation 3.5.2.-2, page 3-149 of "...
V1 = np.zeros_like(x_vf) if imt.name == 'PGV': idx = x_vf <= 75 V1[idx] = 4.28e-5 * x_vf[idx] * (H - 30) idx = x_vf > 75 V1[idx] = 3.21e-3 * (H - 30) V1 = 10 ** V1 else: idx = x_vf <= 75 V1[idx] = 7.06e-5 * x_vf[idx] * (H - 30) idx = x_vf > 75...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-2 page 151 for t...
mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=0) stddevs = self._get_stddevs(stddev_types, dists.rrup) mean = self._apply_amplification_factor(mean, sites.vs30) return mean, stddevs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_mean(self, imt, mag, hypo_depth, rrup, d): """ Return mean value as defined in equation 3.5.1-1 page 148 """
# clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6 # in "Technical Reports on National Seismic Hazard Maps for Japan" mag = min(mag, 8.3) if imt.name == 'PGV': mean = ( 0.58 * mag + 0.0038 * hypo_depth + d ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_stddevs(self, stddev_types, rrup): """ Return standard deviations as defined in equation 3.5.5-2 page 151 """
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(rrup) std[rrup <= 20] = 0.23 idx = (rrup > 20) & (rrup <= 30) std[idx] = 0.23 - 0.03 * np.log10(rrup[idx] / 20) / np.log10(30. / 20.) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_stddevs(self, stddev_types, pgv): """ Return standard deviations as defined in equation 3.5.5-1 page 151 """
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(pgv) std[pgv <= 25] = 0.20 idx = (pgv > 25) & (pgv <= 50) std[idx] = 0.20 - 0.05 * (pgv[idx] - 25) / 25 std[pgv > 50] = 0.15 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_memory(calc_id=-1): """ Plot the memory occupation """
dstore = util.read(calc_id) plots = [] for task_name in dstore['task_info']: mem = dstore['task_info/' + task_name]['mem_gb'] plots.append((task_name, mem)) plt = make_figure(plots) plt.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_array(pmap, nsites, imtls, inner_idx=0): """ Convert the probability map into a composite array with header :param pmap: probability map :param ns...
lst = [] # build the export dtype, of the form PGA-0.1, PGA-0.2 ... for imt, imls in imtls.items(): for iml in imls: lst.append(('%s-%s' % (imt, iml), F32)) curves = numpy.zeros(nsites, numpy.dtype(lst)) for sid, pcurve in pmap.items(): curve = curves[sid] idx = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_hazard_maps(curves, imls, poes): """ Given a set of hazard curve poes, interpolate a hazard map at the specified ``poe``. :param curves: 2D array of ...
poes = numpy.array(poes) if len(poes.shape) == 0: # `poes` was passed in as a scalar; # convert it to 1D array of 1 element poes = poes.reshape(1) if len(curves.shape) == 1: # `curves` was passed as 1 dimensional array, there is a single site curves = curves.reshap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_hmap(pmap, imtls, poes): """ Compute the hazard maps associated to the passed probability map. :param pmap: hazard curves in the form of a ProbabilityMa...
M, P = len(imtls), len(poes) hmap = probability_map.ProbabilityMap.build(M, P, pmap, dtype=F32) if len(pmap) == 0: return hmap # empty hazard map for i, imt in enumerate(imtls): curves = numpy.array([pmap[sid].array[imtls(imt), 0] for sid in pmap.sids]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_uhs(hmap, info): """ Make Uniform Hazard Spectra curves for each location. :param hmap: array of shape (N, M, P) :param info: a dictionary with keys poe...
uhs = numpy.zeros(len(hmap), info['uhs_dt']) for p, poe in enumerate(info['poes']): for m, imt in enumerate(info['imtls']): if imt.startswith(('PGA', 'SA')): uhs[str(poe)][imt] = hmap[:, m, p] return uhs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_array(self, ebruptures): """ Convert a list of ebruptures into an array of dtype RuptureRata.dt """
data = [] for ebr in ebruptures: rup = ebr.rupture self.cmaker.add_rup_params(rup) ruptparams = tuple(getattr(rup, param) for param in self.params) point = rup.surface.get_middle_point() multi_lons, multi_lats = rup.surface.get_surface_boundar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, rup_array): """ Store the ruptures in array format. """
self.nruptures += len(rup_array) offset = len(self.datastore['rupgeoms']) rup_array.array['gidx1'] += offset rup_array.array['gidx2'] += offset previous = self.datastore.get_attr('ruptures', 'nbytes', 0) self.datastore.extend( 'ruptures', rup_array, nbytes=pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Save information about the rupture codes as attributes of the 'ruptures' dataset. """
if 'ruptures' not in self.datastore: # for UCERF return codes = numpy.unique(self.datastore['ruptures']['code']) attr = {'code_%d' % code: ' '.join( cls.__name__ for cls in BaseRupture.types[code]) for code in codes} self.datastore.set_attrs('rup...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_nonlinear_magnitude_term(self, C, mag): """ Computes the non-linear magnitude term """
return self._compute_linear_magnitude_term(C, mag) +\ C["b3"] * ((mag - 7.0) ** 2.)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_magnitude_distance_term(self, C, rjb, mag): """ Returns the magntude dependent distance term """
rval = np.sqrt(rjb ** 2. + C["h"] ** 2.) return (C["b4"] + C["b5"] * (mag - 4.5)) * np.log(rval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_bnl(self, C_AMP, vs30): """ Gets the nonlinear term, given by equation 8 of Atkinson & Boore 2006 """
# Default case 8d bnl = np.zeros_like(vs30) if np.all(vs30 >= self.CONSTS["Vref"]): return bnl # Case 8a bnl[vs30 < self.CONSTS["v1"]] = C_AMP["b1sa"] # Cade 8b idx = np.logical_and(vs30 > self.CONSTS["v1"], vs30 <= self.C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_stddevs(self, C, stddev_types, stddev_shape): """ Returns the standard deviations given in Table 2 """
stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(C["sigtot"] + np.zeros(stddev_shape)) elif stddev_type == const.StdDev.INTRA_EVENT: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tidy(fnames): """ Reformat a NRML file in a canonical form. That also means reducing the precision of the floats to a standard value. If the file is invalid,...
for fname in fnames: try: node = nrml.read(fname) except ValueError as err: print(err) return with open(fname + '.bak', 'wb') as f: f.write(open(fname, 'rb').read()) with open(fname, 'wb') as f: # make sure the xmlns i.e. t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_hdf5(input): """ Convert .xml and .npz files to .hdf5 files. """
with performance.Monitor('to_hdf5') as mon: for input_file in input: if input_file.endswith('.npz'): output = convert_npz_hdf5(input_file, input_file[:-3] + 'hdf5') elif input_file.endswith('.xml'): # for source model files output = convert_xml_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rup_array(ebruptures, srcfilter=nofilter): """ Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from eve...
if not BaseRupture._code: BaseRupture.init() # initialize rupture codes rups = [] geoms = [] nbytes = 0 offset = 0 for ebrupture in ebruptures: rup = ebrupture.rupture mesh = surface_to_array(rup.surface) sy, sz = mesh.shape[1:] # sanity checks assert ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_cluster(sources, srcfilter, num_ses, param): """ Yields ruptures generated by a cluster of sources. :param sources: A sequence of sources of the same ...
eb_ruptures = [] numpy.random.seed(sources[0].serial) [grp_id] = set(src.src_group_id for src in sources) # AccumDict of arrays with 3 elements weight, nsites, calc_time calc_times = AccumDict(accum=numpy.zeros(3, numpy.float32)) # Set the parameters required to compute the number of occurrence...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sites(calc_id=-1): """ Plot the sites """
# NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as p dstore = util.read(calc_id) sitecol = dstore['sitecol'] lons, lats = sitecol.lons, sitecol.lats if len(lons) > 1 and cross_idl(*lons): lons %= 360 fig, ax = p.subplots() ax.grid(True) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_distance_term(self, C, rrup, backarc): """ Returns the distance scaling term, which varies depending on whether the site is in the forearc or the backar...
# Geometric attenuation function distance_scale = -np.log10(np.sqrt(rrup ** 2 + 3600.0)) # Anelastic attenuation in the backarc distance_scale[backarc] += (C["c2"] * rrup[backarc]) # Anelastic Attenuation in the forearc idx = np.logical_not(backarc) distance_scal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_scaling_term(self, C, rrup): """ Applies the Cascadia correction factor from Table 2 and the positive correction factor given on Page 567 """
a_f = 0.15 + 0.0007 * rrup a_f[a_f > 0.35] = 0.35 return C["af"] + a_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_mean(self, C, mag, rjb): """ Compute mean value, see table 2. """
m1 = 6.4 r1 = 50. h = 6. R = np.sqrt(rjb ** 2 + h ** 2) R1 = np.sqrt(r1 ** 2 + h ** 2) less_r1 = rjb < r1 ge_r1 = rjb >= r1 mean = (C['c1'] + C['c4'] * (mag - m1) * np.log(R) + C['c5'] * rjb + C['c8'] * (8.5 - mag) ** 2) mean[les...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_weichert_factor(beta, cmag, cyear, end_year): ''' Gets the Weichert adjustment factor for each the magnitude bins :param float beta: Beta value of Gutenberg & Richter parameter (b * log(10.)) :param np.ndarray cmag: Magnitude values of the completeness table :param np.ndar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_even_magnitude_completeness(completeness_table, catalogue=None): ''' To make the magnitudes evenly spaced, render to a constant 0.1 magnitude unit :param np.ndarray completeness_table: Completeness table in format [[year, mag]] :param catalogue: Instance of openquake.hmtk.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(objects, key=None): """ Raise a ValueError if there is a duplicated object, otherwise returns the objects as they are. """
dupl = [] for obj, group in itertools.groupby(sorted(objects), key): if sum(1 for _ in group) > 1: dupl.append(obj) if dupl: raise ValueError('Found duplicates %s' % dupl) return objects
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(weighted_objects, num_samples, seed): """ Take random samples of a sequence of weighted objects :param weighted_objects: A finite sequence of objects ...
weights = [] for obj in weighted_objects: w = obj.weight if isinstance(obj.weight, float): weights.append(w) else: weights.append(w['weight']) numpy.random.seed(seed) idxs = numpy.random.choice(len(weights), num_samples, p=weights) # NB: returning an ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_info(smlt): """ Given a path to a source model logic tree, collect all of the path names to the source models it contains and build 1. a dictionary s...
n = nrml.read(smlt) try: blevels = n.logicTree except Exception: raise InvalidFile('%s is not a valid source_model_logic_tree_file' % smlt) paths = collections.defaultdict(set) # branchID -> paths applytosources = collections.defaultdict(list) # branchID ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toml(uncertainty): """ Converts an uncertainty node into a TOML string """
text = uncertainty.text.strip() if not text.startswith('['): # a bare GSIM name was passed text = '[%s]' % text for k, v in uncertainty.attrib.items(): try: v = ast.literal_eval(v) except ValueError: v = repr(v) text += '\n%s = %s' % (k, v) retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """ Compact representation for the names """
names = self.names.split() if len(names) == 1: return names[0] elif len(names) == 2: return ' '.join(names) else: return ' '.join([names[0], '...', names[-1]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_skeleton(self): """ Return an empty copy of the source model, i.e. without sources, but with the proper attributes for each SourceGroup contained within....
src_groups = [] for grp in self.src_groups: sg = copy.copy(grp) sg.sources = [] src_groups.append(sg) return self.__class__(self.names, self.weight, self.path, src_groups, self.num_gsim_paths, self.ordinal, self.samples)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enumerate_paths(self): """ Generate all possible paths starting from this branch set. :returns: Generator of two-item tuples. Each tuple contains weight of t...
for path in self._enumerate_paths([]): flat_path = [] weight = 1.0 while path: path, branch = path weight *= branch.weight flat_path.append(branch) yield weight, flat_path[::-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_source(self, source): # pylint: disable=R0911,R0912 """ Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it. """
for key, value in self.filters.items(): if key == 'applyToTectonicRegionType': if value != source.tectonic_region_type: return False elif key == 'applyToSourceType': if value == 'area': if not isinstance(source, ohs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_uncertainty_to_geometry(self, source, value): """ Modify ``source`` geometry with the uncertainty value ``value`` """
if self.uncertainty_type == 'simpleFaultDipRelative': source.modify('adjust_dip', dict(increment=value)) elif self.uncertainty_type == 'simpleFaultDipAbsolute': source.modify('set_dip', dict(dip=value)) elif self.uncertainty_type == 'simpleFaultGeometryAbsolute': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_uncertainty_to_mfd(self, mfd, value): """ Modify ``mfd`` object with uncertainty value ``value``. """
if self.uncertainty_type == 'abGRAbsolute': a, b = value mfd.modify('set_ab', dict(a_val=a, b_val=b)) elif self.uncertainty_type == 'bGRRelative': mfd.modify('increment_b', dict(value=value)) elif self.uncertainty_type == 'maxMagGRRelative': mfd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_source_models(self, gsim_lt): """ Yield the underlying LtSourceModel, multiple times if there is sampling """
num_gsim_paths = 1 if self.num_samples else gsim_lt.get_num_paths() for i, rlz in enumerate(self): yield LtSourceModel( rlz.value, rlz.weight, ('b1',), [], num_gsim_paths, i, 1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_each_source(self): """ True if there is an applyToSources for each source. """
return (self.info.applytosources and self.info.applytosources == self.source_ids)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_tree(self, tree_node, validate): """ Parse the whole tree and point ``root_branchset`` attribute to the tree's root. """
self.info = collect_info(self.filename) self.source_ids = collections.defaultdict(list) t0 = time.time() for depth, branchinglevel_node in enumerate(tree_node.nodes): self.parse_branchinglevel(branchinglevel_node, depth, validate) dt = time.time() - t0 if val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_branchinglevel(self, branchinglevel_node, depth, validate): """ Parse one branching level. :param branchinglevel_node: ``etree.Element`` object with ta...
new_open_ends = set() branchsets = branchinglevel_node.nodes for number, branchset_node in enumerate(branchsets): branchset = self.parse_branchset(branchset_node, depth, number, validate) self.parse_branches(branchset_node, br...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_branches(self, branchset_node, branchset, validate): """ Create and attach branches at ``branchset_node`` to ``branchset``. :param branchset_node: Same...
weight_sum = 0 branches = branchset_node.nodes values = [] for branchnode in branches: weight = ~branchnode.uncertaintyWeight weight_sum += weight value_node = node_from_elem(branchnode.uncertaintyModel) if value_node.text is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_path(self, seed): """ Return the model name and a list of branch ids. :param seed: the seed used for the sampling """
branchset = self.root_branchset branch_ids = [] while branchset is not None: [branch] = sample(branchset.branches, 1, seed) branch_ids.append(branch.branch_id) branchset = branch.child_branchset modelname = self.root_branchset.get_branch_by_id(branch_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_simple_fault_geometry_surface(self, node): """ Parses a simple fault geometry surface """
spacing = node["spacing"] usd, lsd, dip = (~node.upperSeismoDepth, ~node.lowerSeismoDepth, ~node.dip) # Parse the geometry coords = split_coords_2d(~node.LineString.posList) trace = geo.Line([geo.Point(*p) for p in coords]) return trace, usd, lsd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_complex_fault_geometry_surface(self, node): """ Parses a complex fault geometry surface """
spacing = node["spacing"] edges = [] for edge_node in node.nodes: coords = split_coords_3d(~edge_node.LineString.posList) edges.append(geo.Line([geo.Point(*p) for p in coords])) return edges, spacing
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_planar_geometry_surface(self, node): """ Parses a planar geometry surface """
nodes = [] for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]: nodes.append(geo.Point(getattr(node, key)["lon"], getattr(node, key)["lat"], getattr(node, key)["depth"])) top_left, top_right, bottom_ri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_simple_fault_geometry(self, node, _float_re): """ Validates a node representation of a simple fault geometry """
try: # Parse the geometry coords = split_coords_2d(~node.LineString.posList) trace = geo.Line([geo.Point(*p) for p in coords]) except ValueError: # If the geometry cannot be created then use the LogicTreeError # to point the user to the incorr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_complex_fault_geometry(self, node, _float_re): """ Validates a node representation of a complex fault geometry - this check merely verifies that th...
valid_edges = [] for edge_node in node.nodes: try: coords = split_coords_3d(edge_node.LineString.posList.text) edge = geo.Line([geo.Point(*p) for p in coords]) except ValueError: # See use of validation error in simple geometry cas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_planar_fault_geometry(self, node, _float_re): """ Validares a node representation of a planar fault geometry """
valid_spacing = node["spacing"] for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]: lon = getattr(node, key)["lon"] lat = getattr(node, key)["lat"] depth = getattr(node, key)["depth"] valid_lon = (lon >= -180.0) and (lon <= 180.0) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_uncertainties(self, branch_ids, source_group): """ Parse the path through the source model logic tree and return "apply uncertainties" function. :param...
branchset = self.root_branchset branchsets_and_uncertainties = [] branch_ids = list(branch_ids[::-1]) while branchset is not None: branch = branchset.get_branch_by_id(branch_ids.pop(-1)) if not branchset.uncertainty_type == 'sourceModel': branchs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_one(self): """ Check that all the inner weights are 1 up to the precision """
return all(abs(v - 1.) < pmf.PRECISION for v in self.dic.values())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_(cls, gsim): """ Generate a trivial GsimLogicTree from a single GSIM instance. """
ltbranch = N('logicTreeBranch', {'branchID': 'b1'}, nodes=[N('uncertaintyModel', text=str(gsim)), N('uncertaintyWeight', text='1.0')]) lt = N('logicTree', {'logicTreeID': 'lt1'}, nodes=[N('logicTreeBranchingLevel', {'branchingLevelID': 'bl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_imts(self, imts): """ Make sure the IMTs are recognized by all GSIMs in the logic tree """
for trt in self.values: for gsim in self.values[trt]: for attr in dir(gsim): coeffs = getattr(gsim, attr) if not isinstance(coeffs, CoeffsTable): continue for imt in imts: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce(self, trts): """ Reduce the GsimLogicTree. :param trts: a subset of tectonic region types :returns: a reduced GsimLogicTree instance """
new = object.__new__(self.__class__) vars(new).update(vars(self)) if trts != {'*'}: new.branches = [] for br in self.branches: branch = BranchTuple(br.trt, br.id, br.gsim, br.weight, br.trt in trts) new...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_num_branches(self): """ Return the number of effective branches for tectonic region type, as a dictionary. """
num = {} for trt, branches in itertools.groupby( self.branches, operator.attrgetter('trt')): num[trt] = sum(1 for br in branches if br.effective) return num
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_num_paths(self): """ Return the effective number of paths in the tree. """
# NB: the algorithm assume a symmetric logic tree for the GSIMs; # in the future we may relax such assumption num_branches = self.get_num_branches() if not sum(num_branches.values()): return 0 num = 1 for val in num_branches.values(): if val: # t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_faulting_style_term(Frss, pR, Fnss, pN, rake): """ Compute SHARE faulting style adjustment term. """
if rake > 30.0 and rake <= 150.0: return np.power(Frss, 1 - pR) * np.power(Fnss, -pN) elif rake > -120.0 and rake <= -60.0: return np.power(Frss, - pR) * np.power(Fnss, 1 - pN) else: return np.power(Frss, - pR) * np.power(Fnss, - pN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_stddevs(self, C, stddev_types, mag, num_sites): """ Return total standard deviation as for equation 35, page 1021. """
stddevs = [] for _ in stddev_types: if mag < 7.16: sigma = C['c11'] + C['c12'] * mag elif mag >= 7.16: sigma = C['c13'] stddevs.append(np.zeros(num_sites) + sigma) return stddevs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_term2(self, C, mag, rrup): """ This computes the term f2 in equation 32, page 1021 """
c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2 R = np.sqrt(rrup ** 2 + c78_factor) return C['c4'] * np.log(R) + (C['c5'] + C['c6'] * mag) * rrup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_term3(self, C, rrup): """ This computes the term f3 in equation 34, page 1021 but corrected according to the erratum. """
f3 = np.zeros_like(rrup) idx_between_70_130 = (rrup > 70) & (rrup <= 130) idx_greater_130 = rrup > 130 f3[idx_between_70_130] = ( C['c9'] * (np.log(rrup[idx_between_70_130]) - np.log(70)) ) f3[idx_greater_130] = ( C['c9'] * (np.log(rrup[idx_gre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_window_cutoff(sw_time, time_cutoff): """ Allows for cutting the declustering time window at a specific time, outside of which an event of any magnitude ...
sw_time = np.array( [(time_cutoff / DAYS) if x > (time_cutoff / DAYS) else x for x in sw_time]) return(sw_time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_geometry(self, input_geometry, upper_depth, lower_depth): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.point.Point class, otherwise if already instance of class accept class :param input_geometry: Input geometry (point) as ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def select_catalogue(self, selector, distance, selector_type='circle', distance_metric='epicentral', point_depth=None, upper_eq_depth=None, lower_eq_depth=None): ''' Selects the catalogue associated to the point source. Effectively a wrapper to t...