orange-bioinformatics / _bioinformatics / obiDicty.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
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
import sys, pprint, time, re
from itertools import *
import urllib
import urllib2
import socket
import os
from collections import defaultdict
import pickle

import orange
from Orange.orng import orngServerFiles

defaddress = "http://bcm.fri.uni-lj.si/microarray/api/index.php?"
#defaddresspipa = "https://pipa.fri.uni-lj.si/pipa/script/api/orange.py?action="
defaddresspipa = "https://pipa.fri.uni-lj.si/PIPA/PIPAapi/PIPAorange.py"
defaddresspipa_coverage = "https://pipa.biolab.si/tbrowse/api/pipa.py"

pipaparuser = "pipa_username"
pipaparpass = "pipa_password"

#utility functions - from Marko's mMisc.py

def splitN(origsize, maxchunk):
    """
    Splits an integer into chunks of given size. Each created chunk
    except possibly the last one is of maximum allowed size.
    Chunks are returned in list.
    """
    l = [maxchunk]*(origsize/maxchunk)
    a = origsize % maxchunk
    if a > 0: 
        l.append(a)
    return l

def split(l, maxchunk):
    """
    Splits list l into chunks of size maxchunk. Each created chunk
    except possibly the last one is of maximum allowed size.
    """
    sizes = splitN(len(l), maxchunk)
    out = []
    tillNow = 0
    for s in sizes:
        out.append(l[tillNow:tillNow+s])
        tillNow += s
    return out       

def lloc(l,n):
    """
    List location in list of list structure.
    Enable the use of negative locations:
    -1 is the last element, -2 second last...
    """
    if n < 0:
        return len(l[0])+n
    else:
        return n

def loc(l,n):
    """
    List location.
    Enable the use of negative locations:
    -1 is the last element, -2 second last...
    """
    if n < 0:
        return len(l)+n
    else:
        return n

def nth(l,n):
    """
    Returns only nth elemnt in a list.
    """
    n = lloc(l,n)
    return [ a[n] for a in l ]

def imnth(l, ns):
    """
    Return only columns as specified in ns. Returns an generator.
    """
    ns = [ lloc(l,n) for n in ns ]
    for a in l:
        yield [ a[n] for n in ns ]

def flatten(l,r=0):
    """
    Flatten a python structure into a list. Leave strings alone.
    """
    if type(l) == type("a"):
        return [ l ]
    try: #if enumerable then flatten it's elements
        rec = [ flatten(a,r=r+1) for a in l ]
        ret = []
        for a in rec:
            ret = ret + a
        return ret
    except:
        return [ l ]

def mxrange(lr):
    """
    Multiple xranges. Can be used to traverse matrices.
    This function is very slow due to unknown number of
    parameters.

    >>> mxrange([3,5]) 
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
    >>> mxrange([[3,5,1],[9,0,-3]])
    [(3, 9), (3, 6), (3, 3), (4, 9), (4, 6), (4, 3)]
    """
    if len(lr) == 0:
        yield ()
    else:
        #it can work with single numbers
        index = lr[0]
        if type(1) == type(index):
            index = [ index ]
        for a in range(*index):
            for b in mxrange(lr[1:]):
                yield tuple([a] + list(b))


def issequencens(x):
    """
    Is x a sequence and not string ? We say it is if it has a __getitem__ 
    method and it is not an instance of basestring.
    """
    return hasattr(x, '__getitem__') and not isinstance(x, basestring)

#end utility functions

import statc
#median = statc.median

def median(l):
    if len(l) == 0:
        return None
    else:
        return statc.median(l)



socket.setdefaulttimeout(60)

verbose = 0

class HttpGetException(Exception): pass

def replaceChars(address):
    return address.replace(" ", "%20")

def httpGet(address, *args, **kwargs):
    if verbose: 
        print address, args, kwargs,  " "
    address = replaceChars(address)
    t1 = time.time()
    f = urllib2.urlopen(address, *args, **kwargs)
    read = f.read()
    if verbose:
        print "bytes", len(read),
    if verbose:
        print time.time() - t1
    return read

def txt2ll(s, separ=' ', lineSepar='\n'):
    return [ a.split(separ) for a in s.split(lineSepar) ]

class AuthenticationError(Exception):
    pass

class DBInterface(object):
 
    def __init__(self, address):
        self.address = address

    def raw(self, request, data=None, tryN=3):
        if verbose:
            print "tryN", tryN

        def try_down():
            try:
                if data == None:
                    return httpGet(self.address + request)
                else:
                    return httpGet(self.address + request, data=urllib.urlencode(data))
            except urllib2.HTTPError, e:
                if e.code == 403:
                    raise AuthenticationError()
                else:
                    raise e

        if tryN > 1:
            try:
                return try_down()
            except IOError:
                return self.raw(request, data=data, tryN=tryN-1)
        else:
            return try_down()

    def get(self, request, data=None, tryN=3):
        rawf = self.raw(request, data)
        if rawf == None:
            print "rawf == None!"
            raise Exception("Connection error when contacting " + self.address + request)
        if rawf.startswith("error: authentication failed"):
            raise AuthenticationError()
        elif rawf[:1] == "<" or rawf[:5] == "error" or rawf.startswith("MOD_PYTHON ERROR"): #an error occurred - starting some html input
            #TODO are there any other kinds of errors?
            if tryN > 0:
                if verbose:
                    print "trying again"
                return self.get(request, data=data, tryN=tryN-1)
            else:
                if verbose:
                    print rafw[:1000]
                raise Exception("Error with the database")

        a = txt2ll(rawf, separ='\t')
        
        if a[-1][0] == "": #remove empty line on end
            a = a[:-1]
        return a

def _test():
    import doctest
    doctest.testmod()

def splitTableOnColumn(ll,n):
    omap = {}
    n = lloc(ll,n)
    for l in ll:
        cell = omap.get(l[n], [])
        cell.append(l)
        omap[l[n]] = cell
    return omap

def neededColumns(legend, want):
    return [ legend.index(a) for a in want ]

def onlyColumns(ll, legend, want):
    return list(imnth(ll, neededColumns(legend, want)))

def ll2dic(ll, key=0, value=1):
    """
    Converts LL to map. Key is key position, value value position
    """
    names = nth(ll, lloc(ll, key))
    if len(names) == len(set(names)):
        return dict(list(imnth(ll, [ lloc(ll, key),  lloc(ll, value) ] )))
    else:
        raise Exception("all keys are not unique")

def dic2ll(dic):

    columns = sorted(dic.values()[0].keys())
    ll = []
    for key, d in dic.items():
        ll.append([ key ] + [ d[a] for a in columns ])
    return columns,ll

def allUnique(els):
    return len(els) == len(set(els))

