Calculate coverage in parallel using mosdepth.

    Removes duplicates and secondary reads from the counts:
    if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
339880
def calculate(bam_file, data, sv_bed):
    
    params = {"min": dd.get_coverage_depth_min(data)}
    variant_regions = dd.get_variant_regions_merged(data)
    if not variant_regions:
        variant_regions = _create_genome_regions(data)
    # Back compatible with previous pre-mosdepth callable files
    callable_file = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align",
                                                                 dd.get_sample_name(data))),
                                 "%s-coverage.callable.bed" % (dd.get_sample_name(data)))
    if not utils.file_uptodate(callable_file, bam_file):
        vr_quantize = ("0:1:%s:" % (params["min"]), ["NO_COVERAGE", "LOW_COVERAGE", "CALLABLE"])
        to_calculate = [("variant_regions", variant_regions,
                         vr_quantize, None, "coverage_perbase" in dd.get_tools_on(data)),
                        ("sv_regions", bedutils.clean_file(sv_bed, data, prefix="svregions-"),
                         None, None, False),
                        ("coverage", bedutils.clean_file(dd.get_coverage(data), data, prefix="cov-"),
                         None, DEPTH_THRESHOLDS, False)]
        depth_files = {}
        for target_name, region_bed, quantize, thresholds, per_base in to_calculate:
            if region_bed:
                cur_depth = {}
                depth_info = run_mosdepth(data, target_name, region_bed, quantize=quantize, thresholds=thresholds,
                                          per_base=per_base)
                for attr in ("dist", "regions", "thresholds", "per_base"):
                    val = getattr(depth_info, attr, None)
                    if val:
                        cur_depth[attr] = val
                depth_files[target_name] = cur_depth
                if target_name == "variant_regions":
                    callable_file = depth_info.quantize
    else:
        depth_files = {}
    final_callable = _subset_to_variant_regions(callable_file, variant_regions, data)
    return final_callable, depth_files
277194
public void writeCoverageResults() {
        File coverageFile = new File(this.testSessionDir,
                ICS_MAP.get(this.requestId));
        if (coverageFile.exists()) {
            return;
        }
        OutputStream fos = null;
        try {
            fos = new FileOutputStream(coverageFile, false);
            writeDocument(fos, this.coverageDoc);
        } catch (FileNotFoundException e) {
        } finally {
            try {
                // Fortify Mod: If fos is null, then nothing was written
                if( fos != null) {
                    fos.close();
                    LOGR.config("Wrote coverage results to "
                        + coverageFile.getCanonicalPath());
                    }
                else {
                    // If nothing was written, then there should be an exception message.  
                    // If an additional message is desired, then add it here.
                    }
            } catch (IOException ioe) {
                LOGR.warning(ioe.getMessage());
            }
        }

    }
1242811
function (coverage /*, testName */) {
        var store = this.store;
        Object.keys(coverage).forEach(function (key) {
            var fileCoverage = coverage[key];
            if (store.hasKey(key)) {
                store.setObject(key, utils.mergeFileCoverage(fileCoverage, store.getObject(key)));
            } else {
                store.setObject(key, fileCoverage);
            }
        });
    }
