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_path) volume = etree.fromstring(volume_xml) base_volume_capacity = base_volume.find(".//capacity") volume.append(base_volume_capacity) if cow: backing_xml = BACKING_STORE_DEFAULT_CONFIG.format(base_path) backing_store = etree.fromstring(backing_xml) volume.append(backing_store) return etree.tostring(volume).decode('utf-8')
<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 * target/permission/label """
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(path) except EnvironmentError: logger.exception("Unable to delete storage pool folder.")
<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) except libvirt.libvirtError: logger.exception("Unable to delete storage volumes.")
<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 one, the clone will be created within the storage pool. The following values are set into the disk XML configuration: * name * target/path * target/permission/label * backingStore/path if copy on write is enabled """
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( pool_path.replace('/', '_'))) pool = hypervisor.storagePoolDefineXML(BASE_POOL_CONFIG.format( pool_path.replace('/', '_'), pool_path)) pool.setAutostart(True) pool.create() pool.refresh() volume = hypervisor.storageVolLookupByPath(image) else: raise RuntimeError( "%s disk does not exist." % image) xml = disk_xml(identifier, storage_pool.XMLDesc(0), volume.XMLDesc(0), cow) if cow: storage_pool.createXML(xml, 0) else: storage_pool.createXMLFrom(xml, volume, 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 _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.exception('Provided hook has no name: %s.', hook)
<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 of either group or integer elements :param group: pairing group if an element is a group element :return: """
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) return bytes_to_int(h_challenge.digest())
<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 size is less than the length of chars as this function uses random.choice which uses random sampling without replacement. :param size: size of the random string to generate :param chars: the set of characters to use to generate the random string. Uses alphanumerics by default. :return: the random string generated """
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: encoded[attrName] = encodeAttr(self._vals[attrName]) else: encoded[attrName] = self._vals[at.name] return encoded
<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 attrNames: a list of attributes the schema contains :return: submitted Schema """
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 schemaId: The schema ID (reference to claim definition schema) :param iA: accumulator ID :param L: maximum number of claims within accumulator. :return: Submitted accumulator public key """
accum, tails, accPK, accSK = await self._nonRevocationIssuer.issueAccumulator( schemaId, iA, L) accPK = await self.wallet.submitAccumPublic(schemaId=schemaId, accumPK=accPK, accum=accum, tails=tails) await self.wallet.submitAccumSecret(schemaId=schemaId, accumSK=accSK) return accPK
<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: claim's sequence number within accumulator """
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 given user and schema. :param schemaId: The schema ID (reference to claim definition schema) :param claimRequest: A claim request containing prover ID and prover-generated values :param iA: accumulator ID :param i: claim's sequence number within accumulator :return: The claim (both primary and non-revocation) """
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.getAccumulator(schemaId)).iA # TODO this has un-obvious side-effects await self._genContxt(schemaId, iA, claimRequest.userId) (c1, claim) = await self._issuePrimaryClaim(schemaId, attributes, claimRequest.U) # TODO re-enable when revocation registry is fully implemented c2 = await self._issueNonRevocationClaim(schemaId, claimRequest.Ur, iA, i) if claimRequest.Ur else None signature = Claims(primaryClaim=c1, nonRevocClaim=c2) return (signature, claim)
<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 allClaimRequest: a map of schema ID to a claim request containing prover ID and prover-generated values :return: The claims (both primary and non-revocation) """
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 presented (revealed attributes, predicates, timestamps for non-revocation) :param proof: a proof :return: True if verified successfully and false otherwise. """
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 proofRequest.predicates.keys() != proof.requestedProof.predicates.keys(): raise ValueError('Received predicates ={} do not correspond to requested={}'.format( proof.requestedProof.predicates.keys(), proofRequest.predicates.keys())) TauList = [] for (uuid, proofItem) in proof.proofs.items(): if proofItem.proof.nonRevocProof: TauList += await self._nonRevocVerifier.verifyNonRevocation( proofRequest, proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.nonRevocProof) if proofItem.proof.primaryProof: TauList += await self._primaryVerifier.verify(proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.primaryProof) CHver = self._get_hash(proof.aggregatedProof.CList, self._prepare_collection(TauList), cmod.integer(proofRequest.nonce)) return CHver == proof.aggregatedProof.cHash
<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 given Schema. :param schemaId: The schema ID (reference to claim definition schema) :param claims: claims to be processed and saved """
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, signature.nonRevocClaim)
<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 claim definition. """
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 presented (revealed attributes, predicates, timestamps for non-revocation) :return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values) """
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 signed values. Examples: '17133d482ba4f605' => 1662740067609015813 'b6dbb1c2b362bf51' => -5270423489115668655 :param hex_string: the string representation of a zipkin ID :returns: signed int representation """
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' -5270423489115668655 => 'b6dbb1c2b362bf51' :param signed_int: an int to convert :returns: unsigned hex string """
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_AIOZIPKIN_KEY) -> Application: """Sets required parameters in aiohttp applications for aiozipkin. Tracer added into application context and cleaned after application shutdown. You can provide custom tracer_key, if default name is not suitable. """
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: Application) -> None: await app[tracer_key].close() app.on_cleanup.append(close_aiozipkin) return app
<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_AIOZIPKIN_KEY in aiohttp application context, you can provide own key, if for some reason default one is not suitable. """
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 it as parent on next child span. """
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 object. """
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: params.append(c.parent_id) h = DELIMITER.join(params) headers = {SINGLE_HEADER: h} 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_context(headers: Headers) -> Optional[TraceContext]: """Converts available headers to TraceContext, if headers mapping does not contain zipkin headers, function returns None. """
# 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 headers for h in required) has_b3_single = SINGLE_HEADER in headers if not(has_b3_single or has_b3): return None if has_b3: debug = parse_debug_header(headers) sampled = debug if debug else parse_sampled_header(headers) context = TraceContext( trace_id=headers[TRACE_ID_HEADER.lower()], parent_id=headers.get(PARENT_ID_HEADER.lower()), span_id=headers[SPAN_ID_HEADER.lower()], sampled=sampled, debug=debug, shared=False, ) return context return _parse_single_header(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 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 of keys specified, filter works only for selected keys """
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 with the addition of the faulting style term as given in equation 5, page 465. Converts also displacement responce spectrum values to SA. """
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/s) and also convert from base 10 to base e. if imt.name == "PGA": mean = np.log((10 ** mean) / g) elif imt.name == "SA": mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) * 1e-2 / g) else: mean = np.log(10 ** mean) return 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 ground_motion_fields(rupture, sites, imts, gsim, truncation_level, realizations, correlation_model=None, seed=None): """ Given an earthquake rupture, the ground motion field calculator computes ground shaking over a set of sites, by randomly sampling a ground shaking intensity model. A ground motion field represents a possible 'realization' of the ground shaking due to an earthquake rupture. .. note:: This calculator is using random numbers. In order to reproduce the same results numpy random numbers generator needs to be seeded, see http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html :param openquake.hazardlib.source.rupture.Rupture rupture: Rupture to calculate ground motion fields radiated from. :param openquake.hazardlib.site.SiteCollection sites: Sites of interest to calculate GMFs. :param imts: List of intensity measure type objects (see :mod:`openquake.hazardlib.imt`). :param gsim: Ground-shaking intensity model, instance of subclass of either :class:`~openquake.hazardlib.gsim.base.GMPE` or :class:`~openquake.hazardlib.gsim.base.IPE`. :param truncation_level: Float, number of standard deviations for truncation of the intensity distribution, or ``None``. :param realizations: Integer number of GMF realizations to compute. :param correlation_model: Instance of correlation model object. See :mod:`openquake.hazardlib.correlation`. Can be ``None``, in which case non-correlated ground motion fields are calculated. Correlation model is not used if ``truncation_level`` is zero. :param int seed: The seed used in the numpy random number generator :returns: Dictionary mapping intensity measure type objects (same as in parameter ``imts``) to 2d numpy arrays of floats, representing different realizations of ground shaking intensity for all sites in the collection. First dimension represents sites and second one is for realizations. """
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.exists(archive): sys.exit('%s does not exist' % archive) t0 = time.time() oqdata = os.path.abspath(oqdata) assert archive.endswith('.zip'), archive os.mkdir(oqdata) zipfile.ZipFile(archive).extractall(oqdata) dbpath = os.path.join(oqdata, 'db.sqlite3') db = Db(sqlite3.connect, dbpath, isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES) n = 0 for fname in os.listdir(oqdata): mo = re.match('calc_(\d+)\.hdf5', fname) if mo: job_id = int(mo.group(1)) fullname = os.path.join(oqdata, fname)[:-5] # strip .hdf5 db("UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x", getpass.getuser(), fullname, job_id) safeprint('Restoring ' + fname) n += 1 dt = time.time() - t0 safeprint('Extracted %d calculations into %s in %d seconds' % (n, oqdata, dt))
<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_area: The area of the rupture to float on the fault surface, in squared km. :param rupture_length: The target length (spatial extension along fault trace) of the rupture, in km. :param cell_area: 2d numpy array representing area of mesh cells in squared km. :param cell_length: 2d numpy array of the shape as ``cell_area`` representing cells' length in km. :returns: A list of slice objects. Number of items in the list is equal to number of possible locations of the requested rupture on the fault surface. Each slice can be used to get a portion of the whole fault surface mesh that would represent the location of the rupture. """
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): for col in range(ncols): if col in dead_ends: continue # find the lengths of all possible subsurfaces containing # only the current row and from the current column till # the last one. lengths_acc = numpy.add.accumulate(cell_length[row, col:]) # find the "best match" number of columns, the one that gives # the least difference between actual and requested rupture # length (note that we only consider top row here, mainly # for simplicity: it's not yet clear how many rows will we # end up with). rup_cols = numpy.argmin(numpy.abs(lengths_acc - rupture_length)) last_col = rup_cols + col + 1 if last_col == ncols and lengths_acc[rup_cols] < rupture_length: # rupture doesn't fit along length (the requested rupture # length is greater than the length of the part of current # row that starts from the current column). if col != 0: # if we are not in the first column, it means that we # hit the right border, so we need to go to the next # row. break # now try to find the optimum (the one providing the closest # to requested area) number of rows. areas_acc = numpy.sum(cell_area[row:, col:last_col], axis=1) areas_acc = numpy.add.accumulate(areas_acc, axis=0) rup_rows = numpy.argmin(numpy.abs(areas_acc - rupture_area)) last_row = rup_rows + row + 1 if last_row == nrows and areas_acc[rup_rows] < rupture_area: # rupture doesn't fit along width. # we can try to extend it along length but only if we are # at the first row if row == 0: if last_col == ncols: # there is no place to extend, exiting return rupture_slices else: # try to extend along length areas_acc = numpy.sum(cell_area[:, col:], axis=0) areas_acc = numpy.add.accumulate(areas_acc, axis=0) rup_cols = numpy.argmin( numpy.abs(areas_acc - rupture_area)) last_col = rup_cols + col + 1 if last_col == ncols \ and areas_acc[rup_cols] < rupture_area: # still doesn't fit, return return rupture_slices else: # row is not the first and the required area exceeds # available area starting from target row and column. # mark the column as "dead end" so we don't create # one more rupture from the same column on all # subsequent rows. dead_ends.add(col) # here we add 1 to last row and column numbers because we want # to return slices for cutting the mesh of vertices, not the cell # data (like cell_area or cell_length). rupture_slices.append((slice(row, last_row + 1), slice(col, last_col + 1))) return rupture_slices
<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.CONSTANTS["logMaxR"], self.CONSTANTS["logMinR"])) # Magnitude p_n.append(self._get_normalised_term(rup.mag, self.CONSTANTS["maxMw"], self.CONSTANTS["minMw"])) # Vs30 p_n.append(self._get_normalised_term(np.log10(sites.vs30), self.CONSTANTS["logMaxVs30"], self.CONSTANTS["logMinVs30"])) # Depth p_n.append(self._get_normalised_term(rup.hypo_depth, self.CONSTANTS["maxD"], self.CONSTANTS["minD"])) # Style of Faulting p_n.append(self._get_normalised_term(sof, self.CONSTANTS["maxFM"], self.CONSTANTS["minFM"])) return p_n
<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 symmetric truncation. :param truncation_level: Positive float number representing the truncation on both sides around the mean, in units of sigma. :param values: Numpy array of values as input to a survival function for the given distribution. :returns: Numpy array of survival function results in a range between 0 and 1. True """
# 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 truncation, that is ``a = - truncation_level`` # and ``b = + truncation_level``. # calculate CDF of b phi_b = ndtr(truncation_level) # calculate Z as ``Z = CDF(b) - CDF(a)``, here we assume that # ``CDF(a) == CDF(- truncation_level) == 1 - CDF(b)`` z = phi_b * 2 - 1 # calculate the result of survival function of ``values``, # and restrict it to the interval where probability is defined -- # 0..1. here we use some transformations of the original formula # that is ``SF(x) = 1 - (CDF(x) - CDF(a)) / Z`` in order to minimize # number of arithmetic operations and function calls: # ``SF(x) = (Z - CDF(x) + CDF(a)) / Z``, # ``SF(x) = (CDF(b) - CDF(a) - CDF(x) + CDF(a)) / Z``, # ``SF(x) = (CDF(b) - CDF(x)) / Z``. return ((phi_b - ndtr(values)) / z).clip(0.0, 1.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 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 GMPE. """
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() if imt_name == 'SA': raise ValueError('specify period as float value ' 'to declare SA IMT') imt_coeffs = dict(zip(coeff_names, map(float, row[1:]))) try: sa_period = float(imt_name) except Exception: if imt_name not in imt_module.registry: raise ValueError('unknown IMT %r' % imt_name) imt = imt_module.registry[imt_name]() self.non_sa_coeffs[imt] = imt_coeffs else: if sa_damping is None: raise TypeError('attribute "sa_damping" is required ' 'for tables defining SA') imt = imt_module.SA(sa_period, sa_damping) self.sa_coeffs[imt] = imt_coeffs
<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 total sigma value """
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, save into the registry a callable function with the same signature of the original method. :param str method_name: the method to decorate :param bool completeness: True if the method accepts in input an optional parameter for the completeness table :param fields: a dictionary of field spec corresponding to the keys expected to be present in the config dictionary for the decorated method, e.g. time_bin=numpy.float, b_value=1E-6 """
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 {} self.set_defaults(config, fields) self.check_config(config, fields) return fn(obj, catalogue, config, *args, **kwargs) new_method = decorator(caller, original_method) setattr(class_obj, method_name, new_method) instance = class_obj() func = functools.partial(new_method, instance) func.fields = fields func.model = instance func.completeness = completeness functools.update_wrapper(func, new_method) self[class_obj.__name__] = func return class_obj return class_decorator
<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"]: stress_drop += (C["b2"] * (C["m2"] - self.CONSTANTS["mstar"]) + (C["b3"] * (rup.mag - C["m2"]))) else: stress_drop += (C["b2"] * (rup.mag - self.CONSTANTS["mstar"])) stress_drop = np.exp(stress_drop) # Get corner frequency (equation 4) f0 = 4.9 * 1.0E6 * 3.2 * ((stress_drop / m_0) ** (1. / 3.)) return 1. / f0
<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] = C["c1"] * self.CONSTANTS["r1"] +\ C["c2"] * (self.CONSTANTS["r2"] - self.CONSTANTS["r1"]) +\ C["c3"] * (rrup[idx] - self.CONSTANTS["r2"]) return f_p
<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 = sites.vs30 > self.CONSTANTS["v1"] f_s[idx] += (C["c4"] * np.log(self.CONSTANTS["v1"] / C["vref"])) idx = np.logical_not(idx) f_s[idx] += (C["c4"] * np.log(sites.vs30[idx] / C["vref"])) return f_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 + # 2nd term C['c3'] * R - # 3rd term C['c4'] * np.log10(R) + # 4th term C['c5'] * hypo_depth ) # convert from base 10 to base e if imt == PGV(): mean = np.log(10 ** mean) else: # convert from cm/s**2 to g mean = np.log((10 ** mean) * 1e-2 / g) return 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 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 retrieve """
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 data = [] for line in lines[i + 2:]: columns = line.split() if len(columns) == 6: data.append(PStatData(*columns)) rows = [(rec.ncalls, rec.cumtime, rec.path) for rec in data] # here is an example of the expected output table: # ====== ======= ======================================================== # ncalls cumtime path # ====== ======= ======================================================== # 1 33.502 commands/run.py:77(_run) # 1 33.483 calculators/base.py:110(run) # 1 25.166 calculators/classical.py:115(execute) # 1 25.104 baselib.parallel.py:249(apply_reduce) # 1 25.099 calculators/classical.py:41(classical) # 1 25.099 hazardlib/calc/hazard_curve.py:164(classical) return views.rst_table(rows, header='ncalls cumtime path'.split())
<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=hc_id) rcalc = base.calculators(oq, rcalc_id) rcalc.run(pdb=pdb, exports=exports, **params) return rcalc
<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 layer """
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, params)') prof.runctx(stmt, globals(), locals()) pstat = calc_path + '.pstat' prof.dump_stats(pstat) print('Saved profiling info in %s' % pstat) print(get_pstats(pstat, slowest)) else: _run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params)
<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'): modname, _ext = os.path.splitext(fname) mod = importlib.import_module( 'openquake.hazardlib.scalerel.' + modname) for cls in mod.__dict__.values(): if inspect.isclass(cls) and issubclass(cls, base_class) \ and cls != base_class \ and not inspect.isabstract(cls): gsims[cls.__name__] = cls return dict((k, gsims[k]) for k in sorted(gsims))
<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`. :param streamer: if True, starts a streamer with multiprocessing.Process """
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, cores in self.host_cores: if self.status(host)[0][1] == 'running': print('%s:%s already running' % (host, self.ctrl_port)) continue ctrl_url = 'tcp://%s:%s' % (host, self.ctrl_port) if host == '127.0.0.1': # localhost args = [sys.executable] else: args = ['ssh', host, self.remote_python] args += ['-m', 'openquake.baselib.workerpool', ctrl_url, self.task_out_url, cores] starting.append(' '.join(args)) po = subprocess.Popen(args) self.pids.append(po.pid) return 'starting %s' % starting
<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: sock.send('stop') stopped.append(host) if hasattr(self, 'streamer'): self.streamer.terminate() return 'stopped %s' % stopped
<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,)) proc.start() sock.pid = proc.pid self.workers.append(sock) # start control loop accepting the commands stop and kill with z.Socket(self.ctrl_url, z.zmq.REP, 'bind') as ctrlsock: for cmd in ctrlsock: if cmd in ('stop', 'kill'): msg = getattr(self, cmd)() ctrlsock.send(msg) break elif cmd == 'getpid': ctrlsock.send(self.pid) elif cmd == 'get_num_workers': ctrlsock.send(self.num_workers)
<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 configuration or stop the foreign' ' DbServer instance') % (remote_server_path, server_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 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() and apparently # it works, but then run-demos.sh hangs after the end of the first # calculation, but only if the DbServer is started by oq engine (!?) subprocess.Popen([sys.executable, '-m', 'openquake.server.dbserver', '-l', 'INFO']) # wait for the dbserver to start waiting_seconds = 30 while get_status() == 'not-running': if waiting_seconds == 0: sys.exit('The DbServer cannot be started after 30 seconds. ' 'Please check the configuration') time.sleep(1) waiting_seconds -= 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 run_server(dbpath=os.path.expanduser(config.dbserver.file), dbhostport=None, loglevel='WARN'): """ Run the DbServer on the given database file and port. If not given, use the settings in openquake.cfg. """
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(dirname): os.makedirs(dirname) # create and upgrade the db if needed db('PRAGMA foreign_keys = ON') # honor ON DELETE CASCADE actions.upgrade_db(db) # the line below is needed to work around a very subtle bug of sqlite; # we need new connections, see https://github.com/gem/oq-engine/pull/3002 db.close() # reset any computation left in the 'executing' state actions.reset_is_running(db) # configure logging and start the server logging.basicConfig(level=getattr(logging, loglevel)) DbServer(db, addr).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 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) logging.warning('DB server started with %s on %s, pid %d', sys.executable, self.frontend, self.pid) if ZMQ: # start task_in->task_out streamer thread c = config.zworkers threading.Thread( target=w._streamer, args=(self.master_host, c.task_in_port, c.task_out_port) ).start() logging.warning('Task streamer started from %s -> %s', c.task_in_port, c.task_out_port) # start zworkers and wait a bit for them msg = self.master.start() logging.warning(msg) time.sleep(1) # start frontend->backend proxy for the database workers try: z.zmq.proxy(z.bind(self.frontend, z.zmq.ROUTER), z.bind(self.backend, z.zmq.DEALER)) except (KeyboardInterrupt, z.zmq.ZMQError): for sock in dworkers: sock.running = False sock.zsocket.close() logging.warning('DB server stopped') finally: self.stop()
<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.SiteCollection`. :param rupture: Instance of :class:`openquake.hazardlib.source.rupture.BaseRupture` :returns: (filtered sites, distance context) """
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] else: raise FarAwayRupture( '%d: %d km' % (rupture.serial, distances.min())) return sites, DistancesContext([(self.filter_distance, distances)])
<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 == 'rake': value = rupture.rake elif param == 'ztor': value = rupture.surface.get_top_edge_depth() elif param == 'hypo_lon': value = rupture.hypocenter.longitude elif param == 'hypo_lat': value = rupture.hypocenter.latitude elif param == 'hypo_depth': value = rupture.hypocenter.depth elif param == 'width': value = rupture.surface.get_width() else: raise ValueError('%s requires unknown rupture parameter %r' % (type(self).__name__, param)) setattr(rupture, param, 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 make_contexts(self, sites, rupture): """ Filter the site collection with respect to the rupture and create context objects. :param sites: Instance of :class:`openquake.hazardlib.site.SiteCollection`. :param rupture: Instance of :class:`openquake.hazardlib.source.rupture.BaseRupture` :returns: Tuple of two items: sites and distances context. :raises ValueError: If any of declared required parameters (site, rupture and distance parameters) is unknown. """
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 self.reqv else None) if reqv_obj and isinstance(rupture.surface, PlanarSurface): reqv = reqv_obj.get(dctx.repi, rupture.mag) if 'rjb' in self.REQUIRES_DISTANCES: dctx.rjb = reqv if 'rrup' in self.REQUIRES_DISTANCES: reqv_rup = numpy.sqrt(reqv**2 + rupture.hypocenter.depth**2) dctx.rrup = reqv_rup self.add_rup_params(rupture) # NB: returning a SitesContext make sures that the GSIM cannot # access site parameters different from the ones declared sctx = SitesContext(self.REQUIRES_SITES_PARAMETERS, sites) return sctx, dctx
<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 minimum_distance are rounded up to the minimum_distance. Otherwise, returns the original DistancesContext unchanged. """
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_distances] = minimum_distance setattr(ctx, dist, array) return ctx
<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 never generates a ground motion value higher than a given level at a given site. Such calculation is performed starting from the conditional probability that an occurrence of the current rupture is producing a ground motion value higher than the level of interest at the site of interest. The actual formula used for such calculation depends on the temporal occurrence model the rupture is associated with. The calculation can be performed for multiple intensity measure levels and multiple sites in a vectorized fashion. :param poes: 2D numpy array containing conditional probabilities the the a rupture occurrence causes a ground shaking value exceeding a ground motion level at a site. First dimension represent sites, second dimension intensity measure levels. ``poes`` can be obtained calling the :meth:`method <openquake.hazardlib.gsim.base.GroundShakingIntensityModel.get_poes> """
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 that a # rupture occurrence does not cause a ground motion exceedance, and # thesummation `∑` is done over the number of occurrences `k`. # # `p(k|T)` is given by the attribute probs_occur and # `p(X<x|rup)` is computed as ``1 - poes``. # Converting from 1d to 2d if len(poes.shape) == 1: poes = numpy.reshape(poes, (-1, len(poes))) p_kT = self.probs_occur prob_no_exceed = numpy.array( [v * ((1 - poes) ** i) for i, v in enumerate(p_kT)]) prob_no_exceed = numpy.sum(prob_no_exceed, axis=0) prob_no_exceed[prob_no_exceed > 1.] = 1. # sanity check prob_no_exceed[poes == 0.] = 1. # avoid numeric issues return prob_no_exceed # parametric rupture tom = self.temporal_occurrence_model return tom.get_probability_no_exceedance(self.occurrence_rate, poes)
<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: attribute_array = np.hstack([attribute_array, np.nan]) except: print(irow, key) msg = 'Input file format error at line: %d' % (irow + 2) msg += ' key: %s' % (key) raise ValueError(msg) return attribute_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 _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: attribute_array = np.hstack([attribute_array, np.nan]) except: msg = 'Input file format error at line: %d' % (irow + 2) msg += ' key: %s' % (key) raise ValueError(msg) return attribute_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 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 flag_vector: Boolean vector specifying whether each event is valid (therefore written) or otherwise :param numpy.ndarray magnitude_table: Magnitude-time table specifying the year and magnitudes of completeness ''' # First apply purging conditions output_catalogue = self.apply_purging(catalogue, flag_vector, magnitude_table) outfile = open(self.output_file, 'wt') writer = csv.DictWriter(outfile, fieldnames=self.OUTPUT_LIST) writer.writeheader() # Quick check to remove nan arrays for key in self.OUTPUT_LIST: cond = (isinstance(output_catalogue.data[key], np.ndarray) and np.all(np.isnan(output_catalogue.data[key]))) if cond: output_catalogue.data[key] = [] # Write the catalogue for iloc in range(0, output_catalogue.get_number_events()): row_dict = {} for key in self.OUTPUT_LIST: if len(output_catalogue.data[key]) > 0: row_dict[key] = output_catalogue.data[key][iloc] else: row_dict[key] = '' writer.writerow(row_dict) outfile.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 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: Boolean vector specifying whether each event is valid (therefore written) or otherwise :param numpy.ndarray magnitude_table: Magnitude-time table specifying the year and magnitudes of completeness ''' output_catalogue = deepcopy(catalogue) if magnitude_table is not None: if flag_vector is not None: output_catalogue.catalogue_mt_filter( magnitude_table, flag_vector) return output_catalogue else: output_catalogue.catalogue_mt_filter( magnitude_table) return output_catalogue if flag_vector is not None: output_catalogue.purge_catalogue(flag_vector) return output_catalogue
<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: :class:`~openquake.hazardlib.geo.point.Point` object representing the coordinates of target point to be projected :param reference: :class:`~openquake.hazardlib.geo.point.Point` object representing the coordinates of the reference point. :returns: x y z """
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, projected.longitude, projected.latitude) return (dists * math.sin(math.radians(azims)), dists * math.cos(math.radians(azims)), depths)
<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, sreffc, f_sr = self._get_smr_coeffs(C, C_SITE, idx, n_sites, hard_rock_sa) snc = np.zeros(n_sites) alpha = self.CONSTANTS["alpha"] beta = self.CONSTANTS["beta"] smr = np.zeros(n_sites) sa_soil = hard_rock_sa + ln_a_n_max # Get lnSF ln_sf = self._get_ln_sf(C, C_SITE, idx, n_sites, rup) lnamax_idx = np.exp(ln_a_n_max) < 1.25 not_lnamax_idx = np.logical_not(lnamax_idx) for i in range(1, 5): idx_i = idx[i] if not np.any(idx_i): # No sites of the given site class continue idx2 = np.logical_and(lnamax_idx, idx_i) if np.any(idx2): # Use the approximate method for SRC and SNC c_a = C_SITE["LnAmax1D{:g}".format(i)] /\ (np.log(beta) - np.log(sreffc[idx2] ** alpha + beta)) c_b = -c_a * np.log(sreffc[idx2] ** alpha + beta) snc[idx2] = np.exp((c_a * (alpha - 1.) * np.log(beta) * np.log(10.0 * beta) - np.log(10.0) * (c_b + ln_sf[idx2])) / (c_a * (alpha * np.log(10.0 * beta) - np.log(beta)))) # For the cases when ln_a_n_max >= 1.25 idx2 = np.logical_and(not_lnamax_idx, idx_i) if np.any(idx2): snc[idx2] = (np.exp((ln_a_n_max[idx2] * np.log(sreffc[idx2] ** alpha + beta) - ln_sf[idx2] * np.log(beta)) / C_SITE["LnAmax1D{:g}".format(i)]) - beta) **\ (1.0 / alpha) smr[idx_i] = sreff[idx_i] * (snc[idx_i] / sreffc[idx_i]) *\ f_sr[idx_i] # For the cases when site class = i and SMR != 0 idx2 = np.logical_and(idx_i, np.fabs(smr) > 0.0) if np.any(idx2): sa_soil[idx2] += (-C_SITE["LnAmax1D{:g}".format(i)] * (np.log(smr[idx2] ** alpha + beta) - np.log(beta)) / (np.log(sreffc[idx2] ** alpha + beta) - np.log(beta))) return sa_soil
<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 f_sr[idx[i]] += C_SITE["fsr{:g}".format(i)] return sreff, sreffc, 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 logical vectors for each of the site classes """
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 return site_class, 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_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"] + x_ij[idx] + gn_exp) c_m = min(rup.mag, self.CONSTANTS["m_c"]) r_ij = self.CONSTANTS["xcro"] + x_ij + np.exp(C["c1"] + C["c2"] * c_m) return C["gUM"] * np.log(r_ij) +\ C["gcrL"] * np.log(x_ij + 200.0) +\ g_n + C["eum"] * x_ij + C["ecrV"] * dists.rvolc + C["gamma_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 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"] * (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 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"] * (rup.mag - 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 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 that is not found in the Fortran code, and is thus neglected here. """
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_volc[r_volc >= 80.0] = 80.0 # Get r_ij - distance for geometric spreading (equations 3 and 4) c_m = min(rup.mag, self.CONSTANTS["m_c"]) r_ij = x_ij + np.exp(C["alpha"] + C["beta"] * c_m) return C["gSL"] * np.log(r_ij) + \ C["gLL"] * np.log(x_ij + 200.) +\ C["eSL"] * x_ij + qslh * x_ij +\ C["eSLV"] * dists.rvolc + C["gamma"]
<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( C['tau'] * C['tau'] + phi_ss * phi_ss) + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(phi_ss + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(C['tau'] + np.zeros(num_sites)) 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 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_value are considered. 0.1 """
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 :param min_value: compare only the elements larger than min_value :returns: the relative distance between the arrays '0.11292' """
bigvalues = array_ref > min_value reldiffsquare = (1. - array[bigvalues] / array_ref[bigvalues]) ** 2 return numpy.sqrt(reldiffsquare.mean())