idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
233,100
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
233,101
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
233,102
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
233,103
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 : values = list ( numpy . concatenate ( values ) ) else : values = sum (...
Parses the MultiMFD as a Node
233,104
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
233,105
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
233,106
def get_distributed_seismicity_source_nodes ( source ) : source_nodes = [ ] source_nodes . append ( Node ( "magScaleRel" , text = source . magnitude_scaling_relationship . __class__ . __name__ ) ) source_nodes . append ( Node ( "ruptAspectRatio" , text = source . rupture_aspect_ratio ) ) source_nodes . append ( obj_to_...
Returns list of nodes of attributes common to all distributed seismicity source classes
233,107
def get_fault_source_nodes ( source ) : source_nodes = [ ] source_nodes . append ( Node ( "magScaleRel" , text = source . magnitude_scaling_relationship . __class__ . __name__ ) ) source_nodes . append ( Node ( "ruptAspectRatio" , text = source . rupture_aspect_ratio ) ) source_nodes . append ( obj_to_node ( source . m...
Returns list of nodes of attributes common to all fault source classes
233,108
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 ...
Retreives a dictionary of source attributes from the source class
233,109
def build_area_source_node ( area_source ) : source_nodes = [ build_area_source_geometry ( area_source ) ] 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
233,110
def build_simple_fault_source_node ( fault_source ) : source_nodes = [ build_simple_fault_geometry ( fault_source ) ] 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
233,111
def build_complex_fault_source_node ( fault_source ) : source_nodes = [ build_complex_fault_geometry ( fault_source ) ] 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
233,112
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 ....
Writes a source model to XML .
233,113
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 .
233,114
def get_fault_type_dummy_variables ( self , rup ) : is_normal = np . array ( self . RAKE_THRESH < - rup . rake < ( 180. - self . RAKE_THRESH ) ) is_reverse = np . array ( self . RAKE_THRESH < rup . rake < ( 180. - self . RAKE_THRESH ) ) if not self . ALREADY_WARNED and is_normal . any ( ) : msg = ( 'Normal faulting not...
Fault - type classification dummy variable based on rup . rake .
233,115
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 , ...
Reads the data from the csv file
233,116
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
233,117
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 : if key in [ 'longitude' , 'latitude' ] : continue strain . data [ key...
Main writer function for the csv file
233,118
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_va...
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 .
233,119
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 = fou...
Load the configuration make each section available in a separate dict .
233,120
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
233,121
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 , f...
Compute and return mean
233,122
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
233,123
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 .
233,124
def init ( self ) : if hasattr ( self , 'data' ) : return if isinstance ( self . dstore , str ) : self . dstore = hdf5 . File ( self . dstore , 'r' ) else : self . dstore . open ( 'r' ) if self . sids is None : self . sids = self . dstore [ 'sitecol' ] . sids oq = self . dstore [ 'oqparam' ] self . imtls = oq . imtls s...
Read the poes and set the . data attribute with the hazard curves
233,125
def get_mean ( self , grp = None ) : self . init ( ) if len ( self . weights ) == 1 : 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 : dic = ( { g...
Compute the mean curve as a ProbabilityMap
233,126
def init ( self ) : if hasattr ( self , 'computers' ) : 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 ...
Initialize the computers . Should be called on the workers
233,127
def _compute_forearc_backarc_term ( self , C , sites , dists , rup ) : flag1 = np . zeros ( len ( dists . rhypo ) ) ind1 = np . logical_and ( ( dists . rhypo < 335 ) , ( dists . rhypo >= 205 ) ) flag1 [ ind1 ] = 1.0 flag2 = np . zeros ( len ( dists . rhypo ) ) ind2 = ( dists . rhypo >= 335 ) flag2 [ ind2 ] = 1.0 flag3 ...
Compute back - arc term of Equation 3
233,128
def _build_data ( self , amplification_group ) : n_levels = len ( amplification_group ) 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 ) ...
Creates the numpy array tables from the hdf5 tables
233,129
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_interpolat...
Returns the amplification factors for the given rupture and site conditions .
233,130
def get_mean_table ( self , imt , rctx ) : 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 : interpolator = interp1d ( nu...
Returns amplification factors for the mean given the rupture and intensity measure type .
233,131
def get_sigma_tables ( self , imt , rctx , stddev_types ) : output_tables = [ ] for stddev_type in stddev_types : 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 . sh...
Returns modification factors for the standard deviations given the rupture and intensity measure type .
233,132
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 : self . GMPE_TABLE = os . path . abspath ( os . path . j...
Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory .
233,133
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" ...
If amplification data is specified then reads into memory and updates the required rupture and site parameters
233,134
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
233,135
def get_mean_and_stddevs ( self , sctx , rctx , dctx , imt , stddev_types ) : imls = self . _return_tables ( rctx . mag , imt , "IMLs" ) idx = numpy . searchsorted ( self . m_w , rctx . mag ) dists = self . distances [ : , 0 , idx - 1 ] mean = self . _get_mean ( imls , dctx , dists ) stddevs = self . _get_stddevs ( dis...
Returns the mean and standard deviations
233,136
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 ...
Returns the total standard deviation of the intensity measure level from the tables .
233,137
def _return_tables ( self , mag , imt , val_type ) : if imt . name in 'PGA PGV' : 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_t...
Returns the vector of ground motions or standard deviations corresponding to the specific magnitude and intensity measure type .
233,138
def apply_magnitude_interpolation ( self , mag , iml_table ) : if mag > self . m_w [ - 1 ] : mag = self . m_w [ - 1 ] 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 ] ) ) m_interpolato...
Interpolates the tables to the required magnitude level
233,139
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_IN...
Calculate and return the mean intensity for deep soil sites .
233,140
def _get_mean_rock ( self , mag , _rake , rrup , is_reverse , imt ) : if mag <= self . NEAR_FIELD_SATURATION_MAG : C = self . COEFFS_ROCK_LOWMAG [ imt ] else : C = self . COEFFS_ROCK_HIMAG [ imt ] mag = 8.5 if mag > 8.5 else mag mean = ( C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c3' ] * ( ( 8.5 - mag ) ** 2.5 ) + C [ 'c4' ]...
Calculate and return the mean intensity for rock sites .
233,141
def _get_stddev_rock ( self , mag , imt ) : C = self . COEFFS_ROCK_STDDERR [ imt ] if mag > C [ 'maxmag' ] : return C [ 'maxsigma' ] else : return C [ 'sigma0' ] + C [ 'magfactor' ] * mag
Calculate and return total standard deviation for rock sites .
233,142
def _get_stddev_deep_soil ( self , mag , imt ) : if mag > 7 : mag = 7 C = self . COEFFS_SOIL [ imt ] return C [ 'sigma0' ] + C [ 'magfactor' ] * mag
Calculate and return total standard deviation for deep soil sites .
233,143
def zip ( what , archive_zip = '' , risk_file = '' ) : if os . path . isdir ( what ) : oqzip . zip_all ( what ) elif what . endswith ( '.xml' ) and '<logicTree' in open ( what ) . read ( 512 ) : oqzip . zip_source_model ( what , archive_zip ) elif what . endswith ( '.xml' ) and '<exposureModel' in open ( what ) . read ...
Zip into an archive one or two job . ini files with all related files
233,144
def reduce ( fname , reduction_factor ) : if fname . endswith ( '.csv' ) : with open ( fname ) as f : line = f . readline ( ) if csv . Sniffer ( ) . has_header ( line ) : header = line all_lines = f . readlines ( ) else : header = None f . seek ( 0 ) all_lines = f . readlines ( ) lines = general . random_filter ( all_l...
Produce a submodel from fname by sampling the nodes randomly . Supports source models site models and exposure models . As a special case it is also able to reduce . csv files by sampling the lines . This is a debugging utility to reduce large computations to small ones .
233,145
def downsample_mesh ( mesh , tol = 1.0 ) : idx = _find_turning_points ( mesh , tol ) if mesh . depths is not None : return RectangularMesh ( lons = mesh . lons [ : , idx ] , lats = mesh . lats [ : , idx ] , depths = mesh . depths [ : , idx ] ) else : return RectangularMesh ( lons = mesh . lons [ : , idx ] , lats = mesh...
Returns a mesh sampled at a lower resolution - if the difference in azimuth is larger than the specified tolerance a turn is assumed
233,146
def downsample_trace ( mesh , tol = 1.0 ) : idx = _find_turning_points ( mesh , tol ) if mesh . depths is not None : return numpy . column_stack ( [ mesh . lons [ 0 , idx ] , mesh . lats [ 0 , idx ] , mesh . depths [ 0 , idx ] ] ) else : return numpy . column_stack ( [ mesh . lons [ 0 , idx ] , mesh . lats [ 0 , idx ] ...
Downsamples the upper edge of a fault within a rectangular mesh retaining node points only if changes in direction on the order of tol are found
233,147
def get_ry0_distance ( self , mesh ) : top_edge = self . mesh [ 0 : 1 ] mean_strike = self . get_strike ( ) dst1 = geodetic . distance_to_arc ( top_edge . lons [ 0 , 0 ] , top_edge . lats [ 0 , 0 ] , ( mean_strike + 90. ) % 360 , mesh . lons , mesh . lats ) dst2 = geodetic . distance_to_arc ( top_edge . lons [ 0 , - 1 ...
Compute the minimum distance between each point of a mesh and the great circle arcs perpendicular to the average strike direction of the fault trace and passing through the end - points of the trace .
233,148
def get_rx_distance ( self , mesh ) : top_edge = self . mesh [ 0 : 1 ] dists = [ ] if top_edge . lons . shape [ 1 ] < 3 : i = 0 p1 = Point ( top_edge . lons [ 0 , i ] , top_edge . lats [ 0 , i ] , top_edge . depths [ 0 , i ] ) p2 = Point ( top_edge . lons [ 0 , i + 1 ] , top_edge . lats [ 0 , i + 1 ] , top_edge . depth...
Compute distance between each point of mesh and surface s great circle arc .
233,149
def get_top_edge_depth ( self ) : top_edge = self . mesh [ 0 : 1 ] if top_edge . depths is None : return 0 else : return numpy . min ( top_edge . depths )
Return minimum depth of surface s top edge .
233,150
def get_area ( self ) : mesh = self . mesh _ , _ , _ , area = mesh . get_cell_dimensions ( ) return numpy . sum ( area )
Compute area as the sum of the mesh cells area values .
233,151
def get_surface_boundaries ( self ) : mesh = self . mesh lons = numpy . concatenate ( ( mesh . lons [ 0 , : ] , mesh . lons [ 1 : , - 1 ] , mesh . lons [ - 1 , : - 1 ] [ : : - 1 ] , mesh . lons [ : - 1 , 0 ] [ : : - 1 ] ) ) lats = numpy . concatenate ( ( mesh . lats [ 0 , : ] , mesh . lats [ 1 : , - 1 ] , mesh . lats [...
Returns the boundaries in the same format as a multiplanar surface with two one - element lists of lons and lats
233,152
def get_resampled_top_edge ( self , angle_var = 0.1 ) : mesh = self . mesh top_edge = [ Point ( mesh . lons [ 0 ] [ 0 ] , mesh . lats [ 0 ] [ 0 ] , mesh . depths [ 0 ] [ 0 ] ) ] for i in range ( len ( mesh . triangulate ( ) [ 1 ] [ 0 ] ) - 1 ) : v1 = numpy . asarray ( mesh . triangulate ( ) [ 1 ] [ 0 ] [ i ] ) v2 = num...
This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction provided a certain tolerance angle .
233,153
def get_hypo_location ( self , mesh_spacing , hypo_loc = None ) : mesh = self . mesh centroid = mesh . get_middle_point ( ) if hypo_loc is None : return centroid total_len_y = ( len ( mesh . depths ) - 1 ) * mesh_spacing y_distance = hypo_loc [ 1 ] * total_len_y y_node = int ( numpy . round ( y_distance / mesh_spacing ...
The method determines the location of the hypocentre within the rupture
233,154
def viewlog ( calc_id , host = 'localhost' , port = 8000 ) : base_url = 'http://%s:%s/v1/calc/' % ( host , port ) start = 0 psize = 10 try : while True : url = base_url + '%d/log/%d:%d' % ( calc_id , start , start + psize ) rows = json . load ( urlopen ( url ) ) for row in rows : print ( ' ' . join ( row ) ) start += l...
Extract the log of the given calculation ID from the WebUI
233,155
def pickle_sequence ( objects ) : cache = { } out = [ ] for obj in objects : obj_id = id ( obj ) if obj_id not in cache : if isinstance ( obj , Pickled ) : cache [ obj_id ] = obj else : cache [ obj_id ] = Pickled ( obj ) out . append ( cache [ obj_id ] ) return out
Convert an iterable of objects into a list of pickled objects . If the iterable contains copies the pickling will be done only once . If the iterable contains objects already pickled they will not be pickled again .
233,156
def check_mem_usage ( soft_percent = None , hard_percent = None ) : soft_percent = soft_percent or config . memory . soft_mem_limit hard_percent = hard_percent or config . memory . hard_mem_limit used_mem_percent = psutil . virtual_memory ( ) . percent if used_mem_percent > hard_percent : raise MemoryError ( 'Using mor...
Display a warning if we are running out of memory
233,157
def init_workers ( ) : setproctitle ( 'oq-worker' ) signal . signal ( signal . SIGTERM , signal . SIG_DFL ) try : import prctl except ImportError : pass else : prctl . set_pdeathsig ( signal . SIGKILL )
Waiting function used to wake up the process pool
233,158
def get ( self ) : val = self . pik . unpickle ( ) if self . tb_str : etype = val . __class__ msg = '\n%s%s: %s' % ( self . tb_str , etype . __name__ , val ) if issubclass ( etype , KeyError ) : raise RuntimeError ( msg ) else : raise etype ( msg ) return val
Returns the underlying value or raise the underlying exception
233,159
def sum ( cls , iresults ) : res = object . __new__ ( cls ) res . received = [ ] res . sent = 0 for iresult in iresults : res . received . extend ( iresult . received ) res . sent += iresult . sent name = iresult . name . split ( '#' , 1 ) [ 0 ] if hasattr ( res , 'name' ) : assert res . name . split ( '#' , 1 ) [ 0 ] ...
Sum the data transfer information of a set of results
233,160
def log_percent ( self ) : done = self . total - self . todo percent = int ( float ( done ) / self . total * 100 ) if not hasattr ( self , 'prev_percent' ) : self . prev_percent = 0 self . progress ( 'Sent %s of data in %d %s task(s)' , humansize ( self . sent . sum ( ) ) , self . total , self . name ) elif percent > s...
Log the progress of the computation in percentage
233,161
def submit ( self , * args , func = None , monitor = None ) : monitor = monitor or self . monitor func = func or self . task_func if not hasattr ( self , 'socket' ) : self . __class__ . running_tasks = self . tasks self . socket = Socket ( self . receiver , zmq . PULL , 'bind' ) . __enter__ ( ) monitor . backurl = 'tcp...
Submit the given arguments to the underlying task
233,162
def reduce ( self , agg = operator . add , acc = None ) : return self . submit_all ( ) . reduce ( agg , acc )
Submit all tasks and reduce the results
233,163
def convert ( self , imtls , idx = 0 ) : curve = numpy . zeros ( 1 , imtls . dt ) for imt in imtls : curve [ imt ] = self . array [ imtls ( imt ) , idx ] return curve [ 0 ]
Convert a probability curve into a record of dtype imtls . dt .
233,164
def nbytes ( self ) : try : N , L , I = get_shape ( [ self ] ) except AllEmptyProbabilityMaps : return 0 return BYTES_PER_FLOAT * N * L * I
The size of the underlying array
233,165
def convert ( self , imtls , nsites , idx = 0 ) : curves = numpy . zeros ( nsites , imtls . dt ) for imt in curves . dtype . names : curves_by_imt = curves [ imt ] for sid in self : curves_by_imt [ sid ] = self [ sid ] . array [ imtls ( imt ) , idx ] return curves
Convert a probability map into a composite array of length nsites and dtype imtls . dt .
233,166
def filter ( self , sids ) : dic = self . __class__ ( self . shape_y , self . shape_z ) for sid in sids : try : dic [ sid ] = self [ sid ] except KeyError : pass return dic
Extracs a submap of self for the given sids .
233,167
def extract ( self , inner_idx ) : out = self . __class__ ( self . shape_y , 1 ) for sid in self : curve = self [ sid ] array = curve . array [ : , inner_idx ] . reshape ( - 1 , 1 ) out [ sid ] = ProbabilityCurve ( array ) return out
Extracts a component of the underlying ProbabilityCurves specified by the index inner_idx .
233,168
def compare ( what , imt , calc_ids , files , samplesites = 100 , rtol = .1 , atol = 1E-4 ) : sids , imtls , poes , arrays = getdata ( what , calc_ids , samplesites ) try : levels = imtls [ imt ] except KeyError : sys . exit ( '%s not found. The available IMTs are %s' % ( imt , list ( imtls ) ) ) imt2idx = { imt : i fo...
Compare the hazard curves or maps of two or more calculations
233,169
def build_filename ( filename , filetype = 'png' , resolution = 300 ) : filevals = os . path . splitext ( filename ) if filevals [ 1 ] : filetype = filevals [ 1 ] [ 1 : ] if not filetype : filetype = 'png' filename = filevals [ 0 ] + '.' + filetype if not resolution : resolution = 300 return filename , filetype , resol...
Uses the input properties to create the string of the filename
233,170
def _get_catalogue_bin_limits ( catalogue , dmag ) : mag_bins = np . arange ( float ( np . floor ( np . min ( catalogue . data [ 'magnitude' ] ) ) ) - dmag , float ( np . ceil ( np . max ( catalogue . data [ 'magnitude' ] ) ) ) + dmag , dmag ) counter = np . histogram ( catalogue . data [ 'magnitude' ] , mag_bins ) [ 0...
Returns the magnitude bins corresponing to the catalogue
233,171
def plot_depth_histogram ( catalogue , bin_width , normalisation = False , bootstrap = None , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : if ax is None : fig , ax = plt . subplots ( figsize = figure_size ) else : fig = ax . get_figure ( ) if len ( catalogue . data [ 'depth' ...
Creates a histogram of the depths in the catalogue
233,172
def plot_magnitude_depth_density ( catalogue , mag_int , depth_int , logscale = False , normalisation = False , bootstrap = None , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : if len ( catalogue . data [ 'depth' ] ) == 0 : raise ValueError ( 'No depths reported in catalogue!'...
Creates a density plot of the magnitude and depth distribution
233,173
def plot_magnitude_time_scatter ( catalogue , plot_error = False , fmt_string = 'o' , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : if ax is None : fig , ax = plt . subplots ( figsize = figure_size ) else : fig = ax . get_figure ( ) dtime = catalogue . get_decimal_time ( ) if ...
Creates a simple scatter plot of magnitude with time
233,174
def plot_magnitude_time_density ( catalogue , mag_int , time_int , completeness = None , normalisation = False , logscale = True , bootstrap = None , xlim = [ ] , ylim = [ ] , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : if ax is None : fig , ax = plt . subplots ( figsize = f...
Creates a plot of magnitude - time density
233,175
def _plot_completeness ( ax , comw , start_time , end_time ) : comw = np . array ( comw ) comp = np . column_stack ( [ np . hstack ( [ end_time , comw [ : , 0 ] , start_time ] ) , np . hstack ( [ comw [ 0 , 1 ] , comw [ : , 1 ] , comw [ - 1 , 1 ] ] ) ] ) ax . step ( comp [ : - 1 , 0 ] , comp [ 1 : , 1 ] , linestyle = '...
Adds completeness intervals to a plot
233,176
def get_completeness_adjusted_table ( catalogue , completeness , dmag , offset = 1.0E-5 , end_year = None , plot = False , figure_size = ( 8 , 6 ) , filename = None , filetype = 'png' , dpi = 300 , ax = None ) : if not end_year : end_year = catalogue . end_year mag_bins = _get_catalogue_bin_limits ( catalogue , dmag ) ...
Counts the number of earthquakes in each magnitude bin and normalises the rate to annual rates taking into account the completeness
233,177
def plot_observed_recurrence ( catalogue , completeness , dmag , end_year = None , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : if isinstance ( completeness , float ) : completeness = np . array ( [ [ np . min ( catalogue . data [ 'year' ] ) , completeness ] ] ) if not end_ye...
Plots the observed recurrence taking into account the completeness
233,178
def get_number_observations ( self ) : if isinstance ( self . data , dict ) and ( 'exx' in self . data . keys ( ) ) : return len ( self . data [ 'exx' ] ) else : return 0
Returns the number of observations in the data file
233,179
def plot_lc ( calc_id , aid = None ) : dstore = util . read ( calc_id ) dset = dstore [ 'agg_curves-rlzs' ] if aid is None : plt = make_figure ( dset . attrs [ 'return_periods' ] , dset . value ) else : sys . exit ( 'Not implemented yet' ) plt . show ( )
Plot loss curves given a calculation id and an asset ordinal .
233,180
def get_weighted_poes ( gsim , sctx , rctx , dctx , imt , imls , truncation_level , weighting = DEFAULT_WEIGHTING ) : if truncation_level is not None and truncation_level < 0 : raise ValueError ( 'truncation level must be zero, positive number ' 'or None' ) gsim . _check_imt ( imt ) adjustment = nga_west2_epistemic_adj...
This function implements the NGA West 2 GMPE epistemic uncertainty adjustment factor without re - calculating the actual GMPE each time .
233,181
def register_fields ( w ) : PARAMS_LIST = [ BASE_PARAMS , GEOMETRY_PARAMS , MFD_PARAMS ] for PARAMS in PARAMS_LIST : for _ , param , dtype in PARAMS : w . field ( param , fieldType = dtype , size = FIELD_SIZE ) PARAMS_LIST = [ RATE_PARAMS , STRIKE_PARAMS , DIP_PARAMS , RAKE_PARAMS , NPW_PARAMS , HDEPTH_PARAMS , HDW_PAR...
Register shapefile fields .
233,182
def extract_source_params ( src ) : tags = get_taglist ( src ) data = [ ] for key , param , vtype in BASE_PARAMS : if key in src . attrib : if vtype == "c" : data . append ( ( param , src . attrib [ key ] ) ) elif vtype == "f" : data . append ( ( param , float ( src . attrib [ key ] ) ) ) else : data . append ( ( param...
Extract params from source object .
233,183
def parse_complex_fault_geometry ( node ) : assert "complexFaultGeometry" in node . tag geometry = { "intermediateEdges" : [ ] } for subnode in node : crds = subnode . nodes [ 0 ] . nodes [ 0 ] . text if "faultTopEdge" in subnode . tag : geometry [ "faultTopEdge" ] = numpy . array ( [ [ crds [ i ] , crds [ i + 1 ] , cr...
Parses a complex fault geometry node returning both the attributes and parameters in a dictionary
233,184
def parse_planar_fault_geometry ( node ) : assert "planarSurface" in node . tag geometry = { "strike" : node . attrib [ "strike" ] , "dip" : node . attrib [ "dip" ] } upper_depth = numpy . inf lower_depth = 0.0 tags = get_taglist ( node ) corner_points = [ ] for locn in [ "topLeft" , "topRight" , "bottomRight" , "botto...
Parses a planar fault geometry node returning both the attributes and parameters in a dictionary
233,185
def extract_mfd_params ( src ) : tags = get_taglist ( src ) if "incrementalMFD" in tags : mfd_node = src . nodes [ tags . index ( "incrementalMFD" ) ] elif "truncGutenbergRichterMFD" in tags : mfd_node = src . nodes [ tags . index ( "truncGutenbergRichterMFD" ) ] elif "arbitraryMFD" in tags : mfd_node = src . nodes [ t...
Extracts the MFD parameters from an object
233,186
def extract_source_hypocentral_depths ( src ) : if "pointSource" not in src . tag and "areaSource" not in src . tag : hds = dict ( [ ( key , None ) for key , _ in HDEPTH_PARAMS ] ) hdsw = dict ( [ ( key , None ) for key , _ in HDW_PARAMS ] ) return hds , hdsw tags = get_taglist ( src ) hdd_nodeset = src . nodes [ tags ...
Extract source hypocentral depths .
233,187
def extract_source_planes_strikes_dips ( src ) : if "characteristicFaultSource" not in src . tag : strikes = dict ( [ ( key , None ) for key , _ in PLANES_STRIKES_PARAM ] ) dips = dict ( [ ( key , None ) for key , _ in PLANES_DIPS_PARAM ] ) return strikes , dips tags = get_taglist ( src ) surface_set = src . nodes [ ta...
Extract strike and dip angles for source defined by multiple planes .
233,188
def set_params ( w , src ) : params = extract_source_params ( src ) params . update ( extract_geometry_params ( src ) ) mfd_pars , rate_pars = extract_mfd_params ( src ) params . update ( mfd_pars ) params . update ( rate_pars ) strikes , dips , rakes , np_weights = extract_source_nodal_planes ( src ) params . update (...
Set source parameters .
233,189
def set_area_geometry ( w , src ) : assert "areaSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "areaGeometry" ) ] area_attrs = parse_area_geometry ( geometry_node ) w . poly ( parts = [ area_attrs [ "polygon" ] . tolist ( ) ] )
Set area polygon as shapefile geometry
233,190
def set_point_geometry ( w , src ) : assert "pointSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "pointGeometry" ) ] point_attrs = parse_point_geometry ( geometry_node ) w . point ( point_attrs [ "point" ] [ 0 ] , point_attrs [ "point" ] [ 1 ] )
Set point location as shapefile geometry .
233,191
def set_simple_fault_geometry ( w , src ) : assert "simpleFaultSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "simpleFaultGeometry" ) ] fault_attrs = parse_simple_fault_geometry ( geometry_node ) w . line ( parts = [ fault_attrs [ "trace" ] . tolist ( ) ] )
Set simple fault trace coordinates as shapefile geometry .
233,192
def set_simple_fault_geometry_3D ( w , src ) : assert "simpleFaultSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "simpleFaultGeometry" ) ] fault_attrs = parse_simple_fault_geometry ( geometry_node ) build_polygon_from_fault_attrs ( w , fault_attrs )
Builds a 3D polygon from a node instance
233,193
def appraise_source_model ( self ) : for src in self . sources : src_taglist = get_taglist ( src ) if "areaSource" in src . tag : self . has_area_source = True npd_node = src . nodes [ src_taglist . index ( "nodalPlaneDist" ) ] npd_size = len ( npd_node ) hdd_node = src . nodes [ src_taglist . index ( "hypoDepthDist" )...
Identify parameters defined in NRML source model file so that shapefile contains only source model specific fields .
233,194
def write ( self , destination , source_model , name = None ) : if os . path . exists ( destination ) : os . remove ( destination ) self . destination = destination if name : source_model . name = name output_source_model = Node ( "sourceModel" , { "name" : name } ) dic = groupby ( source_model . sources , operator . i...
Exports to NRML
233,195
def filter_params ( self , src_mod ) : STRIKE_PARAMS [ src_mod . num_np : ] = [ ] DIP_PARAMS [ src_mod . num_np : ] = [ ] RAKE_PARAMS [ src_mod . num_np : ] = [ ] NPW_PARAMS [ src_mod . num_np : ] = [ ] HDEPTH_PARAMS [ src_mod . num_hd : ] = [ ] HDW_PARAMS [ src_mod . num_hd : ] = [ ] PLANES_STRIKES_PARAM [ src_mod . n...
Remove params uneeded by source_model
233,196
def tostring ( node , indent = 4 , nsmap = None ) : out = io . BytesIO ( ) writer = StreamingXMLWriter ( out , indent , nsmap = nsmap ) writer . serialize ( node ) return out . getvalue ( )
Convert a node into an XML string by using the StreamingXMLWriter . This is useful for testing purposes .
233,197
def parse ( source , remove_comments = True , ** kw ) : return ElementTree . parse ( source , SourceLineParser ( ) , ** kw )
Thin wrapper around ElementTree . parse
233,198
def iterparse ( source , events = ( 'end' , ) , remove_comments = True , ** kw ) : return ElementTree . iterparse ( source , events , SourceLineParser ( ) , ** kw )
Thin wrapper around ElementTree . iterparse
233,199
def _displayattrs ( attrib , expandattrs ) : if not attrib : return '' if expandattrs : alist = [ '%s=%r' % item for item in sorted ( attrib . items ( ) ) ] else : alist = list ( attrib ) return '{%s}' % ', ' . join ( alist )
Helper function to display the attributes of a Node object in lexicographic order .