def reverseDic(d):
    """
    Create a reverse dictionary if a unique reverse is possible.
    """
    if allUnique(d.values()):
        return dict([ (b,a) for a,b in d.items() ])

def chainLookup(a, dics, force=[]):
    """
    Goes through a list of dictionaries. On each step try to
    transform current key to value. The values becomes the key
    for next search If unsuccessfull, query the next
    dictionary with current key. Force last translation.
    """
    force = [ loc(dics, i) for i in force ]
    for i,dic in enumerate(dics):
        if i in force: #force specified translations
            a = dic[a]
        else:
            if a in dic:
                a = dic[a]
    return a

class DBCommon(object):

    def fromBuffer(self, addr):
        return self.buffer.get(self.address + addr)

    def toBuffer(self, addr, cont, version, autocommit=True):
        if self.buffer:
            return self.buffer.add(self.address + addr, cont, version=version, autocommit=autocommit)

    def bufferCommit(self):
        if self.buffer:
            self.buffer.commit()

    def bufferFun(self, bufkey, bufver, reload, fn, *args, **kwargs):
        """
        If bufkey is already present in buffer, return its contents.
        If not, run function with arguments and save its result
        into the buffer.
        """
        if self.inBuffer(bufkey) == bufver and reload == False:
            res = self.fromBuffer(bufkey)
        else:
            res = fn(*args, **kwargs)
            self.toBuffer(bufkey, res, bufver)
        return res

    def sq(self, s1, data=None, buffer=True, bufadd="", bufname=None, bufver="0", reload=False, bufferkey=None, db=None):
        if db == None:
            db = self.db
        if buffer:
            bufkey = bufadd + (bufname if bufname != None else s1)
            if bufferkey != None:
                bufkey = bufferkey(bufkey, data)
            res = self.bufferFun(bufkey, bufver, reload, db.get, s1, data=data)
        else:
            res = db.get(s1, data=data)
        return res[1:],res[0]

    def inBuffer(self, addr):
        if self.buffer:
            return self.buffer.contains(self.address + addr)
        else:
            return False

    def dictionarize(self, ids, fn, *args, **kwargs):
        """
        Creates a dictionary from id: function result.
        Callback for each part done.
        """
        callback = kwargs.pop("callback", None)
        odic = {}
        for a,b in izip(ids, fn(*args, **kwargs)):
            odic[a] = b
            if callback: callback()
        return odic

    def downloadMulti_bufcommand_replace_multi(self, command, data=None, chunk=100, bufferkey=None, transformfn=None):
        """
        Get function which gives buffer address for an id and a function 
        which replaces $MULTI$.
        """

        def bufferkey1(command, data):
            if transformfn:
                return "TRANS " + command
            else:
                return command

        def replace_multi(command, data, repl):
            return command.replace("$MULTI$", repl),\
                dict((a,b.replace("$MULTI$", repl)) for a,b in sorted(data.items())) if data != None else None

        if bufferkey == None:
            bufferkey=bufferkey1

        bufcommand = lambda x, c=command, d=data: bufferkey(*replace_multi(c, d, x))
        return bufcommand, replace_multi

    def downloadMulti(self, command, ids, data=None, chunk=100, transformfn=None, bufferkey=None, separatefn=None, bufreload=False, bufver="0"):
        """
        Downloads multiple results at once.
        Results in the same order as in ids.

        Bufferkey transforms command and data into buffer key.
        bufver is a function returning buffer version for a given id. if
            a string is given, use it for all ids
        """

        sids = split(ids,chunk)
    
        bufverfn = None
        if isinstance(bufver, basestring):
            bufverfn = lambda x: bufver
        else:
            bufverfn = bufver

        bufcommand, replace_multi = self.downloadMulti_bufcommand_replace_multi(command, data=data, chunk=chunk, bufferkey=bufferkey, transformfn=transformfn)

        for i,sidp in enumerate(sids):

            buffered = []
            unbuffered = []
        
            for a in sidp:
                if self.inBuffer(bufcommand(a)) == bufverfn(a) and bufreload == False:
                    buffered.append(a)
                else:
                    unbuffered.append(a)

            res = []
            legend = []

            if len(unbuffered) > 0:
                com1, d1 = replace_multi(command, data, ",".join(unbuffered))
                res, legend = self.sq(com1, data=d1, buffer=False) #get unbuffered part
            else:
                # get legend from buffer also
                legend = self.fromBuffer(bufcommand(buffered[0]))[0]

            #split on different values of the first column - first attribute

            if not separatefn:
                antss = splitTableOnColumn(res, 0)
            else:
                legend, antss = separatefn([legend]+res)

            #if transform before saving is requested, do it
            if transformfn:
                nantss = {}
                nlegend = None
                for a,b in antss.items():
                    nb, nlegend = transformfn(b, legend)
                    nantss[a] = nb
                legend = nlegend
                antss = nantss
 
            #here save buffer
            for a,b in antss.items():
                self.toBuffer(bufcommand(a), [ legend ] + b, bufverfn(a), autocommit=False)
            self.bufferCommit()
            

            #get buffered from the buffer
            antssb = dict([ (b, self.fromBuffer(bufcommand(b))[1:]) for b in buffered ])
            antss.update(antssb)

            #put results in order
            tl = []
            for ci in sidp:
                yield antss[ci], legend

    def exampleTables(self, ids, chipsm=None, spotmap={}, callback=None, exclude_constant_labels=False, annots={}, chipfn=None, allowed_labels=None):
        """
        Create example tables from chip readings, spot mappings and 
        group specifications.

        group is the output from "sortAnnotations" function. 
        spotmap is a dictionary of { spotid: gene }
        chipsm is a dictionary of chip readings

        Callback: number of chipids + 2
        """

        if verbose:
            print "Creating example table"

        if callback: callback()

        amap = {}
        amapnext = 0

        togen = []

        groupnames = []
        groupvals = []
        groupannots = []

        if chipsm == None:
            chipdl = chipfn(ids)

        for chipid in ids:

            if chipsm != None:
                chipdata = chipsm[chipid]
            else:
                chipdata = chipdl.next()

            if callback: callback()

            #add to current position mapping
            repeats = {}
            for id,_ in chipdata:
                rep = repeats.get(id, 0)
                repeats[id] = rep+1
                key = (id, rep)
                if key not in amap:
                    amap[key] = amapnext
                    amapnext += 1

            vals = [ None ] * len(amap)

            repeats = {}
            for id,v in chipdata:
                rep = repeats.get(id, 0)
                repeats[id] = rep+1
                key = (id, rep)
                putind = amap[key]
                vals[putind] = v
            groupvals.append(vals)

            groupnames.append(chipid) 

            newannots = [['id', str(chipid)]] #add chipid to annotations
            if annots:
                newannots += annots[chipid]
            groupannots.append(newannots)

        togen = (groupnames, groupvals, groupannots)
        
        if callback: callback()

        ddb = [ None ]*len(amap)
        for (a,rep),pos in amap.items():
            if len(spotmap):
                ddb[pos] = spotmap.get(a, "#"+a)
            else:
                ddb[pos] = a

        #this is sorted position mapping: key -> sortedind
        posMap = dict( (k,i) for i,k in enumerate(sorted(amap.keys())) )
        revmap = dict( ( (i,k) for k,i in amap.items() ) )
        #permutation[i] holds target of current [i]
        permutation = [ posMap[revmap[i]] for i in range(len(amap)) ]

        def enlength(a, tlen):
            """ Adds Nones to the end of the list """
            if len(a) < tlen:
                return a + [ "None" ]*(tlen-len(a))
            else:
                return a

        def enlengthl(l, tlen):
            return [ enlength(a, tlen) for a in l ]
    
        groupnames, groupvals, groupannots = togen

        et = createExampleTable(groupnames, 
            enlengthl(groupvals, len(ddb)),
            groupannots, ddb, exclude_constant_labels=exclude_constant_labels, permutation=permutation, allowed_labels=allowed_labels)

        if callback: callback()

        return et

