lib.py 63.7 KB
Newer Older
jhoogenboom's avatar
jhoogenboom committed
1
2
#!/usr/bin/env python

3
import re, sys, argparse, random, itertools
jhoogenboom's avatar
jhoogenboom committed
4
#import numpy as np  # Imported only when calling nnls()
jhoogenboom's avatar
jhoogenboom committed
5
6

from ConfigParser import RawConfigParser, MissingSectionHeaderError
7
from StringIO import StringIO
jhoogenboom's avatar
jhoogenboom committed
8
9
10
11

# Patterns that match entire sequences.
PAT_SEQ_RAW = re.compile("^[ACGT]*$")
PAT_SEQ_TSSV = re.compile("^(?:[ACGT]+\(\d+\))*$")
12
PAT_SEQ_ALLELENAME_STR = re.compile(  # First line: n_ACT[m] or alias.
jhoogenboom's avatar
jhoogenboom committed
13
    "^(?:(?:(?:CE)?-?\d+(?:\.\d+)?_(?:[ACGT]+\[\d+\])*)|((?!_).+?))"
jhoogenboom's avatar
jhoogenboom committed
14
    "(?:_[-+]\d+(?:\.1)?(?P<a>(?:(?<=\.1)-)|(?<!\.1)[ACGT]+)>"  # _+3A>
15
        "(?!(?P=a))(?:[ACGT]+|-))*$")  # Portion of variants after '>'.
16
17
18
PAT_SEQ_ALLELENAME_SNP = re.compile(
    "^REF$|^(?:(?:(?<=^)|(?<!^) )"  # 'REF' or space-separated variants.
    "\d+(?:\.1)?(?P<a>(?:(?<=\.1)-)|(?<!\.1)[ACGT]+)>"
19
        "(?!(?P=a))(?:[ACGT]+|-))+$")  # Portion of variants after '>'.
20
21
PAT_SEQ_ALLELENAME_MT = re.compile(
    "^REF$|^(?:(?:(?<=^)|(?<!^) )"  # 'REF' or space-separated variants.
22
    "(?:-?\d+\.\d+[ACGT]|(?P<a>[ACGT])?\d+(?(a)(?!(?P=a)))(?:[ACGT-]|del)))+$")
jhoogenboom's avatar
jhoogenboom committed
23

24
# Patterns that match blocks of TSSV-style sequences and allele names.
jhoogenboom's avatar
jhoogenboom committed
25
26
PAT_TSSV_BLOCK = re.compile("([ACGT]+)\((\d+)\)")
PAT_ALLELENAME_BLOCK = re.compile("([ACGT]+)\[(\d+)\]")
27
PAT_ALIAS = re.compile("^(?!_).+$")
jhoogenboom's avatar
jhoogenboom committed
28

29
30
31
32
# Patterns that match a single variant.
PAT_VARIANT_STR = re.compile(
    "^(?P<pos>[-+]\d+)(?:\.(?P<ins>1))?"
    "(?P<old>(?:(?<=\.1)-)|(?<!\.1)[ACGT]+)>"
33
    "(?!(?P=old))(?P<new>[ACGT]+|-)$")
34
35
36
PAT_VARIANT_SNP = re.compile(
    "^(?P<pos>\d+)(?:\.(?P<ins>1))?"
    "(?P<old>(?:(?<=\.1)-)|(?<!\.1)[ACGT]+)>"
37
    "(?!(?P=old))(?P<new>[ACGT]+|-)$")
38
39
40
41
PAT_VARIANT_MT = re.compile(
    "^(?P<old>(?P<a>[ACGT])|-?)"
    "(?P<pos>\d+)(?(a)|(?:\.(?P<ins>\d+))?)"
    "(?P<new>[ACGT-]|del)$")
jhoogenboom's avatar
jhoogenboom committed
42
43

# Patterns that match (parts of) an STR definition.
44
PAT_STR_DEF = re.compile("^(?:(?:(?<=^)|(?<!^)\s+)[ACGT]+\s+\d+\s+\d+)*$")
jhoogenboom's avatar
jhoogenboom committed
45
46
47
PAT_STR_DEF_BLOCK = re.compile("([ACGT]+)\s+(\d+)\s+(\d+)")

# Pattern to split a comma-, semicolon-, or space-separated list.
48
49
50
51
52
PAT_SPLIT = re.compile("\s*[,; \t]\s*")

# Pattern that matches a chromosome name/number.
PAT_CHROMOSOME = re.compile(
    "^(?:[Cc][Hh][Rr](?:[Oo][Mm])?)?([1-9XYM]|1\d|2[0-2])$")
jhoogenboom's avatar
jhoogenboom committed
53

jhoogenboom's avatar
jhoogenboom committed
54
55
# Default regular expression to capture sample tags in file names.
# This is the default of the -e command line option.
jhoogenboom's avatar
jhoogenboom committed
56
DEF_TAG_EXPR = "^(.*?)(?:\.[^.]+)?$"
jhoogenboom's avatar
jhoogenboom committed
57
58
59
60
61

# Default formatting template to write sample tags.
# This is the default of the -f command line option.
DEF_TAG_FORMAT = "\\1"

62
63
64
65
66
# Default formatting template to construct output file names for batch
# processing.  \1 and \2 refer to sample tag and tool name.
# This is the default for the -o command line option with batch support.
DEF_OUTFILE_FORMAT = "\\1-\\2.out"

jhoogenboom's avatar
jhoogenboom committed
67
68
69
70
71
72
# IUPAC Table of complementary bases.
COMPL = {"A": "T", "T": "A", "U": "A", "G": "C", "C": "G", "R": "Y", "Y": "R",
         "K": "M", "M": "K", "B": "V", "V": "B", "D": "H", "H": "D",
         "a": "t", "t": "a", "u": "a", "g": "c", "c": "g", "r": "y", "y": "r",
         "k": "m", "m": "k", "b": "v", "v": "b", "d": "h", "h": "d"}

73
74
75
# Special values that may appear in the place of a sequence.
SEQ_SPECIAL_VALUES = ("No data", "Other sequences")

jhoogenboom's avatar
jhoogenboom committed
76

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
def get_genome_pos(location, x, invert=False):
    """Get the genome position of the x-th base in a sequence."""
    if invert:
        offset = 0
        for i in range(1, len(location)):
            if i % 2:
                # Starting position.
                pos = location[i]
            elif pos <= x <= location[i]:
                # x is in the current range
                break
            else:
                offset += location[i]-pos+1
        else:
            if len(location) % 2:
                raise ValueError("Position %i is outside sequence range" % x)
        return offset + x - pos
    else:
        for i in range(1, len(location)):
            if i % 2:
                # Starting position.
                pos = location[i]
            elif location[i]-pos < x:
                # x is after this ending position
                x -= location[i]-pos+1
            else:
                # x is before this ending position
                break
        return pos + x
#get_genome_pos


109
def call_variants(template, sequence, location="suffix", cache=True,
jhoogenboom's avatar
jhoogenboom committed
110
111
112
                  debug=False):
    """
    Perform a global alignment of sequence to template and return a
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    list of variants detected.  The format (nomenclature) of the
    returned variants depends on the location argument.

    If location is "suffix" (the default), all variants are given as
    substitutions in the form posX>Y, where the first base in the
    template is pos=1.  With location set to "prefix", bases are counted
    from right to left instead.  Insertions and deletions are written as
    pos.1->Y and posX>-, respectively.

    If location is a tuple ("M", position) with any integer for the
    position, variants are written following the mtDNA nomenclature
    guidelines.  The given position is that of the first base in the
    template.

    If location is a tuple ("chromosome name", position), a
    NotImplementedError is raised.
jhoogenboom's avatar
jhoogenboom committed
129
130
131
132
133
134
135
136
137

    By default, the results of this function are cached.  Set cache to
    False to suppress caching the result and reduce memory usage.

    Setting debug to True will cause the alignment matrices to be
    printed to sys.stdout.  Be aware that they can be quite large.
    """
    # Saving the results in a cache to avoid repeating alignments.
    try:
