comparison phage_annotation_table.py @ 1:32e011fa615c draft

planemo upload commit edc74553919d09dcbe27fcadf144612c1ad3a2a2
author cpt
date Wed, 26 Apr 2023 03:42:32 +0000
parents
children
comparison
equal deleted inserted replaced
0:6a4d1bd8ac1d 1:32e011fa615c
1 #!/usr/bin/env python
2 # vim: set fileencoding=utf-8
3 import os
4 import argparse
5 from gff3 import (
6 genes,
7 get_gff3_id,
8 get_rbs_from,
9 feature_test_true,
10 feature_lambda,
11 feature_test_type,
12 )
13 from CPT_GFFParser import gffParse, gffWrite
14 from Bio import SeqIO
15 from jinja2 import Environment, FileSystemLoader
16 import logging
17 from math import floor
18
19 logging.basicConfig(level=logging.DEBUG)
20 log = logging.getLogger(name="pat")
21
22 # Path to script, required because of Galaxy.
23 SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
24 # Path to the HTML template for the report
25
26
27 def genes_all(feature_list, feature_type=["gene"], sort=False):
28 """
29 Simple filter to extract gene features from the feature set.
30 """
31
32 if not sort:
33 for x in feature_lambda(
34 feature_list, feature_test_type, {"types": feature_type}, subfeatures=True
35 ):
36 yield x
37 else:
38 data = list(genes_all(feature_list, feature_type, sort=False))
39 data = sorted(data, key=lambda feature: feature.location.start)
40 for x in data:
41 yield x
42
43
44 def checkSubs(feature, qualName):
45 subFeats = []
46 res = ""
47 subFeats = feature.sub_features
48 while len(subFeats) > 0:
49 for feat in subFeats:
50 for i in feat.qualifiers.keys():
51 for j in qualName:
52 if i == j:
53 if res == "":
54 res = feat.qualifiers[i][0]
55 else:
56 res += "; " + feat.qualifiers[i][0]
57 if res != "":
58 return res
59 tempFeats = []
60 for feat in subFeats: # Should be breadth-first results
61 for x in feat.sub_features:
62 tempFeats.append(x)
63 subFeats = tempFeats
64 return res
65
66
67 def annotation_table_report(record, types, wanted_cols, gaf_data, searchSubs):
68 getTypes = []
69 for x in [y.strip() for y in types.split(",")]:
70 getTypes.append(x)
71 getTypes.append("gene")
72 sorted_features = list(genes_all(record.features, getTypes, sort=True))
73 if wanted_cols is None or len(wanted_cols.strip()) == 0:
74 return [], []
75 useSubs = searchSubs
76
77 def rid(record, feature):
78 """Organism ID"""
79 return record.id
80
81 def id(record, feature):
82 """ID"""
83 return feature.id
84
85 def featureType(record, feature):
86 """Type"""
87 return feature.type
88
89 def name(record, feature):
90 """Name"""
91 for x in ["Name", "name"]:
92 for y in feature.qualifiers.keys():
93 if x == y:
94 return feature.qualifiers[x][0]
95 if useSubs:
96 res = checkSubs(feature, ["Name", "name"])
97 if res != "":
98 return res
99 return "None"
100
101 def start(record, feature):
102 """Boundary"""
103 return str(feature.location.start + 1)
104
105 def end(record, feature):
106 """Boundary"""
107 return str(feature.location.end)
108
109 def location(record, feature):
110 """Location"""
111 return str(feature.location.start + 1) + "..{0.end}".format(feature.location)
112
113 def length(record, feature):
114 """CDS Length (AA)"""
115
116 if feature.type == "CDS":
117 cdss = [feature]
118 else:
119 cdss = list(genes(feature.sub_features, feature_type="CDS", sort=True))
120
121 if cdss == []:
122 return "None"
123 res = (sum([len(cds) for cds in cdss]) / 3) - 1
124 if floor(res) == res:
125 res = int(res)
126 return str(res)
127
128 def notes(record, feature):
129 """User entered Notes"""
130 for x in ["Note", "note", "Notes", "notes"]:
131 for y in feature.qualifiers.keys():
132 if x == y:
133 return feature.qualifiers[x][0]
134 if useSubs:
135 res = checkSubs(feature, ["Note", "note", "Notes", "notes"])
136 if res != "":
137 return res
138 return "None"
139
140 def date_created(record, feature):
141 """Created"""
142 return feature.qualifiers.get("date_creation", ["None"])[0]
143
144 def date_last_modified(record, feature):
145 """Last Modified"""
146 res = feature.qualifiers.get("date_last_modified", ["None"])[0]
147 if res != "None":
148 return res
149 if useSubs:
150 res = checkSubs(feature, ["date_last_modified"])
151 if res != "":
152 return res
153 return "None"
154
155 def description(record, feature):
156 """Description"""
157 res = feature.qualifiers.get("description", ["None"])[0]
158 if res != "None":
159 return res
160 if useSubs:
161 res = checkSubs(feature, ["description"])
162 if res != "":
163 return res
164 return "None"
165
166 def owner(record, feature):
167 """Owner
168
169 User who created the feature. In a 464 scenario this may be one of
170 the TAs."""
171 for x in ["Owner", "owner"]:
172 for y in feature.qualifiers.keys():
173 if x == y:
174 return feature.qualifiers[x][0]
175 if useSubs:
176 res = checkSubs(feature, ["Owner", "owner"])
177 if res != "":
178 return res
179 return "None"
180
181 def product(record, feature):
182 """Product
183
184 User entered product qualifier (collects "Product" and "product"
185 entries)"""
186 """User entered Notes"""
187 for x in ["product", "Product"]:
188 for y in feature.qualifiers.keys():
189 if x == y:
190 return feature.qualifiers[x][0]
191 if useSubs:
192 res = checkSubs(feature, ["product", "Product"])
193 if res != "":
194 return res
195 return "None"
196
197 def note(record, feature):
198 """Note
199
200 User entered Note qualifier(s)"""
201 return feature.qualifiers.get("Note", [])
202
203 def strand(record, feature):
204 """Strand"""
205 return "+" if feature.location.strand > 0 else "-"
206
207 def sd_spacing(record, feature):
208 """Shine-Dalgarno spacing"""
209 rbss = get_rbs_from(gene)
210 if len(rbss) == 0:
211 return "None"
212 else:
213 resp = []
214 for rbs in rbss:
215 cdss = list(genes(feature.sub_features, feature_type="CDS", sort=True))
216 if len(cdss) == 0:
217 return "No CDS"
218 if rbs.location.strand > 0:
219 distance = min(
220 cdss, key=lambda x: x.location.start - rbs.location.end
221 )
222 distance_val = str(distance.location.start - rbs.location.end)
223 resp.append(distance_val)
224 else:
225 distance = min(
226 cdss, key=lambda x: x.location.end - rbs.location.start
227 )
228 distance_val = str(rbs.location.start - distance.location.end)
229 resp.append(distance_val)
230
231 if len(resp) == 1:
232 return str(resp[0])
233 return resp
234
235 def sd_seq(record, feature):
236 """Shine-Dalgarno sequence"""
237 rbss = get_rbs_from(gene)
238 if len(rbss) == 0:
239 return "None"
240 else:
241 resp = []
242 for rbs in rbss:
243 resp.append(str(rbs.extract(record).seq))
244 if len(resp) == 1:
245 return str(resp[0])
246 else:
247 return resp
248
249 def start_codon(record, feature):
250 """Start Codon"""
251 if feature.type == "CDS":
252 cdss = [feature]
253 else:
254 cdss = list(genes(feature.sub_features, feature_type="CDS", sort=True))
255
256 data = [x for x in cdss]
257 if len(data) == 1:
258 return str(data[0].extract(record).seq[0:3])
259 else:
260 return [
261 "{0} ({1.location.start}..{1.location.end}:{1.location.strand})".format(
262 x.extract(record).seq[0:3], x
263 )
264 for x in data
265 ]
266
267 def stop_codon(record, feature):
268 """Stop Codon"""
269 return str(feature.extract(record).seq[-3:])
270
271 def dbxrefs(record, feature):
272 """DBxrefs"""
273 """User entered Notes"""
274 for x in ["Dbxref", "db_xref", "DB_xref", "DBxref", "DB_Xref", "DBXref"]:
275 for y in feature.qualifiers.keys():
276 if x == y:
277 return feature.qualifiers[x][0]
278 return "None"
279
280 def upstream_feature(record, feature):
281 """Next gene upstream"""
282 if feature.strand > 0:
283 upstream_features = [
284 x
285 for x in sorted_features
286 if (
287 x.location.start < feature.location.start
288 and x.type == "gene"
289 and x.strand == feature.strand
290 )
291 ]
292 if len(upstream_features) > 0:
293 foundSelf = False
294 featCheck = upstream_features[-1].sub_features
295 for x in featCheck:
296 if x == feature:
297 foundSelf = True
298 break
299 featCheck = featCheck + x.sub_features
300 if foundSelf:
301 if len(upstream_features) > 1:
302 return upstream_features[-2]
303 return None
304 return upstream_features[-1]
305 else:
306 return None
307 else:
308 upstream_features = [
309 x
310 for x in sorted_features
311 if (
312 x.location.end > feature.location.end
313 and x.type == "gene"
314 and x.strand == feature.strand
315 )
316 ]
317
318 if len(upstream_features) > 0:
319 foundSelf = False
320 featCheck = upstream_features[0].sub_features
321 for x in featCheck:
322 if x == feature:
323 foundSelf = True
324 break
325 featCheck = featCheck + x.sub_features
326 if foundSelf:
327 if len(upstream_features) > 1:
328 return upstream_features[1]
329 return None
330 return upstream_features[0]
331 else:
332 return None
333
334 def upstream_feature__name(record, feature):
335 """Next gene upstream"""
336 up = upstream_feature(record, feature)
337 if up:
338 return str(up.id)
339 return "None"
340
341 def ig_dist(record, feature):
342 """Distance to next upstream gene on same strand"""
343 up = upstream_feature(record, feature)
344 if up:
345 dist = None
346 if feature.strand > 0:
347 dist = feature.location.start - up.location.end
348 else:
349 dist = up.location.start - feature.location.end
350 return str(dist)
351 else:
352 return "None"
353
354 def _main_gaf_func(record, feature, gaf_data, attr):
355 if feature.id in gaf_data:
356 return [x[attr] for x in gaf_data[feature.id]]
357 return []
358
359 def gaf_annotation_extension(record, feature, gaf_data):
360 """GAF Annotation Extension
361
362 Contains cross references to other ontologies that can be used
363 to qualify or enhance the annotation. The cross-reference is
364 prefaced by an appropriate GO relationship; references to
365 multiple ontologies can be entered. For example, if a gene
366 product is localized to the mitochondria of lymphocytes, the GO
367 ID (column 5) would be mitochondrion ; GO:0005439, and the
368 annotation extension column would contain a cross-reference to
369 the term lymphocyte from the Cell Type Ontology.
370 """
371 return _main_gaf_func(record, feature, gaf_data, "annotation_extension")
372
373 def gaf_aspect(record, feature, gaf_data):
374 """GAF Aspect code
375
376 E.g. P (biological process), F (molecular function) or C (cellular component)
377 """
378 return _main_gaf_func(record, feature, gaf_data, "aspect")
379
380 def gaf_assigned_by(record, feature, gaf_data):
381 """GAF Creating Organisation"""
382 return _main_gaf_func(record, feature, gaf_data, "assigned_by")
383
384 def gaf_date(record, feature, gaf_data):
385 """GAF Creation Date"""
386 return _main_gaf_func(record, feature, gaf_data, "date")
387
388 def gaf_db(record, feature, gaf_data):
389 """GAF DB"""
390 return _main_gaf_func(record, feature, gaf_data, "db")
391
392 def gaf_db_reference(record, feature, gaf_data):
393 """GAF DB Reference"""
394 return _main_gaf_func(record, feature, gaf_data, "db_reference")
395
396 def gaf_evidence_code(record, feature, gaf_data):
397 """GAF Evidence Code"""
398 return _main_gaf_func(record, feature, gaf_data, "evidence_code")
399
400 def gaf_go_id(record, feature, gaf_data):
401 """GAF GO ID"""
402 return _main_gaf_func(record, feature, gaf_data, "go_id")
403
404 def gaf_go_term(record, feature, gaf_data):
405 """GAF GO Term"""
406 return _main_gaf_func(record, feature, gaf_data, "go_term")
407
408 def gaf_id(record, feature, gaf_data):
409 """GAF ID"""
410 return _main_gaf_func(record, feature, gaf_data, "id")
411
412 def gaf_notes(record, feature, gaf_data):
413 """GAF Notes"""
414 return _main_gaf_func(record, feature, gaf_data, "notes")
415
416 def gaf_owner(record, feature, gaf_data):
417 """GAF Creator"""
418 return _main_gaf_func(record, feature, gaf_data, "owner")
419
420 def gaf_with_or_from(record, feature, gaf_data):
421 """GAF With/From"""
422 return _main_gaf_func(record, feature, gaf_data, "with_or_from")
423
424 cols = []
425 data = []
426 funcs = []
427 lcl = locals()
428 for x in [y.strip().lower() for y in wanted_cols.split(",")]:
429 if not x:
430 continue
431 if x == "type":
432 x = "featureType"
433 if x in lcl:
434 funcs.append(lcl[x])
435 # Keep track of docs
436 func_doc = lcl[x].__doc__.strip().split("\n\n")
437 # If there's a double newline, assume following text is the
438 # "help" and the first part is the "name". Generate empty help
439 # if not provided
440 if len(func_doc) == 1:
441 func_doc += [""]
442 cols.append(func_doc)
443 elif "__" in x:
444 chosen_funcs = [lcl[y] for y in x.split("__")]
445 func_doc = [
446 " of ".join(
447 [y.__doc__.strip().split("\n\n")[0] for y in chosen_funcs[::-1]]
448 )
449 ]
450 cols.append(func_doc)
451 funcs.append(chosen_funcs)
452
453 for gene in genes_all(record.features, getTypes, sort=True):
454 row = []
455 for func in funcs:
456 if isinstance(func, list):
457 # If we have a list of functions, repeatedly apply them
458 value = gene
459 for f in func:
460 if value is None:
461 value = "None"
462 break
463
464 value = f(record, value)
465 else:
466 # Otherwise just apply the lone function
467 if func.__name__.startswith("gaf_"):
468 value = func(record, gene, gaf_data)
469 else:
470 value = func(record, gene)
471
472 if isinstance(value, list):
473 collapsed_value = ", ".join(value)
474 value = [str(collapsed_value)] # .encode("unicode_escape")]
475 else:
476 value = str(value) # .encode("unicode_escape")
477
478 row.append(value)
479 # print row
480 data.append(row)
481 return data, cols
482
483
484 def parseGafData(file):
485 cols = []
486 data = {}
487 # '10d04a01-5ed8-49c8-b724-d6aa4df5a98d': {
488 # 'annotation_extension': '',
489 # 'aspect': '',
490 # 'assigned_by': 'CPT',
491 # 'date': '2017-05-04T16:25:22.161916Z',
492 # 'db': 'UniProtKB',
493 # 'db_reference': 'GO_REF:0000100',
494 # 'evidence_code': 'ISA',
495 # 'gene': '0d307196-833d-46e8-90e9-d80f7a041d88',
496 # 'go_id': 'GO:0039660',
497 # 'go_term': 'structural constituent of virion',
498 # 'id': '10d04a01-5ed8-49c8-b724-d6aa4df5a98d',
499 # 'notes': 'hit was putative minor structural protein',
500 # 'owner': 'amarc1@tamu.edu',
501 # 'with_or_from': 'UNIREF90:B2ZYZ7'
502 # },
503 for row in file:
504 if row.startswith("#"):
505 # Header
506 cols = (
507 row.strip().replace("# ", "").replace("GO Term", "go_term").split("\t")
508 )
509 else:
510 line = row.strip().split("\t")
511 tmp = dict(zip(cols, line))
512 if "gene" not in tmp.keys():
513 continue
514 if tmp["gene"] not in data:
515 data[tmp["gene"]] = []
516
517 data[tmp["gene"]].append(tmp)
518 return data
519
520
521 def evaluate_and_report(
522 annotations,
523 genome,
524 types="gene",
525 reportTemplateName="phage_annotation_validator.html",
526 annotationTableCols="",
527 gafData=None,
528 searchSubs=False,
529 ):
530 """
531 Generate our HTML evaluation of the genome
532 """
533 # Get features from GFF file
534 seq_dict = SeqIO.to_dict(SeqIO.parse(genome, "fasta"))
535 # Get the first GFF3 record
536 # TODO: support multiple GFF3 files.
537 at_table_data = []
538 gaf = {}
539 if gafData:
540 gaf = parseGafData(gafData)
541
542 for record in gffParse(annotations, base_dict=seq_dict):
543 if reportTemplateName.endswith(".html"):
544 record.id = record.id.replace(".", "-")
545 log.info("Producing an annotation table for %s" % record.id)
546 annotation_table_data, annotation_table_col_names = annotation_table_report(
547 record, types, annotationTableCols, gaf, searchSubs
548 )
549 at_table_data.append((record, annotation_table_data))
550 # break
551
552 # This is data that will go into our HTML template
553 kwargs = {
554 "annotation_table_data": at_table_data,
555 "annotation_table_col_names": annotation_table_col_names,
556 }
557
558 env = Environment(
559 loader=FileSystemLoader(SCRIPT_PATH), trim_blocks=True, lstrip_blocks=True
560 )
561 if reportTemplateName.endswith(".html"):
562 env.filters["nice_id"] = str(get_gff3_id).replace(".", "-")
563 else:
564 env.filters["nice_id"] = get_gff3_id
565
566 def join(listy):
567 return "\n".join(listy)
568
569 env.filters.update({"join": join})
570 tpl = env.get_template(reportTemplateName)
571 return tpl.render(**kwargs).encode("utf-8")
572
573
574 if __name__ == "__main__":
575 parser = argparse.ArgumentParser(
576 description="rebase gff3 features against parent locations", epilog=""
577 )
578 parser.add_argument(
579 "annotations", type=argparse.FileType("r"), help="Parent GFF3 annotations"
580 )
581 parser.add_argument("genome", type=argparse.FileType("r"), help="Genome Sequence")
582
583 parser.add_argument(
584 "--types",
585 help="Select extra types to display in output (Will always include gene)",
586 )
587
588 parser.add_argument(
589 "--reportTemplateName",
590 help="Report template file name",
591 default="phageqc_report_full.html",
592 )
593 parser.add_argument(
594 "--annotationTableCols",
595 help="Select columns to report in the annotation table output format",
596 )
597 parser.add_argument(
598 "--gafData", help="CPT GAF-like table", type=argparse.FileType("r")
599 )
600 parser.add_argument(
601 "--searchSubs",
602 help="Attempt to populate fields from sub-features if qualifier is empty",
603 action="store_true",
604 )
605
606 args = parser.parse_args()
607
608 print(evaluate_and_report(**vars(args)).decode("utf-8"))