Source

orange-bioinformatics / orangecontrib / bio / ppi.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
from __future__ import absolute_import

import os
import urllib2
import shutil
import gzip
import zipfile
import xml.dom.minidom as minidom
import csv
import sqlite3
import errno

from StringIO import StringIO
from collections import defaultdict, namedtuple
from operator import itemgetter

from Orange.utils import serverfiles
from Orange.utils import ConsoleProgressBar, wget

from . import taxonomy

from .taxonomy import pickled_cache


def mkdir_p(path, mode=0o777):
    try:
        os.makedirs(path, mode)
    except OSError as err:
        if err.errno == errno.EEXIST:
            pass
        else:
            raise


class PPIDatabase(object):
    """
    A general interface for protein-protein interaction database access.

    An example::

        >>> ppidb = MySuperPPIDatabase()
        >>> ppidb.organisms() # List all organisms (taxids)
        ['...

        >>> ppidb.ids() # List all protein ids
        ['...

        >>> ppidb.ids(taxid="9606") # List all human protein ids.
        ['...

        >>> ppidb.links() # List all links
        [('...

    """
    def __init__(self):
        pass

    def organisms(self):
        """
        Return all organism ncbi taxonomy ids contained in this database.
        """
        raise NotImplementedError

    def ids(self, taxid=None):
        """
        Return a list of all protein ids. If `taxid` (as returned by
        `organisms()`) is not ``None`` limit the results to ids to
        this organism only.

        """
        raise NotImplementedError

    def synonyms(self, id):
        """
        Return a list of synonyms for primary `id` (as returned by `ids`).
        """
        raise NotImplementedError

    def all_edges(self, taxid=None):
        """
        Return a list of all edges. If `taxid` is not ``None`` return the
        edges for this organism only.

        """
        raise NotImplementedError

    def edges(self, id1, id2=None):
        """
        Return a list of all edges (a list of 3-tuples (id1, id2, score)).
        """
        raise NotImplementedError

    def all_edges_annotated(self, taxid=None):
        """
        Return a list of all edges annotated. If taxid is not None
        return the edges for this organism only.

        """
        res = []
        for id in self.ids(taxid):
            res.extend(self.edges_annotated(id))
        return res

    def edges_annotated(self, id=None):
        """
        Return a list of all edges annotated.
        """
        raise NotImplementedError

    def search_id(self, name, taxid=None):
        """
        Search the database for protein name. Return a list of matching
        primary ids. Use `taxid` to limit the results to a single organism.

        """
        raise NotImplementedError

    def extract_network(self, ids):
        """
        """
        from Orange import network

        graph = network.Graph()
        for id in ids:
            graph.add_node(id, synonyms=",".join(self.synonyms(id)))

        for id in ids:
            edges = self.edges(id)

            for id1, id2, score in edges:
                graph.add_edge(id1, id2, weight=score)

        return graph

    @classmethod
    def download_data(self):
        """
        Download the latest PPI data for local work.
        """
        raise NotImplementedError


