See
        :meth:`openquake.hazardlib.source.base.BaseSeismicSource.count_ruptures`
        for description of parameters and return value.
171775
def count_ruptures(self):
        
        return (len(self.get_annual_occurrence_rates()) *
                len(self.nodal_plane_distribution.data) *
                len(self.hypocenter_distribution.data))
1150972
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False):
    
    if isinstance(mag_scale_rel, BaseMSR):
        return mag_scale_rel
    elif isinstance(mag_scale_rel, str):
        if not mag_scale_rel in SCALE_RELS.keys():
            raise ValueError('Magnitude scaling relation %s not supported!'
                             % mag_scale_rel)
        else:
            return SCALE_RELS[mag_scale_rel]()
    else:
        if use_default:
            # Returns the Wells and Coppersmith string
            return WC1994()
        else:
            raise ValueError('Magnitude Scaling Relation Not Defined!')
528434
def _check_count(self, result, func, args):
        #pylint: disable=unused-argument
        
        if result == 0:
            raise ctypes.WinError(ctypes.get_last_error())
        return args
274259
def dynamic_symbols_count(self):
        
        if not self._ptr:
            raise BfdException("BFD not initialized")

        return _bfd.get_bfd_attribute(
            self._ptr, BfdAttributes.DYNAMIC_SYMCOUNT)
860824
def add_rup_params(self, rupture):
        
        for param in self.REQUIRES_RUPTURE_PARAMETERS:
            if param == 'mag':
                value = rupture.mag
            elif param == 'strike':
                value = rupture.surface.get_strike()
            elif param == 'dip':
                value = rupture.surface.get_dip()
            elif param == 'rake':
                value = rupture.rake
            elif param == 'ztor':
                value = rupture.surface.get_top_edge_depth()
            elif param == 'hypo_lon':
                value = rupture.hypocenter.longitude
            elif param == 'hypo_lat':
                value = rupture.hypocenter.latitude
            elif param == 'hypo_depth':
                value = rupture.hypocenter.depth
            elif param == 'width':
                value = rupture.surface.get_width()
            else:
                raise ValueError('%s requires unknown rupture parameter %r' %
                                 (type(self).__name__, param))
            setattr(rupture, param, value)
978381
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 enumerate(node):
            probs = pmf.PMF(valid.pmf(rupnode['probs_occur']))
            rup = RuptureConverter.convert_node(self, rupnode)
            rup.tectonic_region_type = trt
            rup.weight = None if rups_weights is None else rups_weights[i]
            rup_pmf_data.append((rup, probs))
        nps = source.NonParametricSeismicSource(
            node['id'], node['name'], trt, rup_pmf_data)
        nps.splittable = 'rup_weights' not in node.attrib
        return nps
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
46872
def value_counts(arg, metric_name='count'):
    
    base = ir.find_base_table(arg)
    metric = base.count().name(metric_name)

    try:
        arg.get_name()
    except com.ExpressionError:
        arg = arg.name('unnamed')

    return base.group_by(arg).aggregate(metric)
91383
def build_ruptures(sources, src_filter, param, monitor):
    
    [src] = sources
    res = AccumDict()
    res.calc_times = []
    sampl_mon = monitor('sampling ruptures', measuremem=True)
    res.trt = DEFAULT_TRT
    background_sids = src.get_background_sids(src_filter)
    sitecol = src_filter.sitecol
    samples = getattr(src, 'samples', 1)
    n_occ = AccumDict(accum=0)
    t0 = time.time()
    with sampl_mon:
        for sam_idx in range(samples):
            for ses_idx, ses_seed in param['ses_seeds']:
                seed = sam_idx * TWO16 + ses_seed
                rups, occs = generate_event_set(
                    src, background_sids, src_filter, ses_idx, seed)
                for rup, occ in zip(rups, occs):
                    n_occ[rup] += occ
    tot_occ = sum(n_occ.values())
    dic = {'eff_ruptures': {src.src_group_id: src.num_ruptures}}
    eb_ruptures = [EBRupture(rup, src.id, src.src_group_id, n, samples)
                   for rup, n in n_occ.items()]
    dic['rup_array'] = stochastic.get_rup_array(eb_ruptures, src_filter)
    dt = time.time() - t0
    dic['calc_times'] = {src.id: numpy.array([tot_occ, len(sitecol), dt], F32)}
    return dic
