design.py 14.7 KB
Newer Older
Sander Bollen's avatar
Sander Bollen committed
1
from builtins import (map, open, str)
Bollen's avatar
init  
Bollen committed
2
3
__author__ = 'ahbbollen'

Sander Bollen's avatar
Sander Bollen committed
4
from tempfile import NamedTemporaryFile
5
from subprocess import check_call, call
Bollen's avatar
init  
Bollen committed
6
7
8
import os
import warnings

9
from Bio.Seq import Seq
Bollen's avatar
init  
Bollen committed
10
from pyfaidx import Fasta
Sander Bollen's avatar
Sander Bollen committed
11
from pysam import AlignmentFile
Bollen's avatar
init  
Bollen committed
12

Sander Bollen's avatar
Sander Bollen committed
13
from .models import Primer, Region
Sander Bollen's avatar
Sander Bollen committed
14
from .primer3 import Primer3, parse_primer3_output
15
16
from .utils import (NoPrimersException, calc_gc, NEW_VCF,
                    generate_fastq_from_primers, is_at_least_version_samtools)
Bollen's avatar
init  
Bollen committed
17

Sander Bollen's avatar
Sander Bollen committed
18
19
PRIMER3_SCRIPT = os.path.join(os.path.join(os.path.dirname(__file__),
                                           "static"), 'getprimers.sh')
Bollen's avatar
init  
Bollen committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


def get_sequence_fasta(region, reference=None, padding=True):
    ref = Fasta(reference)
    if "chr" not in list(ref.keys())[0] and "chr" in region.chr:
        chrom = region.chr.split("chr")[1]
    elif "chr" not in region.chr and "chr" in list(ref.keys())[0]:
        chrom = "chr" + region.chr
    else:
        chrom = region.chr

    if not padding:
        return ref[chrom][region.start:region.stop].seq
    else:
        return ref[chrom][region.start_w_padding:region.stop_w_padding].seq


def run_primer3(sequence, region, padding=True,
                primer3_script=PRIMER3_SCRIPT, product_size="200-450",
39
40
                n_primers=4, prim3_exe=None, **kwargs):
    """Run primer 3. All other kwargs will be passed on to primer3"""
Bollen's avatar
init  
Bollen committed
41
42
43
44
45
46
47
48
49
    if padding:
        target_start = region.padding_left
        target_len = len(sequence) - region.padding_left - region.padding_right
    else:
        target_start = 1
        target_len = len(sequence)

    target = ",".join(map(str, [target_start, target_len]))

50
    p3 = Primer3(prim3_exe, sequence, target, target, **kwargs)
Sander Bollen's avatar
Sander Bollen committed
51
52
    p3_out = p3.run()
    primers = parse_primer3_output(p3_out)
Bollen's avatar
init  
Bollen committed
53
54
55
    return primers


56
57
58
59
60
61
62
63
64
65
66
67
68
69
def samtools_version_check(samtools_exe):
    """Check whether samtools version >= 1.3.0"""
    out = NamedTemporaryFile()

    args = [samtools_exe, "--version"]
    r = call(args, stdout=out)

    if r != 0:  # old samtools versions do not have a version command
        return False

    with open(out.name, "r") as handle:
        lines = handle.readlines()

    version_line = lines[0]
70
    try:
Sander Bollen's avatar
Sander Bollen committed
71
        return is_at_least_version_samtools(version_line, (1, 3))
72
73
74
75
    except ValueError:
        warnings.warn("Could not determine samtools version. "
                      "Assuming it is at least as recent as version 1.3")
        return True
76
77


Sander Bollen's avatar
Sander Bollen committed
78
79
def aln_primers(primers, bwa_exe=None, samtools_exe=None, ref=None,
                output_bam=None):