131357
def run_count(bam_file, dexseq_gff, stranded, out_file, data):
    
    assert file_exists(bam_file), "%s does not exist." % bam_file
    sort_order = bam._get_sort_order(bam_file, {})
    assert sort_order, "Cannot determine sort order of %s." % bam_file
    strand_flag = _strand_flag(stranded)
    assert strand_flag, "%s is not a valid strandedness value." % stranded
    if not dexseq_gff:
        logger.info("No DEXSeq GFF file was found, skipping exon-level counting.")
        return None
    elif not file_exists(dexseq_gff):
        logger.info("%s was not found, so exon-level counting is being "
                    "skipped." % dexseq_gff)
        return None

    dexseq_count = _dexseq_count_path()
    if not dexseq_count:
        logger.info("DEXseq is not installed, skipping exon-level counting.")
        return None

    if dd.get_aligner(data) == "bwa":
        logger.info("Can't use DEXSeq with bwa alignments, skipping exon-level counting.")
        return None

    sort_flag = "name" if sort_order == "queryname" else "pos"
    is_paired = bam.is_paired(bam_file)
    paired_flag = "yes" if is_paired else "no"
    bcbio_python = sys.executable

    if file_exists(out_file):
        return out_file
    cmd = ("{bcbio_python} {dexseq_count} -f bam -r {sort_flag} -p {paired_flag} "
           "-s {strand_flag} {dexseq_gff} {bam_file} {tx_out_file}")
    message = "Counting exon-level counts with %s and %s." % (bam_file, dexseq_gff)
    with file_transaction(data, out_file) as tx_out_file:
        do.run(cmd.format(**locals()), message)
    return out_file
400019
def _combine_coverages(items, work_dir, input_backs=None):
    
    out_file = os.path.join(work_dir, "sample_coverages.txt")
    if not utils.file_exists(out_file):
        with file_transaction(items[0], out_file) as tx_out_file:
            with open(tx_out_file, 'w') as out_f:
                for data in items:
                    cov_file = tz.get_in(["depth", "bins", "seq2c"], data)
                    with open(cov_file) as cov_f:
                        out_f.write(cov_f.read())
                if input_backs:
                    for input_back in input_backs:
                        with open(input_back) as in_handle:
                            for line in in_handle:
                                if len(line.split()) >= 4:
                                    out_f.write(line)
    return out_file
932309
def _merge_nbval_coverage_data(cov):
    """"""
    if not cov:
        return

    suffix = _make_suffix(cov)
    if suffix is True:
        # Note: If suffix is true, we are running in parallel, so several
        # files will be generated. This will cause some warnings about "no coverage"
        # but is otherwise OK. Do nothing.
        return

    # Get the filename of the nbval coverage:
    filename = cov.data_files.filename + '.' + suffix

    # Read coverage generated by nbval in this run:
    nbval_data = coverage.CoverageData(debug=cov.debug)
    try:
        nbval_data.read_file(os.path.abspath(filename))
    except coverage.CoverageException:
        return

    # Set up aliases (following internal coverage.py code here)
    aliases = None
    if cov.config.paths:
        aliases = coverage.files.PathAliases()
        for paths in cov.config.paths.values():
            result = paths[0]
            for pattern in paths[1:]:
                aliases.add(pattern, result)

    # Merge nbval data into pytest-cov data:
    cov.data.update(nbval_data, aliases=aliases)
    # Delete our nbval coverage data
    coverage.misc.file_be_gone(filename)
1087735
def code_coverage
      return 0.0 if code_lines.size.zero?
      ran_lines.size.to_f / code_lines.size.to_f
    end
1290060
function( count ) {
		var test = this.test,
			popped = false,
			acceptCallCount = count;

		if ( typeof acceptCallCount === "undefined" ) {
			acceptCallCount = 1;
		}

		test.semaphore += 1;
		test.usedAsync = true;
		pauseProcessing();

		return function done() {

			if ( popped ) {
				test.pushFailure( "Too many calls to the `assert.async` callback",
					sourceFromStacktrace( 2 ) );
				return;
			}
			acceptCallCount -= 1;
			if ( acceptCallCount > 0 ) {
				return;
			}

			test.semaphore -= 1;
			popped = true;
			resumeProcessing();
		};
	}
1089246
function deleteStats(collection) {
      var coverageType;
      for (coverageType in collection) {
        if (collection.hasOwnProperty(coverageType)) {
          if (collection[coverageType].hasOwnProperty("total")) {
            delete collection[coverageType].total;
          }
          if (collection[coverageType].hasOwnProperty("covered")) {
            delete collection[coverageType].covered;
          }
          if (collection[coverageType].hasOwnProperty("skipped")) {
            delete collection[coverageType].skipped;
          }
        }
      }
    }
