idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
44,300 | 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 . |
44,301 | 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 . |
44,302 | 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 . |
44,303 | 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 |
44,304 | 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 |
44,305 | 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 |
44,306 | 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 |
44,307 | 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 |
44,308 | 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 |
44,309 | 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 |
44,310 | 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 |
44,311 | 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 |
44,312 | 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 |
44,313 | 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 |
44,314 | 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 . |
44,315 | 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 . |
44,316 | 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 . |
44,317 | 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 . |
44,318 | 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 |
44,319 | 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 |
44,320 | 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 |
44,321 | 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 . |
44,322 | 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 . |
44,323 | 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 . |
44,324 | 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 |
44,325 | 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 . |
44,326 | 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 . |
44,327 | 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 |
44,328 | 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 . |
44,329 | 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 |
44,330 | 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 |
44,331 | 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 . |
44,332 | def parse ( source , remove_comments = True , ** kw ) : return ElementTree . parse ( source , SourceLineParser ( ) , ** kw ) | Thin wrapper around ElementTree . parse |
44,333 | def iterparse ( source , events = ( 'end' , ) , remove_comments = True , ** kw ) : return ElementTree . iterparse ( source , events , SourceLineParser ( ) , ** kw ) | Thin wrapper around ElementTree . iterparse |
44,334 | 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 . |
44,335 | def _display ( node , indent , expandattrs , expandvals , output ) : attrs = _displayattrs ( node . attrib , expandattrs ) if node . text is None or not expandvals : val = '' elif isinstance ( node . text , str ) : val = ' %s' % repr ( node . text . strip ( ) ) else : val = ' %s' % repr ( node . text ) output . write (... | Core function to display a Node object |
44,336 | def to_literal ( self ) : if not self . nodes : return ( self . tag , self . attrib , self . text , [ ] ) else : return ( self . tag , self . attrib , self . text , list ( map ( to_literal , self . nodes ) ) ) | Convert the node into a literal Python object |
44,337 | def pprint ( self , stream = None , indent = 1 , width = 80 , depth = None ) : pp . pprint ( to_literal ( self ) , stream , indent , width , depth ) | Pretty print the underlying literal Python object |
44,338 | def read_nodes ( fname , filter_elem , nodefactory = Node , remove_comments = True ) : try : for _ , el in iterparse ( fname , remove_comments = remove_comments ) : if filter_elem ( el ) : yield node_from_elem ( el , nodefactory ) el . clear ( ) except Exception : etype , exc , tb = sys . exc_info ( ) msg = str ( exc )... | Convert an XML file into a lazy iterator over Node objects satifying the given specification i . e . a function element - > boolean . |
44,339 | def node_from_xml ( xmlfile , nodefactory = Node ) : root = parse ( xmlfile ) . getroot ( ) return node_from_elem ( root , nodefactory ) | Convert a . xml file into a Node object . |
44,340 | def node_from_ini ( ini_file , nodefactory = Node , root_name = 'ini' ) : fileobj = open ( ini_file ) if isinstance ( ini_file , str ) else ini_file cfp = configparser . RawConfigParser ( ) cfp . read_file ( fileobj ) root = nodefactory ( root_name ) sections = cfp . sections ( ) for section in sections : params = dict... | Convert a . ini file into a Node object . |
44,341 | def node_to_ini ( node , output = sys . stdout ) : for subnode in node : output . write ( u'\n[%s]\n' % subnode . tag ) for name , value in sorted ( subnode . attrib . items ( ) ) : output . write ( u'%s=%s\n' % ( name , value ) ) output . flush ( ) | Convert a Node object with the right structure into a . ini file . |
44,342 | def node_copy ( node , nodefactory = Node ) : return nodefactory ( node . tag , node . attrib . copy ( ) , node . text , [ node_copy ( n , nodefactory ) for n in node ] ) | Make a deep copy of the node |
44,343 | def context ( fname , node ) : try : yield node except Exception : etype , exc , tb = sys . exc_info ( ) msg = 'node %s: %s, line %s of %s' % ( striptag ( node . tag ) , exc , getattr ( node , 'lineno' , '?' ) , fname ) raise_ ( etype , msg , tb ) | Context manager managing exceptions and adding line number of the current node and name of the current file to the error message . |
44,344 | def shorten ( self , tag ) : if tag . startswith ( '{' ) : ns , _tag = tag . rsplit ( '}' ) tag = self . nsmap . get ( ns [ 1 : ] , '' ) + _tag return tag | Get the short representation of a fully qualified tag |
44,345 | def _write ( self , text ) : spaces = ' ' * ( self . indent * self . indentlevel ) t = spaces + text . strip ( ) + '\n' if hasattr ( t , 'encode' ) : t = t . encode ( self . encoding , 'xmlcharrefreplace' ) self . stream . write ( t ) | Write text by respecting the current indentlevel |
44,346 | def start_tag ( self , name , attrs = None ) : if not attrs : self . _write ( '<%s>' % name ) else : self . _write ( '<' + name ) for ( name , value ) in sorted ( attrs . items ( ) ) : self . _write ( ' %s=%s' % ( name , quoteattr ( scientificformat ( value ) ) ) ) self . _write ( '>' ) self . indentlevel += 1 | Open an XML tag |
44,347 | def getnodes ( self , name ) : "Return the direct subnodes with name 'name'" for node in self . nodes : if striptag ( node . tag ) == name : yield node | Return the direct subnodes with name name |
44,348 | def append ( self , node ) : "Append a new subnode" if not isinstance ( node , self . __class__ ) : raise TypeError ( 'Expected Node instance, got %r' % node ) self . nodes . append ( node ) | Append a new subnode |
44,349 | def parse_bytes ( self , bytestr , isfinal = True ) : with self . _context ( ) : self . filename = None self . p . Parse ( bytestr , isfinal ) return self . _root | Parse a byte string . If the string is very large split it in chuncks and parse each chunk with isfinal = False then parse an empty chunk with isfinal = True . |
44,350 | def parse_file ( self , file_or_fname ) : with self . _context ( ) : if hasattr ( file_or_fname , 'read' ) : self . filename = getattr ( file_or_fname , 'name' , file_or_fname . __class__ . __name__ ) self . p . ParseFile ( file_or_fname ) else : self . filename = file_or_fname with open ( file_or_fname , 'rb' ) as f :... | Parse a file or a filename |
44,351 | def _get_magnitudes_from_spacing ( self , magnitudes , delta_m ) : min_mag = np . min ( magnitudes ) max_mag = np . max ( magnitudes ) if ( max_mag - min_mag ) < delta_m : raise ValueError ( 'Bin width greater than magnitude range!' ) mag_bins = np . arange ( np . floor ( min_mag ) , np . ceil ( max_mag ) , delta_m ) i... | If a single magnitude spacing is input then create the bins |
44,352 | def _merge_data ( dat1 , dat2 ) : cnt = 0 for key in dat1 : flg1 = len ( dat1 [ key ] ) > 0 flg2 = len ( dat2 [ key ] ) > 0 if flg1 != flg2 : cnt += 1 if cnt : raise Warning ( 'Cannot merge catalogues with different' + ' attributes' ) return None else : for key in dat1 : if isinstance ( dat1 [ key ] , np . ndarray ) : ... | Merge two data dictionaries containing catalogue data |
44,353 | def _get_row_str ( self , i ) : row_data = [ "{:s}" . format ( self . data [ 'eventID' ] [ i ] ) , "{:g}" . format ( self . data [ 'year' ] [ i ] ) , "{:g}" . format ( self . data [ 'month' ] [ i ] ) , "{:g}" . format ( self . data [ 'day' ] [ i ] ) , "{:g}" . format ( self . data [ 'hour' ] [ i ] ) , "{:g}" . format (... | Returns a string representation of the key information in a row |
44,354 | def load_to_array ( self , keys ) : data = np . empty ( ( len ( self . data [ keys [ 0 ] ] ) , len ( keys ) ) ) for i in range ( 0 , len ( self . data [ keys [ 0 ] ] ) ) : for j , key in enumerate ( keys ) : data [ i , j ] = self . data [ key ] [ i ] return data | This loads the data contained in the catalogue into a numpy array . The method works only for float data |
44,355 | def load_from_array ( self , keys , data_array ) : if len ( keys ) != np . shape ( data_array ) [ 1 ] : raise ValueError ( 'Key list does not match shape of array!' ) for i , key in enumerate ( keys ) : if key in self . INT_ATTRIBUTE_LIST : self . data [ key ] = data_array [ : , i ] . astype ( int ) else : self . data ... | This loads the data contained in an array into the catalogue object |
44,356 | def catalogue_mt_filter ( self , mt_table , flag = None ) : if flag is None : flag = np . ones ( self . get_number_events ( ) , dtype = bool ) for comp_val in mt_table : id0 = np . logical_and ( self . data [ 'year' ] . astype ( float ) < comp_val [ 0 ] , self . data [ 'magnitude' ] < comp_val [ 1 ] ) print ( id0 ) fla... | Filter the catalogue using a magnitude - time table . The table has two columns and n - rows . |
44,357 | def get_bounding_box ( self ) : return ( np . min ( self . data [ "longitude" ] ) , np . max ( self . data [ "longitude" ] ) , np . min ( self . data [ "latitude" ] ) , np . max ( self . data [ "latitude" ] ) ) | Returns the bounding box of the catalogue |
44,358 | def get_decimal_time ( self ) : return decimal_time ( self . data [ 'year' ] , self . data [ 'month' ] , self . data [ 'day' ] , self . data [ 'hour' ] , self . data [ 'minute' ] , self . data [ 'second' ] ) | Returns the time of the catalogue as a decimal |
44,359 | def sort_catalogue_chronologically ( self ) : dec_time = self . get_decimal_time ( ) idx = np . argsort ( dec_time ) if np . all ( ( idx [ 1 : ] - idx [ : - 1 ] ) > 0. ) : return self . select_catalogue_events ( idx ) | Sorts the catalogue into chronological order |
44,360 | def purge_catalogue ( self , flag_vector ) : id0 = np . where ( flag_vector ) [ 0 ] self . select_catalogue_events ( id0 ) self . get_number_events ( ) | Purges present catalogue with invalid events defined by flag_vector |
44,361 | def select_catalogue_events ( self , id0 ) : for key in self . data : if isinstance ( self . data [ key ] , np . ndarray ) and len ( self . data [ key ] ) > 0 : self . data [ key ] = self . data [ key ] [ id0 ] elif isinstance ( self . data [ key ] , list ) and len ( self . data [ key ] ) > 0 : self . data [ key ] = [ ... | Orders the events in the catalogue according to an indexing vector . |
44,362 | def get_depth_distribution ( self , depth_bins , normalisation = False , bootstrap = None ) : if len ( self . data [ 'depth' ] ) == 0 : raise ValueError ( 'Depths missing in catalogue' ) if len ( self . data [ 'depthError' ] ) == 0 : self . data [ 'depthError' ] = np . zeros ( self . get_number_events ( ) , dtype = flo... | Gets the depth distribution of the earthquake catalogue to return a single histogram . Depths may be normalised . If uncertainties are found in the catalogue the distrbution may be bootstrap sampled |
44,363 | def get_depth_pmf ( self , depth_bins , default_depth = 5.0 , bootstrap = None ) : if len ( self . data [ 'depth' ] ) == 0 : return PMF ( [ ( 1.0 , default_depth ) ] ) depth_hist = self . get_depth_distribution ( depth_bins , normalisation = True , bootstrap = bootstrap ) depth_hist = np . around ( depth_hist , 3 ) whi... | Returns the depth distribution of the catalogue as a probability mass function |
44,364 | def get_magnitude_depth_distribution ( self , magnitude_bins , depth_bins , normalisation = False , bootstrap = None ) : if len ( self . data [ 'depth' ] ) == 0 : raise ValueError ( 'Depths missing in catalogue' ) if len ( self . data [ 'depthError' ] ) == 0 : self . data [ 'depthError' ] = np . zeros ( self . get_numb... | Returns a 2 - D magnitude - depth histogram for the catalogue |
44,365 | def get_magnitude_time_distribution ( self , magnitude_bins , time_bins , normalisation = False , bootstrap = None ) : return bootstrap_histogram_2D ( self . get_decimal_time ( ) , self . data [ 'magnitude' ] , time_bins , magnitude_bins , xsigma = np . zeros ( self . get_number_events ( ) ) , ysigma = self . data [ 's... | Returns a 2 - D histogram indicating the number of earthquakes in a set of time - magnitude bins . Time is in decimal years! |
44,366 | def concatenate ( self , catalogue ) : atts = getattr ( self , 'data' ) attn = getattr ( catalogue , 'data' ) data = _merge_data ( atts , attn ) if data is not None : setattr ( self , 'data' , data ) for attrib in vars ( self ) : atts = getattr ( self , attrib ) attn = getattr ( catalogue , attrib ) if attrib is 'end_y... | This method attaches one catalogue to the current one |
44,367 | def expose_outputs ( dstore , owner = getpass . getuser ( ) , status = 'complete' ) : oq = dstore [ 'oqparam' ] exportable = set ( ekey [ 0 ] for ekey in export . export ) calcmode = oq . calculation_mode dskeys = set ( dstore ) & exportable dskeys . add ( 'fullreport' ) rlzs = dstore [ 'csm_info' ] . rlzs if len ( rlz... | Build a correspondence between the outputs in the datastore and the ones in the database . |
44,368 | def raiseMasterKilled ( signum , _stack ) : if OQ_DISTRIBUTE . startswith ( 'celery' ) : signal . signal ( signal . SIGINT , inhibitSigInt ) msg = 'Received a signal %d' % signum if signum in ( signal . SIGTERM , signal . SIGINT ) : msg = 'The openquake master process was killed manually' if hasattr ( signal , 'SIGHUP'... | When a SIGTERM is received raise the MasterKilled exception with an appropriate error message . |
44,369 | def job_from_file ( job_ini , job_id , username , ** kw ) : hc_id = kw . get ( 'hazard_calculation_id' ) try : oq = readinput . get_oqparam ( job_ini , hc_id = hc_id ) except Exception : logs . dbcmd ( 'finish' , job_id , 'failed' ) raise if 'calculation_mode' in kw : oq . calculation_mode = kw . pop ( 'calculation_mod... | Create a full job profile from a job config file . |
44,370 | def check_obsolete_version ( calculation_mode = 'WebUI' ) : if os . environ . get ( 'JENKINS_URL' ) or os . environ . get ( 'TRAVIS' ) : return headers = { 'User-Agent' : 'OpenQuake Engine %s;%s;%s;%s' % ( __version__ , calculation_mode , platform . platform ( ) , config . distribution . oq_distribute ) } try : req = R... | Check if there is a newer version of the engine . |
44,371 | def encode ( val ) : if isinstance ( val , ( list , tuple ) ) : return [ encode ( v ) for v in val ] elif isinstance ( val , str ) : return val . encode ( 'utf-8' ) else : return val | Encode a string assuming the encoding is UTF - 8 . |
44,372 | def raise_ ( tp , value = None , tb = None ) : if value is not None and isinstance ( tp , Exception ) : raise TypeError ( "instance exception may not have a separate value" ) if value is not None : exc = tp ( value ) else : exc = tp if exc . __traceback__ is not tb : raise exc . with_traceback ( tb ) raise exc | A function that matches the Python 2 . x raise statement . This allows re - raising exceptions with the cls value and traceback on Python 2 and 3 . |
44,373 | def plot_pyro ( calc_id = - 1 ) : import matplotlib . pyplot as p dstore = util . read ( calc_id ) sitecol = dstore [ 'sitecol' ] asset_risk = dstore [ 'asset_risk' ] . value pyro , = numpy . where ( dstore [ 'multi_peril' ] [ 'PYRO' ] == 1 ) lons = sitecol . lons [ pyro ] lats = sitecol . lats [ pyro ] p . scatter ( l... | Plot the pyroclastic cloud and the assets |
44,374 | def get_resampled_coordinates ( lons , lats ) : num_coords = len ( lons ) assert num_coords == len ( lats ) lons1 = numpy . array ( lons ) lats1 = numpy . array ( lats ) lons2 = numpy . concatenate ( ( lons1 [ 1 : ] , lons1 [ : 1 ] ) ) lats2 = numpy . concatenate ( ( lats1 [ 1 : ] , lats1 [ : 1 ] ) ) distances = geodet... | Resample polygon line segments and return the coordinates of the new vertices . This limits distortions when projecting a polygon onto a spherical surface . |
44,375 | def get_middle_point ( self ) : lons = self . mesh . lons . squeeze ( ) lats = self . mesh . lats . squeeze ( ) depths = self . mesh . depths . squeeze ( ) lon_bar = lons . mean ( ) lat_bar = lats . mean ( ) idx = np . argmin ( ( lons - lon_bar ) ** 2 + ( lats - lat_bar ) ** 2 ) return Point ( lons [ idx ] , lats [ idx... | Compute coordinates of surface middle point . |
44,376 | def modify ( self , modification , parameters ) : if modification not in self . MODIFICATIONS : raise ValueError ( 'Modification %s is not supported by %s' % ( modification , type ( self ) . __name__ ) ) meth = getattr ( self , 'modify_%s' % modification ) meth ( ** parameters ) self . check_constraints ( ) | Apply a single modification to an MFD parameters . |
44,377 | def _get_stddevs ( self , rup , arias , stddev_types , sites ) : stddevs = [ ] if rup . mag < 4.7 : tau = 0.611 elif rup . mag > 7.6 : tau = 0.475 else : tau = 0.611 - 0.047 * ( rup . mag - 4.7 ) sigma1 , sigma2 = self . _get_intra_event_sigmas ( sites ) sigma = np . copy ( sigma1 ) idx = arias >= 0.125 sigma [ idx ] =... | Return standard deviations as defined in table 1 p . 200 . |
44,378 | def _get_intra_event_sigmas ( self , sites ) : sigma1 = 1.18 * np . ones_like ( sites . vs30 ) sigma2 = 0.94 * np . ones_like ( sites . vs30 ) idx1 = np . logical_and ( sites . vs30 >= 360.0 , sites . vs30 < 760.0 ) idx2 = sites . vs30 < 360.0 sigma1 [ idx1 ] = 1.17 sigma2 [ idx1 ] = 0.93 sigma1 [ idx2 ] = 0.96 sigma2 ... | The intra - event term nonlinear and dependent on both the site class and the expected ground motion . In this case the sigma coefficients are determined from the site class as described below Eq . 14 |
44,379 | def _get_pga_on_rock ( self , C , rup , dists ) : return np . exp ( self . _get_magnitude_scaling_term ( C , rup ) + self . _get_path_scaling ( C , dists , rup . mag ) ) | Returns the median PGA on rock which is a sum of the magnitude and distance scaling |
44,380 | def modify ( self , modification , parameters ) : for src in self : src . modify ( modification , parameters ) | Apply a modification to the underlying point sources with the same parameters for all sources |
44,381 | def _compute_mean ( self , C , mag , ztor , rrup ) : gc0 = 0.2418 ci = 0.3846 gch = 0.00607 g4 = 1.7818 ge = 0.554 gm = 1.414 mean = ( gc0 + ci + ztor * gch + C [ 'gc1' ] + gm * mag + C [ 'gc2' ] * ( 10 - mag ) ** 3 + C [ 'gc3' ] * np . log ( rrup + g4 * np . exp ( ge * mag ) ) ) return mean | Compute mean value as in subroutine getGeom in hazgridXnga2 . f |
44,382 | def abort ( job_id ) : job = logs . dbcmd ( 'get_job' , job_id ) if job is None : print ( 'There is no job %d' % job_id ) return elif job . status not in ( 'executing' , 'running' ) : print ( 'Job %d is %s' % ( job . id , job . status ) ) return name = 'oq-job-%d' % job . id for p in psutil . process_iter ( ) : if p . ... | Abort the given job |
44,383 | def compose ( scripts , name = 'main' , description = None , prog = None , version = None ) : assert len ( scripts ) >= 1 , scripts parentparser = argparse . ArgumentParser ( description = description , add_help = False ) parentparser . add_argument ( '--version' , '-v' , action = 'version' , version = version ) subpar... | Collects together different scripts and builds a single script dispatching to the subparsers depending on the first argument i . e . the name of the subparser to invoke . |
44,384 | def _add ( self , name , * args , ** kw ) : argname = list ( self . argdict ) [ self . _argno ] if argname != name : raise NameError ( 'Setting argument %s, but it should be %s' % ( name , argname ) ) self . _group . add_argument ( * args , ** kw ) self . all_arguments . append ( ( args , kw ) ) self . names . append (... | Add an argument to the underlying parser and grow the list . all_arguments and the set . names |
44,385 | def arg ( self , name , help , type = None , choices = None , metavar = None , nargs = None ) : kw = dict ( help = help , type = type , choices = choices , metavar = metavar , nargs = nargs ) default = self . argdict [ name ] if default is not NODEFAULT : kw [ 'nargs' ] = nargs or '?' kw [ 'default' ] = default kw [ 'h... | Describe a positional argument |
44,386 | def opt ( self , name , help , abbrev = None , type = None , choices = None , metavar = None , nargs = None ) : kw = dict ( help = help , type = type , choices = choices , metavar = metavar , nargs = nargs ) default = self . argdict [ name ] if default is not NODEFAULT : kw [ 'default' ] = default kw [ 'metavar' ] = me... | Describe an option |
44,387 | def flg ( self , name , help , abbrev = None ) : abbrev = abbrev or '-' + name [ 0 ] longname = '--' + name . replace ( '_' , '-' ) self . _add ( name , abbrev , longname , action = 'store_true' , help = help ) | Describe a flag |
44,388 | def check_arguments ( self ) : for name , default in self . argdict . items ( ) : if name not in self . names and default is NODEFAULT : raise NameError ( 'Missing argparse specification for %r' % name ) | Make sure all arguments have a specification |
44,389 | def callfunc ( self , argv = None ) : if not self . checked : self . check_arguments ( ) self . checked = True namespace = self . parentparser . parse_args ( argv or sys . argv [ 1 : ] ) return self . func ( ** vars ( namespace ) ) | Parse the argv list and extract a dictionary of arguments which is then passed to the function underlying the script . |
44,390 | def incremental_value ( self , slip_moment , mmax , mag_value , bbar , dbar ) : delta_m = mmax - mag_value dirac_term = np . zeros_like ( mag_value ) dirac_term [ np . fabs ( delta_m ) < 1.0E-12 ] = 1.0 a_1 = self . _get_a1 ( bbar , dbar , slip_moment , mmax ) return a_1 * ( bbar * np . exp ( bbar * delta_m ) * ( delta... | Returns the incremental rate of earthquakes with M = mag_value |
44,391 | def _get_a2 ( bbar , dbar , slip_moment , mmax ) : return ( ( dbar - bbar ) / bbar ) * ( slip_moment / _scale_moment ( mmax ) ) | Returns the A2 value defined in II . 4 of Table 2 |
44,392 | def incremental_value ( self , slip_moment , mmax , mag_value , bbar , dbar ) : delta_m = mmax - mag_value a_3 = self . _get_a3 ( bbar , dbar , slip_moment , mmax ) return a_3 * bbar * ( np . exp ( bbar * delta_m ) - 1.0 ) * ( delta_m > 0.0 ) | Returns the incremental rate with Mmax = Mag_value |
44,393 | def get_mmax ( self , mfd_conf , msr , rake , area ) : if mfd_conf [ 'Maximum_Magnitude' ] : self . mmax = mfd_conf [ 'Maximum_Magnitude' ] else : self . mmax = msr . get_median_mag ( area , rake ) if ( 'Maximum_Magnitude_Uncertainty' in mfd_conf and mfd_conf [ 'Maximum_Magnitude_Uncertainty' ] ) : self . mmax_sigma = ... | Gets the mmax for the fault - reading directly from the config file or using the msr otherwise |
44,394 | def _get_magnitude_term ( self , C , mag ) : lny = C [ 'C1' ] + ( C [ 'C3' ] * ( ( 8.5 - mag ) ** 2. ) ) if mag > 6.3 : return lny + ( - C [ 'H' ] * C [ 'C5' ] ) * ( mag - 6.3 ) else : return lny + C [ 'C2' ] * ( mag - 6.3 ) | Returns the magnitude scaling term . |
44,395 | def _get_style_of_faulting_term ( self , C , rake ) : f_n , f_r = self . _get_fault_type_dummy_variables ( rake ) return C [ 'C6' ] * f_n + C [ 'C7' ] * f_r | Returns the style of faulting factor |
44,396 | def _get_stddevs ( self , C , stddev_types , nsites ) : stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : stddevs . append ( C [ 'sigma' ] + np . zeros ( nsites , dtype = float ) ) return stddevs | Compute total standard deviation see table 4 . 2 page 50 . |
44,397 | def lon_lat_bins ( bb , coord_bin_width ) : west , south , east , north = bb west = numpy . floor ( west / coord_bin_width ) * coord_bin_width east = numpy . ceil ( east / coord_bin_width ) * coord_bin_width lon_extent = get_longitudinal_extent ( west , east ) lon_bins , _ , _ = npoints_between ( west , 0 , 0 , east , ... | Define bin edges for disaggregation histograms . |
44,398 | def _digitize_lons ( lons , lon_bins ) : if cross_idl ( lon_bins [ 0 ] , lon_bins [ - 1 ] ) : idx = numpy . zeros_like ( lons , dtype = numpy . int ) for i_lon in range ( len ( lon_bins ) - 1 ) : extents = get_longitudinal_extent ( lons , lon_bins [ i_lon + 1 ] ) lon_idx = extents > 0 if i_lon != 0 : extents = get_long... | Return indices of the bins to which each value in lons belongs . Takes into account the case in which longitude values cross the international date line . |
44,399 | def mag_pmf ( matrix ) : nmags , ndists , nlons , nlats , neps = matrix . shape mag_pmf = numpy . zeros ( nmags ) for i in range ( nmags ) : mag_pmf [ i ] = numpy . prod ( [ 1. - matrix [ i , j , k , l , m ] for j in range ( ndists ) for k in range ( nlons ) for l in range ( nlats ) for m in range ( neps ) ] ) return 1... | Fold full disaggregation matrix to magnitude PMF . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.