return a dict of the lengths of sequences in a fasta file
517311
def sequence_length(fasta):
    
    sequences = SeqIO.parse(fasta, "fasta")
    records = {record.id: len(record) for record in sequences}
    return records
251665
def iterate_over_file(self, fasta_path):
        
        with self._open(fasta_path) as f:
            for line in f:
                line = line.rstrip()

                if len(line) == 0:
                    continue

                # have to slice into a bytes object or else I get a single integer
                first_char = line[0:1]

                if first_char == b">":
                    id_and_seq = self._read_header(line)
                    if id_and_seq is not None:
                        yield id_and_seq

                elif first_char == b";":
                    # semicolon are comment characters
                    continue
                else:
                    self.current_lines.append(line)
        # the last sequence is still in the lines buffer after we're done with
        # the file so make sure to yield it
        id_and_seq = self._current_entry()
        if id_and_seq is not None:
            yield id_and_seq
214164
def get_sequence(self, chrom, start, end, strand=None):
            
        # Check if we have an index_dir
        if not self.index_dir:
            print("Index dir is not defined!")
            sys.exit()

        # retrieve all information for this specific sequence
        fasta_file = self.fasta_file[chrom]
        index_file = self.index_file[chrom]
        line_size = self.line_size[chrom]
        total_size = self.size[chrom]

        #print fasta_file, index_file, line_size, total_size
        if start > total_size:
            raise ValueError(
                    "Invalid start {0}, greater than sequence length {1} of {2}!".format(start, total_size, chrom))
        
        if start < 0:
            raise ValueError("Invalid start, < 0!")
        
        if end > total_size:
            raise ValueError(
                    "Invalid end {0}, greater than sequence length {1} of {2}!".format(end, total_size, chrom))


        index = open(index_file, "rb")
        fasta = open(fasta_file)
        seq = self._read(index, fasta, start, end, line_size)
        index.close()
        fasta.close()

        if strand and strand == "-":
            seq = rc(seq)
        return seq
1105773
def read_file(self, fasta_path):
        
        fasta_dictionary = {}
        for (identifier, sequence) in self.iterate_over_file(fasta_path):
            fasta_dictionary[identifier] = sequence
        return fasta_dictionary
910229
def _parse_desc_length_file(cls, fileobj):
        """"""

        value = 0
        for i in xrange(4):
            try:
                b = cdata.uint8(fileobj.read(1))
            except cdata.error as e:
                raise ValueError(e)
            value = (value << 7) | (b & 0x7f)
            if not b >> 7:
                break
        else:
            raise ValueError("invalid descriptor length")

        return value
150158
def _extract_lengths(ll):
    """"""
    results = set()
    if ll is None:
        return []
    for val in ll.split(','):
        m = _NUM_RE.match(val)
        if m:
            results.add(int(val))
        else:
            m = _RANGE_RE.match(val)
            if m is None:
                raise Exception("Unrecognized length specification %s" % ll)
            min = int(m.group('min'))
            max = int(m.group('max'))
            for ii in range(min, max + 1):
                results.add(ii)
    return sorted(list(results))
720076
def read_fastas(input_files):
    
    tumor_file = [y for x, y in input_files.items() if x.startswith('T')][0]
    normal_file = [y for x, y in input_files.items() if x.startswith('N')][0]
    output_files = defaultdict(list)
    output_files = _read_fasta(tumor_file, output_files)
    num_entries = len(output_files)
    output_files = _read_fasta(normal_file, output_files)
    assert len(output_files) == num_entries
    return output_files
25000
def _read_fasta(fasta_file, output_dict):
    
    read_name = None
    with open(fasta_file, 'r') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            if line.startswith('>'):
                read_name = line.lstrip('>')
            else:
                assert read_name is not None, line
                output_dict[read_name].append(line.strip())
    return output_dict
