Esempio n. 1
0
def test_saveload_trajectory():
    """Test pickling for saving and loading 'Trajectory'"""

    var1 = Variable(Pointset(coordarray=array(range(10), float) * 0.1,
                             indepvararray=array(range(10), float) * 0.5),
                    name='v1')
    var2 = Variable(Pointset(coordarray=array(range(10), float) * 0.25 + 1.0,
                             indepvararray=array(range(10), float) * 0.5),
                    name='v2')
    traj = Trajectory('traj1', [var1, var2])
    saveObjects(traj, 'temp_objects.pkl', True)
    traj_loaded = loadObjects('temp_objects.pkl')[0]
    assert traj_loaded(2.0) == traj(2.0)
    os.remove('temp_objects.pkl')
Esempio n. 2
0
 def setup(self):
     # self.y = Point({'y': 4})
     # self.v = Pointset({'coorddict': {'x0': 0.2, 'x1': -1.2},
     #                    'indepvardict': {'t': 0.01},
     #                    'coordtype': float64,
     #                    'indepvartype': float64})
     # self.u = Pointset(
     #     {'coordarray': array([10., 20., 30., 40.])})
     # self.w_x0 = self.wp['x0']
     # self.w_at_1 = self.wp(1.).toarray()
     self.wp = Pointset(
         {'coordarray': array([	[4.456, 2.34634, 7.3431, 5.443],
                                 [-10.0336, -5.2235, -3.23221, -0.01],
                                 [3e5, 3.1e5, 3.3e5, 2.8e5]], float64),
             'coordnames': ['x0', 'x1', 'x2'],
             'indepvarname': 't',
             'indepvararray': array([0.0, 1.0, 2.0, 3.0], float64)})
     self.wp_ins = Pointset(
         {'coorddict': {'x0': [-2.1, -4., -5., -4.5], 'x1': [50., 51., 52., 54.], 'x2': [0.01, 0.02, 0.4, 0.9]},
          'indepvardict': {'t': [1.5, 5.2, 9., 10.]},
          'coordtype': float64,
          'indepvartype': float64,
          'labels': {2: 'b', 3: {'a': {'bif': 'H'}}}
          })
     self.wp2 = Pointset(
         {'coorddict': {'x0': [-4.5, 2, 3], 'x1': [54, 62, 64], 'x2': [0.9, 0.8, 0.2]},
          'indepvardict': {'t': [10, 11, 12]},
          'coordtype': float64,
          'indepvartype': float64,
          'labels': {0: {'a_different': {'bif': 'H'}}, 2: 'd'}
          })
Esempio n. 3
0
 def test_eight(self):
     # wnp = pointsToPointset(self.pointlist)
     # wnp.labels[0] = ('b', {})
     # wnp.addlabel(4, 'c', {'bif': 'H'})  # preferred syntax
     vw = Pointset({
         'coorddict': {
             'x0': [0.1, 0.15],
             'x1': [100., 102],
             'x2': [0.2, 0.1]
         },
         'indepvardict': {
             't': [4.5, 5.0]
         },
         'coordtype': float64,
         'indepvartype': float64,
         'labels': {
             1: 'c'
         }
     })
     self.wp.append(vw)
     self.wp.append(
         Point(
             {'coorddict': {
                 't': 6.5,
                 'x0': 2,
                 'x1': -300,
                 'x2': -0.9997
             }}))
     self.wp.insert(self.wp_ins)
     self.wp.append(self.wp2, skipMatchingIndepvar=True)
     assert len(self.wp) == 13
