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 = request_key ) app . middlewares . append ( m ) async def close_aiozipkin ( app : Application ) -> None : await app [ tracer_key ] . close ( ) app . on_cleanup . append ( close_aiozipkin ) return app | 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_exception . append ( zipkin . on_request_exception ) return trace_config | 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 headers | 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 = { SINGLE_HEADER : h } return headers | 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 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 ) | 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 : v for k , v in data . items ( ) if f ( k , v ) } | 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 ) 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 | 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 ) res , _sig , _eps = gc . compute ( gsim , realizations , seed ) return { imt : res [ imti ] for imti , imt in enumerate ( gc . imts ) } | 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 ) : 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 ] 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 ) ) | 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 lengths_acc = numpy . add . accumulate ( cell_length [ row , col : ] ) 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 : if col != 0 : break 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 : if row == 0 : if last_col == ncols : return rupture_slices else : 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 : return rupture_slices else : dead_ends . add ( col ) rupture_slices . append ( ( slice ( row , last_row + 1 ) , slice ( col , last_col + 1 ) ) ) return rupture_slices | 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 . mag , self . CONSTANTS [ "maxMw" ] , self . CONSTANTS [ "minMw" ] ) ) p_n . append ( self . _get_normalised_term ( np . log10 ( sites . vs30 ) , self . CONSTANTS [ "logMaxVs30" ] , self . CONSTANTS [ "logMinVs30" ] ) ) p_n . append ( self . _get_normalised_term ( rup . hypo_depth , self . CONSTANTS [ "maxD" ] , self . CONSTANTS [ "minD" ] ) ) p_n . append ( self . _get_normalised_term ( sof , self . CONSTANTS [ "maxFM" ] , self . CONSTANTS [ "minFM" ] ) ) return p_n | 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 = 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 | 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 = 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 | 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 . mag - C [ "m2" ] ) ) ) else : stress_drop += ( C [ "b2" ] * ( rup . mag - self . CONSTANTS [ "mstar" ] ) ) stress_drop = np . exp ( stress_drop ) f0 = 4.9 * 1.0E6 * 3.2 * ( ( stress_drop / m_0 ) ** ( 1. / 3. ) ) return 1. / f0 | 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" ] 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 | 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 . 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 | 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 ) + C [ 'c5' ] * hypo_depth ) if imt == PGV ( ) : mean = np . log ( 10 ** mean ) else : mean = np . log ( ( 10 ** mean ) * 1e-2 / g ) return mean | 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' ) : 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 ] return views . rst_table ( rows , header = 'ncalls cumtime path' . split ( ) ) | 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 = 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 | 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 = 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 ) | 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 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 ) ) | 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 . 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' : 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 | 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' ) stopped . append ( host ) if hasattr ( self , 'streamer' ) : self . streamer . terminate ( ) return 'stopped %s' % stopped | 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 . pid = proc . pid self . workers . append ( sock ) 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 ) | 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' ' DbServer instance' ) % ( remote_server_path , server_path ) | 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-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 | 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 not os . path . exists ( dirname ) : os . makedirs ( dirname ) db ( 'PRAGMA foreign_keys = ON' ) actions . upgrade_db ( db ) db . close ( ) actions . reset_is_running ( db ) logging . basicConfig ( level = getattr ( logging , loglevel ) ) DbServer ( db , addr ) . start ( ) | 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 with %s on %s, pid %d' , sys . executable , self . frontend , self . pid ) if ZMQ : 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 ) msg = self . master . start ( ) logging . warning ( msg ) time . sleep ( 1 ) 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 ( ) | 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 ] else : raise FarAwayRupture ( '%d: %d km' % ( rupture . serial , distances . min ( ) ) ) return sites , DistancesContext ( [ ( self . filter_distance , distances ) ] ) | 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 == '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 ) | 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_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 ) sctx = SitesContext ( self . REQUIRES_SITES_PARAMETERS , sites ) return sctx , dctx | 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 , array ) return ctx | 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_exceed = numpy . sum ( prob_no_exceed , axis = 0 ) prob_no_exceed [ prob_no_exceed > 1. ] = 1. prob_no_exceed [ poes == 0. ] = 1. return prob_no_exceed tom = self . temporal_occurrence_model return tom . get_probability_no_exceedance ( self . occurrence_rate , 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 . |
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 at line: %d' % ( irow + 2 ) msg += ' key: %s' % ( key ) raise ValueError ( msg ) return attribute_array | 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 ) msg += ' key: %s' % ( key ) raise ValueError ( msg ) return attribute_array | 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 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 ] = [ ] 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 ( ) | 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 ( magnitude_table ) return output_catalogue if flag_vector is not None : output_catalogue . purge_catalogue ( flag_vector ) return output_catalogue | 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 , projected . longitude , projected . latitude ) return ( dists * math . sin ( math . radians ( azims ) ) , dists * math . cos ( math . radians ( azims ) ) , depths ) | 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 . 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 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 ) : continue idx2 = np . logical_and ( lnamax_idx , idx_i ) if np . any ( idx2 ) : 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 ) ) ) ) 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 ] 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 | 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}" . format ( i ) ] * self . IMF [ i ] ) f_sr [ idx [ i ] ] += C_SITE [ "fsr{:g}" . format ( i ) ] return sreff , sreffc , f_sr | 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 [ idx [ i ] ] = i return site_class , idx | 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 . 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" ] | 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" ] * ( rup . mag - m_c ) | 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 [ "gLL" ] * np . log ( x_ij + 200. ) + C [ "eSL" ] * x_ij + qslh * x_ij + C [ "eSLV" ] * dists . rvolc + C [ "gamma" ] | 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 . 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 | 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 ) return max_diff | 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 . dtype . names ] if a2 . dtype . names is None : assert len ( a2 . shape ) == 2 , a2 . shape width = a2 . shape [ 1 ] fields2 = [ ( 'value%d' % i , a2 . dtype ) for i in range ( width ) ] composite = numpy . zeros ( a1 . shape , numpy . dtype ( fields1 + fields2 ) ) for f1 in dict ( fields1 ) : composite [ f1 ] = a1 [ f1 ] for i in range ( width ) : composite [ 'value%d' % i ] = a2 [ : , i ] return composite fields2 = [ ( f , a2 . dtype . fields [ f ] [ 0 ] ) for f in a2 . dtype . names ] composite = numpy . zeros ( a1 . shape , numpy . dtype ( fields1 + fields2 ) ) for f1 in dict ( fields1 ) : composite [ f1 ] = a1 [ f1 ] for f2 in dict ( fields2 ) : composite [ f2 ] = a2 [ f2 ] return composite | 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 . time ( ) - t0 logging . info ( 'Upgrade completed in %s seconds' , dt ) return versions_applied | 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 [ 'version' ] for s in scripts ) return self . _upgrade ( conn , scripts ) | 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 minversion and version <= minversion : continue elif maxversion and version > maxversion : continue try : previousname = versions [ version ] except KeyError : scripts . append ( match ) versions [ version ] = scriptname else : raise DuplicatedVersion ( 'Duplicated versions {%s,%s}' % ( scriptname , previousname ) ) return scripts | 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 ( scriptname ) | 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 ] , lats [ : - 1 ] , lons [ 1 : ] , lats [ 1 : ] ) distances = geodetic . geodetic_distance ( lons [ : - 1 ] , lats [ : - 1 ] , lons [ 1 : ] , lats [ 1 : ] ) azimuths = numpy . radians ( azimuths ) avg_x = numpy . mean ( distances * numpy . sin ( azimuths ) ) avg_y = numpy . mean ( distances * numpy . cos ( azimuths ) ) azimuth = numpy . degrees ( numpy . arctan2 ( avg_x , avg_y ) ) if azimuth < 0 : azimuth += 360 return azimuth | 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 ] . equally_spaced_points ( self . points [ i ] , section_length ) resampled_points . extend ( points [ 1 : ] ) return Line ( resampled_points ) | 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_length = ( i + 1 ) * section_length while tot_length > acc_length and segment < len ( self . points ) - 1 : last_segment_length = self . points [ segment ] . distance ( self . points [ segment + 1 ] ) acc_length += last_segment_length segment += 1 p1 , p2 = self . points [ segment - 1 : segment + 1 ] offset = tot_length - ( acc_length - last_segment_length ) if offset < 1e-5 : resampled = p1 else : resampled = p1 . equally_spaced_points ( p2 , offset ) [ 1 ] resampled_points . append ( resampled ) return Line ( resampled_points ) | 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" ] , C [ "tau1" ] , 5.0 , 0.5 ) else : return C [ "tau1" ] | 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 ) return tau_model | 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 . StdDev . TOTAL : stddevs . append ( sigma + np . zeros ( num_sites ) ) elif stddev_type == const . StdDev . INTRA_EVENT : stddevs . append ( phi + np . zeros ( num_sites ) ) elif stddev_type == const . StdDev . INTER_EVENT : stddevs . append ( tau + np . zeros ( num_sites ) ) return stddevs | 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 ) ) return stddevs | 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_SETUP [ self . phi_model ] [ key ] [ "var_b" ] } if self . ergodic : imt_list = list ( PHI_S2SS_MODEL [ self . phi_s2ss_model ] . non_sa_coeffs . keys ( ) ) imt_list += list ( PHI_S2SS_MODEL [ self . phi_s2ss_model ] . sa_coeffs . keys ( ) ) else : imt_list = phi_std . keys ( ) phi_std = CoeffsTable ( sa_damping = 5 , table = phi_std ) tau_bar , tau_std = self . _get_tau_vector ( self . TAU , tau_std , imt_list ) phi_bar , phi_std = self . _get_phi_vector ( self . PHI_SS , phi_std , imt_list ) sigma = { } for imt in imt_list : sigma [ imt ] = { } for i , key in enumerate ( self . tau_keys ) : sigma_bar = np . sqrt ( tau_bar [ imt ] [ i ] ** 2. + phi_bar [ imt ] [ i ] ** 2. ) sigma_std = np . sqrt ( tau_std [ imt ] [ i ] ** 2. + phi_std [ imt ] [ i ] ** 2. ) new_key = key . replace ( "tau" , "sigma" ) if sigma_quantile is not None : sigma [ imt ] [ new_key ] = _at_percentile ( sigma_bar , sigma_std , sigma_quantile ) else : sigma [ imt ] [ new_key ] = sigma_bar self . tau_keys [ i ] = new_key self . SIGMA = CoeffsTable ( sa_damping = 5 , table = sigma ) | 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 . magnitude_limits , self . tau_keys ) : t_bar [ imt ] . append ( TAU_EXECUTION [ self . tau_model ] ( imt , mag , tau_mean ) ) t_std [ imt ] . append ( TAU_EXECUTION [ self . tau_model ] ( imt , mag , tau_std ) ) return t_bar , t_std | 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 . sqrt ( phi_ss_mean ** 2. + PHI_S2SS_MODEL [ self . phi_s2ss_model ] [ imt ] [ "mean" ] ** 2. ) phi_ss_std = np . sqrt ( phi_ss_std ** 2. + PHI_S2SS_MODEL [ self . phi_s2ss_model ] [ imt ] [ "var" ] ** 2. ) p_bar [ imt ] . append ( phi_ss_mean ) p_std [ imt ] . append ( phi_ss_std ) return p_bar , p_std | 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 ] u_m = self . magnitude_limits [ i + 1 ] if mag > l_m and mag <= u_m : return ITPL ( mag , C [ self . tau_keys [ i + 1 ] ] , C [ self . tau_keys [ i ] ] , l_m , u_m - l_m ) | 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.