Exemple #1
0
    def __init__(self,
                 dims1,
                 dims2,
                 F,
                 C,
                 r=1,
                 update=False,
                 corr=False,
                 save=False,
                 numpoints=None):
        """F: R^a --> R^b

        Note: I did not assign b automatically (although I could - it would just be b = p*q) since
        you may not want to use all of the entries of S.  Some bordering methods are not
        minimally augmented systems and thus only require certain entries of S."""
        (n, m) = dims2
        TestFunc.__init__(self, dims1, F, C, save=save, numpoints=numpoints)

        self.update = update
        self.corr = corr

        s = max(n, m)

        if self.data is None:
            self.data = args()
        self.data.n, self.data.m = n, m
        self.data.p = s - m + r
        self.data.q = s - n + r
Exemple #2
0
    def __init__(self, dims, F, C, save=False, numpoints=None):
        (n,m) = dims
        TestFunc.__init__(self, dims, F, C, save=save, numpoints=numpoints)

        if self.data is None:
            self.data = args()
        n = len(self.F.coords)
        self.data.P = zeros((n*(n-1)/2, n*(n-1)/2), float)
Exemple #3
0
def get_pysces_model(filename, target='Vode'):
    path, fname = os.path.split(filename)
    m = pysces.model(fname, dir=path)

    max_t = np.Inf

    parlist = m.__fixed_species__ + m.__parameters__
    pardict = dict([(pname, p['initial']) for pname, p in m.__pDict__.items()])
    varlist = m.__species__  # list ['s0', 's1', 's2']

    icdict = dict([(vname, v['initial']) for vname, v in m.__sDict__.items()
                   if not v['fixed']])
    fixed_species = dict([(pname, p['initial'])
                          for pname, p in m.__sDict__.items() if p['fixed']])
    pardict.update(fixed_species)

    fnspecs = {}
    for R in m.__reactions__:  # list ['R1', 'R2', 'R3', 'R4']
        R_info = m.__nDict__[R]
        #assert R_info['Modifiers'] == []
        assert R_info['Type'] == 'Rever'
        arglist = []
        for reagent in R_info['Reagents']:
            r = reagent.replace('self.', '')
            if r in varlist:
                arglist.append(r)
        arglist.sort()
        fnspecs[R] = (arglist, R_info['RateEq'].replace('self.', ''))

    varspecs = make_varspecs(m, fnspecs)

    for fname, fspec in m.__userfuncs__.items():
        # Don't know how these are implemented yet
        fnspec[fname] = fspec

    dsargs = args(name=fname[:-3],
                  varspecs=varspecs,
                  fnspecs=fnspecs,
                  pars=pardict,
                  ics=icdict,
                  tdata=[0, max_t])

    genclassname = target + '_ODEsystem'
    try:
        genclass = getattr(Generator, genclassname)
    except AttributeError:
        raise TypeError("Invalid ODE solver type")
    return genclass(dsargs)
Exemple #4
0
    def __init__(self, testfuncs, flagfuncs, label='Bifurcation', stop=False):
        self.testfuncs = []
        self.flagfuncs = []
        self.found = []
        self.label = label
        self.stop = stop
        self.data = args()

        if not isinstance(testfuncs, list):
            testfuncs = [testfuncs]
        if not isinstance(flagfuncs, list):
            flagfuncs = [flagfuncs]

        self.testfuncs.extend(testfuncs)
        self.flagfuncs.extend(flagfuncs)
        self.tflen = len(self.testfuncs)
Exemple #5
0
    def __init__(self, testfuncs, flagfuncs, label='Bifurcation', stop=False):
        self.testfuncs = []
        self.flagfuncs = []
        self.found = []
        self.label = label
        self.stop = stop
        self.data = args()

        if not isinstance(testfuncs, list):
            testfuncs = [testfuncs]
        if not isinstance(flagfuncs, list):
            flagfuncs = [flagfuncs]

        self.testfuncs.extend(testfuncs)
        self.flagfuncs.extend(flagfuncs)
        self.tflen = len(self.testfuncs)
