Example #1
0
def copy(src, dest, name="", n=1, toGlobal=False, copyExtMsg=False):
    """Make copies of a moose object.

    Parameters
    ----------
    src : vec, element or str
        source object.
    dest : vec, element or str
        Destination object to copy into.
    name : str
        Name of the new object. If omitted, name of the original will be used.
    n : int
        Number of copies to make (default=1).
    toGlobal : bool
        Relevant for parallel environments only. If false, the copies will
        reside on local node, otherwise all nodes get the copies.
    copyExtMsg : bool
        If true, messages to/from external objects are also copied.

    Returns
    -------
    vec
        newly copied vec
    """
    if isinstance(src, str):
        src = _moose.element(src)
    if isinstance(dest, str):
        dest = _moose.element(dest)
    if not name:
        name = src.name
    return _moose.copy(src.id, dest, name, n, toGlobal, copyExtMsg)
Example #2
0
def connect(src, srcfield, dest, destfield, msgtype="Single"):
    """Create a message between `srcfield` on `src` object to
     `destfield` on `dest` object.

     This function is used mainly, to say, connect two entities, and
     to denote what kind of give-and-take relationship they share.
     It enables the 'destfield' (of the 'destobj') to acquire the
     data, from 'srcfield'(of the 'src').

     Parameters
     ----------
     src : element/vec/string
         the source object (or its path) the one that provides information.
     srcfield : str
         source field on self (type of the information).
     destobj : element
         Destination object to connect to (The one that need to get
         information).
     destfield : str
         field to connect to on `destobj`
     msgtype : str
         type of the message. It ca be one of the following (default Single).
         - Single
         - OneToAll
         - AllToOne
         - OneToOne
         - Reduce
         - Sparse

     Returns
     -------
     msgmanager: melement
         message-manager for the newly created message.

     Note
     -----
     Alternatively, one can also use the following form::

     >>> src.connect(srcfield, dest, destfield, msgtype)


     Examples
     --------
     Connect the output of a pulse generator to the input of a spike generator::

     >>> pulsegen = moose.PulseGen('pulsegen')
     >>> spikegen = moose.SpikeGen('spikegen')
     >>> moose.connect(pulsegen, 'output', spikegen, 'Vm')
     Or,
     >>> pulsegen.connect('output', spikegen, 'Vm')
    """
    src = _moose.element(src)
    dest = _moose.element(dest)
    return src.connect(srcfield, dest, destfield, msgtype)
Example #3
0
def append_finfodocs(classname, docstring, indent):
    """Append list of finfos in class name to docstring"""
    try:
        class_element = _moose.element('/classes/%s' % (classname))
    except ValueError:
        raise NameError('class \'%s\' not defined.' % (classname))
    for ftype, rname in finfotypes:
        docstring.write(toUnicode('\n*%s*\n' % (rname.capitalize())))
        try:
            finfo = _moose.element('%s/%s' % (class_element.path, ftype))
            for field in finfo.vec:
                docstring.write(toUnicode(
                    '%s%s: %s\n' % (indent, field.fieldName, field.type)))
        except ValueError:
            docstring.write(toUnicode('%sNone\n' % (indent)))
Example #4
0
def _appendFinfoDocs(classname, docstring, indent):
    """Append list of finfos in class name to docstring"""
    try:
        classElem = _moose.element('/classes/%s' % (classname))
    except ValueError:
        raise NameError('class \'%s\' not defined.' % (classname))
    for ftype, rname in finfotypes:
        docstring.write(u'\n*%s*\n' % (rname.capitalize()))
        try:
            finfo = _moose.element('%s/%s' % (classElem.path, ftype))
            for field in finfo.vec:
                docstring.write(u'%s%s: %s\n' %
                                (indent, field.fieldName, field.type))
        except ValueError:
            docstring.write(u'%sNone\n' % (indent))