Esempio n. 4
0
def make_spike_signal(ts, dur, tmax, loval=0, hival=1, dt=0.1):
    """Helper function: Square-pulse spike signal between two levels, loval
    and hival. Pulses occur at times given by ts array for duration given by
    dur scalar, from time 0 to tmax.

    Returns a single-entry dictionary of Variable objects with key 'Istim'.

    Default loval = 0, hival = 1.

    To improve performance with adaptive time-step solvers, three (two before,
    one after) points are added before and after each pulse, with a minimum
    step time given by dt.
    """
    assert len(ts) > 0, "No spike time events provided!"
    assert isincreasing(ts), "This function expects strictly increasing times"
    assert ts[0] != 0, "This function does not support initial step up at t=0"
    assert dur > dt, "Duration must be larger than dt"
    times = [0]
    vals = [loval]
    # check that ts are separated by at least dur+4*dt
    assert all(np.diff(ts) > dur+4*dt), "Separate events by at least 4*dt"
    assert tmax > ts[-1]+dur, "tmax must be larger than last event end time"
    for t in ts:
        times.extend([t-2.9*dt, t-dt,  t,     t+dur-dt, t+dur, t+dur+dt])
        vals.extend([loval,     loval, hival, hival,    hival, loval])
    if tmax > ts[-1]+dur+dt:
        times.append(tmax)
        vals.append(loval)
    coorddict = {'Istim': vals}
    vpts = Pointset(coorddict=coorddict, indepvararray=times)
    return pointset_to_vars(vpts, discrete=False)
Esempio n. 5
0
 def test_four(self):
     vw = Pointset({
         'coorddict': {
             'x0': [0.1, 0.15],
             'x1': [100., 102],
             'x2': [0.2, 0.1]
         },
         'indepvardict': {
             't': [4.5, 5.0]
         },
         'coordtype': float64,
         'indepvartype': float64,
         'labels': {
             1: 'c'
         }
     })
     self.wp.append(vw)
     self.wp.append(
         Point(
             {'coorddict': {
                 't': 6.5,
                 'x0': 2,
                 'x1': -300,
                 'x2': -0.9997
             }}))
     assert type(self.wp.coordarray) == type(array([1, 2], float64))
Esempio n. 6
0
def test_saveload_point_and_pointset(fname):
    """Test pickling for saving and loading 'Point' and 'Pointset'"""

    x = Point(
        coorddict={
            'x0': [1.123456789],
            'x1': [-0.4],
            'x2': [4000]
        },
        coordtype=float64
    )

    v = Pointset(
        coorddict={
            'x0': 0.2,
            'x1': -1.2
        },
        indepvardict={'t': 0.01},
        coordtype=float,
        indepvartype=float
    )

    saveObjects([x, v], fname, True)
    objs_pts = loadObjects(fname)
    assert objs_pts[0] == x
    assert objs_pts[1] == v
    os.remove(fname)
Esempio n. 7
0
def test_two():
    k = Pointset({
        'coordarray': array(0.1),
        'coordnames': 'k0',
        'indepvarname': 't',
        'indepvararray': array(0.0)
    })
    assert k.dimension == 1
Esempio n. 8
0
def test_saveload_variable():
    """Test pickling for saving and loading 'Variable'"""

    var1 = Variable(Pointset(coordarray=array(range(10), float) * 0.1,
                             indepvararray=array(range(10), float) * 0.5),
                    name='v1')
    saveObjects(var1, 'temp_objects.pkl', True)
    obj_var = loadObjects('temp_objects.pkl')[0]
    assert obj_var(1.5) == var1(1.5)
    os.remove('temp_objects.pkl')
Esempio n. 9
0
def make_noise_signal(dt, t_end, mean, stddev, num_cells, seed=None):
    """Helper function: Gaussian white noise at sample rate = dt for 1 or more cells,
    for a duration of t_end."""
    if seed is not None:
        np.random.seed(seed)
    N = ceil(t_end*1./dt)
    t = np.linspace(0, t_end, N)
    coorddict = {}
    for cellnum in range(num_cells):
        coorddict['noise%i' % (cellnum+1)] = np.random.normal(0, stddev, N)
    vpts = Pointset(coorddict=coorddict, indepvararray=t)
    return pointset_to_vars(vpts, discrete=False)