39877
def sequence_prep(self):
        
        # Create a sorted list of all the FASTA files in the sequence path
        strains = sorted(glob(os.path.join(self.fastapath, '*.fa*'.format(self.fastapath))))
        for sample in strains:
            # Create the object
            metadata = MetadataObject()
            # Set the sample name to be the file name of the sequence by removing the path and file extension
            sample_name = os.path.splitext(os.path.basename(sample))[0]
            if sample_name in self.strainset:
                # Extract the OLNID from the dictionary using the SEQID
                samplename = self.straindict[sample_name]
                # samplename = sample_name
                # Set and create the output directory
                outputdir = os.path.join(self.path, samplename)
                make_path(outputdir)
                # Set the name of the JSON file
                json_metadata = os.path.join(outputdir, '{name}.json'.format(name=samplename))
                if not os.path.isfile(json_metadata):
                    # Create the name and output directory attributes
                    metadata.name = samplename
                    metadata.seqid = sample_name
                    metadata.outputdir = outputdir
                    metadata.jsonfile = json_metadata
                    # Set the name of the FASTA file to use in the analyses
                    metadata.bestassemblyfile = os.path.join(metadata.outputdir,
                                                             '{name}.fasta'.format(name=metadata.name))
                    # Symlink the original file to the output directory
                    relative_symlink(sample, outputdir, '{sn}.fasta'.format(sn=metadata.name))
                    # Associate the corresponding FASTQ files with the assembly
                    metadata.fastqfiles = sorted(glob(os.path.join(self.fastqpath,
                                                                   '{name}*.gz'.format(name=metadata.name))))
                    metadata.forward_fastq, metadata.reverse_fastq = metadata.fastqfiles
                    # Write the object to file
                    self.write_json(metadata)
                else:
                    metadata = self.read_json(json_metadata)
                # Add the metadata object to the list of objects
                self.metadata.append(metadata)
448776
def find_num_contigs(contig_lengths_dict):
    
    # Initialise the dictionary
    num_contigs_dict = dict()
    for file_name, contig_lengths in contig_lengths_dict.items():
        # Use the len() method to count the number of entries in the list
        num_contigs_dict[file_name] = len(contig_lengths)
    return num_contigs_dict
362833
def to_fasta_str(self, line_width=50, include_coords=True):
    
    res = ">" + self.name
    if include_coords:
      res += ":" + str(self.start) + "-" + str(self.end)
      res += " (" + str(self.remaining) + ")"
    m_str = self.meta_data_to_string()
    if m_str:
      res += (" " + m_str)
    res += "\n"
    for i in range(0, len(self.sequenceData), line_width):
      res += self.sequenceData[i:i + line_width]
      if i + line_width < len(self.sequenceData):
        res += "\n"
    return res
346145
def _get_read_depths(cls, read_depths_file, sequence_name, position):
        ''''''
        assert os.path.exists(read_depths_file)
        assert os.path.exists(read_depths_file + '.tbi')
        tbx = pysam.TabixFile(read_depths_file)
        try:
            rows = [x for x in tbx.fetch(sequence_name, position, position + 1)]
        except:
            return None

        if len(rows) > 1: # which happens with indels, mutiple lines for same base of reference
            test_rows = [x for x in rows if x.rstrip().split()[3] != '.']
            if len(test_rows) != 1:
                rows = [rows[-1]]
            else:
                rows = test_rows

        if len(rows) == 1:
            r, p, ref_base, alt_base, ref_counts, alt_counts = rows[0].rstrip().split()
            bases = ref_base if alt_base == '.' else ref_base + ',' + alt_base
            return bases, int(ref_counts), alt_counts
        else:
            return None
53585
def calculate_columns(sequence):
    
    columns = {}

    for row in sequence:
        for key in row.keys():
            if key not in columns:
                columns[key] = len(key)

            value_length = len(str(row[key]))
            if value_length > columns[key]:
                columns[key] = value_length

    return columns
691805
def parse_fasta(infile, upper=False):
    '''
    
    '''
    try:
        fp = must_open(infile)
    except:
        fp = infile
    # keep header
    fa_iter = (x[1] for x in groupby(fp, lambda row: row[0] == '>'))
    for header in fa_iter:
        header = next(header)
        if header[0] != '>':
            continue
        # drop '>'
        header = header.strip()[1:]
        # stitch the sequence lines together and make into upper case
        seq = "".join(s.strip() for s in next(fa_iter))
        if upper:
            seq = seq.upper()
        yield header, seq
266464
def length_by_id(self):
        """"""
        hashmap = dict((seq.id, len(seq)) for seq in self)
        tmp = hashmap.copy()
        hashmap.update(tmp)
        return hashmap
283533
def _read_index_file(self):
        
        param_file = os.path.join(self.index_dir, self.param_file)
        with open(param_file) as f:
            for line in f.readlines():
                (name, fasta_file, index_file, line_size, total_size) = line.strip().split("\t")
                self.size[name] = int(total_size)
                self.fasta_file[name] = fasta_file
                self.index_file[name] = index_file
                self.line_size[name] = int(line_size)
680179
def sequences_from_fasta(path):
    
    from Bio import SeqIO
    return {x.description: x.seq for x in SeqIO.parse(path, 'fasta')}