Evenly reduce counts in cell to target amount.

    This is an internal function and has some restrictions:

    * `dtype` of col must be an integer (i.e. satisfy issubclass(col.dtype.type, np.integer))
    * total counts in cell must be less than target
493632
def _downsample_array(col: np.array, target: int, random_state: int=0,
                      replace: bool = True, inplace: bool=False):
    
    np.random.seed(random_state)
    cumcounts = col.cumsum()
    if inplace:
        col[:] = 0
    else:
        col = np.zeros_like(col)
    total = cumcounts[-1]
    sample = np.random.choice(total, target, replace=replace)
    sample.sort()
    geneptr = 0
    for count in sample:
        while count >= cumcounts[geneptr]:
            geneptr += 1
        col[geneptr] += 1
    return col
439996
def cell(self, row_idx, col_idx):
        
        cell_idx = col_idx + (row_idx * self._column_count)
        return self._cells[cell_idx]
13407
def _column_reduction(self):
        
        #assign each column to its lowest cost row, ensuring that only row
        #or column is assigned once
        i1, j = np.unique(np.argmin(self.c, axis=0), return_index=True)
        self._x[i1] = j

        #if problem is solved, return
        if len(i1) == self.n:
            return False

        self._y[j] = i1

        #reduction_transfer
        #tempc is array with previously assigned matchings masked
        self._v = np.min(self.c, axis=0)
        tempc = self.c.copy()
        tempc[i1, j] = np.inf
        mu = np.min(tempc[i1, :] - self._v[None, :], axis=1)
        self._v[j] -= mu
        return True
629869
def set_xlimits(self, row, column, min=None, max=None):
        
        subplot = self.get_subplot_at(row, column)
        subplot.set_xlimits(min, max)
439662
def safe_round(self, x):
        
        val = x[self.col_name]

        if np.isposinf(val):
            val = sys.maxsize

        elif np.isneginf(val):
            val = -sys.maxsize

        if np.isnan(val):
            val = self.default_val

        if self.subtype == 'integer':
            return int(round(val))

        return val
1196006
def downsample(data, percent):
    
    n_genes = data.shape[0]
    n_cells = data.shape[1]
    new_data = data.copy()
    total_count = float(data.sum())
    to_remove = total_count*percent
    # sum of read counts per cell
    cell_sums = data.sum(0).astype(float)
    # probability of selecting genes per cell
    cell_gene_probs = data/cell_sums
    # probability of selecting cells
    cell_probs = np.array(cell_sums/total_count).flatten()
    cells_selected = np.random.multinomial(to_remove, pvals=cell_probs)
    for i, num_selected in enumerate(cells_selected):
        cell_gene = np.array(cell_gene_probs[:,i]).flatten()
        genes_selected = np.random.multinomial(num_selected, pvals=cell_gene)
        if sparse.issparse(data):
            genes_selected = sparse.csc_matrix(genes_selected).T
        new_data[:,i] -= genes_selected
    new_data[new_data < 0] = 0
    return new_data
1031091
def exclude(self, col: str, val):
        
        try:
            self.df = self.df[self.df[col] != val]
        except Exception as e:
            self.err(e, "Can not exclude rows based on value " + str(val))
26955
def count_rows_with_nans(X):
    """"""
    if X.ndim == 2:
        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()
430212
def reduce_sum(attrs, inputs, proto_obj):
    """"""
    new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
    return 'sum', new_attrs, inputs
321993
def select_number(self, rows: List[Row], column: NumberColumn) -> Number:
        
        numbers: List[float] = []
        for row in rows:
            cell_value = row.values[column.name]
            if isinstance(cell_value, float):
                numbers.append(cell_value)

        return numbers[0] if numbers else -1
517055
def cell_to_packed_rowcol(cell)
    row, col, row_rel, col_rel = cell_to_rowcol(cell)

    exit "Column #{cell} greater than IV in formula\n" if col >= 256
    exit "Row #{cell} greater than 65536 in formula\n" if row >= 65536

    # Set the high bits to indicate if row or col are relative.
    col    |= col_rel << 14
    col    |= row_rel << 15

    row     = [row].pack('v')
    col     = [col].pack('v')

    [row, col]
  end
361798
def sum_(self, col: str) -> float:
        
        try:
            df = self.df[col]
            num = float(df.sum())
            return num
        except Exception as e:
            self.err(e, "Can not sum data on column " + str(col))
