code stringlengths 17 6.64M |
|---|
def crop_largest_square(image, aspect_ratio=1):
(width, height) = image.size
new_width = min(width, int((height * aspect_ratio)))
new_height = min(height, int((width / aspect_ratio)))
left = ((width - new_width) / 2)
top = ((height - new_height) / 2)
right = ((width + new_width) / 2)
botto... |
def dl_image(url, timeout, fn, quality, crop=False, resize=256):
fetched = 1
try:
response = requests.get(url, timeout=timeout)
open(fn, 'wb').write(response.content)
img = Image.open(fn)
if crop:
img = crop_largest_square(img)
has_alpha = ((img.mode in ('RG... |
def dl_urls_concurrent(urls, outfolder, nthreads=1, timeout=1, quality=100, crop=False, resize=256):
os.makedirs(outfolder, exist_ok=True)
num_dl = []
with concurrent.futures.ThreadPoolExecutor(max_workers=nthreads) as executor:
for k in range(0, len(urls), nthreads):
end_ind = min(len... |
def crop_largest_square(image, aspect_ratio=1):
(width, height) = image.size
new_width = min(width, int((height * aspect_ratio)))
new_height = min(height, int((width / aspect_ratio)))
left = ((width - new_width) / 2)
top = ((height - new_height) / 2)
right = ((width + new_width) / 2)
botto... |
def dl_image(url, timeout, fn, quality, crop=False, resize=256):
fetched = 1
try:
response = requests.get(url, timeout=timeout)
open(fn, 'wb').write(response.content)
img = Image.open(fn)
if crop:
img = crop_largest_square(img)
has_alpha = ((img.mode in ('RG... |
def dl_urls_concurrent(urls, outfolder, nthreads=1, timeout=1, quality=100, crop=False, resize=256):
os.makedirs(outfolder, exist_ok=True)
num_dl = []
with concurrent.futures.ThreadPoolExecutor(max_workers=nthreads) as executor:
for k in range(0, len(urls), nthreads):
end_ind = min(len... |
class Actor(nn.Module):
def __init__(self, state_dim, action_dim):
super(Actor, self).__init__()
self.fc1 = nn.Linear(state_dim, 256)
self.fc2 = nn.Linear(256, 256)
self.mu_head = nn.Linear(256, action_dim)
self.sigma_head = nn.Linear(256, action_dim)
def _get_outputs... |
class Discriminator(nn.Module):
def __init__(self, state_dim, action_dim):
super(Discriminator, self).__init__()
self.fc1_1 = nn.Linear((state_dim + action_dim), 128)
self.fc1_2 = nn.Linear(action_dim, 128)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
d... |
class DWBC(object):
def __init__(self, state_dim, action_dim, alpha=7.5, no_pu=False, eta=0.5, d_update_num=100):
self.policy = Actor(state_dim, action_dim).to(device)
self.policy_optimizer = torch.optim.Adam(self.policy.parameters(), lr=0.0001, weight_decay=0.005)
self.discriminator = Di... |
def qlearning_dataset(dataset, terminate_on_end=False):
'\n Returns datasets formatted for use by standard Q-learning algorithms,\n with observations, actions, next_observations, rewards, and a terminal\n flag.\n '
N = dataset['rewards'].shape[0]
obs_ = []
next_obs_ = []
action_ = []
... |
def dataset_setting1(dataset1, dataset2, split_x, exp_num=10):
'\n Returns D_e and D_o of setting 1 in the paper.\n '
dataset_o = dataset_T_trajs(dataset2, 1000)
dataset_o['flag'] = np.zeros_like(dataset_o['terminals'])
(dataset_e, dataset_o_extra) = dataset_split_expert(dataset1, split_x, exp_n... |
def dataset_setting2(dataset1, split_x):
'\n Returns D_e and D_o of setting 2 in the paper.\n '
(dataset_e, dataset_o) = dataset_split_replay(dataset1, split_x)
dataset_e['flag'] = np.ones_like(dataset_e['terminals'])
dataset_o['flag'] = np.zeros_like(dataset_o['terminals'])
return (dataset_... |
def dataset_setting_demodice(dataset1, dataset2, num_e=1, num_o_e=10, num_o_o=1000):
'\n Returns D_e and D_o of setting in demodice.\n '
dataset_o = dataset_T_trajs(dataset2, num_o_o)
dataset_o['flag'] = np.zeros_like(dataset_o['terminals'])
(dataset_e, dataset_o_extra) = dataset_split_expert(da... |
def dataset_split_replay(dataset, split_x, terminate_on_end=False):
'\n Returns D_e and D_o from replay datasets.\n '
N = dataset['rewards'].shape[0]
return_traj = []
obs_traj = [[]]
next_obs_traj = [[]]
action_traj = [[]]
reward_traj = [[]]
done_traj = [[]]
for i in range((N... |
def dataset_split_expert(dataset, split_x, exp_num, terminate_on_end=False):
'\n Returns D_e and expert data in D_o of setting 1 in the paper.\n '
N = dataset['rewards'].shape[0]
return_traj = []
obs_traj = [[]]
next_obs_traj = [[]]
action_traj = [[]]
reward_traj = [[]]
done_traj... |
def dataset_T_trajs(dataset, T, terminate_on_end=False):
'\n Returns T trajs from dataset.\n '
N = dataset['rewards'].shape[0]
return_traj = []
obs_traj = [[]]
next_obs_traj = [[]]
action_traj = [[]]
reward_traj = [[]]
done_traj = [[]]
for i in range((N - 1)):
obs_tra... |
def eval_policy(policy, env_name, seed, mean, std, seed_offset=100, eval_episodes=10):
eval_env = gym.make(env_name)
eval_env.seed((seed + seed_offset))
avg_reward = 0.0
for _ in range(eval_episodes):
(state, done) = (eval_env.reset(), False)
while (not done):
state = ((np.... |
def eval_policy(policy, env_name, seed, mean, std, seed_offset=100, eval_episodes=10):
eval_env = gym.make(env_name)
eval_env.seed((seed + seed_offset))
avg_reward = 0.0
for _ in range(eval_episodes):
(state, done) = (eval_env.reset(), False)
while (not done):
state = ((np.... |
class ReplayBuffer(object):
def __init__(self, state_dim, action_dim, max_size=int(1000000.0)):
self.max_size = max_size
self.ptr = 0
self.size = 0
self.state = np.zeros((max_size, state_dim))
self.action = np.zeros((max_size, action_dim))
self.next_state = np.zero... |
def update_actor(key: PRNGKey, actor: Model, critic: Model, value: Model, batch: Batch, alpha: float, alg: str) -> Tuple[(Model, InfoDict)]:
v = value(batch.observations)
(q1, q2) = critic(batch.observations, batch.actions)
q = jnp.minimum(q1, q2)
if (alg == 'SQL'):
weight = (q - v)
we... |
def default_init(scale: Optional[float]=jnp.sqrt(2)):
return nn.initializers.orthogonal(scale)
|
class MLP(nn.Module):
hidden_dims: Sequence[int]
activations: Callable[([jnp.ndarray], jnp.ndarray)] = nn.relu
activate_final: int = False
layer_norm: bool = False
dropout_rate: Optional[float] = None
@nn.compact
def __call__(self, x: jnp.ndarray, training: bool=False) -> jnp.ndarray:
... |
@flax.struct.dataclass
class Model():
step: int
apply_fn: nn.Module = flax.struct.field(pytree_node=False)
params: Params
tx: Optional[optax.GradientTransformation] = flax.struct.field(pytree_node=False)
opt_state: Optional[optax.OptState] = None
@classmethod
def create(cls, model_def: nn... |
def get_config():
config = ml_collections.ConfigDict()
config.actor_lr = 0.0002
config.value_lr = 0.0002
config.critic_lr = 0.0002
config.hidden_dims = (256, 256)
config.discount = 0.99
config.value_dropout_rate = 0.5
config.layernorm = True
config.tau = 0.005
return config
|
def get_config():
config = ml_collections.ConfigDict()
config.actor_lr = 0.0003
config.value_lr = 0.0003
config.critic_lr = 0.0003
config.hidden_dims = (256, 256)
config.discount = 0.99
config.dropout_rate = 0.1
config.layernorm = True
config.tau = 0.005
return config
|
def get_config():
config = ml_collections.ConfigDict()
config.actor_lr = 0.0003
config.value_lr = 0.0003
config.critic_lr = 0.0003
config.hidden_dims = (256, 256)
config.discount = 0.99
config.dropout_rate = 0
config.layernorm = True
config.tau = 0.005
return config
|
def update_v(critic: Model, value: Model, batch: Batch, alpha: float, alg: str) -> Tuple[(Model, InfoDict)]:
(q1, q2) = critic(batch.observations, batch.actions)
q = jnp.minimum(q1, q2)
def value_loss_fn(value_params: Params) -> Tuple[(jnp.ndarray, InfoDict)]:
v = value.apply({'params': value_par... |
def update_q(critic: Model, value: Model, batch: Batch, discount: float) -> Tuple[(Model, InfoDict)]:
next_v = value(batch.next_observations)
target_q = (batch.rewards + ((discount * batch.masks) * next_v))
def critic_loss_fn(critic_params: Params) -> Tuple[(jnp.ndarray, InfoDict)]:
(q1, q2) = cr... |
def split_into_trajectories(observations, actions, rewards, masks, dones_float, next_observations):
trajs = [[]]
for i in tqdm(range(len(observations))):
trajs[(- 1)].append((observations[i], actions[i], rewards[i], masks[i], dones_float[i], next_observations[i]))
if ((dones_float[i] == 1.0) a... |
def merge_trajectories(trajs):
observations = []
actions = []
rewards = []
masks = []
dones_float = []
next_observations = []
for traj in trajs:
for (obs, act, rew, mask, done, next_obs) in traj:
observations.append(obs)
actions.append(act)
rewar... |
class Dataset(object):
def __init__(self, observations: np.ndarray, actions: np.ndarray, rewards: np.ndarray, masks: np.ndarray, dones_float: np.ndarray, next_observations: np.ndarray, size: int):
self.observations = observations
self.actions = actions
self.rewards = rewards
self.... |
class D4RLDataset(Dataset):
def __init__(self, env: gym.Env, add_env: gym.Env='None', expert_ratio: float=1.0, clip_to_eps: bool=True, heavy_tail: bool=False, heavy_tail_higher: float=0.0, eps: float=1e-05):
dataset = d4rl.qlearning_dataset(env)
if (add_env != 'None'):
add_data = d4rl... |
class ReplayBuffer(Dataset):
def __init__(self, observation_space: gym.spaces.Box, action_dim: int, capacity: int):
observations = np.empty((capacity, *observation_space.shape), dtype=observation_space.dtype)
actions = np.empty((capacity, action_dim), dtype=np.float32)
rewards = np.empty(... |
def _gen_dir_name():
now_str = datetime.now().strftime('%m-%d-%y_%H.%M.%S')
rand_str = ''.join(random.choices(string.ascii_lowercase, k=4))
return f'{now_str}_{rand_str}'
|
class Log():
def __init__(self, root_log_dir, cfg_dict, txt_filename='log.txt', csv_filename='progress.csv', cfg_filename='config.json', flush=True):
self.dir = (Path(root_log_dir) / _gen_dir_name())
self.dir.mkdir(parents=True)
self.txt_file = open((self.dir / txt_filename), 'w')
... |
def evaluate(env_name: str, agent: nn.Module, env: gym.Env, num_episodes: int) -> Dict[(str, float)]:
total_reward_ = []
for _ in range(num_episodes):
(observation, done) = (env.reset(), False)
total_reward = 0.0
while (not done):
action = agent.sample_actions(observation, ... |
def target_update(critic: Model, target_critic: Model, tau: float) -> Model:
new_target_params = jax.tree_util.tree_map((lambda p, tp: ((p * tau) + (tp * (1 - tau)))), critic.params, target_critic.params)
return target_critic.replace(params=new_target_params)
|
@jax.jit
def _update_jit_sql(rng: PRNGKey, actor: Model, critic: Model, value: Model, target_critic: Model, batch: Batch, discount: float, tau: float, alpha: float) -> Tuple[(PRNGKey, Model, Model, Model, Model, Model, InfoDict)]:
(new_value, value_info) = update_v(target_critic, value, batch, alpha, alg='SQL')
... |
@jax.jit
def _update_jit_eql(rng: PRNGKey, actor: Model, critic: Model, value: Model, target_critic: Model, batch: Batch, discount: float, tau: float, alpha: float) -> Tuple[(PRNGKey, Model, Model, Model, Model, Model, InfoDict)]:
(new_value, value_info) = update_v(target_critic, value, batch, alpha, alg='EQL')
... |
class Learner(object):
def __init__(self, seed: int, observations: jnp.ndarray, actions: jnp.ndarray, actor_lr: float=0.0003, value_lr: float=0.0003, critic_lr: float=0.0003, hidden_dims: Sequence[int]=(256, 256), discount: float=0.99, tau: float=0.005, alpha: float=0.1, dropout_rate: Optional[float]=None, value... |
class NormalTanhPolicy(nn.Module):
hidden_dims: Sequence[int]
action_dim: int
state_dependent_std: bool = True
dropout_rate: Optional[float] = None
log_std_scale: float = 1.0
log_std_min: Optional[float] = None
log_std_max: Optional[float] = None
tanh_squash_distribution: bool = True
... |
@functools.partial(jax.jit, static_argnames=('actor_def', 'distribution'))
def _sample_actions(rng: PRNGKey, actor_def: nn.Module, actor_params: Params, observations: np.ndarray, temperature: float=1.0) -> Tuple[(PRNGKey, jnp.ndarray)]:
dist = actor_def.apply({'params': actor_params}, observations, temperature)
... |
def sample_actions(rng: PRNGKey, actor_def: nn.Module, actor_params: Params, observations: np.ndarray, temperature: float=1.0) -> Tuple[(PRNGKey, jnp.ndarray)]:
return _sample_actions(rng, actor_def, actor_params, observations, temperature)
|
def normalize(dataset):
trajs = split_into_trajectories(dataset.observations, dataset.actions, dataset.rewards, dataset.masks, dataset.dones_float, dataset.next_observations)
def compute_returns(traj):
episode_return = 0
for (_, _, rew, _, _, _) in traj:
episode_return += rew
... |
def make_env_and_dataset(env_name: str, seed: int) -> Tuple[(gym.Env, D4RLDataset)]:
env = gym.make(env_name)
env = wrappers.EpisodeMonitor(env)
env = wrappers.SinglePrecision(env)
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.seed(seed)
dataset = D4RLDataset(env)
if... |
def main(_):
summary_writer = SummaryWriter(os.path.join(FLAGS.save_dir, 'tb', str(FLAGS.seed)), write_to_disk=True)
os.makedirs(FLAGS.save_dir, exist_ok=True)
(env, dataset) = make_env_and_dataset(FLAGS.env_name, FLAGS.seed)
action_dim = env.action_space.shape[0]
replay_buffer = ReplayBuffer(env.... |
def normalize(dataset):
trajs = split_into_trajectories(dataset.observations, dataset.actions, dataset.rewards, dataset.masks, dataset.dones_float, dataset.next_observations)
def compute_returns(traj):
episode_return = 0
for (_, _, rew, _, _, _) in traj:
episode_return += rew
... |
def make_env_and_dataset(env_name: str, seed: int) -> Tuple[(gym.Env, D4RLDataset)]:
env = gym.make(env_name)
env = wrappers.EpisodeMonitor(env)
env = wrappers.SinglePrecision(env)
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.seed(seed)
dataset = D4RLDataset(env)
if... |
def main(_):
(env, dataset) = make_env_and_dataset(FLAGS.env_name, FLAGS.seed)
kwargs = dict(FLAGS.config)
kwargs['alpha'] = FLAGS.alpha
kwargs['alg'] = FLAGS.alg
agent = Learner(FLAGS.seed, env.observation_space.sample()[np.newaxis], env.action_space.sample()[np.newaxis], max_steps=FLAGS.max_step... |
class ValueCritic(nn.Module):
hidden_dims: Sequence[int]
layer_norm: bool = False
dropout_rate: Optional[float] = 0.0
@nn.compact
def __call__(self, observations: jnp.ndarray) -> jnp.ndarray:
critic = MLP((*self.hidden_dims, 1), layer_norm=self.layer_norm, dropout_rate=self.dropout_rate)(... |
class Critic(nn.Module):
hidden_dims: Sequence[int]
activations: Callable[([jnp.ndarray], jnp.ndarray)] = nn.relu
layer_norm: bool = False
@nn.compact
def __call__(self, observations: jnp.ndarray, actions: jnp.ndarray) -> jnp.ndarray:
inputs = jnp.concatenate([observations, actions], (- 1... |
class DoubleCritic(nn.Module):
hidden_dims: Sequence[int]
activations: Callable[([jnp.ndarray], jnp.ndarray)] = nn.relu
layer_norm: bool = False
@nn.compact
def __call__(self, observations: jnp.ndarray, actions: jnp.ndarray) -> Tuple[(jnp.ndarray, jnp.ndarray)]:
critic1 = Critic(self.hidd... |
class EpisodeMonitor(gym.ActionWrapper):
'A class that computes episode returns and lengths.'
def __init__(self, env: gym.Env):
super().__init__(env)
self._reset_stats()
self.total_timesteps = 0
def _reset_stats(self):
self.reward_sum = 0.0
self.episode_length = 0... |
class SinglePrecision(gym.ObservationWrapper):
def __init__(self, env):
super().__init__(env)
if isinstance(self.observation_space, Box):
obs_space = self.observation_space
self.observation_space = Box(obs_space.low, obs_space.high, obs_space.shape)
elif isinstance... |
class PSNR():
def __init__(self):
self.data_range = 255
def forward(self, img1, img2):
'\n input:\n img1/img2: (H W C) uint8 ndarray.\n return:\n psnr score, float.\n '
(img1, img2) = (img1.copy(), img2.copy())
return peak_signal_noi... |
class SSIM():
def __init__(self):
self.win_size = None
self.gradient = False
self.data_range = 255
self.multichannel = True
self.gaussian_weights = False
self.full = False
def forward(self, img1, img2):
'\n input:\n img1/img2: (H W C)... |
def filter_order_clips(raw_videos, clip_ends=2):
video_sets = {}
clipped_videos = []
for video in raw_videos:
date_time = '--'.join(video.split('--')[0:2])
if (date_time not in video_sets):
video_sets[date_time] = 0
video_sets[date_time] += 1
for (date_time, num_fra... |
def extract_logs(video_dir, frame_shape):
lr = list(LogReader((video_dir + '/rlog.bz2')))
speed_data = [l.carState.vEgo for l in lr if (l.which() == 'carState')]
speed_data = np.array(speed_data)
resampled_speeds = resample(speed_data, frame_shape)
return resampled_speeds
|
def convert_video(downscaled_dir, video_dir):
downscaled_vid = ((((downscaled_dir + '/') + video_dir.split('-')[(- 1)]) + str(time.time())) + 'preprocessed.mp4')
subprocess.call((((('ffmpeg -r 24 -i ' + video_dir) + '/fcamera.hevc') + ' -c:v libx265 -r 20 -filter:v scale=640:480 -crf 10 -c:a -i ') + downscale... |
def opticalFlowDense(image_current, image_next):
'\n Args:\n image_current : RGB image\n image_next : RGB image\n return:\n optical flow magnitude and angle and stacked in a matrix\n '
image_current = np.array(image_current)
image_next = np.array(image_next)
gray_current ... |
def augment(image_current, image_next):
brightness = np.random.uniform(0.5, 1.5)
img1 = ImageEnhance.Brightness(image_current).enhance(brightness)
img2 = ImageEnhance.Brightness(image_next).enhance(brightness)
color = np.random.uniform(0.5, 1.5)
img1 = ImageEnhance.Brightness(img1).enhance(color)
... |
def op_flow_video(preprocessed_video, augment_frames=True):
op_flows = []
frames = []
count = 0
vidcap = cv.VideoCapture(preprocessed_video)
(success, frame1) = vidcap.read()
frame1 = cv.cvtColor(frame1, cv.COLOR_BGR2RGB)
frame1 = Image.fromarray(frame1).crop((0, 170, 640, 370)).resize((16... |
def write_hdf5(hdf5_path, frames, op_flows, resampled_speeds):
with h5py.File(hdf5_path) as f:
print(len(frames), len(op_flows), len(resampled_speeds))
print(f['frame'], f['op_flow'], f['speed'])
f['frame'].resize((f['frame'].len() + len(frames)), axis=0)
f['op_flow'].resize((f['op... |
def archive_processed(video_dir):
processed_dir = video_dir.split('/')
processed_dir[(- 2)] = 'processed'
processed_dir = '/'.join(processed_dir)
shutil.move(video_dir, processed_dir)
|
class DataGenerator(keras.utils.Sequence):
def __init__(self, batch_size, history_size, hdf5_path, indexes):
self.hdf5_path = hdf5_path
if (indexes is None):
with h5py.File(hdf5_path, 'r') as f:
self.indexes = np.arange(len(f['speed']))
else:
self.i... |
def build_model(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3, 3)
frame = TimeDistributed(SpatialDropout2D(0.2))(frame_inp)
frame = TimeDistributed(Conv2D(8, filter_size, activation=... |
def build_model_flat(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3, 3)
frame = TimeDistributed(SpatialDropout2D(0.2))(frame_inp)
frame = TimeDistributed(Conv2D(4, filter_size, activa... |
def build_model_frame(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3, 3)
base_mod = Xception(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
for l in base_mod.layers... |
def steer_thread():
context = zmq.Context()
poller = zmq.Poller()
logcan = messaging.sub_sock(context, service_list['can'].port)
joystick_sock = messaging.sub_sock(context, service_list['testJoystick'].port, conflate=True, poller=poller)
carstate = messaging.pub_sock(context, service_list['carStat... |
class TextPrint():
def __init__(self):
self.reset()
self.font = pygame.font.Font(None, 20)
def printf(self, screen, textString):
textBitmap = self.font.render(textString, True, BLACK)
screen.blit(textBitmap, [self.x, self.y])
self.y += self.line_height
def reset(... |
def joystick_thread():
context = zmq.Context()
joystick_sock = messaging.pub_sock(context, service_list['testJoystick'].port)
pygame.init()
clock = pygame.time.Clock()
pygame.joystick.init()
joystick_count = pygame.joystick.get_count()
if (joystick_count > 1):
raise ValueError('Mor... |
def _sync_inner_generator(input_queue, *args, **kwargs):
func = args[0]
args = args[1:]
get = input_queue.get
while True:
item = get()
if (item is EndSentinel):
return
(cookie, value) = item
(yield (cookie, func(value, *args, **kwargs)))
|
def _async_streamer_async_inner(input_queue, output_queue, generator_func, args, kwargs):
put = output_queue.put
put_end = True
try:
g = generator_func(input_queue, *args, **kwargs)
for item in g:
put((time(), item))
g.close()
except ExistentialError:
put_en... |
def _running_mean_var(ltc_stats, x):
(old_mean, var) = ltc_stats
mean = min(600.0, ((0.98 * old_mean) + (0.02 * x)))
var = min(5.0, max(0.1, ((0.98 * var) + ((0.02 * (mean - x)) * (old_mean - x)))))
return (mean, var)
|
def _find_next_resend(sent_messages, ltc_stats):
if (not sent_messages):
return (None, None)
oldest_sent_idx = sent_messages._OrderedDict__root[1][2]
(send_time, _) = sent_messages[oldest_sent_idx]
(mean, var) = ltc_stats
next_resend_time = ((send_time + mean) + (40.0 * sqrt(var)))
ret... |
def _do_cleanup(input_queue, output_queue, num_workers, sentinels_received, num_outstanding):
input_fd = input_queue.put_fd()
output_fd = output_queue.get_fd()
poller = select.epoll()
poller.register(input_fd, select.EPOLLOUT)
poller.register(output_fd, select.EPOLLIN)
remaining_outputs = []
... |
def _generate_results(input_stream, input_queue, worker_output_queue, output_queue, num_workers, max_outstanding):
pack_cookie = struct.pack
sent_messages = OrderedDict()
oldest_sent_idx = None
next_resend_time = None
ltc_stats = (5.0, 10.0)
received_messages = {}
next_out = 0
next_in_... |
def _generate_results_unreliable(input_stream, input_queue, worker_output_queue, output_queue, num_workers, max_outstanding_unused):
next_in_item = next(input_stream, EndSentinel)
inputs_remain = (next_in_item is not EndSentinel)
received_messages = deque()
pack_cookie = struct.pack
input_fd = inp... |
def _async_generator(func, max_workers, in_q_size, out_q_size, max_outstanding, async_inner, reliable):
if async_inner:
assert inspect.isgeneratorfunction(func), 'async_inner == True but {} is not a generator'.format(func)
@functools.wraps(func)
def wrapper(input_sequence_or_self, *args, **kwargs... |
def async_generator(max_workers=1, in_q_size=10, out_q_size=12, max_outstanding=10000, async_inner=False, reliable=True):
return (lambda f: _async_generator(f, max_workers, in_q_size, out_q_size, max_outstanding, async_inner, reliable))
|
def cache_path_for_file_path(fn, cache_prefix=None):
dir_ = os.path.join(DEFAULT_CACHE_DIR, 'local')
mkdirs_exists_ok(dir_)
return os.path.join(dir_, os.path.abspath(fn).replace('/', '_'))
|
class DataUnreadableError(Exception):
pass
|
def atomic_write_in_dir(path, **kwargs):
'Creates an atomic writer using a temporary file in the same directory\n as the destination file.\n '
writer = AtomicWriter(path, **kwargs)
return writer._open(_get_fileobject_func(writer, os.path.dirname(path)))
|
def _get_fileobject_func(writer, temp_dir):
def _get_fileobject():
file_obj = writer.get_fileobject(dir=temp_dir)
os.chmod(file_obj.name, 420)
return file_obj
return _get_fileobject
|
def mkdirs_exists_ok(path):
try:
os.makedirs(path)
except OSError:
if (not os.path.isdir(path)):
raise
|
def FileReader(fn):
return open(fn, 'rb')
|
class KBHit():
def __init__(self):
'Creates a KBHit object that you can call to do various keyboard things.\n '
self.set_kbhit_terminal()
def set_kbhit_terminal(self):
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.t... |
class lazy_property(object):
'Defines a property whose value will be computed only once and as needed.\n\n This can only be used on instance methods.\n '
def __init__(self, func):
self._func = func
def __get__(self, obj_self, cls):
value = self._func(obj_self)
setattr(obj_se... |
def write_can_to_msg(data, src, msg):
if (not isinstance(data[0], Sequence)):
data = [data]
can_msgs = msg.init('can', len(data))
for (i, d) in enumerate(data):
if (d[0] < 0):
continue
cc = can_msgs[i]
cc.address = d[0]
cc.busTime = 0
cc.dat = he... |
def convert_old_pkt_to_new(old_pkt):
(m, d) = old_pkt
msg = capnp_log.Event.new_message()
if (len(m) == 3):
(_, pid, t) = m
msg.logMonoTime = t
else:
(t, pid) = m
msg.logMonoTime = int((t * 1000000000.0))
last_velodyne_time = None
if (pid == PID_OBD):
wr... |
def index_log(fn):
index_log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'index_log')
index_log = os.path.join(index_log_dir, 'index_log')
phonelibs_dir = os.path.join(OP_PATH, 'phonelibs')
subprocess.check_call(['make', ('PHONELIBS=' + phonelibs_dir)], cwd=index_log_dir, stdout=op... |
def event_read_multiple(fn):
idx = index_log(fn)
with open(fn, 'rb') as f:
dat = f.read()
return [capnp_log.Event.from_bytes(dat[idx[i]:idx[(i + 1)]]) for i in range((len(idx) - 1))]
|
def event_read_multiple_bytes(dat):
with tempfile.NamedTemporaryFile() as dat_f:
dat_f.write(dat)
dat_f.flush()
idx = index_log(dat_f.name)
return [capnp_log.Event.from_bytes(dat[idx[i]:idx[(i + 1)]]) for i in range((len(idx) - 1))]
|
class MultiLogIterator(object):
def __init__(self, log_paths, wraparound=True):
self._log_paths = log_paths
self._wraparound = wraparound
self._first_log_idx = next((i for i in range(len(log_paths)) if (log_paths[i] is not None)))
self._current_log = self._first_log_idx
se... |
class LogReader(object):
def __init__(self, fn, canonicalize=True):
(_, ext) = os.path.splitext(fn)
data_version = None
with FileReader(fn) as f:
dat = f.read()
if ((ext == '.gz') and (('log_' in fn) or ('log2' in fn))):
dat = zlib.decompress(dat, (zlib.MAX... |
def load_many_logs_canonical(log_paths):
'Load all logs for a sequence of log paths.'
for log_path in log_paths:
for msg in LogReader(log_path):
(yield msg)
|
def big_endian_number(number):
if (number < 256):
return chr(number)
return (big_endian_number((number >> 8)) + chr((number & 255)))
|
def ebml_encode_number(number):
def trailing_bits(rest_of_number, number_of_bits):
if (number_of_bits == 8):
return chr((rest_of_number & 255))
else:
return (trailing_bits((rest_of_number >> 8), (number_of_bits - 8)) + chr((rest_of_number & 255)))
if (number == (- 1)):... |
def ebml_element(element_id, data, length=None):
if (length == None):
length = len(data)
return ((big_endian_number(element_id) + ebml_encode_number(length)) + data)
|
def write_ebml_header(f, content_type, version, read_version):
f.write(ebml_element(440786851, ((((((('' + ebml_element(17030, ben(1))) + ebml_element(17143, ben(1))) + ebml_element(17138, ben(4))) + ebml_element(17139, ben(8))) + ebml_element(17026, content_type)) + ebml_element(17031, ben(version))) + ebml_elem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.