signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def dist(self, other):
dx = self.x - other.x<EOL>dy = self.y - other.y<EOL>return math.sqrt(dx**<NUM_LIT:2> + dy**<NUM_LIT:2>)<EOL>
Distance to some other point.
f1598:c0:m3
def dist_sq(self, other):
dx = self.x - other.x<EOL>dy = self.y - other.y<EOL>return dx**<NUM_LIT:2> + dy**<NUM_LIT:2><EOL>
Distance squared to some other point.
f1598:c0:m4
def round(self):
return Point(int(round(self.x)), int(round(self.y)))<EOL>
Round `x` and `y` to integers.
f1598:c0:m5
def floor(self):
return Point(int(math.floor(self.x)), int(math.floor(self.y)))<EOL>
Round `x` and `y` down to integers.
f1598:c0:m6
def ceil(self):
return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))<EOL>
Round `x` and `y` up to integers.
f1598:c0:m7
def abs(self):
return Point(abs(self.x), abs(self.y))<EOL>
Take the absolute value of `x` and `y`.
f1598:c0:m8
def len(self):
return math.sqrt(self.x**<NUM_LIT:2> + self.y**<NUM_LIT:2>)<EOL>
Length of the vector to this point.
f1598:c0:m9
def scale(self, target_len):
return self * (target_len / self.len())<EOL>
Scale the vector to have the target length.
f1598:c0:m10
def scale_max_size(self, max_size):
return self * (max_size / self).min_dim()<EOL>
Scale this value, keeping aspect ratio, but fitting inside `max_size`.
f1598:c0:m11
def scale_min_size(self, min_size):
return self * (min_size / self).max_dim()<EOL>
Scale this value, keeping aspect ratio, but fitting around `min_size`.
f1598:c0:m12
def transpose(self):
return Point(self.y, self.x)<EOL>
Flip x and y.
f1598:c0:m15
def contained_circle(self, pt, radius):
return self.dist(pt) < radius<EOL>
Is this point inside the circle defined by (`pt`, `radius`)?
f1598:c0:m19
def bound(self, p1, p2=None):
r = Rect(p1, p2)<EOL>return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))<EOL>
Bound this point within the rect defined by (`p1`, `p2`).
f1598:c0:m20
def contains_point(self, pt):
return (self.l < pt.x and self.r > pt.x and<EOL>self.t < pt.y and self.b > pt.y)<EOL>
Is the point inside this rect?
f1598:c1:m15
def contains_circle(self, pt, radius):
return (self.l < pt.x - radius and self.r > pt.x + radius and<EOL>self.t < pt.y - radius and self.b > pt.y + radius)<EOL>
Is the circle completely inside this rect?
f1598:c1:m16
def intersects_circle(self, pt, radius):
<EOL>rect_corner = self.size / <NUM_LIT:2> <EOL>circle_center = (pt - self.center).abs() <EOL>if (circle_center.x > rect_corner.x + radius or<EOL>circle_center.y > rect_corner.y + radius):<EOL><INDENT>return False<EOL><DEDENT>if (circle_center.x <= rect_corner.x or<EOL>circle_center.y <= rect_corner.y):<EOL><INDENT>return True<EOL><DEDENT>return circle_center.dist_sq(rect_corner) <= radius**<NUM_LIT:2><EOL>
Does the circle intersect with this rect?
f1598:c1:m17
def ham_dist(str1, str2):
assert len(str1) == len(str2)<EOL>return sum(c1 != c2 for c1, c2 in zip(str1, str2))<EOL>
Hamming distance. Count the number of differences between str1 and str2.
f1600:m0
def check_error(res, error_enum):
if res.HasField("<STR_LIT:error>"):<EOL><INDENT>enum_name = error_enum.DESCRIPTOR.full_name<EOL>error_name = error_enum.Name(res.error)<EOL>details = getattr(res, "<STR_LIT>", "<STR_LIT>")<EOL>raise RequestError("<STR_LIT>" % (enum_name, error_name, details), res)<EOL><DEDENT>return res<EOL>
Raise if the result has an error, otherwise return the result.
f1602:m0
def decorate_check_error(error_enum):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def _check_error(*args, **kwargs):<EOL><INDENT>return check_error(func(*args, **kwargs), error_enum)<EOL><DEDENT>return _check_error<EOL><DEDENT>return decorator<EOL>
Decorator to call `check_error` on the return value.
f1602:m1
def skip_status(*skipped):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def _skip_status(self, *args, **kwargs):<EOL><INDENT>if self.status not in skipped:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return _skip_status<EOL><DEDENT>return decorator<EOL>
Decorator to skip this call if we're in one of the skipped states.
f1602:m2
def valid_status(*valid):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def _valid_status(self, *args, **kwargs):<EOL><INDENT>if self.status not in valid:<EOL><INDENT>raise protocol.ProtocolError(<EOL>"<STR_LIT>" % (<EOL>func.__name__, self.status, "<STR_LIT:U+002C>".join(map(str, valid))))<EOL><DEDENT>return func(self, *args, **kwargs)<EOL><DEDENT>return _valid_status<EOL><DEDENT>return decorator<EOL>
Decorator to assert that we're in a valid state.
f1602:m3
def catch_game_end(func):
@functools.wraps(func)<EOL>def _catch_game_end(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>prev_status = self.status<EOL>try:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT>except protocol.ProtocolError as protocol_error:<EOL><INDENT>if prev_status == Status.in_game and (<EOL>"<STR_LIT>" in str(protocol_error)):<EOL><INDENT>logging.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return None<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>return _catch_game_end<EOL>
Decorator to handle 'Game has already ended' exceptions.
f1602:m4
@sw.decorate<EOL><INDENT>def _connect(self, host, port, proc, timeout_seconds):<DEDENT>
if "<STR_LIT::>" in host and not host.startswith("<STR_LIT:[>"): <EOL><INDENT>host = "<STR_LIT>" % host<EOL><DEDENT>url = "<STR_LIT>" % (host, port)<EOL>was_running = False<EOL>for i in range(timeout_seconds):<EOL><INDENT>is_running = proc and proc.running<EOL>was_running = was_running or is_running<EOL>if (i >= timeout_seconds // <NUM_LIT:4> or was_running) and not is_running:<EOL><INDENT>logging.warning(<EOL>"<STR_LIT>")<EOL>break<EOL><DEDENT>logging.info("<STR_LIT>", url, i,<EOL>is_running)<EOL>try:<EOL><INDENT>return websocket.create_connection(url, timeout=timeout_seconds)<EOL><DEDENT>except socket.error:<EOL><INDENT>pass <EOL><DEDENT>except websocket.WebSocketBadStatusException as err:<EOL><INDENT>if err.status_code == <NUM_LIT>:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>raise ConnectError("<STR_LIT>")<EOL>
Connect to the websocket, retrying as needed. Returns the socket.
f1602:c2:m1
@valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay)<EOL><INDENT>@decorate_check_error(sc_pb.ResponseCreateGame.Error)<EOL>@sw.decorate<EOL>def create_game(self, req_create_game):<DEDENT>
return self._client.send(create_game=req_create_game)<EOL>
Create a new game. This can only be done by the host.
f1602:c2:m3
@valid_status(Status.launched, Status.init_game)<EOL><INDENT>@decorate_check_error(sc_pb.ResponseSaveMap.Error)<EOL>@sw.decorate<EOL>def save_map(self, map_path, map_data):<DEDENT>
return self._client.send(save_map=sc_pb.RequestSaveMap(<EOL>map_path=map_path, map_data=map_data))<EOL>
Save a map into temp dir so create game can access it in multiplayer.
f1602:c2:m4
@valid_status(Status.launched, Status.init_game)<EOL><INDENT>@decorate_check_error(sc_pb.ResponseJoinGame.Error)<EOL>@sw.decorate<EOL>def join_game(self, req_join_game):<DEDENT>
return self._client.send(join_game=req_join_game)<EOL>
Join a game, done by all connected clients.
f1602:c2:m5
@valid_status(Status.ended, Status.in_game)<EOL><INDENT>@decorate_check_error(sc_pb.ResponseRestartGame.Error)<EOL>@sw.decorate<EOL>def restart(self):<DEDENT>
return self._client.send(restart_game=sc_pb.RequestRestartGame())<EOL>
Restart the game. Only done by the host.
f1602:c2:m6
@valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay)<EOL><INDENT>@decorate_check_error(sc_pb.ResponseStartReplay.Error)<EOL>@sw.decorate<EOL>def start_replay(self, req_start_replay):<DEDENT>
return self._client.send(start_replay=req_start_replay)<EOL>
Start a replay.
f1602:c2:m7
@valid_status(Status.in_game, Status.in_replay)<EOL><INDENT>@sw.decorate<EOL>def game_info(self):<DEDENT>
return self._client.send(game_info=sc_pb.RequestGameInfo())<EOL>
Get the basic information about the game.
f1602:c2:m8
@valid_status(Status.in_game, Status.in_replay)<EOL><INDENT>@sw.decorate<EOL>def data_raw(self):<DEDENT>
return self._client.send(data=sc_pb.RequestData(<EOL>ability_id=True, unit_type_id=True))<EOL>
Get the raw static data for the current game. Prefer `data` instead.
f1602:c2:m9
def data(self):
return static_data.StaticData(self.data_raw())<EOL>
Get the static data for the current game.
f1602:c2:m10
@valid_status(Status.in_game, Status.in_replay, Status.ended)<EOL><INDENT>@sw.decorate<EOL>def observe(self):<DEDENT>
return self._client.send(observation=sc_pb.RequestObservation())<EOL>
Get a current observation.
f1602:c2:m11
@valid_status(Status.in_game, Status.in_replay)<EOL><INDENT>@sw.decorate<EOL>def step(self, count=<NUM_LIT:1>):<DEDENT>
return self._client.send(step=sc_pb.RequestStep(count=count))<EOL>
Step the engine forward by one (or more) step.
f1602:c2:m12
@skip_status(Status.in_replay)<EOL><INDENT>@valid_status(Status.in_game)<EOL>@catch_game_end<EOL>@sw.decorate<EOL>def actions(self, req_action):<DEDENT>
if FLAGS.sc2_log_actions:<EOL><INDENT>for action in req_action.actions:<EOL><INDENT>sys.stderr.write(str(action))<EOL>sys.stderr.flush()<EOL><DEDENT><DEDENT>return self._client.send(action=req_action)<EOL>
Send a `sc_pb.RequestAction`, which may include multiple actions.
f1602:c2:m13
def act(self, action):
if action and action.ListFields(): <EOL><INDENT>return self.actions(sc_pb.RequestAction(actions=[action]))<EOL><DEDENT>
Send a single action. This is a shortcut for `actions`.
f1602:c2:m14
def chat(self, message):
if message:<EOL><INDENT>action_chat = sc_pb.ActionChat(<EOL>channel=sc_pb.ActionChat.Broadcast, message=message)<EOL>action = sc_pb.Action(action_chat=action_chat)<EOL>return self.act(action)<EOL><DEDENT>
Send chat message as a broadcast.
f1602:c2:m15
@valid_status(Status.in_game, Status.ended)<EOL><INDENT>@sw.decorate<EOL>def leave(self):<DEDENT>
return self._client.send(leave_game=sc_pb.RequestLeaveGame())<EOL>
Disconnect from a multiplayer game.
f1602:c2:m16
@valid_status(Status.in_game, Status.ended)<EOL><INDENT>@sw.decorate<EOL>def save_replay(self):<DEDENT>
res = self._client.send(save_replay=sc_pb.RequestSaveReplay())<EOL>return res.data<EOL>
Save a replay, returning the data.
f1602:c2:m17
@valid_status(Status.in_game)<EOL><INDENT>@sw.decorate<EOL>def debug(self, debug_commands):<DEDENT>
if isinstance(debug_commands, sc_debug.DebugCommand):<EOL><INDENT>debug_commands = [debug_commands]<EOL><DEDENT>return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))<EOL>
Run a debug command.
f1602:c2:m18
@skip_status(Status.quit)<EOL><INDENT>@sw.decorate<EOL>def quit(self):<DEDENT>
try:<EOL><INDENT>self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit()))<EOL><DEDENT>except protocol.ConnectionError:<EOL><INDENT>pass <EOL><DEDENT>finally:<EOL><INDENT>self.close()<EOL><DEDENT>
Shut down the SC2 process.
f1602:c2:m19
def _shutdown_proc(p, timeout):
freq = <NUM_LIT:10> <EOL>for _ in range(<NUM_LIT:1> + timeout * freq):<EOL><INDENT>ret = p.poll()<EOL>if ret is not None:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>return ret<EOL><DEDENT>time.sleep(<NUM_LIT:1> / freq)<EOL><DEDENT>logging.warning("<STR_LIT>")<EOL>p.kill()<EOL>return p.wait()<EOL>
Wait for a proc to shut down, then terminate or kill it after `timeout`.
f1605:m0
def __init__(self, run_config, exec_path, version, full_screen=False,<EOL>extra_args=None, verbose=False, host=None, port=None,<EOL>connect=True, timeout_seconds=None, window_size=(<NUM_LIT>, <NUM_LIT>),<EOL>window_loc=(<NUM_LIT:50>, <NUM_LIT:50>), **kwargs):
self._proc = None<EOL>self._controller = None<EOL>self._check_exists(exec_path)<EOL>self._tmp_dir = tempfile.mkdtemp(prefix="<STR_LIT>", dir=run_config.tmp_dir)<EOL>self._host = host or "<STR_LIT:127.0.0.1>"<EOL>self._port = port or portpicker.pick_unused_port()<EOL>self._version = version<EOL>args = [<EOL>exec_path,<EOL>"<STR_LIT>", self._host,<EOL>"<STR_LIT>", str(self._port),<EOL>"<STR_LIT>", os.path.join(run_config.data_dir, "<STR_LIT>"),<EOL>"<STR_LIT>", os.path.join(self._tmp_dir, "<STR_LIT>"),<EOL>]<EOL>if "<STR_LIT::>" in self._host:<EOL><INDENT>args += ["<STR_LIT>"]<EOL><DEDENT>if full_screen:<EOL><INDENT>args += ["<STR_LIT>", "<STR_LIT:1>"]<EOL><DEDENT>else:<EOL><INDENT>args += [<EOL>"<STR_LIT>", "<STR_LIT:0>",<EOL>"<STR_LIT>", str(window_size[<NUM_LIT:0>]),<EOL>"<STR_LIT>", str(window_size[<NUM_LIT:1>]),<EOL>"<STR_LIT>", str(window_loc[<NUM_LIT:0>]),<EOL>"<STR_LIT>", str(window_loc[<NUM_LIT:1>]),<EOL>]<EOL><DEDENT>if verbose or FLAGS.sc2_verbose:<EOL><INDENT>args += ["<STR_LIT>"]<EOL><DEDENT>if self._version and self._version.data_version:<EOL><INDENT>args += ["<STR_LIT>", self._version.data_version.upper()]<EOL><DEDENT>if extra_args:<EOL><INDENT>args += extra_args<EOL><DEDENT>logging.info("<STR_LIT>", "<STR_LIT:U+0020>".join(args))<EOL>try:<EOL><INDENT>with sw("<STR_LIT>"):<EOL><INDENT>self._proc = self._launch(run_config, args, **kwargs)<EOL>if connect:<EOL><INDENT>self._controller = remote_controller.RemoteController(<EOL>self._host, self._port, self, timeout_seconds=timeout_seconds)<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>self.close()<EOL>raise<EOL><DEDENT>
Launch the SC2 process. Args: run_config: `run_configs.lib.RunConfig` object. exec_path: Path to the binary to run. version: `run_configs.lib.Version` object. full_screen: Whether to launch the game window full_screen on win/mac. extra_args: List of additional args for the SC2 process. verbose: Whether to have the SC2 process do verbose logging. host: IP for the game to listen on for its websocket. This is usually "127.0.0.1", or "::1", but could be others as well. port: Port SC2 should listen on for the websocket. connect: Whether to create a RemoteController to connect. timeout_seconds: Timeout for the remote controller. window_size: Screen size if not full screen. window_loc: Screen location if not full screen. **kwargs: Extra arguments for _launch (useful for subclasses).
f1605:c1:m0
@sw.decorate<EOL><INDENT>def close(self):<DEDENT>
if hasattr(self, "<STR_LIT>") and self._controller:<EOL><INDENT>self._controller.quit()<EOL>self._controller.close()<EOL>self._controller = None<EOL><DEDENT>self._shutdown()<EOL>if hasattr(self, "<STR_LIT>") and self._port:<EOL><INDENT>portpicker.return_port(self._port)<EOL>self._port = None<EOL><DEDENT>if hasattr(self, "<STR_LIT>") and os.path.exists(self._tmp_dir):<EOL><INDENT>shutil.rmtree(self._tmp_dir)<EOL><DEDENT>
Shut down the game and clean up.
f1605:c1:m1
def _launch(self, run_config, args, **kwargs):
del kwargs<EOL>try:<EOL><INDENT>with sw("<STR_LIT>"):<EOL><INDENT>return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env)<EOL><DEDENT><DEDENT>except OSError:<EOL><INDENT>logging.exception("<STR_LIT>")<EOL>raise SC2LaunchError("<STR_LIT>" % args)<EOL><DEDENT>
Launch the process and return the process object.
f1605:c1:m10
def _shutdown(self):
if self._proc:<EOL><INDENT>ret = _shutdown_proc(self._proc, <NUM_LIT:3>)<EOL>logging.info("<STR_LIT>", ret)<EOL>self._proc = None<EOL><DEDENT>
Terminate the sub-process.
f1605:c1:m11
def __getitem__(self, indices):
indices = self._indices(indices)<EOL>obj = super(NamedNumpyArray, self).__getitem__(indices)<EOL>if isinstance(obj, np.ndarray): <EOL><INDENT>if not isinstance(indices, tuple):<EOL><INDENT>indices = (indices,)<EOL><DEDENT>new_names = []<EOL>dim = <NUM_LIT:0><EOL>for i, index in enumerate(indices):<EOL><INDENT>if isinstance(index, numbers.Integral):<EOL><INDENT>pass <EOL><DEDENT>elif index is Ellipsis:<EOL><INDENT>end = len(self.shape) - len(indices) + i<EOL>for j in range(dim, end + <NUM_LIT:1>):<EOL><INDENT>new_names.append(self._index_names[j])<EOL><DEDENT>dim = end<EOL><DEDENT>elif (self._index_names[dim] is None or<EOL>(isinstance(index, slice) and index == _NULL_SLICE)):<EOL><INDENT>new_names.append(self._index_names[dim])<EOL><DEDENT>elif isinstance(index, (slice, list, np.ndarray)):<EOL><INDENT>if isinstance(index, np.ndarray) and len(index.shape) > <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>names = sorted(self._index_names[dim].items(),<EOL>key=lambda item: item[<NUM_LIT:1>])<EOL>names = np.array(names, dtype=object) <EOL>sliced = names[index] <EOL>sliced = {n: j for j, (n, _) in enumerate(sliced)} <EOL>new_names.append(sliced)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % (type(index), index))<EOL><DEDENT>dim += <NUM_LIT:1><EOL><DEDENT>obj._index_names = new_names + self._index_names[dim:]<EOL>if len(obj._index_names) != len(obj.shape):<EOL><INDENT>raise IndexError("<STR_LIT>" % (<EOL>len(obj.shape), len(obj._index_names)))<EOL><DEDENT><DEDENT>return obj<EOL>
Get by indexing lookup.
f1606:c1:m4
def __repr__(self):
names = []<EOL>for dim_names in self._index_names:<EOL><INDENT>if dim_names:<EOL><INDENT>dim_names = [n for n, _ in sorted(dim_names.items(),<EOL>key=lambda item: item[<NUM_LIT:1>])]<EOL>if len(dim_names) > <NUM_LIT:11>:<EOL><INDENT>dim_names = dim_names[:<NUM_LIT:5>] + ["<STR_LIT>"] + dim_names[-<NUM_LIT:5>:]<EOL><DEDENT><DEDENT>names.append(dim_names)<EOL><DEDENT>if len(names) == <NUM_LIT:1>:<EOL><INDENT>names = names[<NUM_LIT:0>]<EOL><DEDENT>matches = re.findall(r"<STR_LIT>",<EOL>np.array_repr(self))[<NUM_LIT:0>]<EOL>return "<STR_LIT>" % (<EOL>matches[<NUM_LIT:0>], matches[<NUM_LIT:1>], names, matches[<NUM_LIT:2>])<EOL>
A repr, parsing the original and adding the names param.
f1606:c1:m8
def _indices(self, indices):
if isinstance(indices, tuple):<EOL><INDENT>out = []<EOL>dim = <NUM_LIT:0><EOL>for i, index in enumerate(indices):<EOL><INDENT>if index is Ellipsis:<EOL><INDENT>out.append(index)<EOL>dim = len(self.shape) - len(indices) + i<EOL><DEDENT>else:<EOL><INDENT>out.append(self._get_index(dim, index))<EOL><DEDENT>dim += <NUM_LIT:1><EOL><DEDENT>return tuple(out)<EOL><DEDENT>else:<EOL><INDENT>return self._get_index(<NUM_LIT:0>, indices)<EOL><DEDENT>
Turn all string indices into int indices, preserving ellipsis.
f1606:c1:m11
def _get_index(self, dim, index):
if isinstance(index, six.string_types):<EOL><INDENT>try:<EOL><INDENT>return self._index_names[dim][index]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError("<STR_LIT>" % (index, dim))<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % (dim, index))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return index<EOL><DEDENT>
Turn a string into a real index, otherwise return the index.
f1606:c1:m12
def spatial(action, action_space):
if action_space == ActionSpace.FEATURES:<EOL><INDENT>return action.action_feature_layer<EOL><DEDENT>elif action_space == ActionSpace.RGB:<EOL><INDENT>return action.action_render<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % action_space)<EOL><DEDENT>
Choose the action space for the action proto.
f1609:m0
def move_camera(action, action_space, minimap):
minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)<EOL>
Move the camera.
f1609:m2
def select_point(action, action_space, select_point_act, screen):
select = spatial(action, action_space).unit_selection_point<EOL>screen.assign_to(select.selection_screen_coord)<EOL>select.type = select_point_act<EOL>
Select a unit at a point.
f1609:m3
def select_rect(action, action_space, select_add, screen, screen2):
select = spatial(action, action_space).unit_selection_rect<EOL>out_rect = select.selection_screen_coord.add()<EOL>screen_rect = point.Rect(screen, screen2)<EOL>screen_rect.tl.assign_to(out_rect.p0)<EOL>screen_rect.br.assign_to(out_rect.p1)<EOL>select.selection_add = bool(select_add)<EOL>
Select units within a rectangle.
f1609:m4
def select_idle_worker(action, action_space, select_worker):
del action_space<EOL>action.action_ui.select_idle_worker.type = select_worker<EOL>
Select an idle worker.
f1609:m5
def select_army(action, action_space, select_add):
del action_space<EOL>action.action_ui.select_army.selection_add = select_add<EOL>
Select the entire army.
f1609:m6
def select_warp_gates(action, action_space, select_add):
del action_space<EOL>action.action_ui.select_warp_gates.selection_add = select_add<EOL>
Select all warp gates.
f1609:m7
def select_larva(action, action_space):
del action_space<EOL>action.action_ui.select_larva.SetInParent()<EOL>
Select all larva.
f1609:m8
def select_unit(action, action_space, select_unit_act, select_unit_id):
del action_space<EOL>select = action.action_ui.multi_panel<EOL>select.type = select_unit_act<EOL>select.unit_index = select_unit_id<EOL>
Select a specific unit from the multi-unit selection.
f1609:m9
def control_group(action, action_space, control_group_act, control_group_id):
del action_space<EOL>select = action.action_ui.control_group<EOL>select.action = control_group_act<EOL>select.control_group_index = control_group_id<EOL>
Act on a control group, selecting, setting, etc.
f1609:m10
def unload(action, action_space, unload_id):
del action_space<EOL>action.action_ui.cargo_panel.unit_index = unload_id<EOL>
Unload a unit from a transport/bunker/nydus/etc.
f1609:m11
def build_queue(action, action_space, build_queue_id):
del action_space<EOL>action.action_ui.production_panel.unit_index = build_queue_id<EOL>
Cancel a unit in the build queue.
f1609:m12
def cmd_quick(action, action_space, ability_id, queued):
action_cmd = spatial(action, action_space).unit_command<EOL>action_cmd.ability_id = ability_id<EOL>action_cmd.queue_command = queued<EOL>
Do a quick command like 'Stop' or 'Stim'.
f1609:m13
def cmd_screen(action, action_space, ability_id, queued, screen):
action_cmd = spatial(action, action_space).unit_command<EOL>action_cmd.ability_id = ability_id<EOL>action_cmd.queue_command = queued<EOL>screen.assign_to(action_cmd.target_screen_coord)<EOL>
Do a command that needs a point on the screen.
f1609:m14
def cmd_minimap(action, action_space, ability_id, queued, minimap):
action_cmd = spatial(action, action_space).unit_command<EOL>action_cmd.ability_id = ability_id<EOL>action_cmd.queue_command = queued<EOL>minimap.assign_to(action_cmd.target_minimap_coord)<EOL>
Do a command that needs a point on the minimap.
f1609:m15
def autocast(action, action_space, ability_id):
del action_space<EOL>action.action_ui.toggle_autocast.ability_id = ability_id<EOL>
Toggle autocast.
f1609:m16
@classmethod<EOL><INDENT>def enum(cls, options, values):<DEDENT>
names, real = zip(*options)<EOL>del names <EOL>def factory(i, name):<EOL><INDENT>return cls(i, name, (len(real),), lambda a: real[a[<NUM_LIT:0>]], values)<EOL><DEDENT>return factory<EOL>
Create an ArgumentType where you choose one of a set of known values.
f1609:c1:m2
@classmethod<EOL><INDENT>def scalar(cls, value):<DEDENT>
return lambda i, name: cls(i, name, (value,), lambda a: a[<NUM_LIT:0>], None)<EOL>
Create an ArgumentType with a single scalar in range(value).
f1609:c1:m3
@classmethod<EOL><INDENT>def point(cls): <DEDENT>
def factory(i, name):<EOL><INDENT>return cls(i, name, (<NUM_LIT:0>, <NUM_LIT:0>), lambda a: point.Point(*a).floor(), None)<EOL><DEDENT>return factory<EOL>
Create an ArgumentType that is represented by a point.Point.
f1609:c1:m4
@classmethod<EOL><INDENT>def spec(cls, id_, name, sizes):<DEDENT>
return cls(id_, name, sizes, None, None)<EOL>
Create an ArgumentType to be used in ValidActions.
f1609:c1:m5
@classmethod<EOL><INDENT>def types(cls, **kwargs):<DEDENT>
named = {name: factory(Arguments._fields.index(name), name)<EOL>for name, factory in six.iteritems(kwargs)}<EOL>return cls(**named)<EOL>
Create an Arguments of the possible Types.
f1609:c2:m0
@classmethod<EOL><INDENT>def ui_func(cls, id_, name, function_type, avail_fn=always):<DEDENT>
return cls(id_, name, <NUM_LIT:0>, <NUM_LIT:0>, function_type, FUNCTION_TYPES[function_type],<EOL>avail_fn)<EOL>
Define a function representing a ui action.
f1609:c3:m0
@classmethod<EOL><INDENT>def ability(cls, id_, name, function_type, ability_id, general_id=<NUM_LIT:0>):<DEDENT>
assert function_type in ABILITY_FUNCTIONS<EOL>return cls(id_, name, ability_id, general_id, function_type,<EOL>FUNCTION_TYPES[function_type], None)<EOL>
Define a function represented as a game ability.
f1609:c3:m1
@classmethod<EOL><INDENT>def spec(cls, id_, name, args):<DEDENT>
return cls(id_, name, None, None, None, args, None)<EOL>
Create a Function to be used in ValidActions.
f1609:c3:m2
def __call__(self, *args):
return FunctionCall.init_with_validation(self.id, args)<EOL>
A convenient way to create a FunctionCall from this Function.
f1609:c3:m5
def str(self, space=False):
return "<STR_LIT>" % (str(int(self.id)).rjust(space and <NUM_LIT:4>),<EOL>self.name.ljust(space and <NUM_LIT:50>),<EOL>"<STR_LIT>".join(str(a) for a in self.args))<EOL>
String version. Set space=True to line them all up nicely.
f1609:c3:m7
@classmethod<EOL><INDENT>def init_with_validation(cls, function, arguments):<DEDENT>
func = FUNCTIONS[function]<EOL>args = []<EOL>for arg, arg_type in zip(arguments, func.args):<EOL><INDENT>if arg_type.values: <EOL><INDENT>if isinstance(arg, six.string_types):<EOL><INDENT>try:<EOL><INDENT>args.append([arg_type.values[arg]])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError("<STR_LIT>" % (<EOL>arg, [v.name for v in arg_type.values]))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(arg, (list, tuple)):<EOL><INDENT>arg = arg[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>args.append([arg_type.values(arg)])<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>arg, list(arg_type.values)))<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(arg, int): <EOL><INDENT>args.append([arg])<EOL><DEDENT>else: <EOL><INDENT>args.append(list(arg))<EOL><DEDENT><DEDENT>return cls(func.id, args)<EOL>
Return a `FunctionCall` given some validation for the function and args. Args: function: A function name or id, to be converted into a function id enum. arguments: An iterable of function arguments. Arguments that are enum types can be passed by name. Arguments that only take one value (ie not a point) don't need to be wrapped in a list. Returns: A new `FunctionCall` instance. Raises: KeyError: if the enum name doesn't exist. ValueError: if the enum id doesn't exist.
f1609:c5:m0
@classmethod<EOL><INDENT>def all_arguments(cls, function, arguments):<DEDENT>
if isinstance(arguments, dict):<EOL><INDENT>arguments = Arguments(**arguments)<EOL><DEDENT>elif not isinstance(arguments, Arguments):<EOL><INDENT>arguments = Arguments(*arguments)<EOL><DEDENT>return cls(function, arguments)<EOL>
Helper function for creating `FunctionCall`s with `Arguments`. Args: function: The value to store for the action function. arguments: The values to store for the arguments of the action. Can either be an `Arguments` object, a `dict`, or an iterable. If a `dict` or an iterable is provided, the values will be unpacked into an `Arguments` object. Returns: A new `FunctionCall` instance.
f1609:c5:m1
def pick_unused_ports(num_ports, retry_interval_secs=<NUM_LIT:3>, retry_attempts=<NUM_LIT:5>):
ports = set()<EOL>for _ in range(retry_attempts):<EOL><INDENT>ports.update(<EOL>portpicker.pick_unused_port() for _ in range(num_ports - len(ports)))<EOL>ports.discard(None) <EOL>if len(ports) == num_ports:<EOL><INDENT>return list(ports)<EOL><DEDENT>time.sleep(retry_interval_secs)<EOL><DEDENT>return_ports(ports)<EOL>raise RuntimeError("<STR_LIT>" % num_ports)<EOL>
Reserves and returns a list of `num_ports` unused ports.
f1610:m0
def pick_contiguous_unused_ports(<EOL>num_ports,<EOL>retry_interval_secs=<NUM_LIT:3>,<EOL>retry_attempts=<NUM_LIT:5>):
for _ in range(retry_attempts):<EOL><INDENT>start_port = portpicker.pick_unused_port()<EOL>if start_port is not None:<EOL><INDENT>ports = [start_port + p for p in range(num_ports)]<EOL>if all(portpicker.is_port_free(p) for p in ports):<EOL><INDENT>return ports<EOL><DEDENT>else:<EOL><INDENT>return_ports(ports)<EOL><DEDENT><DEDENT>time.sleep(retry_interval_secs)<EOL><DEDENT>raise RuntimeError("<STR_LIT>" % num_ports)<EOL>
Reserves and returns a list of `num_ports` contiguous unused ports.
f1610:m1
def return_ports(ports):
for port in ports:<EOL><INDENT>portpicker.return_port(port)<EOL><DEDENT>
Returns previously reserved ports so that may be reused.
f1610:m2
def smooth_hue_palette(scale):
<EOL>array = numpy.arange(scale)<EOL>h = array * (<NUM_LIT:6> / scale) <EOL>x = <NUM_LIT:255> * (<NUM_LIT:1> - numpy.absolute(numpy.mod(h, <NUM_LIT:2>) - <NUM_LIT:1>))<EOL>c = <NUM_LIT:255><EOL>out = numpy.zeros(h.shape + (<NUM_LIT:3>,), float)<EOL>r = out[..., <NUM_LIT:0>]<EOL>g = out[..., <NUM_LIT:1>]<EOL>b = out[..., <NUM_LIT:2>]<EOL>mask = (<NUM_LIT:0> < h) & (h < <NUM_LIT:1>)<EOL>r[mask] = c<EOL>g[mask] = x[mask]<EOL>mask = (<NUM_LIT:1> <= h) & (h < <NUM_LIT:2>)<EOL>r[mask] = x[mask]<EOL>g[mask] = c<EOL>mask = (<NUM_LIT:2> <= h) & (h < <NUM_LIT:3>)<EOL>g[mask] = c<EOL>b[mask] = x[mask]<EOL>mask = (<NUM_LIT:3> <= h) & (h < <NUM_LIT:4>)<EOL>g[mask] = x[mask]<EOL>b[mask] = c<EOL>mask = (<NUM_LIT:4> <= h) & (h < <NUM_LIT:5>)<EOL>r[mask] = x[mask]<EOL>b[mask] = c<EOL>mask = <NUM_LIT:5> <= h<EOL>r[mask] = c<EOL>b[mask] = x[mask]<EOL>return out<EOL>
Takes an array of ints and returns a corresponding colored rgb array.
f1611:m0
def piece_wise_linear(scale, points):
assert len(points) >= <NUM_LIT:2><EOL>assert points[<NUM_LIT:0>][<NUM_LIT:0>] == <NUM_LIT:0><EOL>assert points[-<NUM_LIT:1>][<NUM_LIT:0>] == <NUM_LIT:1><EOL>assert all(i < j for i, j in zip(points[:-<NUM_LIT:1>], points[<NUM_LIT:1>:]))<EOL>out = numpy.zeros((scale, <NUM_LIT:3>))<EOL>p1, c1 = points[<NUM_LIT:0>]<EOL>p2, c2 = points[<NUM_LIT:1>]<EOL>next_pt = <NUM_LIT:2><EOL>for i in range(<NUM_LIT:1>, scale):<EOL><INDENT>v = i / scale<EOL>if v > p2:<EOL><INDENT>p1, c1 = p2, c2<EOL>p2, c2 = points[next_pt]<EOL>next_pt += <NUM_LIT:1><EOL><DEDENT>frac = (v - p1) / (p2 - p1)<EOL>out[i, :] = c1 * (<NUM_LIT:1> - frac) + c2 * frac<EOL><DEDENT>return out<EOL>
Create a palette that is piece-wise linear given some colors at points.
f1611:m2
def unit_type(scale=None):
<EOL>palette_size = scale or max(static_data.UNIT_TYPES) + <NUM_LIT:1><EOL>palette = shuffled_hue(palette_size)<EOL>assert len(static_data.UNIT_TYPES) <= len(distinct_colors)<EOL>for i, v in enumerate(static_data.UNIT_TYPES):<EOL><INDENT>palette[v] = distinct_colors[i]<EOL><DEDENT>return palette<EOL>
Returns a palette that maps unit types to rgb colors.
f1611:m5
def __init__(self, data):
self._units = {u.unit_id: u.name for u in data.units}<EOL>self._unit_stats = {u.unit_id: u for u in data.units}<EOL>self._abilities = {a.ability_id: a for a in data.abilities}<EOL>self._general_abilities = {a.remaps_to_ability_id<EOL>for a in data.abilities<EOL>if a.remaps_to_ability_id}<EOL>for a in six.itervalues(self._abilities):<EOL><INDENT>a.hotkey = a.hotkey.lower()<EOL><DEDENT>
Takes data from RequestData.
f1612:c0:m0
@contextlib.contextmanager<EOL>def catch_websocket_connection_errors():
try:<EOL><INDENT>yield<EOL><DEDENT>except websocket.WebSocketConnectionClosedException:<EOL><INDENT>raise ConnectionError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>except websocket.WebSocketTimeoutException:<EOL><INDENT>raise ConnectionError("<STR_LIT>")<EOL><DEDENT>except socket.error as e:<EOL><INDENT>raise ConnectionError("<STR_LIT>" % e)<EOL><DEDENT>
A context manager that translates websocket errors into ConnectionError.
f1613:m0
@sw.decorate<EOL><INDENT>def read(self):<DEDENT>
if FLAGS.sc2_verbose_protocol:<EOL><INDENT>self._log("<STR_LIT>".center(<NUM_LIT>, "<STR_LIT:->"))<EOL>start = time.time()<EOL><DEDENT>response = self._read()<EOL>if FLAGS.sc2_verbose_protocol:<EOL><INDENT>self._log("<STR_LIT>" % (<NUM_LIT:1000> * (time.time() - start)))<EOL>self._log_packet(response)<EOL><DEDENT>if not response.HasField("<STR_LIT:status>"):<EOL><INDENT>raise ProtocolError("<STR_LIT>")<EOL><DEDENT>prev_status = self._status<EOL>self._status = Status(response.status) <EOL>if response.error:<EOL><INDENT>err_str = ("<STR_LIT>"<EOL>"<STR_LIT>" % (<EOL>prev_status, self._status, "<STR_LIT:\n>".join(response.error)))<EOL>logging.error(err_str)<EOL>raise ProtocolError(err_str)<EOL><DEDENT>return response<EOL>
Read a Response, do some validation, and return it.
f1613:c2:m3
@sw.decorate<EOL><INDENT>def write(self, request):<DEDENT>
if FLAGS.sc2_verbose_protocol:<EOL><INDENT>self._log("<STR_LIT>".center(<NUM_LIT>, "<STR_LIT:->") + "<STR_LIT:\n>")<EOL>self._log_packet(request)<EOL><DEDENT>self._write(request)<EOL>
Write a Request.
f1613:c2:m4
def send_req(self, request):
self.write(request)<EOL>return self.read()<EOL>
Write a pre-filled Request and return the Response.
f1613:c2:m5
def send(self, **kwargs):
assert len(kwargs) == <NUM_LIT:1>, "<STR_LIT>"<EOL>res = self.send_req(sc_pb.Request(**kwargs))<EOL>return getattr(res, list(kwargs.keys())[<NUM_LIT:0>])<EOL>
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
f1613:c2:m6
def _log(self, s):
<EOL>sys.stderr.write(s)<EOL>sys.stderr.flush()<EOL>
r"""Log a string. It flushes but doesn't append \n, so do that yourself.
f1613:c2:m8
def _read(self):
with sw("<STR_LIT>"):<EOL><INDENT>with catch_websocket_connection_errors():<EOL><INDENT>response_str = self._sock.recv()<EOL><DEDENT><DEDENT>if not response_str:<EOL><INDENT>raise ProtocolError("<STR_LIT>")<EOL><DEDENT>response = sc_pb.Response()<EOL>with sw("<STR_LIT>"):<EOL><INDENT>response.ParseFromString(response_str)<EOL><DEDENT>return response<EOL>
Actually read the response and parse it, returning a Response.
f1613:c2:m9
def _write(self, request):
with sw("<STR_LIT>"):<EOL><INDENT>request_str = request.SerializeToString()<EOL><DEDENT>with sw("<STR_LIT>"):<EOL><INDENT>with catch_websocket_connection_errors():<EOL><INDENT>self._sock.send(request_str)<EOL><DEDENT><DEDENT>
Actually serialize and write the request.
f1613:c2:m10
def _to_point(dims):
assert dims<EOL>if isinstance(dims, (tuple, list)):<EOL><INDENT>if len(dims) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(dims))<EOL><DEDENT>else:<EOL><INDENT>width = int(dims[<NUM_LIT:0>])<EOL>height = int(dims[<NUM_LIT:1>])<EOL>if width <= <NUM_LIT:0> or height <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>".format(dims))<EOL><DEDENT>else:<EOL><INDENT>return point.Point(width, height)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>size = int(dims)<EOL>if size <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(dims))<EOL><DEDENT>else:<EOL><INDENT>return point.Point(size, size)<EOL><DEDENT><DEDENT>
Convert (width, height) or size -> point.Point.
f1614:m0
def parse_agent_interface_format(<EOL>feature_screen=None,<EOL>feature_minimap=None,<EOL>rgb_screen=None,<EOL>rgb_minimap=None,<EOL>action_space=None,<EOL>camera_width_world_units=None,<EOL>use_feature_units=False,<EOL>use_raw_units=False,<EOL>use_unit_counts=False,<EOL>use_camera_position=False):
if feature_screen or feature_minimap:<EOL><INDENT>feature_dimensions = Dimensions(<EOL>screen=feature_screen,<EOL>minimap=feature_minimap)<EOL><DEDENT>else:<EOL><INDENT>feature_dimensions = None<EOL><DEDENT>if rgb_screen or rgb_minimap:<EOL><INDENT>rgb_dimensions = Dimensions(<EOL>screen=rgb_screen,<EOL>minimap=rgb_minimap)<EOL><DEDENT>else:<EOL><INDENT>rgb_dimensions = None<EOL><DEDENT>return AgentInterfaceFormat(<EOL>feature_dimensions=feature_dimensions,<EOL>rgb_dimensions=rgb_dimensions,<EOL>action_space=(action_space and actions.ActionSpace[action_space.upper()]),<EOL>camera_width_world_units=camera_width_world_units,<EOL>use_feature_units=use_feature_units,<EOL>use_raw_units=use_raw_units,<EOL>use_unit_counts=use_unit_counts,<EOL>use_camera_position=use_camera_position<EOL>)<EOL>
Creates an AgentInterfaceFormat object from keyword args. Convenient when using dictionaries or command-line arguments for config. Note that the feature_* and rgb_* properties define the respective spatial observation dimensions and accept: * None or 0 to disable that spatial observation. * A single int for a square observation with that side length. * A (int, int) tuple for a rectangular (width, height) observation. Args: feature_screen: If specified, so must feature_minimap be. feature_minimap: If specified, so must feature_screen be. rgb_screen: If specified, so must rgb_minimap be. rgb_minimap: If specified, so must rgb_screen be. action_space: ["FEATURES", "RGB"]. camera_width_world_units: An int. use_feature_units: A boolean, defaults to False. use_raw_units: A boolean, defaults to False. use_unit_counts: A boolean, defaults to False. use_camera_position: A boolean, defaults to False. Returns: An `AgentInterfaceFormat` object. Raises: ValueError: If an invalid parameter is specified.
f1614:m1
def features_from_game_info(<EOL>game_info,<EOL>use_feature_units=False,<EOL>use_raw_units=False,<EOL>action_space=None,<EOL>hide_specific_actions=True,<EOL>use_unit_counts=False,<EOL>use_camera_position=False):
if game_info.options.HasField("<STR_LIT>"):<EOL><INDENT>fl_opts = game_info.options.feature_layer<EOL>feature_dimensions = Dimensions(<EOL>screen=(fl_opts.resolution.x, fl_opts.resolution.y),<EOL>minimap=(fl_opts.minimap_resolution.x, fl_opts.minimap_resolution.y))<EOL><DEDENT>else:<EOL><INDENT>feature_dimensions = None<EOL><DEDENT>if game_info.options.HasField("<STR_LIT>"):<EOL><INDENT>rgb_opts = game_info.options.render<EOL>rgb_dimensions = Dimensions(<EOL>screen=(rgb_opts.resolution.x, rgb_opts.resolution.y),<EOL>minimap=(rgb_opts.minimap_resolution.x, rgb_opts.minimap_resolution.y))<EOL><DEDENT>else:<EOL><INDENT>rgb_dimensions = None<EOL><DEDENT>map_size = game_info.start_raw.map_size<EOL>camera_width_world_units = game_info.options.feature_layer.width<EOL>return Features(<EOL>agent_interface_format=AgentInterfaceFormat(<EOL>feature_dimensions=feature_dimensions,<EOL>rgb_dimensions=rgb_dimensions,<EOL>use_feature_units=use_feature_units,<EOL>use_raw_units=use_raw_units,<EOL>use_unit_counts=use_unit_counts,<EOL>use_camera_position=use_camera_position,<EOL>camera_width_world_units=camera_width_world_units,<EOL>action_space=action_space,<EOL>hide_specific_actions=hide_specific_actions),<EOL>map_size=map_size)<EOL>
Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.ResponseGameInfo` from the game. use_feature_units: Whether to include the feature unit observation. use_raw_units: Whether to include raw unit data in observations. This differs from feature_units because it includes units outside the screen and hidden units, and because unit positions are given in terms of world units instead of screen units. action_space: If you pass both feature and rgb sizes, then you must also specify which you want to use for your actions as an ActionSpace enum. hide_specific_actions: [bool] Some actions (eg cancel) have many specific versions (cancel this building, cancel that spell) and can be represented in a more general form. If a specific action is available, the general will also be available. If you set `hide_specific_actions` to False, the specific versions will also be available, but if it's True, the specific ones will be hidden. Similarly, when transforming back, a specific action will be returned as the general action. This simplifies the action space, though can lead to some actions in replays not being exactly representable using only the general actions. use_unit_counts: Whether to include unit_counts observation. Disabled by default since it gives information outside the visible area. use_camera_position: Whether to include the camera's position (in world units) in the observations. Returns: A features object matching the specified parameterisation.
f1614:m2
def _init_valid_functions(action_dimensions):
sizes = {<EOL>"<STR_LIT>": tuple(int(i) for i in action_dimensions.screen),<EOL>"<STR_LIT>": tuple(int(i) for i in action_dimensions.screen),<EOL>"<STR_LIT>": tuple(int(i) for i in action_dimensions.minimap),<EOL>}<EOL>types = actions.Arguments(*[<EOL>actions.ArgumentType.spec(t.id, t.name, sizes.get(t.name, t.sizes))<EOL>for t in actions.TYPES])<EOL>functions = actions.Functions([<EOL>actions.Function.spec(f.id, f.name, tuple(types[t.id] for t in f.args))<EOL>for f in actions.FUNCTIONS])<EOL>return actions.ValidActions(types, functions)<EOL>
Initialize ValidFunctions and set up the callbacks.
f1614:m3
def unpack(self, obs):
planes = getattr(obs.feature_layer_data, self.layer_set)<EOL>plane = getattr(planes, self.name)<EOL>return self.unpack_layer(plane)<EOL>
Return a correctly shaped numpy array for this feature.
f1614:c13:m0
@staticmethod<EOL><INDENT>@sw.decorate<EOL>def unpack_layer(plane):<DEDENT>
size = point.Point.build(plane.size)<EOL>if size == (<NUM_LIT:0>, <NUM_LIT:0>):<EOL><INDENT>return None<EOL><DEDENT>data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per_pixel])<EOL>if plane.bits_per_pixel == <NUM_LIT:1>:<EOL><INDENT>data = np.unpackbits(data)<EOL>if data.shape[<NUM_LIT:0>] != size.x * size.y:<EOL><INDENT>data = data[:size.x * size.y]<EOL><DEDENT><DEDENT>return data.reshape(size.y, size.x)<EOL>
Return a correctly shaped numpy array given the feature layer bytes.
f1614:c13:m1
@staticmethod<EOL><INDENT>@sw.decorate<EOL>def unpack_rgb_image(plane):<DEDENT>
assert plane.bits_per_pixel == <NUM_LIT>, "<STR_LIT>".format(plane.bits_per_pixel)<EOL>size = point.Point.build(plane.size)<EOL>data = np.frombuffer(plane.data, dtype=np.uint8)<EOL>return data.reshape(size.y, size.x, <NUM_LIT:3>)<EOL>
Return a correctly shaped numpy array given the image bytes.
f1614:c13:m2
def __init__(<EOL>self,<EOL>feature_dimensions=None,<EOL>rgb_dimensions=None,<EOL>action_space=None,<EOL>camera_width_world_units=None,<EOL>use_feature_units=False,<EOL>use_raw_units=False,<EOL>use_unit_counts=False,<EOL>use_camera_position=False,<EOL>hide_specific_actions=True):
if not feature_dimensions and not rgb_dimensions:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if action_space:<EOL><INDENT>if not isinstance(action_space, actions.ActionSpace):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if ((action_space == actions.ActionSpace.FEATURES and<EOL>not feature_dimensions) or<EOL>(action_space == actions.ActionSpace.RGB and<EOL>not rgb_dimensions)):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>action_space, feature_dimensions, rgb_dimensions))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if feature_dimensions and rgb_dimensions:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif feature_dimensions:<EOL><INDENT>action_space = actions.ActionSpace.FEATURES<EOL><DEDENT>else:<EOL><INDENT>action_space = actions.ActionSpace.RGB<EOL><DEDENT><DEDENT>self._feature_dimensions = feature_dimensions<EOL>self._rgb_dimensions = rgb_dimensions<EOL>self._action_space = action_space<EOL>self._camera_width_world_units = camera_width_world_units or <NUM_LIT><EOL>self._use_feature_units = use_feature_units<EOL>self._use_raw_units = use_raw_units<EOL>self._use_unit_counts = use_unit_counts<EOL>self._use_camera_position = use_camera_position<EOL>self._hide_specific_actions = hide_specific_actions<EOL>if action_space == actions.ActionSpace.FEATURES:<EOL><INDENT>self._action_dimensions = feature_dimensions<EOL><DEDENT>else:<EOL><INDENT>self._action_dimensions = rgb_dimensions<EOL><DEDENT>
Initializer. Args: feature_dimensions: Feature layer `Dimension`s. Either this or rgb_dimensions (or both) must be set. rgb_dimensions: RGB `Dimension`. Either this or feature_dimensions (or both) must be set. action_space: If you pass both feature and rgb sizes, then you must also specify which you want to use for your actions as an ActionSpace enum. camera_width_world_units: The width of your screen in world units. If your feature_dimensions.screen=(64, 48) and camera_width is 24, then each px represents 24 / 64 = 0.375 world units in each of x and y. It'll then represent a camera of size (24, 0.375 * 48) = (24, 18) world units. use_feature_units: Whether to include feature unit data in observations. use_raw_units: Whether to include raw unit data in observations. This differs from feature_units because it includes units outside the screen and hidden units, and because unit positions are given in terms of world units instead of screen units. use_unit_counts: Whether to include unit_counts observation. Disabled by default since it gives information outside the visible area. use_camera_position: Whether to include the camera's position (in world units) in the observations. hide_specific_actions: [bool] Some actions (eg cancel) have many specific versions (cancel this building, cancel that spell) and can be represented in a more general form. If a specific action is available, the general will also be available. If you set `hide_specific_actions` to False, the specific versions will also be available, but if it's True, the specific ones will be hidden. Similarly, when transforming back, a specific action will be returned as the general action. This simplifies the action space, though can lead to some actions in replays not being exactly representable using only the general actions. Raises: ValueError: if the parameters are inconsistent.
f1614:c17:m0