:param self: mdtraj.Trajectory
    :param idx: possible slices over frames,
    :param value:
    :return:
542446
def trajectory_set_item(self, idx, value):
    
    import mdtraj
    assert isinstance(self, mdtraj.Trajectory), type(self)
    if not isinstance(value, mdtraj.Trajectory):
        raise TypeError("value to assign is of incorrect type(%s). Should be mdtraj.Trajectory" % type(value))
    idx = np.index_exp[idx]
    frames, atoms = None, None
    if isinstance(idx, (list, tuple)):
        if len(idx) == 1:
            frames, atoms = idx[0], slice(None, None, None)
        if len(idx) == 2:
            frames, atoms = idx[0], idx[1]
        if len(idx) >= 3 or len(idx) == 0:
            raise IndexError("invalid slice by %s" % idx)

    self.xyz[frames, atoms] = value.xyz
    self._time[frames] = value.time
    self.unitcell_lengths[frames] = value.unitcell_lengths
    self.unitcell_angles[frames] = value.unitcell_angles
145746
def get_trajectories(self, index, rollout_length, history_length):
        
        indexes = np.arange(index - rollout_length + 1, index + 1, dtype=int)
        return self.get_transitions(indexes, history_length)
981146
def get_frame(self, idx, history_length=1):
        
        if idx >= self.current_size:
            raise VelException("Requested frame beyond the size of the buffer")

        if history_length > 1:
            assert self.state_buffer.shape[-1] == 1, \
                "State buffer must have last dimension of 1 if we want frame history"

        accumulator = []

        last_frame = self.state_buffer[idx]
        accumulator.append(last_frame)

        for i in range(history_length - 1):
            prev_idx = (idx - 1) % self.buffer_capacity

            if prev_idx == self.current_idx:
                raise VelException("Cannot provide enough history for the frame")
            elif self.dones_buffer[prev_idx]:
                # If previous frame was done - just append zeroes
                accumulator.append(np.zeros_like(last_frame))
            else:
                idx = prev_idx
                accumulator.append(self.state_buffer[idx])

        # We're pushing the elements in reverse order
        return np.concatenate(accumulator[::-1], axis=-1)
257331
def _handle_result_by_idx_slice(self, idx_slice):
        
        opts = dict(self.options)
        skip = opts.pop('skip', 0)
        limit = opts.pop('limit', None)
        py_to_couch_validate('skip', skip)
        py_to_couch_validate('limit', limit)
        start = idx_slice.start
        stop = idx_slice.stop
        data = None
        # start and stop cannot be None and both must be greater than 0
        if all(i is not None and i >= 0 for i in [start, stop]) and start < stop:
            if limit is not None:
                if start >= limit:
                    # Result is out of range
                    return dict()
                if stop > limit:
                    # Ensure that slice does not extend past original limit
                    return self._ref(skip=skip+start, limit=limit-start, **opts)
            data = self._ref(skip=skip+start, limit=stop-start, **opts)
        elif start is not None and stop is None and start >= 0:
            if limit is not None:
                if start >= limit:
                    # Result is out of range
                    return dict()
                # Ensure that slice does not extend past original limit
                data = self._ref(skip=skip+start, limit=limit-start, **opts)
            else:
                data = self._ref(skip=skip+start, **opts)
        elif start is None and stop is not None and stop >= 0:
            if limit is not None and stop > limit:
                # Ensure that slice does not extend past original limit
                data = self._ref(skip=skip, limit=limit, **opts)
            else:
                data = self._ref(skip=skip, limit=stop, **opts)
        return data
541951
def define_trajectory(self, trajectory_id, offset, n_pieces):
        
        self._send_packet(struct.pack('<BBBBIB',
                                      self.COMMAND_DEFINE_TRAJECTORY,
                                      trajectory_id,
                                      self.TRAJECTORY_LOCATION_MEM,
                                      self.TRAJECTORY_TYPE_POLY4D,
                                      offset,
                                      n_pieces))
1347684
def _call(self, x):
        """"""
        with self.op.mutex:
            result = pyshearlab.SLshearrecadjoint2D(x, self.op.shearlet_system)
            return np.moveaxis(result, -1, 0)
