| 135 | return len(self.indices) |
| 136 | |
| 137 | def sample_sequence(self, idx): |
| 138 | buffer_start_idx, buffer_end_idx, sample_start_idx, sample_end_idx = self.indices[idx] |
| 139 | result = dict() |
| 140 | for key in self.keys: |
| 141 | input_arr = self.replay_buffer[key] |
| 142 | # performance optimization, avoid small allocation if possible |
| 143 | if key not in self.key_first_k: |
| 144 | sample = input_arr[buffer_start_idx:buffer_end_idx] |
| 145 | else: |
| 146 | # performance optimization, only load used obs steps |
| 147 | n_data = buffer_end_idx - buffer_start_idx |
| 148 | k_data = min(self.key_first_k[key], n_data) |
| 149 | # fill value with Nan to catch bugs |
| 150 | # the non-loaded region should never be used |
| 151 | sample = np.full( |
| 152 | (n_data,) + input_arr.shape[1:], |
| 153 | fill_value=np.nan, |
| 154 | dtype=input_arr.dtype, |
| 155 | ) |
| 156 | try: |
| 157 | sample[:k_data] = input_arr[buffer_start_idx : buffer_start_idx + k_data] |
| 158 | except Exception as e: |
| 159 | raise RuntimeError( |
| 160 | f"Failed to copy data: k_data={k_data}, buffer_start_idx={buffer_start_idx}, " |
| 161 | f"input_arr.shape={input_arr.shape}" |
| 162 | ) from e |
| 163 | data = sample |
| 164 | if (sample_start_idx > 0) or (sample_end_idx < self.sequence_length): |
| 165 | data = np.zeros( |
| 166 | shape=(self.sequence_length,) + input_arr.shape[1:], |
| 167 | dtype=input_arr.dtype, |
| 168 | ) |
| 169 | if sample_start_idx > 0: |
| 170 | data[:sample_start_idx] = sample[0] |
| 171 | if sample_end_idx < self.sequence_length: |
| 172 | data[sample_end_idx:] = sample[-1] |
| 173 | data[sample_start_idx:sample_end_idx] = sample |
| 174 | result[key] = data |
| 175 | return result |