:param src: a hazardlib source
        :param sites: the sites affected by it
        :yields: (rup, sctx, dctx)
323896
def gen_rup_contexts(self, src, sites):
        
        sitecol = sites.complete
        N = len(sitecol)
        fewsites = N <= FEWSITES
        rupdata = []  # rupture data
        for rup, sites in self._gen_rup_sites(src, sites):
            try:
                with self.ctx_mon:
                    sctx, dctx = self.make_contexts(sites, rup)
            except FarAwayRupture:
                continue
            yield rup, sctx, dctx
            if fewsites:  # store rupdata
                try:
                    rate = rup.occurrence_rate
                    probs_occur = numpy.zeros(0, numpy.float64)
                except AttributeError:  # for nonparametric ruptures
                    rate = numpy.nan
                    probs_occur = rup.probs_occur
                row = [src.id or 0, rate]
                for rup_param in self.REQUIRES_RUPTURE_PARAMETERS:
                    row.append(getattr(rup, rup_param))
                for dist_param in self.REQUIRES_DISTANCES:
                    row.append(get_distances(rup, sitecol, dist_param))
                closest = rup.surface.get_closest_points(sitecol)
                row.append(closest.lons)
                row.append(closest.lats)
                row.append(rup.weight)
                row.append(probs_occur)
                rupdata.append(tuple(row))
        if rupdata:
            dtlist = [('srcidx', numpy.uint32), ('occurrence_rate', float)]
            for rup_param in self.REQUIRES_RUPTURE_PARAMETERS:
                dtlist.append((rup_param, float))
            for dist_param in self.REQUIRES_DISTANCES:
                dtlist.append((dist_param, (float, (N,))))
            dtlist.append(('lon', (float, (N,))))  # closest lons
            dtlist.append(('lat', (float, (N,))))  # closest lats
            dtlist.append(('mutex_weight', float))
            dtlist.append(('probs_occur', vfloat64))
            self.rupdata = numpy.array(rupdata, dtlist)
        else:
            self.rupdata = ()
1151684
def iter_sparts(self):
        
        for s in self._sparts:
            yield (s.partname, s.content_type, s.reltype, s.blob)
7303
def iter_sources(self):
        """"""
        for src_id in xrange(self.get_source_count()):
            yield src_id, self.get_source_name(src_id)
878820
def gen_trace_planes(self, ridx):
        
        with h5py.File(self.source_file, "r") as hdf5:
            for idx in ridx:
                trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
                plane = hdf5[trace + "/RupturePlanes"][:].astype("float64")
                yield trace, plane
1337273
def load_targets(explanatory_rasters):
    

    explanatory_raster_arrays = []
    aff = None
    shape = None
    crs = None

    for raster in explanatory_rasters:
        logger.debug(raster)
        with rasterio.open(raster) as src:
            ar = src.read(1)  # TODO band num? 

            # Save or check the geotransform
            if not aff:
                aff = src.affine
            else:
                assert aff == src.affine

            # Save or check the shape
            if not shape:
                shape = ar.shape
            else:
                assert shape == ar.shape

            # Save or check the geotransform
            if not crs:
                crs = src.crs
            else:
                assert crs == src.crs

        # Flatten in one dimension
        arf = ar.flatten()
        explanatory_raster_arrays.append(arf)

    expl = np.array(explanatory_raster_arrays).T

    raster_info = {
        'affine': aff,
        'shape': shape,
        'crs': crs
    }
    return expl, raster_info
21668
def get_site_dos(self, site):
        
        site_dos = functools.reduce(add_densities, self.pdos[site].values())
        return Dos(self.efermi, self.energies, site_dos)
270059
def _get_smr_coeffs(self, C, C_SITE, idx, n_sites, sa_rock):
        
        # Get SR
        sreff = np.zeros(n_sites)
        sreffc = np.zeros(n_sites)
        f_sr = np.zeros(n_sites)
        for i in range(1, 5):
            sreff[idx[i]] += (np.exp(sa_rock[idx[i]]) * self.IMF[i])
            sreffc[idx[i]] += (C_SITE["Src1D{:g}".format(i)] * self.IMF[i])
            # Get f_SR
            f_sr[idx[i]] += C_SITE["fsr{:g}".format(i)]
        return sreff, sreffc, f_sr
506325
def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):
        
        self.monitor = monitor
        hazard_getter = riskinput.hazard_getter
        if hazard is None:
            with monitor('getting hazard'):
                hazard_getter.init()
                hazard = hazard_getter.get_hazard()
        sids = hazard_getter.sids
        assert len(sids) == 1
        with monitor('computing risk', measuremem=False):
            # this approach is slow for event_based_risk since a lot of
            # small arrays are passed (one per realization) instead of
            # a long array with all realizations; ebrisk does the right
            # thing since it calls get_output directly
            assets_by_taxo = get_assets_by_taxo(riskinput.assets, epspath)
            for rlzi, haz in sorted(hazard[sids[0]].items()):
                out = self.get_output(assets_by_taxo, haz, rlzi)
                yield out
741462
def sites(c):
    
    # TODO: This is super lolzy but we haven't actually tackled nontrivial
    # in-Python task calling yet, so we do this to get a copy of 'our' context,
    # which has been updated with the per-collection config data of the
    # docs/www subcollections.
    docs_c = Context(config=c.config.clone())
    www_c = Context(config=c.config.clone())
    docs_c.update(**docs.configuration())
    www_c.update(**www.configuration())
    # Must build both normally first to ensure good intersphinx inventory files
    # exist =/ circular dependencies ahoy! Do it quietly to avoid pulluting
    # output; only super-serious errors will bubble up.
    # TODO: wants a 'temporarily tweak context settings' contextmanager
    # TODO: also a fucking spinner cuz this confuses me every time I run it
    # when the docs aren't already prebuilt
    docs_c["run"].hide = True
    www_c["run"].hide = True
    docs["build"](docs_c)
    www["build"](www_c)
    docs_c["run"].hide = False
    www_c["run"].hide = False
    # Run the actual builds, with nitpick=True (nitpicks + tracebacks)
    docs["build"](docs_c, nitpick=True)
    www["build"](www_c, nitpick=True)