class BioGRID(PPIDatabase):
    """
    Access `BioGRID <http://thebiogrid.org>`_ PPI data.

    Example ::

        >>> biogrid = BioGRID()
        >>> print biogrid.organism() # Print a list of all organism ncbi taxis in BioGRID
        [u'10090',...

        >>> print biogrid.ids(taxid="9606") # Print a set of all human protein ids
        [u'110004'

        >>> print biogrid.synonyms("110004") # Print a list of all synonyms for protein id '110004' as reported by BioGRID
        [u'3803', u'CU464060.2', u'CD158b', u'p58.2', u'CD158B1', u'NKAT6']

        >>>

    """

    SCHEMA = [
        ("links",
         """\
         biogrid_interaction_id text,
         biogrid_id_interactor_a text,
         biogrid_id_interactor_b text,
         experimental_system text,
         experimental_system_type text,
         author text,
         pubmed_id text,
         throughput text,
         score real,
         modification text,
         phenotypes text,
         qualifications text,
         tags text,
         source_database text
         """),
        ("proteins",
         """\
         biogrid_id_interactor text,
         entrez_gene_interactor text,
         systematic_name_interactor text,
         official_symbol_interactor text,
         synonyms_interactor text,
         organism_interactor text,
         """)
    ]

    VERSION = "2.0"

    # All column names in the BioGRID tab2 source table.
    FIELDS = ['biogrid_interaction_id',
              'entrez_gene_interactor_a',
              'entrez_gene_interactor_b',
              'biogrid_id_interactor_a',
              'biogrid_id_interactor_b',
              'systematic_name_interactor_a',
              'systematic_name_interactor_b',
              'official_symbol_interactor_a',
              'official_symbol_interactor_b',
              'synonyms_interactor_a',
              'synonyms_interactor_b',
              'experimental_system',
              'experimental_system_type',
              'author',
              'pubmed_id',
              'organism_interactor_a',
              'organism_interactor_b',
              'throughput',
              'score',
              'modification',
              'phenotypes',
              'qualifications',
              'tags',
              'source_database'
              ]

    DOMAIN = "PPI"
    SERVER_FILE = "BIOGRID-ALL.sqlite"

    def __init__(self):
        self.filename = serverfiles.localpath_download(
            self.DOMAIN, self.SERVER_FILE)

        # assert version matches
        self.db = sqlite3.connect(self.filename)
        self.init_db_index()

    def organisms(self):
        cur = self.db.execute("select distinct organism_interactor \n"
                              "from proteins")
        return cur.fetchall()

    def ids(self, taxid=None):
        """
        Return a list of all protein ids (biogrid_id_interactors).
        If `taxid` is not None limit the results to ids from this organism
        only.

        """
        if taxid is None:
            cur = self.db.execute("""\
                select biogrid_id_interactor
                from proteins""")
        else:
            cur = self.db.execute("""\
                select biogrid_id_interactor
                from proteins
                where organism_interactor=?""",
                (taxid,))

        return [t[0] for t in cur.fetchall()]

    def synonyms(self, id):
        """
        Return a list of synonyms for primary `id`.
        """
        cur = self.db.execute("""\
            select entrez_gene_interactor,
                   systematic_name_interactor,
                   official_symbol_interactor,
                   synonyms_interactor
            from proteins
            where biogrid_id_interactor=?""",
            (id,))
        rec = cur.fetchone()
        if rec:
            synonyms = list(rec[:-1]) + \
                       (rec[-1].split("|") if rec[-1] is not None else [])
            return [s for s in synonyms if s is not None]
        else:
            return []

    def all_edges(self, taxid=None):
        """
        Return a list of all edges. If taxid is not None return the
        edges for this organism only.

        """
        if taxid is not None:
            cur = self.db.execute("""\
                select biogrid_id_interactor_a, biogrid_id_interactor_a, score
                from links left join proteins on
                    biogrid_id_interactor_a=biogrid_id_interactor or
                    biogrid_id_interactor_b=biogrid_id_interactor
                where organism_interactor=?
            """, (taxid,))
        else:
            cur = self.db.execute("""\
                select biogrid_id_interactor_a, biogrid_id_interactor_a, score
                from links
            """)
        edges = cur.fetchall()
        return edges

    def edges(self, id):
        """
        Return a list of all interactions where id is a participant
        (a list of 3-tuples (id_a, id_b, score)).

        """

        cur = self.db.execute("""\
            select biogrid_id_interactor_a, biogrid_id_interactor_b, score
            from links
            where biogrid_id_interactor_a=? or biogrid_id_interactor_b=?
        """, (id, id))
        return cur.fetchall()

    def all_edges_annotated(self, taxid=None):
        """
        Return a list of all edges annotated. If taxid is not None
        return the edges for this organism only.

        """
        if taxid is not None:
            cur = self.db.execute("""\
                select *
                from links left join proteins on
                    biogrid_id_interactor_a=biogrid_id_interactor or
                    biogrid_id_interactor_b=biogrid_id_interactor
                where organism_interactor=?
            """, (taxid,))
        else:
            cur = self.db.execute("""\
                select *
                from links
            """)
        edges = cur.fetchall()
        return edges

    def edges_annotated(self, id):
        """ Return a list of all links
        """
        cur = self.db.execute("""\
            select *
            from links
            where biogrid_id_interactor_a=? or biogrid_id_interactor_b=?
        """, (id, id))
        return cur.fetchall()

    def search_id(self, name, taxid=None):
        """
        Search the database for protein name. Return a list of matching
        primary ids. Use `taxid` to limit the results to a single organism.

        """
        # TODO: synonyms_interactor can contain multiple synonyms
        # (should create an indexed table of synonyms)
        if taxid is None:
            cur = self.db.execute("""\
                select biogrid_id_interactor
                from proteins
                where (biogrid_id_interactor=? or
                       entrez_gene_interactor=? or
                       systematic_name_interactor=? or
                       official_symbol_interactor=? or
                       synonyms_interactor=?)
            """, ((name,) * 5))
        else:
            cur = self.db.execute("""\
                select biogrid_id_interactor
                from proteins
                where (biogrid_id_interactor=? or
                       entrez_gene_interactor=? or
                       systematic_name_interactor=? or
                       official_symbol_interactor=? or
                       synonyms_interactor=?)
                      and organism_interactor=?
            """, ((name,) * 5) + (taxid,))
        res = map(itemgetter(0), cur)
        return res

    @classmethod
    def download_data(cls, address):
        """
        Pass the address of the latest BIOGRID-ALL release (in tab2 format).
        """
        stream = urllib2.urlopen(address)
        stream = StringIO(stream.read())
        zfile = zipfile.ZipFile(stream)
        # Expecting only one file.
        filename = zfile.namelist()[0]

        filepath = serverfiles.localpath("PPI", "BIOGRID-ALL.tab2")
        mkdir_p(os.path.dirname(filepath))

        with open(filepath, "wb") as f:
            shutil.copyfileobj(zfile.open(filename, "r"), f)

        cls.init_db(filepath)

    @classmethod
    def init_db(cls, filepath):
        """
        Initialize the sqlite data base from a BIOGRID-ALL.*tab2.txt file
        format.

        """
        dirname = os.path.dirname(filepath)
        rows = csv.reader(open(filepath, "rb"), delimiter="\t")
        rows.next()  # read the header line

        con = sqlite3.connect(os.path.join(dirname, BioGRID.SERVER_FILE))
        con.execute("drop table if exists links")  # Drop old table
        con.execute("drop table if exists proteins")  # Drop old table

        con.execute("""\
            create table links (
                biogrid_interaction_id text,
                biogrid_id_interactor_a text,
                biogrid_id_interactor_b text,
                experimental_system text,
                experimental_system_type text,
                author text,
                pubmed_id text,
                throughput text,
                score real,
                modification text,
                phenotypes text,
                qualifications text,
                tags text,
                source_database text
            )""")

        con.execute("""\
            create table proteins (
                biogrid_id_interactor text,
                entrez_gene_interactor text,
                systematic_name_interactor text,
                official_symbol_interactor text,
                synonyms_interactor text,
                organism_interactor text
            )""")

        proteins = {}

        # Values that go in the links table
        link_indices = [0, 3, 4, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 23]
        # Values that go in the proteins table
        interactor_a_indices = [3, 1, 5, 7, 9, 15]
        # Values that go in the proteins table
        interactor_b_indices = [4, 2, 6, 8, 10, 16]

        def to_none(val):
            return None if val == "-" else val

        def processlinks(rowiter):
            for row in rowiter:
                fields = map(to_none, row)
                yield [fields[i] for i in link_indices]

                interactor_a = [fields[i] for i in interactor_a_indices]
                interactor_b = [fields[i] for i in interactor_b_indices]
                proteins[interactor_a[0]] = interactor_a
                proteins[interactor_b[0]] = interactor_b

        con.executemany("""
            insert into links values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, processlinks(rows))

        con.executemany("""\
            insert into proteins values (?, ?, ?, ?, ?, ?)
            """, proteins.itervalues())
        con.commit()
        con.close()

    def init_db_index(self):
        """
        Will create an indexes (if not already present) in the database
        for faster searching by primary ids.

        """
        self.db.execute("""\
        create index if not exists index_on_biogrid_id_interactor_a
           on links (biogrid_id_interactor_a)
        """)
        self.db.execute("""\
        create index if not exists index_on_biogrid_id_interactor_b
           on links (biogrid_id_interactor_b)
        """)
        self.db.execute("""\
        create index if not exists index_on_biogrid_id_interactor
           on proteins (biogrid_id_interactor)
        """)


STRINGInteraction = namedtuple(
    "STRINGInteraciton",
    ["protein_id1",
     "protein_id2",
     "combined_score",
     "mode",
     "action",
     "score"]
)


class STRING(PPIDatabase):
    """
    Access `STRING <http://www.string-db.org/>`_ PPI database.
    """

    DATABASE_SCHEMA = """\
    Database schema
    ---------------
    table `links`:
        - `protein_id1`: id (text)
        - `protein_id2`: id (text)
        - `score`: combined score (int)

    table `actions`:
        - `protein_id1`: id (text)
        - `protein_id2`: id (text)
        - `mode`: mode (text)
        - `action`: action type (text)
        - `score`: action score (int)

    table `proteins`:
        - `protein_id`: protein id in STRING (text) (in the form of {taxid}.{name})
        - `taxid`: organism taxid (text)

    table `aliases`:
        - `protein_id: id (text)
        - `alias`: protein alias (text)
        - `source`: protein alias source (text)

    """
    DOMAIN = "PPI"
    FILENAME = "string-protein.sqlite"
    VERSION = "2.0"

    # Mapping from taxonomy.common_taxids() to taxids in STRING.

    TAXID_MAP = {"352472": "44689",  # Dictyostelium discoideum
                 "562": None,
                 "2104": "272634",   # Mycoplasma pneumoniae M129
                 "4530": "39947",    # Oryza sativa Japonica Group
                 "4754": None,
                 "8355": None,
                 "4577": None
                 }

    def __init__(self):
        self.filename = serverfiles.localpath_download(
            self.DOMAIN, self.FILENAME
        )
        self.db = sqlite3.connect(self.filename)

    @classmethod
    def common_taxids(cls):
        common = taxonomy.common_taxids()
        common = [cls.TAXID_MAP.get(id, id) for id in common]
        return filter(None, common)

    def organisms(self):
        """
        Return all organism taxids contained in this database.
        """
        cur = self.db.execute("select distinct taxid from proteins")
        return [r[0] for r in cur.fetchall()]

    def ids(self, taxid=None):
        """
        Return a list of all protein ids. If `taxid` is not None limit
        the results to ids from this organism only.

        """
        if taxid is not None:
            cur = self.db.execute("""\
                select protein_id
                from proteins
                where taxid=?
                """, (taxid,))
        else:
            cur = self.db.execute("""\
                select protein_id
                from proteins
                """)
        return [r[0] for r in cur.fetchall()]

    def synonyms(self, id):
        """
        Return a list of synonyms for primary `id` as reported by STRING
        (proteins.aliases.{version}.txt file)
        """
        cur = self.db.execute("""\
            select alias
            from aliases
            where protein_id=?
            """, (id,))
        res = cur.fetchall()
        return [r[0] for r in res]

    def synonyms_with_source(self, id):
        """
        Return a list of synonyms for primary `id` along with its
        source as reported by STRING (proteins.aliases.{version}.txt file)

        """
        cur = self.db.execute("""\
            select alias, source
            from aliases
            where protein_id=?
            """, (id,))
        res = cur.fetchall()
        return [(syn, set(source.split(" "))) \
                for syn, source in res]

    def all_edges(self, taxid=None):
        """
        Return a list of all edges. If taxid is not None return the edges
        for this organism only.

        .. note:: This may take some time (and memory).

        """
        if taxid is not None:
            cur = self.db.execute("""\
                select links.protein_id1, links.protein_id2, score
                from links join proteins on
                    links.protein_id1=proteins.protein_id
                where taxid=?
                """, (taxid,))
        else:
            cur = self.db.execute("""\
                select protein_id1, protein_id1, score
                from links
                """)
        return cur.fetchall()

    def edges(self, id):
        """
        Return a list of all edges (a list of 3-tuples (id1, id2, score)).
        """
        cur = self.db.execute("""\
            select protein_id1, protein_id2, score
            from links
            where protein_id1=?
            """, (id,))
        return cur.fetchall()

    def all_edges_annotated(self, taxid=None):
        res = []
        for id in self.ids(taxid):
            res.extend(self.edges_annotated(id))
        return res

    def edges_annotated(self, id):
        cur = self.db.execute("""\
            select links.protein_id1, links.protein_id2, links.score,
                   actions.action, actions.mode, actions.score
            from links left join actions on
                   links.protein_id1=actions.protein_id1 and
                   links.protein_id2=actions.protein_id2
            where links.protein_id1=?
        """, (id,))
        return map(STRINGInteraction._make, cur.fetchall())

    def search_id(self, name, taxid=None):
        if taxid is None:
            cur = self.db.execute("""\
                select proteins.protein_id
                from proteins natural join aliases
                where aliases.alias=?
            """, (name,))
        else:
            cur = self.db.execute("""\
                select proteins.protein_id
                from proteins natural join aliases
                where aliases.alias=? and proteins.taxid=?
            """, (name, taxid))
        return map(itemgetter(0), cur)

    @classmethod
    def download_data(cls, version, taxids=None):
        """
        Download the  PPI data for local work (this may take some time).
        Pass the version of the  STRING release e.g. v8.3.
        The resulting sqlite database will only contain the protein
        interactions for `taxids` (if None taxonomy.common_taxids() will
        be used).

        """
        dir = serverfiles.localpath("PPI")

        base_url = "http://www.string-db.org/newstring_download/"
        links = "protein.links.{version}.txt.gz".format(version=version)
        actions = "protein.actions.{version}.txt.gz".format(version=version)
        aliases = "protein.aliases.{version}.txt.gz".format(version=version)

        def wgeti(f, dir, progress):
            if not os.path.exists(os.path.join(dir, f)):
                print "Downloading:", f
                wget(base_url + f, dir, progress=progress)
            else:
                print "Already downloaded - skiping:", f

        wgeti(links, dir, progress=True)
        wgeti(actions, dir, progress=True)
        wgeti(aliases, dir, progress=True)

        cls.init_db(version, taxids)

    @classmethod
    def init_db(cls, version, taxids=None):
        """
        Initialize the sqlite3 data base. `version` must contain a
        STRING release version e.g 'v8.3'. If `taxids` is not `None` it
        must contain a list of tax-ids in the STRING database for which
        to extract the interactions for.

        """
        def counter():
            i = 0
            while True:
                yield i
                i += 1

        dir = serverfiles.localpath(cls.DOMAIN)

        links_filename = os.path.join(
            dir, "protein.links.{version}.txt.gz".format(version=version)
        )
        actions_filename = os.path.join(
            dir, "protein.actions.{version}.txt.gz".format(version=version)
        )
        aliases_filename = os.path.join(
            dir, "protein.aliases.{version}.txt.gz".format(version=version)
        )

        links_fileobj = open(links_filename, "rb")
        actions_fileobj = open(actions_filename, "rb")
        aliases_fileobj = open(aliases_filename, "rb")

        links_file = gzip.GzipFile(fileobj=links_fileobj)
        actions_file = gzip.GzipFile(fileobj=actions_fileobj)
        aliases_file = gzip.GzipFile(fileobj=aliases_fileobj)

        progress = ConsoleProgressBar("Processing links:")
        progress(0.0)
        filesize = os.stat(links_filename).st_size

        if taxids:
            taxids = set(taxids)
        else:
            taxids = set(cls.common_taxids())

        con = sqlite3.connect(
            serverfiles.localpath(cls.DOMAIN, cls.FILENAME))

        with con:
            con.execute("drop table if exists links")
            con.execute("drop table if exists proteins")
            con.execute("drop table if exists actions")
            con.execute("drop table if exists aliases")

            con.execute("""
                create table links
                    (protein_id1 text, protein_id2 text, score int)
            """)

            con.execute("""
                create table proteins
                    (protein_id text, taxid text)
            """)

            con.execute("""
                create table actions
                    (protein_id1 text, protein_id2 text, mode text,
                     action text, score int)
            """)

            con.execute("""
                create table aliases
                    (protein_id text, alias text, source text)
            """)

            links_file.readline()  # read the header

            reader = csv.reader(links_file, delimiter=" ")

            def read_links(reader, taxids, progress):
                split = str.split
                for i, (p1, p2, score) in enumerate(reader):
                    if split(p1, ".", 1)[0] in taxids and \
                            split(p2, ".", 1)[0] in taxids:
                        yield intern(p1), intern(p2), int(score)

                    if i % 1000000 == 0:
                        # Update the progress every 1000000 lines
                        progress(100.0 * links_fileobj.tell() / filesize)

            con.executemany("insert into links values (?, ?, ?)",
                            read_links(reader, taxids, progress))

            progress.finish()

            proteins = con.execute("select distinct protein_id1 from links")
            proteins = [res[0] for res in proteins]
            progress = ConsoleProgressBar("Processing proteins:")

            def protein_taxids(proteins):
                protein_taxids = []
                for i, prot in enumerate(proteins):
                    taxid = prot.split(".", 1)[0]
                    protein_taxids.append((prot, taxid))
                    if i % 1000 == 0:
                        progress(100.0 * i / len(proteins))
                protein_taxids.sort()
                return protein_taxids

            con.executemany("insert into proteins values (?, ?)",
                            protein_taxids(proteins))

            progress.finish()

            filesize = os.stat(actions_filename).st_size

            actions_file.readline()  # read header

            progress = ConsoleProgressBar("Processing actions:")
            reader = csv.reader(actions_file, delimiter="\t")

            def read_actions(reader):
                split = str.split
                for i, (p1, p2, mode, action, a_is_acting, score) in \
                        enumerate(reader):
                    if split(p1, ".", 1)[0] in taxids and \
                            split(p2, ".", 1)[0] in taxids:
                        yield intern(p1), intern(p2), mode, action, int(score)

                    if i % 10000 == 0:
                        progress(100.0 * actions_fileobj.tell() / filesize)

            con.executemany("insert into actions values (?, ?, ?, ?, ?)",
                            read_actions(reader))

            progress.finish()

            filesize = os.stat(aliases_filename).st_size
            aliases_file.readline()  # read header

            progress = ConsoleProgressBar("Processing aliases:")

            reader = csv.reader(aliases_file, delimiter="\t")

            def read_aliases(reader, taxids, progress):
                for i, (taxid, name, alias, source) in enumerate(reader):
                    if taxid in taxids:
                        yield (".".join([taxid, name]),
                               alias.decode("utf-8", errors="ignore"),
                               source.decode("utf-8", errors="ignore"))
                    if i % 10000 == 0:
                        progress(100.0 * aliases_fileobj.tell() / filesize)

            con.executemany("insert into aliases values (?, ?, ?)",
                            read_aliases(reader, taxids, progress))

            progress.finish()

            print "Indexing the database"

            con.execute("""\
            create index if not exists index_link_protein_id1
                on links (protein_id1)""")

            con.execute("""\
                create index if not exists index_action_protein_id1
                    on actions (protein_id1)""")

            con.execute("""\
                create index if not exists index_proteins_id
                    on proteins (protein_id)""")

            con.execute("""\
                create index if not exists index_taxids
                    on proteins (taxid)""")

            con.execute("""\
                create index if not exists index_aliases_id
                    on aliases (protein_id)""")

            con.execute("""\
                create index if not exists index_aliases_alias
                    on aliases (alias)""")

            con.executescript("""
                DROP TABLE IF EXISTS version;

                CREATE TABLE version (
                     string_version text,
                     api_version text
                );""")

            con.execute("""
                INSERT INTO version
                VALUES (?, ?)""", (version, cls.VERSION))


STRINGDetailedInteraction = namedtuple(
    "STRINGDetailedInteraction",
    ["protein_id1",
     "protein_id2",
     "combined_score",
     "mode",
     "action",
     "score",
     "neighborhood",
     "fusion",
     "cooccurence",
     "coexpression",
     "experimental",
     "database",
     "textmining"]
)


class STRINGDetailed(STRING):
    """
    Access `STRING <http://www.string-db.org/>`_ PPI database.
    This class also allows access to subscores per channel.

    .. note::
        This data is released under a `Creative Commons
        Attribution-Noncommercial-Share Alike 3.0 License
        <http://creativecommons.org/licenses/by-nc-sa/3.0/>`_.

        If you want to use this data for commercial purposes you must
        get a license from STRING.

    """

    DATABASE_SCHEMA = """\
    DATABASE SCHEMA
    ===============

    table `evidence`:
        - `protein_id1`: protein id (text)
        - `protein_id2`: protein id (text)
        - `neighborhood`: score (int)
        - `fusion`: score (int)
        - `cooccurence`: score (int)
        - `coexpression`: score (int)
        - `experimental`: score (int)
        - `database`: score (int)
        - `textmining`: score (int)

    """
    FILENAME_DETAILED = "string-protein-detailed.sqlite"

    def __init__(self):
        STRING.__init__(self)
        db_file = serverfiles.localpath(self.DOMAIN, self.FILENAME)
        db_detailed_file = serverfiles.localpath_download(
            self.DOMAIN, self.FILENAME_DETAILED
        )

        self.db_detailed = sqlite3.connect(db_detailed_file)
        self.db_detailed.execute("ATTACH DATABASE ? as string", (db_file,))

    def edges_annotated(self, id):
        edges = STRING.edges_annotated(self, id)
        edges_nc = []
        for edge in edges:
            id1, id2 = edge.protein_id1, edge.protein_id2
            cur = self.db_detailed.execute("""\
                SELECT neighborhood, fusion, cooccurence, coexpression,
                       experimental, database, textmining
                FROM evidence
                WHERE protein_id1=? AND protein_id2=?
                """, (id1, id2))
            res = cur.fetchone()
            if res:
                evidence = res
            else:
                evidence = [0] * 7
            edges_nc.append(
                STRINGDetailedInteraction(*(tuple(edge) + tuple(evidence)))
            )
        return edges_nc

    @classmethod
    def download_data(cls, version, taxids=None):
        baseurl = "http://www.string-db.org/newstring_download/"
        links_filename = ("protein.links.detailed.{version}.txt.gz"
                          .format(version=version))

        dir = serverfiles.localpath(cls.DOMAIN)
        local_filename = os.path.join(dir, links_filename)

        if not os.path.exists(local_filename):
            wget(baseurl + links_filename, dir, progress=True)
        else:
            print "Already downloaded - skiping"

        cls.init_db(version, taxids)

    @classmethod
    def init_db(cls, version, taxids=None):
        dir = serverfiles.localpath(cls.DOMAIN)

        links_filename = ("protein.links.detailed.{version}.txt.gz"
                          .format(version=version))
        links_filename = os.path.join(dir, links_filename)

        if taxids:
            taxids = set(taxids)
        else:
            taxids = set(cls.common_taxids())

        links_fileobj = open(links_filename, "rb")
        links_file = gzip.GzipFile(fileobj=links_fileobj)

        con = sqlite3.connect(os.path.join(dir, cls.FILENAME_DETAILED))
        with con:
            con.execute("""\
                DROP TABLE IF EXISTS evidence
            """)

            con.execute("""\
                CREATE TABLE evidence(
                     protein_id1 TEXT,
                     protein_id2 TEXT,
                     neighborhood INTEGER,
                     fusion INTEGER,
                     cooccurence INTEGER,
                     coexpression INTEGER,
                     experimental INTEGER,
                     database INTEGER,
                     textmining INTEGER
                    )
                """)

            links = csv.reader(links_file, delimiter=" ")
            links.next()  # Read header
            filesize = os.stat(links_filename).st_size

            progress = ConsoleProgressBar("Processing links file:")
            progress(1.0)

            def read_links(reader):
                split = str.split
                for i, (p1, p2, n, f, c, cx, ex, db, t, _) in \
                        enumerate(reader):
                    if split(p1, ".", 1)[0] in taxids and \
                            split(p2, ".", 1)[0] in taxids:
                        yield intern(p1), intern(p2), n, f, c, cx, ex, db, t

                    if i % 100000 == 0:
                        progress(100.0 * links_fileobj.tell() / filesize)

            con.executemany("""
                INSERT INTO evidence
                VALUES  (?, ?, ?, ?, ?, ?, ?, ?, ?)
                """, read_links(links))

            progress.finish()

            print "Indexing"
            con.execute("""\
                CREATE INDEX IF NOT EXISTS index_evidence
                    ON evidence (protein_id1, protein_id2)
            """)

            con.executescript("""
                DROP TABLE IF EXISTS version;

                CREATE TABLE version (
                     string_version text,
                     api_version text
                );
                """)

            con.execute("""
                INSERT INTO version
                VALUES (?, ?)""", (version, cls.VERSION))


##########
# Obsolete
##########

class Interaction(object):
    def __init__(self, protein1, protein2, ref1=None, ref2=None, conf1=None, conf2=None):
        self.protein1, self.protein2 = protein1, protein2
        self.ref1, self.ref2 = ref1, ref2
        self.conf1, self.conf2 = conf1, conf2
        self.org1, self.org2 = None, None


class MIPS(object):
    VERSION = 1

    def __init__(self):
        self.load()

    def load(self):
        self.protein_names = defaultdict(set)
        self.refs = {}
        self.confidance = {}

        def process(element):
            d = {}
            participants = element.getElementsByTagName("proteinParticipant")
            proteins = []
            for protein in participants:
                interactor = protein.getElementsByTagName("proteinInteractor")[0]
                names = []
                for name in interactor.getElementsByTagName("shortLabel") + \
                            interactor.getElementsByTagName("fullName"):
                    names.append((name.tagName, name.childNodes[0].data))

                refs = []
                for ref in interactor.getElementsByTagName("primaryRef"):
                    refs += [(ref.tagName, ref.attributes.items())]
                org = dict(interactor.getElementsByTagName("organism")[0].attributes.items()).get("ncbiTaxId")
                conf = protein.getElementsByTagName("confidence")[0].attributes.items()
                proteins.append((names, refs, conf, org))
            interaction = Interaction(proteins[0][0][1][1], proteins[1][0][1][1])
            interaction.ref1, interaction.ref2 = proteins[0][1], proteins[1][1]
            interaction.conf1, interaction.conf2 = proteins[0][2], proteins[1][2]
            interaction.org1, interaction.org2 = proteins[0][3], proteins[1][3]

            self.protein_names[interaction.protein1].add(proteins[0][0][0][1])
            self.protein_names[interaction.protein2].add(proteins[1][0][0][1])

            return interaction

        document = minidom.parse(serverfiles.localpath_download("PPI", "allppis.xml"))
        interactions = document.getElementsByTagName("interaction")
        self.interactions = [process(interaction) for interaction in interactions]

        self.protein_interactions = defaultdict(set)

        for inter in self.interactions:
            self.protein_names[inter.protein1] = dict(inter.ref1[0][1]).get("id")
            self.protein_names[inter.protein2] = dict(inter.ref2[0][1]).get("id")
            self.protein_interactions[inter.protein1].add(inter)
            self.protein_interactions[inter.protein2].add(inter)

    def __iter__(self):
        return iter(self.interactions)

    @classmethod
    def download(cls):
        src = urllib2.urlopen("http://mips.helmholtz-muenchen.de/proj/ppi/data/mppi.gz")
        dest = serverfiles.localpath("PPI", "mppi.gz")
        shutil.copyfileobj(src, open(dest, "wb"))

    @classmethod
    @pickled_cache(None, [("PPI", "allppis.xml")], version=1)
    def _get_instance(cls):
        return MIPS()

    @classmethod
    def get_instance(cls):
        if not hasattr(cls, "_instance"):
            cls._instance = cls._get_instance()
        return cls._instance


def mips_interactions(protein=None):
    mips = MIPS.get_instance()
    if protein is None:
        return list(mips)
    else:
        return mips.protein_interactions.get(protein)


def mips_proteins():
    return set(MIPS.get_instance().protein_names.keys())


class BioGRIDInteraction(object):
    """ An object representing a BioGRID interaction. Each member of this object
    represents a data from a single column of BIOGRID-ALL.tab file.

    Attributes:
        - *interactor_a*    - BioGRID identifier
        - *interactor_b*    - BioGRID identifier
        - *official_symbol_a*    - An official symbol for *interactor_a*
        - *official_symbol_b*    - An official symbol for *interactor_b*
        - *aliases_for_a*    - Aliases separated by '|'
        - *aliases_for_b*    - Aliases separated by '|'
        - *experimental_system*     - Experimental system (see BioGRID documentation on www.thebiogrid.org for a list of valid entrys)
        - *source*    -
        - *organism_a_id*    - NCBI Taxonomy identifier for *interactor_a*'s organism
        - *organism_b_id*    - NCBI Taxonomy identifier for *interactor_b*'s organism
    """
    __slots__ = ["interactor_a", "interactor_b", "official_symbol_a", "official_symbol_b", "aliases_for_a", "aliases_for_b", "experimental_system", "source", "pubmed_id", "organism_a_id", "organism_b_id"]

    def __init__(self, line):
        for attr, val in zip(self.__slots__, line.split("\t")):
            setattr(self, attr, val)


class _BioGRID_Old(object):
    """ A BioGRID database interface
    Example::
        >>> ## finding all interactions for Homo sapiens sapiens
        >>> grid = BioGRID(case_insensitive=True)
        >>> proteins = proteins = biogrid.proteins() ## All proteins
        >>> proteins = [p for p in proteins if any(["9606" in [int.organism_a_id, int.organism_b_id] for int in grid.get(p)])]
    """
    VERSION = 1

    def __init__(self, case_insensitive=True):
#        warnings.warn("obiPPi._BioGRID_Old class is deprecated. Use obiPPI.BioGRID")
        self.case_insensitive = case_insensitive
        self._case = (lambda name: name.lower()) if self.case_insensitive else (lambda name: name)
        self.load()

    def load(self):
        text = open(serverfiles.localpath_download("PPI", "BIOGRID-ALL.tab"), "rb").read()
        text = text.split("SOURCE\tPUBMED_ID\tORGANISM_A_ID\tORGANISM_B_ID\n", 1)[-1]
        self.interactions = [BioGRIDInteraction(line) for line in text.splitlines() if line.strip()]

        self.protein_interactions = defaultdict(set)
        self.protein_names = {}

        case = self._case

        def update(keys, value, collection):
            for k in keys:
                collection.setdefault(k, set()).add(value)

        for inter in self.interactions:
            update(map(case, [inter.official_symbol_a] + inter.aliases_for_a.split("|")), case(inter.interactor_a), self.protein_names)
            update(map(case, [inter.official_symbol_b] + inter.aliases_for_b.split("|")), case(inter.interactor_b), self.protein_names)

            self.protein_interactions[case(inter.interactor_a)].add(inter)
            self.protein_interactions[case(inter.interactor_b)].add(inter)

        self.protein_interactions = dict(self.protein_interactions)

        if case("N/A") in self.protein_names:
            del self.protein_names[case("N/A")]

    def proteins(self):
        """ Return all protein names in BioGRID (from INTERACTOR_A, and INTERACTOR_B columns).
        """
        return self.protein_interactions.keys()

    def __iter__(self):
        """ Iterate over all BioGRIDInteraction objects.
        """
        return iter(self.interactions)

    def __getitem__(self, key):
        """ Return a list of protein interactions that a protein is a part of.
        """
        key = self._case(key)
#        keys = self.protein_alias_matcher.match(key)
        if key not in self.protein_interactions:
            keys = self.protein_names.get(key, [])
        else:
            keys = [key]
        if keys:
            return list(reduce(set.union, [self.protein_interactions.get(k, []) for k in keys], set()))
        else:
            raise KeyError(key)

    def get(self, key, default=None):
        """ Return a list of protein interactions that a protein is a part of.
        """
        key = self._case(key)
#        keys = self.protein_alias_matcher.match(key)
        if key not in self.protein_interactions:
            keys = self.protein_names.get(keys, [])
        else:
            keys = [key]
        if keys:
            return list(reduce(set.union, [self.protein_interactions.get(k, []) for k in keys], set()))
        else:
            return default

    @classmethod
    def get_instance(cls):
        if getattr(cls, "_instance", None) is None:
            cls._instance = _BioGRID_Old()
        return cls._instance


def biogrid_interactions(name=None):
    """Return a list of protein interactions (BioGRIDInteraction objects) that a protein is a part of.
    """
    if name:
        return list(_BioGRID_Old.get_instance().get(name, set()))
    else:
        return _BioGRID_Old.get_instance().interactions


def biogrid_proteins():
    """ Return all protein names in BioGRID (from INTERACTOR_A, and INTERACTOR_B columns).
    """
    return _BioGRID_Old.get_instance().proteins()


if __name__ == "__main__":
    for protein in mips_proteins():
        print "Protein", protein, "interacts with",
        print ",".join(set(reduce(list.__add__, [[inter.protein1, inter.protein2] for inter in mips_interactions(protein)], [])) - set([protein]))