[973924]: / qiita_db / software.py

Download this file

2061 lines (1793 with data), 76.9 kB

   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
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from json import dumps, loads
from copy import deepcopy
import inspect
import warnings
import networkx as nx
from qiita_core.qiita_settings import qiita_config
import qiita_db as qdb
from configparser import ConfigParser
class Command(qdb.base.QiitaObject):
r"""An executable command available in the system
Attributes
----------
active
post_processing_cmd
analysis_only
default_parameter_sets
description
merging_scheme
name
naming_order
optional_parameters
outputs
parameters
required_parameters
software
description
cli
parameters_table
Methods
-------
_check_id
activate
Class Methods
-------------
create
exists
get_commands_by_input_type
get_html_generator
get_validator
See Also
--------
qiita_db.software.Software
"""
_table = "software_command"
@classmethod
def get_commands_by_input_type(cls, artifact_types, active_only=True,
exclude_analysis=True, prep_type=None):
"""Returns the commands that can process the given artifact types
Parameters
----------
artifact_type : list of str
The artifact types
active_only : bool, optional
If True, return only active commands, otherwise return all commands
Default: True
exclude_analysis : bool, optional
If True, return commands that are not part of the analysis pipeline
Returns
-------
generator of qiita_db.software.Command
The commands that can process the given artifact tyoes
"""
with qdb.sql_connection.TRN:
sql = """SELECT DISTINCT command_id
FROM qiita.command_parameter
JOIN qiita.parameter_artifact_type
USING (command_parameter_id)
JOIN qiita.artifact_type USING (artifact_type_id)
JOIN qiita.software_command USING (command_id)
WHERE artifact_type IN %s"""
if active_only:
sql += " AND active = True"
if exclude_analysis:
sql += " AND is_analysis = False"
qdb.sql_connection.TRN.add(sql, [tuple(artifact_types)])
cids = set(qdb.sql_connection.TRN.execute_fetchflatten())
if prep_type is not None:
dws = [w for w in qdb.software.DefaultWorkflow.iter()
if prep_type in w.data_type]
if dws:
cmds = {n.default_parameter.command.id
for w in dws for n in w.graph.nodes}
cids = cmds & cids
return [cls(cid) for cid in cids]
@classmethod
def get_html_generator(cls, artifact_type):
"""Returns the command that generete the HTML for the given artifact
Parameters
----------
artifact_type : str
The artifact type to search the HTML generator for
Returns
-------
qiita_db.software.Command
The newly created command
Raises
------
qdb.exceptions.QiitaDBError when the generete the HTML command can't
be found
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_id
FROM qiita.software_command
JOIN qiita.software_artifact_type USING (software_id)
JOIN qiita.artifact_type USING (artifact_type_id)
WHERE artifact_type = %s
AND name = 'Generate HTML summary'
AND active = true"""
qdb.sql_connection.TRN.add(sql, [artifact_type])
try:
res = qdb.sql_connection.TRN.execute_fetchlast()
except IndexError:
raise qdb.exceptions.QiitaDBError(
"There is no command to generate the HTML summary for "
"artifact type '%s'" % artifact_type)
return cls(res)
@classmethod
def get_validator(cls, artifact_type):
"""Returns the command that validates the given artifact
Parameters
----------
artifact_type : str
The artifact type to search the Validate for
Returns
-------
qiita_db.software.Command
The newly created command
Raises
------
qdb.exceptions.QiitaDBError when the Validate command can't be found
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_id
FROM qiita.software_command
JOIN qiita.software_artifact_type USING (software_id)
JOIN qiita.artifact_type USING (artifact_type_id)
WHERE artifact_type = %s
AND name = 'Validate'
AND active = true"""
qdb.sql_connection.TRN.add(sql, [artifact_type])
try:
res = qdb.sql_connection.TRN.execute_fetchlast()
except IndexError:
raise qdb.exceptions.QiitaDBError(
"There is no command to generate the Validate for "
"artifact type '%s'" % artifact_type)
return cls(res)
def _check_id(self, id_):
"""Check that the provided ID actually exists in the database
Parameters
----------
id_ : int
The ID to test
Notes
-----
This function overwrites the base function, as the sql layout doesn't
follow the same conventions done in the other classes.
"""
with qdb.sql_connection.TRN:
sql = """SELECT EXISTS(
SELECT *
FROM qiita.software_command
WHERE command_id = %s)"""
qdb.sql_connection.TRN.add(sql, [id_])
return qdb.sql_connection.TRN.execute_fetchlast()
@classmethod
def exists(cls, software, name):
"""Checks if the command already exists in the system
Parameters
----------
qiita_db.software.Software
The software to which this command belongs to.
name : str
The name of the command
Returns
-------
bool
Whether the command exists in the system or not
"""
with qdb.sql_connection.TRN:
sql = """SELECT EXISTS(SELECT *
FROM qiita.software_command
WHERE software_id = %s
AND name = %s)"""
qdb.sql_connection.TRN.add(sql, [software.id, name])
return qdb.sql_connection.TRN.execute_fetchlast()
@classmethod
def create(cls, software, name, description, parameters, outputs=None,
analysis_only=False):
r"""Creates a new command in the system
The supported types for the parameters are:
- string: the parameter is a free text input
- integer: the parameter is an integer
- float: the parameter is a float
- artifact: the parameter is an artifact instance, the artifact id
will be stored
- reference: the parameter is a reference instance, the reference
id will be stored
- choice: the format of this should be `choice:<json-dump-of-list>`
in which json-dump-of-list is the JSON dump of a list containing
the acceptable values
Parameters
----------
software : qiita_db.software.Software
The software to which this command belongs to.
name : str
The name of the command
description : str
The description of the command
parameters : dict
The description of the parameters that this command received. The
format is: {parameter_name: (parameter_type, default, name_order,
check_biom_merge, qiita_optional_parameter (optional))},
where parameter_name, parameter_type and default are strings,
name_order is an optional integer value and check_biom_merge is
an optional boolean value. name_order is used to specify the order
of the parameter when automatically naming the artifacts.
check_biom_merge is used when merging artifacts in the analysis
pipeline. qiita_optional_parameter is an optional bool to "force"
the parameter to be optional
outputs : dict, optional
The description of the outputs that this command generated. The
format is either {output_name: artifact_type} or
{output_name: (artifact_type, check_biom_merge)}
analysis_only : bool, optional
If true, then the command will only be available on the analysis
pipeline. Default: False.
Returns
-------
qiita_db.software.Command
The newly created command
Raises
------
QiitaDBError
- If parameters is empty
- If the parameters dictionary is malformed
- If one of the parameter types is not supported
- If the default value of a choice parameter is not listed in
the available choices
QiitaDBDuplicateError
- If the command already exists
Notes
-----
If the default value for a parameter is NULL, then the parameter will
be required. On the other hand, if it is provided, the parameter will
be optional and the default value will be used when the user doesn't
overwrite it.
"""
# Perform some sanity checks in the parameters dictionary
if not parameters:
raise qdb.exceptions.QiitaDBError(
"Error creating command %s. At least one parameter should "
"be provided." % name)
sql_param_values = []
sql_artifact_params = []
for pname, vals in parameters.items():
qiita_optional_parameter = False
if 'qiita_optional_parameter' in vals:
qiita_optional_parameter = True
vals.remove('qiita_optional_parameter')
lenvals = len(vals)
if lenvals == 2:
ptype, dflt = vals
name_order = None
check_biom_merge = False
elif lenvals == 4:
ptype, dflt, name_order, check_biom_merge = vals
else:
raise qdb.exceptions.QiitaDBError(
"Malformed parameters dictionary, the format should be "
"either {param_name: [parameter_type, default]} or "
"{parameter_name: (parameter_type, default, name_order, "
"check_biom_merge)}. Found: %s for parameter name %s"
% (vals, pname))
# Check that the type is one of the supported types
supported_types = ['string', 'integer', 'float', 'reference',
'boolean', 'prep_template', 'analysis']
if ptype not in supported_types and not ptype.startswith(
('choice', 'mchoice', 'artifact')):
supported_types.extend(['choice', 'mchoice', 'artifact'])
raise qdb.exceptions.QiitaDBError(
"Unsupported parameters type '%s' for parameter %s. "
"Supported types are: %s"
% (ptype, pname, ', '.join(supported_types)))
if ptype.startswith(('choice', 'mchoice')) and dflt is not None:
choices = set(loads(ptype.split(':')[1]))
dflt_val = dflt
if ptype.startswith('choice'):
# In the choice case, the dflt value is a single string,
# create a list with it the string on it to use the
# issuperset call below
dflt_val = [dflt_val]
else:
# jsonize the list to store it in the DB
dflt = dumps(dflt)
if not choices.issuperset(dflt_val):
raise qdb.exceptions.QiitaDBError(
"The default value '%s' for the parameter %s is not "
"listed in the available choices: %s"
% (dflt, pname, ', '.join(choices)))
if ptype.startswith('artifact'):
atypes = loads(ptype.split(':')[1])
sql_artifact_params.append(
[pname, 'artifact', atypes])
else:
# a parameter will be required (not optional) if
# qiita_optional_parameter is false and there is the default
# value (dflt) is None
required = not qiita_optional_parameter and dflt is None
sql_param_values.append([pname, ptype, required, dflt,
name_order, check_biom_merge])
with qdb.sql_connection.TRN:
if cls.exists(software, name):
raise qdb.exceptions.QiitaDBDuplicateError(
"command", "software: %d, name: %s"
% (software.id, name))
# Add the command to the DB
sql = """INSERT INTO qiita.software_command
(name, software_id, description, is_analysis)
VALUES (%s, %s, %s, %s)
RETURNING command_id"""
sql_params = [name, software.id, description, analysis_only]
qdb.sql_connection.TRN.add(sql, sql_params)
c_id = qdb.sql_connection.TRN.execute_fetchlast()
# Add the parameters to the DB
sql = """INSERT INTO qiita.command_parameter
(command_id, parameter_name, parameter_type,
required, default_value, name_order, check_biom_merge)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING command_parameter_id"""
sql_params = [
[c_id, pname, p_type, reqd, default, no, chm]
for pname, p_type, reqd, default, no, chm in sql_param_values]
qdb.sql_connection.TRN.add(sql, sql_params, many=True)
qdb.sql_connection.TRN.execute()
# Add the artifact parameters
sql_type = """INSERT INTO qiita.parameter_artifact_type
(command_parameter_id, artifact_type_id)
VALUES (%s, %s)"""
supported_types = []
for pname, p_type, atypes in sql_artifact_params:
sql_params = [c_id, pname, p_type, True, None, None, False]
qdb.sql_connection.TRN.add(sql, sql_params)
pid = qdb.sql_connection.TRN.execute_fetchlast()
sql_params = [
[pid, qdb.util.convert_to_id(at, 'artifact_type')]
for at in atypes]
qdb.sql_connection.TRN.add(sql_type, sql_params, many=True)
supported_types.extend([atid for _, atid in sql_params])
# If the software type is 'artifact definition', there are a couple
# of extra steps
if software.type == 'artifact definition':
# If supported types is not empty, link the software with these
# types
if supported_types:
sql = """INSERT INTO qiita.software_artifact_type
(software_id, artifact_type_id)
VALUES (%s, %s)"""
sql_params = [[software.id, atid]
for atid in supported_types]
qdb.sql_connection.TRN.add(sql, sql_params, many=True)
# If this is the validate command, we need to add the
# provenance and name parameters. These are used internally,
# that's why we are adding them here
if name == 'Validate':
sql = """INSERT INTO qiita.command_parameter
(command_id, parameter_name, parameter_type,
required, default_value)
VALUES (%s, 'name', 'string', 'False',
'dflt_name'),
(%s, 'provenance', 'string', 'False', NULL)
"""
qdb.sql_connection.TRN.add(sql, [c_id, c_id])
# Add the outputs to the command
if outputs:
sql_args = []
for pname, at in outputs.items():
if isinstance(at, tuple):
sql_args.append(
[pname, c_id,
qdb.util.convert_to_id(at[0], 'artifact_type'),
at[1]])
else:
try:
at_id = qdb.util.convert_to_id(at, 'artifact_type')
except qdb.exceptions.QiitaDBLookupError:
msg = (f'Error creating {software.name}, {name}, '
f'{description} - Unknown artifact_type: '
f'{at}')
raise ValueError(msg)
sql_args.append([pname, c_id, at_id, False])
sql = """INSERT INTO qiita.command_output
(name, command_id, artifact_type_id,
check_biom_merge)
VALUES (%s, %s, %s, %s)"""
qdb.sql_connection.TRN.add(sql, sql_args, many=True)
qdb.sql_connection.TRN.execute()
return cls(c_id)
@property
def software(self):
"""The software to which this command belongs to
Returns
-------
qiita_db.software.Software
the software to which this command belongs to
"""
with qdb.sql_connection.TRN:
sql = """SELECT software_id
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return Software(qdb.sql_connection.TRN.execute_fetchlast())
@property
def name(self):
"""The name of the command
Returns
-------
str
The name of the command
"""
with qdb.sql_connection.TRN:
sql = """SELECT name
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def post_processing_cmd(self):
"""Additional processing commands required for merging
Returns
-------
str
Returns the additional processing command for merging
"""
with qdb.sql_connection.TRN:
sql = """SELECT post_processing_cmd
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
cmd = qdb.sql_connection.TRN.execute_fetchlast()
if cmd:
# assume correctly formatted json data
# load data into dictionary; don't return JSON
return loads(qdb.sql_connection.TRN.execute_fetchlast())
return None
@property
def description(self):
"""The description of the command
Returns
-------
str
The description of the command
"""
with qdb.sql_connection.TRN:
sql = """SELECT description
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def parameters(self):
"""Returns the parameters that the command accepts
Returns
-------
dict
Dictionary of {parameter_name: [ptype, dflt]}
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_name, parameter_type, default_value
FROM qiita.command_parameter
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
res = qdb.sql_connection.TRN.execute_fetchindex()
return {pname: [ptype, dflt] for pname, ptype, dflt in res}
@property
def required_parameters(self):
"""Returns the required parameters that the command accepts
Returns
-------
dict
Dictionary of {parameter_name: ptype}
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_parameter_id, parameter_name,
parameter_type, array_agg(
artifact_type ORDER BY artifact_type) AS
artifact_type
FROM qiita.command_parameter
LEFT JOIN qiita.parameter_artifact_type
USING (command_parameter_id)
LEFT JOIN qiita.artifact_type USING (artifact_type_id)
WHERE command_id = %s AND required = True
GROUP BY command_parameter_id"""
qdb.sql_connection.TRN.add(sql, [self.id])
res = qdb.sql_connection.TRN.execute_fetchindex()
return {pname: (ptype, atype) for _, pname, ptype, atype in res}
@property
def optional_parameters(self):
"""Returns the optional parameters that the command accepts
Returns
-------
dict
Dictionary of {parameter_name: [ptype, default]}
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_name, parameter_type, default_value
FROM qiita.command_parameter
WHERE command_id = %s AND required = false"""
qdb.sql_connection.TRN.add(sql, [self.id])
res = qdb.sql_connection.TRN.execute_fetchindex()
# Define a function to load the json storing the default parameters
# if ptype is multiple choice. When I added it to the for loop as
# a one liner if, made the code a bit hard to read
def dflt_fmt(dflt, ptype):
if ptype.startswith('mchoice'):
return loads(dflt)
return dflt
return {pname: [ptype, dflt_fmt(dflt, ptype)]
for pname, ptype, dflt in res}
@property
def default_parameter_sets(self):
"""Returns the list of default parameter sets
Returns
-------
generator
generator of qiita_db.software.DefaultParameters
"""
with qdb.sql_connection.TRN:
sql = """SELECT default_parameter_set_id
FROM qiita.default_parameter_set
WHERE command_id = %s
ORDER BY default_parameter_set_id"""
qdb.sql_connection.TRN.add(sql, [self.id])
res = qdb.sql_connection.TRN.execute_fetchflatten()
for pid in res:
yield DefaultParameters(pid)
@property
def outputs(self):
"""Returns the list of output artifact types
Returns
-------
list of str
The output artifact types
"""
with qdb.sql_connection.TRN:
sql = """SELECT name, artifact_type
FROM qiita.command_output
JOIN qiita.artifact_type USING (artifact_type_id)
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchindex()
@property
def active(self):
"""Returns if the command is active or not
Returns
-------
bool
Whether the command is active or not
Notes
-----
This method differentiates between commands based on analysis_only or
the software type. The commands that are not for analysis (processing)
and are from an artifact definition software will return as active
if they have the same name than a command that is active; this helps
for situations where the processing plugins are updated but some
commands didn't change its version.
"""
with qdb.sql_connection.TRN:
cmd_type = self.software.type
if self.analysis_only or cmd_type == 'artifact definition':
sql = """SELECT active
FROM qiita.software_command
WHERE command_id = %s"""
else:
sql = """SELECT EXISTS (
SELECT active FROM qiita.software_command
WHERE name IN (
SELECT name FROM qiita.software_command
WHERE command_id = %s) AND active = true)"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
def activate(self):
"""Activates the command"""
sql = """UPDATE qiita.software_command
SET active = %s
WHERE command_id = %s"""
qdb.sql_connection.perform_as_transaction(sql, [True, self.id])
@property
def analysis_only(self):
"""Returns if the command is an analysis-only command
Returns
-------
bool
Whether the command is analysis only or not
"""
with qdb.sql_connection.TRN:
sql = """SELECT is_analysis
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def naming_order(self):
"""The ordered list of parameters to use to name the output artifacts
Returns
-------
list of str
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_name
FROM qiita.command_parameter
WHERE command_id = %s AND name_order IS NOT NULL
ORDER BY name_order"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchflatten()
@property
def merging_scheme(self):
"""The values to check when merging the output result
Returns
-------
dict of {'parameters': [list of str],
'outputs': [list of str]
'ignore_parent_command': bool}
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_name
FROM qiita.command_parameter
WHERE command_id = %s AND check_biom_merge = TRUE
ORDER BY parameter_name"""
qdb.sql_connection.TRN.add(sql, [self.id])
params = qdb.sql_connection.TRN.execute_fetchflatten()
sql = """SELECT name
FROM qiita.command_output
WHERE command_id = %s AND check_biom_merge = TRUE
ORDER BY name"""
qdb.sql_connection.TRN.add(sql, [self.id])
outputs = qdb.sql_connection.TRN.execute_fetchflatten()
sql = """SELECT ignore_parent_command
FROM qiita.software_command
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
ipc = qdb.sql_connection.TRN.execute_fetchlast()
return {'parameters': params,
'outputs': outputs,
'ignore_parent_command': ipc}
@property
def resource_allocation(self):
"""The resource allocation defined in the database for this command
Returns
-------
str
"""
with qdb.sql_connection.TRN:
sql = """SELECT allocation FROM
qiita.processing_job_resource_allocation
WHERE name = %s and
job_type = 'RESOURCE_PARAMS_COMMAND'"""
qdb.sql_connection.TRN.add(sql, [self.name])
result = qdb.sql_connection.TRN.execute_fetchflatten()
# if no matches for both type and name were found, query the
# 'default' value for the type
if not result:
sql = """SELECT allocation FROM
qiita.processing_job_resource_allocation WHERE
name = %s and job_type = 'RESOURCE_PARAMS_COMMAND'"""
qdb.sql_connection.TRN.add(sql, ['default'])
result = qdb.sql_connection.TRN.execute_fetchflatten()
if not result:
raise ValueError("Could not match '%s' to a resource "
"allocation!" % self.name)
return result[0]
@property
def processing_jobs(self):
"""All the processing_jobs that used this command
Returns
-------
list of qiita_db.processing_job.ProcessingJob
List of jobs that used this command.
"""
with qdb.sql_connection.TRN:
sql = """SELECT processing_job_id FROM
qiita.processing_job
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
jids = qdb.sql_connection.TRN.execute_fetchflatten()
return [qdb.processing_job.ProcessingJob(j) for j in jids]
class Software(qdb.base.QiitaObject):
r"""A software package available in the system
Attributes
----------
name
version
description
commands
publications
environment_name
start_script
Methods
-------
add_publications
create
See Also
--------
qiita_db.software.Command
"""
_table = "software"
@classmethod
def iter(cls, active=True):
"""Iterates over all active software
Parameters
----------
active : bool, optional
If True will only return active software
Returns
-------
list of qiita_db.software.Software
The software objects
"""
sql = """SELECT software_id
FROM qiita.software {0}
ORDER BY software_id""".format(
'WHERE active = True' if active else '')
with qdb.sql_connection.TRN:
qdb.sql_connection.TRN.add(sql)
for s_id in qdb.sql_connection.TRN.execute_fetchflatten():
yield cls(s_id)
@classmethod
def deactivate_all(cls):
"""Deactivates all the plugins in the system"""
with qdb.sql_connection.TRN:
sql = "UPDATE qiita.software SET active = False"
qdb.sql_connection.TRN.add(sql)
sql = "UPDATE qiita.software_command SET active = False"
qdb.sql_connection.TRN.add(sql)
qdb.sql_connection.TRN.execute()
@classmethod
def from_file(cls, fp, update=False):
"""Installs/updates a plugin from a plugin configuration file
Parameters
----------
fp : str
Path to the plugin configuration file
update : bool, optional
If true, update the values in the database with the current values
in the config file. Otherwise, use stored values and warn if config
file contents and database contents do not match
Returns
-------
qiita_db.software.Software
The software object for the contents of `fp`
Raises
------
qiita_db.exceptions.QiitaDBOperationNotPermittedError
If the plugin type in the DB and in the config file doesn't match
If the (client_id, client_secret) pair in the DB and in the config
file doesn't match
"""
config = ConfigParser()
with open(fp, newline=None) as conf_file:
config.read_file(conf_file)
name = config.get('main', 'NAME')
version = config.get('main', 'VERSION')
description = config.get('main', 'DESCRIPTION')
env_script = config.get('main', 'ENVIRONMENT_SCRIPT')
start_script = config.get('main', 'START_SCRIPT')
software_type = config.get('main', 'PLUGIN_TYPE')
publications = config.get('main', 'PUBLICATIONS')
publications = loads(publications) if publications else []
client_id = config.get('oauth2', 'CLIENT_ID')
client_secret = config.get('oauth2', 'CLIENT_SECRET')
if cls.exists(name, version):
# This plugin already exists, check that all the values are the
# same and return the existing plugin
with qdb.sql_connection.TRN:
sql = """SELECT software_id
FROM qiita.software
WHERE name = %s AND version = %s"""
qdb.sql_connection.TRN.add(sql, [name, version])
instance = cls(qdb.sql_connection.TRN.execute_fetchlast())
warning_values = []
sql_update = """UPDATE qiita.software
SET {0} = %s
WHERE software_id = %s"""
values = [description, env_script, start_script]
attrs = ['description', 'environment_script', 'start_script']
for value, attr in zip(values, attrs):
if value != instance.__getattribute__(attr):
if update:
qdb.sql_connection.TRN.add(
sql_update.format(attr), [value, instance.id])
else:
warning_values.append(attr)
# Having a different plugin type should be an error,
# independently if the user is trying to update plugins or not
if software_type != instance.type:
raise qdb.exceptions.QiitaDBOperationNotPermittedError(
'The plugin type of the plugin "%s" version %s does '
'not match the one in the system' % (name, version))
if publications != instance.publications:
if update:
instance.add_publications(publications)
else:
warning_values.append('publications')
if (client_id != instance.client_id or
client_secret != instance.client_secret):
if update:
sql = """INSERT INTO qiita.oauth_identifiers
(client_id, client_secret)
SELECT %s, %s
WHERE NOT EXISTS(SELECT *
FROM qiita.oauth_identifiers
WHERE client_id = %s
AND client_secret = %s)"""
qdb.sql_connection.TRN.add(
sql, [client_id, client_secret,
client_id, client_secret])
sql = """UPDATE qiita.oauth_software
SET client_id = %s
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(
sql, [client_id, instance.id])
else:
raise qdb.exceptions.QiitaDBOperationNotPermittedError(
'The (client_id, client_secret) pair of the '
'plugin "%s" version "%s" does not match the one '
'in the system' % (name, version))
if warning_values:
warnings.warn(
'Plugin "%s" version "%s" config file does not match '
'with stored information. Check the config file or '
'run "qiita plugin update" to update the plugin '
'information. Offending values: %s'
% (name, version, ", ".join(sorted(warning_values))),
qdb.exceptions.QiitaDBWarning)
qdb.sql_connection.TRN.execute()
else:
# This is a new plugin, create it
instance = cls.create(
name, version, description, env_script, start_script,
software_type, publications=publications, client_id=client_id,
client_secret=client_secret)
return instance
@classmethod
def exists(cls, name, version):
"""Returns whether the plugin (name, version) already exists
Parameters
----------
name : str
The name of the plugin
version : str
The version of the plugin
"""
with qdb.sql_connection.TRN:
sql = """SELECT EXISTS(
SELECT * FROM qiita.software
WHERE name = %s AND version = %s)"""
qdb.sql_connection.TRN.add(sql, [name, version])
return qdb.sql_connection.TRN.execute_fetchlast()
@classmethod
def create(cls, name, version, description, environment_script,
start_script, software_type, publications=None,
client_id=None, client_secret=None):
r"""Creates a new software in the system
Parameters
----------
name : str
The name of the software
version : str
The version of the software
description : str
The description of the software
environment_script : str
The script used to start the environment in which the plugin runs
start_script : str
The script used to start the plugin
software_type : str
The type of the software
publications : list of (str, str), optional
A list with the (DOI, pubmed_id) of the publications attached to
the software
client_id : str, optional
The client_id of the software. Default: randomly generated
client_secret : str, optional
The client_secret of the software. Default: randomly generated
Raises
------
qiita_db.exceptions.QiitaDBError
If one of client_id or client_secret is provided but not both
"""
with qdb.sql_connection.TRN:
sql = """INSERT INTO qiita.software
(name, version, description, environment_script,
start_script, software_type_id)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING software_id"""
type_id = qdb.util.convert_to_id(software_type, "software_type")
sql_params = [name, version, description, environment_script,
start_script, type_id]
qdb.sql_connection.TRN.add(sql, sql_params)
s_id = qdb.sql_connection.TRN.execute_fetchlast()
instance = cls(s_id)
if publications:
instance.add_publications(publications)
id_is_none = client_id is None
secret_is_none = client_secret is None
if id_is_none and secret_is_none:
# Both are none, generate new ones
client_id = qdb.util.create_rand_string(50, punct=False)
client_secret = qdb.util.create_rand_string(255, punct=False)
elif id_is_none ^ secret_is_none:
# One has been provided but not the other, raise an error
raise qdb.exceptions.QiitaDBError(
'Plugin "%s" version "%s" cannot be created, please '
'provide both client_id and client_secret or none of them'
% (name, version))
# At this point both client_id and client_secret are defined
sql = """INSERT INTO qiita.oauth_identifiers
(client_id, client_secret)
SELECT %s, %s
WHERE NOT EXISTS(SELECT *
FROM qiita.oauth_identifiers
WHERE client_id = %s
AND client_secret = %s)"""
qdb.sql_connection.TRN.add(
sql, [client_id, client_secret, client_id, client_secret])
sql = """INSERT INTO qiita.oauth_software (software_id, client_id)
VALUES (%s, %s)"""
qdb.sql_connection.TRN.add(sql, [s_id, client_id])
return instance
@classmethod
def from_name_and_version(cls, name, version):
"""Returns the software object with the given name and version
Parameters
----------
name: str
The software name
version : str
The software version
Returns
-------
qiita_db.software.Software
The software with the given name and version
Raises
------
qiita_db.exceptions.QiitaDBUnknownIDError
If no software with the given name and version exists
"""
with qdb.sql_connection.TRN:
sql = """SELECT software_id
FROM qiita.software
WHERE name = %s AND version = %s"""
qdb.sql_connection.TRN.add(sql, [name, version])
res = qdb.sql_connection.TRN.execute_fetchindex()
if not res:
raise qdb.exceptions.QiitaDBUnknownIDError(
"%s %s" % (name, version), cls._table)
return cls(res[0][0])
@property
def name(self):
"""The name of the software
Returns
-------
str
The name of the software
"""
with qdb.sql_connection.TRN:
sql = "SELECT name FROM qiita.software WHERE software_id = %s"
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def version(self):
"""The version of the software
Returns
-------
str
The version of the software
"""
with qdb.sql_connection.TRN:
sql = "SELECT version FROM qiita.software WHERE software_id = %s"
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def description(self):
"""The description of the software
Returns
-------
str
The software description
"""
with qdb.sql_connection.TRN:
sql = """SELECT description
FROM qiita.software
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def commands(self):
"""The list of commands attached to this software
Returns
-------
list of qiita_db.software.Command
The commands attached to this software package
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_id
FROM qiita.software_command
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return [Command(cid)
for cid in qdb.sql_connection.TRN.execute_fetchflatten()]
def get_command(self, cmd_name):
"""Returns the command with the given name in the software
Parameters
----------
cmd_name: str
The command with the given name
Returns
-------
qiita_db.software.Command
The command with the given name in this software
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_id
FROM qiita.software_command
WHERE software_id =%s AND name=%s"""
qdb.sql_connection.TRN.add(sql, [self.id, cmd_name])
res = qdb.sql_connection.TRN.execute_fetchindex()
if not res:
raise qdb.exceptions.QiitaDBUnknownIDError(
cmd_name, "software_command")
return Command(res[0][0])
@property
def publications(self):
"""The publications attached to the software
Returns
-------
list of (str, str)
The list of DOI and pubmed_id attached to the publication
"""
with qdb.sql_connection.TRN:
sql = """SELECT p.doi, p.pubmed_id
FROM qiita.publication p
JOIN qiita.software_publication sp
ON p.doi = sp.publication_doi
WHERE sp.software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchindex()
def add_publications(self, publications):
"""Add publications to the software
Parameters
----------
publications : list of 2-tuples of str
A list with the (DOI, pubmed_id) of the publications to be attached
to the software
Notes
-----
For more information about pubmed id, visit
https://www.nlm.nih.gov/bsd/disted/pubmedtutorial/020_830.html
"""
with qdb.sql_connection.TRN:
sql = """INSERT INTO qiita.publication (doi, pubmed_id)
SELECT %s, %s
WHERE NOT EXISTS(SELECT *
FROM qiita.publication
WHERE doi = %s)"""
args = [[doi, pid, doi] for doi, pid in publications]
qdb.sql_connection.TRN.add(sql, args, many=True)
sql = """INSERT INTO qiita.software_publication
(software_id, publication_doi)
SELECT %s, %s
WHERE NOT EXISTS(SELECT *
FROM qiita.software_publication
WHERE software_id = %s AND
publication_doi = %s)"""
sql_params = [[self.id, doi, self.id, doi]
for doi, _ in publications]
qdb.sql_connection.TRN.add(sql, sql_params, many=True)
qdb.sql_connection.TRN.execute()
@property
def environment_script(self):
"""The script used to start the plugin environment
Returns
-------
str
The script used to start the environment
"""
with qdb.sql_connection.TRN:
sql = """SELECT environment_script
FROM qiita.software
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def start_script(self):
"""The script used to start the plugin
Returns
-------
str
The plugin's start script
"""
with qdb.sql_connection.TRN:
sql = """SELECT start_script
FROM qiita.software
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def type(self):
"""Returns the type of the software
Returns
-------
str
The type of the software
"""
with qdb.sql_connection.TRN:
sql = """SELECT software_type
FROM qiita.software_type
JOIN qiita.software USING (software_type_id)
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def deprecated(self):
"""Returns if the software is deprecated or not
Returns
-------
bool
Whether the software is deprecated or not
"""
with qdb.sql_connection.TRN:
sql = """SELECT deprecated
FROM qiita.software
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@deprecated.setter
def deprecated(self, deprecate):
"""Changes deprecated of the software
Parameters
----------
deprecate : bool
New software deprecate value
"""
sql = """UPDATE qiita.software SET deprecated = %s
WHERE software_id = %s"""
qdb.sql_connection.perform_as_transaction(sql, [deprecate, self._id])
@property
def active(self):
"""Returns if the software is active or not
Returns
-------
bool
Whether the software is active or not
"""
with qdb.sql_connection.TRN:
sql = "SELECT active FROM qiita.software WHERE software_id = %s"
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
def activate(self):
"""Activates the plugin"""
sql = """UPDATE qiita.software
SET active = %s
WHERE software_id = %s"""
qdb.sql_connection.perform_as_transaction(sql, [True, self.id])
@property
def client_id(self):
"""Returns the client id of the plugin
Returns
-------
str
The client id of the software
"""
with qdb.sql_connection.TRN:
sql = """SELECT client_id
FROM qiita.oauth_software
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def client_secret(self):
"""Returns the client secret of the plugin
Returns
-------
str
The client secrect of the plugin
"""
with qdb.sql_connection.TRN:
sql = """SELECT client_secret
FROM qiita.oauth_software
JOIN qiita.oauth_identifiers USING (client_id)
WHERE software_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
def register_commands(self):
"""Registers the software commands"""
url = "%s%s" % (qiita_config.base_url, qiita_config.portal_dir)
cmd = '%s; %s "%s" "register" "ignored"' % (
self.environment_script, self.start_script, url)
# it can be assumed that any command beginning with 'source'
# is calling 'source', an internal command of 'bash' and hence
# should be executed from bash, instead of sh.
# TODO: confirm that exit_code propagates from bash to sh to
# rv.
if cmd.startswith('source'):
cmd = "bash -c '%s'" % cmd
p_out, p_err, rv = qdb.processing_job._system_call(cmd)
if rv != 0:
s = "cmd: %s\nexit status: %d\n" % (cmd, rv)
s += "stdout: %s\nstderr: %s\n" % (p_out, p_err)
raise ValueError(s)
class DefaultParameters(qdb.base.QiitaObject):
"""Models a default set of parameters of a command
Attributes
----------
name
values
Methods
-------
exists
create
iter
to_str
to_file
See Also
--------
qiita_db.software.Command
"""
_table = 'default_parameter_set'
@classmethod
def exists(cls, command, **kwargs):
r"""Check if a parameter set already exists
Parameters
----------
command : qiita_db.software.Command
The command to which the parameter set belongs to
kwargs : dict of {str: str}
The parameters and their values
Returns
-------
bool
Whether if the parameter set exists in the given command
Raises
------
qiita_db.exceptions.QiitaDBError
- If there are missing parameters for the given command
- If `kwargs` contains parameters not originally defined in the
command
"""
with qdb.sql_connection.TRN:
command_params = set(command.optional_parameters)
user_params = set(kwargs)
missing_in_user = command_params - user_params
extra_in_user = user_params - command_params
if missing_in_user or extra_in_user:
raise qdb.exceptions.QiitaDBError(
"The given set of parameters do not match the ones for "
"the command.\nMissing parameters: %s\n"
"Extra parameters: %s\n"
% (', '.join(missing_in_user), ', '.join(extra_in_user)))
sql = """SELECT parameter_set
FROM qiita.default_parameter_set
WHERE command_id = %s"""
qdb.sql_connection.TRN.add(sql, [command.id])
for p_set in qdb.sql_connection.TRN.execute_fetchflatten():
if p_set == kwargs:
return True
return False
@classmethod
def create(cls, param_set_name, command, **kwargs):
r"""Create a new parameter set for the given command
Parameters
----------
param_set_name: str
The name of the new parameter set
command : qiita_db.software.Command
The command to add the new parameter set
kwargs : dict
The parameters and their values
Returns
-------
qiita_db.software.Parameters
The new parameter set instance
Raises
------
qiita_db.exceptions.QiitaDBError
- If there are missing parameters for the given command
- If there are extra parameters in `kwargs` than for the given
command
qdb.exceptions.QiitaDBDuplicateError
- If the parameter set already exists
"""
with qdb.sql_connection.TRN:
# setting to default values all parameters not in the user_params
cmd_params = command.optional_parameters
missing_in_user = {k: cmd_params[k][1]
for k in (set(cmd_params) - set(kwargs))}
if missing_in_user:
kwargs.update(missing_in_user)
# If the columns in kwargs and command do not match, cls.exists
# will raise the error for us
if cls.exists(command, **kwargs):
raise qdb.exceptions.QiitaDBDuplicateError(
cls._table, "Values: %s" % kwargs)
sql = """INSERT INTO qiita.default_parameter_set
(command_id, parameter_set_name, parameter_set)
VALUES (%s, %s, %s)
RETURNING default_parameter_set_id"""
sql_args = [command.id, param_set_name, dumps(kwargs)]
qdb.sql_connection.TRN.add(sql, sql_args)
return cls(qdb.sql_connection.TRN.execute_fetchlast())
@property
def name(self):
"""The name of the parameter set
Returns
-------
str
The name of the parameter set
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_set_name
FROM qiita.default_parameter_set
WHERE default_parameter_set_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def values(self):
"""The values of the parameter set
Returns
-------
dict of {str: object}
Dictionary with the parameters values keyed by parameter name
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameter_set
FROM qiita.default_parameter_set
WHERE default_parameter_set_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def command(self):
"""The command that this parameter set belongs to
Returns
-------
qiita_db.software.Command
The command that this parameter set belongs to
"""
with qdb.sql_connection.TRN:
sql = """SELECT command_id
FROM qiita.default_parameter_set
WHERE default_parameter_set_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return Command(qdb.sql_connection.TRN.execute_fetchlast())
class Parameters(object):
"""Represents an instance of parameters used to process an artifact
Raises
------
qiita_db.exceptions.QiitaDBOperationNotPermittedError
If trying to instantiate this class directly. In order to instantiate
this class, the classmethods `load` or `from_default_params` should
be used.
"""
def __eq__(self, other):
"""Equality based on the parameter values and the command"""
if type(self) is not type(other):
return False
if self.command != other.command:
return False
if self.values != other.values:
return False
return True
@classmethod
def load(cls, command, json_str=None, values_dict=None):
"""Load the parameters set form a json str or from a dict of values
Parameters
----------
command : qiita_db.software.Command
The command to which the parameter set belongs to
json_str : str, optional
The json string encoding the parameters
values_dict : dict of {str: object}, optional
The dictionary with the parameter values
Returns
-------
qiita_db.software.Parameters
The loaded parameter set
Raises
------
qiita_db.exceptions.QiitaDBError
- If `json_str` and `values` are both provided
- If neither `json_str` or `values` are provided
- If `json_str` or `values` do not encode a parameter set of
the provided command.
Notes
-----
The parameters `json_str` and `values_dict` are mutually exclusive,
only one of them should be provided at a time. However, one of them
should always be provided.
"""
if json_str is None and values_dict is None:
raise qdb.exceptions.QiitaDBError(
"Either `json_str` or `values_dict` should be provided.")
elif json_str is not None and values_dict is not None:
raise qdb.exceptions.QiitaDBError(
"Either `json_str` or `values_dict` should be provided, "
"but not both")
elif json_str is not None:
parameters = loads(json_str)
error_msg = ("The provided JSON string doesn't encode a "
"parameter set for command %s" % command.id)
else:
if not isinstance(values_dict, dict):
raise qdb.exceptions.QiitaDBError(
"The provided value_dict is %s (i.e. not None) but also "
"not a dictionary for command %s" % (
values_dict, command.id))
parameters = deepcopy(values_dict)
error_msg = ("The provided values dictionary doesn't encode a "
"parameter set for command %s" % command.id)
# setting to default values all parameters not in the user_params
cmd_params = command.optional_parameters
missing_in_user = {k: cmd_params[k][1]
for k in (set(cmd_params) - set(parameters))}
if missing_in_user:
parameters.update(missing_in_user)
with qdb.sql_connection.TRN:
cmd_reqd_params = command.required_parameters
cmd_opt_params = command.optional_parameters
values = {}
for key in cmd_reqd_params:
try:
values[key] = parameters.pop(key)
except KeyError:
raise qdb.exceptions.QiitaDBError(
"%s. Missing required parameter: %s"
% (error_msg, key))
for key in cmd_opt_params:
try:
values[key] = parameters.pop(key)
except KeyError:
raise qdb.exceptions.QiitaDBError(
"%s. Missing optional parameter: %s"
% (error_msg, key))
if parameters:
raise qdb.exceptions.QiitaDBError(
"%s. Extra parameters: %s"
% (error_msg, ', '.join(parameters.keys())))
return cls(values, command)
@classmethod
def from_default_params(cls, dflt_params, req_params, opt_params=None):
"""Creates the parameter set from a `dflt_params` set
Parameters
----------
dflt_params : qiita_db.software.DefaultParameters
The DefaultParameters object in which this instance is based on
req_params : dict of {str: object}
The required parameters values, keyed by parameter name
opt_params : dict of {str: object}, optional
The optional parameters to change from the default set, keyed by
parameter name. Default: None, use the values in `dflt_params`
Raises
------
QiitaDBError
- If there are missing requried parameters
- If there is an unknown required ot optional parameter
"""
with qdb.sql_connection.TRN:
command = dflt_params.command
cmd_req_params = command.required_parameters
cmd_opt_params = command.optional_parameters
missing_reqd = set(cmd_req_params) - set(req_params)
extra_reqd = set(req_params) - set(cmd_req_params)
if missing_reqd or extra_reqd:
raise qdb.exceptions.QiitaDBError(
"Provided required parameters not expected.\n"
"Missing required parameters: %s\n"
"Extra required parameters: %s\n"
% (', '.join(missing_reqd), ', '.join(extra_reqd)))
if opt_params:
extra_opts = set(opt_params) - set(cmd_opt_params)
if extra_opts:
raise qdb.exceptions.QiitaDBError(
"Extra optional parameters provded: %s"
% ', '.join(extra_opts))
values = dflt_params.values
values.update(req_params)
if opt_params:
values.update(opt_params)
return cls(values, command)
def __init__(self, values, command):
# Time for some python magic! The __init__ function should not be used
# outside of this module, users should always be using one of the above
# classmethods to instantiate the object. Lets test that it is the case
# First, we are going to get the current frame (i.e. this __init__)
# function and the caller to the __init__
current_frame = inspect.currentframe()
caller_frame = current_frame.f_back
# The file names where the function is defined is stored in the
# f_code.co_filename attribute, and in this case it has to be the same
# for both of them. Also, we are restricing that the name of the caller
# should be either `load` or `from_default_params`, which are the two
# classmethods defined above
current_file = current_frame.f_code.co_filename
caller_file = caller_frame.f_code.co_filename
caller_name = caller_frame.f_code.co_name
if current_file != caller_file or \
caller_name not in ['load', 'from_default_params']:
raise qdb.exceptions.QiitaDBOperationNotPermittedError(
"qiita_db.software.Parameters can't be instantiated directly. "
"Please use one of the classmethods: `load` or "
"`from_default_params`")
self._values = values
self._command = command
@property
def command(self):
"""The command to which this parameter set belongs to
Returns
-------
qiita_db.software.Command
The command to which this parameter set belongs to
"""
return self._command
@property
def values(self):
"""The values of the parameters
Returns
-------
dict of {str: object}
The parameter values keyed by parameter name
"""
return self._values
def dump(self):
"""Return the values in the parameter as JSON
Returns
-------
str
The parameter values as a JSON string
"""
return dumps(self._values, sort_keys=True)
class DefaultWorkflowNode(qdb.base.QiitaObject):
r"""Represents a node in a default software workflow
Attributes
----------
command
parameters
"""
_table = "default_workflow_node"
@property
def default_parameter(self):
"""The default parameter set to use in this node
Returns
-------
qiita_db.software.DefaultParameters
"""
with qdb.sql_connection.TRN:
sql = """SELECT default_parameter_set_id
FROM qiita.default_workflow_node
WHERE default_workflow_node_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
params_id = qdb.sql_connection.TRN.execute_fetchlast()
return qdb.software.DefaultParameters(params_id)
class DefaultWorkflowEdge(qdb.base.QiitaObject):
r"""Represents an edge in a default software workflow
Attributes
----------
connections
"""
_table = "default_workflow_edge"
@property
def connections(self):
"""Retrieve how the commands are connected using this edge
Returns
-------
list of [str, str]
The list of pairs of output parameter name and input parameter name
used to connect the output of the source command to the input of
the destination command.
"""
with qdb.sql_connection.TRN:
sql = """SELECT name, parameter_name, artifact_type
FROM qiita.default_workflow_edge_connections c
JOIN qiita.command_output o
ON c.parent_output_id = o.command_output_id
JOIN qiita.command_parameter p
ON c.child_input_id = p.command_parameter_id
LEFT JOIN qiita.artifact_type USING (artifact_type_id)
WHERE default_workflow_edge_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchindex()
class DefaultWorkflow(qdb.base.QiitaObject):
r"""Represents a software's default workflow
A default workflow is defined by a Directed Acyclic Graph (DAG) in which
the nodes represent the commands to be executed with the default parameter
set to use and the edges represent the command precedence, including
which outputs of the source command are provided as input to the
destination command.
"""
_table = "default_workflow"
@classmethod
def iter(cls, active=True):
"""Iterates over all active DefaultWorkflow
Parameters
----------
active : bool, optional
If True will only return active software
Returns
-------
list of qiita_db.software.DefaultWorkflow
The DefaultWorkflow objects
"""
sql = """SELECT default_workflow_id
FROM qiita.default_workflow {0}
ORDER BY default_workflow_id""".format(
'WHERE active = True' if active else '')
with qdb.sql_connection.TRN:
qdb.sql_connection.TRN.add(sql)
for s_id in qdb.sql_connection.TRN.execute_fetchflatten():
yield cls(s_id)
@property
def active(self):
"""Retrieves active status of the default workflow
Returns
-------
active : bool
active value
"""
with qdb.sql_connection.TRN:
sql = """SELECT active
FROM qiita.default_workflow
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@active.setter
def active(self, active):
"""Changes active status of the default workflow
Parameters
----------
active : bool
New active value
"""
sql = """UPDATE qiita.default_workflow SET active = %s
WHERE default_workflow_id = %s"""
qdb.sql_connection.perform_as_transaction(sql, [active, self._id])
@property
def name(self):
with qdb.sql_connection.TRN:
sql = """SELECT name
FROM qiita.default_workflow
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@property
def description(self):
"""Retrieves the description of the default workflow
Returns
-------
str
description value
"""
with qdb.sql_connection.TRN:
sql = """SELECT description
FROM qiita.default_workflow
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchlast()
@description.setter
def description(self, description):
"""Changes the description of the default workflow
Parameters
----------
description : str
New description value
"""
sql = """UPDATE qiita.default_workflow SET description = %s
WHERE default_workflow_id = %s"""
qdb.sql_connection.perform_as_transaction(sql, [description, self._id])
@property
def data_type(self):
"""Retrieves all the data_types accepted by the default workflow
Returns
----------
list of str
The data types
"""
with qdb.sql_connection.TRN:
sql = """SELECT data_type
FROM qiita.default_workflow_data_type
LEFT JOIN qiita.data_type USING (data_type_id)
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchflatten()
@property
def artifact_type(self):
"""Retrieves artifact_type that the workflow can be applied to
Returns
----------
str
The name of the artifact type this workflow can be applied to
"""
with qdb.sql_connection.TRN:
sql = """SELECT artifact_type
FROM qiita.artifact_type
LEFT JOIN qiita.default_workflow USING (artifact_type_id)
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchflatten()[0]
@property
def graph(self):
"""Returns the graph that represents the workflow
Returns
-------
networkx.DiGraph
The graph representing the default workflow.
"""
g = nx.DiGraph()
with qdb.sql_connection.TRN:
# Retrieve all graph workflow nodes
sql = """SELECT default_workflow_node_id
FROM qiita.default_workflow_node
WHERE default_workflow_id = %s
ORDER BY default_workflow_node_id"""
qdb.sql_connection.TRN.add(sql, [self.id])
db_nodes = qdb.sql_connection.TRN.execute_fetchflatten()
nodes = {n_id: DefaultWorkflowNode(n_id) for n_id in db_nodes}
# Retrieve all graph edges
sql = """SELECT DISTINCT default_workflow_edge_id, parent_id,
child_id
FROM qiita.default_workflow_edge e
JOIN qiita.default_workflow_node n
ON e.parent_id = n.default_workflow_node_id
OR e.child_id = n.default_workflow_node_id
WHERE default_workflow_id = %s
ORDER BY default_workflow_edge_id"""
qdb.sql_connection.TRN.add(sql, [self.id])
db_edges = qdb.sql_connection.TRN.execute_fetchindex()
# let's track what nodes are actually being used so if they do not
# have an edge we still return them as part of the graph
used_nodes = nodes.copy()
for edge_id, p_id, c_id in db_edges:
e = DefaultWorkflowEdge(edge_id)
g.add_edge(nodes[p_id], nodes[c_id], connections=e)
if p_id in used_nodes:
del used_nodes[p_id]
if c_id in used_nodes:
del used_nodes[c_id]
# adding the missing nodes
for ms in used_nodes:
g.add_node(nodes[ms])
return g
@property
def parameters(self):
"""Retrieves the parameters that the workflow can be applied to
Returns
----------
dict, dict
The dictionary of valid key: value pairs given by the sample or
the preparation info file
"""
with qdb.sql_connection.TRN:
sql = """SELECT parameters
FROM qiita.default_workflow
WHERE default_workflow_id = %s"""
qdb.sql_connection.TRN.add(sql, [self.id])
return qdb.sql_connection.TRN.execute_fetchflatten()[0]
@parameters.setter
def parameters(self, values):
"""Sets the parameters that the workflow can be applied to
Parameters
----------
dict : {'sample': dict, 'prep': dict}
dict of dict with the key: value pairs for the 'sample' and 'prep'
info files
Raises
------
ValueError
if the passed parameter is not a properly formated dict
"""
if not isinstance(values, dict) or \
set(values.keys()) != set(['prep', 'sample']):
raise ValueError("Improper format for values, should be "
"{'sample': dict, 'prep': dict} ")
with qdb.sql_connection.TRN:
sql = """UPDATE qiita.default_workflow
SET parameters = %s
WHERE default_workflow_id = %s"""
qdb.sql_connection.perform_as_transaction(
sql, [dumps(values), self._id])