Downsample the matrix rows or columns (currently supporting kmeans only). Users can optionally pass in a DataFrame to be downsampled (and this will be incorporated into the network object).
490148
def downsample(self, df=None, ds_type='kmeans', axis='row', num_samples=100, random_state=1000):
    '''
    
    '''

    return downsample_fun.main(self, df, ds_type, axis, num_samples, random_state)
513784
def to_nmatrix
      each_vector.select do |vector|
        vector.numeric? && !vector.include_values?(*Daru::MISSING_VALUES)
      end.map(&:to_a).transpose.to_nm
    end
640000
def _downsample(self, how, **kwargs):
        
        self._set_binner()
        how = self._is_cython_func(how) or how
        ax = self.ax
        obj = self._selected_obj

        if not len(ax):
            # reset to the new freq
            obj = obj.copy()
            obj.index.freq = self.freq
            return obj

        # do we have a regular frequency
        if ax.freq is not None or ax.inferred_freq is not None:

            if len(self.grouper.binlabels) > len(ax) and how is None:

                # let's do an asfreq
                return self.asfreq()

        # we are downsampling
        # we want to call the actual grouper method here
        result = obj.groupby(
            self.grouper, axis=self.axis).aggregate(how, **kwargs)

        result = self._apply_loffset(result)
        return self._wrap_result(result)
26619
def run_norm(net, df=None, norm_type='zscore', axis='row', keep_orig=False):
  '''
  
  '''

  # df here is actually a dictionary of several dataframes, 'mat', 'mat_orig',
  # etc
  if df is None:
    df = net.dat_to_df()

  if norm_type == 'zscore':
    df = zscore_df(df, axis, keep_orig)

  if norm_type == 'qn':
    df = qn_df(df, axis, keep_orig)

  net.df_to_dat(df)
9653
function transpose(matrix) {
	// For NxN matrix
	var n = matrix[0].length;
	var temp;

	// Walk through columns
	for (var i = 0, j = 0; i < n; i++) {
		j = i;
		// Walk through rows
		while (j < n) {
			if (i !== j) {
				temp = matrix[i][j];
				matrix[i][j] = matrix[j][i];
				matrix[j][i] = temp;
			}
			j++;
		}
	}
}
966043
def matrix_from_edges(edges):
    ''''''
    max_col = 0
    cols = []
    rows = []
    vals = []
    if type(edges) is defaultdict:
        edge_list = []
        for i, neighbors in edges.items():
            for j in neighbors:
                if i <= j:
                    edge_list.append((i,j))
        edges = edge_list
    for i, edge in enumerate(edges):
        s, t = edge[0], edge[1]
        weight = 1 if len(edge) == 2 else edge[2]
        cols.append(min(s,t))
        cols.append(max(s,t))
        rows.append(i)
        rows.append(i)
        vals.append(weight)
        vals.append(-weight)
        if cols[-1] > max_col:
            max_col = cols[-1]
    return coo_matrix((vals, (rows, cols)), shape=(rows[-1]+1, max_col+1))
581978
def create_matrixes(chip, input, df, args):
    # type: (Iterable[pd.DataFrame], Iterable[pd.DataFrame], pd.DataFrame, Namespace) -> List[pd.DataFrame]
    ""

    genome = args.chromosome_sizes

    chip = put_dfs_in_chromosome_dict(chip)
    input = put_dfs_in_chromosome_dict(input)
    all_chromosomes = natsorted(set(list(chip.keys()) + list(input.keys())))

    # print("df1\n", df, file=sys.stderr)
    islands = enriched_bins(df, args)
    # print("islands1\n", islands, file=sys.stderr)


    logging.info("Creating matrixes from count data.")
    dfms = Parallel(n_jobs=args.number_cores)(delayed(_create_matrixes)(
        chromosome, chip, input, islands, genome[chromosome],
        args.window_size) for chromosome in all_chromosomes)

    return dfms
126078
def conv_block_downsample(x,
                          kernel,
                          strides,
                          padding,
                          separability=0,
                          name=None,
                          reuse=None):
  """"""
  with tf.variable_scope(
      name, default_name="conv_block_downsample", values=[x], reuse=reuse):
    hidden_size = int(x.get_shape()[-1])
    res = conv_block(
        x,
        int(1.25 * hidden_size), [((1, 1), kernel)],
        padding=padding,
        strides=strides,
        name="res_conv")

    x = subseparable_conv_block(
        x,
        hidden_size, [((1, 1), kernel)],
        padding=padding,
        separability=separability,
        name="conv0")
    x = subseparable_conv_block(
        x,
        int(1.25 * hidden_size), [((1, 1), kernel)],
        padding=padding,
        separability=separability,
        name="conv1")
    x = pool(x, kernel, "MAX", padding, strides=strides)

    x += res

    x = subseparable_conv_block(
        x,
        2 * hidden_size, [((1, 1), kernel)],
        first_relu=False,
        padding=padding,
        separability=separability,
        name="conv2")
    x = subseparable_conv_block(
        x,
        int(2.5 * hidden_size), [((1, 1), kernel)],
        padding=padding,
        separability=separability,
        name="conv3")
    return x