Esempio n. 10
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)
Esempio n. 11
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)
Esempio n. 12
0
def finitePRC(model, ref_traj_period, evname, pertcoord, pertsize=0.05,
              settle=5, verbose=False, skip=1, do_pert=_default_pert,
              keep_trajs=False, stop_at_t=np.inf, force_T=np.nan):
    """Return a Pointset with dependent variable 'D_phase', measured from 0 to 1,
    where D_phase > 0 is an advance.

    Pass a Generator or Model instance for model.
    Pass a Trajectory or Pointset for the ref_traj_period argument.
    Pass the event name in the model that indicates the periodicity.
    Use skip > 1 to sub-sample the points computed along the trajectory at
     the skip rate.
    Use a do_pert function to do any non-standard perturbation, e.g. if there
     are domain boundary conditions that need special treatment. This function
     takes four or five arguments (model, ic, pertcoord, pertsize, perttime=None)
     and returns the new point ic (not just ic[pertcoord]).
    Use settle=0 to perform no forward integration before the time window in
     which the perturbation will be applied, or a fraction < 1 to ensure an
     integration past the event point (e.g. for non-cycles).
    Use stop_at_t to calculate a partial PRC, from perturbation time 0 to this
     value.
    Use force_T to force the period to be whatever value you like.

    Note: Depending on your model, there may be regions of the PRC that are
    offset by a constant amount to the rest of the PRC. This is a "wart" that
    needs improvement.
    """
    tag_pts = False
    if not isinstance(model, Model.Model):
        # temporarily embed into a model object
        model = embed(model)
        if keep_trajs:
            tag_pts = True
            print "Note: model object will be stored in PRC attribute _model"
    try:
        all_pts = ref_traj_period.sample()
        ref_pts = all_pts[::skip]
        if ref_pts[-1] != all_pts[-1]:
            # ensure last point at t=T is present
            ref_pts.append(all_pts[[-1]])
        if np.isnan(force_T):
            T = ref_traj_period.indepdomain[1]-ref_traj_period.indepdomain[0]
        else:
            T = force_T
    except AttributeError:
        # already passed points
        ref_pts = ref_traj_period[::skip]
        if ref_pts[-1] != ref_traj_period[-1]:
            ref_pts.append(ref_traj_period[[-1]])
        if np.isnan(force_T):
            T = ref_traj_period.indepvararray[-1]-ref_traj_period.indepvararray[0]
        else:
            T = force_T
    ref_ts = ref_pts.indepvararray
    PRCvals = []
    t_off = 0
    if verbose:
        print "Period T =", T
    for i, t0 in enumerate(ref_ts):
        if t0 > stop_at_t:
            break
        ic = do_pert(model, ref_pts[i], pertcoord, pertsize, t0)
        if verbose:
            print i, "of", len(ref_ts), ": t0 = ", t0, "of", T, "  t_end", settle*T+t0
            print "   ", ic
        model.set(ics=ic.copy(), tdata=[0, (settle+1)*T+t0])
        if keep_trajs:
            model.compute(trajname='pert_%i'%i, force=True)
            evts = model.getTrajEventTimes('pert_%i'%i, evname)
        else:
            model.compute(trajname='pert', force=True)
            evts = model.getTrajEventTimes('pert', evname)
        if verbose:
            print "    Last event:", evts[-1]
        if i == 0:
            # make sure to always use the same event number
            evnum = max(0,len(evts)-2)
        val = (T-np.mod(evts[evnum]+t0, T))/T
        ## assume continuity of PRC: hack-fix modulo wart by testing these vals
        # and using the closest to previous value
        if i > 0:
            test_vals = np.array([val-2, val-1, val-0.5, val, val+0.5, val+1, val+2])
            m = np.argmin(abs(PRCvals[-1] - test_vals))
            val = test_vals[m]
            if verbose and abs(PRCvals[-1] - val) > 0.05:
                print "\nCorrected value", i, PRCvals, val
        else:
            # i = 0. Check that value is adjusted to be closest to zero,
            # given that we assume the minimum will be at the beginning of the run.
            test_vals = np.array([val-1, val, val+1])
            m = np.argmin(abs(test_vals))
            val = test_vals[m]
        PRCvals.append(val)
    PRC = Pointset(coordarray=[PRCvals], coordnames=['D_phase'],
                    indepvararray=ref_ts[:len(PRCvals)], indepvarname='t')
    if tag_pts:
        PRC._model = model
    else:
        PRC._model = None
    return PRC
