idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
232,100 | def _compute_mean ( self , C , mag , rjb ) : # line 1686 in hazgridXnga2.f ffc = self . _compute_finite_fault_correction ( mag ) d = np . sqrt ( rjb ** 2 + ( C [ 'c7' ] ** 2 ) * ( ffc ** 2 ) ) # lines 1663, 1694-1696 in hazgridXnga2.f mean = ( C [ 'c1' ] + C [ 'c2' ] * ( mag - 6. ) + C [ 'c3' ] * ( ( mag - 6. ) ** 2 ) - C [ 'c4' ] * np . log ( d ) - C [ 'c6' ] * d ) factor = np . log ( rjb / 100. ) idx = factor > 0 mean [ idx ] -= ( C [ 'c5' ] - C [ 'c4' ] ) * factor [ idx ] return mean | Compute ground motion mean value . | 222 | 7 |
232,101 | 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 . | 122 | 30 |
232,102 | def get_vulnerability_functions_04 ( fname ) : categories = dict ( assetCategory = set ( ) , lossCategory = set ( ) , vulnerabilitySetID = set ( ) ) imts = set ( ) taxonomies = set ( ) vf_dict = { } # imt, taxonomy -> vulnerability function for vset in nrml . read ( fname ) . vulnerabilityModel : categories [ 'assetCategory' ] . add ( vset [ 'assetCategory' ] ) categories [ 'lossCategory' ] . add ( vset [ 'lossCategory' ] ) categories [ 'vulnerabilitySetID' ] . add ( vset [ 'vulnerabilitySetID' ] ) IML = vset . IML imt_str = IML [ 'IMT' ] imls = ~ IML imts . add ( imt_str ) for vfun in vset . getnodes ( 'discreteVulnerability' ) : taxonomy = vfun [ 'vulnerabilityFunctionID' ] if taxonomy in taxonomies : raise InvalidFile ( 'Duplicated vulnerabilityFunctionID: %s: %s, line %d' % ( taxonomy , fname , vfun . lineno ) ) taxonomies . add ( taxonomy ) with context ( fname , vfun ) : loss_ratios = ~ vfun . lossRatio coefficients = ~ vfun . coefficientsVariation if len ( loss_ratios ) != len ( imls ) : raise InvalidFile ( 'There are %d loss ratios, but %d imls: %s, line %d' % ( len ( loss_ratios ) , len ( imls ) , fname , vfun . lossRatio . lineno ) ) if len ( coefficients ) != len ( imls ) : raise InvalidFile ( 'There are %d coefficients, but %d imls: %s, line %d' % ( len ( coefficients ) , len ( imls ) , fname , vfun . coefficientsVariation . lineno ) ) with context ( fname , vfun ) : vf_dict [ imt_str , taxonomy ] = scientific . VulnerabilityFunction ( taxonomy , imt_str , imls , loss_ratios , coefficients , vfun [ 'probabilisticDistribution' ] ) categories [ 'id' ] = '_' . join ( sorted ( categories [ 'vulnerabilitySetID' ] ) ) del categories [ 'vulnerabilitySetID' ] return vf_dict , categories | Parse the vulnerability model in NRML 0 . 4 format . | 541 | 13 |
232,103 | def upgrade_file ( path , multipoint ) : node0 = nrml . read ( path , chatty = False ) [ 0 ] shutil . copy ( path , path + '.bak' ) # make a backup of the original file tag = striptag ( node0 . tag ) gml = True if tag == 'vulnerabilityModel' : vf_dict , cat_dict = get_vulnerability_functions_04 ( path ) # below I am converting into a NRML 0.5 vulnerabilityModel node0 = Node ( 'vulnerabilityModel' , cat_dict , nodes = [ obj_to_node ( val ) for val in vf_dict . values ( ) ] ) gml = False elif tag == 'fragilityModel' : node0 = read_nrml . convert_fragility_model_04 ( nrml . read ( path ) [ 0 ] , path ) gml = False elif tag == 'sourceModel' : node0 = nrml . read ( path ) [ 0 ] dic = groupby ( node0 . nodes , operator . itemgetter ( 'tectonicRegion' ) ) node0 . nodes = [ Node ( 'sourceGroup' , dict ( tectonicRegion = trt , name = "group %s" % i ) , nodes = srcs ) for i , ( trt , srcs ) in enumerate ( dic . items ( ) , 1 ) ] if multipoint : sourceconverter . update_source_model ( node0 , path + '.bak' ) with open ( path , 'wb' ) as f : nrml . write ( [ node0 ] , f , gml = gml ) | Upgrade to the latest NRML version | 368 | 7 |
232,104 | 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 . | 63 | 12 |
232,105 | 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 : return SCALE_RELS [ mag_scale_rel ] ( ) else : if use_default : # Returns the Wells and Coppersmith string return WC1994 ( ) else : raise ValueError ( 'Magnitude Scaling Relation Not Defined!' ) | Returns the magnitude scaling relation in a format readable by openquake . hazardlib | 155 | 16 |
232,106 | def npd_to_pmf ( nodal_plane_dist , use_default = False ) : if isinstance ( nodal_plane_dist , PMF ) : # Aready in PMF format - return 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 | 108 | 14 |
232,107 | 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_from_file ( job_ini , job_id , username , * * kw ) kw [ 'username' ] = username eng . run_calc ( job_id , oqparam , exports , * * kw ) for line in logs . dbcmd ( 'list_outputs' , job_id , False ) : safeprint ( line ) return job_id | Run a job using the specified config file and other options . | 193 | 12 |
232,108 | def run_tile ( job_ini , sites_slice ) : return run_job ( job_ini , sites_slice = ( sites_slice . start , sites_slice . stop ) ) | Used in tiling calculations | 41 | 5 |
232,109 | 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 : abort ( job_id ) resp = logs . dbcmd ( 'del_calc' , job_id , getpass . getuser ( ) ) except RuntimeError as err : safeprint ( err ) else : if 'success' in resp : print ( 'Removed %d' % job_id ) else : print ( resp [ 'error' ] ) | Delete a calculation and all associated outputs . | 173 | 8 |
232,110 | def smart_run ( job_ini , oqparam , log_level , log_file , exports , reuse_hazard ) : haz_checksum = readinput . get_checksum32 ( oqparam , hazard = True ) # retrieve an old calculation with the right checksum, if any job = logs . dbcmd ( 'get_job_from_checksum' , haz_checksum ) reuse = reuse_hazard and job and os . path . exists ( job . ds_calc_dir + '.hdf5' ) # recompute the hazard and store the checksum ebr = ( oqparam . calculation_mode == 'event_based_risk' and 'gmfs' not in oqparam . inputs ) if ebr : kw = dict ( calculation_mode = 'event_based' ) if ( oqparam . sites or 'sites' in oqparam . inputs or 'site_model' in oqparam . inputs ) : # remove exposure from the hazard kw [ 'exposure_file' ] = '' else : kw = { } if not reuse : hc_id = run_job ( job_ini , log_level , log_file , exports , * * kw ) if job is None : logs . dbcmd ( 'add_checksum' , hc_id , haz_checksum ) elif not reuse_hazard or not os . path . exists ( job . ds_calc_dir + '.hdf5' ) : logs . dbcmd ( 'update_job_checksum' , hc_id , haz_checksum ) if ebr : run_job ( job_ini , log_level , log_file , exports , hazard_calculation_id = hc_id ) else : hc_id = job . id logging . info ( 'Reusing job #%d' , job . id ) run_job ( job_ini , log_level , log_file , exports , hazard_calculation_id = hc_id ) | Run calculations by storing their hazard checksum and reusing previous calculations if requested . | 441 | 16 |
232,111 | 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_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : stddevs . append ( self . _get_total_sigma ( C , std_intra , std_inter ) ) elif stddev_type == const . StdDev . INTRA_EVENT : stddevs . append ( std_intra ) elif stddev_type == const . StdDev . INTER_EVENT : stddevs . append ( std_inter ) return stddevs | Returns the standard deviations as described in the ALEATORY UNCERTAINTY MODEL section of the paper . Equations 13 to 19 pages 147 to 151 | 249 | 31 |
232,112 | def _compute_intra_event_std ( self , C , vs30 , pga1100 , sigma_pga ) : # Get intra-event standard deviation at the base of the site profile sig_lnyb = np . sqrt ( C [ 's_lny' ] ** 2. - C [ 's_lnAF' ] ** 2. ) sig_lnab = np . sqrt ( sigma_pga ** 2. - C [ 's_lnAF' ] ** 2. ) # Get linearised relationship between f_site and ln PGA alpha = self . _compute_intra_event_alpha ( C , vs30 , pga1100 ) return np . sqrt ( ( sig_lnyb ** 2. ) + ( C [ 's_lnAF' ] ** 2. ) + ( ( alpha ** 2. ) * ( sig_lnab ** 2. ) ) + ( 2.0 * alpha * C [ 'rho' ] * sig_lnyb * sig_lnab ) ) | Returns the intra - event standard deviation at the site as defined in equation 15 page 147 | 229 | 17 |
232,113 | 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 [ idx ] = C [ 'k2' ] * pga1100 [ idx ] * temp1 return alpha | Returns the linearised functional relationship between fsite and pga1100 determined from the partial derivative defined on equation 17 on page 148 | 164 | 25 |
232,114 | 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 | 57 | 20 |
232,115 | def generate_event_set ( ucerf , background_sids , src_filter , ses_idx , seed ) : serial = seed + ses_idx * TWO16 # get rates from file 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 ( 'Considering "%s", %d ruptures' , ucerf . source_id , len ( indices ) ) # get ruptures from the indices ruptures = [ ] rupture_occ = [ ] for iloc , n_occ in zip ( indices , occurrences [ indices ] ) : ucerf_rup = ucerf . get_ucerf_rupture ( iloc , src_filter ) if ucerf_rup : ucerf_rup . serial = serial serial += 1 ruptures . append ( ucerf_rup ) rupture_occ . append ( n_occ ) # sample background sources background_ruptures , background_n_occ = sample_background_model ( hdf5 , ucerf . idx_set [ "grid_key" ] , ucerf . tom , seed , background_sids , ucerf . min_mag , ucerf . npd , ucerf . hdd , ucerf . usd , ucerf . lsd , ucerf . msr , ucerf . aspect , ucerf . tectonic_region_type ) for i , brup in enumerate ( background_ruptures ) : brup . serial = serial serial += 1 ruptures . append ( brup ) rupture_occ . extend ( background_n_occ ) assert len ( ruptures ) < TWO16 , len ( ruptures ) # < 2^16 ruptures per SES return ruptures , rupture_occ | Generates the event set corresponding to a particular branch | 426 | 10 |
232,116 | 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 # Select magnitudes above the minimum magnitudes mag_idx = bg_magnitudes >= min_mag mags = bg_magnitudes [ mag_idx ] rates = hdf5 [ "/" . join ( [ "Grid" , branch_key , "RateArray" ] ) ] [ filter_idx , : ] rates = rates [ : , mag_idx ] valid_locs = hdf5 [ "Grid/Locations" ] [ filter_idx , : ] # Sample remaining rates sampler = tom . sample_number_of_occurrences ( rates , seed ) background_ruptures = [ ] background_n_occ = [ ] for i , mag in enumerate ( mags ) : rate_idx = numpy . where ( sampler [ : , i ] ) [ 0 ] rate_cnt = sampler [ rate_idx , i ] occurrence = rates [ rate_idx , i ] locations = valid_locs [ rate_idx , : ] ruptures = generate_background_ruptures ( tom , locations , occurrence , mag , npd , hdd , upper_seismogenic_depth , lower_seismogenic_depth , msr , aspect , trt ) background_ruptures . extend ( ruptures ) background_n_occ . extend ( rate_cnt . tolist ( ) ) return background_ruptures , background_n_occ | Generates a rupture set from a sample of the background model | 415 | 12 |
232,117 | def get_median_area ( self , mag , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : # their "All" case return 10.0 ** ( - 3.49 + 0.91 * mag ) elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : # strike slip return 10.0 ** ( - 3.42 + 0.90 * mag ) elif rake > 0 : # thrust/reverse return 10.0 ** ( - 3.99 + 0.98 * mag ) else : # normal return 10.0 ** ( - 2.87 + 0.82 * mag ) | The values are a function of both magnitude and rake . | 146 | 11 |
232,118 | def get_std_dev_area ( self , mag , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : # their "All" case return 0.24 elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : # strike slip return 0.22 elif rake > 0 : # thrust/reverse return 0.26 else : # normal return 0.22 | Standard deviation for WC1994 . Magnitude is ignored . | 95 | 11 |
232,119 | def get_std_dev_mag ( self , rake ) : assert rake is None or - 180 <= rake <= 180 if rake is None : # their "All" case return 0.24 elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : # strike slip return 0.23 elif rake > 0 : # thrust/reverse return 0.25 else : # normal return 0.25 | Standard deviation on the magnitude for the WC1994 area relation . | 93 | 12 |
232,120 | 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 . | 111 | 23 |
232,121 | 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 ( ) : # all points have zero depth, no need to waste memory depths = None return cls ( lons , lats , depths ) | Create a mesh object from a collection of points . | 131 | 10 |
232,122 | 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 . | 33 | 17 |
232,123 | def get_closest_points ( self , mesh ) : min_idx = cdist ( self . xyz , mesh . xyz ) . argmin ( axis = 0 ) # lose shape 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 , lats , deps ) | Find closest point of this mesh for each point in the other mesh | 127 | 13 |
232,124 | 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 . | 97 | 14 |
232,125 | def _get_proj_convex_hull ( self ) : # create a projection centered in the center of points collection proj = geo_utils . OrthographicProjection ( * geo_utils . get_spherical_bounding_box ( self . lons , self . lats ) ) # project all the points and create a shapely multipoint object. # need to copy an array because otherwise shapely misinterprets it coords = numpy . transpose ( proj ( self . lons . flat , self . lats . flat ) ) . copy ( ) multipoint = shapely . geometry . MultiPoint ( coords ) # create a 2d polygon from a convex hull around that multipoint return proj , multipoint . convex_hull | 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 . | 168 | 29 |
232,126 | def get_joyner_boore_distance ( self , mesh ) : # we perform a hybrid calculation (geodetic mesh-to-mesh distance # and distance on the projection plane for close points). first, # we find the closest geodetic distance for each point of target # mesh to this one. in general that distance is greater than # the exact distance to enclosing polygon of this mesh and it # depends on mesh spacing. but the difference can be neglected # if calculated geodetic distance is over some threshold. # get the highest slice from the 3D mesh distances = geodetic . min_geodetic_distance ( ( self . lons , self . lats ) , ( mesh . lons , mesh . lats ) ) # here we find the points for which calculated mesh-to-mesh # distance is below a threshold. this threshold is arbitrary: # lower values increase the maximum possible error, higher # values reduce the efficiency of that filtering. the maximum # error is equal to the maximum difference between a distance # from site to two adjacent points of the mesh and distance # from site to the line connecting them. thus the error is # a function of distance threshold and mesh spacing. the error # is maximum when the site lies on a perpendicular to the line # connecting points of the mesh and that passes the middle # point between them. the error then can be calculated as # ``err = trsh - d = trsh - \sqrt(trsh^2 - (ms/2)^2)``, where # ``trsh`` and ``d`` are distance to mesh points (the one # we found on the previous step) and distance to the line # connecting them (the actual distance) and ``ms`` is mesh # spacing. the threshold of 40 km gives maximum error of 314 # meters for meshes with spacing of 10 km and 5.36 km for # meshes with spacing of 40 km. if mesh spacing is over # ``(trsh / \sqrt(2)) * 2`` then points lying in the middle # of mesh cells (that is inside the polygon) will be filtered # out by the threshold and have positive distance instead of 0. # so for threshold of 40 km mesh spacing should not be more # than 56 km (typical values are 5 to 10 km). idxs = ( distances < 40 ) . nonzero ( ) [ 0 ] # indices on the first dimension if not len ( idxs ) : # no point is close enough, return distances as they are return distances # for all the points that are closer than the threshold we need # to recalculate the distance and set it to zero, if point falls # inside the enclosing polygon of the mesh. for doing that we # project both this mesh and the points of the second mesh--selected # by distance threshold--to the same Cartesian space, define # minimum shapely polygon enclosing the mesh and calculate point # to polygon distance, which gives the most accurate value # of distance in km (and that value is zero for points inside # the polygon). proj , polygon = self . _get_proj_enclosing_polygon ( ) if not isinstance ( polygon , shapely . geometry . Polygon ) : # either line or point is our enclosing polygon. draw # a square with side of 10 m around in order to have # a proper polygon instead. polygon = polygon . buffer ( self . DIST_TOLERANCE , 1 ) mesh_xx , mesh_yy = proj ( mesh . lons [ idxs ] , mesh . lats [ idxs ] ) # replace geodetic distance values for points-closer-than-the-threshold # by more accurate point-to-polygon distance values. distances [ idxs ] = geo_utils . point_to_polygon_distance ( polygon , mesh_xx , mesh_yy ) return distances | Compute and return Joyner - Boore distance to each point of mesh . Point s depth is ignored . | 827 | 22 |
232,127 | def get_convex_hull ( self ) : proj , polygon2d = self . _get_proj_convex_hull ( ) # if mesh had only one point, the convex hull is a point. if there # were two, it is a line string. we need to return a convex polygon # object, so extend that area-less geometries by some arbitrarily # small distance. if isinstance ( polygon2d , ( shapely . geometry . LineString , shapely . geometry . Point ) ) : polygon2d = polygon2d . buffer ( self . DIST_TOLERANCE , 1 ) # avoid circular imports from openquake . hazardlib . geo . polygon import Polygon return Polygon . _from_2d ( polygon2d , proj ) | Get a convex polygon object that contains projections of all the points of the mesh . | 181 | 18 |
232,128 | 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 = len ( points [ 0 ] ) for i , row in enumerate ( points ) : assert len ( row ) == num_cols , 'lists of points are not of uniform length' for j , point in enumerate ( row ) : lons [ i , j ] = point . longitude lats [ i , j ] = point . latitude depths [ i , j ] = point . depth if not depths . any ( ) : depths = None return cls ( lons , lats , depths ) | Create a rectangular mesh object from a list of lists of points . Lists in a list are supposed to have the same length . | 208 | 25 |
232,129 | def get_middle_point ( self ) : num_rows , num_cols = self . lons . shape mid_row = num_rows // 2 depth = 0 if num_rows & 1 == 1 : # there are odd number of rows mid_col = num_cols // 2 if num_cols & 1 == 1 : # odd number of columns, we can easily take # the middle point depth = self . depths [ mid_row , mid_col ] return Point ( self . lons [ mid_row , mid_col ] , self . lats [ mid_row , mid_col ] , depth ) else : # even number of columns, need to take two middle # points on the middle row lon1 , lon2 = self . lons [ mid_row , mid_col - 1 : mid_col + 1 ] lat1 , lat2 = self . lats [ mid_row , mid_col - 1 : mid_col + 1 ] depth1 = self . depths [ mid_row , mid_col - 1 ] depth2 = self . depths [ mid_row , mid_col ] else : # there are even number of rows. take the row just above # and the one just below the middle and find middle point # of each submesh1 = self [ mid_row - 1 : mid_row ] submesh2 = self [ mid_row : mid_row + 1 ] p1 , p2 = submesh1 . get_middle_point ( ) , submesh2 . get_middle_point ( ) lon1 , lat1 , depth1 = p1 . longitude , p1 . latitude , p1 . depth lon2 , lat2 , depth2 = p2 . longitude , p2 . latitude , p2 . depth # we need to find the middle between two points depth = ( depth1 + depth2 ) / 2.0 lon , lat = geo_utils . get_middle_point ( lon1 , lat1 , lon2 , lat2 ) return Point ( lon , lat , depth ) | Return the middle point of the mesh . | 448 | 8 |
232,130 | 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 . sum ( left * left , axis = - 1 ) ) bottom = along_azimuth [ 1 : ] right = updip [ : , 1 : ] br_area = geo_utils . triangle_area ( bottom , right , diag ) bottom_length = numpy . sqrt ( numpy . sum ( bottom * bottom , axis = - 1 ) ) right_length = numpy . sqrt ( numpy . sum ( right * right , axis = - 1 ) ) cell_area = tl_area + br_area tl_center = ( points [ : - 1 , : - 1 ] + points [ : - 1 , 1 : ] + points [ 1 : , : - 1 ] ) / 3 br_center = ( points [ : - 1 , 1 : ] + points [ 1 : , : - 1 ] + points [ 1 : , 1 : ] ) / 3 cell_center = ( ( tl_center * tl_area . reshape ( tl_area . shape + ( 1 , ) ) + br_center * br_area . reshape ( br_area . shape + ( 1 , ) ) ) / cell_area . reshape ( cell_area . shape + ( 1 , ) ) ) cell_length = ( ( top_length * tl_area + bottom_length * br_area ) / cell_area ) cell_width = ( ( left_length * tl_area + right_length * br_area ) / cell_area ) return cell_center , cell_length , cell_width , cell_area | Calculate centroid width length and area of each mesh cell . | 449 | 14 |
232,131 | def triangulate ( self ) : points = geo_utils . spherical_to_cartesian ( self . lons , self . lats , self . depths ) # triangulate the mesh by defining vectors of triangles edges: # → 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 . | 128 | 11 |
232,132 | 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 ] ) if is_3d : dist_val = np . sqrt ( dist_val . flatten ( ) ** 2.0 + ( data [ : , 2 ] - data [ iloc , 2 ] ) ** 2.0 ) id0 = np . where ( dist_val <= max_dist ) [ 0 ] w_val = ( np . exp ( - ( dist_val [ id0 ] ** 2.0 ) / ( config [ 'BandWidth' ] ** 2. ) ) ) . flatten ( ) smoothed_value [ iloc ] = np . sum ( w_val * data [ id0 , 3 ] ) / np . sum ( w_val ) return smoothed_value , np . sum ( data [ : , - 1 ] ) , np . sum ( smoothed_value ) | Applies the smoothing kernel to the data | 283 | 9 |
232,133 | 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 ) : # not removed yet os . remove ( filename ) print ( 'Removed %s' % filename ) | Remove one calculation ID from the database and remove its datastore | 97 | 13 |
232,134 | 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 ( mo . group ( 1 ) ) purge_one ( calc_id , user ) | Remove all calculations of the given user | 130 | 7 |
232,135 | 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 . | 77 | 17 |
232,136 | def PolygonPatch ( polygon , * * kwargs ) : def coding ( ob ) : # The codes will be all "LINETO" commands, except for "MOVETO"s at the # beginning of each subpath 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' ) : # Shapely ptype = polygon . geom_type if ptype == 'Polygon' : polygon = [ Polygon ( polygon ) ] elif ptype == 'MultiPolygon' : polygon = [ Polygon ( p ) for p in polygon ] else : raise ValueError ( "A polygon or multi-polygon representation is required" ) else : # GeoJSON polygon = getattr ( polygon , '__geo_interface__' , polygon ) ptype = polygon [ "type" ] if ptype == 'Polygon' : polygon = [ Polygon ( polygon ) ] elif ptype == 'MultiPolygon' : polygon = [ Polygon ( p ) for p in polygon [ 'coordinates' ] ] else : raise ValueError ( "A polygon or multi-polygon representation is required" ) vertices = concatenate ( [ concatenate ( [ asarray ( t . exterior ) [ : , : 2 ] ] + [ asarray ( r ) [ : , : 2 ] for r in t . interiors ] ) for t in polygon ] ) codes = concatenate ( [ concatenate ( [ coding ( t . exterior ) ] + [ coding ( r ) for r in t . interiors ] ) for t in polygon ] ) return PathPatch ( Path ( vertices , codes ) , * * kwargs ) | Constructs a matplotlib patch from a geometric object | 423 | 11 |
232,137 | 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 [ "SA" ] [ : ] fle . close ( ) | 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 | 149 | 44 |
232,138 | 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 | 111 | 5 |
232,139 | 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" ] ) + c3 * ( rval - self . CONSTANTS [ "Rref" ] ) return f_r | Returns the distance attenuation factor | 165 | 6 |
232,140 | def get_distance_coefficients ( self , C , imt ) : c3 = self . c3 [ imt ] [ "c3" ] if self . c3 else C [ "c3" ] return c3 | Returns the c3 term | 49 | 5 |
232,141 | def get_sigma_mu_adjustment ( self , C , imt , rup , dists ) : if imt . name in "PGA PGV" : # PGA and PGV are 2D arrays of dimension [nmags, ndists] 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 . mags , sigma_mu , axis = 0 ) sigma_mu_m = intpl1 ( rup . mag ) # Linear interpolation with distance intpl2 = interp1d ( self . dists , sigma_mu_m , bounds_error = False , fill_value = ( sigma_mu_m [ 0 ] , sigma_mu_m [ - 1 ] ) ) return intpl2 ( dists . rjb ) # In the case of SA the array is of dimension [nmags, ndists, nperiods] # Get values for given magnitude if rup . mag <= self . mags [ 0 ] : sigma_mu_m = self . s_a [ 0 , : , : ] elif rup . mag >= self . mags [ - 1 ] : sigma_mu_m = self . s_a [ - 1 , : , : ] else : intpl1 = interp1d ( self . mags , self . s_a , axis = 0 ) sigma_mu_m = intpl1 ( rup . mag ) # Get values for period - N.B. ln T, linear sigma mu interpolation if imt . period <= self . periods [ 0 ] : sigma_mu_t = sigma_mu_m [ : , 0 ] elif imt . period >= self . periods [ - 1 ] : sigma_mu_t = sigma_mu_m [ : , - 1 ] else : intpl2 = interp1d ( np . log ( self . periods ) , sigma_mu_m , axis = 1 ) sigma_mu_t = intpl2 ( np . log ( imt . period ) ) intpl3 = interp1d ( self . dists , sigma_mu_t , bounds_error = False , fill_value = ( sigma_mu_t [ 0 ] , sigma_mu_t [ - 1 ] ) ) return intpl3 ( dists . rjb ) | Returns the sigma mu adjustment factor | 596 | 7 |
232,142 | def get_site_amplification ( self , C , sites ) : ampl = np . zeros ( sites . vs30 . shape ) # For observed vs30 sites ampl [ sites . vs30measured ] = ( C [ "d0_obs" ] + C [ "d1_obs" ] * np . log ( sites . vs30 [ sites . vs30measured ] ) ) # For inferred Vs30 sites idx = np . logical_not ( sites . vs30measured ) ampl [ idx ] = ( C [ "d0_inf" ] + C [ "d1_inf" ] * np . log ( sites . vs30 [ idx ] ) ) return ampl | Returns the linear site amplification term depending on whether the Vs30 is observed of inferred | 150 | 16 |
232,143 | 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 . sqrt ( C [ "phi0" ] ** 2.0 + sigma_s ** 2. ) 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 ( tau ** 2. + phi ** 2. ) + np . zeros ( stddev_shape ) ) elif stddev_type == const . StdDev . INTRA_EVENT : stddevs . append ( phi + np . zeros ( stddev_shape ) ) elif stddev_type == const . StdDev . INTER_EVENT : stddevs . append ( tau + np . zeros ( stddev_shape ) ) return stddevs | Returns the standard deviations with different site standard deviation for inferred vs . observed vs30 sites . | 332 | 18 |
232,144 | 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 . sin ( ( lons1 - lons2 ) / 2.0 ) ** 2.0 ) ) return diameter * distance | Calculate the geodetic distance between two points or two collections of points . | 162 | 17 |
232,145 | 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 ( lats1 ) * cos_lat2 * numpy . cos ( lons1 - lons2 ) ) ) return ( 360 - true_course ) % 360 | Calculate the azimuth between two points or two collections of points . | 171 | 16 |
232,146 | def min_distance_to_segment ( seglons , seglats , lons , lats ) : # Check the size of the seglons, seglats arrays assert len ( seglons ) == len ( seglats ) == 2 # Compute the azimuth of the segment seg_azim = azimuth ( seglons [ 0 ] , seglats [ 0 ] , seglons [ 1 ] , seglats [ 1 ] ) # Compute the azimuth of the direction obtained # connecting the first point defining the segment and each site azimuth1 = azimuth ( seglons [ 0 ] , seglats [ 0 ] , lons , lats ) # Compute the azimuth of the direction obtained # connecting the second point defining the segment and each site azimuth2 = azimuth ( seglons [ 1 ] , seglats [ 1 ] , lons , lats ) # Find the points inside the band defined by the two lines perpendicular # to the segment direction passing through the two vertexes of the segment. # For these points the closest distance is the distance from the great arc. idx_in = numpy . nonzero ( ( numpy . cos ( numpy . radians ( seg_azim - azimuth1 ) ) >= 0.0 ) & ( numpy . cos ( numpy . radians ( seg_azim - azimuth2 ) ) <= 0.0 ) ) # Find the points outside the band defined by the two line perpendicular # to the segment direction passing through the two vertexes of the segment. # For these points the closest distance is the minimum of the distance from # the two point vertexes. idx_out = numpy . nonzero ( ( numpy . cos ( numpy . radians ( seg_azim - azimuth1 ) ) < 0.0 ) | ( numpy . cos ( numpy . radians ( seg_azim - azimuth2 ) ) > 0.0 ) ) # Find the indexes of points 'on the left of the segment' idx_neg = numpy . nonzero ( numpy . sin ( numpy . radians ( ( azimuth1 - seg_azim ) ) ) < 0.0 ) # Now let's compute the distances for the two cases. dists = numpy . zeros_like ( lons ) if len ( idx_in [ 0 ] ) : dists [ idx_in ] = distance_to_arc ( seglons [ 0 ] , seglats [ 0 ] , seg_azim , lons [ idx_in ] , lats [ idx_in ] ) if len ( idx_out [ 0 ] ) : dists [ idx_out ] = min_geodetic_distance ( ( seglons , seglats ) , ( lons [ idx_out ] , lats [ idx_out ] ) ) # Finally we correct the sign of the distances in order to make sure that # the points on the right semispace defined using as a reference the # direction defined by the segment (i.e. the direction defined by going # from the first point to the second one) have a positive distance and # the others a negative one. dists = abs ( dists ) dists [ idx_neg ] = - dists [ idx_neg ] return dists | This function computes the shortest distance to a segment in a 2D reference system . | 741 | 17 |
232,147 | 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 . | 105 | 24 |
232,148 | def intervals_between ( lon1 , lat1 , depth1 , lon2 , lat2 , depth2 , length ) : assert length > 0 hdist = geodetic_distance ( lon1 , lat1 , lon2 , lat2 ) vdist = depth2 - depth1 # if this method is called multiple times with coordinates that are # separated by the same distance, because of floating point imprecisions # the total distance may have slightly different values (for instance if # the distance between two set of points is 65 km, total distance can be # 64.9999999999989910 and 65.0000000000020322). These two values bring to # two different values of num_intervals (32 in the first case and 33 in # the second), and this is a problem because for the same distance we # should have the same number of intervals. To reduce potential differences # due to floating point errors, we therefore round total_distance to a # fixed precision (7) total_distance = round ( numpy . sqrt ( hdist ** 2 + vdist ** 2 ) , 7 ) num_intervals = int ( round ( total_distance / length ) ) if num_intervals == 0 : return numpy . array ( [ lon1 ] ) , numpy . array ( [ lat1 ] ) , numpy . array ( [ depth1 ] ) dist_factor = ( length * num_intervals ) / total_distance return npoints_towards ( lon1 , lat1 , depth1 , azimuth ( lon1 , lat1 , lon2 , lat2 ) , hdist * dist_factor , vdist * dist_factor , num_intervals + 1 ) | Find a list of points between two given ones that lie on the same great circle arc and are equally spaced by length km . | 364 | 25 |
232,149 | 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 ) # the last point should be left intact rlons [ - 1 ] = lon2 rlats [ - 1 ] = lat2 rdepths [ - 1 ] = depth2 return rlons , rlats , rdepths | Find a list of specified number of points between two given ones that are equally spaced along the great circle arc connecting given points . | 169 | 25 |
232,150 | 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 = numpy . arange ( npoints , dtype = float ) vdists *= vdist / ( npoints - 1 ) sin_dists = numpy . sin ( hdists ) cos_dists = numpy . cos ( hdists ) sin_lat = numpy . sin ( rlat ) cos_lat = numpy . cos ( rlat ) sin_lats = sin_lat * cos_dists + cos_lat * sin_dists * numpy . cos ( tc ) lats = numpy . degrees ( numpy . arcsin ( sin_lats ) ) dlon = numpy . arctan2 ( numpy . sin ( tc ) * sin_dists * cos_lat , cos_dists - sin_lat * sin_lats ) lons = numpy . mod ( rlon - dlon + numpy . pi , 2 * numpy . pi ) - numpy . pi lons = numpy . degrees ( lons ) depths = vdists + depth # the first point should be left intact lons [ 0 ] = lon lats [ 0 ] = lat depths [ 0 ] = depth return lons , lats , depths | 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 . | 376 | 30 |
232,151 | 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 . | 121 | 30 |
232,152 | 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!' ) # rupture metric is selected and dip != 90 or 'rupture' if ( 'rupture' in distance_metric ) and ( fabs ( self . dip - 90 ) > 1E-5 ) : # Use rupture distance self . catalogue = selector . within_rupture_distance ( self . geometry , distance , upper_depth = upper_eq_depth , lower_depth = lower_eq_depth ) else : # Use Joyner-Boore distance self . catalogue = selector . within_joyner_boore_distance ( self . geometry , distance , upper_depth = upper_eq_depth , lower_depth = lower_eq_depth ) if self . catalogue . get_number_events ( ) < 5 : # Throw a warning regarding the small number of earthquakes in # the source! warnings . warn ( 'Source %s (%s) has fewer than 5 events' % ( self . id , self . name ) ) | Selects earthquakes within a distance of the fault | 266 | 9 |
232,153 | 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_figure ( ) for config in configs : model = RecurrenceBranch ( area , slip , msr , rake , shear_modulus , disp_length_ratio , msr_sigma , weight = 1.0 ) model . get_recurrence ( config ) occurrence = model . recurrence . occur_rates cumulative = np . array ( [ np . sum ( occurrence [ iloc : ] ) for iloc in range ( 0 , len ( occurrence ) ) ] ) if 'AndersonLuco' in config [ 'Model_Name' ] : flt_label = config [ 'Model_Name' ] + ' - ' + config [ 'Model_Type' ] + ' Type' else : flt_label = config [ 'Model_Name' ] flt_color = np . random . uniform ( 0.1 , 1.0 , 3 ) ax . semilogy ( model . magnitudes , cumulative , '-' , label = flt_label , color = flt_color , linewidth = 2. ) ax . semilogy ( model . magnitudes , model . recurrence . occur_rates , '--' , color = flt_color , linewidth = 2. ) ax . set_xlabel ( 'Magnitude' ) ax . set_ylabel ( 'Annual Rate' ) ax . legend ( bbox_to_anchor = ( 1.1 , 1.0 ) ) _save_image ( fig , filename , filetype , dpi ) | Plots a set of recurrence models | 434 | 8 |
232,154 | 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 ( "gml:exterior" , nodes = [ linear_ring_node ] ) polygon_node = Node ( "gml:Polygon" , nodes = [ exterior_node ] ) upper_depth_node = Node ( "upperSeismoDepth" , text = area_source . upper_seismogenic_depth ) lower_depth_node = Node ( "lowerSeismoDepth" , text = area_source . lower_seismogenic_depth ) return Node ( "areaGeometry" , { 'discretization' : area_source . area_discretization } , nodes = [ polygon_node , upper_depth_node , lower_depth_node ] ) | Returns the area source geometry as a Node | 258 | 8 |
232,155 | 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_node = Node ( "lowerSeismoDepth" , text = point_source . lower_seismogenic_depth ) return Node ( "pointGeometry" , nodes = [ point_node , upper_depth_node , lower_depth_node ] ) | Returns the poing source geometry as a Node | 159 | 9 |
232,156 | 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 | 111 | 9 |
232,157 | 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 ( "lowerSeismoDepth" , text = fault_source . lower_seismogenic_depth ) return Node ( "simpleFaultGeometry" , nodes = [ linestring_node , dip_node , upper_depth_node , lower_depth_node ] ) | Returns the simple fault source geometry as a Node | 158 | 9 |
232,158 | 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 : # Top Edge node_name = "faultTopEdge" elif iloc == ( num_edges - 1 ) : # Bottom edge node_name = "faultBottomEdge" else : # Intermediate edge node_name = "intermediateEdge" edge_nodes . append ( Node ( node_name , nodes = [ build_linestring_node ( edge , with_depth = True ) ] ) ) return Node ( "complexFaultGeometry" , nodes = edge_nodes ) | Returns the complex fault source geometry as a Node | 165 | 9 |
232,159 | 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 | 83 | 11 |
232,160 | def build_truncated_gr_mfd ( mfd ) : return Node ( "truncGutenbergRichterMFD" , { "aValue" : mfd . a_val , "bValue" : mfd . b_val , "minMag" : mfd . min_mag , "maxMag" : mfd . max_mag } ) | Parses the truncated Gutenberg Richter MFD as a Node | 80 | 14 |
232,161 | def build_arbitrary_mfd ( mfd ) : magnitudes = Node ( "magnitudes" , text = mfd . magnitudes ) occur_rates = Node ( "occurRates" , text = mfd . occurrence_rates ) return Node ( "arbitraryMFD" , nodes = [ magnitudes , occur_rates ] ) | Parses the arbitrary MFD as a Node | 77 | 10 |
232,162 | def build_youngs_coppersmith_mfd ( mfd ) : return Node ( "YoungsCoppersmithMFD" , { "minMag" : mfd . min_mag , "bValue" : mfd . b_val , "characteristicMag" : mfd . char_mag , "characteristicRate" : mfd . char_rate , "binWidth" : mfd . bin_width } ) | Parses the Youngs & Coppersmith MFD as a node . Note that the MFD does not hold the total moment rate but only the characteristic rate . Therefore the node is written to the characteristic rate version regardless of whether or not it was originally created from total moment rate | 94 | 57 |
232,163 | def build_multi_mfd ( mfd ) : node = Node ( "multiMFD" , dict ( kind = mfd . kind , size = mfd . size ) ) for name in sorted ( mfd . kwargs ) : values = mfd . kwargs [ name ] if name in ( 'magnitudes' , 'occurRates' ) : if len ( values [ 0 ] ) > 1 : # tested in multipoint_test.py values = list ( numpy . concatenate ( values ) ) else : values = sum ( values , [ ] ) node . append ( Node ( name , text = values ) ) if 'occurRates' in mfd . kwargs : lengths = [ len ( rates ) for rates in mfd . kwargs [ 'occurRates' ] ] node . append ( Node ( 'lengths' , text = lengths ) ) return node | Parses the MultiMFD as a Node | 197 | 10 |
232,164 | def build_nodal_plane_dist ( npd ) : npds = [ ] for prob , npd in npd . data : nodal_plane = Node ( "nodalPlane" , { "dip" : npd . dip , "probability" : prob , "strike" : npd . strike , "rake" : npd . rake } ) npds . append ( nodal_plane ) return Node ( "nodalPlaneDist" , nodes = npds ) | Returns the nodal plane distribution as a Node instance | 111 | 10 |
232,165 | def build_hypo_depth_dist ( hdd ) : hdds = [ ] for ( prob , depth ) in hdd . data : hdds . append ( Node ( "hypoDepth" , { "depth" : depth , "probability" : prob } ) ) return Node ( "hypoDepthDist" , nodes = hdds ) | Returns the hypocentral depth distribution as a Node instance | 76 | 11 |
232,166 | def get_distributed_seismicity_source_nodes ( source ) : source_nodes = [ ] # parse msr source_nodes . append ( Node ( "magScaleRel" , text = source . magnitude_scaling_relationship . __class__ . __name__ ) ) # Parse aspect ratio source_nodes . append ( Node ( "ruptAspectRatio" , text = source . rupture_aspect_ratio ) ) # Parse MFD source_nodes . append ( obj_to_node ( source . mfd ) ) # Parse nodal plane distribution source_nodes . append ( build_nodal_plane_dist ( source . nodal_plane_distribution ) ) # Parse hypocentral depth distribution source_nodes . append ( build_hypo_depth_dist ( source . hypocenter_distribution ) ) return source_nodes | Returns list of nodes of attributes common to all distributed seismicity source classes | 197 | 14 |
232,167 | def get_fault_source_nodes ( source ) : source_nodes = [ ] # parse msr source_nodes . append ( Node ( "magScaleRel" , text = source . magnitude_scaling_relationship . __class__ . __name__ ) ) # Parse aspect ratio source_nodes . append ( Node ( "ruptAspectRatio" , text = source . rupture_aspect_ratio ) ) # Parse MFD source_nodes . append ( obj_to_node ( source . mfd ) ) # Parse Rake source_nodes . append ( Node ( "rake" , text = source . rake ) ) if len ( getattr ( source , 'hypo_list' , [ ] ) ) : source_nodes . append ( build_hypo_list_node ( source . hypo_list ) ) if len ( getattr ( source , 'slip_list' , [ ] ) ) : source_nodes . append ( build_slip_list_node ( source . slip_list ) ) return source_nodes | Returns list of nodes of attributes common to all fault source classes | 237 | 12 |
232,168 | def get_source_attributes ( source ) : attrs = { "id" : source . source_id , "name" : source . name , "tectonicRegion" : source . tectonic_region_type } if isinstance ( source , NonParametricSeismicSource ) : if source . data [ 0 ] [ 0 ] . weight is not None : weights = [ ] for data in source . data : weights . append ( data [ 0 ] . weight ) attrs [ 'rup_weights' ] = numpy . array ( weights ) print ( attrs ) return attrs | Retreives a dictionary of source attributes from the source class | 128 | 12 |
232,169 | def build_area_source_node ( area_source ) : # parse geometry source_nodes = [ build_area_source_geometry ( area_source ) ] # parse common distributed attributes source_nodes . extend ( get_distributed_seismicity_source_nodes ( area_source ) ) return Node ( "areaSource" , get_source_attributes ( area_source ) , nodes = source_nodes ) | Parses an area source to a Node class | 95 | 10 |
232,170 | def build_simple_fault_source_node ( fault_source ) : # Parse geometry source_nodes = [ build_simple_fault_geometry ( fault_source ) ] # Parse common fault source attributes source_nodes . extend ( get_fault_source_nodes ( fault_source ) ) return Node ( "simpleFaultSource" , get_source_attributes ( fault_source ) , nodes = source_nodes ) | Parses a simple fault source to a Node class | 100 | 11 |
232,171 | def build_complex_fault_source_node ( fault_source ) : # Parse geometry source_nodes = [ build_complex_fault_geometry ( fault_source ) ] # Parse common fault source attributes source_nodes . extend ( get_fault_source_nodes ( fault_source ) ) return Node ( "complexFaultSource" , get_source_attributes ( fault_source ) , nodes = source_nodes ) | Parses a complex fault source to a Node class | 100 | 11 |
232,172 | def write_source_model ( dest , sources_or_groups , name = None , investigation_time = None ) : if isinstance ( sources_or_groups , nrml . SourceModel ) : with open ( dest , 'wb' ) as f : nrml . write ( [ obj_to_node ( sources_or_groups ) ] , f , '%s' ) return if isinstance ( sources_or_groups [ 0 ] , sourceconverter . SourceGroup ) : groups = sources_or_groups else : # passed a list of sources srcs_by_trt = groupby ( sources_or_groups , operator . attrgetter ( 'tectonic_region_type' ) ) groups = [ sourceconverter . SourceGroup ( trt , srcs_by_trt [ trt ] ) for trt in srcs_by_trt ] name = name or os . path . splitext ( os . path . basename ( dest ) ) [ 0 ] nodes = list ( map ( obj_to_node , sorted ( groups ) ) ) attrs = { "name" : name } if investigation_time is not None : attrs [ 'investigation_time' ] = investigation_time source_model = Node ( "sourceModel" , attrs , nodes = nodes ) with open ( dest , 'wb' ) as f : nrml . write ( [ source_model ] , f , '%s' ) return dest | Writes a source model to XML . | 321 | 8 |
232,173 | def _get_stddevs ( self , coeffs , stddev_types , num_sites ) : stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES stddevs . append ( coeffs [ 'sigma' ] + np . zeros ( num_sites ) ) return np . array ( stddevs ) | Return total sigma as reported in Table 2 p . 1202 . | 109 | 14 |
232,174 | def get_fault_type_dummy_variables ( self , rup ) : # normal faulting is_normal = np . array ( self . RAKE_THRESH < - rup . rake < ( 180. - self . RAKE_THRESH ) ) # reverse raulting is_reverse = np . array ( self . RAKE_THRESH < rup . rake < ( 180. - self . RAKE_THRESH ) ) if not self . ALREADY_WARNED and is_normal . any ( ) : # make sure that the warning is printed only once to avoid # flooding the terminal msg = ( 'Normal faulting not supported by %s; ' 'treating as strike-slip' % type ( self ) . __name__ ) warnings . warn ( msg , UserWarning ) self . ALREADY_WARNED = True is_strike_slip = ~ is_reverse | is_normal is_strike_slip = is_strike_slip . astype ( float ) return is_strike_slip | Fault - type classification dummy variable based on rup . rake . | 230 | 14 |
232,175 | def read_data ( self , scaling_factor = 1E-9 , strain_headers = None ) : if strain_headers : self . strain . data_variables = strain_headers else : self . strain . data_variables = STRAIN_VARIABLES datafile = open ( self . filename , 'r' ) reader = csv . DictReader ( datafile ) self . strain . data = dict ( [ ( name , [ ] ) for name in reader . fieldnames ] ) for row in reader : for name in row . keys ( ) : if 'region' in name . lower ( ) : self . strain . data [ name ] . append ( row [ name ] ) elif name in self . strain . data_variables : self . strain . data [ name ] . append ( scaling_factor * float ( row [ name ] ) ) else : self . strain . data [ name ] . append ( float ( row [ name ] ) ) for key in self . strain . data . keys ( ) : if 'region' in key : self . strain . data [ key ] = np . array ( self . strain . data [ key ] , dtype = 'S13' ) else : self . strain . data [ key ] = np . array ( self . strain . data [ key ] ) self . _check_invalid_longitudes ( ) if 'region' not in self . strain . data : print ( 'No tectonic regionalisation found in input file!' ) self . strain . data_variables = self . strain . data . keys ( ) # Update data with secondary data (i.e. 2nd invariant, e1h, e2h etc. self . strain . get_secondary_strain_data ( ) return self . strain | Reads the data from the csv file | 381 | 9 |
232,176 | def _check_invalid_longitudes ( self ) : idlon = self . strain . data [ 'longitude' ] > 180. if np . any ( idlon ) : self . strain . data [ 'longitude' ] [ idlon ] = self . strain . data [ 'longitude' ] [ idlon ] - 360. | Checks to ensure that all longitudes are in the range - 180 . to 180 | 73 | 17 |
232,177 | def write_file ( self , strain , scaling_factor = 1E-9 ) : if not isinstance ( strain , GeodeticStrain ) : raise ValueError ( 'Strain data must be instance of GeodeticStrain' ) for key in strain . data . keys ( ) : if key in strain . data_variables : # Return strain value back to original scaling if key in [ 'longitude' , 'latitude' ] : continue strain . data [ key ] = strain . data [ key ] / scaling_factor # Slice seismicity rates into separate dictionary vectors strain , output_variables = self . slice_rates_to_data ( strain ) outfile = open ( self . filename , 'wt' ) print ( 'Writing strain data to file %s' % self . filename ) writer = csv . DictWriter ( outfile , fieldnames = output_variables ) writer . writeheader ( ) for iloc in range ( 0 , strain . get_number_observations ( ) ) : row_dict = { } for key in output_variables : if len ( strain . data [ key ] ) > 0 : # Ignores empty dictionary attributes row_dict [ key ] = strain . data [ key ] [ iloc ] writer . writerow ( row_dict ) outfile . close ( ) print ( 'done!' ) | Main writer function for the csv file | 290 | 8 |
232,178 | def slice_rates_to_data ( self , strain ) : output_variables = list ( strain . data ) cond = ( isinstance ( strain . target_magnitudes , np . ndarray ) or isinstance ( strain . target_magnitudes , list ) ) if cond : magnitude_list = [ '%.3f' % mag for mag in strain . target_magnitudes ] else : return strain , output_variables # Ensure that the number of rows in the rate array corresponds to the # number of observations assert np . shape ( strain . seismicity_rate ) [ 0 ] == strain . get_number_observations ( ) for iloc , magnitude in enumerate ( magnitude_list ) : strain . data [ magnitude ] = strain . seismicity_rate [ : , iloc ] output_variables . extend ( magnitude_list ) return strain , output_variables | For the strain data checks to see if seismicity rates have been calculated . If so each column in the array is sliced and stored as a single vector in the strain . data dictionary with the corresponding magnitude as a key . | 191 | 44 |
232,179 | def read ( * paths , * * validators ) : paths = config . paths + list ( paths ) parser = configparser . ConfigParser ( ) found = parser . read ( os . path . normpath ( os . path . expanduser ( p ) ) for p in paths ) if not found : raise IOError ( 'No configuration file found in %s' % str ( paths ) ) config . found = found config . clear ( ) for section in parser . sections ( ) : config [ section ] = sec = DotDict ( parser . items ( section ) ) for k , v in sec . items ( ) : sec [ k ] = validators . get ( k , lambda x : x ) ( v ) | Load the configuration make each section available in a separate dict . | 150 | 12 |
232,180 | def boolean ( flag ) : s = flag . lower ( ) if s in ( '1' , 'yes' , 'true' ) : return True elif s in ( '0' , 'no' , 'false' ) : return False raise ValueError ( 'Unknown flag %r' % s ) | Convert string in boolean | 65 | 5 |
232,181 | def _get_mean ( self , vs30 , mag , rrup , imt , scale_fac ) : C_HR , C_BC , C_SR , SC = self . _extract_coeffs ( imt ) rrup = self . _clip_distances ( rrup ) f0 = self . _compute_f0_factor ( rrup ) f1 = self . _compute_f1_factor ( rrup ) f2 = self . _compute_f2_factor ( rrup ) pga_bc = self . _get_pga_bc ( f0 , f1 , f2 , SC , mag , rrup , vs30 , scale_fac ) # compute mean values for hard-rock sites (vs30 >= 2000), # and non-hard-rock sites (vs30 < 2000) and add soil amplification # term mean = np . zeros_like ( vs30 ) self . _compute_mean ( C_HR , f0 , f1 , f2 , SC , mag , rrup , vs30 >= 2000.0 , mean , scale_fac ) self . _compute_mean ( C_BC , f0 , f1 , f2 , SC , mag , rrup , vs30 < 2000.0 , mean , scale_fac ) self . _compute_soil_amplification ( C_SR , vs30 , pga_bc , mean ) # convert from base 10 to base e if imt == PGV ( ) : mean = np . log ( 10 ** mean ) else : # convert from cm/s**2 to g mean = np . log ( ( 10 ** mean ) * 1e-2 / g ) return mean | Compute and return mean | 370 | 5 |
232,182 | def _get_pga_bc ( self , f0 , f1 , f2 , SC , mag , rrup , vs30 , scale_fac ) : pga_bc = np . zeros_like ( vs30 ) self . _compute_mean ( self . COEFFS_BC [ PGA ( ) ] , f0 , f1 , f2 , SC , mag , rrup , vs30 < 2000.0 , pga_bc , scale_fac ) return ( 10 ** pga_bc ) * 1e-2 / g | Compute and return PGA on BC boundary | 120 | 9 |
232,183 | def _extract_coeffs ( self , imt ) : C_HR = self . COEFFS_HARD_ROCK [ imt ] C_BC = self . COEFFS_BC [ imt ] C_SR = self . COEFFS_SOIL_RESPONSE [ imt ] SC = self . COEFFS_STRESS [ imt ] return C_HR , C_BC , C_SR , SC | Extract dictionaries of coefficients specific to required intensity measure type . | 98 | 13 |
232,184 | def init ( self ) : if hasattr ( self , 'data' ) : # already initialized return if isinstance ( self . dstore , str ) : self . dstore = hdf5 . File ( self . dstore , 'r' ) else : self . dstore . open ( 'r' ) # if not if self . sids is None : self . sids = self . dstore [ 'sitecol' ] . sids oq = self . dstore [ 'oqparam' ] self . imtls = oq . imtls self . poes = self . poes or oq . poes self . data = { } try : hcurves = self . get_hcurves ( self . imtls ) # shape (R, N) except IndexError : # no data return for sid , hcurve_by_rlz in zip ( self . sids , hcurves . T ) : self . data [ sid ] = datadict = { } for rlzi , hcurve in enumerate ( hcurve_by_rlz ) : datadict [ rlzi ] = lst = [ None for imt in self . imtls ] for imti , imt in enumerate ( self . imtls ) : lst [ imti ] = hcurve [ imt ] | Read the poes and set the . data attribute with the hazard curves | 293 | 14 |
232,185 | def get_mean ( self , grp = None ) : self . init ( ) if len ( self . weights ) == 1 : # one realization # the standard deviation is zero pmap = self . get ( 0 , grp ) for sid , pcurve in pmap . items ( ) : array = numpy . zeros ( pcurve . array . shape [ : - 1 ] + ( 2 , ) ) array [ : , 0 ] = pcurve . array [ : , 0 ] pcurve . array = array return pmap else : # multiple realizations dic = ( { g : self . dstore [ 'poes/' + g ] for g in self . dstore [ 'poes' ] } if grp is None else { grp : self . dstore [ 'poes/' + grp ] } ) pmaps = self . rlzs_assoc . combine_pmaps ( dic ) return stats . compute_pmap_stats ( pmaps , [ stats . mean_curve , stats . std_curve ] , self . weights , self . imtls ) | Compute the mean curve as a ProbabilityMap | 242 | 10 |
232,186 | def init ( self ) : if hasattr ( self , 'computers' ) : # init already called return with hdf5 . File ( self . rupgetter . filename , 'r' ) as parent : self . weights = parent [ 'weights' ] . value self . computers = [ ] for ebr in self . rupgetter . get_ruptures ( self . srcfilter ) : sitecol = self . sitecol . filtered ( ebr . sids ) try : computer = calc . gmf . GmfComputer ( ebr , sitecol , self . oqparam . imtls , self . cmaker , self . oqparam . truncation_level , self . correl_model ) except FarAwayRupture : # due to numeric errors, ruptures within the maximum_distance # when written, can be outside when read; I found a case with # a distance of 99.9996936 km over a maximum distance of 100 km continue self . computers . append ( computer ) | Initialize the computers . Should be called on the workers | 217 | 11 |
232,187 | def _compute_forearc_backarc_term ( self , C , sites , dists , rup ) : # flag 1 (R < 335 & R >= 205) flag1 = np . zeros ( len ( dists . rhypo ) ) ind1 = np . logical_and ( ( dists . rhypo < 335 ) , ( dists . rhypo >= 205 ) ) flag1 [ ind1 ] = 1.0 # flag 2 (R >= 335) flag2 = np . zeros ( len ( dists . rhypo ) ) ind2 = ( dists . rhypo >= 335 ) flag2 [ ind2 ] = 1.0 # flag 3 (R < 240 & R >= 140) flag3 = np . zeros ( len ( dists . rhypo ) ) ind3 = np . logical_and ( ( dists . rhypo < 240 ) , ( dists . rhypo >= 140 ) ) flag3 [ ind3 ] = 1.0 # flag 4 (R >= 240) flag4 = np . zeros ( len ( dists . rhypo ) ) ind4 = ( dists . rhypo >= 240 ) flag4 [ ind4 ] = 1.0 A = flag1 * ( ( 205 - dists . rhypo ) / 150 ) + flag2 B = flag3 * ( ( 140 - dists . rhypo ) / 100 ) + flag4 if ( rup . hypo_depth < 80 ) : FHR = A else : FHR = B H0 = 100 # Heaviside function if ( rup . hypo_depth >= H0 ) : H = 1 else : H = 0 # ARC = 0 for back-arc - ARC = 1 for forearc ARC = np . zeros ( len ( sites . backarc ) ) idxarc = ( sites . backarc == 1 ) ARC [ idxarc ] = 1.0 return ( ( C [ 'c41' ] * ( 1 - ARC ) * H ) + ( C [ 'c42' ] * ( 1 - ARC ) * H * FHR ) + ( C [ 'c51' ] * ARC * H ) + ( C [ 'c52' ] * ARC * H * FHR ) ) | Compute back - arc term of Equation 3 | 488 | 10 |
232,188 | def _build_data ( self , amplification_group ) : # Determine shape of the tables n_levels = len ( amplification_group ) # Checks the first group in the amplification group and returns the # shape of the SA array - implicitly assumes the SA array in all # amplification groups is the same shape level = next ( iter ( amplification_group ) ) n_d , n_p , n_m = amplification_group [ level ] [ "IMLs/SA" ] . shape assert n_d == len ( self . distances ) , ( n_d , len ( self . distances ) ) assert n_m == len ( self . magnitudes ) , ( n_m , len ( self . magnitudes ) ) # Instantiate the arrays with ones self . mean = { "SA" : numpy . ones ( [ n_d , n_p , n_m , n_levels ] ) , "PGA" : numpy . ones ( [ n_d , 1 , n_m , n_levels ] ) , "PGV" : numpy . ones ( [ n_d , 1 , n_m , n_levels ] ) } self . sigma = { } for stddev_type in [ const . StdDev . TOTAL , const . StdDev . INTER_EVENT , const . StdDev . INTRA_EVENT ] : level = next ( iter ( amplification_group ) ) if stddev_type in amplification_group [ level ] : self . sigma [ stddev_type ] = deepcopy ( self . mean ) for iloc , ( level , amp_model ) in enumerate ( amplification_group . items ( ) ) : if "SA" in amp_model [ "IMLs" ] : if iloc == 0 : self . periods = amp_model [ "IMLs/T" ] [ : ] else : assert numpy . allclose ( self . periods , amp_model [ "IMLs/T" ] [ : ] ) for imt in [ "SA" , "PGA" , "PGV" ] : if imt in amp_model [ "IMLs" ] : self . mean [ imt ] [ : , : , : , self . argidx [ iloc ] ] = amp_model [ "IMLs/" + imt ] [ : ] for stddev_type in self . sigma : self . sigma [ stddev_type ] [ imt ] [ : , : , : , self . argidx [ iloc ] ] = amp_model [ "/" . join ( [ stddev_type , imt ] ) ] [ : ] self . shape = ( n_d , n_p , n_m , n_levels ) | Creates the numpy array tables from the hdf5 tables | 598 | 13 |
232,189 | def get_amplification_factors ( self , imt , sctx , rctx , dists , stddev_types ) : dist_level_table = self . get_mean_table ( imt , rctx ) sigma_tables = self . get_sigma_tables ( imt , rctx , stddev_types ) mean_interpolator = interp1d ( self . values , numpy . log10 ( dist_level_table ) , axis = 1 ) sigma_interpolators = [ interp1d ( self . values , sigma_table , axis = 1 ) for sigma_table in sigma_tables ] if self . element == "Rupture" : mean_amp = 10.0 ** mean_interpolator ( getattr ( rctx , self . parameter ) ) [ 0 ] * numpy . ones_like ( dists ) sigma_amps = [ ] for sig_interpolator in sigma_interpolators : sigma_amps . append ( sig_interpolator ( getattr ( rctx , self . parameter ) ) [ 0 ] * numpy . ones_like ( dists ) ) else : mean_amp = 10.0 ** mean_interpolator ( getattr ( sctx , self . parameter ) ) [ 0 , : ] sigma_amps = [ ] for sig_interpolator in sigma_interpolators : sigma_amps . append ( sig_interpolator ( getattr ( sctx , self . parameter ) ) [ 0 , : ] * numpy . ones_like ( dists ) ) return mean_amp , sigma_amps | Returns the amplification factors for the given rupture and site conditions . | 362 | 12 |
232,190 | def get_mean_table ( self , imt , rctx ) : # Levels by Distances if imt . name in 'PGA PGV' : interpolator = interp1d ( self . magnitudes , numpy . log10 ( self . mean [ imt . name ] ) , axis = 2 ) output_table = 10.0 ** ( interpolator ( rctx . mag ) . reshape ( self . shape [ 0 ] , self . shape [ 3 ] ) ) else : # For spectral accelerations - need two step process # Interpolate period - log-log space interpolator = interp1d ( numpy . log10 ( self . periods ) , numpy . log10 ( self . mean [ "SA" ] ) , axis = 1 ) period_table = interpolator ( numpy . log10 ( imt . period ) ) # Interpolate magnitude - linear-log space mag_interpolator = interp1d ( self . magnitudes , period_table , axis = 1 ) output_table = 10.0 ** mag_interpolator ( rctx . mag ) return output_table | Returns amplification factors for the mean given the rupture and intensity measure type . | 241 | 14 |
232,191 | def get_sigma_tables ( self , imt , rctx , stddev_types ) : output_tables = [ ] for stddev_type in stddev_types : # For PGA and PGV only needs to apply magnitude interpolation if imt . name in 'PGA PGV' : interpolator = interp1d ( self . magnitudes , self . sigma [ stddev_type ] [ imt . name ] , axis = 2 ) output_tables . append ( interpolator ( rctx . mag ) . reshape ( self . shape [ 0 ] , self . shape [ 3 ] ) ) else : # For spectral accelerations - need two step process # Interpolate period interpolator = interp1d ( numpy . log10 ( self . periods ) , self . sigma [ stddev_type ] [ "SA" ] , axis = 1 ) period_table = interpolator ( numpy . log10 ( imt . period ) ) mag_interpolator = interp1d ( self . magnitudes , period_table , axis = 1 ) output_tables . append ( mag_interpolator ( rctx . mag ) ) return output_tables | Returns modification factors for the standard deviations given the rupture and intensity measure type . | 264 | 15 |
232,192 | def init ( self , fle = None ) : if fle is None : fname = self . kwargs . get ( 'gmpe_table' , self . GMPE_TABLE ) if fname is None : raise ValueError ( 'You forgot to set GMPETable.GMPE_TABLE!' ) elif os . path . isabs ( fname ) : self . GMPE_TABLE = fname else : # NB: (hackish) GMPE_DIR must be set externally self . GMPE_TABLE = os . path . abspath ( os . path . join ( self . GMPE_DIR , fname ) ) fle = h5py . File ( self . GMPE_TABLE , "r" ) try : # this is the format inside the datastore self . distance_type = fle [ "distance_type" ] . value except KeyError : # this is the original format outside the datastore self . distance_type = decode ( fle [ "Distances" ] . attrs [ "metric" ] ) self . REQUIRES_DISTANCES = set ( [ self . distance_type ] ) # Load in magnitude self . m_w = fle [ "Mw" ] [ : ] # Load in distances self . distances = fle [ "Distances" ] [ : ] # Load intensity measure types and levels self . imls = hdf_arrays_to_dict ( fle [ "IMLs" ] ) self . DEFINED_FOR_INTENSITY_MEASURE_TYPES = set ( self . _supported_imts ( ) ) if "SA" in self . imls and "T" not in self . imls : raise ValueError ( "Spectral Acceleration must be accompanied by " "periods" ) # Get the standard deviations self . _setup_standard_deviations ( fle ) if "Amplification" in fle : self . _setup_amplification ( fle ) | Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory . | 422 | 26 |
232,193 | def _setup_amplification ( self , fle ) : self . amplification = AmplificationTable ( fle [ "Amplification" ] , self . m_w , self . distances ) if self . amplification . element == "Sites" : self . REQUIRES_SITES_PARAMETERS = set ( [ self . amplification . parameter ] ) elif self . amplification . element == "Rupture" : # set the site and rupture parameters on the instance self . REQUIRES_SITES_PARAMETERS = set ( ) self . REQUIRES_RUPTURE_PARAMETERS = ( self . REQUIRES_RUPTURE_PARAMETERS | { self . amplification . parameter } ) | If amplification data is specified then reads into memory and updates the required rupture and site parameters | 164 | 17 |
232,194 | def _supported_imts ( self ) : imt_list = [ ] for key in self . imls : if "SA" in key : imt_list . append ( imt_module . SA ) elif key == "T" : continue else : try : factory = getattr ( imt_module , key ) except Exception : continue imt_list . append ( factory ) return imt_list | Updates the list of supported IMTs from the tables | 89 | 11 |
232,195 | def get_mean_and_stddevs ( self , sctx , rctx , dctx , imt , stddev_types ) : # Return Distance Tables imls = self . _return_tables ( rctx . mag , imt , "IMLs" ) # Get distance vector for the given magnitude idx = numpy . searchsorted ( self . m_w , rctx . mag ) dists = self . distances [ : , 0 , idx - 1 ] # Get mean and standard deviations mean = self . _get_mean ( imls , dctx , dists ) stddevs = self . _get_stddevs ( dists , rctx . mag , dctx , imt , stddev_types ) if self . amplification : # Apply amplification mean_amp , sigma_amp = self . amplification . get_amplification_factors ( imt , sctx , rctx , getattr ( dctx , self . distance_type ) , stddev_types ) mean = numpy . log ( mean ) + numpy . log ( mean_amp ) for iloc in range ( len ( stddev_types ) ) : stddevs [ iloc ] *= sigma_amp [ iloc ] return mean , stddevs else : return numpy . log ( mean ) , stddevs | Returns the mean and standard deviations | 299 | 6 |
232,196 | def _get_stddevs ( self , dists , mag , dctx , imt , stddev_types ) : stddevs = [ ] for stddev_type in stddev_types : if stddev_type not in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES : raise ValueError ( "Standard Deviation type %s not supported" % stddev_type ) sigma = self . _return_tables ( mag , imt , stddev_type ) interpolator_std = interp1d ( dists , sigma , bounds_error = False ) stddev = interpolator_std ( getattr ( dctx , self . distance_type ) ) stddev [ getattr ( dctx , self . distance_type ) < dists [ 0 ] ] = sigma [ 0 ] stddev [ getattr ( dctx , self . distance_type ) > dists [ - 1 ] ] = sigma [ - 1 ] stddevs . append ( stddev ) return stddevs | Returns the total standard deviation of the intensity measure level from the tables . | 240 | 14 |
232,197 | def _return_tables ( self , mag , imt , val_type ) : if imt . name in 'PGA PGV' : # Get scalar imt if val_type == "IMLs" : iml_table = self . imls [ imt . name ] [ : ] else : iml_table = self . stddevs [ val_type ] [ imt . name ] [ : ] n_d , n_s , n_m = iml_table . shape iml_table = iml_table . reshape ( [ n_d , n_m ] ) else : if val_type == "IMLs" : periods = self . imls [ "T" ] [ : ] iml_table = self . imls [ "SA" ] [ : ] else : periods = self . stddevs [ val_type ] [ "T" ] [ : ] iml_table = self . stddevs [ val_type ] [ "SA" ] [ : ] low_period = round ( periods [ 0 ] , 7 ) high_period = round ( periods [ - 1 ] , 7 ) if ( round ( imt . period , 7 ) < low_period ) or ( round ( imt . period , 7 ) > high_period ) : raise ValueError ( "Spectral period %.3f outside of valid range " "(%.3f to %.3f)" % ( imt . period , periods [ 0 ] , periods [ - 1 ] ) ) # Apply log-log interpolation for spectral period interpolator = interp1d ( numpy . log10 ( periods ) , numpy . log10 ( iml_table ) , axis = 1 ) iml_table = 10. ** interpolator ( numpy . log10 ( imt . period ) ) return self . apply_magnitude_interpolation ( mag , iml_table ) | Returns the vector of ground motions or standard deviations corresponding to the specific magnitude and intensity measure type . | 418 | 19 |
232,198 | def apply_magnitude_interpolation ( self , mag , iml_table ) : # do not allow "mag" to exceed maximum table magnitude if mag > self . m_w [ - 1 ] : mag = self . m_w [ - 1 ] # Get magnitude values if mag < self . m_w [ 0 ] or mag > self . m_w [ - 1 ] : raise ValueError ( "Magnitude %.2f outside of supported range " "(%.2f to %.2f)" % ( mag , self . m_w [ 0 ] , self . m_w [ - 1 ] ) ) # It is assumed that log10 of the spectral acceleration scales # linearly (or approximately linearly) with magnitude m_interpolator = interp1d ( self . m_w , numpy . log10 ( iml_table ) , axis = 1 ) return 10.0 ** m_interpolator ( mag ) | Interpolates the tables to the required magnitude level | 204 | 10 |
232,199 | def _get_mean_deep_soil ( self , mag , rake , rrup , is_reverse , imt ) : if mag <= self . NEAR_FIELD_SATURATION_MAG : c4 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c4lowmag' ] c5 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c5lowmag' ] else : c4 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c4himag' ] c5 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c5himag' ] c2 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c2' ] c3 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c3' ] C = self . COEFFS_SOIL [ imt ] if is_reverse : c1 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c1r' ] c6 = C [ 'c6r' ] else : c1 = self . COEFFS_SOIL_IMT_INDEPENDENT [ 'c1ss' ] c6 = C [ 'c6ss' ] # clip mag if greater than 8.5. This is to avoid # ValueError: negative number cannot be raised to a fractional power mag = 8.5 if mag > 8.5 else mag return ( c1 + c2 * mag + c6 + C [ 'c7' ] * ( ( 8.5 - mag ) ** 2.5 ) - c3 * numpy . log ( rrup + c4 * numpy . exp ( c5 * mag ) ) ) | Calculate and return the mean intensity for deep soil sites . | 402 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.