Search is not available for this dataset
text stringlengths 75 104k |
|---|
def select_catalogue_events(self, id0):
'''
Orders the events in the catalogue according to an indexing vector
:param np.ndarray id0:
Pointer array indicating the locations of selected events
'''
for key in self.data.keys():
if isinstance(
... |
def gcmt_to_simple_array(self, centroid_location=True):
"""
Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients (for soil amplification)
... |
def _compute_linear_magnitude_term(self, C, mag):
"""
Compute and return second term in equations (1a)
and (1b), pages 2981 and 2982, respectively.
"""
if mag <= self.c1:
# this is the second term in eq. (1a), p. 2981
return C['a2'] * (mag - self.c1)
... |
def from_shapefile(output, input_shp_files, validate):
"""
Convert multiple ESRI Shapefile(s) into a single NRML source model file.
"""
input_parser = shapefileparser.ShapefileParser()
source_model = input_parser.read(input_shp_files[0], validate)
for f in input_shp_files[1:]:
source_mod... |
def _compute_magnitude(self, rup, C):
"""
Compute the first term of the equation described on p. 199:
``b1 + b2 * M + b3 * M**2``
"""
return C['b1'] + (C['b2'] * rup.mag) + (C['b3'] * (rup.mag ** 2)) |
def _compute_distance(self, rup, dists, imt, C):
"""
Compute the second term of the equation described on p. 199:
``(b4 + b5 * M) * log(sqrt(Rjb ** 2 + b6 ** 2))``
"""
return (((C['b4'] + C['b5'] * rup.mag)
* np.log10((np.sqrt(dists.rjb ** 2.0 + C['b6'] ** 2.0))... |
def _get_site_amplification(self, sites, imt, C):
"""
Compute the third term of the equation described on p. 199:
``b7 * Ss + b8 * Sa``
"""
Ss, Sa = self._get_site_type_dummy_variables(sites)
return (C['b7'] * Ss) + (C['b8'] * Sa) |
def _get_site_type_dummy_variables(self, sites):
"""
Get site type dummy variables, ``Ss`` (for soft and stiff soil sites)
and ``Sa`` (for rock sites).
"""
Ss = np.zeros((len(sites.vs30),))
Sa = np.zeros((len(sites.vs30),))
# Soft soil; Vs30 < 360 m/s. Page 199.
... |
def _get_mechanism(self, sites, rup, imt, C):
"""
Compute the fourth term of the equation described on p. 199:
``b9 * Fn + b10 * Fr``
"""
Fn, Fr = self._get_fault_type_dummy_variables(sites, rup, imt)
return (C['b9'] * Fn) + (C['b10'] * Fr) |
def _get_fault_type_dummy_variables(self, sites, rup, imt):
"""
Same classification of SadighEtAl1997. Akkar and Bommer 2010 is based
on Akkar and Bommer 2007b; read Strong-Motion Dataset and Record
Processing on p. 514 (Akkar and Bommer 2007b).
"""
Fn, Fr = 0, 0
... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
sites.vs30 = 600 * np.ones(len(sites.vs30))
mean, stddevs = ... |
def mesh(self):
"""
:returns: mesh corresponding to the whole multi surface
"""
meshes = [surface.mesh for surface in self.surfaces]
lons = numpy.concatenate([m.lons for m in meshes])
lats = numpy.concatenate([m.lats for m in meshes])
depths = numpy.concatenate([m... |
def _get_edge_set(self, tol=0.1):
"""
Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance
"""
edges = []
for surface in self.surfaces:
if isinstance(surface, GriddedSurface):
... |
def get_min_distance(self, mesh):
"""
For each point in ``mesh`` compute the minimum distance to each
surface element and return the smallest value.
See :meth:`superclass method
<.base.BaseSurface.get_min_distance>`
for spec of input and result values.
"""
... |
def get_closest_points(self, mesh):
"""
For each point in ``mesh`` find the closest surface element, and return
the corresponding closest point.
See :meth:`superclass method
<.base.BaseSurface.get_closest_points>`
for spec of input and result values.
"""
... |
def get_top_edge_depth(self):
"""
Compute top edge depth of each surface element and return area-weighted
average value (in km).
"""
areas = self._get_areas()
depths = numpy.array(
[surf.get_top_edge_depth() for surf in self.surfaces])
return numpy.sum... |
def get_strike(self):
"""
Compute strike of each surface element and return area-weighted average
value (in range ``[0, 360]``) using formula from:
http://en.wikipedia.org/wiki/Mean_of_circular_quantities
Note that the original formula has been adapted to compute a weighted
... |
def get_dip(self):
"""
Compute dip of each surface element and return area-weighted average
value (in range ``(0, 90]``).
Given that dip values are constrained in the range (0, 90], the simple
formula for weighted mean is used.
"""
areas = self._get_areas()
... |
def get_width(self):
"""
Compute width of each surface element, and return area-weighted
average value (in km).
"""
areas = self._get_areas()
widths = numpy.array([surf.get_width() for surf in self.surfaces])
return numpy.sum(areas * widths) / numpy.sum(areas) |
def get_bounding_box(self):
"""
Compute bounding box for each surface element, and then return
the bounding box of all surface elements' bounding boxes.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the b... |
def get_middle_point(self):
"""
If :class:`MultiSurface` is defined by a single surface, simply
returns surface's middle point, otherwise find surface element closest
to the surface's bounding box centroid and return corresponding
middle point.
Note that the concept of m... |
def _get_areas(self):
"""
Return surface elements area values in a numpy array.
"""
if self.areas is None:
self.areas = []
for surf in self.surfaces:
self.areas.append(surf.get_area())
self.areas = numpy.array(self.areas)
retur... |
def _get_cartesian_edge_set(self):
"""
For the GC2 calculations a set of cartesian representations of the
fault edges are needed. In this present case we use a common cartesian
framework for all edges, as opposed to defining a separate orthographic
projection per edge
"""... |
def _setup_gc2_framework(self):
"""
This method establishes the GC2 framework for a multi-segment
(and indeed multi-typology) case based on the description in
Spudich & Chiou (2015) - see section on Generalized Coordinate
System for Multiple Rupture Traces
"""
# G... |
def _get_gc2_coordinates_for_rupture(self, edge_sets):
"""
Calculates the GC2 coordinates for the nodes of the upper edge of the
fault
"""
# Establish GC2 length - for use with Ry0
rup_gc2t, rup_gc2u = self.get_generalised_coordinates(
edge_sets[:, 0], edge_s... |
def _get_ut_i(self, seg, sx, sy):
"""
Returns the U and T coordinate for a specific trace segment
:param seg:
End points of the segment edge
:param sx:
Sites longitudes rendered into coordinate system
:param sy:
Sites latitudes rendered into... |
def get_generalised_coordinates(self, lons, lats):
"""
Transforms the site positions into the generalised coordinate form
described by Spudich and Chiou (2015) for the multi-rupture and/or
discordant case
Spudich, Paul and Chiou, Brian (2015) Strike-parallel and strike-normal
... |
def get_rx_distance(self, mesh):
"""
For each point determine the corresponding rx distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_rx_distance>`
for spec of input and result values.
"""
# If the GC2 calculations h... |
def get_ry0_distance(self, mesh):
"""
For each point determine the corresponding Ry0 distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_ry0_distance>`
for spec of input and result values.
"""
# If the GC2 calculation... |
def from_model_files(cls, limits, input_model, investigation_time=1.0,
simple_mesh_spacing=1.0, complex_mesh_spacing=5.0,
mfd_width=0.1, area_discretisation=10.0):
"""
Reads the hazard model from a file
:param list limits:
Grid conf... |
def get_rates(self, mmin, mmax=np.inf):
"""
Returns the cumulative rates greater than Mmin
:param float mmin:
Minimum magnitude
"""
nsrcs = self.number_sources()
for iloc, source in enumerate(self.source_model):
print("Source Number %s of %s, Name... |
def _get_point_location(self, location):
"""
Returns the location in the output grid corresponding to the cell in
which the epicentre lays
:param location:
Source hypocentre as instance of :class:
openquake.hazardlib.geo.point.Point
:returns:
... |
def _get_point_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a point source
:param source:
Point source as instance of :class:
openquake.hazardlib.source.point.PointSource
:param float mmin:
Minimum Magnitude
:param float mmax... |
def _get_area_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource
"""
poi... |
def _get_fault_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a simple or complex fault source
:param source:
Fault source as instance of :class:
openquake.hazardlib.source.simple_fault.SimpleFaultSource or
openquake.hazardlib.source.complex_f... |
def _get_point_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a point source
:param source:
Point source as instance of :class:
openquake.hazardlib.source.point.PointSource
:param float mmin:
Minimum Magnitude
:param float mmax... |
def _get_fault_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a simple or complex fault source
:param source:
Fault source as instance of :class:
openquake.hazardlib.source.simple_fault.SimpleFaultSource or
openquake.hazardlib.source.complex_f... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... |
def _get_distance_scaling(self, C, mag, rhypo):
"""
Returns the distance scalig term
"""
return (C["a3"] * np.log(rhypo)) + (C["a4"] + C["a5"] * mag) * rhypo |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coefficients specific to required
# ... |
def _get_distance_scaling_term(self, C, rjb, mag):
"""
Returns the distance scaling component of the model
Equation 10, Page 63
"""
# Depth adjusted distance, equation 11 (Page 63)
rval = np.sqrt(rjb ** 2.0 + C["c11"] ** 2.0)
f_0, f_1, f_2 = self._get_distance_seg... |
def _get_distance_segment_coefficients(self, rval):
"""
Returns the coefficients describing the distance attenuation shape
for three different distance bins, equations 12a - 12c
"""
# Get distance segment ends
nsites = len(rval)
# Equation 12a
f_0 = np.log... |
def collect_files(dirpath, cond=lambda fullname: True):
"""
Recursively collect the files contained inside dirpath.
:param dirpath: path to a readable directory
:param cond: condition on the path to collect the file
"""
files = []
for fname in os.listdir(dirpath):
fullname = os.path... |
def extract_from_zip(path, candidates):
"""
Given a zip archive and a function to detect the presence of a given
filename, unzip the archive into a temporary directory and return the
full path of the file. Raise an IOError if the file cannot be found
within the archive.
:param path: pathname of... |
def get_params(job_inis, **kw):
"""
Parse one or more INI-style config files.
:param job_inis:
List of configuration files (or list containing a single zip archive)
:param kw:
Optionally override some parameters
:returns:
A dictionary of parameters
"""
input_zip = No... |
def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1,
**kw):
"""
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find... |
def get_csv_header(fname, sep=','):
"""
:param fname: a CSV file
:param sep: the separator (default comma)
:returns: the first line of fname
"""
with open(fname, encoding='utf-8-sig') as f:
return next(f).split(sep) |
def read_csv(fname, sep=','):
"""
:param fname: a CSV file with an header and float fields
:param sep: separato (default the comma)
:return: a structured array of floats
"""
with open(fname, encoding='utf-8-sig') as f:
header = next(f).strip().split(sep)
dt = numpy.dtype([(h, num... |
def get_mesh(oqparam):
"""
Extract the mesh of points to compute from the sites,
the sites_csv, or the region.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
"""
global pmap, exposure, gmfs, eids
if 'exposure' in oqparam.inputs and exposure is None:
... |
def get_site_model(oqparam):
"""
Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ...
"""
req_site_params = get_gsim_lt(oqparam).req_site_params
... |
def get_site_collection(oqparam):
"""
Returns a SiteCollection instance by looking at the points and the
site model defined by the configuration parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
"""
mesh = get_mesh(oqparam)
req_site_params = g... |
def get_gsim_lt(oqparam, trts=['*']):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param trts:
a sequence of tectonic region types as strings; trts=['*']
means that there is no filtering
:returns:
a GsimLogicTree instance obtained by ... |
def get_rlzs_by_gsim(oqparam):
"""
Return an ordered dictionary gsim -> [realization index]. Work for
gsim logic trees with a single tectonic region type.
"""
cinfo = source.CompositionInfo.fake(get_gsim_lt(oqparam))
ra = cinfo.get_rlzs_assoc()
dic = {}
for rlzi, gsim_by_trt in enumerate... |
def get_rupture(oqparam):
"""
Read the `rupture_model` file and by filter the site collection
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an hazardlib rupture
"""
rup_model = oqparam.inputs['rupture_model']
[rup_node] = nrml.read(r... |
def get_source_model_lt(oqparam, validate=True):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
a :class:`openquake.commonlib.logictree.SourceModelLogicTree`
instance
"""
fname = oqparam.inputs.get('source_model_logic_tree')
if... |
def check_nonparametric_sources(fname, smodel, investigation_time):
"""
:param fname:
full path to a source model file
:param smodel:
source model object
:param investigation_time:
investigation_time to compare with in the case of
nonparametric sources
:returns:
... |
def store_sm(smodel, filename, monitor):
"""
:param smodel: a :class:`openquake.hazardlib.nrml.SourceModel` instance
:param filename: path to an hdf5 file (cache_XXX.hdf5)
:param monitor: a Monitor instance with an .hdf5 attribute
"""
h5 = monitor.hdf5
with monitor('store source model'):
... |
def get_source_models(oqparam, gsim_lt, source_model_lt, monitor,
in_memory=True, srcfilter=None):
"""
Build all the source models generated by the logic tree.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param gsim_lt:
a :class:`o... |
def random_filtered_sources(sources, srcfilter, seed):
"""
:param sources: a list of sources
:param srcfilte: a SourceFilter instance
:param seed: a random seed
:returns: an empty list or a list with a single filtered source
"""
random.seed(seed)
while sources:
src = random.choic... |
def get_composite_source_model(oqparam, monitor=None, in_memory=True,
srcfilter=SourceFilter(None, {})):
"""
Parse the XML and build a complete composite source model in memory.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param m... |
def get_risk_model(oqparam):
"""
Return a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
"""
tmap = _get_taxonomy_mapping(oqparam.inputs)
fragdict = get_risk_models(oqparam, 'fragility')
v... |
def get_exposure(oqparam):
"""
Read the full exposure in memory and build a list of
:class:`openquake.risklib.asset.Asset` instances.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an :class:`Exposure` instance or a compatible AssetCollection... |
def get_sitecol_assetcol(oqparam, haz_sitecol=None, cost_types=()):
"""
:param oqparam: calculation parameters
:param haz_sitecol: the hazard site collection
:param cost_types: the expected cost types
:returns: (site collection, asset collection, discarded)
"""
global exposure
asset_haza... |
def get_pmap_from_csv(oqparam, fnames):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fnames:
a space-separated list of .csv relative filenames
:returns:
the site mesh and the hazard curves read by the .csv files
"""
if not oqpar... |
def get_pmap_from_nrml(oqparam, fname):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fname:
an XML file containing hazard curves
:returns:
site mesh, curve array
"""
hcurves_by_imt = {}
oqparam.hazard_imtls = imtls = {}
... |
def get_scenario_from_nrml(oqparam, fname):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fname:
the NRML files containing the GMFs
:returns:
a pair (eids, gmf array)
"""
if not oqparam.imtls:
oqparam.set_risk_imtls(get_r... |
def get_mesh_hcurves(oqparam):
"""
Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site
"""
i... |
def reduce_source_model(smlt_file, source_ids, remove=True):
"""
Extract sources from the composite source model
"""
found = 0
to_remove = []
for paths in logictree.collect_info(smlt_file).smpaths.values():
for path in paths:
logging.info('Reading %s', path)
root ... |
def get_input_files(oqparam, hazard=False):
"""
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: input path names in a specific order
"""
fnames = [] # files entering in the checksum
for key in oqparam.inputs:
fname = oqparam.input... |
def get_checksum32(oqparam, hazard=False):
"""
Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume
"""
# NB: using adler32 & 0xffffffff is the documented way... |
def smart_save(dbpath, archive, calc_id):
"""
Make a copy of the db, remove the incomplete jobs and add the copy
to the archive
"""
tmpdir = tempfile.mkdtemp()
newdb = os.path.join(tmpdir, os.path.basename(dbpath))
shutil.copy(dbpath, newdb)
try:
with sqlite3.connect(newdb) as co... |
def dump(archive, calc_id=0, user=None):
"""
Dump the openquake database and all the complete calculations into a zip
file. In a multiuser installation must be run as administrator.
"""
t0 = time.time()
assert archive.endswith('.zip'), archive
getfnames = 'select ds_calc_dir || ".hdf5" from ... |
def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta):
'''
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:... |
def _get_a1_value(bbar, dbar, slip, beta, mmax):
"""
Returns the A1 value defined in I.9 (Table 2)
"""
return ((dbar - bbar) / dbar) * (slip / beta) *\
np.exp(-(dbar / 2.) * mmax) |
def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta):
'''
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:... |
def _get_a2_value(bbar, dbar, slip, beta, mmax):
"""
Returns the A2 value defined in II.8 (Table 3)
"""
return ((dbar - bbar) / bbar) * (slip / beta) *\
np.exp(-(dbar / 2.) * mmax) |
def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta):
'''
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:... |
def _get_a3_value(bbar, dbar, slip, beta, mmax):
"""
Returns the A3 value defined in III.4 (Table 4)
"""
return (dbar * (dbar - bbar) / (bbar ** 2.)) * (slip / beta) *\
np.exp(-(dbar / 2.) * mmax) |
def get_mfd(self, slip, fault_width, shear_modulus=30.0,
disp_length_ratio=1.25E-5):
'''
Calculates activity rate on the fault
:param float slip:
Slip rate in mm/yr
:param fault_width:
Width of the fault (km)
:param float shear_modulus:
... |
def load_version():
"""Loads a file content"""
filename = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"cpt", "__init__.py"))
with open(filename, "rt") as version_file:
conan_init = version_file.read()
version = re.searc... |
def builds(self, confs):
"""For retro compatibility directly assigning builds"""
self._named_builds = {}
self._builds = []
for values in confs:
if len(values) == 2:
self._builds.append(BuildConf(values[0], values[1], {}, {}, self.reference))
elif l... |
def patch_default_base_profile(conan_api, profile_abs_path):
"""If we have a profile including default, but the users default in config is that the default
is other, we have to change the include"""
text = tools.load(profile_abs_path)
if "include(default)" in text: # User didn't specified a custom prof... |
def get_user_if_exists(strategy, details, user=None, *args, **kwargs):
"""Return a User with the given username iff the User exists."""
if user:
return {'is_new': False}
try:
username = details.get('username')
# Return the user if it exists
return {
'is_new': Fal... |
def update_email(strategy, details, user=None, *args, **kwargs):
"""Update the user's email address using data from provider."""
if user:
email = details.get('email')
if email and user.email != email:
user.email = email
strategy.storage.user.changed(user) |
def _merge_two_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy.
Once Python 3.6+ only is supported, replace method with ``z = {**x, **y}``
"""
z = x.copy()
z.update(y)
return z |
def _map_user_details(self, response):
"""Maps key/values from the response to key/values in the user model.
Does not transfer any key/value that is empty or not present in the response.
"""
dest = {}
for source_key, dest_key in self.CLAIMS_TO_DETAILS_KEY_MAP.items():
... |
def get_user_claims(self, access_token, claims=None, token_type='Bearer'):
"""Returns a dictionary with the values for each claim requested."""
data = self.get_json(
self.USER_INFO_URL,
headers={'Authorization': '{token_type} {token}'.format(token_type=token_type, token=access_to... |
def _setup_ipc(self):
'''
Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC.
'''
log.debug('Setting up the server IPC puller to receive from the listener')
self.ctx = zmq.Context()
# subscribe to listener
... |
def _cleanup_buffer(self):
'''
Periodically cleanup the buffer.
'''
if not self._buffer:
return
while True:
time.sleep(60)
log.debug('Cleaning up buffer')
items = self._buffer.items()
# The ``items`` function should also... |
def _compile_prefixes(self):
'''
Create a dict of all OS prefixes and their compiled regexs
'''
self.compiled_prefixes = {}
for dev_os, os_config in self.config.items():
if not os_config:
continue
self.compiled_prefixes[dev_os] = []
... |
def _identify_prefix(self, msg, data):
'''
Check the message again each OS prefix and if matched return the
message dict
'''
prefix_id = -1
for prefix in data:
msg_dict = {}
prefix_id += 1
match = None
if '__python_fun__' in... |
def _identify_os(self, msg):
'''
Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing.
'''
ret = []
for dev_os, data in self.compiled_prefixes.items():
# TODO Should we prevent attepmting to determine t... |
def start(self):
'''
Take the messages from the queue,
inspect and identify the operating system,
then queue the message correspondingly.
'''
# metric counters
napalm_logs_server_messages_received = Counter(
"napalm_logs_server_messages_received",
... |
def _setup_ipc(self):
'''
Subscribe to the right topic
in the device IPC and publish to the
publisher proxy.
'''
self.ctx = zmq.Context()
# subscribe to device IPC
log.debug('Creating the dealer IPC for %s', self._name)
self.sub = self.ctx.socket(z... |
def _compile_messages(self):
'''
Create a list of all OS messages and their compiled regexs
'''
self.compiled_messages = []
if not self._config:
return
for message_dict in self._config.get('messages', {}):
error = message_dict['error']
... |
def _parse(self, msg_dict):
'''
Parse a syslog message and check what OpenConfig object should
be generated.
'''
error_present = False
# log.debug('Matching the message:')
# log.debug(msg_dict)
for message in self.compiled_messages:
# log.debug... |
def _emit(self, **kwargs):
'''
Emit an OpenConfig object given a certain combination of
fields mappeed in the config to the corresponding hierarchy.
'''
oc_dict = {}
for mapping, result_key in kwargs['mapping']['variables'].items():
result = kwargs[result_key]... |
def _publish(self, obj):
'''
Publish the OC object.
'''
bin_obj = umsgpack.packb(obj)
self.pub.send(bin_obj) |
def start(self):
'''
Start the worker process.
'''
# metrics
napalm_logs_device_messages_received = Counter(
'napalm_logs_device_messages_received',
"Count of messages received by the device process",
['device_os']
)
napalm_logs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.