Sander Bollen's avatar
Sander Bollen committed
80
    """
Sander Bollen's avatar
Sander Bollen committed
81
82
    Align primers with BWA.
    This only works with BWA-ALN due to the short read length.
Sander Bollen's avatar
Sander Bollen committed
83
84
85
86
87
    :param primers: List of primers
    :param bwa_exe: Path to BWA
    :param samtools_exe: Path to samtools
    :param ref: Path to reference fasta
    :param output_bam: Path to final bam file
Sander Bollen's avatar
Sander Bollen committed
88
    :return: instance of pysam.AlignmentFile
Sander Bollen's avatar
Sander Bollen committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    """
    fq1 = NamedTemporaryFile()
    fq2 = NamedTemporaryFile()
    sai1 = NamedTemporaryFile()
    sai2 = NamedTemporaryFile()

    generate_fastq_from_primers(primers, fq1.name, fq2.name)
    aln_args1 = [bwa_exe, 'aln', ref, fq1.name]
    aln_args2 = [bwa_exe, 'aln', ref, fq2.name]

    r = check_call(aln_args1, stdout=sai1)
    if r != 0:
        raise ValueError("bwa aln crashed with error code {0}".format(r))
    r = check_call(aln_args2, stdout=sai2)
    if r != 0:
        raise ValueError("bwa aln crashed with error code {0}".format(r))

    sam = NamedTemporaryFile()
Sander Bollen's avatar
Sander Bollen committed
107
108
    sam_args = [bwa_exe, 'sampe', ref, sai1.name, sai2.name, fq1.name,
                fq2.name]
Sander Bollen's avatar
Sander Bollen committed
109
110
111
112
113
114
115
116
    r = check_call(sam_args, stdout=sam)
    if r != 0:
        raise ValueError("bwa sampe crashed with error code {0}".format(r))

    bam = NamedTemporaryFile()
    bam_args = [samtools_exe, 'view', '-Shb', sam.name]
    r = check_call(bam_args, stdout=bam)
    if r != 0:
Sander Bollen's avatar
Sander Bollen committed
117
118
119
        raise ValueError(
            "samtools view crashed with error code {0}".format(r)
        )
Sander Bollen's avatar
Sander Bollen committed
120

121
    if samtools_version_check(samtools_exe):
Sander Bollen's avatar
Sander Bollen committed
122
123
        final_args = [samtools_exe, 'sort', '-O', 'bam', '-o', output_bam,
                      bam.name]
124
125
    else:
        final_args = [samtools_exe, 'sort', "-f", bam.name, output_bam]
Sander Bollen's avatar
Sander Bollen committed
126
127
    r = check_call(final_args)
    if r != 0:
Sander Bollen's avatar
Sander Bollen committed
128
129
130
        raise ValueError(
            "samtools sort crashed with error code {0}".format(r)
        )
Sander Bollen's avatar
Sander Bollen committed
131
132
133
134

    index_args = [samtools_exe, "index", output_bam]
    r = check_call(index_args)
    if r != 0:
Sander Bollen's avatar
Sander Bollen committed
135
136
137
        raise ValueError(
            "samtools index crashed with error code {0}".format(r)
        )
Sander Bollen's avatar
Sander Bollen committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

    # cleanup
    for i in [fq1, fq2, sai1, sai2, sam, bam]:
        i.close()

    return AlignmentFile(output_bam, "rb")


def _get_match_fraction(aligned_segment):
    """Get the fraction of a read matching the reference"""
    matching_bases = aligned_segment.cigartuples[0][1]
    return float(matching_bases)/aligned_segment.query_length


def _read_on_same_chrom(aligned_segment, variant=None, region=None):
    """Return true if read is on same chromosome as variant or region"""
    read_chrom = aligned_segment.reference_name.split("chr")[-1]
    if variant is not None:
        variant_chrom = variant.chromosome.split("chr")[-1]
    elif region is not None:
        variant_chrom = region.chr.split("chr")[-1]
    else:
        raise ValueError
    return read_chrom == variant_chrom
Bollen's avatar
init  
Bollen committed
162
163


Sander Bollen's avatar
Sander Bollen committed
164
165
166
167
168
169
def _has_alternative_alignments(aligned_segment):
    """Return true if read has alternative alignments"""
    tags = aligned_segment.get_tags()
    return "XA" in [x[0] for x in tags]


