Calculate shape statistics using regionprops applied to the object mask.
        
        Args:
            stat_names: List of statistics to be extracted from those calculated by regionprops.

        Returns:
            Dictionary of shape statistics
547370
def calc_shape_statistics(self, stat_names):
        
        stats = {}
        try:
            all_props = [regionprops(m) for m in self.masks]
        except TypeError:
            print(self.masks)
            exit()
        for stat in stat_names:
            stats[stat] = np.mean([p[0][stat] for p in all_props])
        return stats
245036
def get_feature_names(clf, vec=None, bias_name='<BIAS>', feature_names=None,
                      num_features=None, estimator_feature_names=None):
    # type: (Any, Any, Optional[str], Any, int, Any) -> FeatureNames
    
    if not has_intercept(clf):
        bias_name = None

    if feature_names is None:
        if vec and hasattr(vec, 'get_feature_names'):
            return FeatureNames(vec.get_feature_names(), bias_name=bias_name)
        else:
            if estimator_feature_names is None:
                num_features = num_features or get_num_features(clf)
                return FeatureNames(
                    n_features=num_features,
                    unkn_template='x%d',
                    bias_name=bias_name
                )
            return FeatureNames(estimator_feature_names, bias_name=bias_name)

    num_features = num_features or get_num_features(clf)
    if isinstance(feature_names, FeatureNames):
        if feature_names.n_features != num_features:
            raise ValueError("feature_names has a wrong n_features: "
                             "expected=%d, got=%d" % (num_features,
                                                      feature_names.n_features))
        # Make a shallow copy setting proper bias_name
        return FeatureNames(
            feature_names.feature_names,
            n_features=num_features,
            bias_name=bias_name,
            unkn_template=feature_names.unkn_template)
    else:
        if len(feature_names) != num_features:
            raise ValueError("feature_names has a wrong length: "
                             "expected=%d, got=%d" % (num_features,
                                                      len(feature_names)))
        return FeatureNames(feature_names, bias_name=bias_name)
58765
def get_t_statistics(self):
        '''
        

        '''

        X = self._get_X()
        cat_X, ncat_X = self._get_cat_and_ncat(X)

        mean_delta = self._get_mean_delta(cat_X, ncat_X)
        cat_var = sparse_var(cat_X)
        ncat_var = sparse_var(ncat_X)
        cat_n = cat_X.shape[0]
        ncat_n = ncat_X.shape[0]
        pooled_stderr = np.sqrt(cat_var / cat_n + ncat_var / ncat_n)

        tt = mean_delta / pooled_stderr

        # Use Satterthaite-Welch adjustment for degrees of freedom
        degs_of_freedom = (cat_var ** 2 / cat_n + ncat_var ** 2 / ncat_n) ** 2 / (
                (cat_var ** 2 / cat_n) ** 2 / (cat_n - 1)
                + (ncat_var ** 2 / ncat_n) ** 2 / (ncat_n - 1)
        )

        only_in_neutral_mask = self.tdf_[['cat', 'ncat']].sum(axis=1) == 0
        pvals = stats.t.sf(np.abs(tt), degs_of_freedom)
        tt[only_in_neutral_mask] = 0
        pvals[only_in_neutral_mask] = 0

        return tt, pvals
1210278
def _calculate_feature_stats(feature_list, prepared, serialization_file):  # pylint: disable=R0914
    """"""
    # Create feature only list
    feats = [x for x, _ in prepared]  # Label is not necessary

    # Calculate all means / mins / maxs
    means = numpy.mean(feats, 0)
    mins = numpy.min(feats, 0)
    maxs = numpy.max(feats, 0)

    # Calculate, min, max and mean vector for each feature with
    # normalization
    start = 0
    mode = 'w'
    arguments = {'newline': ''}
    if sys.version_info.major < 3:
        mode += 'b'
        arguments = {}
    with open(serialization_file, mode, **arguments) as csvfile:
        spamwriter = csv.writer(csvfile,
                                delimiter=str(';'),
                                quotechar=str('"'),
                                quoting=csv.QUOTE_MINIMAL)
        for feature in feature_list:
            end = start + feature.get_dimension()
            # append the data to the feature class
            feature.mean = numpy.array(means[start:end])
            feature.min = numpy.array(mins[start:end])
            feature.max = numpy.array(maxs[start:end])
            start = end
            for mean, fmax, fmin in zip(feature.mean, feature.max,
                                        feature.min):
                spamwriter.writerow([mean, fmax - fmin])
1356554
def get_prop_range_defs(class_names, def_list):
    

    try:
        cls_options = set(class_names + ['kdr_AllClasses'])
        return [rng_def for rng_def in def_list \
                if not isinstance(rng_def, BlankNode) \
                and cls_options.difference(\
                        set(rng_def.get('kds_appliesToClass', []))) < \
                        cls_options]
    except AttributeError:
        return []
813770
def _get_cmaps(names):
    """"""
    import matplotlib.pyplot as plt
    available_cmaps = list(
        chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
    names = list(names)
    wrongs = []
    for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
                                         arg not in available_cmaps)):
        if isinstance(arg, str):
            similarkeys = get_close_matches(arg, available_cmaps)
        if similarkeys != []:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
        else:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Run function without arguments to see all colormaps" % arg)
        names.remove(arg)
        wrongs.append(arg)
    if not names and not wrongs:
        names = sorted(m for m in available_cmaps if not m.endswith("_r"))
    return names
1356615
def names(self) -> [str]:
        
        return sorted([name for name in self.axes_by_sname.keys() if name is not ''])