def bufferkeypipa(command, data):
    """ Do not save password to the buffer! """
    command = command + " v5" #add version
    if data != None:
        data = data.copy()
        if pipaparpass in data:
            data.pop(pipaparpass)
        return command + " " +  urllib.urlencode(sorted(data.items()))
    else:
        return command

class PIPA(DBCommon):

    def __init__(self, address=defaddresspipa, buffer=None, username=None, password=None):
        self.address = address
        self.db=DBInterface(address)
        self.db_coverage=DBInterface(defaddresspipa_coverage) #temporary
        self.buffer = buffer
        self.username = None
        if username != None:
            self.username = username
            self.password = password

    def add_auth(self, data=None):
        if self.username == None:
            return data
        authdic = { pipaparuser: self.username, pipaparpass: self.password }
        if data != None:
            authdic.update(data)
        return authdic

    def annotations(self, reload=False, bufver="0"):
        """
        Returns a dictionary of (id: dictionary of annotations).
        """
        #res, legend = self.sq("mapping_list", data=self.add_auth(), reload=reload, bufferkey=bufferkeypipa, bufver=bufver)
        res, legend = self.sq("", data=self.add_auth({"action": "expression_list"}), reload=reload, bufferkey=bufferkeypipa, bufver=bufver)
        return dict( (sa[0], dict(zip(legend[1:], sa[1:]))) for sa in res )

    def chips(self, ids, ctype, reload=False, bufver="0"):
        def separatefn(res):
            #each one is own rown
            #genes are in the first row
            #remove unknown
            genes = res[0][1:]
            cids = nth(res,0)[1:]

            antss = {}
            for i,cid in enumerate(cids):
                row = i+1
                vals = res[row][1:]
                antss[cid] = [ list(a) for a in zip(genes, vals) if a[1] != "?" ]
            return ['gene_id', 'value'], antss

        download_command = "gene_expression"
        datadict = {"action": download_command, "ids":"$MULTI$", 'transpose':'1'}
        if ctype != None:
            datadict["type"] = ctype
        antss = self.downloadMulti("", ids, data=self.add_auth(datadict), chunk=10, separatefn=separatefn, bufferkey=bufferkeypipa, bufreload=reload, bufver=bufver)
        for a,legend in antss:
            yield a

    def coverage(self, id_, genome, chromosome, reload=False, bufver="0", raw=False):
        data = self.add_auth({"action": "coverage_strand", "chr_name": str(chromosome), 
            "pixel_size": "1", "genome": genome, "sample_id": str(id_), "raw": str(raw).lower()})

        def comp():

            d = dict(data)

            def get():
                #sq returns [ "all lines after first", "firstline"] - take first column!
                #do not use buffering on this stage!
                a = self.sq("", data=d, reload=reload, buffer=False, bufferkey=bufferkeypipa, bufver=bufver, db=self.db_coverage)[1][0].strip("[]")
                return map(int, a.split(", "))
                
            d["strand"] = "plus"
            plus = get()
            d["strand"] = "minus"
            minus = get()

            import numpy
            return numpy.array([plus, minus])
        
        bufkey =  bufferkeypipa("", data)
        return self.bufferFun(bufkey, bufver, reload, comp)


    def gene_expression_types(self, reload=False, bufver="0"):
        #res, legend = self.sq("gene_expression_type", data={self.add_auth(), reload=reload, bufferkey=bufferkeypipa, bufver=bufver)
        res, legend = self.sq("", data=self.add_auth({"action":"gene_expression_type"}), reload=reload, bufferkey=bufferkeypipa, bufver=bufver)
        return sorted(tuple(a) for a in res)

    def chips_keynaming(self, ctype):
        keynamingfn,_ = self.downloadMulti_bufcommand_replace_multi("", data=self.add_auth({"action": "gene_expression", "ids":"$MULTI$", 'transpose':'1', 'type':ctype}), chunk=100, bufferkey=bufferkeypipa, transformfn=None)
        return keynamingfn

    def get_data(self, exclude_constant_labels=False, average=median, 
        ids=None, callback=None, bufver="0", transform=None, ctype=None, allowed_labels=None):
        """
        Get data in a single example table with labels of individual attributes
        set to annotations for query and post-processing
        instructions.

        Parameters: 
            average: function used for combining multiple reading of the same spot on
                a chip. If None, no averaging is done. Fuction should take a list
                of floats and return an "averaged" float.
            ids: a list of chip ids. If absent, make a search
            exclude_constant_labels: if a label has the same value in whole 
                example table, remove it
            format: if short, use short format for chip download
            ctype: expression type, from gene_expression_types

        Defaults: Median averaging.
        """

        def optcb():
            if callback: callback()

        cbc = CallBack(1, optcb, callbacks=10)

        if not ids:
            return None

        cbc.end()

        #downloads annotations
        cbc = CallBack(len(ids), optcb, callbacks=10)

        readall = self.annotations()

        read = {}
        for a,b in readall.items():
            read[a] = b.items()

        cbc.end()

        #till now downloads were small

        import time
        tstart = time.time()

        #here download actually happens
        chipfn = None

        chipfn = lambda x: self.chips(x, ctype, bufver=bufver)
       
        if verbose:
            print "DOWNLOAD TIME", time.time() - tstart

        cbc = CallBack(len(ids)*2+len(ids)+1, optcb, callbacks=999-30)
        et = self.exampleTables(ids, spotmap={}, callback=cbc, annots=read, exclude_constant_labels=exclude_constant_labels, chipfn=chipfn, allowed_labels=allowed_labels)
        cbc.end()

        cbc = CallBack(1, optcb, callbacks=10)

        #transformation is performed prior to averaging
        if transform != None:
            transformValues(et, fn=transform) #in place transform
            cbc()

        #if average function is given, use it to join same spotids
        if average != None:
            et = averageAttributes(et, fn=average)
            cbc()

        cbc.end()

        return et

