idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
44,000
def _get_SRF_sigma ( self , imt_per ) : if imt_per < 0.6 : srf = 0.8 elif 0.6 <= imt_per < 1 : srf = self . _interp_function ( 0.7 , 0.8 , 1 , 0.6 , imt_per ) elif 1 <= imt_per <= 10 : srf = self . _interp_function ( 0.6 , 0.7 , 10 , 1 , imt_per ) else : srf = 1 return srf
Table 8 and equation 19 of 2013 report . NB change in notation 2013 report calls this term sigma_t but it is referred to here as sigma . Note that Table 8 is identical to Table 7 in the 2013 report .
44,001
def _get_dL2L ( self , imt_per ) : if imt_per < 0.18 : dL2L = - 0.06 elif 0.18 <= imt_per < 0.35 : dL2L = self . _interp_function ( 0.12 , - 0.06 , 0.35 , 0.18 , imt_per ) elif 0.35 <= imt_per <= 10 : dL2L = self . _interp_function ( 0.65 , 0.12 , 10 , 0.35 , imt_per ) else : dL2L = 0 return dL2L
Table 3 and equation 19 of 2013 report .
44,002
def _get_dS2S ( self , imt_per ) : if imt_per == 0 : dS2S = 0.05 elif 0 < imt_per < 0.15 : dS2S = self . _interp_function ( - 0.15 , 0.05 , 0.15 , 0 , imt_per ) elif 0.15 <= imt_per < 0.45 : dS2S = self . _interp_function ( 0.4 , - 0.15 , 0.45 , 0.15 , imt_per ) elif 0.45 <= imt_per < 3.2 : dS2S = 0.4 elif 3.2 <= imt_p...
Table 4 of 2013 report
44,003
def context ( src ) : try : yield except Exception : etype , err , tb = sys . exc_info ( ) msg = 'An error occurred with source id=%s. Error: %s' msg %= ( src . source_id , err ) raise_ ( etype , msg , tb )
Used to add the source_id to the error message . To be used as
44,004
def get_bounding_box ( self , lon , lat , trt = None , mag = None ) : if trt is None : maxdist = max ( self ( trt , mag ) for trt in self . dic ) else : maxdist = self ( trt , mag ) a1 = min ( maxdist * KM_TO_DEGREES , 90 ) a2 = min ( angular_distance ( maxdist , lat ) , 180 ) return lon - a2 , lat - a1 , lon + a2 , la...
Build a bounding box around the given lon lat by computing the maximum_distance at the given tectonic region type and magnitude .
44,005
def get_affected_box ( self , src ) : mag = src . get_min_max_mag ( ) [ 1 ] maxdist = self ( src . tectonic_region_type , mag ) bbox = get_bounding_box ( src , maxdist ) return ( fix_lon ( bbox [ 0 ] ) , bbox [ 1 ] , fix_lon ( bbox [ 2 ] ) , bbox [ 3 ] )
Get the enlarged bounding box of a source .
44,006
def sitecol ( self ) : if 'sitecol' in vars ( self ) : return self . __dict__ [ 'sitecol' ] if self . filename is None or not os . path . exists ( self . filename ) : return with hdf5 . File ( self . filename , 'r' ) as h5 : self . __dict__ [ 'sitecol' ] = sc = h5 . get ( 'sitecol' ) return sc
Read the site collection from . filename and cache it
44,007
def hypocentre_patch_index ( cls , hypocentre , rupture_top_edge , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : totaln_patch = len ( rupture_top_edge ) indexlist = [ ] dist_list = [ ] for i , index in enumerate ( range ( 1 , totaln_patch ) ) : p0 , p1 , p2 , p3 = cls . get_fault_patch_vertices ( rupture_...
This methods finds the index of the fault patch including the hypocentre .
44,008
def get_surface_vertexes ( cls , fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : dip_tan = math . tan ( math . radians ( dip ) ) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_depth / dip_tan strike = fault_trace [ 0 ] . azimuth ( fault_trace [ - 1 ] ) azimuth =...
Get surface main vertexes .
44,009
def surface_projection_from_fault_data ( cls , fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : lons , lats = cls . get_surface_vertexes ( fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) return Mesh ( lons , lats , depths = None ) . get_convex_hull ( )
Get a surface projection of the simple fault surface .
44,010
def _compute_distance_term ( self , C , mag , rrup ) : term1 = C [ 'b' ] * rrup term2 = - np . log ( rrup + C [ 'c' ] * np . exp ( C [ 'd' ] * mag ) ) return term1 + term2
Compute second and third terms in equation 1 p . 901 .
44,011
def _compute_focal_depth_term ( self , C , hypo_depth ) : focal_depth = hypo_depth if focal_depth > 125.0 : focal_depth = 125.0 hc = 15.0 return float ( focal_depth >= hc ) * C [ 'e' ] * ( focal_depth - hc )
Compute fourth term in equation 1 p . 901 .
44,012
def _compute_site_class_term ( self , C , vs30 ) : site_term = np . zeros ( len ( vs30 ) ) site_term [ vs30 > 1100.0 ] = C [ 'CH' ] site_term [ ( vs30 > 600 ) & ( vs30 <= 1100 ) ] = C [ 'C1' ] site_term [ ( vs30 > 300 ) & ( vs30 <= 600 ) ] = C [ 'C2' ] site_term [ ( vs30 > 200 ) & ( vs30 <= 300 ) ] = C [ 'C3' ] site_te...
Compute nine - th term in equation 1 p . 901 .
44,013
def _compute_magnitude_squared_term ( self , P , M , Q , W , mag ) : return P * ( mag - M ) + Q * ( mag - M ) ** 2 + W
Compute magnitude squared term equation 5 p . 909 .
44,014
def _compute_slab_correction_term ( self , C , rrup ) : slab_term = C [ 'SSL' ] * np . log ( rrup ) return slab_term
Compute path modification term for slab events that is the 8 - th term in equation 1 p . 901 .
44,015
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : dists_mod = copy . deepcopy ( dists ) dists_mod . rrup [ dists . rrup <= 5. ] = 5. return super ( ) . get_mean_and_stddevs ( sites , rup , dists_mod , imt , stddev_types )
Using a minimum distance of 5km for the calculation .
44,016
def confirm ( prompt ) : while True : try : answer = input ( prompt ) except KeyboardInterrupt : return False answer = answer . strip ( ) . lower ( ) if answer not in ( 'y' , 'n' ) : print ( 'Please enter y or n' ) continue return answer == 'y'
Ask for confirmation given a prompt and return a boolean value .
44,017
def _csv_header ( self ) : fields = [ 'id' , 'number' , 'taxonomy' , 'lon' , 'lat' ] for name in self . cost_types [ 'name' ] : fields . append ( name ) if 'per_area' in self . cost_types [ 'type' ] : fields . append ( 'area' ) if self . occupancy_periods : fields . extend ( self . occupancy_periods . split ( ) ) field...
Extract the expected CSV header from the exposure metadata
44,018
def build_vf_node ( vf ) : nodes = [ Node ( 'imls' , { 'imt' : vf . imt } , vf . imls ) , Node ( 'meanLRs' , { } , vf . mean_loss_ratios ) , Node ( 'covLRs' , { } , vf . covs ) ] return Node ( 'vulnerabilityFunction' , { 'id' : vf . id , 'dist' : vf . distribution_name } , nodes = nodes )
Convert a VulnerabilityFunction object into a Node suitable for XML conversion .
44,019
def get_riskmodel ( taxonomy , oqparam , ** extra ) : riskmodel_class = registry [ oqparam . calculation_mode ] argnames = inspect . getfullargspec ( riskmodel_class . __init__ ) . args [ 3 : ] known_args = set ( name for name , value in inspect . getmembers ( oqparam . __class__ ) if isinstance ( value , valid . Param...
Return an instance of the correct riskmodel class depending on the attribute calculation_mode of the object oqparam .
44,020
def Beachball ( fm , linewidth = 2 , facecolor = 'b' , bgcolor = 'w' , edgecolor = 'k' , alpha = 1.0 , xy = ( 0 , 0 ) , width = 200 , size = 100 , nofill = False , zorder = 100 , outfile = None , format = None , fig = None ) : plot_width = width * 0.95 if not fig : fig = plt . figure ( figsize = ( 3 , 3 ) , dpi = 100 )...
Draws a beach ball diagram of an earthquake focal mechanism .
44,021
def StrikeDip ( n , e , u ) : r2d = 180 / np . pi if u < 0 : n = - n e = - e u = - u strike = np . arctan2 ( e , n ) * r2d strike = strike - 90 while strike >= 360 : strike = strike - 360 while strike < 0 : strike = strike + 360 x = np . sqrt ( np . power ( n , 2 ) + np . power ( e , 2 ) ) dip = np . arctan2 ( x , u ) ...
Finds strike and dip of plane given normal vector having components n e and u .
44,022
def AuxPlane ( s1 , d1 , r1 ) : r2d = 180 / np . pi z = ( s1 + 90 ) / r2d z2 = d1 / r2d z3 = r1 / r2d sl1 = - np . cos ( z3 ) * np . cos ( z ) - np . sin ( z3 ) * np . sin ( z ) * np . cos ( z2 ) sl2 = np . cos ( z3 ) * np . sin ( z ) - np . sin ( z3 ) * np . cos ( z ) * np . cos ( z2 ) sl3 = np . sin ( z3 ) * np . sin...
Get Strike and dip of second plane .
44,023
def MT2Plane ( mt ) : ( d , v ) = np . linalg . eig ( mt . mt ) D = np . array ( [ d [ 1 ] , d [ 0 ] , d [ 2 ] ] ) V = np . array ( [ [ v [ 1 , 1 ] , - v [ 1 , 0 ] , - v [ 1 , 2 ] ] , [ v [ 2 , 1 ] , - v [ 2 , 0 ] , - v [ 2 , 2 ] ] , [ - v [ 0 , 1 ] , v [ 0 , 0 ] , v [ 0 , 2 ] ] ] ) IMAX = D . argmax ( ) IMIN = D . arg...
Calculates a nodal plane of a given moment tensor .
44,024
def TDL ( AN , BN ) : XN = AN [ 0 ] YN = AN [ 1 ] ZN = AN [ 2 ] XE = BN [ 0 ] YE = BN [ 1 ] ZE = BN [ 2 ] AAA = 1.0 / ( 1000000 ) CON = 57.2957795 if np . fabs ( ZN ) < AAA : FD = 90. AXN = np . fabs ( XN ) if AXN > 1.0 : AXN = 1.0 FT = np . arcsin ( AXN ) * CON ST = - XN CT = YN if ST >= 0. and CT < 0 : FT = 180. - FT...
Helper function for MT2Plane .
44,025
def MT2Axes ( mt ) : ( D , V ) = np . linalg . eigh ( mt . mt ) pl = np . arcsin ( - V [ 0 ] ) az = np . arctan2 ( V [ 2 ] , - V [ 1 ] ) for i in range ( 0 , 3 ) : if pl [ i ] <= 0 : pl [ i ] = - pl [ i ] az [ i ] += np . pi if az [ i ] < 0 : az [ i ] += 2 * np . pi if az [ i ] > 2 * np . pi : az [ i ] -= 2 * np . pi p...
Calculates the principal axes of a given moment tensor .
44,026
def tapered_gutenberg_richter_cdf ( moment , moment_threshold , beta , corner_moment ) : cdf = np . exp ( ( moment_threshold - moment ) / corner_moment ) return ( ( moment / moment_threshold ) ** ( - beta ) ) * cdf
Tapered Gutenberg Richter Cumulative Density Function
44,027
def tapered_gutenberg_richter_pdf ( moment , moment_threshold , beta , corner_moment ) : return ( ( beta / moment + 1. / corner_moment ) * tapered_gutenberg_richter_cdf ( moment , moment_threshold , beta , corner_moment ) )
Tapered Gutenberg - Richter Probability Density Function
44,028
def makedirs ( path ) : if os . path . exists ( path ) : if not os . path . isdir ( path ) : raise RuntimeError ( '%s already exists and is not a directory.' % path ) else : os . makedirs ( path )
Make all of the directories in the path using os . makedirs .
44,029
def _get_observed_mmax ( catalogue , config ) : if config [ 'input_mmax' ] : obsmax = config [ 'input_mmax' ] if config [ 'input_mmax_uncertainty' ] : return config [ 'input_mmax' ] , config [ 'input_mmax_uncertainty' ] else : raise ValueError ( 'Input mmax uncertainty must be specified!' ) max_location = np . argmax (...
Check see if observed mmax values are input if not then take from the catalogue
44,030
def _get_magnitude_vector_properties ( catalogue , config ) : mmin = config . get ( 'input_mmin' , np . min ( catalogue [ 'magnitude' ] ) ) neq = np . float ( np . sum ( catalogue [ 'magnitude' ] >= mmin - 1.E-7 ) ) return neq , mmin
If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties
44,031
def get_dip ( self ) : if self . dip is None : mesh = self . mesh self . dip , self . strike = mesh . get_mean_inclination_and_azimuth ( ) return self . dip
Return the fault dip as the average dip over the mesh .
44,032
def check_surface_validity ( cls , edges ) : full_boundary = [ ] left_boundary = [ ] right_boundary = [ ] for i in range ( 1 , len ( edges ) - 1 ) : left_boundary . append ( edges [ i ] . points [ 0 ] ) right_boundary . append ( edges [ i ] . points [ - 1 ] ) full_boundary . extend ( edges [ 0 ] . points ) full_boundar...
Check validity of the surface .
44,033
def surface_projection_from_fault_data ( cls , edges ) : lons = [ ] lats = [ ] for edge in edges : for point in edge : lons . append ( point . longitude ) lats . append ( point . latitude ) lons = numpy . array ( lons , dtype = float ) lats = numpy . array ( lats , dtype = float ) return Mesh ( lons , lats , depths = N...
Get a surface projection of the complex fault surface .
44,034
def check_time_event ( oqparam , occupancy_periods ) : time_event = oqparam . time_event if time_event and time_event not in occupancy_periods : raise ValueError ( 'time_event is %s in %s, but the exposure contains %s' % ( time_event , oqparam . inputs [ 'job_ini' ] , ', ' . join ( occupancy_periods ) ) )
Check the time_event parameter in the datastore by comparing with the periods found in the exposure .
44,035
def get_idxs ( data , eid2idx ) : uniq , inv = numpy . unique ( data [ 'eid' ] , return_inverse = True ) idxs = numpy . array ( [ eid2idx [ eid ] for eid in uniq ] ) [ inv ] return idxs
Convert from event IDs to event indices .
44,036
def import_gmfs ( dstore , fname , sids ) : array = writers . read_composite_array ( fname ) . array imts = [ name [ 4 : ] for name in array . dtype . names [ 3 : ] ] n_imts = len ( imts ) gmf_data_dt = numpy . dtype ( [ ( 'rlzi' , U16 ) , ( 'sid' , U32 ) , ( 'eid' , U64 ) , ( 'gmv' , ( F32 , ( n_imts , ) ) ) ] ) eids ...
Import in the datastore a ground motion field CSV file .
44,037
def save_params ( self , ** kw ) : if ( 'hazard_calculation_id' in kw and kw [ 'hazard_calculation_id' ] is None ) : del kw [ 'hazard_calculation_id' ] vars ( self . oqparam ) . update ( ** kw ) self . datastore [ 'oqparam' ] = self . oqparam attrs = self . datastore [ '/' ] . attrs attrs [ 'engine_version' ] = engine_...
Update the current calculation parameters and save engine_version
44,038
def run ( self , pre_execute = True , concurrent_tasks = None , close = True , ** kw ) : with self . _monitor : self . _monitor . username = kw . get ( 'username' , '' ) self . _monitor . hdf5 = self . datastore . hdf5 if concurrent_tasks is None : ct = self . oqparam . concurrent_tasks else : ct = concurrent_tasks if ...
Run the calculation and return the exported outputs .
44,039
def export ( self , exports = None ) : self . exported = getattr ( self . precalc , 'exported' , { } ) if isinstance ( exports , tuple ) : fmts = exports elif exports : fmts = exports . split ( ',' ) elif isinstance ( self . oqparam . exports , tuple ) : fmts = self . oqparam . exports else : fmts = self . oqparam . ex...
Export all the outputs in the datastore in the given export formats . Individual outputs are not exported if there are multiple realizations .
44,040
def before_export ( self ) : try : csm_info = self . datastore [ 'csm_info' ] except KeyError : csm_info = self . datastore [ 'csm_info' ] = self . csm . info for sm in csm_info . source_models : for sg in sm . src_groups : assert sg . eff_ruptures != - 1 , sg for key in self . datastore : self . datastore . set_nbytes...
Set the attributes nbytes
44,041
def read_inputs ( self ) : oq = self . oqparam self . _read_risk_data ( ) self . check_overflow ( ) if ( 'source_model_logic_tree' in oq . inputs and oq . hazard_calculation_id is None ) : self . csm = readinput . get_composite_source_model ( oq , self . monitor ( ) , srcfilter = self . src_filter ) self . init ( )
Read risk data and sources if any
44,042
def pre_execute ( self ) : oq = self . oqparam if 'gmfs' in oq . inputs or 'multi_peril' in oq . inputs : assert not oq . hazard_calculation_id , ( 'You cannot use --hc together with gmfs_file' ) self . read_inputs ( ) if 'gmfs' in oq . inputs : save_gmfs ( self ) else : self . save_multi_peril ( ) elif 'hazard_curves'...
Check if there is a previous calculation ID . If yes read the inputs by retrieving the previous calculation ; if not read the inputs directly .
44,043
def init ( self ) : oq = self . oqparam if not oq . risk_imtls : if self . datastore . parent : oq . risk_imtls = ( self . datastore . parent [ 'oqparam' ] . risk_imtls ) if 'precalc' in vars ( self ) : self . rlzs_assoc = self . precalc . rlzs_assoc elif 'csm_info' in self . datastore : csm_info = self . datastore [ '...
To be overridden to initialize the datasets needed by the calculation
44,044
def read_exposure ( self , haz_sitecol = None ) : with self . monitor ( 'reading exposure' , autoflush = True ) : self . sitecol , self . assetcol , discarded = ( readinput . get_sitecol_assetcol ( self . oqparam , haz_sitecol , self . riskmodel . loss_types ) ) if len ( discarded ) : self . datastore [ 'discarded' ] =...
Read the exposure the riskmodel and update the attributes . sitecol . assetcol
44,045
def save_riskmodel ( self ) : self . datastore [ 'risk_model' ] = rm = self . riskmodel self . datastore [ 'taxonomy_mapping' ] = self . riskmodel . tmap attrs = self . datastore . getitem ( 'risk_model' ) . attrs attrs [ 'min_iml' ] = hdf5 . array_of_vstr ( sorted ( rm . min_iml . items ( ) ) ) self . datastore . set_...
Save the risk models in the datastore
44,046
def store_rlz_info ( self , eff_ruptures = None ) : if hasattr ( self , 'csm' ) : self . csm . info . update_eff_ruptures ( eff_ruptures ) self . rlzs_assoc = self . csm . info . get_rlzs_assoc ( self . oqparam . sm_lt_path ) if not self . rlzs_assoc : raise RuntimeError ( 'Empty logic tree: too much filtering?' ) self...
Save info about the composite source model inside the csm_info dataset
44,047
def read_shakemap ( self , haz_sitecol , assetcol ) : oq = self . oqparam E = oq . number_of_ground_motion_fields oq . risk_imtls = oq . imtls or self . datastore . parent [ 'oqparam' ] . imtls extra = self . riskmodel . get_extra_imts ( oq . risk_imtls ) if extra : logging . warning ( 'There are risk functions for not...
Enabled only if there is a shakemap_id parameter in the job . ini . Download unzip parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastore .
44,048
def bind ( end_point , socket_type ) : sock = context . socket ( socket_type ) try : sock . bind ( end_point ) except zmq . error . ZMQError as exc : sock . close ( ) raise exc . __class__ ( '%s: %s' % ( exc , end_point ) ) return sock
Bind to a zmq URL ; raise a proper error if the URL is invalid ; return a zmq socket .
44,049
def send ( self , obj ) : self . zsocket . send_pyobj ( obj ) self . num_sent += 1 if self . socket_type == zmq . REQ : return self . zsocket . recv_pyobj ( )
Send an object to the remote server ; block and return the reply if the socket type is REQ .
44,050
def angular_distance ( km , lat , lat2 = None ) : if lat2 is not None : lat = max ( abs ( lat ) , abs ( lat2 ) ) return km * KM_TO_DEGREES / math . cos ( lat * DEGREES_TO_RAD )
Return the angular distance of two points at the given latitude .
44,051
def assoc ( objects , sitecol , assoc_dist , mode , asset_refs = ( ) ) : if isinstance ( objects , numpy . ndarray ) or hasattr ( objects , 'lons' ) : return _GeographicObjects ( objects ) . assoc ( sitecol , assoc_dist , mode ) else : return _GeographicObjects ( sitecol ) . assoc2 ( objects , assoc_dist , mode , asset...
Associate geographic objects to a site collection .
44,052
def line_intersects_itself ( lons , lats , closed_shape = False ) : assert len ( lons ) == len ( lats ) if len ( lons ) <= 3 : return False west , east , north , south = get_spherical_bounding_box ( lons , lats ) proj = OrthographicProjection ( west , east , north , south ) xx , yy = proj ( lons , lats ) if not shapely...
Return True if line of points intersects itself . Line with the last point repeating the first one considered intersecting itself .
44,053
def get_bounding_box ( obj , maxdist ) : if hasattr ( obj , 'get_bounding_box' ) : return obj . get_bounding_box ( maxdist ) elif hasattr ( obj , 'polygon' ) : bbox = obj . polygon . get_bbox ( ) else : if isinstance ( obj , list ) : lons = numpy . array ( [ loc . longitude for loc in obj ] ) lats = numpy . array ( [ l...
Return the dilated bounding box of a geometric object .
44,054
def get_spherical_bounding_box ( lons , lats ) : north , south = numpy . max ( lats ) , numpy . min ( lats ) west , east = numpy . min ( lons ) , numpy . max ( lons ) assert ( - 180 <= west <= 180 ) and ( - 180 <= east <= 180 ) , ( west , east ) if get_longitudinal_extent ( west , east ) < 0 : if hasattr ( lons , 'flat...
Given a collection of points find and return the bounding box as a pair of longitudes and a pair of latitudes .
44,055
def get_middle_point ( lon1 , lat1 , lon2 , lat2 ) : if lon1 == lon2 and lat1 == lat2 : return lon1 , lat1 dist = geodetic . geodetic_distance ( lon1 , lat1 , lon2 , lat2 ) azimuth = geodetic . azimuth ( lon1 , lat1 , lon2 , lat2 ) return geodetic . point_at ( lon1 , lat1 , azimuth , dist / 2.0 )
Given two points return the point exactly in the middle lying on the same great circle arc .
44,056
def cartesian_to_spherical ( vectors ) : rr = numpy . sqrt ( numpy . sum ( vectors * vectors , axis = - 1 ) ) xx , yy , zz = vectors . T lats = numpy . degrees ( numpy . arcsin ( ( zz / rr ) . clip ( - 1. , 1. ) ) ) lons = numpy . degrees ( numpy . arctan2 ( yy , xx ) ) depths = EARTH_RADIUS - rr return lons . T , lats...
Return the spherical coordinates for coordinates in Cartesian space .
44,057
def triangle_area ( e1 , e2 , e3 ) : e1_length = numpy . sqrt ( numpy . sum ( e1 * e1 , axis = - 1 ) ) e2_length = numpy . sqrt ( numpy . sum ( e2 * e2 , axis = - 1 ) ) e3_length = numpy . sqrt ( numpy . sum ( e3 * e3 , axis = - 1 ) ) s = ( e1_length + e2_length + e3_length ) / 2.0 return numpy . sqrt ( s * ( s - e1_le...
Get the area of triangle formed by three vectors .
44,058
def normalized ( vector ) : length = numpy . sum ( vector * vector , axis = - 1 ) length = numpy . sqrt ( length . reshape ( length . shape + ( 1 , ) ) ) return vector / length
Get unit vector for a given one .
44,059
def point_to_polygon_distance ( polygon , pxx , pyy ) : pxx = numpy . array ( pxx ) pyy = numpy . array ( pyy ) assert pxx . shape == pyy . shape if pxx . ndim == 0 : pxx = pxx . reshape ( ( 1 , ) ) pyy = pyy . reshape ( ( 1 , ) ) result = numpy . array ( [ polygon . distance ( shapely . geometry . Point ( pxx . item (...
Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane .
44,060
def cross_idl ( lon1 , lon2 , * lons ) : lons = ( lon1 , lon2 ) + lons l1 , l2 = min ( lons ) , max ( lons ) return l1 * l2 < 0 and abs ( l1 - l2 ) > 180
Return True if two longitude values define line crossing international date line .
44,061
def normalize_lons ( l1 , l2 ) : if l1 > l2 : l1 , l2 = l2 , l1 delta = l2 - l1 if l1 < 0 and l2 > 0 and delta > 180 : return [ ( - 180 , l1 ) , ( l2 , 180 ) ] elif l1 > 0 and l2 > 180 and delta < 180 : return [ ( l1 , 180 ) , ( - 180 , l2 - 360 ) ] elif l1 < - 180 and l2 < 0 and delta < 180 : return [ ( l1 + 360 , 180...
An international date line safe way of returning a range of longitudes .
44,062
def get_closest ( self , lon , lat , depth = 0 ) : xyz = spherical_to_cartesian ( lon , lat , depth ) min_dist , idx = self . kdtree . query ( xyz ) return self . objects [ idx ] , min_dist
Get the closest object to the given longitude and latitude and its distance .
44,063
def assoc2 ( self , assets_by_site , assoc_dist , mode , asset_refs ) : assert mode in 'strict filter' , mode self . objects . filtered asset_dt = numpy . dtype ( [ ( 'asset_ref' , vstr ) , ( 'lon' , F32 ) , ( 'lat' , F32 ) ] ) assets_by_sid = collections . defaultdict ( list ) discarded = [ ] for assets in assets_by_s...
Associated a list of assets by site to the site collection used to instantiate GeographicObjects .
44,064
def ffconvert ( fname , limit_states , ff , min_iml = 1E-10 ) : with context ( fname , ff ) : ffs = ff [ 1 : ] imls = ff . imls nodamage = imls . attrib . get ( 'noDamageLimit' ) if nodamage == 0 : logging . warning ( 'Found a noDamageLimit=0 in %s, line %s, ' 'using %g instead' , fname , ff . lineno , min_iml ) nodama...
Convert a fragility function into a numpy array plus a bunch of attributes .
44,065
def taxonomy ( value ) : try : value . encode ( 'ascii' ) except UnicodeEncodeError : raise ValueError ( 'tag %r is not ASCII' % value ) if re . search ( r'\s' , value ) : raise ValueError ( 'The taxonomy %r contains whitespace chars' % value ) return value
Any ASCII character goes into a taxonomy except spaces .
44,066
def update_validators ( ) : validators . update ( { 'fragilityFunction.id' : valid . utf8 , 'vulnerabilityFunction.id' : valid . utf8 , 'consequenceFunction.id' : valid . utf8 , 'asset.id' : valid . asset_id , 'costType.name' : valid . cost_type , 'costType.type' : valid . cost_type_type , 'cost.type' : valid . cost_ty...
Call this to updade the global nrml . validators
44,067
def barray ( iterlines ) : lst = [ line . encode ( 'utf-8' ) for line in iterlines ] arr = numpy . array ( lst ) return arr
Array of bytes
44,068
def losses_by_tag ( dstore , tag ) : dt = [ ( tag , vstr ) ] + dstore [ 'oqparam' ] . loss_dt_list ( ) aids = dstore [ 'assetcol/array' ] [ tag ] dset , stats = _get ( dstore , 'avg_losses' ) arr = dset . value tagvalues = dstore [ 'assetcol/tagcol/' + tag ] [ 1 : ] for s , stat in enumerate ( stats ) : out = numpy . z...
Statistical average losses by tag . For instance call
44,069
def dump ( self , fname ) : url = '%s/v1/calc/%d/datastore' % ( self . server , self . calc_id ) resp = self . sess . get ( url , stream = True ) down = 0 with open ( fname , 'wb' ) as f : logging . info ( 'Saving %s' , fname ) for chunk in resp . iter_content ( CHUNKSIZE ) : f . write ( chunk ) down += len ( chunk ) p...
Dump the remote datastore on a local path .
44,070
def _compute_small_mag_correction_term ( C , mag , rhypo ) : if mag >= 3.00 and mag < 5.5 : min_term = np . minimum ( rhypo , C [ 'Rm' ] ) max_term = np . maximum ( min_term , 10 ) term_ln = np . log ( max_term / 20 ) term_ratio = ( ( 5.50 - mag ) / C [ 'a1' ] ) temp = ( term_ratio ) ** C [ 'a2' ] * ( C [ 'b1' ] + C [ ...
small magnitude correction applied to the median values
44,071
def _apply_adjustments ( COEFFS , C_ADJ , tau_ss , mean , stddevs , sites , rup , dists , imt , stddev_types , log_phi_ss , NL = None , tau_value = None ) : c1_dists = _compute_C1_term ( C_ADJ , dists ) phi_ss = _compute_phi_ss ( C_ADJ , rup . mag , c1_dists , log_phi_ss , C_ADJ [ 'mean_phi_ss' ] ) mean_corr = np . exp...
This method applies adjustments to the mean and standard deviation . The small - magnitude adjustments are applied to mean whereas the embeded single station sigma logic tree is applied to the total standard deviation .
44,072
def get_info ( self , sm_id ) : sm = self . source_models [ sm_id ] num_samples = sm . samples if self . num_samples else 0 return self . __class__ ( self . gsim_lt , self . seed , num_samples , [ sm ] , self . tot_weight )
Extract a CompositionInfo instance containing the single model of index sm_id .
44,073
def get_source_model ( self , src_group_id ) : for smodel in self . source_models : for src_group in smodel . src_groups : if src_group . id == src_group_id : return smodel
Return the source model for the given src_group_id
44,074
def get_model ( self , sm_id ) : sm = self . source_models [ sm_id ] if self . source_model_lt . num_samples : self . source_model_lt . num_samples = sm . samples new = self . __class__ ( self . gsim_lt , self . source_model_lt , [ sm ] , self . optimize_same_id ) new . sm_id = sm_id return new
Extract a CompositeSourceModel instance containing the single model of index sm_id .
44,075
def new ( self , sources_by_grp ) : source_models = [ ] for sm in self . source_models : src_groups = [ ] for src_group in sm . src_groups : sg = copy . copy ( src_group ) sg . sources = sorted ( sources_by_grp . get ( sg . id , [ ] ) , key = operator . attrgetter ( 'id' ) ) src_groups . append ( sg ) newsm = logictree...
Generate a new CompositeSourceModel from the given dictionary .
44,076
def check_dupl_sources ( self ) : dd = collections . defaultdict ( list ) for src_group in self . src_groups : for src in src_group : try : srcid = src . source_id except AttributeError : srcid = src [ 'id' ] dd [ srcid ] . append ( src ) dupl = [ ] for srcid , srcs in sorted ( dd . items ( ) ) : if len ( srcs ) > 1 : ...
Extracts duplicated sources i . e . sources with the same source_id in different source groups . Raise an exception if there are sources with the same ID which are not duplicated .
44,077
def get_sources ( self , kind = 'all' ) : assert kind in ( 'all' , 'indep' , 'mutex' ) , kind sources = [ ] for sm in self . source_models : for src_group in sm . src_groups : if kind in ( 'all' , src_group . src_interdep ) : for src in src_group : if sm . samples > 1 : src . samples = sm . samples sources . append ( s...
Extract the sources contained in the source models by optionally filtering and splitting them depending on the passed parameter .
44,078
def init_serials ( self , ses_seed ) : sources = self . get_sources ( ) serial = ses_seed for src in sources : nr = src . num_ruptures src . serial = serial serial += nr
Generate unique seeds for each rupture with numpy . arange . This should be called only in event based calculators
44,079
def get_maxweight ( self , weight , concurrent_tasks , minweight = MINWEIGHT ) : totweight = self . get_weight ( weight ) ct = concurrent_tasks or 1 mw = math . ceil ( totweight / ct ) return max ( mw , minweight )
Return an appropriate maxweight for use in the block_splitter
44,080
def weight_list_to_tuple ( data , attr_name ) : if len ( data [ 'Value' ] ) != len ( data [ 'Weight' ] ) : raise ValueError ( 'Number of weights do not correspond to number of ' 'attributes in %s' % attr_name ) weight = np . array ( data [ 'Weight' ] ) if fabs ( np . sum ( weight ) - 1. ) > 1E-7 : raise ValueError ( 'W...
Converts a list of values and corresponding weights to a tuple of values
44,081
def parse_tect_region_dict_to_tuples ( region_dict ) : output_region_dict = [ ] tuple_keys = [ 'Displacement_Length_Ratio' , 'Shear_Modulus' ] for region in region_dict : for val_name in tuple_keys : region [ val_name ] = weight_list_to_tuple ( region [ val_name ] , val_name ) region [ 'Magnitude_Scaling_Relation' ] = ...
Parses the tectonic regionalisation dictionary attributes to tuples
44,082
def get_scaling_relation_tuple ( msr_dict ) : for iloc , value in enumerate ( msr_dict [ 'Value' ] ) : if not value in SCALE_REL_MAP . keys ( ) : raise ValueError ( 'Scaling relation %s not supported!' % value ) msr_dict [ 'Value' ] [ iloc ] = SCALE_REL_MAP [ value ] ( ) return weight_list_to_tuple ( msr_dict , 'Magnit...
For a dictionary of scaling relation values convert string list to object list and then to tuple
44,083
def read_file ( self , mesh_spacing = 1.0 ) : tectonic_reg = self . process_tectonic_regionalisation ( ) model = mtkActiveFaultModel ( self . data [ 'Fault_Model_ID' ] , self . data [ 'Fault_Model_Name' ] ) for fault in self . data [ 'Fault_Model' ] : fault_geometry = self . read_fault_geometry ( fault [ 'Fault_Geometr...
Reads the file and returns an instance of the FaultSource class .
44,084
def process_tectonic_regionalisation ( self ) : if 'tectonic_regionalisation' in self . data . keys ( ) : tectonic_reg = TectonicRegionalisation ( ) tectonic_reg . populate_regions ( parse_tect_region_dict_to_tuples ( self . data [ 'tectonic_regionalisation' ] ) ) else : tectonic_reg = None return tectonic_reg
Processes the tectonic regionalisation from the yaml file
44,085
def read_fault_geometry ( self , geo_dict , mesh_spacing = 1.0 ) : if geo_dict [ 'Fault_Typology' ] == 'Simple' : raw_trace = geo_dict [ 'Fault_Trace' ] trace = Line ( [ Point ( raw_trace [ ival ] , raw_trace [ ival + 1 ] ) for ival in range ( 0 , len ( raw_trace ) , 2 ) ] ) geometry = SimpleFaultGeometry ( trace , geo...
Creates the fault geometry from the parameters specified in the dictionary .
44,086
def _get_distance_scaling_term ( self , C , mag , rrup ) : return ( C [ "r1" ] + C [ "r2" ] * mag ) * np . log10 ( rrup + C [ "r3" ] )
Returns the distance scaling parameter
44,087
def _get_style_of_faulting_term ( self , C , rake ) : if rake > - 150.0 and rake <= - 30.0 : return C [ 'fN' ] elif rake > 30.0 and rake <= 150.0 : return C [ 'fR' ] else : return C [ 'fSS' ]
Returns the style of faulting term . Cauzzi et al . determind SOF from the plunge of the B - T - and P - axes . For consistency with existing GMPEs the Wells & Coppersmith model is preferred
44,088
def _get_site_amplification_term ( self , C , vs30 ) : s_b , s_c , s_d = self . _get_site_dummy_variables ( vs30 ) return ( C [ "sB" ] * s_b ) + ( C [ "sC" ] * s_c ) + ( C [ "sD" ] * s_d )
Returns the site amplification term on the basis of Eurocode 8 site class
44,089
def _get_site_dummy_variables ( self , vs30 ) : s_b = np . zeros_like ( vs30 ) s_c = np . zeros_like ( vs30 ) s_d = np . zeros_like ( vs30 ) s_b [ np . logical_and ( vs30 >= 360. , vs30 < 800. ) ] = 1.0 s_c [ np . logical_and ( vs30 >= 180. , vs30 < 360. ) ] = 1.0 s_d [ vs30 < 180 ] = 1.0 return s_b , s_c , s_d
Returns the Eurocode 8 site class dummy variable
44,090
def get_recurrence ( self , config ) : model = MFD_MAP [ config [ 'Model_Name' ] ] ( ) model . setUp ( config ) model . get_mmax ( config , self . msr , self . rake , self . area ) model . mmax = model . mmax + ( self . msr_sigma * model . mmax_sigma ) if 'AndersonLucoAreaMmax' in config [ 'Model_Name' ] : if not self ...
Calculates the recurrence model for the given settings as an instance of the openquake . hmtk . models . IncrementalMFD
44,091
def get_tectonic_regionalisation ( self , regionalisation , region_type = None ) : if region_type : self . trt = region_type if not self . trt in regionalisation . key_list : raise ValueError ( 'Tectonic region classification missing or ' 'not defined in regionalisation' ) for iloc , key_val in enumerate ( regionalisat...
Defines the tectonic region and updates the shear modulus magnitude scaling relation and displacement to length ratio using the regional values if not previously defined for the fault
44,092
def select_catalogue ( self , selector , distance , distance_metric = "rupture" , 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 ) : self . catalogue = selector . within_ruptur...
Select earthquakes within a specied distance of the fault
44,093
def generate_config_set ( self , config ) : if isinstance ( config , dict ) : self . config = [ ( config , 1.0 ) ] elif isinstance ( config , list ) : total_weight = 0. self . config = [ ] for params in config : weight = params [ 'Model_Weight' ] total_weight += params [ 'Model_Weight' ] self . config . append ( ( para...
Generates a list of magnitude frequency distributions and renders as a tuple
44,094
def collapse_branches ( self , mmin , bin_width , mmax ) : master_mags = np . arange ( mmin , mmax + ( bin_width / 2. ) , bin_width ) master_rates = np . zeros ( len ( master_mags ) , dtype = float ) for model in self . mfd_models : id0 = np . logical_and ( master_mags >= np . min ( model . magnitudes ) - 1E-9 , master...
Collapse the logic tree branches into a single IncrementalMFD
44,095
def generate_fault_source_model ( self ) : source_model = [ ] model_weight = [ ] for iloc in range ( 0 , self . get_number_mfd_models ( ) ) : model_mfd = EvenlyDiscretizedMFD ( self . mfd [ 0 ] [ iloc ] . min_mag , self . mfd [ 0 ] [ iloc ] . bin_width , self . mfd [ 0 ] [ iloc ] . occur_rates . tolist ( ) ) if isinsta...
Creates a resulting openquake . hmtk fault source set .
44,096
def attrib ( self ) : return dict ( [ ( 'id' , str ( self . id ) ) , ( 'name' , str ( self . name ) ) , ( 'tectonicRegion' , str ( self . trt ) ) , ] )
General XML element attributes for a seismic source as a dict .
44,097
def attrib ( self ) : return dict ( [ ( 'aValue' , str ( self . a_val ) ) , ( 'bValue' , str ( self . b_val ) ) , ( 'minMag' , str ( self . min_mag ) ) , ( 'maxMag' , str ( self . max_mag ) ) , ] )
An dict of XML element attributes for this MFD .
44,098
def attrib ( self ) : return dict ( [ ( 'probability' , str ( self . probability ) ) , ( 'strike' , str ( self . strike ) ) , ( 'dip' , str ( self . dip ) ) , ( 'rake' , str ( self . rake ) ) , ] )
A dict of XML element attributes for this NodalPlane .
44,099
def jbcorrelation ( sites_or_distances , imt , vs30_clustering = False ) : if hasattr ( sites_or_distances , 'mesh' ) : distances = sites_or_distances . mesh . get_distance_matrix ( ) else : distances = sites_or_distances if imt . period < 1 : if not vs30_clustering : b = 8.5 + 17.2 * imt . period else : b = 40.7 - 15....
Returns the Jayaram - Baker correlation model .