Sander Bollen's avatar
Sander Bollen committed
170
171
def create_primer_from_pair(read1, read2, position=0,
                            reverse_as_complement=True):
Sander Bollen's avatar
Sander Bollen committed
172
    """Create primer from read pair"""
173
174
175
176
177
    if reverse_as_complement:
        seq = Seq(read2.query_sequence)
        reverse_seq = str(seq.reverse_complement())
    else:
        reverse_seq = read2.query_sequence
Sander Bollen's avatar
Sander Bollen committed
178
179
180
181
    return Primer(
        chromosome=read1.reference_name,
        position=position,
        left=read1.query_sequence,
182
        right=reverse_seq,
Sander Bollen's avatar
Sander Bollen committed
183
184
185
186
187
188
189
190
191
192
193
        left_pos=read1.reference_start,
        right_pos=read2.reference_start,
        left_len=read1.query_length,
        right_len=read2.query_length,
        left_gc=calc_gc(read1.query_sequence),
        right_gc=calc_gc(read2.query_sequence)
    )


def create_primers_bwa(bam_handle, variant=None, region=None):
    """
Sander Bollen's avatar
Sander Bollen committed
194
    Find correct pairs in a bam file containing primers for a variant or region
Sander Bollen's avatar
Sander Bollen committed
195
196
197
    This requires to hold the bam file in memory. Use only with small bam files
    :param bam_handle: pysam.AlignmentFile instance
    :param variant: variant
Sander Bollen's avatar
Sander Bollen committed
198
    :param region: region
Sander Bollen's avatar
Sander Bollen committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    :return: generator of primers
    """
    if variant is not None and region is not None:
        raise ValueError("Either variant _or_ region must be set")
    elif variant is None and region is None:
        raise ValueError("Either variant _or_ region must be set")

    pairs = {}  # bucket to hold pairs
    for read in bam_handle:
        if read.is_read1:
            if read.query_name in pairs:
                pairs[read.query_name].update({"r1": read})
            else:
                pairs[read.query_name] = {"r1": read}
        elif read.is_read2:
            if read.query_name in pairs:
                pairs[read.query_name].update({"r2": read})
            else:
                pairs[read.query_name] = {"r2": read}

    for pair in pairs.values():
        # must match at least 90%
        # must be on same chromosome as variant
        # may not have alternative alignments
        # pair must be complete
        if "r1" not in pair or "r2" not in pair:
            continue
        if _get_match_fraction(pair['r1']) < 0.9:
            continue
        if _get_match_fraction(pair['r2']) < 0.9:
            continue

        if variant is not None:
            if not _read_on_same_chrom(pair['r1'], variant=variant):
                continue
            if not _read_on_same_chrom(pair['r2'], variant=variant):
                continue
Bollen's avatar
init  
Bollen committed
236
        else:
Sander Bollen's avatar
Sander Bollen committed
237
238
239
240
            if not _read_on_same_chrom(pair['r1'], region=region):
                continue
            if not _read_on_same_chrom(pair['r2'], region=region):
                continue
Bollen's avatar
init  
Bollen committed
241

Sander Bollen's avatar
Sander Bollen committed
242
243
244
245
246
247
        if _has_alternative_alignments(pair['r1']):
            continue
        if _has_alternative_alignments(pair['r2']):
            continue

        if variant is not None:
Sander Bollen's avatar
Sander Bollen committed
248
249
            yield create_primer_from_pair(pair['r1'], pair['r2'],
                                          variant.position_g_start)
Sander Bollen's avatar
Sander Bollen committed
250
        else:
Sander Bollen's avatar
Sander Bollen committed
251
252
            position = int(region.start) + int((float(
                (int(region.stop) - int(region.start)))/2))
Sander Bollen's avatar
Sander Bollen committed
253
254
255
            yield create_primer_from_pair(pair['r1'], pair['r2'], position)


Sander Bollen's avatar
Sander Bollen committed
256
257
def find_best_bwa(bam, variant=None, region=None, accept_snp=False,
                  field=None, max_freq=None, dbsnp=None):
