idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
25,000 | def signed_int_to_unsigned_hex ( signed_int : int ) -> str : 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 | Converts a signed int value to a 64 - bit hex string . |
25,001 | def setup ( app : Application , tracer : Tracer , * , skip_routes : Optional [ AbstractRoute ] = None , tracer_key : str = APP_AIOZIPKIN_KEY , request_key : str = REQUEST_AIOZIPKIN_KEY ) -> Application : app [ tracer_key ] = tracer m = middleware_maker ( skip_routes = skip_routes , tracer_key = tracer_key , request_key... | Sets required parameters in aiohttp applications for aiozipkin . |
25,002 | def get_tracer ( app : Application , tracer_key : str = APP_AIOZIPKIN_KEY ) -> Tracer : return cast ( Tracer , app [ tracer_key ] ) | Returns tracer object from application context . |
25,003 | def request_span ( request : Request , request_key : str = REQUEST_AIOZIPKIN_KEY ) -> SpanAbc : return cast ( SpanAbc , request [ request_key ] ) | Returns span created by middleware from request context you can use it as parent on next child span . |
25,004 | def make_trace_config ( tracer : Tracer ) -> aiohttp . TraceConfig : 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_except... | Creates aiohttp . TraceConfig with enabled aiozipking instrumentation for aiohttp client . |
25,005 | def create_endpoint ( service_name : str , * , ipv4 : OptStr = None , ipv6 : OptStr = None , port : OptInt = None ) -> Endpoint : return Endpoint ( service_name , ipv4 , ipv6 , port ) | Factory function to create Endpoint object . |
25,006 | def make_headers ( context : TraceContext ) -> Headers : 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 h... | Creates dict with zipkin headers from supplied trace context . |
25,007 | def make_single_header ( context : TraceContext ) -> Headers : c = context if c . debug : sampled = 'd' elif c . sampled : sampled = '1' else : sampled = '0' params = [ c . trace_id , c . span_id , sampled ] if c . parent_id is not None : params . append ( c . parent_id ) h = DELIMITER . join ( params ) headers = { SIN... | Creates dict with zipkin single header format . |
25,008 | def make_context ( headers : Headers ) -> Optional [ TraceContext ] : 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 o... | Converts available headers to TraceContext if headers mapping does not contain zipkin headers function returns None . |
25,009 | def filter_none ( data : Dict [ str , Any ] , keys : OptKeys = None ) -> Dict [ str , Any ] : def limited_filter ( k : str , v : Any ) -> bool : return k not in keys or v is not None 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 :... | Filter keys from dict with None values . |
25,010 | def _compute_faulting_style_term ( self , C , rake ) : 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' ] | Compute faulting style term as a function of rake angle value as given in equation 5 page 465 . |
25,011 | def _compute_mean ( self , C , mag , dists , vs30 , rake , imt ) : 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 ) ) if imt . name == "PGA" : mean = np . log ( ( 10 ** mean ) / g ) el... | 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 . |
25,012 | def ground_motion_fields ( rupture , sites , imts , gsim , truncation_level , realizations , correlation_model = None , seed = None ) : cmaker = ContextMaker ( rupture . tectonic_region_type , [ gsim ] ) gc = GmfComputer ( rupture , sites , [ str ( imt ) for imt in imts ] , cmaker , truncation_level , correlation_model... | 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 . |
25,013 | def restore ( archive , oqdata ) : if os . path . exists ( oqdata ) : sys . exit ( '%s exists already' % oqdata ) if '://' in archive : resp = requests . get ( archive ) _ , archive = archive . rsplit ( '/' , 1 ) with open ( archive , 'wb' ) as f : f . write ( resp . content ) if not os . path . exists ( archive ) : sy... | Build a new oqdata directory from the data contained in the zip archive |
25,014 | def _float_ruptures ( rupture_area , rupture_length , cell_area , cell_length ) : nrows , ncols = cell_length . shape if rupture_area >= numpy . sum ( cell_area ) : return [ slice ( None ) ] rupture_slices = [ ] dead_ends = set ( ) for row in range ( nrows ) : for col in range ( ncols ) : if col in dead_ends : continue... | Get all possible unique rupture placements on the fault surface . |
25,015 | def rhypo_to_rjb ( rhypo , mag ) : 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 | Converts hypocentral distance to an equivalent Joyner - Boore distance dependent on the magnitude |
25,016 | def get_pn ( self , rup , sites , dists , sof ) : p_n = [ ] 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" ] ) ) p_n . append ( self . _get_normalised_term ( rup . ma... | Normalise the input parameters within their upper and lower defined range |
25,017 | def _truncnorm_sf ( truncation_level , values ) : phi_b = ndtr ( truncation_level ) z = phi_b * 2 - 1 return ( ( phi_b - ndtr ( values ) ) / z ) . clip ( 0.0 , 1.0 ) | Survival function for truncated normal distribution . |
25,018 | def to_distribution_values ( self , values ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) return numpy . log ( values ) | Returns numpy array of natural logarithms of values . |
25,019 | def set_parameters ( self ) : 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 ) | Combines the parameters of the GMPE provided at the construction level with the ones originally assigned to the backbone modified GMPE . |
25,020 | def _setup_table_from_str ( self , table , sa_damping ) : 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... | Builds the input tables from a string definition |
25,021 | def get_distance_term ( self , C , rrup , mag ) : return ( C [ "r1" ] + C [ "r2" ] * mag ) * np . log ( np . sqrt ( rrup ** 2. + C [ "h1" ] ** 2. ) ) | Returns distance scaling term |
25,022 | def get_sigma ( imt ) : 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 ) ) | Return the value of the total sigma |
25,023 | def check_config ( self , config , fields_spec ) : 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 ) | Check that config has each field in fields_spec if a default has not been provided . |
25,024 | def set_defaults ( self , config , fields_spec ) : 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 | Set default values got from fields_spec into the config dictionary |
25,025 | def add ( self , method_name , completeness = False , ** fields ) : def class_decorator ( class_obj ) : original_method = getattr ( class_obj , method_name ) if sys . version [ 0 ] == '2' : original_method = original_method . im_func def caller ( fn , obj , catalogue , config = None , * args , ** kwargs ) : config = co... | Class decorator . |
25,026 | def get_magnitude_term ( self , C , rup ) : b0 , stress_drop = self . _get_sof_terms ( C , rup . rake ) if rup . mag <= C [ "m1" ] : return b0 else : m_0 = 10.0 ** ( 1.5 * rup . mag + 16.05 ) if rup . mag > C [ "m2" ] : stress_drop += ( C [ "b2" ] * ( C [ "m2" ] - self . CONSTANTS [ "mstar" ] ) + ( C [ "b3" ] * ( rup .... | Returns the magnitude scaling term in equation 3 |
25,027 | def get_distance_term ( self , C , rrup ) : 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" ] ... | Returns the distance scaling term in equation 7 |
25,028 | def _get_sof_terms ( self , C , rake ) : if rake >= 45.0 and rake <= 135.0 : return C [ "b0R" ] , C [ "b1R" ] elif rake <= - 45. and rake >= - 135.0 : return C [ "b0N" ] , C [ "b1N" ] else : return C [ "b0SS" ] , C [ "b1SS" ] | Returns the style - of - faulting scaling parameters |
25,029 | def get_site_amplification ( self , C , sites ) : dz1 = sites . z1pt0 - np . exp ( self . _get_lnmu_z1 ( sites . vs30 ) ) f_s = C [ "c5" ] * dz1 f_s [ dz1 > self . CONSTANTS [ "dz1ref" ] ] = ( C [ "c5" ] * self . CONSTANTS [ "dz1ref" ] ) idx = sites . vs30 > self . CONSTANTS [ "v1" ] f_s [ idx ] += ( C [ "c4" ] * np . ... | Returns the site amplification term |
25,030 | def _compute_mean ( self , C , g , mag , hypo_depth , dists , imt ) : delta = 0.00750 * 10 ** ( 0.507 * mag ) if mag < 6.5 : R = np . sqrt ( dists . rhypo ** 2 + delta ** 2 ) else : R = np . sqrt ( dists . rrup ** 2 + delta ** 2 ) mean = ( C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c3' ] * R - C [ 'c4' ] * np . log10 ( R ) +... | Compute mean according to equation on Table 2 page 2275 . |
25,031 | def get_pstats ( pstatfile , n ) : 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' ) : b... | Return profiling information as an RST table . |
25,032 | def run2 ( job_haz , job_risk , calc_id , concurrent_tasks , pdb , loglevel , exports , params ) : 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 = l... | Run both hazard and risk one after the other |
25,033 | def run ( job_ini , slowest = False , hc = None , param = '' , concurrent_tasks = None , exports = '' , loglevel = 'info' , pdb = None ) : dbserver . ensure_on ( ) if param : params = oqvalidation . OqParam . check ( dict ( p . split ( '=' , 1 ) for p in param . split ( ',' ) ) ) else : params = { } if slowest : prof =... | Run a calculation bypassing the database layer |
25,034 | def _get_available_class ( base_class ) : 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... | Return an ordered dictionary with the available classes in the scalerel submodule with classes that derives from base_class keyed by class name . |
25,035 | def start ( self , streamer = False ) : if streamer and not general . socket_ready ( self . task_in_url ) : 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 ... | Start multiple workerpools possibly on remote servers via ssh and possibly a streamer depending on the streamercls . |
25,036 | def stop ( self ) : 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' ) stopp... | Send a stop command to all worker pools |
25,037 | def start ( self ) : setproctitle ( 'oq-zworkerpool %s' % self . ctrl_url [ 6 : ] ) 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 .... | Start worker processes and a control loop |
25,038 | def stop ( self ) : for sock in self . workers : os . kill ( sock . pid , signal . SIGTERM ) return 'WorkerPool %s stopped' % self . ctrl_url | Send a SIGTERM to all worker processes |
25,039 | def kill ( self ) : for sock in self . workers : os . kill ( sock . pid , signal . SIGKILL ) return 'WorkerPool %s killed' % self . ctrl_url | Send a SIGKILL to all worker processes |
25,040 | def get_status ( address = None ) : address = address or ( config . dbserver . host , DBSERVER_PORT ) return 'running' if socket_ready ( address ) else 'not-running' | Check if the DbServer is up . |
25,041 | def check_foreign ( ) : 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' ' DbSe... | Check if we the DbServer is the right one |
25,042 | def ensure_on ( ) : if get_status ( ) == 'not-running' : if config . dbserver . multi_user : sys . exit ( 'Please start the DbServer: ' 'see the documentation for details' ) subprocess . Popen ( [ sys . executable , '-m' , 'openquake.server.dbserver' , '-l' , 'INFO' ] ) waiting_seconds = 30 while get_status ( ) == 'not... | Start the DbServer if it is off |
25,043 | def run_server ( dbpath = os . path . expanduser ( config . dbserver . file ) , dbhostport = None , loglevel = 'WARN' ) : if dbhostport : dbhost , port = dbhostport . split ( ':' ) addr = ( dbhost , int ( port ) ) else : addr = ( config . dbserver . listen , DBSERVER_PORT ) dirname = os . path . dirname ( dbpath ) if n... | Run the DbServer on the given database file and port . If not given use the settings in openquake . cfg . |
25,044 | def start ( self ) : 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... | Start database worker threads |
25,045 | def stop ( self ) : if ZMQ : logging . warning ( self . master . stop ( ) ) z . context . term ( ) self . db . close ( ) | Stop the DbServer and the zworkers if any |
25,046 | def _compute_term_3_4 ( self , dists , C ) : cutoff = 6.056877878 rhypo = dists . rhypo . copy ( ) rhypo [ rhypo <= cutoff ] = cutoff return C [ 'c3' ] * np . log ( rhypo ) + C [ 'c4' ] * rhypo | Compute term 3 and 4 in equation 1 page 1 . |
25,047 | def _compute_distance_scaling ( self , C , rhypo ) : return C [ "c" ] * np . log10 ( np . sqrt ( ( rhypo ** 2. ) + ( C [ "h" ] ** 2. ) ) ) + ( C [ "d" ] * rhypo ) | Returns the distance scaling term accounting for geometric and anelastic attenuation |
25,048 | def _compute_site_scaling ( self , C , vs30 ) : site_term = np . zeros ( len ( vs30 ) , dtype = float ) site_term [ vs30 < 760.0 ] = C [ "e" ] return site_term | Returns the site scaling term as a simple coefficient |
25,049 | def filter ( self , sites , rupture ) : 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 ] ... | Filter the site collection with respect to the rupture . |
25,050 | def add_rup_params ( self , 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 =... | Add . REQUIRES_RUPTURE_PARAMETERS to the rupture |
25,051 | def make_contexts ( self , sites , rupture ) : 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_reg... | Filter the site collection with respect to the rupture and create context objects . |
25,052 | def roundup ( self , minimum_distance ) : 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 [ : ] array [ small_distances ] = minimum_distance setattr ( ctx , dist , arr... | 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 . |
25,053 | def get_probability_no_exceedance ( self , poes ) : if numpy . isnan ( self . occurrence_rate ) : 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_exc... | 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 . |
25,054 | def _float_check ( self , attribute_array , value , irow , key ) : 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 a... | Checks if value is valid float appends to array if valid appends nan if not |
25,055 | def _int_check ( self , attribute_array , value , irow , key ) : 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 ... | Checks if value is valid integer appends to array if valid appends nan if not |
25,056 | def write_file ( self , catalogue , flag_vector = None , magnitude_table = None ) : 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 ( ) for key ... | Writes the catalogue to file purging events if necessary . |
25,057 | def apply_purging ( self , catalogue , flag_vector , magnitude_table ) : 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 ... | Apply all the various purging conditions if specified . |
25,058 | def get_xyz_from_ll ( projected , reference ) : 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 , projec... | This method computes the x y and z coordinates of a set of points provided a reference point |
25,059 | def get_magnitude_scaling_term ( self , C , rup ) : 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" ] ) ) | Returns the magnitude scaling term in equations 1 and 2 |
25,060 | def add_site_amplification ( self , C , C_SITE , sites , sa_rock , idx , rup ) : n_sites = sites . vs30 . shape hard_rock_sa = sa_rock - C [ "lnSC1AM" ] ln_a_n_max = self . _get_ln_a_n_max ( C , n_sites , idx , rup ) sreff , sreffc , f_sr = self . _get_smr_coeffs ( C , C_SITE , idx , n_sites , hard_rock_sa ) snc = np .... | Applies the site amplification scaling defined in equations from 10 to 15 |
25,061 | def _get_smr_coeffs ( self , C , C_SITE , idx , n_sites , sa_rock ) : 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}" . ... | Returns the SReff and SReffC terms needed for equation 14 and 15 |
25,062 | def _get_ln_a_n_max ( self , C , n_sites , idx , rup ) : 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 | Defines the rock site amplification defined in equations 10a and 10b |
25,063 | def _get_ln_sf ( self , C , C_SITE , idx , n_sites , rup ) : 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 | Returns the log SF term required for equation 12 |
25,064 | def _get_site_classification ( self , vs30 ) : 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 [ id... | 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 |
25,065 | def get_sof_term ( self , C , rup ) : if rup . rake <= - 45.0 and rup . rake >= - 135.0 : return C [ "FN_UM" ] elif rup . rake > 45.0 and rup . rake < 135.0 : return C [ "FRV_UM" ] else : return 0.0 | In the case of the upper mantle events separate coefficients are considered for normal reverse and strike - slip |
25,066 | def get_distance_term ( self , C , dists , rup ) : 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 . CONSTA... | Returns the distance attenuation term |
25,067 | def get_magnitude_scaling_term ( self , C , rup ) : if rup . ztor > 25.0 : 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" ] ) ) | Returns magnitude scaling term which is dependent on top of rupture depth - as described in equations 1 and 2 |
25,068 | def get_magnitude_scaling_term ( self , C , rup ) : 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" ] ... | Returns the magnitude scaling defined in equation 1 |
25,069 | def get_distance_term ( self , C , dists , rup ) : x_ij = dists . rrup if rup . ztor >= 50. : qslh = C [ "eSLH" ] * ( 0.02 * rup . ztor - 1.0 ) else : qslh = 0.0 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 ... | Returns the distance scaling term in equation 2a |
25,070 | def _get_stddevs ( self , C , stddev_types , num_sites , mag , c1_rrup , log_phi_ss , mean_phi_ss ) : 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 . StdD... | Return standard deviations |
25,071 | def max_rel_diff ( curve_ref , curve , min_value = 0.01 ) : 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 ) ret... | Compute the maximum relative difference between two curves . Only values greather or equal than the min_value are considered . |
25,072 | def rmsep ( array_ref , array , min_value = 0 ) : bigvalues = array_ref > min_value reldiffsquare = ( 1. - array [ bigvalues ] / array_ref [ bigvalues ] ) ** 2 return numpy . sqrt ( reldiffsquare . mean ( ) ) | Root Mean Square Error Percentage for two arrays . |
25,073 | def log ( array , cutoff ) : arr = numpy . copy ( array ) arr [ arr < cutoff ] = cutoff return numpy . log ( arr ) | Compute the logarithm of an array with a cutoff on the small values |
25,074 | def compose_arrays ( a1 , a2 , firstfield = 'etag' ) : assert len ( a1 ) == len ( a2 ) , ( len ( a1 ) , len ( a2 ) ) if a1 . dtype . names is None and len ( a1 . shape ) == 1 : a1 = numpy . array ( a1 , numpy . dtype ( [ ( firstfield , a1 . dtype ) ] ) ) fields1 = [ ( f , a1 . dtype . fields [ f ] [ 0 ] ) for f in a1 .... | Compose composite arrays by generating an extended datatype containing all the fields . The two arrays must have the same length . |
25,075 | def check_script ( upgrade , conn , dry_run = True , debug = True ) : conn = WrappedConnection ( conn , debug = debug ) try : upgrade ( conn ) except Exception : conn . rollback ( ) raise else : if dry_run : conn . rollback ( ) else : conn . commit ( ) | An utility to debug upgrade scripts written in Python |
25,076 | def apply_sql_script ( conn , fname ) : sql = open ( fname ) . read ( ) try : for query in sql . split ( '\n\n' ) : conn . execute ( query ) except Exception : logging . error ( 'Error executing %s' % fname ) raise | Apply the given SQL script to the database |
25,077 | def upgrade_db ( conn , pkg_name = 'openquake.server.db.schema.upgrades' , skip_versions = ( ) ) : upgrader = UpgradeManager . instance ( conn , pkg_name ) t0 = time . time ( ) try : versions_applied = upgrader . upgrade ( conn , skip_versions ) except : conn . rollback ( ) raise else : conn . commit ( ) dt = time . ti... | Upgrade a database by running several scripts in a single transaction . |
25,078 | def run ( self , templ , * args ) : curs = self . _conn . cursor ( ) query = curs . mogrify ( templ , args ) if self . debug : print ( query ) curs . execute ( query ) return curs | A simple utility to run SQL queries . |
25,079 | def install_versioning ( self , conn ) : logging . info ( 'Creating the versioning table %s' , self . version_table ) conn . executescript ( CREATE_VERSIONING % self . version_table ) self . _insert_script ( self . read_scripts ( ) [ 0 ] , conn ) | Create the version table into an already populated database and insert the base script . |
25,080 | def init ( self , conn ) : base = self . read_scripts ( ) [ 0 ] [ 'fname' ] logging . info ( 'Creating the initial schema from %s' , base ) apply_sql_script ( conn , os . path . join ( self . upgrade_dir , base ) ) self . install_versioning ( conn ) | Create the version table and run the base script on an empty database . |
25,081 | def upgrade ( self , conn , skip_versions = ( ) ) : db_versions = self . get_db_versions ( conn ) self . starting_version = max ( db_versions ) to_skip = sorted ( db_versions | set ( skip_versions ) ) scripts = self . read_scripts ( None , None , to_skip ) if not scripts : return [ ] self . ending_version = max ( s [ '... | Upgrade the database from the current version to the maximum version in the upgrade scripts . |
25,082 | def get_db_versions ( self , conn ) : curs = conn . cursor ( ) query = 'select version from {}' . format ( self . version_table ) try : curs . execute ( query ) return set ( version for version , in curs . fetchall ( ) ) except : raise VersioningNotInstalled ( 'Run oq engine --upgrade-db' ) | Get all the versions stored in the database as a set . |
25,083 | def read_scripts ( self , minversion = None , maxversion = None , skip_versions = ( ) ) : scripts = [ ] versions = { } for scriptname in sorted ( os . listdir ( self . upgrade_dir ) ) : match = self . parse_script_name ( scriptname ) if match : version = match [ 'version' ] if version in skip_versions : continue elif m... | Extract the upgrade scripts from a directory as a list of dictionaries ordered by version . |
25,084 | def extract_upgrade_scripts ( self ) : link_pattern = '>\s*{0}\s*<' . format ( self . pattern [ 1 : - 1 ] ) page = urllib . request . urlopen ( self . upgrades_url ) . read ( ) for mo in re . finditer ( link_pattern , page ) : scriptname = mo . group ( 0 ) [ 1 : - 1 ] . strip ( ) yield self . parse_script_name ( script... | Extract the OpenQuake upgrade scripts from the links in the GitHub page |
25,085 | def average_azimuth ( self ) : if len ( self . points ) == 2 : return self . points [ 0 ] . azimuth ( self . points [ 1 ] ) lons = numpy . array ( [ point . longitude for point in self . points ] ) lats = numpy . array ( [ point . latitude for point in self . points ] ) azimuths = geodetic . azimuth ( lons [ : - 1 ] , ... | Calculate and return weighted average azimuth of all line s segments in decimal degrees . |
25,086 | def resample ( self , section_length ) : if len ( self . points ) < 2 : return Line ( self . points ) resampled_points = [ ] resampled_points . extend ( self . points [ 0 ] . equally_spaced_points ( self . points [ 1 ] , section_length ) ) for i in range ( 2 , len ( self . points ) ) : points = resampled_points [ - 1 ]... | Resample this line into sections . |
25,087 | def get_length ( self ) : length = 0 for i , point in enumerate ( self . points ) : if i != 0 : length += point . distance ( self . points [ i - 1 ] ) return length | Calculate and return the length of the line as a sum of lengths of all its segments . |
25,088 | def resample_to_num_points ( self , num_points ) : assert len ( self . points ) > 1 , "can not resample the line of one point" section_length = self . get_length ( ) / ( num_points - 1 ) resampled_points = [ self . points [ 0 ] ] segment = 0 acc_length = 0 last_segment_length = 0 for i in range ( num_points - 1 ) : tot... | Resample the line to a specified number of points . |
25,089 | def cena_tau ( imt , mag , params ) : if imt . name == "PGV" : C = params [ "PGV" ] else : C = params [ "SA" ] if mag > 6.5 : return C [ "tau3" ] elif ( mag > 5.5 ) and ( mag <= 6.5 ) : return ITPL ( mag , C [ "tau3" ] , C [ "tau2" ] , 5.5 , 1.0 ) elif ( mag > 5.0 ) and ( mag <= 5.5 ) : return ITPL ( mag , C [ "tau2" ]... | Returns the inter - event standard deviation tau for the CENA case |
25,090 | def get_tau_at_quantile ( mean , stddev , quantile ) : tau_model = { } for imt in mean : tau_model [ imt ] = { } for key in mean [ imt ] : if quantile is None : tau_model [ imt ] [ key ] = mean [ imt ] [ key ] else : tau_model [ imt ] [ key ] = _at_percentile ( mean [ imt ] [ key ] , stddev [ imt ] [ key ] , quantile )... | Returns the value of tau at a given quantile in the form of a dictionary organised by intensity measure |
25,091 | def get_stddevs ( self , mag , imt , stddev_types , num_sites ) : tau = self . _get_tau ( imt , mag ) phi = self . _get_phi ( imt , mag ) sigma = np . sqrt ( tau ** 2. + phi ** 2. ) stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const ... | Returns the standard deviations for either the ergodic or non - ergodic models |
25,092 | def get_stddevs ( self , mag , imt , stddev_types , num_sites ) : stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : sigma = self . _get_total_sigma ( imt , mag ) stddevs . append ( sigma + np . zeros ( num_sites )... | Returns the total standard deviation |
25,093 | def _get_sigma_at_quantile ( self , sigma_quantile ) : tau_std = TAU_SETUP [ self . tau_model ] [ "STD" ] phi_std = deepcopy ( self . PHI_SS . sa_coeffs ) phi_std . update ( self . PHI_SS . non_sa_coeffs ) for key in phi_std : phi_std [ key ] = { "a" : PHI_SETUP [ self . phi_model ] [ key ] [ "var_a" ] , "b" : PHI_SETU... | Calculates the total standard deviation at the specified quantile |
25,094 | def _get_tau_vector ( self , tau_mean , tau_std , imt_list ) : self . magnitude_limits = MAG_LIMS_KEYS [ self . tau_model ] [ "mag" ] self . tau_keys = MAG_LIMS_KEYS [ self . tau_model ] [ "keys" ] t_bar = { } t_std = { } for imt in imt_list : t_bar [ imt ] = [ ] t_std [ imt ] = [ ] for mag , key in zip ( self . magnit... | Gets the vector of mean and variance of tau values corresponding to the specific model and returns them as dictionaries |
25,095 | def _get_phi_vector ( self , phi_mean , phi_std , imt_list ) : p_bar = { } p_std = { } for imt in imt_list : p_bar [ imt ] = [ ] p_std [ imt ] = [ ] for mag in self . magnitude_limits : phi_ss_mean = get_phi_ss ( imt , mag , phi_mean ) phi_ss_std = get_phi_ss ( imt , mag , phi_std ) if self . ergodic : phi_ss_mean = np... | Gets the vector of mean and variance of phi values corresponding to the specific model and returns them as dictionaries |
25,096 | def _get_total_sigma ( self , imt , mag ) : C = self . SIGMA [ imt ] if mag <= self . magnitude_limits [ 0 ] : return C [ self . tau_keys [ 0 ] ] elif mag > self . magnitude_limits [ - 1 ] : return C [ self . tau_keys [ - 1 ] ] else : for i in range ( len ( self . tau_keys ) - 1 ) : l_m = self . magnitude_limits [ i ] ... | Returns the estimated total standard deviation for a given intensity measure type and magnitude |
25,097 | def get_hcurves_and_means ( dstore ) : rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) getter = getters . PmapGetter ( dstore , rlzs_assoc ) pmaps = getter . get_pmaps ( ) return dict ( zip ( getter . rlzs , pmaps ) ) , dstore [ 'hcurves/mean' ] | Extract hcurves from the datastore and compute their means . |
25,098 | def _compute_mean ( self , C , mag , rhypo , hypo_depth , mean , idx ) : mean [ idx ] = ( C [ 'C1' ] + C [ 'C2' ] * mag + C [ 'C3' ] * np . log ( rhypo [ idx ] + C [ 'C4' ] * np . exp ( C [ 'C5' ] * mag ) ) + C [ 'C6' ] * hypo_depth ) | Compute mean value according to equations 10 and 11 page 226 . |
25,099 | def _compute_std ( self , C , stddevs , idx ) : for stddev in stddevs : stddev [ idx ] += C [ 'sigma' ] | Compute total standard deviation see tables 3 and 4 pages 227 and 228 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.