Example #5
0
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
Example #6
0
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' )
Example #7
0
def showmsg(el):
    """Print the incoming and outgoing messages of `el`.

    Parameters
    ----------
    el : melement/vec/str
        Object whose messages are to be displayed.

    Returns
    -------
    None

    """
    obj = _moose.element(el)
    print('INCOMING:')
    for msg in obj.msgIn:
        print(
            msg.e2.path,
            msg.destFieldsOnE2,
            '<---',
            msg.e1.path,
            msg.srcFieldsOnE1)
    print('OUTGOING:')
    for msg in obj.msgOut:
        print(
            msg.e1.path,
            msg.srcFieldsOnE1,
            '--->',
            msg.e2.path,
            msg.destFieldsOnE2)
Example #8
0
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
Example #9
0
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]
Example #10
0
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]
Example #11
0
def _getMooseDoc(tokens, inherited=False):
    """Return MOOSE builtin documentation.
    """
    indent = '  '
    docstring = io.StringIO()
    with closing(docstring):
        if not tokens:
            return ""
        try:
            classElem = _moose.element('/classes/%s' % (tokens[0]))
        except ValueError:
            raise NameError("Name '%s' not defined." % (tokens[0]))

        if len(tokens) > 1:
            docstring.write(getFieldDoc(tokens))
            return docstring.getvalue()

        docstring.write(u'%s\n' % (classElem.docs))
        _appendFinfoDocs(tokens[0], docstring, indent)
        if not inherited:
            return docstring.getvalue()

        mro = eval('_moose.%s' % (tokens[0])).mro()
        for class_ in mro[1:]:
            if class_ == _moose.melement:
                break
            docstring.write(u"\n# Inherited from '%s'\n" % (class_.__name__))
            _appendFinfoDocs(class_.__name__, docstring, indent)
            if class_ == _moose.Neutral:
                break
        return docstring.getvalue()
Example #12
0
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' )
Example #13
0
def enzProxify( enz, enzc, direction, pool, poolc ):
    if enzc == poolc:
        return
    enze = _moose.element( enz )
    # kcat and k2 are indept of volume, just time^-1
    km = enze.numKm
    proxify( enz, enzc, direction, pool, poolc )
    enze.numKm = km
Example #14
0
def enzProxify( enz, enzc, direction, pool, poolc ):
    if enzc == poolc:
        return
    enze = _moose.element( enz )
    # kcat and k2 are indept of volume, just time^-1
    km = enze.numKm
    proxify( enz, enzc, direction, pool, poolc )
    enze.numKm = km
Example #15
0
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)
Example #16
0
def reacProxify( reac, reacc, direction, pool, poolc ):
    if reacc == poolc:
        return
    reac_elm = _moose.element( reac )
    kf = reac_elm.numKf
    kb = reac_elm.numKb
    proxify( reac, reacc, direction, pool, poolc )
    reac_elm.numKf = kf
    reac_elm.numKb = kb
Example #17
0
def findCompt( elm ):
    elm = _moose.element( elm )
    pa = elm.parent
    while pa.path != '/':
        if _moose.Neutral(pa).isA[ 'ChemCompt' ]:
            return pa.path
        pa = pa.parent
    print( 'Error: No compartment parent found for ' + elm.path )
    return '/'
Example #18
0
def findCompt( elm ):
    elm = _moose.element( elm )
    pa = elm.parent
    while pa.path != '/':
        if _moose.Neutral(pa).isA[ 'ChemCompt' ]:
            return pa.path
        pa = pa.parent
    print( 'Error: No compartment parent found for ' + elm.path )
    return '/'
Example #19
0
def reacProxify( reac, reacc, direction, pool, poolc ):
    if reacc == poolc:
        return
    reac_elm = _moose.element( reac )
    kf = reac_elm.numKf
    kb = reac_elm.numKb
    proxify( reac, reacc, direction, pool, poolc )
    reac_elm.numKf = kf
    reac_elm.numKb = kb
