Generates a sub-trajectory
776078
@Override
	public Trajectory subList(int fromIndex, int toIndex) {
		Trajectory t = new Trajectory(dimension);
		
		for(int i = fromIndex; i < toIndex; i++){
			t.add(this.get(i));
		}
		return t;
	}
82050
def _GenerateStopTimesTuples(self):
    """"""
    stoptimes = self.GetStopTimes()
    for i, st in enumerate(stoptimes):
      yield st.GetFieldValuesTuple(self.trip_id)
449132
def subdivide(self, N=1, method=0):
        
        triangles = vtk.vtkTriangleFilter()
        triangles.SetInputData(self.polydata())
        triangles.Update()
        originalMesh = triangles.GetOutput()
        if method == 0:
            sdf = vtk.vtkLoopSubdivisionFilter()
        elif method == 1:
            sdf = vtk.vtkLinearSubdivisionFilter()
        elif method == 2:
            sdf = vtk.vtkAdaptiveSubdivisionFilter()
        elif method == 3:
            sdf = vtk.vtkButterflySubdivisionFilter()
        else:
            colors.printc("~times Error in subdivide: unknown method.", c="r")
            exit()
        if method != 2:
            sdf.SetNumberOfSubdivisions(N)
        sdf.SetInputData(originalMesh)
        sdf.Update()
        return self.updateMesh(sdf.GetOutput())
292576
def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor:
        """"""
        return x + self.dropout(sublayer(self.norm(x)))
647154
def imitate_path(self, y_des):
        

        # set initial state and goal
        if y_des.ndim == 1: 
            y_des = y_des.reshape(1,len(y_des))
        self.y0 = y_des[:,0].copy()
        self.y_des = y_des.copy()
        self.goal = self.gen_goal(y_des)
        
        self.check_offset()

        if not (self.timesteps == y_des.shape[1]):
            # generate function to interpolate the desired trajectory
            import scipy.interpolate
            path = np.zeros((self.dmps, self.timesteps))
            x = np.linspace(0, self.cs.run_time, y_des.shape[1])
            for d in range(self.dmps):
                path_gen = scipy.interpolate.interp1d(x, y_des[d])
                for t in range(self.timesteps):  
                    path[d, t] = path_gen(t * self.dt)
            y_des = path

        # calculate velocity of y_des
        dy_des = np.diff(y_des) / self.dt
        # add zero to the beginning of every row
        dy_des = np.hstack((np.zeros((self.dmps, 1)), dy_des))

        # calculate acceleration of y_des
        ddy_des = np.diff(dy_des) / self.dt
        # add zero to the beginning of every row
        ddy_des = np.hstack((np.zeros((self.dmps, 1)), ddy_des))

        f_target = np.zeros((y_des.shape[1], self.dmps))
        # find the force required to move along this trajectory
        for d in range(self.dmps):
            f_target[:,d] = ddy_des[d] - self.ay[d] * \
                            (self.by[d] * (self.goal[d] - y_des[d]) - \
                            dy_des[d])

        # efficiently generate weights to realize f_target
        self.gen_weights(f_target)

        '''# plot the basis function activations
        import matplotlib.pyplot as plt
        plt.figure()
        plt.subplot(211)
        plt.plot(psi_track)
        plt.title('psi_track')

        # plot the desired forcing function vs approx
        plt.subplot(212)
        plt.plot(f_target[:,0])
        plt.plot(np.sum(psi_track * self.w[0], axis=1))
        plt.legend(['f_target', 'w*psi'])
        plt.tight_layout()
        plt.show()'''

        self.reset_state()
        return y_des
1198237
def _integrate_fixed_trajectory(self, h, T, step, relax):
        """"""
        # initialize the solution using initial condition
        solution = np.hstack((self.t, self.y))

        while self.successful():

            self.integrate(self.t + h, step, relax)
            current_step = np.hstack((self.t, self.y))
            solution = np.vstack((solution, current_step))

            if (h > 0) and (self.t >= T):
                break
            elif (h < 0) and (self.t <= T):
                break
            else:
                continue

        return solution