329008
def update(self, src):
        
        assert src.tectonic_region_type == self.trt, (
            src.tectonic_region_type, self.trt)
        if not src.min_mag:  # if not set already
            src.min_mag = self.min_mag.get(self.trt) or self.min_mag['default']
        # checking mutex ruptures
        if (not isinstance(src, NonParametricSeismicSource) and
                self.rup_interdep == 'mutex'):
            msg = "Mutually exclusive ruptures can only be "
            msg += "modelled using non-parametric sources"
            raise ValueError(msg)

        nr = get_set_num_ruptures(src)
        if nr == 0:  # the minimum_magnitude filters all ruptures
            return
        self.tot_ruptures += nr
        self.sources.append(src)
        _, max_mag = src.get_min_max_mag()
        prev_max_mag = self.max_mag
        if prev_max_mag is None or max_mag > prev_max_mag:
            self.max_mag = max_mag
378127
def _inject_addresses(self, subjects):
    
    logger.debug('Injecting addresses to %s: %s', self, subjects)
    with self._resolve_context():
      addresses = tuple(subjects)
      thts, = self._scheduler.product_request(TransitiveHydratedTargets,
                                              [BuildFileAddresses(addresses)])

    self._index(thts.closure)

    yielded_addresses = set()
    for address in subjects:
      if address not in yielded_addresses:
        yielded_addresses.add(address)
        yield address
1227394
def seq_site_length(self):
        
        relative_positions_set = set()
        for peak_descr in self:
            relative_positions_set.update(peak_descr.relative_positions)
        return len(relative_positions_set)
1256327
def context(src):
    
    try:
        yield
    except Exception:
        etype, err, tb = sys.exc_info()
        msg = 'An error occurred with source id=%s. Error: %s'
        msg %= (src.source_id, err)
        raise_(etype, msg, tb)
844830
def split_sources(srcs):
    
    from openquake.hazardlib.source import splittable
    sources = []
    split_time = {}  # src.id -> time
    for src in srcs:
        t0 = time.time()
        mag_a, mag_b = src.get_min_max_mag()
        min_mag = src.min_mag
        if mag_b < min_mag:  # discard the source completely
            continue
        has_serial = hasattr(src, 'serial')
        if has_serial:
            src.serial = numpy.arange(
                src.serial, src.serial + src.num_ruptures)
        if not splittable(src):
            sources.append(src)
            split_time[src.id] = time.time() - t0
            continue
        if min_mag:
            splits = []
            for s in src:
                s.min_mag = min_mag
                mag_a, mag_b = s.get_min_max_mag()
                if mag_b < min_mag:
                    continue
                s.num_ruptures = s.count_ruptures()
                if s.num_ruptures:
                    splits.append(s)
        else:
            splits = list(src)
        split_time[src.id] = time.time() - t0
        sources.extend(splits)
        has_samples = hasattr(src, 'samples')
        if len(splits) > 1:
            start = 0
            for i, split in enumerate(splits):
                split.source_id = '%s:%s' % (src.source_id, i)
                split.src_group_id = src.src_group_id
                split.id = src.id
                if has_serial:
                    nr = split.num_ruptures
                    split.serial = src.serial[start:start + nr]
                    start += nr
                if has_samples:
                    split.samples = src.samples
        elif splits:  # single source
            splits[0].id = src.id
            if has_serial:
                splits[0].serial = src.serial
            if has_samples:
                splits[0].samples = src.samples
    return sources, split_time
495678
def closestsites(struct_blk, struct_def, pos):
    
    blk_close_sites = struct_blk.get_sites_in_sphere(pos, 5, include_index=True)
    blk_close_sites.sort(key=lambda x: x[1])
    def_close_sites = struct_def.get_sites_in_sphere(pos, 5, include_index=True)
    def_close_sites.sort(key=lambda x: x[1])

    return blk_close_sites[0], def_close_sites[0]
1099622
def expand_source_paths(paths):
    
    for src_path in paths:
        # only track the source path if we can find it to avoid double-reloads
        # when the source and the compiled path change because on some
        # platforms they are not changed at the same time
        if src_path.endswith(('.pyc', '.pyo')):
            py_path = get_py_path(src_path)
            if os.path.exists(py_path):
                src_path = py_path
        yield src_path
381024
def _compute_shallow_site_response(self, C, sites, pga1100):
        
        stiff_factor = C['c10'] + (C['k2'] * C['n'])
        # Initially default all sites to intermediate rock value
        fsite = stiff_factor * np.log(sites.vs30 / C['k1'])
        # Check for soft soil sites
        idx = sites.vs30 < C['k1']
        if np.any(idx):
            pga_scale = np.log(pga1100[idx] +
                               (C['c'] * ((sites.vs30[idx] / C['k1']) **
                                C['n']))) - np.log(pga1100[idx] + C['c'])
            fsite[idx] = C['c10'] * np.log(sites.vs30[idx] / C['k1']) + \
                (C['k2'] * pga_scale)
        # Any very hard rock sites are rendered to the constant amplification
        # factor
        idx = sites.vs30 >= 1100.
        if np.any(idx):
            fsite[idx] = stiff_factor * log(1100. / C['k1'])

        return fsite