Exemple #6
0
def get_pysces_model(filename, target='Vode'):
    path, fname = os.path.split(filename)
    m = pysces.model(fname, dir=path)

    max_t = np.Inf

    parlist = m.__fixed_species__ + m.__parameters__
    pardict = dict([(pname, p['initial']) for pname, p in m.__pDict__.items()])
    varlist = m.__species__ # list ['s0', 's1', 's2']

    icdict = dict([(vname, v['initial']) for vname, v in m.__sDict__.items() if not v['fixed']])
    fixed_species = dict([(pname, p['initial']) for pname, p in m.__sDict__.items() if p['fixed']])
    pardict.update(fixed_species)

    fnspecs = {}
    for R in m.__reactions__: # list ['R1', 'R2', 'R3', 'R4']
        R_info = m.__nDict__[R]
        #assert R_info['Modifiers'] == []
        assert R_info['Type'] == 'Rever'
        arglist = []
        for reagent in R_info['Reagents']:
            r = reagent.replace('self.','')
            if r in varlist:
                arglist.append(r)
        arglist.sort()
        fnspecs[R] = (arglist, R_info['RateEq'].replace('self.',''))

    varspecs = make_varspecs(m, fnspecs)

    for fname, fspec in m.__userfuncs__.items():
        # Don't know how these are implemented yet
        fnspec[fname] = fspec

    dsargs = args(name=fname[:-3],
                  varspecs=varspecs,
                  fnspecs=fnspecs,
                  pars=pardict,
                  ics=icdict,
                  tdata=[0, max_t])

    genclassname = target + '_ODEsystem'
    try:
        genclass = getattr(Generator, genclassname)
    except AttributeError:
        raise TypeError("Invalid ODE solver type")
    return genclass(dsargs)
Exemple #7
0
    def __init__(self, dims1, dims2, F, C, r=1, update=False, corr=False, save=False, numpoints=None):
        """F: R^a --> R^b

        Note: I did not assign b automatically (although I could - it would just be b = p*q) since
        you may not want to use all of the entries of S.  Some bordering methods are not
        minimally augmented systems and thus only require certain entries of S."""
        (n,m) = dims2
        TestFunc.__init__(self, dims1, F, C, save=save, numpoints=numpoints)

        self.update = update
        self.corr = corr

        s = max(n,m)

        if self.data is None:
            self.data = args()
        self.data.n, self.data.m = n, m
        self.data.p = s-m+r
        self.data.q = s-n+r
Exemple #8
0
def defineSystem():
    # Create an object of args class from common module
    DSargs = cmn.args(name='Genetic Toggle Switch with SA')

    # Initialize the DSargs object with parameters
    #DSargs.pars = aux.parameter_set_1()
    #DSargs.pars = aux.parameter_set_2()
    DSargs.pars = aux.parameter_set_3()

    # obtain the differential equations:
    DSargs.varspecs = aux.equations()
    # obtain the auxiliary functions:
    DSargs.fnspecs = aux.functions()

    # Set initial conditions:
    DSargs.ics = {'X': 1, 'Y': 1}

    DSargs.xdomain = {'X': [0, 1.0e+4], 'Y': [0, 1.0e+4]}

    # Set the range of integration:
    DSargs.tdomain = [0, 100]
    return DSargs
Exemple #9
0
def defineSystem(): 
    '''
    Create an object that defines the desired ODE system. 
    ''' 
    # Create an object of args class from common module 
    DSargs = cmn.args(name='Toggle switch of two genes X and Y')

    # Set the parameters:
    DSargs.pars = aux.parameter_set_4()
    # Set the variables:
    DSargs.varspecs = aux.equations() 
    # Set the auxiliary functions:
    DSargs.fnspecs = aux.functions()

    # Set initial conditions:
    DSargs.ics = {'X': 10, 'Y': 10}

    DSargs.xdomain = {'X': [0, 1.0e+4], 'Y':[0, 1.0e+4]}

    # Set the range of integration:
    DSargs.tdomain = [0,100]    
    return DSargs  
Exemple #10
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
Exemple #11
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
Exemple #12
0
    def __init__(self, (a,b), (n,m), F, C, r=1, update=False, corr=False, save=False, numpoints=None):
        """F: R^a --> R^b
        
        Note: I did not assign b automatically (although I could - it would just be b = p*q) since
        you may not want to use all of the entries of S.  Some bordering methods are not 
        minimally augmented systems and thus only require certain entries of S."""
        
        TestFunc.__init__(self, (a,b), F, C, save=save, numpoints=numpoints)

        self.update = update
        self.corr = corr
        
        s = max(n,m)
        
        if self.data is None:
            self.data = args()
        self.data.n, self.data.m = n, m 
        self.data.p = s-m+r
        self.data.q = s-n+r

    def setdata(self, A):
        """Note: p, q <= min(n,m)"""
        self.data.Brand = 2*(random((A.shape[0],self.data.p))-0.5)
        self.data.Crand = 2*(random((A.shape[1],self.data.q))-0.5)
        self.data.D = zeros((self.data.q,self.data.p), Float)

        if self.update:
            U, S, Vh = linalg.svd(A)
            self.data.B = U[:,-1*self.data.p:]
            self.data.C = num_transpose(Vh)[:,-1*self.data.q:]
        else:
