def disconnectReactant( reacOrEnz, reactant, duppool ): outMsgs = reacOrEnz.msgOut infoPath = duppool.path + '/info' if _moose.exists( infoPath ): info = _moose.element( infoPath ) else: info = _moose.Annotator( infoPath ) #_moose.le( reactant ) notes = "" #_moose.showmsg( reacOrEnz ) for i in outMsgs: #print "killing msg from {} to {}\nfor {} and {}".format( reacOrEnz.path, reactant.path, i.srcFieldsOnE1[0], i.srcFieldsOnE2[0] ) if i.e1 == reactant: msgStr = identifyMsg( i.e2, i.e2.srcFieldsOnE2[0], i.e1 ) if len( msgStr ) > 0: notes += msgStr _moose.delete( i ) elif i.e2 == reactant: msgStr = identifyMsg( i.e1[0], i.srcFieldsOnE1[0], i.e2[0] ) if len( msgStr ) > 0: notes += msgStr _moose.delete( i ) #print "MSGS to rebuild:", notes info.notes += notes
def syncDataHandler(target): """Synchronize data handlers for target. Parameters ---------- target : melement/vec/str Target element or vec or path string. Raises ------ NotImplementedError The call to the underlying C++ function does not work. Notes ----- This function is defined for completeness, but currently it does not work. """ raise NotImplementedError( 'The implementation is not working for IntFire - goes to invalid objects. \ First fix that issue with SynBase or something in that line.') if isinstance(target, str): if not _moose.exists(target): raise ValueError('%s: element does not exist.' % (target)) target = _moose.vec(target) _moose.syncDataHandler(target)
def disconnectReactant(reacOrEnz, reactant, duppool): outMsgs = reacOrEnz.msgOut infoPath = duppool.path + '/info' if _moose.exists(infoPath): info = moose.element(infoPath) else: info = moose.Annotator(infoPath) #_moose.le( reactant ) notes = "" #_moose.showmsg( reacOrEnz ) for i in outMsgs: #print("killing msg from {} to {}\nfor {} and {}".format( # reacOrEnz.path, reactant.path, i.srcFieldsOnE1, # i.srcFieldsOnE2)) if i.e1 == reactant: msgStr = identifyMsg(i.e2, i.e2.srcFieldsOnE2[0], i.e1) if len(msgStr) > 0: notes += msgStr _moose.delete(i) elif i.e2 == reactant: msgStr = identifyMsg(i.e1[0], i.srcFieldsOnE1[0], i.e2[0]) if len(msgStr) > 0: notes += msgStr _moose.delete(i) # print("MSGS to rebuild:", notes) info.notes += notes
def le(el=None): """List elements under `el` or current element if no argument specified. Parameters ---------- el : str/melement/vec/None The element or the path under which to look. If `None`, children of current working element are displayed. Returns ------- List of path of child elements """ if el is None: el = _moose.getCwe() elif isinstance(el, str): if not _moose.exists(el): raise ValueError('no such element') el = _moose.element(el) elif isinstance(el, _moose.vec): el = el[0] print("Elements under '%s'" % el.path) for ch in el.children: print(" %s" % ch.path) return [child.path for child in el.children]
def syncDataHandler(target): """Synchronize data handlers for target. Parameters ---------- target : melement/vec/str Target element or vec or path string. Raises ------ NotImplementedError The call to the underlying C++ function does not work. Notes ----- This function is defined for completeness, but currently it does not work. """ raise NotImplementedError('The implementation is not working for IntFire - goes to invalid objects. \ First fix that issue with SynBase or something in that line.') if isinstance(target, str): if not _moose.exists(target): raise ValueError('%s: element does not exist.' % (target)) target = _moose.vec(target) _moose.syncDataHandler(target)
def le(el=None): """List elements under `el` or current element if no argument specified. Parameters ---------- el : str/melement/vec/None The element or the path under which to look. If `None`, children of current working element are displayed. Returns ------- List of path of child elements """ if el is None: el = _moose.getCwe() elif isinstance(el, str): if not _moose.exists(el): raise ValueError('no such element') el = _moose.element(el) elif isinstance(el, _moose.vec): el = el[0] print('Elements under', el.path) for ch in el.children: print(ch.path) return [child.path for child in el.children]
def loadGenCsp(target, filename, solver="gsl"): target = target.replace(" ", "") path = '/' + target #Moving the model under /modelname/model and graphs under /model/graphs. #This is passed while loading-time which will be easy for setting the stoich path mpath = '/' + target + '/' + "model" if moose.exists(mpath): moose.delete(mpath) modelpath1 = moose.Neutral('%s' % (target)) modelpath = moose.Neutral('%s/%s' % (modelpath1.path, "model")) model = mutils.loadModel(filename, modelpath.path, solver) if not moose.exists(modelpath1.path + '/data'): graphspath = moose.Neutral('%s/%s' % (modelpath1.path, "data")) dataPath = moose.element(modelpath1.path + '/data') i = 0 nGraphs = moose.wildcardFind(modelpath.path + '/graphs/##[TYPE=Table2]') for graphs in nGraphs: if not moose.exists(dataPath.path + '/graph_' + str(i)): graphspath = moose.Neutral('%s/%s' % (dataPath.path, "graph_" + str(i))) else: graphspath = moose.element(dataPath.path + '/graph_' + str(i)) moose.move(graphs.path, graphspath) if len(nGraphs) > 0: i = i + 1 for moregraphs in moose.wildcardFind(modelpath.path + '/moregraphs/##[TYPE=Table2]'): if not moose.exists(dataPath.path + '/graph_' + str(i)): graphspath = moose.Neutral('%s/%s' % (dataPath.path, "graph_" + str(i))) else: graphspath = moose.element(dataPath.path + '/graph_' + str(i)) moose.move(moregraphs.path, graphspath) if moose.exists(modelpath.path + '/info'): AnnotatorOld = moose.element(modelpath.path + '/info') AnnotatorNew = moose.Annotator(modelpath1.path + '/info') AnnotatorNew.runtime = AnnotatorOld.runtime AnnotatorNew.solver = AnnotatorOld.solver moose.delete(AnnotatorOld) moose.delete(modelpath.path + '/graphs') moose.delete(modelpath.path + '/moregraphs') return (modelpath1, modelpath1.path)
def restoreXreacs(basepath): proxyInfo = _moose.wildcardFind(basepath + "/##/#_xfer_#/info") for i in proxyInfo: msgs = i.notes.split(msgSeparator) oldRates = getOldRates(msgs) #print( "Deleting {}".format( i.parent.path ) ) _moose.delete(i.parent) for j in msgs[1:]: if len(j) > 0: args = j.split(' ') assert (len(args) == 4) #_moose.showfield( args[0] ) #check to see if object exist before moose.connect, cases where object is deleted but #_xref_ annotation info field still holds the reference if (_moose.exists(args[0]) and _moose.exists(args[2])): moose.connect(args[0], args[1], args[2], args[3]) #print( "Reconnecting {}".format( args ) ) #_moose.showfield( args[0] ) restoreOldRates(oldRates, msgs)
def showfields(el, field="*", showtype=False): """Show the fields of the element `el`, their data types and values in human readable format. Convenience function for GENESIS users. Parameters ---------- el : melement/str Element or path of an existing element. field : str Field to be displayed. If '*' (default), all fields are displayed. showtype : bool If True show the data type of each field. False by default. Returns ------- string """ if isinstance(el, str): if not _moose.exists(el): raise ValueError("no such element: %s" % el) el = _moose.element(el) result = [] if field == "*": value_field_dict = _moose.getFieldDict(el.className, "valueFinfo") max_type_len = max(len(dtype) for dtype in value_field_dict.values()) max_field_len = max(len(dtype) for dtype in value_field_dict.keys()) result.append("\n[" + el.path + "]\n") for key, dtype in sorted(value_field_dict.items()): if (dtype == "bad" or key == "this" or key == "dummy" or key == "me" or dtype.startswith("vector") or "ObjId" in dtype): continue value = el.getField(key) if showtype: typestr = dtype.ljust(max_type_len + 4) ## The following hack is for handling both Python 2 and ## 3. Directly putting the print command in the if/else ## clause causes syntax error in both systems. result.append(typestr + " ") result.append( key.ljust(max_field_len + 4) + "=" + str(value) + "\n") else: try: result.append(field + "=" + el.getField(field)) except AttributeError: pass # Genesis silently ignores non existent fields print("".join(result)) return "".join(result)
def showfield(el, field='*', showtype=False): """Show the fields of the element `el`, their data types and values in human readable format. Convenience function for GENESIS users. Parameters ---------- el : melement/str Element or path of an existing element. field : str Field to be displayed. If '*' (default), all fields are displayed. showtype : bool If True show the data type of each field. False by default. Returns ------- string """ if isinstance(el, str): if not _moose.exists(el): raise ValueError('no such element: %s' % el) el = _moose.element(el) result = [] if field == '*': value_field_dict = _moose.getFieldDict(el.className, 'valueFinfo') max_type_len = max(len(dtype) for dtype in value_field_dict.values()) max_field_len = max(len(dtype) for dtype in value_field_dict.keys()) result.append('\n[' + el.path + ']\n') for key, dtype in sorted(value_field_dict.items()): if dtype == 'bad' or key == 'this' or key == 'dummy' \ or key == 'me' or dtype.startswith('vector') \ or 'ObjId' in dtype: continue value = el.getField(key) if showtype: typestr = dtype.ljust(max_type_len + 4) # The following hack is for handling both Python 2 and # 3. Directly putting the print command in the if/else # clause causes syntax error in both systems. result.append(typestr + ' ') result.append( key.ljust(max_field_len + 4) + '=' + str(value) + '\n') else: try: result.append(field + '=' + el.getField(field)) except AttributeError: pass # Genesis silently ignores non existent fields print(''.join(result)) return ''.join(result)
def proxify( reac, reacc, direction, pool, poolc ): reacc_elm = _moose.element( reacc ) reac_elm = _moose.element( reac ) # Preserve the rates which were set up for the x-compt reacn #_moose.showfield( reac ) dupname = pool.name + '_xfer_' + _moose.element(poolc).name #print "#############", pool, dupname, poolc if _moose.exists( reacc + '/' + dupname ): duppool = _moose.element( reacc + '/' + dupname ) else: # This also deals with cases where the duppool is buffered. duppool = _moose.copy(pool, reacc_elm, dupname ) duppool.diffConst = 0 # diffusion only happens in original compt removeEnzFromPool( duppool ) disconnectReactant( reac, pool, duppool ) _moose.connect( reac, direction, duppool, 'reac' )
def proxify(reac, reacc, direction, pool, poolc): reacc_elm = moose.element(reacc) reac_elm = moose.element(reac) # Preserve the rates which were set up for the x-compt reacn #_moose.showfield( reac ) dupname = pool.name + '_xfer_' + moose.element(poolc).name # print("#############", pool, dupname, poolc) if _moose.exists(reacc + '/' + dupname): duppool = moose.element(reacc + '/' + dupname) else: # This also deals with cases where the duppool is buffered. duppool = _moose.copy(pool, reacc_elm, dupname) duppool.diffConst = 0 # diffusion only happens in original compt removeEnzFromPool(duppool) disconnectReactant(reac, pool, duppool) moose.connect(reac, direction, duppool, 'reac')
def showfield(el, field='*', showtype=False): """Show the fields of the element `el`, their data types and values in human readable format. Convenience function for GENESIS users. Parameters ---------- el : melement/str Element or path of an existing element. field : str Field to be displayed. If '*' (default), all fields are displayed. showtype : bool If True show the data type of each field. False by default. Returns ------- None """ if isinstance(el, str): if not _moose.exists(el): raise ValueError('no such element') el = _moose.element(el) if field == '*': value_field_dict = _moose.getFieldDict(el.className, 'valueFinfo') max_type_len = max(len(dtype) for dtype in value_field_dict.values()) max_field_len = max(len(dtype) for dtype in value_field_dict.keys()) print('\n[', el.path, ']') for key, dtype in sorted(value_field_dict.items()): if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith( 'vector') or 'ObjId' in dtype: continue value = el.getField(key) if showtype: typestr = dtype.ljust(max_type_len + 4) # The following hack is for handling both Python 2 and # 3. Directly putting the print command in the if/else # clause causes syntax error in both systems. print(typestr, end=' ') print(key.ljust(max_field_len + 4), '=', value) else: try: print(field, '=', el.getField(field)) except AttributeError: pass # Genesis silently ignores non existent fields
def element(arg): """Convert a path or an object to the appropriate builtin moose class instance Parameters ---------- arg : str/vec/moose object path of the moose element to be converted or another element (possibly available as a superclass instance). Returns ------- melement MOOSE element (object) corresponding to the `arg` converted to write subclass. """ if isinstance(arg, str): assert _moose.exists(arg), "Path '%s' does not exists." % arg return _moose.element(arg)
def exists(path): """Returns True if an object with given path already exists.""" return _moose.exists(path)
def loadFile(filename, target, solver="gsl", merge=True): """Try to load a model from specified `filename` under the element `target`. if `merge` is True, the contents are just loaded at target. If false, everything is deleted from the parent of target unless the parent is root. Returns ------- a dict containing at least these three entries: modeltype: type of the loaded model. subtype: subtype of the loaded model, None if no specific subtype modelroot: root element of the model, None if could not be located - as is the case with Python scripts """ loaderror = "" num = 1 libsfound = True model = '/' newTarget = target while moose.exists(newTarget): newTarget = target + "-" + str(num) num = num + 1 target = newTarget istext = True with open(filename, 'rb') as infile: istext = mtypes.istextfile(infile) if not istext: print('Cannot handle any binary formats yet') return None # parent, child = posixpath.split(target) # p = moose.Neutral(parent) # if not merge and p.path != '/': # for ch in p.children: # moose.delete(ch) try: modeltype = mtypes.getType(filename) subtype = mtypes.getSubtype(filename, modeltype) except KeyError: raise FileLoadError('Do not know how to handle this filetype: %s' % (filename)) pwe = moose.getCwe() #self.statusBar.showMessage('Loading model, please wait') # app = QtGui.qApp # app.setOverrideCursor(QtGui.QCursor(Qt.Qt.BusyCursor)) #shows a hourglass - or a busy/working arrow if modeltype == 'genesis': if subtype == 'kkit' or subtype == 'prototype': model, modelpath = loadGenCsp(target, filename, solver) xcord, ycord = [], [] if moose.exists(moose.element(modelpath).path): process = True compt = len(moose.wildcardFind(modelpath + '/##[ISA=CubeMesh]')) if not compt: loaderror = "Model has no compartment, atleast one compartment should exist to display the widget" process = False else: p = len(moose.wildcardFind(modelpath + '/##[ISA=PoolBase]')) if p < 2: loaderror = "Model has no pool, atleast two pool should exist to display the widget" process = False if process: if moose.exists(moose.element(modelpath).path): mObj = moose.wildcardFind( moose.element(modelpath).path + '/##[ISA=PoolBase]' + ',' + moose.element(modelpath).path + '/##[ISA=ReacBase]' + ',' + moose.element(modelpath).path + '/##[ISA=EnzBase]' + ',' + moose.element(modelpath).path + '/##[ISA=StimulusTable]') for p in mObj: if not isinstance(moose.element(p.parent), moose.CplxEnzBase): xcord.append(moose.element(p.path + '/info').x) ycord.append(moose.element(p.path + '/info').y) recalculatecoordinatesforKkit(mObj, xcord, ycord) for ememb in moose.wildcardFind( moose.element(modelpath).path + '/##[ISA=EnzBase]'): objInfo = ememb.path + '/info' #Enzyme's textcolor (from kkit) will be bgcolor (in moose) if moose.exists(objInfo): bgcolor = moose.element(objInfo).color moose.element(objInfo).color = moose.element( objInfo).textColor moose.element(objInfo).textColor = bgcolor moose.Annotator(moose.element(modelpath).path + '/info').modeltype = "kkit" else: print(" path doesn't exists") #moose.le(modelpath) else: print('Only kkit and prototype files can be loaded.') elif modeltype == 'cspace': model, modelpath = loadGenCsp(target, filename) if moose.exists(modelpath): moose.Annotator( (moose.element(modelpath).path + '/info')).modeltype = "cspace" addSolver(modelpath, 'gsl') elif modeltype == 'xml': if subtype == 'neuroml': popdict, projdict = neuroml.loadNeuroML_L123(filename) # Circus to get the container of populations from loaded neuroml for popinfo in list(popdict.values()): for cell in list(popinfo[1].values()): solver = moose.HSolve(cell.path + "/hsolve") solver.target = cell.path # model = cell.parent # break # break # Moving model to a new location under the model name # model name is the filename without extension model = moose.Neutral("/" + splitext(basename(filename))[0]) element = moose.Neutral(model.path + "/model") if (moose.exists("/cells")): moose.move("/cells", element.path) if (moose.exists("/elec")): moose.move("/elec", model.path) if (moose.exists("/library")): moose.move("/library", model.path) # moose.move("cells/", cell.path) elif subtype == 'sbml': foundLibSBML_ = False try: import libsbml foundLibSBML_ = True except ImportError: pass if foundLibSBML_: if target != '/': if moose.exists(target): moose.delete(target) model, loaderror = 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 # TODO: check with Aditya how to specify the target for # neuroml reader # app.restoreOverrideCursor() return { 'modeltype': modeltype, 'subtype': subtype, 'model': model, 'foundlib': libsfound, 'loaderror': loaderror }