From aca403470ae87f49782542a63c8dcc4649553369 Mon Sep 17 00:00:00 2001
From: Dilawar Singh <dilawars@ncbs.res.in>
Date: Mon, 14 Nov 2016 12:02:44 +0530
Subject: [PATCH] Squashed 'moose-gui/' changes from 1e5f537..e49ca7d

e49ca7d Changes Function symbol to summation symbol, objectedit.py function expr is not editable as this summation of pools, some cleanup with colors selection,Function which is now just summation object, set's up setN for output as input is nout
328b8f5 for now function output connected to pool via setConc message, but there is "increment" which depend on the function input this will be fixed later
16075b3 cleanup with colormap string from genesis file
aa377ed resetup for multicompartment model before setting up the solver
26d2be7 Changes made are related to functions which now doesn't need parent as pool but if exist like in case of genesis then it displays as its, setsolver: setting ticks to table, 18 is not required as its set default when table is created
7ad2bb9 plot are saved to csv forms
20a76af some more cleanup
653b464 added units for Km, kcat is added which display in object editor
cbf2c5e added units for volume which display in object editor, vector data for stimulusTable is editable for enz_cplx delete and move is not allowed so removed the icons
6882e0b some more colors to ignore which are light
faad938 If compartment is moved,then object is move then, movement of object with respect to qtscenecoro-ordinates was not moving correctly that is correctly, in KKitOrdinateUtil: pygraphviz:- instead of larrow for reaction I have circle for now, if one needs to save the image of the model loaded
0f0674d small cleanup
0ab70d7 cleaner way to set co-ordinate with round trip
49a3f9c time being removing import sbml
0622266 instead of pygraphviz_layout which was dependent on pygrapviz installation using graphviz_layot from networkx itself
a62e275 MMENZ and cplx connection exist, if MMEnz is moved then arrow to cplx is updated
ad437db saved sbmlfile return to calling function
a108d2c Instead of spring_layout using pygraphviz_layout which can be further used for saving the layout image to png format
624f52b 1.Getting layout co-ordinates to Genesis co-ordinates 2.Automaticlayout done using pyqgraphviz for files for sbml and cspace. 3.Separate messge if missing output for StimulusTable and Function
db36afc Size of the compartment is cleanedup
1ef13c9 QGraphicsRectItem when no children, then setRect size is fixed to default size

git-subtree-dir: moose-gui
git-subtree-split: e49ca7da411f0cc7ad8b62ff077522ef92ba2390
---
 defaults.py                  |   3 +
 icons/classIcon/Function.png | Bin 597 -> 986 bytes
 mload.py                     |   4 +-
 objectedit.py                |  31 ++++++++--
 plugins/default.py           |   6 +-
 plugins/kkit.py              | 113 +++++++++++++++++++++++++++-------
 plugins/kkitOrdinateUtil.py  |  30 +++++----
 plugins/kkitQGraphics.py     |  14 +++--
 plugins/kkitUtil.py          |  22 ++++---
 plugins/kkitViewcontrol.py   | 115 ++++++++++++++++++++++++-----------
 plugins/modelBuild.py        |  25 +++++---
 plugins/setsolver.py         |  33 ++++++++--
 12 files changed, 295 insertions(+), 101 deletions(-)