Exemple #13
0
    def process(self, X, V, C):
        data = args()
        data.X = todict(C, X)
        data.V = todict(C, V)

        self.found.append(data)
Exemple #14
0
def find_recurrences(data, refix, r, times=None, ignore_small=0,
                     which_norm=2):
    """Find recurrences of a trajectory in a ball of radius r centred at the
    reference point given by refix in data.

    If recurrence times are desired, pass an associated time array corresponding
    to the points in the data.

    If ignore_small > 0, recurrences of fewer than this number of data points
       will be treated as anomalous and ignored completely.

    Returns a structure (class common.args) having attributes:
        partitions -- pairs of entry and exit indices for each recurrence in
                the ball
        ball_ixs -- all consecutive indices into data for each recurrence
        partitions_lengths -- number of indices in each partition
        rec_times -- times to next recurrence in the set from previous
    """
    if times is not None:
        assert len(times) == len(data), "Times must have same length as data"
    # ball_ixs is already sorted
    ball_ixs = find_nearby_ball(data, refix, r, which_norm, include_ref=True)
    result = args(ball_ixs=[], partitions=[], partition_lengths=[],
                  rec_times=None)
    if len(ball_ixs) == 0:
        # No points found in ball
        return result
    # find boundaries of each partition between contiguous indices
    partition_bds = out_of_seq(ball_ixs)
    if len(partition_bds) == 0:
        result.ball_ixs = ball_ixs
        result.partitions = [(ball_ixs[0], ball_ixs[-1])]
        result.partition_lengths = [ball_ixs[-1] - ball_ixs[0] + 1]
        if times is not None:
            # only update this if times present to be consistent with other
            # changes of rec_times from default None
            result.rec_times = [Inf]
        return result
    else:
        plen = ball_ixs[partition_bds[0]-1] - ball_ixs[0] + 1
        if plen > ignore_small:
            partitions = [(ball_ixs[0], ball_ixs[partition_bds[0]-1])]
        else:
            partitions = []
    # find contiguous indices (and corresponding times)
    for i in range(len(partition_bds)-1):
        plo = ball_ixs[partition_bds[i]]
        phi = ball_ixs[partition_bds[i+1]-1]
        plen = phi - plo + 1
        if plen > ignore_small:
            partitions.append((plo, phi))
    plo = ball_ixs[partition_bds[-1]]
    phi = ball_ixs[-1]
    plen = phi - plo + 1
    if plen > ignore_small:
        partitions.append((plo, phi))
    result.ball_ixs = ball_ixs
    result.partitions = partitions
    result.partition_lengths = [p[1]-p[0]+1 for p in partitions]
    if times is None:
        return result
    else:
        result.rec_times = recurrence_times(times, partitions)
        return result