def bufferkeypipax(command, data):
    """ Do not save password to the buffer! """
    command = command + " v7" #add version
    if data != None:
        data = data.copy()
        if pipaparpass in data:
            data.pop(pipaparpass)
        return command + " " +  urllib.urlencode(sorted(data.items()))
    else:
        return command


class PIPAx(PIPA):
    """`PIPAx <http://pipa.biolab.si/?page_id=23>` api interface.
    """

    API_ADDRESS = "https://pipa.biolab.si/pipax/api.py"

    def __init__(self, address=API_ADDRESS, buffer=None,
                 username=None, password=None):
        self.address = address
        self.db = DBInterface(address)
        self.buffer = buffer
        self.username = username
        self.password = password

    def genomes(self, reload=False, bufver="0"):
        """Return a list of available genomes as a list of
        (genome_id, genome_name) tuples.

        >>> pipax.genomes()
        [('dd', 'Dictyostelium discoideum'), ('dp', 'Dictyostelium purpureum')]

        """
        data = {"action": "genomes"}
        res, _ = self.sq("", data=data, reload=reload, bufver=bufver)
        return [tuple(r) for r in res]

    def mappings(self, reload=False, bufver="0"):
        """Return a dictionary of {unique_id: dictionary_of_annotations}
        where the keys for dictionary_of_annotations are
        ["id", data_id", "data_name", "genomes_id"]

        >>> mappings = pipax.mappings()

        """
        data = self.add_auth({"action": "mappings"})
        res, legend = self.sq("", data=data, reload=reload,
                              bufferkey=bufferkeypipax,
                              bufver=bufver)

        return dict((sa[0], dict(zip(legend[1:], sa[1:]))) for sa in res)

    def result_types(self, reload=False, bufver="0"):
        """Return a list of available result type templates.
        """
        data = {"action": "results_templates"}
        res, _ = self.sq("", data=data, reload=reload, bufver=bufver)
        return sorted(tuple(a) for a in res)

    def results_list(self, rtype, reload=False, bufver="0"):
        """Return a list of available results for a result type template
        `rtype` (a key from the `result_types` return value).

        """
        data = {"action": "results",
                "results_templates_id": rtype}
        data = self.add_auth(data)
        res, legend = self.sq("", data=data, reload=reload,
                              bufferkey=bufferkeypipax,
                              bufver=bufver)
        # index by unique_id (last column)
        res = splitTableOnColumn(res, -1)
        return dict((id, dict(zip(legend, line[0]))) \
                    for id, line in res.items())

    def download_key_function(self):
        data = self.add_auth({"action": "download",
                              "ids": "$MULTI$"}
                                )
        keynamingfn, _ = self.downloadMulti_bufcommand_replace_multi("",
                         data=data, chunk=100, bufferkey=bufferkeypipax,
                         transformfn=None)
        return keynamingfn

    def get_data(self, ids=None, result_type=None,
                 exclude_constant_labels=False, average=median,
                 callback=None, bufver="0", transform=None,
                 allowed_labels=None, reload=False):
        """
        Get data in a single example table with labels of individual
        attributes set to annotations for query and post-processing
        instructions.

        :param ids: If `result_type` is specified then this must
            be a list of  `unique_id`s or (id, data_id) tuples as
            returned by `mappings`. Else the `ids` must be a list
            of `unique_id`s as returned by `results_list`.
        :type ids: list

        :param result_type: Result template type id as returned by
             `result_types`. Not specified by default (see `ids`.)
        :type result_type: str

        :param exclude_constant_labels: If a label has the same value
            in whole example table, remove it.
        :type exclude_constant_labels: bool

        :param average: Function used for combining multiple reading of
            the same spot on a chip. If None, no averaging is done.
            Function should take a list of floats and return an "averaged"
            float (default `median`).
        :type average: function

        """

        def optcb():
            if callback:
                callback()

        def argsort(a):
            sort = sorted([(map(int, item), i) for i, item in enumerate(a)])
            return [i for _, i in sort]

        cbc = CallBack(len(ids), optcb, callbacks=10)

        if result_type is not None:
            ids_sort = argsort(ids)
            res_list = self.results_list(result_type, reload=reload,
                                         bufver=bufver)
            # Map (data_id, mapping_id) to unique_id
            res_types_to_unique_id = \
                dict(((annot["data_id"], annot["mappings_id"]),
                      annot["unique_id"]) \
                     for annot in res_list.values())

            mappings = self.mappings(reload=reload, bufver=bufver)

            def id_map(mappings_unique_id):
                cbc()
                if isinstance(mappings_unique_id, tuple):
                    data_id, mappings_id = mappings_unique_id
                else:
                    annot = mappings[mappings_unique_id]
                    data_id = annot["data_id"]
                    mappings_id = annot["id"]
                return res_types_to_unique_id[data_id, mappings_id]

            ids = map(id_map, ids)
        else:
            result_type_set = set(id.rsplit("_", 1)[-1] for id in ids)
            if len(result_type_set) != 1:
                raise ValueError("""\
Can only retrieve a single result_template_type at a time"""
)
            result_type = result_type_set.pop()
            res_list = self.results_list(result_type, reload=reload,
                                         bufver=bufver)
            sort_keys = [(int(res_list[id]["data_id"]),
                          int(res_list[id]["mappings_id"]))\
                         for id in ids]
            ids_sort = argsort(sort_keys)

        # Sort the ids for use by pipax api
        ids_sorted = [ids[i] for i in ids_sort]

        read = {}
        for a, b in res_list.items():
            read[a] = b.items()

        cbc.end()

        download_func = lambda x: self.download(x, reload=reload,
                                                bufver=bufver)

        cbc = CallBack(len(ids_sorted) + 3, optcb,
                       callbacks=99 - 20)
        et = self.exampleTables(ids_sorted, spotmap={}, callback=cbc,
                            annots=read,
                            exclude_constant_labels=exclude_constant_labels,
                            chipfn=download_func,
                            allowed_labels=allowed_labels)
        cbc.end()

        # Restore input ids order.
        domain = orange.Domain([et.domain[id] for id in ids], None)
        domain.addmetas(et.domain.getmetas())
        et = orange.ExampleTable(domain, et)

        cbc = CallBack(2, optcb, callbacks=10)

        #transformation is performed prior to averaging
        if transform != None:
            transformValues(et, fn=transform)  # in place transform
            cbc()

        #if average function is given, use it to join same spotids
        if average != None:
            et = averageAttributes(et, fn=average)
            cbc()

        cbc.end()

        return et

    def download(self, result_ids, reload=False, bufver="0"):
        """result_ids must be sorted (by `(data_id, mappings_id)`)
        """
        data = {"action": "download", "ids": "$MULTI$"}
        data = self.add_auth(data)
        antss = self.downloadMulti("", result_ids, data=data, chunk=10,
                                   bufferkey=bufferkeypipax, bufreload=reload,
                                   bufver=bufver)
        for a, legend in antss:
            yield a

    def downloadMulti(self, command, ids, data=None, chunk=100,
                      transformfn=None, bufferkey=None, separatefn=None,
                      bufreload=False, bufver="0"):
        """
        Downloads multiple results at once.
        Results in the same order as in ids.

        Bufferkey transforms command and data into buffer key.
        bufver is a function returning buffer version for a given id. if
            a string is given, use it for all ids
        """

        sids = split(ids, chunk)

        bufverfn = None
        if isinstance(bufver, basestring):
            bufverfn = lambda x: bufver
        else:
            bufverfn = bufver

        bufcommand, replace_multi = \
                self.downloadMulti_bufcommand_replace_multi(command,
                                data=data, chunk=chunk, bufferkey=bufferkey,
                                transformfn=transformfn
                                )

        for i, sidp in enumerate(sids):

            buffered = []
            unbuffered = []

            for a in sidp:
                if self.inBuffer(bufcommand(a)) == bufverfn(a) and \
                        bufreload == False:
                    buffered.append(a)
                else:
                    unbuffered.append(a)

            res = []
            legend = []

            if len(unbuffered) > 0:
                com1, d1 = replace_multi(command, data, ",".join(unbuffered))
                # get unbuffered part
                res, legend = self.sq(com1, data=d1, buffer=False)
            else:
                # get legend from buffer also
                legend = self.fromBuffer(bufcommand(buffered[0]))[0]

            legend = ["gene_id", "value"]
            genes = nth(res, 0)

            antss = {}
            for i, cid in enumerate(unbuffered):
                col = i + 1
                vals = nth(res, col)
                antss[cid] = [[a, b] for a, b in zip(genes, vals) if b != "?"]

            #here save buffer
            for a, b in antss.items():
                self.toBuffer(bufcommand(a), [legend] + b, bufverfn(a),
                              autocommit=False)
            self.bufferCommit()

            #get buffered from the buffer
            antssb = dict([(b, self.fromBuffer(bufcommand(b))[1:]) \
                           for b in buffered])
            antss.update(antssb)

            #put results in order
            for ci in sidp:
                yield antss[ci], legend