927198
def extend(self, trajectory):
        
        if self.time_step != trajectory.time_step:
            raise ValueError('Trajectory not extended: Time steps of trajectories is incompatible')

        if len(self.species) != len(trajectory.species) and self.species != trajectory.species:
            raise ValueError('Trajectory not extended: species in trajectory do not match')

        self.to_positions()
        trajectory.to_positions()

        self.frac_coords = np.concatenate((self.frac_coords, trajectory.frac_coords), axis=0)
        self.lattice, self.constant_lattice = self._combine_attribute(self.lattice, trajectory.lattice,
                                                                      self.frac_coords.shape[0],
                                                                      trajectory.frac_coords.shape[0])
        self.site_properties = self._combine_attribute(self.site_properties, trajectory.site_properties,
                                                       self.frac_coords.shape[0], trajectory.frac_coords.shape[0])
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
866355
def get_frame_with_future(self, frame_idx, env_idx):
        
        if frame_idx == self.current_idx:
            raise VelException("Cannot provide enough future for the frame")

        past_frame = self.get_frame(frame_idx, env_idx)

        if not self.dones_buffer[frame_idx, env_idx]:
            # We're not done
            next_idx = (frame_idx + 1) % self.buffer_capacity
            next_frame = self.state_buffer[next_idx, env_idx]

            if self.frame_history > 1:
                future_frame = np.concatenate([
                    past_frame.take(indices=np.arange(1, past_frame.shape[-1]), axis=-1), next_frame
                ], axis=-1)
            else:
                future_frame = next_frame
        else:
            # We are done
            future_frame = np.zeros_like(past_frame)

        return past_frame, future_frame
320618
def _set_position(self, value):
        
        pX, pY = self.position
        x, y = value
        dX = x - pX
        dY = y - pY
        self.moveBy((dX, dY))
267382
def _ensure_valid_index(self, value):
        
        # GH5632, make sure that we are a Series convertible
        if not len(self.index) and is_list_like(value):
            try:
                value = Series(value)
            except (ValueError, NotImplementedError, TypeError):
                raise ValueError('Cannot set a frame with no defined index '
                                 'and a value that cannot be converted to a '
                                 'Series')

            self._data = self._data.reindex_axis(value.index.copy(), axis=1,
                                                 fill_value=np.nan)
1238679
def get_frame_with_future_forward_steps(self, frame_idx, env_idx, forward_steps, discount_factor):
        
        index_array = np.arange(frame_idx, frame_idx+forward_steps) % self.current_size

        if self.current_idx in index_array:
            raise VelException("Cannot provide enough future for the frame")

        past_frame = self.get_frame(frame_idx, env_idx)
        dones_array = self.dones_buffer[index_array, env_idx]

        rewards_array = self.reward_buffer[index_array, env_idx]
        discounted_rewards_array = rewards_array * (discount_factor ** np.arange(forward_steps))

        if dones_array.any():
            # Are we done between current frame and frame + n
            done = True

            dones_shifted = np.zeros_like(dones_array)
            dones_shifted[1:] = dones_array[:-1]
            reward = discounted_rewards_array[~np.logical_or.accumulate(dones_shifted)].sum()
            future_frame = np.zeros_like(past_frame)
        else:
            done = False
            reward = discounted_rewards_array.sum()

            if forward_steps >= self.frame_history:
                frame_indices = (index_array[:self.frame_history] + 1) % self.buffer_capacity
                future_frame = np.moveaxis(self.state_buffer[frame_indices, env_idx], 0, -2).reshape(past_frame.shape)
            else:
                frame_candidate = np.moveaxis(
                    self.state_buffer[(index_array + 1) % self.buffer_capacity, env_idx], 0, -2
                )
                frame_candidate_target_shape = (
                    list(frame_candidate.shape[:-2]) + [frame_candidate.shape[-2] * frame_candidate.shape[-1]]
                )

                future_frame = np.concatenate([
                    past_frame[..., (frame_candidate_target_shape[-1] - past_frame.shape[-1]):],
                    frame_candidate.reshape(frame_candidate_target_shape)
                ], -1)

        return past_frame, future_frame, reward, done
698769
def extract_value(self, agg, idx, name=''):
        
        if not isinstance(idx, (tuple, list)):
            idx = [idx]
        instr = instructions.ExtractValue(self.block, agg, idx, name=name)
        self._insert(instr)
        return instr
687486
def get_transition(self, frame_idx, env_idx):
        
        past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)

        data_dict = {
            'observations': past_frame,
            'observations_next': future_frame,
            'actions': self.action_buffer[frame_idx, env_idx],
            'rewards': self.reward_buffer[frame_idx, env_idx],
            'dones': self.dones_buffer[frame_idx, env_idx],
        }

        for name in self.extra_data:
            data_dict[name] = self.extra_data[name][frame_idx, env_idx]

        return data_dict
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()
992215
def _get_index(self, value):
        
        error_msg = 'value {0} not found'.format(value)

        if self.state_values is None:
            if isinstance(value, numbers.Integral) and (0 <= value < self.n):
                return value
            else:
                raise ValueError(error_msg)

        # if self.state_values is not None:
        if self.state_values.ndim == 1:
            try:
                idx = np.where(self.state_values == value)[0][0]
                return idx
            except IndexError:
                raise ValueError(error_msg)
        else:
            idx = 0
            while idx < self.n:
                if np.array_equal(self.state_values[idx], value):
                    return idx
                idx += 1
            raise ValueError(error_msg)
1275065
def load_image(self, idx):
        
        im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcategories/{}.jpg'.format(self.siftflow_dir, idx))
        in_ = np.array(im, dtype=np.float32)
        in_ = in_[:,:,::-1]
        in_ -= self.mean
        in_ = in_.transpose((2,0,1))
        return in_