primer3.py 8.29 KB
Newer Older
1
2
3
4
5
6
7
8
9
"""
prinia.primer3
~~~~~~~~~~~~~~

:copyright: (c) 2017-2018 Sander Bollen
:copyright: (c) 2017-2018 Leiden University Medical Center
:license: MIT
"""
from pathlib import Path
Sander Bollen's avatar
Sander Bollen committed
10
11
from tempfile import NamedTemporaryFile
from subprocess import check_call
12
from typing import Optional
Sander Bollen's avatar
Sander Bollen committed
13
import os
14
import json
Sander Bollen's avatar
Sander Bollen committed
15

16
17
import re

18
from jinja2 import Template
19
20
from jsonschema import validate

21
22
23
from .models import Primer


24
25
SETTINGS_SCHEMA = (Path(__file__).parent / Path("static") /
                   Path("primer3_settings_schema.json"))
26
TEMPLATE = Path(__file__).parent / Path("static") / Path("primer3_conf.j2")
27
28


29
30
def parse_settings(settings_file: Optional[Path] = None,
                   settings_schema: Path = SETTINGS_SCHEMA) -> dict:
31
32
33
34
35
36
37
    """
    Parse settings file to settings dictionary.

    Parameters not specified in settings_file will be taken from default values
    in schema. If settings_file is None, all values will be the default values
    in schema
    :param settings_file: Optional path to settings file
38
39
    :param settings_schema: Path to schema json for settings. Default is
    supplied schema in static/primer3_settings_schema.json
40
41
42
    :return: dict with settings
    :raises: ValidationError if settings_file does not conform to schema
    """
43
    with settings_schema.open("r") as schema_handle:
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        schema_dict = json.load(schema_handle)

    defaults = {k: v['default'] for k, v in schema_dict['properties'].items()}

    if settings_file is None:
        return defaults

    with settings_file.open("r") as settings_handle:
        settings_dict = json.load(settings_handle)

    validate(settings_dict, schema_dict)  # raises ValidationError if failure

    default_keys = defaults.keys() - settings_dict.keys()
    default_dict = {k: defaults[k] for k in default_keys}
    generated_dict = {**settings_dict, **default_dict}

    # if range is set, but optimum size is not, calculate opt size
    if ('primer_product_opt_size' in default_dict and
            "primer_product_size_range" in settings_dict):
        product_range = settings_dict['primer_product_size_range']
        min_size, max_size = product_range.split("-")
