reads in standard position weight matrix format,
    rows are different types of base, columns are individual residues
345067
def pWMRead(fileHandle, alphabetSize=4):
    
    lines = fileHandle.readlines()
    assert len(lines) == alphabetSize
    l = [ [ float(i) ] for i in lines[0].split() ]
    for line in lines[1:]:
        l2 = [ float(i) for i in line.split() ]
        assert len(l) == len(l2)
        for i in xrange(0, len(l)):
            l[i].append(l2[i])
    for i in xrange(0, len(l)):
        j = sum(l[i]) + 0.0
        l[i] = [ k/j for k in l[i] ]
    return l
97102
private static Matrix readMatlabSparse(
             File matrixFile,
             Type matrixType,
             boolean transposeOnRead) throws IOException {

         Matrix matrix = new GrowingSparseMatrix();
         BufferedReader br = new BufferedReader(new FileReader(matrixFile));
         for (String line = null; (line = br.readLine()) != null; ) {
             String[] rowColVal = line.split("\\s+");
             int row = Integer.parseInt(rowColVal[0]) - 1;
             int col = Integer.parseInt(rowColVal[1]) - 1;
             double value = Double.parseDouble(rowColVal[2]);
             if (transposeOnRead)
                 matrix.set(col, row, value);
             else
                 matrix.set(row, col, value);
         }
         br.close();
         return matrix;
     }
412239
function _Matrix(numRows, numColumns, data) {
  if(!Number.isInteger(numRows))
    throw new TypeError("/numRows/ must be an integer.");
  if(!Number.isInteger(numColumns))
      throw new TypeError("/numColumns/ must be an integer.");

  var _values;
  var _numValues = numRows * numColumns;
  if (!data || data === undefined)
    _values = [];
  else if (!util.isNumberArray(data))
    throw new TypeError('Invalid values for vector.');
  else
    _values = data;

  // Make sure the matrix has numRows * numColumns values
  if (_values.length < _numValues) {
    var zeros = Array(_numValues - _values.length).fill(0);
    _values = _values.concat(zeros);
  } else if (_values.length > _numValues) {
    _values = _values.slice(0, _numValues);
  }

  var size = {"rows": numRows, "columns": numColumns};
  readonly(this, "size", size);
  readonly(this, "values", _values);
  readonly(this, "rows", _getRows(this));
  readonly(this, "columns", _getColumns(this));
}
684082
def ReadLsbBytes(rd, offset, value_size):
  """"""

  encoding = None
  if value_size == 1:
    encoding = '<B'
  elif value_size == 2:
    encoding = '<H'
  elif value_size == 4:
    encoding = '<L'
  else:
    raise errors.HidError('Invalid value size specified')

  ret, = struct.unpack(encoding, rd[offset:offset + value_size])
  return ret
274869
def M(self, t, tips=None, gaps=None):
        """"""
        assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t)
        with scipy.errstate(under='ignore'): # don't worry if some values 0
            if ('expD', t) not in self._cached:
                self._cached[('expD', t)] = scipy.exp(self.D * self.mu * t)
            expD = self._cached[('expD', t)]
            # swap axes to broadcast multiply D as diagonal matrix
            temp = scipy.ascontiguousarray((self.A.swapaxes(0, 1)
                    * expD).swapaxes(1, 0), dtype=float)
            M = broadcastMatrixMultiply(temp, self.Ainv)
            assert M.min() > -1e-3, "Overly negative M: {0}".format(M.min())
            M[M < 0] = 0.0
            if tips is None:
                return scipy.tile(M, (self.nsites, 1, 1))
            else:
                newM = scipy.zeros((len(tips), N_CODON))
                for i in range(len(tips)):
                    newM[i] =(M[0][:,tips[i]])
                if gaps is not None:
                    newM[gaps] = scipy.ones(N_CODON, dtype='float')
                return newM