Example #20
0
def restoreOldRates( oldRates, msgs ):
    #print oldRates, msgs
    if len( msgs ) > 1 :
        m1 = msgs[1].split( msgSeparator )[0]
        elm = _moose.element( m1.split( ' ' )[0] )
        if elm.isA[ 'ReacBase' ]:
            elm.numKf = oldRates[0]
            elm.numKb = oldRates[1]
        elif elm.isA[ 'enzBase' ]:
            elm.numKm = oldRates[0]
Example #21
0
def getOldRates( msgs ):
    if len( msgs ) > 1 :
        m1 = msgs[1].split( msgSeparator )[0]
        elm = _moose.element( m1.split( ' ' )[0] )
        if elm.isA[ 'ReacBase' ]:
            return [elm.numKf, elm.numKb]
        elif elm.isA[ 'EnzBase' ]:
            return [elm.numKm,]
    print( "Warning: getOldRates did not have any messages" )
    return [0,]
Example #22
0
def restoreOldRates( oldRates, msgs ):
    #print oldRates, msgs
    if len( msgs ) > 1 :
        m1 = msgs[1].split( msgSeparator )[0]
        elm = _moose.element( m1.split( ' ' )[0] )
        if elm.isA[ 'ReacBase' ]:
            elm.numKf = oldRates[0]
            elm.numKb = oldRates[1]
        elif elm.isA[ 'enzBase' ]:
            elm.numKm = oldRates[0]
Example #23
0
def getOldRates( msgs ):
    if len( msgs ) > 1 :
        m1 = msgs[1].split( msgSeparator )[0]
        elm = _moose.element( m1.split( ' ' )[0] )
        if elm.isA[ 'ReacBase' ]:
            return [elm.numKf, elm.numKb]
        elif elm.isA[ 'EnzBase' ]:
            return [elm.numKm,]
    print( "Warning: getOldRates did not have any messages" )
    return [0,]
Example #24
0
def getmoosedoc(tokens, inherited=False):
    """Return MOOSE builtin documentation.

    Parameters
    ----------
    tokens : (className, [fieldName])
        tuple containing one or two strings specifying class name
        and field name (optional) to get documentation for.

    inherited: bool (default: False)
        include inherited fields.

    Returns
    -------
    docstring : str
        Documentation string for class `className`.`fieldName` if both
        are specified, for the class `className` if fieldName is not
        specified. In the latter case, the fields and their data types
        and finfo types are listed.

    Raises
    ------
    NameError
        If class or field does not exist.

    """
    indent = '    '
    docstring = StringIO()
    with closing(docstring):
        if not tokens:
            return ""
        try:
            class_element = _moose.element('/classes/%s' % (tokens[0]))
        except ValueError as e:
            raise NameError('name \'%s\' not defined.' % (tokens[0]))
        if len(tokens) > 1:
            docstring.write(toUnicode(getfielddoc(tokens)))
        else:
            docstring.write(toUnicode('%s\n' % (class_element.docs)))
            append_finfodocs(tokens[0], docstring, indent)
            if inherited:
                mro = eval('_moose.%s' % (tokens[0])).mro()
                for class_ in mro[1:]:
                    if class_ == _moose.melement:
                        break
                    docstring.write(
                        toUnicode('\n\n#Inherited from %s#\n' %
                                  (class_.__name__)))
                    append_finfodocs(class_.__name__, docstring, indent)
                    if class_ == _moose.Neutral:  # Neutral is the toplevel moose class
                        break
        return docstring.getvalue()
