Reads a Dinosaur tsv file.

    :returns: {featureKey1: {attribute1:value1, attribute2:value2, ...}, ...}

    See also :func:`importPeptideFeatures`
430138
def _importDinosaurTsv(filelocation):
    
    with io.open(filelocation, 'r', encoding='utf-8') as openFile:
        #NOTE: this is pretty similar to importing percolator results, maybe unify in a common function
        lines = openFile.readlines()
        headerDict = dict([[y,x] for (x,y) in enumerate(lines[0].strip().split('\t'))])
        featureDict = dict()
        for linePos, line in enumerate(lines[1:]):
            featureId = str(linePos)
            fields = line.strip().split('\t')
            entryDict = dict()
            for headerName, headerPos in viewitems(headerDict):
                entryDict[headerName] = float(fields[headerPos])
                if headerName in ['rtApex', 'rtEnd', 'rtStart', 'fwhm']:
                    #Covnert to seconds
                    entryDict[headerName] *= 60
                elif headerName in ['charge', 'intensitySum', 'nIsotopes', 'nScans', 'intensityApex']:
                    entryDict[headerName] = int(entryDict[headerName])
            featureDict[featureId] = entryDict
    return featureDict
623295
def _readlines(fname, fpointer1=open, fpointer2=open):  # pragma: no cover
    """"""
    # fpointer1, fpointer2 arguments to ease testing
    try:
        with fpointer1(fname, "r") as fobj:
            return fobj.readlines()
    except UnicodeDecodeError:  # pragma: no cover
        with fpointer2(fname, "r", encoding="utf-8") as fobj:
            return fobj.readlines()
987607
private TreeMap<Integer, Pair<String, String>> loadFeatureName(Map<String, Integer> featureIndex, BufferedReader br) throws Exception {

		TreeMap<Integer, Pair<String, String>> featureNames = new TreeMap<Integer, Pair<String, String>>();

		String temp = null;
		while (StringUtil.isNotBlank(temp = br.readLine())) {

			int indexOf = temp.indexOf(" ");

			int id = ObjConver.getIntValue(temp.substring(0, indexOf));

			if (indexOf > 0) {
				temp = temp.substring(indexOf);
			}

			String[] split = temp.split(":");

			if (split.length == 1) {
				featureNames.put(id, Pair.with(temp.trim(), ""));
			} else {
				String name = split[1];
				if (split.length > 2) {
					for (int j = 2; j < split.length; j++) {
						name += ":" + split[j];
					}
				}

				int lastFeatureId = featureIndex.get(split[0].trim());

				if ("/".equals(name)) {
					name = "//";
				}

				if (name.contains("//")) {
					name = name.replaceAll("//", "/XIEGANG/");
				}
				String featureName = toFeatureName(name.trim().split("/"), lastFeatureId);

				featureNames.put(id, Pair.with(split[0].trim(), featureName));

			}

		}

		return featureNames;

	}
223662
def read_file(filename):
    
    dtype = np.dtype([('same_cell', np.int32),
                      ('N1', np.int),
                      ('N2', np.int),
                      ('time', np.float)
                      ])
    if pd is not None:
        timings = pd.read_csv(filename, header=None,
                              engine="c",
                              dtype={'same_cell': np.int32,
                                     'N1': np.int,
                                     'N2': np.int,
                                     'time': np.float},
                              index_col=None,
                              names=['same_cell', 'N1', 'N2', 'time'],
                              delim_whitespace=True)
    else:
        timings = np.loadtxt(filename, dtype=dtype)
    return timings
7695
def extract_feature_order_from_model_xml(file_path):
    

    root = xml.etree.ElementTree.parse(file_path).getroot()
    feature_order_node = root.find('featureOrder')

    features = []
    for child in feature_order_node:
        features.append(child.attrib['name'])

    return features
957725
def read(*components, **kwargs):
    
    rstrip = kwargs.get("rstrip", True)
    comment_char = kwargs.get("comment_char", None)

    ignore_comments = comment_char is not None

    file = open(path(*components))
    lines = file.readlines()
    file.close()

    # Multiple definitions to handle all cases.
    if ignore_comments:
        comment_line_re = re.compile("^\s*{char}".format(char=comment_char))
        not_comment_re = re.compile("[^{char}]+".format(char=comment_char))

        if rstrip:
            # Ignore comments, and right strip results.
            return [re.match(not_comment_re, line).group(0).rstrip()
                    for line in lines
                    if not re.match(comment_line_re, line)]
        else:
            # Ignore comments, and don't strip results.
            return [re.match(not_comment_re, line).group(0)
                    for line in lines
                    if not re.match(comment_line_re, line)]
    elif rstrip:
        # No comments, and right strip results.
        return [line.rstrip() for line in lines]
    else:
        # Just a good old-fashioned read!
        return lines