Sander Bollen's avatar
Sander Bollen committed
258
259
    primers = []
    for primer in create_primers_bwa(bam, variant=variant, region=region):
Sander Bollen's avatar
Sander Bollen committed
260
        if not accept_snp and max_freq is not None and dbsnp is not None:
Sander Bollen's avatar
Sander Bollen committed
261
262
263
264
265
            prim = find_snps(primer, dbsnp, field)
            if prim.snp_freq <= max_freq:
                primers.append(prim)
        else:
            primers.append(primer)
Bollen's avatar
init  
Bollen committed
266
267
    if len(primers) == 0:
        raise NoPrimersException("No suitable primers could be detected")
Sander Bollen's avatar
Sander Bollen committed
268
269
    else:
        return primers
Bollen's avatar
init  
Bollen committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294


def _freq_in_query(query, field):
    """
    Get amount of records and frequencies for a query (= reader iterator)
    :param query: VCF reader iterator
    :param field: the field to fetch
    :return:
    """
    n = 0
    freqs = []
    for record in query:
        n += 1
        try:
            freqs += list(map(float, record.INFO[field]))
        except ValueError:
            freqs += [0]
        except KeyError:
            freqs += [0]
    return n, freqs


def find_snps(primer, db_snp=None, field="AF"):
    try:
        import vcf
Sander Bollen's avatar
Sander Bollen committed
295
    except ImportError:
Bollen's avatar
init  
Bollen committed
296
297
        return None

298
299
300
    if db_snp is None:
        return None

Bollen's avatar
init  
Bollen committed
301
302
303
304
305
306
    reader = vcf.Reader(filename=db_snp)

    left_end = int(primer.left_pos) + len(primer.left)
    right_end = int(primer.right_pos) + len(primer.right)

    contigs = list(reader.contigs.keys())
307
    if len(contigs) == 0:
Sander Bollen's avatar
Sander Bollen committed
308
309
310
311
        raise ValueError(
            "The VCF file does not contain contigs in the header."
        )
    if "chr" in contigs[0] and "chr" not in primer.chromosome:
Bollen's avatar
init  
Bollen committed
312
        chrom = "chr" + primer.chromosome
Sander Bollen's avatar
Sander Bollen committed
313
    elif "chr" in primer.chromosome and "chr" not in contigs[0]:
Bollen's avatar
init  
Bollen committed
314
315
316
317
318
319
320
321
322
323
324
        chrom = primer.chromosome.split("chr")[1]
    else:
        chrom = primer.chromosome

    if NEW_VCF:
        query = reader.fetch(chrom, int(primer.left_pos), left_end)
    else:
        query = reader.fetch(chrom, int(primer.left_pos) + 1, left_end)

    left_n, left_freqs = _freq_in_query(query, field)

Sander Bollen's avatar
Sander Bollen committed
325
326
    # can't have two pysam queries open at the same time,
    # so have to do this this way
Bollen's avatar
init  
Bollen committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    if NEW_VCF:
        right_query = reader.fetch(chrom, int(primer.right_pos), right_end)
    else:
        right_query = reader.fetch(chrom, int(primer.right_pos) + 1, right_end)

    right_n, right_freqs = _freq_in_query(right_query, field)
    n = left_n + right_n
    freqs = right_freqs + left_freqs

    if n > 0:
        primer.contains_SNP = True
        primer.contains_freq_SNP = True
        if len(freqs) > 0:
            primer.snp_freq = max(freqs)
    return primer


def chop_region(region, size):
    """
    Chop a region in multiple regions with max size `size`
    Child regions inherit the padding of their parents
    :param region: the region to be chopped
    :param size: integer
    :return: List[Region]
    """
    if len(region) <= size:
        return [region]
