bghomstats.py 8.87 KB
Newer Older
jhoogenboom's avatar
jhoogenboom committed
1
#!/usr/bin/env python
2 3

#
4
# Copyright (C) 2017 Jerry Hoogenboom
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# This file is part of FDSTools, data analysis tools for Next
# Generation Sequencing of forensic DNA markers.
#
# FDSTools is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# FDSTools is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FDSTools.  If not, see <http://www.gnu.org/licenses/>.
#

jhoogenboom's avatar
jhoogenboom committed
23
"""
jhoogenboom's avatar
jhoogenboom committed
24 25 26 27 28
Compute allele-centric statistics for background noise in homozygous
reference samples (min, max, mean, sample variance).

Compute a profile of recurring background noise for each unique allele
in the database of reference samples.  The profiles obtained can be used
jhoogenboom's avatar
jhoogenboom committed
29 30 31 32
by bgcorrect to filter background noise from samples.  If many reference
samples are heterozygous (as is usually the case with forensic STR
markers), it is preferable to use bgestimate instead, since it can
handle heterozygous samples as well.
jhoogenboom's avatar
jhoogenboom committed
33
"""
34
from errno import EPIPE
35
from ..lib import pos_int_arg, add_input_output_args, get_input_output_files,\
36
                  add_allele_detection_args, parse_allelelist,\
37
                  get_sample_data, add_sequence_format_args, adjust_stats,\
jhoogenboom's avatar
jhoogenboom committed
38
                  add_random_subsampling_args
jhoogenboom's avatar
jhoogenboom committed
39

40
__version__ = "1.0.1"
jhoogenboom's avatar
jhoogenboom committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64


# Default values for parameters are specified below.

# Default minimum amount of background to consider, as a percentage of
# the highest allele.
# This value can be overridden by the -m command line option.
_DEF_THRESHOLD_PCT = 0.5

# Default minimum number of reads to consider.
# This value can be overridden by the -n command line option.
_DEF_THRESHOLD_ABS = 5

# Default minimum number of samples for each true allele.
# This value can be overridden by the -s command line option.
_DEF_MIN_SAMPLES = 2

# Default minimum number of samples required for each background product
# to be included in the analysis, as a percentage of the number of
# samples with a certain true allele.
# This value can be overridden by the -S command line option.
_DEF_MIN_SAMPLE_PCT = 80.


65
def add_sample_data(data, sample_data, sample_alleles, min_pct, min_abs, tag):
jhoogenboom's avatar
jhoogenboom committed
66 67 68 69 70
    # Check presence of all alleles.
    for marker in sample_alleles:
        allele = sample_alleles[marker]
        if (marker, allele) not in sample_data:
            raise ValueError(
71 72
                "Missing allele %s of marker %s in sample %s!" %
                        (allele, marker, tag))
jhoogenboom's avatar
jhoogenboom committed
73 74
        elif 0 in sample_data[marker, allele]:
            raise ValueError(
75 76
                "Allele %s of marker %s has 0 reads on one strand in "
                    "sample %s!" % (allele, marker, tag))
jhoogenboom's avatar
jhoogenboom committed
77

jhoogenboom's avatar
jhoogenboom committed
78 79
    # Enter the read counts into data and check the thresholds.
    for marker, sequence in sample_data:
80
        if marker not in sample_alleles:
jhoogenboom's avatar
jhoogenboom committed
81 82 83
            # Sample does not participate in this marker.
            continue
        allele = sample_alleles[marker]
jhoogenboom's avatar
jhoogenboom committed
84
        factors = [100./x for x in sample_data[marker, allele]]
jhoogenboom's avatar
jhoogenboom committed
85 86 87 88 89 90 91 92
        if (marker, allele) not in data:
            data[marker, allele] = {}
        if sequence not in data[marker, allele]:
            data[marker, allele][sequence] = [None, None, 0]
        for direction in (0, 1):
            data[marker, allele][sequence][direction] = adjust_stats(
                sample_data[marker, sequence][direction] * factors[direction],
                data[marker, allele][sequence][direction])
jhoogenboom's avatar
jhoogenboom committed
93 94 95
        if sum(count >= min_abs and count*factor >= min_pct
               for count, factor in
               zip(sample_data[marker, sequence], factors)):
jhoogenboom's avatar
jhoogenboom committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            data[marker, allele][sequence][2] += 1
#add_sample_data


def filter_data(data, min_samples, min_sample_pct):
    """
    Remove all alleles from data that have less than min_samples samples
    and remove all stats of sequences that don't pass the detection
    thresholds in at least min_sample_pct per cent of the samples with a
    particular allele.  Also add explicit zeros to the stats of the
    sequences that were not seen in all samples with a given allele.
    """
    for marker, allele in data.keys():
        if data[marker, allele][allele][2] < min_samples:
            del data[marker, allele]
            continue
        factor = 100./data[marker, allele][allele][2]
        for sequence in data[marker, allele].keys():
            if data[marker, allele][sequence][2] * factor < min_sample_pct:
                del data[marker, allele][sequence]
                continue
            for i in range(data[marker, allele][sequence][0]["n"],
                           data[marker, allele][allele][2]):
                for direction in (0, 1):
                    adjust_stats(0, data[marker, allele][sequence][direction])
#filter_data