266592
def _counts_to_coverages(sample_data, counts_in_1x):
    
    if not counts_in_1x:
        return {None: None}

    return OrderedDict(
        (_count_to_coverage(x, counts_in_1x), _count_to_coverage(y, counts_in_1x))
        for x, y in sample_data.items()
    )
511859
def run(bam_file, data, out_dir):
    """"""
    m = {"base": None, "secondary": []}
    m.update(_mirbase_stats(data, out_dir))
    m["secondary"].append(_seqcluster_stats(data, out_dir))
891217
def mp_check_impl(self, process_count):
        

        from multiprocessing import Process, Queue

        options = self.reporter.options

        # this is the function that will be run in a separate process,
        # which will handle the tasks queue and feed into the results
        # queue
        func = _mp_run_check

        # normally this would happen lazily, but since we'll have
        # multiple processes all running reports at the same time, we
        # need to make sure the setup is done before-hand. This is
        # hackish, but in particular this keeps the HTML reports from
        # trying to perform the default data copy over and over.
        self.reporter.setup()

        # enqueue the sub-reports for multi-processing. Other types of
        # changes can happen sync.
        changes = list(self.collect_impl())

        task_count = 0
        tasks = Queue()
        results = Queue()

        try:
            # as soon as we start using the tasks queue, we need to be
            # catching the KeyboardInterrupt event so that we can
            # drain the queue and lets its underlying thread terminate
            # happily.

            # TODO: is there a better way to handle this shutdown
            # gracefully?

            # feed any sub-reports to the tasks queue
            for index in range(0, len(changes)):
                change = changes[index]
                if isinstance(change, (DistJarReport, DistClassReport)):
                    changes[index] = None
                    tasks.put((index, change))
                    task_count += 1

            # infrequent edge case, but don't bother starting more
            # helpers than we'll ever use
            process_count = min(process_count, task_count)

            # start the number of helper processes, and make sure
            # there are that many stop sentinels at the end of the
            # tasks queue
            for _i in range(0, process_count):
                tasks.put(None)
                process = Process(target=func, args=(tasks, results, options))
                process.daemon = False
                process.start()

            # while the helpers are running, perform our checks
            for change in changes:
                if change:
                    change.check()

            # get all of the results and feed them back into our change
            for _i in range(0, task_count):
                index, change = results.get()
                changes[index] = change

        except KeyboardInterrupt:
            # drain the tasks queue so it will exit gracefully
            for _change in iter(tasks.get, None):
                pass
            raise

        # complete the check by setting our internal collection of
        # child changes and returning our overall status
        c = False
        for change in changes:
            c = c or change.is_change()
        self.changes = changes
        return c, None
141821
def report(self, stream):
        
        if not self.xcoverageToStdout:
            # This will create a false stream where output will be ignored
            stream = StringIO()
            
        super(XCoverage, self).report(stream)
        if not hasattr(self, 'coverInstance'):
            # nose coverage plugin 1.0 and earlier
            import coverage
            self.coverInstance = coverage._the_coverage

        modules = [module
                    for name, module in sys.modules.items()
                    if self.wantModuleCoverage(name, module)]
        log.debug("Coverage report will cover modules: %s", modules)
        morfs = [m.__file__ for m in modules if hasattr(m, '__file__')]
        self.coverInstance.xml_report(morfs, outfile=self.xcoverageFile)
122705
def check_schema_coverage(doc, schema):
    '''
    
    '''
    error_list = []
    to_delete = []
    for entry in doc.list_tuples():
        (name, value, index, seq) = entry
        temp_schema = schema_match_up(doc, schema)
        if not name in temp_schema.list_values("name"):
            error_list.append( ("[error]", "doc", seq, "a name of '{}' not found in schema".format(name)) )
            to_delete.append(seq)
        else:
            # check subs
            el = check_schema_coverage(doc[name, value, index], temp_schema["name", name])
            error_list.extend(el)
    for seq in to_delete:
        doc.seq_delete(seq)
    return error_list
