docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Gets path from query string
Args:
req (flask.request): Request object from Flask
Returns:
path (str): Value of "path" parameter from query string
Raises:
exceptions.UserError: If "path" is not found in query string | def get_path_from_query_string(req):
if req.args.get('path') is None:
raise exceptions.UserError('Path not found in query string')
return req.args.get('path') | 444,372 |
Initialize context manager
Args:
path (str, unicode): Path to project folder | def __init__(self, path):
self.path = os.path.join(path, app.config['XCESSIV_NOTEBOOK_NAME']) | 444,373 |
Returns path for meta-features
Args:
path (str): Absolute/local path of xcessiv folder | def meta_features_path(self, path):
return os.path.join(
path,
app.config['XCESSIV_META_FEATURES_FOLDER'],
str(self.id)
) + '.npy' | 444,391 |
Deletes meta-features of base learner if it exists
Args:
path (str): Absolute/local path of xcessiv folder | def delete_meta_features(self, path):
if os.path.exists(self.meta_features_path(path)):
os.remove(self.meta_features_path(path)) | 444,393 |
Returns a string value that contains the Python code for the ensemble
Args:
cv_source (str, unicode): String containing actual code for base learner
cross-validation used to generate secondary meta-features.
Returns:
base_learner_code (str, unicode): String that... | def export_as_code(self, cv_source):
rand_value = ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(25))
base_learner_code = ''
base_learner_code += 'base_learner_list_{} = []\n'.format(rand_value)
base_learner_code += 'm... | 444,396 |
Export the ensemble as a single Python file and saves it to `file_path`.
This is EXPERIMENTAL as putting different modules together would probably wreak havoc
especially on modules that make heavy use of global variables.
Args:
file_path (str, unicode): Absolute/local path of place... | def export_as_file(self, file_path, cv_source):
if os.path.exists(file_path):
raise exceptions.UserError('{} already exists'.format(file_path))
with open(file_path, 'wb') as f:
f.write(self.export_as_code(cv_source).encode('utf8')) | 444,397 |
Exports the ensemble as a Python package and saves it to `package_path`.
Args:
package_path (str, unicode): Absolute/local path of place to save package in
cv_source (str, unicode): String containing actual code for base learner
cross-validation used to generate seconda... | def export_as_package(self, package_path, cv_source):
if os.path.exists(package_path):
raise exceptions.UserError('{} already exists'.format(package_path))
package_name = os.path.basename(os.path.normpath(package_path))
os.makedirs(package_path)
# Write __init__.p... | 444,398 |
Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary learner
has the method.
Args:
X (array-like)... | def _process_using_meta_feature_generator(self, X, meta_feature_generator):
all_learner_meta_features = []
for idx, base_learner in enumerate(self.base_learners):
single_learner_meta_features = getattr(base_learner,
self.meta_featu... | 444,423 |
Build the data structure for a new event.
Args:
type: An event type.
id: The uuid identifier for the event.
data: A dict containing data for the event. These data
must be json serializable.
metadata: A dict containing metadata about the event.
These must be j... | def NewEvent(
type: str, id: UUID = None, data: JsonDict = None, metadata: JsonDict = None
) -> NewEventData:
return NewEventData(id or uuid4(), type, data, metadata) | 444,505 |
Count learnable parameters.
Args:
scope: Restrict the count to a variable scope.
exclude: Regex to match variable names to exclude.
graph: Operate on a graph other than the current default graph.
Returns:
Number of learnable parameters as integer. | def count_weights(scope=None, exclude=None, graph=None):
if scope:
scope = scope if scope.endswith('/') else scope + '/'
graph = graph or tf.get_default_graph()
vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if scope:
vars_ = [var for var in vars_ if var.name.startswith(scope)]
if e... | 444,879 |
Empirical KL divergence of two normals with diagonal covariance.
Args:
lhs: Diagonal Normal distribution.
rhs: Diagonal Normal distribution.
name: Name scope for the op.
Returns:
KL divergence from lhs to rhs. | def _custom_diag_normal_kl(lhs, rhs, name=None): # pylint: disable=unused-argument
with tf.name_scope(name or 'kl_divergence'):
mean0 = lhs.mean()
mean1 = rhs.mean()
logstd0 = tf.log(lhs.stddev())
logstd1 = tf.log(rhs.stddev())
logstd0_2, logstd1_2 = 2 * logstd0, 2 * logstd1
return 0.5 * (... | 444,880 |
Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via attributes. | def define_simulation_graph(batch_env, algo_cls, config):
# pylint: disable=unused-variable
step = tf.Variable(0, False, dtype=tf.int32, name='global_step')
is_training = tf.placeholder(tf.bool, name='is_training')
should_log = tf.placeholder(tf.bool, name='should_log')
do_report = tf.placeholder(tf.bool, ... | 444,883 |
Create environments and apply all desired wrappers.
Args:
constructor: Constructor of an OpenAI gym environment.
num_agents: Number of environments to combine in the batch.
env_processes: Whether to step environment in external processes.
Returns:
In-graph environments object. | def define_batch_env(constructor, num_agents, env_processes):
with tf.variable_scope('environments'):
if env_processes:
envs = [
tools.wrappers.ExternalProcess(constructor)
for _ in range(num_agents)]
else:
envs = [constructor() for _ in range(num_agents)]
batch_env = to... | 444,884 |
Create a saver for the variables we want to checkpoint.
Args:
exclude: List of regexes to match variable names to exclude.
Returns:
Saver object. | def define_saver(exclude=None):
variables = []
exclude = exclude or []
exclude = [re.compile(regex) for regex in exclude]
for variable in tf.global_variables():
if any(regex.match(variable.name) for regex in exclude):
continue
variables.append(variable)
saver = tf.train.Saver(variables, keep_... | 444,885 |
Save a new configuration by name.
If a logging directory is specified, is will be created and the configuration
will be stored there. Otherwise, a log message will be printed.
Args:
config: Configuration object.
logdir: Location for writing summaries and checkpoints if specified.
Returns:
Configu... | def save_config(config, logdir=None):
if logdir:
with config.unlocked:
config.logdir = logdir
message = 'Start a new run and write summaries and checkpoints to {}.'
tf.logging.info(message.format(config.logdir))
tf.gfile.MakeDirs(config.logdir)
config_path = os.path.join(config.logdir, 'c... | 444,887 |
Load a configuration from the log directory.
Args:
logdir: The logging directory containing the configuration file.
Raises:
IOError: The logging directory does not contain a configuration file.
Returns:
Configuration object. | def load_config(logdir):
# pylint: disable=missing-raises-doc
config_path = logdir and os.path.join(logdir, 'config.yaml')
if not config_path or not tf.gfile.Exists(config_path):
message = (
'Cannot resume an existing run since the logging directory does not '
'contain a configuration file.... | 444,888 |
Generate random agent input and keep track of statistics.
Args:
observ_shape: Shape for the random observations.
action_shape: Shape for the action space.
min_duration: Minimum number of steps per episode.
max_duration: Maximum number of steps per episode.
Attributes:
steps: List... | def __init__(self, observ_shape, action_shape, min_duration, max_duration):
self._observ_shape = observ_shape
self._action_shape = action_shape
self._min_duration = min_duration
self._max_duration = max_duration
self._random = np.random.RandomState(0)
self.steps = []
self.durations = [] | 444,891 |
Constructor for an instance of the environment.
Args:
config: Object providing configurations via attributes.
outdir: Directory to store videos in.
Raises:
NotImplementedError: For action spaces other than Box and Discrete.
Returns:
Wrapped OpenAI Gym environment. | def _create_environment(config, outdir):
if isinstance(config.env, str):
env = gym.make(config.env)
else:
env = config.env()
# Ensure that the environment has the specification attribute set as expected
# by the monitor wrapper.
if not hasattr(env, 'spec'):
setattr(env, 'spec', getattr(env, 'sp... | 444,896 |
Create and configure an evaluation loop.
Args:
graph: Object providing graph elements via attributes.
eval_steps: Number of evaluation steps per epoch.
Returns:
Loop object. | def _define_loop(graph, eval_steps):
loop = tools.Loop(
None, graph.step, graph.should_log, graph.do_report, graph.force_reset)
loop.add_phase(
'eval', graph.done, graph.score, graph.summary, eval_steps,
report_every=eval_steps,
log_every=None,
checkpoint_every=None,
feed={gra... | 444,897 |
Recover checkpoint and render videos from it.
Args:
logdir: Logging directory of the trained algorithm.
outdir: Directory to store rendered videos in.
num_agents: Number of environments to simulate in parallel.
num_episodes: Total number of episodes to simulate.
checkpoint: Checkpoint name to loa... | def visualize(
logdir, outdir, num_agents, num_episodes, checkpoint=None,
env_processes=True):
config = utility.load_config(logdir)
with tf.device('/cpu:0'):
batch_env = utility.define_batch_env(
lambda: _create_environment(config, outdir),
num_agents, env_processes)
graph = utili... | 444,898 |
Reset all variables in a nested tuple to zeros.
Args:
variables: Nested tuple or list of variables.
indices: Batch indices to reset, defaults to all.
Returns:
Operation. | def reinit_nested_vars(variables, indices=None):
if isinstance(variables, (tuple, list)):
return tf.group(*[
reinit_nested_vars(variable, indices) for variable in variables])
if indices is None:
return variables.assign(tf.zeros_like(variables))
else:
zeros = tf.zeros([tf.shape(indices)[0]] ... | 444,900 |
Assign tensors to matching nested tuple of variables.
Args:
variables: Nested tuple or list of variables to update.
tensors: Nested tuple or list of tensors to assign.
indices: Batch indices to assign to; default to all.
Returns:
Operation. | def assign_nested_vars(variables, tensors, indices=None):
if isinstance(variables, (tuple, list)):
return tf.group(*[
assign_nested_vars(variable, tensor)
for variable, tensor in zip(variables, tensors)])
if indices is None:
return variables.assign(tensors)
else:
return tf.scatter_u... | 444,901 |
Create histogram summaries of the gradient.
Summaries can be grouped via regexes matching variables names.
Args:
grad_vars: List of (gradient, variable) tuples as returned by optimizers.
groups: Mapping of name to regex for grouping summaries.
scope: Name scope for this operation.
Returns:
Summ... | def gradient_summaries(grad_vars, groups=None, scope='gradients'):
groups = groups or {r'all': r'.*'}
grouped = collections.defaultdict(list)
for grad, var in grad_vars:
if grad is None:
continue
for name, pattern in groups.items():
if re.match(pattern, var.name):
name = re.sub(patt... | 444,907 |
Create histogram summaries for the provided variables.
Summaries can be grouped via regexes matching variables names.
Args:
vars_: List of variables to summarize.
groups: Mapping of name to regex for grouping summaries.
scope: Name scope for this operation.
Returns:
Summary tensor. | def variable_summaries(vars_, groups=None, scope='weights'):
groups = groups or {r'all': r'.*'}
grouped = collections.defaultdict(list)
for var in vars_:
for name, pattern in groups.items():
if re.match(pattern, var.name):
name = re.sub(pattern, name, var.name)
grouped[name].append(va... | 444,908 |
Set the length of a tensor along the specified dimension.
Args:
tensor: Tensor to define shape of.
axis: Dimension to set the static shape for.
value: Integer holding the length.
Raises:
ValueError: When the tensor already has a different length specified. | def set_dimension(tensor, axis, value):
shape = tensor.shape.as_list()
if shape[axis] not in (value, None):
message = 'Cannot set dimension {} of tensor {} to {}; is already {}.'
raise ValueError(message.format(axis, tensor.name, value, shape[axis]))
shape[axis] = value
tensor.set_shape(shape) | 444,909 |
Combine multiple environments to step them in batch.
To step environments in parallel, environments must support a
`blocking=False` argument to their step and reset functions that makes them
return callables instead to receive the result at a later time.
Args:
envs: List of environments.
b... | def __init__(self, envs, blocking):
self._envs = envs
self._blocking = blocking
observ_space = self._envs[0].observation_space
if not all(env.observation_space == observ_space for env in self._envs):
raise ValueError('All environments must use the same observation space.')
action_space = ... | 444,915 |
Forward a batch of actions to the wrapped environments.
Args:
actions: Batched action to apply to the environment.
Raises:
ValueError: Invalid actions.
Returns:
Batch of observations, rewards, and done flags. | def step(self, actions):
for index, (env, action) in enumerate(zip(self._envs, actions)):
if not env.action_space.contains(action):
message = 'Invalid action at index {}: {}'
raise ValueError(message.format(index, action))
if self._blocking:
transitions = [
env.step(ac... | 444,916 |
Reset the environment and convert the resulting observation.
Args:
indices: The batch indices of environments to reset; defaults to all.
Returns:
Batch of observations. | def reset(self, indices=None):
if indices is None:
indices = np.arange(len(self._envs))
if self._blocking:
observs = [self._envs[index].reset() for index in indices]
else:
observs = [self._envs[index].reset(blocking=False) for index in indices]
observs = [observ() for observ in ... | 444,917 |
Augment the observation with past observations.
Implemented as a Numpy ring buffer holding the necessary past observations.
Args:
env: OpenAI Gym environment to wrap.
past_indices: List of non-negative integers indicating the time offsets
from the current time step of observations to inclu... | def __init__(self, env, past_indices, flatten):
if 0 not in past_indices:
raise KeyError('Past indices should include 0 for the current frame.')
self._env = env
self._past_indices = past_indices
self._step = 0
self._buffer = None
self._capacity = max(past_indices) + 1
self._flatte... | 444,924 |
Request an attribute from the environment.
Note that this involves communication with the external process, so it can
be slow.
Args:
name: Attribute to access.
Returns:
Value of the attribute. | def __getattr__(self, name):
self._conn.send((self._ACCESS, name))
return self._receive() | 444,947 |
Asynchronously call a method of the external environment.
Args:
name: Name of the method to call.
*args: Positional arguments to forward to the method.
**kwargs: Keyword arguments to forward to the method.
Returns:
Promise object that blocks and provides the return value when called. | def call(self, name, *args, **kwargs):
payload = name, args, kwargs
self._conn.send((self._CALL, payload))
return self._receive | 444,948 |
Step the environment.
Args:
action: The action to apply to the environment.
blocking: Whether to wait for the result.
Returns:
Transition tuple when blocking, otherwise callable that returns the
transition tuple. | def step(self, action, blocking=True):
promise = self.call('step', action)
if blocking:
return promise()
else:
return promise | 444,950 |
Reset the environment.
Args:
blocking: Whether to wait for the result.
Returns:
New observation when blocking, otherwise callable that returns the new
observation. | def reset(self, blocking=True):
promise = self.call('reset')
if blocking:
return promise()
else:
return promise | 444,951 |
The process waits for actions and sends back environment results.
Args:
constructor: Constructor for the OpenAI Gym environment.
conn: Connection for communication to the main process.
Raises:
KeyError: When receiving a message of unknown type. | def _worker(self, constructor, conn):
try:
env = constructor()
while True:
try:
# Only block for short times to have keyboard exceptions be raised.
if not conn.poll(0.1):
continue
message, payload = conn.recv()
except (EOFError, KeyboardInte... | 444,953 |
Forward action to the wrapped environment.
Args:
action: Action to apply to the environment.
Raises:
ValueError: Invalid action.
Returns:
Converted observation, converted reward, done flag, and info object. | def step(self, action):
observ, reward, done, info = self._env.step(action)
observ = self._convert_observ(observ)
reward = self._convert_reward(reward)
return observ, reward, done, info | 444,954 |
Convert the observation to 32 bits.
Args:
observ: Numpy observation.
Raises:
ValueError: Observation contains infinite values.
Returns:
Numpy observation with 32-bit data type. | def _convert_observ(self, observ):
if not np.isfinite(observ).all():
raise ValueError('Infinite observation encountered.')
if observ.dtype == np.float64:
return observ.astype(np.float32)
if observ.dtype == np.int64:
return observ.astype(np.int32)
return observ | 444,956 |
Convert the reward to 32 bits.
Args:
reward: Numpy reward.
Raises:
ValueError: Rewards contain infinite values.
Returns:
Numpy reward with 32-bit data type. | def _convert_reward(self, reward):
if not np.isfinite(reward).all():
raise ValueError('Infinite reward encountered.')
return np.array(reward, dtype=np.float32) | 444,957 |
Cache observation and action space to not recompute them repeatedly.
Args:
env: OpenAI Gym environment. | def __init__(self, env):
self._env = env
self._observation_space = self._env.observation_space
self._action_space = self._env.action_space | 444,958 |
Specify the shape and dtype of the mean to be estimated.
Note that a float mean to zero submitted elements is NaN, while computing
the integer mean of zero elements raises a division by zero error.
Args:
shape: Shape of the mean to compute.
dtype: Data type of the mean to compute. | def __init__(self, shape, dtype):
self._dtype = dtype
self._sum = tf.Variable(lambda: tf.zeros(shape, dtype), False)
self._count = tf.Variable(lambda: 0, trainable=False) | 444,959 |
Combine corresponding elements in multiple nested structure to tuples.
The nested structures can consist of any combination of lists, tuples, and
dicts. All provided structures must have the same nesting.
Args:
*structures: Nested structures.
flatten: Whether to flatten the resulting structure into a tu... | def zip_(*structures, **kwargs):
# pylint: disable=differing-param-doc,missing-param-doc
# Named keyword arguments are not allowed after *args in Python 2.
flatten = kwargs.pop('flatten', False)
assert not kwargs, 'zip() got unexpected keyword arguments.'
return map(
lambda *x: x if len(x) > 1 else x... | 444,963 |
Combine all leaves of a nested structure into a tuple.
The nested structure can consist of any combination of tuples, lists, and
dicts. Dictionary keys will be discarded but values will ordered by the
sorting of the keys.
Args:
structure: Nested structure.
Returns:
Flat tuple. | def flatten_(structure):
if isinstance(structure, dict):
if structure:
structure = zip(*sorted(structure.items(), key=lambda x: x[0]))[1]
else:
# Zip doesn't work on an the items of an empty dictionary.
structure = ()
if isinstance(structure, (tuple, list)):
result = []
for elem... | 444,965 |
Run the loop schedule for a specified number of steps.
Call the operation of the current phase until the global step reaches the
specified maximum step. Phases are repeated over and over in the order they
were added.
Args:
sess: Session to use to run the phase operation.
saver: Saver used ... | def run(self, sess, saver, max_step=None):
global_step = sess.run(self._step)
steps_made = 1
while True:
if max_step and global_step >= max_step:
break
phase, epoch, steps_in = self._find_current_phase(global_step)
phase_step = epoch * phase.steps + steps_in
if steps_in ... | 444,969 |
Determine whether a periodic event should happen at this step.
Args:
phase_step: The incrementing step.
batch: The number of steps progressed at once.
every: The interval of the period.
Returns:
Boolean of whether the event should happen. | def _is_every_steps(self, phase_step, batch, every):
if not every:
return False
covered_steps = range(phase_step, phase_step + batch)
return any((step + 1) % every == 0 for step in covered_steps) | 444,970 |
Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase object, epoch number, and phase steps within the epoch. | def _find_current_phase(self, global_step):
epoch_size = sum(phase.steps for phase in self._phases)
epoch = int(global_step // epoch_size)
steps_in = global_step % epoch_size
for phase in self._phases:
if steps_in < phase.steps:
return phase, epoch, steps_in
steps_in -= phase.st... | 444,971 |
Combine operations of a phase.
Keeps track of the mean score and when to report it.
Args:
done: Tensor indicating whether current score can be used.
score: Tensor holding the current, possibly intermediate, score.
summary: Tensor holding summary string to write if not an empty string.
R... | def _define_step(self, done, score, summary):
if done.shape.ndims == 0:
done = done[None]
if score.shape.ndims == 0:
score = score[None]
score_mean = streaming_mean.StreamingMean((), tf.float32)
with tf.control_dependencies([done, score, summary]):
done_score = tf.gather(score, tf... | 444,972 |
Store a checkpoint if a log directory was provided to the constructor.
The directory will be created if needed.
Args:
sess: Session containing variables to store.
saver: Saver used for checkpointing.
global_step: Step number of the checkpoint name. | def _store_checkpoint(self, sess, saver, global_step):
if not self._logdir or not saver:
return
tf.gfile.MakeDirs(self._logdir)
filename = os.path.join(self._logdir, 'model.ckpt')
saver.save(sess, filename, global_step) | 444,973 |
Constructor for an instance of the environment.
Args:
config: Object providing configurations via attributes.
Raises:
NotImplementedError: For action spaces other than Box and Discrete.
Returns:
Wrapped OpenAI Gym environment. | def _create_environment(config):
if isinstance(config.env, str):
env = gym.make(config.env)
else:
env = config.env()
if config.max_length:
env = tools.wrappers.LimitDuration(env, config.max_length)
if isinstance(env.action_space, gym.spaces.Box):
if config.normalize_ranges:
env = tools.... | 444,974 |
Create and configure a training loop with training and evaluation phases.
Args:
graph: Object providing graph elements via attributes.
logdir: Log directory for storing checkpoints and summaries.
train_steps: Number of training steps per epoch.
eval_steps: Number of evaluation steps per epoch.
Ret... | def _define_loop(graph, logdir, train_steps, eval_steps):
loop = tools.Loop(
logdir, graph.step, graph.should_log, graph.do_report,
graph.force_reset)
loop.add_phase(
'train', graph.done, graph.score, graph.summary, train_steps,
report_every=train_steps,
log_every=train_steps // 2,
... | 444,975 |
Training and evaluation entry point yielding scores.
Resolves some configuration attributes, creates environments, graph, and
training loop. By default, assigns all operations to the CPU.
Args:
config: Object providing configurations via attributes.
env_processes: Whether to step environments in separat... | def train(config, env_processes):
tf.reset_default_graph()
if config.update_every % config.num_agents:
tf.logging.warn('Number of agents should divide episodes per update.')
with tf.device('/cpu:0'):
batch_env = utility.define_batch_env(
lambda: _create_environment(config),
config.num_a... | 444,976 |
Split a nested dict of sequence tensors into a batch of chunks.
This function does not expect a batch of sequences, but a single sequence. A
`length` key is added if it did not exist already.
Args:
sequence: Nested dict of tensors with time dimension.
chunk_length: Size of chunks the sequence will be sp... | def chunk_sequence(sequence, chunk_length=200, padding_value=0):
if 'length' in sequence:
length = sequence.pop('length')
else:
length = tf.shape(tools.nested.flatten(sequence)[0])[0]
num_chunks = (length - 1) // chunk_length + 1
padding_length = chunk_length * num_chunks - length
padded = tools.ne... | 444,979 |
Selects the used frames of a sequence, up to its length.
This function does not expect a batch of sequences, but a single sequence.
The sequence must be a dict with `length` key, which will removed from the
result.
Args:
sequence: Nested dict of tensors with time dimension.
Returns:
Nested dict of ... | def remove_padding(sequence):
length = sequence.pop('length')
sequence = tools.nested.map(lambda tensor: tensor[:length], sequence)
return sequence | 444,980 |
Normalize a single or batch tensor.
Applies the activated transformations in the constructor using current
estimates of mean and variance.
Args:
value: Batch or single value tensor.
Returns:
Normalized batch or single value tensor. | def transform(self, value):
with tf.name_scope(self._name + '/transform'):
no_batch_dim = value.shape.ndims == self._mean.shape.ndims
if no_batch_dim:
# Add a batch dimension if necessary.
value = value[None, ...]
if self._center:
value -= self._mean[None, ...]
i... | 444,982 |
Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor. | def update(self, value):
with tf.name_scope(self._name + '/update'):
if value.shape.ndims == self._mean.shape.ndims:
# Add a batch dimension if necessary.
value = value[None, ...]
count = tf.shape(value)[0]
with tf.control_dependencies([self._count.assign_add(count)]):
... | 444,983 |
Create a scalar or histogram summary matching the rank of the tensor.
Args:
name: Name for the summary.
tensor: Tensor to summarize.
Returns:
Summary tensor. | def _summary(self, name, tensor):
if tensor.shape.ndims == 0:
return tf.summary.scalar(name, tensor)
else:
return tf.summary.histogram(name, tensor) | 444,987 |
Create a memory that stores episodes.
Each transition tuple consists of quantities specified by the template.
These quantities would typically be be observations, actions, rewards, and
done indicators.
Args:
template: Nested tensors to derive shapes and dtypes of each transition.
capacity:... | def __init__(self, template, capacity, max_length, scope):
self._capacity = capacity
self._max_length = max_length
with tf.variable_scope(scope) as var_scope:
self._scope = var_scope
self._length = tf.Variable(tf.zeros(capacity, tf.int32), False)
self._buffers = tools.nested.map(
... | 444,988 |
Tensor holding the current length of episodes.
Args:
rows: Episodes to select length from, defaults to all.
Returns:
Batch tensor of sequence lengths. | def length(self, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
return tf.gather(self._length, rows) | 444,989 |
Append a batch of transitions to rows of the memory.
Args:
transitions: Tuple of transition quantities with batch dimension.
rows: Episodes to append to, defaults to all.
Returns:
Operation. | def append(self, transitions, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
assert_capacity = tf.assert_less(
rows, self._capacity,
message='capacity exceeded')
with tf.control_dependencies([assert_capacity]):
assert_max_len... | 444,990 |
Replace full episodes.
Args:
episodes: Tuple of transition quantities with batch and time dimensions.
length: Batch of sequence lengths.
rows: Episodes to replace, defaults to all.
Returns:
Operation. | def replace(self, episodes, length, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
assert_capacity = tf.assert_less(
rows, self._capacity, message='capacity exceeded')
with tf.control_dependencies([assert_capacity]):
assert_max_lengt... | 444,991 |
Access a batch of episodes from the memory.
Padding elements after the length of each episode are unspecified and might
contain old data.
Args:
rows: Episodes to select, defaults to all.
Returns:
Tuple containing a tuple of transition quantities with batch and time
dimensions, and a... | def data(self, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
episode = tools.nested.map(lambda var: tf.gather(var, rows), self._buffers)
length = tf.gather(self._length, rows)
return episode, length | 444,992 |
Reset episodes in the memory.
Internally, this only sets their lengths to zero. The memory entries will
be overridden by future calls to append() or replace().
Args:
rows: Episodes to clear, defaults to all.
Returns:
Operation. | def clear(self, rows=None):
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
return tf.scatter_update(self._length, rows, tf.zeros_like(rows)) | 444,993 |
Put an OpenAI Gym environment into the TensorFlow graph.
Args:
env: OpenAI Gym environment. | def __init__(self, env):
self._env = env
observ_shape = self._parse_shape(self._env.observation_space)
observ_dtype = self._parse_dtype(self._env.observation_space)
action_shape = self._parse_shape(self._env.action_space)
action_dtype = self._parse_dtype(self._env.action_space)
with tf.name... | 444,994 |
Get a tensor shape from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
Shape tuple. | def _parse_shape(self, space):
if isinstance(space, gym.spaces.Discrete):
return ()
if isinstance(space, gym.spaces.Box):
return space.shape
raise NotImplementedError() | 444,996 |
Get a tensor dtype from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
TensorFlow data type. | def _parse_dtype(self, space):
if isinstance(space, gym.spaces.Discrete):
return tf.int32
if isinstance(space, gym.spaces.Box):
return tf.float32
raise NotImplementedError() | 444,997 |
Batch of environments inside the TensorFlow graph.
Args:
batch_env: Batch environment. | def __init__(self, batch_env):
self._batch_env = batch_env
batch_dims = (len(self._batch_env),)
observ_shape = self._parse_shape(self._batch_env.observation_space)
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
action_shape = self._parse_shape(self._batch_env.action_space)
... | 444,998 |
Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation. | def simulate(self, action):
with tf.name_scope('environment/simulate'):
if action.dtype in (tf.float16, tf.float32, tf.float64):
action = tf.check_numerics(action, 'action')
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ, reward, done = tf.py_func(
... | 444,999 |
Reset the batch of environments.
Args:
indices: The batch indices of the environments to reset; defaults to all.
Returns:
Batch tensor of the new observations. | def reset(self, indices=None):
if indices is None:
indices = tf.range(len(self._batch_env))
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ = tf.py_func(
self._batch_env.reset, [indices], observ_dtype, name='reset')
observ = tf.check_numerics(observ, 'observ... | 445,000 |
Create an instance of the PPO algorithm.
Args:
batch_env: In-graph batch environment.
step: Integer tensor holding the current training step.
is_training: Boolean tensor for whether the algorithm should train.
should_log: Boolean tensor for whether summaries should be returned.
config... | def __init__(self, batch_env, step, is_training, should_log, config):
self._batch_env = batch_env
self._step = step
self._is_training = is_training
self._should_log = should_log
self._config = config
self._observ_filter = parts.StreamingNormalize(
self._batch_env.observ[0], center=T... | 445,001 |
Reset the recurrent states and stored episode.
Args:
agent_indices: Tensor containing current batch indices.
Returns:
Summary tensor. | def begin_episode(self, agent_indices):
with tf.name_scope('begin_episode/'):
if self._last_state is None:
reset_state = tf.no_op()
else:
reset_state = utility.reinit_nested_vars(
self._last_state, agent_indices)
reset_buffer = self._current_episodes.clear(agent_in... | 445,002 |
Compute batch of actions and a summary for a batch of observation.
Args:
agent_indices: Tensor containing current batch indices.
observ: Tensor of a batch of observations for all agents.
Returns:
Tuple of action batch tensor and summary tensor. | def perform(self, agent_indices, observ):
with tf.name_scope('perform/'):
observ = self._observ_filter.transform(observ)
if self._last_state is None:
state = None
else:
state = tools.nested.map(
lambda x: tf.gather(x, agent_indices), self._last_state)
with tf... | 445,003 |
Add episodes to the memory and perform update steps if memory is full.
During training, add the collected episodes of the batch indices that
finished their episode to the memory. If the memory is full, train on it,
and then clear the memory. A summary string is returned if requested at
this step.
... | def end_episode(self, agent_indices):
with tf.name_scope('end_episode/'):
return tf.cond(
self._is_training,
lambda: self._define_end_episode(agent_indices), str) | 445,006 |
Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episodes
memory serves to collect multiple episodes in... | def _initialize_memory(self, policy_params):
# We store observation, action, policy parameters, and reward.
template = (
self._batch_env.observ[0],
self._batch_env.action[0],
tools.nested.map(lambda x: x[0, 0], policy_params),
self._batch_env.reward[0])
with tf.variable_... | 445,008 |
Compute the current combined loss and perform a gradient update step.
The sequences must be a dict containing the keys `length` and `sequence`,
where the latter is a tuple containing observations, actions, parameters of
the behavioral policy, rewards, and advantages.
Args:
sequence: Sequences of... | def _update_step(self, sequence):
observ, action, old_policy_params, reward, advantage = sequence['sequence']
length = sequence['length']
old_policy = self._policy_type(**old_policy_params)
value_loss, value_summary = self._value_loss(observ, reward, length)
network = self._network(observ, leng... | 445,012 |
Compute the loss function for the value baseline.
The value loss is the difference between empirical and approximated returns
over the collected episodes. Returns the loss tensor and a summary strin.
Args:
observ: Sequences of observations.
reward: Sequences of reward.
length: Batch of s... | def _value_loss(self, observ, reward, length):
with tf.name_scope('value_loss'):
value = self._network(observ, length).value
return_ = utility.discounted_return(
reward, length, self._config.discount)
advantage = return_ - value
value_loss = 0.5 * self._mask(advantage ** 2, le... | 445,013 |
Adjust the KL policy between the behavioral and current policy.
Compute how much the policy actually changed during the multiple
update steps. Adjust the penalty strength for the next training phase if we
overshot or undershot the target divergence too much.
Args:
observ: Sequences of observatio... | def _adjust_penalty(self, observ, old_policy_params, length):
old_policy = self._policy_type(**old_policy_params)
with tf.name_scope('adjust_penalty'):
network = self._network(observ, length)
print_penalty = tf.Print(0, [self._penalty], 'current penalty: ')
with tf.control_dependencies([p... | 445,015 |
Set padding elements of a batch of sequences to a constant.
Useful for setting padding elements to zero before summing along the time
dimension, or for preventing infinite results in padding elements.
Args:
tensor: Tensor of sequences.
length: Batch of sequence lengths.
padding_value: Va... | def _mask(self, tensor, length, padding_value=0):
with tf.name_scope('mask'):
range_ = tf.range(tensor.shape[1].value)
mask = range_[None, :] < length[:, None]
if tensor.shape.ndims > 2:
for _ in range(tensor.shape.ndims - 2):
mask = mask[..., None]
mask = tf.tile(ma... | 445,016 |
Updates the connector with the specified uuid.
if description is empty, the existing description will be removed.
Parameters:
- connector (String), Connnector Id which is a UUID
- name (string) - Name of the service
- timezone (json object) - Should have a valid struc... | def update(self, connectorId, name, description, timezone, enabled):
url = "api/v0002/historianconnectors/%s" % (connectorId)
connectorBody = {}
connectorBody["name"] = name
connectorBody["description"] = description
connectorBody["timezone"] = timezone
connect... | 445,316 |
Retrieve the service with the specified id.
Parameters:
- serviceId (String), Service Id which is a UUID
Throws APIException on failure. | def __getitem__(self, key):
url = "api/v0002/s2s/services/%s" % (key)
r = self._apiClient.get(url)
if r.status_code == 200:
return ServiceBinding(**r.json())
if r.status_code == 404:
self.__missing__(key)
else:
raise ApiException(r) | 445,320 |
Updates the service with the specified id.
if description is empty, the existing description will be removed.
Parameters:
- serviceId (String), Service Id which is a UUID
- serviceName (string), name of service
- credentials (json), json object of credentials
... | def update(self, serviceId, serviceName, credentials, description):
url = "api/v0002/s2s/services/%s" % (serviceId)
serviceBody = {}
serviceBody["name"] = serviceName
serviceBody["description"] = description
serviceBody["credentials"] = credentials
r = self._a... | 445,323 |
Create a physical interface.
Parameters:
- name (string)
- description (string, optional)
Returns: physical interface id, response.
Throws APIException on failure. | def createPhysicalInterface(self, name, description=None):
req = ApiClient.allPhysicalInterfacesUrl % (self.host, "/draft")
body = {"name" : name}
if description:
body["description"] = description
resp = requests.post(req, auth=self.credentials, headers={"Content-Typ... | 445,408 |
Update a physical interface.
Parameters:
- physicalInterfaceId (string)
- name (string)
- schemaId (string)
- description (string, optional)
Throws APIException on failure. | def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None):
req = ApiClient.onePhysicalInterfacesUrl % (self.host, "/draft", physicalInterfaceId)
body = {"name" : name, "schemaId" : schemaId}
if description:
body["description"] = description
... | 445,409 |
Get a physical interface.
Parameters:
- physicalInterfaceId (string)
- draft (boolean)
Throws APIException on failure. | def getPhysicalInterface(self, physicalInterfaceId, draft=False):
if draft:
req = ApiClient.onePhysicalInterfaceUrl % (self.host, "/draft", physicalInterfaceId)
else:
req = ApiClient.onePhysicalInterfaceUrl % (self.host, "", physicalInterfaceId)
resp = requests.... | 445,411 |
Create an event mapping for a physical interface.
Parameters:
physicalInterfaceId (string) - value returned by the platform when creating the physical interface
eventTypeId (string) - value returned by the platform when creating the event type
eventId (string) - matches the event i... | def createEvent(self, physicalInterfaceId, eventTypeId, eventId):
req = ApiClient.allEventsUrl % (self.host, "/draft", physicalInterfaceId)
body = {"eventId" : eventId, "eventTypeId" : eventTypeId}
resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/jso... | 445,412 |
Gets a logical interface.
Parameters:
- logicalInterfaceId (string)
- draft (boolean)
Throws APIException on failure. | def getLogicalInterface(self, logicalInterfaceId, draft=False):
if draft:
req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId)
else:
req = ApiClient.oneLogicalInterfaceUrl % (self.host, "", logicalInterfaceId)
resp = requests.get(req... | 445,417 |
Gets a rule for a logical interface.
Parameters:
- logicalInterfaceId (string)
- ruleId (string)
- draft (boolean)
Throws APIException on failure. | def getRuleForLogicalInterface(self, logicalInterfaceId, ruleId, draft=False):
if draft:
req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId)
else:
req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "", logicalInterfa... | 445,418 |
Adds a rule to a logical interface.
Parameters:
- logicalInterfaceId (string)
- name (string)
- condition (string)
- (description (string, optional)
Returns: rule id (string), response (object).
Throws APIException on failure. | def addRuleToLogicalInterface(self, logicalInterfaceId, name, condition, description=None, alias=None):
req = ApiClient.allRulesForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId)
body = {"name" : name, "condition" : condition}
if description:
body["description"... | 445,419 |
Updates a rule on a logical interface..
Parameters:
- logicalInterfaceId (string),
- ruleId (string)
- name (string)
- condition (string)
- description (string, optional)
Returns: response (object).
Throws APIException on failure. | def updateRuleOnLogicalInterface(self, logicalInterfaceId, ruleId, name, condition, description=None):
req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId)
body = {"logicalInterfaceId" : logicalInterfaceId, "id" : ruleId, "name" : name, "condition" :... | 445,420 |
Deletes a rule from a logical interface
Parameters:
- logicalInterfaceId (string),
- ruleId (string)
Returns: response (object)
Throws APIException on failure | def deleteRuleOnLogicalInterface(self, logicalInterfaceId, ruleId):
req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId)
resp = requests.delete(req, auth=self.credentials, verify=self.verify)
if resp.status_code == 204:
self.logge... | 445,421 |
Adds a physical interface to a device type.
Parameters:
- typeId (string) - the device type
- physicalInterfaceId (string) - the id returned by the platform on creation of the physical interface
Throws APIException on failure. | def addPhysicalInterfaceToDeviceType(self, typeId, physicalInterfaceId):
req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "/draft", typeId)
body = {"id" : physicalInterfaceId}
resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, da... | 445,422 |
Gets the physical interface associated with a device type.
Parameters:
- typeId (string) - the device type
- draft (boolean)
Throws APIException on failure. | def getPhysicalInterfaceOnDeviceType(self, typeId, draft=False):
if draft:
req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "/draft", typeId)
else:
req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "", typeId)
resp = requests.get(req,... | 445,423 |
Get all logical interfaces for a device type.
Parameters:
- typeId (string)
- draft (boolean)
Returns:
- list of logical interface ids
- HTTP response object
Throws APIException on failure. | def getLogicalInterfacesOnDeviceType(self, typeId, draft=False):
if draft:
req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "/draft", typeId)
else:
req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "", typeId)
resp = requests.get(req,... | 445,424 |
Adds a logical interface to a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
- description (string) - optional (not used)
Throws APIException on failure. | def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId):
req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "/draft", typeId)
body = {"id" : logicalInterfaceId}
# body = {"name" : "required but not used!!!", "id" : logicalInterfaceId, "schemaId" : schemaId}
# ... | 445,425 |
Removes a logical interface from a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
Throws APIException on failure. | def removeLogicalInterfaceFromDeviceType(self, typeId, logicalInterfaceId):
req = ApiClient.oneDeviceTypeLogicalInterfaceUrl % (self.host, typeId, logicalInterfaceId)
resp = requests.delete(req, auth=self.credentials, verify=self.verify)
if resp.status_code == 204:
self.logg... | 445,426 |
Get all the mappings for a device type.
Parameters:
- typeId (string) - the device type
- draft (boolean) - draft or active
Throws APIException on failure. | def getMappingsOnDeviceType(self, typeId, draft=False):
if draft:
req = ApiClient.allDeviceTypeMappingsUrl % (self.host, "/draft", typeId)
else:
req = ApiClient.allDeviceTypeMappingsUrl % (self.host, "", typeId)
resp = requests.get(req, auth=self.credentials, ve... | 445,427 |
Gets the mappings for a logical interface from a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the platform returned id of the logical interface
Throws APIException on failure. | def getMappingsOnDeviceTypeForLogicalInterface(self, typeId, logicalInterfaceId, draft=False):
if draft:
req = ApiClient.oneDeviceTypeMappingUrl % (self.host, "/draft", typeId, logicalInterfaceId)
else:
req = ApiClient.oneDeviceTypeMappingUrl % (self.host, "", typeId, lo... | 445,428 |
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure. | def validateDeviceTypeConfiguration(self, typeId):
req = ApiClient.draftDeviceTypeUrl % (self.host, typeId)
body = {"operation" : "validate-configuration"}
resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body),
... | 445,429 |
Validate the logical interface configuration.
Parameters:
- logicalInterfaceId (string)
Throws APIException on failure. | def validateLogicalInterfaceConfiguration(self, logicalInterfaceId):
req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId)
body = {"operation" : "validate-configuration"}
resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/... | 445,430 |
Gets the state for a logical interface for a device.
Parameters:
- typeId (string) - the platform device type
- deviceId (string) - the platform device id
- logicalInterfaceId (string) - the platform returned id of the logical interface
Throws APIException on failure. | def getDeviceStateForLogicalInterface(self, typeId, deviceId, logicalInterfaceId):
req = ApiClient.deviceStateUrl % (self.host, typeId, deviceId, logicalInterfaceId)
resp = requests.get(req, auth=self.credentials, verify=self.verify)
if resp.status_code == 200:
self.logger.d... | 445,431 |
Gets the state for a logical interface for a thing.
Parameters:
- thingTypeId (string) - the platform thing type
- thingId (string) - the platform thing id
- logicalInterfaceId (string) - the platform returned id of the logical interface
Throws APIException on failure... | def getThingStateForLogicalInterface(self, thingTypeId, thingId, logicalInterfaceId):
req = ApiClient.thingStateUrl % (self.host, thingTypeId, thingId, logicalInterfaceId)
resp = requests.get(req, auth=self.credentials, verify=self.verify)
if resp.status_code == 200:
self.lo... | 445,432 |
Perform an operation against the thing state for a logical interface
Parameters:
- thingTypeId (string)
- thingId (string)
- logicalInterfaceId (string)
Throws APIException on failure. | def resetThingStateForLogicalInterface(self, thingTypeId, thingId , logicalInterfaceId):
req = ApiClient.thingStateUrl % (self.host, "", thingTypeId,thingId , logicalInterfaceId)
body = {"operation" : "reset-state"}
resp = requests.patch(req, auth=self.credentials, headers={"Content-Typ... | 445,433 |
Get all logical interfaces for a thing type.
Parameters:
- thingTypeId (string)
- draft (boolean)
Returns:
- list of logical interface ids
- HTTP response object
Throws APIException on failure. | def getLogicalInterfacesOnThingType(self, thingTypeId, draft=False):
if draft:
req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "/draft", thingTypeId)
else:
req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "", thingTypeId)
resp = reque... | 445,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.