-
Notifications
You must be signed in to change notification settings - Fork 26
/
MGI.py
2234 lines (1927 loc) · 101 KB
/
MGI.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 csv
import os
from datetime import datetime
import logging
import re
from dipper.sources.PostgreSQLSource import PostgreSQLSource
from dipper.models.assoc.Association import Assoc
from dipper.models.Dataset import Dataset
from dipper.models.assoc.G2PAssoc import G2PAssoc
from dipper.models.Genotype import Genotype
from dipper.models.Reference import Reference
from dipper import config
from dipper import curie_map
from dipper.utils.GraphUtils import GraphUtils
from dipper.models.GenomicFeature import Feature, makeChromID
logger = logging.getLogger(__name__)
class MGI(PostgreSQLSource):
"""
This is the [Mouse Genome Informatics](http://www.informatics.jax.org/) resource,
from which we process genotype and phenotype data about laboratory mice.
Genotypes leverage the GENO genotype model.
Here, we connect to their public database, and download a subset of tables/views to get specifically at the
geno-pheno data, then iterate over the tables. We end up effectively performing joins when adding nodes
to the graph.
In order to use this parser, you will need to have user/password connection details in your conf.json file, like:
dbauth : {
'mgi' : {'user' : '<username>', 'password' : '<password>'}
}
You can request access by contacting mgi-help@jax.org
"""
# CONSIDER IF WE NEED:
# mgi_organism_acc_view: Consider using this for the taxon mapping instead of the hashmap encoded below
# mgi_reference_allele_view: Don't believe this view is used in either the genotype of phenotype view
# all_allele_cellline_view: When we want to start dealing with cell lines
# mgi_note_strain_view: prose descriptions of strains.
# prb_strain_summary_view: Don't believe this view is used in either the genotype of phenotype view
# prb_strain_marker_view: eventually i think we want this because it has other relevant markers that are affected
tables = [
'mgi_dbinfo',
'gxd_genotype_view',
'gxd_genotype_summary_view',
'gxd_allelepair_view',
'all_summary_view',
'all_allele_view',
'all_allele_mutation_view',
'mrk_marker_view',
'voc_annot_view',
'voc_evidence_view',
'bib_acc_view',
'prb_strain_view',
'mrk_summary_view',
'mrk_acc_view',
'prb_strain_acc_view',
'prb_strain_genotype_view',
'mgi_note_vocevidence_view',
'mgi_note_allele_view',
'mrk_location_cache', # gene locations
]
# for testing purposes, this is a list of internal db keys to match and select only portions of the source
test_keys = {
'allele': [1612, 1609, 1303, 56760, 816699, 51074, 14595, 816707, 246, 38139, 4334, 817387, 8567,
476, 42885, 3658, 1193, 6978, 6598, 16698, 626329, 33649,
835532, 7861, 33649, 6308, 1285, 827608],
'marker': [357, 38043, 305574, 444020, 34578, 9503, 38712, 17679, 445717, 38415, 12944,
377, 77197, 18436, 30157, 14252, 412465, 38598, 185833, 35408, 118781,
37270, 31169, 25040, 81079],
'annot': [6778, 12035, 189442, 189443, 189444, 189445, 189446, 189447, 189448, 189449, 189450,
189451, 189452, 318424, 717023, 717024, 717025, 717026, 717027, 717028, 717029, 5123647,
928426, 5647502, 6173775, 6173778, 6173780, 6173781, 6620086, 13487622, 13487623,
13487624, 23241933, 23534428, 23535949, 23546035, 24722398, 29645663, 29645664,
29645665, 29645666, 29645667, 29645682, 43803707, 43804057, 43805682, 43815003,
43838073, 58485679, 59357863, 59357864, 59357865, 59357866, 59357867, 60448185,
60448186, 60448187, 62628962, 69611011, 69611253, 79642481, 79655585, 80436328,
83942519, 84201418, 90942381, 90942382, 90942384, 90942385, 90942386, 90942389,
90942390, 90942391, 90942392, 92947717, 92947729, 92947735, 92947757, 92948169,
92948441, 92948518, 92949200, 92949301, 93092368, 93092369, 93092370, 93092371,
93092372, 93092373, 93092374, 93092375, 93092376, 93092377, 93092378, 93092379,
93092380, 93092381, 93092382, 93401080, 93419639, 93436973, 93436974, 93436975,
93436976, 93436977, 93459094, 93459095, 93459096, 93459097, 93484431, 93484432,
93491333, 93491334, 93491335, 93491336, 93491337, 93510296, 93510297, 93510298,
93510299, 93510300, 93548463, 93551440, 93552054, 93576058, 93579091, 93579870,
93581813, 93581832, 93581841, 93581890, 93583073, 93583786, 93584586, 93587213,
93604448, 93607816, 93613038, 93614265, 93618579, 93620355, 93621390, 93624755,
93626409, 93626918, 93636629, 93642680, 93643814, 93643825, 93647695, 93648755, 93652704,
5123647, 71668107, 71668108, 71668109, 71668110, 71668111, 71668112, 71668113,
71668114, 74136778, 107386012, 58485691],
'genotype': [81, 87, 142, 206, 281, 283, 286, 287, 341, 350, 384, 406, 407, 411, 425, 457, 458, 461, 476, 485,
537, 546, 551,
553, 11702, 12910, 13407, 13453, 14815, 26655, 28610, 37313, 38345, 59766, 60082,
65406, 64235],
'pub': [73197, 165659, 134151, 76922, 181903, 26681, 128938, 80054, 156949, 159965, 53672, 170462,
206876, 87798, 100777, 176693, 139205, 73199, 74017, 102010, 152095, 18062, 216614, 61933,
13385, 32366, 114625, 182408, 140802],
'strain': [30639, 33832, 33875, 33940, 36012, 59504, 34338, 34382, 47670, 59802, 33946, 31421,
64, 40, 14, -2, 30639, 15975, 35077, 12610, -1, 28319, 27026, 141, 62299],
'notes': [5114, 53310, 53311, 53312, 53313, 53314, 53315, 53316, 53317, 53318, 53319, 53320,
71099, 501751, 501752, 501753, 501754, 501755, 501756, 501757, 744108, 1055341,
6049949, 6621213, 6621216, 6621218, 6621219, 7108498, 14590363, 14590364, 14590365,
25123358, 25123360, 26688159, 32028545, 32028546, 32028547, 32028548, 32028549,
32028564, 37833486, 47742903, 47743253, 47744878, 47754199, 47777269, 65105483,
66144014, 66144015, 66144016, 66144017, 66144018, 70046116, 78382808, 78383050,
103920312, 103920318, 103920319, 103920320, 103920322, 103920323, 103920324,
103920325, 103920326, 103920328, 103920330, 103920331, 103920332, 103920333,
106390006, 106390018, 106390024, 106390046, 106390458, 106390730, 106390807,
106391489, 106391590, 106579450, 106579451, 106579452, 106579453, 106579454,
106579455, 106579456, 106579457, 106579458, 106579459, 106579460, 106579461,
106579462, 106579463, 106579464, 106949909, 106949910, 106969368, 106969369,
106996040, 106996041, 106996042, 106996043, 106996044, 107022123, 107022124,
107022125, 107022126, 107052057, 107052058, 107058959, 107058960, 107058961,
107058962, 107058963, 107077922, 107077923, 107077924, 107077925, 107077926,
107116089, 107119066, 107119680, 107154485, 107155254, 107158128, 107159385,
107160435, 107163154, 107163183, 107163196, 107163271, 107164877, 107165872,
107166942, 107168838, 107170557, 107174867, 107194346, 107198590, 107205179,
107206725, 107212120, 107214364, 107214911, 107215700, 107218519, 107218642,
107219974, 107221415, 107222064, 107222717, 107235068, 107237686, 107242709,
107244121, 107244139, 107248964, 107249091, 107250401, 107251870, 107255383, 107256603]
}
def __init__(self):
super().__init__('mgi')
self.namespaces.update(curie_map.get())
# update the dataset object with details about this resource
self.dataset = Dataset('mgi', 'MGI', 'http://www.informatics.jax.org/', None,
'http://www.informatics.jax.org/mgihome/other/copyright.shtml')
# check if config exists; if it doesn't, error out and let user know
if 'dbauth' not in config.get_config() and 'mgi' not in config.get_config()['dbauth']:
logger.error("not configured with PG user/password.")
# source-specific warnings. will be cleared when resolved.
logger.warn("we are ignoring normal phenotypes for now")
# so that we don't have to deal with BNodes, we will create hash lookups for the internal identifiers
# the hash will hold the type-specific-object-keys to MGI public identifiers. then, subsequent
# views of the table will lookup the identifiers in the hash. this allows us to do the 'joining' on the
# fly
self.idhash = {'allele': {}, 'marker': {}, 'publication': {}, 'strain': {},
'genotype': {}, 'annot': {}, 'notes': {}}
self.markers = {'classes': [], 'indiv': []} # to store if a marker is a class or indiv
self.label_hash = {} # use this to store internally generated labels for various features
self.geno_bkgd = {} # use this to store the genotype strain ids for building genotype labels
self.wildtype_alleles = set()
# also add the gene ids from the config in order to capture transgenes of the test set
if 'test_ids' not in config.get_config() or 'gene' not in config.get_config()['test_ids']:
logger.warn("not configured with gene test ids.")
else:
self.test_ids = config.get_config()['test_ids']['gene']
return
def fetch(self, is_dl_forced=False):
"""
For the MGI resource, we connect to the remote database, and pull the tables into local files.
We'll check the local table versions against the remote version
:return:
"""
# create the connection details for MGI
cxn = config.get_config()['dbauth']['mgi']
cxn.update({'host': 'mgi-adhoc.jax.org', 'database': 'mgd', 'port': 5432})
self.dataset.setFileAccessUrl(''.join(('jdbc:postgresql://', cxn['host'], ':',
str(cxn['port']), '/', cxn['database'])))
# process the tables
# self.fetch_from_pgdb(self.tables, cxn, 100) # for testing only
self.fetch_from_pgdb(self.tables, cxn, None, is_dl_forced)
self.fetch_from_pgdb(['mgi_dbinfo'], cxn, None, True) # always get this - it has the verion info
self.fetch_transgene_genes_from_db(cxn)
datestamp = ver = None
# get the resource version information from table mgi_dbinfo, already fetched above
outfile = '/'.join((self.rawdir, 'mgi_dbinfo'))
if os.path.exists(outfile):
with open(outfile, 'r') as f:
f.readline() # read the header row; skip
info = f.readline()
cols = info.split('\t')
ver = cols[0] # col 0 is public_version
ver = ver.replace('MGI ', '') # MGI 5.20 --> 5.20
# MGI has a datestamp for the data within the database; use it instead of the download date
# datestamp in the table: 2014-12-23 00:14:20
d = cols[7].strip() # modification date
datestamp = datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
f.close()
self.dataset.setVersion(datestamp, ver)
return
def parse(self, limit=None):
"""
We process each of the postgres tables in turn. The order of processing is important here, as we build
up a hashmap of internal vs external identifers (unique keys by type to MGI id). These include
allele, marker (gene), publication, strain, genotype, annotation (association), and descriptive notes.
:param limit: Only parse this many lines of each table
:return:
"""
if limit is not None:
logger.info("Only parsing first %d rows of each file", limit)
logger.info("Parsing files...")
if self.testOnly:
self.testMode = True
# the following will provide us the hash-lookups
# These must be processed in a specific order
self._process_prb_strain_acc_view(limit)
self._process_mrk_acc_view()
self._process_all_summary_view(limit)
self._process_bib_acc_view(limit)
self._process_gxd_genotype_summary_view(limit)
# The following will use the hash populated above to lookup the ids when filling in the graph
self._process_prb_strain_view(limit)
self._process_gxd_genotype_view(limit)
self._process_mrk_marker_view(limit)
self._process_mrk_acc_view_for_equiv(limit)
self._process_mrk_summary_view(limit)
self._process_all_allele_view(limit)
self._process_all_allele_mutation_view(limit)
self._process_gxd_allele_pair_view(limit)
self._process_voc_annot_view(limit)
self._process_voc_evidence_view(limit)
self._process_mgi_note_vocevidence_view(limit)
self._process_mrk_location_cache(limit)
self.process_mgi_relationship_transgene_genes(limit)
self.process_mgi_note_allele_view(limit)
logger.info("Finished parsing.")
self.load_bindings()
for g in [self.graph, self.testgraph]:
Assoc(self.name).load_all_properties(g)
gu = GraphUtils(curie_map.get())
gu.loadAllProperties(g)
logger.info("Loaded %d nodes", len(self.graph))
return
def fetch_transgene_genes_from_db(self, cxn):
"""
This is a custom query to fetch the non-mouse genes that are part of transgene alleles.
:param cxn:
:return:
"""
query = "" + \
"select r._relationship_key as rel_key, " + \
"r._object_key_1 as object_1, " + \
"a.accid as allele_id, " + \
"alabel.label as allele_label, " + \
"rc._category_key as category_key, " + \
"rc.name as category_name, " +\
"t._term_key as property_key, " +\
"t.term as property_name, " +\
"rp.value as property_value " +\
"from mgi_relationship r " +\
"join mgi_relationship_category rc " +\
"on r._category_key = rc._category_key " +\
"join acc_accession a " +\
"on r._object_key_1 = a._object_key " +\
"and rc._mgitype_key_1 = a._mgitype_key " +\
"and a._logicaldb_key = 1 " +\
"join all_label alabel " +\
"on a._object_key = alabel._allele_key " +\
"and alabel._label_status_key = 1 " +\
"and alabel.priority = 1 " +\
"join mgi_relationship_property rp " +\
"on r._relationship_key = rp._relationship_key " +\
"and rp._propertyname_key = 12948292 " +\
"join voc_term t " +\
"on rp._propertyname_key = t._term_key " +\
"where r._category_key = 1004 "
self.fetch_query_from_pgdb('mgi_relationship_transgene_genes', query, None, cxn)
return
def _process_gxd_genotype_view(self, limit=None):
"""
This table indicates the relationship between a genotype and it's background strain. It leverages the
Genotype class methods to do this.
Makes these triples:
<MGI:genotypeid> GENO:has_reference_part <MGI:strainid>
<MGI:strainid> a GENO:genomic_background
If the genotype id isn't in the hashmap, it adds it here (but this shouldn't happen):
<MGI:genotypeid> a GENO:genotype
If the strain isn't in the hashmap, it also adds it here with a monarchized identifier using the
unique key of the strain, formatted like: :_mgistrainkey12345
:param limit:
:return:
"""
line_counter = 0
if self.testMode:
g = self.testgraph
else:
g = self.graph
geno = Genotype(g)
raw = '/'.join((self.rawdir, 'gxd_genotype_view'))
logger.info("getting genotypes and their backgrounds")
gu = GraphUtils(curie_map.get())
with open(raw, 'r') as f1:
f1.readline() # read the header row; skip
for line in f1:
line_counter += 1
(genotype_key, strain_key, isconditional, note, existsas_key, createdby_key, modifiedby_key,
creation_date, modification_date, strain, mgiid, dbname, createdbymodifiedby, existsas,
empty) = line.split('\t')
if self.testMode is True:
if int(genotype_key) not in self.test_keys.get('genotype'):
continue
if self.idhash['genotype'].get(genotype_key) is None:
# just in case we haven't seen it before, catch and add the id mapping here
self.idhash['genotype'][genotype_key] = mgiid
geno.addGenotype(mgiid, None)
# the label is elsewhere... need to add the MGI label as a synonym
# if it's in the hash, assume that the individual was created elsewhere
strain_id = self.idhash['strain'].get(strain_key)
background_type = geno.genoparts['genomic_background']
if strain_id is None or int(strain_key) < 0:
if strain_id is None:
# some of the strains don't have public identifiers!
# so we make one up, and add it to the hash
strain_id = self._makeInternalIdentifier('strain', strain_key)
if self.nobnodes:
strain_id = ':' + strain_id
self.idhash['strain'].update({strain_key: strain_id})
gu.addComment(g, strain_id, "strain_key:"+strain_key)
elif int(strain_key) < 0:
# these are ones that are unidentified/unknown. so add instances of each.
strain_id = self._makeInternalIdentifier('strain', re.sub(':', '', str(strain_id)))
strain_id += re.sub(':', '', str(mgiid))
if self.nobnodes:
strain_id = ':' + strain_id
gu.addDescription(g, strain_id, "This genomic background is unknown. " +
"This is a placeholder background for " + mgiid + ".")
background_type = geno.genoparts['unspecified_genomic_background']
# add it back to the idhash
logger.warn("adding background as internal id: %s %s: %s", strain_key, strain, strain_id)
self.label_hash[strain_id] = strain
geno.addGenomicBackgroundToGenotype(strain_id, mgiid, background_type)
# add this to a hash lookup so we can build the genotype label later
self.geno_bkgd[mgiid] = strain_id
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_gxd_genotype_summary_view(self, limit=None):
"""
Add the genotype internal id to mgiid mapping to the idhashmap. Also, add them as individuals to the graph.
We re-format the label to put the background strain in brackets after the gvc.
We must pass through the file once to get the ids and aggregate the vslcs into a hashmap into the genotype
Triples created:
<genotype id> a GENO:intrinsic_genotype
<genotype id> rdfs:label "<gvc> [bkgd]"
:param limit:
:return:
"""
if self.testMode:
g = self.testgraph
else:
g = self.graph
line_counter = 0
geno_hash = {}
raw = '/'.join((self.rawdir, 'gxd_genotype_summary_view'))
logger.info("building labels for genotypes")
gu = GraphUtils(curie_map.get())
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(accession_key, accid, prefixpart, numericpart, logicaldb_key, object_key, mgitype_key,
private, preferred, createdby_key, modifiedby_key, creation_date, modification_date,
mgiid, subtype, description, short_description) = line.split('\t')
if self.testMode is True:
if int(object_key) not in self.test_keys.get('genotype'):
continue
# add the internal genotype to mgi mapping
self.idhash['genotype'][object_key] = mgiid
if preferred == '1':
d = re.sub('\,', '/', short_description.strip())
if mgiid not in geno_hash:
geno_hash[mgiid] = {'vslcs': [d], 'subtype': subtype, 'key': object_key}
else:
vslcs = geno_hash[mgiid].get('vslcs')
vslcs.append(d)
else:
pass
# TODO what to do with != preferred
if not self.testMode and limit is not None and line_counter > limit:
break
# now, loop through the hash and add the genotypes as individuals
# we add the mgi genotype as a synonym (we generate our own label later)
gutil = Genotype(g)
for gt in geno_hash:
geno = geno_hash.get(gt)
gvc = sorted(geno.get('vslcs'))
label = '; '.join(gvc) + ' [' + geno.get('subtype') + ']'
gutil.addGenotype(gt, None)
gu.addComment(g, gt, self._makeInternalIdentifier('genotype', geno.get('key')))
gu.addSynonym(g, gt, label.strip())
gu.loadProperties(g, gutil.object_properties, gu.OBJPROP)
gu.loadProperties(g, gutil.annotation_properties, gu.ANNOTPROP)
gu.loadAllProperties(g)
return
def _process_all_summary_view(self, limit):
"""
Here, we get the allele definitions: id, label, description, type
We also add the id to this source's global idhash for lookup later
<alleleid> a OWL:NamedIndividual
rdf:label "allele symbol"
dc:description "long allele name"
:param limit:
:return:
"""
gu = GraphUtils(curie_map.get())
if self.testMode:
g = self.testgraph
else:
g = self.graph
line_counter = 0
raw = '/'.join((self.rawdir, 'all_summary_view'))
logger.info("getting alleles and their labels and descriptions")
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(accession_key, accid, prefixpart, numericpart, logicaldb_key, object_key, mgitype_key,
private, preferred, createdby_key, modifiedby_key, creation_date, modification_date,
mgiid, subtype, description, short_description) = line.split('\t')
# NOTE:May want to filter alleles based on the preferred field (preferred = 1) or will get duplicates
# (24288, to be exact... Reduced to 480 if filtered on preferred = 1)
if self.testMode is True:
if int(object_key) not in self.test_keys.get('allele'):
continue
# we are setting the allele type to None, so that we can add the type later
# (since we don't actually know if it's a reference or altered allele)
altype = None # temporary; we'll assign the type later
# If we want to filter on preferred:
if preferred == '1':
# add the allele key to the hash for later lookup
self.idhash['allele'][object_key] = mgiid
# TODO consider not adding the individuals in this one
gu.addIndividualToGraph(g, mgiid, short_description.strip(), altype, description.strip())
self.label_hash[mgiid] = short_description.strip()
# TODO deal with non-preferreds, are these deprecated?
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_all_allele_view(self, limit):
"""
Add the allele as a variant locus (or reference locus if wild-type).
If the marker is specified, we add the link to the marker.
We assume that the MGI ids are available in the idhash, added in all_summary_view.
We add the sequence alteration as a BNode here, if there is a marker. Otherwise, the
allele itself is a sequence alteration.
Triples:
<MGI:allele_id> a GENO:variant_locus
OR GENO:reference_locus
OR GENO:sequence_alteration IF no marker_id specified.
[GENO:has_variant_part OR GENO:has_reference_part] <MGI:marker_id>
GENO:derived_from <MGI:strain_id>
GENO:has_variant_part <_seq_alt_id>
<_seq_alt_id> a GENO:sequence_alteration
derives_from <strain_id>
:param limit:
:return:
"""
# transmission_key -> inheritance? Need to locate related table.
gu = GraphUtils(curie_map.get())
if self.testMode:
g = self.testgraph
else:
g = self.graph
geno = Genotype(g)
line_counter = 0
logger.info("adding alleles, mapping to markers, extracting their sequence alterations")
raw = '/'.join((self.rawdir, 'all_allele_view'))
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(allele_key, marker_key, strain_key, mode_key, allele_type_key, allele_status_key,
transmission_key, collection_key, symbol, name, nomensymbol, iswildtype, isextinct, ismixed,
refs_key, markerallele_status_key,
createdby_key, modifiedby_key, approvedby_key, approval_date, creation_date,
modification_date, markersymbol, term, statusnum, strain, collection,
createdby, modifiedby, approvedby,
markerallele_status, jnum, jnumid, citation, short_citation) = line.split('\t')
# TODO update processing to use this view better - including jnums!
if self.testMode is True:
if int(allele_key) not in self.test_keys.get('allele'):
continue
allele_id = self.idhash['allele'].get(allele_key)
if allele_id is None:
logger.error("what to do! can't find allele_id. skipping %s %s", allele_key, symbol)
continue
if marker_key is not None and marker_key != '':
# we make the assumption here that the markers have already been added to the table
marker_id = self.idhash['marker'].get(marker_key)
if marker_id is None:
logger.error("what to do! can't find marker_id. skipping %s %s", marker_key, symbol)
continue
strain_id = self.idhash['strain'].get(strain_key)
iseqalt_id = self._makeInternalIdentifier('seqalt', allele_key)
if self.nobnodes:
# in test mode, we want to make these identified nodes
iseqalt_id = ':'+iseqalt_id
# for non-wild type alleles:
if iswildtype == '0':
locus_type = geno.genoparts['variant_locus']
locus_rel = geno.properties['is_sequence_variant_instance_of']
# for wild type alleles:
elif iswildtype == '1':
locus_type = geno.genoparts['reference_locus']
locus_rel = geno.properties['is_reference_instance_of']
# add the allele to the wildtype set for lookup later
self.wildtype_alleles.add(allele_id)
else:
locus_rel = None
locus_type = None
gu.addIndividualToGraph(g, allele_id, symbol, locus_type)
gu.makeLeader(g, allele_id)
self.label_hash[allele_id] = symbol
# HACK - if the label of the allele == marker, then make the thing a seq alt
allele_label = self.label_hash.get(allele_id)
marker_label = self.label_hash.get(marker_id)
if allele_label is not None and allele_label == marker_label:
gu.addSameIndividual(g, allele_id, marker_id)
elif marker_id is not None:
# marker_id will be none if the allele is not linked to a marker (as in, it's not mapped to a locus)
geno.addAlleleOfGene(allele_id, marker_id, locus_rel)
# sequence alteration in strain
if iswildtype == '0':
sa_label = symbol
sa_id = iseqalt_id
if marker_key is not None and marker_key != '':
# sequence alteration has label reformatted(symbol)
if re.match(".*<.*>.*", symbol):
sa_label = re.sub(".*<", "<", symbol)
elif re.match("\+", symbol):
# TODO: Check to see if this is the proper handling, as while symbol is just +,
# TODO (con't) marker symbol has entries without any <+>.
sa_label = '<+>'
geno.addSequenceAlterationToVariantLocus(iseqalt_id, allele_id)
else:
# make the sequence alteration == allele
sa_id = allele_id
# else this will end up adding the non-located transgenes as sequence alterations also
# removing the < and > from sa
sa_label = re.sub('[\<\>]', '', sa_label)
# gu.addIndividualToGraph(g,sa_id,sa_label,None,name)
geno.addSequenceAlteration(sa_id, sa_label, None, name)
self.label_hash[sa_id] = sa_label
if strain_id is not None:
geno.addSequenceDerivesFrom(allele_id, strain_id)
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_gxd_allele_pair_view(self, limit):
"""
This assumes that the genotype and alleles have already been added to the id hashmap.
We use the Genotype methods to add all the parts we need.
Triples added:
<genotype_id> has_part <vslc>
<vslc> has_part <allele1>
<vslc> has_part <allele2>
<vslc> has_zygosity <zygosity>
:param limit:
:return:
"""
gu = GraphUtils(curie_map.get())
if self.testMode:
g = self.testgraph
else:
g = self.graph
line_counter = 0
geno = Genotype(g)
raw = '/'.join((self.rawdir, 'gxd_allelepair_view'))
logger.info("processing allele pairs (VSLCs) for genotypes")
geno_hash = {}
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(allelepair_key, genotype_key, allele_key_1, allele_key_2, marker_key,
mutantcellline_key_1, mutantcellline_key_2, pairstate_key, compound_key, sequencenum,
createdby_key, modifiedby_key, creation_date, modification_date,
symbol, chromosome, allele1, allele2, allelestate, compound) = line.split('\t')
# NOTE: symbol = gene/marker,
# allele1 + allele2 = VSLC,
# allele1/allele2 = variant locus,
# allelestate = zygosity
# FIXME Need to handle alleles not in the *<*> format, incl gene traps, induced mut, & transgenics
if self.testMode is True:
if int(genotype_key) not in self.test_keys.get('genotype'):
continue
genotype_id = self.idhash['genotype'].get(genotype_key)
if genotype_id not in geno_hash:
geno_hash[genotype_id] = set()
if genotype_id is None:
logger.error("genotype_id not found for key %s; skipping", genotype_key)
continue
allele1_id = self.idhash['allele'].get(allele_key_1)
allele2_id = self.idhash['allele'].get(allele_key_2)
# Need to map the allelestate to a zygosity term
zygosity_id = self._map_zygosity(allelestate)
ivslc_id = self._makeInternalIdentifier('vslc', allelepair_key)
if self.nobnodes:
# make this a real id in test mode
ivslc_id = ':'+ivslc_id
geno_hash[genotype_id].add(ivslc_id)
# TODO: VSLC label likely needs processing similar to the processing in the all_allele_view
# FIXME: handle null alleles
vslc_label = allele1+'/'
if allele2_id is None:
if zygosity_id in [geno.zygosity['hemizygous'], geno.zygosity['hemizygous-x'],
geno.zygosity['hemizygous-y']]:
vslc_label += '0'
elif zygosity_id == geno.zygosity['heterozygous']:
vslc_label += '+'
elif zygosity_id == geno.zygosity['indeterminate']:
vslc_label += '?'
elif zygosity_id == geno.zygosity['homozygous']:
vslc_label += allele1 # we shouldn't get here, but for testing this is handy
else:
logger.info("A different kind of zygosity is found: %s", zygosity_id)
vslc_label += '?'
else:
vslc_label += allele2
gu.addIndividualToGraph(g, ivslc_id, vslc_label, geno.genoparts['variant_single_locus_complement'])
self.label_hash[ivslc_id] = vslc_label
rel1 = rel2 = geno.object_properties['has_alternate_part']
if allele1_id in self.wildtype_alleles:
rel1 = geno.object_properties['has_reference_part']
if allele2_id in self.wildtype_alleles:
rel2 = geno.object_properties['has_reference_part']
geno.addPartsToVSLC(ivslc_id, allele1_id, allele2_id, zygosity_id, rel1, rel2)
# if genotype_id not in geno_hash:
# geno_hash[genotype_id] = [vslc_label]
# else:
# geno_hash[genotype_id] += [vslc_label]
if not self.testMode and limit is not None and line_counter > limit:
break
# build the gvc and the genotype label
for gt in geno_hash.keys():
if gt is None: # not sure why, but sometimes this is the case
continue
vslcs = sorted(list(geno_hash[gt]))
gvc_label = None
if len(vslcs) > 1:
gvc_id = re.sub('_', '', ('-'.join(vslcs)))
gvc_id = re.sub(':', '', gvc_id)
gvc_id = '_'+gvc_id
if self.nobnodes:
gvc_id = ':'+gvc_id
vslc_labels = []
for v in vslcs:
vslc_labels.append(self.label_hash[v])
gvc_label = '; '.join(vslc_labels)
gu.addIndividualToGraph(g, gvc_id, gvc_label, geno.genoparts['genomic_variation_complement'])
self.label_hash[gvc_id] = gvc_label
for v in vslcs:
geno.addParts(v, gvc_id, geno.object_properties['has_alternate_part'])
geno.addVSLCtoParent(v, gvc_id)
geno.addParts(gvc_id, gt, geno.object_properties['has_alternate_part'])
elif len(vslcs) == 1:
gvc_id = vslcs[0]
gvc_label = self.label_hash[gvc_id]
# type the VSLC as also a GVC
gu.addIndividualToGraph(g, gvc_id, gvc_label, geno.genoparts['genomic_variation_complement'])
geno.addVSLCtoParent(gvc_id, gt)
else:
logger.info("No VSLCs for %s", gt)
# make the genotype label = gvc + background
bkgd_id = self.geno_bkgd.get(gt)
if bkgd_id is not None:
bkgd_label = self.label_hash.get(bkgd_id)
if bkgd_label is None:
bkgd_label = bkgd_id # just in case
else:
bkgd_label = 'n.s.'
if gvc_label is not None:
genotype_label = gvc_label + ' ['+bkgd_label+']'
else:
genotype_label = '['+bkgd_label+']'
gu.addIndividualToGraph(g, gt, genotype_label)
self.label_hash[gt] = genotype_label
return
def _process_all_allele_mutation_view(self, limit):
"""
This fetches the mutation type for the alleles, and maps them to the sequence alteration.
Note that we create a BNode for the sequence alteration because it isn't publically identified.
<sequence alteration id> a <SO:mutation_type>
:param limit:
:return:
"""
gu = GraphUtils(curie_map.get())
if self.testMode:
g = self.testgraph
else:
g = self.graph
line_counter = 0
raw = '/'.join((self.rawdir, 'all_allele_mutation_view'))
logger.info("getting mutation types for sequence alterations")
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(allele_key, mutation_key, creation_date, modification_date, mutation) = line.split('\t')
iseqalt_id = self._makeInternalIdentifier('seqalt', allele_key)
if self.nobnodes is True:
if self.testMode and int(allele_key) not in self.test_keys.get('allele'):
continue
iseqalt_id = ':'+iseqalt_id
# TODO we might need to map the seq alteration to the MGI id for unlocated things; need to use hashmap
# map the sequence_alteration_type
seq_alt_type_id = self._map_seq_alt_type(mutation)
gu.addIndividualToGraph(g, iseqalt_id, None, seq_alt_type_id)
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_voc_annot_view(self, limit):
"""
This MGI table represents associations between things.
We currently filter this table on abnormal Genotype-Phenotype associations, but may be expanded in the future.
We add the internal annotation id to the idhashmap. It is expected that the genotypes have already
been added to the idhash
:param limit:
:return:
"""
# TODO also get Strain/Attributes (annottypekey = 1000)
# TODO what is Phenotype (Derived) vs non-derived? (annottypekey = 1015)
# TODO is evidence in this table? what is the evidence vocab key?
gu = GraphUtils(curie_map.get())
if self.testMode:
g = self.testgraph
else:
g = self.graph
line_counter = 0
logger.info("getting G2P associations")
raw = '/'.join((self.rawdir, 'voc_annot_view'))
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
(annot_key, annot_type_key, object_key, term_key, qualifier_key,
creation_date, modification_date, qualifier, term, sequence_num,
accid, logicaldb_key, vocab_key, mgi_type_key, evidence_vocab_key, anot_type) = line.split('\t')
if self.testMode is True:
if int(annot_key) not in self.test_keys.get('annot'):
continue
# iassoc_id = self._makeInternalIdentifier('annot', annot_key)
# assoc_id = self.make_id(iassoc_id)
assoc_id = None
if annot_type_key == '1002': # Mammalian Phenotype/Genotype are curated G2P assoc
line_counter += 1
# TODO add NOT annotations
# skip 'normal'
if qualifier == 'norm':
logger.info("found normal phenotype: %s", term)
continue
# We expect the label for the phenotype to be taken care of elsewhere
gu.addClassToGraph(g, accid, None)
genotype_id = self.idhash['genotype'].get(object_key)
if genotype_id is None:
logger.error("can't find genotype id for %s", object_key)
else:
# add the association
assoc = G2PAssoc(self.name, genotype_id, accid)
assoc.add_association_to_graph(g)
assoc_id = assoc.get_association_id()
elif annot_type_key == '1005': # OMIM/Genotype are disease-models
if qualifier_key == '1614157': # skip NOT annotations for now FIXME
continue
genotype_id = self.idhash['genotype'].get(object_key)
omim_id = 'OMIM:'+str(accid)
if genotype_id is None:
logger.error("can't find genotype id for %s", object_key)
else:
# add the association
assoc = Assoc(self.name)
assoc.set_subject(genotype_id)
assoc.set_object(omim_id)
assoc.set_relationship(gu.object_properties['model_of'])
assoc.add_association_to_graph(g)
assoc_id = assoc.get_association_id()
elif annot_type_key == '1011':
# marker category == type
marker_id = self.idhash['marker'].get(object_key)
term_id = self._map_marker_category(str(term_key))
# note that the accid here is an internal mouse cv term, and we don't use it.
if term_id is not None and marker_id is not None:
gu.addType(g, marker_id, term_id)
elif annot_type_key == '1012': # allele/Disease
allele_id = self.idhash['allele'].get(object_key)
omim_id = 'OMIM:'+str(accid)
if allele_id is None:
logger.error("can't find genotype id for %s", object_key)
else:
# add the association
assoc = Assoc(self.name)
assoc.set_subject(allele_id)
assoc.set_object(omim_id)
assoc.set_relationship(gu.object_properties['model_of'])
assoc.add_association_to_graph(g)
assoc_id = assoc.get_association_id()
if assoc_id is not None:
# add the assoc to the hashmap (using the monarch id)
self.idhash['annot'][annot_key] = assoc_id
gu.addComment(g, assoc_id, "annot_key:"+annot_key)
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_voc_evidence_view(self, limit):
"""
Here we fetch the evidence (code and publication) for the associations.
The evidence codes are mapped from the standard GO codes to ECO.
J numbers are added for publications.
We will only add the evidence if the annotation is in our idhash.
Triples:
<annot_id> dc:evidence <evidence_id>
<pub_id> a owl:NamedIndividual
<annot_id> dc:source <pub_id>
:param limit:
:return:
"""
if self.testMode:
g = self.testgraph
else:
g = self.graph
gu = GraphUtils(curie_map.get())
line_counter = 0
logger.info("getting evidence and pubs for annotations")
raw = '/'.join((self.rawdir, 'voc_evidence_view'))
with open(raw, 'r') as f:
f.readline() # read the header row; skip
for line in f:
line_counter += 1
(annot_evidence_key, annot_key, evidence_term_key, refs_key, inferred_from,
created_by_key, modified_by_key, creation_date, modification_date,
evidence_code, evidence_seq_num, jnumid, jnum, short_citation,
created_by, modified_by) = line.split('\t')
if self.testMode is True:
if int(annot_key) not in self.test_keys.get('annot'):
continue
# add the association id to map to the evidence key (to attach the right note to the right assn)
self.idhash['notes'][annot_evidence_key] = annot_key
assoc_id = self.idhash['annot'].get(annot_key)
if assoc_id is None:
# assume that we only want to add the evidence/source for annots that we have in our db
continue
evidence_id = self._map_evidence_id(evidence_code)
r = Reference(jnumid)
r.addRefToGraph(g)
# add the ECO and citation information to the annot
gu.addTriple(g, assoc_id, Assoc.object_properties['has_evidence'], evidence_id)
gu.addTriple(g, assoc_id, Assoc.object_properties['has_source'], jnumid)
if not self.testMode and limit is not None and line_counter > limit:
break
return
def _process_bib_acc_view(self, limit):
"""
This traverses the table twice:
once to look up the internal key to J number mapping for the id hashmap
then again to make the equivalences. All internal keys have both a J and MGI identifier.
This will make equivalences between the different pub ids
Triples:
<pub_id> a owl:NamedIndividual
<other_pub_id> a owl:NamedIndividual