From 857789f8c82449b96035fa3c0292aa875436f3ad Mon Sep 17 00:00:00 2001 From: Nicolas Renaud Date: Fri, 18 May 2018 11:41:14 +0200 Subject: [PATCH] new examples --- example/basemap/baseimport.py | 1 + example/basemap/menu.py | 3 - example/qmflows-namd/baseimport.py | 9 + example/qmflows-namd/menu.py | 255 ++++++++++------------------- example/qmflows-namd/qmfxplorer.py | 3 +- h5xplorer/menu_tools.py | 4 +- h5xplorer/standarddialogs.py | 39 ++++- 7 files changed, 134 insertions(+), 180 deletions(-) create mode 100644 example/qmflows-namd/baseimport.py diff --git a/example/basemap/baseimport.py b/example/basemap/baseimport.py index 78a71fc..891c44f 100644 --- a/example/basemap/baseimport.py +++ b/example/basemap/baseimport.py @@ -1,3 +1,4 @@ +%matplotlib inline from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np diff --git a/example/basemap/menu.py b/example/basemap/menu.py index b6d355f..bc4a8ea 100644 --- a/example/basemap/menu.py +++ b/example/basemap/menu.py @@ -52,9 +52,6 @@ def context_menu(self, treeview, position): data_dict = {'_mean':mean,'_wave':wave} treeview.emitDict.emit(data_dict) - # with open('baseplot.py','r') as f: - # cmd = f.readlines() - # cmd = ''.join(cmd) cmd = 'basemap(_wave,_mean)' data_dict = {'exec_cmd':cmd} treeview.emitDict.emit(data_dict) \ No newline at end of file diff --git a/example/qmflows-namd/baseimport.py b/example/qmflows-namd/baseimport.py new file mode 100644 index 0000000..2b56094 --- /dev/null +++ b/example/qmflows-namd/baseimport.py @@ -0,0 +1,9 @@ +%matplotlib inline +import numpy as np +import matplotlib.pyplot as plt + +def plot_time_series(values): + print(values.shape) + for col in values.T: + plt.plot(col) + plt.show() \ No newline at end of file diff --git a/example/qmflows-namd/menu.py b/example/qmflows-namd/menu.py index 1650302..ab5aef2 100644 --- a/example/qmflows-namd/menu.py +++ b/example/qmflows-namd/menu.py @@ -1,193 +1,118 @@ -import viztools from PyQt5 import QtWidgets -from deeprank.tools import pdb2sql, sparse +from h5xplorer.menu_tools import * +from h5xplorer.menu_plot import * +import numpy as np def context_menu(self, treeview, position): """Generate a right-click menu for the items""" - # make sure tha there is only one item selected - items = [self._index_to_item(index) for index in treeview.selectedIndexes()] + item = get_current_item(self,treeview,single=True) - if len(items)!=1: - return - item = items[0] + data = get_group_data(get_current_hdf5_group(self,item)) - try: + if data is None: + list_operations = ['Print attrs','-','Eigenvalue','Coupling'] - _type = self.root_item.data_file[item.name].attrs['type'] + elif data.ndim == 1: + list_operations = ['Print attrs','-','Plot Hist', 'Plot Line'] + elif data.ndim == 2: + list_operations = ['Print attrs','-','Plot Hist', 'Plot Map'] - if _type == 'molecule': - molgrp = self.root_item.data_file[item.name] - _context_mol(item,treeview,position,molgrp) + else: + list_operations = ['Print attrs'] - if _type == 'sparse_matrix': - _context_sparse(item,treeview,position) + action,actions = get_actions(treeview,position,list_operations) - if _type == 'epoch': - _context_epoch(item,treeview,position) + if action == actions['Print attrs']: + send_dict_to_console(self,item,treeview) - if _type == 'losses': - _context_losses(item,treeview,position) + if 'Plot Hist' in actions: + if action == actions['Plot Hist']: + plot_histogram(self,item,treeview) - except Exception as inst: - print(type(inst)) - print(inst) - return + if 'Plot Line' in actions: + if action == actions['Plot Line']: + plot_line(self,item,treeview) -def _context_mol(item,treeview,position,molgrp): + if 'Plot Map' in actions: + if action == actions['Plot Map']: + plot2d(self,item,treeview) - menu = QtWidgets.QMenu() - actions = {} - list_operations = ['Load in PyMol','Load in VMD','PDB2SQL'] + if 'Eigenvalue' in actions: + if action == actions['Eigenvalue']: + plot_eigen(self,item,treeview) - for operation in list_operations: - actions[operation] = menu.addAction(operation) - action = menu.exec_(treeview.viewport().mapToGlobal(position)) + if 'Coupling' in actions: + if action == actions['Coupling']: + plot_coupling(self,item,treeview) - if action == actions['Load in VMD']: - _,cplx_name,mol_name = item.name.split('/') - viztools.create3Ddata(mol_name,molgrp) - viztools.launchVMD(mol_name) +def plot_eigen(self,item,treeview): - if action == actions['Load in PyMol']: - _,cplx_name,mol_name = item.name.split('/') - viztools.create3Ddata(mol_name,molgrp) - viztools.launchPyMol(mol_name) + indexes = get_user_values(['indexes'],vartypes='str',windowtitle='Enter indexes')[0] + indexes = indexes.split(',') - if action == actions['PDB2SQL']: - _,cplx_name,mol_name = item.name.split('/') - db = pdb2sql(molgrp['complex'].value) - treeview.emitDict.emit({'sql_' + item.basename: db}) + ind_values = [] + for ind in indexes: + if '-' in ind: + ind_values += list(range(int(ind.split('-')[0]),int(ind.split('-')[-1])+1)) + elif ind == 'all': + ind_values += [ind] + else: + ind_values += int(ind) + + grp = get_current_hdf5_group(self,item) + point_groups = list(filter(lambda x: 'point_' in x,list(grp.keys()))) + selected_values = [] + for subgroup in point_groups: + values = grp[subgroup + '/cp2k/mo/eigenvalues'].value + if ind_values == ['all']: + selected_values.append(values) + else: + selected_values.append(values[ind_values]) + selected_values = np.array(selected_values) -def _context_sparse(item,treeview,position): + data_dict = {'_data':selected_values} + treeview.emitDict.emit(data_dict) - menu = QtWidgets.QMenu() - actions = {} - list_operations = ['Load Matrix','Plot Histogram'] + data_dict = {'exec_cmd':'plot_time_series(_data)'} + treeview.emitDict.emit(data_dict) - for operation in list_operations: - actions[operation] = menu.addAction(operation) - action = menu.exec_(treeview.viewport().mapToGlobal(position)) - name = item.basename + '_' + item.name.split('/')[2] +def plot_coupling(self,item,treeview): - if action == actions['Load Matrix']: + indexes = get_user_values(['index1','index2'],vartypes='str',windowtitle='Enter indexes') - subgrp = item.data_file[item.name] - data_dict = {} - if not subgrp.attrs['sparse']: - data_dict[item.name] = subgrp['value'].value - else: - molgrp = item.data_file[item.parent.parent.parent.name] - grid = {} - lx = len(molgrp['grid_points/x'].value) - ly = len(molgrp['grid_points/y'].value) - lz = len(molgrp['grid_points/z'].value) - shape = (lx,ly,lz) - spg = sparse.FLANgrid(sparse=True,index=subgrp['index'].value,value=subgrp['value'].value,shape=shape) - data_dict[name] = spg.to_dense() - treeview.emitDict.emit(data_dict) - - if action == actions['Plot Histogram']: - - value = item.data_file[item.name]['value'].value - data_dict = {'value':value} - treeview.emitDict.emit(data_dict) - - cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.hist(value,25)\nplt.show()\n" - data_dict = {'exec_cmd':cmd} - treeview.emitDict.emit(data_dict) - -def _context_epoch(item,treeview,position): - - menu = QtWidgets.QMenu() - actions = {} - list_operations = ['Scatter Plot'] - - for operation in list_operations: - actions[operation] = menu.addAction(operation) - action = menu.exec_(treeview.viewport().mapToGlobal(position)) - - if action == actions['Scatter Plot']: - - - values = [] - train_out = item.data_file[item.name+'/train/outputs'].value - train_tar = item.data_file[item.name+'/train/targets'].value - values.append([x for x in train_out]) - values.append([x for x in train_tar]) - - - valid_out = item.data_file[item.name+'/valid/outputs'].value - valid_tar = item.data_file[item.name+'/valid/targets'].value - values.append([x for x in valid_tar]) - values.append([x for x in valid_out]) - - - test_out = item.data_file[item.name+'/test/outputs'].value - test_tar = item.data_file[item.name+'/test/targets'].value - values.append([x for x in test_tar]) - values.append([x for x in test_out]) - - vmin = np.array([x for a in values for x in a]).min() - vmax = np.array([x for a in values for x in a]).max() - delta = vmax-vmin - values.append([vmax + 0.1*delta]) - values.append([vmin - 0.1*delta]) - - data_dict = {'_values':values} - treeview.emitDict.emit(data_dict) - - data_dict = {} - cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\n" - cmd += "fig,ax = plt.subplots()\n" - cmd += "ax.scatter(_values[0],_values[1],c='red',label='train')\n" - cmd += "ax.scatter(_values[2],_values[3],c='blue',label='valid')\n" - cmd += "ax.scatter(_values[4],_values[5],c='green',label='test')\n" - cmd += "legen = ax.legend(loc='upper left')\n" - cmd += "ax.set_xlabel('Targets')\n" - cmd += "ax.set_ylabel('Predictions')\n" - cmd += "ax.plot([_values[-2],_values[-1]],[_values[-2],_values[-1]])\n" - cmd += "plt.show()\n" - data_dict['exec_cmd'] = cmd - treeview.emitDict.emit(data_dict) - -def _context_losses(item,treeview,position): - - menu = QtWidgets.QMenu() - actions = {} - list_operations = ['Plot Losses'] - - for operation in list_operations: - actions[operation] = menu.addAction(operation) - action = menu.exec_(treeview.viewport().mapToGlobal(position)) - - if action == actions['Plot Losses']: - - - values = [] - test = item.data_file[item.name+'/test'].value - train = item.data_file[item.name+'/train'].value - valid = item.data_file[item.name+'/valid'].value - values.append([x for x in train]) - values.append([x for x in valid]) - values.append([x for x in test]) - - data_dict = {'_values':values} - treeview.emitDict.emit(data_dict) - - data_dict = {} - cmd = "%matplotlib inline\nimport matplotlib.pyplot as plt\n" - cmd += "fig,ax = plt.subplots()\n" - cmd += "plt.plot(_values[0],c='red',label='train')\n" - cmd += "plt.plot(_values[1],c='blue',label='valid')\n" - cmd += "plt.plot(_values[2],c='green',label='test')\n" - cmd += "legen = ax.legend(loc='upper right')\n" - cmd += "ax.set_xlabel('Epoch')\n" - cmd += "ax.set_ylabel('Losses')\n" - cmd += "plt.show()\n" - data_dict['exec_cmd'] = cmd - treeview.emitDict.emit(data_dict) + both_ind_val = [] + for index in indexes: + index = index.split() + ind_values = [] + for ind in index: + if '-' in ind: + ind_values += list(range(int(ind.split('-')[0]),int(ind.split('-')[-1])+1)) + elif ind == 'all': + ind_values += [ind] + else: + ind_values += [int(ind)] + both_ind_val.append(ind_values) + + grp = get_current_hdf5_group(self,item) + point_groups = list(filter(lambda x: 'coupling_' in x,list(grp.keys()))) + selected_values = [] + for subgroup in point_groups: + + values = grp[subgroup].value + norb = values.shape[0] + + for i in range(2): + if both_ind_val[i] == ['all']: + both_ind_val[i] = list(range(norb)) + + selected_values.append(values[np.ix_(both_ind_val[0],both_ind_val[1])].flatten()) + selected_values = np.array(selected_values) + data_dict = {'_data':selected_values} + treeview.emitDict.emit(data_dict) + data_dict = {'exec_cmd':'plot_time_series(_data)'} + treeview.emitDict.emit(data_dict) diff --git a/example/qmflows-namd/qmfxplorer.py b/example/qmflows-namd/qmfxplorer.py index a774db8..143bab8 100755 --- a/example/qmflows-namd/qmfxplorer.py +++ b/example/qmflows-namd/qmfxplorer.py @@ -1,4 +1,5 @@ #!/usr/bin/env python from h5xplorer.h5xplorer import h5xplorer -app = h5xplorer() \ No newline at end of file +import menu +app = h5xplorer(menu.context_menu,baseimport='baseimport.py') \ No newline at end of file diff --git a/h5xplorer/menu_tools.py b/h5xplorer/menu_tools.py index f5475d7..4b51063 100644 --- a/h5xplorer/menu_tools.py +++ b/h5xplorer/menu_tools.py @@ -135,7 +135,7 @@ def print_attributes(self,item,treeview): data[a] = 0 treeview.emitDict.emit(data) -def get_user_values(varnames,windowtitle='Enter Values'): +def get_user_values(varnames,vartypes='float',windowtitle='Enter Values'): """Get the values of variables from the users Args: @@ -145,6 +145,6 @@ def get_user_values(varnames,windowtitle='Enter Values'): Returns: list: list of float of the desired variables """ - dialog = Dialog(varnames) + dialog = Dialog(varnames,vartypes=vartypes) dialog.exec_() return dialog.returnValues() \ No newline at end of file diff --git a/h5xplorer/standarddialogs.py b/h5xplorer/standarddialogs.py index 7a02076..6493012 100644 --- a/h5xplorer/standarddialogs.py +++ b/h5xplorer/standarddialogs.py @@ -24,12 +24,17 @@ class Dialog(QDialog): varnames (list): Name of the variable we want to input """ - def __init__(self, varnames, window_name = 'Enter Values', parent=None): + def __init__(self, varnames, vartypes = 'float', window_name = 'Enter Values', parent=None): super(Dialog, self).__init__(parent) frameStyle = QFrame.Sunken | QFrame.Panel self.varnames = varnames + self.vartypes = vartypes + if not isinstance(self.vartypes,list): + self.vartypes = [vartypes]*len(self.varnames) + + self.Label,self.Button,self.values = {},{},{} for name in varnames: @@ -40,8 +45,8 @@ def __init__(self, varnames, window_name = 'Enter Values', parent=None): self.closeButton = QPushButton("OK") - for name in varnames: - self.Button[name].clicked.connect(partial(self.setValue, name)) + for name,vtype in zip(self.varnames,self.vartypes): + self.Button[name].clicked.connect(partial(self.setValue, name,vtype)) self.closeButton.clicked.connect(self.close) self.native = QCheckBox() @@ -63,17 +68,33 @@ def __init__(self, varnames, window_name = 'Enter Values', parent=None): self.setWindowTitle(window_name) - def setValue(self,name): + def setValue(self,name,vtype): """Set the value of the variable Args: name (str): variable name + type (str): variable type """ - d, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", - "Amount:", 37.56, -10000, 10000, 2) - if ok: - self.Label[name].setText("$%g" % d) - self.values[name] = d + if vtype == 'float': + d, ok = QInputDialog.getDouble(self, "Get Double", + "Value:", 37.56, -10000, 10000, 2) + if ok: + self.Label[name].setText("$%g" % d) + self.values[name] = d + + elif vtype == 'str': + text, ok = QInputDialog.getText(self, "Get String", + "Value:", QLineEdit.Normal, '') + if ok and text != '': + self.Label[name].setText(text) + self.values[name] = text + + elif vtype == 'int': + i, ok = QInputDialog.getInt(self, "Get Integer", + "Value:", 25, 0, 100, 1) + if ok: + self.Label[name].setText("%d%%" % i) + self.values[name] = i def returnValues(self): """Return the values of all the variables