-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.py
493 lines (417 loc) 路 14.4 KB
/
files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
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
151
152
153
154
155
156
157
158
159
160
161
162
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
__author__ = "Vini Salazar"
__license__ = "MIT"
__maintainer__ = "Vini Salazar"
__url__ = "https://github.com/vinisalazar/bioprov"
__version__ = "0.1.18a"
"""
Contains the File and SeqFile classes and related functions.
"""
import numpy as np
from dataclasses import dataclass
from pathlib import Path
from Bio import SeqIO, AlignIO
from bioprov.utils import (
get_size,
Warnings,
serializer_filter,
serializer,
file_to_sha1,
pattern_replacer,
)
class File:
"""
Class for holding files and file information.
"""
def __init__(self, path, tag=None, attributes=None, _get_hash=True):
"""
:param path: A UNIX-like file _path.
:param tag: optional tag describing the file.
:param attributes: Miscellaneous attributes.
"""
self.path = Path(path).absolute()
assert (
not self.path.is_dir()
), f"The path must be to a file, not a directory, you passed:\n'{path}'"
self.name = self.path.stem
self.basename = self.path.name
self.directory = self.path.parent
self.extension = self.path.suffix
if tag is None:
tag = self.name
if attributes is None:
attributes = {}
self.tag = tag
self.attributes = attributes
self._exists = self.path.exists()
self.size = get_size(self.path)
self.raw_size = get_size(self.path, convert=False)
self._sha1 = file_to_sha1(self.path)
# Provenance attributes
self._entity = None
def __repr__(self):
return str(self.path)
def __str__(self):
return self.__repr__()
@property
def sha1(self):
self._sha1 = file_to_sha1(self.path)
return self._sha1
@sha1.setter
def sha1(self, value):
self._sha1 = value # no cover
@property
def exists(self):
self._exists = self.path.exists()
return self._exists
@exists.setter
def exists(self, value):
self._exists = value # no cover
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self._size = value
@property
def entity(self):
return self._entity
@entity.setter
def entity(self, value):
self._entity = value
def replace_path(self, old_terms, new, warnings=False):
"""
Replace the current File path.
Usually used for switching between users.
:param old_terms: Terms to be replaced in the path.
:param new: New term.
:param warnings: Whether to warn if sha1 checksum differs or file does not exist.
:return: Updates self.
"""
old_hash, old_exists = self._sha1, self._exists
self.path = Path(pattern_replacer(str(self.path), old_terms, new))
# TODO: replace these print statements for logger warning/debug level
if warnings:
if not self.exists and old_exists:
print(
f"Warning: file {self.path} was marked as existing but was not found."
)
if old_hash and self.sha1 != old_hash and self.exists: # no cover
print(
f"Warning: file {self.path} previous sha1 checksum differs from the current."
)
def serializer(self):
return serializer(self)
class Directory:
"""
Class for holding information about directories.
"""
def __init__(self, path, tag=None):
self.path = Path(path).absolute()
self.name = self.path.stem
self.basename = self.path.name
if tag is None:
tag = self.name
self.tag = tag
self._exists = self.path.exists()
# Provenance attributes
self._entity = None
def replace_path(self, old_terms, new, warnings=False):
"""
Replace the current File path.
Usually used for switching between users.
:param old_terms: Terms to be replaced in the path.
:param new: New term.
:param warnings: Whether to warn if sha1 checksum differs or file does not exist.
:return: Updates self.
"""
old_exists = self._exists
self.path = Path(pattern_replacer(str(self.path), old_terms, new))
# TODO: replace these print statements for logger warning/debug level
if warnings:
if not self.exists and old_exists:
print(
f"Warning: file {self.path} was marked as existing but was not found."
)
def __repr__(self):
return str(self.path)
def __str__(self):
return self.__repr__()
@property
def exists(self):
self._exists = self.path.exists()
return self._exists
@exists.setter
def exists(self, value):
self._exists = value # no cover
def serializer(self):
return serializer(self)
def get_subdirs(self):
return [i for i in self.path.iterdir() if i.is_dir()]
def get_files(self):
return [i for i in self.path.iterdir() if i.is_file()]
def add_files_to_object(self, object_, kind="files"):
"""
Add files or subdirs in self to object_, can be either a Sample or Project.
:param object_: bioprov.Project or bioprov.Sample
:param kind: Whether to add files or subdirectories.
:return: Updates object_.files
"""
choices = ("file", "dir", "subdir", "f", "d")
kind = kind.lower()
if kind.endswith("s"):
kind = kind[:-1] # chop the 's' off
assert kind in choices, Warnings()["choices"](kind, choices, "kind")
if kind in ("f", "file"):
files = [File(i) for i in self.get_files()]
object_.add_files(files)
elif kind in ("dir", "subdir", "d"):
dirs = [Directory(i) for i in self.get_subdirs()]
object_.add_files(dirs)
else:
raise Exception(
"Could not add Directory content to object."
"Please specify a valid kind."
)
class SeqFile(File):
"""
Class for holding sequence file and sequence information. Inherits from File.
This class support records parsed with the BioPython.SeqIO module.
"""
seqfile_formats = (
"fasta",
"clustal",
"fastq",
"fastq-sanger",
"fastq-solexa",
"fastq-illumina",
"genbank",
"gb",
"nexus",
"stockholm",
"swiss",
"tab",
"qual",
)
def __init__(
self,
path,
tag=None,
format="fasta",
parser="seq",
document=None,
import_records=False,
calculate_seqstats=False,
):
"""
:param path: A UNIX-like file _path.
:param tag: optional tag describing the file.
:param format: Format to be parsed by SeqIO.parse()
:param parser: Bio parser to be used. Can be 'seq' (default) to be parsed by SeqIO or 'align'
to be parsed with AlignIO.
:param document: prov.model.ProvDocument.
:param import_records: Whether to import sequence data as Bio objects
:param calculate_seqstats: Whether to calculate SeqStats
"""
format_l = format.lower()
assert format in SeqFile.seqfile_formats, Warnings()["choices"](
format, SeqFile.seqfile_formats, "format"
)
super().__init__(path, tag, document)
self.format = format_l
self.records = None
self._generator = None
self._seqstats = None
self._parser = parser
self.number_seqs: int
self.total_bps: int
self.mean_bp: float
self.min_bp: int
self.max_bp: int
self.N50: int
self.GC: float
if self.exists:
self._seqrecordgenerator()
else:
import_records = False
calculate_seqstats = False
if import_records:
self.import_records()
calculate_seqstats = True
if calculate_seqstats:
self._seqstats = self._calculate_seqstats(self.records)
def _seqrecordgenerator(self):
"""
Runs _seqrecordgenerator with the format.
"""
self._generator = seqrecordgenerator(
self.path, format=self.format, parser=self._parser
)
@property
def generator(self):
if self._generator is None:
self._seqrecordgenerator()
return self._generator
@generator.setter
def generator(self, value):
self._generator = value
@property
def seqstats(self):
if self._seqstats is None:
self._seqstats = self._calculate_seqstats()
return self._seqstats
@seqstats.setter
def seqstats(self, value):
self._seqstats = value
def import_records(self):
assert self.exists, "Cannot import, file does not exist."
self.records = SeqIO.to_dict(self._generator)
def serializer(self):
keys = ("records",)
return serializer_filter(self, keys)
def _calculate_seqstats(
self,
calculate_gc=True,
megabases=False,
percentage=False,
decimals=5,
):
"""
:param calculate_gc: Whether to calculate GC content. Disabled if amino acid file.
:param megabases: Whether to convert number of sequences to megabases.
:param percentage: Whether to convert GC content to percentage (value * 100)
:param decimals: Number of decimals to round.
:return: SeqStats instance.
"""
assert isinstance(self.records, dict), Warnings()["incorrect_type"](
self.records, dict
)
bp_array, GC = [], 0
aminoacids = "LMFWKQESPVIYHRND"
# We use enumerate to check the first item for amino acids.
for ix, (key, SeqRecord) in enumerate(self.records.items()):
if ix == 0:
seq = str(SeqRecord.seq)
if any(i in aminoacids for i in seq):
calculate_gc = False # no cover
# Add length of sequences (number of base pairs)
bp_array.append(len(SeqRecord.seq))
# Only count if there are no aminoacids.
if calculate_gc:
GC += SeqRecord.seq.upper().count("G")
GC += SeqRecord.seq.upper().count("C")
# Convert to array
bp_array = np.array(bp_array)
number_seqs = len(bp_array)
total_bps = bp_array.sum()
mean_bp = round(bp_array.mean(), decimals)
N50 = calculate_N50(bp_array)
min_bp = bp_array.min()
max_bp = bp_array.max()
if calculate_gc:
GC = round(GC / total_bps, decimals)
if percentage:
GC *= 100
else:
GC = np.nan
if megabases:
total_bps /= 10e5
self._seqstats = SeqStats(
number_seqs, total_bps, mean_bp, min_bp, max_bp, N50, GC
)
for k, value in self._seqstats.__dict__.items():
setattr(self, k, value)
return self._seqstats
@dataclass
class SeqStats:
"""
Dataclass to describe sequence statistics.
"""
number_seqs: int
total_bps: int
mean_bp: float
min_bp: int
max_bp: int
N50: int
GC: float
def calculate_N50(array):
"""
Calculate N50 from an array of contig lengths.
https://github.com/vikas0633/python/blob/master/N50.py
Based on the Broad Institute definition:
https://www.broad.harvard.edu/crd/wiki/index.php/N50
:param array: list of contig lengths
:return: N50 value
"""
array.sort()
new_array = []
for x in array:
new_array += [x] * x
if len(new_array) % 2 == 0:
ix = int(len(new_array) / 2)
return (new_array[ix] + new_array[ix - 1]) / 2
else:
ix = int((len(new_array) / 2) - 0.5)
return new_array[ix]
def seqrecordgenerator(path, format, parser="seq", warnings=False):
"""
:param path: Path to file.
:param format: format to pass to SeqIO.parse().
:param parser: Whether to import records with SeqIO (default) or AlignIO
:param warnings: Whether to warn if sha1 checksum differs or file does not exist.
:return: A generator of SeqRecords.
"""
parser_l = parser.lower()
available_parsers = ("seq", "align")
assert parser in available_parsers, Warnings()["choices"](
parser, available_parsers, "parser"
)
kind_dict = {
"seq": lambda _path, _format: SeqIO.parse(path, format=format),
"align": lambda _path, _format: AlignIO.parse(path, format=format),
}
try:
records = kind_dict[parser_l](path, format)
return records
except FileNotFoundError:
if warnings:
print(Warnings()["not_exist"](path))
print(
"The file was loaded as a BioProv object, but it does not exist on the specified path."
)
return None
def deserialize_files_dict(files_dict):
"""
Deserialize a dictionary of files in JSON format.
:param files_dict: dict of dicts.
:return: dict of File instances.
"""
for tag, file in files_dict.items():
if file is not None:
if "format" in file.keys():
if file["format"] in SeqFile.seqfile_formats:
# TODO: don't import records again (slow)
# Get them straight from the JSON file.
files_dict[tag] = SeqFile(
path=file["path"],
tag=file["tag"],
)
_ = files_dict[tag].generator
for seqstats_attr_ in SeqStats.__dataclass_fields__.keys():
if seqstats_attr_ in file.keys():
setattr(
files_dict[tag],
seqstats_attr_,
file[seqstats_attr_],
)
else:
if file["path"].endswith("/"):
files_dict[tag] = Directory(file["path"], tag=file["tag"])
else:
files_dict[tag] = File(file["path"], tag=file["tag"])
for attr_, value_ in file.items():
if attr_ not in ("path",):
try:
setattr(files_dict[tag], attr_, value_)
except AttributeError:
pass
return files_dict