Returns a Dade matrix from input numpy matrix. Any annotations are added
    as header. If filename is provided and valid, said matrix is also saved
    as text.
422540
def to_dade_matrix(M, annotations="", filename=None):
    

    n, m = M.shape
    A = np.zeros((n + 1, m + 1))
    A[1:, 1:] = M
    if not annotations:
        annotations = np.array(["" for _ in n], dtype=str)
    A[0, :] = annotations
    A[:, 0] = annotations.T
    if filename:
        try:
            np.savetxt(filename, A, fmt='%i')
            print("I saved input matrix in dade format as " + str(filename))
        except ValueError as e:
            print("I couldn't save input matrix.")
            print(str(e))
        finally:
            return A

    return A
1301266
def get_font_matrix(self):
        
        matrix = Matrix()
        cairo.cairo_get_font_matrix(self._pointer, matrix._pointer)
        self._check_status()
        return matrix
931250
def to_sympy_column_matrix(matrix):
    
    matrix = to_sympy_matrix(matrix)
    if matrix.cols == 1:
        return matrix
    elif matrix.rows == 1:
        return matrix.T
    else:
        raise ValueError('Cannot convert {0!r} to a column matrix'.format(matrix))
745894
def matrix(fasta_path: 'path to tictax annotated fasta input',
           scafstats_path: 'path to BBMap scaftstats file'):
    '''
    
    '''
    records = SeqIO.parse(fasta_path, 'fasta')
    df = tictax.matrix(records, scafstats_path)
    df.to_csv(sys.stdout)
105721
private Matrix<Double> generateIdentityMatrix(final int numDimension) {
    final List<List<Double>> rows = new ArrayList<>(numDimension);
    for (int i = 0; i < numDimension; i++) {
      final List<Double> row = new ArrayList<>(numDimension);
      for (int j = 0; j < numDimension; j++) {
        final double value = i == j ? 1 : 0;
        row.add(value);
      }
      rows.add(row);
    }
    return new RowMatrix(rows);
  }
942870
public static SimpleMatrix loadBinary( String fileName )
            throws IOException {
        DMatrix mat = MatrixIO.loadBin(fileName);

        // see if its a DMatrixRMaj
        if( mat instanceof DMatrixRMaj) {
            return SimpleMatrix.wrap((DMatrixRMaj)mat);
        } else {
            // if not convert it into one and wrap it
            return SimpleMatrix.wrap( new DMatrixRMaj(mat));
        }
    }
793840
def load_data(filename):
    
    data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9)
    return data.as_matrix()
655298
def matrix(self) -> np.ndarray:
        
        num_qubits = self.num_qubits()
        if num_qubits is None:
            raise ValueError('Unknown number of qubits')
        num_dim = 2 ** num_qubits
        result = np.zeros((num_dim, num_dim), dtype=np.complex128)
        for gate, coefficient in self.items():
            result += protocols.unitary(gate) * coefficient
        return result
198839
def array(self):
        
        if self.bands == 1:
            return self.matrix()
        else:
            arr = self.raster.ReadAsArray().transpose(1, 2, 0)
            if isinstance(self.nodata, list):
                for i in range(0, self.bands):
                    arr[:, :, i][arr[:, :, i] == self.nodata[i]] = np.nan
            else:
                arr[arr == self.nodata] = np.nan
            return arr
491890
def _from_numpy(np_array):
    

    # Convert the numpy array to nd4j context dtype
    required_dtype = get_np_dtype(get_context_dtype())
    if np_array.dtype != required_dtype:
        raise Exception("{} is required, got {}".format(
            repr(required_dtype), repr(np_array.dtype)))

    # Nd4j does not have 1-d vectors.
    # So we add a dummy dimension.
    if np_array.ndim == 1:
        np_array = np.expand_dims(np_array, 0)

    # We have to maintain references to all incoming
    # numpy arrays. Else they will get GCed

    # creates a Nd4j array from a numpy array
    # To create an Nd4j array, we need 3 things:
    # buffer, strides, and shape

    # Get the buffer
    # A buffer is basically an array. To get the buffer object
    # we need a pointer to the first element and the size.
    pointer_address, _ = np_array.__array_interface__['data']
    _refs.append(np_array)
    pointer = native_ops.pointerForAddress(pointer_address)
    size = np_array.size
    mapping = {
        np.float64: DoublePointer,
        np.float32: FloatPointer,
    }
    pointer = mapping[required_dtype](pointer)
    buff = Nd4j.createBuffer(pointer, size)
    assert buff.address() == pointer_address
    _refs.append(buff)
    # Get the strides
    # strides = tuple of bytes to step in each
    # dimension when traversing an array.
    elem_size = buff.getElementSize()
    # Make sure word size is same in both python
    # and java worlds
    assert elem_size == np_array.dtype.itemsize
    strides = np_array.strides
    # numpy uses byte wise strides. We have to
    # convert it to word wise strides.
    strides = [dim / elem_size for dim in strides]

    # Finally, shape:
    shape = np_array.shape

    nd4j_array = Nd4j.create(buff, shape, strides, 0)
    assert buff.address() == nd4j_array.data().address()
    return nd4j_array