138
        return call_variants.cache[template, sequence, location]
jhoogenboom's avatar
jhoogenboom committed
139
    except KeyError:
140
        cache_key = location
jhoogenboom's avatar
jhoogenboom committed
141
142
143
144
145
146
147
148
149
150

    row_offset = len(template) + 1
    matrix_match = [0] * row_offset * (len(sequence)+1)
    matrix_gap1 = [-sys.maxint-1] * row_offset * (len(sequence)+1)
    matrix_gap2 = [-sys.maxint-1] * row_offset * (len(sequence)+1)

    MATCH_SCORE = 1
    MISMATCH_SCORE = -1
    GAP_OPEN_SCORE = -10
    GAP_EXTEND_SCORE = -1
151
152
153
154
155
156
157
158
    variant_format = "%i%s>%s"

    if location == "prefix":
        location = ("prefix", -len(template))
    elif location == "suffix":
        # Include plus signs for position numbers.
        variant_format = "%+i%s>%s"
        location = ("suffix", 1)
159
    elif type(location) != tuple or len(location) < 2:
160
        raise ValueError("Unknown location %r. It should be 'prefix', "
161
162
            "'suffix', or a tuple (chromosome, position [, endpos])" %
            location)
jhoogenboom's avatar
jhoogenboom committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
232
233
234

    for i in range(len(matrix_match)):
        x = i % row_offset
        y = i / row_offset

        # Initialisation of first row and column.
        if x == 0 or y == 0:
            if x != 0:
                # Top row.
                matrix_gap1[i] = GAP_OPEN_SCORE + GAP_EXTEND_SCORE * (x - 1)
                matrix_match[i] = matrix_gap1[i]
            elif y != 0:
                # Left column.
                matrix_gap2[i] = GAP_OPEN_SCORE + GAP_EXTEND_SCORE * (y - 1)
                matrix_match[i] = matrix_gap2[i]
            continue

        matrix_gap1[i] = max(
            matrix_match[i-1] + GAP_OPEN_SCORE,
            matrix_gap1[i-1] + GAP_EXTEND_SCORE)
        matrix_gap2[i] = max(
            matrix_match[i-row_offset] + GAP_OPEN_SCORE,
            matrix_gap2[i-row_offset] + GAP_EXTEND_SCORE)

        if template[x-1] == sequence[y-1]:
            match = MATCH_SCORE
        else:
            match = MISMATCH_SCORE

        matrix_match[i] = max(
            matrix_match[i-1-row_offset] + match,
            matrix_gap1[i],
            matrix_gap2[i])

    if debug:
        print("GAP1")
        for i in range(0, len(matrix_gap1), row_offset):
            print(("%5i" * row_offset) % tuple(matrix_gap1[i:i+row_offset]))
        print("GAP2")
        for i in range(0, len(matrix_gap2), row_offset):
            print(("%5i" * row_offset) % tuple(matrix_gap2[i:i+row_offset]))
        print("Match")
        for i in range(0, len(matrix_match), row_offset):
            print(("%5i" * row_offset) % tuple(matrix_match[i:i+row_offset]))


    # Backtracking.
    variants = []
    variant_template = 0
    variant_sequence = 0
    i = len(matrix_match) - 1
    while i >= 0:
        x = i % row_offset
        y = i / row_offset

        if matrix_gap1[i] == matrix_match[i]:
            # Go horizontally.  Deletion.
            variant_template += 1
            i -= 1
            continue

        if matrix_gap2[i] == matrix_match[i]:
            # Go vertically.  Insertion.
            variant_sequence += 1
            i -= row_offset
            continue

        # Only backtracking diagonally if a gap is out of the question.
        # Go diagonally.  Either match or mismatch.
        if i == 0 or template[x - 1] == sequence[y - 1]:
            # Match.  Flush variants.
            if variant_template or variant_sequence:
235
236
237
238
239
240
                if location[0] == "M":
                    # MtDNA variants are one-base-at-a-time.
                    for j in range(
                            max(variant_template, variant_sequence)-1, -1, -1):
                        variants.append("%s%i%s%s" % (
                            template[x+j] if j < variant_template else "",#"-",
241
242
                            get_genome_pos(
                                location, x + min(j, variant_template-1)),
243
244
                            ".%i" % (j-variant_template+1)
                                if j >= variant_template else "",
245
                            sequence[y+j] if j < variant_sequence else "del"))
246
                elif variant_template == 0:
jhoogenboom's avatar
jhoogenboom committed
247
                    # Insertions: "-131.1->C" instead of "-130->C".
248
                    variants.append(variant_format % (
249
                        get_genome_pos(location, x - 1),
250
                        ".1-",
jhoogenboom's avatar
jhoogenboom committed
251
252
                        sequence[y:y+variant_sequence]))
                else:
253
                    variants.append(variant_format % (
254
                        get_genome_pos(location, x),
jhoogenboom's avatar
jhoogenboom committed
255
256
257
258
259
260
261
262
263
264
                        template[x:x+variant_template],
                        sequence[y:y+variant_sequence] or "-"))
                variant_template = 0
                variant_sequence = 0
        else:
            # Start/extend mismatch.
            variant_template += 1
            variant_sequence += 1
        i -= 1 + row_offset

265
266
    # Variants were called from right to left.  Reverse their order.
    if location[0] != "prefix":
jhoogenboom's avatar
jhoogenboom committed
267
268
269
270
        variants.reverse()

    # Store the result in the cache.
    if cache:
271
        call_variants.cache[template, sequence, cache_key] = variants
jhoogenboom's avatar
jhoogenboom committed
272
273
274
275
276
    return variants
#call_variants
call_variants.cache = {}


277
def mutate_sequence(seq, variants, location=None):
jhoogenboom's avatar
jhoogenboom committed
278
    """Apply the given variants to the given sequence."""
279
    if type(location) != tuple or len(location) < 2:
280
        pattern = PAT_VARIANT_STR
281
        location = (None, 0)
282
283
    elif location[0] == "M":
        pattern = PAT_VARIANT_MT
284
        location = (location[0], location[1]-1) + tuple(location[2:])
285
286
    else:
        pattern = PAT_VARIANT_SNP
287
        location = (location[0], location[1]-1) + tuple(location[2:])
288
289

    seq = [[]] + [[base] for base in seq]
jhoogenboom's avatar
jhoogenboom committed
290
    for variant in variants:
291
        vm = pattern.match(variant)
jhoogenboom's avatar
jhoogenboom committed
292
293
        if vm is None:
            raise ValueError("Unrecognised variant '%s'" % variant)
294
295
296
297
        pos = int(vm.group("pos"))
        ins = int(vm.group("ins") or 0)
        old = vm.group("old")
        new = vm.group("new")
jhoogenboom's avatar
jhoogenboom committed
298
299
        if old == "-":
            old = ""
300
        if new == "-" or new == "del":
jhoogenboom's avatar
jhoogenboom committed
301
302
            new = ""
        if pos < 0:
303
            pos += len(seq)
304
305
        pos = get_genome_pos(location, pos, True)
        if pos < 0 or (pos == 0 and not ins) or pos >= len(seq):
