idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
233,000 | def split ( src , chunksize = MINWEIGHT ) : for i , block in enumerate ( block_splitter ( src . iter_ruptures ( ) , chunksize , key = operator . attrgetter ( 'mag' ) ) ) : rup = block [ 0 ] source_id = '%s:%d' % ( src . source_id , i ) amfd = mfd . ArbitraryMFD ( [ rup . mag ] , [ rup . mag_occ_rate ] ) rcs = RuptureCo... | Split a complex fault source in chunks |
233,001 | def get_bounding_box ( self , maxdist ) : locations = [ rup . hypocenter for rup in self . ruptures ] return get_bounding_box ( locations , maxdist ) | Bounding box containing all the hypocenters enlarged by the maximum distance |
233,002 | def show_attrs ( key , calc_id = - 1 ) : ds = util . read ( calc_id ) try : attrs = h5py . File . __getitem__ ( ds . hdf5 , key ) . attrs except KeyError : print ( '%r is not in %s' % ( key , ds ) ) else : if len ( attrs ) == 0 : print ( '%s has no attributes' % key ) for name , value in attrs . items ( ) : print ( nam... | Show the attributes of a HDF5 dataset in the datastore . |
233,003 | def compare_mean_curves ( calc_ref , calc , nsigma = 3 ) : dstore_ref = datastore . read ( calc_ref ) dstore = datastore . read ( calc ) imtls = dstore_ref [ 'oqparam' ] . imtls if dstore [ 'oqparam' ] . imtls != imtls : raise RuntimeError ( 'The IMTs and levels are different between ' 'calculation %d and %d' % ( calc_... | Compare the hazard curves coming from two different calculations . |
233,004 | def _get_stddevs ( self , sites , rup , C , stddev_types , ln_y_ref , exp1 , exp2 ) : ret = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : ret . append ( 0.65 * np . ones_like ( sites . vs30 ) ) return ret | Returns the standard deviation which is fixed at 0 . 65 for every site |
233,005 | def build_imls ( ff , continuous_fragility_discretization , steps_per_interval = 0 ) : if ff . format == 'discrete' : imls = ff . imls if ff . nodamage and ff . nodamage < imls [ 0 ] : imls = [ ff . nodamage ] + imls if steps_per_interval > 1 : gen_imls = fine_graining ( imls , steps_per_interval ) else : gen_imls = im... | Build intensity measure levels from a fragility function . If the function is continuous they are produced simply as a linear space between minIML and maxIML . If the function is discrete they are generated with a complex logic depending on the noDamageLimit and the parameter steps per interval . |
233,006 | def insured_loss_curve ( curve , deductible , insured_limit ) : losses , poes = curve [ : , curve [ 0 ] <= insured_limit ] limit_poe = interpolate . interp1d ( * curve , bounds_error = False , fill_value = 1 ) ( deductible ) return numpy . array ( [ losses , numpy . piecewise ( poes , [ poes > limit_poe ] , [ limit_poe... | Compute an insured loss ratio curve given a loss ratio curve |
233,007 | def bcr ( eal_original , eal_retrofitted , interest_rate , asset_life_expectancy , asset_value , retrofitting_cost ) : return ( ( eal_original - eal_retrofitted ) * asset_value * ( 1 - numpy . exp ( - interest_rate * asset_life_expectancy ) ) / ( interest_rate * retrofitting_cost ) ) | Compute the Benefit - Cost Ratio . |
233,008 | def pairwise_mean ( values ) : "Averages between a value and the next value in a sequence" return numpy . array ( [ numpy . mean ( pair ) for pair in pairwise ( values ) ] ) | Averages between a value and the next value in a sequence |
233,009 | def pairwise_diff ( values ) : "Differences between a value and the next value in a sequence" return numpy . array ( [ x - y for x , y in pairwise ( values ) ] ) | Differences between a value and the next value in a sequence |
233,010 | def mean_std ( fractions ) : n = fractions . shape [ 0 ] if n == 1 : return fractions [ 0 ] , numpy . ones_like ( fractions [ 0 ] ) * numpy . nan return numpy . mean ( fractions , axis = 0 ) , numpy . std ( fractions , axis = 0 , ddof = 1 ) | Given an N x M matrix returns mean and std computed on the rows i . e . two M - dimensional vectors . |
233,011 | def broadcast ( func , composite_array , * args ) : dic = { } dtypes = [ ] for name in composite_array . dtype . names : dic [ name ] = func ( composite_array [ name ] , * args ) dtypes . append ( ( name , dic [ name ] . dtype ) ) res = numpy . zeros ( dic [ name ] . shape , numpy . dtype ( dtypes ) ) for name in dic :... | Broadcast an array function over a composite array |
233,012 | def average_loss ( lc ) : losses , poes = ( lc [ 'loss' ] , lc [ 'poe' ] ) if lc . dtype . names else lc return - pairwise_diff ( losses ) @ pairwise_mean ( poes ) | Given a loss curve array with poe and loss fields computes the average loss on a period of time . |
233,013 | def normalize_curves_eb ( curves ) : non_zero_curves = [ ( losses , poes ) for losses , poes in curves if losses [ - 1 ] > 0 ] if not non_zero_curves : return curves [ 0 ] [ 0 ] , numpy . array ( [ poes for _losses , poes in curves ] ) else : max_losses = [ losses [ - 1 ] for losses , _poes in non_zero_curves ] referen... | A more sophisticated version of normalize_curves used in the event based calculator . |
233,014 | def sample ( self , means , covs , idxs , epsilons = None ) : if epsilons is None : return means self . set_distribution ( epsilons ) res = self . distribution . sample ( means , covs , means * covs , idxs ) return res | Sample the epsilons and apply the corrections to the means . This method is called only if there are nonzero covs . |
233,015 | def mean_loss_ratios_with_steps ( self , steps ) : loss_ratios = self . mean_loss_ratios if min ( loss_ratios ) > 0.0 : loss_ratios = numpy . concatenate ( [ [ 0.0 ] , loss_ratios ] ) if max ( loss_ratios ) < 1.0 : loss_ratios = numpy . concatenate ( [ loss_ratios , [ 1.0 ] ] ) return fine_graining ( loss_ratios , step... | Split the mean loss ratios producing a new set of loss ratios . The new set of loss ratios always includes 0 . 0 and 1 . 0 |
233,016 | def sample ( self , probs , _covs , idxs , epsilons ) : self . set_distribution ( epsilons ) return self . distribution . sample ( self . loss_ratios , probs ) | Sample the . loss_ratios with the given probabilities . |
233,017 | def build ( self , continuous_fragility_discretization , steps_per_interval ) : newfm = copy . copy ( self ) for key , ffl in self . items ( ) : newfm [ key ] = ffl . build ( self . limitStates , continuous_fragility_discretization , steps_per_interval ) return newfm | Return a new FragilityModel instance in which the values have been replaced with FragilityFunctionList instances . |
233,018 | def compute_gmfs ( rupgetter , srcfilter , param , monitor ) : getter = GmfGetter ( rupgetter , srcfilter , param [ 'oqparam' ] ) with monitor ( 'getting ruptures' ) : getter . init ( ) return getter . compute_gmfs_curves ( monitor ) | Compute GMFs and optionally hazard curves |
233,019 | def _get_minmax_edges ( self , edge ) : if isinstance ( edge , Line ) : depth_vals = np . array ( [ node . depth for node in edge . points ] ) else : depth_vals = edge [ : , 2 ] temp_upper_depth = np . min ( depth_vals ) if not self . upper_depth : self . upper_depth = temp_upper_depth else : if temp_upper_depth < self... | Updates the upper and lower depths based on the input edges |
233,020 | def _get_magnitude_term ( self , C , mag ) : if mag >= self . CONSTS [ "Mh" ] : return C [ "e1" ] + C [ "b3" ] * ( mag - self . CONSTS [ "Mh" ] ) else : return C [ "e1" ] + ( C [ "b1" ] * ( mag - self . CONSTS [ "Mh" ] ) ) + ( C [ "b2" ] * ( mag - self . CONSTS [ "Mh" ] ) ** 2. ) | Returns the magnitude scaling term - equation 3 |
233,021 | def _get_distance_term ( self , C , rjb , mag ) : c_3 = self . _get_anelastic_coeff ( C ) rval = np . sqrt ( rjb ** 2. + C [ "h" ] ** 2. ) return ( C [ "c1" ] + C [ "c2" ] * ( mag - self . CONSTS [ "Mref" ] ) ) * np . log ( rval / self . CONSTS [ "Rref" ] ) + c_3 * ( rval - self . CONSTS [ "Rref" ] ) | Returns the general distance scaling term - equation 2 |
233,022 | def _get_site_term ( self , C , vs30 ) : dg1 , dg2 = self . _get_regional_site_term ( C ) return ( C [ "g1" ] + dg1 ) + ( C [ "g2" ] + dg2 ) * np . log ( vs30 ) | Returns only a linear site amplification term |
233,023 | def _get_stddevs ( self , C , stddev_types , num_sites ) : assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types ) stddevs = [ np . zeros ( num_sites ) + C [ 'SigmaTot' ] for _ in stddev_types ] return stddevs | Return standard deviations as defined in tables below |
233,024 | def _compute_mean ( self , C , mag , rrup , hypo_depth , delta_R , delta_S , delta_V , delta_I , vs30 ) : mean = ( C [ 'A1' ] + ( C [ 'A2' ] + C [ 'A2R' ] * delta_R + C [ 'A2V' ] * delta_V ) * mag + ( C [ 'A3' ] + C [ 'A3S' ] * delta_S + C [ 'A3V' ] * delta_V ) * np . log10 ( np . power ( ( rrup ** 3 + C [ 'd' ] ** 3 )... | Compute MMI Intensity Value as per Equation in Table 5 and Table 7 pag 198 . |
233,025 | def _get_stddevs ( self , C , stddev_types , num_sites ) : sigma_inter = C [ 'tau' ] + np . zeros ( num_sites ) sigma_intra = C [ 'sigma' ] + np . zeros ( num_sites ) std = [ ] for stddev_type in stddev_types : if stddev_type == const . StdDev . TOTAL : std += [ np . sqrt ( sigma_intra ** 2 + sigma_inter ** 2 ) ] elif ... | Return total standard deviation as described in paragraph 5 . 2 pag 200 . |
233,026 | def plot_assets ( calc_id = - 1 , site_model = False ) : import matplotlib . pyplot as p from openquake . hmtk . plotting . patch import PolygonPatch dstore = util . read ( calc_id ) try : region = dstore [ 'oqparam' ] . region except KeyError : region = None sitecol = dstore [ 'sitecol' ] try : assetcol = dstore [ 'as... | Plot the sites and the assets |
233,027 | def _get_adjustment ( mag , year , mmin , completeness_year , t_f , mag_inc = 0.1 ) : if len ( completeness_year ) == 1 : if ( mag >= mmin ) and ( year >= completeness_year [ 0 ] ) : return 1.0 else : return False kval = int ( ( ( mag - mmin ) / mag_inc ) ) + 1 if ( kval >= 1 ) and ( year >= completeness_year [ kval - ... | If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor |
233,028 | def get_catalogue_bounding_polygon ( catalogue ) : upper_lon = np . max ( catalogue . data [ 'longitude' ] ) upper_lat = np . max ( catalogue . data [ 'latitude' ] ) lower_lon = np . min ( catalogue . data [ 'longitude' ] ) lower_lat = np . min ( catalogue . data [ 'latitude' ] ) return Polygon ( [ Point ( lower_lon , ... | Returns a polygon containing the bounding box of the catalogue |
233,029 | def make_from_catalogue ( cls , catalogue , spacing , dilate ) : new = cls ( ) cat_bbox = get_catalogue_bounding_polygon ( catalogue ) if dilate > 0 : cat_bbox = cat_bbox . dilate ( dilate ) new . update ( { 'xmin' : np . min ( cat_bbox . lons ) , 'xmax' : np . max ( cat_bbox . lons ) , 'xspc' : spacing , 'ymin' : np .... | Defines the grid on the basis of the catalogue |
233,030 | def write_to_csv ( self , filename ) : fid = open ( filename , 'wt' ) header_info = [ 'Longitude' , 'Latitude' , 'Depth' , 'Observed Count' , 'Smoothed Rate' , 'b-value' ] writer = csv . DictWriter ( fid , fieldnames = header_info ) headers = dict ( ( name0 , name0 ) for name0 in header_info ) writer . writerow ( heade... | Exports to simple csv |
233,031 | def _validate_hazard_metadata ( md ) : if ( md . get ( 'statistics' ) is not None and ( md . get ( 'smlt_path' ) is not None or md . get ( 'gsimlt_path' ) is not None ) ) : raise ValueError ( 'Cannot specify both `statistics` and logic tree ' 'paths' ) if md . get ( 'statistics' ) is not None : if md . get ( 'statistic... | Validate metadata dict of attributes which are more or less the same for hazard curves hazard maps and disaggregation histograms . |
233,032 | def _set_metadata ( element , metadata , attr_map , transform = str ) : for kw , attr in attr_map . items ( ) : value = metadata . get ( kw ) if value is not None : element . set ( attr , transform ( value ) ) | Set metadata attributes on a given element . |
233,033 | def serialize ( self , data ) : with open ( self . dest , 'wb' ) as fh : root = et . Element ( 'nrml' ) self . add_hazard_curves ( root , self . metadata , data ) nrml . write ( list ( root ) , fh ) | Write a sequence of hazard curves to the specified file . |
233,034 | def add_hazard_curves ( self , root , metadata , data ) : hazard_curves = et . SubElement ( root , 'hazardCurves' ) _set_metadata ( hazard_curves , metadata , _ATTR_MAP ) imls_elem = et . SubElement ( hazard_curves , 'IMLs' ) imls_elem . text = ' ' . join ( map ( scientificformat , metadata [ 'imls' ] ) ) gml_ns = nrml... | Add hazard curves stored into data as child of the root element with metadata . See the documentation of the method serialize and the constructor for a description of data and metadata respectively . |
233,035 | def serialize ( self , data , fmt = '%10.7E' ) : gmf_set_nodes = [ ] for gmf_set in data : gmf_set_node = Node ( 'gmfSet' ) if gmf_set . investigation_time : gmf_set_node [ 'investigationTime' ] = str ( gmf_set . investigation_time ) gmf_set_node [ 'stochasticEventSetId' ] = str ( gmf_set . stochastic_event_set_id ) gm... | Serialize a collection of ground motion fields to XML . |
233,036 | def serialize ( self , data , investigation_time ) : with open ( self . dest , 'wb' ) as fh : root = et . Element ( 'nrml' ) ses_container = et . SubElement ( root , 'ruptureCollection' ) ses_container . set ( 'investigationTime' , str ( investigation_time ) ) for grp_id in sorted ( data ) : attrs = dict ( id = grp_id ... | Serialize a collection of stochastic event sets to XML . |
233,037 | def serialize ( self , data ) : with open ( self . dest , 'wb' ) as fh : root = et . Element ( 'nrml' ) hazard_map = et . SubElement ( root , 'hazardMap' ) _set_metadata ( hazard_map , self . metadata , _ATTR_MAP ) for lon , lat , iml in data : node = et . SubElement ( hazard_map , 'node' ) node . set ( 'lon' , str ( l... | Serialize hazard map data to XML . |
233,038 | def serialize ( self , data ) : gml_ns = nrml . SERIALIZE_NS_MAP [ 'gml' ] with open ( self . dest , 'wb' ) as fh : root = et . Element ( 'nrml' ) uh_spectra = et . SubElement ( root , 'uniformHazardSpectra' ) _set_metadata ( uh_spectra , self . metadata , _ATTR_MAP ) periods_elem = et . SubElement ( uh_spectra , 'peri... | Write a sequence of uniform hazard spectra to the specified file . |
233,039 | def check_config ( config , data ) : essential_keys = [ 'input_mmin' , 'b-value' , 'sigma-b' ] for key in essential_keys : if not key in config . keys ( ) : raise ValueError ( 'For KijkoSellevolBayes the key %s needs to ' 'be set in the configuation' % key ) if 'tolerance' not in config . keys ( ) or not config [ 'tole... | Check config file inputs |
233,040 | def _compute_mean ( self , C , mag , rjb ) : ffc = self . _compute_finite_fault_correction ( mag ) d = np . sqrt ( rjb ** 2 + ( C [ 'c7' ] ** 2 ) * ( ffc ** 2 ) ) mean = ( C [ 'c1' ] + C [ 'c2' ] * ( mag - 6. ) + C [ 'c3' ] * ( ( mag - 6. ) ** 2 ) - C [ 'c4' ] * np . log ( d ) - C [ 'c6' ] * d ) factor = np . log ( rjb... | Compute ground motion mean value . |
233,041 | def _compute_finite_fault_correction ( self , mag ) : mw_j96 = mblg_to_mw_johnston_96 ( mag ) mw_ab87 = mblg_to_mw_atkinson_boore_87 ( mag ) t1 = np . exp ( - 1.25 + 0.227 * mw_j96 ) t2 = np . exp ( - 1.25 + 0.227 * mw_ab87 ) return np . sqrt ( t1 * t2 ) | Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations . |
233,042 | def get_vulnerability_functions_04 ( fname ) : categories = dict ( assetCategory = set ( ) , lossCategory = set ( ) , vulnerabilitySetID = set ( ) ) imts = set ( ) taxonomies = set ( ) vf_dict = { } for vset in nrml . read ( fname ) . vulnerabilityModel : categories [ 'assetCategory' ] . add ( vset [ 'assetCategory' ] ... | Parse the vulnerability model in NRML 0 . 4 format . |
233,043 | def upgrade_file ( path , multipoint ) : node0 = nrml . read ( path , chatty = False ) [ 0 ] shutil . copy ( path , path + '.bak' ) tag = striptag ( node0 . tag ) gml = True if tag == 'vulnerabilityModel' : vf_dict , cat_dict = get_vulnerability_functions_04 ( path ) node0 = Node ( 'vulnerabilityModel' , cat_dict , nod... | Upgrade to the latest NRML version |
233,044 | def _compute_term_3 ( self , C , rrup , mag ) : return ( C [ 'a3' ] * np . log10 ( rrup + C [ 'a4' ] * np . power ( 10 , C [ 'a5' ] * mag ) ) ) | This computes the third term in equation 2 page 2 . |
233,045 | def mag_scale_rel_to_hazardlib ( mag_scale_rel , use_default = False ) : if isinstance ( mag_scale_rel , BaseMSR ) : return mag_scale_rel elif isinstance ( mag_scale_rel , str ) : if not mag_scale_rel in SCALE_RELS . keys ( ) : raise ValueError ( 'Magnitude scaling relation %s not supported!' % mag_scale_rel ) else : r... | Returns the magnitude scaling relation in a format readable by openquake . hazardlib |
233,046 | def npd_to_pmf ( nodal_plane_dist , use_default = False ) : if isinstance ( nodal_plane_dist , PMF ) : return nodal_plane_dist else : if use_default : return PMF ( [ ( 1.0 , NodalPlane ( 0.0 , 90.0 , 0.0 ) ) ] ) else : raise ValueError ( 'Nodal Plane distribution not defined' ) | Returns the nodal plane distribution as an instance of the PMF class |
233,047 | def run_job ( job_ini , log_level = 'info' , log_file = None , exports = '' , username = getpass . getuser ( ) , ** kw ) : job_id = logs . init ( 'job' , getattr ( logging , log_level . upper ( ) ) ) with logs . handle ( job_id , log_level , log_file ) : job_ini = os . path . abspath ( job_ini ) oqparam = eng . job_fro... | Run a job using the specified config file and other options . |
233,048 | def run_tile ( job_ini , sites_slice ) : return run_job ( job_ini , sites_slice = ( sites_slice . start , sites_slice . stop ) ) | Used in tiling calculations |
233,049 | def del_calculation ( job_id , confirmed = False ) : if logs . dbcmd ( 'get_job' , job_id ) is None : print ( 'There is no job %d' % job_id ) return if confirmed or confirm ( 'Are you sure you want to (abort and) delete this calculation and ' 'all associated outputs?\nThis action cannot be undone. (y/n): ' ) : try : ab... | Delete a calculation and all associated outputs . |
233,050 | def smart_run ( job_ini , oqparam , log_level , log_file , exports , reuse_hazard ) : haz_checksum = readinput . get_checksum32 ( oqparam , hazard = True ) job = logs . dbcmd ( 'get_job_from_checksum' , haz_checksum ) reuse = reuse_hazard and job and os . path . exists ( job . ds_calc_dir + '.hdf5' ) ebr = ( oqparam . ... | Run calculations by storing their hazard checksum and reusing previous calculations if requested . |
233,051 | def _get_stddevs ( self , C , sites , pga1100 , sigma_pga , stddev_types ) : std_intra = self . _compute_intra_event_std ( C , sites . vs30 , pga1100 , sigma_pga ) std_inter = C [ 't_lny' ] * np . ones_like ( sites . vs30 ) stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDAR... | Returns the standard deviations as described in the ALEATORY UNCERTAINTY MODEL section of the paper . Equations 13 to 19 pages 147 to 151 |
233,052 | def _compute_intra_event_std ( self , C , vs30 , pga1100 , sigma_pga ) : sig_lnyb = np . sqrt ( C [ 's_lny' ] ** 2. - C [ 's_lnAF' ] ** 2. ) sig_lnab = np . sqrt ( sigma_pga ** 2. - C [ 's_lnAF' ] ** 2. ) alpha = self . _compute_intra_event_alpha ( C , vs30 , pga1100 ) return np . sqrt ( ( sig_lnyb ** 2. ) + ( C [ 's_l... | Returns the intra - event standard deviation at the site as defined in equation 15 page 147 |
233,053 | def _compute_intra_event_alpha ( self , C , vs30 , pga1100 ) : alpha = np . zeros_like ( vs30 , dtype = float ) idx = vs30 < C [ 'k1' ] if np . any ( idx ) : temp1 = ( pga1100 [ idx ] + C [ 'c' ] * ( vs30 [ idx ] / C [ 'k1' ] ) ** C [ 'n' ] ) ** - 1. temp1 = temp1 - ( ( pga1100 [ idx ] + C [ 'c' ] ) ** - 1. ) alpha [ i... | Returns the linearised functional relationship between fsite and pga1100 determined from the partial derivative defined on equation 17 on page 148 |
233,054 | def _get_total_sigma ( self , C , std_intra , std_inter ) : return np . sqrt ( std_intra ** 2. + std_inter ** 2. + C [ 'c_lny' ] ** 2. ) | Returns the total sigma term for the arbitrary horizontal component of ground motion defined by equation 18 page 150 |
233,055 | def generate_event_set ( ucerf , background_sids , src_filter , ses_idx , seed ) : serial = seed + ses_idx * TWO16 with h5py . File ( ucerf . source_file , 'r' ) as hdf5 : occurrences = ucerf . tom . sample_number_of_occurrences ( ucerf . rate , seed ) indices , = numpy . where ( occurrences ) logging . debug ( 'Consid... | Generates the event set corresponding to a particular branch |
233,056 | def sample_background_model ( hdf5 , branch_key , tom , seed , filter_idx , min_mag , npd , hdd , upper_seismogenic_depth , lower_seismogenic_depth , msr = WC1994 ( ) , aspect = 1.5 , trt = DEFAULT_TRT ) : bg_magnitudes = hdf5 [ "/" . join ( [ "Grid" , branch_key , "Magnitude" ] ) ] . value mag_idx = bg_magnitudes >= m... | Generates a rupture set from a sample of the background model |
233,057 | def get_median_area ( self , mag , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : return 10.0 ** ( - 3.49 + 0.91 * mag ) elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : return 10.0 ** ( - 3.42 + 0.90 * mag ) elif rake > 0 : return 10.0 ** ( - 3.99 + 0.98 * mag ) else : retu... | The values are a function of both magnitude and rake . |
233,058 | def get_std_dev_area ( self , mag , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : return 0.24 elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : return 0.22 elif rake > 0 : return 0.26 else : return 0.22 | Standard deviation for WC1994 . Magnitude is ignored . |
233,059 | def get_std_dev_mag ( self , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : return 0.24 elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : return 0.23 elif rake > 0 : return 0.25 else : return 0.25 | Standard deviation on the magnitude for the WC1994 area relation . |
233,060 | def set_parameters ( self ) : for key in dir ( self ) : if key . startswith ( 'REQUIRES_' ) : setattr ( self , key , getattr ( self . gmpe , key ) ) if key . startswith ( 'DEFINED_' ) : if not key . endswith ( 'FOR_INTENSITY_MEASURE_TYPES' ) : setattr ( self , key , getattr ( self . gmpe , key ) ) | Combines the parameters of the GMPE provided at the construction level with the ones assigned to the average GMPE . |
233,061 | def from_points_list ( cls , points ) : lons = numpy . zeros ( len ( points ) , dtype = float ) lats = lons . copy ( ) depths = lons . copy ( ) for i in range ( len ( points ) ) : lons [ i ] = points [ i ] . longitude lats [ i ] = points [ i ] . latitude depths [ i ] = points [ i ] . depth if not depths . any ( ) : dep... | Create a mesh object from a collection of points . |
233,062 | def get_min_distance ( self , mesh ) : return cdist ( self . xyz , mesh . xyz ) . min ( axis = 0 ) | Compute and return the minimum distance from the mesh to each point in another mesh . |
233,063 | def get_closest_points ( self , mesh ) : min_idx = cdist ( self . xyz , mesh . xyz ) . argmin ( axis = 0 ) if hasattr ( mesh , 'shape' ) : min_idx = min_idx . reshape ( mesh . shape ) lons = self . lons . take ( min_idx ) lats = self . lats . take ( min_idx ) deps = self . depths . take ( min_idx ) return Mesh ( lons ,... | Find closest point of this mesh for each point in the other mesh |
233,064 | def get_distance_matrix ( self ) : assert self . lons . ndim == 1 distances = geodetic . geodetic_distance ( self . lons . reshape ( self . lons . shape + ( 1 , ) ) , self . lats . reshape ( self . lats . shape + ( 1 , ) ) , self . lons , self . lats ) return numpy . matrix ( distances , copy = False ) | Compute and return distances between each pairs of points in the mesh . |
233,065 | def _get_proj_convex_hull ( self ) : proj = geo_utils . OrthographicProjection ( * geo_utils . get_spherical_bounding_box ( self . lons , self . lats ) ) coords = numpy . transpose ( proj ( self . lons . flat , self . lats . flat ) ) . copy ( ) multipoint = shapely . geometry . MultiPoint ( coords ) return proj , multi... | Create a projection centered in the center of this mesh and define a convex polygon in that projection enveloping all the points of the mesh . |
233,066 | def get_joyner_boore_distance ( self , mesh ) : distances = geodetic . min_geodetic_distance ( ( self . lons , self . lats ) , ( mesh . lons , mesh . lats ) ) idxs = ( distances < 40 ) . nonzero ( ) [ 0 ] if not len ( idxs ) : return distances proj , polygon = self . _get_proj_enclosing_polygon ( ) if not isinstance ( ... | Compute and return Joyner - Boore distance to each point of mesh . Point s depth is ignored . |
233,067 | def get_convex_hull ( self ) : proj , polygon2d = self . _get_proj_convex_hull ( ) if isinstance ( polygon2d , ( shapely . geometry . LineString , shapely . geometry . Point ) ) : polygon2d = polygon2d . buffer ( self . DIST_TOLERANCE , 1 ) from openquake . hazardlib . geo . polygon import Polygon return Polygon . _fro... | Get a convex polygon object that contains projections of all the points of the mesh . |
233,068 | def from_points_list ( cls , points ) : assert points is not None and len ( points ) > 0 and len ( points [ 0 ] ) > 0 , 'list of at least one non-empty list of points is required' lons = numpy . zeros ( ( len ( points ) , len ( points [ 0 ] ) ) , dtype = float ) lats = lons . copy ( ) depths = lons . copy ( ) num_cols ... | Create a rectangular mesh object from a list of lists of points . Lists in a list are supposed to have the same length . |
233,069 | def get_middle_point ( self ) : num_rows , num_cols = self . lons . shape mid_row = num_rows // 2 depth = 0 if num_rows & 1 == 1 : mid_col = num_cols // 2 if num_cols & 1 == 1 : depth = self . depths [ mid_row , mid_col ] return Point ( self . lons [ mid_row , mid_col ] , self . lats [ mid_row , mid_col ] , depth ) els... | Return the middle point of the mesh . |
233,070 | def get_cell_dimensions ( self ) : points , along_azimuth , updip , diag = self . triangulate ( ) top = along_azimuth [ : - 1 ] left = updip [ : , : - 1 ] tl_area = geo_utils . triangle_area ( top , left , diag ) top_length = numpy . sqrt ( numpy . sum ( top * top , axis = - 1 ) ) left_length = numpy . sqrt ( numpy . s... | Calculate centroid width length and area of each mesh cell . |
233,071 | def triangulate ( self ) : points = geo_utils . spherical_to_cartesian ( self . lons , self . lats , self . depths ) along_azimuth = points [ : , 1 : ] - points [ : , : - 1 ] updip = points [ : - 1 ] - points [ 1 : ] diag = points [ : - 1 , 1 : ] - points [ 1 : , : - 1 ] return points , along_azimuth , updip , diag | Convert mesh points to vectors in Cartesian space . |
233,072 | def smooth_data ( self , data , config , is_3d = False ) : max_dist = config [ 'Length_Limit' ] * config [ 'BandWidth' ] smoothed_value = np . zeros ( len ( data ) , dtype = float ) for iloc in range ( 0 , len ( data ) ) : dist_val = haversine ( data [ : , 0 ] , data [ : , 1 ] , data [ iloc , 0 ] , data [ iloc , 1 ] ) ... | Applies the smoothing kernel to the data |
233,073 | def purge_one ( calc_id , user ) : filename = os . path . join ( datadir , 'calc_%s.hdf5' % calc_id ) err = dbcmd ( 'del_calc' , calc_id , user ) if err : print ( err ) elif os . path . exists ( filename ) : os . remove ( filename ) print ( 'Removed %s' % filename ) | Remove one calculation ID from the database and remove its datastore |
233,074 | def purge_all ( user = None , fast = False ) : user = user or getpass . getuser ( ) if os . path . exists ( datadir ) : if fast : shutil . rmtree ( datadir ) print ( 'Removed %s' % datadir ) else : for fname in os . listdir ( datadir ) : mo = re . match ( 'calc_(\d+)\.hdf5' , fname ) if mo is not None : calc_id = int (... | Remove all calculations of the given user |
233,075 | def purge ( calc_id ) : if calc_id < 0 : try : calc_id = datastore . get_calc_ids ( datadir ) [ calc_id ] except IndexError : print ( 'Calculation %d not found' % calc_id ) return purge_one ( calc_id , getpass . getuser ( ) ) | Remove the given calculation . If you want to remove all calculations use oq reset . |
233,076 | def PolygonPatch ( polygon , ** kwargs ) : def coding ( ob ) : n = len ( getattr ( ob , 'coords' , None ) or ob ) vals = ones ( n , dtype = Path . code_type ) * Path . LINETO vals [ 0 ] = Path . MOVETO return vals if hasattr ( polygon , 'geom_type' ) : ptype = polygon . geom_type if ptype == 'Polygon' : polygon = [ Pol... | Constructs a matplotlib patch from a geometric object |
233,077 | def retreive_sigma_mu_data ( self ) : fle = h5py . File ( os . path . join ( BASE_PATH , "KothaEtAl2019_SigmaMu_Fixed.hdf5" ) , "r" ) self . mags = fle [ "M" ] [ : ] self . dists = fle [ "R" ] [ : ] self . periods = fle [ "T" ] [ : ] self . pga = fle [ "PGA" ] [ : ] self . pgv = fle [ "PGV" ] [ : ] self . s_a = fle [ "... | For the general form of the GMPE this retrieves the sigma mu values from the hdf5 file using the general model i . e . sigma mu factors that are independent of the choice of region or depth |
233,078 | def get_magnitude_scaling ( self , C , mag ) : d_m = mag - self . CONSTANTS [ "Mh" ] if mag < self . CONSTANTS [ "Mh" ] : return C [ "e1" ] + C [ "b1" ] * d_m + C [ "b2" ] * ( d_m ** 2.0 ) else : return C [ "e1" ] + C [ "b3" ] * d_m | Returns the magnitude scaling term |
233,079 | def get_distance_term ( self , C , rup , rjb , imt ) : h = self . _get_h ( C , rup . hypo_depth ) rval = np . sqrt ( rjb ** 2. + h ** 2. ) c3 = self . get_distance_coefficients ( C , imt ) f_r = ( C [ "c1" ] + C [ "c2" ] * ( rup . mag - self . CONSTANTS [ "Mref" ] ) ) * np . log ( rval / self . CONSTANTS [ "Rref" ] ) +... | Returns the distance attenuation factor |
233,080 | def get_distance_coefficients ( self , C , imt ) : c3 = self . c3 [ imt ] [ "c3" ] if self . c3 else C [ "c3" ] return c3 | Returns the c3 term |
233,081 | def get_sigma_mu_adjustment ( self , C , imt , rup , dists ) : if imt . name in "PGA PGV" : sigma_mu = getattr ( self , imt . name . lower ( ) ) if rup . mag <= self . mags [ 0 ] : sigma_mu_m = sigma_mu [ 0 , : ] elif rup . mag >= self . mags [ - 1 ] : sigma_mu_m = sigma_mu [ - 1 , : ] else : intpl1 = interp1d ( self .... | Returns the sigma mu adjustment factor |
233,082 | def get_site_amplification ( self , C , sites ) : ampl = np . zeros ( sites . vs30 . shape ) ampl [ sites . vs30measured ] = ( C [ "d0_obs" ] + C [ "d1_obs" ] * np . log ( sites . vs30 [ sites . vs30measured ] ) ) idx = np . logical_not ( sites . vs30measured ) ampl [ idx ] = ( C [ "d0_inf" ] + C [ "d1_inf" ] * np . lo... | Returns the linear site amplification term depending on whether the Vs30 is observed of inferred |
233,083 | def get_stddevs ( self , C , stddev_shape , stddev_types , sites ) : stddevs = [ ] tau = C [ "tau_event" ] sigma_s = np . zeros ( sites . vs30measured . shape , dtype = float ) sigma_s [ sites . vs30measured ] += C [ "sigma_s_obs" ] sigma_s [ np . logical_not ( sites . vs30measured ) ] += C [ "sigma_s_inf" ] phi = np .... | Returns the standard deviations with different site standard deviation for inferred vs . observed vs30 sites . |
233,084 | def geodetic_distance ( lons1 , lats1 , lons2 , lats2 , diameter = 2 * EARTH_RADIUS ) : lons1 , lats1 , lons2 , lats2 = _prepare_coords ( lons1 , lats1 , lons2 , lats2 ) distance = numpy . arcsin ( numpy . sqrt ( numpy . sin ( ( lats1 - lats2 ) / 2.0 ) ** 2.0 + numpy . cos ( lats1 ) * numpy . cos ( lats2 ) * numpy . si... | Calculate the geodetic distance between two points or two collections of points . |
233,085 | def azimuth ( lons1 , lats1 , lons2 , lats2 ) : lons1 , lats1 , lons2 , lats2 = _prepare_coords ( lons1 , lats1 , lons2 , lats2 ) cos_lat2 = numpy . cos ( lats2 ) true_course = numpy . degrees ( numpy . arctan2 ( numpy . sin ( lons1 - lons2 ) * cos_lat2 , numpy . cos ( lats1 ) * numpy . sin ( lats2 ) - numpy . sin ( la... | Calculate the azimuth between two points or two collections of points . |
233,086 | def min_distance_to_segment ( seglons , seglats , lons , lats ) : assert len ( seglons ) == len ( seglats ) == 2 seg_azim = azimuth ( seglons [ 0 ] , seglats [ 0 ] , seglons [ 1 ] , seglats [ 1 ] ) azimuth1 = azimuth ( seglons [ 0 ] , seglats [ 0 ] , lons , lats ) azimuth2 = azimuth ( seglons [ 1 ] , seglats [ 1 ] , lo... | This function computes the shortest distance to a segment in a 2D reference system . |
233,087 | def min_geodetic_distance ( a , b ) : if isinstance ( a , tuple ) : a = spherical_to_cartesian ( a [ 0 ] . flatten ( ) , a [ 1 ] . flatten ( ) ) if isinstance ( b , tuple ) : b = spherical_to_cartesian ( b [ 0 ] . flatten ( ) , b [ 1 ] . flatten ( ) ) return cdist ( a , b ) . min ( axis = 0 ) | Compute the minimum distance between first mesh and each point of the second mesh when both are defined on the earth surface . |
233,088 | def intervals_between ( lon1 , lat1 , depth1 , lon2 , lat2 , depth2 , length ) : assert length > 0 hdist = geodetic_distance ( lon1 , lat1 , lon2 , lat2 ) vdist = depth2 - depth1 total_distance = round ( numpy . sqrt ( hdist ** 2 + vdist ** 2 ) , 7 ) num_intervals = int ( round ( total_distance / length ) ) if num_inte... | Find a list of points between two given ones that lie on the same great circle arc and are equally spaced by length km . |
233,089 | def npoints_between ( lon1 , lat1 , depth1 , lon2 , lat2 , depth2 , npoints ) : hdist = geodetic_distance ( lon1 , lat1 , lon2 , lat2 ) vdist = depth2 - depth1 rlons , rlats , rdepths = npoints_towards ( lon1 , lat1 , depth1 , azimuth ( lon1 , lat1 , lon2 , lat2 ) , hdist , vdist , npoints ) rlons [ - 1 ] = lon2 rlats ... | Find a list of specified number of points between two given ones that are equally spaced along the great circle arc connecting given points . |
233,090 | def npoints_towards ( lon , lat , depth , azimuth , hdist , vdist , npoints ) : assert npoints > 1 rlon , rlat = numpy . radians ( lon ) , numpy . radians ( lat ) tc = numpy . radians ( 360 - azimuth ) hdists = numpy . arange ( npoints , dtype = float ) hdists *= ( hdist / EARTH_RADIUS ) / ( npoints - 1 ) vdists = nump... | Find a list of specified number of points starting from a given one along a great circle arc with a given azimuth measured in a given point . |
233,091 | def _prepare_coords ( lons1 , lats1 , lons2 , lats2 ) : lons1 = numpy . radians ( lons1 ) lats1 = numpy . radians ( lats1 ) assert lons1 . shape == lats1 . shape lons2 = numpy . radians ( lons2 ) lats2 = numpy . radians ( lats2 ) assert lons2 . shape == lats2 . shape return lons1 , lats1 , lons2 , lats2 | Convert two pairs of spherical coordinates in decimal degrees to numpy arrays of radians . Makes sure that respective coordinates in pairs have the same shape . |
233,092 | def select_catalogue ( self , selector , distance , distance_metric = 'joyner-boore' , upper_eq_depth = None , lower_eq_depth = None ) : if selector . catalogue . get_number_events ( ) < 1 : raise ValueError ( 'No events found in catalogue!' ) if ( 'rupture' in distance_metric ) and ( fabs ( self . dip - 90 ) > 1E-5 ) ... | Selects earthquakes within a distance of the fault |
233,093 | def plot_recurrence_models ( configs , area , slip , msr , rake , shear_modulus = 30.0 , disp_length_ratio = 1.25E-5 , msr_sigma = 0. , figure_size = ( 8 , 6 ) , filename = None , filetype = 'png' , dpi = 300 , ax = None ) : if ax is None : fig , ax = plt . subplots ( figsize = figure_size ) else : fig = ax . get_figur... | Plots a set of recurrence models |
233,094 | def build_area_source_geometry ( area_source ) : geom = [ ] for lon_lat in zip ( area_source . polygon . lons , area_source . polygon . lats ) : geom . extend ( lon_lat ) poslist_node = Node ( "gml:posList" , text = geom ) linear_ring_node = Node ( "gml:LinearRing" , nodes = [ poslist_node ] ) exterior_node = Node ( "g... | Returns the area source geometry as a Node |
233,095 | def build_point_source_geometry ( point_source ) : xy = point_source . location . x , point_source . location . y pos_node = Node ( "gml:pos" , text = xy ) point_node = Node ( "gml:Point" , nodes = [ pos_node ] ) upper_depth_node = Node ( "upperSeismoDepth" , text = point_source . upper_seismogenic_depth ) lower_depth_... | Returns the poing source geometry as a Node |
233,096 | def build_linestring_node ( line , with_depth = False ) : geom = [ ] for p in line . points : if with_depth : geom . extend ( ( p . x , p . y , p . z ) ) else : geom . extend ( ( p . x , p . y ) ) poslist_node = Node ( "gml:posList" , text = geom ) return Node ( "gml:LineString" , nodes = [ poslist_node ] ) | Parses a line to a Node class |
233,097 | def build_simple_fault_geometry ( fault_source ) : linestring_node = build_linestring_node ( fault_source . fault_trace , with_depth = False ) dip_node = Node ( "dip" , text = fault_source . dip ) upper_depth_node = Node ( "upperSeismoDepth" , text = fault_source . upper_seismogenic_depth ) lower_depth_node = Node ( "l... | Returns the simple fault source geometry as a Node |
233,098 | def build_complex_fault_geometry ( fault_source ) : num_edges = len ( fault_source . edges ) edge_nodes = [ ] for iloc , edge in enumerate ( fault_source . edges ) : if iloc == 0 : node_name = "faultTopEdge" elif iloc == ( num_edges - 1 ) : node_name = "faultBottomEdge" else : node_name = "intermediateEdge" edge_nodes ... | Returns the complex fault source geometry as a Node |
233,099 | def build_evenly_discretised_mfd ( mfd ) : occur_rates = Node ( "occurRates" , text = mfd . occurrence_rates ) return Node ( "incrementalMFD" , { "binWidth" : mfd . bin_width , "minMag" : mfd . min_mag } , nodes = [ occur_rates ] ) | Returns the evenly discretized MFD as a Node |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.