def readMatrix(infile,
               format="full",
               separator="\t",
               numeric_type=numpy.float,
               take="all",
               headers=True,
               missing=None,
               ):
    """read a matrix from file ane return a numpy matrix.

    formats accepted are:
    * full
    * sparse
    * phylip
    """

    row_headers, col_headers = [], []

    lines = filter(lambda x: x[0] != "#", infile.readlines())

    if len(lines) == 0:
        raise IOError("no input")

    if format == "full":

        if headers:
            col_headers = lines[0][:-1].split("\t")[1:]
            del lines[0]

        num_rows = len(lines)

        if take != "all":
            num_cols = len(take)
        else:
            l = len(string.split(lines[0][:-1], "\t"))
            if headers:
                take = range(1, l)
            else:
                take = range(0, l)

        num_cols = len(take)

        matrix = numpy.zeros((num_rows, num_cols), numeric_type)

        nrow = 0
        for l in lines:
            data = l[:-1].split("\t")
            if headers:
                row_headers.append(data[0])

            if missing is None:
                try:
                    data = map(lambda x: float(data[x]), take)
                except ValueError, msg:
                    raise ValueError("error %s: data=%s" % (msg, str(data)))
                except IndexError, msg:
                    raise IndexError("error %s: data=%s" % (msg, str(data)))

            else:
                d = []
                for x in take:
                    try:
                        d.append(float(data[x]))
                    except ValueError:
                        d.append(missing)
                    except __HOLE__, msg:
                        raise IndexError(
                            "error %s: data=%s" % (msg, str(data)))

                data = d

            matrix[nrow] = data

            nrow += 1

    elif format == "phylip":
        # read in symmetric phylip matrices
        # note: they can wrap around
        if take != "all":
            raise "phylip matrix does not support take - only full matrices are processed."

        if not headers:
            raise "phylip matrix always has headers."

        num_rows = int(lines[0].strip())

        num_cols = num_rows

        matrix = numpy.zeros((num_rows, num_cols), numeric_type)
        take = range(1, num_rows)

        nrow = 0
        ncol = 0
        for l in lines[1:]:

            data = re.split("\s+", l[:-1])

            if ncol == 0:
                row_headers.append(data[0])

            try:
                data = map(float, data[1:len(data)])
            except ValueError:
                raise "parsing error in conversion to float in line %s" % l

            for x in range(len(data)):
                matrix[nrow][ncol] = data[x]
                ncol += 1

            # deal with wrapping around
            if ncol == num_cols:
                ncol = 0
                nrow += 1

        col_headers = row_headers

    return matrix, row_headers, col_headers
dataset/ETHPy150Open CGATOxford/cgat/CGAT/MatlabTools.py/readMatrix