306
            raise ValueError(
307
308
                "Position of variant '%s' is outside sequence range" %
                    (variant))
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        if (not ins and old and old != "".join("".join(x[:1])
                for x in seq[pos:pos+len(old)])):
            raise ValueError(
                "Incorrect original sequence in variant '%s'; should be '%s'!"
                % (variant, "".join("".join(x[:1])
                    for x in seq[pos:pos+len(old)])))
        elif not ins and not old:
            # MtDNA substitution with reference base omitted.
            old = "".join("".join(x[:1]) for x in seq[pos:pos+len(new)])
        if not ins:
            # Remove old bases, retaining those inserted between/after.
            seq[pos:pos+len(old)] = [
                [""] + x[1:] for x in seq[pos:pos+len(old)]]
            # Place new entirely in the position of the first old base.
            seq[pos][0] = new
jhoogenboom's avatar
jhoogenboom committed
324
        else:
325
326
327
328
329
            # Insert new exactly ins positions after pos.
            while len(seq[pos]) <= ins:
                seq[pos].append("")
            seq[pos][ins] = new
    return "".join("".join(x) for x in seq)
jhoogenboom's avatar
jhoogenboom committed
330
331
332
#mutate_sequence


333
def parse_library(libfile, stream=False):
jhoogenboom's avatar
jhoogenboom committed
334
    try:
335
        if not stream:
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
            libfile = sys.stdin if libfile == "-" else open(libfile, "r")
        if libfile == sys.stdin:
            # Can't seek on pipes, so read it into a buffer first.
            libfile = StringIO(sys.stdin.read())
        try:
            library = parse_library_ini(libfile)
            if not stream:
                libfile.close()
            return library
        except MissingSectionHeaderError:
            # Not an ini file.
            pass
        libfile.seek(0)
        library = parse_library_tsv(libfile)
        if not stream and libfile != sys.stdin:
351
352
            libfile.close()
        return library
353
354
    except ValueError as err:
        raise argparse.ArgumentTypeError(err)
jhoogenboom's avatar
jhoogenboom committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#parse_library


def parse_library_tsv(handle):
    """
    Parse a TSSV library file (tab-separated values format).

    The provided file should contain at least four columns: marker name,
    left flanking sequence, right flanking sequence, and STR definition.

    Return a nested dict with top-level keys "flanks" and "regex".
    """
    library = {
      "flanks": {},
369
      "regex": {},
370
      "blocks_middle": {}
jhoogenboom's avatar
jhoogenboom committed
371
372
    }
    for line in handle:
jhoogenboom's avatar
jhoogenboom committed
373
        line = [x.strip() for x in line.rstrip("\r\n").split("\t")]
jhoogenboom's avatar
jhoogenboom committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        if line == [""]:
            continue
        if len(line) < 4:
            raise ValueError(
                "Invalid library file: encountered line with %i columns, "
                "need at least 4" % len(line))
        marker = line[0]
        if PAT_SEQ_RAW.match(line[1]) is None:
            raise ValueError("Flanking sequence '%s' of marker %s is invalid" %
                             (line[1], marker))
        if PAT_SEQ_RAW.match(line[2]) is None:
            raise ValueError("Flanking sequence '%s' of marker %s is invalid" %
                             (line[2], marker))
        if PAT_STR_DEF.match(line[3]) is None:
            raise ValueError("STR definition '%s' of marker %s is invalid" %
                             (line[3], marker))
        library["flanks"][marker] = line[1:3]
391
392
393
        library["blocks_middle"][marker] = [
            (block[0], int(block[1]), int(block[2])) for block in
                PAT_STR_DEF_BLOCK.findall(line[3])]
394
        library["regex"][marker] = re.compile(
395
396
397
            "".join(("^", "".join(
                "(%s){%s,%s}" % x for x in PAT_STR_DEF_BLOCK.findall(line[3])),
                "$")))
jhoogenboom's avatar
jhoogenboom committed
398
399
400
401
402
403
404
405
406
407
    return library
#parse_library_tsv


def parse_library_ini(handle):
    library = {
      "flanks": {},
      "prefix": {},
      "suffix": {},
      "regex": {},
408
      "blocks_middle": {},
409
410
      "nostr_reference": {},
      "genome_position": {},
411
412
      "length_adjust": {},
      "block_length": {},
413
      "max_expected_copies": {},
414
      "expected_length": {},
jhoogenboom's avatar
jhoogenboom committed
415
416
417
418
419
420
421
422
423
424
      "aliases": {}
    }
    markers = set()

    ini = RawConfigParser()
    ini.optionxform = str
    ini.readfp(handle)
    for section in ini.sections():
        for marker in ini.options(section):
            value = ini.get(section, marker)
425
426
            section_low = section.lower()
            if section_low == "flanks":
jhoogenboom's avatar
jhoogenboom committed
427
428
429
430
431
432
433
434
435
436
437
438
                values = PAT_SPLIT.split(value)
                if len(values) != 2:
                    raise ValueError(
                        "For marker %s, %i flanking sequences were given,"
                        "need exactly 2" % (marker, len(values)))
                for value in values:
                    if PAT_SEQ_RAW.match(value) is None:
                        raise ValueError(
                            "Flanking sequence '%s' of marker %s is invalid" %
                            (value, marker))
                library["flanks"][marker] = values
                markers.add(marker)
439
            elif section_low == "prefix":
440
441
442
                if marker in library["nostr_reference"]:
                    raise ValueError(
                        "A prefix was defined for non-STR marker %s" % marker)
jhoogenboom's avatar
jhoogenboom committed
443
444
445
446
447
448
                values = PAT_SPLIT.split(value)
                for value in values:
                    if PAT_SEQ_RAW.match(value) is None:
                        raise ValueError(
                            "Prefix sequence '%s' of marker %s is invalid" %
                            (value, marker))
449
                library["prefix"][marker] = values
jhoogenboom's avatar
jhoogenboom committed
450
                markers.add(marker)
451
            elif section_low == "suffix":
452
453
454
                if marker in library["nostr_reference"]:
                    raise ValueError(
                        "A suffix was defined for non-STR marker %s" % marker)
jhoogenboom's avatar
jhoogenboom committed
455
456
457
458
459
460
                values = PAT_SPLIT.split(value)
                for value in values:
                    if PAT_SEQ_RAW.match(value) is None:
                        raise ValueError(
                            "Suffix sequence '%s' of marker %s is invalid" %
                            (value, marker))
461
                library["suffix"][marker] = values
jhoogenboom's avatar
jhoogenboom committed
462
                markers.add(marker)
463
464
465
466
467
468
469
            elif section_low == "genome_position":
                values = PAT_SPLIT.split(value)
                chromosome = PAT_CHROMOSOME.match(values[0])
                if chromosome is None:
                    raise ValueError(
                        "Invalid chromosome '%s' for marker %s." %
                        (values[0], marker))
470
471
472
473
474
475
476
477
478
479
480
481
482
                pos = [chromosome.group(1)]
                for i in range(1, len(values)):
                    try:
                        pos.append(int(values[i]))
                    except:
                        raise ValueError(
                            "Position '%s' of marker %s is not a valid integer"
                            % (values[i], marker))
                    if not i % 2 and pos[-2] >= pos[-1]:
                        raise ValueError(
                            "End position %i of marker %s must be higher than "
                            "corresponding start position %i" %
                            (pos[-1], marker, pos[-2]))
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
483
484
                if len(values) == 1:
                    pos.append(1)
485
                library["genome_position"][marker] = tuple(pos)
486
                markers.add(marker)
487
            elif section_low == "length_adjust":
jhoogenboom's avatar
jhoogenboom committed
488
489
490
491
492
493
494
495
                try:
                    value = int(value)
                except:
                    raise ValueError(
                        "Length adjustment '%s' of marker %s is not a valid "
                        "integer" % (value, marker))
                library["length_adjust"][marker] = value
                markers.add(marker)
496
            elif section_low == "block_length":
jhoogenboom's avatar
jhoogenboom committed
497
498
499
500
501
502
503
504
                try:
                    value = int(value)
                except:
                    raise ValueError(
                        "Block length '%s' of marker %s is not a valid integer"
                        % (value, marker))
                library["block_length"][marker] = value
                markers.add(marker)
