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
|
"""The main frame."""
# If we are running the unit tests.
import sys
if __name__ == '__main__':
sys.path.insert(1, '..')
import wx
import wx.html
import math
import os
import os.path
import re
import time
import threading
import webbrowser
import platform
import tempfile
import urllib2
from About import About
from IdentifierListEditor import IdentifierListEditor
from ModelEditor import ModelEditor, EVT_SPECIES_OR_REACTIONS_MODIFIED
from Record import Record
from MethodEditor import MethodEditor
from Launcher import Launcher
from TrajectoriesList import TrajectoriesList
from PlotTimeSeries import closeAll
from resourcePath import resourcePath
from DuplicateDialog import DuplicateDialog
from StateModified import EVT_STATE_MODIFIED
from fio.SpeciesTextParser import SpeciesTextParser
from fio.ReactionTextParser import ReactionTextParser
from fio.TimeEventTextParser import TimeEventTextParser
from fio.TriggerEventTextParser import TriggerEventTextParser
from fio.ParameterTextParser import ParameterTextParser
from fio.CompartmentTextParser import CompartmentTextParser
from state.State import State
import state.simulationMethods as simulationMethods
from messages import UpdateVersionFrame, ScrolledMessageFrame,\
CompilationError, CompilingMessage, truncatedMessageBox,\
truncatedErrorBox, openWrite
class CompileSolverThread(threading.Thread):
"""Thread for compiling a solver."""
def __init__(self, application, compilationArguments,
successFunction, successArguments,
failureFunction, failureArguments):
threading.Thread.__init__(self)
self.application = application
self.compilationArguments = compilationArguments
self.successFunction = successFunction
self.successArguments = successArguments
self.failureFunction = failureFunction
self.failureArguments = failureArguments
def run(self):
error = self.application.state.compileSolver(*self.compilationArguments)
wx.CallAfter(self.application.destroyCompilingMessage)
if error:
wx.CallAfter(self.application.showCompilationErrors, error)
wx.CallAfter(self.failureFunction, *self.failureArguments)
else:
wx.CallAfter(self.successFunction, *self.successArguments)
def computePartition(x, n, i):
"""Compute the i_th fair partition of x into n parts.
x is the number to partition.
n is the number of partitions.
i is the partition index.
"""
p = x // n
if i < x % n:
p += 1
return p
class MainFrame(wx.Frame):
"""The main frame."""
def __init__(self, parent=None):
"""Constructor."""
# Data.
self.lock = threading.Lock()
self.title = 'Cain'
self.filename = ''
self.state = State()
self.isModified = False
# Dictionary with model identifiers as the keys. The value type is
# a list of the species table, reaction table, time events table,
# trigger events table, parameters table, and compartments table.
self.modelTables = {}
# Widgets.
# Note: A small screen is typically 1280x800, but may be as small
# as 1024x600 for a netbook.
wx.Frame.__init__(self, parent, -1, self.title, size=(1280, 750))
self.initializeStatusBar()
self.createMenuBar()
self.createToolBar()
self.splitter = wx.SplitterWindow(self,
style=wx.SP_NOBORDER|wx.SP_3DSASH)
panel = wx.Panel(self.splitter)
self.modelsList = \
IdentifierListEditor(panel, 'Models',
insert=self.modelInsert,
clone=self.modelClone,
duplicate=self.modelDuplicate,
edit=self.modelEdit,
delete=self.modelDelete,
toolTip='The list of models. Use + to add a new model. You must select a model before launching a simulation.')
self.Bind(EVT_STATE_MODIFIED, self.onStateModified, self.modelsList)
self.methodsList = \
IdentifierListEditor(panel, 'Methods',
insert=self.methodInsert,
clone=self.methodClone,
duplicate=None,
edit=self.methodEdit,
delete=self.methodDelete,
toolTip='The list of methods. Use + to add a new method. You must select a method before launching a simulation.')
self.Bind(EVT_STATE_MODIFIED, self.onStateModified, self.methodsList)
# I need to construct the launcher before the method editor because
# the latter updates the former when a new method is selected.
self.launcher = Launcher(panel, self, self.directLaunch,
self.launchCustomSimulations,
self.stopSimulation, self.killSimulation,
self.saveExecutable, self.exportJobs,
self.exportMathematica,
self.importSolution)
self.methodEditor = MethodEditor(panel, self)
self.Bind(EVT_STATE_MODIFIED, self.onStateModified, self.methodEditor)
self.record = Record(panel)
self.trajectoriesList = TrajectoriesList(panel, self)
self.Bind(EVT_STATE_MODIFIED, self.onStateModified,
self.trajectoriesList)
self.modelEditor = ModelEditor(self.splitter)
self.Bind(EVT_SPECIES_OR_REACTIONS_MODIFIED,
self.onSpeciesOrReactionsModified, self.modelEditor)
self.Bind(EVT_STATE_MODIFIED, self.onStateModified, self.modelEditor)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onModelSelected,
self.modelsList.list)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onModelDeselected,
self.modelsList.list)
self.Bind(wx.EVT_LIST_ITEM_SELECTED,
self.onMethodSelected,
self.methodsList.list)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED,
self.onMethodDeselected,
self.methodsList.list)
self.Bind(wx.EVT_CLOSE, self.onCloseWindow)
row = wx.BoxSizer(wx.HORIZONTAL)
row.Add(self.modelsList, 2, wx.EXPAND)
row.Add(self.methodsList, 2, wx.EXPAND)
row.Add(self.methodEditor, 0, wx.EXPAND)
row.Add(self.record, 3, wx.EXPAND)
row.Add(self.launcher, 0, wx.EXPAND)
row.Add(self.trajectoriesList, 4, wx.EXPAND)
panel.SetSizer(row)
self.splitter.SetMinimumPaneSize(20)
# Give equal expanding space to the top and bottom.
self.splitter.SetSashGravity(0.5)
self.splitter.SplitHorizontally(panel, self.modelEditor)
self.clearModel()
self.clearMethod()
self.updateTrajectories()
# Set up the help system.
wx.FileSystem.AddHandler(wx.ZipFSHandler())
# No bookmarks.
self.help = wx.html.HtmlHelpController\
(wx.html.HF_TOOLBAR | wx.html.HF_CONTENTS | wx.html.HF_INDEX |
wx.html.HF_SEARCH | wx.html.HF_PRINT)
cwd = os.getcwd()
# CONTINUE REMOVE
#self.help.SetTempDir(os.path.join(cwd, 'help'))
self.help.SetTempDir(tempfile.mkdtemp())
self.help.AddBook(os.path.join(cwd, 'help', 'cain.htb'))
# CONTINUE REMOVE
if False:
wx.MessageBox('Unable to open help file. Working directory = '
+ cwd,
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
wx.CallAfter(self.setSashes)
# In initializing the widgets, the state is set as being modified.
# Reset to an unmodified state.
wx.CallAfter(self.setNotModified)
# Check the application version.
wx.CallAfter(self.checkVersion)
def setSashes(self):
height = self.GetSize()[1]
self.splitter.SetSashPosition(3*height//10)
def checkVersion(self):
try:
url = 'http://cain.sourceforge.net/version.txt'
currentVersion = urllib2.urlopen(url, timeout=2).read()
c = currentVersion.split('.')
t = self.state.version.split('.')
if int(t[0]) < int(c[0]) or \
(int(t[0]) == int(c[0]) and int(t[1]) < int(c[1])):
UpdateVersionFrame(self).Show()
except:
pass
def setNotModified(self):
self.isModified = False
def initializeStatusBar(self):
self.statusBar = self.CreateStatusBar()
def menuData(self):
return [("&File", (
("&New", "New simulation", self.onNew),
("&Open", "Open a file", self.onOpen),
("&Save", "Save a file", self.onSave),
("Save &As", "Save as", self.onSaveAs),
("", "", ""),
("&Import SBML", "Import SBML model", self.onImportSbml),
("Import &Text Model", "Import text model", self.onImportTextModel),
("&Export SBML", "Export SBML model", self.onExportSbml),
("&Export CMDL", "Export CMDL model", self.onExportCmdl),
("", "", ""),
("&About...", "Show about window", self.onAbout),
("&Quit", "Quit", self.onCloseWindow))),
("&Help", (
("&Help", "Documentation", self.onHelp),))]
def createMenuBar(self):
menuBar = wx.MenuBar()
for eachMenuData in self.menuData():
menuLabel = eachMenuData[0]
menuItems = eachMenuData[1]
menuBar.Append(self.createMenu(menuItems), menuLabel)
self.SetMenuBar(menuBar)
def createToolBar(self):
toolBar = self.CreateToolBar()
# The default bitmap size is 16 by 15 pixels.
# CONTINUE: The long help strings don't show in the status bar on OS X.
# CONTINUE: Try wx.Bitmap(os.path.join(resourcePath, 'gui/icons/16x16/filenew.png'))
# CONTINUE I could use AddLabelTool instead.
# File tools.
bmp = wx.Image(os.path.join(resourcePath,
'gui/icons/16x16/filenew.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='New',
longHelpString='Clear all data and start a new problem.')
# tool = toolBar.AddLabelTool(-1, 'New', bmp, shortHelp='New',
# longHelp='Clear all data and start a new problem.')
self.Bind(wx.EVT_MENU, self.onNew, tool)
bmp = wx.Image(os.path.join(resourcePath,
'gui/icons/16x16/fileopen.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Open',
longHelpString='Open a file.')
self.Bind(wx.EVT_MENU, self.onOpen, tool)
bmp = wx.Image(os.path.join(resourcePath,
'gui/icons/16x16/filesave.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Save',
longHelpString='Save the models, methods, and simulation output.')
self.Bind(wx.EVT_MENU, self.onSave, tool)
bmp = wx.Image(os.path.join(resourcePath,
'gui/icons/16x16/filesaveas.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Save as',
longHelpString='Save the models, methods, and simulation output with a new file name.')
self.Bind(wx.EVT_MENU, self.onSaveAs, tool)
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/exit.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Quit',
longHelpString='Quit Cain.')
self.Bind(wx.EVT_MENU, self.onCloseWindow, tool)
toolBar.AddSeparator()
# Random number generator.
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/dice.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Seed the RNG',
longHelpString='Seed the Mersenne Twister')
self.Bind(wx.EVT_MENU, self.onSeed, tool)
toolBar.AddSeparator()
# Help tools.
bmp = wx.Image(os.path.join(resourcePath,
'gui/icons/16x16/preferences-system.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Preferences',
longHelpString='Open the preferences dialog.')
self.Bind(wx.EVT_MENU, self.onPreferences, tool)
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/help.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
tool = toolBar.AddTool(-1, bmp, shortHelpString='Help',
longHelpString='Open the help browser.')
self.Bind(wx.EVT_MENU, self.onHelp, tool)
toolBar.Realize()
def createMenu(self, menuData):
menu = wx.Menu()
for eachItem in menuData:
if len(eachItem) == 2:
label = eachItem[0]
subMenu = self.createMenu(eachItem[1])
menu.AppendMenu(wx.NewId(), label, subMenu)
else:
self.createMenuItem(menu, *eachItem)
return menu
def createMenuItem(self, menu, label, status, handler, kind=wx.ITEM_NORMAL):
if label:
menuItem = menu.Append(-1, label, status, kind)
self.Bind(wx.EVT_MENU, handler, menuItem)
else:
menu.AppendSeparator()
# File menu callbacks.
def clear(self):
# Kill any running simulation.
if self.launcher.isRunning:
if wx.MessageBox('There is a running simulation. Do you want to continue and kill the simulation?', 'Warning', wx.YES|wx.NO) == wx.YES:
self.killSimulation()
else:
return
self.filename = ''
self.SetTitle(self.title + ' -- ' + self.filename)
self.state.clear()
self.clearModelList()
self.clearMethodList()
self.updateTrajectories()
self.isModified = False
def saveChanges(self, message):
"""If there are modifications check to see if the user wants to save
them. Return true if there are no changes, they want to discard the
changes, or if they successfully save the changes. Otherwise (if
they hit cancel or are unable to save the changes) return false."""
# If there are unsaved changes.
if self.isModified:
# Check to see if they want to save the changes.
dialog = wx.MessageDialog(self, message, 'Save changes?',
wx.YES_NO|wx.CANCEL)
result = dialog.ShowModal()
dialog.Destroy()
if result == wx.ID_CANCEL:
return False
if result == wx.ID_YES:
# If the state is not successfully be saved.
if not self.onSave(None):
return False
return True
def onNew(self, event):
"""Make an empty model."""
if self.saveChanges('Do you want to save your changes before clearing the state?'):
self.clear()
def onOpen(self, event):
if not self.saveChanges('Do you want to save your changes before opening a new file?'):
return
wildcardXml = "XML files (*.xml)|*.xml|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Open a file...", os.getcwd(),
style=wx.OPEN, wildcard=wildcardXml)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
self.readFile(dialog.GetPath())
dialog.Destroy()
def onSave(self, event):
"""Return true if the file is saved."""
if not self.filename:
return self.onSaveAs(event)
else:
if not self.syncSelectedModelAndMethod\
('Error! Correct before saving.') or\
not self.parseModelsAndMethods\
('Error! Correct before saving.'):
return False
return self.saveFile()
def onSaveAs(self, event):
"""Return true if the file is saved."""
if not self.syncSelectedModelAndMethod\
('Error! Correct before saving.') or\
not self.parseModelsAndMethods\
('Error! Correct before saving.'):
return False
wildcardXml = "XML files (*.xml)|*.xml|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcardXml)
result = False
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
if not os.path.splitext(filename)[1]:
filename = filename + '.xml'
self.filename = filename
result = self.saveFile()
if result:
self.SetTitle(self.title + ' -- ' + self.filename)
dialog.Destroy()
return result
def onImportSbml(self, event):
wildcardXml = "XML files (*.xml)|*.xml|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Import SBML model...", os.getcwd(),
style=wx.OPEN, wildcard=wildcardXml)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
self.importSbml(dialog.GetPath())
dialog.Destroy()
def onImportTextModel(self, event):
wildcard = "Text files (*.txt)|*.txt|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Import text model...", os.getcwd(),
style=wx.OPEN, wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
self.importTextModel(dialog.GetPath())
dialog.Destroy()
def onExportSbml(self, event):
id = self.modelsList.getSelectedText()
if id == None:
wx.MessageBox('No model is selected.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
self.syncModel(id)
if not self.parseModel(id, None, 'Error! Cannot export model.'):
return
wildcardXml = "XML files (*.xml)|*.xml|" + "All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Export SBML model...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcardXml)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
if not os.path.splitext(filename)[1]:
filename = filename + '.xml'
self.exportSbml(id, filename)
dialog.Destroy()
def onExportCmdl(self, event):
id = self.modelsList.getSelectedText()
if id == None:
wx.MessageBox('No model is selected.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
self.syncModel(id)
if not self.parseModel(id, None, 'Error! Cannot export model.'):
return
wildcardXml = "CMDL files (*.cmdl)|*.cmdl|" + "All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Export CMDL model...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcardXml)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
if not os.path.splitext(filename)[1]:
filename = filename + '.cmdl'
self.exportCmdl(id, filename)
dialog.Destroy()
def onAbout(self, event):
dialog = About()
dialog.ShowModal()
dialog.Destroy()
def onCloseWindow(self, event):
"""Close all of the matplotlib figures before destroying this window."""
if self.saveChanges('Do you want to save your changes before quitting?'):
# Close the children of the simulation output panel.
self.trajectoriesList.tearDown()
# Close the plotting windows.
closeAll()
self.Destroy()
def onStateModified(self, event):
self.isModified = True
# Random number menu callbacks.
def onSeed(self, event):
# Get the seed.
s = wx.GetTextFromUser('Enter a 32-bit unsigned integer seed.',
'Mersenne Twister Seed', '0', self)
# Check the validity.
if not s:
return
try:
seed = int(s)
except:
wx.MessageBox(s + ' is not an integer.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
if not (0 <= seed and seed < 2**32):
wx.MessageBox(s + ' is not a 32-bit unsigned integer.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
# Set the seed.
self.state.seedMt19937(seed)
# Help menu callbacks.
def onPreferences(self, event):
self.state.preferences.openDialog()
def onHelp(self, event):
self.displayHelp()
def displayHelp(self, x=None):
if x:
self.help.Display(x)
else:
self.help.DisplayContents()
# Call this here because the window needs to be created first.
self.help.GetHelpWindow().Bind(wx.html.EVT_HTML_LINK_CLICKED,
self.onLinkClicked)
def onLinkClicked(self, event):
"""Open external resources in a browser."""
href = event.GetLinkInfo().GetHref()
if len(href) > 4 and href[0:4] == 'http':
version = platform.python_version_tuple()
if 10 * int(version[0]) + int(version[1]) >= 25:
# Open the page in a new tab.
# This function is new in python 2.5.
webbrowser.open_new_tab(href)
else:
# Open the page in a new window.
webbrowser.open_new(href)
else:
event.Skip()
# Simulation functions.
def cacheModel(self):
"""Get the selected model. Return True if a model is selected."""
# Store for use in finishSimulations().
self.modelId = self.modelsList.getSelectedText()
if not self.modelId:
wx.MessageBox('No model selected.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return False
self.syncModel(self.modelId)
return True
def cacheModelAndMethod(self):
"""Get the selected model and method. Return True if they are valid."""
if not self.cacheModel():
return False
# Store for use in finishSimulations().
self.methodId = self.methodsList.getSelectedText()
if not self.methodId:
wx.MessageBox('No method is selected.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return False
if not self.syncMethod\
(self.methodId, 'Error! Bad simulation parameters.') or\
not self.parseModel(self.modelId, self.methodId,
'Error! Bad model.')\
or not self.parseMethods\
(self.methodId, 'Error! Bad simulation parameters.'):
return False
return True
def launchSimulations(self, useCustomSolver):
method = self.state.methods[self.methodId]
if simulationMethods.isStochastic(method.timeDependence,
method.category):
self.numberOfTrajectories = self.launcher.trajectories.GetValue()
numberOfProcesses = self.launcher.cores.GetValue()
if self.numberOfTrajectories > numberOfProcesses:
trajectoriesPerTask =\
int(pow(float(self.numberOfTrajectories) /
numberOfProcesses,
self.launcher.getGranularity()))
else:
trajectoriesPerTask = 1
else:
self.numberOfTrajectories = 1
numberOfProcesses = 1
trajectoriesPerTask = 1
assert numberOfProcesses >= 1
self.launcher.gauge.SetRange(self.numberOfTrajectories)
self.launcher.gauge.SetValue(0)
self.trajectoryCount = 0
self.startTime = time.time()
recordedSpecies, recordedReactions = self.record.get()
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.isRunning = False
self.launcher.update()
return
error = self.state.launchSuiteOfSimulations\
(self, self.modelId, self.methodId, recordedSpecies,
recordedReactions, numberOfProcesses,
self.numberOfTrajectories, trajectoriesPerTask,
self.launcher.getNiceIncrement(), useCustomSolver)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.isRunning = False
self.launcher.update()
return
def reportRecordedErrors(self, method, recordedSpecies, recordedReactions):
"""Return an error message if the recorded species and recorded
reactions are not valid for the specified method. If there are no
errors, return None."""
category = simulationMethods.categories[method.timeDependence]\
[method.category]
if category in ('Time Series, Uniform', 'Time Series, Deterministic')\
and not (recordedSpecies or recordedReactions):
return 'No species or reactions are being recorded.'
# No need to check TimeSeriesAllReactions.
if category in ('Histograms, Transient Behavior',
'Histograms, Steady State',
'Statistics, Transient Behavior',
'Statistics, Steady State') and not recordedSpecies:
return 'No species are being recorded.'
# No errors.
return None
def evaluateModel(self):
"""Return True if the model can be evaluated.
Call cacheModel() or cacheModelAndMethod() before calling this
function."""
error = self.state.evaluateModel(self.modelId)
if error:
truncatedErrorBox(error)
return False
return True
def hasLaunchErrors(self):
"""Return True if there are errors that prevent a launch."""
if not self.cacheModelAndMethod() or not self.evaluateModel():
return True
method = self.state.methods[self.methodId]
# If the method is stochastic, check that the initial amounts are
# integers.
if simulationMethods.isStochastic(method.timeDependence,
method.category) and\
not self.state.models[self.modelId].hasIntegerInitialAmounts():
wx.MessageBox('For stochastic methods the initial amounts must be integer-valued.', 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return True
# If the method is deterministic, check that they have not already
# generated a trajectory.
if not simulationMethods.isStochastic(method.timeDependence,
method.category) and\
(self.modelId, self.methodId) in self.state.output:
wx.MessageBox('This is a deterministic method.\nThe trajectory has already been generated.', 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return True
# If the method does not support events, check that the model does
# not have events.
model = self.state.models[self.modelId]
if not simulationMethods.supportsEvents(method.timeDependence) and\
(model.timeEvents or model.triggerEvents):
wx.MessageBox('This model has events, but the method does not support them.\nUse a solver in the "Use Events" category.', 'Error!',
style=wx.OK|wx.ICON_EXCLAMATION)
return True
return False
def launchCustomSimulations(self):
# Check for errors and ensure that the executable has been compiled.
if self.hasLaunchErrors():
self.launcher.abort()
return
self.compileSolver(self.launchSimulations, (True,),
self.launcher.abort, ())
def directLaunch(self):
"""Launch simulations with built-in mass action solvers or with
a Python solver."""
if self.hasLaunchErrors():
self.launcher.abort()
return
method = self.state.methods[self.methodId]
if simulationMethods.hasGeneric[method.timeDependence]\
[method.category][method.method] and\
self.state.models[self.modelId].hasOnlyMassActionKineticLaws():
self.launchSimulations(False)
elif simulationMethods.hasPython[method.timeDependence]\
[method.category][method.method]:
self.launchPythonSimulations()
elif simulationMethods.hasCustom[method.timeDependence]\
[method.category][method.method]:
self.compileSolver(self.launchSimulations, (True,),
self.launcher.abort, ())
else:
wx.MessageBox(\
'There is no suitable solver for this model and method.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.abort()
def launchPythonSimulations(self):
method = self.state.methods[self.methodId]
self.numberOfTrajectories = self.launcher.trajectories.GetValue()
self.launcher.gauge.SetRange(self.numberOfTrajectories)
self.launcher.gauge.SetValue(0)
self.trajectoryCount = 0
self.startTime = time.time()
recordedSpecies, recordedReactions = self.record.get()
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.isRunning = False
self.launcher.update()
return
error = self.state.launchPythonSimulation\
(self, self.modelId, self.methodId, recordedSpecies,
recordedReactions, self.numberOfTrajectories)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.isRunning = False
self.launcher.update()
return
def incrementProgressGauge(self, numberOfTrajectories):
self.lock.acquire()
try:
self.trajectoryCount += numberOfTrajectories
self.launcher.gauge.SetValue(self.trajectoryCount)
# If we have generated all of the trajectories.
if self.trajectoryCount == self.numberOfTrajectories:
wx.CallAfter(self.finishSimulations)
finally:
self.lock.release()
def saveExecutable(self):
"""Save an executable. Compile it if necessary."""
if not self.cacheModelAndMethod():
return
if not self.evaluateModel():
return
choice = wx.GetSingleChoiceIndex('Choose the kind of solver.',
'Choose Solver',
['Custom solver for this model.',
'Generic solver.'])
if choice == 0:
self.compileSolver(self.saveExecutableCustom, (),
lambda : None, ())
elif choice == 1:
self.saveExecutableMassAction()
def saveExecutableCustom(self):
method = self.state.methods[self.methodId]
if sys.platform in ('win32', 'win64'):
wildcard = "Executable files (*.exe)|*.exe|" + \
"All files (*.*)|*.*"
else:
wildcard = ""
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
self.state.saveCustomExecutable(self.modelId, self.methodId,
filename)
dialog.Destroy()
def saveExecutableMassAction(self):
method = self.state.methods[self.methodId]
if not simulationMethods.hasGeneric[method.timeDependence]\
[method.category][method.method]:
wx.MessageBox(\
'This method does not have a generic mass action solver.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
if sys.platform in ('win32', 'win64'):
wildcard = "Executable files (*.exe)|*.exe|" + \
"All files (*.*)|*.*"
else:
wildcard = ""
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
self.state.saveGenericExecutable(self.methodId, filename)
dialog.Destroy()
def exportMathematica(self):
"""Export the selected model and simulation parameters to a
Mathematica notebook."""
if not self.cacheModelAndMethod() or not self.evaluateModel():
return
method = self.state.methods[self.methodId]
recordedSpecies, recordedReactions = self.record.get()
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
wildcard = "Mathematica Notebooks (*.nb)|*.nb|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
fileName = dialog.GetPath()
if os.path.splitext(fileName)[1] != '.nb':
fileName += '.nb'
outputFile = openWrite(fileName)
if outputFile:
self.state.exportMathematica(self.modelId, self.methodId,
recordedSpecies, recordedReactions,
outputFile)
# A placeholder with zero trajectories may have been created.
self.updateSimulations()
dialog.Destroy()
def compileSolver(self, successFunction, successArguments,
failureFunction, failureArguments):
"""Call self.cacheModelAndMethod() to define self.modelId,
self.methodId before calling this function."""
method = self.state.methods[self.methodId]
if not simulationMethods.hasCustom[method.timeDependence]\
[method.category][method.method]:
wx.MessageBox(\
'This method cannot be compiled into a custom solver.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
failureFunction(*failureArguments)
return
# Check that the solver has not already been compiled.
if self.state.hasCustomSolver(self.modelId, self.methodId):
successFunction(*successArguments)
return
# Check the recorded species and reactions.
recordedSpecies, recordedReactions = self.record.get()
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
failureFunction(*failureArguments)
return
# Start compiling.
self.compilingMessage = CompilingMessage()
self.compilingMessage.Show()
thread = CompileSolverThread(self, (self.modelId, self.methodId,
recordedSpecies, recordedReactions),
successFunction, successArguments,
failureFunction, failureArguments)
thread.start()
def showCompilationErrors(self, errors):
CompilationError(errors).Show()
self.launcher.update()
def destroyCompilingMessage(self):
self.compilingMessage.Destroy()
# CONTINUE: When the job is stopped or killed, it reports more simulations
# than are actually completed.
def endSimulationsMessage(self, title, elapsedTime):
self.updateSimulations()
message = 'Model: ' + self.modelId + ', Method: ' + self.methodId
message += '\nGenerated %d trajectories in %f seconds.' % \
(self.state.successfulTrajectories, elapsedTime)
if self.state.errorMessages:
message += '\n%d simulations failed.' %\
len(self.state.errorMessages)
for error in self.state.errorMessages:
message += '\n%s' % error
ScrolledMessageFrame(message, title, (600, 300)).Show()
def stopSimulation(self):
elapsedTime = time.time() - self.startTime
self.state.stopSimulation()
self.endSimulationsMessage('Stopped', elapsedTime)
def killSimulation(self):
# CONTINUE: Figure out how to kill process on Windows. When I use
# subprocess.kill(), I get an Access denied error.
if sys.platform in ('win32', 'win64'):
wx.MessageBox('Killing a simulation is not supported on MS '\
'Windows. Use the Task Manager to kill the solvers.',
'Not Supported', style=wx.OK)
return
elapsedTime = time.time() - self.startTime
self.state.killSimulation()
self.endSimulationsMessage('Killed', elapsedTime)
def finishSimulations(self):
elapsedTime = time.time() - self.startTime
self.state.tearDownSimulation()
self.launcher.isRunning = False
self.launcher.update()
self.endSimulationsMessage('Finished', elapsedTime)
def exportJobs(self):
if not self.cacheModelAndMethod() or not self.evaluateModel():
return
method = self.state.methods[self.methodId]
if simulationMethods.isStochastic(method.timeDependence,
method.category):
numberOfTrajectories = self.launcher.trajectories.GetValue()
numberOfProcesses = self.launcher.cores.GetValue()
else:
numberOfTrajectories = 1
numberOfProcesses = 1
recordedSpecies, recordedReactions = self.record.get()
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
if numberOfProcesses == 1:
wildcard = "Text files (*.txt)|*.txt|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Export job as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcard)
else:
wildcard = "All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Select base name...",
os.getcwd(), style=wx.SAVE,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
self.exportSuiteOfJobs(dialog.GetPath(), self.modelId,
self.methodId, recordedSpecies,
recordedReactions, numberOfTrajectories,
numberOfProcesses)
# A placeholder with zero trajectories may have been created.
self.updateSimulations()
dialog.Destroy()
def exportSuiteOfJobs(self, fileName, modelId, methodId, recordedSpecies,
recordedReactions, numberOfTrajectories,
numberOfProcesses):
# If necessary, start a new output container for this model and method.
self.state.ensureOutput(modelId, methodId, recordedSpecies,
recordedReactions)
if numberOfProcesses == 1:
if not os.path.splitext(fileName)[1]:
fileName += '.txt'
outputFile = openWrite(fileName)
if not outputFile:
return
self.state.exportJob(outputFile, modelId, methodId,
recordedSpecies, recordedReactions,
numberOfTrajectories)
else:
width = int(math.log10(numberOfProcesses - 0.1)) + 1
format = '_%0' + str(width) + 'd.txt'
for index in range(numberOfProcesses):
n = computePartition(numberOfTrajectories, numberOfProcesses,
index)
if n != 0:
outputFile = openWrite(fileName + format % index)
if not outputFile:
return
self.state.exportJob(outputFile, modelId, methodId,
recordedSpecies, recordedReactions, n,
index)
def importSolution(self):
if not self.cacheModelAndMethod():
return
method = self.state.methods[self.methodId]
if simulationMethods.usesStatistics(method.timeDependence,
method.category):
self.importStatistics()
else:
self.importTrajectories()
def importStatistics(self):
# The solution must not have been imported before.
if (self.modelId, self.methodId) in self.state.output:
wx.MessageBox('This solution for this model and method has already been imported.', 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.abort()
return
# Get the recorded species.
recordedSpecies, recordedReactions = self.record.get()
method = self.state.methods[self.methodId]
error = self.reportRecordedErrors(method, recordedSpecies,
recordedReactions)
if error:
wx.MessageBox(error, 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.abort()
return
wildcard = "Text files (*.txt)|*.txt|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Import solution statistics...",
os.getcwd(), style=wx.FD_OPEN,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
try:
self.state.importStatistics(filename, self.modelId,
self.methodId, recordedSpecies)
self.updateSimulations()
except Exception, exception:
truncatedErrorBox("Problem in importing %s.\n" % filename +
str(exception))
self.deleteOutput(self.modelId, self.methodId)
dialog.Destroy()
def importTrajectories(self):
# They must have exported this job.
if not (self.modelId, self.methodId) in self.state.output:
wx.MessageBox('This job was not exported. There is no placeholder for the output.', 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.abort()
return
# If the method is deterministic, check that they have not already
# generated a trajectory.
method = self.state.methods[self.methodId]
if not simulationMethods.isStochastic(method.timeDependence,
method.category) and\
self.state.output[(self.modelId, self.methodId)].populations:
wx.MessageBox('This is a deterministic method.\nThe trajectory has already been generated.', 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.launcher.abort()
return
wildcard = "Text files (*.txt)|*.txt|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Import trajectories...", os.getcwd(),
style=wx.FD_OPEN|wx.FD_MULTIPLE,
wildcard=wildcard)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
try:
self.state.importSuiteOfTrajectories(dialog.GetPaths(),
self.modelId,
self.methodId)
except Exception, exception:
truncatedErrorBox("Problem in importing trajectories.\n" +
str(exception))
self.updateSimulations()
dialog.Destroy()
def updateSimulations(self):
self.launcher.gauge.SetValue(0)
self.updateTrajectoriesCount(self.modelId, self.methodId)
self.setModelPermissions(self.modelId)
self.setMethodPermissions(self.methodId)
self.updateRecorded(self.modelId, self.methodId)
self.launcher.update()
# File I/O.
def readFile(self, filename='', useMessageBox=True):
filename = os.path.abspath(filename)
# Check that the file exists.
if not os.path.isfile(filename) and useMessageBox:
wx.MessageBox("The file %s does not exist." % filename,
"Error!", style=wx.OK|wx.ICON_EXCLAMATION)
return
# Determine if this is a Cain or an SBML file.
try:
if re.search('<sbml', open(filename, 'r').read()):
self.importSbml(filename, useMessageBox)
return
except Exception, exception:
if useMessageBox:
truncatedErrorBox('Problem in determining the file type for ' +
filename + '.\n' + str(exception))
return
# Read the Cain file.
try:
self.clear()
errors = ''
errors = self.state.read(filename)
if errors and useMessageBox:
truncatedErrorBox(errors)
for id in self.state.models:
model = self.state.models[id]
self.modelTables[id] = [model.writeSpeciesTable(),
model.writeReactionsTable(),
model.writeTimeEventsTable(),
model.writeTriggerEventsTable(),
model.writeParametersTable(),
model.writeCompartmentsTable()]
self.modelsList.insertItem(id)
for id in self.state.methods:
self.methodsList.insertItem(id)
self.clearModel()
self.modelsList.select()
self.clearMethod()
self.methodsList.select()
self.updateTrajectories()
self.filename = filename
self.SetTitle(self.title + ' -- ' + self.filename)
self.isModified = False
except Exception, exception:
if useMessageBox:
truncatedErrorBox("Problem in reading %s.\n" % filename +
errors + '\n' + str(exception))
def importSbml(self, filename, useMessageBox=True):
if not os.path.isfile(filename) and useMessageBox:
wx.MessageBox("The file %s does not exist." % filename,
"Error!", style=wx.OK|wx.ICON_EXCLAMATION)
return
try:
errors = ''
(id, errors) = self.state.importSbmlModel(filename)
if errors and useMessageBox:
truncatedErrorBox(errors)
if id:
self.modelTables[id] =\
[self.state.models[id].writeSpeciesTable(),
self.state.models[id].writeReactionsTable(),
self.state.models[id].writeTimeEventsTable(),
self.state.models[id].writeTriggerEventsTable(),
self.state.models[id].writeParametersTable(),
self.state.models[id].writeCompartmentsTable()]
self.modelsList.insertItem(id)
# Select the model.
self.modelsList.selectLast()
self.isModified = True
except Exception, exception:
if useMessageBox:
truncatedErrorBox("Problem in importing %s.\n" % filename +
errors + '\n' + str(exception))
def importTextModel(self, filename, useMessageBox=True):
if not os.path.isfile(filename) and useMessageBox:
wx.MessageBox("The file %s does not exist." % filename,
"Error!", style=wx.OK|wx.ICON_EXCLAMATION)
return
try:
id = self.state.importTextModel(filename)
assert id
self.modelTables[id] =\
[self.state.models[id].writeSpeciesTable(),
self.state.models[id].writeReactionsTable(),
self.state.models[id].writeTimeEventsTable(),
self.state.models[id].writeTriggerEventsTable(),
self.state.models[id].writeParametersTable(),
self.state.models[id].writeCompartmentsTable()]
self.modelsList.insertItem(id)
# Select the model.
self.modelsList.selectLast()
self.isModified = True
except Exception, exception:
if useMessageBox:
truncatedErrorBox("Problem in importing text model %s.\n"
% filename + '\n' + str(exception))
def exportSbml(self, id, filename):
self.modelId = id
if not self.evaluateModel():
return
outputFile = openWrite(filename)
if outputFile:
version = int(self.state.preferences.data['SBML']['Version'])
self.state.writeSbml(id, outputFile, version)
def exportCmdl(self, id, filename):
self.modelId = id
if not self.evaluateModel():
return
outputFile = openWrite(filename)
if not outputFile:
return
self.state.models[id].writeCmdl(outputFile)
# Model editor callbacks.
def modelInsert(self):
id = self.state.insertNewModel()
model = self.state.models[id]
self.modelTables[id] = [model.writeSpeciesTable(),
model.writeReactionsTable(),
model.writeTimeEventsTable(),
model.writeTriggerEventsTable(),
model.writeParametersTable(),
model.writeCompartmentsTable()]
return id
def modelClone(self, id):
newId = self.state.insertCloneModel(id)
model = self.state.models[newId]
self.modelTables[newId] = [model.writeSpeciesTable(),
model.writeReactionsTable(),
model.writeTimeEventsTable(),
model.writeTriggerEventsTable(),
model.writeParametersTable(),
model.writeCompartmentsTable()]
return newId
def modelDuplicate(self, id):
dialog = DuplicateDialog(self)
result = dialog.ShowModal()
if result != wx.ID_OK:
return None
multiplicity = dialog.getMultiplicity()
useScaling = dialog.useScaling()
dialog.Destroy()
newId = self.state.insertDuplicatedModel(id, multiplicity, useScaling)
model = self.state.models[newId]
self.modelTables[newId] = [model.writeSpeciesTable(),
model.writeReactionsTable(),
model.writeTimeEventsTable(),
model.writeTriggerEventsTable(),
model.writeParametersTable(),
model.writeCompartmentsTable()]
return newId
def modelEdit(self, old, new):
if new in self.state.models:
wx.MessageBox("Cannot change identifier %s to %s." % (old, new),
"Error!", style=wx.OK|wx.ICON_EXCLAMATION)
return False
# Rename the model identifier in:
# The state.
self.state.changeModelId(old, new)
# The model list.
self.modelTables[new] = self.modelTables[old]
del self.modelTables[old]
# The trajectories list.
self.trajectoriesList.changeModelId(old, new)
return True
def modelDelete(self, id):
assert id in self.state.models
self.clearModel()
del self.state.models[id]
del self.modelTables[id]
def onModelSelected(self, event):
id = self.modelsList.getText(event.GetIndex())
if id:
self.updateModel(id)
self.launcher.update()
def onModelDeselected(self, event):
id = self.modelsList.getText(event.GetIndex())
if id:
self.modelTables[id] = self.modelEditor.getTableData()
self.clearModel()
self.launcher.update()
def getSelectedModelId(self):
return self.modelsList.getSelectedText()
def getSelectedMethodInfo(self):
"""Return the method information as a tuple of method, hasGeneric,
hasCustom, and hasPython. This is the information that the launcher
needs to enable the appropriate buttons. Return a tuple of None's if
no method is selected."""
methodId = self.methodsList.getSelectedText()
if not methodId:
return (None, None, None, None)
m = self.state.methods[methodId]
i, j, k = m.timeDependence, m.category, m.method
return (simulationMethods.methods[i][j][k],
simulationMethods.hasGeneric[i][j][k],
simulationMethods.hasCustom[i][j][k],
simulationMethods.hasPython[i][j][k])
# Simulation parameters editor callbacks.
def methodInsert(self):
"""Insert new simulation parameters. Return the new identifier."""
self.syncSelectedMethod()
return self.state.insertNewMethod()
def methodClone(self, id):
"""Insert a clone of the specified simulation parameters. Return the
new identifier. If the simulation parameters are not valid, return
None."""
if not self.syncMethod(id, 'Error'):
return None
return self.state.insertCloneMethod(id)
def methodEdit(self, old, new):
if new in self.state.methods:
wx.MessageBox("Cannot change identifier %s to %s." % (old, new),
"Error!", style=wx.OK|wx.ICON_EXCLAMATION)
return False
# Rename the identifier in:
# The state.
self.state.changeMethodId(old, new)
# The trajectories list.
self.trajectoriesList.changeMethodId(old, new)
return True
def methodDelete(self, id):
sp = self.state.methods
assert id in sp
self.clearMethod()
del sp[id]
def onMethodSelected(self, event):
id = self.methodsList.getText(event.GetIndex())
assert id
self.updateMethod(id)
self.launcher.update()
def onMethodDeselected(self, event):
id = self.methodsList.getText(event.GetIndex())
# Note that a method might be deselected right after being deleted.
# Thus we need to check if the method still exists.
if id in self.state.methods:
self.syncMethod(id, 'Error')
self.parseMethods(id)
self.clearMethod()
self.launcher.update()
# Trajectories display callbacks.
def updatePermissions(self):
# Check the models and methods.
modelId = self.modelsList.getSelectedText()
if modelId:
self.setModelPermissions(modelId)
methodId = self.methodsList.getSelectedText()
if methodId:
self.setMethodPermissions(methodId)
self.updateRecorded(modelId, methodId)
def deleteOutput(self, modelId, methodId):
self.state.deleteOutput(modelId, methodId)
self.updatePermissions()
def deleteAllOutput(self):
self.state.deleteAllOutput()
self.updatePermissions()
# CONTINUE: Remove. This will be implemented in ExportTimeSeries.
def exportCsv(self, modelId, methodId):
wildcardCsv = "CSV files (*.csv)|*.csv|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcardCsv)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
if not os.path.splitext(filename)[1]:
filename = filename + '.csv'
outputFile = openWrite(filename)
if outputFile:
self.state.exportCsv(modelId, methodId, outputFile)
dialog.Destroy()
def exportGnuplot(self, modelId, methodId):
# CONTINUE
# Exporting statistics is not currently supported.
method = self.state.methods[methodId]
category = simulationMethods.categories[method.timeDependence]\
[method.category]
if category in ('Statistics, Transient Behavior',
'Statistics, Steady State'):
wx.MessageBox('Exporting ' + category + ' is not yet supported.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
wildcardGnuplot = "Gnuplot data files (*.dat)|*.dat|" + \
"All files (*.*)|*.*"
dialog = wx.FileDialog(self, "Save as...", os.getcwd(),
style=wx.SAVE|wx.OVERWRITE_PROMPT,
wildcard=wildcardGnuplot)
if dialog.ShowModal() == wx.ID_OK:
os.chdir(dialog.GetDirectory())
filename = dialog.GetPath()
baseName = os.path.splitext(os.path.split(filename)[1])[0]
if not os.path.splitext(filename)[1]:
filename = filename + '.dat'
self.state.exportGnuplot(modelId, methodId, baseName, filename)
dialog.Destroy()
# Other.
def saveFile(self):
"""Return true if the file was saved."""
outputFile = openWrite(self.filename)
if not outputFile:
return False
self.state.write(outputFile)
self.isModified = False
return True
def clearModelList(self):
self.modelsList.clear()
self.modelTables = {}
self.clearModel()
def clearModel(self):
self.modelEditor.clear()
self.clearRecorded()
def updateModel(self, id):
self.modelEditor.setTableData(self.modelTables[id])
self.setModelPermissions(id)
self.updateRecorded(modelId=id)
def setModelPermissions(self, id):
if self.state.doesModelHaveDependentOutput(id):
self.modelsList.disableDelete()
self.modelEditor.disable()
else:
self.modelsList.enableDelete()
self.modelEditor.enable()
# CONTINUE: I should move the implementation to MethodEditor.
def updateMethod(self, id):
m = self.state.methods[id]
editor = self.methodEditor
editor.setMethod(m.timeDependence, m.category, m.method, m.options)
editor.startTime.SetValue(str(m.startTime))
editor.equilibrationTime.SetValue(str(m.equilibrationTime))
editor.recordingTime.SetValue(str(m.recordingTime))
if m.maximumSteps is not None:
editor.maximumSteps.SetValue(str(m.maximumSteps))
else:
editor.maximumSteps.SetValue('')
editor.frames.SetValue(m.numberOfFrames)
editor.bins.SetValue(m.numberOfBins)
editor.multiplicity.SetValue(m.multiplicity)
if m.solverParameter is not None:
editor.solverParameter.SetValue(str(m.solverParameter))
else:
editor.solverParameter.SetValue('')
self.setMethodPermissions(id)
self.updateRecorded(methodId=id)
def clearMethod(self):
editor = self.methodEditor
editor.setMethod(0, 0, 0, 0)
editor.startTime.SetValue('0')
editor.equilibrationTime.SetValue('0')
editor.recordingTime.SetValue('1')
editor.maximumSteps.SetValue('')
editor.frames.SetValue(11)
editor.bins.SetValue(32)
editor.multiplicity.SetValue(4)
editor.solverParameter.SetValue('')
self.methodEditor.Disable()
self.clearRecorded()
def clearMethodList(self):
self.methodsList.clear()
self.clearMethod()
def setMethodPermissions(self, id):
if self.state.doesMethodHaveDependentOutput(id):
self.methodsList.disableDelete()
# Move the focus to the launcher. Without this, if the cursor is in
# a text control and the widget is disabled then the user can
# still edit the text.
self.launcher.SetFocus()
self.methodEditor.Disable()
else:
self.methodsList.enableDelete()
self.methodEditor.Enable()
def clearRecorded(self):
"""Empty lists of species and reactions to record."""
self.record.set([], [])
def onSpeciesOrReactionsModified(self, event):
self.updateRecorded()
def updateRecorded(self, modelId=None, methodId=None):
# Get the selected model and method if they were not passed as
# parameters.
if not modelId:
modelId = self.modelsList.getSelectedText()
if not methodId:
methodId = self.methodsList.getSelectedText()
# If there is not a selected model and method, clear the recorded
# items and return.
if not (modelId and methodId):
self.clearRecorded()
return
speciesIdentifiers, reactionIdentifiers =\
self.modelEditor.getSpeciesAndReactionIdentifiers()
# If there is output for the model and method, display the recorded
# items and disable input.
if (modelId, methodId) in self.state.output:
output = self.state.output[(modelId, methodId)]
# Display all species and reactions.
self.record.set(speciesIdentifiers, reactionIdentifiers)
# Check the recorded species and reactions
self.record.checkList(output.recordedSpecies,
output.recordedReactions)
# Disable input.
self.record.disable()
return
# Otherwise display the items that can be recorded.
timeDependenceIndex = self.methodEditor.timeDependence.GetSelection()
categoryIndex = self.methodEditor.category.GetSelection()
category = simulationMethods.categories[timeDependenceIndex]\
[categoryIndex]
if category in ('Time Series, Uniform', 'Time Series, Deterministic'):
# Display the species and reactions.
self.record.set(speciesIdentifiers, reactionIdentifiers)
# Check each of the species, but not the reactions.
self.record.checkSpecies(True)
# Enable selection.
self.record.enable()
elif category == 'Time Series, All Reactions':
# Each reaction event is recorded, so every species and reaction
# are recorded.
self.record.set(speciesIdentifiers, reactionIdentifiers)
self.record.checkAll(True)
self.record.disable()
elif category in ('Histograms, Transient Behavior',
'Histograms, Steady State',
'Statistics, Transient Behavior',
'Statistics, Steady State'):
# Only species may be recorded.
self.record.set(speciesIdentifiers, [])
# Check each of the species.
self.record.checkSpecies(True)
self.record.enable()
else:
assert False
def updateTrajectories(self):
self.trajectoriesList.clear()
for key in self.state.output:
self.trajectoriesList.insertItem(
key[0], key[1], str(self.state.output[key].size()))
def updateTrajectoriesCount(self, modelId, methodId):
"""Update the trajectories count."""
key = (modelId, methodId)
assert key in self.state.output
self.trajectoriesList.update(modelId, methodId,
str(self.state.output[key].size()))
def syncSelectedModel(self):
id = self.modelsList.getSelectedText()
# Do nothing if no model is selected.
if not id:
return
# CONTINUE: Do nothing if the model has not been modified.
self.syncModel(id)
def syncModel(self, id):
self.modelTables[id] = self.modelEditor.getTableData()
def syncSelectedMethod(self, errorMessage = 'Error!'):
id = self.methodsList.getSelectedText()
# Do nothing if no parameters are selected.
if not id:
return True
# CONTINUE: Do nothing if the parameters have not been modified.
return self.syncMethod(id, errorMessage)
# CONTINUE Perhaps move the implementation.
def syncMethod(self, id, errorMessage):
editor = self.methodEditor
errors = ''
# The time interval.
try:
startTime = float(editor.startTime.GetValue())
except:
errors += 'The start time must be a floating point value.\n'
try:
equilibrationTime = float(editor.equilibrationTime.GetValue())
except:
errors += 'The equilibration time must be a floating point value.\n'
try:
recordingTime = float(editor.recordingTime.GetValue())
except:
errors += 'The recording time must be a floating point value.\n'
if editor.maximumSteps.GetValue():
try:
maximumSteps = float(editor.maximumSteps.GetValue())
except:
errors += 'The maximum steps must be either blank or a floating point value.\n'
else:
maximumSteps = None
# The solver parameter.
parameterValue = None
if editor.solverParameter.GetValue():
try:
parameterValue = float(editor.solverParameter.GetValue())
except:
errors = 'The solver parameter must be a floating point value.\n'
if not errors:
errors = self.state.editMethod\
(id,
editor.timeDependence.GetSelection(),
editor.category.GetSelection(),
editor.method.GetSelection(),
editor.options.GetSelection(),
startTime,
equilibrationTime,
recordingTime,
maximumSteps,
editor.frames.GetValue(),
editor.bins.GetValue(),
editor.multiplicity.GetValue(),
parameterValue)
if errors:
truncatedErrorBox('Invalid simulation parameters.\n' + errors)
return False
return True
def syncSelectedModelAndMethod(self, errorMessage = 'Error!'):
self.syncSelectedModel()
return self.syncSelectedMethod(errorMessage)
# CONTINUE: Get rid of errorMessage parameter.
def parseModel(self, id, methodId, errorMessage = 'Error!'):
# The identifiers that are accumulated as each component is parsed.
identifiers = []
# Update the model table.
if not self.parseParametersTable(id, identifiers):
return False
if not self.parseCompartmentsTable(id, identifiers):
return False
if not self.parseSpeciesTable(id, identifiers):
return False
if not self.parseReactionsTable(id, identifiers):
return False
if not self.parseTimeEventsTable(id, identifiers):
return False
if not self.parseTriggerEventsTable(id, identifiers):
return False
error = self.state.hasErrorsInModel(id, methodId)
if error:
truncatedErrorBox('Model ' + id + ' is invalid.\n' + error)
return False
return True
# CONTINUE: Get rid of errorMessage parameter.
def parseMethods(self, id, errorMessage = 'Error!'):
error = self.state.hasErrorsInMethod(id)
if error:
truncatedErrorBox('Invalid simulation parameters.\n' + error)
return False
return True
def parseModelsAndMethods(self, errorMessage = 'Error!'):
# Parse the models.
for id in self.state.models:
if not self.parseModel(id, None):
return False
# Parse the currently edited simulation parameters.
id = self.methodsList.getSelectedText()
# If a set of simulation parameters are selected.
if id:
return self.parseMethods(id, errorMessage)
return True
def parseSpeciesTable(self, id, identifiers):
model = self.state.models[id]
parser = SpeciesTextParser()
model.speciesIdentifiers, model.species = \
parser.parseTable(self.modelTables[id][0], identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def parseReactionsTable(self, id, identifiers):
model = self.state.models[id]
parser = ReactionTextParser()
model.reactions = parser.parseTable(self.modelTables[id][1],
model.speciesIdentifiers,
identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def parseTimeEventsTable(self, id, identifiers):
model = self.state.models[id]
parser = TimeEventTextParser()
model.timeEvents = parser.parseTable(self.modelTables[id][2],
identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def parseTriggerEventsTable(self, id, identifiers):
model = self.state.models[id]
parser = TriggerEventTextParser()
model.triggerEvents = parser.parseTable(self.modelTables[id][3],
identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def parseParametersTable(self, id, identifiers):
model = self.state.models[id]
parser = ParameterTextParser()
model.parameters = parser.parseTable(self.modelTables[id][4],
identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def parseCompartmentsTable(self, id, identifiers):
model = self.state.models[id]
parser = CompartmentTextParser()
model.compartments = parser.parseTable(self.modelTables[id][5],
identifiers)
if parser.errorMessage:
truncatedErrorBox('In model ' + id + ': ' + parser.errorMessage)
return False
return True
def main():
app = wx.PySimpleApp()
#frame = MainFrame()
#frame.Show(True)
message = '\n'.join(['Long error message-------------------------------------------------------------------------number ' + str(n) + '.' for n in range(1,61)])
messageFrame = ScrolledMessageFrame(message, 'Errors', (600, 300))
messageFrame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
|