Esempio n. 13
0
def one_period_traj(model, ev_name, ev_t_tol, ev_norm_tol, T_est,
                    verbose=False, initial_settle=6, restore_old_ics=False,
                    use_quadratic_interp=False):
    """
    Utility to extract a single period of a limit cycle of the model using forward
    integration, up to a tolerance given in terms of both the period and the norm of the
    vector of variables in the limit cycle at the period endpoints.

    Requires a non-terminal event in the model that is detected exactly once per period.
    Assumes model initial conditions are already in domain of attraction for limit cycle.

    T_est is an initial estimate of period.
    use_quadratic_interp option (default False) indicates whether to make the returned
    trajectory interpolated more accurately using quadratic functions rather than linear ones.
    This option takes a lot longer to complete!

    The model argument can be an instance of a Generator class or Model class.

    Returned trajectory will have name 'one_period'.
    """
    if not isinstance(model, Model.Model):
        # temporarily embed into a model object
        model = embed(model)
    if use_quadratic_interp:
        old_interp_setting = model.query('algparams')['poly_interp']
        model.set(algparams={'poly_interp': True})
    trajname = '_test_period_'
    old_ics = model.query('ics')
    settle = initial_settle
    tries = 1
    success = False
    while not success and tries < 8:
        model.compute(trajname=trajname, tdata=[0,T_est*(settle+0.2)], force=True)
        evts = model.getTrajEventTimes(trajname, ev_name)
        all_evs = model.getTrajEventTimes(trajname)
        if len(evts) <= 2:
            raise RuntimeError("Not enough events found")
        ref_ic = model(trajname, evts[-1])
        t_check = 10000*np.ones((tries,),float)
        norm_check = 10000*np.ones((tries,),float)
        T = np.zeros((tries,),float)
        look_range = list(range(1, min((tries+1, len(evts)))))
        if verbose:
            print("\n Tries: ", tries, "\n")
        for lookback in look_range:
            try:
                d_evts = [evts[i]-evts[i-lookback] for i in \
                                    range(lookback, len(evts))]
            except KeyError:
                # no more events left to look back at
                break
            else:
                prev_val = model(trajname, evts[-(1+lookback)])
                t_check[lookback-1] = abs(d_evts[-1]-d_evts[-2])
                norm_check[lookback-1] = np.linalg.norm(ref_ic-prev_val)
                T[lookback-1] = d_evts[-1]
        T_est = T[0]
        t_ix = np.argmin(t_check)
        n_ix = np.argmin(norm_check)
        ix1 = min((t_ix, n_ix))
        ix2 = max((t_ix, n_ix))
        if verbose:
            print(t_check, norm_check, T)
            print(ix1, ix2)
        if t_check[ix1] < ev_t_tol and norm_check[ix1] < ev_norm_tol:
            success = True
            T_final = T[ix1]
        elif ix1 != ix2 and t_check[ix2] < ev_t_tol and norm_check[ix2] < ev_norm_tol:
            success = True
            T_final = T[ix2]
        else:
            tries += 1
            settle = tries*2
            model.set(ics = ref_ic)
    if success:
        model.set(ics=ref_ic, tdata=[0, T_final])
        model.compute(trajname='one_period', force=True)
        ref_traj = model['one_period']
        # insert the ON event at beginning of traj
        ref_traj.events[ev_name] = Pointset(indepvararray=[0],
                                        coordarray=np.array([ref_ic.coordarray]).T,
                                        coordnames=ref_ic.coordnames)
        ref_pts = ref_traj.sample()
        # restore old ICs
        if restore_old_ics:
            model.set(ics=old_ics)
        if use_quadratic_interp:
            model.set(algparams={'poly_interp': old_interp_setting})
        return ref_traj, ref_pts, T_final
    else:
        print("norm check was", norm_check)
        print("t check was", t_check)
        raise RuntimeError("Failure to converge after 80 iterations")
