code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def train(self, states, actions, next_states, rewards, done, weights=None): """ Train DDPG Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is ...
Train DDPG Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ddpg.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error """ if isinstance(actions, tf...
Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/ddpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ddpg.py
MIT
def __init__( self, state_shape, action_dim, q_func=None, name="DQN", lr=0.001, adam_eps=1e-07, units=(32, 32), epsilon=0.1, epsilon_min=None, epsilon_decay_step=int(1e6), n_wa...
Initialize DQN agent Args: state_shape (iterable of int): Observation space shape action_dim (int): Dimension of discrete action q_function (QFunc): Custom Q function class. If ``None`` (default), Q function is constructed with ``QFunc``. name (str): Nam...
__init__
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def get_action(self, state, test=False, tensor=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. tensor (bool): When ``True``, return type is ``tf.Tensor`` Returns: ...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. tensor (bool): When ``True``, return type is ``tf.Tensor`` Returns: tf.Tensor or np.ndarray or float: Selected action
get_action
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def train(self, states, actions, next_states, rewards, done, weights=None): """ Train DQN Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is N...
Train DQN Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error """ if isinstance(actions, tf...
Compute TD error Args: states actions next_states rewars dones Returns tf.Tensor: TD error
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = OffPolicyAgent.get_argument(parser...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/algos/dqn.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/dqn.py
MIT
def __init__( self, state_shape, units=(32, 32), lr=0.001, enable_sn=False, name="GAIfO", **kwargs): """ Initialize GAIfO Args: state_shape (iterable of int): action_dim (int): ...
Initialize GAIfO Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``(32, 32)`` lr (float): Learning rate. The default is ``0.001`` enable_sn (bool): Whether enable Spectral Normalization. The defa...
__init__
python
keiohta/tf2rl
tf2rl/algos/gaifo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gaifo.py
MIT
def inference(self, states, actions, next_states): """ Infer Reward with GAIfO Args: states actions next_states Returns: tf.Tensor: Reward """ assert states.shape == next_states.shape if states.ndim == 1: ...
Infer Reward with GAIfO Args: states actions next_states Returns: tf.Tensor: Reward
inference
python
keiohta/tf2rl
tf2rl/algos/gaifo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gaifo.py
MIT
def __init__( self, state_shape, action_dim, units=[32, 32], lr=0.001, enable_sn=False, name="GAIL", **kwargs): """ Initialize GAIL Args: state_shape (iterable of int): action...
Initialize GAIL Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``[32, 32]`` lr (float): Learning rate. The default is ``0.001`` enable_sn (bool): Whether enable Spectral Normalization. The defai...
__init__
python
keiohta/tf2rl
tf2rl/algos/gail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gail.py
MIT
def inference(self, states, actions, next_states): """ Infer Reward with GAIL Args: states actions next_states Returns: tf.Tensor: Reward """ if states.ndim == actions.ndim == 1: states = np.expand_dims(states,...
Infer Reward with GAIL Args: states actions next_states Returns: tf.Tensor: Reward
inference
python
keiohta/tf2rl
tf2rl/algos/gail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/gail.py
MIT
def __init__( self, clip=True, clip_ratio=0.2, name="PPO", **kwargs): """ Initialize PPO Args: clip (bool): Whether clip or not. The default is ``True``. clip_ratio (float): Probability ratio is clipped between ...
Initialize PPO Args: clip (bool): Whether clip or not. The default is ``True``. clip_ratio (float): Probability ratio is clipped between ``1-clip_ratio`` and ``1+clip_ratio``. name (str): Name of agent. The default is ``"PPO"``. state_shape (iterable of ...
__init__
python
keiohta/tf2rl
tf2rl/algos/ppo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ppo.py
MIT
def train(self, states, actions, advantages, logp_olds, returns): """ Train PPO Args: states actions advantages logp_olds returns """ # Train actor and critic if self.actor_critic is not None: actor_...
Train PPO Args: states actions advantages logp_olds returns
train
python
keiohta/tf2rl
tf2rl/algos/ppo.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/ppo.py
MIT
def __init__( self, state_shape, action_dim, name="SAC", max_action=1., lr=3e-4, lr_alpha=3e-4, actor_units=(256, 256), critic_units=(256, 256), tau=5e-3, alpha=.2, auto_alpha=...
Initialize SAC Args: state_shape (iterable of int): action_dim (int): name (str): Name of network. The default is ``"SAC"`` max_action (float): lr (float): Learning rate. The default is ``3e-4``. lr_alpha (alpha): Learning rate fo...
__init__
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def get_action(self, state, test=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action """ assert isinstance(state,...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action
get_action
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def train(self, states, actions, next_states, rewards, dones, weights=None): """ Train SAC Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights is ...
Train SAC Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns np.ndarray: TD error """ if isinstance(actions, t...
Compute TD error Args: states actions next_states rewars dones Returns np.ndarray: TD error
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = OffPolicyAgent.get_argument(parser...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/algos/sac.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac.py
MIT
def __init__(self, action_dim, obs_shape=(84, 84, 9), n_conv_layers=4, n_conv_filters=32, feature_dim=50, tau_encoder=0.05, tau_critic=0.01, auto_alpha=True, lr_sac=1e...
Initialize SAC+AE Args: action_dim (int): obs_shape: (iterable of int): The default is ``(84, 84, 9)`` n_conv_layers (int): Number of convolutional layers at encoder. The default is ``4`` n_conv_filters (int): Number of filters in convolutional layers. T...
__init__
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def get_action(self, state, test=False): """ Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action Notes: When the input i...
Get action Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: tf.Tensor or float: Selected action Notes: When the input image have different size, cropped image is used ...
get_action
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def train(self, states, actions, next_states, rewards, dones, weights=None): """ Train SAC+AE Args: states actions next_states rewards done weights (optional): Weights for importance sampling """ if weights ...
Train SAC+AE Args: states actions next_states rewards done weights (optional): Weights for importance sampling
train
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = SAC.get_argument(parser) p...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/algos/sac_ae.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/sac_ae.py
MIT
def __init__( self, state_shape, action_dim, name="TD3", actor_update_freq=2, policy_noise=0.2, noise_clip=0.5, critic_units=(400, 300), **kwargs): """ Initialize TD3 Args: sh...
Initialize TD3 Args: shate_shape (iterable of ints): Observation state shape action_dim (int): Action dimension name (str): Network name. The default is ``"TD3"``. actor_update_freq (int): Number of critic updates per one actor upate. policy_...
__init__
python
keiohta/tf2rl
tf2rl/algos/td3.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/td3.py
MIT
def compute_td_error(self, states, actions, next_states, rewards, dones): """ Compute TD error Args: states actions next_states rewars dones Returns: np.ndarray: Sum of two TD errors. """ td_errors1...
Compute TD error Args: states actions next_states rewars dones Returns: np.ndarray: Sum of two TD errors.
compute_td_error
python
keiohta/tf2rl
tf2rl/algos/td3.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/td3.py
MIT
def __init__( self, state_shape, action_dim, units=(32, 32), n_latent_unit=32, lr=5e-5, kl_target=0.5, reg_param=0., enable_sn=False, enable_gp=False, name="VAIL", **kwargs): ...
Initialize VAIL Args: state_shape (iterable of int): action_dim (int): units (iterable of int): The default is ``(32, 32)`` lr (float): Learning rate. The default is ``5e-5`` kl_target (float): The default is ``0.5`` reg_param (fl...
__init__
python
keiohta/tf2rl
tf2rl/algos/vail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vail.py
MIT
def _compute_kl_latent(self, means, log_stds): r""" Compute KL divergence of latent spaces over standard Normal distribution to compute loss in eq.5. The formulation of KL divergence between two normal distributions is as follows: ln(\sigma_2 / \sigma_1) + {(\mu_1 - \mu_2)^2...
Compute KL divergence of latent spaces over standard Normal distribution to compute loss in eq.5. The formulation of KL divergence between two normal distributions is as follows: ln(\sigma_2 / \sigma_1) + {(\mu_1 - \mu_2)^2 + \sigma_1^2 - \sigma_2^2} / (2 * \sigma_2^2) Sinc...
_compute_kl_latent
python
keiohta/tf2rl
tf2rl/algos/vail.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vail.py
MIT
def __init__( self, state_shape, action_dim, is_discrete, actor=None, critic=None, actor_critic=None, max_action=1., actor_units=(256, 256), critic_units=(256, 256), lr_actor=1e-3, ...
Initialize VPG Args: state_shape (iterable of int): action_dim (int): is_discrete (bool): actor: critic: actor_critic: max_action (float): maximum action size. actor_units (iterable of int): Numbers of unit...
__init__
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def get_action(self, state, test=False): """ Get action and probability Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray or float: Selected action np.ndarray or f...
Get action and probability Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray or float: Selected action np.ndarray or float: Log(p)
get_action
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def get_action_and_val(self, state, test=False): """ Get action, probability, and critic value Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray: Selected action n...
Get action, probability, and critic value Args: state: Observation state test (bool): When ``False`` (default), policy returns exploratory action. Returns: np.ndarray: Selected action np.ndarray: Log(p) np.ndarray: Critic value ...
get_action_and_val
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def train(self, states, actions, advantages, logp_olds, returns): """ Train VPG Args: states actions advantages logp_olds returns """ # Train actor and critic actor_loss, logp_news = self._train_actor_body( ...
Train VPG Args: states actions advantages logp_olds returns
train
python
keiohta/tf2rl
tf2rl/algos/vpg.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/algos/vpg.py
MIT
def __init__(self, env, noop_max=30): """ Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None self.noop_action = 0 ...
Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def reset(self, **kwargs): """ Do no-op action for a number of steps in [1, noop_max]. """ self.env.reset(**kwargs) if self.override_num_noops is not None: noops = self.override_num_noops else: noops = self.unwrapped.np_random.randint( ...
Do no-op action for a number of steps in [1, noop_max].
reset
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env): """ Take action on reset for environments that are fixed until firing. """ gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3
Take action on reset for environments that are fixed until firing.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env): """ Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation. """ gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = True
Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def reset(self, **kwargs): """ Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes. """ if self.was_real_done: obs = self.env.reset(**kwa...
Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes.
reset
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, skip=4): """ Return only every `skip`-th frame """ gym.Wrapper.__init__(self, env) # most recent raw observations (for max pooling across time steps) self._obs_buffer = np.zeros( (2,)+env.observation_space.shape, dtype=np.uint8) ...
Return only every `skip`-th frame
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def step(self, action): """ Repeat action, sum reward, and max over last observations. """ total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_...
Repeat action, sum reward, and max over last observations.
step
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, width=84, height=84, grayscale=True, dict_space_key=None): """ Warp frames to 84x84 as done in the Nature paper and later work. If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which observation should be warped. ...
Warp frames to 84x84 as done in the Nature paper and later work. If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which observation should be warped.
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env, k): """ Stack k last frames. Returns lazy array, which is much more memory efficient. See also baselines.common.atari_wrappers.LazyFrames """ gym.Wrapper.__init__(self, env) self.k = k self.frames = deque([], maxlen=k) shp =...
Stack k last frames. Returns lazy array, which is much more memory efficient. See also baselines.common.atari_wrappers.LazyFrames
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, frames): """ This object ensures that common frames between the observations are only stored once. It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay buffers. This object should only be converted to numpy array before being p...
This object ensures that common frames between the observations are only stored once. It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay buffers. This object should only be converted to numpy array before being passed to the model. You'd not b...
__init__
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False): """ Configure environment for DeepMind-style Atari. """ if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFr...
Configure environment for DeepMind-style Atari.
wrap_deepmind
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def wrap_dqn(env, stack_frames=4, episodic_life=True, reward_clipping=True, wrap_ndarray=False): """ Apply a common set of wrappers for Atari games. """ assert 'NoFrameskip' in env.spec.id if episodic_life: env = EpisodicLifeEnv(env) env = NoopResetEnv(env, noop_max=30) ...
Apply a common set of wrappers for Atari games.
wrap_dqn
python
keiohta/tf2rl
tf2rl/envs/atari_wrapper.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/atari_wrapper.py
MIT
def __init__(self, env_fn, batch_size, thread_pool=4, max_episode_steps=1000): """ Args: env_fn: function Function to make an environment batch_size: int Batch size thread_pool: int Thread pool size max_epis...
Args: env_fn: function Function to make an environment batch_size: int Batch size thread_pool: int Thread pool size max_episode_steps: int Maximum step of an episode
__init__
python
keiohta/tf2rl
tf2rl/envs/multi_thread_env.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/multi_thread_env.py
MIT
def step(self, actions, name=None): """ Args: actions: tf.Tensor Actions whose shape is float32[batch_size, dim_action] name: str Operator name Returns: obs: tf.Tensor [batch_size, dim_obs] reward: ...
Args: actions: tf.Tensor Actions whose shape is float32[batch_size, dim_action] name: str Operator name Returns: obs: tf.Tensor [batch_size, dim_obs] reward: tf.Tensor [batch_size] ...
step
python
keiohta/tf2rl
tf2rl/envs/multi_thread_env.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/multi_thread_env.py
MIT
def py_step(self, actions): """ Args: actions: np.array Actions whose shape is [batch_size, dim_action] Returns: obs: np.array reward: np.array done: np.array """ def _process(offset): for idx_env in ra...
Args: actions: np.array Actions whose shape is [batch_size, dim_action] Returns: obs: np.array reward: np.array done: np.array
py_step
python
keiohta/tf2rl
tf2rl/envs/multi_thread_env.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/multi_thread_env.py
MIT
def experience(self, x): """Learn input values without computing the output values of them""" if self.until is not None and self.count >= self.until: return count_x = x.shape[self.batch_axis] if count_x == 0: return self.count += count_x rate = ...
Learn input values without computing the output values of them
experience
python
keiohta/tf2rl
tf2rl/envs/normalizer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/normalizer.py
MIT
def __call__(self, x, update=True): """Normalize mean and variance of values based on emprical values. Args: x (ndarray or Variable): Input values update (bool): Flag to learn the input values Returns: ndarray or Variable: Normalized output values """ ...
Normalize mean and variance of values based on emprical values. Args: x (ndarray or Variable): Input values update (bool): Flag to learn the input values Returns: ndarray or Variable: Normalized output values
__call__
python
keiohta/tf2rl
tf2rl/envs/normalizer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/normalizer.py
MIT
def make(id, **kwargs): r""" Make gym.Env with version tolerance Args: id (str) : Id specifying `gym.Env` registered to `gym.env.registry`. Valid format is `"^(?:[\w:-]+\/)?([\w:.-]+)-v(\d+)$"` See https://github.com/openai/gym/blob/v0.21.0/gym/envs/registratio...
Make gym.Env with version tolerance Args: id (str) : Id specifying `gym.Env` registered to `gym.env.registry`. Valid format is `"^(?:[\w:-]+\/)?([\w:.-]+)-v(\d+)$"` See https://github.com/openai/gym/blob/v0.21.0/gym/envs/registration.py#L17-L19 Returns: ...
make
python
keiohta/tf2rl
tf2rl/envs/utils.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/envs/utils.py
MIT
def __init__( self, policy, env, args, irl, expert_obs, expert_next_obs, expert_act, test_env=None): """ Initialize Trainer class Args: policy: Policy to be trained ...
Initialize Trainer class Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters specified with command line irl expert_obs expert_next_obs expert_act ...
__init__
python
keiohta/tf2rl
tf2rl/experiments/irl_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/irl_trainer.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = Trainer.get_argument(parser) ...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/experiments/irl_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/irl_trainer.py
MIT
def __init__(self, *args, n_eval_episodes_per_model=5, **kwargs): """ Initialize ME-TRPO Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters specified with command line test_env (gym....
Initialize ME-TRPO Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters specified with command line test_env (gym.Env): Environment for test. reward_fn (callable): Reward function...
__init__
python
keiohta/tf2rl
tf2rl/experiments/me_trpo_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/me_trpo_trainer.py
MIT
def predict_next_state(self, obses, acts, idx=None): """ Predict Next State Args: obses acts idx (int): Index number of dynamics mode to use. If ``None`` (default), choose randomly. Returns: np.ndarray: next state """ is_s...
Predict Next State Args: obses acts idx (int): Index number of dynamics mode to use. If ``None`` (default), choose randomly. Returns: np.ndarray: next state
predict_next_state
python
keiohta/tf2rl
tf2rl/experiments/me_trpo_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/me_trpo_trainer.py
MIT
def finish_horizon(self, last_val=0): """ TODO: These codes are completly identical to the ones defined in on_policy_trainer.py. Use it. """ samples = self.local_buffer._encode_sample( np.arange(self.local_buffer.get_stored_size())) rews = np.append(samples["rew"], la...
TODO: These codes are completly identical to the ones defined in on_policy_trainer.py. Use it.
finish_horizon
python
keiohta/tf2rl
tf2rl/experiments/me_trpo_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/me_trpo_trainer.py
MIT
def __init__(self, input_dim, output_dim, units=[32, 32], name="DymamicsModel", gpu=0): """ Initialize DynamicsModel Args: input_dim (int) output_dim (int) units (iterable of int): The default is ``[32, 32]`` name (str): The default is ``"Dynamics...
Initialize DynamicsModel Args: input_dim (int) output_dim (int) units (iterable of int): The default is ``[32, 32]`` name (str): The default is ``"DynamicsModel"`` gpu (int): The default is ``0``.
__init__
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def call(self, inputs): """ Call Dynamics Model Args: inputs (tf.Tensor) Returns: tf.Tensor """ features = self.l1(inputs) features = self.l2(features) return self.l3(features)
Call Dynamics Model Args: inputs (tf.Tensor) Returns: tf.Tensor
call
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def get_action(self, obs): """ Get random action Args: obs Returns: float: action """ return np.random.uniform( low=-self._max_action, high=self._max_action, size=self._act_dim)
Get random action Args: obs Returns: float: action
get_action
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def get_actions(self, obses): """ Get batch actions Args: obses Returns: np.dnarray: batch actions """ batch_size = obses.shape[0] return np.random.uniform( low=-self._max_action, high=self._max_action, ...
Get batch actions Args: obses Returns: np.dnarray: batch actions
get_actions
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def __init__( self, policy, env, args, reward_fn, buffer_size=int(1e6), n_dynamics_model=1, lr=0.001, **kwargs): """ Initialize MPCTrainer class Args: policy: Policy to be tra...
Initialize MPCTrainer class Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters specified with command line test_env (gym.Env): Environment for test. reward_fn (callable): Reward...
__init__
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def predict_next_state(self, obses, acts): """ Predict Next State Args: obses acts Returns: np.ndarray: next state """ obs_diffs = np.zeros_like(obses) inputs = np.concatenate([obses, acts], axis=1) for dynamics_model ...
Predict Next State Args: obses acts Returns: np.ndarray: next state
predict_next_state
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def collect_episodes(self, n_rollout=1): """ Collect Episodes Args: n_rollout (int): Number of rollout. The default is ``1`` """ for _ in range(n_rollout): obs = self._env.reset() for _ in range(self._episode_max_steps): act = ...
Collect Episodes Args: n_rollout (int): Number of rollout. The default is ``1``
collect_episodes
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def fit_dynamics(self, n_epoch=1): """ Fit dynamics Args: n_epocs (int): Number of epocs to fit """ inputs, labels = self._make_inputs_output_pairs(n_epoch) dataset = tf.data.Dataset.from_tensor_slices((inputs, labels)) dataset = dataset.batch(self._...
Fit dynamics Args: n_epocs (int): Number of epocs to fit
fit_dynamics
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ parser = Trainer.get_argument(parser) ...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/experiments/mpc_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/mpc_trainer.py
MIT
def evaluate_policy(self, total_steps): """ Evaluate policy Args: total_steps (int): Current total steps of training """ avg_test_return = 0. avg_test_steps = 0 if self._save_test_path: replay_buffer = get_replay_buffer( se...
Evaluate policy Args: total_steps (int): Current total steps of training
evaluate_policy
python
keiohta/tf2rl
tf2rl/experiments/on_policy_trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/on_policy_trainer.py
MIT
def __init__( self, policy, env, args, test_env=None): """ Initialize Trainer class Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters...
Initialize Trainer class Args: policy: Policy to be trained env (gym.Env): Environment for train args (Namespace or dict): config parameters specified with command line test_env (gym.Env): Environment for test.
__init__
python
keiohta/tf2rl
tf2rl/experiments/trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/trainer.py
MIT
def evaluate_policy_continuously(self): """ Periodically search the latest checkpoint, and keep evaluating with the latest model until user kills process. """ if self._model_dir is None: self.logger.error("Please specify model directory by passing command line argument `--mod...
Periodically search the latest checkpoint, and keep evaluating with the latest model until user kills process.
evaluate_policy_continuously
python
keiohta/tf2rl
tf2rl/experiments/trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/trainer.py
MIT
def get_argument(parser=None): """ Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser """ if parser is None: parser = arg...
Create or update argument parser for command line program Args: parser (argparse.ArgParser, optional): argument parser Returns: argparse.ArgParser: argument parser
get_argument
python
keiohta/tf2rl
tf2rl/experiments/trainer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/experiments/trainer.py
MIT
def discount_cumsum(x, discount): """Forked from rllab for computing discounted cumulative sums of vectors. Args: x: np.ndarray or tf.Tensor Vector of inputs discount: float Discount factor Returns: Discounted cumulative summation. If input is [x0, x1, x2], ...
Forked from rllab for computing discounted cumulative sums of vectors. Args: x: np.ndarray or tf.Tensor Vector of inputs discount: float Discount factor Returns: Discounted cumulative summation. If input is [x0, x1, x2], then the output is: [x0 + dis...
discount_cumsum
python
keiohta/tf2rl
tf2rl/misc/discount_cumsum.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/discount_cumsum.py
MIT
def huber_loss(x, delta=1.): """ Args: x: np.ndarray or tf.Tensor Values to compute the huber loss. delta: float Positive floating point value. Represents the maximum possible gradient magnitude. Returns: tf.Tensor The huber loss. """ del...
Args: x: np.ndarray or tf.Tensor Values to compute the huber loss. delta: float Positive floating point value. Represents the maximum possible gradient magnitude. Returns: tf.Tensor The huber loss.
huber_loss
python
keiohta/tf2rl
tf2rl/misc/huber_loss.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/huber_loss.py
MIT
def observe(self, x): """Compute next mean and std Args: x: float Input data. """ self._n.assign_add(1) numerator = x - self._mean self._mean.assign_add((x - self._mean) / self._n) self._mean_diff.assign_add(numerator * (x - self._mean...
Compute next mean and std Args: x: float Input data.
observe
python
keiohta/tf2rl
tf2rl/misc/normalizer.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/normalizer.py
MIT
def periodically(body, period, name="periodically"): """ Periodically performs a tensorflow op. The body tensorflow op will be executed every `period` times the periodically op is executed. More specifically, with `n` the number of times the op has been executed, the body will be executed when `n` ...
Periodically performs a tensorflow op. The body tensorflow op will be executed every `period` times the periodically op is executed. More specifically, with `n` the number of times the op has been executed, the body will be executed when `n` is a non zero positive multiple of `period` (i.e. there ...
periodically
python
keiohta/tf2rl
tf2rl/misc/periodic_ops.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/periodic_ops.py
MIT
def is_return_code_zero(args): """ Return true if the given command's return code is zero. All the messages to stdout or stderr are suppressed. forked from https://github.com/chainer/chainerrl/blob/master/chainerrl/misc/is_return_code_zero.py """ with open(os.devnull, 'wb') as FNULL: try...
Return true if the given command's return code is zero. All the messages to stdout or stderr are suppressed. forked from https://github.com/chainer/chainerrl/blob/master/chainerrl/misc/is_return_code_zero.py
is_return_code_zero
python
keiohta/tf2rl
tf2rl/misc/prepare_output_dir.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/prepare_output_dir.py
MIT
def prepare_output_dir(args, user_specified_dir=None, argv=None, time_format='%Y%m%dT%H%M%S.%f', suffix=""): """ Prepare a directory for outputting training results. An output directory, which ends with the current datetime string, is created. Then the following infomation is save...
Prepare a directory for outputting training results. An output directory, which ends with the current datetime string, is created. Then the following infomation is saved into the directory: args.txt: command line arguments command.txt: command itself environ.txt: environmental varia...
prepare_output_dir
python
keiohta/tf2rl
tf2rl/misc/prepare_output_dir.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/misc/prepare_output_dir.py
MIT
def _compute_dist(self, states): """ Args: states: np.ndarray or tf.Tensor Inputs to neural network. Returns: tfp.distributions.Categorical Categorical distribution whose probabilities are computed using softmax activation...
Args: states: np.ndarray or tf.Tensor Inputs to neural network. Returns: tfp.distributions.Categorical Categorical distribution whose probabilities are computed using softmax activation of a neural network
_compute_dist
python
keiohta/tf2rl
tf2rl/policies/tfp_categorical_actor.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/policies/tfp_categorical_actor.py
MIT
def _compute_dist(self, states): """ Args: states: np.ndarray or tf.Tensor Inputs to neural network. Returns: tfp.distributions.MultivariateNormalDiag Multivariate normal distribution object whose mean and standard deviati...
Args: states: np.ndarray or tf.Tensor Inputs to neural network. Returns: tfp.distributions.MultivariateNormalDiag Multivariate normal distribution object whose mean and standard deviation is output of a neural network
_compute_dist
python
keiohta/tf2rl
tf2rl/policies/tfp_gaussian_actor.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/policies/tfp_gaussian_actor.py
MIT
def call(self, states, test=False): """ Compute actions and log probabilities of the selected action """ dist = self._compute_dist(states) if test: raw_actions = dist.mean() else: raw_actions = dist.sample() log_pis = dist.log_prob(raw_acti...
Compute actions and log probabilities of the selected action
call
python
keiohta/tf2rl
tf2rl/policies/tfp_gaussian_actor.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/policies/tfp_gaussian_actor.py
MIT
def random_crop(input_imgs, output_size): """ Args: input_imgs: np.ndarray Images whose shape is (batch_size, width, height, channels) output_size: Int Output width and height size. Returns: """ assert input_imgs.ndim == 4, f"The dimension of input images m...
Args: input_imgs: np.ndarray Images whose shape is (batch_size, width, height, channels) output_size: Int Output width and height size. Returns:
random_crop
python
keiohta/tf2rl
tf2rl/tools/img_tools.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/tools/img_tools.py
MIT
def center_crop(img, output_size): """ Args: img: np.ndarray Input image array. The shape is (width, height, channel) output_size: int Width and height size for output image Returns: """ is_single_img = img.ndim == 3 h, w = img.shape[:2] if is_single_i...
Args: img: np.ndarray Input image array. The shape is (width, height, channel) output_size: int Width and height size for output image Returns:
center_crop
python
keiohta/tf2rl
tf2rl/tools/img_tools.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/tools/img_tools.py
MIT
def preprocess_img(img, bits=5): """Preprocessing image, see https://arxiv.org/abs/1807.03039.""" bins = 2 ** bits if bits < 8: obs = tf.cast(tf.floor(img / 2 ** (8 - bits)), dtype=tf.float32) obs = obs / bins obs = obs + tf.random.uniform(shape=obs.shape) / bins obs = obs - 0.5 retu...
Preprocessing image, see https://arxiv.org/abs/1807.03039.
preprocess_img
python
keiohta/tf2rl
tf2rl/tools/img_tools.py
https://github.com/keiohta/tf2rl/blob/master/tf2rl/tools/img_tools.py
MIT
def resolve_snakefile(path: Optional[Path], allow_missing: bool = False): """Get path to the snakefile. Arguments --------- path: Optional[Path] -- The path to the snakefile. If not provided, default locations will be tried. """ if path is None: for p in SNAKEFILE_CHOICES: i...
Get path to the snakefile. Arguments --------- path: Optional[Path] -- The path to the snakefile. If not provided, default locations will be tried.
resolve_snakefile
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def workflow( self, resource_settings: ResourceSettings, config_settings: Optional[ConfigSettings] = None, storage_settings: Optional[StorageSettings] = None, workflow_settings: Optional[WorkflowSettings] = None, deployment_settings: Optional[DeploymentSettings] = None, ...
Create the workflow API. Note that if provided, this also changes to the provided workdir. It will change back to the previous working directory when the workflow API object is deleted. Arguments --------- config_settings: ConfigSettings -- The config settings for the workflow....
workflow
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def print_exception(self, ex: Exception): """Print an exception during workflow execution in a human readable way (with adjusted line numbers for exceptions raised in Snakefiles and stack traces that hide Snakemake internals for better readability). Arguments --------- e...
Print an exception during workflow execution in a human readable way (with adjusted line numbers for exceptions raised in Snakefiles and stack traces that hide Snakemake internals for better readability). Arguments --------- ex: Exception -- The exception to print.
print_exception
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def dag( self, dag_settings: Optional[DAGSettings] = None, ): """Create a DAG API. Arguments --------- dag_settings: DAGSettings -- The DAG settings for the DAG API. """ if dag_settings is None: dag_settings = DAGSettings() return...
Create a DAG API. Arguments --------- dag_settings: DAGSettings -- The DAG settings for the DAG API.
dag
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def lint(self, json: bool = False): """Lint the workflow. Arguments --------- json: bool -- Whether to print the linting results as JSON. Returns ------- True if any lints were printed """ workflow = self._get_workflow(check_envvars=False) ...
Lint the workflow. Arguments --------- json: bool -- Whether to print the linting results as JSON. Returns ------- True if any lints were printed
lint
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def execute_workflow( self, executor: str = "local", execution_settings: Optional[ExecutionSettings] = None, remote_execution_settings: Optional[RemoteExecutionSettings] = None, scheduling_settings: Optional[SchedulingSettings] = None, group_settings: Optional[GroupSettin...
Execute the workflow. Arguments --------- executor: str -- The executor to use. execution_settings: ExecutionSettings -- The execution settings for the workflow. resource_settings: ResourceSettings -- The resource settings for the workflow. remote_execution_settings: Rem...
execute_workflow
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def create_report( self, reporter: str = "html", report_settings: Optional[ReportSettingsBase] = None, ): """Create a report for the workflow. Arguments --------- report: Path -- The path to the report. report_stylesheet: Optional[Path] -- The path to...
Create a report for the workflow. Arguments --------- report: Path -- The path to the report. report_stylesheet: Optional[Path] -- The path to the report stylesheet. reporter: str -- report plugin to use (default: html)
create_report
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def conda_cleanup_envs(self): """Cleanup the conda environments of the workflow.""" self.workflow_api.deployment_settings.imply_deployment_method( DeploymentMethod.CONDA ) self.workflow_api._workflow.conda_cleanup_envs()
Cleanup the conda environments of the workflow.
conda_cleanup_envs
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def conda_create_envs(self): """Only create the conda environments of the workflow.""" self.workflow_api.deployment_settings.imply_deployment_method( DeploymentMethod.CONDA ) self.workflow_api._workflow.conda_create_envs()
Only create the conda environments of the workflow.
conda_create_envs
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def conda_list_envs(self): """List the conda environments of the workflow.""" self.workflow_api.deployment_settings.imply_deployment_method( DeploymentMethod.CONDA ) self.workflow_api._workflow.conda_list_envs()
List the conda environments of the workflow.
conda_list_envs
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def container_cleanup_images(self): """Cleanup the container images of the workflow.""" self.workflow_api.deployment_settings.imply_deployment_method( DeploymentMethod.APPTAINER ) self.workflow_api._workflow.container_cleanup_images()
Cleanup the container images of the workflow.
container_cleanup_images
python
snakemake/snakemake
src/snakemake/api.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/api.py
MIT
def timedelta_to_str(self, x): """Conversion of timedelta to str without fractions of seconds""" mm, ss = divmod(x.seconds, 60) hh, mm = divmod(mm, 60) s = "%d:%02d:%02d" % (hh, mm, ss) if x.days: def plural(n): return n, abs(n) != 1 and "s" or "" ...
Conversion of timedelta to str without fractions of seconds
timedelta_to_str
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def to_tsv(self, extended_fmt): """Return ``str`` with the TSV representation of this record""" def to_tsv_str(x): """Conversion of value to str for TSV (None becomes "-")""" if x is None: return "-" elif isinstance(x, float): return f...
Return ``str`` with the TSV representation of this record
to_tsv
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def to_tsv_str(x): """Conversion of value to str for TSV (None becomes "-")""" if x is None: return "-" elif isinstance(x, float): return f"{x:.2f}" else: return str(x)
Conversion of value to str for TSV (None becomes "-")
to_tsv_str
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def to_json(self, extended_fmt): """Return ``str`` with the JSON representation of this record""" import json return json.dumps( dict(zip(self.get_header(extended_fmt), self.get_benchmarks(extended_fmt))), sort_keys=True, )
Return ``str`` with the JSON representation of this record
to_json
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def benchmarked(pid=None, benchmark_record=None, interval=BENCHMARK_INTERVAL): """Measure benchmark parameters while within the context manager Yields a ``BenchmarkRecord`` with the results (values are set after leaving context). If ``pid`` is ``None`` then the PID of the current process will be used....
Measure benchmark parameters while within the context manager Yields a ``BenchmarkRecord`` with the results (values are set after leaving context). If ``pid`` is ``None`` then the PID of the current process will be used. If ``benchmark_record`` is ``None`` then a new ``BenchmarkRecord`` is created...
benchmarked
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def print_benchmark_tsv(records, file_, extended_fmt): """Write benchmark records to file-like the object""" logger.debug("Benchmarks in TSV format") print("\t".join(BenchmarkRecord.get_header(extended_fmt)), file=file_) for r in records: print(r.to_tsv(extended_fmt), file=file_)
Write benchmark records to file-like the object
print_benchmark_tsv
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def print_benchmark_jsonl(records, file_, extended_fmt): """Write benchmark records to file-like the object""" logger.debug("Benchmarks in JSONL format") for r in records: print(r.to_json(extended_fmt), file=file_)
Write benchmark records to file-like the object
print_benchmark_jsonl
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def write_benchmark_records(records, path, extended_fmt): """Write benchmark records to file at path""" with open(path, "wt") as f: if path.endswith(".jsonl"): print_benchmark_jsonl(records, f, extended_fmt) else: print_benchmark_tsv(records, f, extended_fmt)
Write benchmark records to file at path
write_benchmark_records
python
snakemake/snakemake
src/snakemake/benchmark.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/benchmark.py
MIT
def parse_consider_ancient( args: Optional[List[str]], ) -> Mapping[str, Set[Union[str, int]]]: """Parse command line arguments for marking input files as ancient. Args: args: List of RULE=INPUTITEMS pairs, where INPUTITEMS is a comma-separated list of input item names or indices (0-b...
Parse command line arguments for marking input files as ancient. Args: args: List of RULE=INPUTITEMS pairs, where INPUTITEMS is a comma-separated list of input item names or indices (0-based). Returns: A mapping of rules to sets of their ancient input items. Raises: ...
parse_consider_ancient
python
snakemake/snakemake
src/snakemake/cli.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cli.py
MIT
def generate_parser_metadata(parser, args): """Given a populated parser, generate the original command along with metadata that can be handed to a logger to use as needed. """ command = "snakemake %s" % " ".join( parser._source_to_settings["command_line"][""][1] ) metadata = args.__dict_...
Given a populated parser, generate the original command along with metadata that can be handed to a logger to use as needed.
generate_parser_metadata
python
snakemake/snakemake
src/snakemake/cli.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cli.py
MIT
def args_to_api(args, parser): """Convert argparse args to API calls.""" # handle legacy executor names if args.dryrun: args.executor = "dryrun" elif args.touch: args.executor = "touch" elif args.executor is None: args.executor = "local" if args.report: args.rep...
Convert argparse args to API calls.
args_to_api
python
snakemake/snakemake
src/snakemake/cli.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cli.py
MIT