Example #25
0
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)
Example #26
0
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)
Example #27
0
def getmoosedoc(tokens, inherited=False):
    """Return MOOSE builtin documentation.

    Parameters
    ----------
    tokens : (className, [fieldName])
        tuple containing one or two strings specifying class name
        and field name (optional) to get documentation for.

    inherited: bool (default: False)
        include inherited fields.

    Returns
    -------
    docstring : str
        Documentation string for class `className`.`fieldName` if both
        are specified, for the class `className` if fieldName is not
        specified. In the latter case, the fields and their data types
        and finfo types are listed.

    Raises
    ------
    NameError
        If class or field does not exist.

    """
    indent = '    '
    docstring = StringIO()
    with closing(docstring):
        if not tokens:
            return ""
        try:
            class_element = _moose.element('/classes/%s' % (tokens[0]))
        except ValueError as e:
            raise NameError('name \'%s\' not defined.' % (tokens[0]))
        if len(tokens) > 1:
            docstring.write(toUnicode(getfielddoc(tokens)))
        else:
            docstring.write(toUnicode('%s\n' % (class_element.docs)))
            append_finfodocs(tokens[0], docstring, indent)
            if inherited:
                mro = eval('_moose.%s' % (tokens[0])).mro()
                for class_ in mro[1:]:
                    if class_ == _moose.melement:
                        break
                    docstring.write(toUnicode(
                        '\n\n#Inherited from %s#\n' % (class_.__name__)))
                    append_finfodocs(class_.__name__, docstring, indent)
                    if class_ == _moose.Neutral:    # Neutral is the toplevel moose class
                        break
        return docstring.getvalue()
Example #28
0
def getFieldDoc(tokens, indent=''):
    """Return the documentation for field specified by `tokens`.

    Parameters
    ----------
    tokens : (className, fieldName) str
        A sequence whose first element is a MOOSE class name and second
        is the field name.

    indent : str
        indentation (default: empty string) prepended to builtin
        documentation string.

    Returns
    -------
    docstring : str
        string of the form
        `{indent}{className}.{fieldName}: {datatype} - {finfoType}\n{Description}\n`

    Raises
    ------
    NameError
        If the specified fieldName is not present in the specified class.
    """
    assert (len(tokens) > 1)
    classname = tokens[0]
    fieldname = tokens[1]
    while True:
        try:
            classelement = _moose.element('/classes/' + classname)
            for finfo in classelement.children:
                for fieldelement in finfo:
                    baseinfo = ''
                    if classname != tokens[0]:
                        baseinfo = ' (inherited from {})'.format(classname)
                    if fieldelement.fieldName == fieldname:
                        # The field elements are
                        # /classes/{ParentClass}[0]/{fieldElementType}[N].
                        finfotype = fieldelement.name
                        return u'{indent}{classname}.{fieldname}: type={type}, finfotype={finfotype}{baseinfo}\n\t{docs}\n'.format(
                            indent=indent,
                            classname=tokens[0],
                            fieldname=fieldname,
                            type=fieldelement.type,
                            finfotype=finfotype,
                            baseinfo=baseinfo,
                            docs=fieldelement.docs)
            classname = classelement.baseClass
        except ValueError:
            raise NameError('`%s` has no field called `%s`' %
                            (tokens[0], tokens[1]))
Example #29
0
def getfielddoc(tokens, indent=''):
    """Return the documentation for field specified by `tokens`.

    Parameters
    ----------
    tokens : (className, fieldName) str
        A sequence whose first element is a MOOSE class name and second
        is the field name.

    indent : str
        indentation (default: empty string) prepended to builtin
        documentation string.

    Returns
    -------
    docstring : str
        string of the form
        `{indent}{className}.{fieldName}: {datatype} - {finfoType}\n{Description}\n`

    Raises
    ------
    NameError
        If the specified fieldName is not present in the specified class.
    """
    assert(len(tokens) > 1)
    classname = tokens[0]
    fieldname = tokens[1]
    while True:
        try:
            classelement = _moose.element('/classes/' + classname)
            for finfo in classelement.children:
                for fieldelement in finfo:
                    baseinfo = ''
                    if classname != tokens[0]:
                        baseinfo = ' (inherited from {})'.format(classname)
                    if fieldelement.fieldName == fieldname:
                        # The field elements are
                        # /classes/{ParentClass}[0]/{fieldElementType}[N].
                        finfotype = fieldelement.name
                        return '{indent}{classname}.{fieldname}: type={type}, finfotype={finfotype}{baseinfo}\n\t{docs}\n'.format(
                            indent=indent, classname=tokens[0],
                            fieldname=fieldname,
                            type=fieldelement.type,
                            finfotype=finfotype,
                            baseinfo=baseinfo,
                            docs=fieldelement.docs)
            classname = classelement.baseClass
        except ValueError:
            raise NameError('`%s` has no field called `%s`'
                            % (tokens[0], tokens[1]))