985566
def read_in_weight_table(self, in_weight_table):
        
        print("Reading the weight table...")
        with open_csv(in_weight_table, "r") as csvfile:
            reader = csv.reader(csvfile)
            header_row = next(reader)
            # check number of columns in the weight table
            if len(header_row) < len(self.header_wt):
                raise Exception(self.error_messages[4])
            # check header
            if header_row[1:len(self.header_wt)] != self.header_wt[1:]:
                raise Exception(self.error_messages[5])

        self.dict_list = \
            np.loadtxt(
                in_weight_table,
                delimiter=",",
                usecols=(0, 1, 2, 3, 4),
                skiprows=1,
                dtype={
                    'names': (self.header_wt[0],
                              self.header_wt[1],
                              self.header_wt[2],
                              self.header_wt[3],
                              self.header_wt[4]),
                    'formats': ('i8', 'f8', 'i8', 'i8', 'i8')
                },
            )

        self.count = self.dict_list.shape[0]
        self.size_stream_id = \
            len(np.unique(np.array(self.dict_list[self.header_wt[0]],
                                   dtype=np.int32)))
1171176
def parse_blosum_table(table, coeff_type=int, key_type='row'):
    

    lines = table.split("\n")
    # drop comments
    lines = [line for line in lines if not line.startswith("#")]
    # drop CR endline characters
    lines = [line.replace("\r", "") for line in lines]
    # skip empty lines
    lines = [line for line in lines if line]

    labels = lines[0].split()

    if len(labels) < 20:
        raise ValueError(
            "Expected 20+ amino acids but first line '%s' has %d fields" % (
                lines[0],
                len(labels)))
    coeffs = {}
    for line in lines[1:]:

        fields = line.split()
        assert len(fields) >= 21, \
            "Expected AA and 20+ coefficients but '%s' has %d fields" % (
                line, len(fields))
        x = fields[0]
        for i, coeff_str in enumerate(fields[1:]):
            y = labels[i]
            coeff = coeff_type(coeff_str)
            if key_type == 'pair':
                coeffs[(x, y)] = coeff
            elif key_type == 'pair_string':
                coeffs[x + y] = coeff
            else:
                assert key_type == 'row', "Unknown key type: %s" % key_type
                if x not in coeffs:
                    coeffs[x] = {}
                coeffs[x][y] = coeff
    return coeffs
296388
def rst_table(self, array):
        """"""
        # Determine cell width for each column
        cell_dict = {}
        for i, row in enumerate(array):
            for j, val in enumerate(row):
                if j not in cell_dict:
                    cell_dict[j] = []
                cell_dict[j].append(val)
        for item in cell_dict:
            cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1  # Contains adapted width for each column

        # Format top line
        num_cols = len(array[0])
        form = '+'
        for col in range(num_cols):
            form += (cell_dict[col] + 1) * '-'
            form += '+'
        form += '\n'

        # Format values
        for i, row in enumerate(array):
            form += '| '
            for j, val in enumerate(row):
                cell_width = cell_dict[j]
                form += str(val) + (cell_width - len(val)) * ' ' + '| '
            form.rstrip()
            form += '\n'

            # Seperation lines
            form += '+'
            if i == 0:
                sign = '='
            else:
                sign = '-'
            for col in range(num_cols):
                form += (cell_dict[col] + 1) * sign
                form += '+'
            form += '\n'
        return form
1064830
def _fileToMatrix(file_name):
    """"""
    # TODO: np.loadtxt() might be an alternative
    #     try:
    if 1 < 3:
        lres = []
        for line in open(file_name, 'r').readlines():
            if len(line) > 0 and line[0] not in ('%', '#'):
                lres.append(list(map(float, line.split())))
        res = lres
    while res != [] and res[0] == []:  # remove further leading empty lines
        del res[0]
    return res
    #     except:
    print('could not read file ' + file_name)
507679
def readTableFromDelimited(f, separator="\t"):
    
    rowNames = []
    columnNames = []
    matrix = []

    first = True
    for line in f.readlines():
        line = line.rstrip()
        if len(line) == 0:
            continue

        row = line.split(separator)
        if first:
            columnNames = row[1:]
            first = False
        else:
            rowNames.append(row[0])
            matrix.append([float(c) for c in row[1:]])

    return Table(rowNames, columnNames, matrix)
396285
def mkcols(l, rows):
    '''
    
    '''
    cols = []
    base = 0
    while len(l) > rows and len(l) % rows != 0:
        l.append("")
    for i in range(rows, len(l) + rows, rows):
        cols.append(l[base:i])
        base = i
    return cols
