partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
PPOModel.create_reward_encoder
Creates TF ops to track and increment recent average cumulative reward.
ml-agents/mlagents/trainers/ppo/models.py
def create_reward_encoder(): """Creates TF ops to track and increment recent average cumulative reward.""" last_reward = tf.Variable(0, name="last_reward", trainable=False, dtype=tf.float32) new_reward = tf.placeholder(shape=[], dtype=tf.float32, name='new_reward') update_reward = tf.ass...
def create_reward_encoder(): """Creates TF ops to track and increment recent average cumulative reward.""" last_reward = tf.Variable(0, name="last_reward", trainable=False, dtype=tf.float32) new_reward = tf.placeholder(shape=[], dtype=tf.float32, name='new_reward') update_reward = tf.ass...
[ "Creates", "TF", "ops", "to", "track", "and", "increment", "recent", "average", "cumulative", "reward", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L49-L54
[ "def", "create_reward_encoder", "(", ")", ":", "last_reward", "=", "tf", ".", "Variable", "(", "0", ",", "name", "=", "\"last_reward\"", ",", "trainable", "=", "False", ",", "dtype", "=", "tf", ".", "float32", ")", "new_reward", "=", "tf", ".", "placehol...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOModel.create_curiosity_encoders
Creates state encoders for current and future observations. Used for implementation of Curiosity-driven Exploration by Self-supervised Prediction See https://arxiv.org/abs/1705.05363 for more details. :return: current and future state encoder tensors.
ml-agents/mlagents/trainers/ppo/models.py
def create_curiosity_encoders(self): """ Creates state encoders for current and future observations. Used for implementation of Curiosity-driven Exploration by Self-supervised Prediction See https://arxiv.org/abs/1705.05363 for more details. :return: current and future state enc...
def create_curiosity_encoders(self): """ Creates state encoders for current and future observations. Used for implementation of Curiosity-driven Exploration by Self-supervised Prediction See https://arxiv.org/abs/1705.05363 for more details. :return: current and future state enc...
[ "Creates", "state", "encoders", "for", "current", "and", "future", "observations", ".", "Used", "for", "implementation", "of", "Curiosity", "-", "driven", "Exploration", "by", "Self", "-", "supervised", "Prediction", "See", "https", ":", "//", "arxiv", ".", "...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L56-L114
[ "def", "create_curiosity_encoders", "(", "self", ")", ":", "encoded_state_list", "=", "[", "]", "encoded_next_state_list", "=", "[", "]", "if", "self", ".", "vis_obs_size", ">", "0", ":", "self", ".", "next_visual_in", "=", "[", "]", "visual_encoders", "=", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOModel.create_inverse_model
Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_next_state: Tensor corresponding to encoded next state.
ml-agents/mlagents/trainers/ppo/models.py
def create_inverse_model(self, encoded_state, encoded_next_state): """ Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_nex...
def create_inverse_model(self, encoded_state, encoded_next_state): """ Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_nex...
[ "Creates", "inverse", "model", "TensorFlow", "ops", "for", "Curiosity", "module", ".", "Predicts", "action", "taken", "given", "current", "and", "future", "encoded", "states", ".", ":", "param", "encoded_state", ":", "Tensor", "corresponding", "to", "encoded", "...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L116-L134
[ "def", "create_inverse_model", "(", "self", ",", "encoded_state", ",", "encoded_next_state", ")", ":", "combined_input", "=", "tf", ".", "concat", "(", "[", "encoded_state", ",", "encoded_next_state", "]", ",", "axis", "=", "1", ")", "hidden", "=", "tf", "."...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOModel.create_forward_model
Creates forward model TensorFlow ops for Curiosity module. Predicts encoded future state based on encoded current state and given action. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_next_state: Tensor corresponding to encoded next state.
ml-agents/mlagents/trainers/ppo/models.py
def create_forward_model(self, encoded_state, encoded_next_state): """ Creates forward model TensorFlow ops for Curiosity module. Predicts encoded future state based on encoded current state and given action. :param encoded_state: Tensor corresponding to encoded current state. :p...
def create_forward_model(self, encoded_state, encoded_next_state): """ Creates forward model TensorFlow ops for Curiosity module. Predicts encoded future state based on encoded current state and given action. :param encoded_state: Tensor corresponding to encoded current state. :p...
[ "Creates", "forward", "model", "TensorFlow", "ops", "for", "Curiosity", "module", ".", "Predicts", "encoded", "future", "state", "based", "on", "encoded", "current", "state", "and", "given", "action", ".", ":", "param", "encoded_state", ":", "Tensor", "correspon...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L136-L151
[ "def", "create_forward_model", "(", "self", ",", "encoded_state", ",", "encoded_next_state", ")", ":", "combined_input", "=", "tf", ".", "concat", "(", "[", "encoded_state", ",", "self", ".", "selected_actions", "]", ",", "axis", "=", "1", ")", "hidden", "="...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOModel.create_ppo_optimizer
Creates training-specific Tensorflow ops for PPO models. :param probs: Current policy probabilities :param old_probs: Past policy probabilities :param value: Current value estimate :param beta: Entropy regularization strength :param entropy: Current policy entropy :param ...
ml-agents/mlagents/trainers/ppo/models.py
def create_ppo_optimizer(self, probs, old_probs, value, entropy, beta, epsilon, lr, max_step): """ Creates training-specific Tensorflow ops for PPO models. :param probs: Current policy probabilities :param old_probs: Past policy probabilities :param value: Current value estimate ...
def create_ppo_optimizer(self, probs, old_probs, value, entropy, beta, epsilon, lr, max_step): """ Creates training-specific Tensorflow ops for PPO models. :param probs: Current policy probabilities :param old_probs: Past policy probabilities :param value: Current value estimate ...
[ "Creates", "training", "-", "specific", "Tensorflow", "ops", "for", "PPO", "models", ".", ":", "param", "probs", ":", "Current", "policy", "probabilities", ":", "param", "old_probs", ":", "Past", "policy", "probabilities", ":", "param", "value", ":", "Current"...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L153-L195
[ "def", "create_ppo_optimizer", "(", "self", ",", "probs", ",", "old_probs", ",", "value", ",", "entropy", ",", "beta", ",", "epsilon", ",", "lr", ",", "max_step", ")", ":", "self", ".", "returns_holder", "=", "tf", ".", "placeholder", "(", "shape", "=", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOPolicy.evaluate
Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo object containing inputs. :return: Outputs from network as defined by self.inference_dict.
ml-agents/mlagents/trainers/ppo/policy.py
def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo object containing inputs. :return: Outputs from network as defined by self.inference_dict. """ feed_dict = {self.model.batch_size: len(brain_info.vector_o...
def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo object containing inputs. :return: Outputs from network as defined by self.inference_dict. """ feed_dict = {self.model.batch_size: len(brain_info.vector_o...
[ "Evaluates", "policy", "for", "the", "agent", "experiences", "provided", ".", ":", "param", "brain_info", ":", "BrainInfo", "object", "containing", "inputs", ".", ":", "return", ":", "Outputs", "from", "network", "as", "defined", "by", "self", ".", "inference_...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/policy.py#L63-L87
[ "def", "evaluate", "(", "self", ",", "brain_info", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "batch_size", ":", "len", "(", "brain_info", ".", "vector_observations", ")", ",", "self", ".", "model", ".", "sequence_length", ":", "1", "}",...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOPolicy.update
Updates model using buffer. :param num_sequences: Number of trajectories in batch. :param mini_batch: Experience batch. :return: Output from update process.
ml-agents/mlagents/trainers/ppo/policy.py
def update(self, mini_batch, num_sequences): """ Updates model using buffer. :param num_sequences: Number of trajectories in batch. :param mini_batch: Experience batch. :return: Output from update process. """ feed_dict = {self.model.batch_size: num_sequences, ...
def update(self, mini_batch, num_sequences): """ Updates model using buffer. :param num_sequences: Number of trajectories in batch. :param mini_batch: Experience batch. :return: Output from update process. """ feed_dict = {self.model.batch_size: num_sequences, ...
[ "Updates", "model", "using", "buffer", ".", ":", "param", "num_sequences", ":", "Number", "of", "trajectories", "in", "batch", ".", ":", "param", "mini_batch", ":", "Experience", "batch", ".", ":", "return", ":", "Output", "from", "update", "process", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/policy.py#L89-L144
[ "def", "update", "(", "self", ",", "mini_batch", ",", "num_sequences", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "batch_size", ":", "num_sequences", ",", "self", ".", "model", ".", "sequence_length", ":", "self", ".", "sequence_length", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOPolicy.get_intrinsic_rewards
Generates intrinsic reward used for Curiosity-based training. :BrainInfo curr_info: Current BrainInfo. :BrainInfo next_info: Next BrainInfo. :return: Intrinsic rewards for all agents.
ml-agents/mlagents/trainers/ppo/policy.py
def get_intrinsic_rewards(self, curr_info, next_info): """ Generates intrinsic reward used for Curiosity-based training. :BrainInfo curr_info: Current BrainInfo. :BrainInfo next_info: Next BrainInfo. :return: Intrinsic rewards for all agents. """ if self.use_curio...
def get_intrinsic_rewards(self, curr_info, next_info): """ Generates intrinsic reward used for Curiosity-based training. :BrainInfo curr_info: Current BrainInfo. :BrainInfo next_info: Next BrainInfo. :return: Intrinsic rewards for all agents. """ if self.use_curio...
[ "Generates", "intrinsic", "reward", "used", "for", "Curiosity", "-", "based", "training", ".", ":", "BrainInfo", "curr_info", ":", "Current", "BrainInfo", ".", ":", "BrainInfo", "next_info", ":", "Next", "BrainInfo", ".", ":", "return", ":", "Intrinsic", "rewa...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/policy.py#L146-L177
[ "def", "get_intrinsic_rewards", "(", "self", ",", "curr_info", ",", "next_info", ")", ":", "if", "self", ".", "use_curiosity", ":", "if", "len", "(", "curr_info", ".", "agents", ")", "==", "0", ":", "return", "[", "]", "feed_dict", "=", "{", "self", "....
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOPolicy.get_value_estimate
Generates value estimates for bootstrapping. :param brain_info: BrainInfo to be used for bootstrapping. :param idx: Index in BrainInfo of agent. :return: Value estimate.
ml-agents/mlagents/trainers/ppo/policy.py
def get_value_estimate(self, brain_info, idx): """ Generates value estimates for bootstrapping. :param brain_info: BrainInfo to be used for bootstrapping. :param idx: Index in BrainInfo of agent. :return: Value estimate. """ feed_dict = {self.model.batch_size: 1, ...
def get_value_estimate(self, brain_info, idx): """ Generates value estimates for bootstrapping. :param brain_info: BrainInfo to be used for bootstrapping. :param idx: Index in BrainInfo of agent. :return: Value estimate. """ feed_dict = {self.model.batch_size: 1, ...
[ "Generates", "value", "estimates", "for", "bootstrapping", ".", ":", "param", "brain_info", ":", "BrainInfo", "to", "be", "used", "for", "bootstrapping", ".", ":", "param", "idx", ":", "Index", "in", "BrainInfo", "of", "agent", ".", ":", "return", ":", "Va...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/policy.py#L179-L199
[ "def", "get_value_estimate", "(", "self", ",", "brain_info", ",", "idx", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "batch_size", ":", "1", ",", "self", ".", "model", ".", "sequence_length", ":", "1", "}", "for", "i", "in", "range", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOPolicy.update_reward
Updates reward value for policy. :param new_reward: New reward to save.
ml-agents/mlagents/trainers/ppo/policy.py
def update_reward(self, new_reward): """ Updates reward value for policy. :param new_reward: New reward to save. """ self.sess.run(self.model.update_reward, feed_dict={self.model.new_reward: new_reward})
def update_reward(self, new_reward): """ Updates reward value for policy. :param new_reward: New reward to save. """ self.sess.run(self.model.update_reward, feed_dict={self.model.new_reward: new_reward})
[ "Updates", "reward", "value", "for", "policy", ".", ":", "param", "new_reward", ":", "New", "reward", "to", "save", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/policy.py#L208-L214
[ "def", "update_reward", "(", "self", ",", "new_reward", ")", ":", "self", ".", "sess", ".", "run", "(", "self", ".", "model", ".", "update_reward", ",", "feed_dict", "=", "{", "self", ".", "model", ".", "new_reward", ":", "new_reward", "}", ")" ]
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCTrainer.add_experiences
Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param take_action_outputs: The outputs ...
ml-agents/mlagents/trainers/bc/trainer.py
def add_experiences(self, curr_info: AllBrainInfo, next_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param...
def add_experiences(self, curr_info: AllBrainInfo, next_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param...
[ "Adds", "experiences", "to", "each", "agent", "s", "experience", "history", ".", ":", "param", "curr_info", ":", "Current", "AllBrainInfo", "(", "Dictionary", "of", "all", "current", "brains", "and", "corresponding", "BrainInfo", ")", ".", ":", "param", "next_...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/trainer.py#L87-L114
[ "def", "add_experiences", "(", "self", ",", "curr_info", ":", "AllBrainInfo", ",", "next_info", ":", "AllBrainInfo", ",", "take_action_outputs", ")", ":", "# Used to collect information about student performance.", "info_student", "=", "curr_info", "[", "self", ".", "br...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCTrainer.process_experiences
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllBrainInfo :param next_info: Next AllBrainInfo
ml-agents/mlagents/trainers/bc/trainer.py
def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllB...
def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllB...
[ "Checks", "agent", "histories", "for", "processing", "condition", "and", "processes", "them", "as", "necessary", ".", "Processing", "involves", "calculating", "value", "and", "advantage", "targets", "for", "model", "updating", "step", ".", ":", "param", "current_i...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/trainer.py#L116-L132
[ "def", "process_experiences", "(", "self", ",", "current_info", ":", "AllBrainInfo", ",", "next_info", ":", "AllBrainInfo", ")", ":", "info_student", "=", "next_info", "[", "self", ".", "brain_name", "]", "for", "l", "in", "range", "(", "len", "(", "info_stu...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCTrainer.end_episode
A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets.
ml-agents/mlagents/trainers/bc/trainer.py
def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.evaluation_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 ...
def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.evaluation_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 ...
[ "A", "signal", "that", "the", "Episode", "has", "ended", ".", "The", "buffer", "must", "be", "reset", ".", "Get", "only", "called", "when", "the", "academy", "resets", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/trainer.py#L134-L143
[ "def", "end_episode", "(", "self", ")", ":", "self", ".", "evaluation_buffer", ".", "reset_local_buffers", "(", ")", "for", "agent_id", "in", "self", ".", "cumulative_rewards", ":", "self", ".", "cumulative_rewards", "[", "agent_id", "]", "=", "0", "for", "a...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCTrainer.update_policy
Updates the policy.
ml-agents/mlagents/trainers/bc/trainer.py
def update_policy(self): """ Updates the policy. """ self.demonstration_buffer.update_buffer.shuffle() batch_losses = [] num_batches = min(len(self.demonstration_buffer.update_buffer['actions']) // self.n_sequences, self.batches_per_epoch) ...
def update_policy(self): """ Updates the policy. """ self.demonstration_buffer.update_buffer.shuffle() batch_losses = [] num_batches = min(len(self.demonstration_buffer.update_buffer['actions']) // self.n_sequences, self.batches_per_epoch) ...
[ "Updates", "the", "policy", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/trainer.py#L152-L171
[ "def", "update_policy", "(", "self", ")", ":", "self", ".", "demonstration_buffer", ".", "update_buffer", ".", "shuffle", "(", ")", "batch_losses", "=", "[", "]", "num_batches", "=", "min", "(", "len", "(", "self", ".", "demonstration_buffer", ".", "update_b...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_global_steps
Creates TF ops to track and increment global training step.
ml-agents/mlagents/trainers/models.py
def create_global_steps(): """Creates TF ops to track and increment global training step.""" global_step = tf.Variable(0, name="global_step", trainable=False, dtype=tf.int32) increment_step = tf.assign(global_step, tf.add(global_step, 1)) return global_step, increment_step
def create_global_steps(): """Creates TF ops to track and increment global training step.""" global_step = tf.Variable(0, name="global_step", trainable=False, dtype=tf.int32) increment_step = tf.assign(global_step, tf.add(global_step, 1)) return global_step, increment_step
[ "Creates", "TF", "ops", "to", "track", "and", "increment", "global", "training", "step", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L43-L47
[ "def", "create_global_steps", "(", ")", ":", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "name", "=", "\"global_step\"", ",", "trainable", "=", "False", ",", "dtype", "=", "tf", ".", "int32", ")", "increment_step", "=", "tf", ".", "assign",...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_visual_input
Creates image input op. :param camera_parameters: Parameters for visual observation from BrainInfo. :param name: Desired name of input op. :return: input op.
ml-agents/mlagents/trainers/models.py
def create_visual_input(camera_parameters, name): """ Creates image input op. :param camera_parameters: Parameters for visual observation from BrainInfo. :param name: Desired name of input op. :return: input op. """ o_size_h = camera_parameters['height'] o...
def create_visual_input(camera_parameters, name): """ Creates image input op. :param camera_parameters: Parameters for visual observation from BrainInfo. :param name: Desired name of input op. :return: input op. """ o_size_h = camera_parameters['height'] o...
[ "Creates", "image", "input", "op", ".", ":", "param", "camera_parameters", ":", "Parameters", "for", "visual", "observation", "from", "BrainInfo", ".", ":", "param", "name", ":", "Desired", "name", "of", "input", "op", ".", ":", "return", ":", "input", "op...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L55-L73
[ "def", "create_visual_input", "(", "camera_parameters", ",", "name", ")", ":", "o_size_h", "=", "camera_parameters", "[", "'height'", "]", "o_size_w", "=", "camera_parameters", "[", "'width'", "]", "bw", "=", "camera_parameters", "[", "'blackAndWhite'", "]", "if",...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_vector_input
Creates ops for vector observation input. :param name: Name of the placeholder op. :param vec_obs_size: Size of stacked vector observation. :return:
ml-agents/mlagents/trainers/models.py
def create_vector_input(self, name='vector_observation'): """ Creates ops for vector observation input. :param name: Name of the placeholder op. :param vec_obs_size: Size of stacked vector observation. :return: """ self.vector_in = tf.placeholder(shape=[None, self...
def create_vector_input(self, name='vector_observation'): """ Creates ops for vector observation input. :param name: Name of the placeholder op. :param vec_obs_size: Size of stacked vector observation. :return: """ self.vector_in = tf.placeholder(shape=[None, self...
[ "Creates", "ops", "for", "vector", "observation", "input", ".", ":", "param", "name", ":", "Name", "of", "the", "placeholder", "op", ".", ":", "param", "vec_obs_size", ":", "Size", "of", "stacked", "vector", "observation", ".", ":", "return", ":" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L75-L99
[ "def", "create_vector_input", "(", "self", ",", "name", "=", "'vector_observation'", ")", ":", "self", ".", "vector_in", "=", "tf", ".", "placeholder", "(", "shape", "=", "[", "None", ",", "self", ".", "vec_obs_size", "]", ",", "dtype", "=", "tf", ".", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_vector_observation_encoder
Builds a set of hidden state encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: Graph scope for the encoder ops. :param observation_input: Input vector. :param h_size: Hidden layer size. :param activation: What type of activation function t...
ml-agents/mlagents/trainers/models.py
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope, reuse): """ Builds a set of hidden state encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: Graph scope for th...
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope, reuse): """ Builds a set of hidden state encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: Graph scope for th...
[ "Builds", "a", "set", "of", "hidden", "state", "encoders", ".", ":", "param", "reuse", ":", "Whether", "to", "re", "-", "use", "the", "weights", "within", "the", "same", "scope", ".", ":", "param", "scope", ":", "Graph", "scope", "for", "the", "encoder...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L112-L131
[ "def", "create_vector_observation_encoder", "(", "observation_input", ",", "h_size", ",", "activation", ",", "num_layers", ",", "scope", ",", "reuse", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "hidden", "=", "observation_input", "for...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_visual_observation_encoder
Builds a set of visual (CNN) encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: The scope of the graph within which to create the ops. :param image_input: The placeholder for the image input to use. :param h_size: Hidden layer size. :param ...
ml-agents/mlagents/trainers/models.py
def create_visual_observation_encoder(self, image_input, h_size, activation, num_layers, scope, reuse): """ Builds a set of visual (CNN) encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: The scope of the g...
def create_visual_observation_encoder(self, image_input, h_size, activation, num_layers, scope, reuse): """ Builds a set of visual (CNN) encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: The scope of the g...
[ "Builds", "a", "set", "of", "visual", "(", "CNN", ")", "encoders", ".", ":", "param", "reuse", ":", "Whether", "to", "re", "-", "use", "the", "weights", "within", "the", "same", "scope", ".", ":", "param", "scope", ":", "The", "scope", "of", "the", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L133-L155
[ "def", "create_visual_observation_encoder", "(", "self", ",", "image_input", ",", "h_size", ",", "activation", ",", "num_layers", ",", "scope", ",", "reuse", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "conv1", "=", "tf", ".", "l...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_discrete_action_masking_layer
Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension [None x total_number_of_action] :param action_size: A list containing the number of possible ...
ml-agents/mlagents/trainers/models.py
def create_discrete_action_masking_layer(all_logits, action_masks, action_size): """ Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension ...
def create_discrete_action_masking_layer(all_logits, action_masks, action_size): """ Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension ...
[ "Creates", "a", "masking", "layer", "for", "the", "discrete", "actions", ":", "param", "all_logits", ":", "The", "concatenated", "unnormalized", "action", "probabilities", "for", "all", "branches", ":", "param", "action_masks", ":", "The", "mask", "for", "the", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L158-L175
[ "def", "create_discrete_action_masking_layer", "(", "all_logits", ",", "action_masks", ",", "action_size", ")", ":", "action_idx", "=", "[", "0", "]", "+", "list", "(", "np", ".", "cumsum", "(", "action_size", ")", ")", "branches_logits", "=", "[", "all_logits...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_observation_streams
Creates encoding stream for observations. :param num_streams: Number of streams to create. :param h_size: Size of hidden linear layers in stream. :param num_layers: Number of hidden linear layers in stream. :return: List of encoded streams.
ml-agents/mlagents/trainers/models.py
def create_observation_streams(self, num_streams, h_size, num_layers): """ Creates encoding stream for observations. :param num_streams: Number of streams to create. :param h_size: Size of hidden linear layers in stream. :param num_layers: Number of hidden linear layers in stream...
def create_observation_streams(self, num_streams, h_size, num_layers): """ Creates encoding stream for observations. :param num_streams: Number of streams to create. :param h_size: Size of hidden linear layers in stream. :param num_layers: Number of hidden linear layers in stream...
[ "Creates", "encoding", "stream", "for", "observations", ".", ":", "param", "num_streams", ":", "Number", "of", "streams", "to", "create", ".", ":", "param", "h_size", ":", "Size", "of", "hidden", "linear", "layers", "in", "stream", ".", ":", "param", "num_...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L177-L225
[ "def", "create_observation_streams", "(", "self", ",", "num_streams", ",", "h_size", ",", "num_layers", ")", ":", "brain", "=", "self", ".", "brain", "activation_fn", "=", "self", ".", "swish", "self", ".", "visual_in", "=", "[", "]", "for", "i", "in", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_recurrent_encoder
Builds a recurrent encoder for either state or observations (LSTM). :param sequence_length: Length of sequence to unroll. :param input_state: The input tensor to the LSTM cell. :param memory_in: The input memory to the LSTM cell. :param name: The scope of the LSTM cell.
ml-agents/mlagents/trainers/models.py
def create_recurrent_encoder(input_state, memory_in, sequence_length, name='lstm'): """ Builds a recurrent encoder for either state or observations (LSTM). :param sequence_length: Length of sequence to unroll. :param input_state: The input tensor to the LSTM cell. :param memory_i...
def create_recurrent_encoder(input_state, memory_in, sequence_length, name='lstm'): """ Builds a recurrent encoder for either state or observations (LSTM). :param sequence_length: Length of sequence to unroll. :param input_state: The input tensor to the LSTM cell. :param memory_i...
[ "Builds", "a", "recurrent", "encoder", "for", "either", "state", "or", "observations", "(", "LSTM", ")", ".", ":", "param", "sequence_length", ":", "Length", "of", "sequence", "to", "unroll", ".", ":", "param", "input_state", ":", "The", "input", "tensor", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L228-L249
[ "def", "create_recurrent_encoder", "(", "input_state", ",", "memory_in", ",", "sequence_length", ",", "name", "=", "'lstm'", ")", ":", "s_size", "=", "input_state", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", "]", "m_size", "=", "memory...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_cc_actor_critic
Creates Continuous control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers.
ml-agents/mlagents/trainers/models.py
def create_cc_actor_critic(self, h_size, num_layers): """ Creates Continuous control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. """ hidden_streams = self.create_observation_streams(2, h_size, num_lay...
def create_cc_actor_critic(self, h_size, num_layers): """ Creates Continuous control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. """ hidden_streams = self.create_observation_streams(2, h_size, num_lay...
[ "Creates", "Continuous", "control", "actor", "-", "critic", "model", ".", ":", "param", "h_size", ":", "Size", "of", "hidden", "linear", "layers", ".", ":", "param", "num_layers", ":", "Number", "of", "hidden", "linear", "layers", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L251-L308
[ "def", "create_cc_actor_critic", "(", "self", ",", "h_size", ",", "num_layers", ")", ":", "hidden_streams", "=", "self", ".", "create_observation_streams", "(", "2", ",", "h_size", ",", "num_layers", ")", "if", "self", ".", "use_recurrent", ":", "self", ".", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
LearningModel.create_dc_actor_critic
Creates Discrete control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers.
ml-agents/mlagents/trainers/models.py
def create_dc_actor_critic(self, h_size, num_layers): """ Creates Discrete control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. """ hidden_streams = self.create_observation_streams(1, h_size, num_layer...
def create_dc_actor_critic(self, h_size, num_layers): """ Creates Discrete control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. """ hidden_streams = self.create_observation_streams(1, h_size, num_layer...
[ "Creates", "Discrete", "control", "actor", "-", "critic", "model", ".", ":", "param", "h_size", ":", "Size", "of", "hidden", "linear", "layers", ".", ":", "param", "num_layers", ":", "Number", "of", "hidden", "linear", "layers", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L310-L380
[ "def", "create_dc_actor_critic", "(", "self", ",", "h_size", ",", "num_layers", ")", ":", "hidden_streams", "=", "self", ".", "create_observation_streams", "(", "1", ",", "h_size", ",", "num_layers", ")", "hidden", "=", "hidden_streams", "[", "0", "]", "if", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
OnlineBCTrainer.add_experiences
Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param take_action_outputs: The outputs ...
ml-agents/mlagents/trainers/bc/online_trainer.py
def add_experiences(self, curr_info: AllBrainInfo, next_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param...
def add_experiences(self, curr_info: AllBrainInfo, next_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param...
[ "Adds", "experiences", "to", "each", "agent", "s", "experience", "history", ".", ":", "param", "curr_info", ":", "Current", "AllBrainInfo", "(", "Dictionary", "of", "all", "current", "brains", "and", "corresponding", "BrainInfo", ")", ".", ":", "param", "next_...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/online_trainer.py#L47-L97
[ "def", "add_experiences", "(", "self", ",", "curr_info", ":", "AllBrainInfo", ",", "next_info", ":", "AllBrainInfo", ",", "take_action_outputs", ")", ":", "# Used to collect teacher experience into training buffer", "info_teacher", "=", "curr_info", "[", "self", ".", "b...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
OnlineBCTrainer.process_experiences
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllBrainInfo :param next_info: Next AllBrainInfo
ml-agents/mlagents/trainers/bc/online_trainer.py
def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllB...
def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllB...
[ "Checks", "agent", "histories", "for", "processing", "condition", "and", "processes", "them", "as", "necessary", ".", "Processing", "involves", "calculating", "value", "and", "advantage", "targets", "for", "model", "updating", "step", ".", ":", "param", "current_i...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/online_trainer.py#L99-L117
[ "def", "process_experiences", "(", "self", ",", "current_info", ":", "AllBrainInfo", ",", "next_info", ":", "AllBrainInfo", ")", ":", "info_teacher", "=", "next_info", "[", "self", ".", "brain_to_imitate", "]", "for", "l", "in", "range", "(", "len", "(", "in...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
flatten
Yield items from any nested iterable; see REF.
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
def flatten(items,enter=lambda x:isinstance(x, list)): # http://stackoverflow.com/a/40857703 # https://github.com/ctmakro/canton/blob/master/canton/misc.py """Yield items from any nested iterable; see REF.""" for x in items: if enter(x): yield from flatten(x) else: ...
def flatten(items,enter=lambda x:isinstance(x, list)): # http://stackoverflow.com/a/40857703 # https://github.com/ctmakro/canton/blob/master/canton/misc.py """Yield items from any nested iterable; see REF.""" for x in items: if enter(x): yield from flatten(x) else: ...
[ "Yield", "items", "from", "any", "nested", "iterable", ";", "see", "REF", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L496-L504
[ "def", "flatten", "(", "items", ",", "enter", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "list", ")", ")", ":", "# http://stackoverflow.com/a/40857703", "# https://github.com/ctmakro/canton/blob/master/canton/misc.py", "for", "x", "in", "items", ":", "if"...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
replace_strings_in_list
A value in replace_with_strings can be either single string or list of strings
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
def replace_strings_in_list(array_of_strigs, replace_with_strings): "A value in replace_with_strings can be either single string or list of strings" potentially_nested_list = [replace_with_strings.get(s) or s for s in array_of_strigs] return list(flatten(potentially_nested_list))
def replace_strings_in_list(array_of_strigs, replace_with_strings): "A value in replace_with_strings can be either single string or list of strings" potentially_nested_list = [replace_with_strings.get(s) or s for s in array_of_strigs] return list(flatten(potentially_nested_list))
[ "A", "value", "in", "replace_with_strings", "can", "be", "either", "single", "string", "or", "list", "of", "strings" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L506-L509
[ "def", "replace_strings_in_list", "(", "array_of_strigs", ",", "replace_with_strings", ")", ":", "potentially_nested_list", "=", "[", "replace_with_strings", ".", "get", "(", "s", ")", "or", "s", "for", "s", "in", "array_of_strigs", "]", "return", "list", "(", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
remove_duplicates_from_list
Preserves the order of elements in the list
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
def remove_duplicates_from_list(array): "Preserves the order of elements in the list" output = [] unique = set() for a in array: if a not in unique: unique.add(a) output.append(a) return output
def remove_duplicates_from_list(array): "Preserves the order of elements in the list" output = [] unique = set() for a in array: if a not in unique: unique.add(a) output.append(a) return output
[ "Preserves", "the", "order", "of", "elements", "in", "the", "list" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L511-L519
[ "def", "remove_duplicates_from_list", "(", "array", ")", ":", "output", "=", "[", "]", "unique", "=", "set", "(", ")", "for", "a", "in", "array", ":", "if", "a", "not", "in", "unique", ":", "unique", ".", "add", "(", "a", ")", "output", ".", "appen...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
pool_to_HW
Convert from NHWC|NCHW => HW
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == 'NCHW': return [shape[2], shape[3]] return [shape[1], shape[2]]
def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == 'NCHW': return [shape[2], shape[3]] return [shape[1], shape[2]]
[ "Convert", "from", "NHWC|NCHW", "=", ">", "HW" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L523-L530
[ "def", "pool_to_HW", "(", "shape", ",", "data_frmt", ")", ":", "if", "len", "(", "shape", ")", "!=", "4", ":", "return", "shape", "# Not NHWC|NCHW, return as is", "if", "data_frmt", "==", "'NCHW'", ":", "return", "[", "shape", "[", "2", "]", ",", "shape"...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
convert
Converts a TensorFlow model into a Barracuda model. :param source_file: The TensorFlow Model :param target_file: The name of the file the converted model will be saved to :param trim_unused_by_output: The regexp to match output nodes to remain in the model. All other uconnected nodes will be removed. :p...
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
def convert(source_file, target_file, trim_unused_by_output="", verbose=False, compress_f16=False): """ Converts a TensorFlow model into a Barracuda model. :param source_file: The TensorFlow Model :param target_file: The name of the file the converted model will be saved to :param trim_unused_by_out...
def convert(source_file, target_file, trim_unused_by_output="", verbose=False, compress_f16=False): """ Converts a TensorFlow model into a Barracuda model. :param source_file: The TensorFlow Model :param target_file: The name of the file the converted model will be saved to :param trim_unused_by_out...
[ "Converts", "a", "TensorFlow", "model", "into", "a", "Barracuda", "model", ".", ":", "param", "source_file", ":", "The", "TensorFlow", "Model", ":", "param", "target_file", ":", "The", "name", "of", "the", "file", "the", "converted", "model", "will", "be", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L901-L1034
[ "def", "convert", "(", "source_file", ",", "target_file", ",", "trim_unused_by_output", "=", "\"\"", ",", "verbose", "=", "False", ",", "compress_f16", "=", "False", ")", ":", "if", "(", "type", "(", "verbose", ")", "==", "bool", ")", ":", "args", "=", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
demo_to_buffer
Loads demonstration file and uses it to fill training buffer. :param file_path: Location of demonstration file (.demo). :param sequence_length: Length of trajectories to fill buffer. :return:
ml-agents/mlagents/trainers/demo_loader.py
def demo_to_buffer(file_path, sequence_length): """ Loads demonstration file and uses it to fill training buffer. :param file_path: Location of demonstration file (.demo). :param sequence_length: Length of trajectories to fill buffer. :return: """ brain_params, brain_infos, _ = load_demonstr...
def demo_to_buffer(file_path, sequence_length): """ Loads demonstration file and uses it to fill training buffer. :param file_path: Location of demonstration file (.demo). :param sequence_length: Length of trajectories to fill buffer. :return: """ brain_params, brain_infos, _ = load_demonstr...
[ "Loads", "demonstration", "file", "and", "uses", "it", "to", "fill", "training", "buffer", ".", ":", "param", "file_path", ":", "Location", "of", "demonstration", "file", "(", ".", "demo", ")", ".", ":", "param", "sequence_length", ":", "Length", "of", "tr...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/demo_loader.py#L39-L48
[ "def", "demo_to_buffer", "(", "file_path", ",", "sequence_length", ")", ":", "brain_params", ",", "brain_infos", ",", "_", "=", "load_demonstration", "(", "file_path", ")", "demo_buffer", "=", "make_demo_buffer", "(", "brain_infos", ",", "brain_params", ",", "sequ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
load_demonstration
Loads and parses a demonstration file. :param file_path: Location of demonstration file (.demo). :return: BrainParameter and list of BrainInfos containing demonstration data.
ml-agents/mlagents/trainers/demo_loader.py
def load_demonstration(file_path): """ Loads and parses a demonstration file. :param file_path: Location of demonstration file (.demo). :return: BrainParameter and list of BrainInfos containing demonstration data. """ # First 32 bytes of file dedicated to meta-data. INITIAL_POS = 33 if...
def load_demonstration(file_path): """ Loads and parses a demonstration file. :param file_path: Location of demonstration file (.demo). :return: BrainParameter and list of BrainInfos containing demonstration data. """ # First 32 bytes of file dedicated to meta-data. INITIAL_POS = 33 if...
[ "Loads", "and", "parses", "a", "demonstration", "file", ".", ":", "param", "file_path", ":", "Location", "of", "demonstration", "file", "(", ".", "demo", ")", ".", ":", "return", ":", "BrainParameter", "and", "list", "of", "BrainInfos", "containing", "demons...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/demo_loader.py#L51-L94
[ "def", "load_demonstration", "(", "file_path", ")", ":", "# First 32 bytes of file dedicated to meta-data.", "INITIAL_POS", "=", "33", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "raise", "FileNotFoundError", "(", "\"The demonstration fi...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
TrainerController._save_model
Saves current model to checkpoint folder. :param steps: Current number of steps in training process. :param saver: Tensorflow saver for session.
ml-agents/mlagents/trainers/trainer_controller.py
def _save_model(self, steps=0): """ Saves current model to checkpoint folder. :param steps: Current number of steps in training process. :param saver: Tensorflow saver for session. """ for brain_name in self.trainers.keys(): self.trainers[brain_name].save_mode...
def _save_model(self, steps=0): """ Saves current model to checkpoint folder. :param steps: Current number of steps in training process. :param saver: Tensorflow saver for session. """ for brain_name in self.trainers.keys(): self.trainers[brain_name].save_mode...
[ "Saves", "current", "model", "to", "checkpoint", "folder", ".", ":", "param", "steps", ":", "Current", "number", "of", "steps", "in", "training", "process", ".", ":", "param", "saver", ":", "Tensorflow", "saver", "for", "session", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L91-L99
[ "def", "_save_model", "(", "self", ",", "steps", "=", "0", ")", ":", "for", "brain_name", "in", "self", ".", "trainers", ".", "keys", "(", ")", ":", "self", ".", "trainers", "[", "brain_name", "]", ".", "save_model", "(", ")", "self", ".", "logger", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
TrainerController._write_training_metrics
Write all CSV metrics :return:
ml-agents/mlagents/trainers/trainer_controller.py
def _write_training_metrics(self): """ Write all CSV metrics :return: """ for brain_name in self.trainers.keys(): if brain_name in self.trainer_metrics: self.trainers[brain_name].write_training_metrics()
def _write_training_metrics(self): """ Write all CSV metrics :return: """ for brain_name in self.trainers.keys(): if brain_name in self.trainer_metrics: self.trainers[brain_name].write_training_metrics()
[ "Write", "all", "CSV", "metrics", ":", "return", ":" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L106-L113
[ "def", "_write_training_metrics", "(", "self", ")", ":", "for", "brain_name", "in", "self", ".", "trainers", ".", "keys", "(", ")", ":", "if", "brain_name", "in", "self", ".", "trainer_metrics", ":", "self", ".", "trainers", "[", "brain_name", "]", ".", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
TrainerController._export_graph
Exports latest saved models to .nn format for Unity embedding.
ml-agents/mlagents/trainers/trainer_controller.py
def _export_graph(self): """ Exports latest saved models to .nn format for Unity embedding. """ for brain_name in self.trainers.keys(): self.trainers[brain_name].export_model()
def _export_graph(self): """ Exports latest saved models to .nn format for Unity embedding. """ for brain_name in self.trainers.keys(): self.trainers[brain_name].export_model()
[ "Exports", "latest", "saved", "models", "to", ".", "nn", "format", "for", "Unity", "embedding", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L115-L120
[ "def", "_export_graph", "(", "self", ")", ":", "for", "brain_name", "in", "self", ".", "trainers", ".", "keys", "(", ")", ":", "self", ".", "trainers", "[", "brain_name", "]", ".", "export_model", "(", ")" ]
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
TrainerController.initialize_trainers
Initialization of the trainers :param trainer_config: The configurations of the trainers
ml-agents/mlagents/trainers/trainer_controller.py
def initialize_trainers(self, trainer_config: Dict[str, Dict[str, str]]): """ Initialization of the trainers :param trainer_config: The configurations of the trainers """ trainer_parameters_dict = {} for brain_name in self.external_brains: trainer_parameters =...
def initialize_trainers(self, trainer_config: Dict[str, Dict[str, str]]): """ Initialization of the trainers :param trainer_config: The configurations of the trainers """ trainer_parameters_dict = {} for brain_name in self.external_brains: trainer_parameters =...
[ "Initialization", "of", "the", "trainers", ":", "param", "trainer_config", ":", "The", "configurations", "of", "the", "trainers" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L122-L169
[ "def", "initialize_trainers", "(", "self", ",", "trainer_config", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ")", ":", "trainer_parameters_dict", "=", "{", "}", "for", "brain_name", "in", "self", ".", "external_brains", ":", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
TrainerController._reset_env
Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment.
ml-agents/mlagents/trainers/trainer_controller.py
def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. """ if self.meta_curriculum is not None: return env.reset(train_mode=self.fast_simulatio...
def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. """ if self.meta_curriculum is not None: return env.reset(train_mode=self.fast_simulatio...
[ "Resets", "the", "environment", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L183-L193
[ "def", "_reset_env", "(", "self", ",", "env", ":", "BaseUnityEnvironment", ")", ":", "if", "self", ".", "meta_curriculum", "is", "not", "None", ":", "return", "env", ".", "reset", "(", "train_mode", "=", "self", ".", "fast_simulation", ",", "config", "=", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
SocketCommunicator.close
Sends a shutdown signal to the unity environment, and closes the socket connection.
ml-agents-envs/mlagents/envs/socket_communicator.py
def close(self): """ Sends a shutdown signal to the unity environment, and closes the socket connection. """ if self._socket is not None and self._conn is not None: message_input = UnityMessage() message_input.header.status = 400 self._communicator_sen...
def close(self): """ Sends a shutdown signal to the unity environment, and closes the socket connection. """ if self._socket is not None and self._conn is not None: message_input = UnityMessage() message_input.header.status = 400 self._communicator_sen...
[ "Sends", "a", "shutdown", "signal", "to", "the", "unity", "environment", "and", "closes", "the", "socket", "connection", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/socket_communicator.py#L84-L97
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_socket", "is", "not", "None", "and", "self", ".", "_conn", "is", "not", "None", ":", "message_input", "=", "UnityMessage", "(", ")", "message_input", ".", "header", ".", "status", "=", "400", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
fuse_batchnorm_weights
float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a;
ml-agents/mlagents/trainers/barracuda.py
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): # https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp """ float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ...
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): # https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp """ float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ...
[ "float", "sqrt_var", "=", "sqrt", "(", "var_data", "[", "i", "]", ")", ";", "a_data", "[", "i", "]", "=", "bias_data", "[", "i", "]", "-", "slope_data", "[", "i", "]", "*", "mean_data", "[", "i", "]", "/", "sqrt_var", ";", "b_data", "[", "i", "...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/barracuda.py#L63-L73
[ "def", "fuse_batchnorm_weights", "(", "gamma", ",", "beta", ",", "mean", ",", "var", ",", "epsilon", ")", ":", "# https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp", "scale", "=", "gamma", "/", "np", ".", "sqrt", "(", "var", "+", "epsilon", ")", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
rnn
- Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi)
ml-agents/mlagents/trainers/barracuda.py
def rnn(name, input, state, kernel, bias, new_state, number_of_gates = 2): ''' - Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) ''' nn = Build(name) nn.tanh( nn.mad(kernel=kernel, bias=bias, x=nn.concat(input, state)), out=new_state); return nn.layers;
def rnn(name, input, state, kernel, bias, new_state, number_of_gates = 2): ''' - Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) ''' nn = Build(name) nn.tanh( nn.mad(kernel=kernel, bias=bias, x=nn.concat(input, state)), out=new_state); return nn.layers;
[ "-", "Ht", "=", "f", "(", "Xt", "*", "Wi", "+", "Ht_1", "*", "Ri", "+", "Wbi", "+", "Rbi", ")" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/barracuda.py#L309-L318
[ "def", "rnn", "(", "name", ",", "input", ",", "state", ",", "kernel", ",", "bias", ",", "new_state", ",", "number_of_gates", "=", "2", ")", ":", "nn", "=", "Build", "(", "name", ")", "nn", ".", "tanh", "(", "nn", ".", "mad", "(", "kernel", "=", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
gru
- zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz) - rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr) - ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh) - Ht = (1-zt).ht + zt.Ht_1
ml-agents/mlagents/trainers/barracuda.py
def gru(name, input, state, kernel_r, kernel_u, kernel_c, bias_r, bias_u, bias_c, new_state, number_of_gates = 2): ''' - zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz) - rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr) - ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh) - Ht = (1-zt).ht + zt.Ht_1 ''' ...
def gru(name, input, state, kernel_r, kernel_u, kernel_c, bias_r, bias_u, bias_c, new_state, number_of_gates = 2): ''' - zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz) - rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr) - ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh) - Ht = (1-zt).ht + zt.Ht_1 ''' ...
[ "-", "zt", "=", "f", "(", "Xt", "*", "Wz", "+", "Ht_1", "*", "Rz", "+", "Wbz", "+", "Rbz", ")", "-", "rt", "=", "f", "(", "Xt", "*", "Wr", "+", "Ht_1", "*", "Rr", "+", "Wbr", "+", "Rbr", ")", "-", "ht", "=", "g", "(", "Xt", "*", "Wh",...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/barracuda.py#L320-L345
[ "def", "gru", "(", "name", ",", "input", ",", "state", ",", "kernel_r", ",", "kernel_u", ",", "kernel_c", ",", "bias_r", ",", "bias_u", ",", "bias_c", ",", "new_state", ",", "number_of_gates", "=", "2", ")", ":", "nn", "=", "Build", "(", "name", ")",...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
lstm
Full: - it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi) - ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf) - ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc) - Ct = ft . Ct_1 + it . ct - ot = f(Xt*Wo + Ht_1*Ro + Po . Ct + Wbo + Rbo) - Ht = ot . h(Ct)
ml-agents/mlagents/trainers/barracuda.py
def lstm(name, input, state_c, state_h, kernel_i, kernel_j, kernel_f, kernel_o, bias_i, bias_j, bias_f, bias_o, new_state_c, new_state_h): ''' Full: - it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi) - ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf) - ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc) - Ct = ft . ...
def lstm(name, input, state_c, state_h, kernel_i, kernel_j, kernel_f, kernel_o, bias_i, bias_j, bias_f, bias_o, new_state_c, new_state_h): ''' Full: - it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi) - ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf) - ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc) - Ct = ft . ...
[ "Full", ":", "-", "it", "=", "f", "(", "Xt", "*", "Wi", "+", "Ht_1", "*", "Ri", "+", "Pi", ".", "Ct_1", "+", "Wbi", "+", "Rbi", ")", "-", "ft", "=", "f", "(", "Xt", "*", "Wf", "+", "Ht_1", "*", "Rf", "+", "Pf", ".", "Ct_1", "+", "Wbf", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/barracuda.py#L347-L383
[ "def", "lstm", "(", "name", ",", "input", ",", "state_c", ",", "state_h", ",", "kernel_i", ",", "kernel_j", ",", "kernel_f", ",", "kernel_o", ",", "bias_i", ",", "bias_j", ",", "bias_f", ",", "bias_o", ",", "new_state_c", ",", "new_state_h", ")", ":", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCPolicy.evaluate
Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo input to network. :return: Results of evaluation.
ml-agents/mlagents/trainers/bc/policy.py
def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo input to network. :return: Results of evaluation. """ feed_dict = {self.model.dropout_rate: self.evaluate_rate, self.model.sequence_l...
def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo input to network. :return: Results of evaluation. """ feed_dict = {self.model.dropout_rate: self.evaluate_rate, self.model.sequence_l...
[ "Evaluates", "policy", "for", "the", "agent", "experiences", "provided", ".", ":", "param", "brain_info", ":", "BrainInfo", "input", "to", "network", ".", ":", "return", ":", "Results", "of", "evaluation", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/policy.py#L46-L61
[ "def", "evaluate", "(", "self", ",", "brain_info", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "dropout_rate", ":", "self", ".", "evaluate_rate", ",", "self", ".", "model", ".", "sequence_length", ":", "1", "}", "feed_dict", "=", "self", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BCPolicy.update
Performs update on model. :param mini_batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update.
ml-agents/mlagents/trainers/bc/policy.py
def update(self, mini_batch, num_sequences): """ Performs update on model. :param mini_batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update. """ feed_dict = {self.model.dropout_rate: self.update_rate, ...
def update(self, mini_batch, num_sequences): """ Performs update on model. :param mini_batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update. """ feed_dict = {self.model.dropout_rate: self.update_rate, ...
[ "Performs", "update", "on", "model", ".", ":", "param", "mini_batch", ":", "Batch", "of", "experiences", ".", ":", "param", "num_sequences", ":", "Number", "of", "sequences", "to", "process", ".", ":", "return", ":", "Results", "of", "update", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/policy.py#L63-L93
[ "def", "update", "(", "self", ",", "mini_batch", ",", "num_sequences", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "dropout_rate", ":", "self", ".", "update_rate", ",", "self", ".", "model", ".", "batch_size", ":", "num_sequences", ",", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
Curriculum.increment_lesson
Increments the lesson number depending on the progress given. :param measure_val: Measure of progress (either reward or percentage steps completed). :return Whether the lesson was incremented.
ml-agents/mlagents/trainers/curriculum.py
def increment_lesson(self, measure_val): """ Increments the lesson number depending on the progress given. :param measure_val: Measure of progress (either reward or percentage steps completed). :return Whether the lesson was incremented. """ if not self.dat...
def increment_lesson(self, measure_val): """ Increments the lesson number depending on the progress given. :param measure_val: Measure of progress (either reward or percentage steps completed). :return Whether the lesson was incremented. """ if not self.dat...
[ "Increments", "the", "lesson", "number", "depending", "on", "the", "progress", "given", ".", ":", "param", "measure_val", ":", "Measure", "of", "progress", "(", "either", "reward", "or", "percentage", "steps", "completed", ")", ".", ":", "return", "Whether", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/curriculum.py#L69-L94
[ "def", "increment_lesson", "(", "self", ",", "measure_val", ")", ":", "if", "not", "self", ".", "data", "or", "not", "measure_val", "or", "math", ".", "isnan", "(", "measure_val", ")", ":", "return", "False", "if", "self", ".", "data", "[", "'signal_smoo...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
Curriculum.get_config
Returns reset parameters which correspond to the lesson. :param lesson: The lesson you want to get the config of. If None, the current lesson is returned. :return: The configuration of the reset parameters.
ml-agents/mlagents/trainers/curriculum.py
def get_config(self, lesson=None): """ Returns reset parameters which correspond to the lesson. :param lesson: The lesson you want to get the config of. If None, the current lesson is returned. :return: The configuration of the reset parameters. """ if not ...
def get_config(self, lesson=None): """ Returns reset parameters which correspond to the lesson. :param lesson: The lesson you want to get the config of. If None, the current lesson is returned. :return: The configuration of the reset parameters. """ if not ...
[ "Returns", "reset", "parameters", "which", "correspond", "to", "the", "lesson", ".", ":", "param", "lesson", ":", "The", "lesson", "you", "want", "to", "get", "the", "config", "of", ".", "If", "None", "the", "current", "lesson", "is", "returned", ".", ":...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/curriculum.py#L96-L112
[ "def", "get_config", "(", "self", ",", "lesson", "=", "None", ")", ":", "if", "not", "self", ".", "data", ":", "return", "{", "}", "if", "lesson", "is", "None", ":", "lesson", "=", "self", ".", "lesson_num", "lesson", "=", "max", "(", "0", ",", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
get_gae
Computes generalized advantage estimate for use in updating policy. :param rewards: list of rewards for time-steps t to T. :param value_next: Value estimate for time-step T+1. :param value_estimates: list of value estimates for time-steps t to T. :param gamma: Discount factor. :param lambd: GAE weig...
ml-agents/mlagents/trainers/ppo/trainer.py
def get_gae(rewards, value_estimates, value_next=0.0, gamma=0.99, lambd=0.95): """ Computes generalized advantage estimate for use in updating policy. :param rewards: list of rewards for time-steps t to T. :param value_next: Value estimate for time-step T+1. :param value_estimates: list of value est...
def get_gae(rewards, value_estimates, value_next=0.0, gamma=0.99, lambd=0.95): """ Computes generalized advantage estimate for use in updating policy. :param rewards: list of rewards for time-steps t to T. :param value_next: Value estimate for time-step T+1. :param value_estimates: list of value est...
[ "Computes", "generalized", "advantage", "estimate", "for", "use", "in", "updating", "policy", ".", ":", "param", "rewards", ":", "list", "of", "rewards", "for", "time", "-", "steps", "t", "to", "T", ".", ":", "param", "value_next", ":", "Value", "estimate"...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L364-L377
[ "def", "get_gae", "(", "rewards", ",", "value_estimates", ",", "value_next", "=", "0.0", ",", "gamma", "=", "0.99", ",", "lambd", "=", "0.95", ")", ":", "value_estimates", "=", "np", ".", "asarray", "(", "value_estimates", ".", "tolist", "(", ")", "+", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.increment_step_and_update_last_reward
Increment the step count of the trainer and Updates the last reward
ml-agents/mlagents/trainers/ppo/trainer.py
def increment_step_and_update_last_reward(self): """ Increment the step count of the trainer and Updates the last reward """ if len(self.stats['Environment/Cumulative Reward']) > 0: mean_reward = np.mean(self.stats['Environment/Cumulative Reward']) self.policy.upd...
def increment_step_and_update_last_reward(self): """ Increment the step count of the trainer and Updates the last reward """ if len(self.stats['Environment/Cumulative Reward']) > 0: mean_reward = np.mean(self.stats['Environment/Cumulative Reward']) self.policy.upd...
[ "Increment", "the", "step", "count", "of", "the", "trainer", "and", "Updates", "the", "last", "reward" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L99-L107
[ "def", "increment_step_and_update_last_reward", "(", "self", ")", ":", "if", "len", "(", "self", ".", "stats", "[", "'Environment/Cumulative Reward'", "]", ")", ">", "0", ":", "mean_reward", "=", "np", ".", "mean", "(", "self", ".", "stats", "[", "'Environme...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.construct_curr_info
Constructs a BrainInfo which contains the most recent previous experiences for all agents info which correspond to the agents in a provided next_info. :BrainInfo next_info: A t+1 BrainInfo. :return: curr_info: Reconstructed BrainInfo to match agents of next_info.
ml-agents/mlagents/trainers/ppo/trainer.py
def construct_curr_info(self, next_info: BrainInfo) -> BrainInfo: """ Constructs a BrainInfo which contains the most recent previous experiences for all agents info which correspond to the agents in a provided next_info. :BrainInfo next_info: A t+1 BrainInfo. :return: curr_info: ...
def construct_curr_info(self, next_info: BrainInfo) -> BrainInfo: """ Constructs a BrainInfo which contains the most recent previous experiences for all agents info which correspond to the agents in a provided next_info. :BrainInfo next_info: A t+1 BrainInfo. :return: curr_info: ...
[ "Constructs", "a", "BrainInfo", "which", "contains", "the", "most", "recent", "previous", "experiences", "for", "all", "agents", "info", "which", "correspond", "to", "the", "agents", "in", "a", "provided", "next_info", ".", ":", "BrainInfo", "next_info", ":", ...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L109-L153
[ "def", "construct_curr_info", "(", "self", ",", "next_info", ":", "BrainInfo", ")", "->", "BrainInfo", ":", "visual_observations", "=", "[", "[", "]", "]", "vector_observations", "=", "[", "]", "text_observations", "=", "[", "]", "memories", "=", "[", "]", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.add_experiences
Adds experiences to each agent's experience history. :param curr_all_info: Dictionary of all current brains and corresponding BrainInfo. :param next_all_info: Dictionary of all current brains and corresponding BrainInfo. :param take_action_outputs: The outputs of the Policy's get_action method.
ml-agents/mlagents/trainers/ppo/trainer.py
def add_experiences(self, curr_all_info: AllBrainInfo, next_all_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_all_info: Dictionary of all current brains and corresponding BrainInfo. :param next_all_info: Dictionary of all c...
def add_experiences(self, curr_all_info: AllBrainInfo, next_all_info: AllBrainInfo, take_action_outputs): """ Adds experiences to each agent's experience history. :param curr_all_info: Dictionary of all current brains and corresponding BrainInfo. :param next_all_info: Dictionary of all c...
[ "Adds", "experiences", "to", "each", "agent", "s", "experience", "history", ".", ":", "param", "curr_all_info", ":", "Dictionary", "of", "all", "current", "brains", "and", "corresponding", "BrainInfo", ".", ":", "param", "next_all_info", ":", "Dictionary", "of",...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L155-L235
[ "def", "add_experiences", "(", "self", ",", "curr_all_info", ":", "AllBrainInfo", ",", "next_all_info", ":", "AllBrainInfo", ",", "take_action_outputs", ")", ":", "self", ".", "trainer_metrics", ".", "start_experience_collection_timer", "(", ")", "if", "take_action_ou...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.process_experiences
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Dictionary of all current brains and corresponding BrainInfo. :param new_info: Dictionary of all next brains...
ml-agents/mlagents/trainers/ppo/trainer.py
def process_experiences(self, current_info: AllBrainInfo, new_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Dictionary of...
def process_experiences(self, current_info: AllBrainInfo, new_info: AllBrainInfo): """ Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Dictionary of...
[ "Checks", "agent", "histories", "for", "processing", "condition", "and", "processes", "them", "as", "necessary", ".", "Processing", "involves", "calculating", "value", "and", "advantage", "targets", "for", "model", "updating", "step", ".", ":", "param", "current_i...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L237-L291
[ "def", "process_experiences", "(", "self", ",", "current_info", ":", "AllBrainInfo", ",", "new_info", ":", "AllBrainInfo", ")", ":", "self", ".", "trainer_metrics", ".", "start_experience_collection_timer", "(", ")", "info", "=", "new_info", "[", "self", ".", "b...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.end_episode
A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets.
ml-agents/mlagents/trainers/ppo/trainer.py
def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.training_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 ...
def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.training_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 ...
[ "A", "signal", "that", "the", "Episode", "has", "ended", ".", "The", "buffer", "must", "be", "reset", ".", "Get", "only", "called", "when", "the", "academy", "resets", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L293-L305
[ "def", "end_episode", "(", "self", ")", ":", "self", ".", "training_buffer", ".", "reset_local_buffers", "(", ")", "for", "agent_id", "in", "self", ".", "cumulative_rewards", ":", "self", ".", "cumulative_rewards", "[", "agent_id", "]", "=", "0", "for", "age...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.is_ready_update
Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run
ml-agents/mlagents/trainers/ppo/trainer.py
def is_ready_update(self): """ Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run """ size_of_buffer = len(self.training_buffer.update_buffer['actions']) return size_of_bu...
def is_ready_update(self): """ Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run """ size_of_buffer = len(self.training_buffer.update_buffer['actions']) return size_of_bu...
[ "Returns", "whether", "or", "not", "the", "trainer", "has", "enough", "elements", "to", "run", "update", "model", ":", "return", ":", "A", "boolean", "corresponding", "to", "whether", "or", "not", "update_model", "()", "can", "be", "run" ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L307-L313
[ "def", "is_ready_update", "(", "self", ")", ":", "size_of_buffer", "=", "len", "(", "self", ".", "training_buffer", ".", "update_buffer", "[", "'actions'", "]", ")", "return", "size_of_buffer", ">", "max", "(", "int", "(", "self", ".", "trainer_parameters", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
PPOTrainer.update_policy
Uses demonstration_buffer to update the policy.
ml-agents/mlagents/trainers/ppo/trainer.py
def update_policy(self): """ Uses demonstration_buffer to update the policy. """ self.trainer_metrics.start_policy_update_timer( number_experiences=len(self.training_buffer.update_buffer['actions']), mean_return=float(np.mean(self.cumulative_returns_since_policy_u...
def update_policy(self): """ Uses demonstration_buffer to update the policy. """ self.trainer_metrics.start_policy_update_timer( number_experiences=len(self.training_buffer.update_buffer['actions']), mean_return=float(np.mean(self.cumulative_returns_since_policy_u...
[ "Uses", "demonstration_buffer", "to", "update", "the", "policy", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/trainer.py#L315-L346
[ "def", "update_policy", "(", "self", ")", ":", "self", ".", "trainer_metrics", ".", "start_policy_update_timer", "(", "number_experiences", "=", "len", "(", "self", ".", "training_buffer", ".", "update_buffer", "[", "'actions'", "]", ")", ",", "mean_return", "="...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
UnityEnv.reset
Resets the state of the environment and returns an initial observation. In the case of multi-agent environments, this is a list. Returns: observation (object/list): the initial observation of the space.
gym-unity/gym_unity/envs/unity_env.py
def reset(self): """Resets the state of the environment and returns an initial observation. In the case of multi-agent environments, this is a list. Returns: observation (object/list): the initial observation of the space. """ info = self._env.reset()[self.brain_name]...
def reset(self): """Resets the state of the environment and returns an initial observation. In the case of multi-agent environments, this is a list. Returns: observation (object/list): the initial observation of the space. """ info = self._env.reset()[self.brain_name]...
[ "Resets", "the", "state", "of", "the", "environment", "and", "returns", "an", "initial", "observation", ".", "In", "the", "case", "of", "multi", "-", "agent", "environments", "this", "is", "a", "list", ".", "Returns", ":", "observation", "(", "object", "/"...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/gym-unity/gym_unity/envs/unity_env.py#L109-L124
[ "def", "reset", "(", "self", ")", ":", "info", "=", "self", ".", "_env", ".", "reset", "(", ")", "[", "self", ".", "brain_name", "]", "n_agents", "=", "len", "(", "info", ".", "agents", ")", "self", ".", "_check_agents", "(", "n_agents", ")", "self...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
UnityEnv.step
Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). In the case of multi-agent environments, these are lists. ...
gym-unity/gym_unity/envs/unity_env.py
def step(self, action): """Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). In the case of multi-ag...
def step(self, action): """Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). In the case of multi-ag...
[ "Run", "one", "timestep", "of", "the", "environment", "s", "dynamics", ".", "When", "end", "of", "episode", "is", "reached", "you", "are", "responsible", "for", "calling", "reset", "()", "to", "reset", "this", "environment", "s", "state", ".", "Accepts", "...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/gym-unity/gym_unity/envs/unity_env.py#L126-L169
[ "def", "step", "(", "self", ",", "action", ")", ":", "# Use random actions for all other agents in environment.", "if", "self", ".", "_multiagent", ":", "if", "not", "isinstance", "(", "action", ",", "list", ")", ":", "raise", "UnityGymException", "(", "\"The envi...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
ActionFlattener._create_lookup
Creates a Dict that maps discrete actions (scalars) to branched actions (lists). Each key in the Dict maps to one unique set of branched actions, and each value contains the List of branched actions.
gym-unity/gym_unity/envs/unity_env.py
def _create_lookup(self, branched_action_space): """ Creates a Dict that maps discrete actions (scalars) to branched actions (lists). Each key in the Dict maps to one unique set of branched actions, and each value contains the List of branched actions. """ possible_vals =...
def _create_lookup(self, branched_action_space): """ Creates a Dict that maps discrete actions (scalars) to branched actions (lists). Each key in the Dict maps to one unique set of branched actions, and each value contains the List of branched actions. """ possible_vals =...
[ "Creates", "a", "Dict", "that", "maps", "discrete", "actions", "(", "scalars", ")", "to", "branched", "actions", "(", "lists", ")", ".", "Each", "key", "in", "the", "Dict", "maps", "to", "one", "unique", "set", "of", "branched", "actions", "and", "each",...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/gym-unity/gym_unity/envs/unity_env.py#L279-L289
[ "def", "_create_lookup", "(", "self", ",", "branched_action_space", ")", ":", "possible_vals", "=", "[", "range", "(", "_num", ")", "for", "_num", "in", "branched_action_space", "]", "all_actions", "=", "[", "list", "(", "_action", ")", "for", "_action", "in...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
RpcCommunicator.create_server
Creates the GRPC server.
ml-agents-envs/mlagents/envs/rpc_communicator.py
def create_server(self): """ Creates the GRPC server. """ self.check_port(self.port) try: # Establish communication grpc self.server = grpc.server(ThreadPoolExecutor(max_workers=10)) self.unity_to_external = UnityToExternalServicerImplementati...
def create_server(self): """ Creates the GRPC server. """ self.check_port(self.port) try: # Establish communication grpc self.server = grpc.server(ThreadPoolExecutor(max_workers=10)) self.unity_to_external = UnityToExternalServicerImplementati...
[ "Creates", "the", "GRPC", "server", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/rpc_communicator.py#L46-L63
[ "def", "create_server", "(", "self", ")", ":", "self", ".", "check_port", "(", "self", ".", "port", ")", "try", ":", "# Establish communication grpc", "self", ".", "server", "=", "grpc", ".", "server", "(", "ThreadPoolExecutor", "(", "max_workers", "=", "10"...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
RpcCommunicator.check_port
Attempts to bind to the requested communicator port, checking if it is already in use.
ml-agents-envs/mlagents/envs/rpc_communicator.py
def check_port(self, port): """ Attempts to bind to the requested communicator port, checking if it is already in use. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("localhost", port)) except socket.error: raise UnityWorker...
def check_port(self, port): """ Attempts to bind to the requested communicator port, checking if it is already in use. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("localhost", port)) except socket.error: raise UnityWorker...
[ "Attempts", "to", "bind", "to", "the", "requested", "communicator", "port", "checking", "if", "it", "is", "already", "in", "use", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/rpc_communicator.py#L65-L75
[ "def", "check_port", "(", "self", ",", "port", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "s", ".", "bind", "(", "(", "\"localhost\"", ",", "port", ")", ")", "exce...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
RpcCommunicator.close
Sends a shutdown signal to the unity environment, and closes the grpc connection.
ml-agents-envs/mlagents/envs/rpc_communicator.py
def close(self): """ Sends a shutdown signal to the unity environment, and closes the grpc connection. """ if self.is_open: message_input = UnityMessage() message_input.header.status = 400 self.unity_to_external.parent_conn.send(message_input) ...
def close(self): """ Sends a shutdown signal to the unity environment, and closes the grpc connection. """ if self.is_open: message_input = UnityMessage() message_input.header.status = 400 self.unity_to_external.parent_conn.send(message_input) ...
[ "Sends", "a", "shutdown", "signal", "to", "the", "unity", "environment", "and", "closes", "the", "grpc", "connection", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/rpc_communicator.py#L103-L113
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "message_input", "=", "UnityMessage", "(", ")", "message_input", ".", "header", ".", "status", "=", "400", "self", ".", "unity_to_external", ".", "parent_conn", ".", "send", "(", "...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BrainInfo.process_pixels
Converts byte array observation image into numpy array, re-sizes it, and optionally converts it to grey scale :param gray_scale: Whether to convert the image to grayscale. :param image_bytes: input byte array corresponding to image :return: processed numpy array of observation from envir...
ml-agents-envs/mlagents/envs/brain.py
def process_pixels(image_bytes, gray_scale): """ Converts byte array observation image into numpy array, re-sizes it, and optionally converts it to grey scale :param gray_scale: Whether to convert the image to grayscale. :param image_bytes: input byte array corresponding to image...
def process_pixels(image_bytes, gray_scale): """ Converts byte array observation image into numpy array, re-sizes it, and optionally converts it to grey scale :param gray_scale: Whether to convert the image to grayscale. :param image_bytes: input byte array corresponding to image...
[ "Converts", "byte", "array", "observation", "image", "into", "numpy", "array", "re", "-", "sizes", "it", "and", "optionally", "converts", "it", "to", "grey", "scale", ":", "param", "gray_scale", ":", "Whether", "to", "convert", "the", "image", "to", "graysca...
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/brain.py#L68-L82
[ "def", "process_pixels", "(", "image_bytes", ",", "gray_scale", ")", ":", "s", "=", "bytearray", "(", "image_bytes", ")", "image", "=", "Image", ".", "open", "(", "io", ".", "BytesIO", "(", "s", ")", ")", "s", "=", "np", ".", "array", "(", "image", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BrainInfo.from_agent_proto
Converts list of agent infos to BrainInfo.
ml-agents-envs/mlagents/envs/brain.py
def from_agent_proto(agent_info_list, brain_params): """ Converts list of agent infos to BrainInfo. """ vis_obs = [] for i in range(brain_params.number_visual_observations): obs = [BrainInfo.process_pixels(x.visual_observations[i], ...
def from_agent_proto(agent_info_list, brain_params): """ Converts list of agent infos to BrainInfo. """ vis_obs = [] for i in range(brain_params.number_visual_observations): obs = [BrainInfo.process_pixels(x.visual_observations[i], ...
[ "Converts", "list", "of", "agent", "infos", "to", "BrainInfo", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/brain.py#L85-L138
[ "def", "from_agent_proto", "(", "agent_info_list", ",", "brain_params", ")", ":", "vis_obs", "=", "[", "]", "for", "i", "in", "range", "(", "brain_params", ".", "number_visual_observations", ")", ":", "obs", "=", "[", "BrainInfo", ".", "process_pixels", "(", ...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
BrainParameters.from_proto
Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. :return: BrainParameter object.
ml-agents-envs/mlagents/envs/brain.py
def from_proto(brain_param_proto): """ Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. :return: BrainParameter object. """ resolution = [{ "height": x.height, "width": x.width, "blackA...
def from_proto(brain_param_proto): """ Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. :return: BrainParameter object. """ resolution = [{ "height": x.height, "width": x.width, "blackA...
[ "Converts", "brain", "parameter", "proto", "to", "BrainParameter", "object", ".", ":", "param", "brain_param_proto", ":", "protobuf", "object", ".", ":", "return", ":", "BrainParameter", "object", "." ]
Unity-Technologies/ml-agents
python
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/brain.py#L206-L224
[ "def", "from_proto", "(", "brain_param_proto", ")", ":", "resolution", "=", "[", "{", "\"height\"", ":", "x", ".", "height", ",", "\"width\"", ":", "x", ".", "width", ",", "\"blackAndWhite\"", ":", "x", ".", "gray_scale", "}", "for", "x", "in", "brain_pa...
37d139af636e4a2351751fbf0f2fca5a9ed7457f
train
Dashboard.new
Creates a new, blank dashboard and redirects to it in edit mode
superset/views/dashboard.py
def new(self): """Creates a new, blank dashboard and redirects to it in edit mode""" new_dashboard = models.Dashboard( dashboard_title='[ untitled dashboard ]', owners=[g.user], ) db.session.add(new_dashboard) db.session.commit() return redirect(f'...
def new(self): """Creates a new, blank dashboard and redirects to it in edit mode""" new_dashboard = models.Dashboard( dashboard_title='[ untitled dashboard ]', owners=[g.user], ) db.session.add(new_dashboard) db.session.commit() return redirect(f'...
[ "Creates", "a", "new", "blank", "dashboard", "and", "redirects", "to", "it", "in", "edit", "mode" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/dashboard.py#L32-L40
[ "def", "new", "(", "self", ")", ":", "new_dashboard", "=", "models", ".", "Dashboard", "(", "dashboard_title", "=", "'[ untitled dashboard ]'", ",", "owners", "=", "[", "g", ".", "user", "]", ",", ")", "db", ".", "session", ".", "add", "(", "new_dashboar...
ca2996c78f679260eb79c6008e276733df5fb653
train
TagView.get
List all tags a given object has.
superset/views/tags.py
def get(self, object_type, object_id): """List all tags a given object has.""" if object_id == 0: return json_success(json.dumps([])) query = db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, TaggedObject.object_id == object...
def get(self, object_type, object_id): """List all tags a given object has.""" if object_id == 0: return json_success(json.dumps([])) query = db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, TaggedObject.object_id == object...
[ "List", "all", "tags", "a", "given", "object", "has", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/tags.py#L78-L87
[ "def", "get", "(", "self", ",", "object_type", ",", "object_id", ")", ":", "if", "object_id", "==", "0", ":", "return", "json_success", "(", "json", ".", "dumps", "(", "[", "]", ")", ")", "query", "=", "db", ".", "session", ".", "query", "(", "Tagg...
ca2996c78f679260eb79c6008e276733df5fb653
train
TagView.post
Add new tags to an object.
superset/views/tags.py
def post(self, object_type, object_id): """Add new tags to an object.""" if object_id == 0: return Response(status=404) tagged_objects = [] for name in request.get_json(force=True): if ':' in name: type_name = name.split(':', 1)[0] ...
def post(self, object_type, object_id): """Add new tags to an object.""" if object_id == 0: return Response(status=404) tagged_objects = [] for name in request.get_json(force=True): if ':' in name: type_name = name.split(':', 1)[0] ...
[ "Add", "new", "tags", "to", "an", "object", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/tags.py#L91-L119
[ "def", "post", "(", "self", ",", "object_type", ",", "object_id", ")", ":", "if", "object_id", "==", "0", ":", "return", "Response", "(", "status", "=", "404", ")", "tagged_objects", "=", "[", "]", "for", "name", "in", "request", ".", "get_json", "(", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
TagView.delete
Remove tags from an object.
superset/views/tags.py
def delete(self, object_type, object_id): """Remove tags from an object.""" tag_names = request.get_json(force=True) if not tag_names: return Response(status=403) db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, Tag...
def delete(self, object_type, object_id): """Remove tags from an object.""" tag_names = request.get_json(force=True) if not tag_names: return Response(status=403) db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, Tag...
[ "Remove", "tags", "from", "an", "object", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/tags.py#L123-L136
[ "def", "delete", "(", "self", ",", "object_type", ",", "object_id", ")", ":", "tag_names", "=", "request", ".", "get_json", "(", "force", "=", "True", ")", "if", "not", "tag_names", ":", "return", "Response", "(", "status", "=", "403", ")", "db", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
import_datasource
Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over.
superset/utils/import_datasource.py
def import_datasource( session, i_datasource, lookup_database, lookup_datasource, import_time): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export das...
def import_datasource( session, i_datasource, lookup_database, lookup_datasource, import_time): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export das...
[ "Imports", "the", "datasource", "from", "the", "object", "to", "the", "database", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/import_datasource.py#L23-L74
[ "def", "import_datasource", "(", "session", ",", "i_datasource", ",", "lookup_database", ",", "lookup_datasource", ",", "import_time", ")", ":", "make_transient", "(", "i_datasource", ")", "logging", ".", "info", "(", "'Started import of the datasource: {}'", ".", "fo...
ca2996c78f679260eb79c6008e276733df5fb653
train
run_migrations_online
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
superset/migrations/env.py
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: h...
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: h...
[ "Run", "migrations", "in", "online", "mode", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/migrations/env.py#L68-L111
[ "def", "run_migrations_online", "(", ")", ":", "# this callback is used to prevent an auto-migration from being generated", "# when there are no changes to the schema", "# reference: https://alembic.sqlalchemy.org/en/latest/cookbook.html", "def", "process_revision_directives", "(", "context", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseViz.get_df
Returns a pandas dataframe based on the query object
superset/viz.py
def get_df(self, query_obj=None): """Returns a pandas dataframe based on the query object""" if not query_obj: query_obj = self.query_obj() if not query_obj: return None self.error_msg = '' timestamp_format = None if self.datasource.type == 'tabl...
def get_df(self, query_obj=None): """Returns a pandas dataframe based on the query object""" if not query_obj: query_obj = self.query_obj() if not query_obj: return None self.error_msg = '' timestamp_format = None if self.datasource.type == 'tabl...
[ "Returns", "a", "pandas", "dataframe", "based", "on", "the", "query", "object" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L177-L235
[ "def", "get_df", "(", "self", ",", "query_obj", "=", "None", ")", ":", "if", "not", "query_obj", ":", "query_obj", "=", "self", ".", "query_obj", "(", ")", "if", "not", "query_obj", ":", "return", "None", "self", ".", "error_msg", "=", "''", "timestamp...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseViz.query_obj
Building a query object
superset/viz.py
def query_obj(self): """Building a query object""" form_data = self.form_data self.process_query_filters() gb = form_data.get('groupby') or [] metrics = self.all_metrics or [] columns = form_data.get('columns') or [] groupby = [] for o in gb + columns: ...
def query_obj(self): """Building a query object""" form_data = self.form_data self.process_query_filters() gb = form_data.get('groupby') or [] metrics = self.all_metrics or [] columns = form_data.get('columns') or [] groupby = [] for o in gb + columns: ...
[ "Building", "a", "query", "object" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L249-L317
[ "def", "query_obj", "(", "self", ")", ":", "form_data", "=", "self", ".", "form_data", "self", ".", "process_query_filters", "(", ")", "gb", "=", "form_data", ".", "get", "(", "'groupby'", ")", "or", "[", "]", "metrics", "=", "self", ".", "all_metrics", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseViz.cache_key
The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra`. We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5 days ago" or "now"). The `extra` argum...
superset/viz.py
def cache_key(self, query_obj, **extra): """ The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra`. We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as ...
def cache_key(self, query_obj, **extra): """ The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra`. We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as ...
[ "The", "cache", "key", "is", "made", "out", "of", "the", "key", "/", "values", "in", "query_obj", "plus", "any", "other", "key", "/", "values", "in", "extra", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L336-L358
[ "def", "cache_key", "(", "self", ",", "query_obj", ",", "*", "*", "extra", ")", ":", "cache_dict", "=", "copy", ".", "copy", "(", "query_obj", ")", "cache_dict", ".", "update", "(", "extra", ")", "for", "k", "in", "[", "'from_dttm'", ",", "'to_dttm'", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseViz.data
This is the data object serialized to the js layer
superset/viz.py
def data(self): """This is the data object serialized to the js layer""" content = { 'form_data': self.form_data, 'token': self.token, 'viz_name': self.viz_type, 'filter_select_enabled': self.datasource.filter_select_enabled, } return conte...
def data(self): """This is the data object serialized to the js layer""" content = { 'form_data': self.form_data, 'token': self.token, 'viz_name': self.viz_type, 'filter_select_enabled': self.datasource.filter_select_enabled, } return conte...
[ "This", "is", "the", "data", "object", "serialized", "to", "the", "js", "layer" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L472-L480
[ "def", "data", "(", "self", ")", ":", "content", "=", "{", "'form_data'", ":", "self", ".", "form_data", ",", "'token'", ":", "self", ".", "token", ",", "'viz_name'", ":", "self", ".", "viz_type", ",", "'filter_select_enabled'", ":", "self", ".", "dataso...
ca2996c78f679260eb79c6008e276733df5fb653
train
HistogramViz.query_obj
Returns the query object for this visualization
superset/viz.py
def query_obj(self): """Returns the query object for this visualization""" d = super().query_obj() d['row_limit'] = self.form_data.get( 'row_limit', int(config.get('VIZ_ROW_LIMIT'))) numeric_columns = self.form_data.get('all_columns_x') if numeric_columns is None: ...
def query_obj(self): """Returns the query object for this visualization""" d = super().query_obj() d['row_limit'] = self.form_data.get( 'row_limit', int(config.get('VIZ_ROW_LIMIT'))) numeric_columns = self.form_data.get('all_columns_x') if numeric_columns is None: ...
[ "Returns", "the", "query", "object", "for", "this", "visualization" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L1474-L1486
[ "def", "query_obj", "(", "self", ")", ":", "d", "=", "super", "(", ")", ".", "query_obj", "(", ")", "d", "[", "'row_limit'", "]", "=", "self", ".", "form_data", ".", "get", "(", "'row_limit'", ",", "int", "(", "config", ".", "get", "(", "'VIZ_ROW_L...
ca2996c78f679260eb79c6008e276733df5fb653
train
HistogramViz.get_data
Returns the chart data
superset/viz.py
def get_data(self, df): """Returns the chart data""" chart_data = [] if len(self.groupby) > 0: groups = df.groupby(self.groupby) else: groups = [((), df)] for keys, data in groups: chart_data.extend([{ 'key': self.labelify(keys,...
def get_data(self, df): """Returns the chart data""" chart_data = [] if len(self.groupby) > 0: groups = df.groupby(self.groupby) else: groups = [((), df)] for keys, data in groups: chart_data.extend([{ 'key': self.labelify(keys,...
[ "Returns", "the", "chart", "data" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L1498-L1510
[ "def", "get_data", "(", "self", ",", "df", ")", ":", "chart_data", "=", "[", "]", "if", "len", "(", "self", ".", "groupby", ")", ">", "0", ":", "groups", "=", "df", ".", "groupby", "(", "self", ".", "groupby", ")", "else", ":", "groups", "=", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
PartitionViz.levels_for
Compute the partition at each `level` from the dataframe.
superset/viz.py
def levels_for(self, time_op, groups, df): """ Compute the partition at each `level` from the dataframe. """ levels = {} for i in range(0, len(groups) + 1): agg_df = df.groupby(groups[:i]) if i else df levels[i] = ( agg_df.mean() if time_op...
def levels_for(self, time_op, groups, df): """ Compute the partition at each `level` from the dataframe. """ levels = {} for i in range(0, len(groups) + 1): agg_df = df.groupby(groups[:i]) if i else df levels[i] = ( agg_df.mean() if time_op...
[ "Compute", "the", "partition", "at", "each", "level", "from", "the", "dataframe", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L2648-L2658
[ "def", "levels_for", "(", "self", ",", "time_op", ",", "groups", ",", "df", ")", ":", "levels", "=", "{", "}", "for", "i", "in", "range", "(", "0", ",", "len", "(", "groups", ")", "+", "1", ")", ":", "agg_df", "=", "df", ".", "groupby", "(", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
PartitionViz.nest_values
Nest values at each level on the back-end with access and setting, instead of summing from the bottom.
superset/viz.py
def nest_values(self, levels, level=0, metric=None, dims=()): """ Nest values at each level on the back-end with access and setting, instead of summing from the bottom. """ if not level: return [{ 'name': m, 'val': levels[0][m], ...
def nest_values(self, levels, level=0, metric=None, dims=()): """ Nest values at each level on the back-end with access and setting, instead of summing from the bottom. """ if not level: return [{ 'name': m, 'val': levels[0][m], ...
[ "Nest", "values", "at", "each", "level", "on", "the", "back", "-", "end", "with", "access", "and", "setting", "instead", "of", "summing", "from", "the", "bottom", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L2701-L2726
[ "def", "nest_values", "(", "self", ",", "levels", ",", "level", "=", "0", ",", "metric", "=", "None", ",", "dims", "=", "(", ")", ")", ":", "if", "not", "level", ":", "return", "[", "{", "'name'", ":", "m", ",", "'val'", ":", "levels", "[", "0"...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseDatasource.short_data
Data representation of the datasource sent to the frontend
superset/connectors/base/models.py
def short_data(self): """Data representation of the datasource sent to the frontend""" return { 'edit_url': self.url, 'id': self.id, 'uid': self.uid, 'schema': self.schema, 'name': self.name, 'type': self.type, 'connecti...
def short_data(self): """Data representation of the datasource sent to the frontend""" return { 'edit_url': self.url, 'id': self.id, 'uid': self.uid, 'schema': self.schema, 'name': self.name, 'type': self.type, 'connecti...
[ "Data", "representation", "of", "the", "datasource", "sent", "to", "the", "frontend" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L148-L159
[ "def", "short_data", "(", "self", ")", ":", "return", "{", "'edit_url'", ":", "self", ".", "url", ",", "'id'", ":", "self", ".", "id", ",", "'uid'", ":", "self", ".", "uid", ",", "'schema'", ":", "self", ".", "schema", ",", "'name'", ":", "self", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseDatasource.data
Data representation of the datasource sent to the frontend
superset/connectors/base/models.py
def data(self): """Data representation of the datasource sent to the frontend""" order_by_choices = [] # self.column_names return sorted column_names for s in self.column_names: s = str(s or '') order_by_choices.append((json.dumps([s, True]), s + ' [asc]')) ...
def data(self): """Data representation of the datasource sent to the frontend""" order_by_choices = [] # self.column_names return sorted column_names for s in self.column_names: s = str(s or '') order_by_choices.append((json.dumps([s, True]), s + ' [asc]')) ...
[ "Data", "representation", "of", "the", "datasource", "sent", "to", "the", "frontend" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L166-L215
[ "def", "data", "(", "self", ")", ":", "order_by_choices", "=", "[", "]", "# self.column_names return sorted column_names", "for", "s", "in", "self", ".", "column_names", ":", "s", "=", "str", "(", "s", "or", "''", ")", "order_by_choices", ".", "append", "(",...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseDatasource.get_fk_many_from_list
Update ORM one-to-many list from object list Used for syncing metrics and columns using the same code
superset/connectors/base/models.py
def get_fk_many_from_list( self, object_list, fkmany, fkmany_class, key_attr): """Update ORM one-to-many list from object list Used for syncing metrics and columns using the same code""" object_dict = {o.get(key_attr): o for o in object_list} object_keys = [o.get(key_attr) ...
def get_fk_many_from_list( self, object_list, fkmany, fkmany_class, key_attr): """Update ORM one-to-many list from object list Used for syncing metrics and columns using the same code""" object_dict = {o.get(key_attr): o for o in object_list} object_keys = [o.get(key_attr) ...
[ "Update", "ORM", "one", "-", "to", "-", "many", "list", "from", "object", "list" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L281-L316
[ "def", "get_fk_many_from_list", "(", "self", ",", "object_list", ",", "fkmany", ",", "fkmany_class", ",", "key_attr", ")", ":", "object_dict", "=", "{", "o", ".", "get", "(", "key_attr", ")", ":", "o", "for", "o", "in", "object_list", "}", "object_keys", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseDatasource.update_from_object
Update datasource from a data structure The UI's table editor crafts a complex data structure that contains most of the datasource's properties as well as an array of metrics and columns objects. This method receives the object from the UI and syncs the datasource to match it. S...
superset/connectors/base/models.py
def update_from_object(self, obj): """Update datasource from a data structure The UI's table editor crafts a complex data structure that contains most of the datasource's properties as well as an array of metrics and columns objects. This method receives the object from the UI a...
def update_from_object(self, obj): """Update datasource from a data structure The UI's table editor crafts a complex data structure that contains most of the datasource's properties as well as an array of metrics and columns objects. This method receives the object from the UI a...
[ "Update", "datasource", "from", "a", "data", "structure" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L318-L341
[ "def", "update_from_object", "(", "self", ",", "obj", ")", ":", "for", "attr", "in", "self", ".", "update_from_object_fields", ":", "setattr", "(", "self", ",", "attr", ",", "obj", ".", "get", "(", "attr", ")", ")", "self", ".", "owners", "=", "obj", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
QueryContext.get_query_result
Returns a pandas dataframe based on the query object
superset/common/query_context.py
def get_query_result(self, query_object): """Returns a pandas dataframe based on the query object""" # Here, we assume that all the queries will use the same datasource, which is # is a valid assumption for current setting. In a long term, we may or maynot # support multiple queries fro...
def get_query_result(self, query_object): """Returns a pandas dataframe based on the query object""" # Here, we assume that all the queries will use the same datasource, which is # is a valid assumption for current setting. In a long term, we may or maynot # support multiple queries fro...
[ "Returns", "a", "pandas", "dataframe", "based", "on", "the", "query", "object" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L67-L110
[ "def", "get_query_result", "(", "self", ",", "query_object", ")", ":", "# Here, we assume that all the queries will use the same datasource, which is", "# is a valid assumption for current setting. In a long term, we may or maynot", "# support multiple queries from different data source.", "ti...
ca2996c78f679260eb79c6008e276733df5fb653
train
QueryContext.df_metrics_to_num
Converting metrics to numeric when pandas.read_sql cannot
superset/common/query_context.py
def df_metrics_to_num(self, df, query_object): """Converting metrics to numeric when pandas.read_sql cannot""" metrics = [metric for metric in query_object.metrics] for col, dtype in df.dtypes.items(): if dtype.type == np.object_ and col in metrics: df[col] = pd.to_nu...
def df_metrics_to_num(self, df, query_object): """Converting metrics to numeric when pandas.read_sql cannot""" metrics = [metric for metric in query_object.metrics] for col, dtype in df.dtypes.items(): if dtype.type == np.object_ and col in metrics: df[col] = pd.to_nu...
[ "Converting", "metrics", "to", "numeric", "when", "pandas", ".", "read_sql", "cannot" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L112-L117
[ "def", "df_metrics_to_num", "(", "self", ",", "df", ",", "query_object", ")", ":", "metrics", "=", "[", "metric", "for", "metric", "in", "query_object", ".", "metrics", "]", "for", "col", ",", "dtype", "in", "df", ".", "dtypes", ".", "items", "(", ")",...
ca2996c78f679260eb79c6008e276733df5fb653
train
QueryContext.get_single_payload
Returns a payload of metadata and data
superset/common/query_context.py
def get_single_payload(self, query_obj): """Returns a payload of metadata and data""" payload = self.get_df_payload(query_obj) df = payload.get('df') status = payload.get('status') if status != utils.QueryStatus.FAILED: if df is not None and df.empty: ...
def get_single_payload(self, query_obj): """Returns a payload of metadata and data""" payload = self.get_df_payload(query_obj) df = payload.get('df') status = payload.get('status') if status != utils.QueryStatus.FAILED: if df is not None and df.empty: ...
[ "Returns", "a", "payload", "of", "metadata", "and", "data" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L122-L134
[ "def", "get_single_payload", "(", "self", ",", "query_obj", ")", ":", "payload", "=", "self", ".", "get_df_payload", "(", "query_obj", ")", "df", "=", "payload", ".", "get", "(", "'df'", ")", "status", "=", "payload", ".", "get", "(", "'status'", ")", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
QueryContext.get_df_payload
Handles caching around the df paylod retrieval
superset/common/query_context.py
def get_df_payload(self, query_obj, **kwargs): """Handles caching around the df paylod retrieval""" cache_key = query_obj.cache_key( datasource=self.datasource.uid, **kwargs) if query_obj else None logging.info('Cache key: {}'.format(cache_key)) is_loaded = False stac...
def get_df_payload(self, query_obj, **kwargs): """Handles caching around the df paylod retrieval""" cache_key = query_obj.cache_key( datasource=self.datasource.uid, **kwargs) if query_obj else None logging.info('Cache key: {}'.format(cache_key)) is_loaded = False stac...
[ "Handles", "caching", "around", "the", "df", "paylod", "retrieval" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L152-L237
[ "def", "get_df_payload", "(", "self", ",", "query_obj", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "query_obj", ".", "cache_key", "(", "datasource", "=", "self", ".", "datasource", ".", "uid", ",", "*", "*", "kwargs", ")", "if", "query_obj", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Slice.data
Data used to render slice in templates
superset/models/core.py
def data(self): """Data used to render slice in templates""" d = {} self.token = '' try: d = self.viz.data self.token = d.get('token') except Exception as e: logging.exception(e) d['error'] = str(e) return { 'dat...
def data(self): """Data used to render slice in templates""" d = {} self.token = '' try: d = self.viz.data self.token = d.get('token') except Exception as e: logging.exception(e) d['error'] = str(e) return { 'dat...
[ "Data", "used", "to", "render", "slice", "in", "templates" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L226-L248
[ "def", "data", "(", "self", ")", ":", "d", "=", "{", "}", "self", ".", "token", "=", "''", "try", ":", "d", "=", "self", ".", "viz", ".", "data", "self", ".", "token", "=", "d", ".", "get", "(", "'token'", ")", "except", "Exception", "as", "e...
ca2996c78f679260eb79c6008e276733df5fb653
train
Slice.get_viz
Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz
superset/models/core.py
def get_viz(self, force=False): """Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz """ slice_params = json.loads(self....
def get_viz(self, force=False): """Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz """ slice_params = json.loads(self....
[ "Creates", ":", "py", ":", "class", ":", "viz", ".", "BaseViz", "object", "from", "the", "url_params_multidict", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L305-L322
[ "def", "get_viz", "(", "self", ",", "force", "=", "False", ")", ":", "slice_params", "=", "json", ".", "loads", "(", "self", ".", "params", ")", "slice_params", "[", "'slice_id'", "]", "=", "self", ".", "id", "slice_params", "[", "'json'", "]", "=", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Slice.import_obj
Inserts or overrides slc in the database. remote_id and import_time fields in params_dict are set to track the slice origin and ensure correct overrides for multiple imports. Slice.perm is used to find the datasources and connect them. :param Slice slc_to_import: Slice object to import...
superset/models/core.py
def import_obj(cls, slc_to_import, slc_to_override, import_time=None): """Inserts or overrides slc in the database. remote_id and import_time fields in params_dict are set to track the slice origin and ensure correct overrides for multiple imports. Slice.perm is used to find the datasou...
def import_obj(cls, slc_to_import, slc_to_override, import_time=None): """Inserts or overrides slc in the database. remote_id and import_time fields in params_dict are set to track the slice origin and ensure correct overrides for multiple imports. Slice.perm is used to find the datasou...
[ "Inserts", "or", "overrides", "slc", "in", "the", "database", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L336-L366
[ "def", "import_obj", "(", "cls", ",", "slc_to_import", ",", "slc_to_override", ",", "import_time", "=", "None", ")", ":", "session", "=", "db", ".", "session", "make_transient", "(", "slc_to_import", ")", "slc_to_import", ".", "dashboards", "=", "[", "]", "s...
ca2996c78f679260eb79c6008e276733df5fb653
train
Dashboard.import_obj
Imports the dashboard from the object to the database. Once dashboard is imported, json_metadata field is extended and stores remote_id and import_time. It helps to decide if the dashboard has to be overridden or just copies over. Slices that belong to this dashboard will be wired t...
superset/models/core.py
def import_obj(cls, dashboard_to_import, import_time=None): """Imports the dashboard from the object to the database. Once dashboard is imported, json_metadata field is extended and stores remote_id and import_time. It helps to decide if the dashboard has to be overridden or just cop...
def import_obj(cls, dashboard_to_import, import_time=None): """Imports the dashboard from the object to the database. Once dashboard is imported, json_metadata field is extended and stores remote_id and import_time. It helps to decide if the dashboard has to be overridden or just cop...
[ "Imports", "the", "dashboard", "from", "the", "object", "to", "the", "database", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L488-L615
[ "def", "import_obj", "(", "cls", ",", "dashboard_to_import", ",", "import_time", "=", "None", ")", ":", "def", "alter_positions", "(", "dashboard", ",", "old_to_new_slc_id_dict", ")", ":", "\"\"\" Updates slice_ids in the position json.\n\n Sample position_json dat...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.get_effective_user
Get the effective user, especially during impersonation. :param url: SQL Alchemy URL object :param user_name: Default username :return: The effective username
superset/models/core.py
def get_effective_user(self, url, user_name=None): """ Get the effective user, especially during impersonation. :param url: SQL Alchemy URL object :param user_name: Default username :return: The effective username """ effective_username = None if self.impe...
def get_effective_user(self, url, user_name=None): """ Get the effective user, especially during impersonation. :param url: SQL Alchemy URL object :param user_name: Default username :return: The effective username """ effective_username = None if self.impe...
[ "Get", "the", "effective", "user", "especially", "during", "impersonation", ".", ":", "param", "url", ":", "SQL", "Alchemy", "URL", "object", ":", "param", "user_name", ":", "Default", "username", ":", "return", ":", "The", "effective", "username" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L776-L793
[ "def", "get_effective_user", "(", "self", ",", "url", ",", "user_name", "=", "None", ")", ":", "effective_username", "=", "None", "if", "self", ".", "impersonate_user", ":", "effective_username", "=", "url", ".", "username", "if", "user_name", ":", "effective_...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.select_star
Generates a ``select *`` statement in the proper dialect
superset/models/core.py
def select_star( self, table_name, schema=None, limit=100, show_cols=False, indent=True, latest_partition=False, cols=None): """Generates a ``select *`` statement in the proper dialect""" eng = self.get_sqla_engine( schema=schema, source=utils.sources.get('sql_lab', N...
def select_star( self, table_name, schema=None, limit=100, show_cols=False, indent=True, latest_partition=False, cols=None): """Generates a ``select *`` statement in the proper dialect""" eng = self.get_sqla_engine( schema=schema, source=utils.sources.get('sql_lab', N...
[ "Generates", "a", "select", "*", "statement", "in", "the", "proper", "dialect" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L908-L917
[ "def", "select_star", "(", "self", ",", "table_name", ",", "schema", "=", "None", ",", "limit", "=", "100", ",", "show_cols", "=", "False", ",", "indent", "=", "True", ",", "latest_partition", "=", "False", ",", "cols", "=", "None", ")", ":", "eng", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.all_table_names_in_database
Parameters need to be passed as keyword arguments.
superset/models/core.py
def all_table_names_in_database(self, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments.""" if not self.allow_multi_schema_metadata_fetch: return [] return self.db_engine_spec.fetch_result_sets(self...
def all_table_names_in_database(self, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments.""" if not self.allow_multi_schema_metadata_fetch: return [] return self.db_engine_spec.fetch_result_sets(self...
[ "Parameters", "need", "to", "be", "passed", "as", "keyword", "arguments", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L933-L938
[ "def", "all_table_names_in_database", "(", "self", ",", "cache", "=", "False", ",", "cache_timeout", "=", "None", ",", "force", "=", "False", ")", ":", "if", "not", "self", ".", "allow_multi_schema_metadata_fetch", ":", "return", "[", "]", "return", "self", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.all_table_names_in_schema
Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema name :type schema: str :param cache: whether cache is enabled for the function :type cache: bool :param cac...
superset/models/core.py
def all_table_names_in_schema(self, schema, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema nam...
def all_table_names_in_schema(self, schema, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema nam...
[ "Parameters", "need", "to", "be", "passed", "as", "keyword", "arguments", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L954-L978
[ "def", "all_table_names_in_schema", "(", "self", ",", "schema", ",", "cache", "=", "False", ",", "cache_timeout", "=", "None", ",", "force", "=", "False", ")", ":", "tables", "=", "[", "]", "try", ":", "tables", "=", "self", ".", "db_engine_spec", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.all_view_names_in_schema
Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema name :type schema: str :param cache: whether cache is enabled for the function :type cache: bool :param cac...
superset/models/core.py
def all_view_names_in_schema(self, schema, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema name ...
def all_view_names_in_schema(self, schema, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param schema: schema name ...
[ "Parameters", "need", "to", "be", "passed", "as", "keyword", "arguments", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L984-L1008
[ "def", "all_view_names_in_schema", "(", "self", ",", "schema", ",", "cache", "=", "False", ",", "cache_timeout", "=", "None", ",", "force", "=", "False", ")", ":", "views", "=", "[", "]", "try", ":", "views", "=", "self", ".", "db_engine_spec", ".", "g...
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.all_schema_names
Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param cache: whether cache is enabled for the function :type cache: bool :param cache_timeout: timeout in seconds for the cache :type ca...
superset/models/core.py
def all_schema_names(self, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param cache: whether cache is enabled for the function :type cache:...
def all_schema_names(self, cache=False, cache_timeout=None, force=False): """Parameters need to be passed as keyword arguments. For unused parameters, they are referenced in cache_util.memoized_func decorator. :param cache: whether cache is enabled for the function :type cache:...
[ "Parameters", "need", "to", "be", "passed", "as", "keyword", "arguments", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1013-L1028
[ "def", "all_schema_names", "(", "self", ",", "cache", "=", "False", ",", "cache_timeout", "=", "None", ",", "force", "=", "False", ")", ":", "return", "self", ".", "db_engine_spec", ".", "get_schema_names", "(", "self", ".", "inspector", ")" ]
ca2996c78f679260eb79c6008e276733df5fb653
train
Database.grains_dict
Allowing to lookup grain by either label or duration For backward compatibility
superset/models/core.py
def grains_dict(self): """Allowing to lookup grain by either label or duration For backward compatibility""" d = {grain.duration: grain for grain in self.grains()} d.update({grain.label: grain for grain in self.grains()}) return d
def grains_dict(self): """Allowing to lookup grain by either label or duration For backward compatibility""" d = {grain.duration: grain for grain in self.grains()} d.update({grain.label: grain for grain in self.grains()}) return d
[ "Allowing", "to", "lookup", "grain", "by", "either", "label", "or", "duration" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1050-L1056
[ "def", "grains_dict", "(", "self", ")", ":", "d", "=", "{", "grain", ".", "duration", ":", "grain", "for", "grain", "in", "self", ".", "grains", "(", ")", "}", "d", ".", "update", "(", "{", "grain", ".", "label", ":", "grain", "for", "grain", "in...
ca2996c78f679260eb79c6008e276733df5fb653
train
Log.log_this
Decorator to log user actions
superset/models/core.py
def log_this(cls, f): """Decorator to log user actions""" @functools.wraps(f) def wrapper(*args, **kwargs): user_id = None if g.user: user_id = g.user.get_id() d = request.form.to_dict() or {} # request parameters can overwrite pos...
def log_this(cls, f): """Decorator to log user actions""" @functools.wraps(f) def wrapper(*args, **kwargs): user_id = None if g.user: user_id = g.user.get_id() d = request.form.to_dict() or {} # request parameters can overwrite pos...
[ "Decorator", "to", "log", "user", "actions" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1143-L1200
[ "def", "log_this", "(", "cls", ",", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "None", "if", "g", ".", "user", ":", "user_id", "=", "g", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
api
A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format
superset/views/base.py
def api(f): """ A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as e: logging.exception(e) ...
def api(f): """ A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as e: logging.exception(e) ...
[ "A", "decorator", "to", "label", "an", "endpoint", "as", "an", "API", ".", "Catches", "uncaught", "exceptions", "and", "return", "the", "response", "in", "the", "JSON", "format" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L96-L108
[ "def", "api", "(", "f", ")", ":", "def", "wraps", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":",...
ca2996c78f679260eb79c6008e276733df5fb653
train
handle_api_exception
A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions.
superset/views/base.py
def handle_api_exception(f): """ A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions. """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) ...
def handle_api_exception(f): """ A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions. """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) ...
[ "A", "decorator", "to", "catch", "superset", "exceptions", ".", "Use", "it", "after", "the" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L111-L134
[ "def", "handle_api_exception", "(", "f", ")", ":", "def", "wraps", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "SupersetSecurity...
ca2996c78f679260eb79c6008e276733df5fb653