Example #30
0
def showmsg(el):
    """Print the incoming and outgoing messages of `el`.

    Parameters
    ----------
    el : melement/vec/str
        Object whose messages are to be displayed.

    Returns
    -------
    None

    """
    print(_moose.showmsg(_moose.element(el)))
Example #31
0
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.
    """
    return _moose.element(arg)
Example #32
0
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
Example #33
0
def listmsg(arg):
    """Return a list containing the incoming and outgoing messages of
    `el`.

    Parameters
    ----------
    arg : melement/vec/str
        MOOSE object or path of the object to look into.

    Returns
    -------
    msg : list
        List of Msg objects corresponding to incoming and outgoing connections
        of `arg`.

    """
    obj = _moose.element(arg)
    assert obj
    return _moose.listmsg(obj)
Example #34
0
def showmsg(el):
    """Print the incoming and outgoing messages of `el`.

    Parameters
    ----------
    el : melement/vec/str
        Object whose messages are to be displayed.

    Returns
    -------
    None

    """
    obj = _moose.element(el)
    print('INCOMING:')
    for msg in obj.msgIn:
        print(msg.e2.path, msg.destFieldsOnE2, '<---', msg.e1.path,
              msg.srcFieldsOnE1)
    print('OUTGOING:')
    for msg in obj.msgOut:
        print(msg.e1.path, msg.srcFieldsOnE1, '--->', msg.e2.path,
              msg.destFieldsOnE2)
Example #35
0
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[str]
        path of all children
    """
    el = _moose.getCwe() if el is None else el
    if isinstance(el, str):
        el = _moose.element(el)
    elif isinstance(el, _moose.vec):
        el = el[0]
    return _moose.le(el)
Example #36
0
def listmsg(el):
    """Return a list containing the incoming and outgoing messages of
    `el`.

    Parameters
    ----------
    el : melement/vec/str
        MOOSE object or path of the object to look into.

    Returns
    -------
    msg : list
        List of Msg objects corresponding to incoming and outgoing
        connections of `el`.

    """
    obj = _moose.element(el)
    ret = []
    for msg in obj.inMsg:
        ret.append(msg)
    for msg in obj.outMsg:
        ret.append(msg)
    return ret
Example #37
0
def listmsg(el):
    """Return a list containing the incoming and outgoing messages of
    `el`.

    Parameters
    ----------
    el : melement/vec/str
        MOOSE object or path of the object to look into.

    Returns
    -------
    msg : list
        List of Msg objects corresponding to incoming and outgoing
        connections of `el`.

    """
    obj = _moose.element(el)
    ret = []
    for msg in obj.msgIn:
        ret.append(msg)
    for msg in obj.msgOut:
        ret.append(msg)
    return ret
Example #38
0
def record(obj, field=None, label=None):
    """"""
    global _counter

    # Checking if object is an iterable like list or a tuple, but not a string.
    if hasattr(obj, "__iter__"):
        return [record(o, field, label) for o in obj]

    if isinstance(obj, str):
        obj = _moose.element(obj)

    if field is None:
        field = _defaultField(obj)

    path = _path.format(_counter)
    _counter += 1

    p = _Plot(path, obj, field, label)
    _plots.append(p)

    _moose.connect(p, "requestData", obj, "get_" + field)
    _moose.useClock(_tick, path, "process")

    return p
Example #39
0
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
    }