67067
def downsample(self, factor):
    
    if int(factor) != factor or factor < 1:
      raise ValueError("Argument `factor` must be a positive integer greater than or equal to 1. Got: <{}>({})", type(factor), factor)

    paths = self.interjoint_paths()

    for i, path in enumerate(paths):
      paths[i] = np.concatenate(
        (path[0::factor, :], path[-1:, :]) # preserve endpoints
      )

    ds_skel = PrecomputedSkeleton.simple_merge(
      [ PrecomputedSkeleton.from_path(path) for path in paths ]
    ).consolidate()
    ds_skel.id = self.id

    # TODO: I'm sure this could be sped up if need be.
    index = {}
    for i, vert in enumerate(self.vertices):
      vert = tuple(vert)
      index[vert] = i

    for i, vert in enumerate(ds_skel.vertices):
      vert = tuple(vert)
      ds_skel.radii[i] = self.radii[index[vert]]
      ds_skel.vertex_types[i] = self.vertex_types[index[vert]]

    return ds_skel
921284
def sample(self, num_rows):
        

        sampled_values = []
        for i in range(num_rows):
            sampled_values.append(self._sample_row())

        return pd.DataFrame(sampled_values, columns=self.columns)
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
626521
def denormalize_bbox(bbox, rows, cols):
    
    if rows == 0:
        raise ValueError('Argument rows cannot be zero')
    if cols == 0:
        raise ValueError('Argument cols cannot be zero')

    x_min, y_min, x_max, y_max = bbox[:4]
    denormalized_bbox = [x_min * cols, y_min * rows, x_max * cols, y_max * rows]
    return denormalized_bbox + list(bbox[4:])
306395
def matrix_to_blockmatrix(self, blocksize):
        
        if self.get_width() % blocksize or self.get_height() % blocksize:
            raise ValueError("Number of rows and columns have to be evenly dividable by blocksize")
        selfBlocks = []
        for columnIndex in range(0, self.get_width() - 1, blocksize):
            for rowIndex in range(0, self.get_height() - 1, blocksize):
                currentBlock = []
                for blockRows in self.get_array(False)[columnIndex:columnIndex + blocksize]:
                    currentBlock += blockRows[rowIndex:rowIndex + blocksize]
                selfBlocks.append(Matrix(blocksize, blocksize, currentBlock, rowBased=False))
        return Matrix(self.get_width() / blocksize, self.get_height() / blocksize, selfBlocks, rowBased=False)
127999
def _resample(self, arrays, ji_windows):
        """"""
        # get a destination array template
        win_dst = ji_windows[self.dst_res]
        aff_dst = self._layer_meta[self._res_indices[self.dst_res][0]]["transform"]
        arrays_dst = list()
        for i, array in enumerate(arrays):
            arr_dst = np.zeros((int(win_dst.height), int(win_dst.width)))
            if self._layer_resolution[i] > self.dst_res:
                resampling = getattr(Resampling, self.upsampler)
            elif self._layer_resolution[i] < self.dst_res:
                resampling = getattr(Resampling, self.downsampler)
            else:
                arrays_dst.append(array.copy())
                continue
            reproject(array, arr_dst,  # arr_dst[0, :, :, i],
                      src_transform=self._layer_meta[i]["transform"],
                      dst_transform=aff_dst,
                      src_crs=self._layer_meta[0]["crs"],
                      dst_crs=self._layer_meta[0]["crs"],
                      resampling=resampling)
            arrays_dst.append(arr_dst.copy())
        arrays_dst = np.stack(arrays_dst, axis=2) # n_images x n x m x 10 would be the synergise format
        return arrays_dst
173161
public static Matrix from1DArray(int rows, int columns, double[] array) {
        return Basic1DMatrix.from1DArray(rows, columns, array);
    }
542371
def dropna(self):
        '''
        
        '''
        new = self.copy()
        tmp = self._dict2DF(self, nan, True)
        new.row_labels = list(tmp.index)
        new.col_labels = list(tmp.columns)
        return new
611382
def downsample_trace(mesh, tol=1.0):
    
    idx = _find_turning_points(mesh, tol)
    if mesh.depths is not None:
        return numpy.column_stack([mesh.lons[0, idx],
                                   mesh.lats[0, idx],
                                   mesh.depths[0, idx]])
    else:
        return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx]])