65
        opt_size = int((int(min_size) + (int(max_size) - int(min_size)) // 2))
66
67
68
69
70
        generated_dict['primer_product_opt_size'] = opt_size

    return generated_dict


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def create_primer3_config(settings_dict: dict,
                          sequence_template: str,
                          sequence_target: str,
                          excluded_region: str,
                          template_path: Path = TEMPLATE) -> str:
    """Create primer3 configuration from jinja2 template and settings_dict"""
    with template_path.open("r") as thandle:
        template = Template(thandle.read())

    return template.render(
        {
            "seq": sequence_template,
            "target": sequence_target,
            "excluded_region": excluded_region,
            "settings": settings_dict
        }
    )


Sander Bollen's avatar
Sander Bollen committed
90
91
92
93
94
95
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class Primer3(object):

    def __init__(self, primer3_exe, template, target, excluded_region,
                 opt_prim_length=25, opt_gc_perc=50, min_melting_t=58,
                 max_melting_t=62, min_product_size=200,
                 max_product_size=600):
        self.primer3_exe = primer3_exe
        self.template = template
        self.target = target
        self.excluded_region = excluded_region
        self.opt_prim_length = opt_prim_length
        self.opt_gc_perc = opt_gc_perc
        self.min_melting_t = min_melting_t
        self.max_melting_t = max_melting_t
        self.min_product_size = min_product_size
        self.max_product_size = max_product_size

    @property
    def range(self):
        return "{0}-{1}".format(self.min_product_size, self.max_product_size)

    @property
    def opt_size(self):
        return int(
            self.min_product_size +
            (float((self.max_product_size - self.min_product_size)) / 2)
        )

    def create_config(self, handle):
        """Create config for primer3."""

        cfg_str = "SEQUENCE_ID=example\n" \
                  "SEQUENCE_TEMPLATE={seq}\n" \
                  "SEQUENCE_TARGET={tar}\n" \
                  "SEQUENCE_EXCLUDED_REGION={exc}\n" \
                  "PRIMER_TASK=pick_detection_primers\n" \
                  "PRIMER_PICK_LEFT_PRIMER=1\n" \
                  "PRIMER_PICK_INTERNAL_OLIGO=0\n" \
                  "PRIMER_PICK_RIGHT_PRIMER=1\n" \
                  "PRIMER_MIN_GC=20.0\n" \
                  "PRIMER_INTERNAL_MIN_GC=20.0\n" \
                  "PRIMER_OPT_GC_PERCENT={gc}\n" \
                  "PRIMER_MAX_GC=80.0\n" \
                  "PRIMER_INTERNAL_MAX_GC=80.0\n" \
                  "PRIMER_WT_GC_PERCENT_LT=0.0\n" \
                  "PRIMER_INTERNAL_WT_GC_PERCENT_LT=0.0\n" \
                  "PRIMER_GC_CLAMP=0\n" \
                  "PRIMER_MAX_END_GC=5\n" \
                  "PRIMER_OPT_SIZE={size}\n" \
                  "PRIMER_MIN_SIZE={isize}\n" \
                  "PRIMER_MAX_SIZE={asize}\n" \
                  "PRIMER_MAX_NS_ACCEPTED=0\n" \
                  "PRIMER_PRODUCT_SIZE_RANGE={range}\n" \
                  "PRIMER_PRODUCT_OPT_SIZE={osize}\n" \
                  "PRIMER_PAIR_WT_PRODUCT_SIZE_GT=0.1\n" \
                  "PRIMER_PAIR_WT_PRODUCT_SIZE_LT=0.1\n" \
                  "P3_FILE_FLAG=1\n" \
                  "SEQUENCE_INTERNAL_EXCLUDED_REGION=37,21\n" \
                  "PRIMER_EXPLAIN_FLAG=1\n" \
                  "PRIMER_MIN_TM={it}\n" \
                  "PRIMER_MAX_TM={at}\n" \
Sander Bollen's avatar
Sander Bollen committed
151
                  "PRIMER_NUM_RETURN=200\n" \
Sander Bollen's avatar
Sander Bollen committed
152
153
154
155
156
157
158
159
160
161
162
                  "=".format(seq=self.template, tar=self.target,
                             exc=self.excluded_region,
                             gc=self.opt_gc_perc,
                             size=self.opt_prim_length,
                             isize=self.opt_prim_length-5,
                             asize=self.opt_prim_length+5,
                             range=self.range,
                             osize=self.opt_size,
                             it=self.min_melting_t,
                             at=self.max_melting_t
                             )
Sander Bollen's avatar
Sander Bollen committed
163
164
165
166

        handle.write(cfg_str)

    def run(self):
Sander Bollen's avatar
Sander Bollen committed
167
        cfg = NamedTemporaryFile(delete=False, mode="w")
Sander Bollen's avatar
Sander Bollen committed
168
169
170
        out = NamedTemporaryFile()

        self.create_config(cfg)
Sander Bollen's avatar
Sander Bollen committed
171
        cfg.close()
Sander Bollen's avatar
Sander Bollen committed
172
173
        args = [self.primer3_exe, "-output", out.name, cfg.name]

Sander Bollen's avatar
Sander Bollen committed
174
        _ = check_call(args)  # noqa
Sander Bollen's avatar
Sander Bollen committed
175

176
        retval = []
Sander Bollen's avatar
Sander Bollen committed
177
178
        with open(out.name) as handle:
            for l in handle:
179
                retval.append(l.strip())
Sander Bollen's avatar
Sander Bollen committed
180
181

        out.close()
Sander Bollen's avatar
Sander Bollen committed
182
        os.remove(cfg.name)
183

Sander Bollen's avatar
Sander Bollen committed
184
        return retval
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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


def _parse_single_pair_id(id, lines):
    """Parse single pair id"""
    left_seq_key = "PRIMER_LEFT_{0}_SEQUENCE=".format(id)
    right_seq_key = "PRIMER_RIGHT_{0}_SEQUENCE=".format(id)
    left_pos_key = "PRIMER_LEFT_{0}=".format(id)
    right_pos_key = "PRIMER_RIGHT_{0}=".format(id)
    left_gc_key = "PRIMER_LEFT_{0}_GC_PERCENT".format(id)
    right_gc_key = "PRIMER_RIGHT_{0}_GC_PERCENT".format(id)

    left_seq_line = [x for x in lines if x.startswith(left_seq_key)]
    right_seq_line = [x for x in lines if x.startswith(right_seq_key)]
    left_pos_line = [x for x in lines if x.startswith(left_pos_key)]
    right_pos_line = [x for x in lines if x.startswith(right_pos_key)]
    left_gc_line = [x for x in lines if x.startswith(left_gc_key)]
    right_gc_line = [x for x in lines if x.startswith(right_gc_key)]

    d = {}
    for name, val in zip(
            ["left", "right", "left_gc", "right_gc"],
            [left_seq_line, right_seq_line, left_gc_line, right_gc_line]
    ):
        if len(val) != 1:
            raise ValueError("Value for {n} "
                             "must have exactly one match".format(n=name))
        d[name] = val[0].split("=")[-1]

    for name, val in zip(["left_pos", "right_pos"],
                         [left_pos_line, right_pos_line]):
        if len(val) != 1:
            raise ValueError("Vale for {n} "
                             "must have exactly one match".format(n=name))
        d[name] = val[0].split("=")[-1].split(",")[0]

    return Primer(**d)


def parse_primer3_output(lines):
    """Parse primer3 output to Primers"""
    seq_re = re.compile('^PRIMER_LEFT_(\d+)_SEQUENCE=.+$')

    matches = [seq_re.match(x) for x in lines]
    pair_ids = [int(x.group(1)) for x in matches if x is not None]

    for id in pair_ids:
        yield _parse_single_pair_id(id, lines)