Exemple #15
0
    def newCurve(self, initargs):
        """Create new curve with arguments specified in the dictionary initargs."""
        curvetype = initargs['type'].upper()

        if curvetype not in self.curve_list:
            raise PyDSTool_TypeError(str(curvetype) + ' not an allowable curve type')

        # Check name
        cname = initargs['name']
        if 'force' in initargs:
            if initargs['force'] and cname in self.curves:
                del self.curves[cname]

        if cname in self.curves:
            raise ValueError('Ambiguous name field: ' + cname \
                             + ' already exists (use force=True to override)')

        # Check parameters
        if (curvetype != 'UD-C' and self.model.pars == {}) or \
           (curvetype == 'UD-C' and 'userpars' not in initargs):
            raise ValueError('No parameters defined for this system!')

        # Process initial point
        initargs = initargs.copy()   # ensures no side-effects outside
        if 'initpoint' not in initargs or initargs['initpoint'] is None:
            # Default to initial conditions for model
            if self.model.icdict == {}:
                raise ValueError('No initial point defined for this system!')
            elif 'uservars' in initargs:
                if remain(initargs['uservars'], self.model.icdict.keys()) == []:
                    # uservars just used to select a subset of system's regular state vars
                    initargs['initpoint'] = filteredDict(self.model.icdict,
                                                         initargs['uservars'])
                else:
                    raise ValueError('No initial point defined for this system!')
            else:
                initargs['initpoint'] = self.model.icdict.copy()
            #for p in initargs['freepars']:
            #    initargs['initpoint'][p] = self.model.pars[p]
        else:
            if isinstance(initargs['initpoint'], dict):
                initargs['initpoint'] = initargs['initpoint'].copy()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]
            elif isinstance(initargs['initpoint'], str):
                curvename, pointname = initargs['initpoint'].split(':')
                pointtype = pointname.strip('0123456789')
                if curvename not in self.curves:
                    raise KeyError('No curve of name ' + curvename + ' exists.')
                else:
                    point = self.curves[curvename].getSpecialPoint(pointtype, pointname)
                    if point is None:
                        raise KeyError('No point of name ' + pointname + ' exists.')
                    else:
                        initargs['initpoint'] = point

            # Separate from if-else above since 'str' clause returns type Point
            if isinstance(initargs['initpoint'], Point):
                # Check to see if point contains a cycle.  If it does, assume
                #   we are starting at a cycle and save it in initcycle
                for v in initargs['initpoint'].labels.values():
                    if 'cycle' in v:
                        initargs['initcycle'] = v   # Dictionary w/ cycle, name, and tangent information

                # Save initial point information
                initPoint = {}
                if 'curvename' in locals() and curvename in self.curves:
                    initPoint = self.curves[curvename].parsdict.copy()

                initPoint.update(initargs['initpoint'].copy().todict())
                initargs['initpoint'] = initPoint                
                # initargs['initpoint'] = initargs['initpoint'].copy().todict()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]

        # Process cycle
        if 'initcycle' in initargs:
            if isinstance(initargs['initcycle'], ndarray):
                c0 = {}
                c0['data'] = args(V = {'udotps': None, 'rldot': None})
                c0['cycle'] = Pointset({'coordnames': self.gensys.funcspec.vars,
                                        'coordarray': initargs['initcycle'][1:,:].copy(),
                                        'indepvarname': 't',
                                        'indepvararray': initargs['initcycle'][0,:].copy()
                                        })
                initargs['initcycle'] = c0
            elif isinstance(initargs['initcycle'], Pointset):
                c0 = {}
                c0['data'] = args(V = {'udotps': None, 'rldot': None})
                c0['cycle'] = initargs['initcycle']
                initargs['initcycle'] = c0

        # Load auto module if required
        automod = None
        if curvetype in auto_list:
            if self._autoMod is None:
                self.loadAutoMod()
            automod = self._autoMod

        self.curves[cname] = self.curve_list[curvetype](self.model, self.gensys, automod, self.plot, initargs)
Exemple #16
0
    def process(self, X, V, C):
        data = args()
        data.X = todict(C, X)
        data.V = todict(C, V)

        self.found.append(data)
    def newCurve(self, initargs):
        """Create new curve with arguments specified in the dictionary initargs."""
        curvetype = initargs['type']
        curvetype = curvetype.upper()
        
        if curvetype not in curve_list:
            raise TypeError(curvetype + ' not an allowable curve type')

        # Check name
        if initargs['name'] in self.curves.keys():
            raise AttributeError('Ambiguous name field: ' + initargs['name'] + ' already exists')
        
        # Check parameters
        if self.model.pars == {}:
            raise ValueError('No parameters defined for this system!')

        # Process initial point
        if 'initpoint' not in initargs:
            # Default to initial conditions for model
            if self.model.icdict == {}:
                raise ValueError('No initial point defined for this system!')
            initargs['initpoint'] = self.model.icdict.copy()
            #for p in initargs['freepars']:
            #    initargs['initpoint'][p] = self.model.pars[p]
        else:
            if isinstance(initargs['initpoint'], dict):
                initargs['initpoint'] = initargs['initpoint'].copy()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]
            elif isinstance(initargs['initpoint'], str):
                curvename, pointname = initargs['initpoint'].split(':')
                pointtype = pointname.strip('0123456789')
                if not self.curves.has_key(curvename):
                    raise KeyError('No curve of name ' + curvename + ' exists.')
                else:
                    point = self.curves[curvename].getSpecialPoint(pointtype, pointname)
                    if point is None:
                        raise KeyError('No point of name ' + pointname + ' exists.')
                    else:
                        initargs['initpoint'] = point
                    
            # Separate from if-else above since 'str' clause returns type Point
            if isinstance(initargs['initpoint'], Point):
                # Check to see if point contains a cycle.  If it does, assume
                #   we are starting at a cycle and save it in initcycle
                for v in initargs['initpoint'].labels.itervalues():
                    if v.has_key('cycle'):
                        initargs['initcycle'] = v   # Dictionary w/ cycle, name, and tangent information

                # Save initial point information
                initargs['initpoint'] = initargs['initpoint'].todict()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]
                        
        # Process cycle
        if 'initcycle' in initargs:
            if isinstance(initargs['initcycle'], NumArray):
                c0 = {}
                c0['data'] = args(V = {'udotps': None, 'rldot': None})
                c0['cycle'] = Pointset({'coordnames': self.gensys.funcspec.vars,
                                        'coordarray': num_transpose(initargs['initcycle'][:,1:]).copy(),
                                        'indepvarname': 't',
                                        'indepvararray': num_transpose(initargs['initcycle'][:,0]).copy()
                                       })
                initargs['initcycle'] = c0
            elif isinstance(initargs['initcycle'], Pointset):
                c0 = {}
                c0['data'] = args(V = {'udotps': None, 'rldot': None})
                c0['cycle'] = initargs['initcycle']
                initargs['initcycle'] = c0

        # Load auto module if required
        automod = None
        if curvetype in auto_list:
            if self._autoMod is None:
                self.loadAutoMod()
            automod = self._autoMod
            
        self.curves[initargs['name']] = curve_list[curvetype](self.model, self.gensys, automod, self.plot, initargs)