Esempio n. 14
0
def finitePRC(model, ref_traj_period, evname, pertcoord, pertsize=0.05,
              settle=5, verbose=False, skip=1, do_pert=_default_pert,
              keep_trajs=False, stop_at_t=np.inf, force_T=np.nan):
    """Return a Pointset with dependent variable 'D_phase', measured from 0 to 1,
    where D_phase > 0 is an advance.

    Pass a Generator or Model instance for model.
    Pass a Trajectory or Pointset for the ref_traj_period argument.
    Pass the event name in the model that indicates the periodicity.
    Use skip > 1 to sub-sample the points computed along the trajectory at
     the skip rate.
    Use a do_pert function to do any non-standard perturbation, e.g. if there
     are domain boundary conditions that need special treatment. This function
     takes four or five arguments (model, ic, pertcoord, pertsize, perttime=None)
     and returns the new point ic (not just ic[pertcoord]).
    Use settle=0 to perform no forward integration before the time window in
     which the perturbation will be applied, or a fraction < 1 to ensure an
     integration past the event point (e.g. for non-cycles).
    Use stop_at_t to calculate a partial PRC, from perturbation time 0 to this
     value.
    Use force_T to force the period to be whatever value you like.

    Note: Depending on your model, there may be regions of the PRC that are
    offset by a constant amount to the rest of the PRC. This is a "wart" that
    needs improvement.
    """
    tag_pts = False
    if not isinstance(model, Model.Model):
        # temporarily embed into a model object
        model = embed(model)
        if keep_trajs:
            tag_pts = True
            print("Note: model object will be stored in PRC attribute _model")
    try:
        all_pts = ref_traj_period.sample()
        ref_pts = all_pts[::skip]
        if ref_pts[-1] != all_pts[-1]:
            # ensure last point at t=T is present
            ref_pts.append(all_pts[[-1]])
        if np.isnan(force_T):
            T = ref_traj_period.indepdomain[1]-ref_traj_period.indepdomain[0]
        else:
            T = force_T
    except AttributeError:
        # already passed points
        ref_pts = ref_traj_period[::skip]
        if ref_pts[-1] != ref_traj_period[-1]:
            ref_pts.append(ref_traj_period[[-1]])
        if np.isnan(force_T):
            T = ref_traj_period.indepvararray[-1]-ref_traj_period.indepvararray[0]
        else:
            T = force_T
    ref_ts = ref_pts.indepvararray
    PRCvals = []
    t_off = 0
    if verbose:
        print("Period T =", T)
    for i, t0 in enumerate(ref_ts):
        if t0 > stop_at_t:
            break
        ic = do_pert(model, ref_pts[i], pertcoord, pertsize, t0)
        if verbose:
            print(i, "of", len(ref_ts), ": t0 = ", t0, "of", T, "  t_end", settle*T+t0)
            print("   ", ic)
        model.set(ics=ic.copy(), tdata=[0, (settle+1)*T+t0])
        if keep_trajs:
            model.compute(trajname='pert_%i'%i, force=True)
            evts = model.getTrajEventTimes('pert_%i'%i, evname)
        else:
            model.compute(trajname='pert', force=True)
            evts = model.getTrajEventTimes('pert', evname)
        if verbose:
            print("    Last event:", evts[-1])
        if i == 0:
            # make sure to always use the same event number
            evnum = max(0,len(evts)-2)
        val = (T-np.mod(evts[evnum]+t0, T))/T
        ## assume continuity of PRC: hack-fix modulo wart by testing these vals
        # and using the closest to previous value
        if i > 0:
            test_vals = np.array([val-2, val-1, val-0.5, val, val+0.5, val+1, val+2])
            m = np.argmin(abs(PRCvals[-1] - test_vals))
            val = test_vals[m]
            if verbose and abs(PRCvals[-1] - val) > 0.05:
                print("\nCorrected value", i, PRCvals, val)
        else:
            # i = 0. Check that value is adjusted to be closest to zero,
            # given that we assume the minimum will be at the beginning of the run.
            test_vals = np.array([val-1, val, val+1])
            m = np.argmin(abs(test_vals))
            val = test_vals[m]
        PRCvals.append(val)
    PRC = Pointset(coordarray=[PRCvals], coordnames=['D_phase'],
                    indepvararray=ref_ts[:len(PRCvals)], indepvarname='t')
    if tag_pts:
        PRC._model = model
    else:
        PRC._model = None
    return PRC
