:param source_model: a LtSourceModel instance (or None)
        :returns: the number of realizations per source model (or all)
491405
def get_num_rlzs(self, source_model=None):
        
        if source_model is None:
            return sum(self.get_num_rlzs(sm) for sm in self.source_models)
        if self.num_samples:
            return source_model.samples
        trts = set(sg.trt for sg in source_model.src_groups if sg.eff_ruptures)
        if sum(sg.eff_ruptures for sg in source_model.src_groups) == 0:
            return 0
        return self.gsim_lt.reduce(trts).get_num_paths()
268021
def reduce_source_model(smlt_file, source_ids, remove=True):
    
    found = 0
    to_remove = []
    for paths in logictree.collect_info(smlt_file).smpaths.values():
        for path in paths:
            logging.info('Reading %s', path)
            root = nrml.read(path)
            model = Node('sourceModel', root[0].attrib)
            origmodel = root[0]
            if root['xmlns'] == 'http://openquake.org/xmlns/nrml/0.4':
                for src_node in origmodel:
                    if src_node['id'] in source_ids:
                        model.nodes.append(src_node)
            else:  # nrml/0.5
                for src_group in origmodel:
                    sg = copy.copy(src_group)
                    sg.nodes = []
                    weights = src_group.get('srcs_weights')
                    if weights:
                        assert len(weights) == len(src_group.nodes)
                    else:
                        weights = [1] * len(src_group.nodes)
                    src_group['srcs_weights'] = reduced_weigths = []
                    for src_node, weight in zip(src_group, weights):
                        if src_node['id'] in source_ids:
                            found += 1
                            sg.nodes.append(src_node)
                            reduced_weigths.append(weight)
                    if sg.nodes:
                        model.nodes.append(sg)
            shutil.copy(path, path + '.bak')
            if model:
                with open(path, 'wb') as f:
                    nrml.write([model], f, xmlns=root['xmlns'])
            elif remove:  # remove the files completely reduced
                to_remove.append(path)
    if found:
        for path in to_remove:
            os.remove(path)
591746
def get_model_ids_to_fetch(events, context_hints_per_source):
    
    number_types = (complex, float) + six.integer_types
    model_ids_to_fetch = defaultdict(set)

    for event in events:
        context_hints = context_hints_per_source.get(event.source, {})
        for context_key, hints in context_hints.items():
            for d, value in dict_find(event.context, context_key):
                values = value if isinstance(value, list) else [value]
                model_ids_to_fetch[get_model(hints['app_name'], hints['model_name'])].update(
                    v for v in values if isinstance(v, number_types)
                )

    return model_ids_to_fetch
196133
def _check_sources(self, batch: Dict[str, object]) -> None:
        
        unused_sources = [source for source in batch.keys() if source not in self._model.input_names]
        missing_sources = [source for source in self._model.input_names if source not in batch.keys()]
        # check stream sources
        if unused_sources:
            if self._on_unused_sources == 'warn' and not self._extra_sources_warned:
                logging.warning('Some sources provided by the stream do not match model placeholders. Set '
                                '`main_loop.on_unused_sources` to `ignore` in order to suppress this warning. '
                                'Extra sources: %s', unused_sources)
                self._extra_sources_warned = True
            elif self._on_unused_sources == 'error':
                raise ValueError('Some sources provided by the stream do not match model placeholders. Set'
                                 '`main_loop.on_unused_sources` to `warn` in order to suppress this error.\n'
                                 'Extra sources: {}'.format(unused_sources))

        if missing_sources:
            raise ValueError('Stream does not provide all required sources. Missing sources: {}'
                             .format(missing_sources))
530617
def _load_source_model(self):
		

		# If source_model exists, return it
		if hasattr(self, "source_model"):
			return self.source_model

		# Getting the source model
		module = self.get_python_module()

		# Test if module has inside the model we are looking for
		if hasattr(module, self.model):
			# Setting of source model
			self.source_model = getattr(module, self.model)
			# Setting of verbose name and its plural for later use
			self.source_model.meta__verbose_name = self.source_model._meta.verbose_name
			self.source_model.meta__verbose_name_plural = self.source_model._meta.verbose_name_plural
			return self.source_model
		
		raise ValueError(u"Model {0} does not exist in module".format(self.model, self.module))