505
506
507
508
509
510
511
512
513
514
            elif section_low == "max_expected_copies":
                try:
                    value = int(value)
                except:
                    raise ValueError(
                        "Maximum number of expected copies '%s' of marker %s "
                        "is not a valid integer" % (value, marker))
                library["max_expected_copies"][marker] = value
                markers.add(marker)
            elif section_low == "aliases":
jhoogenboom's avatar
jhoogenboom committed
515
516
517
518
519
                values = PAT_SPLIT.split(value)
                if len(values) != 3:
                    raise ValueError("Alias %s does not have 3 values, but %i"
                                     % (marker, len(values)))
                if PAT_SEQ_RAW.match(values[1]) is None:
520
521
522
523
524
525
526
                    raise ValueError(
                        "Alias sequence '%s' of alias %s is invalid" %
                        (values[1], marker))
                if PAT_ALIAS.match(values[2]) is None:
                    raise ValueError(
                        "Allele name '%s' of alias %s is invalid" %
                        (values[2], marker))
jhoogenboom's avatar
jhoogenboom committed
527
528
529
530
531
532
                library["aliases"][marker] = {
                    "marker": values[0],
                    "sequence": values[1],
                    "name": values[2]
                }
                markers.add(marker)
533
            elif section_low == "repeat":
534
535
536
537
                if marker in library["nostr_reference"]:
                    raise ValueError(
                        "Marker %s was encountered in both [repeat] and "
                        "[no_repeat] sections" % marker)
jhoogenboom's avatar
jhoogenboom committed
538
539
540
541
542
543
                if PAT_STR_DEF.match(value) is None:
                    raise ValueError(
                        "STR definition '%s' of marker %s is invalid" %
                        (value, marker))
                library["regex"][marker] = value
                markers.add(marker)
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
            elif section_low == "no_repeat":
                if marker in library["regex"]:
                    raise ValueError(
                        "Marker %s was encountered in both [repeat] and "
                        "[no_repeat] sections" % marker)
                if marker in library["prefix"] or marker in library["suffix"]:
                    raise ValueError(
                        "A prefix or suffix was defined for non-STR marker %s"
                        % marker)
                if PAT_SEQ_RAW.match(value) is None:
                    raise ValueError(
                        "Reference sequence '%s' of marker %s is invalid" %
                        (value, marker))
                library["nostr_reference"][marker] = value
                markers.add(marker)
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
            elif section_low == "expected_allele_length":
                values = PAT_SPLIT.split(value)
                try:
                    min_length = int(values[0])
                except:
                    raise ValueError(
                        "Minimum expected allele length '%s' of marker %s "
                        "is not a valid integer" % (values[0], marker))
                if len(values) > 1:
                    try:
                        max_length = int(values[1])
                    except:
                        raise ValueError(
                            "Maximum expected allele length '%s' of marker %s "
                            "is not a valid integer" % (values[1], marker))
                else:
                    max_length = sys.maxint
                library["expected_length"][marker] = (min_length, max_length)
                markers.add(marker)
578
579
580
581
582
583
584
585

    # Sanity check: prohibit prefix/suffix for aliases of non-STRs.
    for alias in library["aliases"]:
        if library["aliases"][alias]["marker"] in library["nostr_reference"] \
                and (alias in library["prefix"] or alias in library["suffix"]):
            raise ValueError(
                "A prefix or suffix was defined for alias %s of non-STR "
                "marker %s" % (alias, library["aliases"][alias]["marker"]))
jhoogenboom's avatar
jhoogenboom committed
586

587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    # Sanity check: end position of marker should reflect ref length.
    for marker in library["genome_position"]:
        if marker not in library["nostr_reference"]:
            continue
        pos = library["genome_position"][marker]
        reflength = len(library["nostr_reference"][marker])
        length = 0
        for i in range(2, len(pos), 2):
            length += pos[i] - pos[i-1] + 1
        if reflength < length or (len(pos) % 2 and reflength != length):
            raise ValueError(
                "Length of reference sequence of marker %s is %i bases, but "
                "genome positions add up to %i bases" %
                (marker, reflength, length))

jhoogenboom's avatar
jhoogenboom committed
602
603
604
605
    # Compile regular expressions.
    # NOTE: The libconvert tool expects "(seq){num,num}" blocks ONLY!
    for marker in markers:
        parts = []
606
        blocksm = []
jhoogenboom's avatar
jhoogenboom committed
607
        if marker in library["prefix"]:
jhoogenboom's avatar
jhoogenboom committed
608
            parts += ("(%s){0,1}" % x for x in library["prefix"][marker])
jhoogenboom's avatar
jhoogenboom committed
609
        if marker in library["aliases"]:
610
            blocksm.append((library["aliases"][marker]["sequence"], 0, 1))
jhoogenboom's avatar
jhoogenboom committed
611
        elif marker in library["regex"]:
612
613
614
            blocksm += [(block[0], int(block[1]), int(block[2])) for block in
                        PAT_STR_DEF_BLOCK.findall(library["regex"][marker])]
        parts += ["(%s){%s,%s}" % x for x in blocksm]
jhoogenboom's avatar
jhoogenboom committed
615
        if marker in library["suffix"]:
jhoogenboom's avatar
jhoogenboom committed
616
            parts += ("(%s){0,1}" % x for x in library["suffix"][marker])
jhoogenboom's avatar
jhoogenboom committed
617
618
619
        if parts:
            library["regex"][marker] = re.compile(
                "".join(["^"] + parts + ["$"]))
620
621
        if blocksm:
            library["blocks_middle"][marker] = blocksm
jhoogenboom's avatar
jhoogenboom committed
622
623
    return library
#parse_library_ini
jhoogenboom's avatar
jhoogenboom committed
624
625


626
def load_profiles(profilefile, library=None):
jhoogenboom's avatar
jhoogenboom committed
627
    column_names = profilefile.readline().rstrip("\r\n").split("\t")
628
629
630
    (colid_marker, colid_allele, colid_sequence, colid_fmean, colid_rmean,
     colid_tool) = get_column_ids(column_names, "marker", "allele", "sequence",
        "fmean", "rmean", "tool")
jhoogenboom's avatar
jhoogenboom committed
631
632
633
634
635
636
637
638
639
640
641
642
643

    profiles = {}
    for line in profilefile:
        line = line.rstrip("\r\n").split("\t")
        if line == [""]:
            continue
        marker = line[colid_marker]
        if marker not in profiles:
            profiles[marker] = {
                "m": set(),  # To be replaced by its length below.
                "n": set(),  # To be replaced by its length below.
                "seqs": [],
                "forward": {},  # To be replaced by a list below.
644
645
                "reverse": {},  # To be replaced by a list below.
                "tool": {}  # To be replaced by a list below.
jhoogenboom's avatar
jhoogenboom committed
646
647
648
649
650
651
652
653
654
655
656
657
                }
        allele = ensure_sequence_format(line[colid_allele], "raw",
            library=library, marker=marker)
        sequence = ensure_sequence_format(line[colid_sequence], "raw",
            library=library, marker=marker)
        if (allele, sequence) in profiles[marker]["forward"]:
            raise ValueError(
                "Invalid background noise profiles file: encountered "
                "multiple values for marker '%s' allele '%s' sequence '%s'" %
                (marker, allele, sequence))
        profiles[marker]["forward"][allele,sequence] = float(line[colid_fmean])
        profiles[marker]["reverse"][allele,sequence] = float(line[colid_rmean])
658
        profiles[marker]["tool"][allele, sequence] = line[colid_tool]
