示例#1
0
def test_mapping(pi):
    sm = symbolMapClass({'a': 'A'})
    pi[0] = ['a', ('k', {'bif': 'H', 'otherinfo': 'hello'})]
    pi.update(3, 'c', {'foo': 'bar'})
    pi.update(3, 'h')
    # Mapping 'a' labels to 'A' using mapNames(<symbolMapClass instance>) method of PointInfo
    pi.mapNames(sm)
    assert pi.getLabels() == ['A', 'b', 'c', 'h', 'k']
示例#2
0
def test_mapping(pi):
    sm = symbolMapClass({'a': 'A'})
    pi[0] = ['a', ('k', {'bif': 'H', 'otherinfo': 'hello'})]
    pi.update(3, 'c', {'foo': 'bar'})
    pi.update(3, 'h')
    # Mapping 'a' labels to 'A' using mapNames(<symbolMapClass instance>) method of PointInfo
    pi.mapNames(sm)
    assert pi.getLabels() == ['A', 'b', 'c', 'h', 'k']
def test_mapping(pi):
    sm = symbolMapClass({"a": "A"})
    pi[0] = ["a", ("k", {"bif": "H", "otherinfo": "hello"})]
    pi.update(3, "c", {"foo": "bar"})
    pi.update(3, "h")
    # Mapping 'a' labels to 'A' using mapNames(<symbolMapClass instance>) method of PointInfo
    pi.mapNames(sm)
    assert pi.getLabels() == ["A", "b", "c", "h", "k"]
示例#4
0
 def prepInputs(self, dependencies, nameMap=None):
     if nameMap is None:
         nameMap = symbolMapClass({})
     inputs = {}.fromkeys(self.varsall)
     for (i, o) in dependencies:
         mi = nameMap(i)
         mo = nameMap(o)
         if mi != mo:
             try:
                 inputs[mi].append(mo)
             except AttributeError:
                 inputs[mi] = [mo]
     for k, v in inputs.iteritems():
         if v is None:
             inputs[k] = []
     self.inputs = inputs
 def prepInputs(self, dependencies, nameMap=None):
     if nameMap is None:
         nameMap = symbolMapClass({})
     inputs = {}.fromkeys(self.varsall)
     for (i,o) in dependencies:
         mi = nameMap(i)
         mo = nameMap(o)
         if mi != mo:
             try:
                 inputs[mi].append(mo)
             except AttributeError:
                 inputs[mi] = [mo]
     for k, v in inputs.iteritems():
         if v is None:
             inputs[k] = []
     self.inputs = inputs
示例#6
0
 def add(self, genClass, symbolMapDict, lang, specType='RHSfuncSpec'):
     genName = className(genClass)
     if genName in self.gshDB:
         raise ValueError("Generator %s has already been declared" %
                          genName)
     else:
         infoObj = GenSpecInfoObj()
         infoObj.genClass = genClass
         infoObj.symbolMap = symbolMapClass(symbolMapDict)
         infoObj.lang = lang
         infoObj.specType = specType
         if compareBaseClass(genClass, ctsGen):
             infoObj.domain = Continuous
         else:
             infoObj.domain = Discrete
         self.gshDB[genName] = infoObj