852002
def _add_source(self, source):
        

        try:

            self._add_child(source)

        except AttributeError:

            if isinstance(source, Source):

                raise DuplicatedNode("More than one source with the name '%s'. You cannot use the same name for multiple "
                                     "sources" % source.name)

            else:  # pragma: no cover

                raise

        # Now see if this is a point or extended source, and add them to the
        # appropriate dictionary

        if source.source_type == POINT_SOURCE:

            self._point_sources[source.name] = source

        elif source.source_type == EXTENDED_SOURCE:

            self._extended_sources[source.name] = source

        elif source.source_type == PARTICLE_SOURCE:

            self._particle_sources[source.name] = source

        else:  # pragma: no cover

            raise InvalidInput("Input sources must be either a point source or an extended source")
739967
def get_sm_by_grp(self):
        
        return {grp.id: sm.ordinal for sm in self.source_models
                for grp in sm.src_groups}
549666
def _compute_counts_from_model(model, bexpcube):
        
        data = model.data * bexpcube.data
        ebins = model.hpx.ebins
        ratio = ebins[1:] / ebins[0:-1]
        half_log_ratio = np.log(ratio) / 2.
        int_map = ((data[0:-1].T * ebins[0:-1]) + (data[1:].T * ebins[1:])) * half_log_ratio
        return HpxMap(int_map.T, model.hpx)
615161
protected function determineModelReferenceSource(Model $model)
    {
        $source = $this->getReferenceSource($model);

        // If we have no source to fall back on at all, use the model key
        if ( ! $source) {
            $source = $model->getKeyName();
        }

        return $source;
    }
652178
def model_predictions(self):
        
        if isinstance(self.observed, ContinuousColumn):
            return ValueError("Cannot make model predictions on a continuous scale")
        pred = np.zeros(self.data_size).astype('object')
        for node in self:
            if node.is_terminal:
                pred[node.indices] = max(node.members, key=node.members.get)
        return pred
882865
protected function resolveModelSource(Model $model, $source)
    {
        // If the strategy indicates a method to be called on the model itself, do so
        if ($method = $this->parseAsModelMethodStrategyString($source, $model)) {
            return $model->{$method}();
        }

        // If the strategy indicates an instantiable/callable 'class@method' combination
        if ($data = $this->parseAsInstantiableClassMethodStrategyString($source)) {

            $method   = $data['method'];
            $instance = $data['instance'];

            return $instance->{$method}($model);
        }

        // If the name matches a method name on the model, call it
        if (method_exists($model, $source)) {
            return $model->{$source}();
        }

        return $model->{$source};
    }
61017
def list_datasources(self, source_id):
        
        target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id})
        return base.Query(self.client.get_manager(Datasource), target_url)
4469
def _parse_model(topology, scope, model, inputs=None, outputs=None):
    '''
    
    '''

    if inputs is None:
        inputs = list()
    if outputs is None:
        outputs = list()

    model_type = model.WhichOneof('Type')
    if model_type in ['pipeline', 'pipelineClassifier', 'pipelineRegressor']:
        _parse_pipeline_model(topology, scope, model, inputs, outputs)
    elif model_type in ['neuralNetworkClassifier', 'neuralNetworkRegressor', 'neuralNetwork']:
        _parse_neural_network_model(topology, scope, model, inputs, outputs)
    else:
        _parse_simple_model(topology, scope, model, inputs, outputs)
381664
def get_source_kernel(gta, name, kernel=None):
    """"""

    sm = []
    zs = 0
    for c in gta.components:
        z = c.model_counts_map(name).data.astype('float')
        if kernel is not None:
            shape = (z.shape[0],) + kernel.shape
            z = np.apply_over_axes(np.sum, z, axes=[1, 2]) * np.ones(
                shape) * kernel[np.newaxis, :, :]
            zs += np.sum(z)
        else:
            zs += np.sum(z)

        sm.append(z)

    sm2 = 0
    for i, m in enumerate(sm):
        sm[i] /= zs
        sm2 += np.sum(sm[i] ** 2)

    for i, m in enumerate(sm):
        sm[i] /= sm2

    return sm
560552
def source_setattr():
    

    def source_setattr(value, context, **_params):
        setattr(context["model"].source, context["key"], value)
        return _attr()

    return source_setattr
823299
def _build_model(self):
        

        if "input_dim" not in self.settings:
            raise ValueError("Model parameter input_dim cannot be None.")

        self.sparse_linear = SparseLinear(
            self.settings["input_dim"], self.cardinality, self.settings["bias"]
        )
226252
def get_sources(self, kind='all'):
        
        assert kind in ('all', 'indep', 'mutex'), kind
        sources = []
        for sm in self.source_models:
            for src_group in sm.src_groups:
                if kind in ('all', src_group.src_interdep):
                    for src in src_group:
                        if sm.samples > 1:
                            src.samples = sm.samples
                        sources.append(src)
        return sources