Count reads in defined bins using CollectReadCounts.
337360
def collect_read_counts(data, work_dir):
    
    out_file = os.path.join(work_dir, "%s-target-coverage.hdf5" % dd.get_sample_name(data))
    if not utils.file_exists(out_file):
        with file_transaction(data, out_file) as tx_out_file:
            params = ["-T", "CollectReadCounts", "-I", dd.get_align_bam(data),
                      "-L", tz.get_in(["regions", "bins", "target"], data),
                      "--interval-merging-rule", "OVERLAPPING_ONLY",
                      "-O", tx_out_file, "--format", "HDF5"]
            _run_with_memory_scaling(params, tx_out_file, data)
    return out_file
470421
@Nonnegative
    public static int count(@Nonnull final Path dir) throws IOException {
        try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            return Iterables.size(stream);
        } catch (DirectoryIteratorException ex) {
            // I/O error encounted during the iteration, the cause is an IOException
            throw ex.getCause();
        }
    }
991755
def _locate_bin(bins, n):
    
    while bins[n] != n:
        n = bins[n]
    return n
1129822
def read_count(self, space, start, end):
        
        read_counts = 0
        for read in self._bam.fetch(space, start, end):
            read_counts += 1
        return self._normalize(read_counts, self._total)
1074281
def count(self):
        
        self.log.info("Running 'count'")
        retvals = {}

        # Numbers of 'tasks'
        num_tasks = self._count_tasks()
        retvals['num_tasks'] = num_tasks

        # Numbers of 'files'
        num_files = self._count_repo_files()
        retvals['num_files'] = num_files

        return retvals
1040668
protected void collect(Object key, TaggedMapOutput aRecord,
                         OutputCollector output, Reporter reporter) throws IOException {
    this.collected += 1;
    addLongValue("collectedCount", 1);
    if (aRecord != null) {
      output.collect(key, aRecord.getData());
      reporter.setStatus("key: " + key.toString() + " collected: " + collected);
      addLongValue("actuallyCollectedCount", 1);
    }
  }
1049992
def collect(self):
        

        metrics = {}

        if 'scan' in self.config:
            for ld in os.listdir(self.config['owfs']):
                if '.' in ld:
                    self.read_values(ld, self.config['scan'], metrics)

        for oid, files in self.config.iteritems():
            if oid[:3] == 'id:':
                self.read_values(oid[3:], files, metrics)

        for fn, fv in metrics.iteritems():
            self.publish(fn, fv, 2)
1125557
def _BinsToQuery(self, bins, column_name):
    """"""
    result = []
    # With the current StatsHistogram implementation the last bin simply
    # takes all the values that are greater than range_max_value of
    # the one-before-the-last bin. range_max_value of the last bin
    # is thus effectively ignored.
    for prev_b, next_b in zip([0] + bins[:-1], bins[:-1] + [None]):
      query = "COUNT(CASE WHEN %s >= %f" % (column_name, prev_b)
      if next_b is not None:
        query += " AND %s < %f" % (column_name, next_b)

      query += " THEN 1 END)"

      result.append(query)

    return ", ".join(result)
328289
def read(self, count):
        

        if not self.data:
            raise UnpackException(None, count, 0)

        buff = self.data.read(count)
        if len(buff) < count:
            raise UnpackException(None, count, len(buff))

        return buff
1363440
def _make_reads_for_assembly(number_of_wanted_reads, total_reads, reads_in1, reads_in2, reads_out1, reads_out2, random_seed=None):
        ''''''
        random.seed(random_seed)

        if number_of_wanted_reads < total_reads:
            reads_written = 0
            percent_wanted = 100 * number_of_wanted_reads / total_reads
            file_reader1 = pyfastaq.sequences.file_reader(reads_in1)
            file_reader2 = pyfastaq.sequences.file_reader(reads_in2)
            out1 = pyfastaq.utils.open_file_write(reads_out1)
            out2 = pyfastaq.utils.open_file_write(reads_out2)

            for read1 in file_reader1:
                try:
                    read2 = next(file_reader2)
                except StopIteration:
                    pyfastaq.utils.close(out1)
                    pyfastaq.utils.close(out2)
                    raise Error('Error subsetting reads. No mate found for read ' + read1.id)

                if random.randint(0, 100) <= percent_wanted:
                    print(read1, file=out1)
                    print(read2, file=out2)
                    reads_written += 2

            pyfastaq.utils.close(out1)
            pyfastaq.utils.close(out2)
            return reads_written
        else:
            os.symlink(reads_in1, reads_out1)
            os.symlink(reads_in2, reads_out2)
            return total_reads