1048861
def read_objfile(fname):
    """"""
    verts = defaultdict(list)
    obj_props = []
    with open(fname) as f:
        lines = f.read().splitlines()

    for line in lines:
        if line:
            split_line = line.strip().split(' ', 1)
            if len(split_line) < 2:
                continue

            prefix, value = split_line[0], split_line[1]
            if prefix == 'o':
                obj_props.append({})
                obj = obj_props[-1]
                obj['f'] = []
                obj[prefix] = value
            # For files without an 'o' statement
            elif prefix == 'v' and len(obj_props) < 1:
                obj_props.append({})
                obj = obj_props[-1]
                obj['f'] = []
                obj['o'] = fname
            if obj_props:
                if prefix[0] == 'v':
                    verts[prefix].append([float(val) for val in value.split(' ')])
                elif prefix == 'f':
                    obj[prefix].append(parse_mixed_delim_str(value))
                else:
                    obj[prefix] = value


    # Reindex vertices to be in face index order, then remove face indices.
    verts = {key: np.array(value) for key, value in iteritems(verts)}
    for obj in obj_props:
        obj['f'] = tuple(np.array(verts) if verts[0] else tuple() for verts in zip(*obj['f']))
        for idx, vertname in enumerate(['v' ,'vt', 'vn']):
            if vertname in verts:
                obj[vertname] = verts[vertname][obj['f'][idx].flatten() - 1, :]
            else:
                obj[vertname] = tuple()
        del obj['f']

    geoms = {obj['o']:obj for obj in obj_props}

    return geoms
120641
def read_dependent_peptides(filename):
    
    df = (pd.read_perseus(filename, usecols=_cols)
            .dropna(subset=['DP Ratio mod/base']))
    df['DP Ratio mod/base'] = df['DP Ratio mod/base'].astype(float)
    dep = df.pivot_table('DP Ratio mod/base', index=_index_columns,
                columns='Raw file', aggfunc=np.median)
    localization = _count_localizations(df)
    return dep, localization
854979
def infer_delimiter(filepath):
    
    ext = os.path.splitext(filepath)[1][1:].lower()
    return {"txt": "\t", "tsv": "\t", "csv": ","}.get(ext)
1221827
def _variable_type_to_read_fn(vartype, records):
    
    fn_map = {"String": "read_string", "Array[String]": "read_lines",
              "Array[Array[String]]": "read_tsv",
              "Object": "read_object", "Array[Object]": "read_objects",
              "Array[Array[Object]]": "read_objects",
              "Int": "read_int", "Float": "read_float"}
    for rec_name in records.keys():
        fn_map["%s" % rec_name] = "read_struct"
        fn_map["Array[%s]" % rec_name] = "read_struct"
        fn_map["Array[Array[%s]]" % rec_name] = "read_struct"
    # Read in Files as Strings
    vartype = vartype.replace("File", "String")
    # Can't read arrays of Ints/Floats
    vartype = vartype.replace("Array[Int]", "Array[String]")
    vartype = vartype.replace("Array[Float]", "Array[String]")
    return fn_map[vartype]
959800
def _read_method(schema):
    
    def func(
        self,
        filename,
        seq_label='sequence',
        alphabet=None,
        combine_on='uid',
        use_uids=True,
        **kwargs):
        # Use generic write class to write data.
        df0 = self._data
        df1 = _read(
            filename=filename,
            schema=schema,
            seq_label=seq_label,
            alphabet=alphabet,
            use_uids=use_uids,
            **kwargs
        )
        return df0.phylo.combine(df1, on=combine_on)

    # Update docs
    func.__doc__ = _read_doc_template(schema)
    return func