741118
def report_sections(self):
    
    # Append to self.sections list

    if len(self.qualimap_bamqc_coverage_hist) > 0:
        # Chew back on histogram to prevent long flat tail
        # (find a sensible max x - lose 1% of longest tail)
        max_x = 0
        total_bases_by_sample = dict()
        for s_name, d in self.qualimap_bamqc_coverage_hist.items():
            total_bases_by_sample[s_name] = sum(d.values())
            cumulative = 0
            for count in sorted(d.keys(), reverse=True):
                cumulative += d[count]
                if cumulative / total_bases_by_sample[s_name] > 0.01:
                    max_x = max(max_x, count)
                    break

        rates_within_threshs = dict()
        for s_name, hist in self.qualimap_bamqc_coverage_hist.items():
            total = total_bases_by_sample[s_name]
            # Make a range of depths that isn't stupidly huge for high coverage expts
            depth_range = list(range(0, max_x + 1, math.ceil(float(max_x)/400.0) if max_x > 0 else 1))
            # Check that we have our specified coverages in the list
            for c in self.covs:
                if int(c) not in depth_range:
                    depth_range.append(int(c))
            # Calculate the coverage rates for this range of coverages
            rates_within_threshs[s_name] = _calculate_bases_within_thresholds(hist, total, depth_range)
            # Add requested coverage levels to the General Statistics table
            for c in self.covs:
                if int(c) in rates_within_threshs[s_name]:
                    self.general_stats_data[s_name]['{}_x_pc'.format(c)] = rates_within_threshs[s_name][int(c)]
                else:
                    self.general_stats_data[s_name]['{}_x_pc'.format(c)] = 0

        # Section 1 - BamQC Coverage Histogram
        coverage_histogram_helptext = '''
        For a set of DNA or RNA reads mapped to a reference sequence, such as a genome
        or transcriptome, the depth of coverage at a given base position is the number
        of high-quality reads that map to the reference at that position
        (<a href="https://doi.org/10.1038/nrg3642" target="_blank">Sims et al. 2014</a>).

        QualiMap groups the bases of a reference sequence by their depth of coverage
        (*0&#215;, 1&#215;, &#8230;, N&#215;*), then plots the number of bases of the
        reference (y-axis) at each level of coverage depth (x-axis). This plot shows
        the frequency of coverage depths relative to the reference sequence for each
        read dataset, which provides an indirect measure of the level and variation of
        coverage depth in the corresponding sequenced sample.

        If reads are randomly distributed across the reference sequence, this plot
        should resemble a Poisson distribution (<a href="https://doi.org/10.1016/0888-7543(88)90007-9"
        target="_blank">Lander & Waterman 1988</a>), with a peak indicating approximate
        depth of coverage, and more uniform coverage depth being reflected in a narrower
        spread. The optimal level of coverage depth depends on the aims of the
        experiment, though it should at minimum be sufficiently high to adequately
        address the biological question; greater uniformity of coverage is generally
        desirable, because it increases breadth of coverage for a given depth of
        coverage, allowing equivalent results to be achieved at a lower sequencing depth
        (<a href="https://doi.org/10.1002/gepi.20575" target="_blank">Sampson
        et al. 2011</a>; <a href="https://doi.org/10.1038/nrg3642" target="_blank">Sims
        et al. 2014</a>). However, it is difficult to achieve uniform coverage
        depth in practice, due to biases introduced during sample preparation
        (<a href="https://doi.org/10.1016/j.yexcr.2014.01.008" target="_blank">van
        Dijk et al. 2014</a>), sequencing (<a href="https://doi.org/10.1186/gb-2013-14-5-r51"
        target="_blank">Ross et al. 2013</a>) and read mapping
        (<a href="https://doi.org/10.1038/nrg3642" target="_blank">Sims et al. 2014</a>).

        This plot may include a small peak for regions of the reference sequence with
        zero depth of coverage. Such regions may be absent from the given sample (due
        to a deletion or structural rearrangement), present in the sample but not
        successfully sequenced (due to bias in sequencing or preparation), or sequenced
        but not successfully mapped to the reference (due to the choice of mapping
        algorithm, the presence of repeat sequences, or mismatches caused by variants
        or sequencing errors). Related factors cause most datasets to contain some
        unmapped reads (<a href="https://doi.org/10.1038/nrg3642" target="_blank">Sims
        et al. 2014</a>).'''
        self.add_section (
            name = 'Coverage histogram',
            anchor = 'qualimap-coverage-histogram',
            description = 'Distribution of the number of locations in the reference genome with a given depth of coverage.',
            helptext = coverage_histogram_helptext,
            plot = linegraph.plot(self.qualimap_bamqc_coverage_hist, {
                'id': 'qualimap_coverage_histogram',
                'title': 'Qualimap BamQC: Coverage histogram',
                'ylab': 'Genome bin counts',
                'xlab': 'Coverage (X)',
                'ymin': 0,
                'xmin': 0,
                'xmax': max_x,
                'xDecimals': False,
                'tt_label': '<b>{point.x}X</b>: {point.y}',
            })
        )
        # Section 2 - BamQC cumulative coverage genome fraction
        genome_fraction_helptext = '''
        For a set of DNA or RNA reads mapped to a reference sequence, such as a genome
        or transcriptome, the depth of coverage at a given base position is the number
        of high-quality reads that map to the reference at that position, while the
        breadth of coverage is the fraction of the reference sequence to which reads
        have been mapped with at least a given depth of coverage
        (<a href="https://doi.org/10.1038/nrg3642" target="_blank">Sims et al. 2014</a>).

        Defining coverage breadth in terms of coverage depth is useful, because
        sequencing experiments typically require a specific minimum depth of coverage
        over the region of interest (<a href="https://doi.org/10.1038/nrg3642"
        target="_blank">Sims et al. 2014</a>), so the extent of the reference sequence
        that is amenable to analysis is constrained to lie within regions that have
        sufficient depth. With inadequate sequencing breadth, it can be difficult to
        distinguish the absence of a biological feature (such as a gene) from a lack
        of data (<a href="https://doi.org/10.1101/gr.7050807" target="_blank">Green 2007</a>).

        For increasing coverage depths (*1&#215;, 2&#215;, &#8230;, N&#215;*),
        QualiMap calculates coverage breadth as the percentage of the reference
        sequence that is covered by at least that number of reads, then plots
        coverage breadth (y-axis) against coverage depth (x-axis). This plot
        shows the relationship between sequencing depth and breadth for each read
        dataset, which can be used to gauge, for example, the likely effect of a
        minimum depth filter on the fraction of a genome available for analysis.'''
        self.add_section (
            name = 'Cumulative genome coverage',
            anchor = 'qualimap-cumulative-genome-fraction-coverage',
            description = 'Percentage of the reference genome with at least the given depth of coverage.',
            helptext = genome_fraction_helptext,
            plot = linegraph.plot(rates_within_threshs, {
                'id': 'qualimap_genome_fraction',
                'title': 'Qualimap BamQC: Genome fraction covered by at least X reads',
                'ylab': 'Fraction of reference (%)',
                'xlab': 'Coverage (X)',
                'ymax': 100,
                'ymin': 0,
                'xmin': 0,
                'xmax': max_x,
                'xDecimals': False,
                'tt_label': '<b>{point.x}X</b>: {point.y:.2f}%',
            })
        )

    # Section 3 - Insert size histogram
    if len(self.qualimap_bamqc_insert_size_hist) > 0:
        insert_size_helptext = '''
        To overcome limitations in the length of DNA or RNA sequencing reads,
        many sequencing instruments can produce two or more shorter reads from
        one longer fragment in which the relative position of reads is
        approximately known, such as paired-end or mate-pair reads
        (<a href="https://doi.org/10.1146/annurev-anchem-062012-092628"
        target="_blank">Mardis 2013</a>). Such techniques can extend the reach
        of sequencing technology, allowing for more accurate placement of reads
        (<a href="https://doi.org/10.1146/annurev-genom-090413-025358"
        target="_blank">Reinert et al. 2015</a>) and better resolution of repeat
        regions (<a href="https://doi.org/10.1146/annurev-genom-090413-025358"
        target="_blank">Reinert et al. 2015</a>), as well as detection of
        structural variation (<a href="https://doi.org/10.1038/nrg2958"
        target="_blank">Alkan et al. 2011</a>) and chimeric transcripts
        (<a href="https://doi.org/10.1073/pnas.0904720106"
        target="_blank">Maher et al. 2009</a>).

        All these methods assume that the approximate size of an insert is known.
        (Insert size can be defined as the length in bases of a sequenced DNA or
        RNA fragment, excluding technical sequences such as adapters, which are
        typically removed before alignment.) This plot allows for that assumption
        to be assessed. With the set of mapped fragments for a given sample, QualiMap
        groups the fragments by insert size, then plots the frequency of mapped
        fragments (y-axis) over a range of insert sizes (x-axis). In an ideal case,
        the distribution of fragment sizes for a sequencing library would culminate
        in a single peak indicating average insert size, with a narrow spread
        indicating highly consistent fragment lengths.

        QualiMap calculates insert sizes as follows: for each fragment in which
        every read mapped successfully to the same reference sequence, it
        extracts the insert size from the `TLEN` field of the leftmost read
        (see the <a href="http://qualimap.bioinfo.cipf.es/doc_html/index.html"
        target="_blank">Qualimap 2 documentation</a>), where the `TLEN` (or
        'observed Template LENgth') field contains 'the number of bases from the
        leftmost mapped base to the rightmost mapped base'
        (<a href="https://samtools.github.io/hts-specs/" target="_blank">SAM
        format specification</a>). Note that because it is defined in terms of
        alignment to a reference sequence, the value of the `TLEN` field may
        differ from the insert size due to factors such as alignment clipping,
        alignment errors, or structural variation or splicing in a gap between
        reads from the same fragment.'''
        self.add_section (
            name = 'Insert size histogram',
            anchor = 'qualimap-insert-size-histogram',
            description = 'Distribution of estimated insert sizes of mapped reads.',
            helptext = insert_size_helptext,
            plot = linegraph.plot(self.qualimap_bamqc_insert_size_hist, {
                'id': 'qualimap_insert_size',
                'title': 'Qualimap BamQC: Insert size histogram',
                'ylab': 'Fraction of reads',
                'xlab': 'Insert Size (bp)',
                'ymin': 0,
                'xmin': 0,
                'tt_label': '<b>{point.x} bp</b>: {point.y}',
            })
        )

    # Section 4 - GC-content distribution
    if len(self.qualimap_bamqc_gc_content_dist) > 0:
        gc_content_helptext = '''
        GC bias is the difference between the guanine-cytosine content
        (GC-content) of a set of sequencing reads and the GC-content of the DNA
        or RNA in the original sample. It is a well-known issue with sequencing
        systems, and may be introduced by PCR amplification, among other factors
        (<a href="https://doi.org/10.1093/nar/gks001" target="_blank">Benjamini
        & Speed 2012</a>; <a href="https://doi.org/10.1186/gb-2013-14-5-r51"
        target="_blank">Ross et al. 2013</a>).

        QualiMap calculates the GC-content of individual mapped reads, then
        groups those reads by their GC-content (*1%, 2%, &#8230;, 100%*), and
        plots the frequency of mapped reads (y-axis) at each level of GC-content
        (x-axis). This plot shows the GC-content distribution of mapped reads
        for each read dataset, which should ideally resemble that of the
        original sample. It can be useful to display the GC-content distribution
        of an appropriate reference sequence for comparison, and QualiMap has an
        option to do this (see the <a href="http://qualimap.bioinfo.cipf.es/doc_html/index.html"
        target="_blank">Qualimap 2 documentation</a>).'''
        extra_series = []
        for i, (species_name, species_data) in enumerate(sorted(self.qualimap_bamqc_gc_by_species.items())):
            extra_series.append({
                'name': species_name,
                'data': list(species_data.items()),
                'dashStyle': 'Dash',
                'lineWidth': 1,
                'color': ['#000000', '#E89191'][i % 2],
            })
        if len(self.qualimap_bamqc_gc_content_dist) == 1:
            desc = 'The solid line represents the distribution of GC content of mapped reads for the sample.'
        else:
            desc = 'Each solid line represents the distribution of GC content of mapped reads for a given sample.'
        lg_config = {
            'id': 'qualimap_gc_content',
            'title': 'Qualimap BamQC: GC content distribution',
            'ylab': 'Fraction of reads',
            'xlab': 'GC content (%)',
            'ymin': 0,
            'xmin': 0,
            'xmax': 100,
            'tt_label': '<b>{point.x}%</b>: {point.y:.3f}'
        }
        if len(extra_series) == 1:
            desc += ' The dotted line represents a pre-calculated GC distribution for the reference genome.'
            lg_config['extra_series'] = extra_series
        elif len(extra_series) > 1:
            desc += ' Each dotted line represents a pre-calculated GC distribution for a specific reference genome.'
            lg_config['extra_series'] = extra_series

        self.add_section (
            name = 'GC content distribution',
            anchor = 'qualimap-gc-distribution',
            description = desc,
            helptext = gc_content_helptext,
            plot = linegraph.plot(self.qualimap_bamqc_gc_content_dist, lg_config)
        )