jhoogenboom's avatar
jhoogenboom committed
659
660
661
662
663
664
665
666
667
668
        profiles[marker]["m"].update((allele, sequence))
        profiles[marker]["n"].add(allele)

    # Check completeness and reorder true alleles.
    for marker in profiles:
        profiles[marker]["seqs"] = list(profiles[marker]["n"]) + \
            list(profiles[marker]["m"]-profiles[marker]["n"])
        profiles[marker]["n"] = len(profiles[marker]["n"])
        profiles[marker]["m"] = len(profiles[marker]["m"])
        newprofiles = {"forward": [], "reverse": []}
669
        tools = []
jhoogenboom's avatar
jhoogenboom committed
670
671
672
673
        for i in range(profiles[marker]["n"]):
            allele = profiles[marker]["seqs"][i]
            for direction in newprofiles:
                newprofiles[direction].append([0] * profiles[marker]["m"])
674
            tools.append([""] * profiles[marker]["m"])
jhoogenboom's avatar
jhoogenboom committed
675
676
677
678
679
680
            for j in range(profiles[marker]["m"]):
                sequence = profiles[marker]["seqs"][j]
                if (allele, sequence) in profiles[marker]["forward"]:
                    for direction in newprofiles:
                        newprofiles[direction][i][j] = \
                            profiles[marker][direction][allele, sequence]
681
                    tools[i][j] = profiles[marker]["tool"][allele, sequence]
jhoogenboom's avatar
jhoogenboom committed
682
683
        profiles[marker]["forward"] = newprofiles["forward"]
        profiles[marker]["reverse"] = newprofiles["reverse"]
684
        profiles[marker]["tool"] = tools
jhoogenboom's avatar
jhoogenboom committed
685
686

    return profiles
687
#load_profiles
688
689


690
def pattern_longest_match(pattern, subject):
691
    """Return the longest match of the pattern in the subject string."""
692
693
694
695
696
    # FIXME, this function tries only one match at each position in the
    # sequence, which is not neccessarily the longest match at that
    # position. For now, we'll search the reverse sequence as well.
    # Re-implement this without regular expressions to test all options.
    reverse = False
697
698
    match = None
    pos = 0
699
    pat = re.compile("".join("(%s){%i,%i}" % x for x in pattern))
700
    while pos < len(subject):
701
        m = pat.search(subject, pos)
702
703
704
705
706
        if m is None:
            break
        if match is None or m.end()-m.start() > match.end()-match.start():
            match = m
        pos = m.start() + 1
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755

    # Try to find a longer match from the other end.
    if match is not None:
        subject = reverse_complement(subject)
        pos = 0
        pat = re.compile("".join(
            "(%s){%i,%i}" % (reverse_complement(x[0]), x[1], x[2])
            for x in reversed(pattern)))
        while pos < len(subject):
            m = pat.search(subject, pos)
            if m is None:
                break
            if m.end()-m.start() > match.end()-match.start():
                match = m
                reverse = True
            pos = m.start() + 1

    # Extract the blocks from the match.
    match = [] if match is None or not match.group() else reduce(
        lambda x, i: (
            x[0] + [match.group(i)]*((match.end(i)-x[1])/len(match.group(i))),
            match.end(i)) if match.group(i) else x,
        range(1, match.lastindex+1), ([], match.start()))[0]

    # Return the match in the same sequence orientation as the input.
    return map(reverse_complement, reversed(match)) if reverse else match
#pattern_longest_match


def pattern_longest_match_veryslow(pattern, subject):
    """Return the longest match of the pattern in the subject string."""
    longest = 0
    the_match = []
    # Generate all possible matching sequences for this pattern.
    #print("Finding match of pattern %r to sequence %s" % (pattern, subject))
    for matching_blocks in itertools.product(*(
            [[block[0]]*i for i in range(block[1], block[2]+1)]
            for block in pattern)):
        matching = itertools.chain.from_iterable(matching_blocks)
        matching_seq = "".join(matching)
        matching_len = len(matching_seq)
        if matching_len <= longest:
            continue
        if matching_seq in subject:
            longest = matching_len
            the_match = matching
    #print("Found match covering %i/%i bases" % (longest, len(subject)))
    return the_match
#pattern_longest_match_veryslow
756
757


jhoogenboom's avatar
jhoogenboom committed
758
759
760
def detect_sequence_format(seq):
    """Return format of seq.  One of 'raw', 'tssv', or 'allelename'."""
    if not seq:
jhoogenboom's avatar
jhoogenboom committed
761
        raise ValueError("Empty sequence")
762
    if seq in SEQ_SPECIAL_VALUES:
763
764
        # Special case.
        return False
jhoogenboom's avatar
jhoogenboom committed
765
766
767
768
    if PAT_SEQ_RAW.match(seq):
        return 'raw'
    if PAT_SEQ_TSSV.match(seq):
        return 'tssv'
769
770
    if PAT_SEQ_ALLELENAME_STR.match(seq) or PAT_SEQ_ALLELENAME_MT.match(seq) \
            or PAT_SEQ_ALLELENAME_SNP.match(seq):
jhoogenboom's avatar
jhoogenboom committed
771
        return 'allelename'
jhoogenboom's avatar
jhoogenboom committed
772
    raise ValueError("Unrecognised sequence format")
jhoogenboom's avatar
jhoogenboom committed
773
774
775
#detect_sequence_format


jhoogenboom's avatar
jhoogenboom committed
776
def convert_sequence_tssv_raw(seq):
jhoogenboom's avatar
jhoogenboom committed
777
778
    return "".join(block[0] * int(block[1])
                   for block in PAT_TSSV_BLOCK.findall(seq))
jhoogenboom's avatar
jhoogenboom committed
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
#convert_sequence_tssv_raw


def convert_sequence_raw_tssv(seq, library, marker, return_alias=False):
    # Try to match this marker's pattern, or any of its aliases.
    match = None
    if "aliases" in library:
        for alias in library["aliases"]:
            if (library["aliases"][alias]["marker"] == marker and
                    alias in library["regex"]):
                match = library["regex"][alias].match(seq)
                if match is not None:
                    marker = alias
                    break
    if match is None and marker in library["regex"]:
        match = library["regex"][marker].match(seq)
795
    if match is not None:
jhoogenboom's avatar
jhoogenboom committed
796
797
        parts = ((match.group(i), match.end(i)) for i in range(1, 1 if
            match.lastindex is None else match.lastindex+1) if match.group(i))
jhoogenboom's avatar
jhoogenboom committed
798

799
    # Use heuristics if the sequence does not match the pattern.
jhoogenboom's avatar
jhoogenboom committed
800
    else:
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817

        # Find explictily provided prefix and/or suffix if present.
        pre_suf = ["", ""]
        if "prefix" in library and marker in library["prefix"]:
            for prefix in library["prefix"][marker]:
                if seq.startswith(prefix):
                    pre_suf[0] = prefix
                    seq = seq[len(prefix):]
                    break
        if "suffix" in library and marker in library["suffix"]:
            for suffix in library["suffix"][marker]:
                if seq.endswith(suffix):
                    pre_suf[1] = suffix
                    seq = seq[:-len(suffix)]
                    break

        # Find longest match of middle pattern.
818
        middle = [(seq, len(pre_suf[0])+len(seq))] if seq else []
819
820
821
822
        if middle and marker in library["blocks_middle"]:
            match = pattern_longest_match(library["blocks_middle"][marker],seq)
            matched = "".join(match)
            if matched:
823
824
825
826
827
828

                # If this allele does not match the prefix of this
                # marker, but the canonical prefix of the marker ends
                # with the same sequence as the start of our match, we
                # move that portion of the match into the prefix.
                # Then, we do the same thing with the suffix.