1132616
def get_allowed_shape_ranges(spec):
    

    shaper = NeuralNetworkShaper(spec, False)
    inputs = _get_input_names(spec)
    output = {}

    for input in inputs:
        output[input] = shaper.shape(input)

    return output
883695
def _extract_peaks(specgram, neighborhood, threshold):
    
    kernel = np.ones(shape=neighborhood)
    local_averages = convolve(specgram, kernel / kernel.sum(), mode="constant", cval=0)

    # suppress all points below the floor value
    floor = (1 + threshold) * local_averages
    candidates = np.where(specgram > floor, specgram, 0)

    # grayscale dilation is equivalent to non-maximal suppression
    local_maximums = grey_dilation(candidates, footprint=kernel)
    peak_coords = np.argwhere(specgram == local_maximums)
    peaks = zip(peak_coords[:, 0], peak_coords[:, 1])

    return peaks
559091
def get_res_stats(ds_list, t_srs=None):
    
    if t_srs is None:
        t_srs = get_ds_srs(ds_list[0]) 
    res = np.array([get_res(ds, t_srs=t_srs) for ds in ds_list])
    #Check that all projections are identical
    #gt_array = np.array([ds.GetGeoTransform() for ds in args])
    #xres = gt_array[:,1]
    #yres = -gt_array[:,5]
    #if xres == yres:
    #res = np.concatenate((xres, yres))
    min = np.min(res)
    max = np.max(res)
    mean = np.mean(res)
    med = np.median(res)
    return (min, max, mean, med)
1099720
def _filter_meshes(self):
        

        from scipy.ndimage import generic_filter
        try:
            nanmedian_func = np.nanmedian    # numpy >= 1.9
        except AttributeError:    # pragma: no cover
            from scipy.stats import nanmedian
            nanmedian_func = nanmedian

        if self.filter_threshold is None:
            # filter the entire arrays
            self.background_mesh = generic_filter(
                self.background_mesh, nanmedian_func, size=self.filter_size,
                mode='constant', cval=np.nan)
            self.background_rms_mesh = generic_filter(
                self.background_rms_mesh, nanmedian_func,
                size=self.filter_size, mode='constant', cval=np.nan)
        else:
            # selectively filter
            indices = np.nonzero(self.background_mesh > self.filter_threshold)
            self.background_mesh = self._selective_filter(
                self.background_mesh, indices)
            self.background_rms_mesh = self._selective_filter(
                self.background_rms_mesh, indices)

        return
683411
def postproc_mask (stats_result):
    
    n, mean, scat = stats_result

    ok = np.isfinite (mean)
    n = n[ok]
    mean = mean[ok]
    scat = scat[ok]

    mean *= 180 / np.pi # rad => deg
    scat /= n # variance-of-samples => variance-of-mean
    scat **= 0.5 # variance => stddev
    scat *= 180 / np.pi # rad => deg
    return ok, mean, scat
1033773
def extract_named_ranges(defined_names) #:nodoc:
      named_ranges = []

      defined_names.each do |defined_name|
        name, index, range = defined_name

        # Skip autoFilter ranges.
        next if name == '_xlnm._FilterDatabase'

        # We are only interested in defined names with ranges.
        if range =~ /^([^!]+)!/
          sheet_name = $1

          # Match Print_Area and Print_Titles xlnm types.
          if name =~ /^_xlnm\.(.*)$/
            xlnm_type = $1
            name = "#{sheet_name}!#{xlnm_type}"
          elsif index != -1
            name = "#{sheet_name}!#{name}"
          end

          named_ranges << name
        end
      end

      named_ranges
    end
808571
def select_mask(cls, dataset, selection):
        
        select_mask = None
        for dim, k in selection.items():
            if isinstance(k, tuple):
                k = slice(*k)
            masks = []
            alias = dataset.get_dimension(dim).name
            series = dataset.data[alias]
            if isinstance(k, slice):
                if k.start is not None:
                    # Workaround for dask issue #3392
                    kval = util.numpy_scalar_to_python(k.start)
                    masks.append(kval <= series)
                if k.stop is not None:
                    kval = util.numpy_scalar_to_python(k.stop)
                    masks.append(series < kval)
            elif isinstance(k, (set, list)):
                iter_slc = None
                for ik in k:
                    mask = series == ik
                    if iter_slc is None:
                        iter_slc = mask
                    else:
                        iter_slc |= mask
                masks.append(iter_slc)
            elif callable(k):
                masks.append(k(series))
            else:
                masks.append(series == k)
            for mask in masks:
                if select_mask is not None:
                    select_mask &= mask
                else:
                    select_mask = mask
        return select_mask
975462
def calculate_array_feature_extractor_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType, Int64TensorType, StringTensorType])

    N = operator.inputs[0].type.shape[0]
    extracted_feature_number = len(operator.raw_operator.arrayFeatureExtractor.extractIndex)

    # Save doc_string before over-writing by us
    doc_string = operator.outputs[0].type.doc_string
    operator.outputs[0].type = copy.deepcopy(operator.inputs[0].type)
    operator.outputs[0].type.shape = [N, extracted_feature_number]
    # Assign correct doc_string to the output
    operator.outputs[0].type.doc_string = doc_string
1257783
async def statistics(self, tube_name=None):
        
        args = None
        if tube_name is not None:
            args = (tube_name,)

        res = await self._conn.call('{}.statistics'.format(self._namespace), args)
        if self._conn.version < (1, 7):  # pragma: nocover
            return res.body[0][0]
        return res.body[0]
763609
def get_object_stats(self, obj_name):
        

        return dict(zip(self.captions, self.statistics[obj_name]))