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 disk_xml(identifier, pool_xml, base_volume_xml, cow):
"""Clones volume_xml updating the required fields. * name * target path * backingStore """ |
pool = etree.fromstring(pool_xml)
base_volume = etree.fromstring(base_volume_xml)
pool_path = pool.find('.//path').text
base_path = base_volume.find('.//target/path').text
target_path = os.path.join(pool_path, '%s.qcow2' % identifier)
volume_xml = VOLUME_DEFAULT_CONFIG.format(identifier, target... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pool_create(hypervisor, identifier, pool_path):
"""Storage pool creation. The following values are set in the XML configuration: * name * target/path * targe... |
path = os.path.join(pool_path, identifier)
if not os.path.exists(path):
os.makedirs(path)
xml = POOL_DEFAULT_CONFIG.format(identifier, path)
return hypervisor.storagePoolCreateXML(xml, 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 pool_lookup(hypervisor, disk_path):
"""Storage pool lookup. Retrieves the the virStoragepool which contains the disk at the given path. """ |
try:
volume = hypervisor.storageVolLookupByPath(disk_path)
return volume.storagePoolLookupByVolume()
except libvirt.libvirtError:
return 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 pool_delete(storage_pool, logger):
"""Storage Pool deletion, removes all the created disk images within the pool and the pool itself.""" |
path = etree.fromstring(storage_pool.XMLDesc(0)).find('.//path').text
volumes_delete(storage_pool, logger)
try:
storage_pool.destroy()
except libvirt.libvirtError:
logger.exception("Unable to delete storage pool.")
try:
if os.path.exists(path):
shutil.rmtree(pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def volumes_delete(storage_pool, logger):
"""Deletes all storage volume disks contained in the given storage pool.""" |
try:
for vol_name in storage_pool.listVolumes():
try:
vol = storage_pool.storageVolLookupByName(vol_name)
vol.delete(0)
except libvirt.libvirtError:
logger.exception(
"Unable to delete storage volume %s.", vol_name)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger):
"""Disk image cloning. Given an original disk image it clones it into a new o... |
cow = configuration.get('copy_on_write', False)
try:
volume = hypervisor.storageVolLookupByPath(image)
except libvirt.libvirtError:
if os.path.exists(image):
pool_path = os.path.dirname(image)
logger.info("LibVirt pool does not exist, creating {} pool".format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clone_disk(self, configuration):
"""Clones the disk and returns the path to the new disk.""" |
disk_clone(self._hypervisor, self.identifier, self._storage_pool,
configuration, self.provider_image, self.logger)
disk_name = self._storage_pool.listVolumes()[0]
return self._storage_pool.storageVolLookupByName(disk_name).path() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_configuration(configuration):
"""Returns a dictionary, accepts a dictionary or a path to a JSON file.""" |
if isinstance(configuration, dict):
return configuration
else:
with open(configuration) as configfile:
return json.load(configfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(logger, *args):
"""Environment's cleanup routine.""" |
for obj in args:
if obj is not None and hasattr(obj, 'cleanup'):
try:
obj.cleanup()
except NotImplementedError:
pass
except Exception:
logger.exception("Unable to cleanup %s object", obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allocate(self):
"""Builds the context and the Hooks.""" |
self.logger.debug("Allocating environment.")
self._allocate()
self.logger.debug("Environment successfully allocated.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deallocate(self):
"""Cleans up the context and the Hooks.""" |
self.logger.debug("Deallocating environment.")
self._deallocate()
self.logger.debug("Environment successfully deallocated.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hooks_factory(identifier, configuration, context):
""" Returns the initialized hooks. """ |
manager = HookManager(identifier, configuration)
manager.load_hooks(context)
return manager |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_hooks(self, context):
""" Initializes the Hooks and loads them within the Environment. """ |
for hook in self.configuration.get('hooks', ()):
config = hook.get('configuration', {})
config.update(self.configuration.get('configuration', {}))
try:
self._load_hook(hook['name'], config, context)
except KeyError:
self.logger.ex... |
<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_hash_as_int(*args, group: cmod.PairingGroup = None):
""" Enumerate over the input tuple and generate a hash using the tuple values :param args: sequence ... |
group = group if group else cmod.PairingGroup(PAIRING_GROUP)
h_challenge = sha256()
serialedArgs = [group.serialize(arg) if isGroupElement(arg)
else cmod.Conversion.IP2OS(arg)
for arg in args]
for arg in sorted(serialedArgs):
h_challenge.update(arg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomString(size: int = 20, chars: str = string.ascii_letters + string.digits) -> str: """ Generate a random string of the specified size. Ensure that the si... |
return ''.join(sample(chars, size)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genPrime():
""" Generate 2 large primes `p_prime` and `q_prime` and use them to generate another 2 primes `p` and `q` of 1024 bits """ |
prime = cmod.randomPrime(LARGE_PRIME)
i = 0
while not cmod.isPrime(2 * prime + 1):
prime = cmod.randomPrime(LARGE_PRIME)
i += 1
return prime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encoded(self):
""" This function will encode all the attributes to 256 bit integers :return: """ |
encoded = {}
for i in range(len(self.credType.names)):
self.credType.names[i]
attr_types = self.credType.attrTypes[i]
for at in attr_types:
attrName = at.name
if attrName in self._vals:
if at.encode:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def genSchema(self, name, version, attrNames) -> Schema: """ Generates and submits Schema. :param name: schema name :param version: schema version :param at... |
schema = Schema(name, version, attrNames, self.issuerId)
return await self.wallet.submitSchema(schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def issueAccumulator(self, schemaId: ID, iA, L) -> AccumulatorPublicKey: """ Issues and submits an accumulator used for non-revocation proof. :param schemaI... |
accum, tails, accPK, accSK = await self._nonRevocationIssuer.issueAccumulator(
schemaId, iA, L)
accPK = await self.wallet.submitAccumPublic(schemaId=schemaId,
accumPK=accPK,
accum=accum, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def revoke(self, schemaId: ID, i):
""" Performs revocation of a Claim. :param schemaId: The schema ID (reference to claim definition schema) :param i: clai... |
acc, ts = await self._nonRevocationIssuer.revoke(schemaId, i)
await self.wallet.submitAccumUpdate(schemaId=schemaId, accum=acc,
timestampMs=ts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest, iA=None, i=None) -> (Claims, Dict[str, ClaimAttributeValues]):
""" Issue a claim for the giv... |
schemaKey = (await self.wallet.getSchema(schemaId)).getKey()
attributes = self._attrRepo.getAttributes(schemaKey,
claimRequest.userId)
# TODO re-enable when revocation registry is implemented
# iA = iA if iA else (await self.wallet.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def issueClaims(self, allClaimRequest: Dict[ID, ClaimRequest]) -> \ Dict[ID, Claims]: """ Issue claims for the given users and schemas. :param allClaimReque... |
res = {}
for schemaId, claimReq in allClaimRequest.items():
res[schemaId] = await self.issueClaim(schemaId, claimReq)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def verify(self, proofRequest: ProofRequest, proof: FullProof):
""" Verifies a proof from the prover. :param proofRequest: description of a proof to be pre... |
if proofRequest.verifiableAttributes.keys() != proof.requestedProof.revealed_attrs.keys():
raise ValueError('Received attributes ={} do not correspond to requested={}'.format(
proof.requestedProof.revealed_attrs.keys(), proofRequest.verifiableAttributes.keys()))
if proofRe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims):
""" Processes and saves a received Claim for the... |
await self.wallet.submitContextAttr(schemaId, signature.primaryClaim.m2)
await self.wallet.submitClaimAttributes(schemaId, claimAttributes)
await self._initPrimaryClaim(schemaId, signature.primaryClaim)
if signature.nonRevocClaim:
await self._initNonRevocationClaim(schemaId... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def processClaims(self, allClaims: Dict[ID, Claims]):
""" Processes and saves received Claims. :param claims: claims to be processed and saved for each cla... |
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
res.append(await self.processClaim(schemaId, claim_attributes, claim_signature))
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def presentProof(self, proofRequest: ProofRequest) -> FullProof: """ Presents a proof to the verifier. :param proofRequest: description of a proof to be pre... |
claims, requestedProof = await self._findClaims(proofRequest)
proof = await self._prepareProof(claims, proofRequest.nonce, requestedProof)
return proof |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsigned_hex_to_signed_int(hex_string: str) -> int: """Converts a 64-bit hex string to a signed int value. This is due to the fact that Apache Thrift only has... |
v = struct.unpack(
'q', struct.pack('Q', int(hex_string, 16)))[0] # type: int
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signed_int_to_unsigned_hex(signed_int: int) -> str: """Converts a signed int value to a 64-bit hex string. Examples: 1662740067609015813 => '17133d482ba4f605'... |
hex_string = hex(struct.unpack('Q', struct.pack('q', signed_int))[0])[2:]
if hex_string.endswith('L'):
return hex_string[:-1]
return hex_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(app: Application, tracer: Tracer, *, skip_routes: Optional[AbstractRoute] = None, tracer_key: str = APP_AIOZIPKIN_KEY, request_key: str = REQUEST_AIOZIP... |
app[tracer_key] = tracer
m = middleware_maker(skip_routes=skip_routes,
tracer_key=tracer_key,
request_key=request_key)
app.middlewares.append(m)
# register cleanup signal to close zipkin transport connections
async def close_aiozipkin(app: Applicat... |
<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_tracer( app: Application, tracer_key: str = APP_AIOZIPKIN_KEY) -> Tracer: """Returns tracer object from application context. By default tracer has APP_AIO... |
return cast(Tracer, app[tracer_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 request_span(request: Request, request_key: str = REQUEST_AIOZIPKIN_KEY) -> SpanAbc: """Returns span created by middleware from request context, you can use i... |
return cast(SpanAbc, request[request_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 make_trace_config(tracer: Tracer) -> aiohttp.TraceConfig: """Creates aiohttp.TraceConfig with enabled aiozipking instrumentation for aiohttp client. """ |
trace_config = aiohttp.TraceConfig()
zipkin = ZipkinClientSignals(tracer)
trace_config.on_request_start.append(zipkin.on_request_start)
trace_config.on_request_end.append(zipkin.on_request_end)
trace_config.on_request_exception.append(zipkin.on_request_exception)
return trace_config |
<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_endpoint(service_name: str, *, ipv4: OptStr = None, ipv6: OptStr = None, port: OptInt = None) -> Endpoint: """Factory function to create Endpoint objec... |
return Endpoint(service_name, ipv4, ipv6, port) |
<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_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ |
headers = {
TRACE_ID_HEADER: context.trace_id,
SPAN_ID_HEADER: context.span_id,
FLAGS_HEADER: '0',
SAMPLED_ID_HEADER: '1' if context.sampled else '0',
}
if context.parent_id is not None:
headers[PARENT_ID_HEADER] = context.parent_id
return headers |
<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_single_header(context: TraceContext) -> Headers: """Creates dict with zipkin single header format. """ |
# b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}
c = context
# encode sampled flag
if c.debug:
sampled = 'd'
elif c.sampled:
sampled = '1'
else:
sampled = '0'
params = [c.trace_id, c.span_id, sampled] # type: List[str]
if c.parent_id 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 make_context(headers: Headers) -> Optional[TraceContext]: """Converts available headers to TraceContext, if headers mapping does not contain zipkin headers, f... |
# TODO: add validation for trace_id/span_id/parent_id
# normalize header names just in case someone passed regular dict
# instead dict with case insensitive keys
headers = {k.lower(): v for k, v in headers.items()}
required = (TRACE_ID_HEADER.lower(), SPAN_ID_HEADER.lower())
has_b3 = all(h in... |
<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_none(data: Dict[str, Any], keys: OptKeys = None) -> Dict[str, Any]: """Filter keys from dict with None values. Check occurs only on root level. If list... |
def limited_filter(k: str, v: Any) -> bool:
return k not in keys or v is not None # type: ignore
def full_filter(k: str, v: Any) -> bool:
return v is not None
f = limited_filter if keys is not None else full_filter
return {k: v for k, v in data.items() if f(k, v)} |
<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(self, C, rake):
""" Compute faulting style term as a function of rake angle value as given in equation 5 page 465. """ |
if rake > -120.0 and rake <= -60.0:
return C['aN']
elif rake > 30.0 and rake <= 150.0:
return C['aR']
else:
return C['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 _compute_mean(self, C, mag, dists, vs30, rake, imt):
""" Compute mean value for PGV, PGA and Displacement responce spectrum, as given in equation 2, page 462... |
mean = (self._compute_term_1_2(C, mag) +
self._compute_term_3(C, dists.rhypo) +
self._compute_site_term(C, vs30) +
self._compute_faulting_style_term(C, rake))
# convert from cm/s**2 to g for SA and from m/s**2 to g for PGA (PGV
# is already in cm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ground_motion_fields(rupture, sites, imts, gsim, truncation_level, realizations, correlation_model=None, seed=None):
""" Given an earthquake rupture, the gro... |
cmaker = ContextMaker(rupture.tectonic_region_type, [gsim])
gc = GmfComputer(rupture, sites, [str(imt) for imt in imts],
cmaker, truncation_level, correlation_model)
res, _sig, _eps = gc.compute(gsim, realizations, seed)
return {imt: res[imti] for imti, imt in enumerate(gc.imts)} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore(archive, oqdata):
""" Build a new oqdata directory from the data contained in the zip archive """ |
if os.path.exists(oqdata):
sys.exit('%s exists already' % oqdata)
if '://' in archive:
# get the zip archive from an URL
resp = requests.get(archive)
_, archive = archive.rsplit('/', 1)
with open(archive, 'wb') as f:
f.write(resp.content)
if not os.path.e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _float_ruptures(rupture_area, rupture_length, cell_area, cell_length):
""" Get all possible unique rupture placements on the fault surface. :param rupture_ar... |
nrows, ncols = cell_length.shape
if rupture_area >= numpy.sum(cell_area):
# requested rupture area exceeds the total surface area.
# return the single slice that doesn't cut anything out.
return [slice(None)]
rupture_slices = []
dead_ends = set()
for row in range(nrows):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rhypo_to_rjb(rhypo, mag):
""" Converts hypocentral distance to an equivalent Joyner-Boore distance dependent on the magnitude """ |
epsilon = rhypo - (4.853 + 1.347E-6 * (mag ** 8.163))
rjb = np.zeros_like(rhypo)
idx = epsilon >= 3.
rjb[idx] = np.sqrt((epsilon[idx] ** 2.) - 9.0)
rjb[rjb < 0.0] = 0.0
return rjb |
<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_pn(self, rup, sites, dists, sof):
""" Normalise the input parameters within their upper and lower defined range """ |
# List must be in following order
p_n = []
# Rjb
# Note that Rjb must be clipped at 0.1 km
rjb = rhypo_to_rjb(dists.rhypo, rup.mag)
rjb[rjb < 0.1] = 0.1
p_n.append(self._get_normalised_term(np.log10(rjb),
self.CONSTANT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _truncnorm_sf(truncation_level, values):
""" Survival function for truncated normal distribution. Assumes zero mean, standard deviation equal to one and symm... |
# notation from http://en.wikipedia.org/wiki/Truncated_normal_distribution.
# given that mu = 0 and sigma = 1, we have alpha = a and beta = b.
# "CDF" in comments refers to cumulative distribution function
# of non-truncated distribution with that mu and sigma values.
# assume symmetric truncatio... |
<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_distribution_values(self, values):
""" Returns numpy array of natural logarithms of ``values``. """ |
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# avoid RuntimeWarning: divide by zero encountered in log
return numpy.log(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 set_parameters(self):
""" Combines the parameters of the GMPE provided at the construction level with the ones originally assigned to the backbone modified G... |
for key in (ADMITTED_STR_PARAMETERS + ADMITTED_FLOAT_PARAMETERS +
ADMITTED_SET_PARAMETERS):
try:
val = getattr(self.gmpe, key)
except AttributeError:
pass
else:
setattr(self, key, 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 _setup_table_from_str(self, table, sa_damping):
""" Builds the input tables from a string definition """ |
table = table.strip().splitlines()
header = table.pop(0).split()
if not header[0].upper() == "IMT":
raise ValueError('first column in a table must be IMT')
coeff_names = header[1:]
for row in table:
row = row.split()
imt_name = row[0].upper()
... |
<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, mag):
""" Returns distance scaling term """ |
return (C["r1"] + C["r2"] * mag) *\
np.log(np.sqrt(rrup ** 2. + C["h1"] ** 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 get_sigma(imt):
""" Return the value of the total sigma :param float imt: An :class:`openquake.hazardlib.imt.IMT` instance :returns: A float representing the... |
if imt.period < 0.2:
return np.log(10**0.23)
elif imt.period > 1.0:
return np.log(10**0.27)
else:
return np.log(10**(0.23 + (imt.period - 0.2)/0.8 * 0.04)) |
<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(self, config, fields_spec):
""" Check that `config` has each field in `fields_spec` if a default has not been provided. """ |
for field, type_info in fields_spec.items():
has_default = not isinstance(type_info, type)
if field not in config and not has_default:
raise RuntimeError(
"Configuration not complete. %s missing" % field) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_defaults(self, config, fields_spec):
""" Set default values got from `fields_spec` into the `config` dictionary """ |
defaults = dict([(f, d)
for f, d in fields_spec.items()
if not isinstance(d, type)])
for field, default_value in defaults.items():
if field not in config:
config[field] = default_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, method_name, completeness=False, **fields):
""" Class decorator. Decorate `method_name` by adding a call to `set_defaults` and `check_config`. Then... |
def class_decorator(class_obj):
original_method = getattr(class_obj, method_name)
if sys.version[0] == '2': # Python 2
original_method = original_method.im_func
def caller(fn, obj, catalogue, config=None, *args, **kwargs):
config = config or... |
<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_magnitude_term(self, C, rup):
""" Returns the magnitude scaling term in equation 3 """ |
b0, stress_drop = self._get_sof_terms(C, rup.rake)
if rup.mag <= C["m1"]:
return b0
else:
# Calculate moment (equation 5)
m_0 = 10.0 ** (1.5 * rup.mag + 16.05)
# Get stress-drop scaling (equation 6)
if rup.mag > C["m2"]:
... |
<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):
""" Returns the distance scaling term in equation 7 """ |
f_p = C["c1"] * rrup
idx = np.logical_and(rrup > self.CONSTANTS["r1"],
rrup <= self.CONSTANTS["r2"])
f_p[idx] = (C["c1"] * self.CONSTANTS["r1"]) +\
C["c2"] * (rrup[idx] - self.CONSTANTS["r1"])
idx = rrup > self.CONSTANTS["r2"]
f_p[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 _get_sof_terms(self, C, rake):
""" Returns the style-of-faulting scaling parameters """ |
if rake >= 45.0 and rake <= 135.0:
# Reverse faulting
return C["b0R"], C["b1R"]
elif rake <= -45. and rake >= -135.0:
# Normal faulting
return C["b0N"], C["b1N"]
else:
# Strike slip
return C["b0SS"], C["b1SS"] |
<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_site_amplification(self, C, sites):
""" Returns the site amplification term """ |
# Gets delta normalised z1
dz1 = sites.z1pt0 - np.exp(self._get_lnmu_z1(sites.vs30))
f_s = C["c5"] * dz1
# Calculates site amplification term
f_s[dz1 > self.CONSTANTS["dz1ref"]] = (C["c5"] *
self.CONSTANTS["dz1ref"])
idx = 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 _compute_mean(self, C, g, mag, hypo_depth, dists, imt):
""" Compute mean according to equation on Table 2, page 2275. """ |
delta = 0.00750 * 10 ** (0.507 * mag)
# computing R for different values of mag
if mag < 6.5:
R = np.sqrt(dists.rhypo ** 2 + delta ** 2)
else:
R = np.sqrt(dists.rrup ** 2 + delta ** 2)
mean = (
# 1st term
C['c1'] + C['c2'] * mag... |
<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_pstats(pstatfile, n):
""" Return profiling information as an RST table. :param pstatfile: path to a .pstat file :param n: the maximum number of stats to ... |
with tempfile.TemporaryFile(mode='w+') as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_stats('cumtime')
ps.print_stats(n)
stream.seek(0)
lines = list(stream)
for i, line in enumerate(lines):
if line.startswith(' ncalls'):
break
da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run2(job_haz, job_risk, calc_id, concurrent_tasks, pdb, loglevel, exports, params):
""" Run both hazard and risk, one after the other """ |
hcalc = base.calculators(readinput.get_oqparam(job_haz), calc_id)
hcalc.run(concurrent_tasks=concurrent_tasks, pdb=pdb,
exports=exports, **params)
hc_id = hcalc.datastore.calc_id
rcalc_id = logs.init(level=getattr(logging, loglevel.upper()))
oq = readinput.get_oqparam(job_risk, hc_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 run(job_ini, slowest=False, hc=None, param='', concurrent_tasks=None, exports='', loglevel='info', pdb=None):
""" Run a calculation bypassing the database la... |
dbserver.ensure_on()
if param:
params = oqvalidation.OqParam.check(
dict(p.split('=', 1) for p in param.split(',')))
else:
params = {}
if slowest:
prof = cProfile.Profile()
stmt = ('_run(job_ini, concurrent_tasks, pdb, loglevel, hc, '
'exports... |
<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_available_class(base_class):
'''
Return an ordered dictionary with the available classes in the
scalerel submodule with classes that derives from `base_class`,
keyed by class name.
'''
gsims = {}
for fname in os.listdir(os.path.dirname(__file__)):
if fname.endswith('.py'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, streamer=False):
""" Start multiple workerpools, possibly on remote servers via ssh, and possibly a streamer, depending on the `streamercls`. :pa... |
if streamer and not general.socket_ready(self.task_in_url): # started
self.streamer = multiprocessing.Process(
target=_streamer,
args=(self.master_host, self.task_in_port, self.task_out_port))
self.streamer.start()
starting = []
for host,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Send a "stop" command to all worker pools """ |
stopped = []
for host, _ in self.host_cores:
if self.status(host)[0][1] == 'not-running':
print('%s not running' % host)
continue
ctrl_url = 'tcp://%s:%s' % (host, self.ctrl_port)
with z.Socket(ctrl_url, z.zmq.REQ, 'connect') as sock:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start worker processes and a control loop """ |
setproctitle('oq-zworkerpool %s' % self.ctrl_url[6:]) # strip tcp://
# start workers
self.workers = []
for _ in range(self.num_workers):
sock = z.Socket(self.task_out_port, z.zmq.PULL, 'connect')
proc = multiprocessing.Process(target=self.worker, args=(sock,))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Send a SIGTERM to all worker processes """ |
for sock in self.workers:
os.kill(sock.pid, signal.SIGTERM)
return 'WorkerPool %s stopped' % self.ctrl_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(self):
""" Send a SIGKILL to all worker processes """ |
for sock in self.workers:
os.kill(sock.pid, signal.SIGKILL)
return 'WorkerPool %s killed' % self.ctrl_url |
<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_status(address=None):
""" Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running' """ |
address = address or (config.dbserver.host, DBSERVER_PORT)
return 'running' if socket_ready(address) else 'not-running' |
<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_foreign():
""" Check if we the DbServer is the right one """ |
if not config.dbserver.multi_user:
remote_server_path = logs.dbcmd('get_path')
if different_paths(server_path, remote_server_path):
return('You are trying to contact a DbServer from another'
' instance (got %s, expected %s)\n'
'Check the configurati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_on():
""" Start the DbServer if it is off """ |
if get_status() == 'not-running':
if config.dbserver.multi_user:
sys.exit('Please start the DbServer: '
'see the documentation for details')
# otherwise start the DbServer automatically; NB: I tried to use
# multiprocessing.Process(target=run_server).start()... |
<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_server(dbpath=os.path.expanduser(config.dbserver.file), dbhostport=None, loglevel='WARN'):
""" Run the DbServer on the given database file and port. If n... |
if dbhostport: # assume a string of the form "dbhost:port"
dbhost, port = dbhostport.split(':')
addr = (dbhost, int(port))
else:
addr = (config.dbserver.listen, DBSERVER_PORT)
# create the db directory if needed
dirname = os.path.dirname(dbpath)
if not os.path.exists(dirna... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start database worker threads """ |
# give a nice name to the process
w.setproctitle('oq-dbserver')
dworkers = []
for _ in range(self.num_workers):
sock = z.Socket(self.backend, z.zmq.REP, 'connect')
threading.Thread(target=self.dworker, args=(sock,)).start()
dworkers.append(sock)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop the DbServer and the zworkers if any""" |
if ZMQ:
logging.warning(self.master.stop())
z.context.term()
self.db.close() |
<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_term_3_4(self, dists, C):
""" Compute term 3 and 4 in equation 1 page 1. """ |
cutoff = 6.056877878
rhypo = dists.rhypo.copy()
rhypo[rhypo <= cutoff] = cutoff
return C['c3'] * np.log(rhypo) + C['c4'] * rhypo |
<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_distance_scaling(self, C, rhypo):
""" Returns the distance scaling term accounting for geometric and anelastic attenuation """ |
return C["c"] * np.log10(np.sqrt((rhypo ** 2.) + (C["h"] ** 2.))) +\
(C["d"] * rhypo) |
<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_site_scaling(self, C, vs30):
""" Returns the site scaling term as a simple coefficient """ |
site_term = np.zeros(len(vs30), dtype=float)
# For soil sites add on the site coefficient
site_term[vs30 < 760.0] = C["e"]
return site_term |
<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(self, sites, rupture):
""" Filter the site collection with respect to the rupture. :param sites: Instance of :class:`openquake.hazardlib.site.SiteColl... |
distances = get_distances(rupture, sites, self.filter_distance)
if self.maximum_distance:
mask = distances <= self.maximum_distance(
rupture.tectonic_region_type, rupture.mag)
if mask.any():
sites, distances = sites.filter(mask), distances[mask]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_rup_params(self, rupture):
""" Add .REQUIRES_RUPTURE_PARAMETERS to the rupture """ |
for param in self.REQUIRES_RUPTURE_PARAMETERS:
if param == 'mag':
value = rupture.mag
elif param == 'strike':
value = rupture.surface.get_strike()
elif param == 'dip':
value = rupture.surface.get_dip()
elif param ==... |
<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_contexts(self, sites, rupture):
""" Filter the site collection with respect to the rupture and create context objects. :param sites: Instance of :class:... |
sites, dctx = self.filter(sites, rupture)
for param in self.REQUIRES_DISTANCES - set([self.filter_distance]):
distances = get_distances(rupture, sites, param)
setattr(dctx, param, distances)
reqv_obj = (self.reqv.get(rupture.tectonic_region_type)
if 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 roundup(self, minimum_distance):
""" If the minimum_distance is nonzero, returns a copy of the DistancesContext with updated distances, i.e. the ones below m... |
if not minimum_distance:
return self
ctx = DistancesContext()
for dist, array in vars(self).items():
small_distances = array < minimum_distance
if small_distances.any():
array = array[:] # make a copy first
array[small_distanc... |
<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_probability_no_exceedance(self, poes):
""" Compute and return the probability that in the time span for which the rupture is defined, the rupture itself ... |
if numpy.isnan(self.occurrence_rate): # nonparametric rupture
# Uses the formula
#
# ∑ p(k|T) * p(X<x|rup)^k
#
# where `p(k|T)` is the probability that the rupture occurs k times
# in the time span `T`, `p(X<x|rup)` is the probability ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _float_check(self, attribute_array, value, irow, key):
'''Checks if value is valid float, appends to array if valid, appends
nan if not'''
value = value.strip(' ')
try:
if value:
attribute_array = np.hstack([attribute_array, float(value)])
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 _int_check(self, attribute_array, value, irow, key):
'''Checks if value is valid integer, appends to array if valid, appends
nan if not'''
value = value.strip(' ')
try:
if value:
attribute_array = np.hstack([attribute_array, int(value)])
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 write_file(self, catalogue, flag_vector=None, magnitude_table=None):
'''
Writes the catalogue to file, purging events if necessary.
:param catalogue:
Earthquake catalogue as instance of :class:
openquake.hmtk.seismicity.catalogue.Catalogue
:param numpy.array ... |
<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_purging(self, catalogue, flag_vector, magnitude_table):
'''
Apply all the various purging conditions, if specified.
:param catalogue:
Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`
:param numpy.array flag_vector:
... |
<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_xyz_from_ll(projected, reference):
""" This method computes the x, y and z coordinates of a set of points provided a reference point :param projected: :c... |
azims = geod.azimuth(reference.longitude, reference.latitude,
projected.longitude, projected.latitude)
depths = np.subtract(reference.depth, projected.depth)
dists = geod.geodetic_distance(reference.longitude,
reference.latitude,
... |
<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_magnitude_scaling_term(self, C, rup):
""" Returns the magnitude scaling term in equations 1 and 2 """ |
if rup.mag <= self.CONSTANTS["m_c"]:
return C["ccr"] * rup.mag
else:
return (C["ccr"] * self.CONSTANTS["m_c"]) +\
(C["dcr"] * (rup.mag - self.CONSTANTS["m_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 add_site_amplification(self, C, C_SITE, sites, sa_rock, idx, rup):
""" Applies the site amplification scaling defined in equations from 10 to 15 """ |
n_sites = sites.vs30.shape
# Convert from reference rock to hard rock
hard_rock_sa = sa_rock - C["lnSC1AM"]
# Gets the elastic site amplification ratio
ln_a_n_max = self._get_ln_a_n_max(C, n_sites, idx, rup)
# Retrieves coefficients needed to determine smr
sreff... |
<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_smr_coeffs(self, C, C_SITE, idx, n_sites, sa_rock):
""" Returns the SReff and SReffC terms needed for equation 14 and 15 """ |
# Get SR
sreff = np.zeros(n_sites)
sreffc = np.zeros(n_sites)
f_sr = np.zeros(n_sites)
for i in range(1, 5):
sreff[idx[i]] += (np.exp(sa_rock[idx[i]]) * self.IMF[i])
sreffc[idx[i]] += (C_SITE["Src1D{:g}".format(i)] * self.IMF[i])
# Get f_SR
... |
<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_ln_a_n_max(self, C, n_sites, idx, rup):
""" Defines the rock site amplification defined in equations 10a and 10b """ |
ln_a_n_max = C["lnSC1AM"] * np.ones(n_sites)
for i in [2, 3, 4]:
if np.any(idx[i]):
ln_a_n_max[idx[i]] += C["S{:g}".format(i)]
return ln_a_n_max |
<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_ln_sf(self, C, C_SITE, idx, n_sites, rup):
""" Returns the log SF term required for equation 12 """ |
ln_sf = np.zeros(n_sites)
for i in range(1, 5):
ln_sf_i = (C["lnSC1AM"] - C_SITE["LnAmax1D{:g}".format(i)])
if i > 1:
ln_sf_i += C["S{:g}".format(i)]
ln_sf[idx[i]] += ln_sf_i
return ln_sf |
<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_site_classification(self, vs30):
""" Define the site class categories based on Vs30. Returns a vector of site class values and a dictionary containing l... |
site_class = np.ones(vs30.shape, dtype=int)
idx = {}
idx[1] = vs30 > 600.
idx[2] = np.logical_and(vs30 > 300., vs30 <= 600.)
idx[3] = np.logical_and(vs30 > 200., vs30 <= 300.)
idx[4] = vs30 <= 200.
for i in [2, 3, 4]:
site_class[idx[i]] = i
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 get_sof_term(self, C, rup):
""" In the case of the upper mantle events separate coefficients are considered for normal, reverse and strike-slip """ |
if rup.rake <= -45.0 and rup.rake >= -135.0:
# Normal faulting
return C["FN_UM"]
elif rup.rake > 45.0 and rup.rake < 135.0:
# Reverse faulting
return C["FRV_UM"]
else:
# No adjustment for strike-slip faulting
return 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_distance_term(self, C, dists, rup):
""" Returns the distance attenuation term """ |
x_ij = dists.rrup
gn_exp = np.exp(C["c1"] + 6.5 * C["c2"])
g_n = C["gcrN"] * np.log(self.CONSTANTS["xcro"] + 30. + gn_exp) *\
np.ones_like(x_ij)
idx = x_ij <= 30.0
if np.any(idx):
g_n[idx] = C["gcrN"] * np.log(self.CONSTANTS["xcro"] +
... |
<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_magnitude_scaling_term(self, C, rup):
""" Returns magnitude scaling term, which is dependent on top of rupture depth - as described in equations 1 and 2 ... |
if rup.ztor > 25.0:
# Deep interface events
c_int = C["cint"]
else:
c_int = C["cintS"]
if rup.mag <= self.CONSTANTS["m_c"]:
return c_int * rup.mag
else:
return (c_int * self.CONSTANTS["m_c"]) +\
(C["dint"] * (r... |
<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_magnitude_scaling_term(self, C, rup):
""" Returns the magnitude scaling defined in equation 1 """ |
m_c = self.CONSTANTS["m_c"]
if rup.mag <= m_c:
return C["cSL"] * rup.mag +\
C["cSL2"] * ((rup.mag - self.CONSTANTS["m_sc"]) ** 2.)
else:
return C["cSL"] * m_c +\
C["cSL2"] * ((m_c - self.CONSTANTS["m_sc"]) ** 2.) +\
C["dSL"] ... |
<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, dists, rup):
""" Returns the distance scaling term in equation 2a Note that the paper describes a lower and upper cap on Rvolc tha... |
x_ij = dists.rrup
# Get anelastic scaling term in quation 5
if rup.ztor >= 50.:
qslh = C["eSLH"] * (0.02 * rup.ztor - 1.0)
else:
qslh = 0.0
# r_volc = np.copy(dists.rvolc)
# r_volc[np.logical_and(r_volc > 0.0, r_volc <= 12.0)] = 12.0
# r_v... |
<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, num_sites, mag, c1_rrup, log_phi_ss, mean_phi_ss):
""" Return standard deviations """ |
phi_ss = _compute_phi_ss(C, mag, c1_rrup, log_phi_ss, mean_phi_ss)
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(np.sqrt(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_rel_diff(curve_ref, curve, min_value=0.01):
""" Compute the maximum relative difference between two curves. Only values greather or equal than the min_va... |
assert len(curve_ref) == len(curve), (len(curve_ref), len(curve))
assert len(curve), 'The curves are empty!'
max_diff = 0
for c1, c2 in zip(curve_ref, curve):
if c1 >= min_value:
max_diff = max(max_diff, abs(c1 - c2) / c1)
return max_diff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rmsep(array_ref, array, min_value=0):
""" Root Mean Square Error Percentage for two arrays. :param array_ref: reference array :param array: another array :pa... |
bigvalues = array_ref > min_value
reldiffsquare = (1. - array[bigvalues] / array_ref[bigvalues]) ** 2
return numpy.sqrt(reldiffsquare.mean()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.