code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__( self, url, poolclass=None, chunk_size=1024 ** 2 * 100, table_postfix=''): """ :param str url: The database *url* that'll be used to make a connection. Format follows RFC-1738. I'll create a table ``models`` to store the pickles in if i...
:param str url: The database *url* that'll be used to make a connection. Format follows RFC-1738. I'll create a table ``models`` to store the pickles in if it doesn't exist yet. :param sqlalchemy.pool.Pool poolclass: A class specifying DB connection behavior of...
__init__
python
ottogroup/palladium
palladium/persistence.py
https://github.com/ottogroup/palladium/blob/master/palladium/persistence.py
Apache-2.0
def __init__(self, impl, update_cache_rrule=None, check_version=True, ): """ :param ModelPersister impl: The underlying (decorated) persister object. :param dict update_cache_rrule: Optional keyword argument...
:param ModelPersister impl: The underlying (decorated) persister object. :param dict update_cache_rrule: Optional keyword arguments for a :class:`dateutil.rrule.rrule` that determines when the cache will be updated. See :class:`~palladium.util.RruleThread` for ...
__init__
python
ottogroup/palladium
palladium/persistence.py
https://github.com/ottogroup/palladium/blob/master/palladium/persistence.py
Apache-2.0
def make_ujson_response(obj, status_code=200): """Encodes the given *obj* to json and wraps it in a response. :return: A Flask response. """ json_encoded = ujson.encode(obj, ensure_ascii=False) resp = make_response(json_encoded) resp.mimetype = 'application/json' resp.content_type = '...
Encodes the given *obj* to json and wraps it in a response. :return: A Flask response.
make_ujson_response
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def __init__( self, mapping, params=(), entry_point='/predict', decorator_list_name='predict_decorators', predict_proba=False, unwrap_sample=False, **kwargs ): """ :param mapping: A list of query parameters and their type that...
:param mapping: A list of query parameters and their type that should be included in the request. These will be processed in the :meth:`sample_from_data` method to construct a sample that can be used for prediction. An example that expects two request paramet...
__init__
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def sample_from_data(self, model, data): """Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or si...
Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or similar.
sample_from_data
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def params_from_data(self, model, data): """Retrieve additional parameters (keyword arguments) for ``model.predict`` from request *data*. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the parameter data, typic...
Retrieve additional parameters (keyword arguments) for ``model.predict`` from request *data*. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the parameter data, typically retrieved from ``request.args`` or si...
params_from_data
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def response_from_prediction(self, y_pred, single=True): """Turns a model's prediction in *y_pred* into a JSON response. """ result = y_pred.tolist() if single: result = result[0] response = { 'metadata': get_metadata(), 'result': resul...
Turns a model's prediction in *y_pred* into a JSON response.
response_from_prediction
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def create_predict_function( route, predict_service, decorator_list_name, config): """Creates a predict function and registers it to the Flask app using the route decorator. :param str route: Path of the entry point. :param palladium.interfaces.PredictService predict_service: The p...
Creates a predict function and registers it to the Flask app using the route decorator. :param str route: Path of the entry point. :param palladium.interfaces.PredictService predict_service: The predict service to be registered to this entry point. :param str decorator_list_name: Th...
create_predict_function
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --de...
Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --debug=<debug> Whether or not to use debug mode [default: 0].
devserver_cmd
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def listen(self, io_in, io_out, io_err): """Listens to provided io stream and writes predictions to output. In case of errors, the error stream will be used. """ for line in io_in: if line.strip().lower() == 'exit': break try: y_pr...
Listens to provided io stream and writes predictions to output. In case of errors, the error stream will be used.
listen
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def stream_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Start the streaming server, which listens to stdin, processes line by line, and returns predictions. The input should consist of a list of json objects, where each object will result in a prediction. Each line is processed in a batch. Example input (mus...
Start the streaming server, which listens to stdin, processes line by line, and returns predictions. The input should consist of a list of json objects, where each object will result in a prediction. Each line is processed in a batch. Example input (must be on a single line): [{"sepal length": 1.0, "sepal width":...
stream_cmd
python
ottogroup/palladium
palladium/server.py
https://github.com/ottogroup/palladium/blob/master/palladium/server.py
Apache-2.0
def apply_kwargs(func, **kwargs): """Call *func* with kwargs, but only those kwargs that it accepts. """ new_kwargs = {} params = signature(func).parameters for param_name in params.keys(): if param_name in kwargs: new_kwargs[param_name] = kwargs[param_name] return func(**new...
Call *func* with kwargs, but only those kwargs that it accepts.
apply_kwargs
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def args_from_config(func): """Decorator that injects parameters from the configuration. """ func_args = signature(func).parameters @wraps(func) def wrapper(*args, **kwargs): config = get_config() for i, argname in enumerate(func_args): if len(args) > i or argname in kwa...
Decorator that injects parameters from the configuration.
args_from_config
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def session_scope(session): """Provide a transactional scope around a series of operations.""" try: yield session session.commit() except: session.rollback() raise finally: session.close()
Provide a transactional scope around a series of operations.
session_scope
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def __init__(self, func, rrule, sleep_between_checks=60): """ :param callable func: The function that I will call periodically. :param rrule rrule: The :class:`dateutil.rrule.rrule` recurrence rule that defines when I will do the calls. See the `python-dateutil ...
:param callable func: The function that I will call periodically. :param rrule rrule: The :class:`dateutil.rrule.rrule` recurrence rule that defines when I will do the calls. See the `python-dateutil docs <https://labix.org/python-dateutil>`_ for details on ...
__init__
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def memory_usage_psutil(): """Return the current process memory usage in MB. """ process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) mem_vms = process.memory_info()[1] / float(2 ** 20) return mem, mem_vms
Return the current process memory usage in MB.
memory_usage_psutil
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def upgrade_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Upgrade the database to the latest version. Usage: pld-ugprade [options] Options: --from=<v> Upgrade from a specific version, overriding the version stored in the database. --to=<v> Upgrade...
Upgrade the database to the latest version. Usage: pld-ugprade [options] Options: --from=<v> Upgrade from a specific version, overriding the version stored in the database. --to=<v> Upgrade to a specific version instead of the ...
upgrade_cmd
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def export_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Export a model from one model persister to another. The model persister to export to is supposed to be available in the configuration file under the 'model_persister_export' key. Usage: pld-export [options] Options: --version=<v> Export a...
Export a model from one model persister to another. The model persister to export to is supposed to be available in the configuration file under the 'model_persister_export' key. Usage: pld-export [options] Options: --version=<v> Export a specific version rather than the active ...
export_cmd
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def Partial(func, **kwargs): """Allows the use of partially applied functions in the configuration. """ if isinstance(func, str): func = resolve_dotted_name(func) partial_func = partial(func, **kwargs) update_wrapper(partial_func, func) return partial_func
Allows the use of partially applied functions in the configuration.
Partial
python
ottogroup/palladium
palladium/util.py
https://github.com/ottogroup/palladium/blob/master/palladium/util.py
Apache-2.0
def test_upload(self, mocked_requests, persister): """ test upload of model and metadata """ model = Dummy(name='mymodel') get_md_url = "%s/mymodel-metadata.json" % (self.base_url,) mocked_requests.head(get_md_url, status_code=404) put_model_body = None def handle_put_m...
test upload of model and metadata
test_upload
python
ottogroup/palladium
palladium/tests/test_persistence.py
https://github.com/ottogroup/palladium/blob/master/palladium/tests/test_persistence.py
Apache-2.0
def test_download(self, mocked_requests, persister): """ test download and activation of a model """ expected = Dummy(name='mymodel', __metadata__={}) zipped_model = gzip.compress(pickle.dumps(expected)) get_md_url = "%s/mymodel-metadata.json" % (self.base_url,) mocked_requests....
test download and activation of a model
test_download
python
ottogroup/palladium
palladium/tests/test_persistence.py
https://github.com/ottogroup/palladium/blob/master/palladium/tests/test_persistence.py
Apache-2.0
def test_delete(self, mocked_requests, persister): """ test deleting a model and metadata update """ get_md_url = "%s/mymodel-metadata.json" % (self.base_url,) mocked_requests.head(get_md_url, status_code=200) mocked_requests.get( get_md_url, json={"models": [{"v...
test deleting a model and metadata update
test_delete
python
ottogroup/palladium
palladium/tests/test_persistence.py
https://github.com/ottogroup/palladium/blob/master/palladium/tests/test_persistence.py
Apache-2.0
def flask_app_test(request, config): """A Flask app where _url_map, _view_functions, _rules, and _rules_by_end_point will be reset to the previous values after running the test. """ from palladium.server import app orig_rules = app.url_map._rules app.url_map._rules = [rule for rule in app.u...
A Flask app where _url_map, _view_functions, _rules, and _rules_by_end_point will be reset to the previous values after running the test.
flask_app_test
python
ottogroup/palladium
palladium/tests/__init__.py
https://github.com/ottogroup/palladium/blob/master/palladium/tests/__init__.py
Apache-2.0
def get_task(benchmark, env_id): """Get a task by env_id. Return None if the benchmark doesn't have the env. """ return next( filter(lambda task: task['env_id'] == env_id, benchmark['tasks']), None)
Get a task by env_id. Return None if the benchmark doesn't have the env.
get_task
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/benchmarks.py
MIT
def find_task_for_env_id_in_any_benchmark(env_id): """Find task for env id in any benchmark.""" for bm in _BENCHMARKS: for task in bm['tasks']: if task['env_id'] == env_id: return bm, task return None, None
Find task for env id in any benchmark.
find_task_for_env_id_in_any_benchmark
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/benchmarks.py
MIT
def continuous_mlp_policy_tf_ddpg_benchmarks(): """Run benchmarking experiments for Continuous MLP Policy on TF-DDPG.""" seeds = random.sample(range(100), 5) iterate_experiments(continuous_mlp_policy, MuJoCo1M_ENV_SET, seeds=seeds)
Run benchmarking experiments for Continuous MLP Policy on TF-DDPG.
continuous_mlp_policy_tf_ddpg_benchmarks
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/benchmark_policies.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/benchmark_policies.py
MIT
def benchmark(exec_func=None, *, plot=True, auto=False): """Decorator for benchmark function. Args: exec_func (func): The experiment function. plot (bool): Whether the result of this run needs to be plotted. PNG files will be generated in sub folder /plot. auto (auto): Wheth...
Decorator for benchmark function. Args: exec_func (func): The experiment function. plot (bool): Whether the result of this run needs to be plotted. PNG files will be generated in sub folder /plot. auto (auto): Whether this is automatic benchmarking. JSON files will b...
benchmark
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def iterate_experiments(func, env_ids, snapshot_config=None, seeds=None, xcolumn='TotalEnvSteps', xlabel='Total Environment Steps', ycolumn='Evaluation/AverageReturn', ...
Iterate experiments for benchmarking over env_ids and seeds. Args: env_ids (list[str]): List of environment ids. snapshot_config (garage.experiment.SnapshotConfig): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. seeds (lis...
iterate_experiments
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def _get_log_dir(exec_func_name): """Get the log directory given the experiment name. Args: exec_func_name (str): The function name which runs benchmarks. Returns: str: Log directory. """ cwd = pathlib.Path.cwd() return str(cwd.joinpath('data', 'local', 'benchmarks', exec_func...
Get the log directory given the experiment name. Args: exec_func_name (str): The function name which runs benchmarks. Returns: str: Log directory.
_get_log_dir
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def _read_csv(log_dir, xcolumn, ycolumn): """Read csv files and return xs and ys. Args: log_dir (str): Log directory for csv file. xcolumn (str): Which column should be the JSON x axis. ycolumn (str): Which column should be the JSON y axis. Returns: list: List of x axis poi...
Read csv files and return xs and ys. Args: log_dir (str): Log directory for csv file. xcolumn (str): Which column should be the JSON x axis. ycolumn (str): Which column should be the JSON y axis. Returns: list: List of x axis points. list: List of y axis points.
_read_csv
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def _export_to_json(json_name, xs, xlabel, ys, ylabel, ys_std): """Save selected csv column to JSON preparing for automatic benchmarking. Args: json_name (str): The JSON file name. xs (list): List of x axis points xlabel (str): Label name for x axis. ys (np.array): List of y axi...
Save selected csv column to JSON preparing for automatic benchmarking. Args: json_name (str): The JSON file name. xs (list): List of x axis points xlabel (str): Label name for x axis. ys (np.array): List of y axis points ylabel (str): Label name for y axis. ys_std (n...
_export_to_json
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def _upload_to_gcp_storage(exec_dir): """Upload all files to GCP storage under exec_dir folder. Args: exec_dir (str): The execution directory. """ _bucket = storage.Client().bucket('resl-garage-benchmarks') exec_name = os.path.basename(exec_dir) for folder_name in os.listdir(exec_dir)...
Upload all files to GCP storage under exec_dir folder. Args: exec_dir (str): The execution directory.
_upload_to_gcp_storage
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/helper.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/helper.py
MIT
def run(names): """Run selected benchmarks. Args: names (tuple): Benchmark names. Raises: BadParameter: if any run name is invalid or duplicated. """ if not names: raise click.BadParameter('Empty names!') if len(names) != len(set(names)): raise click.BadParame...
Run selected benchmarks. Args: names (tuple): Benchmark names. Raises: BadParameter: if any run name is invalid or duplicated.
run
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/run_benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/run_benchmarks.py
MIT
def _get_all_options(): """Return a dict containing all benchmark options. Dict of (str: obj) representing benchmark name and its function object. Returns: dict: Benchmark options. """ d = {} d.update(_get_runs_dict(benchmark_algos)) d.update(_get_runs_dict(benchmark_policies)) ...
Return a dict containing all benchmark options. Dict of (str: obj) representing benchmark name and its function object. Returns: dict: Benchmark options.
_get_all_options
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/run_benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/run_benchmarks.py
MIT
def _get_runs_dict(module): """Return a dict containing benchmark options of the module. Dict of (str: obj) representing benchmark name and its function object. Args: module (object): Module object. Returns: dict: Benchmark options of the module. """ d = {} for name, obj ...
Return a dict containing benchmark options of the module. Dict of (str: obj) representing benchmark name and its function object. Args: module (object): Module object. Returns: dict: Benchmark options of the module.
_get_runs_dict
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/run_benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/run_benchmarks.py
MIT
def _echo_run_names(header, d): """Echo run names to the command line. Args: header (str): The header name. d (dict): The dict containing benchmark options. """ click.echo('-----' + header + '-----') for name in d: click.echo(name) click.echo()
Echo run names to the command line. Args: header (str): The header name. d (dict): The dict containing benchmark options.
_echo_run_names
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/run_benchmarks.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/run_benchmarks.py
MIT
def ddpg_garage_tf(ctxt, env_id, seed): """Create garage TensorFlow DDPG model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Rand...
Create garage TensorFlow DDPG model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
ddpg_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/ddpg_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/ddpg_garage_tf.py
MIT
def her_garage_tf(ctxt, env_id, seed): """Create garage TensorFlow HER model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random...
Create garage TensorFlow HER model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
her_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/her_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/her_garage_tf.py
MIT
def ppo_garage_pytorch(ctxt, env_id, seed): """Create garage PyTorch PPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (...
Create garage PyTorch PPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
ppo_garage_pytorch
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/ppo_garage_pytorch.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/ppo_garage_pytorch.py
MIT
def ppo_garage_tf(ctxt, env_id, seed): """Create garage TensorFlow PPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (in...
Create garage TensorFlow PPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial. ...
ppo_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/ppo_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/ppo_garage_tf.py
MIT
def td3_garage_pytorch(ctxt, env_id, seed): """Create garage TensorFlow TD3 model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Localtrainer to create the snapshotter. env_id (str): Environment id of the task. ...
Create garage TensorFlow TD3 model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Localtrainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial...
td3_garage_pytorch
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/td3_garage_pytorch.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/td3_garage_pytorch.py
MIT
def td3_garage_tf(ctxt, env_id, seed): """Create garage TensorFlow TD3 model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random...
Create garage TensorFlow TD3 model and training. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
td3_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/td3_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/td3_garage_tf.py
MIT
def trpo_garage_pytorch(ctxt, env_id, seed): """Create garage PyTorch TRPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. ...
Create garage PyTorch TRPO model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the tria...
trpo_garage_pytorch
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/trpo_garage_pytorch.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/trpo_garage_pytorch.py
MIT
def trpo_garage_tf(ctxt, env_id, seed): """Create garage Tensorflow TROI model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (...
Create garage Tensorflow TROI model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial. ...
trpo_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/trpo_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/trpo_garage_tf.py
MIT
def vpg_garage_pytorch(ctxt, env_id, seed): """Create garage PyTorch VPG model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (...
Create garage PyTorch VPG model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
vpg_garage_pytorch
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/vpg_garage_pytorch.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/vpg_garage_pytorch.py
MIT
def vpg_garage_tf(ctxt, env_id, seed): """Create garage TensorFlow VPG model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (in...
Create garage TensorFlow VPG model and training. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial. ...
vpg_garage_tf
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/algos/vpg_garage_tf.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/algos/vpg_garage_tf.py
MIT
def continuous_mlp_baseline(ctxt, env_id, seed): """Create Continuous MLP Baseline on TF-PPO. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Ran...
Create Continuous MLP Baseline on TF-PPO. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
continuous_mlp_baseline
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/baselines/continuous_mlp_baseline.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/baselines/continuous_mlp_baseline.py
MIT
def gaussian_cnn_baseline(ctxt, env_id, seed): """Create Gaussian CNN Baseline on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int...
Create Gaussian CNN Baseline on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
gaussian_cnn_baseline
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/baselines/gaussian_cnn_baseline.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/baselines/gaussian_cnn_baseline.py
MIT
def gaussian_mlp_baseline(ctxt, env_id, seed): """Create Gaussian MLP Baseline on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int...
Create Gaussian MLP Baseline on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
gaussian_mlp_baseline
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/baselines/gaussian_mlp_baseline.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/baselines/gaussian_mlp_baseline.py
MIT
def categorical_cnn_policy(ctxt, env_id, seed): """Create Categorical CNN Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (i...
Create Categorical CNN Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
categorical_cnn_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/categorical_cnn_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/categorical_cnn_policy.py
MIT
def categorical_lstm_policy(ctxt, env_id, seed): """Create Categorical LSTM Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed ...
Create Categorical LSTM Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
categorical_lstm_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/categorical_lstm_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/categorical_lstm_policy.py
MIT
def categorical_mlp_policy(ctxt, env_id, seed): """Create Categorical MLP Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (i...
Create Categorical MLP Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
categorical_mlp_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/categorical_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/categorical_mlp_policy.py
MIT
def continuous_mlp_policy(ctxt, env_id, seed): """Create Continuous MLP Policy on TF-DDPG. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random...
Create Continuous MLP Policy on TF-DDPG. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
continuous_mlp_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/continuous_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/continuous_mlp_policy.py
MIT
def gaussian_gru_policy(ctxt, env_id, seed): """Create Gaussian GRU Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): R...
Create Gaussian GRU Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
gaussian_gru_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/gaussian_gru_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/gaussian_gru_policy.py
MIT
def gaussian_lstm_policy(ctxt, env_id, seed): """Create Gaussian LSTM Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int):...
Create Gaussian LSTM Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
gaussian_lstm_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/gaussian_lstm_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/gaussian_lstm_policy.py
MIT
def gaussian_mlp_policy(ctxt, env_id, seed): """Create Gaussian MLP Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): R...
Create Gaussian MLP Policy on TF-PPO. Args: ctxt (garage.experiment.ExperimentContext): The experiment configuration used by Trainer to create the snapshotter. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
gaussian_mlp_policy
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/policies/gaussian_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/policies/gaussian_mlp_policy.py
MIT
def continuous_mlp_q_function(ctxt, env_id, seed): """Create Continuous MLP QFunction on TF-DDPG. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int):...
Create Continuous MLP QFunction on TF-DDPG. Args: ctxt (ExperimentContext): The experiment configuration used by :class:`~Trainer` to create the :class:`~Snapshotter`. env_id (str): Environment id of the task. seed (int): Random positive integer for the trial.
continuous_mlp_q_function
python
rlworkgroup/garage
benchmarks/src/garage_benchmarks/experiments/q_functions/continuous_mlp_q_function.py
https://github.com/rlworkgroup/garage/blob/master/benchmarks/src/garage_benchmarks/experiments/q_functions/continuous_mlp_q_function.py
MIT
def setup(self, algo, env): """Set up trainer for algorithm and environment. This method saves algo and env within trainer and creates a sampler. Note: After setup() is called all variables in session should have been initialized. setup() respects existing values in ses...
Set up trainer for algorithm and environment. This method saves algo and env within trainer and creates a sampler. Note: After setup() is called all variables in session should have been initialized. setup() respects existing values in session so policy weights can ...
setup
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def obtain_episodes(self, itr, batch_size=None, agent_update=None, env_update=None): """Obtain one batch of episodes. Args: itr (int): Index of iteration (epoch). batch_size (int): Nu...
Obtain one batch of episodes. Args: itr (int): Index of iteration (epoch). batch_size (int): Number of steps in batch. This is a hint that the sampler may or may not respect. agent_update (object): Value which will be passed into the `agent_up...
obtain_episodes
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def obtain_samples(self, itr, batch_size=None, agent_update=None, env_update=None): """Obtain one batch of samples. Args: itr (int): Index of iteration (epoch). batch_size (int): Number o...
Obtain one batch of samples. Args: itr (int): Index of iteration (epoch). batch_size (int): Number of steps in batch. This is a hint that the sampler may or may not respect. agent_update (object): Value which will be passed into the `agent_upd...
obtain_samples
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def save(self, epoch): """Save snapshot of current batch. Args: epoch (int): Epoch. Raises: NotSetupError: if save() is called before the trainer is set up. """ if not self._has_setup: raise NotSetupError('Use setup() to setup trainer before...
Save snapshot of current batch. Args: epoch (int): Epoch. Raises: NotSetupError: if save() is called before the trainer is set up.
save
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def restore(self, from_dir, from_epoch='last'): """Restore experiment from snapshot. Args: from_dir (str): Directory of the pickle file to resume experiment from. from_epoch (str or int): The epoch to restore from. Can be 'first', 'last' or a numb...
Restore experiment from snapshot. Args: from_dir (str): Directory of the pickle file to resume experiment from. from_epoch (str or int): The epoch to restore from. Can be 'first', 'last' or a number. Not applicable when snapshot_mode='last...
restore
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def log_diagnostics(self, pause_for_plot=False): """Log diagnostics. Args: pause_for_plot (bool): Pause for plot. """ logger.log('Time %.2f s' % (time.time() - self._start_time)) logger.log('EpochTime %.2f s' % (time.time() - self._itr_start_time)) tabular.r...
Log diagnostics. Args: pause_for_plot (bool): Pause for plot.
log_diagnostics
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def train(self, n_epochs, batch_size=None, plot=False, store_episodes=False, pause_for_plot=False): """Start training. Args: n_epochs (int): Number of epochs. batch_size (int or None): Number of environment st...
Start training. Args: n_epochs (int): Number of epochs. batch_size (int or None): Number of environment steps in one batch. plot (bool): Visualize an episode from the policy after each epoch. store_episodes (bool): Save episodes in snapshot. pause_for...
train
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def step_epochs(self): """Step through each epoch. This function returns a magic generator. When iterated through, this generator automatically performs services such as snapshotting and log management. It is used inside train() in each algorithm. The generator initializes two ...
Step through each epoch. This function returns a magic generator. When iterated through, this generator automatically performs services such as snapshotting and log management. It is used inside train() in each algorithm. The generator initializes two variables: `self.step_itr` and ...
step_epochs
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def resume(self, n_epochs=None, batch_size=None, plot=None, store_episodes=None, pause_for_plot=None): """Resume from restored experiment. This method provides the same interface as train(). If not specified, an argumen...
Resume from restored experiment. This method provides the same interface as train(). If not specified, an argument will default to the saved arguments from the last call to train(). Args: n_epochs (int): Number of epochs. batch_size (int): Number of environment...
resume
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def get_env_copy(self): """Get a copy of the environment. Returns: Environment: An environment instance. """ if self._env: return cloudpickle.loads(cloudpickle.dumps(self._env)) else: return None
Get a copy of the environment. Returns: Environment: An environment instance.
get_env_copy
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def __enter__(self): """Set self.sess as the default session. Returns: TFTrainer: This trainer. """ if tf.compat.v1.get_default_session() is not self.sess: self.sess.__enter__() self.sess_entered = True return self
Set self.sess as the default session. Returns: TFTrainer: This trainer.
__enter__
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def __exit__(self, exc_type, exc_val, exc_tb): """Leave session. Args: exc_type (str): Type. exc_val (object): Value. exc_tb (object): Traceback. """ if tf.compat.v1.get_default_session( ) is self.sess and self.sess_entered: self....
Leave session. Args: exc_type (str): Type. exc_val (object): Value. exc_tb (object): Traceback.
__exit__
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def setup(self, algo, env): """Set up trainer and sessions for algorithm and environment. This method saves algo and env within trainer and creates a sampler, and initializes all uninitialized variables in session. Note: After setup() is called all variables in session shou...
Set up trainer and sessions for algorithm and environment. This method saves algo and env within trainer and creates a sampler, and initializes all uninitialized variables in session. Note: After setup() is called all variables in session should have been initialized. s...
setup
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def initialize_tf_vars(self): """Initialize all uninitialized variables in session.""" with tf.name_scope('initialize_tf_vars'): uninited_set = [ e.decode() for e in self.sess.run( tf.compat.v1.report_uninitialized_variables()) ] se...
Initialize all uninitialized variables in session.
initialize_tf_vars
python
rlworkgroup/garage
src/garage/trainer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/trainer.py
MIT
def get_step_type(cls, step_cnt, max_episode_length, done): """Determines the step type based on step cnt and done signal. Args: step_cnt (int): current step cnt of the environment. max_episode_length (int): maximum episode length. done (bool): the done signal return...
Determines the step type based on step cnt and done signal. Args: step_cnt (int): current step cnt of the environment. max_episode_length (int): maximum episode length. done (bool): the done signal returned by Environment. Returns: StepType: the step typ...
get_step_type
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def from_env_step(cls, env_step, last_observation, agent_info, episode_info): """Create a TimeStep from a EnvStep. Args: env_step (EnvStep): the env step returned by the environment. last_observation (numpy.ndarray): A numpy array of shape :...
Create a TimeStep from a EnvStep. Args: env_step (EnvStep): the env step returned by the environment. last_observation (numpy.ndarray): A numpy array of shape :math:`(O^*)` containing the observation for this time step in the environment. These must confo...
from_env_step
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def concatenate(cls, *batches): """Concatenate two or more :class:`TimeStepBatch`s. Args: batches (list[TimeStepBatch]): Batches to concatenate. Returns: TimeStepBatch: The concatenation of the batches. Raises: ValueError: If no TimeStepBatches are ...
Concatenate two or more :class:`TimeStepBatch`s. Args: batches (list[TimeStepBatch]): Batches to concatenate. Returns: TimeStepBatch: The concatenation of the batches. Raises: ValueError: If no TimeStepBatches are provided.
concatenate
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def split(self) -> List['TimeStepBatch']: """Split a :class:`~TimeStepBatch` into a list of :class:`~TimeStepBatch`s. The opposite of concatenate. Returns: list[TimeStepBatch]: A list of :class:`TimeStepBatch`s, with one :class:`~TimeStep` per :class:`~TimeStepBatch...
Split a :class:`~TimeStepBatch` into a list of :class:`~TimeStepBatch`s. The opposite of concatenate. Returns: list[TimeStepBatch]: A list of :class:`TimeStepBatch`s, with one :class:`~TimeStep` per :class:`~TimeStepBatch`.
split
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def to_time_step_list(self) -> List[Dict[str, np.ndarray]]: """Convert the batch into a list of dictionaries. Breaks the :class:`~TimeStepBatch` into a list of single time step sample dictionaries. len(rewards) (or the number of discrete time step) dictionaries are returned Ret...
Convert the batch into a list of dictionaries. Breaks the :class:`~TimeStepBatch` into a list of single time step sample dictionaries. len(rewards) (or the number of discrete time step) dictionaries are returned Returns: list[dict[str, np.ndarray or dict[str, np.ndarray]]]:...
to_time_step_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def from_time_step_list(cls, env_spec, ts_samples): """Create a :class:`~TimeStepBatch` from a list of time step dictionaries. Args: env_spec (EnvSpec): Specification for the environment from which this data was sampled. ts_samples (list[dict[str, np.ndarray or d...
Create a :class:`~TimeStepBatch` from a list of time step dictionaries. Args: env_spec (EnvSpec): Specification for the environment from which this data was sampled. ts_samples (list[dict[str, np.ndarray or dict[str, np.ndarray]]]): keys: ...
from_time_step_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def concatenate(cls, *batches): """Create a EpisodeBatch by concatenating EpisodeBatches. Args: batches (list[EpisodeBatch]): Batches to concatenate. Returns: EpisodeBatch: The concatenation of the batches. """ if __debug__: for b in batches...
Create a EpisodeBatch by concatenating EpisodeBatches. Args: batches (list[EpisodeBatch]): Batches to concatenate. Returns: EpisodeBatch: The concatenation of the batches.
concatenate
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def _episode_ranges(self): """Iterate through start and stop indices for each episode. Yields: tuple[int, int]: Start index (inclusive) and stop index (exclusive). """ start = 0 for length in self.lengths: stop = start + length ...
Iterate through start and stop indices for each episode. Yields: tuple[int, int]: Start index (inclusive) and stop index (exclusive).
_episode_ranges
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def split(self): """Split an EpisodeBatch into a list of EpisodeBatches. The opposite of concatenate. Returns: list[EpisodeBatch]: A list of EpisodeBatches, with one episode per batch. """ episodes = [] for i, (start, stop) in enumerate(self...
Split an EpisodeBatch into a list of EpisodeBatches. The opposite of concatenate. Returns: list[EpisodeBatch]: A list of EpisodeBatches, with one episode per batch.
split
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def to_list(self): """Convert the batch into a list of dictionaries. Returns: list[dict[str, np.ndarray or dict[str, np.ndarray]]]: Keys: * observations (np.ndarray): Non-flattened array of observations. Has shape (T, S^*) (the unflattened state ...
Convert the batch into a list of dictionaries. Returns: list[dict[str, np.ndarray or dict[str, np.ndarray]]]: Keys: * observations (np.ndarray): Non-flattened array of observations. Has shape (T, S^*) (the unflattened state space of the curren...
to_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def from_list(cls, env_spec, paths): """Create a EpisodeBatch from a list of episodes. Args: env_spec (EnvSpec): Specification for the environment from which this data was sampled. paths (list[dict[str, np.ndarray or dict[str, np.ndarray]]]): Keys: ...
Create a EpisodeBatch from a list of episodes. Args: env_spec (EnvSpec): Specification for the environment from which this data was sampled. paths (list[dict[str, np.ndarray or dict[str, np.ndarray]]]): Keys: * episode_infos (dict[str, np.ndarray]): Dicti...
from_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def next_observations(self): r"""Get the observations seen after actions are performed. In an :class:`~EpisodeBatch`, next_observations don't need to be stored explicitly, since the next observation is already stored in the batch. Returns: np.ndarray: The "next_obse...
Get the observations seen after actions are performed. In an :class:`~EpisodeBatch`, next_observations don't need to be stored explicitly, since the next observation is already stored in the batch. Returns: np.ndarray: The "next_observations" with shape :mat...
next_observations
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def episode_infos(self): r"""Get the episode_infos. In an :class:`~EpisodeBatch`, episode_infos only need to be stored once per episode. However, the episode_infos field of :class:`~TimeStepBatch` has shape :math:`(N \bullet [T])`. This method expands episode_infos_by_episode (w...
Get the episode_infos. In an :class:`~EpisodeBatch`, episode_infos only need to be stored once per episode. However, the episode_infos field of :class:`~TimeStepBatch` has shape :math:`(N \bullet [T])`. This method expands episode_infos_by_episode (which have shape :math:`(N)`) to ...
episode_infos
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def observations_list(self): """Split observations into a list. Returns: list[np.ndarray]: Splitted list. """ obs_list = [] for start, stop in self._episode_ranges(): obs_list.append(self.observations[start:stop]) return obs_list
Split observations into a list. Returns: list[np.ndarray]: Splitted list.
observations_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def actions_list(self): """Split actions into a list. Returns: list[np.ndarray]: Splitted list. """ acts_list = [] for start, stop in self._episode_ranges(): acts_list.append(self.actions[start:stop]) return acts_list
Split actions into a list. Returns: list[np.ndarray]: Splitted list.
actions_list
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def padded_agent_infos(self): """Padded agent infos. Returns: dict[str, np.ndarray]: Padded agent infos. Each value must have shape with :math:`(N, max_episode_length)` or :math:`(N, max_episode_length, S^*)`. """ return { k: pad_...
Padded agent infos. Returns: dict[str, np.ndarray]: Padded agent infos. Each value must have shape with :math:`(N, max_episode_length)` or :math:`(N, max_episode_length, S^*)`.
padded_agent_infos
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def padded_env_infos(self): """Padded env infos. Returns: dict[str, np.ndarray]: Padded env infos. Each value must have shape with :math:`(N, max_episode_length)` or :math:`(N, max_episode_length, S^*)`. """ return { k: pad_batch_...
Padded env infos. Returns: dict[str, np.ndarray]: Padded env infos. Each value must have shape with :math:`(N, max_episode_length)` or :math:`(N, max_episode_length, S^*)`.
padded_env_infos
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def _space_soft_contains(space, element): """Check that a space has the same dimensionality as an element. If the space's dimensionality is not available, check that the space contains the element. Args: space (akro.Space or gym.Space): Space to check element (object): Element to check...
Check that a space has the same dimensionality as an element. If the space's dimensionality is not available, check that the space contains the element. Args: space (akro.Space or gym.Space): Space to check element (object): Element to check in space. Returns: bool: True iff t...
_space_soft_contains
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def check_timestep_batch(batch, array_type, ignored_fields=()): """Check a TimeStepBatch of any array type that has .shape. Args: batch (TimeStepBatch): Batch of timesteps. array_type (type): Array type. ignored_fields (set[str]): Set of fields to ignore checking on. Raises: ...
Check a TimeStepBatch of any array type that has .shape. Args: batch (TimeStepBatch): Batch of timesteps. array_type (type): Array type. ignored_fields (set[str]): Set of fields to ignore checking on. Raises: ValueError: If an invariant of TimeStepBatch is broken.
check_timestep_batch
python
rlworkgroup/garage
src/garage/_dtypes.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_dtypes.py
MIT
def render_modes(self): """list: A list of string representing the supported render modes. See render() for a list of modes. """
list: A list of string representing the supported render modes. See render() for a list of modes.
render_modes
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def step(self, action): """Steps the environment with the action and returns a `EnvStep`. If the environment returned the last `EnvStep` of a sequence (either of type TERMINAL or TIMEOUT) at the previous step, this call to `step()` will start a new sequence and `action` will be ignored....
Steps the environment with the action and returns a `EnvStep`. If the environment returned the last `EnvStep` of a sequence (either of type TERMINAL or TIMEOUT) at the previous step, this call to `step()` will start a new sequence and `action` will be ignored. If `spec.max_episode_leng...
step
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def render(self, mode): """Renders the environment. The set of supported modes varies per environment. By convention, if mode is: * rgb_array: Return an `numpy.ndarray` with shape (x, y, 3) and type uint8, representing RGB values for an x-by-y pixel image, suitable ...
Renders the environment. The set of supported modes varies per environment. By convention, if mode is: * rgb_array: Return an `numpy.ndarray` with shape (x, y, 3) and type uint8, representing RGB values for an x-by-y pixel image, suitable for turning into a video. ...
render
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def visualize(self): """Creates a visualization of the environment. This function should be called **only once** after `reset()` to set up the visualization display. The visualization should be updated when the environment is changed (i.e. when `step()` is called.) Calling `clo...
Creates a visualization of the environment. This function should be called **only once** after `reset()` to set up the visualization display. The visualization should be updated when the environment is changed (i.e. when `step()` is called.) Calling `close()` will deallocate any resour...
visualize
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def close(self): """Closes the environment. This method should close all windows invoked by `visualize()`. Override this function in your subclass to perform any necessary cleanup. Environments will automatically `close()` themselves when they are garbage collected or ...
Closes the environment. This method should close all windows invoked by `visualize()`. Override this function in your subclass to perform any necessary cleanup. Environments will automatically `close()` themselves when they are garbage collected or when the program exits. ...
close
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def __getattr__(self, name): """Forward getattr request to wrapped environment. Args: name (str): attr (str): attribute name Returns: object: the wrapped attribute. Raises: AttributeError: if the requested attribute is a private attribute, ...
Forward getattr request to wrapped environment. Args: name (str): attr (str): attribute name Returns: object: the wrapped attribute. Raises: AttributeError: if the requested attribute is a private attribute, or if the requested attribute is not...
__getattr__
python
rlworkgroup/garage
src/garage/_environment.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_environment.py
MIT
def make_optimizer(optimizer_type, module=None, **kwargs): """Create an optimizer for pyTorch & tensorflow algos. Args: optimizer_type (Union[type, tuple[type, dict]]): Type of optimizer. This can be an optimizer type such as 'torch.optim.Adam' or a tuple of type and dictionary,...
Create an optimizer for pyTorch & tensorflow algos. Args: optimizer_type (Union[type, tuple[type, dict]]): Type of optimizer. This can be an optimizer type such as 'torch.optim.Adam' or a tuple of type and dictionary, where dictionary contains arguments to initialize the...
make_optimizer
python
rlworkgroup/garage
src/garage/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_functions.py
MIT
def rollout(env, agent, *, max_episode_length=np.inf, animated=False, pause_per_frame=None, deterministic=False): """Sample a single episode of the agent in the environment. Args: agent (Policy): Policy used to select actions. ...
Sample a single episode of the agent in the environment. Args: agent (Policy): Policy used to select actions. env (Environment): Environment to perform actions in. max_episode_length (int): If the episode reaches this many timesteps, it is truncated. animated (bool): If ...
rollout
python
rlworkgroup/garage
src/garage/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_functions.py
MIT
def obtain_evaluation_episodes(policy, env, max_episode_length=1000, num_eps=100, deterministic=True): """Sample the policy for num_eps episodes and return average values. Args: p...
Sample the policy for num_eps episodes and return average values. Args: policy (Policy): Policy to use as the actor when gathering samples. env (Environment): The environement used to obtain episodes. max_episode_length (int): Maximum episode length. The episode will truncated w...
obtain_evaluation_episodes
python
rlworkgroup/garage
src/garage/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_functions.py
MIT
def log_multitask_performance(itr, batch, discount, name_map=None): r"""Log performance of episodes from multiple tasks. Args: itr (int): Iteration number to be logged. batch (EpisodeBatch): Batch of episodes. The episodes should have either the "task_name" or "task_id" `env_infos`....
Log performance of episodes from multiple tasks. Args: itr (int): Iteration number to be logged. batch (EpisodeBatch): Batch of episodes. The episodes should have either the "task_name" or "task_id" `env_infos`. If the "task_name" is not present, then `name_map` is required,...
log_multitask_performance
python
rlworkgroup/garage
src/garage/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/_functions.py
MIT