124 125 126
def compute_stats(samples_in, outfile, allelefile, annotation_column, min_pct,
                  min_abs, min_samples, min_sample_pct, seqformat, library,
                  marker, limit_reads, drop_samples):
jhoogenboom's avatar
jhoogenboom committed
127

128
    # Parse allele list.
jhoogenboom's avatar
jhoogenboom committed
129 130 131 132 133
    allelelist = {} if allelefile is None \
                    else parse_allelelist(allelefile, seqformat, library)

    # Read sample data.
    data = {}
134
    get_sample_data(
135
        samples_in,
136 137 138
        lambda tag, sample_data: add_sample_data(
            data, sample_data,
            {m: allelelist[tag][m].pop() for m in allelelist[tag]},
139
            min_pct, min_abs, tag),
140
        allelelist, annotation_column, seqformat, library, marker, True,
141
        limit_reads, drop_samples, True)
jhoogenboom's avatar
jhoogenboom committed
142 143 144 145 146

    # Ensure minimum number of samples per allele and filter
    # insignificant background products.
    filter_data(data, min_samples, min_sample_pct)

jhoogenboom's avatar
jhoogenboom committed
147 148
    outfile.write("\t".join(["marker", "allele", "sequence", "n", "fmin",
                     "fmax", "fmean", "fvariance", "rmin", "rmax", "rmean",
149
                     "rvariance", "tool"]) + "\n")
jhoogenboom's avatar
jhoogenboom committed
150 151
    for marker, allele in data:
        for sequence in data[marker, allele]:
jhoogenboom's avatar
jhoogenboom committed
152
            outfile.write("\t".join([marker, allele, sequence] + [
153
                "%.3g" % x if abs(x) > 0.0000000001 else "0" for x in (
jhoogenboom's avatar
jhoogenboom committed
154 155 156 157 158 159 160 161
                    data[marker, allele][sequence][0]["n"],
                    data[marker, allele][sequence][0]["min"],
                    data[marker, allele][sequence][0]["max"],
                    data[marker, allele][sequence][0]["mean"],
                    data[marker, allele][sequence][0]["variance"],
                    data[marker, allele][sequence][1]["min"],
                    data[marker, allele][sequence][1]["max"],
                    data[marker, allele][sequence][1]["mean"],
162 163
                    data[marker, allele][sequence][1]["variance"])] +
                ["bghomstats"]) + "\n")
jhoogenboom's avatar
jhoogenboom committed
164 165 166 167
#compute_stats


def add_arguments(parser):
168
    add_input_output_args(parser)
jhoogenboom's avatar
jhoogenboom committed
169
    add_allele_detection_args(parser)
jhoogenboom's avatar
jhoogenboom committed
170 171
    filtergroup = parser.add_argument_group("filtering options")
    filtergroup.add_argument('-m', '--min-pct', metavar="PCT", type=float,
jhoogenboom's avatar
jhoogenboom committed
172 173 174
        default=_DEF_THRESHOLD_PCT,
        help="minimum amount of background to consider, as a percentage "
             "of the highest allele (default: %4.2f)" % _DEF_THRESHOLD_PCT)
jhoogenboom's avatar
jhoogenboom committed
175
    filtergroup.add_argument('-n', '--min-abs', metavar="N", type=pos_int_arg,
jhoogenboom's avatar
jhoogenboom committed
176 177 178
        default=_DEF_THRESHOLD_ABS,
        help="minimum amount of background to consider, as an absolute "
             "number of reads (default: %(default)s)")
jhoogenboom's avatar
jhoogenboom committed
179 180
    filtergroup.add_argument('-s', '--min-samples', metavar="N",
        type=pos_int_arg,
jhoogenboom's avatar
jhoogenboom committed
181 182 183
        default=_DEF_MIN_SAMPLES,
        help="require this minimum number of samples for each true allele "
             "(default: %(default)s)")
jhoogenboom's avatar
jhoogenboom committed
184 185
    filtergroup.add_argument('-S', '--min-sample-pct', metavar="PCT",
        type=float,
jhoogenboom's avatar
jhoogenboom committed
186 187 188 189
        default=_DEF_MIN_SAMPLE_PCT,
        help="require this minimum number of samples for each background "
             "product, as a percentage of the number of samples with a "
             "particular true allele (default: %(default)s)")
jhoogenboom's avatar
jhoogenboom committed
190
    filtergroup.add_argument('-M', '--marker', metavar="MARKER",
jhoogenboom's avatar
jhoogenboom committed
191
        help="work only on MARKER")
jhoogenboom's avatar
jhoogenboom committed
192 193
    add_sequence_format_args(parser)
    add_random_subsampling_args(parser)
jhoogenboom's avatar
jhoogenboom committed
194 195 196 197
#add_arguments


def run(args):
198 199
    files = get_input_output_files(args)
    if not files:
jhoogenboom's avatar
jhoogenboom committed
200 201
        raise ValueError("please specify an input file, or pipe in the output "
                         "of another program")
202 203 204 205 206 207 208 209 210 211
    try:
        compute_stats(files[0], files[1], args.allelelist,
                      args.annotation_column, args.min_pct, args.min_abs,
                      args.min_samples, args.min_sample_pct,
                      args.sequence_format, args.library, args.marker,
                      args.limit_reads, args.drop_samples)
    except IOError as e:
        if e.errno == EPIPE:
            return
        raise
jhoogenboom's avatar
jhoogenboom committed
212
#run