Exemple #18
0
    def newCurve(self, initargs):
        """Create new curve with arguments specified in the dictionary initargs."""
        curvetype = initargs['type'].upper()

        if curvetype not in self.curve_list:
            raise PyDSTool_TypeError(
                str(curvetype) + ' not an allowable curve type')

        # Check name
        cname = initargs['name']
        if 'force' in initargs:
            if initargs['force'] and cname in self.curves:
                del self.curves[cname]

        if cname in self.curves:
            raise ValueError('Ambiguous name field: ' + cname \
                             + ' already exists (use force=True to override)')

        # Check parameters
        if (curvetype != 'UD-C' and self.model.pars == {}) or \
           (curvetype == 'UD-C' and 'userpars' not in initargs):
            raise ValueError('No parameters defined for this system!')

        # Process initial point
        initargs = initargs.copy()  # ensures no side-effects outside
        if 'initpoint' not in initargs or initargs['initpoint'] is None:
            # Default to initial conditions for model
            if self.model.icdict == {}:
                raise ValueError('No initial point defined for this system!')
            elif 'uservars' in initargs:
                if remain(initargs['uservars'],
                          self.model.icdict.keys()) == []:
                    # uservars just used to select a subset of system's regular state vars
                    initargs['initpoint'] = filteredDict(
                        self.model.icdict, initargs['uservars'])
                else:
                    raise ValueError(
                        'No initial point defined for this system!')
            else:
                initargs['initpoint'] = self.model.icdict.copy()
            #for p in initargs['freepars']:
            #    initargs['initpoint'][p] = self.model.pars[p]
        else:
            if isinstance(initargs['initpoint'], dict):
                initargs['initpoint'] = initargs['initpoint'].copy()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]
            elif isinstance(initargs['initpoint'], str):
                curvename, pointname = initargs['initpoint'].split(':')
                pointtype = pointname.strip('0123456789')
                if curvename not in self.curves:
                    raise KeyError('No curve of name ' + curvename +
                                   ' exists.')
                else:
                    point = self.curves[curvename].getSpecialPoint(
                        pointtype, pointname)
                    if point is None:
                        raise KeyError('No point of name ' + pointname +
                                       ' exists.')
                    else:
                        initargs['initpoint'] = point

            # Separate from if-else above since 'str' clause returns type Point
            if isinstance(initargs['initpoint'], Point):
                # Check to see if point contains a cycle.  If it does, assume
                #   we are starting at a cycle and save it in initcycle
                for v in initargs['initpoint'].labels.values():
                    if 'cycle' in v:
                        initargs[
                            'initcycle'] = v  # Dictionary w/ cycle, name, and tangent information

                # Save initial point information
                initPoint = {}
                if 'curvename' in locals() and curvename in self.curves:
                    initPoint = self.curves[curvename].parsdict.copy()

                initPoint.update(initargs['initpoint'].copy().todict())
                initargs['initpoint'] = initPoint
                # initargs['initpoint'] = initargs['initpoint'].copy().todict()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]

        # Process cycle
        if 'initcycle' in initargs:
            if isinstance(initargs['initcycle'], ndarray):
                c0 = {}
                c0['data'] = args(V={'udotps': None, 'rldot': None})
                c0['cycle'] = Pointset({
                    'coordnames':
                    self.gensys.funcspec.vars,
                    'coordarray':
                    initargs['initcycle'][1:, :].copy(),
                    'indepvarname':
                    't',
                    'indepvararray':
                    initargs['initcycle'][0, :].copy()
                })
                initargs['initcycle'] = c0
            elif isinstance(initargs['initcycle'], Pointset):
                c0 = {}
                c0['data'] = args(V={'udotps': None, 'rldot': None})
                c0['cycle'] = initargs['initcycle']
                initargs['initcycle'] = c0

        # Load auto module if required
        automod = None
        if curvetype in auto_list:
            if self._autoMod is None:
                self.loadAutoMod()
            automod = self._autoMod

        self.curves[cname] = self.curve_list[curvetype](self.model,
                                                        self.gensys, automod,
                                                        self.plot, initargs)