829
830
831
832
833
                middle = match
                match_start = seq.index(matched)
                match_end = match_start + len(matched)
                start = match_start
                end = match_end
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
                modified = False
                if (not pre_suf[0] and "prefix" in library
                        and marker in library["prefix"]):
                    ref = library["prefix"][marker][0]
                    i = min(len(ref), len(matched))
                    while i > 0:
                        if ref.endswith(matched[:i]):
                            start += i
                            matched = matched[i:]
                            modified = True
                            break
                        i -= 1
                if (not pre_suf[1] and "suffix" in library
                        and marker in library["suffix"]):
                    ref = library["suffix"][marker][0]
                    i = min(len(ref), len(matched))
                    while i > 0:
                        if ref.startswith(matched[-i:]):
                            end -= i
                            matched = matched[:-i]
                            modified = True
                            break
                        i -= 1
                if modified:
858
859
                    from_start = start - match_start
                    from_end = match_end - end
860
861
862
863
864
865
866
867
868
869
870
871
872
873
                    while from_start:
                        if from_start < len(middle[0]):
                            middle[0] = middle[0][from_start:]
                            break
                        else:
                            from_start -= len(middle[0])
                            middle = middle[1:]
                    while from_end:
                        if from_end < len(middle[-1]):
                            middle[-1] = middle[-1][:-from_end]
                            break
                        else:
                            from_end -= len(middle[-1])
                            middle = middle[:-1]
874
875
876
877
878
879
                if middle:
                    middle = reduce(
                        lambda x, y: (x[:-1] if x[-1][0] == y else x) +
                            [(y, x[-1][1]+len(y))], middle[1:],
                            [(middle[0],
                              start+len(middle[0])+len(pre_suf[0]))])
880
881
882
883

                pre_suf[0] += seq[:start]
                pre_suf[1] = seq[end:] + pre_suf[1]
                seq = matched
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898

        # Now construct parts.
        parts = []
        if pre_suf[0]:
            parts.append((pre_suf[0], len(pre_suf[0])))
        parts += middle
        if pre_suf[1]:
            parts.append((pre_suf[1], sum(map(len,pre_suf))+len(seq)))

    seq = reduce(
        lambda a, b: (a[0] + "%s(%i)" % (b[0], (b[1]-a[1])/len(b[0])), b[1]),
        reduce(
            lambda x, y: x[:-1] + [y] if x[-1][0] == y[0] else x + [y],
            parts,
            [("", 0)]))[0]
jhoogenboom's avatar
jhoogenboom committed
899
900
901
902
903
904
    return (seq, marker) if return_alias else seq
#convert_sequence_raw_tssv


def convert_sequence_allelename_tssv(seq, library, marker):
    # Check whether there is an alias for this sequence.
905
    alias_of = None
jhoogenboom's avatar
jhoogenboom committed
906
907
908
909
910
    if "aliases" in library:
        for alias in library["aliases"]:
            if library["aliases"][alias]["marker"] == marker and (
                    seq == library["aliases"][alias]["name"] or
                    seq.startswith(library["aliases"][alias]["name"] + "_")):
911
                alias_of = marker
jhoogenboom's avatar
jhoogenboom committed
912
913
914
915
916
917
918
                marker = alias
                seq = "".join([
                    "0_",
                    library["aliases"][alias]["sequence"] + "[1]",
                    seq[len(library["aliases"][alias]["name"]):]])
                break

919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
    nameformat = None
    if PAT_SEQ_ALLELENAME_MT.match(seq) is not None:
        nameformat = "MtDNA"
    elif PAT_SEQ_ALLELENAME_SNP.match(seq) is not None:
        nameformat = "SNP"
    if nameformat is not None:
        # MtDNA and SNP markers.
        try:
            reference = library["nostr_reference"][marker]
        except KeyError:
            raise ValueError(
                "%s allele '%s' found for marker %s, but "
                "no reference sequence was found in the library" %
                (nameformat, seq, marker))
        if seq == "REF":
            return reference + "(1)"
        return mutate_sequence(reference, seq.split(),
            library["genome_position"].get(marker,
                ("M" if nameformat == "MtDNA" else "", 1))) + "(1)"

    # Note: aliases of mtDNA and SNP markers end up here as well.
    # It should NOT look like an alias now, however.
    match = PAT_SEQ_ALLELENAME_STR.match(seq)
942
943
944
    if match is None or match.group(1) is not None:
        raise ValueError("Invalid allele name '%s' encountered!" % seq)

jhoogenboom's avatar
jhoogenboom committed
945
946
947
    allele = seq.split("_")

    # Get and mutate prefix and suffix.
948
949
950
951
952
953
954
955
956
957
958
959
    prefix = ""
    suffix = ""
    if "prefix" in library:
        if marker in library["prefix"]:
            prefix = library["prefix"][marker][0]
        elif alias_of is not None and alias_of in library["prefix"]:
            prefix = library["prefix"][alias_of][0]
    if "suffix" in library:
        if marker in library["suffix"]:
            suffix = library["suffix"][marker][0]
        elif alias_of is not None and alias_of in library["suffix"]:
            suffix = library["suffix"][alias_of][0]
jhoogenboom's avatar
jhoogenboom committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    variants = [[], []]
    for variant in allele[2:]:
        if variant[0] == "-":
            if not prefix:
                raise ValueError("Encountered prefix variant '%s', but marker "
                                 "'%s' has no prefix!" % (variant, marker))
            variants[0].append(variant)
        elif variant[0] == "+":
            if not suffix:
                raise ValueError("Encountered suffix variant '%s', but marker "
                                 "'%s' has no suffix!" % (variant, marker))
            variants[1].append(variant)
        else:
            raise ValueError("Unrecognised variant '%s'" % variant)
    if variants[0]:
        prefix = mutate_sequence(prefix, variants[0])
    if variants[1]:
        suffix = mutate_sequence(suffix, variants[1])

    blocks = []
    if prefix:
        blocks.append((prefix, 1))
    for block in PAT_ALLELENAME_BLOCK.findall(allele[1]):
        blocks.append((block[0], int(block[1])))
    if suffix:
        blocks.append((suffix, 1))
jhoogenboom's avatar
jhoogenboom committed
986
    return "".join("%s(%i)" % block for block in blocks)
jhoogenboom's avatar
jhoogenboom committed
987
988
989
990
991
992
#convert_sequence_allelename_tssv


def convert_sequence_raw_allelename(seq, library, marker):
    # We actually convert raw->allelename via TSSV format.
    seq, alias = convert_sequence_raw_tssv(seq, library, marker, True)
993
994
    blocks = PAT_TSSV_BLOCK.findall(seq)

995
    if "nostr_reference" in library and marker in library["nostr_reference"]:
996
997
998
        # Handle non-STR markers here.
        if alias != marker:
            return library["aliases"][alias]["name"]
999
1000
1001
        if not blocks:
            # Oh dear, empty sequence... Primer dimer?
            blocks = (("",),)
1002
1003
1004
1005
1006
1007
        if library["nostr_reference"][marker] == blocks[0][0]:
            return "REF"
        return " ".join(
            call_variants(library["nostr_reference"][marker], blocks[0][0],
                library["genome_position"].get(marker, "suffix")))

1008
1009
1010
    # Find prefix and suffix.
    prefix = suffix = this_prefix = this_suffix = ""
    remaining_blocks = len(blocks)
1011
1012
1013
1014
1015
    if "prefix" in library:
        if alias in library["prefix"]:
            prefix = library["prefix"][alias][0]
        elif marker in library["prefix"]:
            prefix = library["prefix"][marker][0]
jhoogenboom's avatar
jhoogenboom committed
1016
        if prefix and remaining_blocks > 0 and blocks[0][1] == "1":
1017
            remaining_blocks -= 1
1018
1019
1020
1021
1022
    if "suffix" in library:
        if alias in library["suffix"]:
            suffix = library["suffix"][alias][0]
        elif marker in library["suffix"]:
            suffix = library["suffix"][marker][0]