669556
def xstep(self):
        
        """

        self.X, self.ss = sp.prox_nuclear(self.S - self.Y - self.U,
                                          1/self.rho)
950865
def _get_linear_trajectory(x0, velocity, t):
  
  x0 = tf.convert_to_tensor(x0)
  velocity = tf.convert_to_tensor(velocity)
  t = tf.convert_to_tensor(t)
  if x0.shape.ndims != 1:
    raise ValueError("x0 must be a rank 1 tensor")
  if velocity.shape.ndims != 1:
    raise ValueError("velocity must be a rank 1 tensor")
  if t.shape.ndims != 1:
    raise ValueError("t must be a rank 1 tensor")
  x0 = tf.expand_dims(x0, axis=0)
  velocity = tf.expand_dims(velocity, axis=0)
  dx = velocity * tf.expand_dims(t, axis=-1)
  linear_trajectories = x0 + dx
  assert linear_trajectories.shape.ndims == 2, \
    "linear_trajectories should be a rank 2 tensor"
  return linear_trajectories
967037
function setSubStepsToSteps (subSteps) {
  const steps = JSON.parse(JSON.stringify(STEPS.language));
  subSteps.forEach(subStep => steps[subStep.parentStep].subSteps.push(subStep));
  return steps;
}
732977
public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){
		int increment = 1;
		if(overlapping==false){
			increment=windowWidth;
		}
		ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>();
		boolean trackEndReached = false;
		
		for(int i = 0; i < t.size(); i=i+increment)
		{
			int upperBound = i+(windowWidth);
			if(upperBound>t.size()){
				upperBound=t.size();
				trackEndReached=true;
			}
			Trajectory help = new Trajectory(2, i);
			for(int j = i; j < upperBound; j++){
				help.add(t.get(j));
			}
			subTrajectories.add(help);
			if(trackEndReached){
				i=t.size();
			}
		}
		return subTrajectories;
	}
959376
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
    """"""
    from scipy import integrate
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib.colors import cnames

    def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0):
        """Compute the time-derivative of a Lorentz system."""
        x, y, z = coords
        return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]

    # Choose random starting points, uniformly distributed from -15 to 15
    np.random.seed(rseed)
    x0 = -15 + 30 * np.random.random((N_trajectories, 3))

    # Solve for the trajectories
    t = np.linspace(0, 2, 500)
    x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
                      for x0i in x0])

    # Set up figure & 3D axis for animation
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1], projection='3d')
    ax.axis('off')

    # choose a different color for each trajectory
    colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))

    # set up lines and points
    lines = sum([ax.plot([], [], [], '-', c=c)
                 for c in colors], [])
    pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
               for c in colors], [])

    # prepare the axes limits
    ax.set_xlim((-25, 25))
    ax.set_ylim((-35, 35))
    ax.set_zlim((5, 55))

    # set point-of-view: specified by (altitude degrees, azimuth degrees)
    ax.view_init(30, 0)

    # initialization function: plot the background of each frame
    def init():
        for line, pt in zip(lines, pts):
            line.set_data([], [])
            line.set_3d_properties([])

            pt.set_data([], [])
            pt.set_3d_properties([])
        return lines + pts

    # animation function: called sequentially
    def animate(i):
        # we'll step two time-steps per frame.  This leads to nice results.
        i = (2 * i) % x_t.shape[1]

        for line, pt, xi in zip(lines, pts, x_t):
            x, y, z = xi[:i + 1].T
            line.set_data(x, y)
            line.set_3d_properties(z)

            pt.set_data(x[-1:], y[-1:])
            pt.set_3d_properties(z[-1:])

        ax.view_init(30, 0.3 * i)
        fig.canvas.draw()
        return lines + pts

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=frames, interval=interval)
235965
def render(self,
            trajectories: Tuple[NonFluents, Fluents, Fluents, Fluents, np.array],
            batch: Optional[int] = None) -> None:
        '''
        '''

        non_fluents, initial_state, states, actions, interms, rewards = trajectories

        non_fluents = dict(non_fluents)
        states  = dict((name, fluent[0]) for name, fluent in states)
        actions = dict((name, fluent[0]) for name, fluent in actions)
        rewards = rewards[0]

        idx = self._compiler.rddl.domain.state_fluent_ordering.index('location/1')

        start = initial_state[idx][0]
        g = non_fluents['GOAL/1']
        path = states['location/1']
        deltas = actions['move/1']

        centers = non_fluents['DECELERATION_ZONE_CENTER/2']
        decays = non_fluents['DECELERATION_ZONE_DECAY/1']
        zones = [(x, y, d) for (x, y), d in zip(centers, decays)]

        self._ax1 = plt.gca()

        self._render_state_space()
        self._render_start_and_goal_positions(start, g)
        self._render_deceleration_zones(zones)
        self._render_state_action_trajectory(start, path, deltas)

        plt.title('Navigation', fontweight='bold')
        plt.legend(loc='lower right')
        plt.show()
1263618
def generate(self, step, params):
        
        subfactory = self.get_factory()
        logger.debug(
            "SubFactory: Instantiating %s.%s(%s), create=%r",
            subfactory.__module__, subfactory.__name__,
            utils.log_pprint(kwargs=params),
            step,
        )
        force_sequence = step.sequence if self.FORCE_SEQUENCE else None
        return step.recurse(subfactory, params, force_sequence=force_sequence)
249376
def load_trajectory(name, format=None, skip=1):
    '''

    '''
    df = datafile(name, format=format)

    ret = {}
    t, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    ret['t'] = t
    ret['coords'] = coords
    ret['boxes'] = boxes

    return ret
1092493
public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){
		Trajectory track = null;
		for(int i = 0; i < t.size() ; i++){
			if(t.get(i).getID()==id){
				track = t.get(i);
				break;
			}
		}
		return track;
	}
280685
def _complete_trajectory(self, trajectory, index):
    """"""

    assert isinstance(trajectory, Trajectory)

    # This *should* be the case.
    assert trajectory.last_time_step.action is None

    # Add to completed trajectories.
    self._completed_trajectories.append(trajectory)

    # Make a new one to replace it.
    self._trajectories[index] = Trajectory()
1338843
def downsample_trajectories(trajectories, downsampler, *args, **kwargs):
  '''
  '''
  X = np.vstack(trajectories)
  traj_lengths = list(map(len, trajectories))
  inds = np.sort(downsampler(X, *args, **kwargs))
  new_traj = []
  for stop in np.cumsum(traj_lengths):
    n = np.searchsorted(inds, stop)
    new_traj.append(X[inds[:n]])
    inds = inds[n:]
  return new_traj