Skip to content

Commit 51907f9

Browse files
committed
attrs for context
1 parent 5dc5b7f commit 51907f9

File tree

4 files changed

+181
-49
lines changed

4 files changed

+181
-49
lines changed

Diff for: DeepXplorer.py

+180-48
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,11 @@ class QIPythonWidget(RichJupyterWidget):
3333
Convenience class for a live IPython console widget.
3434
We can replace the standard banner using the customBanner argument
3535
https://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application
36+
possible colors lightbg,linux,nocolor
3637
"""
37-
def __init__(self,customBanner=None,colors='linux',*args,**kwargs):
38+
39+
40+
def __init__(self,customBanner=None,colors='lightbg',*args,**kwargs):
3841
if not customBanner is None: self.banner=customBanner
3942
super(QIPythonWidget, self).__init__(*args,**kwargs)
4043
self.kernel_manager = kernel_manager = QtInProcessKernelManager()
@@ -61,19 +64,29 @@ def printText(self,text):
6164
""" Prints some plain text to the console """
6265
self._append_plain_text(text)
6366

64-
def executeCommand(self,command):
67+
def executeCommand(self,command,hidden=False,interactive=False):
6568
""" Execute a command in the frame of the console widget """
66-
self._execute(command,False)
69+
self.execute(source=command,hidden=hidden,interactive=interactive)
6770

6871
def import_value(self,HDF5Object):
6972
HDF5Object.emitDict.connect(self.get_value)
7073

7174
@pyqtSlot(dict)
7275
def get_value(self,variableDict):
73-
self.pushVariables(variableDict)
74-
for k in variableDict:
75-
self.printText(k + '\n')
76-
self.executeCommand('print(%s)' %k)
76+
77+
# exectute a command
78+
keys = list(variableDict.keys())
79+
if keys[0].startswith('exec_cmd'):
80+
for k,cmd in variableDict.items():
81+
self._execute(cmd,False)
82+
83+
# push a variable in the console
84+
# print it if the name doesnt start with _
85+
else:
86+
self.pushVariables(variableDict)
87+
for k in variableDict:
88+
if not k.startswith('_'):
89+
self.executeCommand('%s' %k)
7790

7891
class DummyHDF5Group(dict):
7992
def __init__(self,dictionary, attrs ={}, name="DummyHDF5Group"):
@@ -321,21 +334,35 @@ def set_up_treeview(self, treeview):
321334
treeview.customContextMenuRequested.connect(functools.partial(self.context_menu, treeview))
322335

323336
def context_menu(self, treeview, position):
337+
324338
"""Generate a right-click menu for the items"""
325339

326340
# make sure tha there is only one item selected
327341
items = [self._index_to_item(index) for index in treeview.selectedIndexes()]
328-
if len(items)>1:
342+
if len(items)!=1:
329343
return
330344
item = items[0]
331345

332-
if len(item.name.split('/')) != 3:
333-
return
346+
try:
347+
_type = self.root_item.data_file[item.name].attrs['type']
334348

335-
# no right click if no children
336-
if not item._has_children:
349+
if _type == 'molecule':
350+
self._context_mol(item,treeview,position)
351+
352+
if _type == 'sparse_matrix':
353+
self._context_sparse(item,treeview,position)
354+
355+
if _type == 'epoch':
356+
self._context_epoch(item,treeview,position)
357+
358+
if _type == 'losses':
359+
self._context_losses(item,treeview,position)
360+
361+
except:
337362
return
338363

364+
def _context_mol(self,item,treeview,position):
365+
339366
menu = QtWidgets.QMenu()
340367
actions = {}
341368
list_operations = ['Load in PyMol','Load in VMD','PDB2SQL']
@@ -345,28 +372,152 @@ def context_menu(self, treeview, position):
345372
action = menu.exec_(treeview.viewport().mapToGlobal(position))
346373

347374
if action == actions['Load in VMD']:
348-
cplx_name = item.name.split('/')[1]
349-
mol_name = item.name.split('/')[2]
350-
grp_name = '/' + cplx_name + '/' + mol_name
351-
molgrp = self.root_item.data_file[grp_name]
375+
_,cplx_name,mol_name = item.name.split('/')
376+
molgrp = self.root_item.data_file[item.name]
352377
viztools.create3Ddata(mol_name,molgrp)
353378
viztools.launchVMD(mol_name,self.res)
354379

355380
if action == actions['Load in PyMol']:
356-
cplx_name = item.name.split('/')[1]
357-
mol_name = item.name.split('/')[2]
358-
grp_name = '/' + cplx_name + '/' + mol_name
359-
molgrp = self.root_item.data_file[grp_name]
381+
_,cplx_name,mol_name = item.name.split('/')
382+
molgrp = self.root_item.data_file[item.name]
360383
viztools.create3Ddata(mol_name,molgrp)
361384
viztools.launchPyMol(mol_name)
362385

363386
if action == actions['PDB2SQL']:
364-
cplx_name = item.name.split('/')[1]
365-
mol_name = item.name.split('/')[2]
366-
grp_name = '/' + cplx_name + '/' + mol_name
367-
molgrp = self.root_item.data_file[grp_name]
387+
_,cplx_name,mol_name = item.name.split('/')
388+
molgrp = self.root_item.data_file[item.name]
368389
db = pdb2sql(molgrp['complex'].value)
369-
treeview.emitDict.emit({'_'+item.basename+'_pb2sql': db})
390+
treeview.emitDict.emit({'sql_' + item.basename: db})
391+
392+
def _context_sparse(self,item,treeview,position):
393+
394+
menu = QtWidgets.QMenu()
395+
actions = {}
396+
list_operations = ['Load Matrix','Plot Histogram']
397+
398+
for operation in list_operations:
399+
actions[operation] = menu.addAction(operation)
400+
action = menu.exec_(treeview.viewport().mapToGlobal(position))
401+
name = item.basename + '_' + item.name.split('/')[2]
402+
403+
if action == actions['Load Matrix']:
404+
405+
subgrp = item.data_file[item.name]
406+
data_dict = {}
407+
if not subgrp.attrs['sparse']:
408+
data_dict[item.name] = subgrp['value'].value
409+
else:
410+
molgrp = item.data_file[item.parent.parent.parent.name]
411+
grid = {}
412+
lx = len(molgrp['grid_points/x'].value)
413+
ly = len(molgrp['grid_points/y'].value)
414+
lz = len(molgrp['grid_points/z'].value)
415+
shape = (lx,ly,lz)
416+
spg = sparse.FLANgrid(sparse=True,index=subgrp['index'].value,value=subgrp['value'].value,shape=shape)
417+
data_dict[name] = spg.to_dense()
418+
treeview.emitDict.emit(data_dict)
419+
420+
if action == actions['Plot Histogram']:
421+
422+
value = item.data_file[item.name]['value'].value
423+
data_dict = {'value':value}
424+
treeview.emitDict.emit(data_dict)
425+
426+
cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.hist(value,25)\nplt.show()\n"
427+
data_dict = {'exec_cmd':cmd}
428+
treeview.emitDict.emit(data_dict)
429+
430+
def _context_epoch(self,item,treeview,position):
431+
432+
menu = QtWidgets.QMenu()
433+
actions = {}
434+
list_operations = ['Scatter Plot']
435+
436+
for operation in list_operations:
437+
actions[operation] = menu.addAction(operation)
438+
action = menu.exec_(treeview.viewport().mapToGlobal(position))
439+
440+
if action == actions['Scatter Plot']:
441+
442+
443+
values = []
444+
train_out = item.data_file[item.name+'/train/outputs'].value
445+
train_tar = item.data_file[item.name+'/train/targets'].value
446+
values.append([x for x in train_out])
447+
values.append([x for x in train_tar])
448+
449+
450+
valid_out = item.data_file[item.name+'/valid/outputs'].value
451+
valid_tar = item.data_file[item.name+'/valid/targets'].value
452+
values.append([x for x in valid_tar])
453+
values.append([x for x in valid_out])
454+
455+
456+
test_out = item.data_file[item.name+'/test/outputs'].value
457+
test_tar = item.data_file[item.name+'/test/targets'].value
458+
values.append([x for x in test_tar])
459+
values.append([x for x in test_out])
460+
461+
462+
vmin = np.array([x for a in values for x in a]).min()
463+
vmax = np.array([x for a in values for x in a]).max()
464+
delta = vmax-vmin
465+
values.append([vmax + 0.1*delta])
466+
values.append([vmin - 0.1*delta])
467+
468+
data_dict = {'_values':values}
469+
treeview.emitDict.emit(data_dict)
470+
471+
data_dict = {}
472+
cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\n"
473+
cmd += "fig,ax = plt.subplots()\n"
474+
cmd += "ax.scatter(_values[0],_values[1],c='red',label='train')\n"
475+
cmd += "ax.scatter(_values[2],_values[3],c='blue',label='valid')\n"
476+
cmd += "ax.scatter(_values[4],_values[5],c='green',label='test')\n"
477+
cmd += "legen = ax.legend(loc='upper left')\n"
478+
cmd += "ax.set_xlabel('Targets')\n"
479+
cmd += "ax.set_ylabel('Predictions')\n"
480+
cmd += "ax.plot([_values[-2],_values[-1]],[_values[-2],_values[-1]])\n"
481+
cmd += "plt.show()\n"
482+
data_dict['exec_cmd'] = cmd
483+
treeview.emitDict.emit(data_dict)
484+
485+
def _context_losses(self,item,treeview,position):
486+
487+
menu = QtWidgets.QMenu()
488+
actions = {}
489+
list_operations = ['Plot Losses']
490+
491+
for operation in list_operations:
492+
actions[operation] = menu.addAction(operation)
493+
action = menu.exec_(treeview.viewport().mapToGlobal(position))
494+
495+
if action == actions['Plot Losses']:
496+
497+
498+
values = []
499+
test = item.data_file[item.name+'/test'].value
500+
train = item.data_file[item.name+'/train'].value
501+
valid = item.data_file[item.name+'/valid'].value
502+
values.append([x for x in train])
503+
values.append([x for x in valid])
504+
values.append([x for x in test])
505+
506+
data_dict = {'_values':values}
507+
treeview.emitDict.emit(data_dict)
508+
509+
data_dict = {}
510+
cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\n"
511+
cmd += "fig,ax = plt.subplots()\n"
512+
cmd += "plt.plot(_values[0],c='red',label='train')\n"
513+
cmd += "plt.plot(_values[1],c='blue',label='valid')\n"
514+
cmd += "plt.plot(_values[2],c='green',label='test')\n"
515+
cmd += "legen = ax.legend(loc='upper right')\n"
516+
cmd += "ax.set_xlabel('Epoch')\n"
517+
cmd += "ax.set_ylabel('Losses')\n"
518+
cmd += "plt.show()\n"
519+
data_dict['exec_cmd'] = cmd
520+
treeview.emitDict.emit(data_dict)
370521

371522
class HDF5TreeWidget(QtWidgets.QTreeView):
372523

@@ -402,32 +553,13 @@ def doubleClicked(self,event):
402553

403554
# get the current item
404555
items = [self.model._index_to_item(index) for index in self.selectedIndexes()]
405-
if len(items)>1:
556+
if len(items)!=1:
406557
return
407558
item=items[0]
408-
409-
# if we have a mapped feature
410-
# we push the matrix
411-
if item.parent.parent.basename == 'mapped_features':
412-
subgrp = item.data_file[item.name]
413-
data_dict = {}
414-
name = item.name.replace('/','_')
415-
if not subgrp.attrs['sparse']:
416-
data_dict[item.name] = subgrp['value'].value
417-
else:
418-
molgrp = item.data_file[item.parent.parent.parent.name]
419-
grid = {}
420-
lx = len(molgrp['grid_points/x'].value)
421-
ly = len(molgrp['grid_points/y'].value)
422-
lz = len(molgrp['grid_points/z'].value)
423-
shape = (lx,ly,lz)
424-
spg = sparse.FLANgrid(sparse=True,index=subgrp['index'].value,value=subgrp['value'].value,shape=shape)
425-
data_dict[name] = spg.to_dense()
426-
self.emitDict.emit(data_dict)
427-
559+
428560
# if the item has no children we push the raw data
429-
elif not item._has_children:
430-
name = item.name.replace('/','_')
561+
if not item._has_children:
562+
name = item.basename + '_' + item.name.split('/')[2]
431563
self.emitDict.emit({name: item.data_file[item.name].value})
432564

433565
# or we skip

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# DeepXplorer
22

3-
Data browser for the HDF5 files created by deeprank. The GUI allows to easily explore file structure, view, the target values and visualize the mapped features in either VMD or PyMol. In addition an the data can be loaded in an embedded iPython console for manipulation and analysis.
3+
Data browser for the HDF5 files created by deeprank. The GUI allows to easily explore file structure, view, the target values and visualize the mapped features in either VMD or PyMol. In addition the data can be loaded in an embedded iPython console for manipulation and analysis.
44

55
![alt-text](./deepxplorer.png)
66

Diff for: epoch.hdf5

74.9 KB
Binary file not shown.

Diff for: example.hdf5

3.79 MB
Binary file not shown.

0 commit comments

Comments
 (0)