jhoogenboom's avatar
jhoogenboom committed
1023
        if suffix and remaining_blocks > 0 and blocks[-1][1] == "1":
1024
            remaining_blocks -= 1
1025
1026
1027
1028
1029
1030
    if remaining_blocks > 0 and prefix and blocks[0][1] == "1":
        this_prefix = blocks[0][0]
        blocks = blocks[1:]
    if remaining_blocks > 0 and suffix and blocks[-1][1] == "1":
        this_suffix = blocks[-1][0]
        blocks = blocks[:-1]
jhoogenboom's avatar
jhoogenboom committed
1031
1032
1033
1034

    # Generate prefix/suffix variants.
    length = 0
    variants = []
1035
    if prefix != this_prefix:
1036
        variants += call_variants(prefix, this_prefix, "prefix")
1037
1038
        length += len(this_prefix) - len(prefix)
    if suffix != this_suffix:
1039
        variants += call_variants(suffix, this_suffix, "suffix")
1040
        length += len(this_suffix) - len(suffix)
jhoogenboom's avatar
jhoogenboom committed
1041
1042
1043

    # We are ready to return the allele name of aliases.
    if alias != marker:
1044
        return "_".join([library["aliases"][alias]["name"]] + variants)
jhoogenboom's avatar
jhoogenboom committed
1045
1046
1047

    # Compute CE allele number for the other alleles.
    # TODO: perhaps produce a more intelligent name if there is exactly
1048
1049
    #       1 alias with the same length, or only 1 alias sequence is
    #       contained somewhere within the allele.
jhoogenboom's avatar
jhoogenboom committed
1050
    blocknames = []
1051
1052
    blocksize = library.get("block_length", {}).get(marker, 4)
    length -= library.get("length_adjust", {}).get(marker, 0)
jhoogenboom's avatar
jhoogenboom committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
    for block in blocks:
        blocknames.append("%s[%s]" % (block[0], block[1]))
        length += len(block[0]) * int(block[1])

    allelename = "CE" + str(length / blocksize)
    if length % blocksize:
        allelename += "." + str(length % blocksize)
    return "_".join([allelename, "".join(blocknames)] + variants)
#convert_sequence_raw_allelename


def ensure_sequence_format(seq, to_format, from_format=None, library=None,
1065
                           marker=None):
jhoogenboom's avatar
jhoogenboom committed
1066
    """Convert seq to 'raw', 'tssv', or 'allelename' format."""
1067
    if seq in SEQ_SPECIAL_VALUES:
1068
        # Special case.
1069
        return seq
jhoogenboom's avatar
jhoogenboom committed
1070
    known_formats = ("raw", "tssv", "allelename")
jhoogenboom's avatar
jhoogenboom committed
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
    if to_format not in known_formats:
        raise ValueError("Unknown format '%s', choose from %s" %
                         (to_format, known_formats))
    if from_format is None:
        from_format = detect_sequence_format(seq) if seq else "raw"
    elif from_format not in known_formats:
        raise ValueError("Unknown format '%s', choose from %s" %
                         (from_format, known_formats))

    # No conversion needed?
    if to_format == from_format:
        return seq

    # From TSSV to raw sequence is easy.
    # We'll need a library and marker name for anything else.
    if (library is None or marker is None) and (from_format != "tssv" or
            to_format != "raw"):
        raise ValueError("Sequence needs to be converted from %s to %s, this "
                          "conversion requires a library file" %
                          (from_format, to_format))

    # Perform conversions.
    if from_format == "allelename":
        seq = convert_sequence_allelename_tssv(seq, library, marker)
    if to_format == "tssv":
        if from_format == "raw":
            return convert_sequence_raw_tssv(seq, library, marker)
        return seq
    if from_format != "raw":
        seq = convert_sequence_tssv_raw(seq)
    if to_format == "raw":
        return seq
    return convert_sequence_raw_allelename(seq, library, marker)
#ensure_sequence_format


jhoogenboom's avatar
jhoogenboom committed
1107
1108
def reverse_complement(sequence):
    """Return the reverse complement of the given DNA sequence."""
jhoogenboom's avatar
jhoogenboom committed
1109
    return "".join(COMPL[x] if x in COMPL else x for x in reversed(sequence))
jhoogenboom's avatar
jhoogenboom committed
1110
1111
1112
#reverse_complement


jhoogenboom's avatar
jhoogenboom committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def nnls(A, C, B=None, max_iter=200, min_change=0.0001, debug=False):
    """
    Solve for B in A * B = C in the least squares sense, s.t. B >= 0.

    Hint: call nnls(B.T, C.T).T to solve for A.

    Algorithm has converged if the sum of squared error has decreased
    by less than a factor of min_change in one iteration.  If debug is
    True, print the sum of squared error to sys.stdout after each
    iteration.

    This code was partially adopted from nimfa.methods.factorization.bd.
    """
    import numpy as np
    if B is None:
        B = np.matrix(np.zeros([A.shape[1], C.shape[1]]))
    E = A.T * A
    F = A.T * C
    prev_score = cur_score = sys.float_info.max
    for i in range(max_iter):
        for n in range(B.shape[0]):
            nn = list(range(n)) + list(range(n + 1, B.shape[0]))
            tmp = (F[n, :] - E[n, nn] * B[nn, :]) / E[n, n]
            tmp[np.isnan(tmp)] = 0
            tmp[tmp < 0] = 0
            B[n, :] = tmp
        prev_score = cur_score
        cur_score = np.square(C - A * B).sum()
        score_change = (prev_score-cur_score)/prev_score

        if debug:
            if i:
                print("%4i %15.6f %15.6f %6.2f" % (i, cur_score,
                    prev_score-cur_score, 100*score_change))
            else:
                print("%4i %15.6f" % (i, cur_score))

        if not cur_score or score_change < min_change:
            # We have converged.
            break

    return B
#nnls


jhoogenboom's avatar
jhoogenboom committed
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
def adjust_stats(value, stats=None):
    """
    Adjust the given stats in place with the given observed value and
    return the adjusted stats as well.  If no stats dict is given,
    create a new stats dict with the following initial values:
    {"n": 1, "min": value, "max": value, "mean": value, "m2": 0.0,
     "variance": 0.0}
    """
    value += 0.0
    if not stats:
        return {"n": 1, "min": value, "max": value, "mean": value, "m2": 0.0,
                "variance": 0.0}
    stats["n"] += 1
    delta = value - stats["mean"]
    stats["mean"] += delta / stats["n"]
    stats["m2"] += delta * (value - stats["mean"])
    try:
        stats["variance"] = stats["m2"] / (stats["n"] - 1)
        stats["min"] = min(stats["min"], value)
        stats["max"] = max(stats["max"], value)
    except ZeroDivisionError:
        stats["variance"] = 0
        stats["min"] = value
        stats["max"] = value
    return stats
#adjust_stats


jhoogenboom's avatar
jhoogenboom committed
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
def get_repeat_pattern(seq):
    """Return compiled regular expression that finds repeats of seq."""
    return re.compile("".join(             # For AGAT, one obtains:
        ["(?:" * (len(seq)-1)] +           # (?:(?:(?:
        ["%s)?" % x for x in seq[1:]] +    # G)?A)?T)?
        ["(?:", seq, ")+"] +               # (?AGAT)+
        ["(?:%s" % x for x in seq[:-1]] +  # (?:A(?:G(?:A
        [")?" * (len(seq)-1)]))            # )?)?)?
#get_repeat_pattern


1197
def read_sample_data_file(infile, data, annotation_column=None, seqformat=None,
1198
                          library=None, default_marker=None,
1199
                          drop_special_seq=False, after_correction=False):
1200
    """Add data from infile to data dict as [marker, sequence]=reads."""
