text
stringlengths
81
112k
Specialised layout algorithm for dealing with graphs with many connected components. This will first fid relative positions for the components by spectrally embedding their centroids, then spectrally embed each individual connected component positioning them according to the centroid embeddings. This provid...
Given a graph compute the spectral embedding of the graph. This is simply the eigenvectors of the laplacian of the graph. Here we use the normalized laplacian. Parameters ---------- data: array of shape (n_samples, n_features) The source data graph: sparse matrix The (weighted)...
Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either side of the hyperplane. This is the basis for a random projection tree, which simply u...
Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either side of the hyperplane. This is the basis for a random projection tree, which simply u...
Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, shape (3,) The internal state of the rng leaf_size: int (opt...
Determine the number of nodes in a tree def num_nodes(tree): """Determine the number of nodes in a tree""" if tree.is_leaf: return 1 else: return 1 + num_nodes(tree.left_child) + num_nodes(tree.right_child)
Determine the number of leaves in a tree def num_leaves(tree): """Determine the number of leaves in a tree""" if tree.is_leaf: return 1 else: return num_leaves(tree.left_child) + num_leaves(tree.right_child)
Determine the most number on non zeros in a hyperplane entry def max_sparse_hyperplane_size(tree): """Determine the most number on non zeros in a hyperplane entry""" if tree.is_leaf: return 0 else: return max( tree.hyperplane.shape[1], max_sparse_hyperplane_size(tree...
Build a random projection forest with ``n_trees``. Parameters ---------- data n_neighbors n_trees rng_state angular Returns ------- forest: list A list of random projection trees. def make_forest(data, n_neighbors, n_trees, rng_state, angular=False): """Build a ran...
Generate an array of sets of candidate nearest neighbors by constructing a random projection forest and taking the leaves of all the trees. Any given tree has leaves that are a set of potential nearest neighbors. Given enough trees the set of all such leaves gives a good likelihood of getting a good set...
Compute a continuous version of the distance to the kth nearest neighbor. That is, this is similar to knn-distance but allows continuous k values rather than requiring an integral k. In esscence we are simply computing the distance such that the cardinality of fuzzy set we generate is k. Parameters...
Compute the ``n_neighbors`` nearest points for each data point in ``X`` under ``metric``. This may be exact, but more likely is approximated via nearest neighbor descent. Parameters ---------- X: array of shape (n_samples, n_features) The input data to compute the k-neighbor graph of. ...
Construct the membership strength data for the 1-skeleton of each local fuzzy simplicial set -- this is formed as a sparse matrix where each row is a local fuzzy simplicial set, with a membership strength for the 1-simplex to each other data point. Parameters ---------- knn_indices: array of sh...
Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geodesic distance at each point, creating a fuzzy simplicial set for eac...
Under the assumption of categorical distance for the intersecting simplicial set perform a fast intersection. Parameters ---------- rows: array An array of the row of each non-zero in the sparse matrix representation. cols: array An array of the column of each non-zero in t...
Reset the local connectivity requirement -- each data sample should have complete confidence in at least one 1-simplex in the simplicial set. We can enforce this by locally rescaling confidences, and then remerging the different local simplicial sets together. Parameters ---------- simplicial_s...
Combine a fuzzy simplicial set with another fuzzy simplicial set generated from categorical data using categorical distances. The target data is assumed to be categorical label data (a vector of labels), and this will update the fuzzy simplicial set to respect that label data. TODO: optional category c...
Given a set of weights and number of epochs generate the number of epochs per sample for each weight. Parameters ---------- weights: array of shape (n_1_simplices) The weights ofhow much we wish to sample each 1-simplex. n_epochs: int The total number of epochs we want to train for...
Reduced Euclidean distance. Parameters ---------- x: array of shape (embedding_dim,) y: array of shape (embedding_dim,) Returns ------- The squared euclidean distance between x and y def rdist(x, y): """Reduced Euclidean distance. Parameters ---------- x: array of shape (...
Improve an embedding using stochastic gradient descent to minimize the fuzzy set cross entropy between the 1-skeletons of the high dimensional and low dimensional fuzzy simplicial sets. In practice this is done by sampling edges based on their membership strength (with the (1-p) terms coming from negati...
Perform a fuzzy simplicial set embedding, using a specified initialisation method and then minimizing the fuzzy set cross entropy between the 1-skeletons of the high and low dimensional fuzzy simplicial sets. Parameters ---------- data: array of shape (n_samples, n_features) The source ...
Given indices and weights and an original embeddings initialize the positions of new points relative to the indices and weights (of their neighbors in the source data). Parameters ---------- indices: array of shape (n_new_samples, n_neighbors) The indices of the neighbors of each new sample...
Fit a, b params for the differentiable curve used in lower dimensional fuzzy simplicial complex construction. We want the smooth curve (from a pre-defined family with simple gradient) that best matches an offset exponential decay. def find_ab_params(spread, min_dist): """Fit a, b params for the differe...
Fit X into an embedded space. Optionally use y for supervised dimension reduction. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a...
Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. ...
Transform X into the existing embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) New data to be transformed. Returns ------- X_new : array, shape (n_samples, n_components) Emb...
Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments on sparse matrix data provided in CSR ind, indptr and data format. Numba doesn't support higher order functions directly, but we can instead JIT compile the version of NN-descent...
Get an InterfaceOptions for the config. def interface_options(score=False, raw=False, features=None, rgb=None): """Get an InterfaceOptions for the config.""" interface = sc_pb.InterfaceOptions() interface.score = score interface.raw = raw if features: interface.feature_layer.width = 24 interface.feat...
Registers a flag whose value parses as a point. def DEFINE_point(name, default, help): # pylint: disable=invalid-name,redefined-builtin """Registers a flag whose value parses as a point.""" flags.DEFINE(PointParser(), name, default, help)
Choose the action space for the action proto. def spatial(action, action_space): """Choose the action space for the action proto.""" if action_space == ActionSpace.FEATURES: return action.action_feature_layer elif action_space == ActionSpace.RGB: return action.action_render else: raise ValueError("...
Move the camera. def move_camera(action, action_space, minimap): """Move the camera.""" minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)
Select a unit at a point. def select_point(action, action_space, select_point_act, screen): """Select a unit at a point.""" select = spatial(action, action_space).unit_selection_point screen.assign_to(select.selection_screen_coord) select.type = select_point_act
Select units within a rectangle. def select_rect(action, action_space, select_add, screen, screen2): """Select units within a rectangle.""" select = spatial(action, action_space).unit_selection_rect out_rect = select.selection_screen_coord.add() screen_rect = point.Rect(screen, screen2) screen_rect.tl.assign...
Select an idle worker. def select_idle_worker(action, action_space, select_worker): """Select an idle worker.""" del action_space action.action_ui.select_idle_worker.type = select_worker
Select the entire army. def select_army(action, action_space, select_add): """Select the entire army.""" del action_space action.action_ui.select_army.selection_add = select_add
Select all warp gates. def select_warp_gates(action, action_space, select_add): """Select all warp gates.""" del action_space action.action_ui.select_warp_gates.selection_add = select_add
Select a specific unit from the multi-unit selection. def select_unit(action, action_space, select_unit_act, select_unit_id): """Select a specific unit from the multi-unit selection.""" del action_space select = action.action_ui.multi_panel select.type = select_unit_act select.unit_index = select_unit_id
Act on a control group, selecting, setting, etc. def control_group(action, action_space, control_group_act, control_group_id): """Act on a control group, selecting, setting, etc.""" del action_space select = action.action_ui.control_group select.action = control_group_act select.control_group_index = control...
Unload a unit from a transport/bunker/nydus/etc. def unload(action, action_space, unload_id): """Unload a unit from a transport/bunker/nydus/etc.""" del action_space action.action_ui.cargo_panel.unit_index = unload_id
Cancel a unit in the build queue. def build_queue(action, action_space, build_queue_id): """Cancel a unit in the build queue.""" del action_space action.action_ui.production_panel.unit_index = build_queue_id
Do a quick command like 'Stop' or 'Stim'. def cmd_quick(action, action_space, ability_id, queued): """Do a quick command like 'Stop' or 'Stim'.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued
Do a command that needs a point on the screen. def cmd_screen(action, action_space, ability_id, queued, screen): """Do a command that needs a point on the screen.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued screen.assign_to(a...
Do a command that needs a point on the minimap. def cmd_minimap(action, action_space, ability_id, queued, minimap): """Do a command that needs a point on the minimap.""" action_cmd = spatial(action, action_space).unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued minimap.assign...
Toggle autocast. def autocast(action, action_space, ability_id): """Toggle autocast.""" del action_space action.action_ui.toggle_autocast.ability_id = ability_id
Create an ArgumentType where you choose one of a set of known values. def enum(cls, options, values): """Create an ArgumentType where you choose one of a set of known values.""" names, real = zip(*options) del names # unused def factory(i, name): return cls(i, name, (len(real),), lambda a: real...
Create an ArgumentType with a single scalar in range(value). def scalar(cls, value): """Create an ArgumentType with a single scalar in range(value).""" return lambda i, name: cls(i, name, (value,), lambda a: a[0], None)
Create an ArgumentType that is represented by a point.Point. def point(cls): # No range because it's unknown at this time. """Create an ArgumentType that is represented by a point.Point.""" def factory(i, name): return cls(i, name, (0, 0), lambda a: point.Point(*a).floor(), None) return factory
Create an Arguments of the possible Types. def types(cls, **kwargs): """Create an Arguments of the possible Types.""" named = {name: factory(Arguments._fields.index(name), name) for name, factory in six.iteritems(kwargs)} return cls(**named)
Define a function representing a ui action. def ui_func(cls, id_, name, function_type, avail_fn=always): """Define a function representing a ui action.""" return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type], avail_fn)
Define a function represented as a game ability. def ability(cls, id_, name, function_type, ability_id, general_id=0): """Define a function represented as a game ability.""" assert function_type in ABILITY_FUNCTIONS return cls(id_, name, ability_id, general_id, function_type, FUNCTION_TYPES[...
String version. Set space=True to line them all up nicely. def str(self, space=False): """String version. Set space=True to line them all up nicely.""" return "%s/%s (%s)" % (str(int(self.id)).rjust(space and 4), self.name.ljust(space and 50), "; ".join(str...
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 ...
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 provide...
Print the valid 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, minima...
Reserves and returns a list of `num_ports` unused ports. def pick_unused_ports(num_ports, retry_interval_secs=3, retry_attempts=5): """Reserves and returns a list of `num_ports` unused ports.""" ports = set() for _ in range(retry_attempts): ports.update( portpicker.pick_unused_port() for _ in range(n...
Reserves and returns a list of `num_ports` contiguous unused ports. def pick_contiguous_unused_ports( num_ports, retry_interval_secs=3, retry_attempts=5): """Reserves and returns a list of `num_ports` contiguous unused ports.""" for _ in range(retry_attempts): start_port = portpicker.pick_unused_po...
Run one thread worth of the environment with agents. 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, players=players, agent_interface_format=sc2_env.parse_agent_interface_format( ...
Run an agent. def main(unused_argv): """Run an agent.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace map_inst = maps.get(FLAGS.map) agent_classes = [] players = [] agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_modu...
Raise if the result has an error, otherwise return the result. def check_error(res, error_enum): """Raise if the result has an error, otherwise return the result.""" if res.HasField("error"): enum_name = error_enum.DESCRIPTOR.full_name error_name = error_enum.Name(res.error) details = getattr(res, "err...
Decorator to call `check_error` on the return value. def decorate_check_error(error_enum): """Decorator to call `check_error` on the return value.""" def decorator(func): @functools.wraps(func) def _check_error(*args, **kwargs): return check_error(func(*args, **kwargs), error_enum) return _check_...
Decorator to skip this call if we're in one of the skipped states. def skip_status(*skipped): """Decorator to skip this call if we're in one of the skipped states.""" def decorator(func): @functools.wraps(func) def _skip_status(self, *args, **kwargs): if self.status not in skipped: return fun...
Decorator to assert that we're in a valid state. def valid_status(*valid): """Decorator to assert that we're in a valid state.""" def decorator(func): @functools.wraps(func) def _valid_status(self, *args, **kwargs): if self.status not in valid: raise protocol.ProtocolError( "`%s` ...
Decorator to handle 'Game has already ended' exceptions. def catch_game_end(func): """Decorator to handle 'Game has already ended' exceptions.""" @functools.wraps(func) def _catch_game_end(self, *args, **kwargs): """Decorator to handle 'Game has already ended' exceptions.""" prev_status = self.status ...
Connect to the websocket, retrying as needed. Returns the socket. def _connect(self, host, port, proc, timeout_seconds): """Connect to the websocket, retrying as needed. Returns the socket.""" if ":" in host and not host.startswith("["): # Support ipv6 addresses. host = "[%s]" % host url = "ws://%s:...
Save a map into temp dir so create game can access it in multiplayer. def save_map(self, map_path, map_data): """Save a map into temp dir so create game can access it in multiplayer.""" return self._client.send(save_map=sc_pb.RequestSaveMap( map_path=map_path, map_data=map_data))
Get the raw static data for the current game. Prefer `data` instead. def data_raw(self): """Get the raw static data for the current game. Prefer `data` instead.""" return self._client.send(data=sc_pb.RequestData( ability_id=True, unit_type_id=True))
Step the engine forward by one (or more) step. def step(self, count=1): """Step the engine forward by one (or more) step.""" return self._client.send(step=sc_pb.RequestStep(count=count))
Send a `sc_pb.RequestAction`, which may include multiple actions. def actions(self, req_action): """Send a `sc_pb.RequestAction`, which may include multiple actions.""" if FLAGS.sc2_log_actions: for action in req_action.actions: sys.stderr.write(str(action)) sys.stderr.flush() return...
Send a single action. This is a shortcut for `actions`. def act(self, action): """Send a single action. This is a shortcut for `actions`.""" if action and action.ListFields(): # Skip no-ops. return self.actions(sc_pb.RequestAction(actions=[action]))
Send chat message as a broadcast. def chat(self, message): """Send chat message as a broadcast.""" if message: action_chat = sc_pb.ActionChat( channel=sc_pb.ActionChat.Broadcast, message=message) action = sc_pb.Action(action_chat=action_chat) return self.act(action)
Save a replay, returning the data. def save_replay(self): """Save a replay, returning the data.""" res = self._client.send(save_replay=sc_pb.RequestSaveReplay()) return res.data
Run a debug command. def debug(self, debug_commands): """Run a debug command.""" if isinstance(debug_commands, sc_debug.DebugCommand): debug_commands = [debug_commands] return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))
Shut down the SC2 process. def quit(self): """Shut down the SC2 process.""" try: # Don't expect a response. self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit())) except protocol.ConnectionError: pass # It's likely already (shutting) down, so continue as if it worked. finally: ...
A run loop to have agents and an environment interact. 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(...
Return the map data for a map by name or path. def map_data(self, map_name): """Return the map data for a map by name or path.""" with gfile.Open(os.path.join(self.data_dir, "Maps", map_name), "rb") as f: return f.read()
Return the replay data given a path to the replay. 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()
A generator yielding the full path to the replays under `replay_dir`. 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 retu...
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...
An iterator over all subclasses of `cls`. 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
Turn all string indices into int indices, preserving ellipsis. def _indices(self, indices): """Turn all string indices into int indices, preserving ellipsis.""" if isinstance(indices, tuple): out = [] dim = 0 for i, index in enumerate(indices): if index is Ellipsis: out.appe...
Turn a string into a real index, otherwise return the index. def _get_index(self, dim, index): """Turn a string into a real index, otherwise return the index.""" if isinstance(index, six.string_types): try: return self._index_names[dim][index] except KeyError: raise KeyError("Name '...
Assign `x` and `y` to an object that has properties `x` and `y`. def assign_to(self, obj): """Assign `x` and `y` to an object that has properties `x` and `y`.""" obj.x = self.x obj.y = self.y
Distance to some other point. def dist(self, other): """Distance to some other point.""" dx = self.x - other.x dy = self.y - other.y return math.sqrt(dx**2 + dy**2)
Distance squared to some other point. def dist_sq(self, other): """Distance squared to some other point.""" dx = self.x - other.x dy = self.y - other.y return dx**2 + dy**2
Round `x` and `y` to integers. def round(self): """Round `x` and `y` to integers.""" return Point(int(round(self.x)), int(round(self.y)))
Round `x` and `y` down to integers. def floor(self): """Round `x` and `y` down to integers.""" return Point(int(math.floor(self.x)), int(math.floor(self.y)))
Round `x` and `y` up to integers. def ceil(self): """Round `x` and `y` up to integers.""" return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))
Bound this point within the rect defined by (`p1`, `p2`). def bound(self, p1, p2=None): """Bound this point within the rect defined by (`p1`, `p2`).""" r = Rect(p1, p2) return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))
Is the point inside this rect? def contains_point(self, pt): """Is the point inside this rect?""" return (self.l < pt.x and self.r > pt.x and self.t < pt.y and self.b > pt.y)
Is the circle completely inside this rect? def contains_circle(self, pt, radius): """Is the circle completely inside this rect?""" return (self.l < pt.x - radius and self.r > pt.x + radius and self.t < pt.y - radius and self.b > pt.y + radius)
Does the circle intersect with this rect? def intersects_circle(self, pt, radius): """Does the circle intersect with this rect?""" # How this works: http://stackoverflow.com/a/402010 rect_corner = self.size / 2 # relative to the rect center circle_center = (pt - self.center).abs() # relative to the r...
Read the ExecuteInfo.txt file and return the base directory. 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 appe...
Launch the game. def start(self, version=None, 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 ...
Create a game for the agents to join. Args: map_name: The map to use. def create_game(self, map_name): """Create a game for the agents to join. Args: map_name: The map to use. """ map_inst = maps.get(map_name) map_data = map_inst.data(self._run_config) if map_name not in self....
Shutdown and free all resources. def close(self): """Shutdown and free all resources.""" for controller in self._controllers: controller.quit() self._controllers = [] for process in self._processes: process.close() self._processes = [] portspicker.return_ports(self._lan_ports) ...
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). def create_game( self, map_name, ...
Shutdown and free all resources. def close(self): """Shutdown and free all resources.""" if self._controller is not None: self._controller.quit() self._controller = None if self._process is not None: self._process.close() self._process = None
Run the agent, connecting to a (remote) host started independently. 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:"...
Run a host which expects one player to connect remotely. 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_mini...
Make sure this stays synced with bin/agent_remote.py. def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst, save_map, interface): """Make sure this stays synced with bin/agent_remote.py.""" # Connect! logging.info("Connecting...") self._controllers = [remote_...