python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Install script for setuptools."""
from importlib import util
from setuptools import find_packages
from setuptools import setup
def get_version():
spec = util.spec_from_file_location('_metadata', 'dm_env/_metadata.py')
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod.__version__
setup(
name='dm-env',
version=get_version(),
description='A Python interface for Reinforcement Learning environments.',
author='DeepMind',
license='Apache License, Version 2.0',
keywords='reinforcement-learning python machine learning',
packages=find_packages(exclude=['examples']),
python_requires='>=3.7',
install_requires=[
'absl-py',
'dm-tree',
'numpy',
],
tests_require=[
'pytest',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| dm_env-master | setup.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Classes that describe numpy arrays."""
import inspect
from typing import Optional
import numpy as np
_INVALID_SHAPE = 'Expected shape %r but found %r'
_INVALID_DTYPE = 'Expected dtype %r but found %r'
_OUT_OF_BOUNDS = 'Values were not all within bounds %s <= %s <= %s'
_VAR_ARGS_NOT_ALLOWED = 'Spec subclasses must not accept *args.'
_VAR_KWARGS_NOT_ALLOWED = 'Spec subclasses must not accept **kwargs.'
_MINIMUM_MUST_BE_LESS_THAN_OR_EQUAL_TO_MAXIMUM = (
'All values in `minimum` must be less than or equal to their corresponding '
'value in `maximum`, got:\nminimum={minimum!r}\nmaximum={maximum!r}.')
_MINIMUM_INCOMPATIBLE_WITH_SHAPE = '`minimum` is incompatible with `shape`'
_MAXIMUM_INCOMPATIBLE_WITH_SHAPE = '`maximum` is incompatible with `shape`'
class Array:
"""Describes a numpy array or scalar shape and dtype.
An `Array` spec allows an API to describe the arrays that it accepts or
returns, before that array exists.
The equivalent version describing a `tf.Tensor` is `TensorSpec`.
"""
__slots__ = ('_shape', '_dtype', '_name')
__hash__ = None
def __init__(self, shape, dtype, name: Optional[str] = None):
"""Initializes a new `Array` spec.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
Raises:
TypeError: If `shape` is not an iterable of elements convertible to int,
or if `dtype` is not convertible to a numpy dtype.
"""
self._shape = tuple(int(dim) for dim in shape)
self._dtype = np.dtype(dtype)
self._name = name
@property
def shape(self):
"""Returns a `tuple` specifying the array shape."""
return self._shape
@property
def dtype(self):
"""Returns a numpy dtype specifying the array dtype."""
return self._dtype
@property
def name(self):
"""Returns the name of the Array."""
return self._name
def __repr__(self):
return 'Array(shape={}, dtype={}, name={})'.format(self.shape,
repr(self.dtype),
repr(self.name))
def __eq__(self, other):
"""Checks if the shape and dtype of two specs are equal."""
if not isinstance(other, Array):
return False
return self.shape == other.shape and self.dtype == other.dtype
def __ne__(self, other):
return not self == other
def _fail_validation(self, message, *args):
message %= args
if self.name:
message += ' for spec %s' % self.name
raise ValueError(message)
def validate(self, value):
"""Checks if value conforms to this spec.
Args:
value: a numpy array or value convertible to one via `np.asarray`.
Returns:
value, converted if necessary to a numpy array.
Raises:
ValueError: if value doesn't conform to this spec.
"""
value = np.asarray(value)
if value.shape != self.shape:
self._fail_validation(_INVALID_SHAPE, self.shape, value.shape)
if value.dtype != self.dtype:
self._fail_validation(_INVALID_DTYPE, self.dtype, value.dtype)
return value
def generate_value(self):
"""Generate a test value which conforms to this spec."""
return np.zeros(shape=self.shape, dtype=self.dtype)
def _get_constructor_kwargs(self):
"""Returns constructor kwargs for instantiating a new copy of this spec."""
# Get the names and kinds of the constructor parameters.
params = inspect.signature(type(self)).parameters
# __init__ must not accept *args or **kwargs, since otherwise we won't be
# able to infer what the corresponding attribute names are.
kinds = {value.kind for value in params.values()}
if inspect.Parameter.VAR_POSITIONAL in kinds:
raise TypeError(_VAR_ARGS_NOT_ALLOWED)
elif inspect.Parameter.VAR_KEYWORD in kinds:
raise TypeError(_VAR_KWARGS_NOT_ALLOWED)
# Note that we assume direct correspondence between the names of constructor
# arguments and attributes.
return {name: getattr(self, name) for name in params.keys()}
def replace(self, **kwargs):
"""Returns a new copy of `self` with specified attributes replaced.
Args:
**kwargs: Optional attributes to replace.
Returns:
A new copy of `self`.
"""
all_kwargs = self._get_constructor_kwargs()
all_kwargs.update(kwargs)
return type(self)(**all_kwargs)
def __reduce__(self):
return Array, (self._shape, self._dtype, self._name)
class BoundedArray(Array):
"""An `Array` spec that specifies minimum and maximum values.
Example usage:
```python
# Specifying the same minimum and maximum for every element.
spec = BoundedArray((3, 4), np.float64, minimum=0.0, maximum=1.0)
# Specifying a different minimum and maximum for each element.
spec = BoundedArray(
(2,), np.float64, minimum=[0.1, 0.2], maximum=[0.9, 0.9])
# Specifying the same minimum and a different maximum for each element.
spec = BoundedArray(
(3,), np.float64, minimum=-10.0, maximum=[4.0, 5.0, 3.0])
```
Bounds are meant to be inclusive. This is especially important for
integer types. The following spec will be satisfied by arrays
with values in the set {0, 1, 2}:
```python
spec = BoundedArray((3, 4), int, minimum=0, maximum=2)
```
Note that one or both bounds may be infinite. For example, the set of
non-negative floats can be expressed as:
```python
spec = BoundedArray((), np.float64, minimum=0.0, maximum=np.inf)
```
In this case `np.inf` would be considered valid, since the upper bound is
inclusive.
"""
__slots__ = ('_minimum', '_maximum')
__hash__ = None
def __init__(self, shape, dtype, minimum, maximum, name=None):
"""Initializes a new `BoundedArray` spec.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
minimum: Number or sequence specifying the minimum element bounds
(inclusive). Must be broadcastable to `shape`.
maximum: Number or sequence specifying the maximum element bounds
(inclusive). Must be broadcastable to `shape`.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
Raises:
ValueError: If `minimum` or `maximum` are not broadcastable to `shape`.
ValueError: If any values in `minimum` are greater than their
corresponding value in `maximum`.
TypeError: If the shape is not an iterable or if the `dtype` is an invalid
numpy dtype.
"""
super(BoundedArray, self).__init__(shape, dtype, name)
try:
bcast_minimum = np.broadcast_to(minimum, shape=shape)
except ValueError as numpy_exception:
raise ValueError(_MINIMUM_INCOMPATIBLE_WITH_SHAPE) from numpy_exception
try:
bcast_maximum = np.broadcast_to(maximum, shape=shape)
except ValueError as numpy_exception:
raise ValueError(_MAXIMUM_INCOMPATIBLE_WITH_SHAPE) from numpy_exception
if np.any(bcast_minimum > bcast_maximum):
raise ValueError(_MINIMUM_MUST_BE_LESS_THAN_OR_EQUAL_TO_MAXIMUM.format(
minimum=minimum, maximum=maximum))
self._minimum = np.array(minimum, dtype=self.dtype)
self._minimum.setflags(write=False)
self._maximum = np.array(maximum, dtype=self.dtype)
self._maximum.setflags(write=False)
@property
def minimum(self):
"""Returns a NumPy array specifying the minimum bounds (inclusive)."""
return self._minimum
@property
def maximum(self):
"""Returns a NumPy array specifying the maximum bounds (inclusive)."""
return self._maximum
def __repr__(self):
template = ('BoundedArray(shape={}, dtype={}, name={}, '
'minimum={}, maximum={})')
return template.format(self.shape, repr(self.dtype), repr(self.name),
self._minimum, self._maximum)
def __eq__(self, other):
if not isinstance(other, BoundedArray):
return False
return (super(BoundedArray, self).__eq__(other) and
(self.minimum == other.minimum).all() and
(self.maximum == other.maximum).all())
def validate(self, value):
value = np.asarray(value)
super(BoundedArray, self).validate(value)
if (value < self.minimum).any() or (value > self.maximum).any():
self._fail_validation(_OUT_OF_BOUNDS, self.minimum, value, self.maximum)
return value
def generate_value(self):
return (np.ones(shape=self.shape, dtype=self.dtype) *
self.dtype.type(self.minimum))
def __reduce__(self):
return BoundedArray, (self._shape, self._dtype, self._minimum,
self._maximum, self._name)
_NUM_VALUES_NOT_POSITIVE = '`num_values` must be a positive integer, got {}.'
_DTYPE_NOT_INTEGRAL = '`dtype` must be integral, got {}.'
_DTYPE_OVERFLOW = (
'`dtype` {} is not big enough to hold `num_values` ({}) without overflow.')
class DiscreteArray(BoundedArray):
"""Represents a discrete, scalar, zero-based space.
This is a special case of the parent `BoundedArray` class. It represents a
0-dimensional numpy array containing a single integer value between
0 and num_values - 1 (inclusive), and exposes a scalar `num_values` property
in addition to the standard `BoundedArray` interface.
For an example use-case, this can be used to define the action space of a
simple RL environment that accepts discrete actions.
"""
_REPR_TEMPLATE = (
'DiscreteArray(shape={self.shape}, dtype={self.dtype}, name={self.name}, '
'minimum={self.minimum}, maximum={self.maximum}, '
'num_values={self.num_values})')
__slots__ = ('_num_values',)
def __init__(self, num_values, dtype=np.int32, name=None):
"""Initializes a new `DiscreteArray` spec.
Args:
num_values: Integer specifying the number of possible values to represent.
dtype: The dtype of the array. Must be an integral type large enough to
hold `num_values` without overflow.
name: Optional string specifying the name of the array.
Raises:
ValueError: If `num_values` is not positive, if `dtype` is not integral,
or if `dtype` is not large enough to hold `num_values` without overflow.
"""
if num_values <= 0 or not np.issubdtype(type(num_values), np.integer):
raise ValueError(_NUM_VALUES_NOT_POSITIVE.format(num_values))
if not np.issubdtype(dtype, np.integer):
raise ValueError(_DTYPE_NOT_INTEGRAL.format(dtype))
num_values = int(num_values)
maximum = num_values - 1
dtype = np.dtype(dtype)
if np.min_scalar_type(maximum) > dtype:
raise ValueError(_DTYPE_OVERFLOW.format(dtype, num_values))
super(DiscreteArray, self).__init__(
shape=(),
dtype=dtype,
minimum=0,
maximum=maximum,
name=name)
self._num_values = num_values
@property
def num_values(self):
"""Returns the number of items."""
return self._num_values
def __repr__(self):
return self._REPR_TEMPLATE.format(self=self) # pytype: disable=duplicate-keyword-argument
def __reduce__(self):
return DiscreteArray, (self._num_values, self._dtype, self._name)
_VALID_STRING_TYPES = (str, bytes)
_INVALID_STRING_TYPE = (
'Expected `string_type` to be one of: {}, got: {{!r}}.'
.format(_VALID_STRING_TYPES))
_INVALID_ELEMENT_TYPE = (
'Expected all elements to be of type: %s. Got value: %r of type: %s.')
class StringArray(Array):
"""Represents an array of variable-length Python strings."""
__slots__ = ('_string_type',)
_REPR_TEMPLATE = (
'{self.__class__.__name__}(shape={self.shape}, '
'string_type={self.string_type}, name={self.name})')
def __init__(self, shape, string_type=str, name=None):
"""Initializes a new `StringArray` spec.
Args:
shape: An iterable specifying the array shape.
string_type: The native Python string type for each element; either
unicode or ASCII. Defaults to unicode.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
"""
if string_type not in _VALID_STRING_TYPES:
raise ValueError(_INVALID_STRING_TYPE.format(string_type))
self._string_type = string_type
super(StringArray, self).__init__(shape=shape, dtype=object, name=name)
@property
def string_type(self):
"""Returns the Python string type for each element."""
return self._string_type
def validate(self, value):
"""Checks if value conforms to this spec.
Args:
value: a numpy array or value convertible to one via `np.asarray`.
Returns:
value, converted if necessary to a numpy array.
Raises:
ValueError: if value doesn't conform to this spec.
"""
value = np.asarray(value, dtype=object)
if value.shape != self.shape:
self._fail_validation(_INVALID_SHAPE, self.shape, value.shape)
for item in value.flat:
if not isinstance(item, self.string_type):
self._fail_validation(
_INVALID_ELEMENT_TYPE, self.string_type, item, type(item))
return value
def generate_value(self):
"""Generate a test value which conforms to this spec."""
empty_string = self.string_type() # pylint: disable=not-callable
return np.full(shape=self.shape, dtype=self.dtype, fill_value=empty_string)
def __repr__(self):
return self._REPR_TEMPLATE.format(self=self) # pytype: disable=duplicate-keyword-argument
def __reduce__(self):
return type(self), (self.shape, self.string_type, self.name)
| dm_env-master | dm_env/specs.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Package metadata for dm_env.
This is kept in a separate module so that it can be imported from setup.py, at
a time when dm_env's dependencies may not have been installed yet.
"""
__version__ = '1.6' # https://www.python.org/dev/peps/pep-0440/
| dm_env-master | dm_env/_metadata.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Reusable fixtures for testing implementations of `dm_env.Environment`.
This generally kicks the tyres on an environment, and checks that it complies
with the interface contract for `dm_env.Environment`.
To test your own environment, all that's required is to inherit from
`EnvironmentTestMixin` and `absltest.TestCase` (in this order), overriding
`make_object_under_test`:
```python
from absl.testing import absltest
from dm_env import test_utils
class MyEnvImplementationTest(test_utils.EnvironmentTestMixin,
absltest.TestCase):
def make_object_under_test(self):
return my_env.MyEnvImplementation()
```
We recommend that you also override `make_action_sequence` in order to generate
a sequence of actions that covers any 'interesting' behaviour in your
environment. For episodic environments in particular, we recommend returning an
action sequence that allows the environment to reach the end of an episode,
otherwise the contract around end-of-episode behaviour will not be checked. The
default implementation of `make_action_sequence` simply generates a dummy action
conforming to the `action_spec` and repeats it 20 times.
You can also add your own tests alongside the defaults if you want to test some
behaviour that's specific to your environment. There are some assertions and
helpers here which may be useful to you in writing these tests.
Note that we disable the pytype: attribute-error static check for the mixin as
absltest.TestCase methods aren't statically available here, only once mixed in.
"""
from absl import logging
import dm_env
import tree
from dm_env import _abstract_test_mixin
_STEP_NEW_ENV_MUST_RETURN_FIRST = (
"calling step() on a fresh environment must produce a step with "
"step_type FIRST, got {}")
_RESET_MUST_RETURN_FIRST = (
"reset() must produce a step with step_type FIRST, got {}.")
_FIRST_MUST_NOT_HAVE_REWARD = "a FIRST step must not have a reward."
_FIRST_MUST_NOT_HAVE_DISCOUNT = "a FIRST step must not have a discount."
_STEP_AFTER_FIRST_MUST_NOT_RETURN_FIRST = (
"calling step() after a FIRST step must not produce another FIRST.")
_FIRST_MUST_COME_AFTER_LAST = (
"step() must produce a FIRST step after a LAST step.")
_FIRST_MUST_ONLY_COME_AFTER_LAST = (
"step() must only produce a FIRST step after a LAST step "
"or on a fresh environment.")
class EnvironmentTestMixin(_abstract_test_mixin.TestMixin):
"""Mixin to help test implementations of `dm_env.Environment`.
Subclasses must override `make_object_under_test` to return an instance of the
`Environment` to be tested.
"""
@property
def environment(self):
"""An alias of `self.object_under_test`, for readability."""
return self.object_under_test
def tearDown(self):
self.environment.close()
# A call to super is required for cooperative multiple inheritance to work.
super().tearDown() # pytype: disable=attribute-error
def make_action_sequence(self):
"""Generates a sequence of actions for a longer test.
Yields:
A sequence of actions compatible with environment's action_spec().
Ideally you should override this to generate an action sequence that will
trigger an end of episode, in order to ensure this behaviour is tested.
Otherwise it will just repeat a test value conforming to the action spec
20 times.
"""
for _ in range(20):
yield self.make_action()
def make_action(self):
"""Returns a single action conforming to the environment's action_spec()."""
spec = self.environment.action_spec()
return tree.map_structure(lambda s: s.generate_value(), spec)
def reset_environment(self):
"""Resets the environment and checks that the returned TimeStep is valid.
Returns:
The TimeStep instance returned by reset().
"""
step = self.environment.reset()
self.assertValidStep(step)
self.assertIs(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_RESET_MUST_RETURN_FIRST.format(step.step_type))
return step
def step_environment(self, action=None):
"""Steps the environment and checks that the returned TimeStep is valid.
Args:
action: Optional action conforming to the environment's action_spec(). If
None then a valid action will be generated.
Returns:
The TimeStep instance returned by step(action).
"""
if action is None:
action = self.make_action()
step = self.environment.step(action)
self.assertValidStep(step)
return step
# Custom assertions
# ----------------------------------------------------------------------------
def assertValidStep(self, step):
"""Checks that a TimeStep conforms to the environment's specs.
Args:
step: An instance of TimeStep.
"""
# pytype: disable=attribute-error
self.assertIsInstance(step, dm_env.TimeStep)
self.assertIsInstance(step.step_type, dm_env.StepType)
if step.step_type is dm_env.StepType.FIRST:
self.assertIsNone(step.reward, _FIRST_MUST_NOT_HAVE_REWARD)
self.assertIsNone(step.discount, _FIRST_MUST_NOT_HAVE_DISCOUNT)
else:
self.assertValidReward(step.reward)
self.assertValidDiscount(step.discount)
self.assertValidObservation(step.observation)
# pytype: enable=attribute-error
def assertConformsToSpec(self, value, spec):
"""Checks that `value` conforms to `spec`.
Args:
value: A potentially nested structure of numpy arrays or scalars.
spec: A potentially nested structure of `specs.Array` instances.
"""
try:
tree.assert_same_structure(value, spec)
except (TypeError, ValueError) as e:
self.fail("`spec` and `value` have mismatching structures: {}".format(e)) # pytype: disable=attribute-error
def validate(path, item, array_spec):
try:
return array_spec.validate(item)
except ValueError as e:
raise ValueError("Value at path {!r} failed validation: {}."
.format("/".join(map(str, path)), e))
tree.map_structure_with_path(validate, value, spec)
def assertValidObservation(self, observation):
"""Checks that `observation` conforms to the `observation_spec()`."""
self.assertConformsToSpec(observation, self.environment.observation_spec())
def assertValidReward(self, reward):
"""Checks that `reward` conforms to the `reward_spec()`."""
self.assertConformsToSpec(reward, self.environment.reward_spec())
def assertValidDiscount(self, discount):
"""Checks that `discount` conforms to the `discount_spec()`."""
self.assertConformsToSpec(discount, self.environment.discount_spec())
# Test cases
# ----------------------------------------------------------------------------
def test_reset(self):
# Won't hurt to check this works twice in a row:
for _ in range(2):
self.reset_environment()
def test_step_on_fresh_environment(self):
# Calling `step()` on a fresh environment should be equivalent to `reset()`.
# Note that the action should be ignored.
step = self.step_environment()
self.assertIs(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_STEP_NEW_ENV_MUST_RETURN_FIRST.format(step.step_type))
step = self.step_environment()
self.assertIsNot(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_STEP_AFTER_FIRST_MUST_NOT_RETURN_FIRST)
def test_step_after_reset(self):
for _ in range(2):
self.reset_environment()
step = self.step_environment()
self.assertIsNot(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_STEP_AFTER_FIRST_MUST_NOT_RETURN_FIRST)
def test_longer_action_sequence(self):
"""Steps the environment using actions generated by `make_action_sequence`.
The sequence of TimeSteps returned are checked for validity.
"""
encountered_last_step = False
for _ in range(2):
step = self.reset_environment()
prev_step_type = step.step_type
for action in self.make_action_sequence():
step = self.step_environment(action)
if prev_step_type is dm_env.StepType.LAST:
self.assertIs(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_FIRST_MUST_COME_AFTER_LAST)
else:
self.assertIsNot(dm_env.StepType.FIRST, step.step_type, # pytype: disable=attribute-error
_FIRST_MUST_ONLY_COME_AFTER_LAST)
if step.last():
encountered_last_step = True
prev_step_type = step.step_type
if not encountered_last_step:
logging.info(
"Could not test the contract around end-of-episode behaviour. "
"Consider implementing `make_action_sequence` so that an end of "
"episode is reached.")
else:
logging.info("Successfully checked end of episode.")
| dm_env-master | dm_env/test_utils.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Base class for TestMixin classes."""
class TestMixin:
"""Base class for TestMixins.
Subclasses must override `make_object_under_test`.
"""
def setUp(self):
# A call to super is required for cooperative multiple inheritance to work.
super().setUp()
test_method = getattr(self, self._testMethodName)
make_obj_kwargs = getattr(test_method, "_make_obj_kwargs", {})
self.object_under_test = self.make_object_under_test(**make_obj_kwargs)
def make_object_under_test(self, **unused_kwargs):
raise NotImplementedError(
"Attempt to run tests from an abstract TestMixin subclass %s. "
"Perhaps you forgot to override make_object_under_test?" % type(self))
| dm_env-master | dm_env/_abstract_test_mixin.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_env.specs."""
import pickle
from absl.testing import absltest
from absl.testing import parameterized
from dm_env import specs
import numpy as np
class ArrayTest(parameterized.TestCase):
def testShapeTypeError(self):
with self.assertRaises(TypeError):
specs.Array(32, np.int32)
def testShapeElementTypeError(self):
with self.assertRaises(TypeError):
specs.Array([None], np.int32)
def testDtypeTypeError(self):
with self.assertRaises(TypeError):
specs.Array((1, 2, 3), "32")
def testScalarShape(self):
specs.Array((), np.int32)
def testStringDtype(self):
specs.Array((1, 2, 3), "int32")
def testNumpyDtype(self):
specs.Array((1, 2, 3), np.int32)
def testDtype(self):
spec = specs.Array((1, 2, 3), np.int32)
self.assertEqual(np.int32, spec.dtype)
def testShape(self):
spec = specs.Array([1, 2, 3], np.int32)
self.assertEqual((1, 2, 3), spec.shape)
def testEqual(self):
spec_1 = specs.Array((1, 2, 3), np.int32)
spec_2 = specs.Array((1, 2, 3), np.int32)
self.assertEqual(spec_1, spec_2)
def testNotEqualDifferentShape(self):
spec_1 = specs.Array((1, 2, 3), np.int32)
spec_2 = specs.Array((1, 3, 3), np.int32)
self.assertNotEqual(spec_1, spec_2)
def testNotEqualDifferentDtype(self):
spec_1 = specs.Array((1, 2, 3), np.int64)
spec_2 = specs.Array((1, 2, 3), np.int32)
self.assertNotEqual(spec_1, spec_2)
def testNotEqualOtherClass(self):
spec_1 = specs.Array((1, 2, 3), np.int32)
spec_2 = None
self.assertNotEqual(spec_1, spec_2)
self.assertNotEqual(spec_2, spec_1)
spec_2 = ()
self.assertNotEqual(spec_1, spec_2)
self.assertNotEqual(spec_2, spec_1)
def testIsUnhashable(self):
spec = specs.Array(shape=(1, 2, 3), dtype=np.int32)
with self.assertRaisesRegex(TypeError, "unhashable type"):
hash(spec)
@parameterized.parameters(
dict(value=np.zeros((1, 2), dtype=np.int32), is_valid=True),
dict(value=np.zeros((1, 2), dtype=np.float32), is_valid=False),
)
def testValidateDtype(self, value, is_valid):
spec = specs.Array((1, 2), np.int32)
if is_valid: # Should not raise any exception.
spec.validate(value)
else:
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._INVALID_DTYPE % (spec.dtype, value.dtype)):
spec.validate(value)
@parameterized.parameters(
dict(value=np.zeros((1, 2), dtype=np.int32), is_valid=True),
dict(value=np.zeros((1, 2, 3), dtype=np.int32), is_valid=False),
)
def testValidateShape(self, value, is_valid):
spec = specs.Array((1, 2), np.int32)
if is_valid: # Should not raise any exception.
spec.validate(value)
else:
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._INVALID_SHAPE % (spec.shape, value.shape)):
spec.validate(value)
def testGenerateValue(self):
spec = specs.Array((1, 2), np.int32)
test_value = spec.generate_value()
spec.validate(test_value)
def testSerialization(self):
desc = specs.Array([1, 5], np.float32, "test")
self.assertEqual(pickle.loads(pickle.dumps(desc)), desc)
@parameterized.parameters(
{"arg_name": "shape", "new_value": (2, 3)},
{"arg_name": "dtype", "new_value": np.int32},
{"arg_name": "name", "new_value": "something_else"})
def testReplace(self, arg_name, new_value):
old_spec = specs.Array([1, 5], np.float32, "test")
new_spec = old_spec.replace(**{arg_name: new_value})
self.assertIsNot(old_spec, new_spec)
self.assertEqual(getattr(new_spec, arg_name), new_value)
for attr_name in set(["shape", "dtype", "name"]).difference([arg_name]):
self.assertEqual(getattr(new_spec, attr_name),
getattr(old_spec, attr_name))
def testReplaceRaisesTypeErrorIfSubclassAcceptsVarArgs(self):
class InvalidSpecSubclass(specs.Array):
def __init__(self, *args): # pylint: disable=useless-super-delegation
super(InvalidSpecSubclass, self).__init__(*args)
spec = InvalidSpecSubclass([1, 5], np.float32, "test")
with self.assertRaisesWithLiteralMatch(
TypeError, specs._VAR_ARGS_NOT_ALLOWED):
spec.replace(name="something_else")
def testReplaceRaisesTypeErrorIfSubclassAcceptsVarKwargs(self):
class InvalidSpecSubclass(specs.Array):
def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
super(InvalidSpecSubclass, self).__init__(**kwargs)
spec = InvalidSpecSubclass(shape=[1, 5], dtype=np.float32, name="test")
with self.assertRaisesWithLiteralMatch(
TypeError, specs._VAR_KWARGS_NOT_ALLOWED):
spec.replace(name="something_else")
class BoundedArrayTest(parameterized.TestCase):
def testInvalidMinimum(self):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._MINIMUM_INCOMPATIBLE_WITH_SHAPE):
specs.BoundedArray((3, 5), np.uint8, (0, 0, 0), (1, 1))
def testInvalidMaximum(self):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._MAXIMUM_INCOMPATIBLE_WITH_SHAPE):
specs.BoundedArray((3, 5), np.uint8, 0, (1, 1, 1))
def testMinMaxAttributes(self):
spec = specs.BoundedArray((1, 2, 3), np.float32, 0, (5, 5, 5))
self.assertEqual(type(spec.minimum), np.ndarray)
self.assertEqual(type(spec.maximum), np.ndarray)
@parameterized.parameters(
dict(spec_dtype=np.float32, min_dtype=np.float64, max_dtype=np.int32),
dict(spec_dtype=np.uint64, min_dtype=np.uint8, max_dtype=float))
def testMinMaxCasting(self, spec_dtype, min_dtype, max_dtype):
minimum = np.array(0., dtype=min_dtype)
maximum = np.array((3.14, 15.9, 265.4), dtype=max_dtype)
spec = specs.BoundedArray(
shape=(1, 2, 3), dtype=spec_dtype, minimum=minimum, maximum=maximum)
self.assertEqual(spec.minimum.dtype, spec_dtype)
self.assertEqual(spec.maximum.dtype, spec_dtype)
def testReadOnly(self):
spec = specs.BoundedArray((1, 2, 3), np.float32, 0, (5, 5, 5))
with self.assertRaisesRegex(ValueError, "read-only"):
spec.minimum[0] = -1
with self.assertRaisesRegex(ValueError, "read-only"):
spec.maximum[0] = 100
def testEqualBroadcastingBounds(self):
spec_1 = specs.BoundedArray(
(1, 2), np.float32, minimum=0.0, maximum=1.0)
spec_2 = specs.BoundedArray(
(1, 2), np.float32, minimum=[0.0, 0.0], maximum=[1.0, 1.0])
self.assertEqual(spec_1, spec_2)
def testNotEqualDifferentMinimum(self):
spec_1 = specs.BoundedArray(
(1, 2), np.float32, minimum=[0.0, -0.6], maximum=[1.0, 1.0])
spec_2 = specs.BoundedArray(
(1, 2), np.float32, minimum=[0.0, 0.0], maximum=[1.0, 1.0])
self.assertNotEqual(spec_1, spec_2)
def testNotEqualOtherClass(self):
spec_1 = specs.BoundedArray(
(1, 2), np.float32, minimum=[0.0, -0.6], maximum=[1.0, 1.0])
spec_2 = specs.Array((1, 2), np.float32)
self.assertNotEqual(spec_1, spec_2)
self.assertNotEqual(spec_2, spec_1)
spec_2 = None
self.assertNotEqual(spec_1, spec_2)
self.assertNotEqual(spec_2, spec_1)
spec_2 = ()
self.assertNotEqual(spec_1, spec_2)
self.assertNotEqual(spec_2, spec_1)
def testNotEqualDifferentMaximum(self):
spec_1 = specs.BoundedArray(
(1, 2), np.int32, minimum=0.0, maximum=2.0)
spec_2 = specs.BoundedArray(
(1, 2), np.int32, minimum=[0.0, 0.0], maximum=[1.0, 1.0])
self.assertNotEqual(spec_1, spec_2)
def testIsUnhashable(self):
spec = specs.BoundedArray(
shape=(1, 2), dtype=np.int32, minimum=0.0, maximum=2.0)
with self.assertRaisesRegex(TypeError, "unhashable type"):
hash(spec)
def testRepr(self):
as_string = repr(specs.BoundedArray(
(1, 2), np.int32, minimum=73.0, maximum=101.0))
self.assertIn("73", as_string)
self.assertIn("101", as_string)
@parameterized.parameters(
dict(value=np.array([[5, 6], [8, 10]], dtype=np.int32), is_valid=True),
dict(value=np.array([[5, 6], [8, 11]], dtype=np.int32), is_valid=False),
dict(value=np.array([[4, 6], [8, 10]], dtype=np.int32), is_valid=False),
)
def testValidateBounds(self, value, is_valid):
spec = specs.BoundedArray((2, 2), np.int32, minimum=5, maximum=10)
if is_valid: # Should not raise any exception.
spec.validate(value)
else:
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._OUT_OF_BOUNDS % (spec.minimum, value, spec.maximum)):
spec.validate(value)
@parameterized.parameters(
# Semi-infinite intervals.
dict(minimum=0., maximum=np.inf, value=0., is_valid=True),
dict(minimum=0., maximum=np.inf, value=1., is_valid=True),
dict(minimum=0., maximum=np.inf, value=np.inf, is_valid=True),
dict(minimum=0., maximum=np.inf, value=-1., is_valid=False),
dict(minimum=0., maximum=np.inf, value=-np.inf, is_valid=False),
dict(minimum=-np.inf, maximum=0., value=0., is_valid=True),
dict(minimum=-np.inf, maximum=0., value=-1., is_valid=True),
dict(minimum=-np.inf, maximum=0., value=-np.inf, is_valid=True),
dict(minimum=-np.inf, maximum=0., value=1., is_valid=False),
# Infinite interval.
dict(minimum=-np.inf, maximum=np.inf, value=1., is_valid=True),
dict(minimum=-np.inf, maximum=np.inf, value=-1., is_valid=True),
dict(minimum=-np.inf, maximum=np.inf, value=-np.inf, is_valid=True),
dict(minimum=-np.inf, maximum=np.inf, value=np.inf, is_valid=True),
# Special case where minimum == maximum.
dict(minimum=0., maximum=0., value=0., is_valid=True),
dict(minimum=0., maximum=0., value=np.finfo(float).eps, is_valid=False),
)
def testValidateBoundsFloat(self, minimum, maximum, value, is_valid):
spec = specs.BoundedArray((), float, minimum=minimum, maximum=maximum)
if is_valid: # Should not raise any exception.
spec.validate(value)
else:
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._OUT_OF_BOUNDS % (spec.minimum, value, spec.maximum)):
spec.validate(value)
def testValidateReturnsValue(self):
spec = specs.BoundedArray([1], np.int32, minimum=0, maximum=1)
validated_value = spec.validate(np.array([0], dtype=np.int32))
self.assertIsNotNone(validated_value)
def testGenerateValue(self):
spec = specs.BoundedArray((2, 2), np.int32, minimum=5, maximum=10)
test_value = spec.generate_value()
spec.validate(test_value)
def testScalarBounds(self):
spec = specs.BoundedArray((), float, minimum=0.0, maximum=1.0)
self.assertIsInstance(spec.minimum, np.ndarray)
self.assertIsInstance(spec.maximum, np.ndarray)
# Sanity check that numpy compares correctly to a scalar for an empty shape.
self.assertEqual(0.0, spec.minimum)
self.assertEqual(1.0, spec.maximum)
# Check that the spec doesn't fail its own input validation.
_ = specs.BoundedArray(
spec.shape, spec.dtype, spec.minimum, spec.maximum)
def testSerialization(self):
desc = specs.BoundedArray([1, 5], np.float32, -1, 1, "test")
self.assertEqual(pickle.loads(pickle.dumps(desc)), desc)
@parameterized.parameters(
{"arg_name": "shape", "new_value": (2, 3)},
{"arg_name": "dtype", "new_value": np.int32},
{"arg_name": "name", "new_value": "something_else"},
{"arg_name": "minimum", "new_value": -2},
{"arg_name": "maximum", "new_value": 2},
)
def testReplace(self, arg_name, new_value):
old_spec = specs.BoundedArray([1, 5], np.float32, -1, 1, "test")
new_spec = old_spec.replace(**{arg_name: new_value})
self.assertIsNot(old_spec, new_spec)
self.assertEqual(getattr(new_spec, arg_name), new_value)
for attr_name in set(["shape", "dtype", "name", "minimum", "maximum"]
).difference([arg_name]):
self.assertEqual(getattr(new_spec, attr_name),
getattr(old_spec, attr_name))
@parameterized.parameters([
dict(minimum=1., maximum=0.),
dict(minimum=[0., 1.], maximum=0.),
dict(minimum=1., maximum=[0., 0.]),
dict(minimum=[0., 1.], maximum=[0., 0.]),
])
def testErrorIfMinimumGreaterThanMaximum(self, minimum, maximum):
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._MINIMUM_MUST_BE_LESS_THAN_OR_EQUAL_TO_MAXIMUM.format(
minimum=minimum, maximum=maximum)):
specs.BoundedArray((2,), np.float32, minimum, maximum, "test")
class DiscreteArrayTest(parameterized.TestCase):
@parameterized.parameters(0, -3)
def testInvalidNumActions(self, num_values):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._NUM_VALUES_NOT_POSITIVE.format(num_values)):
specs.DiscreteArray(num_values=num_values)
@parameterized.parameters(np.float32, object)
def testDtypeNotIntegral(self, dtype):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._DTYPE_NOT_INTEGRAL.format(dtype)):
specs.DiscreteArray(num_values=5, dtype=dtype)
@parameterized.parameters(
dict(dtype=np.uint8, num_values=2 ** 8 + 1),
dict(dtype=np.uint64, num_values=2 ** 64 + 1))
def testDtypeOverflow(self, num_values, dtype):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._DTYPE_OVERFLOW.format(np.dtype(dtype), num_values)):
specs.DiscreteArray(num_values=num_values, dtype=dtype)
def testRepr(self):
as_string = repr(specs.DiscreteArray(num_values=5))
self.assertIn("num_values=5", as_string)
def testProperties(self):
num_values = 5
spec = specs.DiscreteArray(num_values=5)
self.assertEqual(spec.minimum, 0)
self.assertEqual(spec.maximum, num_values - 1)
self.assertEqual(spec.dtype, np.int32)
self.assertEqual(spec.num_values, num_values)
def testSerialization(self):
desc = specs.DiscreteArray(2, np.int32, "test")
self.assertEqual(pickle.loads(pickle.dumps(desc)), desc)
@parameterized.parameters(
{"arg_name": "num_values", "new_value": 4},
{"arg_name": "dtype", "new_value": np.int64},
{"arg_name": "name", "new_value": "something_else"})
def testReplace(self, arg_name, new_value):
old_spec = specs.DiscreteArray(2, np.int32, "test")
new_spec = old_spec.replace(**{arg_name: new_value})
self.assertIsNot(old_spec, new_spec)
self.assertEqual(getattr(new_spec, arg_name), new_value)
for attr_name in set(
["num_values", "dtype", "name"]).difference([arg_name]):
self.assertEqual(getattr(new_spec, attr_name),
getattr(old_spec, attr_name))
class StringArrayTest(parameterized.TestCase):
@parameterized.parameters(int, bool)
def testInvalidStringType(self, string_type):
with self.assertRaisesWithLiteralMatch(
ValueError, specs._INVALID_STRING_TYPE.format(string_type)):
specs.StringArray(shape=(), string_type=string_type)
@parameterized.parameters(
dict(value=[u"foo", u"bar"], spec_string_type=str),
dict(value=(u"foo", u"bar"), spec_string_type=str),
dict(value=np.array([u"foo", u"bar"]), spec_string_type=str),
dict(value=[b"foo", b"bar"], spec_string_type=bytes),
dict(value=(b"foo", b"bar"), spec_string_type=bytes),
dict(value=np.array([b"foo", b"bar"]), spec_string_type=bytes),
)
def testValidateCorrectInput(self, value, spec_string_type):
spec = specs.StringArray(shape=(2,), string_type=spec_string_type)
validated = spec.validate(value)
self.assertIsInstance(validated, np.ndarray)
@parameterized.parameters(
dict(value=np.array(u"foo"), spec_shape=(1,)),
dict(value=np.array([u"foo"]), spec_shape=()),
dict(value=np.array([u"foo", u"bar", u"baz"]), spec_shape=(2,)),
)
def testInvalidShape(self, value, spec_shape):
spec = specs.StringArray(shape=spec_shape, string_type=str)
with self.assertRaisesWithLiteralMatch(
ValueError,
specs._INVALID_SHAPE % (spec_shape, value.shape)):
spec.validate(value)
@parameterized.parameters(
dict(bad_element=42, spec_string_type=str),
dict(bad_element=False, spec_string_type=str),
dict(bad_element=[u"foo"], spec_string_type=str),
dict(bad_element=b"foo", spec_string_type=str),
dict(bad_element=u"foo", spec_string_type=bytes),
)
def testInvalidItemType(self, bad_element, spec_string_type):
spec = specs.StringArray(shape=(3,), string_type=spec_string_type)
good_element = spec_string_type()
value = [good_element, bad_element, good_element]
message = specs._INVALID_ELEMENT_TYPE % (
spec_string_type, bad_element, type(bad_element))
with self.assertRaisesWithLiteralMatch(ValueError, message):
spec.validate(value)
@parameterized.parameters(
dict(
shape=(),
string_type=str,
expected=np.array(u"", dtype=object)),
dict(
shape=(1, 2),
string_type=bytes,
expected=np.array([[b"", b""]], dtype=object)),
)
def testGenerateValue(self, shape, string_type, expected):
spec = specs.StringArray(shape=shape, string_type=string_type)
value = spec.generate_value()
spec.validate(value) # Should be valid.
np.testing.assert_array_equal(expected, value)
@parameterized.parameters(
dict(shape=(), string_type=str, name=None),
dict(shape=(2, 3), string_type=bytes, name="foobar"),
)
def testRepr(self, shape, string_type, name):
spec = specs.StringArray(shape=shape, string_type=string_type, name=name)
spec_repr = repr(spec)
self.assertIn("StringArray", spec_repr)
self.assertIn("shape={}".format(shape), spec_repr)
self.assertIn("string_type={}".format(string_type), spec_repr)
self.assertIn("name={}".format(name), spec_repr)
@parameterized.parameters(
dict(shape=(), string_type=str, name=None),
dict(shape=(2, 3), string_type=bytes, name="foobar"),
)
def testSerialization(self, shape, string_type, name):
spec = specs.StringArray(shape=shape, string_type=string_type, name=name)
self.assertEqual(pickle.loads(pickle.dumps(spec)), spec)
if __name__ == "__main__":
absltest.main()
| dm_env-master | dm_env/specs_test.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A Python interface for reinforcement learning environments."""
from dm_env import _environment
from dm_env._metadata import __version__
Environment = _environment.Environment
StepType = _environment.StepType
TimeStep = _environment.TimeStep
# Helper functions for creating TimeStep namedtuples with default settings.
restart = _environment.restart
termination = _environment.termination
transition = _environment.transition
truncation = _environment.truncation
| dm_env-master | dm_env/__init__.py |
# pylint: disable=g-bad-file-header
# Copyright 2021 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Auto-resetting dm_env.Environment helper class.
The dm_env API states that stepping an environment after a LAST timestep should
return the FIRST timestep of a new episode. Environment authors sometimes miss
this part or find it awkward to implement. This module contains a class that
helps implement the reset behaviour.
"""
import abc
from dm_env import _environment
class AutoResetEnvironment(_environment.Environment):
"""Auto-resetting environment base class.
This class implements the required `step()` and `reset()` methods and
instead requires users to implement `_step()` and `_reset()`. This class
handles the reset behaviour automatically when it detects a LAST timestep.
"""
def __init__(self):
self._reset_next_step = True
@abc.abstractmethod
def _reset(self) -> _environment.TimeStep:
"""Returns a `timestep` namedtuple as per the regular `reset()` method."""
@abc.abstractmethod
def _step(self, action) -> _environment.TimeStep:
"""Returns a `timestep` namedtuple as per the regular `step()` method."""
def reset(self) -> _environment.TimeStep:
self._reset_next_step = False
return self._reset()
def step(self, action) -> _environment.TimeStep:
if self._reset_next_step:
return self.reset()
timestep = self._step(action)
self._reset_next_step = timestep.last()
return timestep
| dm_env-master | dm_env/auto_reset_environment.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Python RL Environment API."""
import abc
import enum
from typing import Any, NamedTuple
from dm_env import specs
class TimeStep(NamedTuple):
"""Returned with every call to `step` and `reset` on an environment.
A `TimeStep` contains the data emitted by an environment at each step of
interaction. A `TimeStep` holds a `step_type`, an `observation` (typically a
NumPy array or a dict or list of arrays), and an associated `reward` and
`discount`.
The first `TimeStep` in a sequence will have `StepType.FIRST`. The final
`TimeStep` will have `StepType.LAST`. All other `TimeStep`s in a sequence will
have `StepType.MID.
Attributes:
step_type: A `StepType` enum value.
reward: A scalar, NumPy array, nested dict, list or tuple of rewards; or
`None` if `step_type` is `StepType.FIRST`, i.e. at the start of a
sequence.
discount: A scalar, NumPy array, nested dict, list or tuple of discount
values in the range `[0, 1]`, or `None` if `step_type` is
`StepType.FIRST`, i.e. at the start of a sequence.
observation: A NumPy array, or a nested dict, list or tuple of arrays.
Scalar values that can be cast to NumPy arrays (e.g. Python floats) are
also valid in place of a scalar array.
"""
# TODO(b/143116886): Use generics here when PyType supports them.
step_type: Any
reward: Any
discount: Any
observation: Any
def first(self) -> bool:
return self.step_type == StepType.FIRST
def mid(self) -> bool:
return self.step_type == StepType.MID
def last(self) -> bool:
return self.step_type == StepType.LAST
class StepType(enum.IntEnum):
"""Defines the status of a `TimeStep` within a sequence."""
# Denotes the first `TimeStep` in a sequence.
FIRST = 0
# Denotes any `TimeStep` in a sequence that is not FIRST or LAST.
MID = 1
# Denotes the last `TimeStep` in a sequence.
LAST = 2
def first(self) -> bool:
return self is StepType.FIRST
def mid(self) -> bool:
return self is StepType.MID
def last(self) -> bool:
return self is StepType.LAST
class Environment(metaclass=abc.ABCMeta):
"""Abstract base class for Python RL environments.
Observations and valid actions are described with `Array` specs, defined in
the `specs` module.
"""
@abc.abstractmethod
def reset(self) -> TimeStep:
"""Starts a new sequence and returns the first `TimeStep` of this sequence.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` of `FIRST`.
reward: `None`, indicating the reward is undefined.
discount: `None`, indicating the discount is undefined.
observation: A NumPy array, or a nested dict, list or tuple of arrays.
Scalar values that can be cast to NumPy arrays (e.g. Python floats)
are also valid in place of a scalar array. Must conform to the
specification returned by `observation_spec()`.
"""
@abc.abstractmethod
def step(self, action) -> TimeStep:
"""Updates the environment according to the action and returns a `TimeStep`.
If the environment returned a `TimeStep` with `StepType.LAST` at the
previous step, this call to `step` will start a new sequence and `action`
will be ignored.
This method will also start a new sequence if called after the environment
has been constructed and `reset` has not been called. Again, in this case
`action` will be ignored.
Args:
action: A NumPy array, or a nested dict, list or tuple of arrays
corresponding to `action_spec()`.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` value.
reward: Reward at this timestep, or None if step_type is
`StepType.FIRST`. Must conform to the specification returned by
`reward_spec()`.
discount: A discount in the range [0, 1], or None if step_type is
`StepType.FIRST`. Must conform to the specification returned by
`discount_spec()`.
observation: A NumPy array, or a nested dict, list or tuple of arrays.
Scalar values that can be cast to NumPy arrays (e.g. Python floats)
are also valid in place of a scalar array. Must conform to the
specification returned by `observation_spec()`.
"""
def reward_spec(self):
"""Describes the reward returned by the environment.
By default this is assumed to be a single float.
Returns:
An `Array` spec, or a nested dict, list or tuple of `Array` specs.
"""
return specs.Array(shape=(), dtype=float, name='reward')
def discount_spec(self):
"""Describes the discount returned by the environment.
By default this is assumed to be a single float between 0 and 1.
Returns:
An `Array` spec, or a nested dict, list or tuple of `Array` specs.
"""
return specs.BoundedArray(
shape=(), dtype=float, minimum=0., maximum=1., name='discount')
@abc.abstractmethod
def observation_spec(self):
"""Defines the observations provided by the environment.
May use a subclass of `specs.Array` that specifies additional properties
such as min and max bounds on the values.
Returns:
An `Array` spec, or a nested dict, list or tuple of `Array` specs.
"""
@abc.abstractmethod
def action_spec(self):
"""Defines the actions that should be provided to `step`.
May use a subclass of `specs.Array` that specifies additional properties
such as min and max bounds on the values.
Returns:
An `Array` spec, or a nested dict, list or tuple of `Array` specs.
"""
def close(self):
"""Frees any resources used by the environment.
Implement this method for an environment backed by an external process.
This method can be used directly
```python
env = Env(...)
# Use env.
env.close()
```
or via a context manager
```python
with Env(...) as env:
# Use env.
```
"""
pass
def __enter__(self):
"""Allows the environment to be used in a with-statement context."""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Allows the environment to be used in a with-statement context."""
del exc_type, exc_value, traceback # Unused.
self.close()
# Helper functions for creating TimeStep namedtuples with default settings.
def restart(observation):
"""Returns a `TimeStep` with `step_type` set to `StepType.FIRST`."""
return TimeStep(StepType.FIRST, None, None, observation)
def transition(reward, observation, discount=1.0):
"""Returns a `TimeStep` with `step_type` set to `StepType.MID`."""
return TimeStep(StepType.MID, reward, discount, observation)
def termination(reward, observation):
"""Returns a `TimeStep` with `step_type` set to `StepType.LAST`."""
return TimeStep(StepType.LAST, reward, 0.0, observation)
def truncation(reward, observation, discount=1.0):
"""Returns a `TimeStep` with `step_type` set to `StepType.LAST`."""
return TimeStep(StepType.LAST, reward, discount, observation)
| dm_env-master | dm_env/_environment.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_env._environment."""
from absl.testing import absltest
from absl.testing import parameterized
import dm_env
class TimeStepHelpersTest(parameterized.TestCase):
@parameterized.parameters(dict(observation=-1), dict(observation=[2., 3.]))
def test_restart(self, observation):
time_step = dm_env.restart(observation)
self.assertIs(dm_env.StepType.FIRST, time_step.step_type)
self.assertEqual(observation, time_step.observation)
self.assertIsNone(time_step.reward)
self.assertIsNone(time_step.discount)
@parameterized.parameters(
dict(observation=-1., reward=2.0, discount=1.0),
dict(observation=(2., 3.), reward=0., discount=0.))
def test_transition(self, observation, reward, discount):
time_step = dm_env.transition(
reward=reward, observation=observation, discount=discount)
self.assertIs(dm_env.StepType.MID, time_step.step_type)
self.assertEqual(observation, time_step.observation)
self.assertEqual(reward, time_step.reward)
self.assertEqual(discount, time_step.discount)
@parameterized.parameters(
dict(observation=-1., reward=2.0),
dict(observation=(2., 3.), reward=0.))
def test_termination(self, observation, reward):
time_step = dm_env.termination(reward=reward, observation=observation)
self.assertIs(dm_env.StepType.LAST, time_step.step_type)
self.assertEqual(observation, time_step.observation)
self.assertEqual(reward, time_step.reward)
self.assertEqual(0.0, time_step.discount)
@parameterized.parameters(
dict(observation=-1., reward=2.0, discount=1.0),
dict(observation=(2., 3.), reward=0., discount=0.))
def test_truncation(self, reward, observation, discount):
time_step = dm_env.truncation(reward, observation, discount)
self.assertIs(dm_env.StepType.LAST, time_step.step_type)
self.assertEqual(observation, time_step.observation)
self.assertEqual(reward, time_step.reward)
self.assertEqual(discount, time_step.discount)
@parameterized.parameters(
dict(step_type=dm_env.StepType.FIRST,
is_first=True, is_mid=False, is_last=False),
dict(step_type=dm_env.StepType.MID,
is_first=False, is_mid=True, is_last=False),
dict(step_type=dm_env.StepType.LAST,
is_first=False, is_mid=False, is_last=True),
)
def test_step_type_helpers(self, step_type, is_first, is_mid, is_last):
time_step = dm_env.TimeStep(
reward=None, discount=None, observation=None, step_type=step_type)
with self.subTest('TimeStep methods'):
self.assertEqual(is_first, time_step.first())
self.assertEqual(is_mid, time_step.mid())
self.assertEqual(is_last, time_step.last())
with self.subTest('StepType methods'):
self.assertEqual(is_first, time_step.step_type.first())
self.assertEqual(is_mid, time_step.step_type.mid())
self.assertEqual(is_last, time_step.step_type.last())
if __name__ == '__main__':
absltest.main()
| dm_env-master | dm_env/_environment_test.py |
# pylint: disable=g-bad-file-header
# Copyright 2021 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for auto_reset_environment."""
from absl.testing import absltest
from dm_env import _environment
from dm_env import auto_reset_environment
from dm_env import specs
from dm_env import test_utils
import numpy as np
class FakeEnvironment(auto_reset_environment.AutoResetEnvironment):
"""Environment that resets after a given number of steps."""
def __init__(self, step_limit):
super(FakeEnvironment, self).__init__()
self._step_limit = step_limit
self._steps_taken = 0
def _reset(self):
self._steps_taken = 0
return _environment.restart(observation=np.zeros(3))
def _step(self, action):
self._steps_taken += 1
if self._steps_taken < self._step_limit:
return _environment.transition(reward=0.0, observation=np.zeros(3))
else:
return _environment.termination(reward=0.0, observation=np.zeros(3))
def action_spec(self):
return specs.Array(shape=(), dtype='int')
def observation_spec(self):
return specs.Array(shape=(3,), dtype='float')
class AutoResetEnvironmentTest(test_utils.EnvironmentTestMixin,
absltest.TestCase):
def make_object_under_test(self):
return FakeEnvironment(step_limit=5)
def make_action_sequence(self):
for _ in range(20):
yield np.array(0)
if __name__ == '__main__':
absltest.main()
| dm_env-master | dm_env/auto_reset_environment_test.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_env.test_utils."""
import itertools
from absl.testing import absltest
import dm_env
from dm_env import specs
from dm_env import test_utils
import numpy as np
REWARD_SPEC = specs.Array(shape=(), dtype=float)
DISCOUNT_SPEC = specs.BoundedArray(shape=(), dtype=float, minimum=0, maximum=1)
OBSERVATION_SPEC = specs.Array(shape=(2, 3), dtype=float)
ACTION_SPEC = specs.BoundedArray(shape=(), dtype=int, minimum=0, maximum=2)
REWARD = REWARD_SPEC.generate_value()
DISCOUNT = DISCOUNT_SPEC.generate_value()
OBSERVATION = OBSERVATION_SPEC.generate_value()
FIRST = dm_env.restart(observation=OBSERVATION)
MID = dm_env.transition(
reward=REWARD, observation=OBSERVATION, discount=DISCOUNT)
LAST = dm_env.truncation(
reward=REWARD, observation=OBSERVATION, discount=DISCOUNT)
class MockEnvironment(dm_env.Environment):
def __init__(self, timesteps):
self._timesteps = timesteps
self._iter_timesteps = itertools.cycle(self._timesteps)
def reset(self):
self._iter_timesteps = itertools.cycle(self._timesteps)
return next(self._iter_timesteps)
def step(self, action):
return next(self._iter_timesteps)
def reward_spec(self):
return REWARD_SPEC
def discount_spec(self):
return DISCOUNT_SPEC
def action_spec(self):
return ACTION_SPEC
def observation_spec(self):
return OBSERVATION_SPEC
def _make_test_case_with_expected_failures(
name,
timestep_sequence,
expected_failures):
class NewTestCase(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return MockEnvironment(timestep_sequence)
for method_name, exception_type in expected_failures:
def wrapped_method(
self, method_name=method_name, exception_type=exception_type):
super_method = getattr(super(NewTestCase, self), method_name)
with self.assertRaises(exception_type):
return super_method()
setattr(NewTestCase, method_name, wrapped_method)
NewTestCase.__name__ = name
return NewTestCase
TestValidTimestepSequence = _make_test_case_with_expected_failures(
name='TestValidTimestepSequence',
timestep_sequence=[FIRST, MID, MID, LAST],
expected_failures=[],
)
# Sequences where the ordering of StepTypes is invalid.
TestTwoFirstStepsInARow = _make_test_case_with_expected_failures(
name='TestTwoFirstStepsInARow',
timestep_sequence=[FIRST, FIRST, MID, MID, LAST],
expected_failures=[
('test_longer_action_sequence', AssertionError),
('test_step_after_reset', AssertionError),
('test_step_on_fresh_environment', AssertionError),
],
)
TestStartsWithMid = _make_test_case_with_expected_failures(
name='TestStartsWithMid',
timestep_sequence=[MID, MID, LAST],
expected_failures=[
('test_longer_action_sequence', AssertionError),
('test_reset', AssertionError),
('test_step_after_reset', AssertionError),
('test_step_on_fresh_environment', AssertionError),
],
)
TestMidAfterLast = _make_test_case_with_expected_failures(
name='TestMidAfterLast',
timestep_sequence=[FIRST, MID, LAST, MID],
expected_failures=[
('test_longer_action_sequence', AssertionError),
],
)
TestFirstAfterMid = _make_test_case_with_expected_failures(
name='TestFirstAfterMid',
timestep_sequence=[FIRST, MID, FIRST],
expected_failures=[
('test_longer_action_sequence', AssertionError),
],
)
# Sequences where one or more TimeSteps have invalid contents.
TestFirstStepHasReward = _make_test_case_with_expected_failures(
name='TestFirstStepHasReward',
timestep_sequence=[
FIRST._replace(reward=1.0), # Should be None.
MID,
MID,
LAST,
],
expected_failures=[
('test_reset', AssertionError),
('test_step_after_reset', AssertionError),
('test_step_on_fresh_environment', AssertionError),
('test_longer_action_sequence', AssertionError),
]
)
TestFirstStepHasDiscount = _make_test_case_with_expected_failures(
name='TestFirstStepHasDiscount',
timestep_sequence=[
FIRST._replace(discount=1.0), # Should be None.
MID,
MID,
LAST,
],
expected_failures=[
('test_reset', AssertionError),
('test_step_after_reset', AssertionError),
('test_step_on_fresh_environment', AssertionError),
('test_longer_action_sequence', AssertionError),
]
)
TestInvalidReward = _make_test_case_with_expected_failures(
name='TestInvalidReward',
timestep_sequence=[
FIRST,
MID._replace(reward=False), # Should be a float.
MID,
LAST,
],
expected_failures=[
('test_step_after_reset', ValueError),
('test_step_on_fresh_environment', ValueError),
('test_longer_action_sequence', ValueError),
]
)
TestInvalidDiscount = _make_test_case_with_expected_failures(
name='TestInvalidDiscount',
timestep_sequence=[
FIRST,
MID._replace(discount=1.5), # Should be between 0 and 1.
MID,
LAST,
],
expected_failures=[
('test_step_after_reset', ValueError),
('test_step_on_fresh_environment', ValueError),
('test_longer_action_sequence', ValueError),
]
)
TestInvalidObservation = _make_test_case_with_expected_failures(
name='TestInvalidObservation',
timestep_sequence=[
FIRST,
MID._replace(observation=np.zeros((3, 4))), # Wrong shape.
MID,
LAST,
],
expected_failures=[
('test_step_after_reset', ValueError),
('test_step_on_fresh_environment', ValueError),
('test_longer_action_sequence', ValueError),
]
)
TestMismatchingObservationStructure = _make_test_case_with_expected_failures(
name='TestInvalidObservation',
timestep_sequence=[
FIRST,
MID._replace(observation=[OBSERVATION]), # Wrong structure.
MID,
LAST,
],
expected_failures=[
('test_step_after_reset', AssertionError),
('test_step_on_fresh_environment', AssertionError),
('test_longer_action_sequence', AssertionError),
]
)
if __name__ == '__main__':
absltest.main()
| dm_env-master | dm_env/test_utils_test.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_env.examples.catch."""
from absl.testing import absltest
from dm_env import test_utils
from examples import catch
class CatchTest(test_utils.EnvironmentTestMixin, absltest.TestCase):
def make_object_under_test(self):
return catch.Catch()
if __name__ == '__main__':
absltest.main()
| dm_env-master | examples/catch_test.py |
# Copyright 2019 The dm_env Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
| dm_env-master | examples/__init__.py |
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Catch reinforcement learning environment."""
import dm_env
from dm_env import specs
import numpy as np
_ACTIONS = (-1, 0, 1) # Left, no-op, right.
class Catch(dm_env.Environment):
"""A Catch environment built on the `dm_env.Environment` class.
The agent must move a paddle to intercept falling balls. Falling balls only
move downwards on the column they are in.
The observation is an array shape (rows, columns), with binary values:
zero if a space is empty; 1 if it contains the paddle or a ball.
The actions are discrete, and by default there are three available:
stay, move left, and move right.
The episode terminates when the ball reaches the bottom of the screen.
"""
def __init__(self, rows: int = 10, columns: int = 5, seed: int = 1):
"""Initializes a new Catch environment.
Args:
rows: number of rows.
columns: number of columns.
seed: random seed for the RNG.
"""
self._rows = rows
self._columns = columns
self._rng = np.random.RandomState(seed)
self._board = np.zeros((rows, columns), dtype=np.float32)
self._ball_x = None
self._ball_y = None
self._paddle_x = None
self._paddle_y = self._rows - 1
self._reset_next_step = True
def reset(self) -> dm_env.TimeStep:
"""Returns the first `TimeStep` of a new episode."""
self._reset_next_step = False
self._ball_x = self._rng.randint(self._columns)
self._ball_y = 0
self._paddle_x = self._columns // 2
return dm_env.restart(self._observation())
def step(self, action: int) -> dm_env.TimeStep:
"""Updates the environment according to the action."""
if self._reset_next_step:
return self.reset()
# Move the paddle.
dx = _ACTIONS[action]
self._paddle_x = np.clip(self._paddle_x + dx, 0, self._columns - 1)
# Drop the ball.
self._ball_y += 1
# Check for termination.
if self._ball_y == self._paddle_y:
reward = 1. if self._paddle_x == self._ball_x else -1.
self._reset_next_step = True
return dm_env.termination(reward=reward, observation=self._observation())
else:
return dm_env.transition(reward=0., observation=self._observation())
def observation_spec(self) -> specs.BoundedArray:
"""Returns the observation spec."""
return specs.BoundedArray(
shape=self._board.shape,
dtype=self._board.dtype,
name="board",
minimum=0,
maximum=1,
)
def action_spec(self) -> specs.DiscreteArray:
"""Returns the action spec."""
return specs.DiscreteArray(
dtype=int, num_values=len(_ACTIONS), name="action")
def _observation(self) -> np.ndarray:
self._board.fill(0.)
self._board[self._ball_y, self._ball_x] = 1.
self._board[self._paddle_y, self._paddle_x] = 1.
return self._board.copy()
| dm_env-master | examples/catch.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module setuptools script."""
import distutils.command.build
from setuptools import setup
description = """PySC2 - StarCraft II Learning Environment
PySC2 is DeepMind's Python component of the StarCraft II Learning Environment
(SC2LE). It exposes Blizzard Entertainment's StarCraft II Machine Learning API
as a Python RL Environment. This is a collaboration between DeepMind and
Blizzard to develop StarCraft II into a rich environment for RL research. PySC2
provides an interface for RL agents to interact with StarCraft 2, getting
observations and sending actions.
We have published an accompanying blogpost and paper
https://deepmind.com/blog/deepmind-and-blizzard-open-starcraft-ii-ai-research-environment/
which outlines our motivation for using StarCraft II for DeepRL research, and
some initial research results using the environment.
Read the README at https://github.com/deepmind/pysc2 for more information.
"""
class BuildCommand(distutils.command.build.build):
def initialize_options(self):
distutils.command.build.build.initialize_options(self)
# To avoid conflicting with the Bazel BUILD file.
self.build_base = '_build'
setup(
name='PySC2',
version='4.0.0',
description='Starcraft II environment and library for training agents.',
long_description=description,
author='DeepMind',
author_email='[email protected]',
cmdclass={'build': BuildCommand},
license='Apache License, Version 2.0',
keywords='StarCraft AI',
url='https://github.com/deepmind/pysc2',
packages=[
'pysc2',
'pysc2.agents',
'pysc2.bin',
'pysc2.env',
'pysc2.lib',
'pysc2.maps',
'pysc2.run_configs',
'pysc2.tests',
],
install_requires=[
'absl-py>=0.1.0',
'deepdiff',
'dm_env',
'enum34',
'mock',
'mpyq',
'numpy>=1.10',
'portpicker>=1.2.0',
'protobuf>=2.6',
'pygame',
'requests',
's2clientprotocol>=4.10.1.75800.0',
's2protocol',
'sk-video',
'websocket-client',
],
entry_points={
'console_scripts': [
'pysc2_agent = pysc2.bin.agent:entry_point',
'pysc2_play = pysc2.bin.play:entry_point',
'pysc2_replay_info = pysc2.bin.replay_info:entry_point',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| pysc2-master | setup.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PySC2 module: https://github.com/deepmind/pysc2 ."""
import os
def load_tests(loader, standard_tests, unused_pattern):
"""Our tests end in `_test.py`, so need to override the test discovery."""
this_dir = os.path.dirname(__file__)
package_tests = loader.discover(start_dir=this_dir, pattern="*_test.py")
standard_tests.addTests(package_tests)
return standard_tests
| pysc2-master | pysc2/__init__.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The library and base Map for defining full maps.
To define your own map just import this library and subclass Map. It will be
automatically registered for creation by `get`.
class NewMap(lib.Map):
prefix = "map_dir"
filename = "map_name"
players = 3
You can build a hierarchy of classes to make your definitions less verbose.
To use a map, either import the map module and instantiate the map directly, or
import the maps lib and use `get`. Using `get` from this lib will work, but only
if you've imported the map module somewhere.
"""
import os
from absl import logging
class DuplicateMapError(Exception):
pass
class NoMapError(Exception):
pass
class Map(object):
"""Base map object to configure a map. To define a map just subclass this.
Attributes:
name: The name of the map/class.
path: Where to find the map file.
directory: Directory for the map
filename: Actual filename. You can skip the ".SC2Map" file ending.
download: Where to download the map.
game_steps_per_episode: Game steps per episode, independent of the step_mul.
0 (default) means no limit.
step_mul: How many game steps per agent step?
score_index: Which score to give for this map. -1 means the win/loss
reward. >=0 is the index into score_cumulative.
score_multiplier: A score multiplier to allow make small scores good.
players: Max number of players for this map.
battle_net: The map name on battle.net, if it exists.
"""
directory = ""
filename = None
download = None
game_steps_per_episode = 0
step_mul = 8
score_index = -1
score_multiplier = 1
players = None
battle_net = None
@property
def path(self):
"""The full path to the map file: directory, filename and file ending."""
if self.filename:
map_path = os.path.join(self.directory, self.filename)
if not map_path.endswith(".SC2Map"):
map_path += ".SC2Map"
return map_path
def data(self, run_config):
"""Return the map data."""
try:
return run_config.map_data(self.path, self.players)
except (IOError, OSError) as e: # Catch both for python 2/3 compatibility.
if self.download and hasattr(e, "filename"):
logging.error("Error reading map '%s' from: %s", self.name, e.filename)
logging.error("Download the map from: %s", self.download)
raise
@property
def name(self):
return self.__class__.__name__
def __str__(self):
return "\n".join(filter(None, [
self.name,
(" file: '%s'" % self.path) if self.path else None,
(" battle_net: '%s'" % self.battle_net) if self.battle_net else None,
" players: %s, score_index: %s, score_multiplier: %s" % (
self.players, self.score_index, self.score_multiplier),
" step_mul: %s, game_steps_per_episode: %s" % (
self.step_mul, self.game_steps_per_episode),
]))
@classmethod
def all_subclasses(cls):
"""An iterator over all subclasses of `cls`."""
for s in cls.__subclasses__():
yield s
for c in s.all_subclasses():
yield c
def get_maps():
"""Get the full dict of maps {map_name: map_class}."""
maps = {}
for mp in Map.all_subclasses():
if mp.filename or mp.battle_net:
map_name = mp.__name__
if map_name in maps:
raise DuplicateMapError("Duplicate map found: " + map_name)
maps[map_name] = mp
return maps
def get(map_name):
"""Get an instance of a map by name. Errors if the map doesn't exist."""
if isinstance(map_name, Map):
return map_name
# Get the list of maps. This isn't at module scope to avoid problems of maps
# being defined after this module is imported.
maps = get_maps()
map_class = maps.get(map_name)
if map_class:
return map_class()
raise NoMapError("Map doesn't exist: %s" % map_name)
| pysc2-master | pysc2/maps/lib.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Register/import the maps, and offer a way to create one by name.
Users of maps should import this module:
from pysc2 import maps
and create the maps by name:
maps.get("MapName")
If you want to create your own map, then import the map lib and subclass Map.
Your subclass will be implicitly registered as a map that can be constructed by
name, as long as it is imported somewhere.
"""
from pysc2.maps import ladder
from pysc2.maps import lib
from pysc2.maps import melee
from pysc2.maps import mini_games
# Use `get` to create a map by name.
get = lib.get
get_maps = lib.get_maps
| pysc2-master | pysc2/maps/__init__.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the melee map configs."""
from pysc2.maps import lib
class Melee(lib.Map):
directory = "Melee"
download = "https://github.com/Blizzard/s2client-proto#map-packs"
players = 2
game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
melee_maps = [
# "Empty128", # Not really playable, but may be useful in the future.
"Flat32",
"Flat48",
"Flat64",
"Flat96",
"Flat128",
"Simple64",
"Simple96",
"Simple128",
]
for name in melee_maps:
globals()[name] = type(name, (Melee,), dict(filename=name))
| pysc2-master | pysc2/maps/melee.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the mini game map configs. These are maps made by Deepmind."""
from pysc2.maps import lib
class MiniGame(lib.Map):
directory = "mini_games"
download = "https://github.com/deepmind/pysc2#get-the-maps"
players = 1
score_index = 0
game_steps_per_episode = 0
step_mul = 8
mini_games = [
"BuildMarines", # 900s
"CollectMineralsAndGas", # 420s
"CollectMineralShards", # 120s
"DefeatRoaches", # 120s
"DefeatZerglingsAndBanelings", # 120s
"FindAndDefeatZerglings", # 180s
"MoveToBeacon", # 120s
]
for name in mini_games:
globals()[name] = type(name, (MiniGame,), dict(filename=name))
| pysc2-master | pysc2/maps/mini_games.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the ladder map configs.
Refer to the map descriptions here:
http://wiki.teamliquid.net/starcraft2/Maps/Ladder_Maps/Legacy_of_the_Void
"""
import re
from pysc2.maps import lib
class Ladder(lib.Map):
players = 2
game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
download = "https://github.com/Blizzard/s2client-proto#map-packs"
ladder_seasons = [
"Ladder2017Season1",
"Ladder2017Season2",
"Ladder2017Season3",
"Ladder2017Season4",
"Ladder2018Season1",
"Ladder2018Season2",
"Ladder2018Season3",
"Ladder2018Season4",
"Ladder2019Season1",
"Ladder2019Season2",
"Ladder2019Season3",
]
for name in ladder_seasons:
globals()[name] = type(name, (Ladder,), dict(directory=name))
# pylint: disable=bad-whitespace, undefined-variable
# pytype: disable=name-error
ladder_maps = [
(Ladder2018Season2, "16-Bit LE", 2),
(Ladder2018Season1, "Abiogenesis LE", 2),
(Ladder2017Season4, "Abyssal Reef LE", 2),
(Ladder2018Season3, "Acid Plant LE", 2),
(Ladder2017Season3, "Acolyte LE", 2),
(Ladder2019Season3, "Acropolis LE", 2),
(Ladder2017Season4, "Ascension to Aiur LE", 2),
(Ladder2019Season1, "Automaton LE", 2),
(Ladder2018Season1, "Backwater LE", 2),
(Ladder2017Season4, "Battle on the Boardwalk LE", 2),
(Ladder2017Season1, "Bel'Shir Vestige LE", 2),
(Ladder2017Season2, "Blood Boil LE", 2),
(Ladder2018Season4, "Blueshift LE", 2),
(Ladder2017Season1, "Cactus Valley LE", 4),
(Ladder2018Season2, "Catalyst LE", 2),
(Ladder2018Season4, "Cerulean Fall LE", 2),
(Ladder2019Season2, "Cyber Forest LE", 2),
(Ladder2018Season2, "Darkness Sanctuary LE", 4),
(Ladder2017Season2, "Defender's Landing LE", 2),
(Ladder2019Season3, "Disco Bloodbath LE", 2),
(Ladder2018Season3, "Dreamcatcher LE", 2),
(Ladder2018Season1, "Eastwatch LE", 2),
(Ladder2019Season3, "Ephemeron LE", 2),
(Ladder2018Season3, "Fracture LE", 2),
(Ladder2017Season3, "Frost LE", 2),
(Ladder2017Season1, "Honorgrounds LE", 4),
(Ladder2017Season3, "Interloper LE", 2),
(Ladder2019Season2, "Kairos Junction LE", 2),
(Ladder2019Season2, "King's Cove LE", 2),
(Ladder2018Season3, "Lost and Found LE", 2),
(Ladder2017Season3, "Mech Depot LE", 2),
(Ladder2018Season1, "Neon Violet Square LE", 2),
(Ladder2019Season2, "New Repugnancy LE", 2),
(Ladder2017Season1, "Newkirk Precinct TE", 2),
(Ladder2017Season4, "Odyssey LE", 2),
(Ladder2017Season1, "Paladino Terminal LE", 2),
(Ladder2018Season4, "Para Site LE", 2),
(Ladder2019Season1, "Port Aleksander LE", 2),
(Ladder2017Season2, "Proxima Station LE", 2),
(Ladder2018Season2, "Redshift LE", 2),
(Ladder2017Season2, "Sequencer LE", 2),
(Ladder2018Season4, "Stasis LE", 2),
(Ladder2019Season3, "Thunderbird LE", 2),
(Ladder2019Season3, "Triton LE", 2),
(Ladder2019Season2, "Turbo Cruise '84 LE", 2),
(Ladder2019Season3, "Winter's Gate LE", 2),
(Ladder2019Season3, "World of Sleepers LE", 2),
(Ladder2019Season1, "Year Zero LE", 2),
# Disabled due to being renamed to Neo Seoul
# (Ladder2018Season1, "Blackpink LE", 2),
]
# pylint: enable=bad-whitespace, undefined-variable
# pytype: enable=name-error
# Create the classes dynamically, putting them into the module scope. They all
# inherit from a parent and set the players based on the map filename.
for parent, bnet, players in ladder_maps:
name = re.sub(r"[ '-]|[LTRS]E$", "", bnet)
map_file = re.sub(r"[ ']", "", bnet)
globals()[name] = type(name, (parent,), dict(
filename=map_file, players=players, battle_net=bnet))
| pysc2-master | pysc2/maps/ladder.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Play an agent with an SC2 instance that isn't owned.
This can be used to play on the sc2ai.net ladder, as well as to play vs humans.
To play on ladder:
$ python -m pysc2.bin.agent_remote --agent <import path> \
--host_port <GamePort> --lan_port <StartPort>
To play vs humans:
$ python -m pysc2.bin.agent_remote --human --map <MapName>
then copy the string it generates which is something similar to above
If you want to play remotely, you'll need to port forward (eg with ssh -L or -R)
the host_port from localhost on one machine to localhost on the other.
You can also set your race, observation options, etc by cmdline flags.
When playing vs humans it launches both instances on the human side. This means
you only need to port-forward a single port (ie the websocket betwen SC2 and the
agent), but you also need to transfer the entire observation, which is much
bigger than the actions transferred over the lan connection between the two SC2
instances. It also makes it easy to maintain version compatibility since they
are the same binary. Unfortunately it means higher cpu usage where the human is
playing, which on a Mac becomes problematic as OSX slows down the instance
running in the background. There can also be observation differences between
Mac/Win and Linux. For these reasons, prefer play_vs_agent which runs the
instance next to the agent, and tunnels the lan actions instead.
"""
import getpass
import importlib
import platform
import sys
import time
from absl import app
from absl import flags
from absl import logging
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import remote_sc2_env
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import portspicker
from pysc2.lib import renderer_human
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", platform.system() == "Linux",
"Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent's race.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", "256",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", "FEATURES",
sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", False,
"Whether to include feature units.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_string("host", "127.0.0.1", "Game Host")
flags.DEFINE_integer("host_port", None, "Host port")
flags.DEFINE_integer("lan_port", None, "Host port")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("human", False, "Whether to host a game as a human.")
flags.DEFINE_integer("timeout_seconds", 300,
"Time in seconds for the remote agent to connect to the "
"game before an exception is raised.")
def main(unused_argv):
if FLAGS.human:
human()
else:
agent()
def agent():
"""Run the agent, connecting to a (remote) host started independently."""
agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
logging.info("Starting agent:")
with remote_sc2_env.RemoteSC2Env(
map_name=FLAGS.map,
host=FLAGS.host,
host_port=FLAGS.host_port,
lan_port=FLAGS.lan_port,
name=FLAGS.agent_name or agent_name,
race=sc2_env.Race[FLAGS.agent_race],
step_mul=FLAGS.step_mul,
agent_interface_format=sc2_env.parse_agent_interface_format(
feature_screen=FLAGS.feature_screen_size,
feature_minimap=FLAGS.feature_minimap_size,
rgb_screen=FLAGS.rgb_screen_size,
rgb_minimap=FLAGS.rgb_minimap_size,
action_space=FLAGS.action_space,
use_feature_units=FLAGS.use_feature_units),
visualize=FLAGS.render) as env:
agents = [agent_cls()]
logging.info("Connected, starting run_loop.")
try:
run_loop.run_loop(agents, env)
except remote_sc2_env.RestartError:
pass
logging.info("Done.")
def human():
"""Run a host which expects one player to connect remotely."""
run_config = run_configs.get()
map_inst = maps.get(FLAGS.map)
if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size:
logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb "
"observations.")
ports = portspicker.pick_contiguous_unused_ports(4) # 2 * num_players
host_proc = run_config.start(extra_ports=ports, host=FLAGS.host,
timeout_seconds=FLAGS.timeout_seconds,
window_loc=(50, 50))
client_proc = run_config.start(extra_ports=ports, host=FLAGS.host,
connect=False, window_loc=(700, 50))
create = sc_pb.RequestCreateGame(
realtime=FLAGS.realtime, local_map=sc_pb.LocalMap(map_path=map_inst.path))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Participant)
controller = host_proc.controller
controller.save_map(map_inst.path, map_inst.data(run_config))
controller.create_game(create)
print("-" * 80)
print("Join host: agent_remote --map %s --host %s --host_port %s "
"--lan_port %s" % (FLAGS.map, FLAGS.host, client_proc.port, ports[0]))
print("-" * 80)
sys.stdout.flush()
join = sc_pb.RequestJoinGame()
join.shared_port = 0 # unused
join.server_ports.game_port = ports.pop(0)
join.server_ports.base_port = ports.pop(0)
join.client_ports.add(game_port=ports.pop(0), base_port=ports.pop(0))
join.race = sc2_env.Race[FLAGS.user_race]
join.player_name = FLAGS.user_name
if FLAGS.render:
join.options.raw = True
join.options.score = True
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
fl = join.options.feature_layer
fl.width = 24
FLAGS.feature_screen_size.assign_to(fl.resolution)
FLAGS.feature_minimap_size.assign_to(fl.minimap_resolution)
if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(join.options.render.resolution)
FLAGS.rgb_minimap_size.assign_to(join.options.render.minimap_resolution)
controller.join_game(join)
if FLAGS.render:
renderer = renderer_human.RendererHuman(
fps=FLAGS.fps, render_feature_grid=False)
renderer.run(run_configs.get(), controller, max_episodes=1)
else: # Still step forward so the Mac/Windows renderer works.
try:
while True:
frame_start_time = time.time()
if not FLAGS.realtime:
controller.step()
obs = controller.observe()
if obs.player_result:
break
time.sleep(max(0, frame_start_time - time.time() + 1 / FLAGS.fps))
except KeyboardInterrupt:
pass
for p in [host_proc, client_proc]:
p.close()
portspicker.return_ports(ports)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/agent_remote.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dump out stats about all the actions that are in use in a set of replays."""
import collections
import multiprocessing
import os
import queue
import signal
import sys
import threading
import time
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import protocol
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import static_data
from pysc2.lib import gfile
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_integer("parallel", 1, "How many instances to run in parallel.")
flags.DEFINE_integer("step_mul", 8, "How many game steps per observation.")
flags.DEFINE_string("replays", None, "Path to a directory of replays.")
flags.mark_flag_as_required("replays")
size = point.Point(16, 16)
interface = sc_pb.InterfaceOptions(
raw=True, score=False,
feature_layer=sc_pb.SpatialCameraSetup(width=24))
size.assign_to(interface.feature_layer.resolution)
size.assign_to(interface.feature_layer.minimap_resolution)
def sorted_dict_str(d):
return "{%s}" % ", ".join("%s: %s" % (k, d[k])
for k in sorted(d, key=d.get, reverse=True))
class ReplayStats(object):
"""Summary stats of the replays seen so far."""
def __init__(self):
self.replays = 0
self.steps = 0
self.camera_move = 0
self.select_pt = 0
self.select_rect = 0
self.control_group = 0
self.maps = collections.defaultdict(int)
self.races = collections.defaultdict(int)
self.unit_ids = collections.defaultdict(int)
self.valid_abilities = collections.defaultdict(int)
self.made_abilities = collections.defaultdict(int)
self.valid_actions = collections.defaultdict(int)
self.made_actions = collections.defaultdict(int)
self.buffs = collections.defaultdict(int)
self.upgrades = collections.defaultdict(int)
self.effects = collections.defaultdict(int)
self.crashing_replays = set()
self.invalid_replays = set()
def merge(self, other):
"""Merge another ReplayStats into this one."""
def merge_dict(a, b):
for k, v in b.items():
a[k] += v
self.replays += other.replays
self.steps += other.steps
self.camera_move += other.camera_move
self.select_pt += other.select_pt
self.select_rect += other.select_rect
self.control_group += other.control_group
merge_dict(self.maps, other.maps)
merge_dict(self.races, other.races)
merge_dict(self.unit_ids, other.unit_ids)
merge_dict(self.valid_abilities, other.valid_abilities)
merge_dict(self.made_abilities, other.made_abilities)
merge_dict(self.valid_actions, other.valid_actions)
merge_dict(self.made_actions, other.made_actions)
merge_dict(self.buffs, other.buffs)
merge_dict(self.upgrades, other.upgrades)
merge_dict(self.effects, other.effects)
self.crashing_replays |= other.crashing_replays
self.invalid_replays |= other.invalid_replays
def __str__(self):
len_sorted_dict = lambda s: (len(s), sorted_dict_str(s))
len_sorted_list = lambda s: (len(s), sorted(s))
new_abilities = ((set(self.valid_abilities.keys())
| set(self.made_abilities.keys()))
- set(static_data.ABILITIES))
new_units = set(self.unit_ids) - set(static_data.UNIT_TYPES)
new_buffs = set(self.buffs) - set(static_data.BUFFS)
new_upgrades = set(self.upgrades) - set(static_data.UPGRADES)
return "\n\n".join((
"Replays: %s, Steps total: %s" % (self.replays, self.steps),
"Camera move: %s, Select pt: %s, Select rect: %s, Control group: %s" % (
self.camera_move, self.select_pt, self.select_rect,
self.control_group),
"Maps: %s\n%s" % len_sorted_dict(self.maps),
"Races: %s\n%s" % len_sorted_dict(self.races),
"Unit ids: %s\n%s" % len_sorted_dict(self.unit_ids),
"New units: %s \n%s" % len_sorted_list(new_units),
"Valid abilities: %s\n%s" % len_sorted_dict(self.valid_abilities),
"Made abilities: %s\n%s" % len_sorted_dict(self.made_abilities),
"New abilities: %s\n%s" % len_sorted_list(new_abilities),
"Valid actions: %s\n%s" % len_sorted_dict(self.valid_actions),
"Made actions: %s\n%s" % len_sorted_dict(self.made_actions),
"Buffs: %s\n%s" % len_sorted_dict(self.buffs),
"New buffs: %s\n%s" % len_sorted_list(new_buffs),
"Upgrades: %s\n%s" % len_sorted_dict(self.upgrades),
"New upgrades: %s\n%s" % len_sorted_list(new_upgrades),
"Effects: %s\n%s" % len_sorted_dict(self.effects),
"Crashing replays: %s\n%s" % len_sorted_list(self.crashing_replays),
"Invalid replays: %s\n%s" % len_sorted_list(self.invalid_replays),
))
class ProcessStats(object):
"""Stats for a worker process."""
def __init__(self, proc_id):
self.proc_id = proc_id
self.time = time.time()
self.stage = ""
self.replay = ""
self.replay_stats = ReplayStats()
def update(self, stage):
self.time = time.time()
self.stage = stage
def __str__(self):
return ("[%2d] replay: %10s, replays: %5d, steps: %7d, game loops: %7s, "
"last: %12s, %3d s ago" % (
self.proc_id, self.replay, self.replay_stats.replays,
self.replay_stats.steps,
self.replay_stats.steps * FLAGS.step_mul, self.stage,
time.time() - self.time))
def valid_replay(info, ping):
"""Make sure the replay isn't corrupt, and is worth looking at."""
if (info.HasField("error") or
info.base_build != ping.base_build or # different game version
info.game_duration_loops < 1000 or
len(info.player_info) != 2):
# Probably corrupt, or just not interesting.
return False
for p in info.player_info:
if p.player_apm < 10 or p.player_mmr < 1000:
# Low APM = player just standing around.
# Low MMR = corrupt replay or player who is weak.
return False
return True
class ReplayProcessor(multiprocessing.Process):
"""A Process that pulls replays and processes them."""
def __init__(self, proc_id, run_config, replay_queue, stats_queue):
super(ReplayProcessor, self).__init__()
self.stats = ProcessStats(proc_id)
self.run_config = run_config
self.replay_queue = replay_queue
self.stats_queue = stats_queue
def run(self):
signal.signal(signal.SIGTERM, lambda a, b: sys.exit()) # Exit quietly.
self._update_stage("spawn")
replay_name = "none"
while True:
self._print("Starting up a new SC2 instance.")
self._update_stage("launch")
try:
with self.run_config.start(
want_rgb=interface.HasField("render")) as controller:
self._print("SC2 Started successfully.")
ping = controller.ping()
for _ in range(300):
try:
replay_path = self.replay_queue.get()
except queue.Empty:
self._update_stage("done")
self._print("Empty queue, returning")
return
try:
replay_name = os.path.basename(replay_path)[:10]
self.stats.replay = replay_name
self._print("Got replay: %s" % replay_path)
self._update_stage("open replay file")
replay_data = self.run_config.replay_data(replay_path)
self._update_stage("replay_info")
info = controller.replay_info(replay_data)
self._print((" Replay Info %s " % replay_name).center(60, "-"))
self._print(info)
self._print("-" * 60)
if valid_replay(info, ping):
self.stats.replay_stats.maps[info.map_name] += 1
for player_info in info.player_info:
race_name = sc_common.Race.Name(
player_info.player_info.race_actual)
self.stats.replay_stats.races[race_name] += 1
map_data = None
if info.local_map_path:
self._update_stage("open map file")
map_data = self.run_config.map_data(info.local_map_path)
for player_id in [1, 2]:
self._print("Starting %s from player %s's perspective" % (
replay_name, player_id))
self.process_replay(controller, replay_data, map_data,
player_id)
else:
self._print("Replay is invalid.")
self.stats.replay_stats.invalid_replays.add(replay_name)
finally:
self.replay_queue.task_done()
self._update_stage("shutdown")
except (protocol.ConnectionError, protocol.ProtocolError,
remote_controller.RequestError):
self.stats.replay_stats.crashing_replays.add(replay_name)
except KeyboardInterrupt:
return
def _print(self, s):
for line in str(s).strip().splitlines():
print("[%s] %s" % (self.stats.proc_id, line))
def _update_stage(self, stage):
self.stats.update(stage)
self.stats_queue.put(self.stats)
def process_replay(self, controller, replay_data, map_data, player_id):
"""Process a single replay, updating the stats."""
self._update_stage("start_replay")
controller.start_replay(sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=map_data,
options=interface,
observed_player_id=player_id))
feat = features.features_from_game_info(controller.game_info())
self.stats.replay_stats.replays += 1
self._update_stage("step")
controller.step()
while True:
self.stats.replay_stats.steps += 1
self._update_stage("observe")
obs = controller.observe()
for action in obs.actions:
act_fl = action.action_feature_layer
if act_fl.HasField("unit_command"):
self.stats.replay_stats.made_abilities[
act_fl.unit_command.ability_id] += 1
if act_fl.HasField("camera_move"):
self.stats.replay_stats.camera_move += 1
if act_fl.HasField("unit_selection_point"):
self.stats.replay_stats.select_pt += 1
if act_fl.HasField("unit_selection_rect"):
self.stats.replay_stats.select_rect += 1
if action.action_ui.HasField("control_group"):
self.stats.replay_stats.control_group += 1
try:
func = feat.reverse_action(action).function
except ValueError:
func = -1
self.stats.replay_stats.made_actions[func] += 1
for valid in obs.observation.abilities:
self.stats.replay_stats.valid_abilities[valid.ability_id] += 1
for u in obs.observation.raw_data.units:
self.stats.replay_stats.unit_ids[u.unit_type] += 1
for b in u.buff_ids:
self.stats.replay_stats.buffs[b] += 1
for u in obs.observation.raw_data.player.upgrade_ids:
self.stats.replay_stats.upgrades[u] += 1
for e in obs.observation.raw_data.effects:
self.stats.replay_stats.effects[e.effect_id] += 1
for ability_id in feat.available_actions(obs.observation):
self.stats.replay_stats.valid_actions[ability_id] += 1
if obs.player_result:
break
self._update_stage("step")
controller.step(FLAGS.step_mul)
def stats_printer(stats_queue):
"""A thread that consumes stats_queue and prints them every 10 seconds."""
proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)]
print_time = start_time = time.time()
width = 107
running = True
while running:
print_time += 10
while time.time() < print_time:
try:
s = stats_queue.get(True, print_time - time.time())
if s is None: # Signal to print and exit NOW!
running = False
break
proc_stats[s.proc_id] = s
except queue.Empty:
pass
replay_stats = ReplayStats()
for s in proc_stats:
replay_stats.merge(s.replay_stats)
print((" Summary %0d secs " % (print_time - start_time)).center(width, "="))
print(replay_stats)
print(" Process stats ".center(width, "-"))
print("\n".join(str(s) for s in proc_stats))
print("=" * width)
def replay_queue_filler(replay_queue, replay_list):
"""A thread that fills the replay_queue with replay filenames."""
for replay_path in replay_list:
replay_queue.put(replay_path)
def main(unused_argv):
"""Dump stats about all the actions that are in use in a set of replays."""
run_config = run_configs.get()
if not gfile.Exists(FLAGS.replays):
sys.exit("{} doesn't exist.".format(FLAGS.replays))
stats_queue = multiprocessing.Queue()
stats_thread = threading.Thread(target=stats_printer, args=(stats_queue,))
try:
# For some reason buffering everything into a JoinableQueue makes the
# program not exit, so save it into a list then slowly fill it into the
# queue in a separate thread. Grab the list synchronously so we know there
# is work in the queue before the SC2 processes actually run, otherwise
# The replay_queue.join below succeeds without doing any work, and exits.
print("Getting replay list:", FLAGS.replays)
replay_list = sorted(run_config.replay_paths(FLAGS.replays))
print(len(replay_list), "replays found.")
if not replay_list:
return
if not FLAGS["sc2_version"].present: # ie not set explicitly.
version = replay.get_replay_version(
run_config.replay_data(replay_list[0]))
run_config = run_configs.get(version=version)
print("Assuming version:", version.game_version)
print()
stats_thread.start()
replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * 10)
replay_queue_thread = threading.Thread(target=replay_queue_filler,
args=(replay_queue, replay_list))
replay_queue_thread.daemon = True
replay_queue_thread.start()
for i in range(min(len(replay_list), FLAGS.parallel)):
p = ReplayProcessor(i, run_config, replay_queue, stats_queue)
p.daemon = True
p.start()
time.sleep(1) # Stagger startups, otherwise they seem to conflict somehow
replay_queue.join() # Wait for the queue to empty.
except KeyboardInterrupt:
print("Caught KeyboardInterrupt, exiting.")
finally:
stats_queue.put(None) # Tell the stats_thread to print and exit.
if stats_thread.is_alive():
stats_thread.join()
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/replay_actions.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for memory leaks."""
# pylint: disable=g-import-not-at-top
import collections
import random
import sys
import time
from absl import app
from absl import flags
try:
import psutil
except ImportError:
sys.exit(
"`psutil` library required to track memory. This can be installed with:\n"
"$ pip install psutil\n"
"and needs the python-dev headers installed, for example:\n"
"$ apt install python-dev")
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import protocol
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
# pylint: enable=g-import-not-at-top
races = {
"random": sc_common.Random,
"protoss": sc_common.Protoss,
"terran": sc_common.Terran,
"zerg": sc_common.Zerg,
}
flags.DEFINE_integer("mem_limit", 2000, "Max memory usage in Mb.")
flags.DEFINE_integer("episodes", 200, "Max number of episodes.")
flags.DEFINE_enum("race", "random", races.keys(), "Which race to play as.")
flags.DEFINE_list("map", "Catalyst", "Which map(s) to test on.")
FLAGS = flags.FLAGS
class Timestep(collections.namedtuple(
"Timestep", ["episode", "time", "cpu", "memory", "name"])):
def __str__(self):
return "[%3d: %7.3f] cpu: %5.1f s, mem: %4d Mb; %s" % self
def main(unused_argv):
for m in FLAGS.map: # Verify they're all valid.
maps.get(m)
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.score = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 84
interface.feature_layer.resolution.y = 84
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
timeline = []
start = time.time()
run_config = run_configs.get()
proc = run_config.start(want_rgb=interface.HasField("render"))
process = psutil.Process(proc.pid)
episode = 1
def add(s):
cpu_times = process.cpu_times() # pytype: disable=wrong-arg-count
cpu = cpu_times.user + cpu_times.system
mem = process.memory_info().rss / 2 ** 20 # In Mb # pytype: disable=wrong-arg-count
step = Timestep(episode, time.time() - start, cpu, mem, s)
print(step)
timeline.append(step)
if mem > FLAGS.mem_limit:
raise MemoryError("%s Mb mem limit exceeded" % FLAGS.mem_limit)
try:
add("Started process")
controller = proc.controller
for _ in range(FLAGS.episodes):
map_inst = maps.get(random.choice(FLAGS.map))
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False, random_seed=episode,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=races[FLAGS.race],
difficulty=sc_pb.CheatInsane)
join = sc_pb.RequestJoinGame(race=races[FLAGS.race], options=interface)
controller.create_game(create)
add("Created game on %s" % map_inst.name)
controller.join_game(join)
add("Joined game")
for i in range(2000):
controller.step(16)
obs = controller.observe()
if obs.player_result:
add("Lost on step %s" % i)
break
if i > 0 and i % 100 == 0:
add("Step %s" % i)
episode += 1
add("Done")
except KeyboardInterrupt:
pass
except (MemoryError, protocol.ConnectionError) as e:
print(e)
finally:
proc.close()
print("Timeline:")
for t in timeline:
print(t)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/mem_leak_check.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Query one or more replays for information."""
import os
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import gfile
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
def _replay_index(replay_dir):
"""Output information for a directory of replays."""
run_config = run_configs.get()
replay_dir = run_config.abs_replay_path(replay_dir)
print("Checking:", replay_dir)
replay_paths = list(run_config.replay_paths(replay_dir))
print("Found %s replays" % len(replay_paths))
if not replay_paths:
return
data = run_config.replay_data(replay_paths[0])
ver = replay.get_replay_version(data)
FLAGS.set_default("sc2_version", ver.game_version)
run_config = run_configs.get() # In case the version changed.
print("Launching version:", run_config.version.game_version)
with run_config.start(want_rgb=False) as controller:
print("-" * 60)
print(",".join((
"filename",
"version",
"map_name",
"game_duration_loops",
"players",
"P1-outcome",
"P1-race",
"P1-apm",
"P2-race",
"P2-apm",
)))
bad_replays = []
try:
for file_path in replay_paths:
file_name = os.path.basename(file_path)
data = run_config.replay_data(file_path)
try:
info = controller.replay_info(data)
except remote_controller.RequestError as e:
bad_replays.append("%s: %s" % (file_name, e))
continue
if info.HasField("error"):
print("failed:", file_name, info.error, info.error_details)
bad_replays.append(file_name)
else:
out = [
file_name,
info.game_version,
info.map_name,
info.game_duration_loops,
len(info.player_info),
sc_pb.Result.Name(info.player_info[0].player_result.result),
sc_common.Race.Name(info.player_info[0].player_info.race_actual),
info.player_info[0].player_apm,
]
if len(info.player_info) >= 2:
out += [
sc_common.Race.Name(
info.player_info[1].player_info.race_actual),
info.player_info[1].player_apm,
]
print(u",".join(str(s) for s in out))
except KeyboardInterrupt:
pass
finally:
if bad_replays:
print("\n")
print("Replays with errors:")
print("\n".join(bad_replays))
def _replay_info(replay_path):
"""Query a replay for information."""
if not replay_path.lower().endswith("sc2replay"):
print("Must be a replay.")
return
run_config = run_configs.get()
data = run_config.replay_data(replay_path)
ver = replay.get_replay_version(data)
FLAGS.set_default("sc2_version", ver.game_version)
run_config = run_configs.get() # In case the version changed.
print("Launching version:", run_config.version.game_version)
with run_config.start(want_rgb=False) as controller:
info = controller.replay_info(data)
print("-" * 60)
print(info)
def main(argv):
if not argv:
raise ValueError("No replay directory or path specified.")
if len(argv) > 2:
raise ValueError("Too many arguments provided.")
path = argv[1]
try:
if gfile.IsDirectory(path):
return _replay_index(path)
else:
return _replay_info(path)
except KeyboardInterrupt:
pass
def entry_point(): # Needed so the setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/replay_info.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compare the observations from multiple binaries."""
import collections
import sys
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import image_differencer
from pysc2.lib import proto_diff
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("diff", False, "Whether to diff the observations.")
flags.DEFINE_integer("truncate", 0,
"Number of characters to truncate diff values to, or 0 "
"for no truncation.")
flags.DEFINE_integer("step_mul", 8, "Game steps per observation.")
flags.DEFINE_integer("count", 100000, "How many observations to run.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
def _clear_non_deterministic_fields(obs):
for unit in obs.observation.raw_data.units:
unit.ClearField("tag")
for order in unit.orders:
order.ClearField("target_unit_tag")
for action in obs.actions:
if action.HasField("action_raw"):
if action.action_raw.HasField("unit_command"):
action.action_raw.unit_command.ClearField("target_unit_tag")
def _is_remote(arg):
return ":" in arg
def main(argv):
"""Compare the observations from multiple binaries."""
if len(argv) <= 1:
sys.exit(
"Please specify binaries to run / to connect to. For binaries to run, "
"specify the executable name. For remote connections, specify "
"<hostname>:<port>. The version must match the replay.")
targets = argv[1:]
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.raw_affects_selection = True
interface.raw_crop_to_playable_area = True
interface.score = True
interface.show_cloaked = True
interface.show_placeholders = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 48
interface.feature_layer.resolution.y = 48
interface.feature_layer.minimap_resolution.x = 48
interface.feature_layer.minimap_resolution.y = 48
interface.feature_layer.crop_to_playable_area = True
interface.feature_layer.allow_cheating_layers = True
run_config = run_configs.get()
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
observed_player_id=1,
realtime=False)
version = replay.get_replay_version(replay_data)
timers = []
controllers = []
procs = []
for target in targets:
timer = stopwatch.StopWatch()
timers.append(timer)
with timer("launch"):
if _is_remote(target):
host, port = target.split(":")
controllers.append(remote_controller.RemoteController(host, int(port)))
else:
proc = run_configs.get(
version=version._replace(binary=target)).start(want_rgb=False)
procs.append(proc)
controllers.append(proc.controller)
diff_counts = [0] * len(controllers)
diff_paths = collections.Counter()
try:
print("-" * 80)
print(controllers[0].replay_info(replay_data))
print("-" * 80)
for controller, t in zip(controllers, timers):
with t("start_replay"):
controller.start_replay(start_replay)
# Check the static data.
static_data = []
for controller, t in zip(controllers, timers):
with t("data"):
static_data.append(controller.data_raw())
if FLAGS.diff:
diffs = {i: proto_diff.compute_diff(static_data[0], d)
for i, d in enumerate(static_data[1:], 1)}
if any(diffs.values()):
print(" Diff in static data ".center(80, "-"))
for i, diff in diffs.items():
if diff:
print(targets[i])
diff_counts[i] += 1
print(diff.report(truncate_to=FLAGS.truncate))
for path in diff.all_diffs():
diff_paths[path.with_anonymous_array_indices()] += 1
else:
print("No diffs in static data.")
# Run some steps, checking speed and diffing the observations.
for _ in range(FLAGS.count):
for controller, t in zip(controllers, timers):
with t("step"):
controller.step(FLAGS.step_mul)
obs = []
for controller, t in zip(controllers, timers):
with t("observe"):
obs.append(controller.observe())
if FLAGS.diff:
for o in obs:
_clear_non_deterministic_fields(o)
diffs = {i: proto_diff.compute_diff(obs[0], o)
for i, o in enumerate(obs[1:], 1)}
if any(diffs.values()):
print((" Diff on step: %s " %
obs[0].observation.game_loop).center(80, "-"))
for i, diff in diffs.items():
if diff:
print(targets[i])
diff_counts[i] += 1
print(diff.report([image_differencer.image_differencer],
truncate_to=FLAGS.truncate))
for path in diff.all_diffs():
diff_paths[path.with_anonymous_array_indices()] += 1
if obs[0].player_result:
break
except KeyboardInterrupt:
pass
finally:
for c in controllers:
c.quit()
c.close()
for p in procs:
p.close()
if FLAGS.diff:
print(" Diff Counts by target ".center(80, "-"))
for target, count in zip(targets, diff_counts):
print(" %5d %s" % (count, target))
print()
print(" Diff Counts by observation path ".center(80, "-"))
for path, count in diff_paths.most_common(100):
print(" %5d %s" % (count, path))
print()
print(" Timings ".center(80, "-"))
for v, t in zip(targets, timers):
print(v)
print(t)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/compare_binaries.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Find and run the tests.
Run as: python -m pysc2.bin.run_tests
"""
from absl.testing import absltest
import pysc2
import pysc2.run_configs.platforms # So that the version flags work.
if __name__ == '__main__':
absltest.main(module=pysc2)
| pysc2-master | pysc2/bin/run_tests.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark observation times."""
import time
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_integer("count", 1000, "How many observations to run.")
flags.DEFINE_integer("step_mul", 16, "How many game steps per observation.")
flags.DEFINE_string("replay", None, "Which replay to run.")
flags.DEFINE_string("map", "Catalyst", "Which map to run.")
FLAGS = flags.FLAGS
def interface_options(score=False, raw=False, features=None, rgb=None,
crop=True):
"""Get an InterfaceOptions for the config."""
interface = sc_pb.InterfaceOptions()
interface.score = score
interface.raw = raw
if features:
if isinstance(features, int):
screen, minimap = features, features
else:
screen, minimap = features
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = screen
interface.feature_layer.resolution.y = screen
interface.feature_layer.minimap_resolution.x = minimap
interface.feature_layer.minimap_resolution.y = minimap
interface.feature_layer.crop_to_playable_area = crop
if rgb:
if isinstance(rgb, int):
screen, minimap = rgb, rgb
else:
screen, minimap = rgb
interface.render.resolution.x = screen
interface.render.resolution.y = screen
interface.render.minimap_resolution.x = minimap
interface.render.minimap_resolution.y = minimap
return interface
configs = [
("raw", interface_options(raw=True)),
("raw-feat-48", interface_options(raw=True, features=48)),
("raw-feat-128", interface_options(raw=True, features=128)),
("raw-feat-128-48", interface_options(raw=True, features=(128, 48))),
("feat-32", interface_options(features=32)),
("feat-48", interface_options(features=48)),
("feat-72-no-crop", interface_options(features=72, crop=False)),
("feat-72", interface_options(features=72)),
("feat-96", interface_options(features=96)),
("feat-128", interface_options(features=128)),
("rgb-64", interface_options(rgb=64)),
("rgb-128", interface_options(rgb=128)),
]
def main(unused_argv):
stopwatch.sw.enable()
results = []
try:
for config, interface in configs:
print((" Starting: %s " % config).center(60, "-"))
timeline = []
run_config = run_configs.get()
if FLAGS.replay:
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data, options=interface, disable_fog=False,
observed_player_id=2)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
else:
map_inst = maps.get(FLAGS.map)
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False, random_seed=1,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(options=interface, race=sc_common.Protoss)
with run_config.start(
want_rgb=interface.HasField("render")) as controller:
if FLAGS.replay:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
if info.local_map_path:
start_replay.map_data = run_config.map_data(info.local_map_path)
controller.start_replay(start_replay)
else:
controller.create_game(create)
controller.join_game(join)
for _ in range(FLAGS.count):
controller.step(FLAGS.step_mul)
start = time.time()
obs = controller.observe()
timeline.append(time.time() - start)
if obs.player_result:
break
results.append((config, timeline))
except KeyboardInterrupt:
pass
names, values = zip(*results)
print("\n\nTimeline:\n")
print(",".join(names))
for times in zip(*values):
print(",".join("%0.2f" % (t * 1000) for t in times))
print(stopwatch.sw)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/benchmark_observe.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark observation times."""
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point_flag
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_integer("step_mul", 8, "Game steps per observation.")
point_flag.DEFINE_point("feature_screen_size", "64",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", None,
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", None,
"Resolution for rendered minimap.")
flags.DEFINE_bool("use_feature_units", True,
"Whether to include feature units.")
flags.DEFINE_bool("use_raw_units", True,
"Whether to include raw units.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
flags.DEFINE_string("map_path", None, "Override the map for this replay.")
flags.mark_flag_as_required("replay")
def main(argv):
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
stopwatch.sw.enable()
interface = sc_pb.InterfaceOptions()
interface.raw = FLAGS.use_feature_units or FLAGS.use_raw_units
interface.score = True
interface.feature_layer.width = 24
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
FLAGS.feature_screen_size.assign_to(interface.feature_layer.resolution)
FLAGS.feature_minimap_size.assign_to(
interface.feature_layer.minimap_resolution)
if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(interface.render.resolution)
FLAGS.rgb_minimap_size.assign_to(interface.render.minimap_resolution)
run_config = run_configs.get()
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
observed_player_id=1)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
try:
with run_config.start(
want_rgb=interface.HasField("render")) as controller:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
map_path = FLAGS.map_path or info.local_map_path
if map_path:
start_replay.map_data = run_config.map_data(map_path)
controller.start_replay(start_replay)
feats = features.features_from_game_info(
game_info=controller.game_info(),
use_feature_units=FLAGS.use_feature_units,
use_raw_units=FLAGS.use_raw_units,
use_unit_counts=interface.raw,
use_camera_position=False,
action_space=actions.ActionSpace.FEATURES)
while True:
controller.step(FLAGS.step_mul)
obs = controller.observe()
feats.transform_obs(obs)
if obs.player_result:
break
except KeyboardInterrupt:
pass
print(stopwatch.sw)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/benchmark_replay.py |
#!/usr/bin/python
# Copyright 2022 DeepMind Technologies Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate version information from replays."""
import os
from absl import app
from pysc2 import run_configs
from pysc2.lib import replay
def main(argv):
if len(argv) <= 1:
raise app.UsageError(
"Please give one or more replay files/directories to scan as argv.")
run_config = run_configs.get()
# Use a set over the full version struct to catch cases where Blizzard failed
# to update the version field properly (eg 5.0.0).
versions = set()
def replay_version(replay_path):
"""Query a replay for information."""
if replay_path.lower().endswith("sc2replay"):
data = run_config.replay_data(replay_path)
try:
version = replay.get_replay_version(data)
except (ValueError, KeyError):
pass # Either corrupt or just old.
except Exception as e: # pylint: disable=broad-except
print("Invalid replay:", replay_path, e)
else:
versions.add(version)
try:
for path in argv[1:]:
if os.path.isdir(path):
for root, _, files in os.walk(path):
for file in files:
replay_version(os.path.join(root, file))
else:
replay_version(path)
except KeyboardInterrupt:
pass
for version in sorted(versions):
print(version)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/replay_version.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the action definitions for actions.py."""
import itertools
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import static_data
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import data_pb2 as sc_data
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_enum("command", None, ["csv", "python"], "What to generate.")
flags.DEFINE_string("map", "Acropolis", "Which map to use.")
flags.mark_flag_as_required("command")
FLAGS = flags.FLAGS
def get_data():
"""Retrieve static data from the game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get(FLAGS.map)
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
return controller.data()
def generate_name(ability):
return (ability.friendly_name or ability.button_name or
ability.link_name)
def sort_key(data, ability):
# Alphabetical, with specifics immediately after their generals.
name = generate_name(ability)
if ability.remaps_to_ability_id:
general = data.abilities[ability.remaps_to_ability_id]
name = "%s %s" % (generate_name(general), name)
return name
def generate_csv(data):
"""Generate a CSV of the abilities for easy commenting."""
print(",".join([
"ability_id",
"link_name",
"link_index",
"button_name",
"hotkey",
"friendly_name",
"remap_to",
"mismatch",
]))
for ability in sorted(data.abilities.values(),
key=lambda a: sort_key(data, a)):
ab_id = ability.ability_id
if ab_id in skip_abilities or (ab_id not in data.general_abilities and
ab_id not in used_abilities):
continue
general = ""
if ab_id in data.general_abilities:
general = "general"
elif ability.remaps_to_ability_id:
general = ability.remaps_to_ability_id
mismatch = ""
if ability.remaps_to_ability_id:
def check_mismatch(ability, parent, attr):
if getattr(ability, attr) != getattr(parent, attr):
return "%s: %s" % (attr, getattr(ability, attr))
parent = data.abilities[ability.remaps_to_ability_id]
mismatch = "; ".join(filter(None, [
check_mismatch(ability, parent, "available"),
check_mismatch(ability, parent, "target"),
check_mismatch(ability, parent, "allow_minimap"),
check_mismatch(ability, parent, "allow_autocast"),
check_mismatch(ability, parent, "is_building"),
check_mismatch(ability, parent, "footprint_radius"),
check_mismatch(ability, parent, "is_instant_placement"),
check_mismatch(ability, parent, "cast_range"),
]))
print(",".join(map(str, [
ability.ability_id,
ability.link_name,
ability.link_index,
ability.button_name,
ability.hotkey,
ability.friendly_name,
general,
mismatch,
])))
def generate_py_abilities(data):
"""Generate the list of functions in actions.py."""
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, '"%s"' % name, func, ab_id]
if general_id:
args.append(general_id)
print(" Function.ability(%s)," % ", ".join(str(v) for v in args))
func_ids = itertools.count(12) # Leave room for the ui funcs.
for ability in sorted(data.abilities.values(),
key=lambda a: sort_key(data, a)):
ab_id = ability.ability_id
if ab_id in skip_abilities or (ab_id not in data.general_abilities and
ab_id not in used_abilities):
continue
name = generate_name(ability).replace(" ", "_")
if ability.target in (sc_data.AbilityData.Target.Value("None"),
sc_data.AbilityData.PointOrNone):
print_action(next(func_ids), name + "_quick", "cmd_quick", ab_id,
ability.remaps_to_ability_id)
if ability.target != sc_data.AbilityData.Target.Value("None"):
print_action(next(func_ids), name+ "_screen", "cmd_screen", ab_id,
ability.remaps_to_ability_id)
if ability.allow_minimap:
print_action(next(func_ids), name + "_minimap", "cmd_minimap", ab_id,
ability.remaps_to_ability_id)
if ability.allow_autocast:
print_action(next(func_ids), name + "_autocast", "autocast", ab_id,
ability.remaps_to_ability_id)
def main(unused_argv):
data = get_data()
print("-" * 60)
if FLAGS.command == "csv":
generate_csv(data)
elif FLAGS.command == "python":
generate_py_abilities(data)
used_abilities = set(static_data.ABILITIES)
frivolous = {6, 7} # Dance and Cheer
# These need a slot id and so are exposed differently.
cancel_slot = {313, 1039, 305, 307, 309, 1832, 1834, 3672}
unload_unit = {410, 415, 397, 1440, 2373, 1409, 914, 3670}
skip_abilities = cancel_slot | unload_unit | frivolous
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/gen_actions.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run through a set of replays, generating new replays from them."""
import os
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import replay
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_string("input_dir", None, "Directory of replays to modify.")
flags.DEFINE_string("output_dir", None, "Where to write them.")
def main(_):
run_config = run_configs.get()
replay_list = sorted(run_config.replay_paths(FLAGS.input_dir))
print(len(replay_list), "replays found.\n")
version = replay.get_replay_version(run_config.replay_data(replay_list[0]))
run_config = run_configs.get(version=version) # Replace the run config.
with run_config.start(want_rgb=False) as controller:
for replay_path in replay_list:
replay_data = run_config.replay_data(replay_path)
info = controller.replay_info(replay_data)
print(" Starting replay: ".center(60, "-"))
print("Path:", replay_path)
print("Size:", len(replay_data), "bytes")
print(" Replay info: ".center(60, "-"))
print(info)
print("-" * 60)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=sc_pb.InterfaceOptions(score=True),
record_replay=True,
observed_player_id=1)
if info.local_map_path:
start_replay.map_data = run_config.map_data(info.local_map_path,
len(info.player_info))
controller.start_replay(start_replay)
while True:
controller.step(1000)
obs = controller.observe()
if obs.player_result:
print("Stepped", obs.observation.game_loop, "game loops")
break
replay_data = controller.save_replay()
replay_save_loc = os.path.join(FLAGS.output_dir,
os.path.basename(replay_path))
with open(replay_save_loc, "wb") as f:
f.write(replay_data)
print("Wrote replay, ", len(replay_data), " bytes to:", replay_save_loc)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/reencode_replays.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Download the battle.net cache files needed by replays.
Adapted from https://github.com/ggtracker/sc2reader .
"""
import binascii
import os
import urllib
from absl import app
from absl import flags
import mpyq
from s2protocol import versions as s2versions
from pysc2 import run_configs
FLAGS = flags.FLAGS
flags.DEFINE_string("bnet_base", None,
"Path to a Battle.net directory to update.")
DEPOT_URL_TEMPLATE = "http://us.depot.battle.net:1119/{hash}.{type}"
def mkdirs(*paths):
for path in paths:
if not os.path.exists(path):
os.makedirs(path)
def test_looks_like_battle_net(path):
path = path.rstrip("/").rstrip("\\")
if os.path.basename(path) != "Battle.net":
raise ValueError("Doesn't look like a Battle.net cache:", path)
if not os.path.isdir(os.path.join(path, "Cache")):
raise ValueError("Missing a Cache subdirectory:", path)
def replay_paths(paths):
"""A generator yielding the full path to the replays under `replay_dir`."""
for path in paths:
if path.lower().endswith(".sc2replay"):
yield path
else:
for f in os.listdir(path):
if f.lower().endswith(".sc2replay"):
yield os.path.join(path, f)
def update_battle_net_cache(replays, bnet_base):
"""Download the battle.net cache files needed by replays."""
test_looks_like_battle_net(bnet_base)
downloaded = 0
failed = set()
for replay_path in replays:
try:
archive = mpyq.MPQArchive(replay_path)
except ValueError:
print("Failed to parse replay:", replay_path)
continue
extracted = archive.extract()
contents = archive.header["user_data_header"]["content"]
header = s2versions.latest().decode_replay_header(contents)
base_build = header["m_version"]["m_baseBuild"]
prot = s2versions.build(base_build)
details_bytes = (extracted.get(b"replay.details") or
extracted.get(b"replay.details.backup"))
details = prot.decode_replay_details(details_bytes)
for map_handle in details["m_cacheHandles"]:
# server = map_handle[4:8].decode("utf-8").strip("\x00 ")
map_hash = binascii.b2a_hex(map_handle[8:]).decode("utf8")
file_type = map_handle[0:4].decode("utf8")
cache_path = os.path.join(
bnet_base, "Cache", map_hash[0:2], map_hash[2:4],
"%s.%s" % (map_hash, file_type))
url = DEPOT_URL_TEMPLATE.format(hash=map_hash, type=file_type)
if not os.path.exists(cache_path) and url not in failed:
mkdirs(os.path.dirname(cache_path))
print(url)
try:
urllib.request.urlretrieve(url, cache_path)
except urllib.error.HTTPError as e:
print("Download failed:", e)
failed.add(url)
else:
downloaded += 1
return downloaded
def main(argv):
replays = list(replay_paths(argv[1:]))
bnet_base = FLAGS.bnet_base or os.path.join(run_configs.get().data_dir,
"Battle.net")
print("Updating cache:", bnet_base)
print("Checking", len(replays), "replays")
downloaded = update_battle_net_cache(replays, bnet_base)
print("Downloaded", downloaded, "files")
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/update_battle_net_cache.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the list of versions for run_configs."""
from absl import app
import requests
# raw version of:
# https://github.com/Blizzard/s2client-proto/blob/master/buildinfo/versions.json
VERSIONS_FILE = "https://raw.githubusercontent.com/Blizzard/s2client-proto/master/buildinfo/versions.json"
def main(argv):
del argv # Unused.
versions = requests.get(VERSIONS_FILE).json()
for v in versions:
version_str = v["label"]
if version_str.count(".") == 1:
version_str += ".0"
print(' Version("%s", %i, "%s", None),' % (
version_str, v["base-version"], v["data-hash"]))
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/gen_versions.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/bin/__init__.py |
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test the apm values of various actions."""
import random
from absl import app
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import units
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import error_pb2 as sc_error
from s2clientprotocol import sc2api_pb2 as sc_pb
def get_units(obs, filter_fn=None, owner=None, unit_type=None, tag=None):
"""Return a dict of units that match the filter."""
if unit_type and not isinstance(unit_type, (list, tuple)):
unit_type = (unit_type,)
return {u.tag: u for u in obs.observation.raw_data.units # pylint: disable=g-complex-comprehension
if ((filter_fn is None or filter_fn(u)) and
(owner is None or u.owner == owner) and
(unit_type is None or u.unit_type in unit_type) and
(tag is None or u.tag == tag))}
def get_unit(*args, **kwargs):
"""Return the first unit that matches, or None."""
try:
return next(iter(get_units(*args, **kwargs).values()))
except StopIteration:
return None
def _xy_locs(mask):
"""Mask should be a set of bools from comparison with a feature layer."""
ys, xs = mask.nonzero()
return [point.Point(x, y) for x, y in zip(xs, ys)]
class Env(object):
"""Test the apm values of various actions."""
def __init__(self):
run_config = run_configs.get()
map_inst = maps.get("Flat64")
self._map_path = map_inst.path
self._map_data = map_inst.data(run_config)
self._sc2_proc = run_config.start(want_rgb=False)
self._controller = self._sc2_proc.controller
self._summary = []
self._features = None
def close(self):
self._controller.quit()
self._sc2_proc.close()
print(" apm name")
for name, info in self._summary:
print("%4d %s" % (info.player_info[0].player_apm, name))
def __enter__(self):
return self
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
self.close()
def __del__(self):
self.close()
def step(self, count=22):
self._controller.step(count)
return self._controller.observe()
def fl_obs(self, obs):
return self._features.transform_obs(obs)
def raw_unit_command(self, ability_id, unit_tags, pos=None, target=None):
"""Send a raw unit command."""
if isinstance(ability_id, str):
ability_id = actions.FUNCTIONS[ability_id].ability_id
action = sc_pb.Action()
cmd = action.action_raw.unit_command
cmd.ability_id = ability_id
if isinstance(unit_tags, (list, tuple)):
cmd.unit_tags.extend(unit_tags)
else:
cmd.unit_tags.append(unit_tags)
if pos:
cmd.target_world_space_pos.x = pos[0]
cmd.target_world_space_pos.y = pos[1]
elif target:
cmd.target_unit_tag = target
response = self._controller.act(action)
for result in response.result:
assert result == sc_error.Success
def fl_action(self, obs, act, *args):
return self._controller.act(self._features.transform_action(
obs.observation, actions.FUNCTIONS[act](*args), skip_available=True))
def check_apm(self, name):
"""Set up a game, yield, then check the apm in the replay."""
interface = sc_pb.InterfaceOptions(raw=True, score=False)
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 64
interface.feature_layer.resolution.y = 64
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
create = sc_pb.RequestCreateGame(
random_seed=1, local_map=sc_pb.LocalMap(map_path=self._map_path,
map_data=self._map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Protoss,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Protoss, options=interface)
self._controller.create_game(create)
self._controller.join_game(join)
self._info = self._controller.game_info()
self._features = features.features_from_game_info(
self._info, use_feature_units=True, use_raw_units=True)
self._map_size = point.Point.build(self._info.start_raw.map_size)
for i in range(60):
yield i, self.step()
data = self._controller.save_replay()
replay_info = self._controller.replay_info(data)
self._summary.append((name, replay_info))
def main(unused_argv):
env = Env()
def rand_fl_coord():
return (point.Point.unit_rand() * 64).floor()
def rand_world_coord():
return (point.Point.unit_rand() * 20).floor() + 20
def random_probe_loc(obs):
return random.choice(_xy_locs(
env.fl_obs(obs).feature_screen.unit_type == units.Protoss.Probe))
def random_probe_tag(obs):
return random.choice(get_units(obs, unit_type=units.Protoss.Probe).keys())
for i, obs in env.check_apm("no-op"):
pass
for i, obs in env.check_apm("fl stop, single probe"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Stop_quick", "now")
for i, obs in env.check_apm("fl smart, single probe, random location"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Smart_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("fl move, single probe, random location"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Move_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("fl stop, random probe"):
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Stop_quick", "now")
for i, obs in env.check_apm("fl move, random probe, random location"):
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Move_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("raw stop, random probe"):
env.raw_unit_command("Stop_quick", random_probe_tag(obs))
for i, obs in env.check_apm("raw move, random probe, random location"):
env.raw_unit_command("Move_screen", random_probe_tag(obs),
rand_world_coord())
probe = None
for i, obs in env.check_apm("raw move, single probe, random location"):
if not probe:
probe = random_probe_tag(obs)
env.raw_unit_command("Move_screen", probe, rand_world_coord())
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/check_apm.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run SC2 to play a game or a replay."""
import getpass
import platform
import sys
import time
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import renderer_human
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", True, "Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_bool("full_screen", False, "Whether to run full screen.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 1, "Game steps per observation.")
flags.DEFINE_bool("render_sync", False, "Turn on sync rendering.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
flags.DEFINE_integer("feature_camera_width", 24,
"Width of the feature layer camera.")
point_flag.DEFINE_point("rgb_screen_size", "256,192",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
point_flag.DEFINE_point("window_size", "640,480",
"Screen size if not full screen.")
flags.DEFINE_string("video", None, "Path to render a video of observations.")
flags.DEFINE_integer("max_game_steps", 0, "Total game steps to run.")
flags.DEFINE_integer("max_episode_steps", 0, "Total game steps per episode.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_enum("bot_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"AI race.")
flags.DEFINE_enum("difficulty", "very_easy", sc2_env.Difficulty._member_names_, # pylint: disable=protected-access
"Bot's strength.")
flags.DEFINE_enum("bot_build", "random", sc2_env.BotBuild._member_names_, # pylint: disable=protected-access
"Bot's build strategy.")
flags.DEFINE_bool("disable_fog", False, "Disable fog of war.")
flags.DEFINE_integer("observed_player", 1, "Which player to observe.")
flags.DEFINE_bool("profile", False, "Whether to turn on code profiling.")
flags.DEFINE_bool("trace", False, "Whether to trace the code execution.")
flags.DEFINE_bool("save_replay", True, "Whether to save a replay at the end.")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("battle_net_map", False, "Use the battle.net map version.")
flags.DEFINE_string("map_path", None, "Override the map for this replay.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
def main(unused_argv):
"""Run SC2 to play a game or a replay."""
if FLAGS.trace:
stopwatch.sw.trace()
elif FLAGS.profile:
stopwatch.sw.enable()
if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay):
sys.exit("Must supply either a map or replay.")
if FLAGS.replay and not FLAGS.replay.lower().endswith("sc2replay"):
sys.exit("Replay must end in .SC2Replay.")
if FLAGS.realtime and FLAGS.replay:
# TODO(tewalds): Support realtime in replays once the game supports it.
sys.exit("realtime isn't possible for replays yet.")
if FLAGS.render and (FLAGS.realtime or FLAGS.full_screen):
sys.exit("disable pygame rendering if you want realtime or full_screen.")
if platform.system() == "Linux" and (FLAGS.realtime or FLAGS.full_screen):
sys.exit("realtime and full_screen only make sense on Windows/MacOS.")
if not FLAGS.render and FLAGS.render_sync:
sys.exit("render_sync only makes sense with pygame rendering on.")
run_config = run_configs.get()
interface = sc_pb.InterfaceOptions()
interface.raw = FLAGS.render
interface.raw_affects_selection = True
interface.raw_crop_to_playable_area = True
interface.score = True
interface.show_cloaked = True
interface.show_burrowed_shadows = True
interface.show_placeholders = True
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
interface.feature_layer.width = FLAGS.feature_camera_width
FLAGS.feature_screen_size.assign_to(interface.feature_layer.resolution)
FLAGS.feature_minimap_size.assign_to(
interface.feature_layer.minimap_resolution)
interface.feature_layer.crop_to_playable_area = True
interface.feature_layer.allow_cheating_layers = True
if FLAGS.render and FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(interface.render.resolution)
FLAGS.rgb_minimap_size.assign_to(interface.render.minimap_resolution)
max_episode_steps = FLAGS.max_episode_steps
if FLAGS.map:
create = sc_pb.RequestCreateGame(
realtime=FLAGS.realtime,
disable_fog=FLAGS.disable_fog)
try:
map_inst = maps.get(FLAGS.map)
except maps.lib.NoMapError:
if FLAGS.battle_net_map:
create.battlenet_map_name = FLAGS.map
else:
raise
else:
if map_inst.game_steps_per_episode:
max_episode_steps = map_inst.game_steps_per_episode
if FLAGS.battle_net_map:
create.battlenet_map_name = map_inst.battle_net
else:
create.local_map.map_path = map_inst.path
create.local_map.map_data = map_inst.data(run_config)
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer,
race=sc2_env.Race[FLAGS.bot_race],
difficulty=sc2_env.Difficulty[FLAGS.difficulty],
ai_build=sc2_env.BotBuild[FLAGS.bot_build])
join = sc_pb.RequestJoinGame(
options=interface, race=sc2_env.Race[FLAGS.user_race],
player_name=FLAGS.user_name)
version = None
else:
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
disable_fog=FLAGS.disable_fog,
observed_player_id=FLAGS.observed_player)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
with run_config.start(
full_screen=FLAGS.full_screen,
window_size=FLAGS.window_size,
want_rgb=interface.HasField("render")) as controller:
if FLAGS.map:
controller.create_game(create)
controller.join_game(join)
else:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
map_path = FLAGS.map_path or info.local_map_path
if map_path:
start_replay.map_data = run_config.map_data(map_path,
len(info.player_info))
controller.start_replay(start_replay)
if FLAGS.render:
renderer = renderer_human.RendererHuman(
fps=FLAGS.fps, step_mul=FLAGS.step_mul,
render_sync=FLAGS.render_sync, video=FLAGS.video)
renderer.run(
run_config, controller, max_game_steps=FLAGS.max_game_steps,
game_steps_per_episode=max_episode_steps,
save_replay=FLAGS.save_replay)
else: # Still step forward so the Mac/Windows renderer works.
try:
while True:
frame_start_time = time.time()
if not FLAGS.realtime:
controller.step(FLAGS.step_mul)
obs = controller.observe()
if obs.player_result:
break
time.sleep(max(0, frame_start_time + 1 / FLAGS.fps - time.time()))
except KeyboardInterrupt:
pass
print("Score: ", obs.observation.score.score)
print("Result: ", obs.player_result)
if FLAGS.map and FLAGS.save_replay:
replay_save_loc = run_config.save_replay(
controller.save_replay(), "local", FLAGS.map)
print("Replay saved to:", replay_save_loc)
# Save scores so we know how the human player did.
with open(replay_save_loc.replace("SC2Replay", "txt"), "w") as f:
f.write("{}\n".format(obs.observation.score.score))
if FLAGS.profile:
print(stopwatch.sw)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/play.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run an agent."""
import importlib
import threading
from absl import app
from absl import flags
from pysc2 import maps
from pysc2.env import available_actions_printer
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import stopwatch
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", True, "Whether to render with pygame.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", None,
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", None,
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", None, sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", False,
"Whether to include feature units.")
flags.DEFINE_bool("use_raw_units", False,
"Whether to include raw units.")
flags.DEFINE_bool("disable_fog", False, "Whether to disable Fog of War.")
flags.DEFINE_integer("max_agent_steps", 0, "Total agent steps.")
flags.DEFINE_integer("game_steps_per_episode", None, "Game steps per episode.")
flags.DEFINE_integer("max_episodes", 0, "Total episodes.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent 1's race.")
flags.DEFINE_string("agent2", "Bot", "Second agent, either Bot or agent class.")
flags.DEFINE_string("agent2_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent2_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent 2's race.")
flags.DEFINE_enum("difficulty", "very_easy", sc2_env.Difficulty._member_names_, # pylint: disable=protected-access
"If agent2 is a built-in Bot, it's strength.")
flags.DEFINE_enum("bot_build", "random", sc2_env.BotBuild._member_names_, # pylint: disable=protected-access
"Bot's build strategy.")
flags.DEFINE_bool("profile", False, "Whether to turn on code profiling.")
flags.DEFINE_bool("trace", False, "Whether to trace the code execution.")
flags.DEFINE_integer("parallel", 1, "How many instances to run in parallel.")
flags.DEFINE_bool("save_replay", True, "Whether to save a replay at the end.")
flags.DEFINE_string("map", None, "Name of a map to use.")
flags.DEFINE_bool("battle_net_map", False, "Use the battle.net map version.")
flags.mark_flag_as_required("map")
def run_thread(agent_classes, players, map_name, visualize):
"""Run one thread worth of the environment with agents."""
with sc2_env.SC2Env(
map_name=map_name,
battle_net_map=FLAGS.battle_net_map,
players=players,
agent_interface_format=sc2_env.parse_agent_interface_format(
feature_screen=FLAGS.feature_screen_size,
feature_minimap=FLAGS.feature_minimap_size,
rgb_screen=FLAGS.rgb_screen_size,
rgb_minimap=FLAGS.rgb_minimap_size,
action_space=FLAGS.action_space,
use_feature_units=FLAGS.use_feature_units,
use_raw_units=FLAGS.use_raw_units),
step_mul=FLAGS.step_mul,
game_steps_per_episode=FLAGS.game_steps_per_episode,
disable_fog=FLAGS.disable_fog,
visualize=visualize) as env:
env = available_actions_printer.AvailableActionsPrinter(env)
agents = [agent_cls() for agent_cls in agent_classes]
run_loop.run_loop(agents, env, FLAGS.max_agent_steps, FLAGS.max_episodes)
if FLAGS.save_replay:
env.save_replay(agent_classes[0].__name__)
def main(unused_argv):
"""Run an agent."""
if FLAGS.trace:
stopwatch.sw.trace()
elif FLAGS.profile:
stopwatch.sw.enable()
map_inst = maps.get(FLAGS.map)
agent_classes = []
players = []
agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
agent_classes.append(agent_cls)
players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent_race],
FLAGS.agent_name or agent_name))
if map_inst.players >= 2:
if FLAGS.agent2 == "Bot":
players.append(sc2_env.Bot(sc2_env.Race[FLAGS.agent2_race],
sc2_env.Difficulty[FLAGS.difficulty],
sc2_env.BotBuild[FLAGS.bot_build]))
else:
agent_module, agent_name = FLAGS.agent2.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
agent_classes.append(agent_cls)
players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent2_race],
FLAGS.agent2_name or agent_name))
threads = []
for _ in range(FLAGS.parallel - 1):
t = threading.Thread(target=run_thread,
args=(agent_classes, players, FLAGS.map, False))
threads.append(t)
t.start()
run_thread(agent_classes, players, FLAGS.map, FLAGS.render)
for t in threads:
t.join()
if FLAGS.profile:
print(stopwatch.sw)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/agent.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the unit definitions for units.py."""
import collections
from absl import app
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import static_data
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
def get_data():
"""Get the game's static data from an actual game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get("Sequencer") # Arbitrary ladder map.
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
return controller.data_raw()
def generate_py_units(data):
"""Generate the list of units in units.py."""
units = collections.defaultdict(list)
for unit in sorted(data.units, key=lambda a: a.name):
if unit.unit_id in static_data.UNIT_TYPES:
units[unit.race].append(unit)
def print_race(name, race):
print("class %s(enum.IntEnum):" % name)
print(' """%s units."""' % name)
for unit in units[race]:
print(" %s = %s" % (unit.name, unit.unit_id))
print("\n")
print(" units.py ".center(60, "-"))
print_race("Neutral", sc_common.NoRace)
print_race("Protoss", sc_common.Protoss)
print_race("Terran", sc_common.Terran)
print_race("Zerg", sc_common.Zerg)
def generate_py_buffs(data):
"""Generate the list of buffs in buffs.py."""
print(" buffs.py ".center(60, "-"))
print("class Buffs(enum.IntEnum):")
print(' """The list of buffs, as returned from RequestData."""')
for buff in sorted(data.buffs, key=lambda a: a.name):
if buff.name and buff.buff_id in static_data.BUFFS:
print(" %s = %s" % (buff.name, buff.buff_id))
print("\n")
def generate_py_upgrades(data):
"""Generate the list of upgrades in upgrades.py."""
print(" upgrades.py ".center(60, "-"))
print("class Upgrades(enum.IntEnum):")
print(' """The list of upgrades, as returned from RequestData."""')
for upgrade in sorted(data.upgrades, key=lambda a: a.name):
if upgrade.name and upgrade.upgrade_id in static_data.UPGRADES:
print(" %s = %s" % (upgrade.name, upgrade.upgrade_id))
print("\n")
def main(unused_argv):
data = get_data()
generate_py_units(data)
generate_py_buffs(data)
generate_py_upgrades(data)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/gen_data.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the list of defined maps."""
from absl import app
from pysc2 import maps
def main(unused_argv):
for _, map_class in sorted(maps.get_maps().items()):
mp = map_class()
if mp.path:
print(mp, "\n")
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/map_list.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Play as a human against an agent by setting up a LAN game.
This needs to be called twice, once for the human, and once for the agent.
The human plays on the host. There you run it as:
$ python -m pysc2.bin.play_vs_agent --human --map <map> --remote <agent ip>
And on the machine the agent plays on:
$ python -m pysc2.bin.play_vs_agent --agent <import path>
The `--remote` arg is used to create an SSH tunnel to the remote agent's
machine, so can be dropped if it's running on the same machine.
SC2 is limited to only allow LAN games on localhost, so we need to forward the
ports between machines. SSH is used to do this with the `--remote` arg. If the
agent is on the same machine as the host, this arg can be dropped. SSH doesn't
forward UDP, so this also sets up a UDP proxy. As part of that it sets up a TCP
server that is also used as a settings server. Note that you won't have an
opportunity to give ssh a password, so you must use ssh keys for authentication.
"""
import getpass
import importlib
import platform
import sys
import time
from absl import app
from absl import flags
from absl import logging
import portpicker
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import lan_sc2_env
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import renderer_human
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", platform.system() == "Linux",
"Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent's race.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", "256",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", "FEATURES",
sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", False,
"Whether to include feature units.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_string("host", "127.0.0.1", "Game Host. Can be 127.0.0.1 or ::1")
flags.DEFINE_integer(
"config_port", 14380,
"Where to set/find the config port. The host starts a tcp server to share "
"the config with the client, and to proxy udp traffic if played over an "
"ssh tunnel. This sets that port, and is also the start of the range of "
"ports used for LAN play.")
flags.DEFINE_string("remote", None,
"Where to set up the ssh tunnels to the client.")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("human", False, "Whether to host a game as a human.")
def main(unused_argv):
if FLAGS.human:
human()
else:
agent()
def agent():
"""Run the agent, connecting to a (remote) host started independently."""
agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
logging.info("Starting agent:")
with lan_sc2_env.LanSC2Env(
host=FLAGS.host,
config_port=FLAGS.config_port,
race=sc2_env.Race[FLAGS.agent_race],
step_mul=FLAGS.step_mul,
realtime=FLAGS.realtime,
agent_interface_format=sc2_env.parse_agent_interface_format(
feature_screen=FLAGS.feature_screen_size,
feature_minimap=FLAGS.feature_minimap_size,
rgb_screen=FLAGS.rgb_screen_size,
rgb_minimap=FLAGS.rgb_minimap_size,
action_space=FLAGS.action_space,
use_unit_counts=True,
use_camera_position=True,
show_cloaked=True,
show_burrowed_shadows=True,
show_placeholders=True,
send_observation_proto=True,
crop_to_playable_area=True,
raw_crop_to_playable_area=True,
allow_cheating_layers=True,
add_cargo_to_units=True,
use_feature_units=FLAGS.use_feature_units),
visualize=FLAGS.render) as env:
agents = [agent_cls()]
logging.info("Connected, starting run_loop.")
try:
run_loop.run_loop(agents, env)
except lan_sc2_env.RestartError:
pass
logging.info("Done.")
def human():
"""Run a host which expects one player to connect remotely."""
run_config = run_configs.get()
map_inst = maps.get(FLAGS.map)
if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size:
logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb "
"observations.")
ports = [FLAGS.config_port + p for p in range(5)] # tcp + 2 * num_players
if not all(portpicker.is_port_free(p) for p in ports):
sys.exit("Need 5 free ports after the config port.")
proc = None
ssh_proc = None
tcp_conn = None
udp_sock = None
try:
proc = run_config.start(extra_ports=ports[1:], timeout_seconds=300,
host=FLAGS.host, window_loc=(50, 50))
tcp_port = ports[0]
settings = {
"remote": FLAGS.remote,
"game_version": proc.version.game_version,
"realtime": FLAGS.realtime,
"map_name": map_inst.name,
"map_path": map_inst.path,
"map_data": map_inst.data(run_config),
"ports": {
"server": {"game": ports[1], "base": ports[2]},
"client": {"game": ports[3], "base": ports[4]},
}
}
create = sc_pb.RequestCreateGame(
realtime=settings["realtime"],
local_map=sc_pb.LocalMap(map_path=settings["map_path"]))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Participant)
controller = proc.controller
controller.save_map(settings["map_path"], settings["map_data"])
controller.create_game(create)
if FLAGS.remote:
ssh_proc = lan_sc2_env.forward_ports(
FLAGS.remote, proc.host, [settings["ports"]["client"]["base"]],
[tcp_port, settings["ports"]["server"]["base"]])
print("-" * 80)
print("Join: play_vs_agent --host %s --config_port %s" % (proc.host,
tcp_port))
print("-" * 80)
tcp_conn = lan_sc2_env.tcp_server(
lan_sc2_env.Addr(proc.host, tcp_port), settings)
if FLAGS.remote:
udp_sock = lan_sc2_env.udp_server(
lan_sc2_env.Addr(proc.host, settings["ports"]["client"]["game"]))
lan_sc2_env.daemon_thread(
lan_sc2_env.tcp_to_udp,
(tcp_conn, udp_sock,
lan_sc2_env.Addr(proc.host, settings["ports"]["server"]["game"])))
lan_sc2_env.daemon_thread(lan_sc2_env.udp_to_tcp, (udp_sock, tcp_conn))
join = sc_pb.RequestJoinGame()
join.shared_port = 0 # unused
join.server_ports.game_port = settings["ports"]["server"]["game"]
join.server_ports.base_port = settings["ports"]["server"]["base"]
join.client_ports.add(game_port=settings["ports"]["client"]["game"],
base_port=settings["ports"]["client"]["base"])
join.race = sc2_env.Race[FLAGS.user_race]
join.player_name = FLAGS.user_name
if FLAGS.render:
join.options.raw = True
join.options.score = True
join.options.raw_affects_selection = True
join.options.raw_crop_to_playable_area = True
join.options.show_cloaked = True
join.options.show_burrowed_shadows = True
join.options.show_placeholders = True
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
fl = join.options.feature_layer
fl.width = 24
FLAGS.feature_screen_size.assign_to(fl.resolution)
FLAGS.feature_minimap_size.assign_to(fl.minimap_resolution)
if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(join.options.render.resolution)
FLAGS.rgb_minimap_size.assign_to(join.options.render.minimap_resolution)
controller.join_game(join)
if FLAGS.render:
renderer = renderer_human.RendererHuman(
fps=FLAGS.fps, render_feature_grid=False)
renderer.run(run_configs.get(), controller, max_episodes=1)
else: # Still step forward so the Mac/Windows renderer works.
while True:
frame_start_time = time.time()
if not FLAGS.realtime:
controller.step()
obs = controller.observe()
if obs.player_result:
break
time.sleep(max(0, frame_start_time - time.time() + 1 / FLAGS.fps))
except KeyboardInterrupt:
pass
finally:
if tcp_conn:
tcp_conn.close()
if proc:
proc.close()
if udp_sock:
udp_sock.close()
if ssh_proc:
ssh_proc.terminate()
for _ in range(5):
if ssh_proc.poll() is not None:
break
time.sleep(1)
if ssh_proc.poll() is None:
ssh_proc.kill()
ssh_proc.wait()
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/play_vs_agent.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the valid actions."""
from absl import app
from absl import flags
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point_flag
FLAGS = flags.FLAGS
point_flag.DEFINE_point("screen_size", "84", "Resolution for screen actions.")
point_flag.DEFINE_point("minimap_size", "64", "Resolution for minimap actions.")
flags.DEFINE_bool("hide_specific", False, "Hide the specific actions")
def main(unused_argv):
"""Print the valid actions."""
feats = features.Features(
# Actually irrelevant whether it's feature or rgb size.
features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(
screen=FLAGS.screen_size,
minimap=FLAGS.minimap_size)))
action_spec = feats.action_spec()
flattened = 0
count = 0
for func in action_spec.functions:
if FLAGS.hide_specific and actions.FUNCTIONS[func.id].general_id != 0:
continue
count += 1
act_flat = 1
for arg in func.args:
for size in arg.sizes:
act_flat *= size
flattened += act_flat
print(func.str(True))
print("Total base actions:", count)
print("Total possible actions (flattened):", flattened)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/valid_actions.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the list of available maps according to the game."""
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in sorted(available_maps.local_map_paths):
print(" ", m)
print()
print("Battle.net maps:")
for m in sorted(available_maps.battlenet_map_names):
print(" ", m)
if __name__ == "__main__":
app.run(main)
| pysc2-master | pysc2/bin/battle_net_maps.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that we blow up if SC2 thinks we did something wrong."""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import protocol
from pysc2.lib import remote_controller
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestProtocolError(utils.TestCase):
"""Verify that we blow up if SC2 thinks we did something wrong."""
def test_error(self):
with run_configs.get().start(want_rgb=False) as controller:
with self.assertRaises(remote_controller.RequestError):
controller.create_game(sc_pb.RequestCreateGame()) # Missing map, etc.
with self.assertRaises(protocol.ProtocolError):
controller.join_game(sc_pb.RequestJoinGame()) # No game to join.
def test_replay_a_replay(self):
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
map_inst = maps.get("Flat64")
map_data = map_inst.data(run_config)
interface = sc_pb.InterfaceOptions(raw=True)
# Play a quick game to generate a replay.
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=interface)
controller.create_game(create)
controller.join_game(join)
controller.step(100)
obs = controller.observe()
replay_data = controller.save_replay()
# Run through the replay verifying that it finishes but wasn't recording
# a replay.
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=map_data,
options=interface,
observed_player_id=1)
controller.start_replay(start_replay)
controller.step(1000)
obs2 = controller.observe()
self.assertEqual(obs.observation.game_loop, obs2.observation.game_loop)
with self.assertRaises(protocol.ProtocolError):
controller.save_replay()
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/protocol_error_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that every version in run_configs actually runs."""
from absl import logging
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
def major_version(v):
return ".".join(v.split(".")[:2])
def log_center(s, *args):
logging.info(((" " + s + " ") % args).center(80, "-"))
class TestVersions(absltest.TestCase):
def test_version_numbers(self):
run_config = run_configs.get()
failures = []
for game_version, version in sorted(run_config.get_versions().items()):
try:
self.assertEqual(game_version, version.game_version)
log_center("starting version check: %s", game_version)
run_config = run_configs.get(version=game_version)
with run_config.start(want_rgb=False) as controller:
ping = controller.ping()
logging.info("expected: %s", version)
logging.info("actual: %s", ", ".join(str(ping).strip().split("\n")))
self.assertEqual(version.build_version, ping.base_build)
if version.game_version != "latest":
self.assertEqual(major_version(ping.game_version),
major_version(version.game_version))
self.assertEqual(version.data_version.lower(),
ping.data_version.lower())
log_center("success: %s", game_version)
except: # pylint: disable=bare-except
log_center("failure: %s", game_version)
logging.exception("Failed")
failures.append(game_version)
self.assertEmpty(failures)
def test_versions_create_game(self):
run_config = run_configs.get()
failures = []
for game_version in sorted(run_config.get_versions().keys()):
try:
log_center("starting create game: %s", game_version)
run_config = run_configs.get(version=game_version)
with run_config.start(want_rgb=False) as controller:
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.score = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 84
interface.feature_layer.resolution.y = 84
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
map_inst = maps.get("Simple64")
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=interface)
controller.create_game(create)
controller.join_game(join)
for _ in range(5):
controller.step(16)
controller.observe()
log_center("success: %s", game_version)
except: # pylint: disable=bare-except
logging.exception("Failed")
log_center("failure: %s", game_version)
failures.append(game_version)
self.assertEmpty(failures)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/versions_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that multiplayer works independently of the SC2Env."""
import os
from absl import logging
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import point
from pysc2.lib import portspicker
from pysc2.lib import run_parallel
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
def print_stage(stage):
logging.info((" %s " % stage).center(80, "-"))
class TestMultiplayer(utils.TestCase):
def test_multi_player(self):
players = 2
run_config = run_configs.get()
parallel = run_parallel.RunParallel()
map_inst = maps.get("Simple64")
screen_size_px = point.Point(64, 64)
minimap_size_px = point.Point(32, 32)
interface = sc_pb.InterfaceOptions()
screen_size_px.assign_to(interface.feature_layer.resolution)
minimap_size_px.assign_to(interface.feature_layer.minimap_resolution)
# Reserve a whole bunch of ports for the weird multiplayer implementation.
ports = portspicker.pick_unused_ports(players * 2)
logging.info("Valid Ports: %s", ports)
# Actually launch the game processes.
print_stage("start")
sc2_procs = [run_config.start(extra_ports=ports, want_rgb=False)
for _ in range(players)]
controllers = [p.controller for p in sc2_procs]
try:
# Save the maps so they can access it.
map_path = os.path.basename(map_inst.path)
print_stage("save_map")
for c in controllers: # Skip parallel due to a race condition on Windows.
c.save_map(map_path, map_inst.data(run_config))
# Create the create request.
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(map_path=map_path))
for _ in range(players):
create.player_setup.add(type=sc_pb.Participant)
# Create the join request.
join = sc_pb.RequestJoinGame(race=sc_common.Random, options=interface)
join.shared_port = 0 # unused
join.server_ports.game_port = ports[0]
join.server_ports.base_port = ports[1]
join.client_ports.add(game_port=ports[2], base_port=ports[3])
# Play a few short games.
for _ in range(2): # 2 episodes
# Create and Join
print_stage("create")
controllers[0].create_game(create)
print_stage("join")
parallel.run((c.join_game, join) for c in controllers)
print_stage("run")
for game_loop in range(1, 10): # steps per episode
# Step the game
parallel.run(c.step for c in controllers)
# Observe
obs = parallel.run(c.observe for c in controllers)
for p_id, o in enumerate(obs):
self.assertEqual(o.observation.game_loop, game_loop)
self.assertEqual(o.observation.player_common.player_id, p_id + 1)
# Act
actions = [sc_pb.Action() for _ in range(players)]
for action in actions:
pt = (point.Point.unit_rand() * minimap_size_px).floor()
pt.assign_to(action.action_feature_layer.camera_move.center_minimap)
parallel.run((c.act, a) for c, a in zip(controllers, actions))
# Done this game.
print_stage("leave")
parallel.run(c.leave for c in controllers)
finally:
print_stage("quit")
# Done, shut down. Don't depend on parallel since it might be broken.
for c in controllers:
c.quit()
for p in sc2_procs:
p.close()
portspicker.return_ports(ports)
parallel.shutdown()
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/multi_player_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that the observations match the observation spec."""
from absl.testing import absltest
from pysc2.agents import random_agent
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestObservationSpec(utils.TestCase):
def test_observation_matches_obs_spec(self):
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.random),
sc2_env.Bot(sc2_env.Race.random, sc2_env.Difficulty.easy)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=(84, 87),
minimap=(64, 67)))) as env:
multiplayer_obs_spec = env.observation_spec()
self.assertIsInstance(multiplayer_obs_spec, tuple)
self.assertLen(multiplayer_obs_spec, 1)
obs_spec = multiplayer_obs_spec[0]
multiplayer_action_spec = env.action_spec()
self.assertIsInstance(multiplayer_action_spec, tuple)
self.assertLen(multiplayer_action_spec, 1)
action_spec = multiplayer_action_spec[0]
agent = random_agent.RandomAgent()
agent.setup(obs_spec, action_spec)
multiplayer_obs = env.reset()
agent.reset()
for _ in range(100):
self.assertIsInstance(multiplayer_obs, tuple)
self.assertLen(multiplayer_obs, 1)
raw_obs = multiplayer_obs[0]
obs = raw_obs.observation
self.check_observation_matches_spec(obs, obs_spec)
act = agent.step(raw_obs)
multiplayer_act = (act,)
multiplayer_obs = env.step(multiplayer_act)
def test_heterogeneous_observations(self):
with sc2_env.SC2Env(
map_name="Simple64",
players=[
sc2_env.Agent(sc2_env.Race.random),
sc2_env.Agent(sc2_env.Race.random)
],
agent_interface_format=[
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=(84, 87),
minimap=(64, 67)
)
),
sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(
screen=128,
minimap=64
)
)
]) as env:
obs_specs = env.observation_spec()
self.assertIsInstance(obs_specs, tuple)
self.assertLen(obs_specs, 2)
actions_specs = env.action_spec()
self.assertIsInstance(actions_specs, tuple)
self.assertLen(actions_specs, 2)
agents = []
for obs_spec, action_spec in zip(obs_specs, actions_specs):
agent = random_agent.RandomAgent()
agent.setup(obs_spec, action_spec)
agent.reset()
agents.append(agent)
time_steps = env.reset()
for _ in range(100):
self.assertIsInstance(time_steps, tuple)
self.assertLen(time_steps, 2)
actions = []
for i, agent in enumerate(agents):
time_step = time_steps[i]
obs = time_step.observation
self.check_observation_matches_spec(obs, obs_specs[i])
actions.append(agent.step(time_step))
time_steps = env.step(actions)
def check_observation_matches_spec(self, obs, obs_spec):
self.assertCountEqual(obs_spec.keys(), obs.keys())
for k, o in obs.items():
if k == "map_name":
self.assertIsInstance(o, str)
continue
descr = "%s: spec: %s != obs: %s" % (k, obs_spec[k], o.shape)
if o.shape == (0,): # Empty tensor can't have a shape.
self.assertIn(0, obs_spec[k], descr)
else:
self.assertEqual(len(obs_spec[k]), len(o.shape), descr)
for a, b in zip(obs_spec[k], o.shape):
if a != 0:
self.assertEqual(a, b, descr)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/obs_spec_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run a random agent for a few steps."""
from absl.testing import absltest
from absl.testing import parameterized
from pysc2.agents import random_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestRandomAgent(parameterized.TestCase, utils.TestCase):
@parameterized.named_parameters(
("features", sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64))),
("rgb", sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(screen=128, minimap=64))),
("all", sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64),
rgb_dimensions=sc2_env.Dimensions(screen=128, minimap=64),
action_space=sc2_env.ActionSpace.FEATURES,
use_unit_counts=True,
use_feature_units=True)),
)
def test_random_agent(self, agent_interface_format):
steps = 250
step_mul = 8
with sc2_env.SC2Env(
map_name=["Simple64", "Simple96"],
players=[sc2_env.Agent([sc2_env.Race.random, sc2_env.Race.terran]),
sc2_env.Bot([sc2_env.Race.zerg, sc2_env.Race.protoss],
sc2_env.Difficulty.easy,
[sc2_env.BotBuild.rush, sc2_env.BotBuild.timing])],
agent_interface_format=agent_interface_format,
step_mul=step_mul,
game_steps_per_episode=steps * step_mul//3) as env:
agent = random_agent.RandomAgent()
run_loop.run_loop([agent], env, steps)
self.assertEqual(agent.steps, steps)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/random_agent_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test host_remote_agent.py."""
from absl.testing import absltest
from pysc2.env import host_remote_agent
from pysc2.lib import remote_controller
from pysc2.lib import run_parallel
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
NUM_MATCHES = 2
STEPS = 100
class TestHostRemoteAgent(utils.TestCase):
def testVsBot(self):
bot_first = True
for _ in range(NUM_MATCHES):
with host_remote_agent.VsBot() as game:
game.create_game(
map_name="Simple64",
bot_difficulty=sc_pb.VeryHard,
bot_first=bot_first)
controller = remote_controller.RemoteController(
host=game.host,
port=game.host_port)
join = sc_pb.RequestJoinGame(options=sc_pb.InterfaceOptions(raw=True))
join.race = sc_common.Random
controller.join_game(join)
for _ in range(STEPS):
controller.step()
response_observation = controller.observe()
if response_observation.player_result:
break
controller.leave()
controller.close()
bot_first = not bot_first
def testVsAgent(self):
parallel = run_parallel.RunParallel()
for _ in range(NUM_MATCHES):
with host_remote_agent.VsAgent() as game:
game.create_game("Simple64")
controllers = [
remote_controller.RemoteController( # pylint:disable=g-complex-comprehension
host=host,
port=host_port)
for host, host_port in zip(game.hosts, game.host_ports)]
join = sc_pb.RequestJoinGame(options=sc_pb.InterfaceOptions(raw=True))
join.race = sc_common.Random
join.shared_port = 0
join.server_ports.game_port = game.lan_ports[0]
join.server_ports.base_port = game.lan_ports[1]
join.client_ports.add(
game_port=game.lan_ports[2],
base_port=game.lan_ports[3])
parallel.run((c.join_game, join) for c in controllers)
for _ in range(STEPS):
parallel.run(c.step for c in controllers)
response_observations = [c.observe() for c in controllers]
if response_observations[0].player_result:
break
parallel.run(c.leave for c in controllers)
parallel.run(c.close for c in controllers)
parallel.shutdown()
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/host_remote_agent_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Solve the nm_easy map using a fixed policy by reading the feature layers."""
from absl.testing import absltest
from pysc2.agents import scripted_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestEasy(utils.TestCase):
steps = 200
step_mul = 16
def test_move_to_beacon(self):
with sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.MoveToBeacon()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShards()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards_feature_units(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64),
use_feature_units=True),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShardsFeatureUnits()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards_raw(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
action_space=sc2_env.ActionSpace.RAW, # or: use_raw_actions=True,
use_raw_units=True),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShardsRaw()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_defeat_roaches(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.DefeatRoaches()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_defeat_roaches_raw(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
action_space=sc2_env.ActionSpace.RAW, # or: use_raw_actions=True,
use_raw_units=True),
step_mul=self.step_mul,
game_steps_per_episode=100*self.steps * self.step_mul) as env:
agent = scripted_agent.DefeatRoachesRaw()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/easy_scripted_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/tests/__init__.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""For test code - build a dummy ResponseObservation proto.
This can then e.g. be passed to features.transform_obs.
"""
import math
import numpy as np
from pysc2.lib import features
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2 as sc_pb
from s2clientprotocol import score_pb2
class Unit(object):
"""Class to hold unit data for the builder."""
def __init__(
self,
unit_type, # see lib/units.py
player_relative, # features.PlayerRelative,
health,
shields=0,
energy=0,
transport_slots_taken=0,
build_progress=1.0):
self.unit_type = unit_type
self.player_relative = player_relative
self.health = health
self.shields = shields
self.energy = energy
self.transport_slots_taken = transport_slots_taken
self.build_progress = build_progress
def fill(self, unit_proto):
"""Fill a proto unit data object from this Unit."""
unit_proto.unit_type = self.unit_type
unit_proto.player_relative = self.player_relative
unit_proto.health = self.health
unit_proto.shields = self.shields
unit_proto.energy = self.energy
unit_proto.transport_slots_taken = self.transport_slots_taken
unit_proto.build_progress = self.build_progress
def as_array(self):
"""Return the unit represented as a numpy array."""
return np.array([
self.unit_type,
self.player_relative,
self.health,
self.shields,
self.energy,
self.transport_slots_taken,
int(self.build_progress * 100)
], dtype=np.int32)
def as_dict(self):
return vars(self)
class FeatureUnit(object):
"""Class to hold feature unit data for the builder."""
def __init__(
self,
unit_type, # see lib/units
alliance, # features.PlayerRelative,
owner, # 1-15, 16=neutral
pos, # common_pb2.Point,
radius,
health,
health_max,
is_on_screen,
shield=0,
shield_max=0,
energy=0,
energy_max=0,
cargo_space_taken=0,
cargo_space_max=0,
build_progress=1.0,
facing=0.0,
display_type=raw_pb2.Visible, # raw_pb.DisplayType
cloak=raw_pb2.NotCloaked, # raw_pb.CloakState
is_selected=False,
is_blip=False,
is_powered=True,
mineral_contents=0,
vespene_contents=0,
assigned_harvesters=0,
ideal_harvesters=0,
weapon_cooldown=0.0):
self.unit_type = unit_type
self.alliance = alliance
self.owner = owner
self.pos = pos
self.radius = radius
self.health = health
self.health_max = health_max
self.is_on_screen = is_on_screen
self.shield = shield
self.shield_max = shield_max
self.energy = energy
self.energy_max = energy_max
self.cargo_space_taken = cargo_space_taken
self.cargo_space_max = cargo_space_max
self.build_progress = build_progress
self.facing = facing
self.display_type = display_type
self.cloak = cloak
self.is_selected = is_selected
self.is_blip = is_blip
self.is_powered = is_powered
self.mineral_contents = mineral_contents
self.vespene_contents = vespene_contents
self.assigned_harvesters = assigned_harvesters
self.ideal_harvesters = ideal_harvesters
self.weapon_cooldown = weapon_cooldown
def as_dict(self):
return vars(self)
class Builder(object):
"""For test code - build a dummy ResponseObservation proto."""
def __init__(self, obs_spec):
self._game_loop = 1
self._player_common = sc_pb.PlayerCommon(
player_id=1,
minerals=20,
vespene=50,
food_cap=36,
food_used=21,
food_army=6,
food_workers=15,
idle_worker_count=2,
army_count=6,
warp_gate_count=0,
larva_count=0,
)
self._score = 300
self._score_details = score_pb2.ScoreDetails(
idle_production_time=0,
idle_worker_time=0,
total_value_units=190,
total_value_structures=230,
killed_value_units=0,
killed_value_structures=0,
collected_minerals=2130,
collected_vespene=560,
collection_rate_minerals=50,
collection_rate_vespene=20,
spent_minerals=2000,
spent_vespene=500,
)
self._obs_spec = obs_spec
self._single_select = None
self._multi_select = None
self._build_queue = None
self._production = None
self._feature_units = None
def game_loop(self, game_loop):
self._game_loop = game_loop
return self
# pylint:disable=unused-argument
def player_common(
self,
player_id=None,
minerals=None,
vespene=None,
food_cap=None,
food_used=None,
food_army=None,
food_workers=None,
idle_worker_count=None,
army_count=None,
warp_gate_count=None,
larva_count=None):
"""Update some or all of the fields in the PlayerCommon data."""
args = dict(locals())
for key, value in args.items():
if value is not None and key != 'self':
setattr(self._player_common, key, value)
return self
def score(self, score):
self._score = score
return self
def score_details(
self,
idle_production_time=None,
idle_worker_time=None,
total_value_units=None,
total_value_structures=None,
killed_value_units=None,
killed_value_structures=None,
collected_minerals=None,
collected_vespene=None,
collection_rate_minerals=None,
collection_rate_vespene=None,
spent_minerals=None,
spent_vespene=None):
"""Update some or all of the fields in the ScoreDetails data."""
args = dict(locals())
for key, value in args.items():
if value is not None and key != 'self':
setattr(self._score_details, key, value)
return self
# pylint:enable=unused-argument
def score_by_category(
self, entry_name, none, army, economy, technology, upgrade):
field = getattr(self._score_details, entry_name)
field.CopyFrom(
score_pb2.CategoryScoreDetails(
none=none,
army=army,
economy=economy,
technology=technology,
upgrade=upgrade))
def score_by_vital(self, entry_name, life, shields, energy):
field = getattr(self._score_details, entry_name)
field.CopyFrom(
score_pb2.VitalScoreDetails(
life=life,
shields=shields,
energy=energy))
def single_select(self, unit):
self._single_select = unit
return self
def multi_select(self, units):
self._multi_select = units
return self
def build_queue(self, build_queue, production=None):
self._build_queue = build_queue
self._production = production
return self
def feature_units(self, feature_units):
self._feature_units = feature_units
return self
def build(self):
"""Builds and returns a proto ResponseObservation."""
response_observation = sc_pb.ResponseObservation()
obs = response_observation.observation
obs.game_loop = self._game_loop
obs.player_common.CopyFrom(self._player_common)
obs.abilities.add(ability_id=1, requires_point=True) # Smart
obs.score.score = self._score
obs.score.score_details.CopyFrom(self._score_details)
def fill(image_data, size, bits):
image_data.bits_per_pixel = bits
image_data.size.y = size[0]
image_data.size.x = size[1]
image_data.data = b'\0' * int(math.ceil(size[0] * size[1] * bits / 8))
if 'feature_screen' in self._obs_spec:
for feature in features.SCREEN_FEATURES:
fill(getattr(obs.feature_layer_data.renders, feature.name),
self._obs_spec['feature_screen'][1:], 8)
if 'feature_minimap' in self._obs_spec:
for feature in features.MINIMAP_FEATURES:
fill(getattr(obs.feature_layer_data.minimap_renders, feature.name),
self._obs_spec['feature_minimap'][1:], 8)
if 'rgb_screen' in self._obs_spec:
fill(obs.render_data.map, self._obs_spec['rgb_screen'][:2], 24)
if 'rgb_minimap' in self._obs_spec:
fill(obs.render_data.minimap, self._obs_spec['rgb_minimap'][:2], 24)
if self._single_select:
self._single_select.fill(obs.ui_data.single.unit)
if self._multi_select:
for unit in self._multi_select:
obs.ui_data.multi.units.add(**unit.as_dict())
if self._build_queue:
for unit in self._build_queue:
obs.ui_data.production.build_queue.add(**unit.as_dict())
if self._production:
for item in self._production:
obs.ui_data.production.production_queue.add(**item)
if self._feature_units:
for tag, feature_unit in enumerate(self._feature_units, 1):
args = dict(tag=tag)
args.update(feature_unit.as_dict())
obs.raw_data.units.add(**args)
return response_observation
| pysc2-master | pysc2/tests/dummy_observation.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that a game and replay have equivalent observations and actions.
Here we verify that the observations processed by replays match the original
observations of the gameplay.
"""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import renderer_ascii
from pysc2.lib import units
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
_EMPTY = 0
def identity_function(name, args):
return lambda _: actions.FUNCTIONS[name](*args)
def any_point(unit_type, obs):
unit_layer = obs.feature_screen.unit_type
y, x = (unit_layer == unit_type).nonzero()
if not y.any():
return None, None
return [x[-1], y[-1]]
def avg_point(unit_type, obs):
unit_layer = obs.feature_screen.unit_type
y, x = (unit_layer == unit_type).nonzero()
if not y.any():
return None, None
return [int(x.mean()), int(y.mean())]
def select(func, unit_type):
return lambda o: actions.FUNCTIONS.select_point('select', func(unit_type, o))
class Config(object):
"""Holds the configuration options."""
def __init__(self):
# Environment.
self.map_name = 'Flat64'
screen_resolution = point.Point(32, 32)
minimap_resolution = point.Point(32, 32)
self.camera_width = 24
self.random_seed = 42
self.interface = sc_pb.InterfaceOptions(
raw=True, score=True,
feature_layer=sc_pb.SpatialCameraSetup(width=self.camera_width))
screen_resolution.assign_to(self.interface.feature_layer.resolution)
minimap_resolution.assign_to(
self.interface.feature_layer.minimap_resolution)
# Hard code an action sequence.
# TODO(petkoig): Consider whether the Barracks and Supply Depot positions
# need to be dynamically determined.
self.actions = {
507: select(any_point, units.Terran.SCV),
963: identity_function('Build_SupplyDepot_screen', ['now', [25, 15]]),
1152: select(avg_point, units.Terran.CommandCenter),
1320: identity_function('Train_SCV_quick', ['now']),
1350: identity_function('Train_SCV_quick', ['now']),
1393: identity_function('Train_SCV_quick', ['now']),
1437: identity_function('Train_SCV_quick', ['now']),
1522: select(any_point, units.Terran.SCV),
1548: identity_function('Build_Barracks_screen', ['now', [25, 25]]),
1752: select(avg_point, units.Terran.CommandCenter),
1937: identity_function('Train_SCV_quick', ['now']),
2400: select(avg_point, units.Terran.Barracks),
2700: identity_function('Train_Marine_quick', ['now']),
3300: identity_function('select_army', ['select']),
}
self.num_observations = max(self.actions.keys()) + 2
self.player_id = 1
class GameController(object):
"""Wrapper class for interacting with the game in play/replay mode."""
def __init__(self, config):
"""Constructs the game controller object.
Args:
config: Interface configuration options.
"""
self._config = config
self._sc2_proc = None
self._controller = None
self._initialize()
def _initialize(self):
"""Initialize play/replay connection."""
run_config = run_configs.get()
self._map_inst = maps.get(self._config.map_name)
self._map_data = self._map_inst.data(run_config)
self._sc2_proc = run_config.start(
want_rgb=self._config.interface.HasField('render'))
self._controller = self._sc2_proc.controller
def start_replay(self, replay_data):
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=self._map_data,
options=self._config.interface,
disable_fog=False,
observed_player_id=self._config.player_id)
self._controller.start_replay(start_replay)
def create_game(self):
create = sc_pb.RequestCreateGame(
random_seed=self._config.random_seed,
local_map=sc_pb.LocalMap(
map_path=self._map_inst.path, map_data=self._map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer,
race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(
race=sc_common.Terran,
options=self._config.interface)
self._controller.create_game(create)
self._controller.join_game(join)
@property
def controller(self):
return self._controller
def close(self):
"""Close the controller connection."""
if self._controller:
self._controller.quit()
self._controller = None
if self._sc2_proc:
self._sc2_proc.close()
self._sc2_proc = None
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.close()
class ReplayObsTest(utils.TestCase):
def _get_replay_data(self, controller, config):
"""Runs a replay to get the replay data."""
f = features.features_from_game_info(game_info=controller.game_info())
observations = {}
last_actions = []
for _ in range(config.num_observations):
raw_obs = controller.observe()
o = raw_obs.observation
obs = f.transform_obs(raw_obs)
if raw_obs.action_errors:
print('action errors:', raw_obs.action_errors)
if o.game_loop == 2:
# Center camera is initiated automatically by the game and reported
# at frame 2.
last_actions = [actions.FUNCTIONS.move_camera.id]
self.assertEqual(last_actions, list(obs.last_actions))
unit_type = obs.feature_screen.unit_type
observations[o.game_loop] = unit_type
if o.game_loop in config.actions:
func = config.actions[o.game_loop](obs)
print(renderer_ascii.screen(obs))
scv_y, scv_x = (units.Terran.SCV == unit_type).nonzero()
print('scv locations: ', sorted(list(zip(scv_x, scv_y))))
print('available actions: ', list(sorted(obs.available_actions)))
print('Making action: %s' % (func,))
# Ensure action is available.
# If a build action is available, we have managed to target an SCV.
self.assertIn(func.function, obs.available_actions)
if (func.function in
(actions.FUNCTIONS.Build_SupplyDepot_screen.id,
actions.FUNCTIONS.Build_Barracks_screen.id)):
# Ensure we can build on that position.
x, y = func.arguments[1]
self.assertEqual(_EMPTY, unit_type[y, x])
action = f.transform_action(o, func)
last_actions = [func.function]
controller.act(action)
else:
last_actions = []
controller.step()
replay_data = controller.save_replay()
return replay_data, observations
def _process_replay(self, controller, observations, config):
f = features.features_from_game_info(game_info=controller.game_info())
while True:
o = controller.observe()
obs = f.transform_obs(o)
if o.player_result: # end of game
break
unit_type = obs.feature_screen.unit_type
self.assertEqual(
tuple(observations[o.observation.game_loop].flatten()),
tuple(unit_type.flatten()))
self.assertIn(len(o.actions), (0, 1), 'Expected 0 or 1 action')
if o.actions:
func = f.reverse_action(o.actions[0])
# Action is reported one frame later.
executed = config.actions.get(o.observation.game_loop - 1, None)
executed_func = executed(obs) if executed else None
print('%4d Sent: %s' % (o.observation.game_loop, executed_func))
print('%4d Returned: %s' % (o.observation.game_loop, func))
if o.observation.game_loop == 2:
# Center camera is initiated automatically by the game and reported
# at frame 2.
self.assertEqual(actions.FUNCTIONS.move_camera.id, func.function)
continue
self.assertEqual(func.function, executed_func.function)
if func.function != actions.FUNCTIONS.select_point.id:
# select_point likes to return Toggle instead of Select.
self.assertEqual(func.arguments, executed_func.arguments)
self.assertEqual(func.function, obs.last_actions[0])
controller.step()
return observations
def test_replay_observations_match(self):
config = Config()
with GameController(config) as game_controller:
game_controller.create_game()
replay_data, observations = self._get_replay_data(
game_controller.controller, config)
game_controller.start_replay(replay_data)
self._process_replay(game_controller.controller, observations, config)
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/tests/replay_obs_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that stepping without observing works correctly for multiple players."""
from absl.testing import absltest
from pysc2.env import sc2_env
from pysc2.lib import actions
from pysc2.tests import utils
AGENT_INTERFACE_FORMAT = sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=32, minimap=32)
)
class StepMulOverrideTest(utils.TestCase):
def test_returns_game_loop_zero_on_first_step_despite_override(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.random)],
step_mul=1,
agent_interface_format=AGENT_INTERFACE_FORMAT) as env:
timestep = env.step(
actions=[actions.FUNCTIONS.no_op()],
step_mul=1234)
self.assertEqual(
timestep[0].observation.game_loop[0],
0)
def test_respects_override(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.random)],
step_mul=1,
agent_interface_format=AGENT_INTERFACE_FORMAT) as env:
expected_game_loop = 0
for delta in range(10):
timestep = env.step(
actions=[actions.FUNCTIONS.no_op()],
step_mul=delta)
expected_game_loop += delta
self.assertEqual(
timestep[0].observation.game_loop[0],
expected_game_loop)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/step_mul_override_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import units
from pysc2.tests import dummy_observation
from s2clientprotocol import common_pb2
_PROBE = dummy_observation.Unit(
units.Protoss.Probe, features.PlayerRelative.SELF, 20, 20, 0, 0, 1.0)
_ZEALOT = dummy_observation.Unit(
units.Protoss.Zealot, features.PlayerRelative.SELF, 100, 50, 0, 0, 1.0)
_MOTHERSHIP = dummy_observation.Unit(
units.Protoss.Mothership, features.PlayerRelative.SELF, 350, 7, 200, 0, 1.0)
class DummyObservationTest(parameterized.TestCase):
def setUp(self):
super(DummyObservationTest, self).setUp()
self._features = features.Features(
features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(
screen=(64, 60), minimap=(32, 28)),
rgb_dimensions=features.Dimensions(
screen=(128, 124), minimap=(64, 60)),
action_space=actions.ActionSpace.FEATURES,
use_feature_units=True
),
map_size=point.Point(256, 256)
)
self._obs_spec = self._features.observation_spec()
self._builder = dummy_observation.Builder(self._obs_spec)
def testFeatureScreenMatchesSpec(self):
obs = self._get_obs()
for f in features.SCREEN_FEATURES:
self._check_layer(
getattr(obs.feature_layer_data.renders, f.name), 64, 60, 8)
def testFeatureMinimapMatchesSpec(self):
obs = self._get_obs()
for f in features.MINIMAP_FEATURES:
self._check_layer(
getattr(obs.feature_layer_data.minimap_renders, f.name), 32, 28, 8)
def testRgbScreenMatchesSpec(self):
obs = self._get_obs()
self._check_layer(obs.render_data.map, 128, 124, 24)
def testGameLoopCanBeSet(self):
self._builder.game_loop(1234)
obs = self._get_obs()
self.assertEqual(obs.game_loop, 1234)
def testPlayerCommonCanBeSet(self):
self._builder.player_common(
minerals=1000,
vespene=200,
food_cap=200,
food_used=198,
food_army=140,
food_workers=58,
army_count=92,
warp_gate_count=7,
larva_count=15)
obs = self._get_obs()
self.assertEqual(obs.player_common.player_id, 1) # (we didn't set it)
self.assertEqual(obs.player_common.minerals, 1000)
self.assertEqual(obs.player_common.vespene, 200)
self.assertEqual(obs.player_common.food_cap, 200)
self.assertEqual(obs.player_common.food_used, 198)
self.assertEqual(obs.player_common.food_army, 140)
self.assertEqual(obs.player_common.food_workers, 58)
self.assertEqual(obs.player_common.idle_worker_count, 2) # (didn't set it)
self.assertEqual(obs.player_common.army_count, 92)
self.assertEqual(obs.player_common.warp_gate_count, 7)
self.assertEqual(obs.player_common.larva_count, 15)
def testScoreCanBeSet(self):
self._builder.score(54321)
obs = self._get_obs()
self.assertEqual(obs.score.score, 54321)
def testScoreDetailsCanBeSet(self):
self._builder.score_details(
idle_production_time=1,
idle_worker_time=2,
total_value_units=3,
killed_value_units=5,
killed_value_structures=6,
collected_minerals=7,
collected_vespene=8,
collection_rate_minerals=9,
collection_rate_vespene=10,
spent_minerals=11,
spent_vespene=12,
)
obs = self._get_obs()
self.assertEqual(obs.score.score_details.idle_production_time, 1)
self.assertEqual(obs.score.score_details.idle_worker_time, 2)
self.assertEqual(obs.score.score_details.total_value_units, 3)
self.assertEqual(obs.score.score_details.total_value_structures, 230)
self.assertEqual(obs.score.score_details.killed_value_units, 5)
self.assertEqual(obs.score.score_details.killed_value_structures, 6)
self.assertEqual(obs.score.score_details.collected_minerals, 7)
self.assertEqual(obs.score.score_details.collected_vespene, 8)
self.assertEqual(obs.score.score_details.collection_rate_minerals, 9)
self.assertEqual(obs.score.score_details.collection_rate_vespene, 10)
self.assertEqual(obs.score.score_details.spent_minerals, 11)
self.assertEqual(obs.score.score_details.spent_vespene, 12)
def testScoreByCategorySpec(self):
# Note that if these dimensions are changed, client code is liable to break.
np.testing.assert_array_equal(
self._obs_spec.score_by_category,
np.array([11, 5], dtype=np.int32))
@parameterized.parameters([entry.name for entry in features.ScoreByCategory])
def testScoreByCategory(self, entry_name):
self._builder.score_by_category(
entry_name,
none=10,
army=1200,
economy=400,
technology=100,
upgrade=200)
response_observation = self._builder.build()
obs = response_observation.observation
entry = getattr(obs.score.score_details, entry_name)
self.assertEqual(entry.none, 10)
self.assertEqual(entry.army, 1200)
self.assertEqual(entry.economy, 400)
self.assertEqual(entry.technology, 100)
self.assertEqual(entry.upgrade, 200)
# Check the transform_obs does what we expect, too.
transformed_obs = self._features.transform_obs(response_observation)
transformed_entry = getattr(transformed_obs.score_by_category, entry_name)
self.assertEqual(transformed_entry.none, 10)
self.assertEqual(transformed_entry.army, 1200)
self.assertEqual(transformed_entry.economy, 400)
self.assertEqual(transformed_entry.technology, 100)
self.assertEqual(transformed_entry.upgrade, 200)
def testScoreByVitalSpec(self):
# Note that if these dimensions are changed, client code is liable to break.
np.testing.assert_array_equal(
self._obs_spec.score_by_vital,
np.array([3, 3], dtype=np.int32))
@parameterized.parameters([entry.name for entry in features.ScoreByVital])
def testScoreByVital(self, entry_name):
self._builder.score_by_vital(
entry_name,
life=1234,
shields=45,
energy=423)
response_observation = self._builder.build()
obs = response_observation.observation
entry = getattr(obs.score.score_details, entry_name)
self.assertEqual(entry.life, 1234)
self.assertEqual(entry.shields, 45)
self.assertEqual(entry.energy, 423)
# Check the transform_obs does what we expect, too.
transformed_obs = self._features.transform_obs(response_observation)
transformed_entry = getattr(transformed_obs.score_by_vital, entry_name)
self.assertEqual(transformed_entry.life, 1234)
self.assertEqual(transformed_entry.shields, 45)
self.assertEqual(transformed_entry.energy, 423)
def testRgbMinimapMatchesSpec(self):
obs = self._get_obs()
self._check_layer(obs.render_data.minimap, 64, 60, 24)
def testNoSingleSelect(self):
obs = self._get_obs()
self.assertFalse(obs.ui_data.HasField("single"))
def testWithSingleSelect(self):
self._builder.single_select(_PROBE)
obs = self._get_obs()
self._check_unit(obs.ui_data.single.unit, _PROBE)
def testNoMultiSelect(self):
obs = self._get_obs()
self.assertFalse(obs.ui_data.HasField("multi"))
def testWithMultiSelect(self):
nits = [_MOTHERSHIP, _PROBE, _PROBE, _ZEALOT]
self._builder.multi_select(nits)
obs = self._get_obs()
self.assertLen(obs.ui_data.multi.units, 4)
for proto, builder in zip(obs.ui_data.multi.units, nits):
self._check_unit(proto, builder)
def testBuildQueue(self):
nits = [_MOTHERSHIP, _PROBE]
production = [
{"ability_id": actions.FUNCTIONS.Train_Mothership_quick.ability_id,
"build_progress": 0.5},
{"ability_id": actions.FUNCTIONS.Train_Probe_quick.ability_id,
"build_progress": 0},
{"ability_id": actions.FUNCTIONS.Research_ShadowStrike_quick.ability_id,
"build_progress": 0},
]
self._builder.build_queue(nits, production)
obs = self._get_obs()
self.assertLen(obs.ui_data.production.build_queue, 2)
for proto, builder in zip(obs.ui_data.production.build_queue, nits):
self._check_unit(proto, builder)
self.assertLen(obs.ui_data.production.production_queue, 3)
for proto, p in zip(obs.ui_data.production.production_queue, production):
self.assertEqual(proto.ability_id, p["ability_id"])
self.assertEqual(proto.build_progress, p["build_progress"])
def testFeatureUnitsAreAdded(self):
feature_units = [
dummy_observation.FeatureUnit(
units.Protoss.Probe,
features.PlayerRelative.SELF,
owner=1,
pos=common_pb2.Point(x=10, y=10, z=0),
radius=1.0,
health=10,
health_max=20,
is_on_screen=True,
shield=0,
shield_max=20
),
dummy_observation.FeatureUnit(
units.Terran.Marine,
features.PlayerRelative.SELF,
owner=1,
pos=common_pb2.Point(x=11, y=12, z=0),
radius=1.0,
health=35,
health_max=45,
is_on_screen=True,
shield=0,
shield_max=0
)
]
self._builder.feature_units(feature_units)
obs = self._get_obs()
for proto, builder in zip(obs.raw_data.units, feature_units):
self._check_feature_unit(proto, builder)
def _get_obs(self):
return self._builder.build().observation
def _check_layer(self, layer, x, y, bits):
self.assertEqual(layer.size.x, x)
self.assertEqual(layer.size.y, y)
self.assertEqual(layer.bits_per_pixel, bits)
def _check_attributes_match(self, a, b, attributes):
for attribute in attributes:
self.assertEqual(getattr(a, attribute), getattr(b, attribute))
def _check_unit(self, proto, builder):
return self._check_attributes_match(proto, builder, vars(builder).keys())
def _check_feature_unit(self, proto, builder):
return self._check_attributes_match(proto, builder, [
"unit_type",
"alliance",
"owner",
"pos",
"radius",
"health",
"health_max",
"is_on_screen",
"shield",
"shield_max"
])
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/dummy_observation_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that various actions do what you'd expect."""
from absl.testing import absltest
from pysc2.lib import actions
from pysc2.lib import units
from pysc2.tests import utils
def raw_ability_ids(obs):
return list(filter(None, (a.action_raw.unit_command.ability_id
for a in obs.actions)))
class ActionsTest(utils.GameReplayTestCase):
@utils.GameReplayTestCase.setup()
def test_general_attack(self):
self.create_unit(unit_type=units.Protoss.Zealot, owner=1, pos=(30, 30))
self.create_unit(unit_type=units.Protoss.Observer, owner=1, pos=(30, 30))
self.step()
obs = self.observe()
zealot = utils.get_unit(obs[0], unit_type=units.Protoss.Zealot)
observer = utils.get_unit(obs[0], unit_type=units.Protoss.Observer)
self.raw_unit_command(0, "Attack_screen", (zealot.tag, observer.tag),
(32, 32))
self.step(64)
obs = self.observe()
zealot = utils.get_unit(obs[0], unit_type=units.Protoss.Zealot)
observer = utils.get_unit(obs[0], unit_type=units.Protoss.Observer)
self.assert_point(zealot.pos, (32, 32))
self.assert_point(observer.pos, (32, 32))
self.assertEqual(
raw_ability_ids(obs[0]),
[actions.FUNCTIONS.Attack_Attack_screen.ability_id])
self.raw_unit_command(0, "Attack_screen", zealot.tag, (34, 34))
self.step(64)
obs = self.observe()
zealot = utils.get_unit(obs[0], unit_type=units.Protoss.Zealot)
observer = utils.get_unit(obs[0], unit_type=units.Protoss.Observer)
self.assert_point(zealot.pos, (34, 34))
self.assert_point(observer.pos, (32, 32))
self.assertEqual(
raw_ability_ids(obs[0]),
[actions.FUNCTIONS.Attack_Attack_screen.ability_id])
self.raw_unit_command(0, "Attack_screen", observer.tag, (34, 34))
self.step(64)
obs = self.observe()
zealot = utils.get_unit(obs[0], unit_type=units.Protoss.Zealot)
observer = utils.get_unit(obs[0], unit_type=units.Protoss.Observer)
self.assert_point(zealot.pos, (34, 34))
self.assert_point(observer.pos, (34, 34))
self.assertEqual(
raw_ability_ids(obs[0]),
[actions.FUNCTIONS.Scan_Move_screen.ability_id])
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/actions_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit test tools."""
import functools
from absl import logging
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import portspicker
from pysc2.lib import run_parallel
from pysc2.lib import stopwatch
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import debug_pb2 as sc_debug
from s2clientprotocol import error_pb2 as sc_error
from s2clientprotocol import raw_pb2 as sc_raw
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestCase(absltest.TestCase):
"""A test base class that enables stopwatch profiling."""
def setUp(self):
super(TestCase, self).setUp()
stopwatch.sw.clear()
stopwatch.sw.enable()
def tearDown(self):
super(TestCase, self).tearDown()
s = str(stopwatch.sw)
if s:
logging.info("Stop watch profile:\n%s", s)
stopwatch.sw.disable()
def get_units(obs, filter_fn=None, owner=None, unit_type=None, tag=None):
"""Return a dict of units that match the filter."""
if unit_type and not isinstance(unit_type, (list, tuple)):
unit_type = (unit_type,)
out = {}
for u in obs.observation.raw_data.units:
if ((filter_fn is None or filter_fn(u)) and
(owner is None or u.owner == owner) and
(unit_type is None or u.unit_type in unit_type) and
(tag is None or u.tag == tag)):
out[u.tag] = u
return out
def get_unit(*args, **kwargs):
"""Return the first unit that matches, or None."""
try:
return next(iter(get_units(*args, **kwargs).values()))
except StopIteration:
return None
def xy_locs(mask):
"""Mask should be a set of bools from comparison with a feature layer."""
ys, xs = mask.nonzero()
return [point.Point(x, y) for x, y in zip(xs, ys)]
def only_in_game(func):
@functools.wraps(func)
def decorator(self, *args, **kwargs):
if self.in_game: # pytype: disable=attribute-error
return func(self, *args, **kwargs)
return decorator
class GameReplayTestCase(TestCase):
"""Tests that run through a game, then verify it still works in a replay."""
@staticmethod
def setup(**kwargs):
"""A decorator to replace unittest.setUp so it can take args."""
def decorator(func): # pylint: disable=missing-docstring
@functools.wraps(func)
def _setup(self): # pylint: disable=missing-docstring
def test_in_game():
print((" %s: Starting game " % func.__name__).center(80, "-"))
self.start_game(**kwargs)
func(self)
def test_in_replay():
self.start_replay()
print((" %s: Starting replay " % func.__name__).center(80, "-"))
func(self)
try:
test_in_game()
test_in_replay()
finally:
self.close()
return _setup
return decorator
def start_game(self, show_cloaked=True, disable_fog=False, players=2):
"""Start a multiplayer game with options."""
self._disable_fog = disable_fog
run_config = run_configs.get()
self._parallel = run_parallel.RunParallel() # Needed for multiplayer.
map_inst = maps.get("Flat64")
self._map_data = map_inst.data(run_config)
self._ports = portspicker.pick_unused_ports(4) if players == 2 else []
self._sc2_procs = [run_config.start(extra_ports=self._ports, want_rgb=False)
for _ in range(players)]
self._controllers = [p.controller for p in self._sc2_procs]
if players == 2:
for c in self._controllers: # Serial due to a race condition on Windows.
c.save_map(map_inst.path, self._map_data)
self._interface = sc_pb.InterfaceOptions()
self._interface.raw = True
self._interface.raw_crop_to_playable_area = True
self._interface.show_cloaked = show_cloaked
self._interface.score = False
self._interface.feature_layer.width = 24
self._interface.feature_layer.resolution.x = 64
self._interface.feature_layer.resolution.y = 64
self._interface.feature_layer.minimap_resolution.x = 64
self._interface.feature_layer.minimap_resolution.y = 64
create = sc_pb.RequestCreateGame(
random_seed=1, disable_fog=self._disable_fog,
local_map=sc_pb.LocalMap(map_path=map_inst.path))
for _ in range(players):
create.player_setup.add(type=sc_pb.Participant)
if players == 1:
create.local_map.map_data = self._map_data
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Protoss,
options=self._interface)
if players == 2:
join.shared_port = 0 # unused
join.server_ports.game_port = self._ports[0]
join.server_ports.base_port = self._ports[1]
join.client_ports.add(game_port=self._ports[2],
base_port=self._ports[3])
self._controllers[0].create_game(create)
self._parallel.run((c.join_game, join) for c in self._controllers)
self._info = self._controllers[0].game_info()
self._features = features.features_from_game_info(
self._info, use_raw_units=True)
self._map_size = point.Point.build(self._info.start_raw.map_size)
print("Map size:", self._map_size)
self.in_game = True
self.step() # Get into the game properly.
def start_replay(self):
"""Switch from the game to a replay."""
self.step(300)
replay_data = self._controllers[0].save_replay()
self._parallel.run(c.leave for c in self._controllers)
for player_id, controller in enumerate(self._controllers):
controller.start_replay(sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=self._map_data,
options=self._interface,
disable_fog=self._disable_fog,
observed_player_id=player_id+1))
self.in_game = False
self.step() # Get into the game properly.
def close(self): # Instead of tearDown.
"""Shut down the SC2 instances."""
# Don't use parallel since it might be broken by an exception.
if hasattr(self, "_controllers") and self._controllers:
for c in self._controllers:
c.quit()
self._controllers = None
if hasattr(self, "_sc2_procs") and self._sc2_procs:
for p in self._sc2_procs:
p.close()
self._sc2_procs = None
if hasattr(self, "_ports") and self._ports:
portspicker.return_ports(self._ports)
self._ports = None
if hasattr(self, "_parallel") and self._parallel is not None:
self._parallel.shutdown()
self._parallel = None
def step(self, count=4):
return self._parallel.run((c.step, count) for c in self._controllers)
def observe(self, disable_fog=False):
return self._parallel.run((c.observe, disable_fog) # pytype: disable=attribute-error
for c in self._controllers) # pytype: disable=attribute-error
@only_in_game
def move_camera(self, x, y):
action = sc_pb.Action()
action.action_raw.camera_move.center_world_space.x = x
action.action_raw.camera_move.center_world_space.y = y
return self._parallel.run((c.act, action) for c in self._controllers) # pytype: disable=attribute-error
@only_in_game
def raw_unit_command(self, player, ability_id, unit_tags, pos=None,
target=None):
"""Issue a raw unit command."""
if isinstance(ability_id, str):
ability_id = actions.FUNCTIONS[ability_id].ability_id
action = sc_pb.Action()
cmd = action.action_raw.unit_command
cmd.ability_id = ability_id
if isinstance(unit_tags, (list, tuple)):
cmd.unit_tags.extend(unit_tags)
else:
cmd.unit_tags.append(unit_tags)
if pos:
cmd.target_world_space_pos.x = pos[0]
cmd.target_world_space_pos.y = pos[1]
elif target:
cmd.target_unit_tag = target
response = self._controllers[player].act(action) # pytype: disable=attribute-error
for result in response.result:
self.assertEqual(result, sc_error.Success)
@only_in_game
def debug(self, player=0, **kwargs):
self._controllers[player].debug([sc_debug.DebugCommand(**kwargs)]) # pytype: disable=attribute-error
def god(self):
"""Stop the units from killing each other so we can observe them."""
self.debug(0, game_state=sc_debug.god)
self.debug(1, game_state=sc_debug.god)
def create_unit(self, unit_type, owner, pos, quantity=1):
if isinstance(pos, tuple):
pos = sc_common.Point2D(x=pos[0], y=pos[1])
elif isinstance(pos, sc_common.Point):
pos = sc_common.Point2D(x=pos.x, y=pos.y)
return self.debug(create_unit=sc_debug.DebugCreateUnit(
unit_type=unit_type, owner=owner, pos=pos, quantity=quantity))
def kill_unit(self, unit_tags):
if not isinstance(unit_tags, (list, tuple)):
unit_tags = [unit_tags]
return self.debug(kill_unit=sc_debug.DebugKillUnit(tag=unit_tags))
def set_energy(self, tag, energy):
self.debug(unit_value=sc_debug.DebugSetUnitValue(
unit_value=sc_debug.DebugSetUnitValue.Energy, value=energy,
unit_tag=tag))
def assert_point(self, proto_pos, pos):
self.assertAlmostEqual(proto_pos.x, pos[0])
self.assertAlmostEqual(proto_pos.y, pos[1])
def assert_layers(self, layers, pos, **kwargs):
for k, v in sorted(kwargs.items()):
self.assertEqual(layers[k, pos.y, pos.x], v,
msg="%s[%s, %s]: expected: %s, got: %s" % (
k, pos.y, pos.x, v, layers[k, pos.y, pos.x]))
def assert_unit(self, unit, **kwargs):
self.assertTrue(unit)
self.assertIsInstance(unit, sc_raw.Unit)
for k, v in sorted(kwargs.items()):
if k == "pos":
self.assert_point(unit.pos, v)
else:
self.assertEqual(getattr(unit, k), v,
msg="%s: expected: %s, got: %s\n%s" % (
k, v, getattr(unit, k), unit))
| pysc2-master | pysc2/tests/utils.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark the ping rate of SC2."""
from absl.testing import absltest
from pysc2 import run_configs
from pysc2.lib import stopwatch
from pysc2.tests import utils
class TestPing(utils.TestCase):
def test_ping(self):
count = 100
with run_configs.get().start(want_rgb=False) as controller:
with stopwatch.sw("first"):
controller.ping()
for _ in range(count):
controller.ping()
self.assertEqual(stopwatch.sw["ping"].num, count)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/ping_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that the multiplayer environment works."""
from absl.testing import absltest
from absl.testing import parameterized
from pysc2.agents import no_op_agent
from pysc2.agents import random_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as common_pb
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestMultiplayerEnv(parameterized.TestCase, utils.TestCase):
@parameterized.named_parameters(
("features",
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64))),
("rgb",
sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(screen=84, minimap=64))),
("features_and_rgb", [
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64)),
sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(screen=128, minimap=32))
]),
("passthrough_and_features", [
sc_pb.InterfaceOptions(
raw=True,
score=True,
feature_layer=sc_pb.SpatialCameraSetup(
resolution=common_pb.Size2DI(x=84, y=84),
minimap_resolution=common_pb.Size2DI(x=64, y=64),
width=24)),
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64))
]),
)
def test_multi_player_env(self, agent_interface_format):
steps = 100
step_mul = 16
players = 2
if not isinstance(agent_interface_format, list):
agent_interface_format = [agent_interface_format] * players
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.random, "random"),
sc2_env.Agent(sc2_env.Race.random, "random")],
step_mul=step_mul,
game_steps_per_episode=steps * step_mul // 2,
agent_interface_format=agent_interface_format) as env:
agents = [
random_agent.RandomAgent() if isinstance(
aif, sc2_env.AgentInterfaceFormat) else no_op_agent.NoOpAgent()
for aif in agent_interface_format
]
run_loop.run_loop(agents, env, steps)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/multi_player_env_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that the debug commands work."""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import units
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import debug_pb2 as sc_debug
from s2clientprotocol import sc2api_pb2 as sc_pb
class DebugTest(absltest.TestCase):
def test_multi_player(self):
run_config = run_configs.get()
map_inst = maps.get("Simple64")
with run_config.start(want_rgb=False) as controller:
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer,
race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Terran,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
info = controller.game_info()
map_size = info.start_raw.map_size
controller.step(2)
obs = controller.observe()
def get_marines(obs):
return {u.tag: u for u in obs.observation.raw_data.units
if u.unit_type == units.Terran.Marine}
self.assertEmpty(get_marines(obs))
controller.debug(sc_debug.DebugCommand(
create_unit=sc_debug.DebugCreateUnit(
unit_type=units.Terran.Marine,
owner=1,
pos=sc_common.Point2D(x=map_size.x // 2, y=map_size.y // 2),
quantity=5)))
controller.step(2)
obs = controller.observe()
marines = get_marines(obs)
self.assertLen(marines, 5)
tags = sorted(marines.keys())
controller.debug([
sc_debug.DebugCommand(kill_unit=sc_debug.DebugKillUnit(
tag=[tags[0]])),
sc_debug.DebugCommand(unit_value=sc_debug.DebugSetUnitValue(
unit_value=sc_debug.DebugSetUnitValue.Life, value=5,
unit_tag=tags[1])),
])
controller.step(2)
obs = controller.observe()
marines = get_marines(obs)
self.assertLen(marines, 4)
self.assertNotIn(tags[0], marines)
self.assertEqual(marines[tags[1]].health, 5)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/debug_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that two built in bots can be watched by an observer."""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestObserver(utils.TestCase):
def test_observer(self):
run_config = run_configs.get()
map_inst = maps.get("Simple64")
with run_config.start(want_rgb=False) as controller:
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_inst.data(run_config)))
create.player_setup.add(
type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy)
create.player_setup.add(
type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryHard)
create.player_setup.add(type=sc_pb.Observer)
controller.create_game(create)
join = sc_pb.RequestJoinGame(
options=sc_pb.InterfaceOptions(), # cheap observations
observed_player_id=0)
controller.join_game(join)
outcome = False
for _ in range(60 * 60): # 60 minutes should be plenty.
controller.step(16)
obs = controller.observe()
if obs.player_result:
print("Outcome after %s steps (%0.1f game minutes):" % (
obs.observation.game_loop, obs.observation.game_loop / (16 * 60)))
for r in obs.player_result:
print("Player %s: %s" % (r.player_id, sc_pb.Result.Name(r.result)))
outcome = True
break
self.assertTrue(outcome)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/observer_test.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that the game renders rgb pixels."""
from absl.testing import absltest
import numpy as np
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import features
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestRender(utils.TestCase):
def test_render(self):
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.score = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 84
interface.feature_layer.resolution.y = 84
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
interface.feature_layer.crop_to_playable_area = True
interface.feature_layer.allow_cheating_layers = True
interface.render.resolution.x = 256
interface.render.resolution.y = 256
interface.render.minimap_resolution.x = 128
interface.render.minimap_resolution.y = 128
def or_zeros(layer, size):
if layer is not None:
return layer.astype(np.int32, copy=False)
else:
return np.zeros((size.y, size.x), dtype=np.int32)
run_config = run_configs.get()
with run_config.start() as controller:
map_inst = maps.get("Simple64")
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random, options=interface)
controller.create_game(create)
controller.join_game(join)
game_info = controller.game_info()
self.assertEqual(interface.raw, game_info.options.raw)
self.assertEqual(interface.feature_layer, game_info.options.feature_layer)
# Can fail if rendering is disabled.
self.assertEqual(interface.render, game_info.options.render)
for _ in range(50):
controller.step(8)
observation = controller.observe()
obs = observation.observation
rgb_screen = features.Feature.unpack_rgb_image(obs.render_data.map)
rgb_minimap = features.Feature.unpack_rgb_image(obs.render_data.minimap)
fl_screen = np.stack(
[or_zeros(f.unpack(obs), interface.feature_layer.resolution)
for f in features.SCREEN_FEATURES])
fl_minimap = np.stack(
[or_zeros(f.unpack(obs), interface.feature_layer.minimap_resolution)
for f in features.MINIMAP_FEATURES])
# Right shapes.
self.assertEqual(rgb_screen.shape, (256, 256, 3))
self.assertEqual(rgb_minimap.shape, (128, 128, 3))
self.assertEqual(fl_screen.shape,
(len(features.SCREEN_FEATURES), 84, 84))
self.assertEqual(fl_minimap.shape,
(len(features.MINIMAP_FEATURES), 64, 64))
# Not all black.
self.assertTrue(rgb_screen.any())
self.assertTrue(rgb_minimap.any())
self.assertTrue(fl_screen.any())
self.assertTrue(fl_minimap.any())
if observation.player_result:
break
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/render_test.py |
#!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that various observations do what you'd expect."""
from absl.testing import absltest
from pysc2.lib import actions
from pysc2.lib import buffs
from pysc2.lib import features
from pysc2.lib import units
from pysc2.tests import utils
from s2clientprotocol import debug_pb2 as sc_debug
from s2clientprotocol import raw_pb2 as sc_raw
# It seems the time from issuing an action until it has an effect is 2 frames.
# It'd be nice if that was faster, and it is 1 in single-player, but in
# multi-player it seems it needs to be propagated to the host and back, which
# takes 2 steps minimum. Unfortunately this also includes camera moves.
EXPECTED_ACTION_DELAY = 2
class ObsTest(utils.GameReplayTestCase):
@utils.GameReplayTestCase.setup()
def test_hallucination(self):
self.god()
# Create some sentries.
self.create_unit(unit_type=units.Protoss.Sentry, owner=1, pos=(30, 30))
self.create_unit(unit_type=units.Protoss.Sentry, owner=2, pos=(30, 28))
self.step()
obs = self.observe()
# Give one enough energy.
tag = utils.get_unit(obs[0], unit_type=units.Protoss.Sentry, owner=1).tag
self.debug(unit_value=sc_debug.DebugSetUnitValue(
unit_value=sc_debug.DebugSetUnitValue.Energy, value=200, unit_tag=tag))
self.step()
obs = self.observe()
# Create a hallucinated archon.
self.raw_unit_command(0, "Hallucination_Archon_quick", tag)
self.step()
obs = self.observe()
# Verify the owner knows it's a hallucination, but the opponent doesn't.
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.Archon)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.Archon)
self.assertTrue(p1.is_hallucination)
self.assertFalse(p2.is_hallucination)
# Create an observer so the opponent has detection.
self.create_unit(unit_type=units.Protoss.Observer, owner=2, pos=(28, 30))
self.step()
obs = self.observe()
# Verify the opponent now also knows it's a hallucination.
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.Archon)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.Archon)
self.assertTrue(p1.is_hallucination)
self.assertTrue(p2.is_hallucination)
@utils.GameReplayTestCase.setup(show_cloaked=False)
def test_hide_cloaked(self):
self.assertFalse(self._info.options.show_cloaked)
self.god()
self.move_camera(32, 32)
# Create some units. One cloaked, one to see it without detection.
self.create_unit(unit_type=units.Protoss.DarkTemplar, owner=1, pos=(30, 30))
self.create_unit(unit_type=units.Protoss.Sentry, owner=2, pos=(28, 30))
self.step(16)
obs = self.observe()
# Verify both can see it, but that only the owner knows details.
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.DarkTemplar)
self.assert_unit(p1, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedAllied)
self.assertIsNone(p2)
screen1 = self._features.transform_obs(obs[0])["feature_screen"]
screen2 = self._features.transform_obs(obs[1])["feature_screen"]
dt = utils.xy_locs(screen1.unit_type == units.Protoss.DarkTemplar)[0]
self.assert_layers(screen1, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
self.assert_layers(screen2, dt, unit_type=0,
unit_hit_points=0, unit_shields=0, cloaked=0)
# Create an observer so the opponent has detection.
self.create_unit(unit_type=units.Protoss.Observer, owner=2, pos=(28, 28))
self.step(16) # It takes a few frames for the observer to detect.
obs = self.observe()
# Verify both can see it, with the same details
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.DarkTemplar)
self.assert_unit(p1, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedAllied)
self.assert_unit(p2, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedDetected)
screen1 = self._features.transform_obs(obs[0])["feature_screen"]
screen2 = self._features.transform_obs(obs[1])["feature_screen"]
dt = utils.xy_locs(screen1.unit_type == units.Protoss.DarkTemplar)[0]
self.assert_layers(screen1, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
self.assert_layers(screen2, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
@utils.GameReplayTestCase.setup()
def test_show_cloaked(self):
self.assertTrue(self._info.options.show_cloaked)
self.god()
self.move_camera(32, 32)
# Create some units. One cloaked, one to see it without detection.
self.create_unit(unit_type=units.Protoss.DarkTemplar, owner=1, pos=(30, 30))
self.create_unit(unit_type=units.Protoss.Sentry, owner=2, pos=(28, 30))
self.step(16)
obs = self.observe()
# Verify both can see it, but that only the owner knows details.
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.DarkTemplar)
self.assert_unit(p1, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedAllied)
self.assert_unit(p2, display_type=sc_raw.Hidden, health=0, shield=0,
cloak=sc_raw.Cloaked)
screen1 = self._features.transform_obs(obs[0])["feature_screen"]
screen2 = self._features.transform_obs(obs[1])["feature_screen"]
dt = utils.xy_locs(screen1.unit_type == units.Protoss.DarkTemplar)[0]
self.assert_layers(screen1, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
self.assert_layers(screen2, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=0, unit_shields=0, cloaked=1)
# Create an observer so the opponent has detection.
self.create_unit(unit_type=units.Protoss.Observer, owner=2, pos=(28, 28))
self.step(16) # It takes a few frames for the observer to detect.
obs = self.observe()
# Verify both can see it, with the same details
p1 = utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar)
p2 = utils.get_unit(obs[1], unit_type=units.Protoss.DarkTemplar)
self.assert_unit(p1, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedAllied)
self.assert_unit(p2, display_type=sc_raw.Visible, health=40, shield=80,
cloak=sc_raw.CloakedDetected)
screen1 = self._features.transform_obs(obs[0])["feature_screen"]
screen2 = self._features.transform_obs(obs[1])["feature_screen"]
dt = utils.xy_locs(screen1.unit_type == units.Protoss.DarkTemplar)[0]
self.assert_layers(screen1, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
self.assert_layers(screen2, dt, unit_type=units.Protoss.DarkTemplar,
unit_hit_points=40, unit_shields=80, cloaked=1)
@utils.GameReplayTestCase.setup()
def test_pos(self):
self.create_unit(unit_type=units.Protoss.Archon, owner=1, pos=(20, 30))
self.create_unit(unit_type=units.Protoss.Observer, owner=1, pos=(40, 30))
self.step()
obs = self.observe()
archon = utils.get_unit(obs[0], unit_type=units.Protoss.Archon)
observer = utils.get_unit(obs[0], unit_type=units.Protoss.Observer)
self.assert_point(archon.pos, (20, 30))
self.assert_point(observer.pos, (40, 30))
self.assertLess(archon.pos.z, observer.pos.z) # The observer flies.
self.assertGreater(archon.radius, observer.radius)
# Move them towards the center, make sure they move.
self.raw_unit_command(0, "Move_screen", (archon.tag, observer.tag),
(30, 25))
self.step(40)
obs2 = self.observe()
archon2 = utils.get_unit(obs2[0], unit_type=units.Protoss.Archon)
observer2 = utils.get_unit(obs2[0], unit_type=units.Protoss.Observer)
self.assertGreater(archon2.pos.x, 20)
self.assertLess(observer2.pos.x, 40)
self.assertLess(archon2.pos.z, observer2.pos.z)
@utils.GameReplayTestCase.setup()
def test_fog(self):
obs = self.observe()
def assert_visible(unit, display_type, alliance, cloak):
self.assert_unit(unit, display_type=display_type, alliance=alliance,
cloak=cloak)
self.create_unit(unit_type=units.Protoss.Sentry, owner=1, pos=(30, 32))
self.create_unit(unit_type=units.Protoss.DarkTemplar, owner=1, pos=(32, 32))
self.step()
obs = self.observe()
assert_visible(utils.get_unit(obs[0], unit_type=units.Protoss.Sentry),
sc_raw.Visible, sc_raw.Self, sc_raw.NotCloaked)
assert_visible(utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar),
sc_raw.Visible, sc_raw.Self, sc_raw.CloakedAllied)
self.assertIsNone(utils.get_unit(obs[1], unit_type=units.Protoss.Sentry))
self.assertIsNone(utils.get_unit(obs[1],
unit_type=units.Protoss.DarkTemplar))
obs = self.observe(disable_fog=True)
assert_visible(utils.get_unit(obs[0], unit_type=units.Protoss.Sentry),
sc_raw.Visible, sc_raw.Self, sc_raw.NotCloaked)
assert_visible(utils.get_unit(obs[0], unit_type=units.Protoss.DarkTemplar),
sc_raw.Visible, sc_raw.Self, sc_raw.CloakedAllied)
assert_visible(utils.get_unit(obs[1], unit_type=units.Protoss.Sentry),
sc_raw.Hidden, sc_raw.Enemy, sc_raw.CloakedUnknown)
assert_visible(utils.get_unit(obs[1], unit_type=units.Protoss.DarkTemplar),
sc_raw.Hidden, sc_raw.Enemy, sc_raw.CloakedUnknown)
@utils.GameReplayTestCase.setup()
def test_effects(self):
def get_effect_proto(obs, effect_id):
for e in obs.observation.raw_data.effects:
if e.effect_id == effect_id:
return e
return None
def get_effect_obs(obs, effect_id):
for e in obs:
if e.effect == effect_id:
return e
return None
self.god()
self.move_camera(32, 32)
# Create some sentries.
self.create_unit(unit_type=units.Protoss.Sentry, owner=1, pos=(30, 30))
self.create_unit(unit_type=units.Protoss.Stalker, owner=1, pos=(28, 30))
self.create_unit(unit_type=units.Protoss.Phoenix, owner=2, pos=(30, 28))
self.step()
obs = self.observe()
# Give enough energy.
sentry = utils.get_unit(obs[0], unit_type=units.Protoss.Sentry)
stalker = utils.get_unit(obs[0], unit_type=units.Protoss.Stalker)
pheonix = utils.get_unit(obs[0], unit_type=units.Protoss.Phoenix)
self.set_energy(sentry.tag, 200)
self.set_energy(pheonix.tag, 200)
self.step()
obs = self.observe()
self.raw_unit_command(0, "Effect_GuardianShield_quick", sentry.tag)
self.step(16)
obs = self.observe()
self.assertIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[0], tag=sentry.tag).buff_ids)
self.assertIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[1], tag=sentry.tag).buff_ids)
self.assertIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[0], tag=stalker.tag).buff_ids)
self.assertIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[1], tag=stalker.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[0], tag=pheonix.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GuardianShield,
utils.get_unit(obs[1], tag=pheonix.tag).buff_ids)
# Both players should see the shield.
e = get_effect_proto(obs[0], features.Effects.GuardianShield)
self.assertIsNotNone(e)
self.assert_point(e.pos[0], (30, 30))
self.assertEqual(e.alliance, sc_raw.Self)
self.assertEqual(e.owner, 1)
self.assertGreater(e.radius, 3)
e = get_effect_proto(obs[1], features.Effects.GuardianShield)
self.assertIsNotNone(e)
self.assert_point(e.pos[0], (30, 30))
self.assertEqual(e.alliance, sc_raw.Enemy)
self.assertEqual(e.owner, 1)
self.assertGreater(e.radius, 3)
# Should show up on the feature layers too.
transformed_obs1 = self._features.transform_obs(obs[0])
transformed_obs2 = self._features.transform_obs(obs[1])
screen1 = transformed_obs1["feature_screen"]
screen2 = transformed_obs2["feature_screen"]
sentry_pos = utils.xy_locs(screen1.unit_type == units.Protoss.Sentry)[0]
self.assert_layers(screen1, sentry_pos, unit_type=units.Protoss.Sentry,
effects=features.Effects.GuardianShield,
buffs=buffs.Buffs.GuardianShield)
self.assert_layers(screen2, sentry_pos, unit_type=units.Protoss.Sentry,
effects=features.Effects.GuardianShield,
buffs=buffs.Buffs.GuardianShield)
phoenix_pos = utils.xy_locs(screen1.unit_type == units.Protoss.Phoenix)[0]
self.assert_layers(screen1, phoenix_pos, unit_type=units.Protoss.Phoenix,
effects=features.Effects.GuardianShield, buffs=0)
self.assert_layers(screen2, phoenix_pos, unit_type=units.Protoss.Phoenix,
effects=features.Effects.GuardianShield, buffs=0)
# Also in the raw_effects.
raw1 = transformed_obs1["raw_effects"]
e = get_effect_obs(raw1, features.Effects.GuardianShield)
self.assertIsNotNone(e)
# Not located at (30, 30) due to map shape and minimap coords.
self.assertGreater(e.x, 20)
self.assertGreater(e.y, 20)
self.assertEqual(e.alliance, sc_raw.Self)
self.assertEqual(e.owner, 1)
self.assertGreater(e.radius, 3)
self.raw_unit_command(1, "Effect_GravitonBeam_screen", pheonix.tag,
target=stalker.tag)
self.step(32)
obs = self.observe()
self.assertIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[0], tag=stalker.tag).buff_ids)
self.assertIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[1], tag=stalker.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[0], tag=sentry.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[1], tag=sentry.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[0], tag=pheonix.tag).buff_ids)
self.assertNotIn(buffs.Buffs.GravitonBeam,
utils.get_unit(obs[1], tag=pheonix.tag).buff_ids)
@utils.GameReplayTestCase.setup()
def test_active(self):
obs = self.observe()
# P1 can see P2.
self.create_unit(
unit_type=units.Protoss.Observer, owner=1,
pos=utils.get_unit(obs[1], unit_type=units.Protoss.Nexus).pos)
self.step(32) # Make sure visibility updates.
obs = self.observe()
for i, o in enumerate(obs):
# Probes are active gathering
for u in utils.get_units(o, unit_type=units.Protoss.Probe).values():
self.assert_unit(u, display_type=sc_raw.Visible, is_active=True)
# Own Nexus is idle
nexus = utils.get_unit(o, unit_type=units.Protoss.Nexus, owner=i+1)
self.assert_unit(nexus, display_type=sc_raw.Visible, is_active=False)
self.assertEmpty(nexus.orders)
# Give it an action.
self.raw_unit_command(i, "Train_Probe_quick", nexus.tag)
# P1 can tell P2's Nexus is idle.
nexus = utils.get_unit(obs[0], unit_type=units.Protoss.Nexus, owner=2)
self.assert_unit(nexus, display_type=sc_raw.Visible, is_active=False)
# Observer is idle.
self.assert_unit(utils.get_unit(obs[0], unit_type=units.Protoss.Observer),
display_type=sc_raw.Visible, is_active=False)
self.assert_unit(utils.get_unit(obs[1], unit_type=units.Protoss.Observer),
display_type=sc_raw.Hidden, is_active=False)
self.step(32)
obs = self.observe()
# All Nexus are now active
nexus0 = utils.get_unit(obs[0], unit_type=units.Protoss.Nexus, owner=1)
nexus1 = utils.get_unit(obs[0], unit_type=units.Protoss.Nexus, owner=2)
nexus2 = utils.get_unit(obs[1], unit_type=units.Protoss.Nexus)
self.assert_unit(nexus0, display_type=sc_raw.Visible, is_active=True)
self.assert_unit(nexus1, display_type=sc_raw.Visible, is_active=True)
self.assert_unit(nexus2, display_type=sc_raw.Visible, is_active=True)
self.assertLen(nexus0.orders, 1)
self.assertLen(nexus2.orders, 1)
self.assertEmpty(nexus1.orders) # Can't see opponent's orders
# Go back to a snapshot
self.kill_unit(utils.get_unit(obs[0], unit_type=units.Protoss.Observer).tag)
self.step(100) # Make sure visibility updates.
obs = self.observe()
self.assertIsNone(utils.get_unit(obs[0], unit_type=units.Protoss.Observer))
# Own Nexus is now active, snapshot isn't.
nexus0 = utils.get_unit(obs[0], unit_type=units.Protoss.Nexus, owner=1)
nexus1 = utils.get_unit(obs[0], unit_type=units.Protoss.Nexus, owner=2)
nexus2 = utils.get_unit(obs[1], unit_type=units.Protoss.Nexus)
self.assert_unit(nexus0, display_type=sc_raw.Visible, is_active=True)
self.assert_unit(nexus1, display_type=sc_raw.Snapshot, is_active=False)
self.assert_unit(nexus2, display_type=sc_raw.Visible, is_active=True)
self.assertLen(nexus0.orders, 1)
self.assertLen(nexus2.orders, 1)
self.assertEmpty(nexus1.orders) # Can't see opponent's orders
@utils.GameReplayTestCase.setup(disable_fog=True)
def test_disable_fog(self):
obs = self.observe()
for i, o in enumerate(obs):
# Probes are active gathering
for u in utils.get_units(o, unit_type=units.Protoss.Probe).values():
self.assert_unit(u, display_type=sc_raw.Visible, is_active=True)
# All Nexus are idle.
own = utils.get_unit(o, unit_type=units.Protoss.Nexus, owner=i+1)
other = utils.get_unit(o, unit_type=units.Protoss.Nexus, owner=2-i)
self.assert_unit(own, display_type=sc_raw.Visible, is_active=False)
self.assert_unit(other, display_type=sc_raw.Visible, is_active=False)
self.assertEmpty(own.orders)
self.assertEmpty(other.orders)
# Give it an action.
self.raw_unit_command(i, "Train_Probe_quick", own.tag)
self.step(32)
obs = self.observe()
# All Nexus are active.
for i, o in enumerate(obs):
own = utils.get_unit(o, unit_type=units.Protoss.Nexus, owner=i+1)
other = utils.get_unit(o, unit_type=units.Protoss.Nexus, owner=2-i)
self.assert_unit(own, display_type=sc_raw.Visible, is_active=True)
self.assert_unit(other, display_type=sc_raw.Visible, is_active=True)
self.assertLen(own.orders, 1)
self.assertEmpty(other.orders)
@utils.GameReplayTestCase.setup()
def test_action_delay(self):
self.observe()
self.create_unit(unit_type=units.Protoss.Zealot, owner=1, pos=(32, 32))
self.step(16)
obs1 = self.observe()
self.assertLen(obs1[0].actions, 0)
zealot1 = utils.get_unit(obs1[0], unit_type=units.Protoss.Zealot, owner=1)
self.assertLen(zealot1.orders, 0)
self.raw_unit_command(0, "Move_screen", zealot1.tag, (30, 30))
# If the delay is taken down to 1, remove this first step of verifying the
# actions length is 0.
self.assertEqual(EXPECTED_ACTION_DELAY, 2)
self.step(1)
obs2 = self.observe()
self.assertLen(obs2[0].action_errors, 0)
self.assertLen(obs2[0].actions, 0)
self.step(1)
obs2 = self.observe()
self.assertLen(obs2[0].action_errors, 0)
self.assertGreaterEqual(len(obs2[0].actions), 1)
for action in obs2[0].actions:
if action.HasField("action_raw"):
break
else:
self.assertFalse("No raw action found")
self.assertEqual(action.game_loop, obs1[0].observation.game_loop+1) # pylint: disable=undefined-loop-variable
unit_command = action.action_raw.unit_command # pylint: disable=undefined-loop-variable
self.assertEqual(unit_command.ability_id,
actions.FUNCTIONS.Move_Move_screen.ability_id)
self.assert_point(unit_command.target_world_space_pos, (30, 30))
self.assertEqual(unit_command.unit_tags[0], zealot1.tag)
zealot2 = utils.get_unit(obs2[0], unit_type=units.Protoss.Zealot, owner=1)
self.assertLen(zealot2.orders, 1)
self.assertEqual(zealot2.orders[0].ability_id,
actions.FUNCTIONS.Move_Move_screen.ability_id)
self.assert_point(zealot2.orders[0].target_world_space_pos, (30, 30))
@utils.GameReplayTestCase.setup()
def test_camera_movement_delay(self):
obs1 = self.observe()
screen1 = self._features.transform_obs(obs1[0])["feature_screen"]
nexus1 = utils.xy_locs(screen1.unit_type == units.Protoss.Nexus)
self.step(1)
obs2 = self.observe()
screen2 = self._features.transform_obs(obs2[0])["feature_screen"]
nexus2 = utils.xy_locs(screen2.unit_type == units.Protoss.Nexus)
self.assertEqual(nexus1, nexus2) # Same place.
loc = obs1[0].observation.raw_data.player.camera
self.move_camera(loc.x + 3, loc.y + 3)
self.step(EXPECTED_ACTION_DELAY + 1)
obs3 = self.observe()
screen3 = self._features.transform_obs(obs3[0])["feature_screen"]
nexus3 = utils.xy_locs(screen3.unit_type == units.Protoss.Nexus)
self.assertNotEqual(nexus1, nexus3) # Different location due to camera.
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/obs_test.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that the general ids in stable ids match what we expect."""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class TestGeneralActions(utils.TestCase):
"""Verify that the general ids in stable ids match what we expect."""
def test_general_actions(self):
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
map_inst = maps.get("Simple64")
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
abilities = controller.data().abilities
errors = []
for f in actions.FUNCTIONS:
if abilities[f.ability_id].remaps_to_ability_id != f.general_id:
errors.append("FUNCTIONS %s/%s has abilitiy %s, general %s, expected "
"general %s" % (
f.id, f.name, f.ability_id, f.general_id,
abilities[f.ability_id].remaps_to_ability_id))
for f in actions.RAW_FUNCTIONS:
if abilities[f.ability_id].remaps_to_ability_id != f.general_id:
errors.append(
"RAW_FUNCTIONS %s/%s has abilitiy %s, general %s, expected "
"general %s" % (
f.id, f.name, f.ability_id, f.general_id,
abilities[f.ability_id].remaps_to_ability_id))
print("\n".join(errors))
self.assertFalse(errors)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/tests/general_actions_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A random agent for starcraft."""
import numpy
from pysc2.agents import base_agent
from pysc2.lib import actions
class RandomAgent(base_agent.BaseAgent):
"""A random agent for starcraft."""
def step(self, obs):
super(RandomAgent, self).step(obs)
function_id = numpy.random.choice(obs.observation.available_actions)
args = [[numpy.random.randint(0, size) for size in arg.sizes]
for arg in self.action_spec.functions[function_id].args]
return actions.FunctionCall(function_id, args)
| pysc2-master | pysc2/agents/random_agent.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Scripted agents."""
import numpy
from pysc2.agents import base_agent
from pysc2.lib import actions
from pysc2.lib import features
_PLAYER_SELF = features.PlayerRelative.SELF
_PLAYER_NEUTRAL = features.PlayerRelative.NEUTRAL # beacon/minerals
_PLAYER_ENEMY = features.PlayerRelative.ENEMY
FUNCTIONS = actions.FUNCTIONS
RAW_FUNCTIONS = actions.RAW_FUNCTIONS
def _xy_locs(mask):
"""Mask should be a set of bools from comparison with a feature layer."""
y, x = mask.nonzero()
return list(zip(x, y))
class MoveToBeacon(base_agent.BaseAgent):
"""An agent specifically for solving the MoveToBeacon map."""
def step(self, obs):
super(MoveToBeacon, self).step(obs)
if FUNCTIONS.Move_screen.id in obs.observation.available_actions:
player_relative = obs.observation.feature_screen.player_relative
beacon = _xy_locs(player_relative == _PLAYER_NEUTRAL)
if not beacon:
return FUNCTIONS.no_op()
beacon_center = numpy.mean(beacon, axis=0).round()
return FUNCTIONS.Move_screen("now", beacon_center)
else:
return FUNCTIONS.select_army("select")
class CollectMineralShards(base_agent.BaseAgent):
"""An agent specifically for solving the CollectMineralShards map."""
def step(self, obs):
super(CollectMineralShards, self).step(obs)
if FUNCTIONS.Move_screen.id in obs.observation.available_actions:
player_relative = obs.observation.feature_screen.player_relative
minerals = _xy_locs(player_relative == _PLAYER_NEUTRAL)
if not minerals:
return FUNCTIONS.no_op()
marines = _xy_locs(player_relative == _PLAYER_SELF)
marine_xy = numpy.mean(marines, axis=0).round() # Average location.
distances = numpy.linalg.norm(numpy.array(minerals) - marine_xy, axis=1)
closest_mineral_xy = minerals[numpy.argmin(distances)]
return FUNCTIONS.Move_screen("now", closest_mineral_xy)
else:
return FUNCTIONS.select_army("select")
class CollectMineralShardsFeatureUnits(base_agent.BaseAgent):
"""An agent for solving the CollectMineralShards map with feature units.
Controls the two marines independently:
- select marine
- move to nearest mineral shard that wasn't the previous target
- swap marine and repeat
"""
def setup(self, obs_spec, action_spec):
super(CollectMineralShardsFeatureUnits, self).setup(obs_spec, action_spec)
if "feature_units" not in obs_spec:
raise Exception("This agent requires the feature_units observation.")
def reset(self):
super(CollectMineralShardsFeatureUnits, self).reset()
self._marine_selected = False
self._previous_mineral_xy = [-1, -1]
def step(self, obs):
super(CollectMineralShardsFeatureUnits, self).step(obs)
marines = [unit for unit in obs.observation.feature_units
if unit.alliance == _PLAYER_SELF]
if not marines:
return FUNCTIONS.no_op()
marine_unit = next((m for m in marines
if m.is_selected == self._marine_selected), marines[0])
marine_xy = [marine_unit.x, marine_unit.y]
if not marine_unit.is_selected:
# Nothing selected or the wrong marine is selected.
self._marine_selected = True
return FUNCTIONS.select_point("select", marine_xy)
if FUNCTIONS.Move_screen.id in obs.observation.available_actions:
# Find and move to the nearest mineral.
minerals = [[unit.x, unit.y] for unit in obs.observation.feature_units
if unit.alliance == _PLAYER_NEUTRAL]
if self._previous_mineral_xy in minerals:
# Don't go for the same mineral shard as other marine.
minerals.remove(self._previous_mineral_xy)
if minerals:
# Find the closest.
distances = numpy.linalg.norm(
numpy.array(minerals) - numpy.array(marine_xy), axis=1)
closest_mineral_xy = minerals[numpy.argmin(distances)]
# Swap to the other marine.
self._marine_selected = False
self._previous_mineral_xy = closest_mineral_xy
return FUNCTIONS.Move_screen("now", closest_mineral_xy)
return FUNCTIONS.no_op()
class CollectMineralShardsRaw(base_agent.BaseAgent):
"""An agent for solving CollectMineralShards with raw units and actions.
Controls the two marines independently:
- move to nearest mineral shard that wasn't the previous target
- swap marine and repeat
"""
def setup(self, obs_spec, action_spec):
super(CollectMineralShardsRaw, self).setup(obs_spec, action_spec)
if "raw_units" not in obs_spec:
raise Exception("This agent requires the raw_units observation.")
def reset(self):
super(CollectMineralShardsRaw, self).reset()
self._last_marine = None
self._previous_mineral_xy = [-1, -1]
def step(self, obs):
super(CollectMineralShardsRaw, self).step(obs)
marines = [unit for unit in obs.observation.raw_units
if unit.alliance == _PLAYER_SELF]
if not marines:
return RAW_FUNCTIONS.no_op()
marine_unit = next((m for m in marines if m.tag != self._last_marine))
marine_xy = [marine_unit.x, marine_unit.y]
minerals = [[unit.x, unit.y] for unit in obs.observation.raw_units
if unit.alliance == _PLAYER_NEUTRAL]
if self._previous_mineral_xy in minerals:
# Don't go for the same mineral shard as other marine.
minerals.remove(self._previous_mineral_xy)
if minerals:
# Find the closest.
distances = numpy.linalg.norm(
numpy.array(minerals) - numpy.array(marine_xy), axis=1)
closest_mineral_xy = minerals[numpy.argmin(distances)]
self._last_marine = marine_unit.tag
self._previous_mineral_xy = closest_mineral_xy
return RAW_FUNCTIONS.Move_pt("now", marine_unit.tag, closest_mineral_xy)
return RAW_FUNCTIONS.no_op()
class DefeatRoaches(base_agent.BaseAgent):
"""An agent specifically for solving the DefeatRoaches map."""
def step(self, obs):
super(DefeatRoaches, self).step(obs)
if FUNCTIONS.Attack_screen.id in obs.observation.available_actions:
player_relative = obs.observation.feature_screen.player_relative
roaches = _xy_locs(player_relative == _PLAYER_ENEMY)
if not roaches:
return FUNCTIONS.no_op()
# Find the roach with max y coord.
target = roaches[numpy.argmax(numpy.array(roaches)[:, 1])]
return FUNCTIONS.Attack_screen("now", target)
if FUNCTIONS.select_army.id in obs.observation.available_actions:
return FUNCTIONS.select_army("select")
return FUNCTIONS.no_op()
class DefeatRoachesRaw(base_agent.BaseAgent):
"""An agent specifically for solving DefeatRoaches using raw actions."""
def setup(self, obs_spec, action_spec):
super(DefeatRoachesRaw, self).setup(obs_spec, action_spec)
if "raw_units" not in obs_spec:
raise Exception("This agent requires the raw_units observation.")
def step(self, obs):
super(DefeatRoachesRaw, self).step(obs)
marines = [unit.tag for unit in obs.observation.raw_units
if unit.alliance == _PLAYER_SELF]
roaches = [unit for unit in obs.observation.raw_units
if unit.alliance == _PLAYER_ENEMY]
if marines and roaches:
# Find the roach with max y coord.
target = sorted(roaches, key=lambda r: r.y)[0].tag
return RAW_FUNCTIONS.Attack_unit("now", marines, target)
return FUNCTIONS.no_op()
| pysc2-master | pysc2/agents/scripted_agent.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A base agent to write custom scripted agents."""
from pysc2.lib import actions
class BaseAgent(object):
"""A base agent to write custom scripted agents.
It can also act as a passive agent that does nothing but no-ops.
"""
def __init__(self):
self.reward = 0
self.episodes = 0
self.steps = 0
self.obs_spec = None
self.action_spec = None
def setup(self, obs_spec, action_spec):
self.obs_spec = obs_spec
self.action_spec = action_spec
def reset(self):
self.episodes += 1
def step(self, obs):
self.steps += 1
self.reward += obs.reward
return actions.FunctionCall(actions.FUNCTIONS.no_op.id, [])
| pysc2-master | pysc2/agents/base_agent.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/agents/__init__.py |
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A no-op agent for starcraft."""
from pysc2.agents import base_agent
from s2clientprotocol import sc2api_pb2 as sc_pb
class NoOpAgent(base_agent.BaseAgent):
"""A no-op agent for starcraft."""
def step(self, obs):
super(NoOpAgent, self).step(obs)
return sc_pb.Action()
| pysc2-master | pysc2/agents/no_op_agent.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for how to run SC2 from a normal install on various platforms."""
import copy
import os
import platform
import subprocess
import sys
from absl import flags
from absl import logging
from pysc2.lib import sc_process
from pysc2.run_configs import lib
flags.DEFINE_enum("sc2_version", None, sorted(lib.VERSIONS.keys()),
"Which version of the game to use.")
flags.DEFINE_bool("sc2_dev_build", False,
"Use a dev build. Mostly useful for testing by Blizzard.")
FLAGS = flags.FLAGS
def _read_execute_info(path, parents):
"""Read the ExecuteInfo.txt file and return the base directory."""
path = os.path.join(path, "StarCraft II/ExecuteInfo.txt")
if os.path.exists(path):
with open(path, "rb") as f: # Binary because the game appends a '\0' :(.
for line in f:
parts = [p.strip() for p in line.decode("utf-8").split("=")]
if len(parts) == 2 and parts[0] == "executable":
exec_path = parts[1].replace("\\", "/") # For windows compatibility.
for _ in range(parents):
exec_path = os.path.dirname(exec_path)
return exec_path
class LocalBase(lib.RunConfig):
"""Base run config for public installs."""
def __init__(self, base_dir, exec_name, version, cwd=None, env=None):
base_dir = os.path.expanduser(base_dir)
version = version or FLAGS.sc2_version or "latest"
cwd = cwd and os.path.join(base_dir, cwd)
super(LocalBase, self).__init__(
replay_dir=os.path.join(base_dir, "Replays"),
data_dir=base_dir, tmp_dir=None, version=version, cwd=cwd, env=env)
if FLAGS.sc2_dev_build:
self.version = self.version._replace(build_version=0)
elif self.version.build_version < lib.VERSIONS["3.16.1"].build_version:
raise sc_process.SC2LaunchError(
"SC2 Binaries older than 3.16.1 don't support the api.")
self._exec_name = exec_name
def start(self, want_rgb=True, **kwargs):
"""Launch the game."""
del want_rgb # Unused
if not os.path.isdir(self.data_dir):
raise sc_process.SC2LaunchError(
"Expected to find StarCraft II installed at '%s'. If it's not "
"installed, do that and run it once so auto-detection works. If "
"auto-detection failed repeatedly, then set the SC2PATH environment "
"variable with the correct location." % self.data_dir)
exec_path = os.path.join(
self.data_dir, "Versions/Base%05d" % self.version.build_version,
self._exec_name)
if not os.path.exists(exec_path):
raise sc_process.SC2LaunchError("No SC2 binary found at: %s" % exec_path)
return sc_process.StarcraftProcess(
self, exec_path=exec_path, version=self.version, **kwargs)
def get_versions(self, containing=None):
versions_dir = os.path.join(self.data_dir, "Versions")
version_prefix = "Base"
versions_found = sorted(int(v[len(version_prefix):])
for v in os.listdir(versions_dir)
if v.startswith(version_prefix))
if not versions_found:
raise sc_process.SC2LaunchError(
"No SC2 Versions found in %s" % versions_dir)
known_versions = [v for v in lib.VERSIONS.values()
if v.build_version in versions_found]
# Add one more with the max version. That one doesn't need a data version
# since SC2 will find it in the .build.info file. This allows running
# versions newer than what are known by pysc2, and so is the default.
known_versions.append(
lib.Version("latest", max(versions_found), None, None))
ret = lib.version_dict(known_versions)
if containing is not None and containing not in ret:
raise ValueError("Unknown game version: %s. Known versions: %s." % (
containing, sorted(ret.keys())))
return ret
class Windows(LocalBase):
"""Run on Windows."""
def __init__(self, version=None):
exec_path = (os.environ.get("SC2PATH") or
_read_execute_info(os.path.expanduser("~/Documents"), 3) or
"C:/Program Files (x86)/StarCraft II")
super(Windows, self).__init__(exec_path, "SC2_x64.exe",
version=version, cwd="Support64")
@classmethod
def priority(cls):
if platform.system() == "Windows":
return 1
class Cygwin(LocalBase):
"""Run on Cygwin. This runs the windows binary within a cygwin terminal."""
def __init__(self, version=None):
exec_path = os.environ.get(
"SC2PATH", "/cygdrive/c/Program Files (x86)/StarCraft II")
super(Cygwin, self).__init__(exec_path, "SC2_x64.exe",
version=version, cwd="Support64")
@classmethod
def priority(cls):
if sys.platform == "cygwin":
return 1
class MacOS(LocalBase):
"""Run on MacOS."""
def __init__(self, version=None):
exec_path = (os.environ.get("SC2PATH") or
_read_execute_info(os.path.expanduser(
"~/Library/Application Support/Blizzard"), 6) or
"/Applications/StarCraft II")
super(MacOS, self).__init__(exec_path, "SC2.app/Contents/MacOS/SC2",
version=version)
@classmethod
def priority(cls):
if platform.system() == "Darwin":
return 1
class Linux(LocalBase):
"""Config to run on Linux."""
known_gl_libs = [ # In priority order. Prefer hardware rendering.
("-eglpath", "libEGL.so"),
("-eglpath", "libEGL.so.1"),
("-osmesapath", "libOSMesa.so"),
("-osmesapath", "libOSMesa.so.8"), # Ubuntu 16.04
("-osmesapath", "libOSMesa.so.6"), # Ubuntu 14.04
]
def __init__(self, version=None):
base_dir = os.environ.get("SC2PATH", "~/StarCraftII")
base_dir = os.path.expanduser(base_dir)
env = copy.deepcopy(os.environ)
env["LD_LIBRARY_PATH"] = ":".join(filter(None, [
os.environ.get("LD_LIBRARY_PATH"),
os.path.join(base_dir, "Libs/")]))
super(Linux, self).__init__(base_dir, "SC2_x64", version=version, env=env)
@classmethod
def priority(cls):
if platform.system() == "Linux":
return 1
def start(self, want_rgb=True, **kwargs):
extra_args = kwargs.pop("extra_args", [])
if want_rgb:
# Figure out whether the various GL libraries exist since SC2 sometimes
# fails if you ask to use a library that doesn't exist.
libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
libs = {lib.strip().split()[0] for lib in libs.split("\n") if lib}
for arg, lib_name in self.known_gl_libs:
if lib_name in libs:
extra_args += [arg, lib_name]
break
else:
extra_args += ["-headlessNoRender"]
logging.info(
"No GL library found, so RGB rendering will be disabled. "
"For software rendering install libosmesa.")
return super(Linux, self).start(
want_rgb=want_rgb, extra_args=extra_args, **kwargs)
| pysc2-master | pysc2/run_configs/platforms.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for various ways to run starcraft."""
import collections
import datetime
import os
from pysc2.lib import gfile
class Version(collections.namedtuple("Version", [
"game_version", "build_version", "data_version", "binary"])):
"""Represents a single version of the game."""
__slots__ = ()
def version_dict(versions):
return {ver.game_version: ver for ver in versions}
# https://github.com/Blizzard/s2client-proto/blob/master/buildinfo/versions.json
# Generate with bin/gen_versions.py or bin/replay_version.py.
VERSIONS = version_dict([
Version("3.13.0", 52910, "8D9FEF2E1CF7C6C9CBE4FBCA830DDE1C", None),
Version("3.14.0", 53644, "CA275C4D6E213ED30F80BACCDFEDB1F5", None),
Version("3.15.0", 54518, "BBF619CCDCC80905350F34C2AF0AB4F6", None),
Version("3.15.1", 54518, "6EB25E687F8637457538F4B005950A5E", None),
Version("3.16.0", 55505, "60718A7CA50D0DF42987A30CF87BCB80", None),
Version("3.16.1", 55958, "5BD7C31B44525DAB46E64C4602A81DC2", None),
Version("3.17.0", 56787, "DFD1F6607F2CF19CB4E1C996B2563D9B", None),
Version("3.17.1", 56787, "3F2FCED08798D83B873B5543BEFA6C4B", None),
Version("3.17.2", 56787, "C690FC543082D35EA0AAA876B8362BEA", None),
Version("3.18.0", 57507, "1659EF34997DA3470FF84A14431E3A86", None),
Version("3.19.0", 58400, "2B06AEE58017A7DF2A3D452D733F1019", None),
Version("3.19.1", 58400, "D9B568472880CC4719D1B698C0D86984", None),
Version("4.0.0", 59587, "9B4FD995C61664831192B7DA46F8C1A1", None),
Version("4.0.2", 59587, "B43D9EE00A363DAFAD46914E3E4AF362", None),
Version("4.1.0", 60196, "1B8ACAB0C663D5510941A9871B3E9FBE", None),
Version("4.1.1", 60321, "5C021D8A549F4A776EE9E9C1748FFBBC", None),
Version("4.1.2", 60321, "33D9FE28909573253B7FC352CE7AEA40", None),
Version("4.1.3", 60321, "F486693E00B2CD305B39E0AB254623EB", None),
Version("4.1.4", 60321, "2E2A3F6E0BAFE5AC659C4D39F13A938C", None),
Version("4.2.0", 62347, "C0C0E9D37FCDBC437CE386C6BE2D1F93", None),
Version("4.2.1", 62848, "29BBAC5AFF364B6101B661DB468E3A37", None),
Version("4.2.2", 63454, "3CB54C86777E78557C984AB1CF3494A0", None),
Version("4.2.3", 63454, "5E3A8B21E41B987E05EE4917AAD68C69", None),
Version("4.2.4", 63454, "7C51BC7B0841EACD3535E6FA6FF2116B", None),
Version("4.3.0", 64469, "C92B3E9683D5A59E08FC011F4BE167FF", None),
Version("4.3.1", 65094, "E5A21037AA7A25C03AC441515F4E0644", None),
Version("4.3.2", 65384, "B6D73C85DFB70F5D01DEABB2517BF11C", None),
Version("4.4.0", 65895, "BF41339C22AE2EDEBEEADC8C75028F7D", None),
Version("4.4.1", 66668, "C094081D274A39219061182DBFD7840F", None),
Version("4.5.0", 67188, "2ACF84A7ECBB536F51FC3F734EC3019F", None),
Version("4.5.1", 67188, "6D239173B8712461E6A7C644A5539369", None),
Version("4.6.0", 67926, "7DE59231CBF06F1ECE9A25A27964D4AE", None),
Version("4.6.1", 67926, "BEA99B4A8E7B41E62ADC06D194801BAB", None),
Version("4.6.2", 69232, "B3E14058F1083913B80C20993AC965DB", None),
Version("4.7.0", 70154, "8E216E34BC61ABDE16A59A672ACB0F3B", None),
Version("4.7.1", 70154, "94596A85191583AD2EBFAE28C5D532DB", None),
Version("4.8.0", 71061, "760581629FC458A1937A05ED8388725B", None),
Version("4.8.1", 71523, "FCAF3F050B7C0CC7ADCF551B61B9B91E", None),
Version("4.8.2", 71663, "FE90C92716FC6F8F04B74268EC369FA5", None),
Version("4.8.3", 72282, "0F14399BBD0BA528355FF4A8211F845B", None),
Version("4.8.4", 73286, "CD040C0675FD986ED37A4CA3C88C8EB5", None),
Version("4.8.5", 73559, "B2465E73AED597C74D0844112D582595", None),
Version("4.8.6", 73620, "AA18FEAD6573C79EF707DF44ABF1BE61", None),
Version("4.9.0", 74071, "70C74A2DCA8A0D8E7AE8647CAC68ACCA", None),
Version("4.9.1", 74456, "218CB2271D4E2FA083470D30B1A05F02", None),
Version("4.9.2", 74741, "614480EF79264B5BD084E57F912172FF", None),
Version("4.9.3", 75025, "C305368C63621480462F8F516FB64374", None),
Version("4.10.0", 75689, "B89B5D6FA7CBF6452E721311BFBC6CB2", None),
Version("4.10.1", 75800, "DDFFF9EC4A171459A4F371C6CC189554", None),
Version("4.10.2", 76052, "D0F1A68AA88BA90369A84CD1439AA1C3", None),
Version("4.10.3", 76114, "CDB276D311F707C29BA664B7754A7293", None),
Version("4.10.4", 76811, "FF9FA4EACEC5F06DEB27BD297D73ED67", None),
Version("4.11.0", 77379, "70E774E722A58287EF37D487605CD384", None),
Version("4.11.1", 77379, "F92D1127A291722120AC816F09B2E583", None),
Version("4.11.2", 77535, "FC43E0897FCC93E4632AC57CBC5A2137", None),
Version("4.11.3", 77661, "A15B8E4247434B020086354F39856C51", None),
Version("4.11.4", 78285, "69493AFAB5C7B45DDB2F3442FD60F0CF", None),
Version("4.12.0", 79998, "B47567DEE5DC23373BFF57194538DFD3", None),
Version("4.12.1", 80188, "44DED5AED024D23177C742FC227C615A", None),
Version("5.0.0", 80949, "9AE39C332883B8BF6AA190286183ED72", None),
Version("5.0.1", 81009, "0D28678BC32E7F67A238F19CD3E0A2CE", None),
Version("5.0.2", 81102, "DC0A1182FB4ABBE8E29E3EC13CF46F68", None),
Version("5.0.3", 81433, "5FD8D4B6B52723B44862DF29F232CF31", None),
Version("5.0.4", 82457, "D2707E265785612D12B381AF6ED9DBF4", None),
Version("5.0.5", 82893, "D795328C01B8A711947CC62AA9750445", None),
Version("5.0.6", 83830, "B4745D6A4F982A3143C183D8ACB6C3E3", None),
Version("5.0.7", 84643, "A389D1F7DF9DD792FBE980533B7119FF", None),
Version("5.0.8", 86383, "22EAC562CD0C6A31FB2C2C21E3AA3680", None),
Version("5.0.9", 87702, "F799E093428D419FD634CCE9B925218C", None),
])
class RunConfig(object):
"""Base class for different run configs."""
def __init__(self, replay_dir, data_dir, tmp_dir, version,
cwd=None, env=None):
"""Initialize the runconfig with the various directories needed.
Args:
replay_dir: Where to find replays. Might not be accessible to SC2.
data_dir: Where SC2 should find the data and battle.net cache.
tmp_dir: The temporary directory. None is system default.
version: The game version to run, a string.
cwd: Where to set the current working directory.
env: What to pass as the environment variables.
"""
self.replay_dir = replay_dir
self.data_dir = data_dir
self.tmp_dir = tmp_dir
self.cwd = cwd
self.env = env
self.version = self._get_version(version)
def map_data(self, map_name, players=None):
"""Return the map data for a map by name or path."""
map_names = [map_name]
if players:
map_names.append(os.path.join(
os.path.dirname(map_name),
"(%s)%s" % (players, os.path.basename(map_name))))
for name in map_names:
path = os.path.join(self.data_dir, "Maps", name)
if gfile.Exists(path):
with gfile.Open(path, "rb") as f:
return f.read()
raise ValueError(f"Map {map_name} not found in {self.data_dir}/Maps.")
def abs_replay_path(self, replay_path):
"""Return the absolute path to the replay, outside the sandbox."""
return os.path.join(self.replay_dir, replay_path)
def replay_data(self, replay_path):
"""Return the replay data given a path to the replay."""
with gfile.Open(self.abs_replay_path(replay_path), "rb") as f:
return f.read()
def replay_paths(self, replay_dir):
"""A generator yielding the full path to the replays under `replay_dir`."""
replay_dir = self.abs_replay_path(replay_dir)
if replay_dir.lower().endswith(".sc2replay"):
yield replay_dir
return
for f in gfile.ListDir(replay_dir):
if f.lower().endswith(".sc2replay"):
yield os.path.join(replay_dir, f)
def save_replay(self, replay_data, replay_dir, prefix=None):
"""Save a replay to a directory, returning the path to the replay.
Args:
replay_data: The result of controller.save_replay(), ie the binary data.
replay_dir: Where to save the replay. This can be absolute or relative.
prefix: Optional prefix for the replay filename.
Returns:
The full path where the replay is saved.
Raises:
ValueError: If the prefix contains the path seperator.
"""
if not prefix:
replay_filename = ""
elif os.path.sep in prefix:
raise ValueError("Prefix '%s' contains '%s', use replay_dir instead." % (
prefix, os.path.sep))
else:
replay_filename = prefix + "_"
now = datetime.datetime.utcnow().replace(microsecond=0)
replay_filename += "%s.SC2Replay" % now.isoformat("-").replace(":", "-")
replay_dir = self.abs_replay_path(replay_dir)
if not gfile.Exists(replay_dir):
gfile.MakeDirs(replay_dir)
replay_path = os.path.join(replay_dir, replay_filename)
with gfile.Open(replay_path, "wb") as f:
f.write(replay_data)
return replay_path
def start(self, version=None, **kwargs):
"""Launch the game. Find the version and run sc_process.StarcraftProcess."""
raise NotImplementedError()
@classmethod
def all_subclasses(cls):
"""An iterator over all subclasses of `cls`."""
for s in cls.__subclasses__():
yield s
for c in s.all_subclasses():
yield c
@classmethod
def name(cls):
return cls.__name__
@classmethod
def priority(cls):
"""None means this isn't valid. Run the one with the max priority."""
return None
def get_versions(self, containing=None):
"""Return a dict of all versions that can be run."""
if containing is not None and containing not in VERSIONS:
raise ValueError("Unknown game version: %s. Known versions: %s." % (
containing, sorted(VERSIONS.keys())))
return VERSIONS
def _get_version(self, game_version):
"""Get the full details for the specified game version."""
if isinstance(game_version, Version):
if not game_version.game_version:
raise ValueError(
"Version '%r' supplied without a game version." % (game_version,))
if (game_version.data_version and
game_version.binary and
game_version.build_version):
return game_version
# Some fields might be missing from serialized versions. Look them up.
game_version = game_version.game_version
if game_version.count(".") == 1:
game_version += ".0"
versions = self.get_versions(containing=game_version)
return versions[game_version]
| pysc2-master | pysc2/run_configs/lib.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for various ways to run starcraft."""
from absl import flags
from pysc2.lib import sc_process
from pysc2.run_configs import platforms
from pysc2.run_configs import lib
flags.DEFINE_string("sc2_run_config", None,
"Which run_config to use to spawn the binary.")
FLAGS = flags.FLAGS
def get(version=None):
"""Get the config chosen by the flags."""
configs = {c.name(): c
for c in lib.RunConfig.all_subclasses() if c.priority()}
if not configs:
raise sc_process.SC2LaunchError("No valid run_configs found.")
if FLAGS.sc2_run_config is None: # Find the highest priority as default.
return max(configs.values(), key=lambda c: c.priority())(version=version)
try:
return configs[FLAGS.sc2_run_config](version=version)
except KeyError:
raise sc_process.SC2LaunchError(
"Invalid run_config. Valid configs are: %s" % (
", ".join(sorted(configs.keys()))))
| pysc2-master | pysc2/run_configs/__init__.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Starcraft II environment for playing LAN games vs humans.
Check pysc2/bin/play_vs_agent.py for documentation.
"""
import binascii
import collections
import hashlib
import json
import os
import shutil
import socket
import struct
import subprocess
import threading
import time
from absl import logging
from pysc2 import run_configs
from pysc2.env import sc2_env
from pysc2.lib import features
from pysc2.lib import run_parallel
from s2clientprotocol import sc2api_pb2 as sc_pb
class Addr(collections.namedtuple("Addr", ["ip", "port"])):
def __str__(self):
ip = "[%s]" % self.ip if ":" in self.ip else self.ip
return "%s:%s" % (ip, self.port)
def daemon_thread(target, args):
t = threading.Thread(target=target, args=args)
t.daemon = True
t.start()
return t
def udp_server(addr):
family = socket.AF_INET6 if ":" in addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.bind(addr)
return sock
def tcp_server(tcp_addr, settings):
"""Start up the tcp server, send the settings."""
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.bind(tcp_addr)
sock.listen(1)
logging.info("Waiting for connection on %s", tcp_addr)
conn, addr = sock.accept()
logging.info("Accepted connection from %s", Addr(*addr[:2]))
# Send map_data independently for py2/3 and json encoding reasons.
write_tcp(conn, settings["map_data"])
send_settings = {k: v for k, v in settings.items() if k != "map_data"}
logging.debug("settings: %s", send_settings)
write_tcp(conn, json.dumps(send_settings).encode())
return conn
def tcp_client(tcp_addr):
"""Connect to the tcp server, and return the settings."""
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
for i in range(300):
logging.info("Connecting to: %s, attempt %d", tcp_addr, i)
try:
sock.connect(tcp_addr)
break
except socket.error:
time.sleep(1)
else:
sock.connect(tcp_addr) # One last try, but don't catch this error.
logging.info("Connected.")
map_data = read_tcp(sock)
settings_str = read_tcp(sock)
if not settings_str:
raise socket.error("Failed to read")
settings = json.loads(settings_str.decode())
logging.info("Got settings. map_name: %s.", settings["map_name"])
logging.debug("settings: %s", settings)
settings["map_data"] = map_data
return sock, settings
def log_msg(prefix, msg):
logging.debug("%s: len: %s, hash: %s, msg: 0x%s", prefix, len(msg),
hashlib.md5(msg).hexdigest()[:6], binascii.hexlify(msg[:25]))
def udp_to_tcp(udp_sock, tcp_conn):
while True:
msg, _ = udp_sock.recvfrom(2**16)
log_msg("read_udp", msg)
if not msg:
return
write_tcp(tcp_conn, msg)
def tcp_to_udp(tcp_conn, udp_sock, udp_to_addr):
while True:
msg = read_tcp(tcp_conn)
if not msg:
return
log_msg("write_udp", msg)
udp_sock.sendto(msg, udp_to_addr)
def read_tcp(conn):
read_size = read_tcp_size(conn, 4)
if not read_size:
return
size = struct.unpack("@I", read_size)[0]
msg = read_tcp_size(conn, size)
log_msg("read_tcp", msg)
return msg
def read_tcp_size(conn, size):
"""Read `size` number of bytes from `conn`, retrying as needed."""
chunks = []
bytes_read = 0
while bytes_read < size:
chunk = conn.recv(size - bytes_read)
if not chunk:
if bytes_read > 0:
logging.warning("Incomplete read: %s of %s.", bytes_read, size)
return
chunks.append(chunk)
bytes_read += len(chunk)
return b"".join(chunks)
def write_tcp(conn, msg):
log_msg("write_tcp", msg)
conn.sendall(struct.pack("@I", len(msg)))
conn.sendall(msg)
def forward_ports(remote_host, local_host, local_listen_ports,
remote_listen_ports):
"""Forwards ports such that multiplayer works between machines.
Args:
remote_host: Where to ssh to.
local_host: "127.0.0.1" or "::1".
local_listen_ports: Which ports to listen on locally to forward remotely.
remote_listen_ports: Which ports to listen on remotely to forward locally.
Returns:
The ssh process.
Raises:
ValueError: if it can't find ssh.
"""
if ":" in local_host and not local_host.startswith("["):
local_host = "[%s]" % local_host
ssh = shutil.which("ssh") or shutil.which("plink")
if not ssh:
raise ValueError("Couldn't find an ssh client.")
args = [ssh, remote_host]
for local_port in local_listen_ports:
args += ["-L", "%s:%s:%s:%s" % (local_host, local_port,
local_host, local_port)]
for remote_port in remote_listen_ports:
args += ["-R", "%s:%s:%s:%s" % (local_host, remote_port,
local_host, remote_port)]
logging.info("SSH port forwarding: %s", " ".join(args))
return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, close_fds=(os.name == "posix"))
class RestartError(Exception):
pass
class LanSC2Env(sc2_env.SC2Env):
"""A Starcraft II environment for playing vs humans over LAN.
This owns a single instance, and expects to join a game hosted by some other
script, likely play_vs_agent.py.
"""
def __init__(self,
*,
host="127.0.0.1",
config_port=None,
race=None,
name="<unknown>",
agent_interface_format=None,
discount=1.,
visualize=False,
step_mul=None,
realtime=False,
replay_dir=None,
replay_prefix=None):
"""Create a SC2 Env that connects to a remote instance of the game.
This assumes that the game is already up and running, and it only needs to
join. You need some other script to launch the process and call
RequestCreateGame. It also assumes that it's a multiplayer game, and that
the ports are consecutive.
You must pass a resolution that you want to play at. You can send either
feature layer resolution or rgb resolution or both. If you send both you
must also choose which to use as your action space. Regardless of which you
choose you must send both the screen and minimap resolutions.
For each of the 4 resolutions, either specify size or both width and
height. If you specify size then both width and height will take that value.
Args:
host: Which ip to use. Either ipv4 or ipv6 localhost.
config_port: Where to find the config port.
race: Race for this agent.
name: The name of this agent, for saving in the replay.
agent_interface_format: AgentInterfaceFormat object describing the
format of communication between the agent and the environment, else
just InterfaceOptions to use passthrough.
discount: Returned as part of the observation.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
replay_dir: Directory to save a replay.
replay_prefix: An optional prefix to use when saving replays.
Raises:
ValueError: if the race is invalid.
ValueError: if the resolutions aren't specified correctly.
ValueError: if the host or port are invalid.
"""
if host not in ("127.0.0.1", "::1"):
raise ValueError("Bad host arguments. Must be a localhost")
if not config_port:
raise ValueError("Must pass a config_port.")
if agent_interface_format is None:
raise ValueError("Please specify agent_interface_format.")
if not race:
race = sc2_env.Race.random
self._num_agents = 1
self._discount = discount
self._step_mul = step_mul or 8
self._realtime = realtime
self._last_step_time = None
self._save_replay_episodes = 1 if replay_dir else 0
self._replay_dir = replay_dir
self._replay_prefix = replay_prefix
self._score_index = -1 # Win/loss only.
self._score_multiplier = 1
self._episode_length = sc2_env.MAX_STEP_COUNT
self._ensure_available_actions = False
self._discount_zero_after_timeout = False
self._parallel = run_parallel.RunParallel() # Needed for multiplayer.
self._game_info = None
self._action_delay_fns = [None]
interface = self._get_interface(
agent_interface_format=agent_interface_format, require_raw=visualize)
self._launch_remote(host, config_port, race, name, interface,
agent_interface_format)
self._finalize(visualize)
def _launch_remote(self, host, config_port, race, name, interface,
agent_interface_format):
"""Make sure this stays synced with bin/play_vs_agent.py."""
self._tcp_conn, settings = tcp_client(Addr(host, config_port))
self._map_name = settings["map_name"]
if settings["remote"]:
self._udp_sock = udp_server(
Addr(host, settings["ports"]["server"]["game"]))
daemon_thread(tcp_to_udp,
(self._tcp_conn, self._udp_sock,
Addr(host, settings["ports"]["client"]["game"])))
daemon_thread(udp_to_tcp, (self._udp_sock, self._tcp_conn))
extra_ports = [
settings["ports"]["server"]["game"],
settings["ports"]["server"]["base"],
settings["ports"]["client"]["game"],
settings["ports"]["client"]["base"],
]
self._run_config = run_configs.get(version=settings["game_version"])
self._sc2_procs = [self._run_config.start(
extra_ports=extra_ports, host=host, window_loc=(700, 50),
want_rgb=interface.HasField("render"))]
self._controllers = [p.controller for p in self._sc2_procs]
# Create the join request.
join = sc_pb.RequestJoinGame(options=interface)
join.race = race
join.player_name = name
join.shared_port = 0 # unused
join.server_ports.game_port = settings["ports"]["server"]["game"]
join.server_ports.base_port = settings["ports"]["server"]["base"]
join.client_ports.add(game_port=settings["ports"]["client"]["game"],
base_port=settings["ports"]["client"]["base"])
self._controllers[0].save_map(settings["map_path"], settings["map_data"])
self._controllers[0].join_game(join)
self._game_info = [self._controllers[0].game_info()]
self._features = [features.features_from_game_info(
game_info=self._game_info[0],
agent_interface_format=agent_interface_format)]
def _restart(self):
# Can't restart since it's not clear how you'd coordinate that with the
# other players.
raise RestartError("Can't restart")
def close(self):
if hasattr(self, "_tcp_conn") and self._tcp_conn:
self._tcp_conn.close()
self._tcp_conn = None
if hasattr(self, "_udp_sock") and self._udp_sock:
self._udp_sock.close()
self._udp_sock = None
self._run_config = None
if hasattr(self, "_parallel") and self._parallel is not None:
self._parallel.shutdown()
self._parallel = None
super(LanSC2Env, self).close()
| pysc2-master | pysc2/env/lan_sc2_env.py |
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Enumerations used for configuring the SC2 environment."""
import enum
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class Race(enum.IntEnum):
random = sc_common.Random
protoss = sc_common.Protoss
terran = sc_common.Terran
zerg = sc_common.Zerg
class Difficulty(enum.IntEnum):
"""Bot difficulties."""
very_easy = sc_pb.VeryEasy
easy = sc_pb.Easy
medium = sc_pb.Medium
medium_hard = sc_pb.MediumHard
hard = sc_pb.Hard
harder = sc_pb.Harder
very_hard = sc_pb.VeryHard
cheat_vision = sc_pb.CheatVision
cheat_money = sc_pb.CheatMoney
cheat_insane = sc_pb.CheatInsane
class BotBuild(enum.IntEnum):
"""Bot build strategies."""
random = sc_pb.RandomBuild
rush = sc_pb.Rush
timing = sc_pb.Timing
power = sc_pb.Power
macro = sc_pb.Macro
air = sc_pb.Air
| pysc2-master | pysc2/env/enums.py |
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates SC2 processes and games for remote agents to connect into."""
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import portspicker
from pysc2.lib import protocol
from pysc2.lib import remote_controller
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
class VsAgent(object):
"""Host a remote agent vs remote agent game.
Starts two SC2 processes, one for each of two remote agents to connect to.
Call create_game, then have the agents connect to their respective port in
host_ports, specifying lan_ports in the join game request.
Agents should leave the game once it has finished, then another game can
be created. Note that failure of either agent to leave prior to creating
the next game will lead to SC2 crashing.
Best used as a context manager for simple and timely resource release.
**NOTE THAT** currently re-connecting to the same SC2 process is flaky.
If you experience difficulties the workaround is to only create one game
per instantiation of VsAgent.
"""
def __init__(self):
self._num_agents = 2
self._run_config = run_configs.get()
self._processes = []
self._controllers = []
self._saved_maps = set()
# Reserve LAN ports.
self._lan_ports = portspicker.pick_unused_ports(self._num_agents * 2)
# Start SC2 processes.
for _ in range(self._num_agents):
process = self._run_config.start(extra_ports=self._lan_ports)
self._processes.append(process)
self._controllers.append(process.controller)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.close()
def __del__(self):
self.close()
def create_game(self, map_name):
"""Create a game for the agents to join.
Args:
map_name: The map to use.
"""
self._reconnect()
map_inst = maps.get(map_name)
map_data = map_inst.data(self._run_config)
if map_name not in self._saved_maps:
for controller in self._controllers:
controller.save_map(map_inst.path, map_data)
self._saved_maps.add(map_name)
# Form the create game message.
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(map_path=map_inst.path),
disable_fog=False)
# Set up for two agents.
for _ in range(self._num_agents):
create.player_setup.add(type=sc_pb.Participant)
# Create the game.
self._controllers[0].create_game(create)
self._disconnect()
def _disconnect(self):
for c in self._controllers:
c.close()
self._controllers = []
def _reconnect(self, **kwargs):
if not self._controllers:
self._controllers = [
remote_controller.RemoteController(p.host, p.port, p, **kwargs)
for p in self._processes]
def save_replay(self, replay_dir, replay_name):
self._reconnect()
return self._run_config.save_replay(
self._controllers[0].save_replay(), replay_dir, replay_name)
@property
def hosts(self):
"""The hosts that the remote agents should connect to."""
return [process.host for process in self._processes]
@property
def host_ports(self):
"""The WebSocket ports that the remote agents should connect to."""
return [process.port for process in self._processes]
@property
def lan_ports(self):
"""The LAN ports which the remote agents should specify when joining."""
return self._lan_ports
def close(self):
"""Shutdown and free all resources."""
try:
self._reconnect(timeout_seconds=1)
for controller in self._controllers:
controller.quit()
except (remote_controller.ConnectError, protocol.ConnectionError):
pass
self._controllers = []
for process in self._processes:
process.close()
self._processes = []
portspicker.return_ports(self._lan_ports)
self._lan_ports = []
class VsBot(object):
"""Host a remote agent vs bot game.
Starts a single SC2 process. Call create_game, then have the agent connect
to host_port.
The agent should leave the game once it has finished, then another game can
be created. Note that failure of the agent to leave prior to creating
the next game will lead to SC2 crashing.
Best used as a context manager for simple and timely resource release.
**NOTE THAT** currently re-connecting to the same SC2 process is flaky.
If you experience difficulties the workaround is to only create one game
per instantiation of VsBot.
"""
def __init__(self):
# Start the SC2 process.
self._run_config = run_configs.get()
self._process = self._run_config.start()
self._controller = self._process.controller
self._saved_maps = set()
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.close()
def __del__(self):
self.close()
def create_game(
self,
map_name,
bot_difficulty=sc_pb.VeryEasy,
bot_race=sc_common.Random,
bot_first=False):
"""Create a game, one remote agent vs the specified bot.
Args:
map_name: The map to use.
bot_difficulty: The difficulty of the bot to play against.
bot_race: The race for the bot.
bot_first: Whether the bot should be player 1 (else is player 2).
"""
self._reconnect()
self._controller.ping()
# Form the create game message.
map_inst = maps.get(map_name)
map_data = map_inst.data(self._run_config)
if map_name not in self._saved_maps:
self._controller.save_map(map_inst.path, map_data)
self._saved_maps.add(map_name)
create = sc_pb.RequestCreateGame(
local_map=sc_pb.LocalMap(map_path=map_inst.path, map_data=map_data),
disable_fog=False)
# Set up for one bot, one agent.
if not bot_first:
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer, race=bot_race, difficulty=bot_difficulty)
if bot_first:
create.player_setup.add(type=sc_pb.Participant)
# Create the game.
self._controller.create_game(create)
self._disconnect()
def _disconnect(self):
self._controller.close()
self._controller = None
def _reconnect(self, **kwargs):
if not self._controller:
self._controller = remote_controller.RemoteController(
self._process.host, self._process.port, self._process, **kwargs)
def save_replay(self, replay_dir, replay_name):
self._reconnect()
return self._run_config.save_replay(
self._controller.save_replay(), replay_dir, replay_name)
@property
def host(self):
"""The host that the remote agent should connect to."""
return self._process.host
@property
def host_port(self):
"""The WebSocket port that the remote agent should connect to."""
return self._process.port
def close(self):
"""Shutdown and free all resources."""
if hasattr(self, "_process") and self._process is not None:
try:
self._reconnect(timeout_seconds=1)
self._controller.quit()
except (remote_controller.ConnectError, protocol.ConnectionError):
pass
self._controller = None
self._process.close()
self._process = None
| pysc2-master | pysc2/env/host_remote_agent.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests of the StarCraft2 mock environment."""
from absl.testing import absltest
import mock
import numpy as np
from pysc2.env import enums
from pysc2.env import environment
from pysc2.env import mock_sc2_env
from pysc2.env import sc2_env
from pysc2.lib import features
from s2clientprotocol import common_pb2
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2
class _TestMixin(object):
def assert_spec(self, array, shape, dtype):
self.assertSequenceEqual(array.shape, shape)
self.assertEqual(array.dtype, dtype)
def assert_equal(self, actual, expected):
np.testing.assert_equal(actual, expected)
def assert_reset(self, env):
expected = env.next_timestep[0]._replace(
step_type=environment.StepType.FIRST, reward=0, discount=0)
timestep = env.reset()
self.assert_equal(timestep, [expected])
def assert_first_step(self, env):
expected = env.next_timestep[0]._replace(
step_type=environment.StepType.FIRST, reward=0, discount=0)
timestep = env.step([mock.sentinel.action])
self.assert_equal(timestep, [expected])
def assert_mid_step(self, env):
expected = env.next_timestep[0]._replace(
step_type=environment.StepType.MID)
timestep = env.step([mock.sentinel.action])
self.assert_equal(timestep, [expected])
def assert_last_step(self, env):
expected = env.next_timestep[0]._replace(
step_type=environment.StepType.LAST,
discount=0.)
timestep = env.step([mock.sentinel.action])
self.assert_equal(timestep, [expected])
def _test_episode(self, env):
env.next_timestep = [env.next_timestep[0]._replace(
step_type=environment.StepType.MID)]
self.assert_first_step(env)
for step in range(1, 10):
env.next_timestep = [env.next_timestep[0]._replace(
reward=step, discount=step / 10)]
self.assert_mid_step(env)
env.next_timestep = [env.next_timestep[0]._replace(
step_type=environment.StepType.LAST, reward=10, discount=0.0)]
self.assert_last_step(env)
def _test_episode_length(self, env, length):
self.assert_reset(env)
for _ in range(length - 1):
self.assert_mid_step(env)
self.assert_last_step(env)
self.assert_first_step(env)
for _ in range(length - 1):
self.assert_mid_step(env)
self.assert_last_step(env)
class TestTestEnvironment(_TestMixin, absltest.TestCase):
def setUp(self):
super(TestTestEnvironment, self).setUp()
self._env = mock_sc2_env._TestEnvironment(
num_agents=1,
observation_spec=({'mock': [10, 1]},),
action_spec=(mock.sentinel.action_spec,))
def test_observation_spec(self):
self.assertEqual(self._env.observation_spec(), ({'mock': [10, 1]},))
def test_action_spec(self):
self.assertEqual(self._env.action_spec(), (mock.sentinel.action_spec,))
def test_default_observation(self):
observation = self._env._default_observation(
self._env.observation_spec()[0], 0)
self.assert_equal(observation, {'mock': np.zeros([10, 1], dtype=np.int32)})
def test_episode(self):
self._env.episode_length = float('inf')
self._test_episode(self._env)
def test_two_episodes(self):
self._env.episode_length = float('inf')
self._test_episode(self._env)
self._test_episode(self._env)
def test_episode_length(self):
self._env.episode_length = 16
self._test_episode_length(self._env, length=16)
class TestSC2TestEnv(_TestMixin, absltest.TestCase):
def test_episode(self):
env = mock_sc2_env.SC2TestEnv(
map_name='nonexistant map',
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32)))
env.episode_length = float('inf')
self._test_episode(env)
def test_episode_length(self):
env = mock_sc2_env.SC2TestEnv(
map_name='nonexistant map',
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32)))
self.assertEqual(env.episode_length, 10)
self._test_episode_length(env, length=10)
def test_screen_minimap_size(self):
env = mock_sc2_env.SC2TestEnv(
map_name='nonexistant map',
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(
screen=(84, 87),
minimap=(64, 67))))
timestep = env.reset()
self.assertLen(timestep, 1)
self.assert_spec(timestep[0].observation['feature_screen'],
[len(features.SCREEN_FEATURES), 87, 84], np.int32)
self.assert_spec(timestep[0].observation['feature_minimap'],
[len(features.MINIMAP_FEATURES), 67, 64], np.int32)
def test_feature_units_are_supported(self):
env = mock_sc2_env.SC2TestEnv(
map_name='nonexistant map',
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32),
use_feature_units=True))
self.assertIn('feature_units', env.observation_spec()[0])
def test_game_info(self):
env = mock_sc2_env.SC2TestEnv(
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32),
use_feature_units=True),
players=[sc2_env.Agent(sc2_env.Race.protoss, 'player'),
sc2_env.Bot(sc2_env.Race.random, sc2_env.Difficulty.easy,
sc2_env.BotBuild.random)])
self.assertLen(env.game_info, 1)
self.assertEqual(
env.game_info[0],
sc2api_pb2.ResponseGameInfo(
start_raw=raw_pb2.StartRaw(
map_size=common_pb2.Size2DI(
x=mock_sc2_env.DUMMY_MAP_SIZE,
y=mock_sc2_env.DUMMY_MAP_SIZE)),
options=sc2api_pb2.InterfaceOptions(
feature_layer=sc2api_pb2.SpatialCameraSetup(
resolution=common_pb2.Size2DI(x=64, y=64),
minimap_resolution=common_pb2.Size2DI(x=32, y=32),
width=24)),
player_info=[
sc2api_pb2.PlayerInfo(
player_id=1,
type=sc2api_pb2.PlayerType.Participant,
race_requested=enums.Race.protoss,
player_name='player'),
sc2api_pb2.PlayerInfo(
player_id=2,
type=sc2api_pb2.PlayerType.Computer,
race_requested=enums.Race.random,
difficulty=enums.Difficulty.easy,
ai_build=enums.BotBuild.random,
player_name='easy')
]))
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/env/mock_sc2_env_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An env wrapper to print the available actions."""
from pysc2.env import base_env_wrapper
class AvailableActionsPrinter(base_env_wrapper.BaseEnvWrapper):
"""An env wrapper to print the available actions."""
def __init__(self, env):
super(AvailableActionsPrinter, self).__init__(env)
self._seen = set()
self._action_spec = self.action_spec()[0]
def step(self, *args, **kwargs):
all_obs = super(AvailableActionsPrinter, self).step(*args, **kwargs)
for obs in all_obs:
for avail in obs.observation["available_actions"]:
if avail not in self._seen:
self._seen.add(avail)
self._print(self._action_spec.functions[avail].str(True))
return all_obs
def _print(self, s):
print(s)
| pysc2-master | pysc2/env/available_actions_printer.py |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests that mock environment has same shape outputs as true environment."""
from absl.testing import absltest
from pysc2.env import mock_sc2_env
from pysc2.env import sc2_env
class TestCompareEnvironments(absltest.TestCase):
@classmethod
def setUpClass(cls):
super(TestCompareEnvironments, cls).setUpClass()
players = [
sc2_env.Agent(race=sc2_env.Race.terran),
sc2_env.Agent(race=sc2_env.Race.protoss),
]
kwargs = {
'map_name': 'Flat64',
'players': players,
'agent_interface_format': [
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=(32, 64),
minimap=(8, 16)
),
rgb_dimensions=sc2_env.Dimensions(
screen=(31, 63),
minimap=(7, 15)
),
action_space=sc2_env.ActionSpace.FEATURES
),
sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(screen=64, minimap=32)
)
]
}
cls._env = sc2_env.SC2Env(**kwargs)
cls._mock_env = mock_sc2_env.SC2TestEnv(**kwargs)
@classmethod
def tearDownClass(cls):
super(TestCompareEnvironments, cls).tearDownClass()
cls._env.close()
cls._mock_env.close()
def test_observation_spec(self):
self.assertEqual(self._env.observation_spec(),
self._mock_env.observation_spec())
def test_action_spec(self):
self.assertEqual(self._env.action_spec(), self._mock_env.action_spec())
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/env/mock_sc2_env_comparison_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/__init__.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A run loop for agent/environment interaction."""
import time
def run_loop(agents, env, max_frames=0, max_episodes=0):
"""A run loop to have agents and an environment interact."""
total_frames = 0
total_episodes = 0
start_time = time.time()
observation_spec = env.observation_spec()
action_spec = env.action_spec()
for agent, obs_spec, act_spec in zip(agents, observation_spec, action_spec):
agent.setup(obs_spec, act_spec)
try:
while not max_episodes or total_episodes < max_episodes:
total_episodes += 1
timesteps = env.reset()
for a in agents:
a.reset()
while True:
total_frames += 1
actions = [agent.step(timestep)
for agent, timestep in zip(agents, timesteps)]
if max_frames and total_frames >= max_frames:
return
if timesteps[0].last():
break
timesteps = env.step(actions)
except KeyboardInterrupt:
pass
finally:
elapsed_time = time.time() - start_time
print("Took %.3f seconds for %s steps: %.3f fps" % (
elapsed_time, total_frames, total_frames / elapsed_time))
| pysc2-master | pysc2/env/run_loop.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Python RL Environment API."""
import abc
import collections
import enum
class TimeStep(collections.namedtuple(
'TimeStep', ['step_type', 'reward', 'discount', 'observation'])):
"""Returned with every call to `step` and `reset` on an environment.
A `TimeStep` contains the data emitted by an environment at each step of
interaction. A `TimeStep` holds a `step_type`, an `observation`, and an
associated `reward` and `discount`.
The first `TimeStep` in a sequence will have `StepType.FIRST`. The final
`TimeStep` will have `StepType.LAST`. All other `TimeStep`s in a sequence will
have `StepType.MID.
Attributes:
step_type: A `StepType` enum value.
reward: A scalar, or 0 if `step_type` is `StepType.FIRST`, i.e. at the
start of a sequence.
discount: A discount value in the range `[0, 1]`, or 0 if `step_type`
is `StepType.FIRST`, i.e. at the start of a sequence.
observation: A NumPy array, or a dict, list or tuple of arrays.
"""
__slots__ = ()
def first(self):
return self.step_type is StepType.FIRST
def mid(self):
return self.step_type is StepType.MID
def last(self):
return self.step_type is StepType.LAST
class StepType(enum.IntEnum):
"""Defines the status of a `TimeStep` within a sequence."""
# Denotes the first `TimeStep` in a sequence.
FIRST = 0
# Denotes any `TimeStep` in a sequence that is not FIRST or LAST.
MID = 1
# Denotes the last `TimeStep` in a sequence.
LAST = 2
class Base(metaclass=abc.ABCMeta): # pytype: disable=ignored-abstractmethod
"""Abstract base class for Python RL environments."""
@abc.abstractmethod
def reset(self):
"""Starts a new sequence and returns the first `TimeStep` of this sequence.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` of `FIRST`.
reward: Zero.
discount: Zero.
observation: A NumPy array, or a dict, list or tuple of arrays
corresponding to `observation_spec()`.
"""
@abc.abstractmethod
def step(self, action):
"""Updates the environment according to the action and returns a `TimeStep`.
If the environment returned a `TimeStep` with `StepType.LAST` at the
previous step, this call to `step` will start a new sequence and `action`
will be ignored.
This method will also start a new sequence if called after the environment
has been constructed and `restart` has not been called. Again, in this case
`action` will be ignored.
Args:
action: A NumPy array, or a dict, list or tuple of arrays corresponding to
`action_spec()`.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` value.
reward: Reward at this timestep.
discount: A discount in the range [0, 1].
observation: A NumPy array, or a dict, list or tuple of arrays
corresponding to `observation_spec()`.
"""
@abc.abstractmethod
def observation_spec(self):
"""Defines the observations provided by the environment.
Returns:
A tuple of specs (one per agent), where each spec is a dict of shape
tuples.
"""
@abc.abstractmethod
def action_spec(self):
"""Defines the actions that should be provided to `step`.
Returns:
A tuple of specs (one per agent), where each spec is something that
defines the shape of the actions.
"""
def close(self):
"""Frees any resources used by the environment.
Implement this method for an environment backed by an external process.
This method be used directly
```python
env = Env(...)
# Use env.
env.close()
```
or via a context manager
```python
with Env(...) as env:
# Use env.
```
"""
pass
def __enter__(self):
"""Allows the environment to be used in a with-statement context."""
return self
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
"""Allows the environment to be used in a with-statement context."""
self.close()
def __del__(self):
self.close()
| pysc2-master | pysc2/env/environment.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import concurrent.futures
import random
from absl.testing import absltest
import dm_env
from dm_env import test_utils
import numpy as np
from pysc2.env import converted_env
from pysc2.env import mock_sc2_env
from pysc2.env import sc2_env
from pysc2.env.converter import converter
from pysc2.env.converter.proto import converter_pb2
from pysc2.lib import features
from s2clientprotocol import common_pb2
from s2clientprotocol import sc2api_pb2
def _action(delay: int):
return {
'function': np.int32(1),
'world': np.int32(2949),
'queued': np.int32(0),
'unit_tags': np.array([1] + [255] * 63, dtype=np.int32),
'target_unit_tag': np.int32(0),
'repeat': np.int32(0),
'delay': np.int32(delay)
}
def _converter_factory(game_info: sc2api_pb2.ResponseGameInfo):
return converter.Converter(
converter_pb2.ConverterSettings(
raw_settings=converter_pb2.ConverterSettings.RawSettings(
num_unit_features=40,
max_unit_selection_size=64,
max_unit_count=512,
resolution=common_pb2.Size2DI(x=128, y=128)),
num_action_types=540,
num_unit_types=217,
num_upgrade_types=86,
max_num_upgrades=40),
environment_info=converter_pb2.EnvironmentInfo(game_info=game_info))
def _agent_interface_format():
return features.AgentInterfaceFormat(
use_raw_units=True, use_raw_actions=True, send_observation_proto=True)
class StreamedEnvTest(absltest.TestCase):
def _check_episode(self, stream):
timestep = stream.reset()
self.assertIsNotNone(timestep)
while True:
timestep = stream.step(_action(random.randint(1, 5)))
if timestep.step_type == dm_env.StepType.LAST:
break
self.assertIsNotNone(timestep)
def test_single_player(self):
env = converted_env.ConvertedEnvironment(
converter_factories=[_converter_factory],
env=mock_sc2_env.SC2TestEnv(
players=[
sc2_env.Agent(race=sc2_env.Race.protoss),
sc2_env.Bot(
race=sc2_env.Race.zerg,
difficulty=sc2_env.Difficulty.very_easy)
],
agent_interface_format=_agent_interface_format(),
game_steps_per_episode=30,
),
)
with converted_env.make_streams(env)[0] as stream:
self._check_episode(stream)
def test_two_player(self):
env = converted_env.ConvertedEnvironment(
converter_factories=[_converter_factory, _converter_factory],
env=mock_sc2_env.SC2TestEnv(
players=[
sc2_env.Agent(race=sc2_env.Race.protoss),
sc2_env.Agent(race=sc2_env.Race.zerg),
],
agent_interface_format=[
_agent_interface_format() for _ in range(2)
],
game_steps_per_episode=30,
),
)
s0, s1 = converted_env.make_streams(env)
with s0, s1:
fs = []
with concurrent.futures.ThreadPoolExecutor() as executor:
fs.append(executor.submit(self._check_episode, s0))
fs.append(executor.submit(self._check_episode, s1))
concurrent.futures.wait(fs)
for f in fs:
f.result()
class StreamedEnvConformanceTest(test_utils.EnvironmentTestMixin,
absltest.TestCase):
def make_object_under_test(self):
env = converted_env.ConvertedEnvironment(
env=mock_sc2_env.SC2TestEnv(
players=[
sc2_env.Agent(race=sc2_env.Race.protoss),
sc2_env.Bot(
race=sc2_env.Race.zerg,
difficulty=sc2_env.Difficulty.very_easy)
],
agent_interface_format=_agent_interface_format(),
game_steps_per_episode=10,
),
converter_factories=[_converter_factory])
return converted_env.make_streams(env)[0]
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/env/converted_env_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Starcraft II environment for playing using remote SC2 instances."""
from typing import Sequence
from absl import logging
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import sc2_env
from pysc2.lib import features
from pysc2.lib import remote_controller
from pysc2.lib import run_parallel
from s2clientprotocol import sc2api_pb2 as sc_pb
class RestartError(Exception):
pass
class RemoteSC2Env(sc2_env.SC2Env):
"""A Remote Starcraft II environment for playing vs other agents or humans.
Unlike SC2Env, this doesn't actually start any instances and only connects
to a remote instance.
This assumes a 2 player game, and works best with play_vs_agent.py.
"""
def __init__(self,
*,
map_name=None,
save_map=True,
host="127.0.0.1",
host_port=None,
lan_port=None,
race=None,
name="<unknown>",
agent_interface_format=None,
discount=1.,
visualize=False,
step_mul=None,
realtime=False,
replay_dir=None,
replay_prefix=None):
"""Create a SC2 Env that connects to a remote instance of the game.
This assumes that the game is already up and running, and that it only
needs to join the game - and leave once the game has ended. You need some
other script to launch the SC2 process and call RequestCreateGame. Note
that you must call close to leave the game when finished. Not doing so
will lead to issues when attempting to create another game on the same
SC2 process.
This class assumes that the game is multiplayer. LAN ports may be
specified either as a base port (from which the others will be implied),
or as an explicit list.
You must specify an agent_interface_format. See the `AgentInterfaceFormat`
documentation for further detail.
Args:
map_name: Name of a SC2 map. Run bin/map_list to get the full list of
known maps. Alternatively, pass a Map instance. Take a look at the
docs in maps/README.md for more information on available maps.
save_map: Whether to save map data before joining the game.
host: Host where the SC2 process we're connecting to is running.
host_port: The WebSocket port for the SC2 process we're connecting to.
lan_port: Either an explicit sequence of LAN ports corresponding to
[server game port, ...base port, client game port, ...base port],
or an int specifying base port - equivalent to specifying the
sequence [lan_port, lan_port+1, lan_port+2, lan_port+3].
race: Race for this agent.
name: The name of this agent, for saving in the replay.
agent_interface_format: AgentInterfaceFormat object describing the
format of communication between the agent and the environment, else
just InterfaceOptions to use passthrough.
discount: Returned as part of the observation.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
replay_dir: Directory to save a replay.
replay_prefix: An optional prefix to use when saving replays.
Raises:
ValueError: if the race is invalid.
ValueError: if the resolutions aren't specified correctly.
ValueError: if lan_port is a sequence but its length != 4.
"""
if agent_interface_format is None:
raise ValueError("Please specify agent_interface_format.")
if not race:
race = sc2_env.Race.random
map_inst = map_name and maps.get(map_name)
self._map_name = map_name
self._game_info = None
self._num_agents = 1
self._discount = discount
self._step_mul = step_mul or (map_inst.step_mul if map_inst else 8)
self._realtime = realtime
self._last_step_time = None
self._save_replay_episodes = 1 if replay_dir else 0
self._replay_dir = replay_dir
self._replay_prefix = replay_prefix
self._score_index = -1 # Win/loss only.
self._score_multiplier = 1
self._episode_length = sc2_env.MAX_STEP_COUNT
self._ensure_available_actions = False
self._discount_zero_after_timeout = False
self._run_config = run_configs.get()
self._parallel = run_parallel.RunParallel() # Needed for multiplayer.
self._in_game = False
self._action_delay_fns = [None]
interface = self._get_interface(
agent_interface_format=agent_interface_format, require_raw=visualize)
if isinstance(lan_port, Sequence):
if len(lan_port) != 4:
raise ValueError("lan_port sequence must be of length 4")
ports = lan_port[:]
else:
ports = [lan_port + p for p in range(4)] # 2 * num players *in the game*.
self._connect_remote(
host, host_port, ports, race, name, map_inst, save_map, interface,
agent_interface_format)
self._finalize(visualize)
def close(self):
# Leave the game so that another may be created in the same SC2 process.
if self._in_game:
logging.info("Leaving game.")
self._controllers[0].leave()
self._in_game = False
logging.info("Left game.")
self._controllers[0].close()
if hasattr(self, "_parallel") and self._parallel is not None:
self._parallel.shutdown()
self._parallel = None
# We don't own the SC2 process, we shouldn't call quit in the super class.
self._controllers = None
self._game_info = None
super(RemoteSC2Env, self).close()
def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst,
save_map, interface, agent_interface_format):
"""Make sure this stays synced with bin/agent_remote.py."""
# Connect!
logging.info("Connecting...")
self._controllers = [remote_controller.RemoteController(host, host_port)]
logging.info("Connected")
if map_inst and save_map:
run_config = run_configs.get()
self._controllers[0].save_map(map_inst.path, map_inst.data(run_config))
# Create the join request.
join = sc_pb.RequestJoinGame(options=interface)
join.race = race
join.player_name = name
join.shared_port = 0 # unused
join.server_ports.game_port = lan_ports.pop(0)
join.server_ports.base_port = lan_ports.pop(0)
join.client_ports.add(
game_port=lan_ports.pop(0), base_port=lan_ports.pop(0))
logging.info("Joining game.")
self._controllers[0].join_game(join)
self._game_info = [self._controllers[0].game_info()]
if not self._map_name:
self._map_name = self._game_info[0].map_name
self._features = [features.features_from_game_info(
game_info=self._game_info[0],
agent_interface_format=agent_interface_format)]
self._in_game = True
logging.info("Game joined.")
def _restart(self):
# Can't restart since it's not clear how you'd coordinate that with the
# other players.
raise RestartError("Can't restart")
| pysc2-master | pysc2/env/remote_sc2_env.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Starcraft II environment."""
# pylint: disable=g-complex-comprehension
import collections
import copy
import random
import time
from absl import logging
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import enums
from pysc2.env import environment
from pysc2.lib import actions as actions_lib
from pysc2.lib import features
from pysc2.lib import metrics
from pysc2.lib import portspicker
from pysc2.lib import renderer_human
from pysc2.lib import run_parallel
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
sw = stopwatch.sw
possible_results = {
sc_pb.Victory: 1,
sc_pb.Defeat: -1,
sc_pb.Tie: 0,
sc_pb.Undecided: 0,
}
Race = enums.Race
Difficulty = enums.Difficulty
BotBuild = enums.BotBuild
# Re-export these names to make it easy to construct the environment.
ActionSpace = actions_lib.ActionSpace # pylint: disable=invalid-name
Dimensions = features.Dimensions # pylint: disable=invalid-name
AgentInterfaceFormat = features.AgentInterfaceFormat # pylint: disable=invalid-name
parse_agent_interface_format = features.parse_agent_interface_format
def to_list(arg):
return arg if isinstance(arg, list) else [arg]
def get_default(a, b):
return b if a is None else a
class Agent(collections.namedtuple("Agent", ["race", "name"])):
"""Define an Agent. It can have a single race or a list of races."""
def __new__(cls, race, name=None):
return super(Agent, cls).__new__(cls, to_list(race), name or "<unknown>")
class Bot(collections.namedtuple("Bot", ["race", "difficulty", "build"])):
"""Define a Bot. It can have a single or list of races or builds."""
def __new__(cls, race, difficulty, build=None):
return super(Bot, cls).__new__(
cls, to_list(race), difficulty, to_list(build or BotBuild.random))
_DelayedAction = collections.namedtuple(
"DelayedAction", ["game_loop", "action"])
REALTIME_GAME_LOOP_SECONDS = 1 / 22.4
MAX_STEP_COUNT = 524000 # The game fails above 2^19=524288 steps.
NUM_ACTION_DELAY_BUCKETS = 10
class SC2Env(environment.Base):
"""A Starcraft II environment.
The implementation details of the action and observation specs are in
lib/features.py
"""
def __init__(self,
*,
map_name=None,
battle_net_map=False,
players=None,
agent_interface_format=None,
discount=1.,
discount_zero_after_timeout=False,
visualize=False,
step_mul=None,
realtime=False,
save_replay_episodes=0,
replay_dir=None,
replay_prefix=None,
game_steps_per_episode=None,
score_index=None,
score_multiplier=None,
random_seed=None,
disable_fog=False,
ensure_available_actions=True,
version=None):
"""Create a SC2 Env.
You must pass a resolution that you want to play at. You can send either
feature layer resolution or rgb resolution or both. If you send both you
must also choose which to use as your action space. Regardless of which you
choose you must send both the screen and minimap resolutions.
For each of the 4 resolutions, either specify size or both width and
height. If you specify size then both width and height will take that value.
Args:
map_name: Name of a SC2 map. Run bin/map_list to get the full list of
known maps. Alternatively, pass a Map instance. Take a look at the
docs in maps/README.md for more information on available maps. Can
also be a list of map names or instances, in which case one will be
chosen at random per episode.
battle_net_map: Whether to use the battle.net versions of the map(s).
players: A list of Agent and Bot instances that specify who will play.
agent_interface_format: A sequence containing one AgentInterfaceFormat per
agent, matching the order of agents specified in the players list. Or
a single AgentInterfaceFormat to be used for all agents. Note that
InterfaceOptions may be supplied in place of AgentInterfaceFormat, in
which case no action or observation processing will be carried out by
PySC2. The sc_pb.ResponseObservation proto will be returned as the
observation for the agent and passed actions must be instances of
sc_pb.Action. This is intended for agents which use custom environment
conversion code.
discount: Returned as part of the observation.
discount_zero_after_timeout: If True, the discount will be zero
after the `game_steps_per_episode` timeout.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
save_replay_episodes: Save a replay after this many episodes. Default of 0
means don't save replays.
replay_dir: Directory to save replays. Required with save_replay_episodes.
replay_prefix: An optional prefix to use when saving replays.
game_steps_per_episode: Game steps per episode, independent of the
step_mul. 0 means no limit. None means use the map default.
score_index: -1 means use the win/loss reward, >=0 is the index into the
score_cumulative with 0 being the curriculum score. None means use
the map default.
score_multiplier: How much to multiply the score by. Useful for negating.
random_seed: Random number seed to use when initializing the game. This
lets you run repeatable games/tests.
disable_fog: Whether to disable fog of war.
ensure_available_actions: Whether to throw an exception when an
unavailable action is passed to step().
version: The version of SC2 to use, defaults to the latest.
Raises:
ValueError: if no map is specified.
ValueError: if wrong number of players are requested for a map.
ValueError: if the resolutions aren't specified correctly.
"""
if not players:
raise ValueError("You must specify the list of players.")
for p in players:
if not isinstance(p, (Agent, Bot)):
raise ValueError(
"Expected players to be of type Agent or Bot. Got: %s." % p)
num_players = len(players)
self._num_agents = sum(1 for p in players if isinstance(p, Agent))
self._players = players
if not 1 <= num_players <= 2 or not self._num_agents:
raise ValueError("Only 1 or 2 players with at least one agent is "
"supported at the moment.")
if not map_name:
raise ValueError("Missing a map name.")
self._battle_net_map = battle_net_map
self._maps = [maps.get(name) for name in to_list(map_name)]
min_players = min(m.players for m in self._maps)
max_players = max(m.players for m in self._maps)
if self._battle_net_map:
for m in self._maps:
if not m.battle_net:
raise ValueError("%s isn't known on Battle.net" % m.name)
if max_players == 1:
if self._num_agents != 1:
raise ValueError("Single player maps require exactly one Agent.")
elif not 2 <= num_players <= min_players:
raise ValueError(
"Maps support 2 - %s players, but trying to join with %s" % (
min_players, num_players))
if save_replay_episodes and not replay_dir:
raise ValueError("Missing replay_dir")
self._realtime = realtime
self._last_step_time = None
self._save_replay_episodes = save_replay_episodes
self._replay_dir = replay_dir
self._replay_prefix = replay_prefix
self._random_seed = random_seed
self._disable_fog = disable_fog
self._ensure_available_actions = ensure_available_actions
self._discount = discount
self._discount_zero_after_timeout = discount_zero_after_timeout
self._default_step_mul = step_mul
self._default_score_index = score_index
self._default_score_multiplier = score_multiplier
self._default_episode_length = game_steps_per_episode
self._run_config = run_configs.get(version=version)
self._parallel = run_parallel.RunParallel() # Needed for multiplayer.
self._game_info = None
self._requested_races = None
if agent_interface_format is None:
raise ValueError("Please specify agent_interface_format.")
if isinstance(agent_interface_format,
(AgentInterfaceFormat, sc_pb.InterfaceOptions)):
agent_interface_format = [agent_interface_format] * self._num_agents
if len(agent_interface_format) != self._num_agents:
raise ValueError(
"The number of entries in agent_interface_format should "
"correspond 1-1 with the number of agents.")
self._action_delay_fns = [
aif.action_delay_fn if isinstance(aif, AgentInterfaceFormat) else None
for aif in agent_interface_format
]
self._interface_formats = agent_interface_format
self._interface_options = [
self._get_interface(interface_format, require_raw=visualize and i == 0)
for i, interface_format in enumerate(agent_interface_format)]
self._launch_game()
self._create_join()
self._finalize(visualize)
def _finalize(self, visualize):
self._delayed_actions = [collections.deque()
for _ in self._action_delay_fns]
if visualize:
self._renderer_human = renderer_human.RendererHuman()
self._renderer_human.init(
self._controllers[0].game_info(),
self._controllers[0].data())
else:
self._renderer_human = None
self._metrics = metrics.Metrics(self._map_name)
self._metrics.increment_instance()
self._last_score = None
self._total_steps = 0
self._episode_steps = 0
self._episode_count = 0
self._obs = [None] * self._num_agents
self._agent_obs = [None] * self._num_agents
self._state = environment.StepType.LAST # Want to jump to `reset`.
logging.info("Environment is ready")
@staticmethod
def _get_interface(interface_format, require_raw):
if isinstance(interface_format, sc_pb.InterfaceOptions):
if require_raw and not interface_format.raw:
interface_options = copy.deepcopy(interface_format)
interface_options.raw = True
return interface_options
else:
return interface_format
aif = interface_format
interface = sc_pb.InterfaceOptions(
raw=(aif.use_feature_units or
aif.use_unit_counts or
aif.use_raw_units or
require_raw),
show_cloaked=aif.show_cloaked,
show_burrowed_shadows=aif.show_burrowed_shadows,
show_placeholders=aif.show_placeholders,
raw_affects_selection=True,
raw_crop_to_playable_area=aif.raw_crop_to_playable_area,
score=True)
if aif.feature_dimensions:
interface.feature_layer.width = aif.camera_width_world_units
aif.feature_dimensions.screen.assign_to(
interface.feature_layer.resolution)
aif.feature_dimensions.minimap.assign_to(
interface.feature_layer.minimap_resolution)
interface.feature_layer.crop_to_playable_area = aif.crop_to_playable_area
interface.feature_layer.allow_cheating_layers = aif.allow_cheating_layers
if aif.rgb_dimensions:
aif.rgb_dimensions.screen.assign_to(interface.render.resolution)
aif.rgb_dimensions.minimap.assign_to(interface.render.minimap_resolution)
return interface
def _launch_game(self):
# Reserve a whole bunch of ports for the weird multiplayer implementation.
if self._num_agents > 1:
self._ports = portspicker.pick_unused_ports(self._num_agents * 2)
logging.info("Ports used for multiplayer: %s", self._ports)
else:
self._ports = []
# Actually launch the game processes.
self._sc2_procs = [
self._run_config.start(extra_ports=self._ports,
want_rgb=interface.HasField("render"))
for interface in self._interface_options]
self._controllers = [p.controller for p in self._sc2_procs]
if self._battle_net_map:
available_maps = self._controllers[0].available_maps()
available_maps = set(available_maps.battlenet_map_names)
unavailable = [m.name for m in self._maps
if m.battle_net not in available_maps]
if unavailable:
raise ValueError("Requested map(s) not in the battle.net cache: %s"
% ",".join(unavailable))
def _create_join(self):
"""Create the game, and join it."""
map_inst = random.choice(self._maps)
self._map_name = map_inst.name
self._step_mul = max(1, self._default_step_mul or map_inst.step_mul)
self._score_index = get_default(self._default_score_index,
map_inst.score_index)
self._score_multiplier = get_default(self._default_score_multiplier,
map_inst.score_multiplier)
self._episode_length = get_default(self._default_episode_length,
map_inst.game_steps_per_episode)
if self._episode_length <= 0 or self._episode_length > MAX_STEP_COUNT:
self._episode_length = MAX_STEP_COUNT
# Create the game. Set the first instance as the host.
create = sc_pb.RequestCreateGame(
disable_fog=self._disable_fog,
realtime=self._realtime)
if self._battle_net_map:
create.battlenet_map_name = map_inst.battle_net
else:
create.local_map.map_path = map_inst.path
map_data = map_inst.data(self._run_config)
if self._num_agents == 1:
create.local_map.map_data = map_data
else:
# Save the maps so they can access it. Don't do it in parallel since SC2
# doesn't respect tmpdir on windows, which leads to a race condition:
# https://github.com/Blizzard/s2client-proto/issues/102
for c in self._controllers:
c.save_map(map_inst.path, map_data)
if self._random_seed is not None:
create.random_seed = self._random_seed
for p in self._players:
if isinstance(p, Agent):
create.player_setup.add(type=sc_pb.Participant)
else:
create.player_setup.add(
type=sc_pb.Computer, race=random.choice(p.race),
difficulty=p.difficulty, ai_build=random.choice(p.build))
self._controllers[0].create_game(create)
# Create the join requests.
agent_players = [p for p in self._players if isinstance(p, Agent)]
sanitized_names = crop_and_deduplicate_names(p.name for p in agent_players)
join_reqs = []
for p, name, interface in zip(agent_players, sanitized_names,
self._interface_options):
join = sc_pb.RequestJoinGame(options=interface)
join.race = random.choice(p.race)
join.player_name = name
if self._ports:
join.shared_port = 0 # unused
join.server_ports.game_port = self._ports[0]
join.server_ports.base_port = self._ports[1]
for i in range(self._num_agents - 1):
join.client_ports.add(game_port=self._ports[i * 2 + 2],
base_port=self._ports[i * 2 + 3])
join_reqs.append(join)
# Join the game. This must be run in parallel because Join is a blocking
# call to the game that waits until all clients have joined.
self._parallel.run((c.join_game, join)
for c, join in zip(self._controllers, join_reqs))
self._game_info = self._parallel.run(c.game_info for c in self._controllers)
for g, interface in zip(self._game_info, self._interface_options):
if g.options.render != interface.render:
logging.warning(
"Actual interface options don't match requested options:\n"
"Requested:\n%s\n\nActual:\n%s", interface, g.options)
self._features = [
features.features_from_game_info(
game_info=g, agent_interface_format=aif, map_name=self._map_name)
for g, aif in zip(self._game_info, self._interface_formats)]
self._requested_races = {
info.player_id: info.race_requested
for info in self._game_info[0].player_info
if info.type != sc_pb.Observer
}
@property
def map_name(self):
return self._map_name
@property
def game_info(self):
"""A list of ResponseGameInfo, one per agent."""
return self._game_info
def static_data(self):
return self._controllers[0].data()
def observation_spec(self):
"""Look at Features for full specs."""
return tuple(f.observation_spec() for f in self._features)
def action_spec(self):
"""Look at Features for full specs."""
return tuple(f.action_spec() for f in self._features)
def action_delays(self):
"""In realtime we track the delay observation -> action executed.
Returns:
A list per agent of action delays, where action delays are a list where
the index in the list corresponds to the delay in game loops, the value
at that index the count over the course of an episode.
Raises:
ValueError: If called when not in realtime mode.
"""
if not self._realtime:
raise ValueError("This method is only supported in realtime mode")
return self._action_delays
def _restart(self):
if (len(self._players) == 1 and len(self._players[0].race) == 1 and
len(self._maps) == 1):
# Need to support restart for fast-restart of mini-games.
self._controllers[0].restart()
else:
if len(self._controllers) > 1:
self._parallel.run(c.leave for c in self._controllers)
self._create_join()
@sw.decorate
def reset(self):
"""Start a new episode."""
self._episode_steps = 0
if self._episode_count:
# No need to restart for the first episode.
self._restart()
self._episode_count += 1
races = [Race(r).name for _, r in sorted(self._requested_races.items())]
logging.info("Starting episode %s: [%s] on %s",
self._episode_count, ", ".join(races), self._map_name)
self._metrics.increment_episode()
self._last_score = [0] * self._num_agents
self._state = environment.StepType.FIRST
if self._realtime:
self._last_step_time = time.time()
self._last_obs_game_loop = None
self._action_delays = [[0] * NUM_ACTION_DELAY_BUCKETS] * self._num_agents
return self._observe(target_game_loop=0)
@sw.decorate("step_env")
def step(self, actions, step_mul=None):
"""Apply actions, step the world forward, and return observations.
Args:
actions: A list of actions meeting the action spec, one per agent, or a
list per agent. Using a list allows multiple actions per frame, but
will still check that they're valid, so disabling
ensure_available_actions is encouraged.
step_mul: If specified, use this rather than the environment's default.
Returns:
A tuple of TimeStep namedtuples, one per agent.
"""
if self._state == environment.StepType.LAST:
return self.reset()
skip = not self._ensure_available_actions
actions = [[f.transform_action(o.observation, a, skip_available=skip)
for a in to_list(acts)]
for f, o, acts in zip(self._features, self._obs, actions)]
if not self._realtime:
actions = self._apply_action_delays(actions)
self._parallel.run((c.actions, sc_pb.RequestAction(actions=a))
for c, a in zip(self._controllers, actions))
self._state = environment.StepType.MID
return self._step(step_mul)
def _step(self, step_mul=None):
step_mul = step_mul or self._step_mul
if step_mul <= 0:
raise ValueError("step_mul should be positive, got {}".format(step_mul))
target_game_loop = self._episode_steps + step_mul
if not self._realtime:
# Send any delayed actions that were scheduled up to the target game loop.
current_game_loop = self._send_delayed_actions(
up_to_game_loop=target_game_loop,
current_game_loop=self._episode_steps)
self._step_to(game_loop=target_game_loop,
current_game_loop=current_game_loop)
return self._observe(target_game_loop=target_game_loop)
def _apply_action_delays(self, actions):
"""Apply action delays to the requested actions, if configured to."""
assert not self._realtime
actions_now = []
for actions_for_player, delay_fn, delayed_actions in zip(
actions, self._action_delay_fns, self._delayed_actions):
actions_now_for_player = []
for action in actions_for_player:
delay = delay_fn() if delay_fn else 1
if delay > 1 and action.ListFields(): # Skip no-ops.
game_loop = self._episode_steps + delay - 1
# Randomized delays mean that 2 delay actions can be reversed.
# Make sure that doesn't happen.
if delayed_actions:
game_loop = max(game_loop, delayed_actions[-1].game_loop)
# Don't send an action this frame.
delayed_actions.append(_DelayedAction(game_loop, action))
else:
actions_now_for_player.append(action)
actions_now.append(actions_now_for_player)
return actions_now
def _send_delayed_actions(self, up_to_game_loop, current_game_loop):
"""Send any delayed actions scheduled for up to the specified game loop."""
assert not self._realtime
while True:
if not any(self._delayed_actions): # No queued actions
return current_game_loop
act_game_loop = min(d[0].game_loop for d in self._delayed_actions if d)
if act_game_loop > up_to_game_loop:
return current_game_loop
self._step_to(act_game_loop, current_game_loop)
current_game_loop = act_game_loop
if self._controllers[0].status_ended:
# We haven't observed and may have hit game end.
return current_game_loop
actions = []
for d in self._delayed_actions:
if d and d[0].game_loop == current_game_loop:
delayed_action = d.popleft()
actions.append(delayed_action.action)
else:
actions.append(None)
self._parallel.run((c.act, a) for c, a in zip(self._controllers, actions))
def _step_to(self, game_loop, current_game_loop):
step_mul = game_loop - current_game_loop
if step_mul < 0:
raise ValueError("We should never need to step backwards")
if step_mul > 0:
with self._metrics.measure_step_time(step_mul):
if not self._controllers[0].status_ended: # May already have ended.
self._parallel.run((c.step, step_mul) for c in self._controllers)
def _get_observations(self, target_game_loop):
# Transform in the thread so it runs while waiting for other observations.
def parallel_observe(c, f):
obs = c.observe(target_game_loop=target_game_loop)
agent_obs = f.transform_obs(obs)
return obs, agent_obs
with self._metrics.measure_observation_time():
self._obs, self._agent_obs = zip(*self._parallel.run(
(parallel_observe, c, f)
for c, f in zip(self._controllers, self._features)))
game_loop = _get_game_loop(self._agent_obs[0])
if (game_loop < target_game_loop and
not any(o.player_result for o in self._obs)):
raise ValueError(
("The game didn't advance to the expected game loop. "
"Expected: %s, got: %s") % (target_game_loop, game_loop))
elif game_loop > target_game_loop and target_game_loop > 0:
logging.warning(
"Received observation %d step(s) late: %d rather than %d.",
game_loop - target_game_loop, game_loop, target_game_loop)
if self._realtime:
# Track delays on executed actions.
# Note that this will underestimate e.g. action sent, new observation
# taken before action executes, action executes, observation taken
# with action. This is difficult to avoid without changing the SC2
# binary - e.g. send the observation game loop with each action,
# return them in the observation action proto.
if self._last_obs_game_loop is not None:
for i, obs in enumerate(self._obs):
for action in obs.actions:
if action.HasField("game_loop"):
delay = action.game_loop - self._last_obs_game_loop
if delay > 0:
num_slots = len(self._action_delays[i])
delay = min(delay, num_slots - 1) # Cap to num buckets.
self._action_delays[i][delay] += 1
break
self._last_obs_game_loop = game_loop
def _observe(self, target_game_loop):
self._get_observations(target_game_loop)
# TODO(tewalds): How should we handle more than 2 agents and the case where
# the episode can end early for some agents?
outcome = [0] * self._num_agents
discount = self._discount
episode_complete = any(o.player_result for o in self._obs)
if episode_complete:
self._state = environment.StepType.LAST
discount = 0
for i, o in enumerate(self._obs):
player_id = o.observation.player_common.player_id
for result in o.player_result:
if result.player_id == player_id:
outcome[i] = possible_results.get(result.result, 0)
if self._score_index >= 0: # Game score, not win/loss reward.
cur_score = [_get_score(o, self._score_index) for o in self._agent_obs]
if self._episode_steps == 0: # First reward is always 0.
reward = [0] * self._num_agents
else:
reward = [cur - last for cur, last in zip(cur_score, self._last_score)]
self._last_score = cur_score
else:
reward = outcome
if self._renderer_human:
self._renderer_human.render(self._obs[0])
cmd = self._renderer_human.get_actions(
self._run_config, self._controllers[0])
if cmd == renderer_human.ActionCmd.STEP:
pass
elif cmd == renderer_human.ActionCmd.RESTART:
self._state = environment.StepType.LAST
elif cmd == renderer_human.ActionCmd.QUIT:
raise KeyboardInterrupt("Quit?")
game_loop = _get_game_loop(self._agent_obs[0])
self._total_steps += game_loop - self._episode_steps
self._episode_steps = game_loop
if self._episode_steps >= self._episode_length:
self._state = environment.StepType.LAST
if self._discount_zero_after_timeout:
discount = 0.0
if self._episode_steps >= MAX_STEP_COUNT:
logging.info("Cut short to avoid SC2's max step count of 2^19=524288.")
if self._state == environment.StepType.LAST:
if (self._save_replay_episodes > 0 and
self._episode_count % self._save_replay_episodes == 0):
self.save_replay(self._replay_dir, self._replay_prefix)
logging.info(("Episode %s finished after %s game steps. "
"Outcome: %s, reward: %s, score: %s"),
self._episode_count, self._episode_steps, outcome, reward,
[_get_score(o) for o in self._agent_obs])
def zero_on_first_step(value):
return 0.0 if self._state == environment.StepType.FIRST else value
return tuple(environment.TimeStep(
step_type=self._state,
reward=zero_on_first_step(r * self._score_multiplier),
discount=zero_on_first_step(discount),
observation=o) for r, o in zip(reward, self._agent_obs))
def send_chat_messages(self, messages, broadcast=True):
"""Useful for logging messages into the replay."""
self._parallel.run(
(c.chat,
message,
sc_pb.ActionChat.Broadcast if broadcast else sc_pb.ActionChat.Team)
for c, message in zip(self._controllers, messages))
def save_replay(self, replay_dir, prefix=None):
if prefix is None:
prefix = self._map_name
replay_path = self._run_config.save_replay(
self._controllers[0].save_replay(), replay_dir, prefix)
logging.info("Wrote replay to: %s", replay_path)
return replay_path
def close(self):
logging.info("Environment Close")
if hasattr(self, "_metrics") and self._metrics:
self._metrics.close()
self._metrics = None
if hasattr(self, "_renderer_human") and self._renderer_human:
self._renderer_human.close()
self._renderer_human = None
# Don't use parallel since it might be broken by an exception.
if hasattr(self, "_controllers") and self._controllers:
for c in self._controllers:
c.quit()
self._controllers = None
if hasattr(self, "_sc2_procs") and self._sc2_procs:
for p in self._sc2_procs:
p.close()
self._sc2_procs = None
if hasattr(self, "_ports") and self._ports:
portspicker.return_ports(self._ports)
self._ports = None
if hasattr(self, "_parallel") and self._parallel is not None:
self._parallel.shutdown()
self._parallel = None
self._game_info = None
def crop_and_deduplicate_names(names):
"""Crops and de-duplicates the passed names.
SC2 gets confused in a multi-agent game when agents have the same
name. We check for name duplication to avoid this, but - SC2 also
crops player names to a hard character limit, which can again lead
to duplicate names. To avoid this we unique-ify names if they are
equivalent after cropping. Ideally SC2 would handle duplicate names,
making this unnecessary.
TODO(b/121092563): Fix this in the SC2 binary.
Args:
names: List of names.
Returns:
De-duplicated names cropped to 32 characters.
"""
max_name_length = 32
# Crop.
cropped = [n[:max_name_length] for n in names]
# De-duplicate.
deduplicated = []
name_counts = collections.Counter(n for n in cropped)
name_index = collections.defaultdict(lambda: 1)
for n in cropped:
if name_counts[n] == 1:
deduplicated.append(n)
else:
deduplicated.append("({}) {}".format(name_index[n], n))
name_index[n] += 1
# Crop again.
recropped = [n[:max_name_length] for n in deduplicated]
if len(set(recropped)) != len(recropped):
raise ValueError("Failed to de-duplicate names")
return recropped
def _get_game_loop(agent_obs):
if isinstance(agent_obs, sc_pb.ResponseObservation):
return agent_obs.observation.game_loop
else:
return agent_obs.game_loop[0]
def _get_score(agent_obs, score_index=0):
if isinstance(agent_obs, sc_pb.ResponseObservation):
if score_index != 0:
raise ValueError(
"Non-zero score index isn't supported for passthrough agents, "
"currently")
return agent_obs.observation.score.score
else:
return agent_obs["score_cumulative"][score_index]
| pysc2-master | pysc2/env/sc2_env.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Environment which uses converters to transform an underlying environment."""
import functools
import threading
from typing import Any, Mapping, NamedTuple, Sequence
import dm_env
import numpy as np
from pysc2.env.converter import converter as converter_lib
from pysc2.env.converter.proto import converter_pb2
from pysc2.lib import actions as sc2_actions
import tree
import typing_extensions
from s2clientprotocol import common_pb2
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2
_BARRIER_TIMEOUT = 30.0
def squeeze_if_necessary(x: np.ndarray) -> np.ndarray:
"""Remove the trailing 1 of inputs."""
if x.shape and x.shape[-1] == 1:
return np.squeeze(x, axis=-1)
else:
return x
def squeeze_spec_if_necessary(x):
"""Remove the trailing 1 of specs inputs."""
if x.shape and x.shape[-1] == 1:
return x.replace(shape=x.shape[:-1])
else:
return x
class ConverterFactory(typing_extensions.Protocol):
def __call__(self, game_info: sc2api_pb2.ResponseGameInfo) -> Any:
"""Returns an environment converter given a game info."""
class ConvertedEnvironment(dm_env.Environment):
"""Env which uses converters to transform an underlying environment.
Note that this is a multiplayer environment. The returned timesteps contain
lists for their reward and observation fields, with entries in those lists
corresponding to the players in the game. A list of actions must be passed
to step - an action per player. Note, however, that this is expected to
be None where the player isn't expected to act on the current game loop
because their previous action delay hasn't expired yet.
If you would prefer to access the environment in a singleplayer fashion,
see `make_streams`, below.
"""
def __init__(self,
env,
converter_factories: Sequence[ConverterFactory],
allow_out_of_turn_actions=False):
"""Initializes the environment.
Args:
env: The underlying environment which is being converted.
converter_factories: One for each agent player in the game.
allow_out_of_turn_actions: Whether to allow agents to act when it's not
their turns. Used for testing.
"""
self._env = env
self._num_players = len(converter_factories)
self._converter_factories = converter_factories
self._initialized = False
converters = [f(_dummy_game_info()) for f in converter_factories]
self._action_specs = [c.action_spec() for c in converters]
self._obs_specs = [c.observation_spec() for c in converters]
self._target_game_loops = [0] * self._num_players
self._converters = [None] * self._num_players
self._game_loop = None
self._allow_out_of_turn_actions = allow_out_of_turn_actions
def reset(self) -> dm_env.TimeStep:
"""Resets the environment."""
self._initialized = True
self._game_loop = 0
self._target_game_loops = [0] * self._num_players
self._converters = [
f(g) for f, g in zip(self._converter_factories, self._env.game_info)
]
return self._convert_timesteps(self._env.reset())
def step(self, actions) -> dm_env.TimeStep:
"""Steps the environment."""
if not self._initialized:
return self.reset()
converted_actions = []
for i, (action, converter) in enumerate(zip(actions, self._converters)):
if action is None:
if self._target_game_loops[i] <= self._game_loop:
raise RuntimeError('No action specified when its your turn.')
converted_actions.append(sc2_actions.FUNCTIONS.no_op())
else:
if (self._target_game_loops[i] > self._game_loop and
not self._allow_out_of_turn_actions):
raise RuntimeError('Can\'t act when not your turn.')
action_with_delay = converter.convert_action(action)
self._target_game_loops[i] = self._game_loop + action_with_delay.delay
num_actions = len(action_with_delay.request_action.actions)
if not num_actions:
converted_actions.append(sc2api_pb2.Action())
else:
converted_actions.append(
[action_with_delay.request_action.actions[0]] * num_actions)
min_delay = min(g for g in self._target_game_loops) - self._game_loop
timestep = self._convert_timesteps(
self._env.step(converted_actions, min_delay))
self._game_loop = max(int(obs['game_loop']) for obs in timestep.observation)
if timestep.last():
self._initialized = False
self._target_game_loops = [0] * len(self._target_game_loops)
return timestep
def observation_spec(self):
return tree.map_structure(squeeze_spec_if_necessary, self._obs_specs)
def action_spec(self):
return self._action_specs
def close(self):
self._env.close()
self._env = None
def send_chat_messages(self, messages: Sequence[str], broadcast: bool = True):
fn = getattr(self._env, 'send_chat_messages', None)
if fn:
# Make sure that chat messages are less than 255 characters
messages = [x[:254] for x in messages]
fn(messages, broadcast)
def save_replay(self, replay_dir, prefix=None):
return self._env.save_replay(replay_dir, prefix)
def action_delays(self):
return self._env.action_delays()
def num_players(self):
return self._num_players
def is_player_turn(self):
return [t <= self._game_loop for t in self._target_game_loops]
def _convert_timesteps(self, timesteps):
def _convert_obs(obs, converter):
if not isinstance(obs, sc2api_pb2.ResponseObservation):
obs = obs['_response_observation']()
env_obs = converter_pb2.Observation(player=obs)
env_obs = converter.convert_observation(observation=env_obs)
return tree.map_structure(squeeze_if_necessary, env_obs)
# Merge the timesteps from a sequence to a single timestep
return dm_env.TimeStep(
step_type=dm_env.StepType(timesteps[0].step_type),
reward=[timestep.reward for timestep in timesteps],
discount=timesteps[0].discount,
observation=[
_convert_obs(ts.observation, t)
for ts, t in zip(timesteps, self._converters)
])
class _Stream(dm_env.Environment):
"""A stream for a single player interacting with a multiplayer environment."""
def __init__(self, player: int, environment: '_StreamedEnvironment'):
self._player = player
self._environment = environment
def reset(self) -> dm_env.TimeStep:
return self._environment.reset(self._player)
def step(self, action) -> dm_env.TimeStep:
return self._environment.step(action, self._player)
def action_spec(self):
return self._environment.action_spec(self._player)
def observation_spec(self):
return self._environment.observation_spec(self._player)
def close(self):
self._environment.close(self._player)
def save_replay(self, replay_dir, prefix=None):
return self._environment.save_replay(replay_dir, prefix)
class _StreamedEnvironment:
"""Env presenting ConvertedEnvironment as multiple single player streams."""
def __init__(self, underlying_env: ConvertedEnvironment):
if not 1 <= underlying_env.num_players() <= 2:
raise ValueError(
f'Unsupported number of players: {underlying_env.num_players()}')
self._underlying_env = underlying_env
self._num_players = underlying_env.num_players()
self._barrier = threading.Barrier(parties=2)
self._lock = threading.Lock()
self._timestep = None
self._actions = [None] * self._num_players
self._closed = [False] * self._num_players
self._closed_lock = threading.Lock()
def reset(self, player: int) -> dm_env.TimeStep:
"""Resets the underlying environment, syncing players."""
self._wait_for_other_player()
if player == 0:
self._timestep = self._underlying_env.reset()
self._wait_for_other_player()
return self._player_timestep(player)
def step(self, action, player: int) -> dm_env.TimeStep:
"""Steps the underlying environment, syncing players."""
self._actions[player] = action
while True:
self._wait_for_other_player()
if player == 0:
self._timestep = self._underlying_env.step(self._actions)
self._actions = [None] * self._num_players
self._wait_for_other_player()
if self._underlying_env.is_player_turn()[player]:
break
return self._player_timestep(player)
def action_spec(self, player: int):
return self._underlying_env.action_spec()[player]
def observation_spec(self, player: int):
return self._underlying_env.observation_spec()[player]
def close(self, player: int):
with self._closed_lock:
self._closed[player] = True
if all(self._closed):
self._underlying_env.close()
def save_replay(self, replay_dir, prefix=None):
with self._lock:
return self._underlying_env.save_replay(replay_dir, prefix)
def _wait_for_other_player(self):
"""Waits for the other player (if there is one) to reach this point."""
if self._num_players == 1:
return
try:
self._barrier.wait(_BARRIER_TIMEOUT)
except threading.BrokenBarrierError:
raise TimeoutError('Timed out waiting for other player')
def _player_timestep(self, player: int):
first_step = self._timestep.step_type is dm_env.StepType.FIRST
return dm_env.TimeStep(
step_type=self._timestep.step_type,
reward=float(self._timestep.reward[player]) if not first_step else None,
discount=self._timestep.discount if not first_step else None,
observation=self._timestep.observation[player])
def make_streams(converted_environment: ConvertedEnvironment):
"""Makes single player environment streams out of a ConvertedEnvironment.
Each stream is expected to be run in a separate thread as steps involving
multiple player must be executed concurrently. Where multiple players are
expected to act but don't within _BARRIER_TIMEOUT, an exception will be
raised.
Args:
converted_environment: A converted environment configured for 1 or 2
players.
Returns:
A dm_env.Environment for each player.
"""
environment = _StreamedEnvironment(converted_environment)
return [
_Stream(p, environment)
for p in range(converted_environment.num_players())
]
def _dummy_game_info() -> sc2api_pb2.ResponseGameInfo:
"""Returns a dummy game info object.
The converter *specs* don't depend on the game info (this is not true for
the converted data). So, rather than instantiating the game to have the
converter generate specs, we can supply this dummy game info instead.
"""
return sc2api_pb2.ResponseGameInfo(
start_raw=raw_pb2.StartRaw(map_size=common_pb2.Size2DI(x=256, y=256)),
player_info=[
sc2api_pb2.PlayerInfo(race_requested=common_pb2.Protoss),
sc2api_pb2.PlayerInfo(race_requested=common_pb2.Protoss)
])
class EnvironmentSpec(NamedTuple):
obs_spec: Mapping[str, Any]
action_spec: Mapping[str, Any]
def get_environment_spec(
converter_settings: converter_pb2.ConverterSettings,) -> EnvironmentSpec:
"""Gets observation and action spec for the specified converter settings.
Args:
converter_settings: The converter settings to get specs for.
Returns:
(observation spec, action spec).
"""
env_info = converter_pb2.EnvironmentInfo(game_info=_dummy_game_info())
cvr = converter_lib.Converter(converter_settings, env_info)
obs_spec = tree.map_structure(squeeze_spec_if_necessary,
cvr.observation_spec())
return EnvironmentSpec(obs_spec, cvr.action_spec())
def make_converter_factories(
all_converter_settings: Sequence[converter_pb2.ConverterSettings]):
"""Makes converter factories from converter settings."""
def converter_factory(settings: converter_pb2.ConverterSettings,
game_info: sc2api_pb2.ResponseGameInfo):
return converter_lib.Converter(
settings, converter_pb2.EnvironmentInfo(game_info=game_info))
return [
functools.partial(converter_factory, s) for s in all_converter_settings
]
| pysc2-master | pysc2/env/converted_env.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A base env wrapper so we don't need to override everything every time."""
from pysc2.env import environment
class BaseEnvWrapper(environment.Base):
"""A base env wrapper so we don't need to override everything every time."""
def __init__(self, env):
self._env = env
def close(self, *args, **kwargs):
return self._env.close(*args, **kwargs)
def action_spec(self, *args, **kwargs):
return self._env.action_spec(*args, **kwargs)
def observation_spec(self, *args, **kwargs):
return self._env.observation_spec(*args, **kwargs)
def reset(self, *args, **kwargs):
return self._env.reset(*args, **kwargs)
def step(self, *args, **kwargs):
return self._env.step(*args, **kwargs)
def save_replay(self, *args, **kwargs):
return self._env.save_replay(*args, **kwargs)
@property
def state(self):
return self._env.state
| pysc2-master | pysc2/env/base_env_wrapper.py |
#!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for sc2_env."""
from absl.testing import absltest
from absl.testing import parameterized
from pysc2.env import sc2_env
class TestNameCroppingAndDeduplication(parameterized.TestCase):
@parameterized.named_parameters(
("empty", [], []),
("single_no_crop", ["agent_1"], ["agent_1"]),
("single_cropped",
["very_long_agent_name_experimental_1"],
["very_long_agent_name_experimenta"]),
("no_dupes_no_crop",
["agent_1", "agent_2"],
["agent_1", "agent_2"]),
("no_dupes_cropped",
["a_very_long_agent_name_experimental",
"b_very_long_agent_name_experimental"],
["a_very_long_agent_name_experimen",
"b_very_long_agent_name_experimen"]),
("dupes_no_crop",
["agent_1", "agent_1"],
["(1) agent_1", "(2) agent_1"]),
("dupes_cropped",
["very_long_agent_name_experimental_c123",
"very_long_agent_name_experimental_c456"],
["(1) very_long_agent_name_experim",
"(2) very_long_agent_name_experim"]),
)
def test(self, names, expected_output):
self.assertEqual(sc2_env.crop_and_deduplicate_names(names), expected_output)
if __name__ == "__main__":
absltest.main()
| pysc2-master | pysc2/env/sc2_env_test.py |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mocking the Starcraft II environment."""
import numpy as np
from pysc2.env import environment
from pysc2.env import sc2_env
from pysc2.lib import features
from pysc2.lib import units
from pysc2.tests import dummy_observation
from s2clientprotocol import common_pb2
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2
DUMMY_MAP_SIZE = 256
class _TestEnvironment(environment.Base):
"""A simple generic test environment.
This class is a lightweight implementation of `environment.Base` that returns
the same timesteps on every observation call. By default, each returned
timestep (one per agent) is reward 0., discount 1., and the observations are
zero `np.ndarrays` of dtype `np.int32` and the shape specified by the
environment's spec.
However, the behavior of the `TestEnvironment` can be configured using the
object's attributes.
Attributes:
next_timestep: The `environment.TimeStep`s to return on the next call to
`step`. When necessary, some fields will be overridden to ensure the
`step_type` contract.
episode_length: if the episode length (number of transitions) exceeds
`episode_length` on a call to `step`, the `step-type` will be set to
`environment.StepType.LAST`, forcing an end of episode. This allows a
stub of a production environment to have end_episodes. Will be ignored if
set to `float('inf')` (the default).
"""
def __init__(self, num_agents, observation_spec, action_spec):
"""Initializes the TestEnvironment.
The `next_observation` is initialized to be reward = 0., discount = 1.,
and an appropriately sized observation of all zeros. `episode_length` is set
to `float('inf')`.
Args:
num_agents: The number of agents.
observation_spec: The observation specs for each player.
action_spec: The action specs for each player.
"""
self._num_agents = num_agents
self._observation_spec = observation_spec
self._action_spec = action_spec
self._episode_steps = 0
self.next_timestep = []
for agent_index, obs_spec in enumerate(observation_spec):
self.next_timestep.append(environment.TimeStep(
step_type=environment.StepType.MID,
reward=0.,
discount=1.,
observation=self._default_observation(obs_spec, agent_index)))
self.episode_length = float('inf')
def reset(self):
"""Restarts episode and returns `next_observation` with `StepType.FIRST`."""
self._episode_steps = 0
return self.step([None] * self._num_agents)
def step(self, actions, step_mul=None):
"""Returns `next_observation` modifying its `step_type` if necessary."""
del step_mul # ignored currently
if len(actions) != self._num_agents:
raise ValueError(
'Expected %d actions, received %d.' % (
self._num_agents, len(actions)))
if self._episode_steps == 0:
step_type = environment.StepType.FIRST
elif self._episode_steps >= self.episode_length:
step_type = environment.StepType.LAST
else:
step_type = environment.StepType.MID
timesteps = []
for timestep in self.next_timestep:
if step_type is environment.StepType.FIRST:
timesteps.append(timestep._replace(
step_type=step_type,
reward=0.,
discount=0.))
elif step_type is environment.StepType.LAST:
timesteps.append(timestep._replace(
step_type=step_type,
discount=0.))
else:
timesteps.append(timestep)
if timesteps[0].step_type is environment.StepType.LAST:
self._episode_steps = 0
else:
self._episode_steps += 1
return timesteps
def action_spec(self):
"""See base class."""
return self._action_spec
def observation_spec(self):
"""See base class."""
return self._observation_spec
def _default_observation(self, obs_spec, agent_index):
"""Returns an observation based on the observation spec."""
observation = {}
for key, spec in obs_spec.items():
observation[key] = np.zeros(shape=spec, dtype=np.int32)
return observation
class SC2TestEnv(_TestEnvironment):
"""A TestEnvironment to swap in for `starcraft2.env.sc2_env.SC2Env`.
Repeatedly returns a mock observation for 10 calls to `step` whereupon it
sets discount to 0. and changes state to READY_TO_END_EPISODE.
Example:
```
@mock.patch(
'starcraft2.env.sc2_env.SC2Env',
mock_sc2_env.SC2TestEnv)
def test_method(self):
env = sc2_env.SC2Env('nonexisting map') # Really a SC2TestEnv.
...
```
See base class for more details.
"""
def __init__(self,
*,
map_name=None,
players=None,
agent_interface_format=None,
discount=1.,
discount_zero_after_timeout=False,
visualize=False,
step_mul=None,
realtime=False,
save_replay_episodes=0,
replay_dir=None,
game_steps_per_episode=None,
score_index=None,
score_multiplier=None,
random_seed=None,
disable_fog=False,
ensure_available_actions=True,
version=None):
"""Initializes an SC2TestEnv.
Args:
map_name: Map name. Ignored.
players: A list of Agent and Bot instances that specify who will play.
agent_interface_format: A sequence containing one AgentInterfaceFormat per
agent, matching the order of agents specified in the players list. Or
a single AgentInterfaceFormat to be used for all agents. Note that
InterfaceOptions may be supplied in place of AgentInterfaceFormat, in
which case no action or observation processing will be carried out by
PySC2. The sc_pb.ResponseObservation proto will be returned as the
observation for the agent and passed actions must be instances of
sc_pb.Action. This is intended for agents which use custom environment
conversion code.
discount: Unused.
discount_zero_after_timeout: Unused.
visualize: Unused.
step_mul: Unused.
realtime: Not supported by the mock environment, throws if set to true.
save_replay_episodes: Unused.
replay_dir: Unused.
game_steps_per_episode: Unused.
score_index: Unused.
score_multiplier: Unused.
random_seed: Unused.
disable_fog: Unused.
ensure_available_actions: Whether to throw an exception when an
unavailable action is passed to step().
version: Unused.
Raises:
ValueError: if args are passed.
"""
del map_name # Unused.
del discount # Unused.
del discount_zero_after_timeout # Unused.
del visualize # Unused.
del step_mul # Unused.
del save_replay_episodes # Unused.
del replay_dir # Unused.
del game_steps_per_episode # Unused.
del score_index # Unused.
del score_multiplier # Unused.
del random_seed # Unused.
del disable_fog # Unused.
del ensure_available_actions # Unused.
del version # Unused.
if realtime:
raise ValueError('realtime mode is not supported by the mock env.')
if not players:
players = [sc2_env.Agent(sc2_env.Race.random)]
num_agents = sum(1 for p in players if isinstance(p, sc2_env.Agent))
if agent_interface_format is None:
raise ValueError('Please specify agent_interface_format.')
if isinstance(agent_interface_format,
(sc2_env.AgentInterfaceFormat, sc2api_pb2.InterfaceOptions)):
agent_interface_format = [agent_interface_format] * num_agents
if len(agent_interface_format) != num_agents:
raise ValueError(
'The number of entries in agent_interface_format should '
'correspond 1-1 with the number of agents.')
self._game_info = _make_dummy_game_info(players, agent_interface_format)
self._agent_interface_formats = agent_interface_format
self._features = [
features.features_from_game_info(
game_info=g, agent_interface_format=aif)
for g, aif in zip(self._game_info, self._agent_interface_formats)]
super(SC2TestEnv, self).__init__(
num_agents=num_agents,
action_spec=tuple(f.action_spec() for f in self._features),
observation_spec=tuple(f.observation_spec() for f in self._features))
self.episode_length = 10
@property
def game_info(self):
return self._game_info
def save_replay(self, *args, **kwargs):
"""Does nothing."""
def _default_observation(self, obs_spec, agent_index):
"""Returns a mock observation from an SC2Env."""
builder = dummy_observation.Builder(obs_spec).game_loop(0)
aif = self._agent_interface_formats[agent_index]
if (isinstance(aif, sc2_env.AgentInterfaceFormat) and
(aif.use_feature_units or aif.use_raw_units)):
feature_units = [
dummy_observation.FeatureUnit(
units.Neutral.LabBot,
features.PlayerRelative.NEUTRAL,
owner=16,
pos=common_pb2.Point(x=10, y=10, z=0),
radius=1.0,
health=5,
health_max=5,
is_on_screen=True,
)
]
builder.feature_units(feature_units)
response_observation = builder.build()
features_ = self._features[agent_index]
observation = features_.transform_obs(response_observation)
# Add bounding box for the minimap camera in top left of feature screen.
if hasattr(observation, 'feature_minimap'):
minimap_camera = observation.feature_minimap.camera
minimap_camera.fill(0)
height, width = [dim // 2 for dim in minimap_camera.shape]
minimap_camera[:height, :width].fill(1)
return observation
def _make_dummy_game_info(players, interface_formats):
"""Makes dummy game infos from player and interface format data."""
player_info = []
for i, p in enumerate(players, start=1):
if isinstance(p, sc2_env.Agent):
player_info.append(
sc2api_pb2.PlayerInfo(
player_id=i,
type=sc2api_pb2.PlayerType.Participant,
race_requested=p.race[0],
player_name=p.name))
else:
player_info.append(
sc2api_pb2.PlayerInfo(
player_id=i,
type=sc2api_pb2.PlayerType.Computer,
race_requested=p.race[0],
difficulty=p.difficulty,
ai_build=p.build[0],
player_name=p.difficulty.name))
game_infos = []
for _, interface_format in zip(players, interface_formats):
game_info = sc2api_pb2.ResponseGameInfo(
player_info=player_info,
start_raw=raw_pb2.StartRaw(
map_size=common_pb2.Size2DI(x=DUMMY_MAP_SIZE, y=DUMMY_MAP_SIZE)))
if isinstance(interface_format, sc2api_pb2.InterfaceOptions):
game_info.options.CopyFrom(interface_format)
else:
if interface_format.feature_dimensions is not None:
fd = interface_format.feature_dimensions
game_info.options.feature_layer.resolution.x = fd.screen.x
game_info.options.feature_layer.resolution.y = fd.screen.y
game_info.options.feature_layer.minimap_resolution.x = fd.minimap.x
game_info.options.feature_layer.minimap_resolution.y = fd.minimap.y
game_info.options.feature_layer.width = (
interface_format.camera_width_world_units)
if interface_format.rgb_dimensions is not None:
rd = interface_format.rgb_dimensions
game_info.options.render.resolution.x = rd.screen.x
game_info.options.render.resolution.y = rd.screen.y
game_info.options.render.minimap_resolution.x = rd.minimap.x
game_info.options.render.minimap_resolution.y = rd.minimap.y
game_info.options.render.width = (
interface_format.camera_width_world_units)
game_infos.append(game_info)
return game_infos
| pysc2-master | pysc2/env/mock_sc2_env.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Derives SC2 interface options from converter settings."""
from pysc2.env.converter.proto import converter_pb2
from s2clientprotocol import common_pb2
from s2clientprotocol import sc2api_pb2
def from_settings(settings: converter_pb2.ConverterSettings):
"""Derives SC2 interface options from converter settings."""
if settings.HasField('visual_settings'):
resolution = settings.visual_settings.screen
else:
resolution = common_pb2.Size2DI(x=1, y=1)
return sc2api_pb2.InterfaceOptions(
feature_layer=sc2api_pb2.SpatialCameraSetup(
width=settings.camera_width_world_units,
allow_cheating_layers=False,
resolution=resolution,
minimap_resolution=settings.minimap,
crop_to_playable_area=settings.crop_to_playable_area),
raw=settings.HasField('raw_settings'),
score=True,
raw_affects_selection=True,
show_cloaked=True,
show_placeholders=True,
show_burrowed_shadows=True,
raw_crop_to_playable_area=settings.crop_to_playable_area)
| pysc2-master | pysc2/env/converter/derive_interface_options.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PySC2 environment converter.
This is a thin wrapper around the pybind implementation, supporting dm specs
and numpy arrays in place of dm_env_rpc protos; also supports documentation
more naturally.
"""
from typing import Any, Mapping
from dm_env import specs
from pysc2.env.converter.cc.python import converter
from pysc2.env.converter.proto import converter_pb2
from dm_env_rpc.v1 import dm_env_rpc_pb2
from dm_env_rpc.v1 import dm_env_utils
from dm_env_rpc.v1 import tensor_utils
from s2clientprotocol import sc2api_pb2
class Converter:
"""PySC2 environment converter.
Converts the PySC2 observation/action interface, supporting more standard
interaction with an ML agent and providing enriched observations.
Limited configuration is supported through the `ConverterSettings` proto.
In particular, clients may choose between 'visual' and 'raw' interfaces.
The visual interface focuses on spatial features and actions which are close
to those used by a human when playing the game. The raw interface retains
some spatial features but focuses on numeric unit data; actions being
specified to units directly, ignoring e.g. the position of the camera.
The converter maintains some state throughout an episode. This state relies
on convert_observation and convert_action being called alternately
throughout the episde. A new converter should be created for each episode.
"""
def __init__(self, settings: converter_pb2.ConverterSettings,
environment_info: converter_pb2.EnvironmentInfo):
self._converter = converter.MakeConverter(
settings=settings.SerializeToString(),
environment_info=environment_info.SerializeToString())
def observation_spec(self) -> Mapping[str, specs.Array]:
"""Returns the observation spec.
This is a flat mapping of string label to dm_env array spec and varies
with the specified converter settings and instantiated environment info.
"""
spec = {}
for k, v in self._converter.ObservationSpec().items():
value = dm_env_rpc_pb2.TensorSpec()
value.ParseFromString(v)
spec[k] = dm_env_utils.tensor_spec_to_dm_env_spec(value)
return spec
def action_spec(self) -> Mapping[str, specs.Array]:
"""Returns the action spec.
This is a flat mapping of string label to dm_env array spec and varies
with the specified converter settings and instantiated environment info.
"""
spec = {}
for k, v in self._converter.ActionSpec().items():
value = dm_env_rpc_pb2.TensorSpec()
value.ParseFromString(v)
spec[k] = dm_env_utils.tensor_spec_to_dm_env_spec(value)
return spec
def convert_observation(
self, observation: converter_pb2.Observation) -> Mapping[str, Any]:
"""Converts a SC2 API observation, enriching it with additional info.
Args:
observation: Proto containing the SC2 API observation proto for the
player, and potentially for his opponent. When operating in supervised
mode must also contain the action taken by the player in response to
this observation.
Returns:
A flat mapping of string labels to numpy arrays / or scalars, as
appropriate.
"""
serialized_converted_obs = self._converter.ConvertObservation(
observation.SerializeToString())
deserialized_converted_obs = {}
for k, v in serialized_converted_obs.items():
value = dm_env_rpc_pb2.Tensor()
value.ParseFromString(v)
try:
unpacked_value = tensor_utils.unpack_tensor(value)
deserialized_converted_obs[k] = unpacked_value
except Exception as e:
raise Exception(f'Unpacking failed for {k}:{v} - {e}')
return deserialized_converted_obs
def convert_action(self, action: Mapping[str, Any]) -> converter_pb2.Action:
"""Converts an agent action into an SC2 API action proto.
Note that the returned action also carries the game loop delay requested
by this player until the next observation.
Args:
action: A flat mapping of string labels to numpy arrays / or scalars.
Returns:
An SC2 API action request + game loop delay.
"""
# TODO(b/210113354): Remove protos serialization over pybind11 boundary.
serialized_action = {
k: tensor_utils.pack_tensor(v).SerializeToString()
for k, v in action.items()
}
converted_action_serialized = self._converter.ConvertAction(
serialized_action)
converted_action = converter_pb2.Action()
converted_action.ParseFromString(converted_action_serialized)
request_action = sc2api_pb2.RequestAction()
request_action.ParseFromString(
converted_action.request_action.SerializeToString())
return converter_pb2.Action(
request_action=request_action, delay=converted_action.delay)
| pysc2-master | pysc2/env/converter/converter.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from pysc2.env.converter import converter
from pysc2.env.converter.proto import converter_pb2
from s2clientprotocol import common_pb2
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2
from s2clientprotocol import spatial_pb2
NUM_ACTION_TYPES = 539
MAX_UNIT_COUNT = 16
NUM_UNIT_TYPES = 243
NUM_UNIT_FEATURES = 40
NUM_UPGRADES = 40
NUM_UPGRADE_TYPES = 86
MAX_UNIT_SELECTION_SIZE = 16
MAP_SIZE = 128
RAW_RESOLUTION = 128
MINIMAP_SIZE = 64
SCREEN_SIZE = 96
def _make_dummy_env_info():
return converter_pb2.EnvironmentInfo(
game_info=sc2api_pb2.ResponseGameInfo(
player_info=[
sc2api_pb2.PlayerInfo(
player_id=1, type=sc2api_pb2.PlayerType.Participant),
sc2api_pb2.PlayerInfo(
player_id=2, type=sc2api_pb2.PlayerType.Participant),
],
start_raw=raw_pb2.StartRaw(
map_size=common_pb2.Size2DI(x=MAP_SIZE, y=MAP_SIZE))))
def _make_converter_settings_common(**kwargs):
return converter_pb2.ConverterSettings(
num_action_types=NUM_ACTION_TYPES,
num_unit_types=NUM_UNIT_TYPES,
num_upgrade_types=NUM_UPGRADE_TYPES,
max_num_upgrades=NUM_UPGRADES,
minimap=common_pb2.Size2DI(x=MINIMAP_SIZE, y=MINIMAP_SIZE),
minimap_features=['height_map', 'visibility_map'],
add_opponent_features=True,
**kwargs)
def _make_converter_settings(mode: str):
if mode == 'visual':
return _make_converter_settings_common(
visual_settings=converter_pb2.ConverterSettings.VisualSettings(
screen=common_pb2.Size2DI(x=SCREEN_SIZE, y=SCREEN_SIZE),
screen_features=['height_map', 'player_relative']))
else:
return _make_converter_settings_common(
raw_settings=converter_pb2.ConverterSettings.RawSettings(
resolution=common_pb2.Size2DI(x=RAW_RESOLUTION, y=RAW_RESOLUTION),
num_unit_features=NUM_UNIT_FEATURES,
max_unit_count=MAX_UNIT_COUNT,
max_unit_selection_size=MAX_UNIT_SELECTION_SIZE,
enable_action_repeat=True))
def _make_observation():
return converter_pb2.Observation(
player=sc2api_pb2.ResponseObservation(
observation=sc2api_pb2.Observation(
player_common=sc2api_pb2.PlayerCommon(player_id=1),
feature_layer_data=spatial_pb2.ObservationFeatureLayer(
minimap_renders=spatial_pb2.FeatureLayersMinimap(
height_map=common_pb2.ImageData(
bits_per_pixel=8,
size=common_pb2.Size2DI(
x=MINIMAP_SIZE, y=MINIMAP_SIZE),
data=bytes(bytearray(MINIMAP_SIZE * MINIMAP_SIZE))),
visibility_map=common_pb2.ImageData(
bits_per_pixel=8,
size=common_pb2.Size2DI(
x=MINIMAP_SIZE, y=MINIMAP_SIZE),
data=bytes(bytearray(MINIMAP_SIZE * MINIMAP_SIZE)))),
renders=spatial_pb2.FeatureLayers(
height_map=common_pb2.ImageData(
bits_per_pixel=8,
size=common_pb2.Size2DI(x=SCREEN_SIZE, y=SCREEN_SIZE),
data=bytes(bytearray(SCREEN_SIZE * SCREEN_SIZE))),
player_relative=common_pb2.ImageData(
bits_per_pixel=8,
size=common_pb2.Size2DI(x=SCREEN_SIZE, y=SCREEN_SIZE),
data=bytes(bytearray(SCREEN_SIZE * SCREEN_SIZE))))))))
class RawConverterTest(absltest.TestCase):
def test_action_spec(self):
cvr = converter.Converter(
settings=_make_converter_settings('raw'),
environment_info=_make_dummy_env_info())
action_spec = cvr.action_spec()
self.assertCountEqual(action_spec.keys(), [
'queued', 'repeat', 'target_unit_tag', 'unit_tags', 'world', 'delay',
'function'
])
for k, v in action_spec.items():
self.assertEqual(k, v.name, msg=k)
self.assertEqual(v.dtype, np.int32, msg=k)
self.assertEqual(
v.shape, (MAX_UNIT_SELECTION_SIZE,) if k == 'unit_tags' else (),
msg=k)
self.assertEqual(v.minimum, (1,) if k == 'delay' else (0,), msg=k)
for k, v in {
'queued': 1,
'repeat': 2,
'target_unit_tag': MAX_UNIT_COUNT - 1,
'world': RAW_RESOLUTION * RAW_RESOLUTION - 1,
'delay': 127,
'function': NUM_ACTION_TYPES - 1
}.items():
self.assertEqual(action_spec[k].maximum, (v,), msg=k)
def test_action_move_camera(self):
cvr = converter.Converter(
settings=_make_converter_settings('raw'),
environment_info=_make_dummy_env_info())
raw_move_camera = {'delay': 17, 'function': 168, 'world': 131}
action = cvr.convert_action(raw_move_camera)
expected = converter_pb2.Action(
delay=17,
request_action=sc2api_pb2.RequestAction(actions=[
sc2api_pb2.Action(
action_raw=raw_pb2.ActionRaw(
camera_move=raw_pb2.ActionRawCameraMove(
center_world_space=common_pb2.Point(x=3.5, y=126.5))))
]))
self.assertEqual(expected.SerializeToString(), action.SerializeToString())
def test_action_smart_unit(self):
cvr = converter.Converter(
settings=_make_converter_settings('raw'),
environment_info=_make_dummy_env_info())
raw_smart_unit = {
'delay': 31,
'function': 1,
'queued': 0,
'repeat': 0,
'unit_tags': [4],
'world': 5
}
action = cvr.convert_action(raw_smart_unit)
expected = converter_pb2.Action(
delay=31,
request_action=sc2api_pb2.RequestAction(actions=[
sc2api_pb2.Action(
action_raw=raw_pb2.ActionRaw(
unit_command=raw_pb2.ActionRawUnitCommand(
ability_id=1,
unit_tags=(4,),
queue_command=False,
target_world_space_pos=common_pb2.Point2D(
x=5.5, y=127.5))))
]))
self.assertEqual(expected.SerializeToString(), action.SerializeToString())
class VisualConverterTest(absltest.TestCase):
def test_action_spec(self):
cvr = converter.Converter(
settings=_make_converter_settings('visual'),
environment_info=_make_dummy_env_info())
action_spec = cvr.action_spec()
self.assertCountEqual(action_spec, [
'build_queue_id', 'control_group_act', 'control_group_id', 'minimap',
'queued', 'screen', 'screen2', 'select_add', 'select_point_act',
'select_unit_act', 'select_unit_id', 'select_worker', 'unload_id',
'delay', 'function'
])
for k, v in action_spec.items():
self.assertEqual(k, v.name, msg=k)
self.assertEqual(v.dtype, np.int32, msg=k)
self.assertEqual(v.shape, (), msg=k)
self.assertEqual(v.minimum, (1,) if (k == 'delay') else (0,), msg=k)
for k, v in {
'build_queue_id': 9,
'control_group_act': 4,
'control_group_id': 9,
'minimap': MINIMAP_SIZE * MINIMAP_SIZE - 1,
'queued': 1,
'screen': SCREEN_SIZE * SCREEN_SIZE - 1,
'screen2': SCREEN_SIZE * SCREEN_SIZE - 1,
'select_add': 1,
'select_point_act': 3,
'select_unit_act': 3,
'select_unit_id': 499,
'select_worker': 3,
'unload_id': 499,
'delay': 127,
'function': NUM_ACTION_TYPES - 1
}.items():
self.assertEqual(action_spec[k].maximum, (v,), msg=k)
def test_action_move_camera(self):
cvr = converter.Converter(
settings=_make_converter_settings('visual'),
environment_info=_make_dummy_env_info())
move_camera = {'delay': 17, 'function': 1, 'minimap': 6}
action = cvr.convert_action(move_camera)
expected = converter_pb2.Action(
delay=17,
request_action=sc2api_pb2.RequestAction(actions=[
sc2api_pb2.Action(
action_feature_layer=spatial_pb2.ActionSpatial(
camera_move=spatial_pb2.ActionSpatialCameraMove(
center_minimap=common_pb2.PointI(x=6, y=0))))
]))
self.assertEqual(expected.SerializeToString(), action.SerializeToString())
def test_action_smart_screen(self):
cvr = converter.Converter(
settings=_make_converter_settings('visual'),
environment_info=_make_dummy_env_info())
smart_screen = {
'delay': np.int32(4),
'function': np.int32(451),
'queued': np.int32(1),
'screen': np.int32(333)
}
action = cvr.convert_action(smart_screen)
expected = converter_pb2.Action(
delay=4,
request_action=sc2api_pb2.RequestAction(actions=[
sc2api_pb2.Action(
action_feature_layer=spatial_pb2.ActionSpatial(
unit_command=spatial_pb2.ActionSpatialUnitCommand(
ability_id=1,
queue_command=True,
target_screen_coord=common_pb2.PointI(
x=333 % SCREEN_SIZE, y=333 // SCREEN_SIZE))))
]))
self.assertEqual(expected.SerializeToString(), action.SerializeToString())
@parameterized.parameters(('visual',), ('raw',))
class ConverterTest(parameterized.TestCase):
def test_construction(self, mode):
converter.Converter(
settings=_make_converter_settings(mode),
environment_info=_make_dummy_env_info())
def test_convert_action_delay(self, mode):
cvr = converter.Converter(
settings=_make_converter_settings(mode),
environment_info=_make_dummy_env_info())
for delay in range(1, 128):
action = cvr.convert_action(dict(function=0, delay=delay))
self.assertEqual(action.delay, delay)
def test_observation_spec(self, mode):
cvr = converter.Converter(
settings=_make_converter_settings(mode),
environment_info=_make_dummy_env_info())
obs_spec = cvr.observation_spec()
expected_fields = [
'away_race_observed', 'away_race_requested', 'game_loop',
'home_race_requested', 'minimap_height_map', 'minimap_visibility_map',
'mmr', 'opponent_player', 'opponent_unit_counts_bow',
'opponent_upgrades_fixed_length', 'player', 'unit_counts_bow',
'upgrades_fixed_length'
]
if mode == 'raw':
expected_fields += ['raw_units']
else:
expected_fields += [
'available_actions', 'screen_height_map', 'screen_player_relative'
]
self.assertCountEqual(list(obs_spec), expected_fields)
for k, v in obs_spec.items():
self.assertEqual(k, v.name, msg=k)
if k.startswith('minimap_') or k.startswith('screen_'):
self.assertEqual(v.dtype, np.uint8, msg=k)
else:
self.assertEqual(v.dtype, np.int32, msg=k)
if 'upgrades_fixed_length' not in k:
self.assertFalse(hasattr(v, 'min'), msg=k)
self.assertFalse(hasattr(v, 'max'), msg=k)
for k, v in {
'minimap_height_map': 255,
'minimap_visibility_map': 3,
'upgrades_fixed_length': NUM_UPGRADE_TYPES + 1,
'opponent_upgrades_fixed_length': NUM_UPGRADE_TYPES + 1
}.items():
self.assertEqual(obs_spec[k].minimum, (0,), msg=k)
self.assertEqual(obs_spec[k].maximum, (v,), msg=k)
if mode == 'visual':
for k, v in {
'screen_height_map': 255,
'screen_player_relative': 4
}.items():
self.assertEqual(obs_spec[k].minimum, (0,), msg=k)
self.assertEqual(obs_spec[k].maximum, (v,), msg=k)
for f in [
'away_race_observed', 'away_race_requested', 'game_loop',
'home_race_requested'
]:
self.assertEqual(obs_spec[f].shape, (1,), msg=f)
self.assertEqual(obs_spec['mmr'].shape, ())
for k, v in {
'player': 11,
'opponent_player': 10,
'unit_counts_bow': NUM_UNIT_TYPES,
'opponent_unit_counts_bow': NUM_UNIT_TYPES,
'upgrades_fixed_length': NUM_UPGRADES,
'opponent_upgrades_fixed_length': NUM_UPGRADES
}.items():
self.assertEqual(obs_spec[k].shape, (v,), k)
if mode == 'raw':
self.assertEqual(obs_spec['raw_units'].shape,
(MAX_UNIT_COUNT, NUM_UNIT_FEATURES + 2))
else:
self.assertEqual(obs_spec['available_actions'].shape, (NUM_ACTION_TYPES,))
def test_observation_matches_spec(self, mode):
cvr = converter.Converter(
settings=_make_converter_settings(mode),
environment_info=_make_dummy_env_info())
obs_spec = cvr.observation_spec()
converted = cvr.convert_observation(_make_observation())
for k, v in obs_spec.items():
self.assertIn(k, converted)
self.assertEqual(v.shape, converted[k].shape)
for k in converted:
self.assertIn(k, obs_spec)
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/env/converter/converter_test.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/proto/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/cc/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/cc/python/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/cc/test_data/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/cc/game_data/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| pysc2-master | pysc2/env/converter/cc/game_data/proto/__init__.py |
# Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from pysc2.env.converter.cc.game_data.proto import buffs_pb2
from pysc2.env.converter.cc.game_data.proto import units_pb2
from pysc2.env.converter.cc.game_data.proto import upgrades_pb2
from pysc2.env.converter.cc.game_data.python import uint8_lookup
class Uint8LookupTest(absltest.TestCase):
def test_pysc2_to_uint8(self):
self.assertEqual(
uint8_lookup.PySc2ToUint8(units_pb2.Zerg.InfestedTerran), 4)
def test_pysc2_to_uint8_buffs(self):
self.assertEqual(
uint8_lookup.PySc2ToUint8Buffs(buffs_pb2.Buffs.BlindingCloudStructure),
3)
def test_pysc2_to_uint8_upgrades(self):
self.assertEqual(
uint8_lookup.PySc2ToUint8Upgrades(upgrades_pb2.Upgrades.Blink), 5)
def test_uint8_to_pysc2(self):
self.assertEqual(
uint8_lookup.Uint8ToPySc2(4), units_pb2.Zerg.InfestedTerran)
def test_uint8_to_pysc2_upgrades(self):
self.assertEqual(
uint8_lookup.Uint8ToPySc2Upgrades(5), upgrades_pb2.Upgrades.Blink)
def test_effect_id_identity(self):
self.assertEqual(uint8_lookup.EffectIdIdentity(17), 17)
if __name__ == '__main__':
absltest.main()
| pysc2-master | pysc2/env/converter/cc/game_data/python/uint8_lookup_test.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.