1201
1202
    # Get column numbers.
    column_names = infile.readline().rstrip("\r\n").split("\t")
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
    colid_sequence = get_column_ids(column_names, "sequence")
    colid_forward = None
    colid_reverse = None
    if after_correction:
        colid_forward, colid_reverse = get_column_ids(column_names,
            "forward_corrected", "reverse_corrected",
            optional=(after_correction != "require"))
    if colid_forward is None:
        colid_forward = get_column_ids(column_names, "forward")
    if colid_reverse is None:
        colid_reverse = get_column_ids(column_names, "reverse")
1214
1215

    # Get marker name column if it exists.
1216
    colid_marker = get_column_ids(column_names, "marker", optional=True)
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227

    # Also try to get annotation column if we have one.
    if annotation_column is not None:
        try:
            colid_annotation = get_column_ids(column_names, annotation_column)
        except:
            annotation_column = None

    found_alleles = []
    for line in infile:
        line = line.rstrip("\r\n").split("\t")
1228
1229
        if drop_special_seq and line[colid_sequence] in SEQ_SPECIAL_VALUES:
            continue
1230
1231
1232
1233
        marker = line[colid_marker] if colid_marker is not None \
            else default_marker
        sequence = line[colid_sequence] if seqformat is None \
            else ensure_sequence_format(line[colid_sequence], seqformat,
1234
                                        library=library, marker=marker)
1235
1236
        if (annotation_column is not None and
                line[colid_annotation].startswith("ALLELE")):
1237
1238
            found_alleles.append((marker, sequence))
        data[marker, sequence] = map(int,
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
            (line[colid_forward], line[colid_reverse]))

    return found_alleles
#read_sample_data_file


def reduce_read_counts(data, limit_reads):
    sum_reads = 0
    for markerallele in data:
        sum_reads += sum(data[markerallele])
    if sum_reads <= limit_reads:
        return

    remove = sorted(random.sample(xrange(sum_reads), sum_reads - limit_reads))
1253
    removed = 0
1254
1255
1256
1257
    seen = 0
    for markerallele in data:
        for direction in (0, 1):
            seen += data[markerallele][direction]
1258
            while removed < len(remove) and seen > remove[removed]:
1259
                data[markerallele][direction] -= 1
1260
                removed += 1
1261
1262
1263
1264
1265
1266
#reduce_read_counts


def get_sample_data(tags_to_files, callback, allelelist=None,
                    annotation_column=None, seqformat=None, library=None,
                    marker=None, homozygotes=False, limit_reads=sys.maxint,
1267
1268
                    drop_samples=0, drop_special_seq=False,
                    after_correction=False):
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
    if drop_samples:
        sample_tags = tags_to_files.keys()
        for tag in random.sample(xrange(len(sample_tags)),
                                 int(len(sample_tags) * drop_samples)):
            del tags_to_files[sample_tags[tag]]

    for tag in tags_to_files:
        data = {}
        alleles = set()
        for infile in tags_to_files[tag]:
1279
            infile = sys.stdin if infile == "-" else open(infile, "r")
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
1280
1281
            alleles.update(read_sample_data_file(
                infile, data, annotation_column, seqformat, library, marker,
1282
                drop_special_seq, after_correction))
1283
1284
            if infile != sys.stdin:
                infile.close()
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
        if limit_reads < sys.maxint:
            reduce_read_counts(data, limit_reads)
        if allelelist is not None:
            if tag not in allelelist:
                allelelist[tag] = {}
            for markerx, allele in alleles:
                if markerx not in allelelist[tag]:
                    allelelist[tag][markerx] = set()
                allelelist[tag][markerx].add(allele)
            if marker:
                if marker in allelelist[tag]:
                    allelelist[tag] = {marker: allelelist[tag][marker]}
                else:
                    allelelist[tag] = {}
            if homozygotes:
jhoogenboom's avatar
jhoogenboom committed
1300
1301
1302
                for markerx in allelelist[tag].keys():
                    if len(allelelist[tag][markerx]) > 1:
                        del allelelist[tag][markerx]
1303
1304
1305
1306
        callback(tag, data)
#get_sample_data


Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
1307
def get_column_ids(column_names, *names, **optional):
jhoogenboom's avatar
jhoogenboom committed
1308
1309
1310
1311
1312
1313
    """Find all names in column_names and return their indices."""
    result = []
    for name in names:
        try:
            result.append(column_names.index(name))
        except ValueError:
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
1314
1315
1316
1317
            if "optional" in optional and optional["optional"]:
                result.append(None)
            else:
                raise ValueError("Column not found in input file: %s" % name)
jhoogenboom's avatar
jhoogenboom committed
1318
1319
1320
1321
1322
1323
    if len(result) == 1:
        return result[0]
    return tuple(result)
#get_column_ids


jhoogenboom's avatar
jhoogenboom committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
def parse_allelelist(allelelist, convert=None, library=None):
    """Read allele list from open file handle."""
    column_names = allelelist.readline().rstrip("\r\n").split("\t")
    colid_sample, colid_marker, colid_allele = get_column_ids(column_names,
        "sample", "marker", "allele")
    alleles = {}
    for line in allelelist:
        line = line.rstrip("\r\n").split("\t")
        sample = line[colid_sample]
        marker = line[colid_marker]
        allele = line[colid_allele]
        if convert is not None:
            allele = ensure_sequence_format(allele, convert, library=library,
                                            marker=marker)
        if sample not in alleles:
            alleles[sample] = {}
        if marker not in alleles[sample]:
            alleles[sample][marker] = set()
        alleles[sample][marker].add(allele)
    return alleles
#parse_allelelist


jhoogenboom's avatar
jhoogenboom committed
1347
1348
1349
1350
1351
1352
1353
1354
1355
def pos_int_arg(value):
    """Convert str to int, raise ArgumentTypeError if not positive."""
    if not value.isdigit() or not int(value):
        raise argparse.ArgumentTypeError(
            "invalid positive int value: '%s'" % value)
    return int(value)
#pos_int_arg


1356
1357
1358
1359
1360
1361
1362
1363
1364
def regex_arg(value):
    """Compile value into a regular expression."""
    try:
        return re.compile(value)
    except re.error as err:
        raise argparse.ArgumentTypeError(err)
#regex_arg


jhoogenboom's avatar
jhoogenboom committed
1365
def add_allele_detection_args(parser):
jhoogenboom's avatar
jhoogenboom committed
1366
1367
    group = parser.add_argument_group("allele detection options")
    group.add_argument('-a', '--allelelist', metavar="ALLELEFILE",
jhoogenboom's avatar
jhoogenboom committed
1368
        type=argparse.FileType('r'),
jhoogenboom's avatar
jhoogenboom committed
1369
1370
1371
        help="file containing a list of the true alleles of each sample "
             "(e.g., obtained from allelefinder)")
    group.add_argument('-c', '--annotation-column', metavar="COLNAME",
jhoogenboom's avatar
jhoogenboom committed
1372
1373
1374
1375
1376
        help="name of a column in the sample files, which contains a value "
             "beginning with 'ALLELE' for the true alleles of the sample")
#add_allele_detection_args


1377
1378
def add_random_subsampling_args(parser):
    group = parser.add_argument_group("random subsampling options (advanced)")
jhoogenboom's avatar
jhoogenboom committed
1379
    group.add_argument('-Q', '--limit-reads', metavar="N", type=pos_int_arg,
1380
1381
1382
1383
1384
1385
        default=sys.maxint,
        help="simulate lower sequencing depth by randomly dropping reads down "
             "to this maximum total number of reads for each sample")
    group.add_argument('-x', '--drop-samples', metavar="N", type=float,
        default=0, help="randomly drop this fraction of input samples")
#add_random_subsampling_args
jhoogenboom's avatar
jhoogenboom committed
1386
1387


1388
1389
def add_sequence_format_args(parser, default_format=None, force=False,