class DictyExpress(DBCommon):
    """
    Type is object id
    """
    
    aoidPairs = txt2ll("""time extractions.developmental_time_point
sample biological_samples.sample
growthCond biological_samples.growth_condition
treatment biological_samples.treatment
replicate biological_sample_replicates.replicate
techReplicate chips.replicate
platform chips.chip_platform
isTimeSeries biological_sample_replicates.is_time_series""")

    obidPairs = txt2ll("""norms normalizations
samples biological_samples
replicates biological_sample_replicates
analysis analysis
experiments experiments
extractions extractions
chips chips""")

    def __init__(self, address=defaddress, buffer=None):
        self.address = address
        self.db = DBInterface(address)
        self.buffer = buffer
        self.preload()

    def preload(self):

        # aoids are mappings from annotation name to annotation id
        self.aoids = ll2dic(self.__annotationTypes(), 1, 0)
        self.saoids = ll2dic(self.aoidPairs, 0, 1)
        self.aoidsr = reverseDic(self.aoids)
        self.saoidsr = reverseDic(self.saoids)

        # obids are mappings from object id to annotation id
        self.obids = ll2dic(self.__objects(), 1, 0)
        self.sobids = ll2dic(self.obidPairs, 0, 1)
        self.obidsr = reverseDic(self.obids)
        self.sobidsr = reverseDic(self.sobids)

    def aoidt(self, s):
        return chainLookup(s, [self.saoids, self.aoids], force=[-1])

    def obidt(self, s):
        return chainLookup(s, [self.sobids, self.obids], force=[-1])
 
    def aoidtr(self, s, **kwargs):
        return chainLookup(s, [self.aoidsr, self.saoidsr], **kwargs)

    def obidtr(self, s):
        return chainLookup(s, [self.obidsr, self.sobidsr])

    def pq(self, q):
        """
        Prepare query. 
        ||| separator between conditions, 
        *** denotes equivalence
        """
        o =  "|||".join([ self.aoidt(a) + "***" + b for a,b in q.items()])
        return o

    def geneInfo(self):
        res,legend = self.sq("action=gene_info")
        return res, legend

    def annotationOptions(self, ao=None, onlyDiff=False, **kwargs):
        """
        Returns annotation options for given query. Returns all possible 
        annotations if the query is omitted.

        If ao is choosen, only result
        """
        params = ""
        if len(kwargs) > 0: params += "&query=" + self.pq(kwargs)
        if ao: params += "&annotation_object_id=" +  self.aoidt(ao)
        res,legend = self.sq("action=get_annotation_options%s" % (params), bufadd=self.address)
        res = onlyColumns(res, legend, ['annotation_object_id', 'value' ])

        #join columns with the annotation object id
        joined = {}
        for key,v in res:
            key = self.aoidtr(key)
            cur = joined.get(key, [])
            cur.append(v)
            joined[key] = cur

        if onlyDiff:
            joined = dict([ (a,b) for a,b in joined.items() if len(b)>1 ])

        return dict([ (a, sorted(b)) for a,b in joined.items() ])

    def annotation(self, type, id):
        return list(self.annotations(type, [ id ]))[0]

    def meaningfulAnnot(self, name):
        if name in self.saoids:
            return True
        else:
            return False

    def keepOnlyMeaningful(self, annot):
        """
        Keep only meaningful annotations
        """
        if type(annot) == type({}):
            return dict( [ (a,b) for a,b in annot.items() \
                if self.meaningfulAnnot(a) ] )
        else:
            return [ [ a,b ] for a,b in annot \
                if self.meaningfulAnnot(a) ]


    def annotations(self, type, ids=None, all=False):
        """
        Returns a generator returning annotations for specified type and ids. 
        If ids are left blank, all annotations are outputed. Annotations are in the same order
        as input ids.
        If all is True, all annotations are kept, else keep only "meaningful".
        """
        
        inputids = False
        if ids != None:
            inputids = True
            antss = self.downloadMulti(
                "action=get_annotations&ids=$MULTI$&object_id=%s" 
                % (self.obidt(type)), ids)
        else:
            res,legend = self.sq(
                "action=get_annotations&object_id=%s"
                % (self.obidt(type)))
            antss = splitTableOnColumn(res, 0)
            ids = nth(antss.items(),0)
            antss = zip(nth(antss.items(),1), [ legend ]*len(antss))

        for ants in izip(antss,ids):
            (res, legend), id = ants
            res2 = onlyColumns(res, legend, ['name', 'value'])
            res2 = [ [ self.aoidtr(a),b ] for a,b in res2 ]
            if not all:
                res2 = self.keepOnlyMeaningful(res2)
            if inputids:
                yield res2
            else:
                yield (id, res2)

    def search(self, type, **kwargs):
        """
        Break search for multiple values of one attribute to independant searches.
        Search is case insensitive.
        
        List of searchable annotation types: self.saoids.keys()

        example usage:
        search("norms", platform='minichip', sample='abcC3-') 
            finds all ids of normalized entries where platform is minchip and 
            sample is abcC3-
        search("norms", platform='minichip', sample=[ 'abcC3-', 'abcG15-']) 
            finds all ids of normalized entries where platform is minichip and 
            sample is abcC3- or those where platform is minichip and sample
            is abcG15-
        """
        
        #search for all combinations of values - this is slow!

        l = []
        for k,v in kwargs.items():
            if not issequencens(v):
                v = [ v ]
            l.append((k,v))

        ares = []

        for r in mxrange([ len(v) for k,v in l ]):
            dico = {}
            for i,a in enumerate(r):
                dico[l[i][0]] = l[i][1][a]

            res,_ = self.sq("action=search&object_id=%s&query=%s" \
                % (self.obidt(type), self.pq(dico)), bufadd=self.address)

            ares += res

        return sorted(set(nth(ares, 0)))


    def chipN(self, id):
        return list(self.chipNs([id]))[0]

    def chipR(self, id):
        return list(self.chipRs([id]))[0]
  
    def chipNs(self, ids, remove_bad=True):
        """
        If removebad = True removes those with weights 0.
        """
          
        def sel(res, legend):
            #Drop unwanted columns - for efficiency
            res = onlyColumns(res, legend, ["spot_id", 'M', 'weights'])
            legend = onlyColumns( [ legend ], legend, ["spot_id", 'M', 'weights'])[0]

            def transf(a):
                if a[2] == 0:
                    return a[0], '', a[2]
                else:
                    return a[0], a[1], a[2]

            res = [ transf(a) for a in res ]
            res = onlyColumns(res, legend, ["spot_id", 'M'])
            legend = onlyColumns( [ legend ], legend, ["spot_id", 'M'])[0]
            return res, legend

        antss = self.downloadMulti("action=get_normalized_data&ids=$MULTI$", ids, chunk=2, transformfn=sel)
        for a,legend in antss:
            yield a   

    def chipNsN(self, ids, annots):
        """
        Download chips using new shorter format.
        """
        chip_map_ids = zip(ids,[ dict(a)['chips.chip_map_id'] for a in annots ])

        def separateByChipsMaps(l):
            begin = 0
            cm = l[0][1]
            cp = 0
            for id,m in l[1:]:
                cp += 1
                if m != cm:
                    yield l[begin:cp]
                    cm = m
                    begin = cp
            yield l[begin:cp+1]
        
        sep = list(separateByChipsMaps(chip_map_ids))
      
        def sel(res, legend):
            #Drop unwanted columns - for efficiency
            res = onlyColumns(res, legend, ["spot_id", 'M'])
            legend = onlyColumns( [ legend ], legend, ["spot_id", 'M'])[0]
            return res, legend

        def separatefn(res):
            #each one is own rown
            #genes are in the first row
            genes = res[0][1:]
            cids = nth(res,0)[1:]

            antss = {}
            for i,cid in enumerate(cids):
                row = i+1
                vals = res[row][1:]
                antss[cid] = [ list(a) for a in zip(genes, vals) ]
            return ['spot_id', 'M'], antss

        for part in sep:
            pids = nth(part,0)
            antss = self.downloadMulti("action=get_normalized_data&mergeexperiments=1&ids=$MULTI$", pids, chunk=10, transformfn=sel, separatefn=separatefn)
            for a, legend in antss:
                yield a

    def chipRs(self, id):
        antss = self.downloadMulti("action=get_raw_data&ids=$MULTI$", ids, chunk=2)
        for a,legend in antss:
            yield a
  
    def spotId(self):
        res,legend = self.sq("action=spot_id_mapping")
        res2 = onlyColumns(res, legend, ["spot_id", 'ddb_g', 'genename'])
        return res2

    def annotationTypes(self):
        """
        Returns all annotation types.
        """
        return self.aoids.keys()

    def objects(self):
        """
        Returns all objects.
        """
        return self.obids.keys()

    def __annotationTypes(self):
        """
        Returns list of [ annotation_object_id, name ]
        """
        res, legend = self.sq("action=get_annotation_types")
        res2 = onlyColumns(res, legend, ["annotation_object_id", 'name'])
        return res2

    def __objects(self):
        res, legend = self.sq("action=get_objects")
        res2 = onlyColumns(res, legend, ["object_id", 'object_name'])
        return res2

    def spotMap(self):
        spotids = self.spotId()
        spotmap = [ (a[0],a[1]) for a in spotids ]

        spotmapd = {}

        for a,b in spotmap:
            if a in spotmapd:
                spotmapd[a] = spotmapd[a] + "-" + b
            else:
                spotmapd[a] = b

        return spotmapd

    def getData(self, *args, **kwargs):
        deprecatedError("Use get_single_data instead")

    def get_data(self, type="norms", exclude_constant_labels=False, average=median, 
        ids=None, callback=None, format="short", transform=None, allowed_labels=None, **kwargs):
        """
        Get data in a single example table with labels of individual attributes
        set to annotations for query and post-processing
        instructions.

        Parameters: 
            average: function used for combining multiple reading of the same spot on
                a chip. If None, no averaging is done. Fuction should take a list
                of floats and return an "averaged" float.
            ids: a list of chip ids. If absent, make a search
            exclude_constant_labels: if a label has the same value in whole 
                example table, remove it
            format: if short, use short format for chip download

        Defaults: Median averaging.
        """

        def optcb():
            if callback: callback()

        cbc = CallBack(1, optcb, callbacks=10)

        if not ids:
            #returns ids of elements that match the search function
            ids = self.search(type, **kwargs)

        cbc.end()

        #downloads annotations
        cbc = CallBack(len(ids), optcb, callbacks=10)

        readall = self.dictionarize(ids, self.annotations, type, ids, all=True, callback=cbc)

        read = {}
        for a,b in readall.items():
            read[a] = self.keepOnlyMeaningful(b)

        annotsinlist = [] #annotations in the same order
        for id in ids:
            annotsinlist.append(readall[id])

        if verbose:
            print zip(ids,[ dict(a)['chips.chip_map_id'] for a in annotsinlist ])

        cbc.end()

        #till now downloads were small

        import time
        tstart = time.time()

        #here download actually happens
        chipfn = None

        if type == "norms":
            if format == "short":
                chipfn = lambda x, al=annotsinlist: self.chipNsN(x, al)
            else:
                chipfn = self.chipNs
        else:
            chipfn = self.chipRs
        
        if verbose:
            print "DOWNLOAD TIME", time.time() - tstart

        cbc = CallBack(len(ids)*2+len(ids)+1, optcb, callbacks=999-30)
        et = self.exampleTables(ids, spotmap=self.spotMap(), callback=cbc, annots=read, exclude_constant_labels=exclude_constant_labels, chipfn=chipfn, allowed_labels=allowed_labels)
        cbc.end()

        cbc = CallBack(1, optcb, callbacks=10)

        #transformation is performed prior to averaging
        if transform != None:
            transformValues(et, fn=transform) #in place transform
            cbc()

        #if average function is given, use it to join same spotids
        if average != None:
            et = averageAttributes(et, fn=average)
            cbc()

        cbc.end()

        return et
    
    def get_single_data(self, *args, **kwargs):
        return self.get_data(*args, **kwargs)

