-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSummaryTable.py
1407 lines (1160 loc) · 61.4 KB
/
SummaryTable.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import csv
import GenomicFeatures
import argparse
import glob
import scipy.stats
import numpy as np
import math
import itertools
import pandas as pd
import Shared
import Organisms
from RangeSet import RangeSet
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Rectangle
def read_hit_files(files, read_depth_filter=1):
"""Read in the list of hits files.
Parameters
----------
read_depth_filter : int
The read depth below which insertion events will be ignored.
"""
return [read_hit_file(f, read_depth_filter) for f in files]
def read_hit_file(filename, read_depth_filter=1):
"""Read in the given hit file.
Parameters
----------
read_depth_filter : int
The read depth below which insertion events will be ignored.
Returns
-------
list of dicts of str to object
Every hit is converted to a dict, specifying its properties according
to the original table columns. Numerical values are converted as
necessary.
"""
result = []
with open(filename, "r") as in_file:
in_file.next()
for line in in_file:
chrom, source, _up_feature_type, up_feature_name, up_gene_name, \
up_feature_dist, _down_feature_type, down_feature_name, \
down_gene_name, down_feature_dist, ig_type, \
hit_pos, hit_count = line.split("\t")
hit_count = int(hit_count)
if hit_count < read_depth_filter:
continue
if "ORF" in ig_type:
gene_name = up_gene_name if up_gene_name != "nan" \
else up_feature_name
assert ig_type in ("ORF(W)-ORF(W)", "ORF(C)-ORF(C)") and \
up_feature_name == down_feature_name and \
up_gene_name == down_gene_name and \
up_feature_dist == down_feature_dist == "0"
else:
gene_name = "nan"
obj = {"chrom": chrom,
"source": source,
# NB: these fields are not used, but take up a lot of
# space. Ignore them for now.
# "up_feature_type": up_feature_type,
# "up_feature_name": up_feature_name,
# "up_gene_name": up_gene_name,
# "up_feature_dist": up_feature_dist,
# "down_feature_type": down_feature_type,
# "down_feature_name": down_feature_name,
# "down_gene_name": down_gene_name,
# "down_feature_dist": down_feature_dist,
# "ig_type": ig_type,
"hit_pos": int(hit_pos),
"hit_count": hit_count,
"gene_name": gene_name}
result.append(obj)
return result
def read_pombe_hit_file(filename, read_depth_filter=1):
# TODO: should be standardized with the Calb hit file.
result = []
with open(filename, "r") as in_file:
reader = csv.reader(in_file)
reader.next()
for line in reader:
chrom, strand, hit_pos, hit_count, gene_name = line
hit_pos = int(hit_pos)
hit_count = int(hit_count)
if hit_count < read_depth_filter:
continue
obj = {"chrom": chrom,
"source": strand,
"hit_pos": hit_pos,
"hit_count": hit_count,
"gene_name": gene_name}
result.append(obj)
return result
def get_hits_from_wig(wig_file):
"""Read hits from a .wig file.
Used in reading Kornmann's cerevisiae hit data.
"""
result = []
with open(wig_file, 'r') as in_file:
in_file.readline() # Drop the header line
for line in in_file:
if line.startswith("variableStep"):
chrom_name = line[line.index("chrom=") + len("chrom="):].strip()
continue
if chrom_name == 'chrM':
continue
hit_pos, reads = line.split()
hit_pos = int(hit_pos)
reads = int(reads)
result.append({"chrom": chrom_name,
"hit_pos": hit_pos,
"hit_count": reads})
return result
TOTAL_HITS = "Total Hits"
TOTAL_READS = "Total Reads"
AVG_READS_PER_HIT = "Mean Reads Per Hit"
ORF_HITS = "Hits in ORFs"
ANNOTATED_FEATURE_HITS = "Hits in Genomic Features"
PER_ANNOTATED_FEATURE_HITS = "% of hits in features"
INTERGENIC_HITS = "Intergenic Hits"
PER_INTERGENIC_HITS = "% of intergenic hits"
FEATURES_HIT = "No. of Features Hit"
PER_FEATURES_HIT = "% of features hit"
AVG_HITS_IN_FEATURE = "Mean hits per feature"
AVG_READS_IN_FEATURE = "Mean reads per feature"
AVG_READS_IN_FEATURE_HIT = "Mean reads per hit in feature"
READS_IN_FEATURES = "Total reads in features"
ALL_STATS = [TOTAL_READS, TOTAL_HITS, PER_ANNOTATED_FEATURE_HITS, PER_INTERGENIC_HITS,
PER_FEATURES_HIT, AVG_HITS_IN_FEATURE, AVG_READS_IN_FEATURE,
AVG_READS_PER_HIT, AVG_READS_IN_FEATURE_HIT]
def get_statistics(dataset, feature_db):
"""Get general statistics about hit files.
Returns
-------
dict
A dict containing the computed stats.
"""
result = {}
result[TOTAL_HITS] = len(dataset)
result[TOTAL_READS] = sum(obj["hit_count"] for obj in dataset)
result[AVG_READS_PER_HIT] = result[TOTAL_READS] / result[TOTAL_HITS]
result[ORF_HITS] = 0
result[ANNOTATED_FEATURE_HITS] = 0
result[INTERGENIC_HITS] = 0
result[READS_IN_FEATURES] = 0
features_hit = set()
for hit in dataset:
features = feature_db.get_features_at_location(hit["chrom"], hit["hit_pos"])
if len(features) == 0:
continue
result[ANNOTATED_FEATURE_HITS] += 1
result[READS_IN_FEATURES] += hit["hit_count"]
features_hit.update(set( f.standard_name for f in features ))
for f in features:
if f.is_orf:
result[ORF_HITS] += 1
break
alb_db = GenomicFeatures.default_alb_db()
result[INTERGENIC_HITS] = result[TOTAL_HITS] - result[ANNOTATED_FEATURE_HITS]
result[FEATURES_HIT] = len(features_hit)
result[PER_INTERGENIC_HITS] = "%.2f%%" % (result[INTERGENIC_HITS] * 100.0 / result[TOTAL_HITS])
result[PER_ANNOTATED_FEATURE_HITS] = "%.2f%%" % (result[ANNOTATED_FEATURE_HITS] * 100.0 / result[TOTAL_HITS])
result[PER_FEATURES_HIT] = "%.2f%%" % (result[FEATURES_HIT] * 100.0 / len(alb_db.get_all_features()))
result[AVG_HITS_IN_FEATURE] = "%.1f" % (result[ANNOTATED_FEATURE_HITS] * 1.0 / result[FEATURES_HIT])
result[AVG_READS_IN_FEATURE] = result[READS_IN_FEATURES] / result[FEATURES_HIT]
result[AVG_READS_IN_FEATURE_HIT] = result[READS_IN_FEATURES] / result[ANNOTATED_FEATURE_HITS]
return result
def analyze_hits(dataset, feature_db, neighborhood_window_size=10000):
"""Analyze a hit dataset into a feature dataset.
Parameters
----------
dataset : list of dict
The hit list, requires that each hit have a "hit_pos", "hit_count" and
"gene_name" field.
feature_db : `GenomicFeatures._FeatureDB`
The feature database to use.
neighborhood_window_size : int
The window size for computing the neighborhood index.
Returns
-------
dict of dicts
A map of standard feature names to its all_analyzed results. The results
themselves are represented as a dict of str to object. For example:
{
"C2_":
{
"feature": the_feature_object,
"hits": 24,
"reads": 5064,
...
}
...,
}
"""
log2 = lambda v: math.log(v, 2)
result = {}
total_reads = sum(h["hit_count"] for h in dataset)
total_reads_log = log2(total_reads)
chroms = set(h["chrom"] for h in dataset)
for chrom in chroms:
hits = [h for h in dataset if h["chrom"] == chrom]
chrom_len = max(len(feature_db[chrom]), max(h["hit_pos"] for h in hits))
# We will count up all of the hits, and then separate them into intra-
# and inter-feature arrays (for the neighborhood index). The separation
# is done via using an exon mask:
exon_mask = np.zeros((chrom_len + 1,), dtype=np.bool)
for feature in feature_db[chrom]:
for exon in feature.exons:
exon_mask[exon[0]:exon[1]+1] = True
domain_mask = np.zeros((chrom_len + 1,), dtype=np.bool)
for feature in feature_db[chrom]:
for domain in feature.domains:
domain_mask[domain[0]:domain[1]+1] = True
# The mask is inverted - the 1 cells are to be kept (they exist and
# have a high mapq), and the 0 cells are to be ignored.
# TODO: refactor.
ignored_mask = np.ones((chrom_len + 1,), dtype=np.bool)
if isinstance(feature_db, GenomicFeatures.AlbicansFeatureDB):
ignored_range_set = Organisms.alb.ignored_regions[chrom]
elif isinstance(feature_db, GenomicFeatures.PombeFeatureDB):
ignored_range_set = Organisms.pom.ignored_regions[chrom]
elif isinstance(feature_db, GenomicFeatures.CerevisiaeFeatureDB):
ignored_range_set = Organisms.cer.ignored_regions[feature_db.get_std_chrom_name(chrom)]
else:
ignored_range_set = RangeSet()
for start, stop in ignored_range_set:
ignored_mask[start:stop+1] = False
hits_across_chrom = np.zeros((chrom_len + 1,), dtype=np.int)
reads_across_chrom = np.zeros((chrom_len + 1,), dtype=np.int)
for hit in hits:
reads_across_chrom[hit["hit_pos"]] += hit["hit_count"]
# TODO: why do we cap the hits at 2? What happens with pooled
# hit all_hits?
hit_pos = hit["hit_pos"]
if hits_across_chrom[hit_pos] < 2:
hits_across_chrom[hit_pos] += 1
# TODO: have the gene_name be in standard format - common names can
# be duplicates, e.g. PDR17
# Hits in ignored locations:
# There seem to be a few tens of these on each chromosome. A random inspection
# with IGV suggests that these are bowtie2 alignment errors - it seems to give
# a high MAPQ to reads that should have a low MAPQ (according to our simulated
# BAM for finding homologous regions).
hits_across_chrom = hits_across_chrom * ignored_mask
reads_across_chrom = reads_across_chrom * ignored_mask
hits_in_features = hits_across_chrom * exon_mask
hits_outside_features = hits_across_chrom * np.invert(exon_mask)
reads_outside_features = reads_across_chrom * np.invert(exon_mask)
records = {} # The per-feature records for this chromosome.
for feature in feature_db[chrom]:
feature_mask = exon_mask[feature.start:feature.stop+1]
domain_feature_mask = domain_mask[feature.start:feature.stop+1]
hits_in_feature = hits_in_features[feature.start:feature.stop+1][feature_mask]
hits_in_domains_count = hits_in_features[feature.start:feature.stop+1][domain_feature_mask].sum()
hits_in_feature_count = hits_in_feature.sum()
reads_in_feature = reads_across_chrom[feature.start:feature.stop+1][feature_mask].sum()
reads_in_domains = reads_across_chrom[feature.start:feature.stop+1][domain_feature_mask].sum()
# The borders of the neighborhood window:
window_start = max(1, feature.start - neighborhood_window_size)
window_end = min(chrom_len, feature.stop + neighborhood_window_size)
hits_outside_feature = hits_outside_features[window_start:window_end+1]
hits_outside_feature_count = hits_outside_feature.sum()
intergenic_region = feature_db.get_interfeature_range(chrom, (window_start, window_end)) - ignored_range_set
insertion_index = float(hits_in_feature_count) / feature.coding_length
# There are some scenarios where large regions have no hits whatsoever:
# * The dataset is very low coverage.
# * A read depth filter was applied, and it greatly decreased coverage.
# * A region is simply deleted.
# Computing the neighborhood index would thus result in a division-by-zero
# error. To prevent this, we assign the neighborhood index to be 0,
# however it's up to the downstream tools to filter this. It's suggested
# to ignore features that had no hits in their neighborhood, as they're
# probably not informative and will increase error rates.
if hits_outside_feature_count == 0:
neighborhood_index = 0
reads_ni = 0
else:
neighborhood_insertion_index = float(hits_outside_feature_count) / intergenic_region.coverage
neighborhood_index = insertion_index / neighborhood_insertion_index
reads_ni = (
(float(reads_in_feature) / feature.coding_length) /
(float(reads_outside_features[window_start:window_end+1].sum()) / intergenic_region.coverage)
)
n_term_insertions = {}
for n_term_len in (50, 100):
if feature.strand == 'W':
n_term_hits = hits_in_feature[:n_term_len].sum()
elif feature.strand == 'C':
n_term_hits = hits_in_feature[max(0, len(hits_in_feature)-n_term_len):].sum()
n_term_insertions["n_term_hits_%d" % n_term_len] = n_term_hits
n_term_insertions["n_term_ni_%d" % n_term_len] = \
(float(n_term_hits) / n_term_len) / neighborhood_insertion_index if \
hits_outside_feature_count > 0 else 0
# TODO: We assume that the 100 bp upstream is always intergenic, but this isn't always the case.
# How should we handle this?
if feature.strand == 'W':
upstream_slice_100 = slice(max(1, feature.start - 100), feature.start)
upstream_slice_50 = slice(max(1, feature.start - 50), feature.start)
elif feature.strand == 'C':
upstream_slice_100 = slice(feature.stop + 1, min(chrom_len, feature.stop + 101))
upstream_slice_50 = slice(feature.stop + 1, min(chrom_len, feature.stop + 51))
else:
# TODO: does this happen? Can this happen? What should we do about it?
# This can happen in cerevisiae ARS regions.
assert False
upstream_slice_100 = slice(0, 0)
upstream_slice_50 = slice(0, 0)
upstream_region_100 = hits_outside_features[upstream_slice_100]
upstream_region_50 = hits_outside_features[upstream_slice_50]
upstream_50_hits = upstream_region_50.sum()
upstream_100_hits = upstream_region_100.sum()
# Compute the longest area without any hits:
hit_ixes = [0] + list(np.where(hits_in_feature > 0)[0]+1) + [feature.coding_length + 1]
longest_free_intervals = []
freedom_indices = []
kornmann_indices = []
logit_fis = []
max_skip_tns = 4+1
for skip_tns in range(max_skip_tns):
longest_interval = \
max(right - left for left, right in
zip(hit_ixes, hit_ixes[1+skip_tns:] or [feature.coding_length + 1])) \
- 1
longest_free_intervals.append(longest_interval)
freedom_index = float(longest_interval) / feature.coding_length
freedom_indices.append(freedom_index)
if longest_interval >= 300 and 0.1 < freedom_index < 0.9:
kornmann_index = (longest_interval * hits_in_feature_count) / (feature.coding_length ** 1.5)
else:
kornmann_index = 0
kornmann_indices.append(kornmann_index)
logit_fis.append(freedom_index / (1.0 + math.e ** (-0.01 * (feature.coding_length - 200))))
records[feature.standard_name] = {
"feature": feature,
"length": len(feature),
"hits": hits_in_feature_count,
"reads": reads_in_feature,
# Can be tested downstream for zero:
"neighborhood_hits": hits_outside_feature_count,
"nc_window_len": intergenic_region.coverage,
"insertion_index": insertion_index,
"neighborhood_index": neighborhood_index,
"reads_ni": reads_ni,
"upstream_hits_50": upstream_50_hits,
"upstream_hits_100": upstream_100_hits,
"max_free_region": longest_free_intervals[0],
"freedom_index": freedom_indices[0],
"logit_fi": logit_fis[0],
# The value is singular, to get the coefficient we subtract the pre from the post later on:
"s_value": log2(reads_in_feature + 1) - total_reads_log, # Add 1 so as to not get a log 0
# Note: the positions are relative to the gene, and the introns are excised:
"hit_locations": [ix+1 for (ix, hit) in enumerate(hits_in_feature) if hit > 0],
"longest_interval": longest_free_intervals[4],
"kornmann_domain_index": kornmann_indices[4],
"domain_ratio": float(feature.domains.coverage) / feature.coding_length,
"hits_in_domains": hits_in_domains_count,
"reads_in_domains": reads_in_domains,
"domain_coverage": feature.domains.coverage,
"skip_longest_free_intervals": longest_free_intervals,
"skip_freedom_indices": freedom_indices,
"skip_kornmann_indices": kornmann_indices,
"logit_fis": logit_fis[0],
"bps_between_hits_in_neihgborhood": intergenic_region.coverage / hits_outside_feature_count if hits_outside_feature_count > 0 else 9999,
"bps_between_hits_in_feature": len(feature) / hits_in_feature_count if hits_in_feature_count > 0 else 9999
}
records[feature.standard_name].update(n_term_insertions)
for skip_tns in range(max_skip_tns):
records[feature.standard_name]["longest_free_interval_%d" % skip_tns] = longest_free_intervals[skip_tns]
records[feature.standard_name]["freedom_index_%d" % skip_tns] = freedom_indices[skip_tns]
records[feature.standard_name]["kornmann_index_%d" % skip_tns] = kornmann_indices[skip_tns]
records[feature.standard_name]["logit_fi_%d" % skip_tns] = logit_fis[skip_tns]
result.update(records)
return result
def write_analyzed_alb_records(records, output_file):
"""Write the analyzed albicans records with a default column configuration
into a csv file.
Parameters
----------
records : list of dicts
A list of analyzed records.
output_file : str
The path to the output file.
"""
cols_config = [
{
"field_name": "feature",
"csv_name": "Standard name",
"format": lambda f: f.standard_name
},
{
"field_name": "feature",
"csv_name": "Common name",
"format": lambda f: f.common_name
},
{
"field_name": "feature",
"csv_name": "Sc ortholog",
"format": lambda f: ','.join(f.cerevisiae_orthologs)
},
{
"field_name": "essential_in_cerevisiae",
"csv_name": "Essential in Sc",
},
{
"field_name": "cer_synthetic_lethal",
"csv_name": "Sc synthetic lethals",
},
{
"field_name": "cer_fitness",
"csv_name": "Sc fitness",
},
{
"field_name": "essential_in_albicans",
"csv_name": "Essential in albicans",
},
{
"field_name": "pombe_ortholog",
"csv_name": "Sp ortholog",
},
{
"field_name": "essential_in_pombe",
"csv_name": "Essential in Sp",
},
{
"field_name": "hits",
"csv_name": "Hits",
"format": "%d"
},
{
"field_name": "reads",
"csv_name": "Reads",
"format": "%d"
},
{
"field_name": "feature",
"csv_name": "Length",
"format": lambda f: len(f)
},
{
"field_name": "neighborhood_index",
"csv_name": "Neighborhood index",
"format": "%.3f"
},
{
"field_name": "upstream_hits_100",
"csv_name": "100 bp upstream hits"
},
{
"field_name": "max_free_region",
"csv_name": "Max free region"
},
{
"field_name": "freedom_index",
"csv_name": "Freedom index",
"format": "%.3f"
},
{
"field_name": "logit_fi",
"csv_name": "Logit FI",
"format": "%.3f"
},
{
"field_name": "kornmann_domain_index",
"csv_name": "Kornmann FI",
"format": "%.3f"
},
{
"field_name": "feature",
"csv_name": "Type",
"format": lambda f: f.type
},
{
"field_name": "feature",
"csv_name": "Description",
"format": lambda f: f.description
},
]
enrich_alb_records(records)
write_data_to_csv(records, cols_config, output_file)
def write_data_to_csv(data, cols_config, output_filename):
"""Write a list of dicts representing data objects into a CSV file using a
specified configuration.
The configuration allows the standard C-style string formatting as well as
passing a custom function for data transformation.
Note
----
This is a legacy method. Consider using pandas instead.
Parameters
----------
data : iterable of dicts of str to object
An iterable of data objects.
cols_config : list of dicts of str to object
An example of a configuration:
[
{
field_name: "field_name", # Mandatory, the field name in the data object dicts.
format: "%.3f", # Optional, default is %s. Can be a callable - in which case, the callable will be executed on the field.
csv_name: "Column name", # Mandatory, must be unique.
sort_by: True, # Optional, default is not to sort by any column. Can only be set once. Cannot be set with a callable for the format.
},
...
]
output_filename : str
The name of the output file.
"""
df = write_data_to_data_frame(data, cols_config)
df.to_csv(output_filename)
def write_data_to_data_frame(data, cols_config):
field_col = "field_name"
format_col = "format"
csv_name_col = "csv_name"
sort_by_col = "sort_by"
# Filter out field names that don't exist:
if data:
filtered_cols_config = []
first_record = data[0]
for col in cols_config:
if col[field_col] not in first_record:
# print "WARNING: %s not in records to print!" % col[field_col]
continue
filtered_cols_config.append(col)
cols_config = filtered_cols_config
# Find sort column:
sort_field = None
for col in cols_config:
if col.get(sort_by_col, False):
sort_field = col[field_col]
break
# Sort by the sort column, if found:
if sort_field is not None:
ordered_dataset = sorted(data, key=lambda record: record[sort_field])
else:
ordered_dataset = data # Default ordering, really
# Cache the formats:
format_cache = {}
for col in cols_config:
col_name = col[csv_name_col]
# NB: previously, when writing directly to CSV, without the pandas
# intermediary, we would use `"%s" % s` formatting, but that doesn't
# work with pandas anymore, so we pass the value as is.
# We can consider adding a special pandas format field.
if format_col not in col:
format_cache[col_name] = lambda s: s
elif callable(col[format_col]):
format_cache[col_name] = col[format_col]
else:
format_cache[col_name] = lambda s: s
result = pd.DataFrame(
data=[[format_cache[col[csv_name_col]](record[col[field_col]]) for col in cols_config] for record in ordered_dataset],
columns=[col[csv_name_col] for col in cols_config]
)
return result
@Shared.memoized
def get_calb_ess_in_sc():
cer_essentials = Organisms.cer.literature_essentials
cer_non_essentials = Organisms.cer.literature_non_essentials
all_alb_fs = GenomicFeatures.default_alb_db().get_all_features()
cer_db = GenomicFeatures.default_cer_db()
return (
set(f.standard_name for f in all_alb_fs if any(cer_db.get_feature_by_name(c).standard_name in cer_essentials for c in f.cerevisiae_orthologs)),
set(f.standard_name for f in all_alb_fs if any(cer_db.get_feature_by_name(c).standard_name in cer_non_essentials for c in f.cerevisiae_orthologs)),
)
@Shared.memoized
def get_calb_orths_in_sp():
return Organisms.get_calb_orths_in_sp()
@Shared.memoized
def get_calb_ess_in_sp():
# TODO: refactor into the Organisms module.
viability_table = pd.read_csv(Shared.get_dependency("pombe/FYPOviability.tsv"),
header=None,
delimiter='\t',
names=["pombe standard name", "essentiality"])
ortholog_table = pd.read_csv(Shared.get_dependency("albicans/C_albicans_SC5314_S_pombe_orthologs.txt"),
skiprows=8,
delimiter='\t',
header=None,
usecols=['albicans standard name', 'pombe standard name'],
names=['albicans standard name', 'albicans common name', 'albicans alb_db id',
'pombe standard name', 'pombe common name', 'pombe alb_db id'])
# TODO: we probably don't want to use the hit table, though the InParanoid
# table is very stringent.
best_hit_table = pd.read_csv(Shared.get_dependency("albicans/C_albicans_SC5314_S_pombe_best_hits.txt"),
skiprows=8,
delimiter='\t',
header=None,
usecols=['albicans standard name', 'pombe standard name'],
names=['albicans standard name', 'albicans common name', 'albicans alb_db id',
'pombe standard name', 'pombe common name', 'pombe alb_db id'])
ortholog_table = pd.concat([ortholog_table, best_hit_table])
joined_table = pd.merge(ortholog_table, viability_table, on="pombe standard name")
essentials = set()
non_essentials = set()
for alb_feature in GenomicFeatures.default_alb_db().get_all_features():
ortholog_row = joined_table[joined_table["albicans standard name"] == alb_feature.standard_name]
if ortholog_row.empty:
continue
ess_annotation = ortholog_row["essentiality"].iloc[0]
if ess_annotation == "viable":
non_essentials.add(alb_feature.standard_name)
elif ess_annotation == "inviable":
essentials.add(alb_feature.standard_name)
return (essentials, non_essentials)
def enrich_with_pombe(records):
"""Add pombe orthologs and essentiality annotations to albicans records."""
# TODO: maybe we should add this to analyze_hits?
essentials, non_essentials = get_calb_ess_in_sp()
sp_orthologs = get_calb_orths_in_sp()
for record in records:
alb_name = record["feature"].standard_name
ortholog_name = sp_orthologs.get(alb_name, "")
ortholog_essentiality = "Yes" if alb_name in essentials else \
"No" if alb_name in non_essentials else \
""
record["pombe_ortholog"] = ortholog_name
record["essential_in_pombe"] = ortholog_essentiality
def enrich_alb_records(records):
"""Enrich albicans records with 3-rd party data.
3-rd party data include orthologs, essentiality from literature, etc."""
# TODO: maybe we should add this to analyze_hits?
cer_db = GenomicFeatures.default_cer_db()
# Pombe:
enrich_with_pombe(records)
# Cerevisiae:
cer_essentials = Organisms.cer.literature_essentials
cer_non_essentials = Organisms.cer.literature_non_essentials
# TODO: document the origin of the synthetic lethal dataset.
cer_synthetic_lethals = {}
with open(Shared.get_dependency("cerevisiae/duplicatesSl_011116.txt"), 'r') as in_file:
in_file.readline()
for line in in_file:
f1_name, f2_name, _, is_double_lethal = line.split()
f1 = cer_db.get_feature_by_name(f1_name)
f2 = cer_db.get_feature_by_name(f2_name)
f1_std_name = f1.standard_name if f1 is not None else ""
f2_std_name = f2.standard_name if f2 is not None else ""
cer_synthetic_lethals[f1_std_name] = cer_synthetic_lethals[f2_std_name] = \
{"1": "Yes", "0": "No"}.get(is_double_lethal, is_double_lethal)
cer_fitness = {}
# TODO: document the origin of the fitness dataset.
with open(Shared.get_dependency("cerevisiae/neFitnessStandard.txt"), 'r') as in_file:
for line in in_file:
fname, fitness = line.split()
feature = cer_db.get_feature_by_name(fname)
if feature is None:
continue
cer_fitness[cer_db.get_feature_by_name(fname).standard_name] = fitness
# Albicans:
# All liteartue phenotypes, no pre-filtering:
alb_phenotype_table_path = Shared.get_dependency("albicans/C_albicans_phenotype_data.tab")
alb_phenotype_table = pd.read_csv(
alb_phenotype_table_path,
delimiter='\t',
header=None,
usecols=['Feature Name', 'Phenotype'],
names=['Feature Name', 'Feature Type', 'Gene Name',
'CGDID', 'Reference', 'Experiment Type', 'Mutant Type',
'Allele', 'Strain background', 'Phenotype', 'Chemical', 'Condition',
'Details', 'Reporter', 'Anatomical Structure', 'Virulence Model', 'Species']
)
alb_pheno_essentials = set(alb_phenotype_table[alb_phenotype_table["Phenotype"] == "inviable"]["Feature Name"])
alb_pheno_non_essentials = set(alb_phenotype_table[alb_phenotype_table["Phenotype"] == "viable"]["Feature Name"])
alb_db = GenomicFeatures.default_alb_db()
alb_pheno_essential_features = set(f.standard_name for f in filter(None, (alb_db.get_feature_by_name(f) for f in alb_pheno_essentials)))
alb_pheno_non_essential_features = set(f.standard_name for f in filter(None, (alb_db.get_feature_by_name(f) for f in alb_pheno_non_essentials)))
alb_pheno_toss_up = alb_pheno_essential_features & alb_pheno_non_essential_features
alb_pheno_essential_consensus = alb_pheno_essential_features - alb_pheno_non_essential_features
alb_pheno_non_essential_consensus = alb_pheno_non_essential_features - alb_pheno_essential_features
roemer_grace_essentials, roemer_grace_non_essentials, \
omeara_grace_essentials, omeara_grace_non_essentials = get_grace_essentials()
homann_deletions = get_homann_deletions()
noble_deletions = get_noble_deletions()
sanglard_deletions = get_sanglard_deletions()
mitchell_essentials = get_mitchell_essentials()
for record in records:
feature = record["feature"]
std_name = feature.standard_name
if feature.cerevisiae_orthologs:
# TODO: according to albicans feature file, a gene may have more than one ortholog, but in practice this doesn't happen.
assert len(feature.cerevisiae_orthologs) == 1
cer_ortholog = cer_db.get_feature_by_name(iter(feature.cerevisiae_orthologs).next()).standard_name
# TODO: ? should be reserved for conflicting entries, not just those
# for which data in not available.
record["essential_in_cerevisiae"] = "Yes" if cer_ortholog in cer_essentials else \
"No" if cer_ortholog in cer_non_essentials else \
"?" if cer_ortholog in Organisms.cer.conflicting_essentials else ""
record["cer_synthetic_lethal"] = cer_synthetic_lethals.get(cer_ortholog, "")
record["cer_fitness"] = cer_fitness.get(cer_ortholog, "")
else:
record["essential_in_cerevisiae"] = ""
record["cer_synthetic_lethal"] = ""
record["cer_fitness"] = ""
record["essential_in_albicans"] = "Yes" if std_name in alb_pheno_essential_consensus else \
"No" if std_name in alb_pheno_non_essential_consensus else \
"?" if std_name in alb_pheno_toss_up else ""
record["essential_in_albicans_grace_roemer"] = "Yes" if std_name in roemer_grace_essentials else \
"No" if std_name in roemer_grace_non_essentials else ""
record["essential_in_albicans_grace_omeara"] = "Yes" if feature.standard_name in omeara_grace_essentials else \
"No" if std_name in omeara_grace_non_essentials else ""
record["homann_deletions"] = "Deleted" if std_name in homann_deletions else ""
record["noble_deletions"] = "Deleted" if std_name in noble_deletions else ""
record["sanglard_deletions"] = "Deleted" if std_name in sanglard_deletions else ""
record["deleted_in_calb"] = ",".join(filter(None, [record["homann_deletions"] and "Homann", record["noble_deletions"] and "Noble", record["sanglard_deletions"] and "Sanglard"]))
record["essential_in_mitchell"] = "Yes" if std_name in mitchell_essentials else ""
record["has_paralog"] = "Yes" if std_name in Organisms.alb.genes_with_paralogs else ""
@Shared.memoized
def get_homann_deletions():
# TODO: the deletions should be listed in the Organisms module instead of here.
alb_db = GenomicFeatures.default_alb_db()
mutants_filepath = Shared.get_dependency("albicans/MUTANT COLLECTIONS IN PROGRESS July 5 2017.xlsx")
mutants_table = pd.read_excel(mutants_filepath, skiprows=1, header=None, parse_cols="A")
return set(f.standard_name for f in (alb_db.get_feature_by_name(str(n) + "_A") for n in mutants_table[0]) if f)
@Shared.memoized
def get_noble_deletions():
alb_db = GenomicFeatures.default_alb_db()
mutants_filepath = Shared.get_dependency("albicans/MUTANT COLLECTIONS IN PROGRESS July 5 2017.xlsx")
mutants_table = pd.read_excel(mutants_filepath, skiprows=1, header=None, parse_cols="P")
return set(f.standard_name for f in (alb_db.get_feature_by_name(n.lower()) for n in mutants_table[0]) if f)
@Shared.memoized
def get_sanglard_deletions():
alb_db = GenomicFeatures.default_alb_db()
mutants_filepath = Shared.get_dependency("albicans/MUTANT COLLECTIONS IN PROGRESS July 5 2017.xlsx")
mutants_table = pd.read_excel(mutants_filepath, skiprows=1, header=None, parse_cols="J")
return set(f.standard_name for f in (alb_db.get_feature_by_name(str(n) + "_A") for n in mutants_table[0]) if f)
@Shared.memoized
def get_grace_essentials():
"""Get names of essential and non-essential feature names in the GRACE
collection.
Feature names are in the standard format.
Returns
-------
tuple of sets of str : (roemer_essentials, roemer_non_essentials,
omeara_essentials, omeara_non_essentials)
"""
# TODO: should be listed in the Organisms module instead of here.
# TODO: figure out if Roemer data actually exists in O'Meara's tables,
# or was it but an illusion.
grace_table_path = Shared.get_dependency("albicans/ncomms7741-s2.xls")
grace_table = pd.read_excel(grace_table_path, sheetname=1, #"Essentiality scores",
skiprows=14, header=None,
names=["orf19 name", "Common", "Description", "Plate", "Position",
"tet growth", "5-FOA excision", "dox growth", "Essentiality Concordance (Y/N)",
"Essential/Not essential", "S. cerevisiae homolog", "S. cerevisiae KO phenotype"])
roemer_grace_essentials = set()
roemer_grace_non_essentials = set()
omeara_grace_essentials = set()
omeara_grace_non_essentials = set()
# Couldn't figure out how to make pandas constrain types in a column, so we
# have to handle all sorts of weirdness, including nan, and make it as
# robust as possible.
def _extract_tet_growth(tet_growth):
str_tet_growth = str(tet_growth)
if "+" not in str_tet_growth:
return None
return float(str_tet_growth.replace("+", ""))
def _extract_foa_excision(foa_excision):
if foa_excision not in ("Yes", "No"):
return None
return foa_excision
alb_db = GenomicFeatures.default_alb_db()
for _ix, line in grace_table.iterrows():
orf19name = line["orf19 name"]
feature = alb_db.get_feature_by_name(orf19name)
if feature is None:
continue
omeara_essential = line["Essential/Not essential"]
if omeara_essential == 'E':
omeara_grace_essentials.add(feature.standard_name)
elif omeara_essential == 'N':
omeara_grace_non_essentials.add(feature.standard_name)
tet_growth = _extract_tet_growth(line["tet growth"])
foa_excision = _extract_foa_excision(line["5-FOA excision"])
if tet_growth is None and foa_excision is None:
continue
if (tet_growth >= 3) or foa_excision == "Yes":
roemer_grace_essentials.add(feature.standard_name)
else:
roemer_grace_non_essentials.add(feature.standard_name)
return (roemer_grace_essentials, roemer_grace_non_essentials,
omeara_grace_essentials, omeara_grace_non_essentials)
@Shared.memoized
def get_mitchell_essentials():
# TODO: should be in Organisms.
alb_db = GenomicFeatures.default_alb_db()
with open(Shared.get_dependency("albicans", "List of possibly ess genes from Aaron Mitchell.csv"), 'r') as in_file:
orfs_19 = [s.strip() for s in in_file.read().split()]
orfs_22 = filter(None, (alb_db.get_feature_by_name(o) for o in orfs_19))
return set(o.standard_name for o in orfs_22)
def compare_insertion_and_neighborhood((analysis_labels, analyses), output_file):
"""Compare the insertion and the neighborhood indices with Pearson and
Spearman correlations.
Parameters
----------
analysis_labels : sequence
The labels for each analysis dataset.
analyses : sequence
A sequence of analyzed datasets (as returned by `analyze_hits`).
output_file : str
The path to the output file.
"""
with open(output_file, 'w') as out_file:
for label, analysis in zip(analysis_labels, analyses):
s1 = np.array([r["insertion_index"] for r in analysis.values()])
s2 = np.array([r["neighborhood_index"] for r in analysis.values()])
pearson = scipy.stats.pearsonr(s1, s2)
spearman = scipy.stats.spearmanr(s1, s2)
out_file.write("%s\nPearson: %s\nSpearman: %s\n" % (label, pearson, spearman))
def perform_pairwise_correlations(analysis_labels, analyzed_records, output_file_prefix):
"""Compute and output Pearson and Spearman correlations between all pairs
of analyzed hits. Various data points per feature are considered for
correlation from within the dataset (hits, reads, etc.).
Parameters
----------
analysis_labels : list of strings
The dataset labels.
analyzed_records : list of lists
A list of the datasets, each dataset a list of records.