From edb505a7e50c81b5b9b7c3f4ae9e259da3da8a90 Mon Sep 17 00:00:00 2001
From: Dilawar Singh <dilawars@ncbs.res.in>
Date: Wed, 15 Feb 2017 12:06:37 +0530
Subject: [PATCH] Squashed 'moose-gui/' changes from 2ba6bd5..2a1f94f

2a1f94f modelRoot is cleanup for plotting if its comes from genesis or sbml, cleanup in networkx clean while import graphvizlayout
9d55f14 Function can be now on pool class also, and networkx need not to be checked for version for using graphviz_layout, import from network.drawing took care off.
35fb3ac If python-libsbml libs in not found, gui was failing to report which is fix here
34df1fb found a way to use networkX graphviz_layout directly using a importing lib, now no need to check networkx version
7b160c2 corrected indentation
e3e5d2e Merge commit 'f0fd0e53a20a237df81c8fc6615d81e66cf270ee'
a89f6b3 BhallaLab/moose#204.

git-subtree-dir: moose-gui
git-subtree-split: 2a1f94f4be0d4643956232d2eed290b649f12a71
---
 PlotWidgetContainer.py      | 18 +++++++++++--
 mgui.py                     | 38 +++++++++++++++-----------
 mload.py                    | 27 +++++++++++++------
 plugins/kkit.py             | 14 ++++++++--
 plugins/kkitOrdinateUtil.py | 53 ++++++++++++++++++++++++++++++-------
 5 files changed, 113 insertions(+), 37 deletions(-)

diff --git a/PlotWidgetContainer.py b/PlotWidgetContainer.py
index f42e0a87..a9656203 100644
--- a/PlotWidgetContainer.py
+++ b/PlotWidgetContainer.py
@@ -9,10 +9,10 @@ __author__      =   "Aviral Goel"
 __credits__     =   ["Upi Lab"]
 __license__     =   "GPL3"
 __version__     =   "1.0.0"
-__maintainer__  =   "Aviral Goel"
+__maintainer__  =   "Aviral Goel,HarshaRani"
 __email__       =   "goel.aviral@gmail.com"
 __status__      =   "Development"
-
+__updated__     =   "Feb 14 2017"
 
 import sys
 import os
@@ -49,6 +49,8 @@ class PlotWidgetContainer(QWidget):
 
         self.model          = moose.element(self.modelRoot)
         if self.modelRoot != "/":
+            self.modelRoot = self.findModelPath(self.modelRoot)
+
             if moose.exists(modelRoot + "/data"):
                 self.data   = moose.element(self.modelRoot + "/data")
             else:
@@ -87,6 +89,18 @@ class PlotWidgetContainer(QWidget):
         if len(self.data.children) == 0:
             self.addPlotWidget()
 
+    def mooseIsInstance(self,element, classNames):
+        return moose.element(element).__class__.__name__ in classNames
+
+
+    def findModelPath(self,element):
+        child = element
+        while not self.mooseIsInstance(element, "Shell"):
+            child = moose.element(element).path
+            element = moose.element(element).parent
+
+        return child
+    
     def deleteWidget(self, graphWidget):
         # print("Deleted => ", graphWidget)
         self.graphWidgets.remove(graphWidget)
diff --git a/mgui.py b/mgui.py
index ede1ba95..30790dd3 100644
--- a/mgui.py
+++ b/mgui.py
@@ -6,7 +6,7 @@
 # Maintainer:
 # Created: Mon Nov 12 09:38:09 2012 (+0530)
 # Version:
-# Last-Updated: Fri Oct 30 11:54:33 2015 (+0530)
+# Last-Updated: Tue Feb 14 15:20:33 2017 (+0530)
 #           By: Harsha
 #     Update #: 1338
 # URL:
@@ -564,7 +564,7 @@ class MWindow(QtGui.QMainWindow):
                 break
         if newSubWindow:
             subwin = self.mdiArea.addSubWindow(widget)