class DatabaseConnection(DictyExpress):
    pass

def allAnnotationVals(annots):
    """
    All annotation valuess for given annotations
    in a dict of { name: set of possible values } pairs.
    """
    av = defaultdict(set)
    for a in annots:
        for name,val in a:
            av[name].add(val)
    return av

def createExampleTable(names, vals, annots, ddb, cname="DDB", \
        exclude_constant_labels=False, permutation=None, always_include=["id"], allowed_labels=None):
    """
    Create an ExampleTable for this group. Attributes are those in
    names. 
    """
    attributes = [ orange.FloatVariable(n, numberOfDecimals=3) \
        for n in names ]

    #exclusion of names with constant values
    annotsvals = allAnnotationVals(annots)
    oknames = set(annotsvals.keys())
    if exclude_constant_labels:
        oknames = set(nth(filter(lambda x: len(x[1]) > 1 or x[0] in always_include, 
            annotsvals.items()), 0))

    if allowed_labels != None:
        oknames = set(filter(lambda x: x in allowed_labels, oknames))

    #print oknames

    for a,an in zip(attributes, annots):
        a.setattr("attributes", dict([(name,str(val)) for name,val in an if name in oknames]))

    domain = orange.Domain(attributes, False)
    ddbv = orange.StringVariable(cname)
    id = orange.newmetaid()
    domain.addmeta(id, ddbv)

    examples = [ None ]*len(ddb)
    for i,(v,d) in enumerate(izip(izip(*vals), ddb)):
        ex = orange.Example(domain, [ floatOrUnknown(a) for a in v ])
        ex[cname] = d

        if permutation:
            examples[permutation[i]] = ex
        else:
            examples[i] = ex

    return orange.ExampleTable(domain,examples)