897286
public void updateColumn(int c, TableColumn col)
    {
        int r = 0;
        while (r < getRowCount())
        {
            TableCellBox cell = cells[c][r];
            if (cell != null)
            {
            	cell.setOwnerColumn(col);
                //minimal width
                int min = cell.getMinimalWidth() / cell.getColspan();
                if (min > col.getMinimalWidth())
                    col.setMinimalWidth(min);
                //maximal width
                int max = cell.getMaximalWidth() / cell.getColspan();
                if (max > col.getMaximalWidth())
                    col.setMaximalWidth(max);
                //fixed width and percentages
                if (cell.wset) 
                {
                    col.wset = true;
                    if (cell.isRelative())
                    {
                        col.setRelative(true);
                        if (col.percent < cell.percent)
                            col.percent = cell.percent;
                    }
                    else
                    {
                        if (cell.getContentWidth() > col.abswidth)
                            col.abswidth = cell.getContentWidth();
                    }
                }
                //ensure the minimal width
                if (col.getWidth() < col.getMinimalWidth())
                    col.setColumnWidth(col.getMinimalWidth());
                r += cell.getRowspan();
            }
            else
                r++;
        }
    }
382097
def sum(data, start=0):
    
    n, d = exact_ratio(start)
    T = type(start)
    partials = {d: n}  # map {denominator: sum of numerators}
    # Micro-optimizations.
    coerce_types_ = coerce_types
    exact_ratio_ = exact_ratio
    partials_get = partials.get
    # Add numerators for each denominator, and track the "current" type.
    for x in data:
        T = coerce_types_(T, type(x))
        n, d = exact_ratio_(x)
        partials[d] = partials_get(d, 0) + n
    if None in partials:
        assert issubclass(T, (float, Decimal))
        assert not isfinite(partials[None])
        return T(partials[None])
    total = Fraction()
    for d, n in sorted(partials.items()):
        total += Fraction(n, d)
    if issubclass(T, int):
        assert total.denominator == 1
        return T(total.numerator)
    if issubclass(T, Decimal):
        return T(total.numerator) / total.denominator
    return T(total)
1028830
def categorical__int(self, column_name, output_column_prefix):
        

        return [_ColumnFunctionTransformation(
            features = [column_name],
            output_column_prefix = output_column_prefix,
            transform_function = lambda col: col.astype(str),
            transform_function_name = "astype(str)")]
111386
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
                filter_type=None, **kwds):
        
        delegate = self._values

        if axis is not None:
            self._get_axis_number(axis)

        if isinstance(delegate, Categorical):
            # TODO deprecate numeric_only argument for Categorical and use
            # skipna as well, see GH25303
            return delegate._reduce(name, numeric_only=numeric_only, **kwds)
        elif isinstance(delegate, ExtensionArray):
            # dispatch to ExtensionArray interface
            return delegate._reduce(name, skipna=skipna, **kwds)
        elif is_datetime64_dtype(delegate):
            # use DatetimeIndex implementation to handle skipna correctly
            delegate = DatetimeIndex(delegate)

        # dispatch to numpy arrays
        elif isinstance(delegate, np.ndarray):
            if numeric_only:
                raise NotImplementedError('Series.{0} does not implement '
                                          'numeric_only.'.format(name))
            with np.errstate(all='ignore'):
                return op(delegate, skipna=skipna, **kwds)

        # TODO(EA) dispatch to Index
        # remove once all internals extension types are
        # moved to ExtensionArrays
        return delegate._reduce(op=op, name=name, axis=axis, skipna=skipna,
                                numeric_only=numeric_only,
                                filter_type=filter_type, **kwds)
1034807
def _extract_colnum(self, col):
        
        if isinteger(col):
            colnum = col

            if (colnum < 0) or (colnum > (self._ncol-1)):
                raise ValueError(
                    "column number should be in [0,%d]" % (0, self._ncol-1))
        else:
            colstr = mks(col)
            try:
                if self.case_sensitive:
                    mess = "column name '%s' not found (case sensitive)" % col
                    colnum = self._colnames.index(colstr)
                else:
                    mess \
                        = "column name '%s' not found (case insensitive)" % col
                    colnum = self._colnames_lower.index(colstr.lower())
            except ValueError:
                raise ValueError(mess)
        return int(colnum)