339302
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False):
    ''''''
    return '[{0}]'.format("\n  ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
511246
def _read_v3_10x_h5(filename):
    
    with tables.open_file(str(filename), 'r') as f:
        try:
            dsets = {}
            for node in f.walk_nodes('/matrix', 'Array'):
                dsets[node.name] = node.read()
            from scipy.sparse import csr_matrix
            M, N = dsets['shape']
            data = dsets['data']
            if dsets['data'].dtype == np.dtype('int32'):
                data = dsets['data'].view('float32')
                data[:] = dsets['data']
            matrix = csr_matrix((data, dsets['indices'], dsets['indptr']),
                                shape=(N, M))
            adata = AnnData(matrix,
                            {'obs_names': dsets['barcodes'].astype(str)},
                            {'var_names': dsets['name'].astype(str),
                             'gene_ids': dsets['id'].astype(str),
                             'feature_types': dsets['feature_type'].astype(str),
                             'genome': dsets['genome'].astype(str)})
            logg.info(t=True)
            return adata
        except KeyError:
            raise Exception('File is missing one or more required datasets.')
949625
def table2matrix(table):
    """"""

    if not is_simpletable(table):
        raise NotSimpleTable("Not able read a cell in the table as a string")
    rows = []
    for tr in table('tr'):
        row = []
        for td in tr('td'):
            td = tdbr2EOL(td) # convert any '<br>' in the td to line ending
            try:
                row.append(td.contents[0])
            except IndexError:
                row.append('')
        rows.append(row)
    return rows
67059
function dfFromMatrixHelper(matrix, startRow, colNames) {
  var nCol = colNames.size();
  var nRow = matrix.length - startRow;
  var columns = allocArray(nCol);
  var j;
  for (j = 0; j < nCol; j++) {
    columns[j] = allocArray(nRow);
  }
  for (var i = 0; i < nRow; i++) {
    var rowArray = matrix[i + startRow];
    if (rowArray.length !== nCol) {
      throw new Error('all row arrays must be of the same size');
    }
    for (j = 0; j < nCol; j++) {
      columns[j][i] = rowArray[j];
    }
  }
  return newDataFrame(columns, colNames);
}
638711
def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ):
    
    alignment = Alignment(species_to_lengths=species_to_lengths)
    # Attributes line
    line = readline( file, skip_blank=True )
    if not line: return None
    fields = line.split() 
    if fields[0] != 'a': raise Exception("Expected 'a ...' line")
    alignment.attributes = parse_attributes( fields[1:] )
    if 'score' in alignment.attributes:
        alignment.score = alignment.attributes['score']
        del alignment.attributes['score']
    else:
        alignment.score = 0
    # Sequence lines
    last_component = None
    while 1:
        line = readline( file )
        # EOF or Blank line terminates alignment components
        if not line or line.isspace(): break
        if line.isspace(): break 
        # Parse row
        fields = line.split()
        if fields[0] == 's':
            # An 's' row contains sequence for a component
            component = Component()
            component.src = fields[1]
            component.start = int( fields[2] )
            component.size = int( fields[3] )
            component.strand = fields[4]
            component.src_size = int( fields[5] )
            if len(fields) > 6: component.text = fields[6].strip()
            # Add to set
            alignment.add_component( component )
            last_component = component
        elif fields[0] == 'e':
            # An 'e' row, when no bases align for a given species this tells
            # us something about the synteny 
            if parse_e_rows:
                component = Component()
                component.empty = True
                component.src = fields[1]
                component.start = int( fields[2] )
                component.size = int( fields[3] )
                component.strand = fields[4]
                component.src_size = int( fields[5] )
                component.text = None
                synteny = fields[6].strip()
                assert len( synteny ) == 1, \
                    "Synteny status in 'e' rows should be denoted with a single character code"
                component.synteny_empty = synteny
                alignment.add_component( component )
                last_component = component
        elif fields[0] == 'i':
            # An 'i' row, indicates left and right synteny status for the 
            # previous component, we hope ;)
            assert fields[1] == last_component.src, "'i' row does not follow matching 's' row"
            last_component.synteny_left = ( fields[2], int( fields[3] ) )
            last_component.synteny_right = ( fields[4], int( fields[5] ) )
        elif fields[0] == 'q':
            assert fields[1] == last_component.src, "'q' row does not follow matching 's' row"
            # TODO: Should convert this to an integer array?
            last_component.quality = fields[2]
            
    return alignment
593181
function _getColumns(matrix) {
  var cols = [];
  for (var i=0; i<matrix.size.columns; i++) {
    cols.push([]);
    for (var j=0; j<matrix.size.rows; j++)
      cols[i].push(matrix.values[i + j * matrix.size.columns]);
  }
  return cols;
}