803945
def close(self):
        
        if 'ruptures' not in self.datastore:  # for UCERF
            return
        codes = numpy.unique(self.datastore['ruptures']['code'])
        attr = {'code_%d' % code: ' '.join(
            cls.__name__ for cls in BaseRupture.types[code])
                for code in codes}
        self.datastore.set_attrs('ruptures', **attr)
244470
def get_adjusted_error_count(self):
    
    p1 =  self._observable.get_attributable_length()
    p1 += self._unobservable.get_attributable_length()
    return p1
332394
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 is too small', src, dt)
            elif 'ComplexFault' in clsname:
                logging.warning(
                    '%s.count_ruptures took %d seconds, perhaps the '
                    'complex_fault_mesh_spacing is too small', src, dt)
            elif 'SimpleFault' in clsname:
                logging.warning(
                    '%s.count_ruptures took %d seconds, perhaps the '
                    'rupture_mesh_spacing is too small', src, dt)
            else:
                # multiPointSource
                logging.warning('count_ruptures %s took %d seconds', src, dt)
    return src.num_ruptures
713102
def get_checksum32(oqparam, hazard=False):
    
    # NB: using adler32 & 0xffffffff is the documented way to get a checksum
    # which is the same between Python 2 and Python 3
    checksum = 0
    for fname in get_input_files(oqparam, hazard):
        checksum = _checksum(fname, checksum)
    if hazard:
        hazard_params = []
        for key, val in vars(oqparam).items():
            if key in ('rupture_mesh_spacing', 'complex_fault_mesh_spacing',
                       'width_of_mfd_bin', 'area_source_discretization',
                       'random_seed', 'ses_seed', 'truncation_level',
                       'maximum_distance', 'investigation_time',
                       'number_of_logic_tree_samples', 'imtls',
                       'ses_per_logic_tree_path', 'minimum_magnitude',
                       'prefilter_sources', 'sites',
                       'pointsource_distance', 'filter_distance'):
                hazard_params.append('%s = %s' % (key, val))
        data = '\n'.join(hazard_params).encode('utf8')
        checksum = zlib.adler32(data, checksum) & 0xffffffff
    return checksum
1171312
def block_count(self):
        

        resp = self.call('block_count')

        for k, v in resp.items():
            resp[k] = int(v)

        return resp
1254718
def gen_rupture_getters(dstore, slc=slice(None),
                        concurrent_tasks=1, hdf5cache=None):
    
    if dstore.parent:
        dstore = dstore.parent
    csm_info = dstore['csm_info']
    trt_by_grp = csm_info.grp_by("trt")
    samples = csm_info.get_samples_by_grp()
    rlzs_by_gsim = csm_info.get_rlzs_by_gsim_grp()
    rup_array = dstore['ruptures'][slc]
    maxweight = numpy.ceil(len(rup_array) / (concurrent_tasks or 1))
    nr, ne = 0, 0
    for grp_id, arr in general.group_array(rup_array, 'grp_id').items():
        if not rlzs_by_gsim[grp_id]:
            # this may happen if a source model has no sources, like
            # in event_based_risk/case_3
            continue
        for block in general.block_splitter(arr, maxweight):
            rgetter = RuptureGetter(
                hdf5cache or dstore.filename, numpy.array(block), grp_id,
                trt_by_grp[grp_id], samples[grp_id], rlzs_by_gsim[grp_id])
            rgetter.weight = getattr(block, 'weight', len(block))
            yield rgetter
            nr += len(block)
            ne += rgetter.num_events
    logging.info('Read %d ruptures and %d events', nr, ne)
817505
def retry_count(self, retries):
        
        if not isinstance(retries, int):
            raise TypeError("retries must be an integer")

        old_retries, self.retries = self.retries, retries
        try:
            yield
        finally:
            self.retries = old_retries
945248
def count(self):
        
        if self.mode == 'spark':
            return self.tordd().count()

        if self.mode == 'local':
            return prod(self.values.values.shape)