625827
def numpy_array_from_list_or_numpy_array(vectors):
    
    # If vectors is not a numpy matrix, create one
    if not isinstance(vectors, numpy.ndarray):
        V = numpy.zeros((vectors[0].shape[0], len(vectors)))
        for index in range(len(vectors)):
            vector = vectors[index]
            V[:, index] = vector
        return V

    return vectors
1130715
def get_numpy_array(self):
        
        # This holds the obect's spectral data, and will be passed to
        # numpy.array() to create a numpy array (matrix) for the matrix math
        # that will be done during the conversion to XYZ.
        values = []

        # Use the required value list to build this dynamically. Default to
        # 0.0, since that ultimately won't affect the outcome due to the math
        # involved.
        for val in self.VALUES:
            values.append(getattr(self, val, 0.0))

        # Create and the actual numpy array/matrix from the spectral list.
        color_array = numpy.array([values])
        return color_array
1209275
function getMatrix(data) {
    var matrix = init(data.version);
    fillFinders(matrix);
    fillAlignAndTiming(matrix);
    fillStub(matrix);

    var penalty = Infinity;
    var bestMask = 0;
    for (var mask = 0; mask < 8; mask++) {
        fillData(matrix, data, mask);
        fillReserved(matrix, data.ec_level, mask);
        var p = calculatePenalty(matrix);
        if (p < penalty) {
            penalty = p;
            bestMask = mask;
        }
    }

    fillData(matrix, data, bestMask);
    fillReserved(matrix, data.ec_level, bestMask);

    return matrix.map(function(row) {
        return row.map(function(cell) {
            return cell & 1;
        });
    });
}
571758
def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
        """"""

        self.matrix = scipy.io.mmread(filename)
        with open(filename + ".rownames") as in_handle:
            self.rownames = [x.strip() for x in in_handle]
            if rowprefix:
                self.rownames = [rowprefix + delim + x for x in self.rownames]
        with open(filename + ".colnames") as in_handle:
            self.colnames = [x.strip() for x in in_handle]
            if colprefix:
                self.colnames = [colprefix + delim + x for x in self.colnames]
1204835
private static Matrix readDenseTextMatrix(File matrix, Type matrixType,
                                              boolean transposeOnRead) 
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(matrix));

        // unknown number of rows, so do a quick scan to determine it
        int rows = 0;
        int cols = -1;
        for (String line = null; (line = br.readLine()) != null; rows++) {
            // Create a scanner to parse out the values from the current line of
            // the file.
            Scanner s = new Scanner(line);
            s.useLocale(Locale.US);
            int vals = 0;
            // Count how many columns the row has
            for (; s.hasNextDouble(); vals++, s.nextDouble())
                ;

            // Base case if the number of columns has not been set
            if (cols == -1) 
                cols = vals;
            // Otherwise, ensure that the number of values in the current row
            // matches the number of values seen in the first
            else {
                if (cols != vals) {
                    throw new MatrixIOException("line " + (rows + 1) + 
                        " contains an inconsistent number of columns. " +
                        cols + " columns expected versus " + vals + " found.");
                }
            }
        }
        br.close();

        if (MATRIX_IO_LOGGER.isLoggable(Level.FINE)) {
            MATRIX_IO_LOGGER.fine("reading in text matrix with " + rows  +
                                  " rows and " + cols + " cols");
        }

        // Once the matrix has had its dimensions determined, re-open the file
        // to load the data into a Matrix instance.  Use a Scanner to parse the
        // text for us.
        Scanner scanner = new Scanner(matrix);
        scanner.useLocale(Locale.US);
        Matrix m = (transposeOnRead)
            ? Matrices.create(cols, rows, matrixType)
            : Matrices.create(rows, cols, matrixType);
        
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                double d = scanner.nextDouble();
                if (transposeOnRead)
                    m.set(col, row, d);
                else
                    m.set(row, col, d);
            }
        }
        scanner.close();
        
        return m;
    }
562595
def asML(self):
        
        return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,
                                      self.values, self.isTransposed)
1302149
def weight_matrices(nn):
    

    if isinstance(nn, ndarray):
        return nn

    try:
        return weight_matrices(nn.connections)
    except:
        pass

    try:
        return weight_matrices(nn.module)
    except:
        pass

    # Network objects are ParameterContainer's too, but won't reshape into a single matrix,
    # so this must come after try nn.connections
    if isinstance(nn, (ParameterContainer, Connection)):
        return reshape(nn.params, (nn.outdim, nn.indim))

    if isinstance(nn, basestring):
        try:
            fn = nn
            nn = NetworkReader(fn, newfile=False)
            return weight_matrices(nn.readFrom(fn))
        except:
            pass
    # FIXME: what does NetworkReader output? (Module? Layer?) need to handle it's type here

    try:
        return [weight_matrices(v) for (k, v) in nn.iteritems()]
    except:
        try:
            connections = nn.module.connections.values()
            nn = []
            for conlist in connections:
                nn += conlist
            return weight_matrices(nn)
        except:
            return [weight_matrices(v) for v in nn]