idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
233,300 | def view_extreme_groups ( token , dstore ) : data = dstore [ 'disagg_by_grp' ] . value data . sort ( order = 'extreme_poe' ) return rst_table ( data [ : : - 1 ] ) | Show the source groups contributing the most to the highest IML |
233,301 | def zip_all ( directory ) : zips = [ ] for cwd , dirs , files in os . walk ( directory ) : if 'ssmLT.xml' in files : zips . append ( zip_source_model ( os . path . join ( cwd , 'ssmLT.xml' ) ) ) for f in files : if f . endswith ( '.xml' ) and 'exposure' in f . lower ( ) : zips . append ( zip_exposure ( os . path . join... | Zip source models and exposures recursively |
233,302 | def zip_source_model ( ssmLT , archive_zip = '' , log = logging . info ) : basedir = os . path . dirname ( ssmLT ) if os . path . basename ( ssmLT ) != 'ssmLT.xml' : orig = ssmLT ssmLT = os . path . join ( basedir , 'ssmLT.xml' ) with open ( ssmLT , 'wb' ) as f : f . write ( open ( orig , 'rb' ) . read ( ) ) archive_zi... | Zip the source model files starting from the smmLT . xml file |
233,303 | def zip_job ( job_ini , archive_zip = '' , risk_ini = '' , oq = None , log = logging . info ) : if not os . path . exists ( job_ini ) : sys . exit ( '%s does not exist' % job_ini ) archive_zip = archive_zip or 'job.zip' if isinstance ( archive_zip , str ) : if not archive_zip . endswith ( '.zip' ) : sys . exit ( '%s do... | Zip the given job . ini file into the given archive together with all related files . |
233,304 | def build_report ( job_ini , output_dir = None ) : calc_id = logs . init ( ) oq = readinput . get_oqparam ( job_ini ) if oq . calculation_mode == 'classical' : oq . calculation_mode = 'preclassical' oq . ground_motion_fields = False output_dir = output_dir or os . path . dirname ( job_ini ) from openquake . calculators... | Write a report . csv file with information about the calculation without running it |
233,305 | def add ( self , name , obj = None ) : if obj : text = '\n::\n\n' + indent ( str ( obj ) ) else : text = views . view ( name , self . dstore ) if text : title = self . title [ name ] line = '-' * len ( title ) self . text += '\n' . join ( [ '\n\n' + title , line , text ] ) | Add the view named name to the report text |
233,306 | def make_report ( self ) : oq , ds = self . oq , self . dstore for name in ( 'params' , 'inputs' ) : self . add ( name ) if 'csm_info' in ds : self . add ( 'csm_info' ) if ds [ 'csm_info' ] . source_models [ 0 ] . name != 'scenario' : self . add ( 'required_params_per_trt' ) self . add ( 'rlzs_assoc' , ds [ 'csm_info' ... | Build the report and return a restructed text string |
233,307 | def save ( self , fname ) : with open ( fname , 'wb' ) as f : f . write ( encode ( self . text ) ) | Save the report |
233,308 | def _compute_mean ( self , imt , mag , rhypo ) : mag = np . zeros_like ( rhypo ) + self . _convert_magnitude ( mag ) rhypo [ rhypo < 10 ] = 10 rhypo = np . log10 ( rhypo ) table = RectBivariateSpline ( self . MAGS , self . DISTS , self . IMTS_TABLES [ imt ] . T ) mean = table . ev ( mag , rhypo ) return mean * np . log... | Compute mean value from lookup table . |
233,309 | def _get_recurrence_model ( input_model ) : if not isinstance ( input_model , ( TruncatedGRMFD , EvenlyDiscretizedMFD , YoungsCoppersmith1985MFD ) ) : raise ValueError ( 'Recurrence model not recognised' ) annual_rates = input_model . get_annual_occurrence_rates ( ) annual_rates = np . array ( [ [ val [ 0 ] , val [ 1 ]... | Returns the annual and cumulative recurrence rates predicted by the recurrence model |
233,310 | def _check_completeness_table ( completeness , catalogue ) : if isinstance ( completeness , np . ndarray ) and np . shape ( completeness ) [ 1 ] == 2 : return completeness elif isinstance ( completeness , float ) : return np . array ( [ [ float ( np . min ( catalogue . data [ 'year' ] ) ) , completeness ] ] ) elif comp... | Generates the completeness table according to different instances |
233,311 | def plot_recurrence_model ( input_model , catalogue , completeness , dmag = 0.1 , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : annual_rates , cumulative_rates = _get_recurrence_model ( input_model ) if not catalogue . end_year : catalogue . update_end_year ( ) cent_mag , t_pe... | Plot a calculated recurrence model over an observed catalogue adjusted for time - varying completeness |
233,312 | def plot_trunc_gr_model ( aval , bval , min_mag , max_mag , dmag , catalogue = None , completeness = None , filename = None , figure_size = ( 8 , 6 ) , filetype = 'png' , dpi = 300 , ax = None ) : input_model = TruncatedGRMFD ( min_mag , max_mag , dmag , aval , bval ) if not catalogue : annual_rates , cumulative_rates ... | Plots a Gutenberg - Richter model |
233,313 | def read ( source , chatty = True , stop = None ) : vparser = ValidatingXmlParser ( validators , stop ) nrml = vparser . parse_file ( source ) if striptag ( nrml . tag ) != 'nrml' : raise ValueError ( '%s: expected a node of kind nrml, got %s' % ( source , nrml . tag ) ) xmlns = nrml . tag . split ( '}' ) [ 0 ] [ 1 : ]... | Convert a NRML file into a validated Node object . Keeps the entire tree in memory . |
233,314 | def write ( nodes , output = sys . stdout , fmt = '%.7E' , gml = True , xmlns = None ) : root = Node ( 'nrml' , nodes = nodes ) namespaces = { xmlns or NRML05 : '' } if gml : namespaces [ GML_NAMESPACE ] = 'gml:' with floatformat ( fmt ) : node_to_xml ( root , output , namespaces ) if hasattr ( output , 'mode' ) and '+... | Convert nodes into a NRML file . output must be a file object open in write mode . If you want to perform a consistency check open it in read - write mode then it will be read after creation and validated . |
233,315 | def to_string ( node ) : with io . BytesIO ( ) as f : write ( [ node ] , f ) return f . getvalue ( ) . decode ( 'utf-8' ) | Convert a node into a string in NRML format |
233,316 | def get_mean_values ( self , C , sites , rup , dists , a1100 ) : if isinstance ( a1100 , np . ndarray ) : temp_vs30 = sites . vs30 temp_z2pt5 = sites . z2pt5 else : temp_vs30 = 1100.0 * np . ones ( len ( sites . vs30 ) ) temp_z2pt5 = self . _select_basin_model ( 1100.0 ) * np . ones_like ( temp_vs30 ) return ( self . _... | Returns the mean values for a specific IMT |
233,317 | def _get_magnitude_term ( self , C , mag ) : f_mag = C [ "c0" ] + C [ "c1" ] * mag if ( mag > 4.5 ) and ( mag <= 5.5 ) : return f_mag + ( C [ "c2" ] * ( mag - 4.5 ) ) elif ( mag > 5.5 ) and ( mag <= 6.5 ) : return f_mag + ( C [ "c2" ] * ( mag - 4.5 ) ) + ( C [ "c3" ] * ( mag - 5.5 ) ) elif mag > 6.5 : return f_mag + ( ... | Returns the magnitude scaling term defined in equation 2 |
233,318 | def _get_geometric_attenuation_term ( self , C , mag , rrup ) : return ( C [ "c5" ] + C [ "c6" ] * mag ) * np . log ( np . sqrt ( ( rrup ** 2. ) + ( C [ "c7" ] ** 2. ) ) ) | Returns the geometric attenuation term defined in equation 3 |
233,319 | def _get_style_of_faulting_term ( self , C , rup ) : if ( rup . rake > 30.0 ) and ( rup . rake < 150. ) : frv = 1.0 fnm = 0.0 elif ( rup . rake > - 150.0 ) and ( rup . rake < - 30.0 ) : fnm = 1.0 frv = 0.0 else : fnm = 0.0 frv = 0.0 fflt_f = ( self . CONSTS [ "c8" ] * frv ) + ( C [ "c9" ] * fnm ) if rup . mag <= 4.5 : ... | Returns the style - of - faulting scaling term defined in equations 4 to 6 |
233,320 | def _get_hanging_wall_term ( self , C , rup , dists ) : return ( C [ "c10" ] * self . _get_hanging_wall_coeffs_rx ( C , rup , dists . rx ) * self . _get_hanging_wall_coeffs_rrup ( dists ) * self . _get_hanging_wall_coeffs_mag ( C , rup . mag ) * self . _get_hanging_wall_coeffs_ztor ( rup . ztor ) * self . _get_hanging_... | Returns the hanging wall scaling term defined in equations 7 to 16 |
233,321 | def _get_hanging_wall_coeffs_rx ( self , C , rup , r_x ) : r_1 = rup . width * cos ( radians ( rup . dip ) ) r_2 = 62.0 * rup . mag - 350.0 fhngrx = np . zeros ( len ( r_x ) ) idx = np . logical_and ( r_x >= 0. , r_x < r_1 ) fhngrx [ idx ] = self . _get_f1rx ( C , r_x [ idx ] , r_1 ) idx = r_x >= r_1 f2rx = self . _get... | Returns the hanging wall r - x caling term defined in equation 7 to 12 |
233,322 | def _get_f1rx ( self , C , r_x , r_1 ) : rxr1 = r_x / r_1 return C [ "h1" ] + ( C [ "h2" ] * rxr1 ) + ( C [ "h3" ] * ( rxr1 ** 2. ) ) | Defines the f1 scaling coefficient defined in equation 9 |
233,323 | def _get_f2rx ( self , C , r_x , r_1 , r_2 ) : drx = ( r_x - r_1 ) / ( r_2 - r_1 ) return self . CONSTS [ "h4" ] + ( C [ "h5" ] * drx ) + ( C [ "h6" ] * ( drx ** 2. ) ) | Defines the f2 scaling coefficient defined in equation 10 |
233,324 | def _get_hanging_wall_coeffs_rrup ( self , dists ) : fhngrrup = np . ones ( len ( dists . rrup ) ) idx = dists . rrup > 0.0 fhngrrup [ idx ] = ( dists . rrup [ idx ] - dists . rjb [ idx ] ) / dists . rrup [ idx ] return fhngrrup | Returns the hanging wall rrup term defined in equation 13 |
233,325 | def _get_hanging_wall_coeffs_mag ( self , C , mag ) : if mag < 5.5 : return 0.0 elif mag > 6.5 : return 1.0 + C [ "a2" ] * ( mag - 6.5 ) else : return ( mag - 5.5 ) * ( 1.0 + C [ "a2" ] * ( mag - 6.5 ) ) | Returns the hanging wall magnitude term defined in equation 14 |
233,326 | def _get_hypocentral_depth_term ( self , C , rup ) : if rup . hypo_depth <= 7.0 : fhyp_h = 0.0 elif rup . hypo_depth > 20.0 : fhyp_h = 13.0 else : fhyp_h = rup . hypo_depth - 7.0 if rup . mag <= 5.5 : fhyp_m = C [ "c17" ] elif rup . mag > 6.5 : fhyp_m = C [ "c18" ] else : fhyp_m = C [ "c17" ] + ( ( C [ "c18" ] - C [ "c... | Returns the hypocentral depth scaling term defined in equations 21 - 23 |
233,327 | def _get_fault_dip_term ( self , C , rup ) : if rup . mag < 4.5 : return C [ "c19" ] * rup . dip elif rup . mag > 5.5 : return 0.0 else : return C [ "c19" ] * ( 5.5 - rup . mag ) * rup . dip | Returns the fault dip term defined in equation 24 |
233,328 | def _get_anelastic_attenuation_term ( self , C , rrup ) : f_atn = np . zeros ( len ( rrup ) ) idx = rrup >= 80.0 f_atn [ idx ] = ( C [ "c20" ] + C [ "Dc20" ] ) * ( rrup [ idx ] - 80.0 ) return f_atn | Returns the anelastic attenuation term defined in equation 25 |
233,329 | def _get_basin_response_term ( self , C , z2pt5 ) : f_sed = np . zeros ( len ( z2pt5 ) ) idx = z2pt5 < 1.0 f_sed [ idx ] = ( C [ "c14" ] + C [ "c15" ] * float ( self . CONSTS [ "SJ" ] ) ) * ( z2pt5 [ idx ] - 1.0 ) idx = z2pt5 > 3.0 f_sed [ idx ] = C [ "c16" ] * C [ "k3" ] * exp ( - 0.75 ) * ( 1.0 - np . exp ( - 0.25 * ... | Returns the basin response term defined in equation 20 |
233,330 | def _get_shallow_site_response_term ( self , C , vs30 , pga_rock ) : vs_mod = vs30 / C [ "k1" ] f_site_g = C [ "c11" ] * np . log ( vs_mod ) idx = vs30 > C [ "k1" ] f_site_g [ idx ] = f_site_g [ idx ] + ( C [ "k2" ] * self . CONSTS [ "n" ] * np . log ( vs_mod [ idx ] ) ) idx = np . logical_not ( idx ) if np . any ( idx... | Returns the shallow site response term defined in equations 17 18 and 19 |
233,331 | def _get_stddevs ( self , C , C_PGA , rup , sites , pga1100 , stddev_types ) : tau_lnpga_b , phi_lnpga_b = self . _get_stddevs_pga ( C_PGA , rup ) num_sites = len ( sites . vs30 ) tau_lnyb = self . _get_taulny ( C , rup . mag ) phi_lnyb = np . sqrt ( self . _get_philny ( C , rup . mag ) ** 2. - self . CONSTS [ "philnAF... | Returns the inter - and intra - event and total standard deviations |
233,332 | def _get_stddevs_pga ( self , C , rup ) : tau_lnpga_b = self . _get_taulny ( C , rup . mag ) phi_lnpga_b = np . sqrt ( self . _get_philny ( C , rup . mag ) ** 2. - self . CONSTS [ "philnAF" ] ** 2. ) return tau_lnpga_b , phi_lnpga_b | Returns the inter - and intra - event coefficients for PGA |
233,333 | def _get_alpha ( self , C , vs30 , pga_rock ) : alpha = np . zeros ( len ( pga_rock ) ) idx = vs30 < C [ "k1" ] if np . any ( idx ) : af1 = pga_rock [ idx ] + self . CONSTS [ "c" ] * ( ( vs30 [ idx ] / C [ "k1" ] ) ** self . CONSTS [ "n" ] ) af2 = pga_rock [ idx ] + self . CONSTS [ "c" ] alpha [ idx ] = C [ "k2" ] * pg... | Returns the alpha the linearised functional relationship between the site amplification and the PGA on rock . Equation 31 . |
233,334 | def decimal_time ( year , month , day , hour , minute , second ) : tmo = np . ones_like ( year , dtype = int ) tda = np . ones_like ( year , dtype = int ) tho = np . zeros_like ( year , dtype = int ) tmi = np . zeros_like ( year , dtype = int ) tse = np . zeros_like ( year , dtype = float ) if any ( month < 1 ) or any ... | Returns the full time as a decimal value |
233,335 | def haversine ( lon1 , lat1 , lon2 , lat2 , radians = False , earth_rad = 6371.227 ) : if not radians : cfact = np . pi / 180. lon1 = cfact * lon1 lat1 = cfact * lat1 lon2 = cfact * lon2 lat2 = cfact * lat2 if not np . shape ( lon1 ) : nlocs1 = 1 lon1 = np . array ( [ lon1 ] ) lat1 = np . array ( [ lat1 ] ) else : nloc... | Allows to calculate geographical distance using the haversine formula . |
233,336 | def greg2julian ( year , month , day , hour , minute , second ) : year = year . astype ( float ) month = month . astype ( float ) day = day . astype ( float ) timeut = hour . astype ( float ) + ( minute . astype ( float ) / 60.0 ) + ( second / 3600.0 ) julian_time = ( ( 367.0 * year ) - np . floor ( 7.0 * ( year + np .... | Function to convert a date from Gregorian to Julian format |
233,337 | def sample_truncated_gaussian_vector ( data , uncertainties , bounds = None ) : nvals = len ( data ) if bounds : if bounds [ 0 ] is not None : lower_bound = ( bounds [ 0 ] - data ) / uncertainties else : lower_bound = - np . inf * np . ones_like ( data ) if bounds [ 1 ] is not None : upper_bound = ( bounds [ 1 ] - data... | Samples a Gaussian distribution subject to boundaries on the data |
233,338 | def hmtk_histogram_2D ( xvalues , yvalues , bins , x_offset = 1.0E-10 , y_offset = 1.0E-10 ) : xbins , ybins = ( bins [ 0 ] - x_offset , bins [ 1 ] - y_offset ) n_x = len ( xbins ) - 1 n_y = len ( ybins ) - 1 counter = np . zeros ( [ n_y , n_x ] , dtype = float ) for j in range ( n_y ) : y_idx = np . logical_and ( yval... | See the explanation for the 1D case - now applied to 2D . |
233,339 | def bootstrap_histogram_1D ( values , intervals , uncertainties = None , normalisation = False , number_bootstraps = None , boundaries = None ) : if not number_bootstraps or np . all ( np . fabs ( uncertainties < PRECISION ) ) : output = hmtk_histogram_1D ( values , intervals ) if normalisation : output = output / floa... | Bootstrap samples a set of vectors |
233,340 | def bootstrap_histogram_2D ( xvalues , yvalues , xbins , ybins , boundaries = [ None , None ] , xsigma = None , ysigma = None , normalisation = False , number_bootstraps = None ) : if ( xsigma is None and ysigma is None ) or not number_bootstraps : output = hmtk_histogram_2D ( xvalues , yvalues , bins = ( xbins , ybins... | Calculates a 2D histogram of data allowing for normalisation and bootstrap sampling |
233,341 | def area_of_polygon ( polygon ) : lon0 = np . mean ( polygon . lons ) lat0 = np . mean ( polygon . lats ) x , y = lonlat_to_laea ( polygon . lons , polygon . lats , lon0 , lat0 ) poly = geometry . Polygon ( zip ( x , y ) ) return poly . area | Returns the area of an OpenQuake polygon in square kilometres |
233,342 | def lti ( self ) : return { lt : i for i , ( lt , dt ) in enumerate ( self . loss_dt_list ( ) ) } | Dictionary extended_loss_type - > extended_loss_type index |
233,343 | def loss_maps_dt ( self , dtype = F32 ) : ltypes = self . loss_dt ( dtype ) . names lst = [ ( 'poe-%s' % poe , dtype ) for poe in self . conditional_loss_poes ] return numpy . dtype ( [ ( lt , lst ) for lt in ltypes ] ) | Return a composite data type for loss maps |
233,344 | def gmf_data_dt ( self ) : return numpy . dtype ( [ ( 'rlzi' , U16 ) , ( 'sid' , U32 ) , ( 'eid' , U64 ) , ( 'gmv' , ( F32 , ( len ( self . imtls ) , ) ) ) ] ) | Return a composite data type for the GMFs |
233,345 | def no_imls ( self ) : return all ( numpy . isnan ( ls ) . any ( ) for ls in self . imtls . values ( ) ) | Return True if there are no intensity measure levels |
233,346 | def get_kinds ( self , kind , R ) : stats = self . hazard_stats ( ) if kind == 'stats' : yield from stats return elif kind == 'rlzs' : for r in range ( R ) : yield 'rlz-%d' % r return elif kind : yield kind return if R > 1 and self . individual_curves or not stats : for r in range ( R ) : yield 'rlz-%03d' % r yield fro... | Yield rlz - 000 rlz - 001 ... mean quantile - 0 . 1 ... |
233,347 | def hazard_stats ( self ) : names = [ ] funcs = [ ] if self . mean_hazard_curves : names . append ( 'mean' ) funcs . append ( stats . mean_curve ) if self . std_hazard_curves : names . append ( 'std' ) funcs . append ( stats . std_curve ) for q in self . quantiles : names . append ( 'quantile-%s' % q ) funcs . append (... | Return a list of item with the statistical functions defined for the hazard calculation |
233,348 | def is_valid_geometry ( self ) : has_sites = ( self . sites is not None or 'sites' in self . inputs or 'site_model' in self . inputs ) if not has_sites and not self . ground_motion_fields : return True if ( 'gmfs' in self . inputs and not has_sites and not self . inputs [ 'gmfs' ] . endswith ( '.xml' ) ) : raise ValueE... | It is possible to infer the geometry only if exactly one of sites sites_csv hazard_curves_csv gmfs_csv region is set . You did set more than one or nothing . |
233,349 | def is_valid_intensity_measure_types ( self ) : if self . ground_motion_correlation_model : for imt in self . imtls : if not ( imt . startswith ( 'SA' ) or imt == 'PGA' ) : raise ValueError ( 'Correlation model %s does not accept IMT=%s' % ( self . ground_motion_correlation_model , imt ) ) if self . risk_files : return... | If the IMTs and levels are extracted from the risk models they must not be set directly . Moreover if intensity_measure_types_and_levels is set directly intensity_measure_types must not be set . |
233,350 | def is_valid_intensity_measure_levels ( self ) : invalid = self . no_imls ( ) and not self . risk_files and ( self . hazard_curves_from_gmfs or self . calculation_mode in ( 'classical' , 'disaggregation' ) ) return not invalid | In order to compute hazard curves intensity_measure_types_and_levels must be set or extracted from the risk models . |
233,351 | def is_valid_sites ( self ) : if 'site_model' in self . inputs and 'sites' in self . inputs : return False elif 'site_model' in self . inputs and self . sites : return False elif 'sites' in self . inputs and self . sites : return False elif self . sites and self . region and self . region_grid_spacing : return False el... | The sites are overdetermined |
233,352 | def is_valid_complex_fault_mesh_spacing ( self ) : rms = getattr ( self , 'rupture_mesh_spacing' , None ) if rms and not getattr ( self , 'complex_fault_mesh_spacing' , None ) : self . complex_fault_mesh_spacing = self . rupture_mesh_spacing return True | The complex_fault_mesh_spacing parameter can be None only if rupture_mesh_spacing is set . In that case it is identified with it . |
233,353 | def is_valid_optimize_same_id_sources ( self ) : if ( self . optimize_same_id_sources and 'classical' in self . calculation_mode or 'disagg' in self . calculation_mode ) : return True elif self . optimize_same_id_sources : return False else : return True | The optimize_same_id_sources can be true only in the classical calculators . |
233,354 | def check_missing ( self , param , action ) : assert action in ( 'debug' , 'info' , 'warn' , 'error' ) , action if self . inputs . get ( param ) : msg = '%s_file in %s is ignored in %s' % ( param , self . inputs [ 'job_ini' ] , self . calculation_mode ) if action == 'error' : raise InvalidFile ( msg ) else : getattr ( ... | Make sure the given parameter is missing in the job . ini file |
233,355 | def get_set_num_ruptures ( src ) : if not src . num_ruptures : t0 = time . time ( ) src . num_ruptures = src . count_ruptures ( ) dt = time . time ( ) - t0 clsname = src . __class__ . __name__ if dt > 10 : if 'Area' in clsname : logging . warning ( '%s.count_ruptures took %d seconds, perhaps the ' 'area discretization ... | Extract the number of ruptures and set it |
233,356 | def mfds2multimfd ( mfds ) : _ , kind = mfds [ 0 ] . tag . split ( '}' ) node = Node ( 'multiMFD' , dict ( kind = kind , size = len ( mfds ) ) ) lengths = None for field in mfd . multi_mfd . ASSOC [ kind ] [ 1 : ] : alias = mfd . multi_mfd . ALIAS . get ( field , field ) if field in ( 'magnitudes' , 'occurRates' ) : da... | Convert a list of MFD nodes into a single MultiMFD node |
233,357 | def update ( self , src ) : assert src . tectonic_region_type == self . trt , ( src . tectonic_region_type , self . trt ) if not src . min_mag : src . min_mag = self . min_mag . get ( self . trt ) or self . min_mag [ 'default' ] if ( not isinstance ( src , NonParametricSeismicSource ) and self . rup_interdep == 'mutex'... | Update the attributes sources min_mag max_mag according to the given source . |
233,358 | def convert_node ( self , node ) : convert = getattr ( self , 'convert_' + striptag ( node . tag ) ) return convert ( node ) | Convert the given rupture node into a hazardlib rupture depending on the node tag . |
233,359 | def convert_simpleFaultRupture ( self , node ) : mag , rake , hypocenter = self . get_mag_rake_hypo ( node ) with context ( self . fname , node ) : surfaces = [ node . simpleFaultGeometry ] rupt = source . rupture . BaseRupture ( mag = mag , rake = rake , tectonic_region_type = None , hypocenter = hypocenter , surface ... | Convert a simpleFaultRupture node . |
233,360 | def convert_multiPlanesRupture ( self , node ) : mag , rake , hypocenter = self . get_mag_rake_hypo ( node ) with context ( self . fname , node ) : surfaces = list ( node . getnodes ( 'planarSurface' ) ) rupt = source . rupture . BaseRupture ( mag = mag , rake = rake , tectonic_region_type = None , hypocenter = hypocen... | Convert a multiPlanesRupture node . |
233,361 | def get_tom ( self , node ) : if 'tom' in node . attrib : tom_cls = tom . registry [ node [ 'tom' ] ] else : tom_cls = tom . registry [ 'PoissonTOM' ] return tom_cls ( time_span = self . investigation_time , occurrence_rate = node . get ( 'occurrence_rate' ) ) | Convert the given node into a Temporal Occurrence Model object . |
233,362 | def convert_mfdist ( self , node ) : with context ( self . fname , node ) : [ mfd_node ] = [ subnode for subnode in node if subnode . tag . endswith ( ( 'incrementalMFD' , 'truncGutenbergRichterMFD' , 'arbitraryMFD' , 'YoungsCoppersmithMFD' , 'multiMFD' ) ) ] if mfd_node . tag . endswith ( 'incrementalMFD' ) : return m... | Convert the given node into a Magnitude - Frequency Distribution object . |
233,363 | def convert_npdist ( self , node ) : with context ( self . fname , node ) : npdist = [ ] for np in node . nodalPlaneDist : prob , strike , dip , rake = ( np [ 'probability' ] , np [ 'strike' ] , np [ 'dip' ] , np [ 'rake' ] ) npdist . append ( ( prob , geo . NodalPlane ( strike , dip , rake ) ) ) if not self . spinning... | Convert the given node into a Nodal Plane Distribution . |
233,364 | def convert_hpdist ( self , node ) : with context ( self . fname , node ) : hcdist = [ ( hd [ 'probability' ] , hd [ 'depth' ] ) for hd in node . hypoDepthDist ] if not self . spinning_floating : hcdist = [ ( 1 , hcdist [ 0 ] [ 1 ] ) ] return pmf . PMF ( hcdist ) | Convert the given node into a probability mass function for the hypo depth distribution . |
233,365 | def convert_areaSource ( self , node ) : geom = node . areaGeometry coords = split_coords_2d ( ~ geom . Polygon . exterior . LinearRing . posList ) polygon = geo . Polygon ( [ geo . Point ( * xy ) for xy in coords ] ) msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) area_discretization = geom . attrib . get ( 'discr... | Convert the given node into an area source object . |
233,366 | def convert_pointSource ( self , node ) : geom = node . pointGeometry lon_lat = ~ geom . Point . pos msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) return source . PointSource ( source_id = node [ 'id' ] , name = node [ 'name' ] , tectonic_region_type = node . attrib . get ( 'tectonicRegion' ) , mfd = self . conve... | Convert the given node into a point source object . |
233,367 | def convert_multiPointSource ( self , node ) : geom = node . multiPointGeometry lons , lats = zip ( * split_coords_2d ( ~ geom . posList ) ) msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) return source . MultiPointSource ( source_id = node [ 'id' ] , name = node [ 'name' ] , tectonic_region_type = node . attrib . ... | Convert the given node into a MultiPointSource object . |
233,368 | def convert_simpleFaultSource ( self , node ) : geom = node . simpleFaultGeometry msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) fault_trace = self . geo_line ( geom ) mfd = self . convert_mfdist ( node ) with context ( self . fname , node ) : try : hypo_list = valid . hypo_list ( node . hypoList ) except Attribut... | Convert the given node into a simple fault object . |
233,369 | def convert_complexFaultSource ( self , node ) : geom = node . complexFaultGeometry edges = self . geo_lines ( geom ) mfd = self . convert_mfdist ( node ) msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) with context ( self . fname , node ) : cmplx = source . ComplexFaultSource ( source_id = node [ 'id' ] , name = n... | Convert the given node into a complex fault object . |
233,370 | def convert_characteristicFaultSource ( self , node ) : char = source . CharacteristicFaultSource ( source_id = node [ 'id' ] , name = node [ 'name' ] , tectonic_region_type = node . attrib . get ( 'tectonicRegion' ) , mfd = self . convert_mfdist ( node ) , surface = self . convert_surfaces ( node . surface ) , rake = ... | Convert the given node into a characteristic fault object . |
233,371 | def convert_nonParametricSeismicSource ( self , node ) : trt = node . attrib . get ( 'tectonicRegion' ) rup_pmf_data = [ ] rups_weights = None if 'rup_weights' in node . attrib : tmp = node . attrib . get ( 'rup_weights' ) rups_weights = numpy . array ( [ float ( s ) for s in tmp . split ( ) ] ) for i , rupnode in enum... | Convert the given node into a non parametric source object . |
233,372 | def convert_sourceGroup ( self , node ) : trt = node [ 'tectonicRegion' ] srcs_weights = node . attrib . get ( 'srcs_weights' ) grp_attrs = { k : v for k , v in node . attrib . items ( ) if k not in ( 'name' , 'src_interdep' , 'rup_interdep' , 'srcs_weights' ) } sg = SourceGroup ( trt , min_mag = self . minimum_magnitu... | Convert the given node into a SourceGroup object . |
233,373 | def _check_list_weights ( parameter , name ) : if not isinstance ( parameter , list ) : raise ValueError ( '%s must be formatted with a list of tuples' % name ) weight = np . sum ( [ val [ 1 ] for val in parameter ] ) if fabs ( weight - 1. ) > 1E-8 : raise ValueError ( '%s weights do not sum to 1.0!' % name ) return pa... | Checks that the weights in a list of tuples sums to 1 . 0 |
233,374 | def build_fault_model ( self , collapse = False , rendered_msr = WC1994 ( ) , mfd_config = None ) : self . source_model = mtkSourceModel ( self . id , self . name ) for fault in self . faults : fault . generate_recurrence_models ( collapse , config = mfd_config , rendered_msr = rendered_msr ) src_model , src_weight = f... | Constructs a full fault model with epistemic uncertainty by enumerating all the possible recurrence models of each fault as separate faults with the recurrence rates multiplied by the corresponding weights . |
233,375 | def read_file ( self , start_year = None , end_year = None , use_centroid = None ) : raw_data = getlines ( self . filename ) num_lines = len ( raw_data ) if ( ( float ( num_lines ) / 5. ) - float ( num_lines / 5 ) ) > 1E-9 : raise IOError ( 'GCMT represented by 5 lines - number in file not' ' a multiple of 5!' ) self .... | Reads the file |
233,376 | def read_ndk_event ( self , raw_data , id0 ) : gcmt = GCMTEvent ( ) ndkstring = raw_data [ id0 ] . rstrip ( '\n' ) gcmt . hypocentre = self . _read_hypocentre_from_ndk_string ( ndkstring ) ndkstring = raw_data [ id0 + 1 ] . rstrip ( '\n' ) gcmt = self . _get_metadata_from_ndk_string ( gcmt , ndkstring ) ndkstring = raw... | Reads a 5 - line batch of data into a set of GCMTs |
233,377 | def _read_hypocentre_from_ndk_string ( self , linestring ) : hypo = GCMTHypocentre ( ) hypo . source = linestring [ 0 : 4 ] hypo . date = _read_date_from_string ( linestring [ 5 : 15 ] ) hypo . time = _read_time_from_string ( linestring [ 16 : 26 ] ) hypo . latitude = float ( linestring [ 27 : 33 ] ) hypo . longitude =... | Reads the hypocentre data from the ndk string to return an instance of the GCMTHypocentre class |
233,378 | def _get_metadata_from_ndk_string ( self , gcmt , ndk_string ) : gcmt . identifier = ndk_string [ : 16 ] inversion_data = re . split ( '[A-Z:]+' , ndk_string [ 17 : 61 ] ) gcmt . metadata [ 'BODY' ] = [ float ( x ) for x in inversion_data [ 1 ] . split ( ) ] gcmt . metadata [ 'SURFACE' ] = [ float ( x ) for x in invers... | Reads the GCMT metadata from line 2 of the ndk batch |
233,379 | def _get_principal_axes_from_ndk_string ( self , ndk_string , exponent ) : axes = GCMTPrincipalAxes ( ) exponent = 10. ** exponent axes . t_axis = { 'eigenvalue' : exponent * float ( ndk_string [ 0 : 8 ] ) , 'plunge' : float ( ndk_string [ 8 : 11 ] ) , 'azimuth' : float ( ndk_string [ 11 : 15 ] ) } axes . b_axis = { 'e... | Gets the principal axes from the ndk string and returns an instance of the GCMTPrincipalAxes class |
233,380 | def _get_moment_from_ndk_string ( self , ndk_string , exponent ) : moment = float ( ndk_string [ 49 : 56 ] ) * ( 10. ** exponent ) version = ndk_string [ : 3 ] magnitude = utils . moment_magnitude_scalar ( moment ) return moment , version , magnitude | Returns the moment and the moment magnitude |
233,381 | def serialise_to_nrml ( self , filename , use_defaults = False ) : source_model = self . convert_to_oqhazardlib ( PoissonTOM ( 1.0 ) , 2.0 , 2.0 , 10.0 , use_defaults = use_defaults ) write_source_model ( filename , source_model , name = self . name ) | Writes the source model to a nrml source model file given by the filename |
233,382 | def input_checks ( catalogue , config , completeness ) : if isinstance ( completeness , np . ndarray ) : if np . shape ( completeness ) [ 1 ] != 2 : raise ValueError ( 'Completeness Table incorrectly configured' ) else : cmag = completeness [ : , 1 ] ctime = completeness [ : , 0 ] elif isinstance ( completeness , float... | Performs a basic set of input checks on the data |
233,383 | def generate_trunc_gr_magnitudes ( bval , mmin , mmax , nsamples ) : sampler = np . random . uniform ( 0. , 1. , nsamples ) beta = bval * np . log ( 10. ) return ( - 1. / beta ) * ( np . log ( 1. - sampler * ( 1 - np . exp ( - beta * ( mmax - mmin ) ) ) ) ) + mmin | Generate a random list of magnitudes distributed according to a truncated Gutenberg - Richter model |
233,384 | def generate_synthetic_magnitudes ( aval , bval , mmin , mmax , nyears ) : nsamples = int ( np . round ( nyears * ( 10. ** ( aval - bval * mmin ) ) , 0 ) ) year = np . random . randint ( 0 , nyears , nsamples ) mags = generate_trunc_gr_magnitudes ( bval , mmin , mmax , nsamples ) return { 'magnitude' : mags , 'year' : ... | Generates a synthetic catalogue for a specified number of years with magnitudes distributed according to a truncated Gutenberg - Richter distribution |
233,385 | def downsample_completeness_table ( comp_table , sample_width = 0.1 , mmax = None ) : new_comp_table = [ ] for i in range ( comp_table . shape [ 0 ] - 1 ) : mvals = np . arange ( comp_table [ i , 1 ] , comp_table [ i + 1 , 1 ] , d_m ) new_comp_table . extend ( [ [ comp_table [ i , 0 ] , mval ] for mval in mvals ] ) if ... | Re - sample the completeness table to a specified sample_width |
233,386 | def reset ( yes ) : ok = yes or confirm ( 'Do you really want to destroy all your data? (y/n) ' ) if not ok : return dbpath = os . path . realpath ( os . path . expanduser ( config . dbserver . file ) ) if os . path . isfile ( dbpath ) and os . access ( dbpath , os . W_OK ) : if dbserver . get_status ( ) == 'running' :... | Remove all the datastores and the database of the current user |
233,387 | def set_status ( db , job_id , status ) : assert status in ( 'created' , 'submitted' , 'executing' , 'complete' , 'aborted' , 'failed' ) , status if status in ( 'created' , 'complete' , 'failed' , 'aborted' ) : is_running = 0 else : is_running = 1 if job_id < 0 : rows = db ( 'SELECT id FROM job ORDER BY id DESC LIMIT ?... | Set the status created executing complete failed aborted consistently with is_running . |
233,388 | def create_job ( db , datadir ) : calc_id = get_calc_id ( db , datadir ) + 1 job = dict ( id = calc_id , is_running = 1 , description = 'just created' , user_name = 'openquake' , calculation_mode = 'to be set' , ds_calc_dir = os . path . join ( '%s/calc_%s' % ( datadir , calc_id ) ) ) return db ( 'INSERT INTO job (?S) ... | Create job for the given user return it . |
233,389 | def import_job ( db , calc_id , calc_mode , description , user_name , status , hc_id , datadir ) : job = dict ( id = calc_id , calculation_mode = calc_mode , description = description , user_name = user_name , hazard_calculation_id = hc_id , is_running = 0 , status = status , ds_calc_dir = os . path . join ( '%s/calc_%... | Insert a calculation inside the database if calc_id is not taken |
233,390 | def get_job ( db , job_id , username = None ) : job_id = int ( job_id ) if job_id > 0 : dic = dict ( id = job_id ) if username : dic [ 'user_name' ] = username try : return db ( 'SELECT * FROM job WHERE ?A' , dic , one = True ) except NotFound : return if username : joblist = db ( 'SELECT * FROM job WHERE user_name=?x ... | If job_id is negative return the last calculation of the current user otherwise returns the job_id unchanged . |
233,391 | def get_calc_id ( db , datadir , job_id = None ) : calcs = datastore . get_calc_ids ( datadir ) calc_id = 0 if not calcs else calcs [ - 1 ] if job_id is None : try : job_id = db ( 'SELECT seq FROM sqlite_sequence WHERE name="job"' , scalar = True ) except NotFound : job_id = 0 return max ( calc_id , job_id ) | Return the latest calc_id by looking both at the datastore and the database . |
233,392 | def list_calculations ( db , job_type , user_name ) : jobs = db ( 'SELECT *, %s FROM job WHERE user_name=?x ' 'AND job_type=?x ORDER BY start_time' % JOB_TYPE , user_name , job_type ) out = [ ] if len ( jobs ) == 0 : out . append ( 'None' ) else : out . append ( 'job_id | status | start_time | ' ' d... | Yield a summary of past calculations . |
233,393 | def create_outputs ( db , job_id , keysize , ds_size ) : rows = [ ( job_id , DISPLAY_NAME . get ( key , key ) , key , size ) for key , size in keysize ] db ( 'UPDATE job SET size_mb=?x WHERE id=?x' , ds_size , job_id ) db . insert ( 'output' , 'oq_job_id display_name ds_key size_mb' . split ( ) , rows ) | Build a correspondence between the outputs in the datastore and the ones in the database . Also update the datastore size in the job table . |
233,394 | def finish ( db , job_id , status ) : db ( 'UPDATE job SET ?D WHERE id=?x' , dict ( is_running = False , status = status , stop_time = datetime . utcnow ( ) ) , job_id ) | Set the job columns is_running status and stop_time . |
233,395 | def del_calc ( db , job_id , user ) : job_id = int ( job_id ) dependent = db ( 'SELECT id FROM job WHERE hazard_calculation_id=?x' , job_id ) if dependent : return { "error" : 'Cannot delete calculation %d: there ' 'are calculations ' 'dependent from it: %s' % ( job_id , [ j . id for j in dependent ] ) } try : owner , ... | Delete a calculation and all associated outputs if possible . |
233,396 | def log ( db , job_id , timestamp , level , process , message ) : db ( 'INSERT INTO log (job_id, timestamp, level, process, message) ' 'VALUES (?X)' , ( job_id , timestamp , level , process , message ) ) | Write a log record in the database . |
233,397 | def get_log ( db , job_id ) : logs = db ( 'SELECT * FROM log WHERE job_id=?x ORDER BY id' , job_id ) out = [ ] for log in logs : time = str ( log . timestamp ) [ : - 4 ] out . append ( '[%s #%d %s] %s' % ( time , job_id , log . level , log . message ) ) return out | Extract the logs as a big string |
233,398 | def save_performance ( db , job_id , records ) : rows = [ ( job_id , rec [ 'operation' ] , rec [ 'time_sec' ] , rec [ 'memory_mb' ] , int ( rec [ 'counts' ] ) ) for rec in records ] db . insert ( 'performance' , 'job_id operation time_sec memory_mb counts' . split ( ) , rows ) | Save in the database the performance information about the given job . |
233,399 | def get_traceback ( db , job_id ) : log = db ( "SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'" , job_id ) if not log : return [ ] response_data = log [ - 1 ] . message . splitlines ( ) return response_data | Return the traceback of the given calculation as a list of lines . The list is empty if the calculation was successful . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.