389632
def determine_coverage(cls, coverage_file):
        
        lines = []
        source_file = 'ERROR'
        for line in coverage_file:
            m = title_re.match(line)
            if m:
                if m.group(2) == '100':
                    return ('', [])
                source_file = m.group(1)
                continue
            m = source_re.match(line)
            if m:
                lines.append(int(m.group(1)))
                continue
            if end_re.match(line):
                break
        line_ranges = cls.make_ranges(lines)
        return (source_file, line_ranges)
942521
def parse_coverage(self, f):
    
    # Get the sample name from the parent parent directory
    # Typical path: <sample name>/raw_data_qualimapReport/coverage_histogram.txt
    s_name = self.get_s_name(f)

    d = dict()
    for l in f['f']:
        if l.startswith('#'):
            continue
        coverage, count = l.split(None, 1)
        coverage = int(round(float(coverage)))
        count = float(count)
        d[coverage] = count

    if len(d) == 0:
        log.debug("Couldn't parse contents of coverage histogram file {}".format(f['fn']))
        return None

    # Find median without importing anything to do it for us
    num_counts = sum(d.values())
    cum_counts = 0
    median_coverage = None
    for thiscov, thiscount in d.items():
        cum_counts += thiscount
        if cum_counts >= num_counts/2:
            median_coverage = thiscov
            break
    self.general_stats_data[s_name]['median_coverage'] = median_coverage

    # Save results
    if s_name in self.qualimap_bamqc_coverage_hist:
        log.debug("Duplicate coverage histogram sample name found! Overwriting: {}".format(s_name))
    self.qualimap_bamqc_coverage_hist[s_name] = d
    self.add_data_source(f, s_name=s_name, section='coverage_histogram')