示例#7
0
def setup_module(PyDSTool):
    # Tests with dummy epoch stubs
    namemap = parseUtils.symbolMapClass({'w': 'w', 'x': 'x', 'y': 'y', 'z': 'z'})
    ep1 = common.args(actives=['x','y'],modulatory=['z','w'],sigma=2,relative_ratios=True,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res1 = transition_psi(ep1, Point({'x': 1, 'y': 0.499, 'z': 0.2, 'w': 0.1}), 0.01)
    res2 = transition_psi(ep1, Point({'x': 1, 'y': 0.601, 'z': 0.3, 'w': 0.1}), 0.01)

    ep2 = common.args(actives=['x'],modulatory=['z','w'],sigma=2,relative_ratios=True,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res3 = transition_psi(ep2, Point({'x': 1, 'z': 0.1, 'w': 0.501}), 0.01)

    ep3 = common.args(actives=['x','y'],modulatory=['z','w'],sigma=2,relative_ratios=False,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res5 = transition_psi(ep3, Point({'x': 1, 'y': 0.499, 'z': 0.2, 'w': 0.1}), 0.01)
    res6 = transition_psi(ep3, Point({'x': 1, 'y': 0.601, 'z': 0.499, 'w': 0.1}), 0.01)

    ep4 = common.args(actives=['x'],modulatory=['z','w'],sigma=2,relative_ratios=False,
                            inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res7 = transition_psi(ep4, Point({'x': 1, 'z': 0.1, 'w': 0.501}), 0.01)

    ep5 = common.args(actives=['x','y'],modulatory=[],sigma=2,relative_ratios=False,
                            inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res9 = transition_psi(ep5, Point({'x': 1, 'y': 0.501}), 0.01)

    ep6 = common.args(fast=['x','y'],slow=['w','z'],order1=['v'],gamma=2,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res10 = transition_tau(ep6, Point({'x': 0.3, 'y': 0.2, 'v':1, 'w': 2.005, 'z': 3}), 0.01)

    PyDSTool.TestDSSRT.ep1 = ep1
    PyDSTool.TestDSSRT.ep2 = ep2
    PyDSTool.TestDSSRT.ep3 = ep3
    PyDSTool.TestDSSRT.ep4 = ep4
    PyDSTool.TestDSSRT.ep5 = ep5
    PyDSTool.TestDSSRT.ep6 = ep6

    PyDSTool.TestDSSRT.res1 = res1
    PyDSTool.TestDSSRT.res2 = res2
    PyDSTool.TestDSSRT.res3 = res3
    # no 4
    PyDSTool.TestDSSRT.res5 = res5
    PyDSTool.TestDSSRT.res6 = res6
    PyDSTool.TestDSSRT.res7 = res7
    # no  8
    PyDSTool.TestDSSRT.res9 = res9
    PyDSTool.TestDSSRT.res10 = res10
示例#8
0
def setup_module(PyDSTool):
    # Tests with dummy epoch stubs
    namemap = parseUtils.symbolMapClass({'w': 'w', 'x': 'x', 'y': 'y', 'z': 'z'})
    ep1 = common.args(actives=['x','y'],modulatory=['z','w'],sigma=2,relative_ratios=True,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res1 = transition_psi(ep1, Point({'x': 1, 'y': 0.499, 'z': 0.2, 'w': 0.1}), 0.01)
    res2 = transition_psi(ep1, Point({'x': 1, 'y': 0.601, 'z': 0.3, 'w': 0.1}), 0.01)

    ep2 = common.args(actives=['x'],modulatory=['z','w'],sigma=2,relative_ratios=True,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res3 = transition_psi(ep2, Point({'x': 1, 'z': 0.1, 'w': 0.501}), 0.01)

    ep3 = common.args(actives=['x','y'],modulatory=['z','w'],sigma=2,relative_ratios=False,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res5 = transition_psi(ep3, Point({'x': 1, 'y': 0.499, 'z': 0.2, 'w': 0.1}), 0.01)
    res6 = transition_psi(ep3, Point({'x': 1, 'y': 0.601, 'z': 0.499, 'w': 0.1}), 0.01)

    ep4 = common.args(actives=['x'],modulatory=['z','w'],sigma=2,relative_ratios=False,
                            inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res7 = transition_psi(ep4, Point({'x': 1, 'z': 0.1, 'w': 0.501}), 0.01)

    ep5 = common.args(actives=['x','y'],modulatory=[],sigma=2,relative_ratios=False,
                            inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res9 = transition_psi(ep5, Point({'x': 1, 'y': 0.501}), 0.01)

    ep6 = common.args(fast=['x','y'],slow=['w','z'],order1=['v'],gamma=2,
                    inv_psi_namemap=namemap, inv_tau_namemap=namemap)
    res10 = transition_tau(ep6, Point({'x': 0.3, 'y': 0.2, 'v':1, 'w': 2.005, 'z': 3}), 0.01)

    PyDSTool.TestDSSRT.ep1 = ep1
    PyDSTool.TestDSSRT.ep2 = ep2
    PyDSTool.TestDSSRT.ep3 = ep3
    PyDSTool.TestDSSRT.ep4 = ep4
    PyDSTool.TestDSSRT.ep5 = ep5
    PyDSTool.TestDSSRT.ep6 = ep6

    PyDSTool.TestDSSRT.res1 = res1
    PyDSTool.TestDSSRT.res2 = res2
    PyDSTool.TestDSSRT.res3 = res3
    # no 4
    PyDSTool.TestDSSRT.res5 = res5
    PyDSTool.TestDSSRT.res6 = res6
    PyDSTool.TestDSSRT.res7 = res7
    # no  8
    PyDSTool.TestDSSRT.res9 = res9
    PyDSTool.TestDSSRT.res10 = res10
示例#9
0
# Tests on Pointset labelling class: PointInfo
# Robert Clewley, November 2005

from PyDSTool import *
from PyDSTool.parseUtils import symbolMapClass

sm = symbolMapClass({'a': 'A'})

pstr = """p = PointInfo()
p[3] = ('a', {'bif': 'sn'})
p[5] = ('a', {'bif': 'h'})
p['a'] = (5, {'bif': 'h'})
p[1] = ('b', {'bif': 'c'})"""

print pstr
exec pstr

print "\nprint p -->\n", p, "\n"
print "p['a'] -->", p['a'], "\n"
print "p.sortByIndex() -->", p.sortByIndex(), "\n"

pupstr1 = "p.update(3, 'a', {'blah': 'tangle'})"
print pupstr1, "\n"
exec pupstr1

print "p[3] -->", p[3]
print "(Notice how the result is not a list because only a single"
print "label exists for index 3)\n"

pupstr2 = "p.update(3, 'c', {'foo': 'bar'})"
print pupstr2, "\n"
示例#10
0
def make_measure(fn_name, fn_spec, **defs):
    """Dynamically create a python function for use with calculation
    context.
    """
    all_defs = defs.copy()
    q = dst.QuantSpec('_dummy_', fn_spec, treatMultiRefs=False)
    import PyDSTool.parseUtils as pu
    mapping = pu.symbolMapClass()
    assumed_modules = []
    tokens = q.parser.tokenized
    for sym in q.freeSymbols:
        # Hack, for now: if first (therefore, assumed all)
        # occurrences of symbol are in quotes, then don't convert.
        # Better solution would be to make parser create "x" as a single
        # symbol, at least with a detect quote option
        first_ix = tokens.index(sym)
        if first_ix == 0 or (first_ix > 0 and tokens[first_ix-1] not in ['"', "'"]):
            if pu.isHierarchicalName(sym):
                parts = sym.split('.')
                if parts[0] == 'sim':
                    mapping[sym] = 'con.'+sym
##                elif parts[0] == 'bombardier':
##                    # special case as this factory function is defined in that
##                    # module so that reference will fail at runtime: remove
##                    # 'bombardier' prefix
##                    rest_sym = '.'.join(parts[1:])
##                    mapping[sym] = rest_sym
##                    scope = globals()
##                    # locals override
##                    scope.update(locals())
##                    if parts[1] in scope:
##                        all_defs[parts[1]] = scope[parts[1]]
##                    else:
##                        raise ValueError("Cannot resolve scope of symbol '%s'"%sym)
                else:
                    # assume module reference
                    assumed_modules.append(parts[0])
                    # record here to ensure inclusion in dyn_dummy
                    mapping[sym] = 'self.'+sym
            else:
                mapping[sym] = 'con.workspace.'+sym
        elif first_ix > 0 and tokens[first_ix-1] in ['"', "'"]:
            # put this symbol in the mapping values to ensure not included
            # as an argument to the function
            mapping[sym] = sym
    q.mapNames(mapping)
    import types
    for module_name in assumed_modules:
        global_scope = globals()
        # test if module name in scope
        if module_name in global_scope:
            _mod = global_scope[module_name]
            if isinstance(_mod, types.ModuleType):
                all_defs[module_name] = _mod

    # dyn_dummy contains dummy mappings but declares symbols to leave
    # evaluating until runtime
    dyn_dummy = dict(zip(mapping.values(), ['']*len(mapping)))
    funq = dst.expr2fun(q, ensure_args=['con'], ensure_dynamic=dyn_dummy,
                   for_funcspec=False, fn_name=fn_name,
                   **all_defs)

    # decorate output
    funq.attr_name = fn_name
    return funq
示例#11
0
def makeSloppyModel(modelName,
                    modelDict,
                    targetGen,
                    globalRefs=None,
                    algParams=None,
                    silent=False,
                    containsRHSdefs=False):
    """
    containsRHSdefs: A boolean indicating whether or not ODEs contain symbols
    indicating that they should include the right-hand sides of other ODEs.
    To indicate that a right hand side of an ODE should be included in another ODE,
    the following symbol should be used: _var_RHS .
    For example
      dy/dt = -k*x/m      |  'y': '-k*x/m'
      dx/dt = y + (dy/dt) |  'x': 'y + _y_RHS'
    """
    if targetGen not in allODEgens:
        print('Valid target ODE solvers: ' + ", ".join(allODEgens))
        raise ValueError('Invalid target ODE solver')
    sModelSpec = sloppyModel(modelName)
    if not silent:
        print("Building sloppy model '%s'" % modelName)

    # first pass to collect names
    varnames = []
    for odeName in modelDict['odes'].keys():
        varnames.append(odeName)
    parnames = []
    if 'parameters' in modelDict:
        for parName in modelDict['parameters'].keys():
            parnames.append(parName)

    pdomains = {}
    xdomains = {}
    if 'domains' in modelDict:
        for name, dom in modelDict['domains'].items():
            if name in parnames:
                pdomains[name] = dom
            elif name in varnames:
                xdomains[name] = dom
            else:
                raise ValueError("Name %s unknown in domain specs" % name)

    if 'derived_params' in modelDict:
        paramMapping = {}
        for assgnName, expr in modelDict['derived_params'].items():
            if not silent:
                print('Adding derived parameters: ', assgnName)
            paramMapping[assgnName] = '(%s)' % expr
        derivedParamsMap = symbolMapClass(paramMapping)
    else:
        derivedParamsMap = None

    odeItems = list(modelDict['odes'].items())
    if containsRHSdefs:
        # the sentinal chosen to indicate a RHS is '_var_RHS'
        _ode_map = {}
        for k, v in odeItems:
            _ode_map['_%s_RHS' % k] = '(%s)' % v
        odeRHSMap = symbolMapClass(_ode_map)

    for odeName, expr in odeItems:
        if not silent:
            print('Adding ODE: ', odeName)
        if odeName in xdomains:
            odeRHS = Var(expr,
                         odeName,
                         specType='RHSfuncSpec',
                         domain=xdomains[odeName])
        else:
            odeRHS = Var(expr, odeName, specType='RHSfuncSpec')

        if containsRHSdefs:
            if not silent:
                print(
                    'Making substitutions based on potential right-hand-side usage in the ODE: ',
                    odeName)
            odeRHS.mapNames(odeRHSMap)

        if derivedParamsMap:
            # Incorporate the derived parameter mappings into the odes.
            # Make this substitution twice because the derived parameters
            # may have internal inter-dependencies. It would be better to
            # have a helper function to resolve these inter-dependencies ahead of time.
            if not silent:
                print('Making derived parameter substitutions in the ODE: ',
                      odeName)
            odeRHS.mapNames(derivedParamsMap)
            odeRHS.mapNames(derivedParamsMap)

        sModelSpec.add(odeRHS)

    auxvarnames = []
    if 'assignments' in modelDict:
        for assgnName, expr in modelDict['assignments'].items():
            if not silent:
                print('Adding assignment: ', assgnName)
            sModelSpec.add(Var(expr, assgnName, specType='ExpFuncSpec'))
            auxvarnames.append(assgnName)

    if 'parameters' in modelDict:
        for parName, val in modelDict['parameters'].items():
            if not silent:
                print('Adding parameter: ', parName, "=", val)
            if parName in pdomains:
                sModelSpec.add(Par(str(val), parName,
                                   domain=pdomains[parName]))
            else:
                sModelSpec.add(Par(str(val), parName))

    auxfndict = {}
    for funSig, expr in modelDict['functions'].items():
        assert ')' == funSig[-1]
        assert '(' in funSig
        major = funSig.replace(')', '').replace(' ', '').split('(')
        args = major[1].split(',')
        name = major[0]
        if not silent:
            print('Adding function: ', name, " of arguments:", args)
        sModelSpec.add(Fun(expr, args, name))
        auxfndict[name] = (args, expr)

    if globalRefs is None:
        globalRefs = []
    if not sModelSpec.isComplete(globalRefs):
        print("Model retains free names: " + ", ".join(sModelSpec.freeSymbols))
        print("These must be resolved in the specification before continuing.")
        print("If one of these is time, then include it explicitly as an")
        print("entry in the argument list ('globalRefs' key)")
        raise ValueError('Incomplete model specification')
    targetlang = theGenSpecHelper(targetGen).lang
    # single-generator model so give both same name
    if algParams is None:
        algParams = {}
    genName = modelName
    sModel = ModelConstructor(modelName,
                              generatorspecs={
                                  genName: {
                                      'modelspec': sModelSpec,
                                      'target': targetGen,
                                      'algparams': algParams
                                  }
                              })
    if not silent:
        print("Adding events with default tolerances...")
    argDict = {'precise': True, 'term': True}
    evcount = 0
    if 'events' in modelDict:
        for evspec, mappingDict in modelDict['events'].items():
            if evspec[:2] == 'lt':
                dircode = -1
            elif evspec[:2] == 'gt':
                dircode = 1
            else:
                raise ValueError(
                    "Invalid event specification: use 'lt' and 'gt'")
            assert '(' == evspec[2], 'Invalid event specification'
            evspec_parts = evspec[3:].replace(')', '').replace(' ',
                                                               '').split(',')
            evexpr = evspec_parts[0]
            threshval = evspec_parts[1]
            evname = 'Event' + str(evcount)
            argDict['name'] = evname
            ev = makeZeroCrossEvent(evexpr, dircode, argDict, varnames,
                                    parnames, [], auxfndict, targetlang)
            evcount += 1
            sModel.addEvents(genName, ev)
            evmap = EvMapping(mappingDict,
                              infodict={
                                  'vars': varnames + auxvarnames,
                                  'pars': parnames
                              })
            sModel.mapEvent(genName, evname, genName, evmap)
    if not silent:
        print("Building target model with default settings")
    return sModel.getModel()
示例#12
0
def makeSloppyModel(modelName, modelDict, targetGen, globalRefs=None,
                    algParams=None, silent=False, containsRHSdefs=False):
    """
    containsRHSdefs: A boolean indicating whether or not ODEs contain symbols
    indicating that they should include the right-hand sides of other ODEs.
    To indicate that a right hand side of an ODE should be included in another ODE,
    the following symbol should be used: _var_RHS .
    For example
      dy/dt = -k*x/m      |  'y': '-k*x/m'
      dx/dt = y + (dy/dt) |  'x': 'y + _y_RHS'
    """
    if targetGen not in allODEgens:
        print 'Valid target ODE solvers: ' + ", ".join(allODEgens)
        raise ValueError('Invalid target ODE solver')
    sModelSpec = sloppyModel(modelName)
    if not silent:
        print "Building sloppy model '%s'"%modelName

    # first pass to collect names
    varnames = []
    for odeName in modelDict['odes'].keys():
        varnames.append(odeName)
    parnames = []
    if 'parameters' in modelDict:
        for parName in modelDict['parameters'].keys():
            parnames.append(parName)

    pdomains = {}
    xdomains = {}
    if 'domains' in modelDict:
        for name, dom in modelDict['domains'].iteritems():
            if name in parnames:
                pdomains[name] = dom
            elif name in varnames:
                xdomains[name] = dom
            else:
                raise ValueError("Name %s unknown in domain specs"%name)

    if 'derived_params' in modelDict:
        paramMapping = {}
        for assgnName, expr in modelDict['derived_params'].iteritems():
            if not silent:
                print 'Adding derived parameters: ', assgnName
            paramMapping[assgnName] = '(%s)' % expr
        derivedParamsMap = symbolMapClass(paramMapping)
    else:
        derivedParamsMap = None

    odeItems = modelDict['odes'].items()
    if containsRHSdefs:
        # the sentinal chosen to indicate a RHS is '_var_RHS'
        _ode_map = {}
        for k,v in odeItems:
            _ode_map['_%s_RHS' % k] = '(%s)' % v
        odeRHSMap = symbolMapClass(_ode_map)

    for odeName, expr in odeItems:
        if not silent:
            print 'Adding ODE: ', odeName
        if odeName in xdomains:
            odeRHS = Var(expr, odeName, specType='RHSfuncSpec', domain=xdomains[odeName])
        else:
            odeRHS = Var(expr, odeName, specType='RHSfuncSpec')

        if containsRHSdefs:
            if not silent:
                print 'Making substitutions based on potential right-hand-side usage in the ODE: ', odeName
            odeRHS.mapNames(odeRHSMap)

        if derivedParamsMap:
            # Incorporate the derived parameter mappings into the odes.
            # Make this substitution twice because the derived parameters
            # may have internal inter-dependencies. It would be better to
            # have a helper function to resolve these inter-dependencies ahead of time.
            if not silent:
                print 'Making derived parameter substitutions in the ODE: ', odeName
            odeRHS.mapNames(derivedParamsMap)
            odeRHS.mapNames(derivedParamsMap)

        sModelSpec.add(odeRHS)

    auxvarnames = []
    if 'assignments' in modelDict:
        for assgnName, expr in modelDict['assignments'].iteritems():
            if not silent:
                print 'Adding assignment: ', assgnName
            sModelSpec.add(Var(expr, assgnName, specType='ExpFuncSpec'))
            auxvarnames.append(assgnName)

    if 'parameters' in modelDict:
        for parName, val in modelDict['parameters'].iteritems():
            if not silent:
                print 'Adding parameter: ', parName, "=", val
            if parName in pdomains:
                sModelSpec.add(Par(str(val), parName, domain=pdomains[parName]))
            else:
                sModelSpec.add(Par(str(val), parName))

    auxfndict = {}
    for funSig, expr in modelDict['functions'].iteritems():
        assert ')' == funSig[-1]
        assert '(' in funSig
        major = funSig.replace(')','').replace(' ','').split('(')
        args = major[1].split(',')
        name = major[0]
        if not silent:
            print 'Adding function: ', name, " of arguments:", args
        sModelSpec.add(Fun(expr, args, name))
        auxfndict[name] = (args, expr)

    if globalRefs is None:
        globalRefs = []
    if not sModelSpec.isComplete(globalRefs):
        print "Model retains free names: " + ", ".join(sModelSpec.freeSymbols)
        print "These must be resolved in the specification before continuing."
        print "If one of these is time, then include it explicitly as an"
        print "entry in the argument list ('globalRefs' key)"
        raise ValueError('Incomplete model specification')
    targetlang = theGenSpecHelper(targetGen).lang
    # single-generator model so give both same name
    if algParams is None:
        algParams = {}
    genName = modelName
    sModel = ModelConstructor(modelName,
                            generatorspecs={genName: {'modelspec': sModelSpec,
                                                      'target': targetGen,
                                                      'algparams': algParams}})
    if not silent:
        print "Adding events with default tolerances..."
    argDict={'precise': True, 'term': True}
    evcount = 0
    if 'events' in modelDict:
        for evspec, mappingDict in modelDict['events'].iteritems():
            if evspec[:2] == 'lt':
                dircode = -1
            elif evspec[:2] == 'gt':
                dircode = 1
            else:
                raise ValueError("Invalid event specification: use 'lt' and 'gt'")
            assert '(' == evspec[2], 'Invalid event specification'
            evspec_parts = evspec[3:].replace(')','').replace(' ','').split(',')
            evexpr = evspec_parts[0]
            threshval = evspec_parts[1]
            evname = 'Event'+str(evcount)
            argDict['name'] = evname
            ev = makeZeroCrossEvent(evexpr, dircode, argDict,
                                 varnames, parnames, [], auxfndict, targetlang)
            evcount += 1
            sModel.addEvents(genName, ev)
            evmap = EvMapping(mappingDict,
                              infodict={'vars': varnames+auxvarnames,
                                        'pars': parnames})
            sModel.mapEvent(genName, evname, genName, evmap)
    if not silent:
        print "Building target model with default settings"
    return sModel.getModel()
"""
Tests on Pointset labelling class: PointInfo
 Robert Clewley, November 2005
"""

from PyDSTool import *
from PyDSTool.parseUtils import symbolMapClass

print "Tests on Pointset labelling class: PointInfo"

sm = symbolMapClass({'a': 'A'})

p = PointInfo()
p[3] = ('a', {'bif': 'sn'})
p[5] = ('a', {'bif': 'h'})
p['a'] = (5, {'bif': 'h'})
p[1] = ('b', {'bif': 'c'})

assert p['a'].keys() == [3,5]
sorted = p.sortByIndex()
assert [s[0] for s in sorted] == [1,3,5]
assert p.getIndices() == [1,3,5]

p.update(3, 'c', {'foo': 'bar'})
p.update(3, 'h')

assert p[3].keys() == ['a','h','c']

try:
    p[-1]
except IndexError:
示例#14
0
def make_measure(fn_name, fn_spec, **defs):
    """Dynamically create a python function for use with calculation
    context.
    """
    all_defs = defs.copy()
    q = dst.QuantSpec('_dummy_', fn_spec, treatMultiRefs=False)
    import PyDSTool.parseUtils as pu
    mapping = pu.symbolMapClass()
    assumed_modules = []
    tokens = q.parser.tokenized
    for sym in q.freeSymbols:
        # Hack, for now: if first (therefore, assumed all)
        # occurrences of symbol are in quotes, then don't convert.
        # Better solution would be to make parser create "x" as a single
        # symbol, at least with a detect quote option
        first_ix = tokens.index(sym)
        if first_ix == 0 or (first_ix > 0 and tokens[first_ix-1] not in ['"', "'"]):
            if pu.isHierarchicalName(sym):
                parts = sym.split('.')
                if parts[0] == 'sim':
                    mapping[sym] = 'con.'+sym
##                elif parts[0] == 'bombardier':
##                    # special case as this factory function is defined in that
##                    # module so that reference will fail at runtime: remove
##                    # 'bombardier' prefix
##                    rest_sym = '.'.join(parts[1:])
##                    mapping[sym] = rest_sym
##                    scope = globals()
##                    # locals override
##                    scope.update(locals())
##                    if parts[1] in scope:
##                        all_defs[parts[1]] = scope[parts[1]]
##                    else:
##                        raise ValueError("Cannot resolve scope of symbol '%s'"%sym)
                else:
                    # assume module reference
                    assumed_modules.append(parts[0])
                    # record here to ensure inclusion in dyn_dummy
                    mapping[sym] = 'self.'+sym
            else:
                mapping[sym] = 'con.workspace.'+sym
        elif first_ix > 0 and tokens[first_ix-1] in ['"', "'"]:
            # put this symbol in the mapping values to ensure not included
            # as an argument to the function
            mapping[sym] = sym
    q.mapNames(mapping)
    import types
    for module_name in assumed_modules:
        global_scope = globals()
        # test if module name in scope
        if module_name in global_scope:
            _mod = global_scope[module_name]
            if isinstance(_mod, types.ModuleType):
                all_defs[module_name] = _mod

    # dyn_dummy contains dummy mappings but declares symbols to leave
    # evaluating until runtime
    dyn_dummy = dict(zip(mapping.values(), ['']*len(mapping)))
    funq = dst.expr2fun(q, ensure_args=['con'], ensure_dynamic=dyn_dummy,
                   for_funcspec=False, fn_name=fn_name,
                   **all_defs)

    # decorate output
    funq.attr_name = fn_name
    return funq