def transformValues(data, fn):
    """
    In place transformation.
    """
    for ex in data:
        for at in data.domain.attributes:
            if not ex[at].isSpecial():
                ex[at] = fn(ex[at])

def averageAttributes(data, joinc="DDB", fn=median):
    """
    Averages attributes with the same "join" parameter using
    specified function. Builds a now dataset. Order of
    "join" parameter stays the same with regard to first
    appearance.
    """

    if verbose:
        print "Averaging attributes"

    valueso = []
    valuess = set(valueso)

    attributes = [ a for a in data.domain.attributes ]
    domain = data.domain
    
    #accumulate values

    for ex in data:
        j = str(ex[joinc])

        if j not in valuess:
            valueso.append(j)
            valuess.add(j)

    valuesddb = [ dict( (n,[]) for n in valueso) for at in attributes ]
    
    for ex in data:
        j = str(ex[joinc])

        for a in range(len(attributes)):
            val = ex[a]
            if not val.isSpecial():
                valuesddb[a][j].append(val.native())

    #create a new example table reusing the domain - apply fn
    examples = []
    for v in valueso:
        example = orange.Example(domain, \
            [ floatOrUnknown(fn(valuesddb[a][v])) for a in range(len(attributes)) ] )
        example[joinc] = v
        examples.append(example)

    return orange.ExampleTable(domain, examples)

def floatOrUnknown(a):
    """
    Converts an element to float if possible.
    If now, output "?".
    """
    try:
        return float(a)
    except:
        return "?"

class CallBack():
    """
    Converts "allparts" callbacks into by "callbacks"
    specified number of callbacks of function fn.
    """

    def __init__(self, allparts, fn, callbacks=100):
        self.allparts = allparts
        self.lastreport = 0.00001
        self.getparts = 0
        self.increase = 1.0/callbacks
        self.callbacks = callbacks
        self.fn = fn
        self.cbs = 0

    def __call__(self):
        self.getparts += 1
        done = float(self.getparts)/self.allparts
        while done > self.lastreport + self.increase:
            self.lastreport += self.increase
            self.fn()
            self.cbs += 1

    def end(self):
        while self.cbs < self.callbacks:
            self.fn()
            self.cbs += 1

class BufferSQLite(object):

    def __init__(self, filename, compress=True):
        self.compress = compress
        self.filename = filename
        self.conn = self.connect()

    def clear(self):
        """
        Removes all entries in the buffer
        """
        self.conn.close()
        os.remove(self.filename)
        self.conn = self.connect()

    def connect(self):
        import sqlite3
        conn = sqlite3.connect(self.filename)
        c = conn.cursor()
        c.execute('''create table if not exists buf
        (address text primary key, time text, con blob)''')
        c.close()
        conn.commit()
        return conn

    def contains(self, addr):
        """ Returns version or False, if it does not exists """
        c = self.conn.cursor()
        c.execute('select time from buf where address=?', (addr,))
        lc = list(c)
        c.close()
        if len(lc) == 0:
            return False
        else:
            return lc[0][0]

    def list(self):
        c = self.conn.cursor()
        c.execute('select address from buf')
        return nth(list(c), 0)

    def add(self, addr, con, version="0", autocommit=True):
        import cPickle, zlib, sqlite3
        if verbose:
            print "Adding", addr
        c = self.conn.cursor()
        if self.compress:
            bin = sqlite3.Binary(zlib.compress(cPickle.dumps(con)))
        else:
            bin = sqlite3.Binary(cPickle.dumps(con))
        c.execute('insert or replace into buf values (?,?,?)', (addr, version, bin))
        c.close()
        if autocommit:
            self.commit()

    def commit(self):
        self.conn.commit()

    def get(self, addr):
        import cPickle, zlib
        if verbose:
            print "getting from buffer", addr
            t = time.time()
        c = self.conn.cursor()
        c.execute('select con from buf where address=?', (addr,))
        ls = list(c)
        first = ls[0][0]
        if verbose:
            print time.time() - t
        if self.compress:
            rc = cPickle.loads(zlib.decompress(first))
        else:
            rc = cPickle.loads(str(first))
        c.close()

        if verbose:
            print time.time() - t
        return rc