522195
def _counts_at_position(positions, orig_reader, cmp_reader):
    
    pos_counts = collections.defaultdict(lambda:
                 collections.defaultdict(lambda:
                 collections.defaultdict(int)))
    for orig_parts in orig_reader:
        cmp_parts = next(cmp_reader)
        for pos in positions:
            try:
                pos_counts[pos][int(orig_parts[pos+1])][int(cmp_parts[pos+1])] += 1
            except IndexError:
                pass
    for pos, count_dict in pos_counts.iteritems():
        for orig_val, cmp_dict in count_dict.iteritems():
            for cmp_val, count in cmp_dict.iteritems():
                yield pos+1, orig_val, cmp_val, count
1233032
def read(self, count):
        

        offset = self.offset
        if self.data:
            avail = len(self.data) - offset
        else:
            avail = 0

        if avail < count:
            raise UnpackException(None, count, avail)

        self.offset = offset + count
        return self.data[offset:self.offset]
1236125
def count_duplicate_starts(bam_file, sample_size=10000000):
    
    count = Counter()
    with bam.open_samfile(bam_file) as samfile:
        # unmapped reads should not be counted
        filtered = ifilter(lambda x: not x.is_unmapped, samfile)
        def read_parser(read):
            return ":".join([str(read.tid), str(read.pos)])
        samples = utils.reservoir_sample(filtered, sample_size, read_parser)

    count.update(samples)
    return count
222130
def series_in_dir(self):
        

        # none_count = 0
        countsd = {}
        # dcmdirseries = []
        for line in self.files_with_info:
            if "SeriesNumber" in line:
                sn = line['SeriesNumber']
            else:
                sn = None
            if sn in countsd:
                countsd[sn] += 1
            else:
                countsd[sn] = 1

        bins = list(countsd)
        counts = list(countsd.values())


        # try:
        #     dcmdirseries = [line['SeriesNumber'] for line in self.files_with_info]
        # except:
        #     return [0], [0]

        # bins, counts = np.unique(dcmdirseries, return_counts=True)
        # binslist = bins.tolist()

        # if None in binslist:
        #     if len(binslist) == 1:
        #         return [0], [0]
        #     else:
        #         logger.warning

        #  kvůli správným intervalům mezi biny je nutno jeden přidat na konce
        # mxb = np.max(bins)
        # if mxb is None:
        #     mxb = 1
        # else:
        #     mxb = mxb + 1
        #
        # binslist.append(mxb)
        # counts, binsvyhodit = np.histogram(dcmdirseries, bins=binslist)

        # return counts.tolist(), bins.tolist()
        return counts, bins
870061
def _CalculateStorageCounters(self, storage_reader):
    
    analysis_reports_counter = collections.Counter()
    analysis_reports_counter_error = False
    event_labels_counter = collections.Counter()
    event_labels_counter_error = False
    parsers_counter = collections.Counter()
    parsers_counter_error = False

    for session in storage_reader.GetSessions():
      # Check for a dict for backwards compatibility.
      if isinstance(session.analysis_reports_counter, dict):
        analysis_reports_counter += collections.Counter(
            session.analysis_reports_counter)
      elif isinstance(session.analysis_reports_counter, collections.Counter):
        analysis_reports_counter += session.analysis_reports_counter
      else:
        analysis_reports_counter_error = True

      # Check for a dict for backwards compatibility.
      if isinstance(session.event_labels_counter, dict):
        event_labels_counter += collections.Counter(
            session.event_labels_counter)
      elif isinstance(session.event_labels_counter, collections.Counter):
        event_labels_counter += session.event_labels_counter
      else:
        event_labels_counter_error = True

      # Check for a dict for backwards compatibility.
      if isinstance(session.parsers_counter, dict):
        parsers_counter += collections.Counter(session.parsers_counter)
      elif isinstance(session.parsers_counter, collections.Counter):
        parsers_counter += session.parsers_counter
      else:
        parsers_counter_error = True

    storage_counters = {}

    warnings_by_path_spec = collections.Counter()
    warnings_by_parser_chain = collections.Counter()

    for warning in list(storage_reader.GetWarnings()):
      warnings_by_path_spec[warning.path_spec.comparable] += 1
      warnings_by_parser_chain[warning.parser_chain] += 1

    storage_counters['warnings_by_path_spec'] = warnings_by_path_spec
    storage_counters['warnings_by_parser_chain'] = warnings_by_parser_chain

    if not analysis_reports_counter_error:
      storage_counters['analysis_reports'] = analysis_reports_counter

    if not event_labels_counter_error:
      storage_counters['event_labels'] = event_labels_counter

    if not parsers_counter_error:
      storage_counters['parsers'] = parsers_counter

    return storage_counters
913740
def count(lines):
  
  words = [w for l in lines for w in l.strip().split()]
  return Counter(words)
596948
def count_mismatches(read):
    
    if read is False:
        return False
    mm = [int(i.split(':')[2]) for i in read[11:] if i.startswith('NM:i:')]
    if len(mm) > 0:
        return sum(mm)
    else:
        return False