Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def increment_lessons(self, measure_vals, reward_buff_sizes=None): ret = {} if reward_buff_sizes: for brain_name, buff_size in reward_buff_sizes.items(): if self._lesson_ready_to_increment(brain_name, buff_size): ...
[ "Attempts to increments all the lessons of all the curriculums in this\n MetaCurriculum. Note that calling this method does not guarantee the\n lesson of a curriculum will increment. The lesson of a curriculum will\n only increment if the specified measure threshold defined in the\n curr...
Please provide a description of the function:def set_all_curriculums_to_lesson_num(self, lesson_num): for _, curriculum in self.brains_to_curriculums.items(): curriculum.lesson_num = lesson_num
[ "Sets all the curriculums in this meta curriculum to a specified\n lesson number.\n\n Args:\n lesson_num (int): The lesson number which all the curriculums will\n be set to.\n " ]
Please provide a description of the function:def get_config(self): config = {} for _, curriculum in self.brains_to_curriculums.items(): curr_config = curriculum.get_config() config.update(curr_config) return config
[ "Get the combined configuration of all curriculums in this\n MetaCurriculum.\n\n Returns:\n A dict from parameter to value.\n " ]
Please provide a description of the function:def reset(self, config=None, train_mode=True, custom_reset_parameters=None) -> AllBrainInfo: if config is None: config = self._resetParameters elif config: logger.info("Academy reset with parameters: {0}" ...
[ "\n Sends a signal to reset the unity environment.\n :return: AllBrainInfo : A data structure corresponding to the initial reset state of the environment.\n " ]
Please provide a description of the function:def step(self, vector_action=None, memory=None, text_action=None, value=None, custom_action=None) -> AllBrainInfo: vector_action = {} if vector_action is None else vector_action memory = {} if memory is None else memory text_action = {} if te...
[ "\n Provides the environment with an action, moves the environment dynamics forward accordingly,\n and returns observation, state, and reward information to the agent.\n :param value: Value estimates provided by agents.\n :param vector_action: Agent's vector action. Can be a scalar or ve...
Please provide a description of the function:def _flatten(cls, arr) -> List[float]: if isinstance(arr, cls.SCALAR_ACTION_TYPES): arr = [float(arr)] if isinstance(arr, np.ndarray): arr = arr.tolist() if len(arr) == 0: return arr if isinstance(a...
[ "\n Converts arrays to list.\n :param arr: numpy vector.\n :return: flattened list.\n " ]
Please provide a description of the function:def _get_state(self, output: UnityRLOutput) -> (AllBrainInfo, bool): _data = {} global_done = output.global_done for brain_name in output.agentInfos: agent_info_list = output.agentInfos[brain_name].value _data[brain_na...
[ "\n Collects experience information from all external brains in environment at current step.\n :return: a dictionary of BrainInfo objects.\n " ]
Please provide a description of the function:def end_experience_collection_timer(self): if self.time_start_experience_collection: curr_delta = time() - self.time_start_experience_collection if self.delta_last_experience_collection is None: self.delta_last_experie...
[ "\n Inform Metrics class that experience collection is done.\n " ]
Please provide a description of the function:def add_delta_step(self, delta: float): if self.delta_last_experience_collection: self.delta_last_experience_collection += delta else: self.delta_last_experience_collection = delta
[ "\n Inform Metrics class about time to step in environment.\n " ]
Please provide a description of the function:def start_policy_update_timer(self, number_experiences: int, mean_return: float): self.last_buffer_length = number_experiences self.last_mean_return = mean_return self.time_policy_update_start = time()
[ "\n Inform Metrics class that policy update has started.\n :int number_experiences: Number of experiences in Buffer at this point.\n :float mean_return: Return averaged across all cumulative returns since last policy update\n " ]
Please provide a description of the function:def end_policy_update(self): if self.time_policy_update_start: self.delta_policy_update = time() - self.time_policy_update_start else: self.delta_policy_update = 0 delta_train_start = time() - self.time_training_start ...
[ "\n Inform Metrics class that policy update has started.\n " ]
Please provide a description of the function:def write_training_metrics(self): with open(self.path, 'w') as file: writer = csv.writer(file) writer.writerow(FIELD_NAMES) for row in self.rows: writer.writerow(row)
[ "\n Write Training Metrics to CSV\n " ]
Please provide a description of the function:def create_reward_encoder(): 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.assign(last_reward, new_reward) ...
[ "Creates TF ops to track and increment recent average cumulative reward." ]
Please provide a description of the function:def create_curiosity_encoders(self): encoded_state_list = [] encoded_next_state_list = [] if self.vis_obs_size > 0: self.next_visual_in = [] visual_encoders = [] next_visual_encoders = [] for i...
[ "\n Creates state encoders for current and future observations.\n Used for implementation of Curiosity-driven Exploration by Self-supervised Prediction\n See https://arxiv.org/abs/1705.05363 for more details.\n :return: current and future state encoder tensors.\n " ]
Please provide a description of the function:def create_inverse_model(self, encoded_state, encoded_next_state): combined_input = tf.concat([encoded_state, encoded_next_state], axis=1) hidden = tf.layers.dense(combined_input, 256, activation=self.swish) if self.brain.vector_action_space_...
[ "\n Creates inverse model TensorFlow ops for Curiosity module.\n Predicts action taken given current and future encoded states.\n :param encoded_state: Tensor corresponding to encoded current state.\n :param encoded_next_state: Tensor corresponding to encoded next state.\n " ]
Please provide a description of the function:def create_forward_model(self, encoded_state, encoded_next_state): combined_input = tf.concat([encoded_state, self.selected_actions], axis=1) hidden = tf.layers.dense(combined_input, 256, activation=self.swish) # We compare against the concat...
[ "\n Creates forward model TensorFlow ops for Curiosity module.\n Predicts encoded future state based on encoded current state and given action.\n :param encoded_state: Tensor corresponding to encoded current state.\n :param encoded_next_state: Tensor corresponding to encoded next state.\...
Please provide a description of the function:def create_ppo_optimizer(self, probs, old_probs, value, entropy, beta, epsilon, lr, max_step): self.returns_holder = tf.placeholder(shape=[None], dtype=tf.float32, name='discounted_rewards') self.advantage = tf.placeholder(shape=[None, 1], dtype=tf.f...
[ "\n Creates training-specific Tensorflow ops for PPO models.\n :param probs: Current policy probabilities\n :param old_probs: Past policy probabilities\n :param value: Current value estimate\n :param beta: Entropy regularization strength\n :param entropy: Current policy ent...
Please provide a description of the function:def evaluate(self, brain_info): feed_dict = {self.model.batch_size: len(brain_info.vector_observations), self.model.sequence_length: 1} epsilon = None if self.use_recurrent: if not self.use_continuous_act: ...
[ "\n Evaluates policy for the agent experiences provided.\n :param brain_info: BrainInfo object containing inputs.\n :return: Outputs from network as defined by self.inference_dict.\n " ]
Please provide a description of the function:def update(self, mini_batch, num_sequences): feed_dict = {self.model.batch_size: num_sequences, self.model.sequence_length: self.sequence_length, self.model.mask_input: mini_batch['masks'].flatten(), ...
[ "\n Updates model using buffer.\n :param num_sequences: Number of trajectories in batch.\n :param mini_batch: Experience batch.\n :return: Output from update process.\n " ]
Please provide a description of the function:def get_intrinsic_rewards(self, curr_info, next_info): if self.use_curiosity: if len(curr_info.agents) == 0: return [] feed_dict = {self.model.batch_size: len(next_info.vector_observations), s...
[ "\n Generates intrinsic reward used for Curiosity-based training.\n :BrainInfo curr_info: Current BrainInfo.\n :BrainInfo next_info: Next BrainInfo.\n :return: Intrinsic rewards for all agents.\n " ]
Please provide a description of the function:def get_value_estimate(self, brain_info, idx): feed_dict = {self.model.batch_size: 1, self.model.sequence_length: 1} for i in range(len(brain_info.visual_observations)): feed_dict[self.model.visual_in[i]] = [brain_info.visual_observations...
[ "\n Generates value estimates for bootstrapping.\n :param brain_info: BrainInfo to be used for bootstrapping.\n :param idx: Index in BrainInfo of agent.\n :return: Value estimate.\n " ]
Please provide a description of the function:def update_reward(self, new_reward): self.sess.run(self.model.update_reward, feed_dict={self.model.new_reward: new_reward})
[ "\n Updates reward value for policy.\n :param new_reward: New reward to save.\n " ]
Please provide a description of the function: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.brain_name] next_info_student = ...
[ "\n Adds experiences to each agent's experience history.\n :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).\n :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).\n :param take_action_out...
Please provide a description of the function:def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): info_student = next_info[self.brain_name] for l in range(len(info_student.agents)): if info_student.local_done[l]: agent_id = info_student...
[ "\n Checks agent histories for processing condition, and processes them as necessary.\n Processing involves calculating value and advantage targets for model updating step.\n :param current_info: Current AllBrainInfo\n :param next_info: Next AllBrainInfo\n " ]
Please provide a description of the function:def end_episode(self): self.evaluation_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 for agent_id in self.episode_steps: self.episode_steps[agent_id] = 0
[ "\n A signal that the Episode has ended. The buffer must be reset.\n Get only called when the academy resets.\n " ]
Please provide a description of the function:def update_policy(self): 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) ...
[ "\n Updates the policy.\n " ]
Please provide a description of the function:def create_global_steps(): 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." ]
Please provide a description of the function:def create_visual_input(camera_parameters, name): o_size_h = camera_parameters['height'] o_size_w = camera_parameters['width'] bw = camera_parameters['blackAndWhite'] if bw: c_channels = 1 else: c_chan...
[ "\n Creates image input op.\n :param camera_parameters: Parameters for visual observation from BrainInfo.\n :param name: Desired name of input op.\n :return: input op.\n " ]
Please provide a description of the function:def create_vector_input(self, name='vector_observation'): self.vector_in = tf.placeholder(shape=[None, self.vec_obs_size], dtype=tf.float32, name=name) if self.normalize: self.running_mean = tf.get_...
[ "\n Creates ops for vector observation input.\n :param name: Name of the placeholder op.\n :param vec_obs_size: Size of stacked vector observation.\n :return:\n " ]
Please provide a description of the function:def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope, reuse): with tf.variable_scope(scope): hidden = observation_input for i in range(num_layers): ...
[ "\n Builds a set of hidden state encoders.\n :param reuse: Whether to re-use the weights within the same scope.\n :param scope: Graph scope for the encoder ops.\n :param observation_input: Input vector.\n :param h_size: Hidden layer size.\n :param activation: What type of a...
Please provide a description of the function:def create_visual_observation_encoder(self, image_input, h_size, activation, num_layers, scope, reuse): with tf.variable_scope(scope): conv1 = tf.layers.conv2d(image_input, 16, kernel_size=[8, 8], strides...
[ "\n Builds a set of visual (CNN) encoders.\n :param reuse: Whether to re-use the weights within the same scope.\n :param scope: The scope of the graph within which to create the ops.\n :param image_input: The placeholder for the image input to use.\n :param h_size: Hidden layer si...
Please provide a description of the function:def create_discrete_action_masking_layer(all_logits, action_masks, action_size): action_idx = [0] + list(np.cumsum(action_size)) branches_logits = [all_logits[:, action_idx[i]:action_idx[i + 1]] for i in range(len(action_size))] branch_masks ...
[ "\n Creates a masking layer for the discrete actions\n :param all_logits: The concatenated unnormalized action probabilities for all branches\n :param action_masks: The mask for the logits. Must be of dimension [None x total_number_of_action]\n :param action_size: A list containing the n...
Please provide a description of the function:def create_observation_streams(self, num_streams, h_size, num_layers): brain = self.brain activation_fn = self.swish self.visual_in = [] for i in range(brain.number_visual_observations): visual_input = self.create_visual_...
[ "\n Creates encoding stream for observations.\n :param num_streams: Number of streams to create.\n :param h_size: Size of hidden linear layers in stream.\n :param num_layers: Number of hidden linear layers in stream.\n :return: List of encoded streams.\n " ]
Please provide a description of the function:def create_recurrent_encoder(input_state, memory_in, sequence_length, name='lstm'): s_size = input_state.get_shape().as_list()[1] m_size = memory_in.get_shape().as_list()[1] lstm_input_state = tf.reshape(input_state, shape=[-1, sequence_lengt...
[ "\n Builds a recurrent encoder for either state or observations (LSTM).\n :param sequence_length: Length of sequence to unroll.\n :param input_state: The input tensor to the LSTM cell.\n :param memory_in: The input memory to the LSTM cell.\n :param name: The scope of the LSTM cell...
Please provide a description of the function: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.memory_in = tf.placeholder(shape=[None, self.m_size], dtype=tf.float32, ...
[ "\n Creates Continuous control actor-critic model.\n :param h_size: Size of hidden linear layers.\n :param num_layers: Number of hidden linear layers.\n " ]
Please provide a description of the function: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 self.use_recurrent: self.prev_action = tf.placeholder(shape=[None, len(se...
[ "\n Creates Discrete control actor-critic model.\n :param h_size: Size of hidden linear layers.\n :param num_layers: Number of hidden linear layers.\n " ]
Please provide a description of the function: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.brain_to_imitate] next_info_tea...
[ "\n Adds experiences to each agent's experience history.\n :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).\n :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).\n :param take_action_out...
Please provide a description of the function:def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo): info_teacher = next_info[self.brain_to_imitate] for l in range(len(info_teacher.agents)): teacher_action_list = len(self.demonstration_buffer[info_teacher...
[ "\n Checks agent histories for processing condition, and processes them as necessary.\n Processing involves calculating value and advantage targets for model updating step.\n :param current_info: Current AllBrainInfo\n :param next_info: Next AllBrainInfo\n " ]
Please provide a description of the function: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 enter(x): yield from flatten(x) else: yield...
[ "Yield items from any nested iterable; see REF." ]
Please provide a description of the function: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(potentia...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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[3]] return [shape[1], shape[2]]
[ " Convert from NHWC|NCHW => HW\n " ]
Please provide a description of the function:def convert(source_file, target_file, trim_unused_by_output="", verbose=False, compress_f16=False): if (type(verbose)==bool): args = Struct() args.verbose = verbose args.print_layers = verbose args.print_source_json = verbose ...
[ "\n Converts a TensorFlow model into a Barracuda model.\n :param source_file: The TensorFlow Model\n :param target_file: The name of the file the converted model will be saved to\n :param trim_unused_by_output: The regexp to match output nodes to remain in the model. All other uconnected nodes will be r...
Please provide a description of the function: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, sequence_length) return brain_params, demo_buffer
[ "\n Loads demonstration file and uses it to fill training buffer.\n :param file_path: Location of demonstration file (.demo).\n :param sequence_length: Length of trajectories to fill buffer.\n :return:\n " ]
Please provide a description of the function: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 file {} does not exist.".format(file_path)) file_extension = pathl...
[ "\n Loads and parses a demonstration file.\n :param file_path: Location of demonstration file (.demo).\n :return: BrainParameter and list of BrainInfos containing demonstration data.\n " ]
Please provide a description of the function:def _save_model(self, steps=0): for brain_name in self.trainers.keys(): self.trainers[brain_name].save_model() self.logger.info('Saved Model')
[ "\n Saves current model to checkpoint folder.\n :param steps: Current number of steps in training process.\n :param saver: Tensorflow saver for session.\n " ]
Please provide a description of the function:def _write_training_metrics(self): for brain_name in self.trainers.keys(): if brain_name in self.trainer_metrics: self.trainers[brain_name].write_training_metrics()
[ "\n Write all CSV metrics\n :return:\n " ]
Please provide a description of the function:def _export_graph(self): for brain_name in self.trainers.keys(): self.trainers[brain_name].export_model()
[ "\n Exports latest saved models to .nn format for Unity embedding.\n " ]
Please provide a description of the function:def initialize_trainers(self, trainer_config: Dict[str, Dict[str, str]]): trainer_parameters_dict = {} for brain_name in self.external_brains: trainer_parameters = trainer_config['default'].copy() trainer_parameters['summary_p...
[ "\n Initialization of the trainers\n :param trainer_config: The configurations of the trainers\n " ]
Please provide a description of the function:def _reset_env(self, env: BaseUnityEnvironment): if self.meta_curriculum is not None: return env.reset(train_mode=self.fast_simulation, config=self.meta_curriculum.get_config()) else: return env.reset(train_mode=self.fast_simu...
[ "Resets the environment.\n\n Returns:\n A Data structure corresponding to the initial reset state of the\n environment.\n " ]
Please provide a description of the function:def close(self): if self._socket is not None and self._conn is not None: message_input = UnityMessage() message_input.header.status = 400 self._communicator_send(message_input.SerializeToString()) if self._socket i...
[ "\n Sends a shutdown signal to the unity environment, and closes the socket connection.\n " ]
Please provide a description of the function: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) bias = beta - gamma * mean / np.sqrt(var + epsilon) return [scale, bias]
[ " float sqrt_var = sqrt(var_data[i]);\n a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var;\n b_data[i] = slope_data[i] / sqrt_var;\n ...\n ptr[i] = b * ptr[i] + a;\n " ]
Please provide a description of the function: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); re...
[]
Please provide a description of the function: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) ...
[]
Please provide a description of the function: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(X...
[]
Please provide a description of the function:def evaluate(self, brain_info): feed_dict = {self.model.dropout_rate: self.evaluate_rate, self.model.sequence_length: 1} feed_dict = self._fill_eval_dict(feed_dict, brain_info) if self.use_recurrent: if brain...
[ "\n Evaluates policy for the agent experiences provided.\n :param brain_info: BrainInfo input to network.\n :return: Results of evaluation.\n " ]
Please provide a description of the function:def update(self, mini_batch, num_sequences): feed_dict = {self.model.dropout_rate: self.update_rate, self.model.batch_size: num_sequences, self.model.sequence_length: self.sequence_length} if self.use_contin...
[ "\n Performs update on model.\n :param mini_batch: Batch of experiences.\n :param num_sequences: Number of sequences to process.\n :return: Results of update.\n " ]
Please provide a description of the function: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_smoothing']: measure_val = self.smoothing_value * 0.25 + 0.75 * measure_val ...
[ "\n Increments the lesson number depending on the progress given.\n :param measure_val: Measure of progress (either reward or percentage\n steps completed).\n :return Whether the lesson was incremented.\n " ]
Please provide a description of the function:def get_config(self, lesson=None): if not self.data: return {} if lesson is None: lesson = self.lesson_num lesson = max(0, min(lesson, self.max_lesson_num)) config = {} parameters = self.data['parameter...
[ "\n Returns reset parameters which correspond to the lesson.\n :param lesson: The lesson you want to get the config of. If None, the\n current lesson is returned.\n :return: The configuration of the reset parameters.\n " ]
Please provide a description of the function:def get_gae(rewards, value_estimates, value_next=0.0, gamma=0.99, lambd=0.95): value_estimates = np.asarray(value_estimates.tolist() + [value_next]) delta_t = rewards + gamma * value_estimates[1:] - value_estimates[:-1] advantage = discount_rewards(r=delta_t...
[ "\n Computes generalized advantage estimate for use in updating policy.\n :param rewards: list of rewards for time-steps t to T.\n :param value_next: Value estimate for time-step T+1.\n :param value_estimates: list of value estimates for time-steps t to T.\n :param gamma: Discount factor.\n :param...
Please provide a description of the function:def increment_step_and_update_last_reward(self): if len(self.stats['Environment/Cumulative Reward']) > 0: mean_reward = np.mean(self.stats['Environment/Cumulative Reward']) self.policy.update_reward(mean_reward) self.policy.in...
[ "\n Increment the step count of the trainer and Updates the last reward\n " ]
Please provide a description of the function:def construct_curr_info(self, next_info: BrainInfo) -> BrainInfo: visual_observations = [[]] vector_observations = [] text_observations = [] memories = [] rewards = [] local_dones = [] max_reacheds = [] ...
[ "\n Constructs a BrainInfo which contains the most recent previous experiences for all agents info\n which correspond to the agents in a provided next_info.\n :BrainInfo next_info: A t+1 BrainInfo.\n :return: curr_info: Reconstructed BrainInfo to match agents of next_info.\n " ]
Please provide a description of the function: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_outputs: self.stats['Policy/Value Estimate'].append(take_act...
[ "\n Adds experiences to each agent's experience history.\n :param curr_all_info: Dictionary of all current brains and corresponding BrainInfo.\n :param next_all_info: Dictionary of all current brains and corresponding BrainInfo.\n :param take_action_outputs: The outputs of the Policy's g...
Please provide a description of the function:def process_experiences(self, current_info: AllBrainInfo, new_info: AllBrainInfo): self.trainer_metrics.start_experience_collection_timer() info = new_info[self.brain_name] for l in range(len(info.agents)): agent_actions = self.tr...
[ "\n Checks agent histories for processing condition, and processes them as necessary.\n Processing involves calculating value and advantage targets for model updating step.\n :param current_info: Dictionary of all current brains and corresponding BrainInfo.\n :param new_info: Dictionary ...
Please provide a description of the function:def end_episode(self): self.training_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 for agent_id in self.episode_steps: self.episode_steps[agent_id] = 0 ...
[ "\n A signal that the Episode has ended. The buffer must be reset.\n Get only called when the academy resets.\n " ]
Please provide a description of the function:def is_ready_update(self): size_of_buffer = len(self.training_buffer.update_buffer['actions']) return size_of_buffer > max(int(self.trainer_parameters['buffer_size'] / self.policy.sequence_length), 1)
[ "\n Returns whether or not the trainer has enough elements to run update model\n :return: A boolean corresponding to whether or not update_model() can be run\n " ]
Please provide a description of the function:def update_policy(self): 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_update))) n_sequenc...
[ "\n Uses demonstration_buffer to update the policy.\n " ]
Please provide a description of the function:def reset(self): info = self._env.reset()[self.brain_name] n_agents = len(info.agents) self._check_agents(n_agents) self.game_over = False if not self._multiagent: obs, reward, done, info = self._single_step(info)...
[ "Resets the state of the environment and returns an initial observation.\n In the case of multi-agent environments, this is a list.\n Returns: observation (object/list): the initial observation of the\n space.\n " ]
Please provide a description of the function:def step(self, action): # Use random actions for all other agents in environment. if self._multiagent: if not isinstance(action, list): raise UnityGymException("The environment was expecting `action` to be a list.") ...
[ "Run one timestep of the environment's dynamics. When end of\n episode is reached, you are responsible for calling `reset()`\n to reset this environment's state.\n Accepts an action and returns a tuple (observation, reward, done, info).\n In the case of multi-agent environments, these ar...
Please provide a description of the function:def _create_lookup(self, branched_action_space): possible_vals = [range(_num) for _num in branched_action_space] all_actions = [list(_action) for _action in itertools.product(*possible_vals)] # Dict should be faster than List for large action...
[ "\n Creates a Dict that maps discrete actions (scalars) to branched actions (lists).\n Each key in the Dict maps to one unique set of branched actions, and each value\n contains the List of branched actions.\n " ]
Please provide a description of the function:def create_server(self): self.check_port(self.port) try: # Establish communication grpc self.server = grpc.server(ThreadPoolExecutor(max_workers=10)) self.unity_to_external = UnityToExternalServicerImplementation(...
[ "\n Creates the GRPC server.\n " ]
Please provide a description of the function:def check_port(self, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("localhost", port)) except socket.error: raise UnityWorkerInUseException(self.worker_id) finally: s.clo...
[ "\n Attempts to bind to the requested communicator port, checking if it is already in use.\n " ]
Please provide a description of the function:def close(self): if self.is_open: message_input = UnityMessage() message_input.header.status = 400 self.unity_to_external.parent_conn.send(message_input) self.unity_to_external.parent_conn.close() s...
[ "\n Sends a shutdown signal to the unity environment, and closes the grpc connection.\n " ]
Please provide a description of the function:def process_pixels(image_bytes, gray_scale): s = bytearray(image_bytes) image = Image.open(io.BytesIO(s)) s = np.array(image) / 255.0 if gray_scale: s = np.mean(s, axis=2) s = np.reshape(s, [s.shape[0], s.shape...
[ "\n Converts byte array observation image into numpy array, re-sizes it,\n and optionally converts it to grey scale\n :param gray_scale: Whether to convert the image to grayscale.\n :param image_bytes: input byte array corresponding to image\n :return: processed numpy array of obs...
Please provide a description of the function:def from_agent_proto(agent_info_list, brain_params): vis_obs = [] for i in range(brain_params.number_visual_observations): obs = [BrainInfo.process_pixels(x.visual_observations[i], brain_params....
[ "\n Converts list of agent infos to BrainInfo.\n " ]
Please provide a description of the function:def from_proto(brain_param_proto): resolution = [{ "height": x.height, "width": x.width, "blackAndWhite": x.gray_scale } for x in brain_param_proto.camera_resolutions] brain_params = BrainParameters(brain_p...
[ "\n Converts brain parameter proto to BrainParameter object.\n :param brain_param_proto: protobuf object.\n :return: BrainParameter object.\n " ]
Please provide a description of the function:def new(self): new_dashboard = models.Dashboard( dashboard_title='[ untitled dashboard ]', owners=[g.user], ) db.session.add(new_dashboard) db.session.commit() return redirect(f'/superset/dashboard/{new...
[ "Creates a new, blank dashboard and redirects to it in edit mode" ]
Please provide a description of the function:def get(self, object_type, object_id): if object_id == 0: return json_success(json.dumps([])) query = db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, TaggedObject.object_id == ...
[ "List all tags a given object has." ]
Please provide a description of the function:def post(self, object_type, object_id): 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." ]
Please provide a description of the function:def delete(self, object_type, object_id): 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, ...
[ "Remove tags from an object." ]
Please provide a description of the function:def import_datasource( session, i_datasource, lookup_database, lookup_datasource, import_time): make_transient(i_datasource) logging.info('Started import of the datasource: {}'.format( i_datasource.to_json())) ...
[ "Imports the datasource from the object to the database.\n\n Metrics and columns and datasource will be overrided if exists.\n This function can be used to import/export dashboards between multiple\n superset instances. Audit metadata isn't copies over.\n " ]
Please provide a description of the function: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,...
[ "Run migrations in 'online' mode.\n\n In this scenario we need to create an Engine\n and associate a connection with the context.\n\n " ]
Please provide a description of the function: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_format = None if self.datasource.type == 'table': ...
[ "Returns a pandas dataframe based on the query object" ]
Please provide a description of the function:def query_obj(self): 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 g...
[ "Building a query object" ]
Please provide a description of the function:def cache_key(self, query_obj, **extra): cache_dict = copy.copy(query_obj) cache_dict.update(extra) for k in ['from_dttm', 'to_dttm']: del cache_dict[k] cache_dict['time_range'] = self.form_data.get('time_range') ...
[ "\n The cache key is made out of the key/values in `query_obj`, plus any\n other key/values in `extra`.\n\n We remove datetime bounds that are hard values, and replace them with\n the use-provided inputs to bounds, which may be time-relative (as in\n \"5 days ago\" or \"now\").\n\...
Please provide a description of the function:def data(self): content = { 'form_data': self.form_data, 'token': self.token, 'viz_name': self.viz_type, 'filter_select_enabled': self.datasource.filter_select_enabled, } return content
[ "This is the data object serialized to the js layer" ]
Please provide a description of the function:def query_obj(self): 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" ]
Please provide a description of the function:def get_data(self, df): chart_data = [] if len(self.groupby) > 0: groups = df.groupby(self.groupby) else: groups = [((), df)] for keys, data in groups: chart_data.extend([{ 'key': se...
[ "Returns the chart data" ]
Please provide a description of the function:def levels_for(self, time_op, groups, df): 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 == 'agg_mean' else ...
[ "\n Compute the partition at each `level` from the dataframe.\n " ]
Please provide a description of the function:def nest_values(self, levels, level=0, metric=None, dims=()): if not level: return [{ 'name': m, 'val': levels[0][m], 'children': self.nest_values(levels, 1, m), } for m in levels[0].ind...
[ "\n Nest values at each level on the back-end with\n access and setting, instead of summing from the bottom.\n " ]
Please provide a description of the function:def short_data(self): return { 'edit_url': self.url, 'id': self.id, 'uid': self.uid, 'schema': self.schema, 'name': self.name, 'type': self.type, 'connection': self.connectio...
[ "Data representation of the datasource sent to the frontend" ]
Please provide a description of the function: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((json.dumps([s, True]), s + ' [asc]')) order_by_choi...
[ "Data representation of the datasource sent to the frontend" ]
Please provide a description of the function: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 = [o.get(key_attr) for o in object_list] # delete fks that have been removed ...
[ "Update ORM one-to-many list from object list\n\n Used for syncing metrics and columns using the same code" ]
Please provide a description of the function:def update_from_object(self, obj): for attr in self.update_from_object_fields: setattr(self, attr, obj.get(attr)) self.owners = obj.get('owners', []) # Syncing metrics metrics = self.get_fk_many_from_list( ob...
[ "Update datasource from a data structure\n\n The UI's table editor crafts a complex data structure that\n contains most of the datasource's properties as well as\n an array of metrics and columns objects. This method\n receives the object from the UI and syncs the datasource to\n ...
Please provide a description of the function: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 d...
[ "Returns a pandas dataframe based on the query object" ]
Please provide a description of the function:def df_metrics_to_num(self, df, query_object): 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_numeric(df[col], err...
[ "Converting metrics to numeric when pandas.read_sql cannot" ]
Please provide a description of the function:def get_single_payload(self, query_obj): 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" ]
Please provide a description of the function:def get_df_payload(self, query_obj, **kwargs): 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 stacktrace ...
[ "Handles caching around the df paylod retrieval" ]
Please provide a description of the function:def data(self): 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 { 'da...
[ "Data used to render slice in templates" ]
Please provide a description of the function:def get_viz(self, force=False): slice_params = json.loads(self.params) slice_params['slice_id'] = self.id slice_params['json'] = 'false' slice_params['slice_name'] = self.slice_name slice_params['viz_type'] = self.viz_type if ...
[ "Creates :py:class:viz.BaseViz object from the url_params_multidict.\n\n :return: object of the 'viz_type' type that is taken from the\n url_params_multidict or self.params.\n :rtype: :py:class:viz.BaseViz\n " ]