Sander Bollen's avatar
Sander Bollen committed
354
355
356
357
    first = Region(chromosome=region.chr, start=region.start,
                   stop=region.start+size,
                   acc_nr=region.acc_nr, padding_left=region.padding_left,
                   padding_right=region.padding_right,
Bollen's avatar
init  
Bollen committed
358
359
360
361
362
363
364
365
366
                   other=region.other_information)
    regions = [first]
    while sum([len(x) for x in regions]) < len(region):
        last = regions[-1]
        if last.stop + size >= region.stop:
            stop = region.stop
        else:
            stop = last.stop + size

Sander Bollen's avatar
Sander Bollen committed
367
368
369
370
        nex = Region(chromosome=region.chr, start=last.stop,
                     stop=stop, acc_nr=region.acc_nr,
                     padding_left=region.padding_left,
                     padding_right=region.padding_right,
Bollen's avatar
init  
Bollen committed
371
372
373
374
375
376
                     other=region.other_information)
        regions.append(nex)
    return regions


def get_primer_from_region(region, reference, product_size, n_prims,
Sander Bollen's avatar
Sander Bollen committed
377
378
                           bwa_exe, samtools_exe, primer3_exe,
                           output_bam=None, dbsnp=None, field=None,
379
380
381
                           max_freq=None, strict=False, min_margin=10,
                           **prim_args):
    """**prim_args will be passed on to primer3"""
Bollen's avatar
init  
Bollen committed
382
383
384
385
386
387
388
389
390
391
392
393
394

    min_length, max_length = list(map(int, product_size.split("-")))
    regions = chop_region(region, min_length)
    if any([x.size(True) > max_length for x in regions]):
        warnings.warn("Current padding results in larger regions than allowed")

    primers = []
    return_regions = []

    for reg in regions:
        sequence = get_sequence_fasta(reg, reference=reference)
        raw_primers = run_primer3(sequence, reg, padding=True,
                                  product_size=product_size,
395
396
                                  n_primers=n_prims, prim3_exe=primer3_exe,
                                  **prim_args)
Sander Bollen's avatar
Sander Bollen committed
397
398
        bam = aln_primers(raw_primers, bwa_exe=bwa_exe,
                          samtools_exe=samtools_exe,
Sander Bollen's avatar
Sander Bollen committed
399
                          ref=reference, output_bam=output_bam)
Sander Bollen's avatar
Sander Bollen committed
400
401
        prims = find_best_bwa(bam, region=reg, dbsnp=dbsnp, field=field,
                              max_freq=max_freq)
Sander Bollen's avatar
Sander Bollen committed
402
403
        tmp_reg = []
        tmp_prim = []
Bollen's avatar
init  
Bollen committed
404
405

        # filter out primers too close to the variant
Sander Bollen's avatar
Sander Bollen committed
406
        for primer in prims:
Sander Bollen's avatar
Sander Bollen committed
407
408
            if not (int(primer.left_pos) + int(primer.left_len) + min_margin
                    ) < int(reg.start):
Sander Bollen's avatar
Sander Bollen committed
409
410
411
412
                continue
            if not (int(primer.right_pos) - min_margin) > int(reg.stop):
                continue

Sander Bollen's avatar
Sander Bollen committed
413
414
415
416
            n_region = Region(start=int(primer.left_pos),
                              stop=int(primer.right_pos)+len(primer.right),
                              chromosome=primer.chromosome,
                              padding_left=0, padding_right=0,
Sander Bollen's avatar
Sander Bollen committed
417
                              acc_nr="NA", other="NA")
Sander Bollen's avatar
Sander Bollen committed
418
419
420
            primer.fragment_sequence = get_sequence_fasta(n_region,
                                                          reference=reference,
                                                          padding=False)
Sander Bollen's avatar
Sander Bollen committed
421
422
423
424
425
426
427
            if strict and len(primer.fragment_sequence) > max_length:
                continue
            else:
                tmp_prim.append(primer)
                tmp_reg.append(reg)
        if len(tmp_prim) > 0 and len(tmp_prim) > 0:
            primers.append(tmp_prim[0])
Bollen's avatar
init  
Bollen committed
428
429
430
431
            return_regions.append(reg)
    if len(primers) == 0 or len(return_regions) == 0:
        raise NoPrimersException
    return return_regions, primers