def download_url(url, repeat=2):
    def do():
        return urllib2.urlopen(url)

    if repeat <= 0:
        do()
    else:
        try:
            return do()
        except:
            return download_url(url, repeat=repeat-1)

def empty_none(s):
    if s:
        return s
    else:
        return None

def join_ats(atts):
    """ Joins attribute attributes together. If all values are the same,
    set the parameter to the common value, else return a list of the
    values in the same order as the attributes are imputed. """
    keys = reduce(lambda x,y: x | y, (set(at.keys()) for at in atts))
    od = {}

    def man(x):
        if issequencens(x):
            return tuple(x)
        else:
            return x

    for k in keys:
        s = set(man(at[k]) for at in atts)
        if len(s) == 1:
            od[k] = list(s)[0]
        else:
            od[k] = str([ at[k] for at in atts ])
    return od

def join_replicates(data, ignorenames=["replicate", "id", "name", "map_stop1"], namefn=None, avg=median):
    """ Join replicates by median. 
    Default parameters work for PIPA data.
    Sort elements in the same order as ignorenames!
    """

    d = defaultdict(list)

    if namefn == None:
        namefn = lambda att: ",".join(att["id"]) if issequencens(att["id"]) else att["id"]

    #key function
    def key_g(att):
        dk = att.copy()
        for iname in ignorenames:
            dk.pop(iname, None)
        
        def man(x):
            if issequencens(x):
                return tuple(x)
            else:
                return x

        return tuple(nth(sorted(((a, man(b)) for a,b in dk.items())), 1))

    #prepare groups
    for i,a in enumerate(data.domain.attributes):
        att = a.attributes
        k = key_g(att)
        d[k].append(i)

    d = dict(d) #want errors with wrong keys

    natts = []

    def nativeOrNone(val):
        if val.isSpecial(): 
            return None
        else: 
            return val.native()

    def avgnone(l):
        """ Removes None and run avg function"""
        l = filter(lambda x: x != None, l)
        if len(l):
            return avg(l)
        else:
            return None

    def data_type(vals): #data type converter
        try:
            _ = [ int(a) for a in vals ]
            return int
        except:
            try:
                _ = [ float(a) for a in vals ]
                return float
            except:
                return lambda x: x

    all_values = defaultdict(set)
    for a in [ at.attributes for at in data.domain.attributes ]:
        for k,v in a.iteritems():
            all_values[k].add(v)

    types = {}
    for k,vals in all_values.iteritems():
        types[k] = data_type(vals)

    for group, elements in d.items():
        a = orange.FloatVariable()
        #here sort elements
    
        def sk(x):
            return [ types[n](x[n]) for n in ignorenames if n in all_values ]

        elements = sorted(elements, key=lambda x: sk(data.domain.attributes[x].attributes))

        a.attributes.update(join_ats([data.domain.attributes[i].attributes for i in elements]))
        a.name = namefn(a.attributes)

        def avgel(ex, el):
            return orange.Value(avgnone([ nativeOrNone(ex[ind]) for ind in el ]))

        a.getValueFrom = lambda ex,rw,el=elements: avgel(ex,el)
        natts.append(a)

    ndom = orange.Domain(natts, data.domain.classVar)
    ndom.addmetas(data.domain.getmetas())
    return orange.ExampleTable(ndom, data)


class DictyBase(object):

    domain = "dictybase"
    filename = "information_mappings.pck"
    tags = [ "Dictyostelium discoideum", "gene", "essential", "dictyBase" ] 
 
    @classmethod
    def version(cls):
        orngServerFiles.localpath_download(cls.domain, cls.filename)
        return orngServerFiles.info(cls.domain, cls.filename)["datetime"]
    
    @classmethod
    def download_information(cls):
        """ 
        Downloads gene information and parses it. 
        Returns a dictionary {ID: (name, synonyms, products)}
        """
        s = download_url("http://www.dictybase.org/db/cgi-bin/dictyBase/download/download.pl?area=general&ID=gene_information.txt").read()
        out = []
        for l in txt2ll(s, separ='\t', lineSepar='\n')[1:]:
            if len(l) == 4:
                id = l[0]
                name = l[1]
                synonyms = filter(None, l[2].split(", "))
                products = l[3]
                out.append((id, name, synonyms, products))
        return dict((a,(b,c,d)) for a,b,c,d in out)

    @classmethod
    def download_mappings(cls):
        """ 
        Downloads DDB-GeneID-UniProt mappings and parses them. 
        Returns a list of (ddb, ddb_g, uniprot) triplets.
        
        2009/04/07: ddb's appear unique
        """
        s = download_url("http://www.dictybase.org/db/cgi-bin/dictyBase/download/download.pl?area=general&ID=DDB-GeneID-UniProt.txt").read()
        out = []
        for l in txt2ll(s, separ='\t', lineSepar='\n')[1:]:
            if len(l) == 4:
                ddb = empty_none(l[0])
                ddb_g = empty_none(l[1])
                name = empty_none(l[2])
                uniprot = empty_none(l[3])
                out.append((ddb, ddb_g, name, uniprot))
        return out

    @classmethod
    def pickle_data(cls):
        info = cls.download_information()
        mappings = cls.download_mappings()
        return pickle.dumps((info,mappings), -1)

    def __init__(self):
        fn = orngServerFiles.localpath_download(self.domain, self.filename)
        self.info, self.mappings = pickle.load(open(fn, 'rb'))

if __name__=="__main__":
    verbose = 1

    def printet(et):
        et.save("ett.tab")
        print open("ett.tab").read()

    """
    a = DictyBase()
    print len(a.info)

    dbc = DictyExpress(buffer=BufferSQLite("../tmpbufnew"))

    print dbc.annotationOptions()

    count = 0
    def cb():
        global count
        count += 1
        #print "CBBB", count

    et = dbc.get_single_data(sample=[ "tagA-", "pkaC-"], callback=cb, exclude_constant_labels=True, allowed_labels=["sample"])
    print et.domain
    print et.domain[0].attributes
    printet(et)
    """

    d = PIPA(buffer=BufferSQLite("../tmpbufnewpipa"))

    print d.gene_expression_types()

    cov = d.coverage("777", chromosome=1, genome="dd")
    print cov

    allids = d.annotations().keys()
    allids = allids[:1]
    print ("list", allids)
    print d.annotations().items()[0]
    print ("annots", d.annotations().items()[:2])

    allids = map(str, allids)

    import math

    data = d.get_data(ids=allids, ctype="3")

    #data = d.get_data(ids=allids, transform=lambda x: math.log(x+1, 2), allowed_labels=["strain"], ctype="3")

    printet(data)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.