Exemple #19
0
    def newCurve(self, initargs):
        """Create new curve with arguments specified in the dictionary initargs."""
        curvetype = initargs['type']
        curvetype = curvetype.upper()

        if curvetype not in curve_list:
            raise TypeError(curvetype + ' not an allowable curve type')

        # Check name
        if initargs['name'] in self.curves.keys():
            raise AttributeError('Ambiguous name field: ' + initargs['name'] +
                                 ' already exists')

        # Check parameters
        if self.model.pars == {}:
            raise ValueError('No parameters defined for this system!')

        # Process initial point
        if 'initpoint' not in initargs:
            # Default to initial conditions for model
            if self.model.icdict == {}:
                raise ValueError('No initial point defined for this system!')
            initargs['initpoint'] = self.model.icdict.copy()
            #for p in initargs['freepars']:
            #    initargs['initpoint'][p] = self.model.pars[p]
        else:
            if isinstance(initargs['initpoint'], dict):
                initargs['initpoint'] = initargs['initpoint'].copy()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]
            elif isinstance(initargs['initpoint'], str):
                curvename, pointname = initargs['initpoint'].split(':')
                pointtype = pointname.strip('0123456789')
                if not self.curves.has_key(curvename):
                    raise KeyError('No curve of name ' + curvename +
                                   ' exists.')
                else:
                    point = self.curves[curvename].getSpecialPoint(
                        pointtype, pointname)
                    if point is None:
                        raise KeyError('No point of name ' + pointname +
                                       ' exists.')
                    else:
                        initargs['initpoint'] = point

            # Separate from if-else above since 'str' clause returns type Point
            if isinstance(initargs['initpoint'], Point):
                # Check to see if point contains a cycle.  If it does, assume
                #   we are starting at a cycle and save it in initcycle
                for v in initargs['initpoint'].labels.itervalues():
                    if v.has_key('cycle'):
                        initargs[
                            'initcycle'] = v  # Dictionary w/ cycle, name, and tangent information

                # Save initial point information
                initargs['initpoint'] = initargs['initpoint'].todict()
                #for p in initargs['freepars']:
                #    if p not in initargs['initpoint'].keys():
                #        initargs['initpoint'][p] = self.model.pars[p]

        # Process cycle
        if 'initcycle' in initargs:
            if isinstance(initargs['initcycle'], NumArray):
                c0 = {}
                c0['data'] = args(V={'udotps': None, 'rldot': None})
                c0['cycle'] = Pointset({
                    'coordnames':
                    self.gensys.funcspec.vars,
                    'coordarray':
                    num_transpose(initargs['initcycle'][:, 1:]).copy(),
                    'indepvarname':
                    't',
                    'indepvararray':
                    num_transpose(initargs['initcycle'][:, 0]).copy()
                })
                initargs['initcycle'] = c0
            elif isinstance(initargs['initcycle'], Pointset):
                c0 = {}
                c0['data'] = args(V={'udotps': None, 'rldot': None})
                c0['cycle'] = initargs['initcycle']
                initargs['initcycle'] = c0

        # Load auto module if required
        automod = None
        if curvetype in auto_list:
            if self._autoMod is None:
                self.loadAutoMod()
            automod = self._autoMod

        self.curves[initargs['name']] = curve_list[curvetype](self.model,
                                                              self.gensys,
                                                              automod,
                                                              self.plot,
                                                              initargs)