330209
def _parse_gene_coordinates(file):
        
        id_map = {}
        col = ['gene_curie', 'start', 'end', 'strand', 'build']
        if os.path.exists(os.path.join(os.path.dirname(__file__), file)):
            with open(os.path.join(os.path.dirname(__file__), file)) as tsvfile:
                reader = csv.reader(tsvfile, delimiter="\t")
                for row in reader:
                    id_map[row[col.index('gene_curie')]] = {
                        'start': row[col.index('start')],
                        'end': row[col.index('end')],
                        'strand': row[col.index('strand')],
                        'build': row[col.index('build')]
                    }
        return id_map
899349
def _read_tRNA_scan(summary_file):
    
    score = 0
    if os.path.getsize(summary_file) == 0:
        return 0
    with open(summary_file) as in_handle:
        # header = in_handle.next().strip().split()
        for line in in_handle:
            if not line.startswith("--"):
                pre = line.strip().split()
                score = pre[-1]
    return score
633835
def shp_dict(shp_fn, fields=None, geom=True):
    
    from pygeotools.lib import timelib
    ds = ogr.Open(shp_fn)
    lyr = ds.GetLayer()
    nfeat = lyr.GetFeatureCount()
    print('%i input features\n' % nfeat)
    if fields is None:
        fields = shp_fieldnames(lyr)
    d_list = []
    for n,feat in enumerate(lyr):
        d = {}
        if geom:
            geom = feat.GetGeometryRef()
            d['geom'] = geom
        for f_name in fields:
            i = str(feat.GetField(f_name))
            if 'date' in f_name:
                # date_f = f_name
                #If d is float, clear off decimal
                i = i.rsplit('.')[0]
                i = timelib.strptime_fuzzy(str(i))
            d[f_name] = i
        d_list.append(d)
    #d_list_sort = sorted(d_list, key=lambda k: k[date_f])
    return d_list
1296771
def read(filename):
    
    # The format is specified at
    # <http://www.intes.de>.

    cells = {}
    meshio_to_permas_type = {
        "vertex": (1, "PLOT1"),
        "line": (2, "PLOTL2"),
        "triangle": (3, "TRIA3"),
        "quad": (4, "QUAD4"),
        "tetra": (4, "TET4"),
        "hexahedron": (8, "HEXE8"),
        "wedge": (6, "PENTA6"),
        "pyramid": (5, "PYRA5"),
    }

    opener = gzip.open if filename.endswith(".gz") else open

    with opener(filename, "rb") as f:
        while True:
            line = f.readline().decode("utf-8")
            if not line or re.search("\\$END STRUCTURE", line):
                break
            for meshio_type, permas_ele in meshio_to_permas_type.items():
                num_nodes = permas_ele[0]
                permas_type = permas_ele[1]

                if re.search("\\$ELEMENT TYPE = {}".format(permas_type), line):
                    while True:
                        line = f.readline().decode("utf-8")
                        if not line or line.startswith("!"):
                            break
                        data = numpy.array(line.split(), dtype=int)
                        if meshio_type in cells:
                            cells[meshio_type].append(data[-num_nodes:])
                        else:
                            cells[meshio_type] = [data[-num_nodes:]]

            if re.search("\\$COOR", line):
                points = []
                while True:
                    line = f.readline().decode("utf-8")
                    if not line or line.startswith("!"):
                        break
                    for r in numpy.array(line.split(), dtype=float)[1:]:
                        points.append(r)

    points = numpy.array(points)
    points = numpy.reshape(points, newshape=(len(points) // 3, 3))
    for key in cells:
        # Subtract one to account for the fact that python indices
        # are 0-based.
        cells[key] = numpy.array(cells[key], dtype=int) - 1

    return Mesh(points, cells)
394373
def read(filename,**kwargs):
    
    base,ext = os.path.splitext(filename)
    if ext in ('.fits','.fz'):
        # Abstract fits here...
        return fitsio.read(filename,**kwargs)
    elif ext in ('.npy'):
        return np.load(filename,**kwargs)
    elif ext in ('.csv'):
        return np.recfromcsv(filename,**kwargs)
    elif ext in ('.txt','.dat'):
        return np.genfromtxt(filename,**kwargs)

    msg = "Unrecognized file type: %s"%filename
    raise ValueError(msg)
813314
def _parse_features(cls, feat_response):
        # type: (Text) -> Dict[Text, Text]
        
        features = {}
        if feat_response.split("-")[0] == "211":
            for line in feat_response.splitlines():
                if line.startswith(" "):
                    key, _, value = line[1:].partition(" ")
                    features[key] = value
        return features