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 test_json_schema_other_types():
"""Test that data types not supported by JSON schema are returned as strings"""
s = Schema({Optional("test_other"): bytes})
assert s.json_schema("my-id") == {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "my-id",
"properties": {"tes... | Test that data types not supported by JSON schema are returned as strings | test_json_schema_other_types | python | keleshev/schema | test_schema.py | https://github.com/keleshev/schema/blob/master/test_schema.py | MIT |
def test_json_schema_root_not_dict(input_schema, expected_keyword, expected_value):
"""Test generating simple JSON Schemas where the root element is not a dict"""
json_schema = Schema(input_schema).json_schema("my-id")
assert json_schema == {
expected_keyword: expected_value,
"$id": "my-id"... | Test generating simple JSON Schemas where the root element is not a dict | test_json_schema_root_not_dict | python | keleshev/schema | test_schema.py | https://github.com/keleshev/schema/blob/master/test_schema.py | MIT |
def test_json_schema_definitions_recursive():
"""Create a JSON schema with an object that refers to itself
This is the example from here: https://json-schema.org/understanding-json-schema/structuring.html#recursion
"""
children = []
person = Schema(
{Optional("name"): str, Optional("childre... | Create a JSON schema with an object that refers to itself
This is the example from here: https://json-schema.org/understanding-json-schema/structuring.html#recursion
| test_json_schema_definitions_recursive | python | keleshev/schema | test_schema.py | https://github.com/keleshev/schema/blob/master/test_schema.py | MIT |
def code(self) -> str:
"""Remove duplicates in autos and errors list and combine them into a single message."""
def uniq(seq: Iterable[Union[str, None]]) -> List[str]:
"""Utility function to remove duplicates while preserving the order."""
seen: Set[str] = set()
uniq... | Remove duplicates in autos and errors list and combine them into a single message. | code | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def uniq(seq: Iterable[Union[str, None]]) -> List[str]:
"""Utility function to remove duplicates while preserving the order."""
seen: Set[str] = set()
unique_list: List[str] = []
for x in seq:
if x is not None and x not in seen:
seen.ad... | Utility function to remove duplicates while preserving the order. | uniq | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def validate(self, data: Any, **kwargs: Any) -> Any:
"""
Validate data using defined sub schema/expressions ensuring all
values are valid.
:param data: Data to be validated with sub defined schemas.
:return: Returns validated data.
"""
# Annotate sub_schema with t... |
Validate data using defined sub schema/expressions ensuring all
values are valid.
:param data: Data to be validated with sub defined schemas.
:return: Returns validated data.
| validate | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def validate(self, data: str, **kwargs: Any) -> str:
"""
Validates data using the defined regex.
:param data: Data to be validated.
:return: Returns validated data.
"""
e = self._error
try:
if self._pattern.search(data):
return data
... |
Validates data using the defined regex.
:param data: Data to be validated.
:return: Returns validated data.
| validate | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def is_valid(self, data: Any, **kwargs: Dict[str, Any]) -> bool:
"""Return whether the given data has passed all the validations
that were specified in the given schema.
"""
try:
self.validate(data, **kwargs)
except SchemaError:
return False
else:
... | Return whether the given data has passed all the validations
that were specified in the given schema.
| is_valid | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _prepend_schema_name(self, message: str) -> str:
"""
If a custom schema name has been defined, prepends it to the error
message that gets raised when a schema error occurs.
"""
if self._name:
message = "{0!r} {1!s}".format(self._name, message)
return messa... |
If a custom schema name has been defined, prepends it to the error
message that gets raised when a schema error occurs.
| _prepend_schema_name | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def json_schema(
self, schema_id: str, use_refs: bool = False, **kwargs: Any
) -> Dict[str, Any]:
"""Generate a draft-07 JSON schema dict representing the Schema.
This method must be called with a schema_id.
:param schema_id: The value of the $id on the main schema
:param us... | Generate a draft-07 JSON schema dict representing the Schema.
This method must be called with a schema_id.
:param schema_id: The value of the $id on the main schema
:param use_refs: Enable reusing object references in the resulting JSON schema.
Schemas with references a... | json_schema | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _create_or_use_ref(return_dict: Dict[str, Any]) -> Dict[str, Any]:
"""If not already seen, return the provided part of the schema unchanged.
If already seen, give an id to the already seen dict and return a reference to the previous part
of the schema instead.
... | If not already seen, return the provided part of the schema unchanged.
If already seen, give an id to the already seen dict and return a reference to the previous part
of the schema instead.
| _create_or_use_ref | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _get_type_name(python_type: Type) -> str:
"""Return the JSON schema name for a Python type"""
if python_type == str:
return "string"
elif python_type == int:
return "integer"
elif python_type == float:
... | Return the JSON schema name for a Python type | _get_type_name | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _to_json_type(value: Any) -> Any:
"""Attempt to convert a constant value (for "const" and "default") to a JSON serializable value"""
if value is None or type(value) in (str, int, float, bool, list, dict):
return value
if type(value) in (tuple, set... | Attempt to convert a constant value (for "const" and "default") to a JSON serializable value | _to_json_type | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _key_allows_additional_properties(key: Any) -> bool:
"""Check if a key is broad enough to allow additional properties"""
if isinstance(key, Optional):
return _key_allows_additional_properties(key.schema)
... | Check if a key is broad enough to allow additional properties | _key_allows_additional_properties | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _get_key_title(key: Any) -> Union[str, None]:
"""Get the title associated to a key (as specified in a Literal object). Return None if not a Literal"""
if isinstance(key, Optional):
return _get_key_title(key.schema)
... | Get the title associated to a key (as specified in a Literal object). Return None if not a Literal | _get_key_title | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _get_key_description(key: Any) -> Union[str, None]:
"""Get the description associated to a key (as specified in a Literal object). Return None if not a Literal"""
if isinstance(key, Optional):
return _get_key_description(key.sch... | Get the description associated to a key (as specified in a Literal object). Return None if not a Literal | _get_key_description | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _get_key_name(key: Any) -> Any:
"""Get the name of a key (as specified in a Literal object). Return the key unchanged if not a Literal"""
if isinstance(key, Optional):
return _get_key_name(key.schema)
... | Get the name of a key (as specified in a Literal object). Return the key unchanged if not a Literal | _get_key_name | python | keleshev/schema | schema/__init__.py | https://github.com/keleshev/schema/blob/master/schema/__init__.py | MIT |
def _to_tag_model_instances(self, tags, tag_kwargs):
"""
Takes an iterable containing either strings, tag objects, or a mixture
of both and returns a list of tag objects while preserving order.
"""
db = router.db_for_write(self.through, instance=self.instance)
case_insen... |
Takes an iterable containing either strings, tag objects, or a mixture
of both and returns a list of tag objects while preserving order.
| _to_tag_model_instances | python | jazzband/django-taggit | taggit/managers.py | https://github.com/jazzband/django-taggit/blob/master/taggit/managers.py | BSD-3-Clause |
def set(self, tags, *, through_defaults=None, **kwargs):
"""
Set the object's tags to the given n tags. If the clear kwarg is True
then all existing tags are removed (using `.clear()`) and the new tags
added. Otherwise, only those tags that are not present in the args are
removed... |
Set the object's tags to the given n tags. If the clear kwarg is True
then all existing tags are removed (using `.clear()`) and the new tags
added. Otherwise, only those tags that are not present in the args are
removed and any new tags added.
Any kwarg apart from 'clear' will ... | set | python | jazzband/django-taggit | taggit/managers.py | https://github.com/jazzband/django-taggit/blob/master/taggit/managers.py | BSD-3-Clause |
def deconstruct(self):
"""
Deconstruct the object, used with migrations.
"""
name, path, args, kwargs = super().deconstruct()
# Remove forced kwargs.
for kwarg in ("serialize", "null"):
del kwargs[kwarg]
# Add arguments related to relations.
# ... |
Deconstruct the object, used with migrations.
| deconstruct | python | jazzband/django-taggit | taggit/managers.py | https://github.com/jazzband/django-taggit/blob/master/taggit/managers.py | BSD-3-Clause |
def slugify_unicode_stripping_prep(tag):
"""
This handles stripping via unidecode if it's installed,
otherwise is a no-op
"""
if unidecode_installed:
return unidecode(tag)
else:
return tag |
This handles stripping via unidecode if it's installed,
otherwise is a no-op
| slugify_unicode_stripping_prep | python | jazzband/django-taggit | taggit/models.py | https://github.com/jazzband/django-taggit/blob/master/taggit/models.py | BSD-3-Clause |
def _parse_tags(tagstring):
"""
Parses tag input, with multiple word input being activated and
delineated by commas and double quotes. Quotes take precedence, so
they may contain commas.
Returns a sorted list of unique tag names.
Ported from Jonathan Buchanan's `django-tagging
<http://djan... |
Parses tag input, with multiple word input being activated and
delineated by commas and double quotes. Quotes take precedence, so
they may contain commas.
Returns a sorted list of unique tag names.
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_
| _parse_tags | python | jazzband/django-taggit | taggit/utils.py | https://github.com/jazzband/django-taggit/blob/master/taggit/utils.py | BSD-3-Clause |
def _deduplicate_tags(self, existing_tag, tag_to_remove):
"""
Remove a tag by merging it into an existing tag
"""
# If this ends up very slow for you, please file a ticket!
# This isn't trying to be performant, in order to keep the code simple.
for item in TaggedItem.obje... |
Remove a tag by merging it into an existing tag
| _deduplicate_tags | python | jazzband/django-taggit | taggit/management/commands/deduplicate_tags.py | https://github.com/jazzband/django-taggit/blob/master/taggit/management/commands/deduplicate_tags.py | BSD-3-Clause |
def test_integers(self):
"""Adding an integer as a tag should raise a ValueError (#237)."""
apple = self.food_model.objects.create(name="apple")
with self.assertRaisesRegex(
ValueError,
(
r"Cannot add 1 \(<(type|class) 'int'>\). "
r"Expecte... | Adding an integer as a tag should raise a ValueError (#237). | test_integers | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_multi_inheritance_similarity_by_tag(self):
"""Test that pears are more similar to apples than watermelons using multi_inheritance"""
apple = self.multi_inheritance_food_model.objects.create(name="apple")
apple.tags.add("green", "juicy", "small", "sour")
pear = self.multi_inheri... | Test that pears are more similar to apples than watermelons using multi_inheritance | test_multi_inheritance_similarity_by_tag | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_similarity_by_tag(self):
"""Test that pears are more similar to apples than watermelons"""
apple = self.food_model.objects.create(name="apple")
apple.tags.add("green", "juicy", "small", "sour")
pear = self.food_model.objects.create(name="pear")
pear.tags.add("green", "j... | Test that pears are more similar to apples than watermelons | test_similarity_by_tag | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_with_double_quoted_multiple_words(self):
"""
Test with double-quoted multiple words.
A completed quote will trigger this. Unclosed quotes are ignored.
"""
self.assertEqual(parse_tags('"one'), ["one"])
self.assertEqual(parse_tags('"one two'), ["one", "two"])
... |
Test with double-quoted multiple words.
A completed quote will trigger this. Unclosed quotes are ignored.
| test_with_double_quoted_multiple_words | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_ordered_by_creation_by_default(self):
"""
Test that the tags are set and returned exactly as they are provided in .set
"""
str_tags = ["red", "green", "delicious"]
sample_obj = TestModel.objects.create()
sample_obj.tags.set(str_tags)
self.assertEqual(str... |
Test that the tags are set and returned exactly as they are provided in .set
| test_ordered_by_creation_by_default | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_default_ordering_on_mixed_operation(self):
"""
Test that our default ordering is preserved even when mixing strings
and objects
"""
tag_obj = Tag.objects.create(name="mcintosh")
tag_obj_2 = Tag.objects.create(name="fuji")
str_tags = ["red", "green", "deli... |
Test that our default ordering is preserved even when mixing strings
and objects
| test_default_ordering_on_mixed_operation | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_tag_natural_key(self):
"""
Test that tags can be dumped and loaded using natural keys.
"""
# confirm count in the DB
self.assertEqual(self._queryset.count(), self.tag_count)
# dump all tags to a file
self._dump_model(Tag)
# Delete all tags
... |
Test that tags can be dumped and loaded using natural keys.
| test_tag_natural_key | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_tag_reloading_with_changed_pk(self):
"""Test that tags are not reliant on the primary key of the tag model.
Test that data is correctly loaded after database state has changed.
"""
original_shape = self._queryset.first()
original_pk = original_shape.pk
original... | Test that tags are not reliant on the primary key of the tag model.
Test that data is correctly loaded after database state has changed.
| test_tag_reloading_with_changed_pk | python | jazzband/django-taggit | tests/tests.py | https://github.com/jazzband/django-taggit/blob/master/tests/tests.py | BSD-3-Clause |
def test_cache_clears_on_add(self):
"""
Test that the prefetch cache gets cleared on tag addition
"""
sample_obj = TestModel.objects.prefetch_related("tags").get()
self.assertTrue(sample_obj.tags.is_cached(sample_obj))
sample_obj.tags.add("4")
self.assertFalse(sa... |
Test that the prefetch cache gets cleared on tag addition
| test_cache_clears_on_add | python | jazzband/django-taggit | tests/test_models.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_models.py | BSD-3-Clause |
def test_cache_clears_on_remove(self):
"""
Test that the prefetch cache gets cleared on tag removal
"""
sample_obj = TestModel.objects.prefetch_related("tags").get()
self.assertTrue(sample_obj.tags.is_cached(sample_obj))
sample_obj.tags.remove("3")
self.assertFal... |
Test that the prefetch cache gets cleared on tag removal
| test_cache_clears_on_remove | python | jazzband/django-taggit | tests/test_models.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_models.py | BSD-3-Clause |
def test_cache_clears_on_clear(self):
"""
Test that the prefetch cache gets cleared when tags are cleared
"""
sample_obj = TestModel.objects.prefetch_related("tags").get()
self.assertTrue(sample_obj.tags.is_cached(sample_obj))
sample_obj.tags.clear()
self.assertF... |
Test that the prefetch cache gets cleared when tags are cleared
| test_cache_clears_on_clear | python | jazzband/django-taggit | tests/test_models.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_models.py | BSD-3-Clause |
def test_taggit_serializer_update(self):
"""Test if serializer class is working properly on updating object"""
request_data = {"tags": ["1", "2", "3"]}
test_model = TestModel.objects.create()
serializer = TestModelSerializer(test_model, data=request_data)
serializer.is_valid()
... | Test if serializer class is working properly on updating object | test_taggit_serializer_update | python | jazzband/django-taggit | tests/test_serializers.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_serializers.py | BSD-3-Clause |
def test_taggit_serializer_create(self):
"""
Test if serializer class is working
properly on creating a object
"""
request_data = {"tags": ["1", "2", "3"]}
serializer = TestModelSerializer(data=request_data)
assert serializer.is_valid()
test_model = seria... |
Test if serializer class is working
properly on creating a object
| test_taggit_serializer_create | python | jazzband/django-taggit | tests/test_serializers.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_serializers.py | BSD-3-Clause |
def test_taggit_serializer_create_with_string(self):
"""
Test that we can pass in a string instead of an array for
a tag list without issues
"""
request_data = {"tags": '["1", "2", "3"]'}
serializer = TestModelSerializer(data=request_data)
assert serializer.is_va... |
Test that we can pass in a string instead of an array for
a tag list without issues
| test_taggit_serializer_create_with_string | python | jazzband/django-taggit | tests/test_serializers.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_serializers.py | BSD-3-Clause |
def test_taggit_removes_tags(self):
"""
Test if the old assigned tags are removed
"""
test_model = TestModel.objects.create()
test_model.tags.add("1")
request_data = {"tags": ["2", "3"]}
serializer = TestModelSerializer(test_model, data=request_data)
ser... |
Test if the old assigned tags are removed
| test_taggit_removes_tags | python | jazzband/django-taggit | tests/test_serializers.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_serializers.py | BSD-3-Clause |
def test_returns_new_data_after_update(self):
"""
Test if the serializer uses fresh data after updating prefetched fields
"""
TestModel.objects.create().tags.add("1")
test_model = TestModel.objects.prefetch_related("tags").get()
assert TestModelSerializer(test_model).da... |
Test if the serializer uses fresh data after updating prefetched fields
| test_returns_new_data_after_update | python | jazzband/django-taggit | tests/test_serializers.py | https://github.com/jazzband/django-taggit/blob/master/tests/test_serializers.py | BSD-3-Clause |
def get_human_normalized_score(game: str, raw_score: float) -> float:
"""Converts game score to human-normalized score."""
game_scores = _ATARI_DATA.get(game, (math.nan, math.nan))
random, human = game_scores[_RANDOM_COL], game_scores[_HUMAN_COL]
return (raw_score - random) / (human - random) | Converts game score to human-normalized score. | get_human_normalized_score | python | google-deepmind/dqn_zoo | dqn_zoo/atari_data.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/atari_data.py | Apache-2.0 |
def _register_atari_environments():
"""Registers Atari environments in Gym to be as similar to Xitari as possible.
Main difference from PongNoFrameSkip-v4, etc. is max_episode_steps is unset
and only the usual 57 Atari games are registered.
"""
for game in atari_data.ATARI_GAMES:
gym.envs.registration.re... | Registers Atari environments in Gym to be as similar to Xitari as possible.
Main difference from PongNoFrameSkip-v4, etc. is max_episode_steps is unset
and only the usual 57 Atari games are registered.
| _register_atari_environments | python | google-deepmind/dqn_zoo | dqn_zoo/gym_atari.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/gym_atari.py | Apache-2.0 |
def reset(self) -> dm_env.TimeStep:
"""Resets the environment and starts a new episode."""
observation = self._gym_env.reset()
lives = np.int32(self._gym_env.ale.lives())
timestep = dm_env.restart((observation, lives))
self._start_of_episode = False
return timestep | Resets the environment and starts a new episode. | reset | python | google-deepmind/dqn_zoo | dqn_zoo/gym_atari.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/gym_atari.py | Apache-2.0 |
def step(self, action: np.int32) -> dm_env.TimeStep:
"""Updates the environment given an action and returns a timestep."""
# If the previous timestep was LAST then we call reset() on the Gym
# environment, otherwise step(). Although Gym environments allow you to step
# through episode boundaries (simila... | Updates the environment given an action and returns a timestep. | step | python | google-deepmind/dqn_zoo | dqn_zoo/gym_atari.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/gym_atari.py | Apache-2.0 |
def __init__(
self,
environment: dm_env.Environment,
max_noop_steps: int,
min_noop_steps: int = 0,
noop_action: int = 0,
seed: Optional[int] = None,
):
"""Initializes the random noops environment wrapper."""
self._environment = environment
if max_noop_steps < min_noop_s... | Initializes the random noops environment wrapper. | __init__ | python | google-deepmind/dqn_zoo | dqn_zoo/gym_atari.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/gym_atari.py | Apache-2.0 |
def step(self, action):
"""Steps environment given action.
If beginning a new episode then random noops are applied as in `reset()`.
Args:
action: action to pass to environment conforming to action spec.
Returns:
`Timestep` from the inner environment unless beginning a new episode, in
... | Steps environment given action.
If beginning a new episode then random noops are applied as in `reset()`.
Args:
action: action to pass to environment conforming to action spec.
Returns:
`Timestep` from the inner environment unless beginning a new episode, in
which case this is the times... | step | python | google-deepmind/dqn_zoo | dqn_zoo/gym_atari.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/gym_atari.py | Apache-2.0 |
def _dqn_default_initializer(
num_input_units: int,
) -> hk.initializers.Initializer:
"""Default initialization scheme inherited from past implementations of DQN.
This scheme was historically used to initialize all weights and biases
in convolutional and linear layers of DQN-type agents' networks.
It initi... | Default initialization scheme inherited from past implementations of DQN.
This scheme was historically used to initialize all weights and biases
in convolutional and linear layers of DQN-type agents' networks.
It initializes each weight as an independent uniform sample from [`-c`, `c`],
where `c = 1 / np.sqrt(... | _dqn_default_initializer | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def conv(
num_features: int,
kernel_shape: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]],
) -> NetworkFn:
"""Convolutional layer with DQN's legacy weight initialization scheme."""
def net_fn(inputs):
"""Function representing conv layer with DQN's legacy initialization."""
num... | Convolutional layer with DQN's legacy weight initialization scheme. | conv | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing conv layer with DQN's legacy initialization."""
num_input_units = inputs.shape[-1] * kernel_shape[0] * kernel_shape[1]
initializer = _dqn_default_initializer(num_input_units)
layer = hk.Conv2D(
num_features,
kernel_shape=kernel_shape,
... | Function representing conv layer with DQN's legacy initialization. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def linear(num_outputs: int, with_bias=True) -> NetworkFn:
"""Linear layer with DQN's legacy weight initialization scheme."""
def net_fn(inputs):
"""Function representing linear layer with DQN's legacy initialization."""
initializer = _dqn_default_initializer(inputs.shape[-1])
layer = hk.Linear(
... | Linear layer with DQN's legacy weight initialization scheme. | linear | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing linear layer with DQN's legacy initialization."""
initializer = _dqn_default_initializer(inputs.shape[-1])
layer = hk.Linear(
num_outputs, with_bias=with_bias, w_init=initializer, b_init=initializer
)
return layer(inputs) | Function representing linear layer with DQN's legacy initialization. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def linear_with_shared_bias(num_outputs: int) -> NetworkFn:
"""Linear layer with single shared bias instead of one bias per output."""
def layer_fn(inputs):
"""Function representing a linear layer with single shared bias."""
initializer = _dqn_default_initializer(inputs.shape[-1])
bias_free_linear = hk... | Linear layer with single shared bias instead of one bias per output. | linear_with_shared_bias | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def layer_fn(inputs):
"""Function representing a linear layer with single shared bias."""
initializer = _dqn_default_initializer(inputs.shape[-1])
bias_free_linear = hk.Linear(
num_outputs, with_bias=False, w_init=initializer
)
linear_output = bias_free_linear(inputs)
bias = hk.get_param... | Function representing a linear layer with single shared bias. | layer_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def noisy_linear(
num_outputs: int, weight_init_stddev: float, with_bias: bool = True
) -> NetworkFn:
"""Linear layer with weight randomization http://arxiv.org/abs/1706.10295."""
def make_noise_sqrt(rng, shape):
noise = jax.random.truncated_normal(rng, lower=-2.0, upper=2.0, shape=shape)
return jax.la... | Linear layer with weight randomization http://arxiv.org/abs/1706.10295. | noisy_linear | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing a linear layer with learned noise distribution."""
num_inputs = inputs.shape[-1]
mu_initializer = _dqn_default_initializer(num_inputs)
mu_layer = hk.Linear(
num_outputs,
name='mu',
with_bias=with_bias,
w_init=mu_initializer,
... | Function representing a linear layer with learned noise distribution. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def dqn_torso() -> NetworkFn:
"""DQN convolutional torso.
Includes scaling from [`0`, `255`] (`uint8`) to [`0`, `1`] (`float32`)`.
Returns:
Network function that `haiku.transform` can be called on.
"""
def net_fn(inputs):
"""Function representing convolutional torso for a DQN Q-network."""
netw... | DQN convolutional torso.
Includes scaling from [`0`, `255`] (`uint8`) to [`0`, `1`] (`float32`)`.
Returns:
Network function that `haiku.transform` can be called on.
| dqn_torso | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing convolutional torso for a DQN Q-network."""
network = hk.Sequential([
lambda x: x.astype(jnp.float32) / 255.0,
conv(32, kernel_shape=(8, 8), stride=(4, 4)),
jax.nn.relu,
conv(64, kernel_shape=(4, 4), stride=(2, 2)),
jax.nn.relu... | Function representing convolutional torso for a DQN Q-network. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def dqn_value_head(num_actions: int, shared_bias: bool = False) -> NetworkFn:
"""Regular DQN Q-value head with single hidden layer."""
last_layer = linear_with_shared_bias if shared_bias else linear
def net_fn(inputs):
"""Function representing value head for a DQN Q-network."""
network = hk.Sequential([... | Regular DQN Q-value head with single hidden layer. | dqn_value_head | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing value head for a DQN Q-network."""
network = hk.Sequential([
linear(512),
jax.nn.relu,
last_layer(num_actions),
])
return network(inputs) | Function representing value head for a DQN Q-network. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def double_dqn_atari_network(num_actions: int) -> NetworkFn:
"""DQN network with shared bias in final layer, expects `uint8` input."""
def net_fn(inputs):
"""Function representing DQN Q-network with shared bias output layer."""
network = hk.Sequential([
dqn_torso(),
dqn_value_head(num_actio... | DQN network with shared bias in final layer, expects `uint8` input. | double_dqn_atari_network | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def net_fn(inputs):
"""Function representing DQN Q-network with shared bias output layer."""
network = hk.Sequential([
dqn_torso(),
dqn_value_head(num_actions, shared_bias=True),
])
return QNetworkOutputs(q_values=network(inputs)) | Function representing DQN Q-network with shared bias output layer. | net_fn | python | google-deepmind/dqn_zoo | dqn_zoo/networks.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/networks.py | Apache-2.0 |
def reset(self) -> None:
"""Resets the agent's episodic state such as frame stack and action repeat.
This method should be called at the beginning of every episode.
""" | Resets the agent's episodic state such as frame stack and action repeat.
This method should be called at the beginning of every episode.
| reset | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def run_loop(
agent: Agent,
environment: dm_env.Environment,
max_steps_per_episode: int = 0,
yield_before_reset: bool = False,
) -> Iterable[
Tuple[
dm_env.Environment, Optional[dm_env.TimeStep], Agent, Optional[Action]
]
]:
"""Repeatedly alternates step calls on environment and agent.... | Repeatedly alternates step calls on environment and agent.
At time `t`, `t + 1` environment timesteps and `t + 1` agent steps have been
seen in the current episode. `t` resets to `0` for the next episode.
Args:
agent: Agent to be run, has methods `step(timestep)` and `reset()`.
environment: Environment ... | run_loop | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def generate_statistics(
trackers: Sequence[Any],
timestep_action_sequence: Iterable[
Tuple[
dm_env.Environment,
Optional[dm_env.TimeStep],
Agent,
Optional[Action],
]
],
) -> Mapping[str, Any]:
"""Generates statistics from a sequence of times... | Generates statistics from a sequence of timestep and actions. | generate_statistics | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def reset(self) -> None:
"""Resets all gathered statistics, not to be called between episodes."""
self._num_steps_since_reset = 0
self._num_steps_over_episodes = 0
self._episode_returns = []
self._current_episode_step = 0
self._current_episode_rewards = [] | Resets all gathered statistics, not to be called between episodes. | reset | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def get(self) -> Mapping[str, Union[int, float, None]]:
"""Aggregates statistics and returns as a dictionary.
Here the convention is `episode_return` is set to `current_episode_return`
if a full episode has not been encountered. Otherwise it is set to
`mean_episode_return` which is the mean return of c... | Aggregates statistics and returns as a dictionary.
Here the convention is `episode_return` is set to `current_episode_return`
if a full episode has not been encountered. Otherwise it is set to
`mean_episode_return` which is the mean return of complete episodes only. If
no steps have been taken at all, ... | get | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def select_action(rng_key, network_params, s_t):
"""Samples action from eps-greedy policy wrt Q-values at given state."""
rng_key, apply_key, policy_key = jax.random.split(rng_key, 3)
q_t = network.apply(network_params, apply_key, s_t[None, ...]).q_values[0]
a_t = distrax.EpsilonGreedy(q_t, expl... | Samples action from eps-greedy policy wrt Q-values at given state. | select_action | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def get_state(self) -> Mapping[str, Any]:
"""Retrieves agent state as a dictionary (e.g. for serialization)."""
# State contains network params to make agent easy to run from a checkpoint.
return {
'rng_key': self._rng_key,
'network_params': self.network_params,
} | Retrieves agent state as a dictionary (e.g. for serialization). | get_state | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def set_state(self, state: Mapping[str, Any]) -> None:
"""Sets agent state from a (potentially de-serialized) dictionary."""
self._rng_key = state['rng_key']
self.network_params = state['network_params'] | Sets agent state from a (potentially de-serialized) dictionary. | set_state | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def __call__(self, t):
"""Implements a linear transition from a begin to an end value."""
frac = min(max(t - self._begin_t, 0), self._decay_steps) / self._decay_steps
return (1 - frac) * self._begin_value + frac * self._end_value | Implements a linear transition from a begin to an end value. | __call__ | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def __init__(self, fname: str):
"""Initializes a `CsvWriter`.
Args:
fname: File name (path) for file to be written to.
"""
dirname = os.path.dirname(fname)
if not os.path.exists(dirname):
os.makedirs(dirname)
self._fname = fname
self._header_written = False
self._fieldnames ... | Initializes a `CsvWriter`.
Args:
fname: File name (path) for file to be written to.
| __init__ | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def write(self, values: collections.OrderedDict[str, float]) -> None:
"""Appends given values as new row to CSV file."""
if self._fieldnames is None:
self._fieldnames = values.keys()
# Open a file in 'append' mode, so we can continue logging safely to the
# same file after e.g. restarting from a c... | Appends given values as new row to CSV file. | write | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def get_state(self) -> Mapping[str, Any]:
"""Retrieves `CsvWriter` state as a `dict` (e.g. for serialization)."""
return {
'header_written': self._header_written,
'fieldnames': self._fieldnames,
} | Retrieves `CsvWriter` state as a `dict` (e.g. for serialization). | get_state | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def set_state(self, state: Mapping[str, Any]) -> None:
"""Sets `CsvWriter` state from a (potentially de-serialized) dictionary."""
self._header_written = state['header_written']
self._fieldnames = state['fieldnames'] | Sets `CsvWriter` state from a (potentially de-serialized) dictionary. | set_state | python | google-deepmind/dqn_zoo | dqn_zoo/parts.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts.py | Apache-2.0 |
def test_error_wrong_end_args(self):
"""Checks error in case none or both of end_t, decay_steps are given."""
with self.assertRaisesRegex(ValueError, 'Exactly one of'):
_ = parts.LinearSchedule(begin_value=0.0, end_value=1.0, begin_t=5)
with self.assertRaisesRegex(ValueError, 'Exactly one of'):
... | Checks error in case none or both of end_t, decay_steps are given. | test_error_wrong_end_args | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_basic(self):
"""Tests sequence of agent and environment interactions in typical usage."""
tape = []
agent = test_utils.DummyAgent(tape)
environment = test_utils.DummyEnvironment(tape, episode_length=4)
episode_index = 0
t = 0 # steps = t + 1
max_steps = 14
loop_outputs = parts... | Tests sequence of agent and environment interactions in typical usage. | test_basic | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_file_writes(self):
"""Tests that file is opened and written correctly."""
writer = parts.CsvWriter('test.csv')
self.mock_open.assert_not_called()
self.fake_file.write.assert_not_called()
writer.write(collections.OrderedDict([('a', 1), ('b', 2)]))
self.mock_open.assert_called_once_with('... | Tests that file is opened and written correctly. | test_file_writes | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_deserialize_after_header(self):
"""Tests that no header is written unnecessarily after deserialization."""
writer1 = parts.CsvWriter('test.csv')
writer1.write(collections.OrderedDict([('a', 1), ('b', 2)]))
self.assertSequenceEqual(
[mock.call('a,b\r\n'), mock.call('1,2\r\n')],
s... | Tests that no header is written unnecessarily after deserialization. | test_deserialize_after_header | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_deserialize_before_header(self):
"""Tests that header is written after deserialization if not written yet."""
writer1 = parts.CsvWriter('test.csv')
self.fake_file.write.assert_not_called()
writer2 = parts.CsvWriter('test.csv')
writer2.set_state(writer1.get_state())
writer2.write(collect... | Tests that header is written after deserialization if not written yet. | test_deserialize_before_header | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_error_new_keys(self):
"""Tests that an error is thrown when an unexpected key occurs."""
writer = parts.CsvWriter('test.csv')
writer.write(collections.OrderedDict([('a', 1), ('b', 2)]))
with self.assertRaisesRegex(ValueError, 'fields not in fieldnames'):
writer.write(collections.OrderedDi... | Tests that an error is thrown when an unexpected key occurs. | test_error_new_keys | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_missing_keys(self):
"""Tests that when a key is missing, an empty value is used."""
writer = parts.CsvWriter('test.csv')
writer.write(collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)]))
writer.write(collections.OrderedDict([('a', 4), ('c', 6)]))
self.assertSequenceEqual(
[mock.... | Tests that when a key is missing, an empty value is used. | test_missing_keys | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def test_create_dir(self):
"""Tests that a csv file dir is created if it doesn't exist yet."""
with mock.patch('os.path.exists') as fake_exists, mock.patch(
'os.makedirs'
) as fake_makedirs:
fake_exists.return_value = False
dirname = '/some/sub/dir'
_ = parts.CsvWriter(dirname + '/... | Tests that a csv file dir is created if it doesn't exist yet. | test_create_dir | python | google-deepmind/dqn_zoo | dqn_zoo/parts_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/parts_test.py | Apache-2.0 |
def trailing_zero_pad(
length: int,
) -> Processor[[List[np.ndarray]], List[np.ndarray]]:
"""Adds trailing zero padding to array lists to ensure a minimum length."""
def trailing_zero_pad_fn(arrays):
padding_length = length - len(arrays)
if padding_length <= 0:
return arrays
zero = np.zeros_l... | Adds trailing zero padding to array lists to ensure a minimum length. | trailing_zero_pad | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def none_to_zero_pad(values: List[Optional[NamedTuple]]) -> List[NamedTuple]:
"""Replaces `None`s in a list of named tuples with zeros of same structure."""
actual_values = [n for n in values if n is not None]
if not actual_values:
raise ValueError('Must have at least one value which is not None.')
if len(... | Replaces `None`s in a list of named tuples with zeros of same structure. | none_to_zero_pad | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def named_tuple_sequence_stack(values: Sequence[NamedTuple]) -> NamedTuple:
"""Converts a sequence of named tuples into a named tuple of tuples."""
# [T(1, 2), T(3, 4), T(5, 6)].
transposed = zip(*values)
# ((1, 3, 5), (2, 4, 6)).
return type(values[0])(*transposed)
# T((1, 3, 5), (2, 4, 6)). | Converts a sequence of named tuples into a named tuple of tuples. | named_tuple_sequence_stack | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def reduce_step_type(
step_types: Sequence[StepType], debug: bool = False
) -> StepType:
"""Outputs a representative step type from an array of step types."""
# Zero padding will appear to be FIRST. Padding should only be seen before the
# FIRST (e.g. 000F) or after LAST (e.g. ML00).
output_step_type = Ste... | Outputs a representative step type from an array of step types. | reduce_step_type | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def aggregate_rewards(
rewards: Sequence[Optional[float]], debug: bool = False
) -> Optional[float]:
"""Sums up rewards, assumes discount is 1."""
if None in rewards:
if debug:
np_rewards = np.array(rewards)
if not (np_rewards[-1] is None and (np_rewards[:-1] == 0).all()):
# Should only ... | Sums up rewards, assumes discount is 1. | aggregate_rewards | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def aggregate_discounts(
discounts: Sequence[Optional[float]], debug: bool = False
) -> Optional[float]:
"""Aggregates array of discounts into a scalar, expects `0`, `1` or `None`."""
if debug:
np_discounts = np.array(discounts)
if not np.isin(np_discounts, [0.0, 1.0, None]).all():
raise ValueErro... | Aggregates array of discounts into a scalar, expects `0`, `1` or `None`. | aggregate_discounts | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def rgb2y(array: np.ndarray) -> np.ndarray:
"""Converts RGB image array into grayscale."""
chex.assert_rank(array, 3)
output = np.tensordot(array, [0.299, 0.587, 1 - (0.299 + 0.587)], (-1, 0))
return output.astype(np.uint8) | Converts RGB image array into grayscale. | rgb2y | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def resize(shape: Tuple[int, ...]) -> Processor[[np.ndarray], np.ndarray]:
"""Resizes array to the given shape."""
if len(shape) != 2:
raise ValueError('Resize shape has to be 2D, given: %s.' % str(shape))
# Image.resize takes (width, height) as output_shape argument.
image_shape = (shape[1], shape[0])
d... | Resizes array to the given shape. | resize | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def apply_additional_discount(
additional_discount: float,
) -> Processor[[float], float]:
"""Returns a function that scales its non-`None` input by a constant."""
return lambda d: None if d is None else additional_discount * d | Returns a function that scales its non-`None` input by a constant. | apply_additional_discount | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def clip_reward(bound: float) -> Processor[[Optional[float]], Optional[float]]:
"""Returns a function that clips non-`None` inputs to (`-bound`, `bound`)."""
def clip_reward_fn(reward):
return None if reward is None else max(min(reward, bound), -bound)
return clip_reward_fn | Returns a function that clips non-`None` inputs to (`-bound`, `bound`). | clip_reward | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def show(prefix: str) -> Processor[[Any], Any]:
"""Prints value and passes through, for debugging."""
def show_fn(value):
print('%s: %s' % (prefix, value))
return value
return show_fn | Prints value and passes through, for debugging. | show | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def reset(self) -> dm_env.TimeStep:
"""Resets environment and provides the first processed timestep."""
reset(self._processor)
timestep = self._environment.reset()
processed_timestep = self._processor(timestep)
assert processed_timestep is not None
self._reset_next_step = False
return proces... | Resets environment and provides the first processed timestep. | reset | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def step(self, action: int) -> dm_env.TimeStep:
"""Steps up to `num_action_repeat` times, returns a processed timestep."""
# This implements the action repeat by repeatedly passing in the last action
# until an actual timestep is returned by the processor.
if self._reset_next_step:
return self.re... | Steps up to `num_action_repeat` times, returns a processed timestep. | step | python | google-deepmind/dqn_zoo | dqn_zoo/processors.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors.py | Apache-2.0 |
def test_can_use_in_an_agent(self):
"""Example of using Atari processor on the agent side."""
env = gym_atari.GymAtari('pong', seed=1)
action_spec = env.action_spec()
agent = AgentWithPreprocessing(num_actions=action_spec.num_values)
agent.reset()
timestep = env.reset()
actions = []
fo... | Example of using Atari processor on the agent side. | test_can_use_in_an_agent | python | google-deepmind/dqn_zoo | dqn_zoo/processors_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors_test.py | Apache-2.0 |
def test_default_on_fixed_input(self):
"""End-to-end test on fixed input.
This is to test (mainly observation) processors do not change due to updates
in underlying library functions.
"""
# Create environment just for the observation spec.
env = gym_atari.GymAtari('pong', seed=1)
rgb_spec, ... | End-to-end test on fixed input.
This is to test (mainly observation) processors do not change due to updates
in underlying library functions.
| test_default_on_fixed_input | python | google-deepmind/dqn_zoo | dqn_zoo/processors_test.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/processors_test.py | Apache-2.0 |
def sample(self, size: int) -> np.ndarray:
"""Returns sample of IDs, uniformly sampled."""
indices = self._random_state.randint(self.size, size=size)
ids = np.fromiter(
(self._ids[idx] for idx in indices), dtype=np.int64, count=len(indices)
)
return ids | Returns sample of IDs, uniformly sampled. | sample | python | google-deepmind/dqn_zoo | dqn_zoo/replay.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py | Apache-2.0 |
def get_state(self) -> Mapping[str, Any]:
"""Retrieves distribution state as a dictionary (e.g. for serialization)."""
return {
'ids': self._ids,
'id_to_index': self._id_to_index,
} | Retrieves distribution state as a dictionary (e.g. for serialization). | get_state | python | google-deepmind/dqn_zoo | dqn_zoo/replay.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py | Apache-2.0 |
def set_state(self, state: Mapping[str, Any]) -> None:
"""Sets distribution state from a (potentially de-serialized) dictionary."""
self._ids = state['ids']
self._id_to_index = state['id_to_index'] | Sets distribution state from a (potentially de-serialized) dictionary. | set_state | python | google-deepmind/dqn_zoo | dqn_zoo/replay.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py | Apache-2.0 |
def sample(self, size: int) -> ReplayStructure:
"""Samples batch of items from replay uniformly, with replacement."""
ids = self._distribution.sample(size)
samples = self.get(ids)
transposed = zip(*samples)
stacked = [np.stack(xs, axis=0) for xs in transposed]
return type(self._structure)(*stack... | Samples batch of items from replay uniformly, with replacement. | sample | python | google-deepmind/dqn_zoo | dqn_zoo/replay.py | https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.