-            title = widget.modelRoot+'/model'
+            title = widget.modelRoot
             #subwin.setWindowTitle('%s: %s' % (view, widget.modelRoot))
             subwin.setWindowTitle('%s: %s' % (view, title))
             subwin.setSizePolicy(QtGui.QSizePolicy.Minimum |
@@ -1105,20 +1105,27 @@ class MWindow(QtGui.QMainWindow):
             ret = []
             ret,pluginName = self.checkPlugin(dialog)
             if pluginName == 'kkit':
-                compt = moose.wildcardFind(ret['model'].path+'/##[ISA=ChemCompt]')
-                if not len(compt):
-                    reply = QtGui.QMessageBox.question(self, "Model is empty","Model has no compartment, atleast one compartment should exist to display the widget\n Do you want another file",
-                                               QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
-                    if reply == QtGui.QMessageBox.Yes:
-                        dialog = LoaderDialog(self,self.tr('Load model from file'))
-                        if dialog.exec_():
-                            ret,pluginName = self.checkPlugin(dialog)
-                            ret,valid = self.dialog_check(ret)
-                    else:
-                        QtGui.QApplication.restoreOverrideCursor()        
+                if (ret['subtype'] == 'sbml' and ret['foundlib'] == False):
+                    reply = QtGui.QMessageBox.question(self, "python-libsbml is not found.","\n Read SBML is not possible.\n This can be installed using \n \n pip python-libsbml  or \n apt-get install python-libsbml",
+                                               QtGui.QMessageBox.Ok)
+                    if reply == QtGui.QMessageBox.Ok:
+                        QtGui.QApplication.restoreOverrideCursor()
                         return
                 else:
-                    valid = True
+                    compt = moose.wildcardFind(ret['model'].path+'/##[ISA=ChemCompt]')
+                    if not len(compt):
+                        reply = QtGui.QMessageBox.question(self, "Model is empty","Model has no compartment, atleast one compartment should exist to display the widget\n Do you want another file",
+                                                   QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
+                        if reply == QtGui.QMessageBox.Yes:
+                            dialog = LoaderDialog(self,self.tr('Load model from file'))
+                            if dialog.exec_():
+                                ret,pluginName = self.checkPlugin(dialog)
+                                ret,valid = self.dialog_check(ret)
+                        else:
+                            QtGui.QApplication.restoreOverrideCursor()        
+                            return
+                    else:
+                        valid = True
             if valid == True:
                 modelAnno = moose.Annotator(ret['model'].path+'/info')
                 if ret['subtype']:
@@ -1148,7 +1155,8 @@ class MWindow(QtGui.QMainWindow):
                 pluginName = subtype_plugin_map['%s/%s' % (ret['modeltype'], ret['subtype'])]
             except KeyError:
                 pluginName = 'default'
-            print 'Loaded model', ret['model'].path
+            if ret['foundlib']:
+                print 'Loaded model', ret['model'].path
             return ret,pluginName
 
     def dialog_check(self,ret):
diff --git a/mload.py b/mload.py
index b91e2888..cf0aeccd 100644
--- a/mload.py
+++ b/mload.py
@@ -118,6 +118,8 @@ def loadFile(filename, target, solver="gsl", merge=True):
     modelroot: root element of the model, None if could not be located - as is the case with Python scripts
     """
     num = 1
+    libsfound = True
+    model = '/'
     newTarget = target
     while moose.exists(newTarget):
         newTarget = target + "-" + str(num)
@@ -184,13 +186,21 @@ def loadFile(filename, target, solver="gsl", merge=True):
 
             # moose.move("cells/", cell.path)
         elif subtype == 'sbml':
-            if target != '/':
-                if moose.exists(target):
-                    moose.delete(target)
-            model = mooseReadSBML(filename,target)
-            if moose.exists(moose.element(model).path):
-                moose.Annotator(moose.element(model).path+'/info').modeltype = "sbml"
-            addSolver(target,'gsl')
+            foundLibSBML_ = False
+            try:
+                import libsbml
+                foundLibSBML_ = True
+            except ImportError:
+                pass
+            if foundLibSBML_:
+                if target != '/':
+                    if moose.exists(target):
+                        moose.delete(target)
+                model = mooseReadSBML(filename,target)
+                if moose.exists(moose.element(model).path):
+                    moose.Annotator(moose.element(model).path+'/info').modeltype = "sbml"
+                addSolver(target,'gsl')
+            libsfound = foundLibSBML_
     else:
         raise FileLoadError('Do not know how to handle this filetype: %s' % (filename))
     moose.setCwe(pwe) # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour
@@ -200,7 +210,8 @@ def loadFile(filename, target, solver="gsl", merge=True):
     # app.restoreOverrideCursor()
     return {'modeltype': modeltype,
             'subtype': subtype,
-            'model': model}
+            'model': model,
+            'foundlib' :libsfound}
 
 
 
diff --git a/plugins/kkit.py b/plugins/kkit.py
index 5b79ea6f..8709044a 100644
--- a/plugins/kkit.py
+++ b/plugins/kkit.py
@@ -1,3 +1,13 @@
+
+__author__      =   "HarshaRani"
+__credits__     =   ["Upi Lab"]
+__license__     =   "GPL3"
+__version__     =   "1.0.0"
+__maintainer__  =   "HarshaRani"
+__email__       =   "hrani@ncbs.res.in"
+__status__      =   "Development"
+__updated__     =   "Feb 14 2017"
+
 import sys
 from PyQt4 import QtGui, QtCore, Qt
 from default import *
@@ -78,7 +88,7 @@ class KkitPlugin(MoosePlugin):
                 writeerror,consistencyMessages,writtentofile = moose.SBML.mooseWriteSBML(self.modelRoot,str(filename),self.coOrdinates)
                 if writeerror == -2:
                     #QtGui.QMessageBox.warning(None,'Could not save the Model','\n WriteSBML :  This copy of MOOSE has not been compiled with SBML writing support.')
-                    QtGui.QMessageBox.warning(None,'Could not save the Model',consistencyMessages)
+                    QtGui.QMessageBox.warning(None,'python-libsbml is not found',consistencyMessages)
                 elif writeerror == -1:
                     QtGui.QMessageBox.warning(None,'Could not save the Model','\n This model is not valid SBML Model, failed in the consistency check')
                 elif writeerror == 1:
@@ -592,7 +602,7 @@ class  KineticsWidget(EditorWidgetBase):
             comptt = ["CubeMesh","CylMesh"]
 
             if objClass in funct:
-                poolt = ["ZombieBufPool","BufPool"]
+                poolt = ["ZombieBufPool","BufPool","ZombiePool","Pool"]
                 if graphicalObj.mobj.parent.className in poolt:
                     xpos = 0
                     ypos = 30
diff --git a/plugins/kkitOrdinateUtil.py b/plugins/kkitOrdinateUtil.py
index a4ac1bc2..dcfeb8ac 100644
--- a/plugins/kkitOrdinateUtil.py
+++ b/plugins/kkitOrdinateUtil.py
@@ -1,8 +1,18 @@
+__author__      =   "HarshaRani"
+__credits__     =   ["Upi Lab"]
+__license__     =   "GPL3"
+__version__     =   "1.0.0"
+__maintainer__  =   "HarshaRani"
+__email__       =   "hrani@ncbs.res.in"
+__status__      =   "Development"
+__updated__     =   "Feb 14 2017"
+
 from moose import *
 import numpy as np
-import networkx as nx
 from collections import Counter
-
+import networkx as nx
+from networkx.drawing.nx_agraph import graphviz_layout
+#import pygraphviz as pgv
 def xyPosition(objInfo,xory):
     try:
         return(float(element(objInfo).getField(xory)))
@@ -181,6 +191,8 @@ def autoCoordinates(meshEntry,srcdesConnection):
     ymin = 0.0
     ymax = 1.0
     G = nx.Graph()
+    #G = pgv.AGraph()
+    positionInfo = {}
     for cmpt,memb in meshEntry.items():
         for enzObj in find_index(memb,'enzyme'):
             #G.add_node(enzObj.path)
@@ -218,17 +230,10 @@ def autoCoordinates(meshEntry,srcdesConnection):
             else:
                 for items in (items for items in out ):
                     G.add_edge(element(items[0]).path,inn.path)
-    position = nx.spring_layout(G)
-    #nx.draw(G,pos=nx.spring_layout(G))
-    #position = nx.spring_layout(G)
-    #import matplotlib.pyplot as plt
-    #plt.savefig('test.png')
-    #position = nx.graphviz_layout(G, prog = 'dot')
-    #agraph = nx.to_agraph(G)
-    #agraph.draw("test.png", format = 'png', prog = 'dot')
     xcord = []
     ycord = []
     
+    position = graphviz_layout(G)
     for item in position.items():
         xy = item[1]
         ann = moose.Annotator(item[0]+'/info')
@@ -237,6 +242,34 @@ def autoCoordinates(meshEntry,srcdesConnection):
         ann.y = xy[1]
         ycord.append(xy[1])
     
+    '''
+    if int( nx.__version__.split( '.' )[-1] ) >= 11:
+     	position = nx.spring_layout( G )
+    else:
+     	position = nx.graphviz_layout(G, prog = 'dot')
+    for item in position.items():
+        xy = item[1]
+        ann = moose.Annotator(item[0]+'/info')
+        ann.x = xy[0]
+        xcord.append(xy[0])
+        ann.y = xy[1]
+        ycord.append(xy[1])
+    '''
+    '''
+    #pygraphviz
+    G.layout()
+    for n in G.nodes():
+        print "inside 250 "
+        value = str(n.attr['pos'])
+        valuelist = (value.split(','))
+        positionInfo[(moose.element(n)).path] ={'x':float(valuelist[0]),'y':float(valuelist[1])}
+        ann = moose.Annotator(moose.element(n).path+'/info')
+        ann.x = float(valuelist[0])
+        ann.y = float(valuelist[1])
+        
+        xcord.append(float(valuelist[0]))
+        xcord.append(float(valuelist[1]))
+    '''
     if xcord and ycord:
         xmin = min(xcord)
         xmax = max(xcord)
-- 
GitLab