Skip to content

Commit 4da1ada

Browse files
committed
cleaned up code and configured for release, moved some settings to config file, updated display text
1 parent c1fd801 commit 4da1ada

File tree

3 files changed

+81
-78
lines changed

3 files changed

+81
-78
lines changed

_metadraft.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"system": {"syslog": true, "current_user": "default"}, "users": {"default": {"metaproteomes": {"demo-1": "(bigg2-scer)-(iND750) (bigg2-eco40)-(iJO1366)"}, "name": "Default", "description": "Default metadraft user"}}, "history": {"sessions": null}}
1+
{"history": {"sessions": null}, "system": {"metadraft_db_version": "2018-1", "syslog": true, "have_blas2": false, "current_user": "default"}, "users": {"default": {"metaproteomes": {}, "name": "Default", "description": "Default metadraft user"}}}

libpython/qtmetadraft.py

Lines changed: 61 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,13 @@
2020
You should have received a copy of the GNU General Public License
2121
along with this program. If not, see <http://www.gnu.org/licenses/>
2222
23-
Author: Brett G. Olivier PhD
24-
Contact email: b.g.olivier@vu.nl
23+
Author: Brett G. Olivier
2524
2625
"""
2726

2827
from __future__ import division, print_function
2928
from __future__ import absolute_import
3029

31-
## http://qt-project.org/forums/viewthread/26126
32-
## http://stackoverflow.com/questions/2304199/how-to-sort-a-qtablewidget-with-my-own-code
33-
## http://qt-project.org/doc/qt-4.8/qtablewidgetitem.html
34-
3530
import os, sys, random, json, itertools
3631
import base64, datetime, re, logging, webbrowser, copy
3732
import zipfile, json, shutil, subprocess, math, time
@@ -49,12 +44,6 @@
4944
sip.setapi(name, API_VERSION)
5045

5146
cDir = os.path.dirname(os.path.abspath(os.sys.argv[0]))
52-
from . import biotools
53-
from . import wrap_orthfind1 as bionoid
54-
from . import report_templates
55-
56-
57-
import cbmpy
5847

5948
try:
6049
import docx
@@ -63,7 +52,6 @@
6352
HAVE_DOCX = False
6453

6554
metadraft_version = '0.9.0'
66-
metadraft_db_version = '2018-1'
6755

6856
HAVE_QT4 = False
6957
HAVE_QT5 = False
@@ -105,7 +93,16 @@
10593
print('Neither Qt4 nor Qt5 detected, please make sure PyQt is installed.')
10694
os.sys.exit(-1)
10795

108-
#import cbmpy as cbm
96+
try:
97+
from . import biotools
98+
from . import wrap_orthfind1 as bionoid
99+
from . import report_templates
100+
import cbmpy
101+
except ImportError as ex:
102+
print('\nERROR: cannot import CBMPy or MetaDraft support libraries.\n')
103+
print(ex)
104+
os.sys.exit(-1)
105+
109106

110107
class NumberTableWidgetItem(QTableWidgetItem):
111108
def __lt__(self, other):
@@ -128,6 +125,7 @@ def __lt__(self, other):
128125

129126
return super(NumberTableWidgetItem, self).__lt__(other)
130127

128+
131129
class NumberTableListLengthItem(QTableWidgetItem):
132130
def __lt__(self, other):
133131
if ( isinstance(other, QTableWidgetItem) ):
@@ -138,6 +136,7 @@ def __lt__(self, other):
138136
return my_value < other_value
139137
return super(NumberTableListLengthItem, self).__lt__(other)
140138

139+
141140
class MyPopup(QWidget):
142141
def __init__(self):
143142
QWidget.__init__(self)
@@ -147,6 +146,7 @@ def paintEvent(self, e):
147146
dc.drawLine(0, 0, 100, 100)
148147
dc.drawLine(100, 0, 0, 100)
149148

149+
150150
class FileTreeView(QTreeView):
151151
def __init__(self, parent=None, rootpath=None):
152152
QTreeView.__init__(self)
@@ -155,9 +155,10 @@ def __init__(self, parent=None, rootpath=None):
155155
self.setModel(model)
156156
self.setRootIndex(model.index(rootpath))
157157

158+
158159
class StreamToLogger(object):
159160
"""
160-
Fake file-like stream object that redirects writes to a logger instance.
161+
Fake file-like stream object that redirects writes to a logger instance. Inspired by
161162
http://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/
162163
163164
"""
@@ -170,17 +171,12 @@ def write(self, buf):
170171
for line in buf.rstrip().splitlines():
171172
self.logger.log(self.log_level, line.rstrip())
172173

174+
def flush(self):
175+
time.sleep(0.001)
173176

174-
## 0: developer, 1: partner, 2: public
175-
RELEASE_STATUS = 0
176-
177-
if RELEASE_STATUS > 0:
178-
DEBUG_MODE = False
179-
DEL_BLAST_TMP = True
180-
else:
181-
DEBUG_MODE = True
182-
# disable cleanup in developer mode (optional)
183-
DEL_BLAST_TMP = True
177+
## Developer mode options
178+
DEBUG_MODE = False
179+
DEL_BLAST_TMP = True
184180

185181
class MetaDraftGUI(QWidget):
186182
appwindow = None
@@ -253,10 +249,11 @@ class MetaDraftGUI(QWidget):
253249
blast_work_dir = os.path.join(cDir, 'data_blast')
254250
blast_tools = os.path.join(cDir, 'bin_base')
255251
result_files = os.path.join(cDir, 'blast_results')
256-
modeldb_base = os.path.join(cDir, 'modeldb', metadraft_db_version)
257-
seqplus_files = os.path.join(cDir, 'modeldb', metadraft_db_version, 'lib_model')
258-
metaproteome_files = os.path.join(cDir, 'modeldb', metadraft_db_version, 'lib_metaproteome')
259-
_dbx_dir_ = os.path.join(cDir, 'modeldb', metadraft_db_version, 'dbx')
252+
metadraft_db_version = 'default'
253+
modeldb_base = None
254+
seqplus_files = None
255+
metaproteome_files = None
256+
_dbx_dir_ = None
260257
link_file = ''
261258
metaproteome_file = ''
262259
result_file = ''
@@ -297,8 +294,16 @@ def __init__(self, appwindow):
297294
super(MetaDraftGUI, self).__init__()
298295
#self.setAttribute(Qt.WA_DeleteOnClose)
299296

297+
# read configuration file and enable syslog
300298
self._readConfig()
301-
## debug
299+
self.metadraft_db_version = self._CONFIG_['system']['metadraft_db_version']
300+
301+
# setup default paths based on dbversion from config file
302+
self.modeldb_base = os.path.join(cDir, 'modeldb', self.metadraft_db_version)
303+
self.seqplus_files = os.path.join(cDir, 'modeldb', self.metadraft_db_version, 'lib_model')
304+
self.metaproteome_files = os.path.join(cDir, 'modeldb', self.metadraft_db_version, 'lib_metaproteome')
305+
self._dbx_dir_ = os.path.join(cDir, 'modeldb', self.metadraft_db_version, 'dbx')
306+
302307
if not self.DEBUG_MODE and self._CONFIG_['system']['syslog']:
303308
self.__SYSLOG_ENABLED__ = True
304309
self.initSysLog()
@@ -321,12 +326,9 @@ def __init__(self, appwindow):
321326
if not os.path.exists(self.metaproteome_files):
322327
os.makedirs(self.metaproteome_files)
323328

324-
325329
self._genedb_path_ = os.path.join(self._dbx_dir_, '_metadraft_genedb.sql')
326330
self._notesdb_path_ = os.path.join(self._dbx_dir_, '_metadraft_notesdb.sql')
327331

328-
329-
330332
self.regex = {'GOterm' : re.compile('GO:\\d{7}')}
331333

332334
# initialise the gene DB
@@ -409,10 +411,7 @@ def f(a, b, c):
409411
#self.widgetButtonPanel()
410412

411413
# setup
412-
if RELEASE_STATUS == 2:
413-
self.appwindow.setWindowTitle('MetaDraft {} - created and developed by Brett G. Olivier PhD (b.g.olivier@vu.nl)'.format(metadraft_version))
414-
else:
415-
self.appwindow.setWindowTitle('MetaDraft {} - Brett G. Olivier (b.g.olivier@vu.nl)'.format(metadraft_version))
414+
self.appwindow.setWindowTitle('MetaDraft {} - Brett G. Olivier (b.g.olivier@vu.nl)'.format(metadraft_version))
416415
self.initDBs()
417416
self._loading_ = False
418417

@@ -624,7 +623,8 @@ def createMenus(self):
624623
menuFile.addAction(excelApp)
625624
menuFile.addAction(sbmlAppArch)
626625
menuFile.addSeparator()
627-
menuFile.addAction(sbmlApp1)
626+
# disabled for now unless requested
627+
#menuFile.addAction(sbmlApp1)
628628
menuFile.addAction(sbmlApp0)
629629
menuFile.addSeparator()
630630
menuFile.addAction(tblxApp)
@@ -646,7 +646,7 @@ def createMenus(self):
646646

647647
self.menuToolsM = menubar.addMenu('&Model options')
648648

649-
model_actions = ['Summary report', 'Gene report', 'Reaction report', 'Metabolite report', 'Export unmatched genes (FASTA)', 'Export unselected genes (FASTA)', 'Export model notes (CSV)']
649+
model_actions = ['Summary report', 'Gene report', 'Reaction report', 'Metabolite report', 'Export unmatched genes (as FASTA)', 'Export unselected genes (as FASTA)', 'Export model notes (CSV)']
650650
for m in model_actions:
651651
self.menuToolsM.addAction(QAction(m, self))
652652
self.menuToolsM.triggered[QAction].connect(self.menu_modelTools)
@@ -720,18 +720,21 @@ def menu_buildAll(self):
720720
@pyqtSlot()
721721
def menu_helpAbout(self):
722722

723-
title = "About MetaDraft"
724-
msg = "This is the MetaDraft version {}-({}), https://systemsbioinformatics.github.io/cbmpy-metadraft/.\n"
725-
msg += "MetaDraft makes use of CBMPy (http://cbmpy.sourceforge.net) technology and is part of the\n"
726-
msg += "MetaToolkit project (https://systemsbioinformatics.github.io/metatoolkit/).\n\n".format(metadraft_version, cbmpy.__version__)
727-
msg += "(c) Brett G. Olivier, Vrije Universiteit Amsterdam, Amsterdam, 2015-2018. All rights reserved\n"
728-
msg += "\nFor support please use the GitHub issue tracker or contact the developers.\n\n\n"
729-
msg += "MetaDraft is distributed with template models, some of which are derived from the UCSD BiGG2 model repository.\n"
723+
title = "About MetaDraft."
724+
msg = "This is MetaDraft version: {} ".format(metadraft_version)
725+
msg += "available from\n https://systemsbioinformatics.github.io/cbmpy-metadraft/.\n\n"
726+
msg += "MetaDraft makes use of CBMPy ({}) technology and is part of the".format(cbmpy.__version__)
727+
msg += "MetaToolkit project. "
728+
msg += "MetaDraft is distributed as Open Source Software, please see the included license.txt for details.\n\n"
729+
msg += "For support please use the GitHub issue tracker or contact the developers.\n\n"
730+
msg += "MetaDraft is distributed with template models, some of which are derived from the UCSD BiGG2 model repository.\n\n"
730731
if HAVE_QT4:
731732
qtv = 'Qt4'
732733
else:
733734
qtv = 'Qt5'
734-
msg += "\nYou are using Py{}.\n".format(qtv)
735+
msg += "You are using Py{} provided by:\n{}.\n\n".format(qtv, os.sys.version)
736+
msg += "(c) Brett G. Olivier, Vrije Universiteit Amsterdam, Amsterdam, 2016-2018."
737+
735738
self.widgetMsgBox(QMessageBox.Information, title, msg)
736739

737740
@pyqtSlot(QAction)
@@ -754,9 +757,9 @@ def menu_modelTools(self, q):
754757
self.func_generateGeneReport()
755758
self.func_generateReactionReport()
756759
self.func_generateMetaboliteReport()
757-
elif rpt == 'Export unmatched genes (FASTA)':
760+
elif rpt == 'Export unmatched genes (as FASTA)':
758761
self.func_exportUnmatchedGenes()
759-
elif rpt == 'Export unselected genes (FASTA)':
762+
elif rpt == 'Export unselected genes (as FASTA)':
760763
self.func_exportUnselectedGenes()
761764
elif rpt == 'Export model notes (CSV)':
762765
self.func_exportNotesDB()
@@ -778,7 +781,7 @@ def func_exportUnmatchedGenes(self):
778781
if LD['search_results'][g] is None:
779782
unmatched.append(g[len(self.gene_prefix):])
780783
#print(unmatched)
781-
fname = self.openFile('Load Input File', self._history_open_dir_, 'Supported (*.gbk *.gbff *.gb *.fasta *.faa *.fa);;FASTA (*.fasta *.faa *.fa);;GenBank (*.gbk *.gbff *.gb)')
784+
fname = self.openFile('Please load original User Proteome file', self._history_open_dir_, 'Supported (*.gbk *.gbff *.gb *.fasta *.faa *.fa);;FASTA (*.fasta *.faa *.fa);;GenBank (*.gbk *.gbff *.gb)')
782785
seq = []
783786
seqout = {}
784787
if fname.endswith('.gbk') or fname.endswith('.gb') or fname.endswith('.gbff'):
@@ -832,7 +835,7 @@ def func_exportUnselectedGenes(self):
832835
if g1 not in unmatched:
833836
unselected.append(g1)
834837

835-
fname = self.openFile('Load Input File', self._history_open_dir_, 'Supported (*.gbk *.gbff *.gb *.fasta *.faa *.fa);;FASTA (*.fasta *.faa *.fa);;GenBank (*.gbk *.gbff *.gb)')
838+
fname = self.openFile('Please load original User Proteome file.', self._history_open_dir_, 'Supported (*.gbk *.gbff *.gb *.fasta *.faa *.fa);;FASTA (*.fasta *.faa *.fa);;GenBank (*.gbk *.gbff *.gb)')
836839
seq = []
837840
seqout = {}
838841
if fname.endswith('.gbk') or fname.endswith('.gb') or fname.endswith('.gbff'):
@@ -2216,7 +2219,6 @@ def toFBC2F():
22162219
cbmpy.writeSBML3FBCV2(xmod, str(self.saveFile('Save converted file', self._history_save_dir_, '*.fbcv2.xml')))
22172220
del xmod
22182221

2219-
22202222
toFBC1 = QPushButton(self.widget_menu_sbmlConvertApp)
22212223
toFBC1.setText('Save as SBML3 FBCv1')
22222224
toFBC1.setEnabled(False)
@@ -2227,7 +2229,6 @@ def toFBC2F():
22272229
toFBC2.setEnabled(False)
22282230
toFBC2.clicked.connect(toFBC2F)
22292231

2230-
22312232
layout = QGridLayout(self.widget_menu_sbmlConvertApp)
22322233
layout.setSpacing(10)
22332234
layout.addWidget(fnamel, 0, 0, 1, 2)
@@ -2724,7 +2725,6 @@ def widgetMsgBox(self, status, title, msg):
27242725
self._msg_box_ = QMessageBox(status, title, msg)
27252726
self._msg_box_.show()
27262727

2727-
27282728
def runOrthfind1(self, par):
27292729
wdir = par[0]
27302730
target = par[1]
@@ -3020,9 +3020,6 @@ def buildMetaProteomeFromSeqplus(self, oid_list, model_lib, optimized_metaproteo
30203020
json.dump(linkDict, Fj, indent=1, separators=(',', ': '))
30213021
Fj.close()
30223022

3023-
3024-
3025-
30263023
#for n in range(len(biotools.IDMAP0)):
30273024
#print(len(biotools.IDMAP0[n]), len(biotools.IDMAP1[n]))
30283025

@@ -3182,8 +3179,6 @@ def applySelection():
31823179

31833180
self.widget_tablegene_selectApp.show()
31843181

3185-
3186-
31873182
self.widget_tablegene_rclickmenu = QMenu()
31883183
menu_item = self.widget_tablegene_rclickmenu.addAction("Filter selection")
31893184
menu_item.triggered.connect(filterSelection)
@@ -4224,7 +4219,6 @@ def func_setSelectionState(self):
42244219
## set metab selection state
42254220
#print('I HAVE SET THE SELECTION STATE')
42264221

4227-
42284222
@pyqtSlot(int)
42294223
def onTabRightChange(self, idx):
42304224
self._last_tab_right_ = self._active_tab_right_
@@ -4270,8 +4264,6 @@ def inpv_stringItemNotInList(self, itm, items):
42704264
else:
42714265
return False
42724266

4273-
4274-
42754267
def inpv_floatItemInRange(self, itm, rmin, rmax):
42764268
try:
42774269
itm = float(itm)
@@ -4905,3 +4897,10 @@ def initUI(self):
49054897
self.setCentralWidget(self._gui_)
49064898
self.setGeometry(200,200,1200,700)
49074899
self.show()
4900+
4901+
4902+
4903+
# Some code in this module has been reused from the following sources
4904+
## http://qt-project.org/forums/viewthread/26126
4905+
## http://stackoverflow.com/questions/2304199/how-to-sort-a-qtablewidget-with-my-own-code
4906+
## http://qt-project.org/doc/qt-4.8/qtablewidgetitem.html

metadraft.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -31,29 +31,33 @@ def run_metadraft():
3131
app = QApplication(sys.argv)
3232
widget_splash = QSplashScreen(QPixmap("images/metatoolkit1-03.jpg"))
3333
widget_splash.show()
34-
if RELEASE_STATUS == 2:
35-
widget_splash.showMessage("Ver {}-({}) beta\nAuthor: Brett G. Olivier PhD\n(c) Brett G. Olivier, Amsterdam, 2017-2018.\nSee Help - About for more details.".format(metadraft_version, cbmpy.__version__), alignment=Qt.AlignBottom)
36-
time.sleep(3)
37-
else:
38-
widget_splash.showMessage("Ver {}-({}) beta\n(c) Brett G. Olivier, Amsterdam, 2017-2018.\nSee Help - About for more details.".format(metadraft_version, cbmpy.__version__), alignment=Qt.AlignBottom)
39-
if RELEASE_STATUS == 1:
40-
time.sleep(2)
34+
widget_splash.showMessage("Ver {}-({})\nAuthor: Brett G. Olivier\n(c) Systems Bioinformatics, VU University Amsterdam, Amsterdam, 2017-2018.\nSee Help - About for more details.".format(metadraft_version, cbmpy.__version__), alignment=Qt.AlignBottom)
35+
time.sleep(2)
4136
ex = MetaDraftApp()
4237
widget_splash.finish(ex)
4338
sys.exit(app.exec_())
4439

4540

4641
if __name__ == '__main__':
47-
import os
42+
import os, json, platform
4843
import systemtest
4944

50-
output_msg = []
51-
BLAST_OK, BLAST_HAVE_LOCAL, pth, output_msg = systemtest.test_blast(output_msg)
52-
if not ( BLAST_OK or BLAST_HAVE_LOCAL ):
53-
print(output_msg[0])
54-
os.sys.exit(1)
55-
elif BLAST_HAVE_LOCAL:
56-
print("\nMetaDraft requires NCBI BLAST but can make use of it's own distribution. I have set the PATH for you but please consider adding \'{}\' to your local '{}' environment variable to remove this message. Please see README.md for details.\n".format(systemtest.local_blast_path, pth))
45+
F = open('_metadraft.cfg', 'r')
46+
config = json.load(F)
47+
F.close()
48+
if platform.architecture() == ('64bit', 'WindowsPE') and not config['system']['have_blas2']:
49+
output_msg = []
50+
BLAST_OK, BLAST_HAVE_LOCAL, pth, output_msg = systemtest.test_blast(output_msg)
51+
if not ( BLAST_OK or BLAST_HAVE_LOCAL ):
52+
print(output_msg[0])
53+
os.sys.exit(1)
54+
elif BLAST_OK and not BLAST_HAVE_LOCAL:
55+
config['system']['have_blas2'] = True
56+
F = open('_metadraft.cfg', 'w')
57+
json.dump(config, F)
58+
F.close()
59+
elif BLAST_HAVE_LOCAL:
60+
print("\nMetaDraft requires NCBI BLAST but can make use of it's own distribution. I have set the PATH for you but please consider adding \'{}\' to your local '{}' environment variable to remove this message. Please see README.md for details.\n".format(systemtest.local_blast_path, pth))
5761

5862
import libpython.qtmetadraft
5963
from libpython.qtmetadraft import *

0 commit comments

Comments
 (0)