diff --git a/defaults.py b/defaults.py
index bb49b93c..6551d2d9 100644
--- a/defaults.py
+++ b/defaults.py
@@ -9,6 +9,9 @@ PLOT_FIELDS={
     'CaConc':['Ca']
     }
 FIELD_UNITS={
+    'volume':'m3',
+    'Km':'mM',
+    'kcat':'s-1',
     'Vm':'V',
     'conc':'mM',
     'concInit':'mM',
diff --git a/icons/classIcon/Function.png b/icons/classIcon/Function.png
index cd17659503a400106b3c1e236cccf65ba79cadb8..d516dddb3e6265868ddf7de3fdccc05507ac038a 100644
GIT binary patch
delta 919
zcmV;I18Dr!1lk87iBL{Q4GJ0x0000DNk~Le0000j0000q2m$~A0Fj|4o{=Fh1|t<Y
zAO_-*RwsW0M@d9MR9M69m|aMdVHAMBZ@7hXnG+3CD6N*QloWO)UPSw;t@@g#1Hlbi
zS}RxhgQew9IH;Q`rU{D9Wje40uAgtywW)+Gkdn-VLN5Y~+F(w>1?phyF5+ks<W2=U
zm(O`Gp6}y*&pGc)E-(7FbK?oDSYGsP$Qi`H5fOinh{t9TMGyp&$qWPnAW>Oad8_s&
z>i_8P?`JUJk7;UZYHn>q^^i%#-QC?JNrGHMLxZ9B0qXuJ$d$LWw5(5;mzSFdEvWlc
zty1cAI*<;9LM0_7w&xDi^HQcQt*WX5D}upbQBlzg*GtrMTYsZQqtO5u2n6!;^IuQB
z4WEApxnbkcXs?(|CIC4c&dA8fp#wa;I@WQoO)i%M==b}jQt8J}pHb^+pRq?I5&`J*
z`6LpF+q-~T*Da6C+1c3uy4`M}P`J44N9`|mE1i{<1>pSryhtSawz`Je=j?VnpU($y
zc6L@GkpwY4qM1<+ha)vL74YflX~_vGYTtj~5yN&mok>YafKN<JP<dxj=Z~H7T!+Jv
zkdOfQ*w|R1QiVDP?M~V?JUkp58w)s1(<PTKqt0V#`}SI`RyLar_`twG#kK3Gb75xs
zVT;AWVzB`4>guX*)S=F&d_JGc<*w&UCKJ^|CX;zQ9sm^zMO{rbo=0whVrFIrz?^@a
z97AUZ-u}2+QR#F#0p#&`PoF%-J1@<xZAPOJz{JGFp`jrr<4^BF<gYH^u=hTrRVrAo
zqNAfnM@Q2SrXkg_S8t|@i;LkGkYrz9-<C-HmdE^;uX%ZSYiqE}>-GBM!edB%&cCuM
zlgXBrmH^jkwHMUq!agVeh@&F$<m7)OfD}cUdhg@SV}(l9dI^C*u;mh)c~sZd(KHQU
zN=nLl7)FmyLr;5qJAiR<aW<PRW*ZCX9yRP7Q79ClQ0QmKVzKOYyCCxj(!KKC`wvQ`
z5=amPVK5lNCjmV?3qFdXR#sNPBArerKXnr6o*f7VrBbQa>jf*+YIT{m6z^l*;WTw-
zZf*{w#bWW@COzIe%=wENm&*lm85tRa=7)IiQjNFon9XL8NKQ_+*=z(>kQ=`9b2yyw
t@$vmBd;YRVSYyME7J1i>c>E6@-vMI^DHkRw<&^*c002ovPDHLkV1f+`v(Eqk

delta 527
zcmV+q0`UFX2h{{2iBL{Q4GJ0x0000DNk~Le0000U0000%2m$~A07;62*O4JF1|&D5
z0nx#cRwsV}!bwCyR9M4f{QUkM18o2c@k&peIlF%S`g7;bJ$Ufo)2C0re*NO+=H}ty
z5fc+rR8-W^(5NgeK~~R5jH|ETzLS`kc=hU4JZel$P515ENt&w<9z7Nm6!h!YFZ{~P
z&CSt7nDA?O@Z@P|XedE*85kJM%*;qLIxQ{j`}cqE#KZ)q(f9)7%8i@Hj~_=9WMgB?
z%*>34h|tkcCqISk*s%jmgq@vz-@bi%TAIZ817Cn#zkVG}Bqk<?NOK7oee>o`G!Z{P
zKjQNNKBHf~dW9yUt*uQRqrZIlf+iv^EJPinzkdBnNg0CA=zstI(aLBF!O%1sQK<3?
z3Xy+j1g>IvG^__A8ZiN8#FA9~kB0TA(W6F>8a-<CsL`WFj~YE{^r+FJMh}S5tgNiG
zGMbBvi#kTXc=HxbL`X=8I!5o^yBAGFR#uiwqwhX^1Y!JVVA!!|Z*6TYno^R+Ss38M
zT8EFH@bdD)uhib&o*Y-7K7AU$I&pDvZ+BZaa*RH6<_x~hB_rdsY17C|*LaNP<KtVh
zWQm)TBbmM3r!QY^-n@C&u3fip-+ub^DJv_hu&}U}mX@olYf?f2D>FHn762PCkPuFR
RdiMYT002ovPDHLkV1oP<`yBuP

diff --git a/mload.py b/mload.py
index d495f2c8..916a33c4 100644
--- a/mload.py
+++ b/mload.py
@@ -54,6 +54,7 @@ from os.path import basename
 from os.path import splitext
 from PyQt4 import QtGui, QtCore, Qt
 from plugins.setsolver import *
+from moose.SBML import *
 
 def loadGenCsp(target,filename,solver="gsl"):
     target = target.replace(" ", "")
@@ -99,7 +100,6 @@ def loadGenCsp(target,filename,solver="gsl"):
     return(modelpath1,modelpath1.path)
 
 def loadFile(filename, target, solver="gsl", merge=True):
-    print " solver @ loadFile",solver
     """Try to load a model from specified `filename` under the element
     `target`.
 
@@ -187,7 +187,7 @@ def loadFile(filename, target, solver="gsl", merge=True):
             if target != '/':
                 if moose.exists(target):
                     moose.delete(target)
-            model = moose.readSBML(filename,target,'gsl')
+            model = mooseReadSBML(filename,target)
             if moose.exists(moose.element(model).path):
                 moose.Annotator(moose.element(model).path+'/info').modeltype = "sbml"
             addSolver(target,'gsl')
diff --git a/objectedit.py b/objectedit.py
index 4e72565e..2545a1e2 100644
--- a/objectedit.py
+++ b/objectedit.py
@@ -6,9 +6,9 @@
 # Maintainer:
 # Created: Wed Jun 30 11:18:34 2010 (+0530)
 # Version:
-# Last-Updated: Wed Mar 28 14:26:59 2014 (+0530)
+# Last-Updated: Wed Aug 3 15:55:59 2016 (+0530)
 #           By: Harsha
-#     Update #: 917
+#     Update #: 
 # URL:
 # Keywords:
 # Compatibility:
@@ -206,10 +206,33 @@ class ObjectEditModel(QtCore.QAbstractTableModel):
                 value = type(oldValue)(value)
                 ann.setField(field,value)
                 self.undoStack.append((index,oldValue))
+            elif field == "vector":
+                for ch in ['[',']']:
+                    if ch in value:
+                        value = value.replace(ch," ")
+                value = value.replace(",", " ")
+                valuelist = []
+                if value.find(',') != -1:
+                    valuelist = value.split(",")
+                elif value.find(' ') != -1:
+                    valuelist = value.split(" ")
+                else:
+                    valuelist = value
+                vectorlist = []
+                for d in valuelist:
+                    try:
+                        float(d)
+                        vectorlist.append(float(d))
+                    except:
+                        pass
+                from numpy import array
+                a = array( vectorlist )
+                self.mooseObject.setField(field, a)
+            
             else:
                 oldValue = self.mooseObject.getField(field)
                 value = type(oldValue)(value)
-                self.mooseObject.setField(field, value)
+                tt = self.mooseObject.setField(field, value)
                 self.undoStack.append((index, oldValue))
             if field == 'name':
                 self.emit(QtCore.SIGNAL('objectNameChanged(PyQt_PyObject)'), self.mooseObject)
@@ -265,7 +288,7 @@ class ObjectEditModel(QtCore.QAbstractTableModel):
                     flag |= QtCore.Qt.ItemIsEditable
             
             if isinstance(self.mooseObject, moose.PoolBase) or isinstance(self.mooseObject,moose.Function): 
-                if field == 'volume':# or field == 'expr':
+                if field == 'volume' or field == 'expr':
                     pass
                 elif setter in self.mooseObject.getFieldNames('destFinfo'):
                     flag |= QtCore.Qt.ItemIsEditable
diff --git a/plugins/default.py b/plugins/default.py
index cb940727..ccf8846d 100644
--- a/plugins/default.py
+++ b/plugins/default.py
@@ -1204,7 +1204,9 @@ class PlotWidget(QWidget):
             x = np.linspace(0, xSrc.currentTime, len(y))
         elif isinstance(xSrc, moose.Table):
             x = xSrc.vector.copy()
-        filename = str(directory)+'/'+'%s.csv' % (ySrc.name)
+        nameVec = ySrc.neighbors['requestOut']
+        name = moose.element(nameVec[0]).name
+        filename = str(directory)+'/'+'%s.csv' %(name)
         np.savetxt(filename, np.vstack((x, y)).transpose())
         print 'Saved data from %s and %s in %s' % (xSrc.path, ySrc.path, filename)
 
@@ -1224,7 +1226,7 @@ class PlotWidget(QWidget):
         if fileDialog2.exec_():
             directory = fileDialog2.directory().path()
             for line in self.lineToDataSource.keys():
-                self.saveCsv(line,directory)
+		        self.saveCsv(line,directory)
 
 
     def getMenus(self):
diff --git a/plugins/kkit.py b/plugins/kkit.py
index d3706c8b..a43aea67 100644
--- a/plugins/kkit.py
+++ b/plugins/kkit.py
@@ -3,6 +3,7 @@ from PyQt4 import QtGui, QtCore, Qt
 from default import *
 from moose import *
 from moose.genesis import write
+from moose import SBML
 #sys.path.append('plugins')
 from mplugin import *
 from kkitUtil import *
@@ -62,22 +63,54 @@ class KkitPlugin(MoosePlugin):
         if filename:
             filename = filename
             if filters[str(filter_)] == 'SBML':
-                writeerror = moose.writeSBML(self.modelRoot,str(filename))
+                self.sceneObj = KkitEditorView(self).getCentralWidget().mooseId_GObj
+                self.coOrdinates = {}
+                for k,v in self.sceneObj.items():
+                    if moose.exists(moose.element(k).path+'/info'):
+                        annoInfo = Annotator(k.path+'/info')
+                        self.coOrdinates[k] = {'x':annoInfo.x, 'y':annoInfo.y}
+
+                #writeerror = moose.writeSBML(self.modelRoot,str(filename),self.coOrdinates)
+                writeerror = -2
+                conisitencyMessages = ""
+                writtentofile = "/test.xml"
+                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','\n WriteSBML :  This copy of MOOSE has not been compiled with SBML writing support.')
+                    QtGui.QMessageBox.warning(None,'Could not save the Model',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:
                     QtGui.QMessageBox.information(None,'Saved the Model','\n File saved to \'{filename}\''.format(filename =filename+'.xml'),QtGui.QMessageBox.Ok)
                 elif writeerror == 0:
                      QtGui.QMessageBox.information(None,'Could not save the Model','\nThe filename could not be opened for writing')
+
             elif filters[str(filter_)] == 'Genesis':
-                self.sceneObj = KkitEditorView(self).getCentralWidget().mooseId_GObj
+                mdtype = moose.Annotator(self.modelRoot+'/info')
                 self.coOrdinates = {}
+                xycord = []
+                self.sceneObj = KkitEditorView(self).getCentralWidget().mooseId_GObj
+                #Here get x,y coordinates from the Annotation, to save layout position 
+                # into genesis
                 for k,v in self.sceneObj.items():
                     if moose.exists(moose.element(k).path+'/info'):
                         annoInfo = Annotator(k.path+'/info')
                         self.coOrdinates[k] = {'x':annoInfo.x, 'y':annoInfo.y}
+                if mdtype.modeltype != "kkit":
+                    #If coordinates come from kkit then directly transfering the co-ordinates 
+                    # else zoomed in factor is applied before saving it to genesis form
+                    for k,v in self.coOrdinates.items():
+                        xycord.append(v['x'])
+                        xycord.append(v['y'])
+                    cmin = min(xycord)
+                    cmax = max(xycord)
+                    for k,v in self.coOrdinates.items():
+                        x = v['x']
+                        xprime = int((20*(float(v['x']-cmin)/float(cmax-cmin)))-10)
+                        v['x'] = xprime
+                        y = v['y']
+                        yprime = int((20*(float(v['y']-cmin)/float(cmax-cmin)))-10)
+                        v['y'] = -yprime
 
                 filename = filename
                 writeerror = write(self.modelRoot,str(filename),self.coOrdinates)
@@ -309,6 +342,13 @@ class  KineticsWidget(EditorWidgetBase):
         self.mooseId_GObj       = {}
         self.srcdesConnection   = {}
         self.editor             = None
+        self.xmin               = 0.0
+        self.xmax               = 1.0
+        self.ymin               = 0.0
+        self.ymax               = 1.0
+        self.xratio             = 1.0
+        self.yratio             = 1.0
+
 
     def reset(self):
         self.createdItem = {}
@@ -330,6 +370,7 @@ class  KineticsWidget(EditorWidgetBase):
 
     def updateModelView(self):
         self.getMooseObj()
+        minmaxratiodict = {'xmin':self.xmin,'xmax':self.xmax,'ymin':self.ymin,'ymax':self.ymax,'xratio':self.xratio,'yratio':self.yratio}
         if not self.m:
             #At the time of model building
             # when we want an empty GraphicView while creating new model,
@@ -337,7 +378,7 @@ class  KineticsWidget(EditorWidgetBase):
             if hasattr(self, 'view') and isinstance(self.view, QtGui.QWidget):
                 self.layout().removeWidget(self.view)
            #self.sceneContainer.setSceneRect(-self.width()/2,-self.height()/2,self.width(),self.height())
-            self.view = GraphicalView(self.modelRoot,self.sceneContainer,self.border,self,self.createdItem)
+            self.view = GraphicalView(self.modelRoot,self.sceneContainer,self.border,self,self.createdItem,minmaxratiodict)
 
             if isinstance(self,kineticEditorWidget):
                 self.view.setRefWidget("editorView")
@@ -355,7 +396,7 @@ class  KineticsWidget(EditorWidgetBase):
             #self.drawLine_arrow()
             if hasattr(self, 'view') and isinstance(self.view, QtGui.QWidget):
                 self.layout().removeWidget(self.view)
-            self.view = GraphicalView(self.modelRoot,self.sceneContainer,self.border,self,self.createdItem)
+            self.view = GraphicalView(self.modelRoot,self.sceneContainer,self.border,self,self.createdItem,minmaxratiodict)
             if isinstance(self,kineticEditorWidget):
                 #self.getMooseObj()
                 self.mooseObjOntoscene()
@@ -380,10 +421,10 @@ class  KineticsWidget(EditorWidgetBase):
         # setupItem
         self.m = wildcardFind(self.modelRoot+'/##[ISA=ChemCompt]')
         if self.m:
-            self.xmin = 0.0
-            self.xmax = 1.0
-            self.ymin = 0.0
-            self.ymax = 1.0
+            # self.xmin = 0.0
+            # self.xmax = 1.0
+            # self.ymin = 0.0
+            # self.ymax = 1.0
             self.autoCordinatepos = {}
             self.srcdesConnection = {}
 
@@ -402,6 +443,7 @@ class  KineticsWidget(EditorWidgetBase):
                 self.xmin,self.xmax,self.ymin,self.ymax,self.autoCordinatepos = autoCoordinates(self.meshEntry,self.srcdesConnection)
             # TODO: size will be dummy at this point, but size I need the availiable size from the Gui
             self.size= QtCore.QSize(1000 ,550)
+
             if self.xmax-self.xmin != 0:
                 self.xratio = (self.size.width()-10)/(self.xmax-self.xmin)
             else: self.xratio = self.size.width()-10
@@ -409,8 +451,13 @@ class  KineticsWidget(EditorWidgetBase):
             if self.ymax-self.ymin:
                 self.yratio = (self.size.height()-10)/(self.ymax-self.ymin)
             else: self.yratio = (self.size.height()-10)
+            
             self.xratio = int(self.xratio)
             self.yratio = int(self.yratio)
+            if self.xratio == 0:
+                self.xratio = 1
+            if self.yratio == 0:
+                self.yratio = 1
             
     def sizeHint(self):
         return QtCore.QSize(800,400)
@@ -493,8 +540,13 @@ class  KineticsWidget(EditorWidgetBase):
                 self.mooseId_GObj[element(tabObj.getId())] = tabItem
 
             for funcObj in find_index(memb,'function'):
-                funcinfo = moose.element(funcObj.parent).path+'/info'
-                funcParent =self.mooseId_GObj[element(funcObj.parent)]
+                funcinfo = moose.element(funcObj).path+'/info'
+                if funcObj.parent.className == "ZombieBufPool" or funcObj.parent.className == "BufPool":
+                    funcinfo = moose.element(funcObj).path+'/info'
+                    Af = Annotator(funcinfo)
+                    funcParent =self.mooseId_GObj[element(funcObj.parent)]
+                elif funcObj.parent.className == "CubeMesh" or funcObj.parent.className == "CylMesh":
+                    funcParent = self.qGraCompt[cmpt]
                 funcItem = FuncItem(funcObj,funcParent)
                 self.mooseId_GObj[element(funcObj.getId())] = funcItem
                 self.setupDisplay(funcinfo,funcItem,"Function")
@@ -513,7 +565,6 @@ class  KineticsWidget(EditorWidgetBase):
     def comptChilrenBoundingRect(self):
         for k, v in self.qGraCompt.items():
             # compartment's rectangle size is calculated depending on children
-            #rectcompt = v.childrenBoundingRect()
             rectcompt = calculateChildBoundingRect(v)
             v.setRect(rectcompt.x()-10,rectcompt.y()-10,(rectcompt.width()+20),(rectcompt.height()+20))
             v.setPen(QtGui.QPen(Qt.QColor(66,66,66,100), self.comptPen, Qt.Qt.SolidLine, Qt.Qt.RoundCap, Qt.Qt.RoundJoin))
@@ -536,9 +587,22 @@ class  KineticsWidget(EditorWidgetBase):
                 bgcolor = getRandColor()
                 Annoinfo.color = str(bgcolor.name())
         if isinstance(self,kineticEditorWidget):
-            xpos,ypos = self.positioninfo(info)
+            funct = ["Function","ZombieFunction"]
+            comptt = ["CubeMesh","CylMesh"]
+
+            if objClass in funct:
+                poolt = ["ZombieBufPool","BufPool"]
+                if graphicalObj.mobj.parent.className in poolt:
+                    xpos = 0
+                    ypos = 30
+                if graphicalObj.mobj.parent.className in comptt:
+                    xpos,ypos = self.positioninfo(info)
+            else:
+                xpos,ypos = self.positioninfo(info)
+
             self.xylist = [xpos,ypos]
             self.xyCord[moose.element(info).parent] = [xpos,ypos]
+
         elif isinstance(self,kineticRunWidget):
             self.editormooseId_GObj = self.editor.getCentralWidget().mooseId_GObj
             editorItem = self.editormooseId_GObj[moose.element(info).parent]
@@ -547,8 +611,8 @@ class  KineticsWidget(EditorWidgetBase):
             #Annoinfo.x = xpos
             #Annoinfo.y = -ypos 
         graphicalObj.setDisplayProperties(xpos,ypos,textcolor,bgcolor)
-        Annoinfo.x = xpos
-        Annoinfo.y = ypos
+        #Annoinfo.x = xpos
+        #Annoinfo.y = ypos
 
     def positioninfo(self,iteminfo):
         Anno = moose.Annotator(self.modelRoot+'/info')
@@ -572,9 +636,8 @@ class  KineticsWidget(EditorWidgetBase):
             #     ypos = 1.0-(y-self.ymin)*self.yratio
             # else:
             #     ypos = (y-self.ymin)*self.yratio
-            ypos = (y-self.ymin)*self.yratio
+            ypos = 1.0 - (y-self.ymin)*self.yratio
         xpos = (x-self.xmin)*self.xratio
-
         return(xpos,ypos)
 
     def drawLine_arrow(self, itemignoreZooming=False):
@@ -601,7 +664,10 @@ class  KineticsWidget(EditorWidgetBase):
                         self.lineCord(src,des,items,itemignoreZooming)
             elif isinstance(out,list):
                 if len(out) == 0:
-                    print "Func pool doesn't have sumtotal"
+                    if inn.className == "StimulusTable":
+                        print inn.name +" doesn't have output"
+                    elif inn.className == "ZombieFunction" or inn.className == "Function":
+                        print inn.name + " doesn't have sumtotal "
                 else:
                     src = self.mooseId_GObj[inn]
                     for items in (items for items in out ):
@@ -692,7 +758,8 @@ class  KineticsWidget(EditorWidgetBase):
             l = elePath[0:pos]
             linfo = moose.Annotator(l+'/info')
             for k, v in self.qGraCompt.items():
-                rectcompt = v.childrenBoundingRect()
+                #rectcompt = v.childrenBoundingRect()
+                rectcompt = calculateChildBoundingRect(v)
                 comptBoundingRect = v.boundingRect()
                 if not comptBoundingRect.contains(rectcompt):
                     self.updateCompartmentSize(v)
@@ -709,8 +776,12 @@ class  KineticsWidget(EditorWidgetBase):
                 '''
     def updateCompartmentSize(self, compartment):
         compartmentBoundary = compartment.rect()
+        #print " compartmentBoundary ",compartmentBoundary, "  ",compartment.childrenBoundingRect()
+        #compartmentBoundary =compartment.childrenBoundingRect()
         #childrenBoundary    = compartment.childrenBoundingRect()
+        #print " 758 ",compartment.childrenBoundaryRect()
         childrenBoundary = calculateChildBoundingRect(compartment)
+        #print " ch ",childrenBoundary
         x = min(compartmentBoundary.x(), childrenBoundary.x())
         y = min(compartmentBoundary.y(), childrenBoundary.y())
         width = max(compartmentBoundary.width(), childrenBoundary.width())
@@ -732,9 +803,9 @@ class  KineticsWidget(EditorWidgetBase):
             # Checking if src (srcdes[0]) or des (srcdes[1]) is ZombieEnz,
             # if yes then need to check if cplx is connected to any mooseObject,
             # so that when Enzyme is moved, cplx connected arrow to other mooseObject(poolItem) should also be updated
-            if( type(srcdes[0]) == EnzItem):
+            if( type(srcdes[0]) == EnzItem or type(srcdes[0] == MMEnzItem)):
                 self.cplxUpdatearrow(srcdes[0])
-            elif( type(srcdes[1]) == EnzItem):
+            elif( type(srcdes[1]) == EnzItem or type(srcdes[1] == MMEnzItem)):
                 self.cplxUpdatearrow(srcdes[1])
             # For calcArrow(src,des,endtype,itemignoreZooming) is to be provided
             arrow = calcArrow(srcdes,self.itemignoreZooming,self.iconScale)
diff --git a/plugins/kkitOrdinateUtil.py b/plugins/kkitOrdinateUtil.py
index 36e8e833..01bcafd4 100644
--- a/plugins/kkitOrdinateUtil.py
+++ b/plugins/kkitOrdinateUtil.py
@@ -76,6 +76,7 @@ def setupMeshObj(modelRoot):
 
 def sizeHint(self):
     return QtCore.QSize(800,400)
+
 def getxyCord(xcord,ycord,list1):
     for item in list1:
         # if isinstance(item,Function):
@@ -175,8 +176,6 @@ def countitems(mitems,objtype):
     return(uniqItems,countuniqItems)
 
 def autoCoordinates(meshEntry,srcdesConnection):
-    #for cmpt,memb in meshEntry.items():
-    #    print memb
     xmin = 0.0
     xmax = 1.0
     ymin = 0.0
@@ -184,15 +183,19 @@ def autoCoordinates(meshEntry,srcdesConnection):
     G = nx.Graph()
     for cmpt,memb in meshEntry.items():
         for enzObj in find_index(memb,'enzyme'):
-            G.add_node(enzObj.path)
+            #G.add_node(enzObj.path)
+            G.add_node(enzObj.path,label='',shape='ellipse',color='',style='filled',fontname='Helvetica',fontsize=12,fontcolor='blue')
     for cmpt,memb in meshEntry.items():
         for poolObj in find_index(memb,'pool'):
-            G.add_node(poolObj.path)
+            #G.add_node(poolObj.path)
+            G.add_node(poolObj.path,label = poolObj.name,shape = 'box',color = '',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
         for cplxObj in find_index(memb,'cplx'):
             G.add_node(cplxObj.path)
-            G.add_edge((cplxObj.parent).path,cplxObj.path)
+            G.add_node(cplxObj.path,label = cplxObj.name,shape = 'box',color = '',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
+            #G.add_edge((cplxObj.parent).path,cplxObj.path)
         for reaObj in find_index(memb,'reaction'):
-            G.add_node(reaObj.path)
+            #G.add_node(reaObj.path)
+            G.add_node(reaObj.path,label='',shape='circle',color='')
         
     for inn,out in srcdesConnection.items():
         if (inn.className =='ZombieReac'): arrowcolor = 'green'
@@ -216,11 +219,16 @@ def autoCoordinates(meshEntry,srcdesConnection):
                 for items in (items for items in out ):
                     G.add_edge(element(items[0]).path,inn.path)
     
-    nx.draw(G,pos=nx.spring_layout(G))
-    #plt.savefig('/home/harsha/Desktop/netwrokXtest.png')
+    #nx.draw(G,pos=nx.spring_layout(G))
+    #position = nx.spring_layout(G)
+    #import matplotlib.pyplot as plt
+    #plt.savefig('/home/harsha/Trash/Trash_SBML/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 = nx.spring_layout(G)
+    
     for item in position.items():
         xy = item[1]
         ann = moose.Annotator(item[0]+'/info')
@@ -228,9 +236,7 @@ def autoCoordinates(meshEntry,srcdesConnection):
         xcord.append(xy[0])
         ann.y = xy[1]
         ycord.append(xy[1])
-    # for y in position.values():
-    #     xcord.append(y[0])
-    #     ycord.append(y[1])
+    
     if xcord and ycord:
         xmin = min(xcord)
         xmax = max(xcord)
diff --git a/plugins/kkitQGraphics.py b/plugins/kkitQGraphics.py
index 222a07d4..27ddbe35 100644
--- a/plugins/kkitQGraphics.py
+++ b/plugins/kkitQGraphics.py
@@ -60,7 +60,7 @@ class FuncItem(KineticsDisplayItem):
     fontMetrics = QtGui.QFontMetrics(font)
     def __init__(self, mobj, parent):
         super(FuncItem, self).__init__(mobj, parent)
-        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, False)
+        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
         self.funcImage = QImage('icons/classIcon/Function.png').scaled(15,33)
         self.bg = QtGui.QGraphicsRectItem(self)
         self.bg.setAcceptHoverEvents(True)
@@ -75,8 +75,14 @@ class FuncItem(KineticsDisplayItem):
         
     def setDisplayProperties(self,x,y,textcolor,bgcolor):
         """Set the display properties of this item."""
-        #With Respect to BuffPool (parent) I am placing at 0,30 (which is below the BuffPool)
-        self.setGeometry(0, 30,self.gobj.boundingRect().width(),self.gobj.boundingRect().height())
+        #With Respect to BuffPool (as parent which is in old genesis) then function are placed at 0,30 (which is below the BuffPool)
+        #else if droped from the GUI then placed wrt position
+        #self.setGeometry(0, 30,self.gobj.boundingRect().width(),self.gobj.boundingRect().height())
+        #self.setGeometry(x,y)
+        if self.gobj.mobj.parent.className == "ZombieBufPool" or self.gobj.mobj.parent.className == "BufPool":
+            self.setGeometry(0, 30,self.gobj.boundingRect().width(),self.gobj.boundingRect().height())
+        else:
+            self.setGeometry(x,y,self.gobj.boundingRect().width(),self.gobj.boundingRect().height())
         self.bg.setBrush(QtGui.QBrush(bgcolor))
         self.setFlag(QtGui.QGraphicsItem.ItemIsMovable,False)
     def refresh(self,scale):
@@ -126,7 +132,7 @@ class PoolItem(KineticsDisplayItem):
     """Class for displaying pools. Uses a QGraphicsSimpleTextItem to
     display the name."""    
     #fontMetrics = None
-    font =QtGui.QFont(KineticsDisplayItem.defaultFontName)
+    font = QtGui.QFont(KineticsDisplayItem.defaultFontName)
     font.setPointSize(KineticsDisplayItem.defaultFontSize)
     fontMetrics = QtGui.QFontMetrics(font)
     def __init__(self, mobj, parent):
diff --git a/plugins/kkitUtil.py b/plugins/kkitUtil.py
index 7904407f..137daf80 100644
--- a/plugins/kkitUtil.py
+++ b/plugins/kkitUtil.py
@@ -13,7 +13,7 @@ colormap_file = open(os.path.join(config.settings[config.KEY_COLORMAP_DIR], 'rai
 colorMap = pickle.load(colormap_file)
 colormap_file.close()
 
-ignoreColor= ["mistyrose","antiquewhite","aliceblue","azure","bisque","black","blanchedalmond","blue","cornsilk","darkolivegreen","darkslategray","dimgray","floralwhite","gainsboro","ghostwhite","honeydew","ivory","lavender","lavenderblush","lemonchiffon","lightcyan","lightgoldenrodyellow","lightgray","lightyellow","linen","mediumblue","mintcream","navy","oldlace","papayawhip","saddlebrown","seashell","snow","wheat","white","whitesmoke"]
+ignoreColor= ["mistyrose","antiquewhite","aliceblue","azure","bisque","black","blanchedalmond","blue","cornsilk","darkolivegreen","darkslategray","dimgray","floralwhite","gainsboro","ghostwhite","honeydew","ivory","lavender","lavenderblush","lemonchiffon","lightcyan","lightgoldenrodyellow","lightgray","lightyellow","linen","mediumblue","mintcream","navy","oldlace","papayawhip","saddlebrown","seashell","snow","wheat","white","whitesmoke","aquamarine","lightsalmon","moccasin","limegreen","snow","sienna","beige","dimgrey","lightsage"]
 matplotcolor = {}
 for name,hexno in matplotlib.colors.cnames.iteritems():
     matplotcolor[name]=hexno
@@ -56,6 +56,8 @@ def colorCheck(fc_bgcolor,fcbg):
         if string its taken as colorname further down in validColorcheck checked for valid color, \
         but for tuple and list its taken as r,g,b value.
     """
+    #import re
+    #fc_bgcolor = re.sub('[^a-zA-Z0-9-_*.]', '', fc_bgcolor)
     if isinstance(fc_bgcolor,str):
         if fc_bgcolor.startswith("#"):
             fc_bgcolor = QColor(fc_bgcolor)
@@ -129,7 +131,7 @@ def handleCollisions(compartments, moveCallback, layoutPt,margin = 5.0):
 def calculateChildBoundingRect(compt):
     ''' In this function I am trying to calculate BoundingRect of the compartments
         looking into children and its children which default "ChildrenBoundingRect"
-        function doing but in multi-compartment cross-compartment reaction 
+        function was doing it but in multi-compartment cross-compartment reaction 
         the arrow width is taken into account which doesn't belong to this perticular compartment
     '''
     ypos = []
@@ -137,14 +139,13 @@ def calculateChildBoundingRect(compt):
     for l in compt.childItems():
         ''' All the children including pool,reac,enz,polygon(arrow),table '''
         if not isinstance(l,QtSvg.QGraphicsSvgItem):
-            xpos.append((l.pos().x())+(l.boundingRect().bottomRight().x()))
-            xpos.append(l.pos().x())
-            ypos.append(l.pos().y()+l.boundingRect().bottomRight().y())
-            ypos.append(l.pos().y())
-            
+            if (not isinstance(l,QtGui.QGraphicsPolygonItem)):
+                xpos.append((l.pos().x())+(l.boundingRect().bottomRight().x()))
+                xpos.append(l.pos().x())
+                ypos.append(l.pos().y()+l.boundingRect().bottomRight().y())
+                ypos.append(l.pos().y())
         if (isinstance(l,PoolItem) or isinstance(l,EnzItem)):
             ''' For Enz cplx height and for pool function height needs to be taken'''
-
             for ll in l.childItems():
                 ''' eleminating polygonItem (arrow) [This is happen in cross-compartment model that arrow from one compartment will be child]
                     pool's outboundary RectItem and Enz's outerboundary Ellipse is eleminating since its same 
@@ -154,5 +155,8 @@ def calculateChildBoundingRect(compt):
                      (not isinstance(ll,QtGui.QGraphicsEllipseItem))
                     ):
                     ypos.append(l.pos().y()+ll.pos().y()+ll.boundingRect().bottomRight().y())
-    calculateRectcompt = QtCore.QRectF(min(xpos),min(ypos),(max(xpos)-min(xpos)),(max(ypos)-min(ypos)))
+    if xpos and ypos:
+        calculateRectcompt = QtCore.QRectF(min(xpos),min(ypos),(max(xpos)-min(xpos)),(max(ypos)-min(ypos)))
+    else:
+        calculateRectcompt = compt.rect()
     return calculateRectcompt
\ No newline at end of file
diff --git a/plugins/kkitViewcontrol.py b/plugins/kkitViewcontrol.py
index 91bcef43..c5c74b54 100644
--- a/plugins/kkitViewcontrol.py
+++ b/plugins/kkitViewcontrol.py
@@ -10,8 +10,9 @@ from moose import utils
 
 class GraphicalView(QtGui.QGraphicsView):
 
-    def __init__(self, modelRoot,parent,border,layoutPt,createdItem):
+    def __init__(self, modelRoot,parent,border,layoutPt,createdItem,minmaxratio):
         QtGui.QGraphicsView.__init__(self,parent)
+        self.minmaxratioDict = minmaxratio
         self.state = None
         self.move  = False
         self.resetState()
@@ -136,7 +137,6 @@ class GraphicalView(QtGui.QGraphicsView):
 
 
     def editorMouseMoveEvent(self, event):
-
         if self.state["press"]["mode"] == INVALID:
             self.state["move"]["happened"] = False
             return
@@ -148,7 +148,7 @@ class GraphicalView(QtGui.QGraphicsView):
             for item in self.selectedItems:
                 if isinstance(item, KineticsDisplayItem) and not isinstance(item,ComptItem) and not isinstance(item,CplxItem):
                     item.moveBy(displacement.x(), displacement.y())
-                    self.layoutPt.positionChange(item.mobj.path)            
+                    self.layoutPt.positionChange(item.mobj.path)   
             self.state["press"]["pos"] = event.pos()
             return
 
@@ -161,7 +161,8 @@ class GraphicalView(QtGui.QGraphicsView):
             actionType = str(item.data(0).toString())
             if actionType == "move":
                 QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
-                initial = item.parent().pos()
+                initial = self.mapToScene(self.state["press"]["pos"])
+                #initial = item.parent().pos()
                 final = self.mapToScene(event.pos())
                 displacement = final-initial
                 if isinstance(item.parent(),KineticsDisplayItem):
@@ -169,10 +170,18 @@ class GraphicalView(QtGui.QGraphicsView):
                     if moose.exists(itemPath):
                         iInfo = itemPath+'/info'
                         anno = moose.Annotator(iInfo)
-                        anno.x = self.mapToScene(event.pos()).x()
-                        anno.y = self.mapToScene(event.pos()).y()
+                        modelAnno = moose.Annotator(self.modelRoot+'/info')
+                        if modelAnno.modeltype == "kkit":
+                            x = ((self.mapToScene(event.pos()).x())+(self.minmaxratioDict['xmin']*self.minmaxratioDict['xratio']))/self.minmaxratioDict['xratio']
+                            y = (1.0 - self.mapToScene(event.pos()).y()+(self.minmaxratioDict['ymin']*self.minmaxratioDict['yratio']))/self.minmaxratioDict['yratio']
+                            anno.x = x
+                            anno.y = y
+                        elif(modelAnno.modeltype == "new_kkit" or modelAnno.modeltype == "sbml" or modelAnno.modeltype == "cspace"):
+                            anno.x = self.mapToScene(event.pos()).x()
+                            anno.y = self.mapToScene(event.pos()).y()
                 
-                if not isinstance(item.parent(),FuncItem) and not isinstance(item.parent(),CplxItem):
+                #if not isinstance(item.parent(),FuncItem) and not isinstance(item.parent(),CplxItem):
+                if not isinstance(item.parent(),CplxItem):
                     self.removeConnector()
                     item.parent().moveBy(displacement.x(), displacement.y())
                     if isinstance(item.parent(),PoolItem):
@@ -241,8 +250,9 @@ class GraphicalView(QtGui.QGraphicsView):
     
     def editorMouseReleaseEvent(self, event):
         if self.move:
-            #self.move = False
+            self.move = False
             self.setCursor(Qt.Qt.ArrowCursor)
+
         if self.state["press"]["mode"] == INVALID:
             self.state["release"]["mode"] = INVALID
             self.resetState()
@@ -410,7 +420,6 @@ class GraphicalView(QtGui.QGraphicsView):
                 startingPosition = self.state["press"]["pos"]
                 endingPosition = event.pos()
                 displacement   = endingPosition - startingPosition
-
                 x0 = startingPosition.x() 
                 x1 = endingPosition.x()
                 y0 = startingPosition.y() 
@@ -531,6 +540,7 @@ class GraphicalView(QtGui.QGraphicsView):
             self.xDisp = 0
             self.yDisp = 0
             self.connectionSign = None
+
             if isinstance(item.mobj,PoolBase) or isinstance(item.mobj,ReacBase):
                 if l == "clone":
                     self.connectionSign = QtSvg.QGraphicsSvgItem('icons/clone.svg')
@@ -545,6 +555,7 @@ class GraphicalView(QtGui.QGraphicsView):
                     self.connectionSign.setZValue(1)
                     self.connectionSign.setToolTip("Click and drag to clone the object")
                     self.connectorlist["clone"] = self.connectionSign 
+                    
             if isinstance(item.mobj,PoolBase):
                 if l == "plot":
                     self.connectionSign = QtSvg.QGraphicsSvgItem('icons/plot.svg')
@@ -561,29 +572,45 @@ class GraphicalView(QtGui.QGraphicsView):
                     self.connectorlist["plot"] = self.connectionSign
 
             if l == "move":
-                self.connectionSign = QtSvg.QGraphicsSvgItem('icons/move.svg')
-                self.connectionSign.setData(0, QtCore.QVariant("move"))
-                self.connectionSign.setParent(self.connectionSource)
-                self.connectionSign.setToolTip("Drag to move.")
-                self.connectionSign.setScale(
-                    (1.0 * rectangle.height()) / self.connectionSign.boundingRect().height()
-                                            )
-                position = item.mapToParent(rectangle.topLeft())
-                self.xDisp = 15
-                self.yDisp = 2
-                self.connectionSign.setZValue(1)
-                self.connectorlist["move"] = self.connectionSign
+                if ((item.mobj.parent.className == "ZombieEnz") or (item.mobj.parent.className == "Enz")):
+                    pass
+                else:
+                    self.connectionSign = QtSvg.QGraphicsSvgItem('icons/move.svg')
+                    self.connectionSign.setData(0, QtCore.QVariant("move"))
+                    self.connectionSign.setParent(self.connectionSource)
+                    self.connectionSign.setToolTip("Drag to move.")
+                    if ( item.mobj.className == "ZombieFunction" or item.mobj.className == "Function"):
+                        self.connectionSign.setScale(
+                        (0.75 * rectangle.height()) / self.connectionSign.boundingRect().height()
+                                                )
+                    else:
+                        self.connectionSign.setScale(
+                            (1 * rectangle.height()) / self.connectionSign.boundingRect().height()
+                                                    )
+                    position = item.mapToParent(rectangle.topLeft())
+                    self.xDisp = 15
+                    self.yDisp = 2
+                    self.connectionSign.setZValue(1)
+                    self.connectorlist["move"] = self.connectionSign
             elif l == "delete":
-                self.connectionSign = QtSvg.QGraphicsSvgItem('icons/delete.svg')
-                self.connectionSign.setParent(self.connectionSource)
-                self.connectionSign.setData(0, QtCore.QVariant("delete"))
-                self.connectionSign.setScale(
-                    (1.0 * rectangle.height()) / self.connectionSign.boundingRect().height()
-                                            )
-                position = item.mapToParent(rectangle.topRight())
-                self.connectionSign.setZValue(1)
-                self.connectionSign.setToolTip("Delete the object")
-                self.connectorlist["delete"] = self.connectionSign
+                if ((item.mobj.parent.className == "ZombieEnz") or (item.mobj.parent.className == "Enz")):
+                    pass
+                else:
+                    self.connectionSign = QtSvg.QGraphicsSvgItem('icons/delete.svg')
+                    self.connectionSign.setParent(self.connectionSource)
+                    self.connectionSign.setData(0, QtCore.QVariant("delete"))
+                    if ( item.mobj.className == "ZombieFunction" or item.mobj.className == "Function"):
+                        self.connectionSign.setScale(
+                        (0.75 * rectangle.height()) / self.connectionSign.boundingRect().height()
+                                                )
+                    else:
+                        self.connectionSign.setScale(
+                            (1.0 * rectangle.height()) / self.connectionSign.boundingRect().height()
+                                                )
+                    position = item.mapToParent(rectangle.topRight())
+                    self.connectionSign.setZValue(1)
+                    self.connectionSign.setToolTip("Delete the object")
+                    self.connectorlist["delete"] = self.connectionSign
 
             if self.connectionSign != None:
                 self.connectionSign.setFlag(QtGui.QGraphicsItem.ItemIsSelectable,True)
@@ -1096,16 +1123,34 @@ class GraphicalView(QtGui.QGraphicsView):
             des.expr = expr
             moose.connect( src, 'nOut', des.x[numVariables], 'input' )
             
-        elif ( isinstance(moose.element(src),Function) and (moose.element(des).className=="Pool") ):
+        elif ( isinstance(moose.element(src),Function) and (moose.element(des).className=="Pool") or  
+               isinstance(moose.element(src),ZombieFunction) and (moose.element(des).className=="ZombiePool")
+            ):
                 if ((element(des).parent).className != 'Enz'):
-                    moose.connect(src, 'valueOut', des, 'increment', 'OneToOne')
+                    #moose.connect(src, 'valueOut', des, 'increment', 'OneToOne')
+                    found = False
+                    if len(moose.element(src).neighbors["valueOut"]):
+                        for psl in moose.element(src).neighbors["valueOut"]:
+                            if moose.element(psl) == moose.element(des):
+                                found = True
+                    if found == False:
+                        moose.connect(src, 'valueOut', des, 'setN', 'OneToOne')
+                    else:
+                        srcdesString = '\"'+moose.element(src).name+'\" is already connected to \"'+ moose.element(des).name +'\" \n'
+                        QtGui.QMessageBox.information(None,'Connection Not possible','{srcdesString}'.format(srcdesString = srcdesString),QtGui.QMessageBox.Ok)
+
+                    
                 else:
                     srcdesString = element(src).className+'-- EnzCplx'
                     QtGui.QMessageBox.information(None,'Connection Not possible','\'{srcdesString}\' not allowed to connect'.format(srcdesString = srcdesString),QtGui.QMessageBox.Ok)
                     callsetupItem = False
-        elif ( isinstance(moose.element(src),Function) and (moose.element(des).className=="BufPool") ):
+        elif ( isinstance(moose.element(src),Function) and (moose.element(des).className=="BufPool") or  
+               isinstance(moose.element(src),ZombieFunction) and (moose.element(des).className=="ZombieBufPool")
+            ):
                 moose.connect(src, 'valueOut', des, 'setN', 'OneToOne')
-        elif ( isinstance(moose.element(src),Function) and (isinstance(moose.element(des),ReacBase) ) ):
+        elif ( isinstance(moose.element(src),Function) and (isinstance(moose.element(des),ReacBase) ) or
+               isinstance(moose.element(src),ZombieFunction) and (moose.element(des).className=="ZombieReac")
+            ):
                 moose.connect(src, 'valueOut', des, 'setNumKf', 'OneToOne')
         elif (((isinstance(moose.element(src),ReacBase))or (isinstance(moose.element(src),EnzBase))) and (isinstance(moose.element(des),PoolBase))):
             found = False
diff --git a/plugins/modelBuild.py b/plugins/modelBuild.py
index 8a174efb..4351ab28 100644
--- a/plugins/modelBuild.py
+++ b/plugins/modelBuild.py
@@ -25,13 +25,16 @@ def checkCreate(scene,view,modelpath,mobj,string,ret_string,num,event_pos,layout
     #     modelRoot = modelpath[0:modelpath.find('/',1)]
     # else:
     #     modelRoot = modelpath
+    print "28 ",modelpath
     if moose.exists(modelpath+'/info'):
         mType = moose.Annotator((moose.element(modelpath+'/info'))).modeltype
-    
+    print " 1 event_pos ",event_pos
     itemAtView = view.sceneContainerPt.itemAt(view.mapToScene(event_pos))
+    print "2 ",itemAtView
     pos = view.mapToScene(event_pos)
+    print " 3 ",pos
     modelpath = moose.element(modelpath)
-
+    print " model path @34 ",modelpath
     if num:
         string_num = ret_string+str(num)
     else:
@@ -121,11 +124,17 @@ def checkCreate(scene,view,modelpath,mobj,string,ret_string,num,event_pos,layout
             updateCompartmentSize(compt)
     elif string == "Function":
         posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
-
         funcObj = moose.Function(mobj.path+'/'+string_num)
         funcinfo = moose.Annotator(funcObj.path+'/info')
-        moose.connect( funcObj, 'valueOut', mobj ,'setN' )
-        funcParent = layoutPt.mooseId_GObj[element(mobj.path)]
+        #moose.connect( funcObj, 'valueOut', mobj ,'setN' )
+        poolclass = ["ZombieBufPool","BufPool"]
+        comptclass = ["CubeMesh","cyclMesh"]
+        if mobj.className in poolclass:
+            funcParent = layoutPt.mooseId_GObj[element(mobj.path)]
+        elif mobj.className in comptclass:
+            funcParent = layoutPt.qGraCompt[moose.element(mobj)]
+            posWrtComp = funcParent.mapFromScene(pos).toPoint()
+            #posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
         qGItem = FuncItem(funcObj,funcParent)
         #print " function ", posWrtComp.x(),posWrtComp.y()
         qGItem.setDisplayProperties(posWrtComp.x(),posWrtComp.y(),QtGui.QColor('red'),QtGui.QColor('green'))
@@ -222,7 +231,6 @@ def createObj(scene,view,modelpath,string,pos,layoutPt):
             mobj = itemAtView.parent().mobj
         else:
             mobj = itemAtView.mobj
-    
     if string == "CubeMesh" or string == "CylMesh":
         ret_string,num = findUniqId(moose.element(modelpath),"Compartment",0)
         comptexist = moose.wildcardFind(modelpath+'/##[ISA=ChemCompt]')
@@ -245,6 +253,9 @@ def createObj(scene,view,modelpath,string,pos,layoutPt):
             ret_string,num = findUniqId(mobj,string,num)
 
     elif string == "Function":
+        mobj = findCompartment(mobj)
+        ret_string,num = findUniqId(mobj,string,num)
+        '''
         if itemAt != None:
             if ((mobj).className != "BufPool"):    
                 QtGui.QMessageBox.information(None,'Drop Not possible','\'{newString}\' has to have BufPool as its parent'.format(newString =string),QtGui.QMessageBox.Ok)
@@ -254,7 +265,7 @@ def createObj(scene,view,modelpath,string,pos,layoutPt):
         else:
             QtGui.QMessageBox.information(None,'Drop Not possible','\'{newString}\' has to have BufPool as its parent'.format(newString =string),QtGui.QMessageBox.Ok)
             return
-
+        '''
     elif string == "Enz" or string == "MMenz":
         if itemAt != None:
             if ((mobj).className != "Pool" and (mobj).className != "BufPool"):    
diff --git a/plugins/setsolver.py b/plugins/setsolver.py
index ae6fb418..f55b0673 100644
--- a/plugins/setsolver.py
+++ b/plugins/setsolver.py
@@ -46,9 +46,32 @@ def addSolver(modelRoot,solver):
 				setCompartmentSolver(modelRoot,currentSolver)
 				return True
 	return False
-
+	
+def positionCompt( compt, side, shiftUp ):
+	y0 = compt.y0
+	y1 = compt.y1
+	if ( shiftUp ):
+		compt.y0 =  (y0 + side)
+		compt.y1 =  (y1 + side)
+	else:
+		compt.y0 = (y0 - y1 )
+		compt.y1 = 0
+		
 def setCompartmentSolver(modelRoot,solver):
 	compts = moose.wildcardFind(modelRoot+'/##[ISA=ChemCompt]')
+
+	if ( len(compts) > 3 ):
+		print "Warning: setSolverOnCompt Cannot handle " ,
+		len(compts) , " chemical compartments\n"
+		return;
+	
+	if ( len(compts) == 2 ):
+		positionCompt( compts[0], compts[1].dy, True )
+	
+	if ( len(compts) == 3 ):
+		positionCompt( compts[0], compts[1].dy, True )
+		positionCompt( compts[2], compts[1].dy, False )
+	
 	for compt in compts:
 		if ( solver == 'gsl' ) or (solver == 'Runge Kutta'):
 			ksolve = moose.Ksolve( compt.path+'/ksolve' )
@@ -60,15 +83,15 @@ def setCompartmentSolver(modelRoot,solver):
 			stoich.ksolve = ksolve
 			if moose.exists(compt.path):
 				stoich.path = compt.path+"/##"
+
 	stoichList = moose.wildcardFind(modelRoot+'/##[ISA=Stoich]')
+	
 	if len( stoichList ) == 2:
 		stoichList[1].buildXreacs( stoichList[0] )
+	
 	if len( stoichList ) == 3:
 		stoichList[1].buildXreacs (stoichList [0])
 		stoichList[1].buildXreacs (stoichList [2])
 
 	for i in stoichList:
-		i.filterXreacs()
-	
-	for x in moose.wildcardFind( modelRoot+'/data/graph#/#' ):
-		x.tick = 18
\ No newline at end of file
+		i.filterXreacs()
\ No newline at end of file
-- 
GitLab