Esempio n. 15
0
 def setup(self):
     # self.y = Point({'y': 4})
     # self.v = Pointset({'coorddict': {'x0': 0.2, 'x1': -1.2},
     #                    'indepvardict': {'t': 0.01},
     #                    'coordtype': float64,
     #                    'indepvartype': float64})
     # self.u = Pointset(
     #     {'coordarray': array([10., 20., 30., 40.])})
     # self.w_x0 = self.wp['x0']
     # self.w_at_1 = self.wp(1.).toarray()
     self.wp = Pointset({
         'coordarray':
         array([[4.456, 2.34634, 7.3431, 5.443],
                [-10.0336, -5.2235, -3.23221, -0.01],
                [3e5, 3.1e5, 3.3e5, 2.8e5]], float64),
         'coordnames': ['x0', 'x1', 'x2'],
         'indepvarname':
         't',
         'indepvararray':
         array([0.0, 1.0, 2.0, 3.0], float64)
     })
     self.wp_ins = Pointset({
         'coorddict': {
             'x0': [-2.1, -4., -5., -4.5],
             'x1': [50., 51., 52., 54.],
             'x2': [0.01, 0.02, 0.4, 0.9]
         },
         'indepvardict': {
             't': [1.5, 5.2, 9., 10.]
         },
         'coordtype': float64,
         'indepvartype': float64,
         'labels': {
             2: 'b',
             3: {
                 'a': {
                     'bif': 'H'
                 }
             }
         }
     })
     self.wp2 = Pointset({
         'coorddict': {
             'x0': [-4.5, 2, 3],
             'x1': [54, 62, 64],
             'x2': [0.9, 0.8, 0.2]
         },
         'indepvardict': {
             't': [10, 11, 12]
         },
         'coordtype': float64,
         'indepvartype': float64,
         'labels': {
             0: {
                 'a_different': {
                     'bif': 'H'
                 }
             },
             2: 'd'
         }
     })
