idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
233,200 | 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 |
233,201 | 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 |
233,202 | 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 |
233,203 | 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 . |
233,204 | 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 . |
233,205 | 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 . |
233,206 | 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 . |
233,207 | 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 |
233,208 | 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 . |
233,209 | 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 |
233,210 | 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 |
233,211 | 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 |
233,212 | 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 |
233,213 | 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 |
233,214 | 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 . |
233,215 | 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 |
233,216 | 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 |
233,217 | 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 |
233,218 | 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 |
233,219 | 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 |
233,220 | 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 |
233,221 | 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 . |
233,222 | 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 |
233,223 | 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 |
233,224 | 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 |
233,225 | 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 |
233,226 | 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 . |
233,227 | 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 |
233,228 | 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 |
233,229 | 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 |
233,230 | 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! |
233,231 | 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 |
233,232 | 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 . |
233,233 | 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 . |
233,234 | 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 . |
233,235 | 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 . |
233,236 | 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 . |
233,237 | 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 . |
233,238 | 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 |
233,239 | 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 . |
233,240 | 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 . |
233,241 | 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 . |
233,242 | 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 . |
233,243 | 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 |
233,244 | 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 |
233,245 | 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 |
233,246 | 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 |
233,247 | 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 |
233,248 | 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 . |
233,249 | 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 |
233,250 | 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 |
233,251 | 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 |
233,252 | 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 |
233,253 | 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 |
233,254 | 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 . |
233,255 | 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 |
233,256 | 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 |
233,257 | 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 |
233,258 | 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 |
233,259 | 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 . |
233,260 | 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 |
233,261 | 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 . |
233,262 | 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 . |
233,263 | 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 . |
233,264 | 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 . |
233,265 | def trt_pmf ( matrices ) : ntrts , nmags , ndists , nlons , nlats , neps = matrices . shape pmf = numpy . zeros ( ntrts ) for t in range ( ntrts ) : pmf [ t ] = 1. - numpy . prod ( [ 1. - matrices [ t , i , j , k , l , m ] for i in range ( nmags ) for j in range ( ndists ) for k in range ( nlons ) for l in range ( nlat... | Fold full disaggregation matrix to tectonic region type PMF . |
233,266 | def db ( cmd , args = ( ) ) : if cmd not in commands : okcmds = '\n' . join ( '%s %s' % ( name , repr ( ' ' . join ( args ) ) if args else '' ) for name , args in sorted ( commands . items ( ) ) ) print ( 'Invalid command "%s": choose one from\n%s' % ( cmd , okcmds ) ) elif len ( args ) != len ( commands [ cmd ] ) : pr... | Run a database command |
233,267 | def mean_curve ( values , weights = None ) : if weights is None : weights = [ 1. / len ( values ) ] * len ( values ) if not isinstance ( values , numpy . ndarray ) : values = numpy . array ( values ) return numpy . average ( values , axis = 0 , weights = weights ) | Compute the mean by using numpy . average on the first axis . |
233,268 | def quantile_curve ( quantile , curves , weights = None ) : if not isinstance ( curves , numpy . ndarray ) : curves = numpy . array ( curves ) R = len ( curves ) if weights is None : weights = numpy . ones ( R ) / R else : weights = numpy . array ( weights ) assert len ( weights ) == R , ( len ( weights ) , R ) result ... | Compute the weighted quantile aggregate of a set of curves . |
233,269 | def _compute_mean ( self , C , mag , rjb ) : mean = ( C [ 'c1' ] + self . _compute_term1 ( C , mag ) + self . _compute_term2 ( C , mag , rjb ) ) return mean | Compute mean value according to equation 3 page 46 . |
233,270 | def _compute_stddevs ( self , C , mag , rjb , imt , stddev_types ) : sigma_ale_m = np . interp ( mag , [ 5.0 , 5.5 , 8.0 ] , [ C [ 'm50' ] , C [ 'm55' ] , C [ 'm80' ] ] ) sigma_ale_rjb = np . interp ( rjb , [ 5.0 , 20.0 ] , [ C [ 'r5' ] , C [ 'r20' ] ] ) sigma_ale = np . sqrt ( sigma_ale_m ** 2 + sigma_ale_rjb ** 2 ) i... | Compute total standard deviation equations 5 and 6 page 48 . |
233,271 | def BA08_AB06 ( self , vs30 , imt , pgar ) : fa = np . ones_like ( vs30 ) if np . isscalar ( vs30 ) : vs30 = np . array ( [ vs30 ] ) if np . isscalar ( pgar ) : pgar = np . array ( [ pgar ] ) vs = copy . copy ( vs30 ) vs [ vs >= 2000 ] = 1999. idx = np . where ( vs30 > 760 ) if np . size ( idx ) > 0 : C = self . COEFFS... | Computes amplification factor similarly to what is done in the 2015 version of the Canada building code . An initial version of this code was kindly provided by Michal Kolaj - Geological Survey of Canada |
233,272 | def scenario_damage ( riskinputs , riskmodel , param , monitor ) : L = len ( riskmodel . loss_types ) D = len ( riskmodel . damage_states ) E = param [ 'number_of_ground_motion_fields' ] R = riskinputs [ 0 ] . hazard_getter . num_rlzs result = dict ( d_asset = [ ] , d_event = numpy . zeros ( ( E , R , L , D ) , F64 ) ,... | Core function for a damage computation . |
233,273 | def form ( value ) : if isinstance ( value , FLOAT + INT ) : if value <= 0 : return str ( value ) elif value < .001 : return '%.3E' % value elif value < 10 and isinstance ( value , FLOAT ) : return '%.5f' % value elif value > 1000 : return '{:,d}' . format ( int ( round ( value ) ) ) elif numpy . isnan ( value ) : retu... | Format numbers in a nice way . |
233,274 | def sum_tbl ( tbl , kfield , vfields ) : pairs = [ ( n , tbl . dtype [ n ] ) for n in [ kfield ] + vfields ] dt = numpy . dtype ( pairs + [ ( 'counts' , int ) ] ) def sum_all ( group ) : vals = numpy . zeros ( 1 , dt ) [ 0 ] for rec in group : for vfield in vfields : vals [ vfield ] += rec [ vfield ] vals [ 'counts' ] ... | Aggregate a composite array and compute the totals on a given key . |
233,275 | def view_slow_sources ( token , dstore , maxrows = 20 ) : info = dstore [ 'source_info' ] . value info . sort ( order = 'calc_time' ) return rst_table ( info [ : : - 1 ] [ : maxrows ] ) | Returns the slowest sources |
233,276 | def view_contents ( token , dstore ) : try : desc = dstore [ 'oqparam' ] . description except KeyError : desc = '' data = sorted ( ( dstore . getsize ( key ) , key ) for key in dstore ) rows = [ ( key , humansize ( nbytes ) ) for nbytes , key in data ] total = '\n%s : %s' % ( dstore . filename , humansize ( os . path .... | Returns the size of the contents of the datastore and its total size |
233,277 | def view_job_info ( token , dstore ) : data = [ [ 'task' , 'sent' , 'received' ] ] for task in dstore [ 'task_info' ] : dset = dstore [ 'task_info/' + task ] if 'argnames' in dset . attrs : argnames = dset . attrs [ 'argnames' ] . split ( ) totsent = dset . attrs [ 'sent' ] sent = [ '%s=%s' % ( a , humansize ( s ) ) fo... | Determine the amount of data transferred from the controller node to the workers and back in a classical calculation . |
233,278 | def avglosses_data_transfer ( token , dstore ) : oq = dstore [ 'oqparam' ] N = len ( dstore [ 'assetcol' ] ) R = dstore [ 'csm_info' ] . get_num_rlzs ( ) L = len ( dstore . get_attr ( 'risk_model' , 'loss_types' ) ) ct = oq . concurrent_tasks size_bytes = N * R * L * 8 * ct return ( '%d asset(s) x %d realization(s) x %... | Determine the amount of average losses transferred from the workers to the controller node in a risk calculation . |
233,279 | def ebr_data_transfer ( token , dstore ) : attrs = dstore [ 'losses_by_event' ] . attrs sent = humansize ( attrs [ 'sent' ] ) received = humansize ( attrs [ 'tot_received' ] ) return 'Event Based Risk: sent %s, received %s' % ( sent , received ) | Display the data transferred in an event based risk calculation |
233,280 | def view_totlosses ( token , dstore ) : oq = dstore [ 'oqparam' ] tot_losses = dstore [ 'losses_by_asset' ] [ 'mean' ] . sum ( axis = 0 ) return rst_table ( tot_losses . view ( oq . loss_dt ( ) ) , fmt = '%.6E' ) | This is a debugging view . You can use it to check that the total losses i . e . the losses obtained by summing the average losses on all assets are indeed equal to the aggregate losses . This is a sanity check for the correctness of the implementation . |
233,281 | def view_portfolio_losses ( token , dstore ) : oq = dstore [ 'oqparam' ] loss_dt = oq . loss_dt ( ) data = portfolio_loss ( dstore ) . view ( loss_dt ) [ : , 0 ] rlzids = [ str ( r ) for r in range ( len ( data ) ) ] array = util . compose_arrays ( numpy . array ( rlzids ) , data , 'rlz' ) return rst_table ( array , fm... | The losses for the full portfolio for each realization and loss type extracted from the event loss table . |
233,282 | def view_portfolio_loss ( token , dstore ) : data = portfolio_loss ( dstore ) loss_types = list ( dstore [ 'oqparam' ] . loss_dt ( ) . names ) header = [ 'portfolio_loss' ] + loss_types mean = [ 'mean' ] + [ row . mean ( ) for row in data . T ] stddev = [ 'stddev' ] + [ row . std ( ddof = 1 ) for row in data . T ] retu... | The mean and stddev loss for the full portfolio for each loss type extracted from the event loss table averaged over the realizations |
233,283 | def view_exposure_info ( token , dstore ) : assetcol = dstore [ 'assetcol/array' ] [ : ] taxonomies = sorted ( set ( dstore [ 'assetcol' ] . taxonomies ) ) cc = dstore [ 'assetcol/cost_calculator' ] ra_flag = [ 'relative' , 'absolute' ] data = [ ( '#assets' , len ( assetcol ) ) , ( '#taxonomies' , len ( taxonomies ) ) ... | Display info about the exposure model |
233,284 | def view_fullreport ( token , dstore ) : from openquake . calculators . reportwriter import ReportWriter return ReportWriter ( dstore ) . make_report ( ) | Display an . rst report about the computation |
233,285 | def performance_view ( dstore ) : data = sorted ( dstore [ 'performance_data' ] , key = operator . itemgetter ( 0 ) ) out = [ ] for operation , group in itertools . groupby ( data , operator . itemgetter ( 0 ) ) : counts = 0 time = 0 mem = 0 for _operation , time_sec , memory_mb , counts_ in group : counts += counts_ t... | Returns the performance view as a numpy array . |
233,286 | def stats ( name , array , * extras ) : std = numpy . nan if len ( array ) == 1 else numpy . std ( array , ddof = 1 ) return ( name , numpy . mean ( array ) , std , numpy . min ( array ) , numpy . max ( array ) , len ( array ) ) + extras | Returns statistics from an array of numbers . |
233,287 | def view_num_units ( token , dstore ) : taxo = dstore [ 'assetcol/tagcol/taxonomy' ] . value counts = collections . Counter ( ) for asset in dstore [ 'assetcol' ] : counts [ taxo [ asset [ 'taxonomy' ] ] ] += asset [ 'number' ] data = sorted ( counts . items ( ) ) data . append ( ( '*ALL*' , sum ( d [ 1 ] for d in data... | Display the number of units by taxonomy |
233,288 | def view_assets_by_site ( token , dstore ) : taxonomies = dstore [ 'assetcol/tagcol/taxonomy' ] . value assets_by_site = dstore [ 'assetcol' ] . assets_by_site ( ) data = [ 'taxonomy mean stddev min max num_sites num_assets' . split ( ) ] num_assets = AccumDict ( ) for assets in assets_by_site : num_assets += { k : [ l... | Display statistical information about the distribution of the assets |
233,289 | def view_required_params_per_trt ( token , dstore ) : csm_info = dstore [ 'csm_info' ] tbl = [ ] for grp_id , trt in sorted ( csm_info . grp_by ( "trt" ) . items ( ) ) : gsims = csm_info . gsim_lt . get_gsims ( trt ) maker = ContextMaker ( trt , gsims ) distances = sorted ( maker . REQUIRES_DISTANCES ) siteparams = sor... | Display the parameters needed by each tectonic region type |
233,290 | def view_global_hcurves ( token , dstore ) : oq = dstore [ 'oqparam' ] nsites = len ( dstore [ 'sitecol' ] ) rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) mean = getters . PmapGetter ( dstore , rlzs_assoc ) . get_mean ( ) array = calc . convert_to_array ( mean , nsites , oq . imtls ) res = numpy . zeros ( 1 ,... | Display the global hazard curves for the calculation . They are used for debugging purposes when comparing the results of two calculations . They are the mean over the sites of the mean hazard curves . |
233,291 | def view_dupl_sources_time ( token , dstore ) : info = dstore [ 'source_info' ] items = sorted ( group_array ( info . value , 'source_id' ) . items ( ) ) tbl = [ ] tot_time = 0 for source_id , records in items : if len ( records ) > 1 : calc_time = records [ 'calc_time' ] . sum ( ) tot_time += calc_time + records [ 'sp... | Display the time spent computing duplicated sources |
233,292 | def view_global_poes ( token , dstore ) : tbl = [ ] imtls = dstore [ 'oqparam' ] . imtls header = [ 'grp_id' ] + [ str ( poe ) for poe in imtls . array ] for grp in sorted ( dstore [ 'poes' ] ) : poes = dstore [ 'poes/' + grp ] nsites = len ( poes ) site_avg = sum ( poes [ sid ] . array for sid in poes ) / nsites gsim_... | Display global probabilities averaged on all sites and all GMPEs |
233,293 | def view_global_hmaps ( token , dstore ) : oq = dstore [ 'oqparam' ] dt = numpy . dtype ( [ ( '%s-%s' % ( imt , poe ) , F32 ) for imt in oq . imtls for poe in oq . poes ] ) array = dstore [ 'hmaps/mean' ] . value . view ( dt ) [ : , 0 ] res = numpy . zeros ( 1 , array . dtype ) for name in array . dtype . names : res [... | Display the global hazard maps for the calculation . They are used for debugging purposes when comparing the results of two calculations . They are the mean over the sites of the mean hazard maps . |
233,294 | def view_global_gmfs ( token , dstore ) : imtls = dstore [ 'oqparam' ] . imtls row = dstore [ 'gmf_data/data' ] [ 'gmv' ] . mean ( axis = 0 ) return rst_table ( [ row ] , header = imtls ) | Display GMFs averaged on everything for debugging purposes |
233,295 | def view_mean_disagg ( token , dstore ) : tbl = [ ] for key , dset in sorted ( dstore [ 'disagg' ] . items ( ) ) : vals = [ ds . value . mean ( ) for k , ds in sorted ( dset . items ( ) ) ] tbl . append ( [ key ] + vals ) header = [ 'key' ] + sorted ( dset ) return rst_table ( sorted ( tbl ) , header = header ) | Display mean quantities for the disaggregation . Useful for checking differences between two calculations . |
233,296 | def view_elt ( token , dstore ) : oq = dstore [ 'oqparam' ] R = len ( dstore [ 'csm_info' ] . rlzs ) dic = group_array ( dstore [ 'losses_by_event' ] . value , 'rlzi' ) header = oq . loss_dt ( ) . names tbl = [ ] for rlzi in range ( R ) : if rlzi in dic : tbl . append ( dic [ rlzi ] [ 'loss' ] . mean ( axis = 0 ) ) els... | Display the event loss table averaged by event |
233,297 | def view_pmap ( token , dstore ) : grp = token . split ( ':' ) [ 1 ] pmap = { } rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) pgetter = getters . PmapGetter ( dstore , rlzs_assoc ) pmap = pgetter . get_mean ( grp ) return str ( pmap ) | Display the mean ProbabilityMap associated to a given source group name |
233,298 | def view_act_ruptures_by_src ( token , dstore ) : data = dstore [ 'ruptures' ] . value [ [ 'srcidx' , 'serial' ] ] counts = sorted ( countby ( data , 'srcidx' ) . items ( ) , key = operator . itemgetter ( 1 ) , reverse = True ) src_info = dstore [ 'source_info' ] . value [ [ 'grp_id' , 'source_id' ] ] table = [ [ 'src_... | Display the actual number of ruptures by source in event based calculations |
233,299 | def view_dupl_sources ( token , dstore ) : fields = [ 'source_id' , 'code' , 'gidx1' , 'gidx2' , 'num_ruptures' ] dic = group_array ( dstore [ 'source_info' ] . value [ fields ] , 'source_id' ) sameid = [ ] dupl = [ ] for source_id , group in dic . items ( ) : if len ( group ) > 1 : sources = [ ] for rec in group : geo... | Show the sources with the same ID and the truly duplicated sources |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.