idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
232,900
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 .
232,901
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 .
232,902
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
232,903
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 .
232,904
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 .
232,905
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
232,906
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
232,907
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 .
232,908
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
232,909
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
232,910
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
232,911
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
232,912
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 .
232,913
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 .
232,914
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 .
232,915
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 .
232,916
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 .
232,917
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 .
232,918
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 .
232,919
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 .
232,920
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 .
232,921
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 .
232,922
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 .
232,923
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 .
232,924
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 .
232,925
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 .
232,926
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 .
232,927
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 .
232,928
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 .
232,929
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 .
232,930
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 .
232,931
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
232,932
def barray ( iterlines ) : lst = [ line . encode ( 'utf-8' ) for line in iterlines ] arr = numpy . array ( lst ) return arr
Array of bytes
232,933
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
232,934
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 .
232,935
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
232,936
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 .
232,937
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 .
232,938
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
232,939
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 .
232,940
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 .
232,941
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 .
232,942
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 .
232,943
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
232,944
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
232,945
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
232,946
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
232,947
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
232,948
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 .
232,949
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
232,950
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 .
232,951
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
232,952
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
232,953
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
232,954
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
232,955
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
232,956
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
232,957
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
232,958
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
232,959
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
232,960
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 .
232,961
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 .
232,962
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 .
232,963
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 .
232,964
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 .
232,965
def hmcorrelation ( sites_or_distances , imt , uncertainty_multiplier = 0 ) : if hasattr ( sites_or_distances , 'mesh' ) : distances = sites_or_distances . mesh . get_distance_matrix ( ) else : distances = sites_or_distances period = imt . period if period < 1.37 : Med_b = 4.231 * period * period - 5.180 * period + 13....
Returns the Heresi - Miranda correlation model .
232,966
def get_lower_triangle_correlation_matrix ( self , sites , imt ) : return numpy . linalg . cholesky ( self . _get_correlation_matrix ( sites , imt ) )
Get lower - triangle matrix as a result of Cholesky - decomposition of correlation matrix .
232,967
def start_ebrisk ( rupgetter , srcfilter , param , monitor ) : with monitor ( 'weighting ruptures' ) : rupgetter . set_weights ( srcfilter , param [ 'num_taxonomies' ] ) if rupgetter . weights . sum ( ) <= param [ 'maxweight' ] : yield ebrisk ( rupgetter , srcfilter , param , monitor ) else : for rgetter in rupgetter ....
Launcher for ebrisk tasks
232,968
def get_min_max_mag ( self ) : "Return the minimum and maximum magnitudes" mag , num_bins = self . _get_min_mag_and_num_bins ( ) return mag , mag + self . bin_width * ( num_bins - 1 )
Return the minimum and maximum magnitudes
232,969
def _get_rate ( self , mag ) : mag_lo = mag - self . bin_width / 2.0 mag_hi = mag + self . bin_width / 2.0 if mag >= self . min_mag and mag < self . char_mag - DELTA_CHAR / 2 : return ( 10 ** ( self . a_val - self . b_val * mag_lo ) - 10 ** ( self . a_val - self . b_val * mag_hi ) ) else : return ( self . char_rate / D...
Calculate and return the annual occurrence rate for a specific bin .
232,970
def _get_min_mag_and_num_bins ( self ) : min_mag = round ( self . min_mag / self . bin_width ) * self . bin_width max_mag = ( round ( ( self . char_mag + DELTA_CHAR / 2 ) / self . bin_width ) * self . bin_width ) min_mag += self . bin_width / 2.0 max_mag -= self . bin_width / 2.0 num_bins = int ( round ( ( max_mag - mi...
Estimate the number of bins in the histogram and return it along with the first bin center value .
232,971
def get_annual_occurrence_rates ( self ) : mag , num_bins = self . _get_min_mag_and_num_bins ( ) rates = [ ] for i in range ( num_bins ) : rate = self . _get_rate ( mag ) rates . append ( ( mag , rate ) ) mag += self . bin_width return rates
Calculate and return the annual occurrence rates histogram .
232,972
def create_geometry ( self , input_geometry , upper_depth , lower_depth ) : self . _check_seismogenic_depths ( upper_depth , lower_depth ) if not isinstance ( input_geometry , Polygon ) : if not isinstance ( input_geometry , np . ndarray ) : raise ValueError ( 'Unrecognised or unsupported geometry ' 'definition' ) if n...
If geometry is defined as a numpy array then create instance of nhlib . geo . polygon . Polygon class otherwise if already instance of class accept class
232,973
def select_catalogue ( self , selector , distance = None ) : if selector . catalogue . get_number_events ( ) < 1 : raise ValueError ( 'No events found in catalogue!' ) self . catalogue = selector . within_polygon ( self . geometry , distance , upper_depth = self . upper_depth , lower_depth = self . lower_depth ) if sel...
Selects the catalogue of earthquakes attributable to the source
232,974
def new ( self , operation = 'no operation' , ** kw ) : self_vars = vars ( self ) . copy ( ) del self_vars [ 'operation' ] del self_vars [ 'children' ] del self_vars [ 'counts' ] del self_vars [ '_flush' ] new = self . __class__ ( operation ) vars ( new ) . update ( self_vars ) vars ( new ) . update ( kw ) return new
Return a copy of the monitor usable for a different operation .
232,975
def from_shakemap ( cls , shakemap_array ) : self = object . __new__ ( cls ) self . complete = self n = len ( shakemap_array ) dtype = numpy . dtype ( [ ( p , site_param_dt [ p ] ) for p in 'sids lon lat depth vs30' . split ( ) ] ) self . array = arr = numpy . zeros ( n , dtype ) arr [ 'sids' ] = numpy . arange ( n , d...
Build a site collection from a shakemap array
232,976
def from_points ( cls , lons , lats , depths = None , sitemodel = None , req_site_params = ( ) ) : assert len ( lons ) < U32LIMIT , len ( lons ) if depths is None : depths = numpy . zeros ( len ( lons ) ) assert len ( lons ) == len ( lats ) == len ( depths ) , ( len ( lons ) , len ( lats ) , len ( depths ) ) self = obj...
Build the site collection from
232,977
def make_complete ( self ) : self . array [ 'sids' ] = numpy . arange ( len ( self ) , dtype = numpy . uint32 ) self . complete = self
Turns the site collection into a complete one if needed
232,978
def filter ( self , mask ) : assert len ( mask ) == len ( self ) , ( len ( mask ) , len ( self ) ) if mask . all ( ) : return self if not mask . any ( ) : return None indices , = mask . nonzero ( ) return self . filtered ( indices )
Create a SiteCollection with only a subset of sites .
232,979
def point_at ( self , horizontal_distance , vertical_increment , azimuth ) : lon , lat = geodetic . point_at ( self . longitude , self . latitude , azimuth , horizontal_distance ) return Point ( lon , lat , self . depth + vertical_increment )
Compute the point with given horizontal vertical distances and azimuth from this point .
232,980
def equally_spaced_points ( self , point , distance ) : lons , lats , depths = geodetic . intervals_between ( self . longitude , self . latitude , self . depth , point . longitude , point . latitude , point . depth , distance ) return [ Point ( lons [ i ] , lats [ i ] , depths [ i ] ) for i in range ( len ( lons ) ) ]
Compute the set of points equally spaced between this point and the given point .
232,981
def to_polygon ( self , radius ) : assert radius > 0 from openquake . hazardlib . geo . polygon import Polygon proj = geo_utils . OrthographicProjection ( self . longitude , self . longitude , self . latitude , self . latitude ) point = shapely . geometry . Point ( * proj ( self . longitude , self . latitude ) ) return...
Create a circular polygon with specified radius centered in the point .
232,982
def closer_than ( self , mesh , radius ) : dists = geodetic . distance ( self . longitude , self . latitude , self . depth , mesh . lons , mesh . lats , 0 if mesh . depths is None else mesh . depths ) return dists <= radius
Check for proximity of points in the mesh .
232,983
def print_csm_info ( fname ) : oqparam = readinput . get_oqparam ( fname ) csm = readinput . get_composite_source_model ( oqparam , in_memory = False ) print ( csm . info ) print ( 'See http://docs.openquake.org/oq-engine/stable/' 'effective-realizations.html for an explanation' ) rlzs_assoc = csm . info . get_rlzs_ass...
Parse the composite source model without instantiating the sources and prints information about its composition and the full logic tree
232,984
def do_build_reports ( directory ) : for cwd , dirs , files in os . walk ( directory ) : for f in sorted ( files ) : if f in ( 'job.ini' , 'job_h.ini' , 'job_haz.ini' , 'job_hazard.ini' ) : job_ini = os . path . join ( cwd , f ) logging . info ( job_ini ) try : reportwriter . build_report ( job_ini , cwd ) except Excep...
Walk the directory and builds pre - calculation reports for all the job . ini files found .
232,985
def info ( calculators , gsims , views , exports , extracts , parameters , report , input_file = '' ) : if calculators : for calc in sorted ( base . calculators ) : print ( calc ) if gsims : for gs in gsim . get_available_gsims ( ) : print ( gs ) if views : for name in sorted ( view ) : print ( name ) if exports : dic ...
Give information . You can pass the name of an available calculator a job . ini file or a zip archive with the input files .
232,986
def classical_split_filter ( srcs , srcfilter , gsims , params , monitor ) : ss = int ( os . environ . get ( 'OQ_SAMPLE_SOURCES' , 0 ) ) if ss : splits , stime = split_sources ( srcs ) srcs = readinput . random_filtered_sources ( splits , srcfilter , ss ) yield classical ( srcs , srcfilter , gsims , params , monitor ) ...
Split the given sources filter the subsources and the compute the PoEs . Yield back subtasks if the split sources contain more than maxweight ruptures .
232,987
def get_azimuth_plunge ( vect , degrees = True ) : if vect [ 0 ] > 0 : vect = - 1. * np . copy ( vect ) vect_hor = sqrt ( vect [ 1 ] ** 2. + vect [ 2 ] ** 2. ) plunge = atan2 ( - vect [ 0 ] , vect_hor ) azimuth = atan2 ( vect [ 2 ] , - vect [ 1 ] ) if degrees : icr = 180. / pi return icr * azimuth % 360. , icr * plunge...
For a given vector in USE format retrieve the azimuth and plunge
232,988
def use_to_ned ( tensor ) : return np . array ( ROT_NED_USE . T * np . matrix ( tensor ) * ROT_NED_USE )
Converts a tensor in USE coordinate sytem to NED
232,989
def ned_to_use ( tensor ) : return np . array ( ROT_NED_USE * np . matrix ( tensor ) * ROT_NED_USE . T )
Converts a tensor in NED coordinate sytem to USE
232,990
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : mean , stddevs = super ( ) . get_mean_and_stddevs ( sites , rup , dists , imt , stddev_types ) if imt == PGA ( ) : freq = 50.0 elif imt == PGV ( ) : freq = 2.0 else : freq = 1. / imt . period x1 = np . min ( [ - 0.18 + 0.17 * np . log10 ( fr...
Using a frequency dependent correction for the mean ground motion . Standard deviation is fixed .
232,991
def get_rlz ( self , rlzstr ) : r mo = re . match ( r'rlz-(\d+)' , rlzstr ) if not mo : return return self . realizations [ int ( mo . group ( 1 ) ) ]
r Get a Realization instance for a string of the form rlz - \ d +
232,992
def export ( datastore_key , calc_id = - 1 , exports = 'csv' , export_dir = '.' ) : dstore = util . read ( calc_id ) parent_id = dstore [ 'oqparam' ] . hazard_calculation_id if parent_id : dstore . parent = util . read ( parent_id ) dstore . export_dir = export_dir with performance . Monitor ( 'export' , measuremem = T...
Export an output from the datastore .
232,993
def convert_UCERFSource ( self , node ) : dirname = os . path . dirname ( self . fname ) source_file = os . path . join ( dirname , node [ "filename" ] ) if "startDate" in node . attrib and "investigationTime" in node . attrib : inv_time = float ( node [ "investigationTime" ] ) if inv_time != self . investigation_time ...
Converts the Ucerf Source node into an SES Control object
232,994
def build_idx_set ( branch_id , start_date ) : code_set = branch_id . split ( "/" ) code_set . insert ( 3 , "Rates" ) idx_set = { "sec" : "/" . join ( [ code_set [ 0 ] , code_set [ 1 ] , "Sections" ] ) , "mag" : "/" . join ( [ code_set [ 0 ] , code_set [ 1 ] , code_set [ 2 ] , "Magnitude" ] ) } idx_set [ "rate" ] = "/"...
Builds a dictionary of keys based on the branch code
232,995
def get_rupture_surface ( mag , nodal_plane , hypocenter , msr , rupture_aspect_ratio , upper_seismogenic_depth , lower_seismogenic_depth , mesh_spacing = 1.0 ) : assert ( upper_seismogenic_depth <= hypocenter . depth and lower_seismogenic_depth >= hypocenter . depth ) rdip = math . radians ( nodal_plane . dip ) azimut...
Create and return rupture surface object with given properties .
232,996
def get_ridx ( self , iloc ) : with h5py . File ( self . source_file , "r" ) as hdf5 : return hdf5 [ self . idx_set [ "geol" ] + "/RuptureIndex" ] [ iloc ]
List of rupture indices for the given iloc
232,997
def get_background_sids ( self , src_filter ) : branch_key = self . idx_set [ "grid_key" ] idist = src_filter . integration_distance ( DEFAULT_TRT ) with h5py . File ( self . source_file , 'r' ) as hdf5 : bg_locations = hdf5 [ "Grid/Locations" ] . value distances = min_geodetic_distance ( src_filter . sitecol . xyz , (...
We can apply the filtering of the background sites as a pre - processing step - this is done here rather than in the sampling of the ruptures themselves
232,998
def iter_ruptures ( self ) : assert self . orig , '%s is not fully initialized' % self for ridx in range ( self . start , self . stop ) : if self . orig . rate [ ridx ] : rup = self . get_ucerf_rupture ( ridx , self . src_filter ) if rup : yield rup
Yield ruptures for the current set of indices
232,999
def get_background_sources ( self , src_filter , sample_factor = None ) : background_sids = self . get_background_sids ( src_filter ) if sample_factor is not None : background_sids = random_filter ( background_sids , sample_factor , seed = 42 ) with h5py . File ( self . source_file , "r" ) as hdf5 : grid_loc = "/" . jo...
Turn the background model of a given branch into a set of point sources