Esempio n. 16
0
class TestPointSet(object):
    def setup(self):
        # self.y = Point({'y': 4})
        # self.v = Pointset({'coorddict': {'x0': 0.2, 'x1': -1.2},
        #                    'indepvardict': {'t': 0.01},
        #                    'coordtype': float64,
        #                    'indepvartype': float64})
        # self.u = Pointset(
        #     {'coordarray': array([10., 20., 30., 40.])})
        # self.w_x0 = self.wp['x0']
        # self.w_at_1 = self.wp(1.).toarray()
        self.wp = Pointset({
            'coordarray':
            array([[4.456, 2.34634, 7.3431, 5.443],
                   [-10.0336, -5.2235, -3.23221, -0.01],
                   [3e5, 3.1e5, 3.3e5, 2.8e5]], float64),
            'coordnames': ['x0', 'x1', 'x2'],
            'indepvarname':
            't',
            'indepvararray':
            array([0.0, 1.0, 2.0, 3.0], float64)
        })
        self.wp_ins = Pointset({
            'coorddict': {
                'x0': [-2.1, -4., -5., -4.5],
                'x1': [50., 51., 52., 54.],
                'x2': [0.01, 0.02, 0.4, 0.9]
            },
            'indepvardict': {
                't': [1.5, 5.2, 9., 10.]
            },
            'coordtype': float64,
            'indepvartype': float64,
            'labels': {
                2: 'b',
                3: {
                    'a': {
                        'bif': 'H'
                    }
                }
            }
        })
        self.wp2 = Pointset({
            'coorddict': {
                'x0': [-4.5, 2, 3],
                'x1': [54, 62, 64],
                'x2': [0.9, 0.8, 0.2]
            },
            'indepvardict': {
                't': [10, 11, 12]
            },
            'coordtype': float64,
            'indepvartype': float64,
            'labels': {
                0: {
                    'a_different': {
                        'bif': 'H'
                    }
                },
                2: 'd'
            }
        })

    def test_three(self):
        assert type(self.wp.coordarray) == type(array([1, 2], float64))

    def test_four(self):
        vw = Pointset({
            'coorddict': {
                'x0': [0.1, 0.15],
                'x1': [100., 102],
                'x2': [0.2, 0.1]
            },
            'indepvardict': {
                't': [4.5, 5.0]
            },
            'coordtype': float64,
            'indepvartype': float64,
            'labels': {
                1: 'c'
            }
        })
        self.wp.append(vw)
        self.wp.append(
            Point(
                {'coorddict': {
                    't': 6.5,
                    'x0': 2,
                    'x1': -300,
                    'x2': -0.9997
                }}))
        assert type(self.wp.coordarray) == type(array([1, 2], float64))

    def test_five(self):
        self.wp.toarray()
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        self.wp.insert(self.wp_ins)
        wp_part = self.wp[3:5]
        assert wp_part.labels[0] == self.wp.labels[3]

    def test_six(self):
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        wpt = self.wp(3.)
        assert wpt.labels == {'a': {'bif': 'SN'}}

    def test_seven(self):
        self.pointlist = []
        self.wp.insert(self.wp_ins)
        for t in self.wp['t']:
            self.pointlist.append(self.wp(t))
        w_reconstructed = pointsToPointset(self.pointlist, 't', self.wp['t'])
        with pytest.raises(ValueError):
            w_double = w_reconstructed.append(w_reconstructed)

    def test_eight(self):
        # wnp = pointsToPointset(self.pointlist)
        # wnp.labels[0] = ('b', {})
        # wnp.addlabel(4, 'c', {'bif': 'H'})  # preferred syntax
        vw = Pointset({
            'coorddict': {
                'x0': [0.1, 0.15],
                'x1': [100., 102],
                'x2': [0.2, 0.1]
            },
            'indepvardict': {
                't': [4.5, 5.0]
            },
            'coordtype': float64,
            'indepvartype': float64,
            'labels': {
                1: 'c'
            }
        })
        self.wp.append(vw)
        self.wp.append(
            Point(
                {'coorddict': {
                    't': 6.5,
                    'x0': 2,
                    'x1': -300,
                    'x2': -0.9997
                }}))
        self.wp.insert(self.wp_ins)
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert len(self.wp) == 13

    def test_nine(self):
        self.wp.insert(self.wp_ins)
        assert self.wp.bylabel('b')['t'][0] == 9.0

    def test_ten(self):
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        self.wp.insert(self.wp_ins)
        assert all(self.wp.bylabel('a')['t'] == array([3., 10.]))

    def test_eleven(self):
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert self.wp.bylabel('d')['t'][0] == 12.0

    def test_twelve(self):
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert all(self.wp.bylabel('a_different')['t'] == array([10.]))

    def test_thirteen(self):
        self.wp.insert(self.wp_ins)
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        z = self.wp[-5:]
        assert z.labels.getIndices() == [1, 2, 4]
Esempio n. 17
0
class TestPointSet(object):
    def setup(self):
        # self.y = Point({'y': 4})
        # self.v = Pointset({'coorddict': {'x0': 0.2, 'x1': -1.2},
        #                    'indepvardict': {'t': 0.01},
        #                    'coordtype': float64,
        #                    'indepvartype': float64})
        # self.u = Pointset(
        #     {'coordarray': array([10., 20., 30., 40.])})
        # self.w_x0 = self.wp['x0']
        # self.w_at_1 = self.wp(1.).toarray()
        self.wp = Pointset(
            {'coordarray': array([	[4.456, 2.34634, 7.3431, 5.443],
                                    [-10.0336, -5.2235, -3.23221, -0.01],
                                    [3e5, 3.1e5, 3.3e5, 2.8e5]], float64),
                'coordnames': ['x0', 'x1', 'x2'],
                'indepvarname': 't',
                'indepvararray': array([0.0, 1.0, 2.0, 3.0], float64)})
        self.wp_ins = Pointset(
            {'coorddict': {'x0': [-2.1, -4., -5., -4.5], 'x1': [50., 51., 52., 54.], 'x2': [0.01, 0.02, 0.4, 0.9]},
             'indepvardict': {'t': [1.5, 5.2, 9., 10.]},
             'coordtype': float64,
             'indepvartype': float64,
             'labels': {2: 'b', 3: {'a': {'bif': 'H'}}}
             })
        self.wp2 = Pointset(
            {'coorddict': {'x0': [-4.5, 2, 3], 'x1': [54, 62, 64], 'x2': [0.9, 0.8, 0.2]},
             'indepvardict': {'t': [10, 11, 12]},
             'coordtype': float64,
             'indepvartype': float64,
             'labels': {0: {'a_different': {'bif': 'H'}}, 2: 'd'}
             })

    def test_three(self):
        assert type(self.wp.coordarray) == type(array([1, 2], float64))

    def test_four(self):
        vw = Pointset(
            {'coorddict': {'x0': [0.1, 0.15], 'x1': [100., 102], 'x2': [0.2, 0.1]},
             'indepvardict': {'t': [4.5, 5.0]},
             'coordtype': float64,
             'indepvartype': float64,
             'labels': {1: 'c'}})
        self.wp.append(vw)
        self.wp.append(Point({'coorddict': {'t': 6.5, 'x0': 2, 'x1': -300, 'x2': -0.9997}}))
        assert type(self.wp.coordarray) == type(array([1, 2], float64))

    def test_five(self):
        self.wp.toarray()
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        self.wp.insert(self.wp_ins)
        wp_part = self.wp[3:5]
        assert wp_part.labels[0] == self.wp.labels[3]

    def test_six(self):
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        wpt = self.wp(3.)
        assert wpt.labels == {'a': {'bif': 'SN'}}

    def test_seven(self):
        self.pointlist = []
        self.wp.insert(self.wp_ins)
        for t in self.wp['t']:
            self.pointlist.append(self.wp(t))
        w_reconstructed = pointsToPointset(
            self.pointlist, 't', self.wp['t'])
        with pytest.raises(ValueError):
            w_double = w_reconstructed.append(w_reconstructed)

    def test_eight(self):
        # wnp = pointsToPointset(self.pointlist)
        # wnp.labels[0] = ('b', {})
        # wnp.addlabel(4, 'c', {'bif': 'H'})  # preferred syntax
        vw = Pointset(
            {'coorddict': {'x0': [0.1, 0.15], 'x1': [100., 102], 'x2': [0.2, 0.1]},
             'indepvardict': {'t': [4.5, 5.0]},
             'coordtype': float64,
             'indepvartype': float64,
             'labels': {1: 'c'}})
        self.wp.append(vw)
        self.wp.append(Point({'coorddict': {'t': 6.5, 'x0': 2, 'x1': -300, 'x2': -0.9997}}))
        self.wp.insert(self.wp_ins)
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert len(self.wp) == 13

    def test_nine(self):
        self.wp.insert(self.wp_ins)
        assert self.wp.bylabel('b')['t'][0] == 9.0

    def test_ten(self):
        self.wp.labels[3] = ('a', {'bif': 'SN'})
        self.wp.insert(self.wp_ins)
        assert all(self.wp.bylabel('a')['t'] == array([3., 10.]))

    def test_eleven(self):
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert self.wp.bylabel('d')['t'][0] == 12.0

    def test_twelve(self):
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        assert all(self.wp.bylabel('a_different')['t'] == array([10.]))

    def test_thirteen(self):
        self.wp.insert(self.wp_ins)
        self.wp.append(self.wp2, skipMatchingIndepvar=True)
        z = self.wp[-5:]
        assert z.labels.getIndices() == [1, 2, 4]