python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
|---|---|---|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Common configuration for all predator_prey__* substrates.
There are two roles: predators and prey. The prey try to eat apples and acorns.
The predators try to eat prey.
Apples are worth 1 reward and can be eaten immediately. Acorns are worth 18
reward but they take a long time to eat. It is not possible to move while eating
so a prey player is especially vulnerable while they eat it.
Predators can also eat other predators, though they get no reward for doing so.
However, a predator might eat another predator anyway in order to remove a
competitor who might otherwise eat its prey.
When prey travel together in tight groups they can defend themselves from being
eaten by predators. When a predator tries to eat its prey then all other prey
who are not currently eating an acorn within a radius of 3 are counted. If there
are more prey than predators within the radius then the predator cannot eat the
prey.
So prey are safer in groups. However, they are also tempted to depart from their
group and strike out alone since that way they are more likely to be the one to
come first to any food they find.
Both predators and prey have limited stamina. They can only move at top speed
for a limited number of consecutive steps, after which they must slow down.
Stamina is visible to all with a colored bar above each player's head. If the
bar over a particular player's head is invisible or green then they can move at
top speed. If it is red then they have depleted their stamina and can only move
slowly until they let it recharge. Stamina is recharged by standing still for
some number of consecutive time steps, how many depends on how much stamina was
depleted. Predators have a faster top speed than prey but they tire more
quickly.
Prey but not predators can cross tall grass (green grassy locations). Prey must
still be careful on grass though since predators can still reach one cell over
the border to eat prey on the edge of safety.
Both predators and prey respawn 200 steps after being eaten.
"""
from typing import Any, Dict, Generator, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict as configdict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ("N", "E", "S", "W")
ITEMS = ("empty", "acorn")
INVISIBLE = (0, 0, 0, 0)
SPRITES = {}
PALETTES = {}
SPRITES["empty"] = """
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
"""
PALETTES["empty"] = {"x": INVISIBLE,}
SPRITES["acorn"] = """
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxBB
xxxxxxbb
xxxxxxxx
"""
PALETTES["acorn"] = {
"x": INVISIBLE,
"B": [158, 85, 25, 255],
"b": [92, 29, 19, 255],
}
PREDATOR_EAT_SPRITE = """
*x*x*x*x
*x*x*x**
x***&x**
xx*&xx**
xx*&xx*&
xx*&xx*x
xx&&xx&x
xxxxxxxx
"""
APPLE_SPRITE = """
xxxxxxxx
xxo|*xxx
x*#|**xx
x#***#xx
x#####xx
xx###xxx
xxxxxxxx
xxxxxxxx
"""
def create_inventory(player_index: int):
"""Return prefab for the inventory of the player at index `player_index`."""
lua_idx = player_index + 1
prefab = {
"name": "inventory",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wait",
"stateConfigs": (
[{"state": "wait"}] +
[{"state": item, "sprite": item, "layer": "overlay"}
for item in ITEMS]),
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ITEMS,
"spriteShapes": [SPRITES[item] for item in ITEMS],
"palettes": [PALETTES[item] for item in ITEMS],
"noRotates": [False]
}
},
{
"component": "AvatarConnector",
"kwargs": {
"playerIndex": lua_idx,
"aliveState": "empty",
"waitState": "wait"
}
},
{
"component": "Inventory",
"kwargs": {
"playerIndex": lua_idx,
}
},
]
}
return prefab
def create_base_prefab(name, layer="upperPhysical"):
"""Returns a base prefab with a given name on the given layer."""
return {
"name": f"{name}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": f"{name}",
"stateConfigs": [{
"state": f"{name}",
"layer": layer,
"sprite": f"{name}",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [name],
"spriteShapes": [SPRITES[name]],
"palettes": [PALETTES[name]],
"noRotates": [True]
}
}]
}
NW_WALL_CORNER = {
"name": "nw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_wall_corner",
"stateConfigs": [{
"state": "nw_wall_corner",
"layer": "upperPhysical",
"sprite": "NwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_NW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NE_WALL_CORNER = {
"name": "ne_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_wall_corner",
"stateConfigs": [{
"state": "ne_wall_corner",
"layer": "upperPhysical",
"sprite": "NeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_NE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SE_WALL_CORNER = {
"name": "se_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_wall_corner",
"stateConfigs": [{
"state": "se_wall_corner",
"layer": "upperPhysical",
"sprite": "SeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_SE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SW_WALL_CORNER = {
"name": "sw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_wall_corner",
"stateConfigs": [{
"state": "sw_wall_corner",
"layer": "upperPhysical",
"sprite": "SwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_SW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NW_INNER_WALL_CORNER = {
"name": "nw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_inner_wall_corner",
"stateConfigs": [{
"state": "nw_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "NwInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_NW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NE_INNER_WALL_CORNER = {
"name": "ne_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_inner_wall_corner",
"stateConfigs": [{
"state": "ne_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "NeInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_NE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SE_INNER_WALL_CORNER = {
"name": "se_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_inner_wall_corner",
"stateConfigs": [{
"state": "se_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "SeInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_SE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SW_INNER_WALL_CORNER = {
"name": "sw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_inner_wall_corner",
"stateConfigs": [{
"state": "sw_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "SwInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_SW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_NORTH = {
"name": "wall_north",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_north",
"stateConfigs": [{
"state": "wall_north",
"layer": "upperPhysical",
"sprite": "WallNorth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallNorth"],
"spriteShapes": [shapes.BRICK_WALL_NORTH],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_EAST = {
"name": "wall_east",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_east",
"stateConfigs": [{
"state": "wall_east",
"layer": "upperPhysical",
"sprite": "WallEast",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallEast"],
"spriteShapes": [shapes.BRICK_WALL_EAST],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_SOUTH = {
"name": "wall_south",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_south",
"stateConfigs": [{
"state": "wall_south",
"layer": "upperPhysical",
"sprite": "WallSouth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallSouth"],
"spriteShapes": [shapes.BRICK_WALL_SOUTH],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_WEST = {
"name": "wall_west",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_west",
"stateConfigs": [{
"state": "wall_west",
"layer": "upperPhysical",
"sprite": "WallWest",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallWest"],
"spriteShapes": [shapes.BRICK_WALL_WEST],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
FILL = {
"name": "fill",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "fill",
"stateConfigs": [{
"state": "fill",
"layer": "upperPhysical",
"sprite": "fill",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["fill"],
"spriteShapes": [shapes.FILL],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
TILED_FLOOR = {
"name": "tiled_floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tiled_floor",
"stateConfigs": [{
"state": "tiled_floor",
"layer": "background",
"sprite": "tiled_floor",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["tiled_floor"],
"spriteShapes": [shapes.TILED_FLOOR_GREY],
"palettes": [{"o": (204, 199, 192, 255),
"-": (194, 189, 182, 255),}],
"noRotates": [False]
}
},
]
}
SAFE_GRASS = {
"name":
"safe_grass",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass",
"stateConfigs": [{
"state": "safe_grass",
"layer": "midPhysical",
"sprite": "safe_grass",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass"],
"spriteShapes": [shapes.GRASS_STRAIGHT],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_N_EDGE = {
"name":
"safe_grass_n_edge",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_n_edge",
"stateConfigs": [{
"state": "safe_grass_n_edge",
"layer": "midPhysical",
"sprite": "safe_grass_n_edge",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_n_edge"],
"spriteShapes": [shapes.GRASS_STRAIGHT_N_EDGE],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_E_EDGE = {
"name":
"safe_grass_e_edge",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_e_edge",
"stateConfigs": [{
"state": "safe_grass_e_edge",
"layer": "midPhysical",
"sprite": "safe_grass_e_edge",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_e_edge"],
"spriteShapes": [shapes.GRASS_STRAIGHT_E_EDGE],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_S_EDGE = {
"name":
"safe_grass_s_edge",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_s_edge",
"stateConfigs": [{
"state": "safe_grass_s_edge",
"layer": "midPhysical",
"sprite": "safe_grass_s_edge",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_s_edge"],
"spriteShapes": [shapes.GRASS_STRAIGHT_S_EDGE],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_W_EDGE = {
"name":
"safe_grass_w_edge",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_w_edge",
"stateConfigs": [{
"state": "safe_grass_w_edge",
"layer": "midPhysical",
"sprite": "safe_grass_w_edge",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_w_edge"],
"spriteShapes": [shapes.GRASS_STRAIGHT_W_EDGE],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_NW_CORNER = {
"name":
"safe_grass_nw_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_nw_corner",
"stateConfigs": [{
"state": "safe_grass_nw_corner",
"layer": "midPhysical",
"sprite": "safe_grass_nw_corner",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_nw_corner"],
"spriteShapes": [shapes.GRASS_STRAIGHT_NW_CORNER],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_NE_CORNER = {
"name":
"safe_grass_ne_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_ne_corner",
"stateConfigs": [{
"state": "safe_grass_ne_corner",
"layer": "midPhysical",
"sprite": "safe_grass_ne_corner",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_ne_corner"],
"spriteShapes": [shapes.GRASS_STRAIGHT_NE_CORNER],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_SE_CORNER = {
"name":
"safe_grass_se_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_se_corner",
"stateConfigs": [{
"state": "safe_grass_se_corner",
"layer": "midPhysical",
"sprite": "safe_grass_se_corner",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_se_corner"],
"spriteShapes": [shapes.GRASS_STRAIGHT_SE_CORNER],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
SAFE_GRASS_SW_CORNER = {
"name":
"safe_grass_sw_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"safe_grass_sw_corner",
"stateConfigs": [{
"state": "safe_grass_sw_corner",
"layer": "midPhysical",
"sprite": "safe_grass_sw_corner",
}],
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["safe_grass_sw_corner"],
"spriteShapes": [shapes.GRASS_STRAIGHT_SW_CORNER],
"palettes": [shapes.GRASS_PALETTE],
"noRotates": [False]
}
},
]
}
def create_apple(apple_reward: float = 1.0):
"""Return a prefab object defining an apple, which can be eaten by prey."""
prefab = {
"name":
"edibleApple",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"apple",
"stateConfigs": [
{
"state": "apple",
"layer": "lowerPhysical",
"sprite": "apple",
},
{
"state": "appleWait",
"layer": "logic",
},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["apple"],
"spriteShapes": [APPLE_SPRITE],
"palettes": [{
"*": (106, 184, 83, 255),
"#": (96, 166, 75, 255),
"o": (61, 130, 62, 255),
"|": (115, 62, 57, 255),
"x": INVISIBLE,
}],
"noRotates": [True],
}
},
{
"component": "AppleEdible",
"kwargs": {
"liveState": "apple",
"waitState": "appleWait",
"rewardForEating": apple_reward,
}
},
{
"component": "FixedRateRegrow",
"kwargs": {
"name": "AppleFixedRateRegrow",
"liveState": "apple",
"waitState": "appleWait",
"regrowRate": 0.007,
}
},
]
}
return prefab
FLOOR_ACORN = {
"name":
"floorAcorn",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"floorAcorn",
"stateConfigs": [
{
"state": "floorAcorn",
"layer": "lowerPhysical",
"sprite": "floorAcorn",
},
{
"state": "acornWait",
"layer": "logic",
},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["floorAcorn"],
"spriteShapes": [shapes.ACORN],
"palettes": [{
"*": (158, 85, 25, 255),
"@": (158, 85, 25, 140),
"o": (92, 29, 19, 255),
"x": INVISIBLE,
}],
"noRotates": [True],
}
},
{
"component": "AcornPickUppable",
"kwargs": {
"liveState": "floorAcorn",
"waitState": "acornWait",
}
},
{
"component": "FixedRateRegrow",
"kwargs": {
"name": "AcornFixedRateRegrow",
"liveState": "floorAcorn",
"waitState": "acornWait",
"regrowRate": 0.01,
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{"component": "Transform"},
]
}
def create_spawn_point_prefab(team):
"""Return a team-specific spawn-point prefab."""
prefab = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs": [{
"state": "playerSpawnPoint",
"layer": "alternateLogic",
"groups": ["{}SpawnPoints".format(team)],
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "invisible",
"spriteNames": [],
"spriteRGBColors": []
}
},
]
}
return prefab
def create_prefabs(apple_reward: float = 1.0):
"""Returns the prefabs dictionary."""
prefabs = {
"spawn_point_prey": create_spawn_point_prefab("prey"),
"spawn_point_predator": create_spawn_point_prefab("predator"),
"apple": create_apple(apple_reward=apple_reward),
"floor_acorn": FLOOR_ACORN,
"nw_wall_corner": NW_WALL_CORNER,
"ne_wall_corner": NE_WALL_CORNER,
"se_wall_corner": SE_WALL_CORNER,
"sw_wall_corner": SW_WALL_CORNER,
"nw_inner_wall_corner": NW_INNER_WALL_CORNER,
"ne_inner_wall_corner": NE_INNER_WALL_CORNER,
"se_inner_wall_corner": SE_INNER_WALL_CORNER,
"sw_inner_wall_corner": SW_INNER_WALL_CORNER,
"wall_north": WALL_NORTH,
"wall_east": WALL_EAST,
"wall_south": WALL_SOUTH,
"wall_west": WALL_WEST,
"fill": FILL,
"tiled_floor": TILED_FLOOR,
"safe_grass": SAFE_GRASS,
"safe_grass_n_edge": SAFE_GRASS_N_EDGE,
"safe_grass_e_edge": SAFE_GRASS_E_EDGE,
"safe_grass_s_edge": SAFE_GRASS_S_EDGE,
"safe_grass_w_edge": SAFE_GRASS_W_EDGE,
"safe_grass_ne_corner": SAFE_GRASS_NE_CORNER,
"safe_grass_se_corner": SAFE_GRASS_SE_CORNER,
"safe_grass_sw_corner": SAFE_GRASS_SW_CORNER,
"safe_grass_nw_corner": SAFE_GRASS_NW_CORNER,
}
return prefabs
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{"component": "Transform"},
]
}
return scene
def _create_avatar_object(player_idx: int, is_predator: bool,
max_stamina: int) -> Dict[str, Any]:
"""Create an avatar object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
live_state_name = "player{}".format(lua_index)
avatar_sprite_name = "avatarSprite{}".format(lua_index)
if is_predator:
spawn_group = "predatorSpawnPoints"
color_palette = shapes.PRED1_PALETTE
sprite = shapes.PERSISTENCE_PREDATOR
if not is_predator:
spawn_group = "preySpawnPoints"
alert_state_name = live_state_name + "alert"
sit_state_name = live_state_name + "sit"
prep_to_eat_state_name = live_state_name + "prepToEat"
first_bite_state_name = live_state_name + "firstBite"
second_bite_state_name = live_state_name + "secondBite"
last_bite_state_name = live_state_name + "lastBite"
alert_sprite_name = "avatarAlertSprite{}".format(lua_index)
sit_sprite_name = "avatarSitSprite{}".format(lua_index)
prep_to_eat_sprite_name = "avatarPrepToEatSprite{}".format(lua_index)
first_bite_sprite_name = "avatarFirstBiteSprite{}".format(lua_index)
second_bite_sprite_name = "avatarSecondBiteSprite{}".format(lua_index)
last_bite_sprite_name = "avatarLastBiteSprite{}".format(lua_index)
color_palette = {**shapes.get_palette(colors.palette[player_idx]
), ** PALETTES["acorn"]}
sprite = shapes.CUTE_AVATAR
alert_sprite = shapes.CUTE_AVATAR_ALERT
sit_sprite = shapes.CUTE_AVATAR_SIT
prep_to_eat_sprite = shapes.CUTE_AVATAR_EAT
first_bite_sprite = shapes.CUTE_AVATAR_FIRST_BITE
second_bite_sprite = shapes.CUTE_AVATAR_SECOND_BITE
last_bite_sprite = shapes.CUTE_AVATAR_LAST_BITE
interact_palette = {
"P": colors.palette[player_idx] + (255,),
"&": (10, 10, 10, 50),
"*": (230, 230, 230, 255),
"x": INVISIBLE,
}
if is_predator:
role_name = "predator"
green_freeze_time = 0
yellow_freeze_time = 1
red_freeze_time = 6
else:
role_name = "prey"
green_freeze_time = 1
yellow_freeze_time = 2
red_freeze_time = 4
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": f"avatar{lua_index}",
"components": [
{
"component": "Transform",
},
{
"component": "Role",
"kwargs": {
"isPredator": is_predator,
}
},
{
"component": "Stamina",
"kwargs": {
"maxStamina": max_stamina,
"classConfig": {"name": role_name,
"greenFreezeTime": green_freeze_time,
"yellowFreezeTime": yellow_freeze_time,
"redFreezeTime": red_freeze_time},
"amountInvisible": 6,
"amountGreen": 6,
"amountYellow": 6,
"amountRed": 1,
"costlyActions": ["move", "turn", "interact"],
}
},
{
"component": "StaminaObservation",
"kwargs": {
"staminaComponent": "Stamina",
}
},
# The `RewardForStaminaLevel` component defines a pseudoreward which
# is useful for training background populations to rapidly learn how
# to control their stamina. For the default "real" substrate, the
# reward it defines should always be zero.
{
"component": "RewardForStaminaLevel",
"kwargs": {
"rewardValue": 0.0,
"bands": [],
}
},
]
}
if is_predator:
avatar_object["components"].extend([
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{
"state": live_state_name,
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
# Player wait type for times when they are zapped out.
{
"state": "playerWait",
"groups": ["playerWaits"]
},
]
}
},
{
"component": "PredatorInteractBeam",
"kwargs": {
"cooldownTime": 5,
"shapes": [PREDATOR_EAT_SPRITE, shapes.FILL],
"palettes": [interact_palette] * 2,
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [sprite],
"palettes": [color_palette],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"additionalLiveStates": [],
"waitState": "playerWait",
"spawnGroup": spawn_group,
"actionOrder": ["move",
"turn",
"interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "AvatarEdible",
},
{
"component": "AvatarRespawn",
"kwargs": {
"framesTillRespawn": 200,
}
},
])
if not is_predator:
avatar_object["components"].extend([
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{
"state": live_state_name,
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
# Player wait type for times when they are zapped out.
{
"state": "playerWait",
"groups": ["playerWaits"]
},
{
"state": alert_state_name,
"layer": "upperPhysical",
"sprite": alert_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": sit_state_name,
"layer": "upperPhysical",
"sprite": sit_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": prep_to_eat_state_name,
"layer": "upperPhysical",
"sprite": prep_to_eat_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": first_bite_state_name,
"layer": "upperPhysical",
"sprite": first_bite_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": second_bite_state_name,
"layer": "upperPhysical",
"sprite": second_bite_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": last_bite_state_name,
"layer": "upperPhysical",
"sprite": last_bite_sprite_name,
"contact": "avatar",
"groups": ["players"]
}
]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"additionalLiveStates": [alert_state_name,
sit_state_name,
prep_to_eat_state_name,
first_bite_state_name,
second_bite_state_name,
last_bite_state_name],
"waitState": "playerWait",
"spawnGroup": spawn_group,
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "InteractEatAcorn",
"kwargs": {
"cooldownTime": 5,
"shapes": [PREDATOR_EAT_SPRITE, shapes.FILL],
"palettes": [interact_palette],
"isEating": False,
"defaultState": live_state_name,
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name, alert_sprite_name,
sit_sprite_name, prep_to_eat_sprite_name,
first_bite_sprite_name, second_bite_sprite_name,
last_bite_sprite_name],
"spriteShapes": [sprite, alert_sprite, sit_sprite,
prep_to_eat_sprite, first_bite_sprite,
second_bite_sprite, last_bite_sprite],
"palettes": [color_palette] * 7,
"noRotates": [True] * 7
}
},
{
"component": "AvatarEatingAnimation",
"kwargs": {
"sit": sit_state_name,
"prepToEat": prep_to_eat_state_name,
"firstBite": first_bite_state_name,
"secondBite": second_bite_state_name,
"lastBite": last_bite_state_name,
"downState": live_state_name,
# On each of 3 eating frames, get one third of `acornReward`.
"acornReward": 18,
}
},
{
"component": "AvatarEdible",
"kwargs": {
"groupRadius": 3,
"predatorRewardForEating": 1.0,
}
},
{
"component": "AvatarRespawn",
"kwargs": {
"framesTillRespawn": 200,
}
},
{
"component": "AvatarAnimation",
"kwargs": {
"upState": alert_state_name,
"downState": live_state_name,
}
},
# The `AcornTaste` component defines pseudorewards which are useful for
# training background populations. For the default "real" substrate,
# the rewards it defines should always be zero,
{
"component": "AcornTaste",
"kwargs": {
"collectReward": 0.0,
"eatReward": 0.0,
"safeAcornConsumptionReward": 0.0,
}
},
])
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def _create_predator_obstacle(player_idx: int) -> Dict[str, Any]:
# Lua is 1-indexed.
lua_idx = player_idx + 1
return {
"name":
"predator_obstacle",
"components": [
{
"component": "StateManager",
"kwargs":
{
"initialState": "obstacleWait",
"stateConfigs": [
{
"state": "obstacleWait"
},
# Block predators from entering any tile with a
# piece on layer 'midPhysical'.
{
"state": "obstacleLive",
"layer": "midPhysical",
"groups": ["obstacles"]
}
]
}
},
{
"component": "Transform",
},
{
"component": "AvatarConnector",
"kwargs": {
"playerIndex": lua_idx,
"aliveState": "obstacleLive",
"waitState": "obstacleWait"
}
},
]
}
def _create_stamina_overlay(player_idx: int,
max_stamina_bar_states: int,
) -> Generator[Dict[str, Any], None, None]:
"""Create stamina marker overlay objects."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
stamina_bar_state_configs = [
# Invisible inactive (dead) overlay type.
{"state": "staminaBarWait"},
]
stamina_bar_sprite_names = []
stamina_bar_sprite_shapes = []
# Each player's stamina bars must be in their own layer so they do not
# interact/collide with other players' stamina bars.
stamina_bar_layer = f"superOverlay_{player_idx}"
# Declare one state per level of the stamina bar.
for i in range(max_stamina_bar_states):
sprite_name = f"sprite_for_level_{i}"
stamina_bar_state_configs.append(
{"state": f"level_{i}",
"layer": stamina_bar_layer,
"sprite": sprite_name})
stamina_bar_sprite_names.append(sprite_name)
xs = "\nxxxxxxxx"
blank_space = xs * 7
number_of_rs = max(6 - i, 0)
number_of_ys = i if i < 7 else 12 - i
number_of_gs = max(i - 6, 0)
if i >= 13:
level = blank_space + xs
else:
level = (
blank_space
+ "\nx"
+ "G" * number_of_gs
+ "Y" * number_of_ys
+ "R" * number_of_rs
+ "x"
)
empty = "\n".join(["x" * 8] * 8)
# Replace the east/south/west sprites with invisible sprites so the only
# stamina bar rendered is the one in the direction that the current player
# is facing.
stamina_bar_sprite_shapes.append((level, empty, empty, empty))
# Create a stamina bar for each compass direction. Only the direction the
# current player is facing is visible.
for direction in ("N", "E", "S", "W"):
yield {
"name": "avatar_stamina_bar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "staminaBarWait",
"stateConfigs": stamina_bar_state_configs
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": stamina_bar_sprite_names,
"spriteShapes": stamina_bar_sprite_shapes,
"palettes": [{"G": (62, 137, 72, 255),
"Y": (255, 216, 97, 255),
"R": (162, 38, 51, 255),
"x": INVISIBLE,}] * max_stamina_bar_states,
"noRotates": [True] * max_stamina_bar_states
}
},
{
"component": "StaminaBar",
"kwargs": {
"playerIndex": lua_idx,
"waitState": "staminaBarWait",
"layer": stamina_bar_layer,
"direction": direction
}
},
]
}
def _build_prey_objects(player_idx: int,
max_stamina_bar_states: int = 19):
"""Build a prey avatar and its associated stamina objects."""
avatar_object = _create_avatar_object(
player_idx, is_predator=False, max_stamina=max_stamina_bar_states - 1)
stamina_bar_objects = _create_stamina_overlay(player_idx,
max_stamina_bar_states)
inventory_object = create_inventory(player_index=player_idx)
game_objects = []
game_objects.append(avatar_object)
game_objects.extend(stamina_bar_objects)
game_objects.append(inventory_object)
return game_objects
def _build_predator_objects(player_idx: int,
max_stamina_bar_states: int = 19):
"""Build a predator avatar and its associated stamina objects and obstacle."""
avatar_object = _create_avatar_object(
player_idx, is_predator=True, max_stamina=max_stamina_bar_states - 1)
stamina_bar_objects = _create_stamina_overlay(player_idx,
max_stamina_bar_states)
predator_obstacle = _create_predator_obstacle(player_idx)
game_objects = []
game_objects.append(avatar_object)
game_objects.extend(stamina_bar_objects)
game_objects.append(predator_obstacle)
return game_objects
def get_config():
"""Default configuration."""
config = configdict.ConfigDict()
# Declare parameters here that we may want to override externally.
# `apple_reward` should be 1.0 for the canonical version of this environment,
# but to train background bots it is sometimes useful to use other values in
# order to control the relative attractiveness of apples and acorns.
config.apple_reward = 1.0
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"STAMINA",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
# The roles assigned to each player.
config.valid_roles = frozenset({"predator", "prey"})
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build predator_and_prey substrate given player roles."""
# Build avatars.
num_players = len(roles)
avatar_objects_and_helpers = []
for player_idx, role in enumerate(roles):
if role == "prey":
avatar_objects_and_helpers.extend(_build_prey_objects(player_idx))
elif role == "predator":
avatar_objects_and_helpers.extend(_build_predator_objects(player_idx))
else:
raise ValueError(f"Unrecognized role: {role}")
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="predator_prey",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation=dict(
map=config.layout.ascii_map,
gameObjects=avatar_objects_and_helpers,
scene=create_scene(),
prefabs=create_prefabs(apple_reward=config.apple_reward),
charPrefabMap=config.layout.char_prefab_map,
),
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/predator_prey.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Allelopathic Harvest.
This substrate contains three different varieties of berry (red, green, & blue)
and a fixed number of berry patches, which could be replanted to grow any color
variety of berry. The growth rate of each berry variety depends linearly on the
fraction that that color comprises of the total. Players have three planting
actions with which they can replant berries in their chosen color. All players
prefer to eat red berries (reward of 2 per red berry they eat versus a reward
of 1 per other colored berry). Players can achieve higher return by selecting
just one single color of berry to plant, but which one to pick is, in principle,
difficult to coordinate (start-up problem) -- though in this case all prefer
red berries, suggesting a globally rational chioce. They also always prefer to
eat berries over spending time planting (free-rider problem).
Allelopathic Harvest was first described in Koster et al. (2020).
Köster, R., McKee, K.R., Everett, R., Weidinger, L., Isaac, W.S., Hughes, E.,
Duenez-Guzman, E.A., Graepel, T., Botvinick, M. and Leibo, J.Z., 2020.
Model-free conventions in multi-agent reinforcement learning with heterogeneous
preferences. arXiv preprint arXiv:2010.09054.
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# How many different colors of berries.
NUM_BERRY_TYPES = 3
DEFAULT_ASCII_MAP = """
333PPPP12PPP322P32PPP1P13P3P3
1PPPP2PP122PPP3P232121P2PP2P1
P1P3P11PPP13PPP31PPPP23PPPPPP
PPPPP2P2P1P2P3P33P23PP2P2PPPP
P1PPPPPPP2PPP12311PP3321PPPPP
133P2PP2PPP3PPP1PPP2213P112P1
3PPPPPPPPPPPPP31PPPPPP1P3112P
PP2P21P21P33PPPPPPP3PP2PPPP1P
PPPPP1P1P32P3PPP22PP1P2PPPP2P
PPP3PP3122211PPP2113P3PPP1332
PP12132PP1PP1P321PP1PPPPPP1P3
PPP222P12PPPP1PPPP1PPP321P11P
PPP2PPPP3P2P1PPP1P23322PP1P13
23PPP2PPPP2P3PPPP3PP3PPP3PPP2
2PPPP3P3P3PP3PP3P1P3PP11P21P1
21PPP2PP331PP3PPP2PPPPP2PP3PP
P32P2PP2P1PPPPPPP12P2PPP1PPPP
P3PP3P2P21P3PP2PP11PP1323P312
2P1PPPPP1PPP1P2PPP3P32P2P331P
PPPPP1312P3P2PPPP3P32PPPP2P11
P3PPPP221PPP2PPPPPPPP1PPP311P
32P3PPPPPPPPPP31PPPP3PPP13PPP
PPP3PPPPP3PPPPPP232P13PPPPP1P
P1PP1PPP2PP3PPPPP33321PP2P3PP
P13PPPP1P333PPPP2PP213PP2P3PP
1PPPPP3PP2P1PP21P3PPPP231P2PP
1331P2P12P2PPPP2PPP3P23P21PPP
P3P131P3PPP13P1PPP222PPPP11PP
2P3PPPPPPPP2P323PPP2PPP1PPP2P
21PPPPPPP12P23P1PPPPPP13P3P11
"""
SPRITE_SIZE = 8
# Map a character to the prefab it represents in the ASCII map.
CHAR_PREFAB_MAP = {
"P": {"type": "all", "list": ["floor", "spawn_point"]},
"W": "wall",
"1": {"type": "all", "list": ["soil", "berry_1"]},
"2": {"type": "all", "list": ["soil", "berry_2"]},
"3": {"type": "all", "list": ["soil", "berry_3"]},
}
# These need to be orthogonal, same intensity and variance.
COLORS = [
(200, 10, 10, 255), # 'Red'
(10, 200, 10, 255), # 'Green'
(10, 10, 200, 255), # 'Blue'
]
ROLE_TO_MOST_TASTY_BERRY_IDX = {
"player_who_likes_red": 0,
"player_who_likes_green": 1,
"player_who_likes_blue": 2,
}
MARKING_SPRITE = """
oxxxxxxo
xoxxxxox
xxoxxoxx
xxxooxxx
xxxooxxx
xxoxxoxx
xoxxxxox
oxxxxxxo
"""
def get_marking_palette(alpha: float) -> Dict[str, Sequence[int]]:
alpha_uint8 = int(alpha * 255)
assert alpha_uint8 >= 0.0 and alpha_uint8 <= 255, "Color value out of range."
return {"x": shapes.ALPHA, "o": (0, 0, 0, alpha_uint8)}
_NUM_DIRECTIONS = 4 # NESW
FLOOR = {
"name": "floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "floor",
"stateConfigs": [{
"state": "floor",
"layer": "background",
"sprite": "Floor",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Floor",],
"spriteShapes": [shapes.DIRT_PATTERN],
"palettes": [{
"x": (55, 55, 55, 255),
"X": (60, 60, 60, 255),
}],
"noRotates": [True]
}
},
{
"component": "Transform",
},
]
}
SOIL = {
"name": "soil",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "soil",
"stateConfigs": [{
"state": "soil",
"layer": "background",
"sprite": "Soil",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Soil",],
"spriteShapes": [shapes.SOIL],
"palettes": [{
"D": (40, 40, 40, 255),
"d": (50, 50, 50, 255),
"X": (60, 60, 60, 255),
"x": (70, 70, 70, 255)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"spriteNames": ["Wall"],
# This color is a dark shade of grey.
"spriteRGBColors": [(40, 40, 40)]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "zapHit"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "fire_1"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "fire_2"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "fire_3"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
def create_berry_prefab(lua_index: int):
"""Return a berry prefab for the given color index (initial color)."""
berry = {
"name": "berry",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "unripe_{}".format(lua_index),
"stateConfigs": [
# Unripe states.
{
"state": "unripe_1",
"layer": "lowerPhysical",
"sprite": "UnripeBerry_1",
"groups": ["unripes"]
},
{
"state": "unripe_2",
"layer": "lowerPhysical",
"sprite": "UnripeBerry_2",
"groups": ["unripes"]
},
{
"state": "unripe_3",
"layer": "lowerPhysical",
"sprite": "UnripeBerry_3",
"groups": ["unripes"]
},
# Ripe states.
{
"state": "ripe_1",
"layer": "lowerPhysical",
"sprite": "RipeBerry_1",
"groups": []
},
{
"state": "ripe_2",
"layer": "lowerPhysical",
"sprite": "RipeBerry_2",
"groups": []
},
{
"state": "ripe_3",
"layer": "lowerPhysical",
"sprite": "RipeBerry_3",
"groups": []
},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [
"UnripeBerry_1",
"UnripeBerry_2",
"UnripeBerry_3",
"RipeBerry_1",
"RipeBerry_2",
"RipeBerry_3",
],
"spriteShapes": [
shapes.BERRY_SEEDS,
shapes.BERRY_SEEDS,
shapes.BERRY_SEEDS,
shapes.BERRY_RIPE,
shapes.BERRY_RIPE,
shapes.BERRY_RIPE,
],
"palettes": [
# Unripe colors
{
"o": COLORS[0],
"O": shapes.scale_color(COLORS[0], 1.5),
"x": (0, 0, 0, 0)
},
{
"o": COLORS[1],
"O": shapes.scale_color(COLORS[1], 1.5),
"x": (0, 0, 0, 0)
},
{
"o": COLORS[2],
"O": shapes.scale_color(COLORS[2], 1.5),
"x": (0, 0, 0, 0)
},
# Ripe colors
{
"d": COLORS[0],
"O": shapes.scale_color(COLORS[0], 1.5),
"o": shapes.scale_color(COLORS[0], 1.25),
"x": (0, 0, 0, 0)
},
{
"d": COLORS[1],
"O": shapes.scale_color(COLORS[1], 1.5),
"o": shapes.scale_color(COLORS[1], 1.25),
"x": (0, 0, 0, 0)
},
{
"d": COLORS[2],
"O": shapes.scale_color(COLORS[2], 1.5),
"o": shapes.scale_color(COLORS[2], 1.25),
"x": (0, 0, 0, 0)
},
],
# Note: the berries do not rotate in this version (unlike in
# the original allelopathic_harvest version, where they do).
"noRotates": [True] * (NUM_BERRY_TYPES * 2)
}
},
{
"component": "Berry",
"kwargs": {
"unripePrefix": "unripe",
"ripePrefix": "ripe",
"colorId": lua_index,
}
},
{
"component": "Edible",
"kwargs": {
"name": "Edible",
"eatingSetsColorToNewborn": True,
}
},
{
"component": "Regrowth",
"kwargs": {
"minimumTimeToRipen": 10,
"baseRate": 5e-6,
"linearGrowth": True,
}
},
{
"component": "Coloring",
"kwargs": {
"numColors": NUM_BERRY_TYPES,
}
},
]
}
return berry
def create_avatar_object(player_idx: int,
most_tasty_berry_idx: int) -> Dict[str, Any]:
"""Return the avatar for the player numbered `player_idx`."""
# Lua is 1-indexed.
lua_index = player_idx + 1
lua_most_tasty_berry_idx = most_tasty_berry_idx + 1
live_state_name = "player{}".format(lua_index)
avatar_sprite_name = "avatarSprite{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
# Player wait type for when they have been zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR],
# This color is white. It should never appear in gameplay. So
# if a white colored avatar does appear then something is
# broken.
"palettes": [shapes.get_palette((255, 255, 255))],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move",
"turn",
"fireZap",
"fire_1",
"fire_2",
"fire_3"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": _NUM_DIRECTIONS},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 1},
"fire_1": {"default": 0, "min": 0, "max": 1},
"fire_2": {"default": 0, "min": 0, "max": 1},
"fire_3": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "Zapper",
"kwargs": {
"cooldownTime": 4,
"beamLength": 3,
"beamRadius": 1,
"beamColor": (253, 253, 253), # the zapper beam is white.
"framesTillRespawn": 25,
"penaltyForBeingZapped": 0, # leave this always at 0.
"rewardForZapping": 0, # leave this always at 0.
# GraduatedSanctionsMarking handles removal instead of Zapper.
"removeHitPlayer": False,
}
},
{
"component": "ReadyToShootObservation",
},
{
"component": "Taste",
"kwargs": {
"mostTastyBerryId": lua_most_tasty_berry_idx,
"rewardMostTasty": 2,
}
},
{
"component": "ColorZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 0,
"numColorZappers": NUM_BERRY_TYPES,
"beamColors": COLORS,
# When `eatingSetsColorToNewborn` and `stochasticallyCryptic`
# are both true than stochastically change back to the
# newborn color after eating a berry with probability
# inversely related to the monoculture fraction. So larger
# monoculture fractions yield lower probabilities of changing
# back to the newborn color.
"stochasticallyCryptic": True,
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
avatar_object["components"].append({
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
"name": "COLOR_ID",
"type": "Doubles",
"shape": [],
"component": "ColorZapper",
"variable": "colorId",
},
{
"name": "MOST_TASTY_BERRY_ID",
"type": "Doubles",
"shape": [],
"component": "Taste",
"variable": "mostTastyBerryId",
},
]
},
})
avatar_object["components"].append({
"component": "AvatarIdsInViewObservation",
})
avatar_object["components"].append({
"component": "AvatarIdsInRangeToZapObservation",
})
return avatar_object
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"floor": FLOOR,
"soil": SOIL,
"wall": WALL,
"spawn_point": SPAWN_POINT,
"berry_1": create_berry_prefab(1),
"berry_2": create_berry_prefab(2),
"berry_3": create_berry_prefab(3),
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 60
PLAYER_COLOR_PALETTES = []
for i in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 0}
FIRE_ZAP = {"move": 0, "turn": 0, "fireZap": 1, "fire_1": 0, "fire_2": 0, "fire_3": 0}
FIRE_ONE = {"move": 0, "turn": 0, "fireZap": 0, "fire_1": 1, "fire_2": 0, "fire_3": 0}
FIRE_TWO = {"move": 0, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 1, "fire_3": 0}
FIRE_THREE = {"move": 0, "turn": 0, "fireZap": 0, "fire_1": 0, "fire_2": 0, "fire_3": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP,
FIRE_ONE,
FIRE_TWO,
FIRE_THREE,
)
# The Scene objece is a non-physical object, it components implement global
# logic. In this case, that includes holding the global berry counters to
# implement the regrowth rate, as well as some of the observations.
def create_scene(num_players: int):
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "GlobalBerryTracker",
"kwargs": {
"numBerryTypes": NUM_BERRY_TYPES,
"numPlayers": num_players,
}
},
{
"component": "GlobalZapTracker",
"kwargs": {
"numBerryTypes": NUM_BERRY_TYPES,
"numPlayers": num_players,
}
},
{
"component": "GlobalMetricHolder",
"kwargs": {
"metrics": [
{"type": "tensor.Int32Tensor",
"shape": (num_players, num_players),
"variable": "playerZapMatrix"},
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
scene["components"].append({
"component": "GlobalMetricReporter",
"kwargs": {
"metrics": [
{
"name": "RIPE_BERRIES_BY_TYPE",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES,),
"component": "GlobalBerryTracker",
"variable": "ripeBerriesPerType",
},
{
"name": "UNRIPE_BERRIES_BY_TYPE",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES,),
"component": "GlobalBerryTracker",
"variable": "unripeBerriesPerType",
},
{
"name": "BERRIES_BY_TYPE",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES,),
"component": "GlobalBerryTracker",
"variable": "berriesPerType",
},
{
"name": "COLORING_BY_PLAYER",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, num_players),
"component": "GlobalBerryTracker",
"variable": "coloringByPlayerMatrix",
},
{
"name": "EATING_TYPES_BY_PLAYER",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, num_players),
"component": "GlobalBerryTracker",
"variable": "eatingTypesByPlayerMatrix",
},
{
"name": "BERRIES_PER_TYPE_BY_COLOR_OF_COLORER",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, NUM_BERRY_TYPES + 1),
"component": "GlobalBerryTracker",
"variable": "berryTypesByColorOfColorer",
},
{
"name": "BERRIES_PER_TYPE_BY_TASTE_OF_COLORER",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, NUM_BERRY_TYPES),
"component": "GlobalBerryTracker",
"variable": "berryTypesByTasteOfColorer",
},
{
"name": "PLAYER_TIMEOUT_COUNT",
"type": "tensor.Int32Tensor",
"shape": (num_players, num_players),
"component": "GlobalZapTracker",
"variable": "fullZapCountMatrix",
},
{
"name": "COLOR_BY_COLOR_ZAP_COUNTS",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES + 1, NUM_BERRY_TYPES + 1),
"component": "GlobalZapTracker",
"variable": "colorByColorZapCounts",
},
{
"name": "COLOR_BY_TASTE_ZAP_COUNTS",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES + 1, NUM_BERRY_TYPES),
"component": "GlobalZapTracker",
"variable": "colorByTasteZapCounts",
},
{
"name": "TASTE_BY_TASTE_ZAP_COUNTS",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, NUM_BERRY_TYPES),
"component": "GlobalZapTracker",
"variable": "tasteByTasteZapCounts",
},
{
"name": "TASTE_BY_COLOR_ZAP_COUNTS",
"type": "tensor.Int32Tensor",
"shape": (NUM_BERRY_TYPES, NUM_BERRY_TYPES + 1),
"component": "GlobalZapTracker",
"variable": "tasteByColorZapCounts",
},
{
"name": "WHO_ZAPPED_WHO",
"type": "tensor.Int32Tensor",
"shape": (num_players, num_players),
"component": "GlobalMetricHolder",
"variable": "playerZapMatrix",
},
]
}
})
return scene
def create_marking_overlay(player_idx: int) -> Dict[str, Any]:
"""Create a graduated sanctions marking overlay object."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
marking_object = {
"name": "avatar_marking",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "avatarMarkingWait",
"stateConfigs": [
# Declare one state per level of the hit logic.
{"state": "level_1",
"layer": "superOverlay",
"sprite": "sprite_for_level_1"},
{"state": "level_2",
"layer": "superOverlay",
"sprite": "sprite_for_level_2"},
{"state": "level_3",
"layer": "superOverlay",
"sprite": "sprite_for_level_3"},
# Invisible inactive (zapped out) overlay type.
{"state": "avatarMarkingWait",
"groups": ["avatarMarkingWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["sprite_for_level_1",
"sprite_for_level_2",
"sprite_for_level_3"],
"spriteShapes": [MARKING_SPRITE,
MARKING_SPRITE,
MARKING_SPRITE],
"palettes": [get_marking_palette(0.0),
get_marking_palette(0.5),
get_marking_palette(1.0)],
"noRotates": [True] * 3
}
},
{
"component": "GraduatedSanctionsMarking",
"kwargs": {
"playerIndex": lua_idx,
"waitState": "avatarMarkingWait",
"hitName": "zapHit",
"recoveryTime": 50,
"hitLogic": [
{"levelIncrement": 1,
"sourceReward": 0,
"targetReward": 0,
"freeze": 25},
{"levelIncrement": -1,
"sourceReward": 0,
"targetReward": -10,
"remove": True}
],
}
},
]
}
return marking_object
def create_colored_avatar_overlay(player_idx: int) -> Dict[str, Any]:
"""Create a colored avatar overlay object."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
overlay_object = {
"name": "avatar_overlay",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "avatarOverlayWait",
"stateConfigs": [
# Invisible active overlay type.
{
"state": "avatarOverlay",
"layer": "overlay",
"sprite": "NewbornAvatar",
"groups": ["avatarOverlays"]
},
# Invisible inactive (zapped out) overlay type.
{
"state": "avatarOverlayWait",
"groups": ["avatarOverlayWaits"]
},
# Colored overlay piece types for use after the player has
# colored a berry with a coloring beam.
{
"state": "coloredPlayer_1",
"layer": "overlay",
"sprite": "ColoredAvatar_1",
"groups": ["avatarOverlays"]
},
{
"state": "coloredPlayer_2",
"layer": "overlay",
"sprite": "ColoredAvatar_2",
"groups": ["avatarOverlays"]
},
{
"state": "coloredPlayer_3",
"layer": "overlay",
"sprite": "ColoredAvatar_3",
"groups": ["avatarOverlays"]
},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NewbornAvatar"] + [
"ColoredAvatar_{}".format(i)
for i in range(1, NUM_BERRY_TYPES + 1)
],
"spriteShapes": [shapes.CUTE_AVATAR] *
(NUM_BERRY_TYPES + 1),
"palettes":
[shapes.get_palette((125, 125, 125))] +
[shapes.get_palette(beam_color) for beam_color in COLORS],
"noRotates": [True] * (NUM_BERRY_TYPES + 1)
}
},
{
"component": "AvatarConnector",
"kwargs": {
"playerIndex": lua_idx,
"aliveState": "avatarOverlay",
"waitState": "avatarOverlayWait"
}
},
]
}
return overlay_object
def create_avatar_and_associated_objects(
roles: Sequence[str]):
"""Returns list of avatar objects and associated other objects."""
avatar_objects = []
additional_objects = []
for player_idx, role in enumerate(roles):
if role == "default":
most_tasty_berry_idx = player_idx % 2
else:
most_tasty_berry_idx = ROLE_TO_MOST_TASTY_BERRY_IDX[role]
avatar_object = create_avatar_object(
player_idx=player_idx, most_tasty_berry_idx=most_tasty_berry_idx)
avatar_objects.append(avatar_object)
overlay_object = create_colored_avatar_overlay(player_idx)
marking_object = create_marking_overlay(player_idx)
additional_objects.append(overlay_object)
additional_objects.append(marking_object)
return avatar_objects + additional_objects
def get_config():
"""Default configuration for the allelopathic harvest level."""
config = config_dict.ConfigDict()
config.episode_timesteps = 2000
config.ascii_map = DEFAULT_ASCII_MAP
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.world_rgb(DEFAULT_ASCII_MAP, SPRITE_SIZE),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default",
"player_who_likes_red",
"player_who_likes_green",
"player_who_likes_blue",})
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build the allelopathic_harvest substrate given roles."""
num_players = len(roles)
game_objects = create_avatar_and_associated_objects(roles=roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="allelopathic_harvest",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=config.episode_timesteps,
spriteSize=SPRITE_SIZE,
topology="TORUS", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": config.ascii_map,
"gameObjects": game_objects,
"scene": create_scene(num_players),
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
"playerPalettes": [PLAYER_COLOR_PALETTES[0]] * num_players,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/allelopathic_harvest.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Common configuration for all territory_* substrates.
See _Territory: Open_ for the general description of the mechanics at play in
this substrate.
"""
from typing import Any, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ["N", "E", "S", "W"]
MARKING_SPRITE = """
oxxxxxxo
xoxxxxox
xxoxxoxx
xxxooxxx
xxxooxxx
xxoxxoxx
xoxxxxox
oxxxxxxo
"""
def get_marking_palette(alpha: float) -> Mapping[str, Sequence[int]]:
alpha_uint8 = int(alpha * 255)
assert alpha_uint8 >= 0.0 and alpha_uint8 <= 255, "Color value out of range."
return {"x": shapes.ALPHA, "o": (0, 0, 0, alpha_uint8)}
FLOOR = {
"name": "floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "floor",
"stateConfigs": [{
"state": "floor",
"layer": "background",
"sprite": "Floor",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Floor",],
"spriteShapes": [shapes.GRAINY_FLOOR],
"palettes": [{
"*": (27, 22, 20, 255),
"+": (23, 17, 15, 255),
}],
"noRotates": [True]
}
},
{
"component": "Transform",
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.FILL],
"palettes": [{"i": (61, 57, 55, 255)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
{
"component": "AllBeamBlocker",
"kwargs": {}
},
]
}
WALL_HIGHLIGHT_NW = {
"name": "nw_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_highlight",
"stateConfigs": [{
"state": "nw_highlight",
"layer": "overlay",
"sprite": "NWHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NWHighlight",],
"spriteShapes": [shapes.NW_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL_HIGHLIGHT_E_W = {
"name": "e_w_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "e_w_highlight",
"stateConfigs": [{
"state": "e_w_highlight",
"layer": "overlay",
"sprite": "EWHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["EWHighlight",],
"spriteShapes": [shapes.E_W_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL_HIGHLIGHT_N_S = {
"name": "n_s_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "n_s_highlight",
"stateConfigs": [{
"state": "n_s_highlight",
"layer": "overlay",
"sprite": "NSHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NSHighlight",],
"spriteShapes": [shapes.N_S_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL_HIGHLIGHT_NE = {
"name": "ne_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_highlight",
"stateConfigs": [{
"state": "ne_highlight",
"layer": "overlay",
"sprite": "NEHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NEHighlight",],
"spriteShapes": [shapes.NE_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL_HIGHLIGHT_SE = {
"name": "se_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_highlight",
"stateConfigs": [{
"state": "se_highlight",
"layer": "overlay",
"sprite": "SEHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SEHighlight",],
"spriteShapes": [shapes.SE_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL_HIGHLIGHT_SW = {
"name": "sw_highlight",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_highlight",
"stateConfigs": [{
"state": "sw_highlight",
"layer": "overlay",
"sprite": "SWHighlight",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SWHighlight",],
"spriteShapes": [shapes.SW_HIGHLIGHT],
"palettes": [shapes.HIGHLIGHT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
SPAWN_POINT = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs": [{
"state": "playerSpawnPoint",
"layer": "logic",
"groups": ["spawnPoints"],
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "invisible",
"spriteNames": [],
"spriteRGBColors": []
}
},
{
"component": "Transform",
},
]
}
def get_dry_painted_wall_palette(base_color: shapes.Color
) -> Mapping[str, shapes.ColorRGBA]:
return {
"*": shapes.scale_color(base_color, 0.75, 200),
"#": shapes.scale_color(base_color, 0.90, 150),
}
def get_brush_palette(
base_color: shapes.Color) -> Mapping[str, shapes.ColorRGBA]:
return {
"*": base_color + (255,),
"&": shapes.scale_color(base_color, 0.75, 255),
"o": shapes.scale_color(base_color, 0.55, 255),
"O": (70, 70, 70, 255),
"-": (143, 96, 74, 255),
"+": (117, 79, 61, 255),
"k": (199, 176, 135, 255),
"x": shapes.ALPHA,
}
PLAYER_COLOR_PALETTES = []
BRUSH_PALETTES = []
for human_readable_color in colors.human_readable:
PLAYER_COLOR_PALETTES.append(shapes.get_palette(human_readable_color))
BRUSH_PALETTES.append(get_brush_palette(human_readable_color))
def create_resource(num_players: int) -> PrefabConfig:
"""Configure the prefab to use for all resource objects."""
# Setup unique states corresponding to each player who can claim the resource.
claim_state_configs = []
claim_sprite_names = []
claim_sprite_rgb_colors = []
for player_idx in range(num_players):
lua_player_idx = player_idx + 1
player_color = colors.human_readable[player_idx]
wet_sprite_name = "Color" + str(lua_player_idx) + "ResourceSprite"
claim_state_configs.append({
"state": "claimed_by_" + str(lua_player_idx),
"layer": "upperPhysical",
"sprite": wet_sprite_name,
"groups": ["claimedResources"]
})
claim_sprite_names.append(wet_sprite_name)
# Use alpha channel to make transparent version of claiming agent's color.
wet_paint_color = player_color + (75,)
claim_sprite_rgb_colors.append(wet_paint_color)
prefab = {
"name": "resource",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "unclaimed",
"stateConfigs": [
{"state": "unclaimed",
"layer": "upperPhysical",
"sprite": "UnclaimedResourceSprite"},
{"state": "destroyed"},
] + claim_state_configs,
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": claim_sprite_names,
"spriteRGBColors": claim_sprite_rgb_colors
}
},
{
"component": "Transform",
},
{
"component": "Resource",
"kwargs": {
"initialHealth": 2,
"destroyedState": "destroyed",
"reward": 1.0,
"rewardRate": 0.01,
"rewardDelay": 25,
"delayTillSelfRepair": 15,
"selfRepairProbability": 0.1,
}
},
]
}
return prefab
def create_resource_texture() -> PrefabConfig:
"""Configure the background texture for a resource. It looks like a wall."""
prefab = {
"name": "resource_texture",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "unclaimed",
"stateConfigs": [
{"state": "unclaimed",
"layer": "lowerPhysical",
"sprite": "UnclaimedResourceSprite"},
{"state": "destroyed"},
],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["UnclaimedResourceSprite",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (61, 61, 61, 255),
"#": (80, 80, 80, 255)}],
"noRotates": [True]
}
},
{
"component": "Transform",
},
]
}
return prefab
def create_reward_indicator(num_players) -> PrefabConfig:
"""Configure object indicating if a resource is currently providing reward."""
# Setup unique states corresponding to each player who can claim the resource.
claim_state_configs = []
claim_sprite_names = []
claim_sprite_shapes = []
claim_palettes = []
claim_no_rotates = []
for player_idx in range(num_players):
lua_player_idx = player_idx + 1
player_color = colors.human_readable[player_idx]
dry_sprite_name = "Color" + str(lua_player_idx) + "DryPaintSprite"
claim_state_configs.append({
"state": "dry_claimed_by_" + str(lua_player_idx),
"layer": "overlay",
"sprite": dry_sprite_name,
})
claim_sprite_names.append(dry_sprite_name)
claim_sprite_shapes.append(shapes.WALL)
claim_palettes.append(get_dry_painted_wall_palette(player_color))
claim_no_rotates.append(True)
prefab = {
"name": "reward_indicator",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inactive",
"stateConfigs": [
{"state": "inactive"},
] + claim_state_configs,
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": claim_sprite_names,
"spriteShapes": claim_sprite_shapes,
"palettes": claim_palettes,
"noRotates": claim_no_rotates
}
},
{
"component": "Transform",
},
{
"component": "RewardIndicator",
},
]
}
return prefab
def create_damage_indicator() -> PrefabConfig:
"""Configure the object indicating whether or not a resource is damaged."""
damaged_resource_sprite = """
,,bb,,,,
,,bb,bb,
,,,b,,b,
,,,b,,,,
,,,b,,,b
,,,bb,,b
,,,bb,,b
b,,,b,,,
"""
damaged_resource_palette = {",": shapes.ALPHA, "b": shapes.BLACK}
prefab = {
"name": "damage_indicator",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inactive",
"stateConfigs": [
{"state": "inactive",
"layer": "superDirectionIndicatorLayer"},
{"state": "damaged",
"layer": "superDirectionIndicatorLayer",
"sprite": "DamagedResource"},
],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["DamagedResource"],
"spriteShapes": [damaged_resource_sprite],
"palettes": [damaged_resource_palette],
"noRotates": [True]
}
},
{
"component": "Transform",
},
]
}
return prefab
def create_prefabs(num_players: int):
"""Returns the prefabs dictionary."""
prefabs = {
"spawn_point": SPAWN_POINT,
"floor": FLOOR,
"wall": WALL,
"wall_highlight_nw": WALL_HIGHLIGHT_NW,
"wall_highlight_e_w": WALL_HIGHLIGHT_E_W,
"wall_highlight_n_s": WALL_HIGHLIGHT_N_S,
"wall_highlight_ne": WALL_HIGHLIGHT_NE,
"wall_highlight_se": WALL_HIGHLIGHT_SE,
"wall_highlight_sw": WALL_HIGHLIGHT_SW,
"resource": create_resource(num_players=num_players),
"resource_texture": create_resource_texture(),
"reward_indicator": create_reward_indicator(num_players),
"damage_indicator": create_damage_indicator(),
}
return prefabs
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0, "fireClaim": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0, "fireClaim": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0, "fireClaim": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0, "fireClaim": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0, "fireClaim": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0, "fireClaim": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0, "fireClaim": 0}
FIRE_ZAP = {"move": 0, "turn": 0, "fireZap": 1, "fireClaim": 0}
FIRE_CLAIM = {"move": 0, "turn": 0, "fireZap": 0, "fireClaim": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP,
FIRE_CLAIM
)
# The Scene object is a non-physical object, its components implement global
# logic.
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
}
]
}
return scene
def create_avatar_object(player_idx: int) -> Mapping[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
color_palette = PLAYER_COLOR_PALETTES[player_idx]
paintbrush_palette = BRUSH_PALETTES[player_idx]
live_state_name = "player{}".format(lua_index)
avatar_sprite_name = "avatarSprite{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
# Player wait state used when they have been zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR_HOLDING_PAINTBRUSH],
"palettes": [{**color_palette, **paintbrush_palette}],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": ["move",
"turn",
"fireZap",
"fireClaim"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 1},
"fireClaim": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "Paintbrush",
"kwargs": {
"shape": shapes.PAINTBRUSH,
"palette": paintbrush_palette,
"playerIndex": lua_index,
}
},
{
"component": "Zapper",
"kwargs": {
"cooldownTime": 4,
"beamLength": 2,
"beamRadius": 1,
"framesTillRespawn": 1e6, # Effectively never respawn.
"penaltyForBeingZapped": 0,
"rewardForZapping": 0,
# GraduatedSanctionsMarking handles removal instead of Zapper.
"removeHitPlayer": False,
}
},
{
"component": "ReadyToShootObservation",
},
{
"component": "ResourceClaimer",
"kwargs": {
"color": color_palette["*"],
"playerIndex": lua_index,
"beamLength": 2,
"beamRadius": 0,
"beamWait": 0,
}
},
{
"component": "Taste",
"kwargs": {
"role": "none",
"rewardAmount": 1.0,
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_marking_overlay(player_idx: int) -> Mapping[str, Any]:
"""Create a graduated sanctions marking overlay object."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
marking_object = {
"name": "avatar_marking",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "avatarMarkingWait",
"stateConfigs": [
# Declare one state per level of the hit logic.
{"state": "level_1",
"layer": "superOverlay",
"sprite": "sprite_for_level_1"},
{"state": "level_2",
"layer": "superOverlay",
"sprite": "sprite_for_level_2"},
# Invisible inactive (zapped out) overlay type.
{"state": "avatarMarkingWait",
"groups": ["avatarMarkingWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["sprite_for_level_1",
"sprite_for_level_2"],
"spriteShapes": [MARKING_SPRITE,
MARKING_SPRITE],
"palettes": [get_marking_palette(0.0),
get_marking_palette(1.0)],
"noRotates": [True] * 3
}
},
{
"component": "GraduatedSanctionsMarking",
"kwargs": {
"playerIndex": lua_idx,
"waitState": "avatarMarkingWait",
"hitName": "zapHit",
"recoveryTime": 50,
"hitLogic": [
{"levelIncrement": 1,
"sourceReward": 0,
"targetReward": 0,
"freeze": 25},
{"levelIncrement": -1,
"sourceReward": 0,
"targetReward": 0,
"remove": True}
],
}
},
]
}
return marking_object
def create_avatar_and_associated_objects(num_players):
"""Returns list of avatars and their associated marking objects."""
avatar_objects = []
additional_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(player_idx)
avatar_objects.append(game_object)
marking_object = create_marking_overlay(player_idx)
additional_objects.append(marking_object)
return avatar_objects + additional_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(120, 184),
})
config.valid_roles = frozenset({"default"})
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given player roles."""
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="territory",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology=config.layout.topology, # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": config.layout.ascii_map,
"gameObjects": create_avatar_and_associated_objects(num_players),
"scene": create_scene(),
"prefabs": create_prefabs(num_players),
"charPrefabMap": config.layout.char_prefab_map,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/territory.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Collaborative Cooking.
A pure common interest cooking game inspired by Carroll et al. (2019) and
Strouse et al. (2021).
Carroll, M., Shah, R., Ho, M.K., Griffiths, T.L., Seshia, S.A., Abbeel, P. and
Dragan, A., 2019. On the utility of learning about humans for human-AI
coordination. arXiv preprint arXiv:1910.05789.
Strouse, D.J., McKee, K.R., Botvinick, M., Hughes, E. and Everett, R., 2021.
Collaborating with Humans without Human Data. arXiv preprint arXiv:2110.08176.
"""
import copy
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict as configdict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
COOKING_TIME = 20
items = ["empty", "tomato", "dish", "soup"]
# Map a character to the prefab it represents in the ASCII map.
CHAR_PREFAB_MAP = {
"P": "spawn_point",
"#": "counter",
"O": "tomato_dispenser",
"D": "dish_dispenser",
"T": "delivery_location",
"C": "cooking_pot",
}
###########
# SPRITES #
###########
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
BACKGROUND_LIGHT = (255, 255, 255, 255)
BACKGROUND_DARK = (82, 82, 82, 255)
OUTLINE = (85, 58, 23, 255)
OUTLINE_DARK = (49, 49, 49, 255)
INVISIBLE = (0, 0, 0, 0)
COUNTER = (115, 81, 39, 255)
SPRITES = {}
PALETTES = {}
SPRITES["interact"] = """
PPPPPPPPPPPPPPPP
PPPPPPPPPPPPPPPP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PP~~~~~~~~~~~~PP
PPPPPPPPPPPPPPPP
PPPPPPPPPPPPPPPP
"""
SPRITES["empty"] = """
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
"""
PALETTES["empty"] = {"~": INVISIBLE, "@": BACKGROUND_LIGHT}
SPRITES["counter"] = """
&&&&&&&&&&&&&&&&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&**************&
&&&&&&&&&&&&&&&&
"""
PALETTES["counter"] = {"*": COUNTER, "&": OUTLINE}
SPRITES["delivery_location"] = SPRITES["counter"]
PALETTES["delivery_location"] = {"*": BACKGROUND_DARK, "&": OUTLINE_DARK}
SPRITES["dish"] = """
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~++++~~~~~~
~~~~~+^^^^+~~~~~
~~~~~+^^^^+~~~~~
~~~~~+^^^^+~~~~~
~~~~~&++++&~~~~~
~~~~~~&&&&~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
"""
PALETTES["dish"] = {
"~": [0, 0, 0, 0],
"+": [255, 255, 255, 255],
"^": [233, 239, 248, 255],
"&": [221, 222, 238, 255]
}
SPRITES["soup"] = SPRITES["dish"]
PALETTES["soup"] = {
"~": [0, 0, 0, 0],
"+": [255, 255, 255, 255],
"^": [236, 58, 74, 255],
"&": [221, 222, 238, 255]
}
SPRITES["dish_dispenser"] = """
&&&&&&&&&&&&&&&&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~++++~~~~~&
&~~~~+^^^^+~~~~&
&~~~~+^^^^+~~~~&
&~~~~+^^^^+~~~~&
&~~~~X++++X~~~~&
&~~~~~XXXX~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&~~~~~~~~~~~~~~&
&&&&&&&&&&&&&&&&
"""
PALETTES["dish_dispenser"] = {
"&": OUTLINE_DARK,
"~": BACKGROUND_DARK,
"+": [255, 255, 255, 255],
"^": [233, 239, 248, 255],
"X": [221, 222, 238, 255]
}
SPRITES["tomato"] = """
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~++^+~~~~~~
~~~~~&O^---~~~~~
~~~~~O-----~~~~~
~~~~~O&-@--~~~~~
~~~~~~OO&&~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
"""
PALETTES["tomato"] = {
"~": [0, 0, 0, 0],
"+": [239, 81, 90, 255],
"^": [29, 139, 43, 255],
"&": [190, 53, 62, 255],
"O": [151, 47, 52, 255],
"-": [236, 58, 74, 255],
"@": [240, 57, 75, 255]
}
SPRITES["tomato_dispenser"] = """
&&&&&&&&&&&&&&&&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,++^+,,,,,&
&,,,,XO^---,,,,&
&,,,,O-----,,,,&
&,,,,O&-@--,,,,&
&,,,,,OOXX,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&,,,,,,,,,,,,,,&
&&&&&&&&&&&&&&&&
"""
PALETTES["tomato_dispenser"] = {
",": BACKGROUND_DARK,
"&": OUTLINE_DARK,
"~": [0, 0, 0, 0],
"+": [239, 81, 90, 255],
"^": [29, 139, 43, 255],
"X": [190, 53, 62, 255],
"O": [151, 47, 52, 255],
"-": [236, 58, 74, 255],
"@": [240, 57, 75, 255]
}
SPRITES["cooking_pot_empty"] = """
&&&&&&&&&&&&&&&&
&~~~++++++++~~~&
&~~+^^^^^^^XO~~&
&~~+^^^^^^XXO~~&
&^^+^^^^^XXXO--&
&^~+^^^^XXXXO~-&
&^~+@@@@AAAAO~-&
&^^+@@@@AAAAO--&
&~~+@@@@AAAAO~~&
&~~@OOOOOOOO-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~~MMMMMMMM~~~&
&&&&&&&&&&&&&&&&
"""
SPRITES["cooking_pot_1"] = """
&&&&&&&&&&&&&&&&
&~~~++++++++~~~&
&~~+^^^^^^^XO~~&
&~~+^^^^^^XXO~~&
&^^+^^^^^XXXO--&
&^~+KKKKLLLLO~-&
&^~+KKKKLLLLO~-&
&^^+KKKKLLLLO--&
&~~+KKKKLLLLO~~&
&~~@OOOOOOOO-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~~MMMMMMMM~~~&
&&&&&&&&&&&&&&&&
"""
SPRITES["cooking_pot_2"] = """
&&&&&&&&&&&&&&&&
&~~~++++++++~~~&
&~~+^^^^^^^XO~~&
&~~+^^^^^^XXO~~&
&^^+KKKKKKLLO--&
&^~+KKKKLKLLO~-&
&^~+KLKKKKLLO~-&
&^^+KKKKKKLLO--&
&~~+KKKKKKLLO~~&
&~~@OOOOOOOO-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~~MMMMMMMM~~~&
&&&&&&&&&&&&&&&&
"""
SPRITES["cooking_pot_3"] = """
&&&&&&&&&&&&&&&&
&~~~++++++++~~~&
&~~+KKKKKKKKO~~&
&~~+KNKKKKKKO~~&
&^^+KKKKKKKKO--&
&^~+KKKKKKKKO~-&
&^~+KKKKKKKKO~-&
&^^+KKNKKKNKO--&
&~~+KKKKKKKKO~~&
&~~@OOOOOOOO-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~@MMMMMMMM-~~&
&~~~MMMMMMMM~~~&
&&&&&&&&&&&&&&&&
"""
PALETTES["cooking_pot"] = {
"&": OUTLINE,
"~": COUNTER,
"+": [224, 231, 240, 255],
"^": [140, 155, 181, 255],
"X": [98, 95, 128, 255],
"O": [238, 241, 241, 255],
"-": [194, 206, 222, 255],
"@": [92, 106, 135, 255],
"A": [65, 66, 97, 255],
"M": [139, 155, 181, 255],
"K": [236, 58, 74, 255],
"L": [161, 43, 43, 255],
"N": [242, 226, 187, 255]
}
SPRITES["loading_bar"] = """
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
~~~abcdefghij~~~
~~~abcdefghij~~~
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~
"""
def create_loading_bar_palette(count, finished=False):
"""Creates an incrementally colored loading bar based on count."""
characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
bars_palette = {"~": INVISIBLE}
for idx in range(0, 10):
if idx < count:
if finished:
bars_palette[characters[idx]] = (15, 188, 15, 255)
else:
bars_palette[characters[idx]] = (201, 178, 50, 255)
else:
bars_palette[characters[idx]] = (255, 255, 255, 255)
return bars_palette
OFFSET_SIZE = 3
for s in ["empty", "tomato", "dish", "soup"]:
SPRITES[s + "_offset"] = ("~~~~~~~~~~~~~~~~\n" * OFFSET_SIZE +
SPRITES[s][1:-OFFSET_SIZE*17])
###########
# PREFABS #
###########
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# pylint: disable=g-complex-comprehension
INVENTORY = {
"name": "inventory",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
"wait",
"stateConfigs": [{
"state": "wait"
}] + [{
"state": item,
"sprite": item,
"layer": "overlay"
} for item in items] + [{
"state": item + "_offset",
"sprite": item + "_offset",
"layer": "overlay"
} for item in items]
}
},
{
"component": "Transform",
"kwargs": {}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": items + [item + "_offset" for item in items],
"spriteShapes": ([SPRITES[item] for item in items] +
[SPRITES[item + "_offset"] for item in items]),
"palettes": ([PALETTES[item] for item in items] +
[PALETTES[item] for item in items]),
"noRotates": [False]
}
},
{
"component": "Inventory",
"kwargs": {
"playerIndex": -1, # Can be overwritten.
"emptyState": "empty",
"waitState": "wait"
}
},
]
}
# pylint: enable=g-complex-comprehension
loading_palettes = ([create_loading_bar_palette(idx) for idx in range(0, 10)] +
[create_loading_bar_palette(10, finished=True)])
LOADING_BAR = {
"name": "loading_bar",
"components": [{
"component": "StateManager",
"kwargs": {
"initialState":
"loading_bar_0",
"stateConfigs": [{
"state": "loading_bar_%d" % d, "layer": "overlay",
"sprite": "loading_bar_%d" % d} for d in range(0, 11)],
}
}, {
"component": "Transform",
"kwargs": {}
}, {
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["loading_bar_%d" % d for d in range(0, 11)],
"spriteShapes": [SPRITES["loading_bar"] for _ in range(0, 11)],
"palettes": loading_palettes,
"noRotates": [True]
}
}, {
"component": "LoadingBarVisualiser",
"kwargs": {
"totalTime": COOKING_TIME,
"customStateNames": ["loading_bar_%d" % d for d in range(0, 11)],
}
}]
}
def create_base_prefab(name, layer="upperPhysical"):
"""Returns a base prefab with a given name on the given layer."""
return {
"name": f"{name}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": f"{name}",
"stateConfigs": [{
"state": f"{name}",
"layer": layer,
"sprite": f"{name}",
}],
}
},
{
"component": "Transform",
"kwargs": {}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [name],
"spriteShapes": [SPRITES[name]],
"palettes": [PALETTES[name]],
"noRotates": [True]
}
}]
}
def create_counter():
"""Returns a prefab which can contain one of any item."""
base_prefab = create_base_prefab("counter")
base_prefab["components"] += [{
"component": "Container",
"kwargs": {
"reward": 0.0
}
}]
return base_prefab
def create_dispenser(prefab_name, item_name):
"""Returns a prefab which dispenses items to avatars upon interaction."""
base_prefab = create_base_prefab(prefab_name)
base_prefab["components"] += [{
"component": "Container",
"kwargs": {
"startingItem": item_name,
"infinite": True,
"reward": 0.0
}
}]
return base_prefab
def create_receiver(prefab_name,
item_name,
reward=0,
global_reward=False):
"""Returns a prefab which can receive items from avatars.
Args:
prefab_name: the name of the prefab.
item_name: the name of the accepted item.
reward: value of reward given to avatar when object receives the item.
global_reward: if true, reward all avatars.
Returns:
A prefab which can receive items.
"""
base_prefab = create_base_prefab(prefab_name)
base_prefab["components"] += [{
"component": "Receiver",
"kwargs": {
"acceptedItems": item_name,
"reward": reward,
"globalReward": global_reward
}
}]
return base_prefab
def create_cooking_pot(time_to_cook, reward=1):
"""Creates a cooking pot for tomatoes."""
state_configs = []
sprite_names = []
pot_sprites = []
cooking_pot_palettes = []
custom_state_names = []
available_foods = ["tomato"]
# Create state for each combination of available foods.
foods_in_pot = ["empty"] + available_foods
for food1 in foods_in_pot:
for food2 in foods_in_pot:
for food3 in foods_in_pot:
sprite_name = "CookingPot_%s_%s_%s" % (food1, food2, food3)
name = "cooking_pot_%s_%s_%s" % (food1, food2, food3)
entry = {"state": name,
"layer": "upperPhysical",
"sprite": sprite_name,
"groups": ["cooking_pot"]}
state_configs.append(entry)
sprite_names.append(sprite_name)
pots_palette = PALETTES["cooking_pot"]
cooking_pot_palettes.append(pots_palette)
custom_state_names.append(name)
if food1 == "empty":
pot_sprites.append(SPRITES["cooking_pot_empty"])
elif food2 == "empty":
pot_sprites.append(SPRITES["cooking_pot_1"])
elif food3 == "empty":
pot_sprites.append(SPRITES["cooking_pot_2"])
else:
pot_sprites.append(SPRITES["cooking_pot_3"])
# Create cooked state.
sprite_name = "CookingPot_cooked"
name = "cooking_pot_cooked"
entry = {"state": "cooking_pot_cooked",
"layer": "upperPhysical",
"sprite": sprite_name,
"groups": ["cooking_pot"]}
state_configs.append(entry)
sprite_names.append(sprite_name)
pot_sprites.append(SPRITES["cooking_pot_3"])
pots_palette = PALETTES["cooking_pot"]
cooking_pot_palettes.append(pots_palette)
custom_state_names.append(name)
cooking_pot = {
"name": "cooking_pot",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": (
"cooking_pot_empty_empty_empty"
),
"stateConfigs": state_configs
}
},
{
"component": "Transform",
"kwargs": {}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": sprite_names,
"spriteShapes": pot_sprites,
"palettes": cooking_pot_palettes,
"noRotates": [True for _ in sprite_names]
}
},
{
"component": "CookingPot",
"kwargs": {
"acceptedItems": available_foods,
"cookingTime": time_to_cook,
"reward": reward,
"customStateNames": custom_state_names
}
},
]
}
return cooking_pot
def create_prefabs(cooking_pot_pseudoreward: float = 0.0):
"""Creates a dictionary mapping names to template game objects."""
prefabs = {
"spawn_point": SPAWN_POINT,
"inventory": INVENTORY,
"loading_bar": LOADING_BAR,
"counter": create_counter(),
"dish_dispenser": create_dispenser(prefab_name="dish_dispenser",
item_name="dish"),
"tomato_dispenser": create_dispenser(prefab_name="tomato_dispenser",
item_name="tomato"),
"delivery_location": create_receiver(prefab_name="delivery_location",
item_name="soup",
reward=20,
global_reward=True),
"cooking_pot": create_cooking_pot(time_to_cook=COOKING_TIME,
reward=cooking_pot_pseudoreward),
}
return prefabs
###########
# ACTIONS #
###########
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
###########
# OBJECTS #
###########
def create_game_objects(ascii_map_string, prefabs):
"""Returns list of game objects from 'ascii_map' and 'char_prefab' mapping."""
# Create all game objects.
game_objects = []
for char, _ in CHAR_PREFAB_MAP.items():
transforms = game_object_utils.get_game_object_positions_from_map(
ascii_map_string, char)
for transform in transforms:
# Add inventory game object for holding and visualising items.
if char == "#" or char == "O" or char == "D":
inventory_object = copy.deepcopy(prefabs["inventory"])
go_transform = game_object_utils.get_first_named_component(
inventory_object, "Transform")
go_transform["kwargs"]["position"] = (transform.position.x,
transform.position.y)
game_objects.append(inventory_object)
# Add loading bar object to cooking pots.
if char == "C":
loading_object = copy.deepcopy(prefabs["loading_bar"])
go_transform = game_object_utils.get_first_named_component(
loading_object, "Transform")
go_transform["kwargs"]["position"] = (transform.position.x,
transform.position.y)
game_objects.append(loading_object)
return game_objects
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
interact_palette = {
"P": colors.palette[player_idx] + (255,),
"~": INVISIBLE,
}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(colors.palette[player_idx])],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"spawnGroup": "spawnPoints",
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": 4},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
}
},
{
"component": "InteractBeam",
"kwargs": {
"cooldownTime": 1,
"shapes": [SPRITES["interact"]],
"palettes": [interact_palette]
}
},
{"component": "AvatarCumulants",},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
avatar_object["components"].append({
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
"name": "ADDED_INGREDIENT_TO_COOKING_POT",
"type": "Doubles",
"shape": [],
"component": "AvatarCumulants",
"variable": "addedIngredientToCookingPot",
},
{
"name": "COLLECTED_SOUP_FROM_COOKING_POT",
"type": "Doubles",
"shape": [],
"component": "AvatarCumulants",
"variable": "collectedSoupFromCookingPot",
},
]
}
})
return avatar_object
def create_avatar_objects(num_players, prefabs):
"""Returns list of avatar objects of length 'num_players'."""
game_objects = []
for player_idx in range(0, num_players):
lua_index = player_idx + 1
game_object = create_avatar_object(player_idx,
TARGET_SPRITE_SELF)
game_objects.append(game_object)
# Add inventory game object which will be connected to player at init.
inventory_object = copy.deepcopy(prefabs["inventory"])
game_object_utils.get_first_named_component(
inventory_object,
"Inventory")["kwargs"]["playerIndex"] = lua_index
game_objects.append(inventory_object)
return game_objects
def get_config():
"""Default configuration for training on the collaborative cooking level."""
config = configdict.ConfigDict()
# Cooking pot pseudoreward should be 0.0 for the canonical version of this
# environment, but in order to train background bots it is sometimes useful
# to give them a pseudoreward when they put items in the cooking pot. It has
# the effect of shaping their behavior a bit in the right direction.
config.cooking_pot_pseudoreward = 0.0
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
config.action_spec = specs.action(len(ACTION_SET))
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build the substrate given player roles."""
num_players = len(roles)
ascii_map = config.layout.ascii_map
prefabs = create_prefabs(
cooking_pot_pseudoreward=config.cooking_pot_pseudoreward)
game_objects = create_game_objects(ascii_map, prefabs)
extra_game_objects = create_avatar_objects(num_players, prefabs)
game_objects += extra_game_objects
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="collaborative_cooking",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ascii_map,
"gameObjects": game_objects,
"prefabs": prefabs,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/collaborative_cooking.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for King of the Hill.
Example video: https://youtu.be/VVAfeObAZzI
See _Capture the Flag_ for the description of the painting, zapping, and
movement mechanics, which also operate in this substrate.
In the King of the Hill substrate the goal is to control the hill region in
the center of the map. The hill is considered to be controlled by a team if at
least 80% of it has been colored in one team's color. The status of the hill is
indicated by indicator tiles around the map an in the center. Red indicator
tiles mean the red team is in control. Blue indicator tiles mean the blue team
is in control. Purple indicator tiles mean no team is in control.
"""
from typing import Any, Dict, Mapping, Optional, Sequence
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import numpy as np
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ["N", "E", "S", "W"]
ASCII_MAP = """
IIIIIIIIIIIIIIIIIIIIIII
IWWWWWWWWWWWWWWWWWWWWWI
IWPPP,PPPP,P,PPPP,PPPWI
IWPPP,,PP,,,,,PP,,PPPWI
IWPPP,,,,,,,,,,,,,PPPWI
IWP,,WW,,,,,,,,,WW,,PWI
IW,,,WWDWWWDWWW,WW,,,WI
IW,,,,,,uuuuuuu,D,,,,WI
IW,,,,WlGGGGGGGrW,,,,WI
IWHWWHWlGGGGGGGrWHWWHWI
IWHWWHWlGGGGGGGrWHWWHWI
IW,,,,DlGGGIGGGrD,,,,WI
IWHWWHWlGGGGGGGrWHWWHWI
IWHWWHWlGGGGGGGrWHWWHWI
IW,,,,WlGGGGGGGrW,,,,WI
IW,,,,D,ddddddd,,,,,,WI
IW,,,WW,WWWDWWWDWW,,,WI
IWQ,,WW,,,,,,,,,WW,,QWI
IWQQQ,,,,,,,,,,,,,QQQWI
IWQQQ,,QQ,,,,,QQ,,QQQWI
IWQQQ,QQQQ,Q,QQQQ,QQQWI
IWWWWWWWWWWWWWWWWWWWWWI
IIIIIIIIIIIIIIIIIIIIIII
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"P": {"type": "all", "list": ["spawn_point_red", "ground"]},
"Q": {"type": "all", "list": ["spawn_point_blue", "ground"]},
"W": "wall",
"D": {"type": "choice",
"list": ["destroyable_wall"] * 9 + ["destroyed_wall"]},
"H": {"type": "choice",
"list": ["destroyable_wall"] * 3 + ["destroyed_wall"]},
"G": "hill",
",": "ground",
"I": {"type": "all", "list": ["indicator", "indicator_frame"]},
# Lines marking the edge of the hill.
"u": {"type": "all", "list": ["ground", "line_north"]},
"r": {"type": "all", "list": ["ground", "line_west"]},
"d": {"type": "all", "list": ["ground", "line_south"]},
"l": {"type": "all", "list": ["ground", "line_east"]},
}
RED_COLOR = (225, 55, 85, 255)
DARKER_RED_COLOR = (200, 35, 55, 255)
DARKEST_RED_COLOR = (160, 5, 25, 255)
BLUE_COLOR = (85, 55, 225, 255)
DARKER_BLUE_COLOR = (55, 35, 200, 255)
DARKEST_BLUE_COLOR = (25, 5, 160, 255)
PURPLE_COLOR = (107, 63, 160, 255)
LINE_NORTH = """
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
oooooooo
"""
LINE_SOUTH = shapes.flip_vertical(LINE_NORTH)
LINE_EAST = """
xxxxxxxo
xxxxxxxo
xxxxxxxo
xxxxxxxo
xxxxxxxo
xxxxxxxo
xxxxxxxo
xxxxxxxo
"""
LINE_WEST = shapes.flip_horizontal(LINE_EAST)
def multiply_tuple(color_tuple, factor):
alpha = color_tuple[3]
return tuple([int(np.min([x * factor, alpha])) for x in color_tuple[0: 3]])
TEAMS_DATA = {
"red": {"color": RED_COLOR,
"spawn_group": "{}SpawnPoints".format("red")},
"blue": {"color": BLUE_COLOR,
"spawn_group": "{}SpawnPoints".format("blue")},
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "AllBeamBlocker",
"kwargs": {}
},
]
}
def get_marking_line(orientation: str):
"""Return a line prefab to trace out the area of the hill."""
if orientation == "N":
shape = LINE_NORTH
elif orientation == "E":
shape = LINE_EAST
elif orientation == "S":
shape = LINE_SOUTH
elif orientation == "W":
shape = LINE_WEST
else:
raise ValueError(f"Unrecognized orientation: {orientation}")
line_name = f"line_{orientation}"
prefab = {
"name": line_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": line_name,
"stateConfigs": [{
"state": line_name,
"layer": "lowerPhysical",
"sprite": line_name,
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [line_name,],
"spriteShapes": [shape],
"palettes": [{"x": (0, 0, 0, 0),
"o": (75, 75, 75, 120)}],
"noRotates": [False]
}
},
]
}
return prefab
INDICATOR_FRAME = {
"name": "indicator_frame",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inert",
"stateConfigs": [
{"state": "inert",
"layer": "superOverlay",
"sprite": "InertFrame"}
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["InertFrame"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": (0, 0, 0, 0),
"x": (55, 55, 55, 255),
"#": (0, 0, 0, 0)}],
"noRotates": [True]
}
},
]
}
INDICATOR = {
"name": "control_indicator",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "uncontrolled",
"stateConfigs": [
{
"state": "uncontrolled",
"layer": "background",
"sprite": "UncontrolledIndicator",
},
{
"state": "red",
"layer": "background",
"sprite": "RedIndicator",
},
{
"state": "blue",
"layer": "background",
"sprite": "BlueIndicator",
}
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"spriteNames": ["UncontrolledIndicator",
"RedIndicator",
"BlueIndicator"],
"spriteRGBColors": [PURPLE_COLOR,
DARKER_RED_COLOR,
DARKER_BLUE_COLOR]
}
},
{"component": "ControlIndicator",},
]
}
def create_ground_prefab(is_hill=False):
"""Return a prefab for a normal ground or a hill prefab."""
if is_hill:
sprite_names = ["RedHill", "BlueHill"]
sprite_colors = [DARKER_RED_COLOR, DARKER_BLUE_COLOR]
groups = ["grounds", "hills"]
clean_groups = ["hill_clean",]
red_groups = ["hill_red",]
blue_groups = ["hill_blue",]
else:
sprite_names = ["RedGround", "BlueGround"]
sprite_colors = [DARKEST_RED_COLOR, DARKEST_BLUE_COLOR]
groups = ["grounds",]
clean_groups = []
red_groups = []
blue_groups = []
prefab = {
"name": "ground",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "clean",
"stateConfigs": [
{
"state": "clean",
"layer": "alternateLogic",
"groups": groups + clean_groups,
},
{
"state": "red",
"layer": "alternateLogic",
"sprite": sprite_names[0],
"groups": groups + red_groups,
},
{
"state": "blue",
"layer": "alternateLogic",
"sprite": sprite_names[1],
"groups": groups + blue_groups,
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"spriteNames": sprite_names,
"spriteRGBColors": sprite_colors
}
},
{
"component": "GroundOrHill",
"kwargs": {
# Must set the name to "Ground" so the color zapper component
# can find the location underneath the avatar to color it.
"name": "Ground",
"teamNames": ["red", "blue"],
"isHill": is_hill,
}
},
]
}
return prefab
def create_destroyable_wall_prefab(initial_state):
"""Return destroyable wall prefab, potentially starting in destroyed state."""
if initial_state == "destroyed":
initial_health = 0
else:
initial_health = 5
prefab = {
"name": "destroyableWall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{
"state": "destroyable",
"layer": "upperPhysical",
"sprite": "DestroyableWall",
},
{
"state": "damaged",
"layer": "upperPhysical",
"sprite": "DamagedWall",
},
{
"state": "destroyed",
"layer": "alternateLogic",
"sprite": "Rubble",
},
],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["DestroyableWall",
"DamagedWall",
"Rubble"],
"spriteShapes": [shapes.WALL,
shapes.WALL,
shapes.WALL],
"palettes": [{"*": (55, 55, 55, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)},
{"*": (55, 55, 55, 255),
"&": (100, 100, 100, 255),
"@": (79, 79, 79, 255),
"#": (152, 152, 152, 255)},
{"*": (0, 0, 0, 255),
"&": (0, 0, 0, 255),
"@": (29, 29, 29, 255),
"#": (0, 0, 0, 255)}],
"noRotates": [True] * 3
}
},
{
"component": "Destroyable",
"kwargs": {"hitNames": ["red", "blue"],
"initialHealth": initial_health,
"damagedHealthLevel": 2}
}
]
}
return prefab
def create_spawn_point_prefab(team):
"""Return a team-specific spawn-point prefab."""
prefab = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs": [{
"state": "playerSpawnPoint",
"layer": "logic",
"groups": [TEAMS_DATA[team]["spawn_group"]],
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "invisible",
"spriteNames": [],
"spriteRGBColors": []
}
},
]
}
return prefab
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"wall": WALL,
"spawn_point_red": create_spawn_point_prefab("red"),
"spawn_point_blue": create_spawn_point_prefab("blue"),
"destroyable_wall": create_destroyable_wall_prefab("destroyable"),
"destroyed_wall": create_destroyable_wall_prefab("destroyed"),
"hill": create_ground_prefab(is_hill=True),
"ground": create_ground_prefab(is_hill=False),
"indicator": INDICATOR,
"indicator_frame": INDICATOR_FRAME,
"line_north": get_marking_line("N"),
"line_east": get_marking_line("E"),
"line_south": get_marking_line("S"),
"line_west": get_marking_line("W"),
}
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0}
FIRE_ZAP_A = {"move": 0, "turn": 0, "fireZap": 1}
FIRE_ZAP_B = {"move": 0, "turn": 0, "fireZap": 2}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP_A, # a short-range beam with a wide area of effect
FIRE_ZAP_B, # a longer range beam with a thin area of effect
)
# The Scene is a non-physical object, its components implement global logic.
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{"component": "Transform",},
{
"component": "HillManager",
"kwargs": {
"percentToCapture": 80,
"rewardPerStepInControl": 1.0,
}
}
]
}
return scene
def create_avatar_object(
player_idx: int,
team: str,
override_taste_kwargs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Create an avatar object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
team_color = TEAMS_DATA[team]["color"]
health1_avatar_sprite_name = "avatarSprite{}Health1".format(lua_index)
health2_avatar_sprite_name = "avatarSprite{}Health2".format(lua_index)
health3_avatar_sprite_name = "avatarSprite{}Health3".format(lua_index)
health1_color_palette = shapes.get_palette(multiply_tuple(team_color, 0.35))
health2_color_palette = shapes.get_palette(team_color)
health3_color_palette = shapes.get_palette(multiply_tuple(team_color, 1.75))
taste_kwargs = {
# select `mode` from:
# ("none", "control_hill", "paint_hill", "zap_while_in_control")
"mode": "none",
"rewardAmount": 0.0,
"zeroMainReward": False,
"minFramesBetweenHillRewards": 0,
}
if override_taste_kwargs:
taste_kwargs.update(override_taste_kwargs)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "health2",
"stateConfigs": [
{"state": "health1",
"layer": "upperPhysical",
"sprite": health1_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
{"state": "health2",
"layer": "upperPhysical",
"sprite": health2_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
{"state": "health3",
"layer": "upperPhysical",
"sprite": health3_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
# Player wait state used when they have been zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [health1_avatar_sprite_name,
health2_avatar_sprite_name,
health3_avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR],
"palettes": [health1_color_palette,
health2_color_palette,
health3_color_palette],
"noRotates": [True] * 3
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": "health2",
"additionalLiveStates": ["health1", "health3"],
"waitState": "playerWait",
"spawnGroup": TEAMS_DATA[team]["spawn_group"],
"actionOrder": ["move",
"turn",
"fireZap"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 2},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
# The following kwarg makes it possible to get rewarded for
# team rewards even when an avatar is "dead".
"skipWaitStateRewards": False,
}
},
{
"component": "ColorZapper",
"kwargs": {
"team": team,
# The color zapper beam is somewhat transparent.
"color": (team_color[0], team_color[1], team_color[2], 150),
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"secondaryBeamCooldownTime": 4,
"secondaryBeamLength": 6,
"secondaryBeamRadius": 0,
"aliveStates": ["health1", "health2", "health3"],
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "ColorZapper",
}
},
{
"component": "ZappedByColor",
"kwargs": {
"team": team,
"allTeamNames": ["red", "blue"],
"framesTillRespawn": 80,
"penaltyForBeingZapped": 0,
"rewardForZapping": 0,
"healthRegenerationRate": 0.05,
"maxHealthOnGround": 2,
"maxHealthOnOwnColor": 3,
"maxHealthOnEnemyColor": 1,
"groundLayer": "alternateLogic",
}
},
{
"component": "TeamMember",
"kwargs": {"team": team}
},
{
"component": "Taste",
"kwargs": taste_kwargs
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def _even_vs_odd_team_assignment(num_players,
taste_kwargs: Optional[Any] = None):
"""Assign players with even ids to red team and odd ids to blue team."""
avatar_objects = []
for player_idx in range(0, num_players):
if player_idx % 2 == 0:
team = "red"
elif player_idx % 2 == 1:
team = "blue"
game_object = create_avatar_object(player_idx, team,
override_taste_kwargs=taste_kwargs)
avatar_objects.append(game_object)
return avatar_objects
def _low_vs_high_team_assignment(num_players,
taste_kwargs: Optional[Any] = None):
"""Assign players with id below the median id to blue and above it to red."""
median = np.median(range(num_players))
avatar_objects = []
for player_idx in range(0, num_players):
if player_idx < median:
team = "blue"
elif player_idx > median:
team = "red"
game_object = create_avatar_object(player_idx, team,
override_taste_kwargs=taste_kwargs)
avatar_objects.append(game_object)
return avatar_objects
def create_avatar_objects(num_players,
taste_kwargs: Optional[Any] = None,
fixed_teams: Optional[bool] = False):
"""Returns list of avatar objects of length 'num_players'."""
assert num_players % 2 == 0, "num players must be divisible by 2"
if fixed_teams:
avatar_objects = _low_vs_high_team_assignment(num_players,
taste_kwargs=taste_kwargs)
else:
avatar_objects = _even_vs_odd_team_assignment(num_players,
taste_kwargs=taste_kwargs)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# If shaping_kwargs are None then use the default reward structure in which
# all positive rewards come from your team being in control of the hill and
# all negative rewwards come from the opposing team being in control of the
# hill. The default reward structure is zero sum.
config.shaping_kwargs = None
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(184, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given player roles."""
num_players = len(roles)
substrate_definition = dict(
levelName="paintball__king_of_the_hill",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(
num_players, taste_kwargs=config.shaping_kwargs),
"scene": create_scene(),
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/paintball__king_of_the_hill.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for boat_race.
Example video: https://youtu.be/sEh1hRJVuFw
Six players engage in a back and forth series of boat races across a river to
reach a patch of apples, which confer reward when eaten. Boats, however, cannot
be rowed by a single player, and thus, players need to find a partner before
each race and coordinate their rowing during the race to cross the river. When
the players are on the boat, they can choose from two different rowing actions
at each timestamp: (a) paddle, which is efficient, but costly if not
coordinated with its partner; and (b) flail, an inefficient action which isn't
affected by the partner's action. When both players paddle simultaneously, the
boat moves one cell every few timesteps. When either player flails, the boat has
a probability of moving one cell, and a reward penalty is given to its partner
if that partner is currently paddling, i.e. if they have executed the paddle
action within the last few timesteps.
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict as configdict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# This substrate only makes sense with exactly six players.
MANDATED_NUM_PLAYERS = 6
NUM_RACES = 8
PARTNER_DURATION = 75
RACE_DURATION = 225
UNROLL_LENGTH = 100
ASCII_MAP = r"""
WWWWWWWWWWWWWWWWWWWWWWWWWW
W W
W W
W W
W RRRRRRRRRRRR W
W RRRRRRRRRRRR W
W RRRRRRRRRRRR W
W RRRRRRRRRRRR W
W W
W S SS SS S W
W S%%SS%%SS%%S W
W S SS SS S W
~~~~~~~~gg~~gg~~gg~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~AA~~AA~~AA~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~AA~~AA~~AA~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~AA~~AA~~AA~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~{{~~{{~~{{~~~~~~~~
~~~~~~~~AA~~AA~~AA~~~~~~~~
~~~~~~~~/\~~/\~~/\~~~~~~~~
~~~~~~~p;:qp;:qp;:q~~~~~~~
W SLJSSLJSSLJS W
W S--SS--SS--S W
W S SS SS S W
W W
W OOOOOOOOOOOO W
W OOOOOOOOOOOO W
W OOOOOOOOOOOO W
W OOOOOOOOOOOO W
W W
W ________________ W
W ________________ W
WWWWWWWWWWWWWWWWWWWWWWWWWW
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"_": {"type": "all", "list": ["floor", "spawn_point"]},
" ": "floor",
"W": "wall",
"S": {"type": "all", "list": ["floor", "semaphore"]},
"A": {"type": "all", "list": ["water_background", "single_apple"]},
"R": {"type": "all", "list": ["floor", "respawning_apple_north"]},
"O": {"type": "all", "list": ["floor", "respawning_apple_south"]},
"%": {"type": "all", "list": ["floor", "barrier_north"]},
"-": {"type": "all", "list": ["floor", "barrier_south"]},
"~": "water_blocking",
"{": "water_background",
"g": {"type": "all", "list": ["goal_north", "water_background"]},
"/": {"type": "all", "list": ["boat_FL", "water_background"]},
"\\": {"type": "all", "list": ["boat_FR", "water_background"]},
"L": {"type": "all", "list": ["floor", "boat_RL"]},
"J": {"type": "all", "list": ["floor", "boat_RR"]},
"p": {"type": "all", "list": ["oar_L", "water_blocking"]},
"q": {"type": "all", "list": ["oar_R", "water_blocking"]},
";": {"type": "all", "list": ["seat_L", "goal_south", "water_background"]},
":": {"type": "all", "list": ["seat_R", "goal_south", "water_background"]},
}
_COMPASS = ["N", "E", "S", "W"]
# The Scene objece is a non-physical object, it components implement global
# logic. In this case, that includes holding the global berry counters to
# implement the regrowth rate, as well as some of the observations.
SCENE = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "partnerChoice",
"stateConfigs": [{
"state": "ForceEmbark",
}, {
"state": "partnerChoice",
}, {
"state": "semaphore_yellow",
}, {
"state": "semaphore_green",
}, {
"state": "boatRace",
}, {
"state": "semaphore_red", # A temporary state at end game.
}],
}
},
{"component": "Transform",},
{
"component": "RaceManager",
"kwargs": {
"raceStartTime": PARTNER_DURATION,
"raceDuration": RACE_DURATION,
},
},
{
"component": "GlobalRaceTracker",
"kwargs": {
"numPlayers": MANDATED_NUM_PLAYERS,
},
},
{
"component": "EpisodeManager",
"kwargs": {
"checkInterval": UNROLL_LENGTH,
},
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
SCENE["components"].append({
"component": "GlobalMetricReporter",
"kwargs": {
"metrics": [
{
"name": "RACE_START",
"type": "tensor.Int32Tensor",
"shape": (MANDATED_NUM_PLAYERS // 2, 2),
"component": "GlobalRaceTracker",
"variable": "raceStart",
},
{
"name": "STROKES",
"type": "tensor.Int32Tensor",
"shape": (MANDATED_NUM_PLAYERS,),
"component": "GlobalRaceTracker",
"variable": "strokes",
},
]
},
})
FLOOR = {
"name": "floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "floor",
"stateConfigs": [{
"state": "floor",
"layer": "background",
"sprite": "Floor",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Floor",],
"spriteShapes": [shapes.GRAINY_FLOOR],
"palettes": [{
"+": (157, 142, 120, 255),
"*": (154, 139, 115, 255),
}],
"noRotates": [True]
}
},
{
"component": "Transform",
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gift"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "zap"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{"component": "Transform",},
]
}
SINGLE_APPLE = {
"name": "single_apple",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "apple",
"stateConfigs": [
{"state": "apple",
"layer": "singleAppleLayer",
"sprite": "apple",
},
{"state": "appleWait",
"layer": "logic",
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["apple"],
"spriteShapes": [shapes.HD_APPLE],
"palettes": [shapes.get_palette((40, 180, 40, 255))],
"noRotates": [False],
}
},
{
"component": "Edible",
"kwargs": {
"liveState": "apple",
"waitState": "appleWait",
"rewardForEating": 1.0,
}
},
]
}
def get_respawning_apple(bank_side: str):
initial_state = "apple" if bank_side == "N" else "applePause"
return {
"name": "apple",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{"state": "apple",
"layer": "superOverlay",
"sprite": "apple",
},
{"state": "appleWait",
"layer": "logic",
},
{"state": "applePause",
"layer": "logic",
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["apple"],
"spriteShapes": [shapes.HD_APPLE],
"palettes": [shapes.get_palette((40, 180, 40, 255))],
"noRotates": [False],
}
},
{
"component": "Edible",
"kwargs": {
"liveState": "apple",
"waitState": "appleWait",
"rewardForEating": 1.0,
}
},
{
"component": "FixedRateRegrow",
"kwargs": {
"liveState": "apple",
"waitState": "appleWait",
"regrowRate": 0.1,
}
},
]
}
SEMAPHORE = {
"name": "semaphore",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "red",
"stateConfigs": [
{"state": "red",
"layer": "upperPhysical",
"sprite": "red",
"groups": ["semaphore"]},
{"state": "yellow",
"layer": "upperPhysical",
"sprite": "yellow",
"groups": ["semaphore"]},
{"state": "green",
"layer": "upperPhysical",
"sprite": "green",
"groups": ["semaphore"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["red", "yellow", "green"],
"spriteShapes": [shapes.COIN] * 3,
"palettes": [shapes.RED_COIN_PALETTE, shapes.COIN_PALETTE,
shapes.GREEN_COIN_PALETTE],
"noRotates": [False] * 3,
}
},
]
}
def get_barrier(bank_side: str = "N"):
initial_state = "off" if bank_side == "N" else "on"
return {
"name": "barrier",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{"state": "on",
"layer": "upperPhysical",
"sprite": "barrierOn",
"groups": ["barrier"]},
{"state": "off",
"layer": "superOverlay",
"sprite": "barrierOff",
"groups": ["barrier"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["barrierOn", "barrierOff"],
"spriteShapes": [shapes.BARRIER_ON, shapes.BARRIER_OFF],
"palettes": [shapes.GRAY_PALETTE] * 2,
"noRotates": [False] * 2,
}
},
]
}
def get_water(layer: str):
"""Get a water game object at the specified layer, possibly with a goal."""
return {
"name": "water_{}".format(layer),
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "water_1",
"stateConfigs": [
{"state": "water_1",
"layer": layer,
"sprite": "water_1",
"groups": ["water"]},
{"state": "water_2",
"layer": layer,
"sprite": "water_2",
"groups": ["water"]},
{"state": "water_3",
"layer": layer,
"sprite": "water_3",
"groups": ["water"]},
{"state": "water_4",
"layer": layer,
"sprite": "water_4",
"groups": ["water"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["water_1", "water_2", "water_3", "water_4"],
"spriteShapes": [shapes.WATER_1, shapes.WATER_2,
shapes.WATER_3, shapes.WATER_4],
"palettes": [shapes.WATER_PALETTE] * 4,
}
},
{
"component": "Animation",
"kwargs": {
"states": ["water_1", "water_2", "water_3", "water_4"],
"gameFramesPerAnimationFrame": 2,
"loop": True,
"randomStartFrame": True,
"group": "water",
}
},
]
}
def get_goal(bank_side: str = "N"):
return {
"name": "water_goal",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "goalNonBlocking",
"stateConfigs": [{
"state": "goalNonBlocking",
"layer": "logic",
}, {
"state": "goalBlocking",
"layer": "upperPhysical",
}],
}
},
{"component": "Transform",},
{
"component": "WaterGoal",
"kwargs": {
"bank_side": bank_side
},
}
]
}
def get_boat(front: bool, left: bool):
suffix = "{}{}".format("F" if front else "R", "L" if left else "R")
shape = {
"FL": shapes.BOAT_FRONT_L,
"FR": shapes.BOAT_FRONT_R,
"RL": shapes.BOAT_REAR_L,
"RR": shapes.BOAT_REAR_R,
}
return {
"name": f"boat_{suffix}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "boat",
"stateConfigs": [
{"state": "boat",
"layer": "lowerPhysical",
"sprite": f"Boat{suffix}",
"groups": ["boat"]},
{"state": "boatFull",
"layer": "overlay",
"sprite": f"Boat{suffix}",
"groups": ["boat"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [f"Boat{suffix}"],
"spriteShapes": [shape[suffix]],
"palettes": [shapes.BOAT_PALETTE],
"noRotates": [False]
}
},
]
}
def get_seat(left: bool):
"""Get a seat prefab. Left seats contain the BoatManager component."""
suffix = "L" if left else "R"
shape = {
"L": shapes.BOAT_SEAT_L,
"R": shapes.BOAT_SEAT_R,
}
seat = {
"name": f"seat_{suffix}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "seat",
"stateConfigs": [
{"state": "seat",
"layer": "lowerPhysical",
"sprite": f"Seat{suffix}",
"groups": ["seat", "boat"]},
{"state": "seatTaken",
"layer": "overlay",
"sprite": f"Seat{suffix}",
"contact": "boat"},
{"state": "seatUsed",
"layer": "lowerPhysical",
"sprite": f"Seat{suffix}"},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [f"Seat{suffix}"],
"spriteShapes": [shape[suffix]],
"palettes": [shapes.BOAT_PALETTE],
"noRotates": [False]
}
},
{
"component": "Seat",
"kwargs": {
},
},
]
}
if left:
seat["components"] += [
{
"component": "BoatManager",
"kwargs": {
"flailEffectiveness": 0.1,
}
}
]
return seat
def get_oar(left: bool):
suffix = "L" if left else "R"
shape = {
"L": [shapes.OAR_DOWN_L, shapes.OAR_UP_L, shapes.OAR_UP_L],
"R": [shapes.OAR_DOWN_R, shapes.OAR_UP_R, shapes.OAR_UP_R],
}
return {
"name": f"oar_{suffix}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "oarDown",
"stateConfigs": [
{"state": "oarDown",
"layer": "overlay",
"sprite": f"OarDown{suffix}",
"groups": ["oar", "boat"]},
{"state": "oarUp_row",
"layer": "overlay",
"sprite": f"OarUp{suffix}Row",
"groups": ["oar", "boat"]},
{"state": "oarUp_flail",
"layer": "overlay",
"sprite": f"OarUp{suffix}Flail",
"groups": ["oar", "boat"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [
f"OarDown{suffix}",
f"OarUp{suffix}Row",
f"OarUp{suffix}Flail",
],
"spriteShapes": shape[suffix],
"palettes": [shapes.GRAY_PALETTE] * 3,
"noRotates": [False] * 3
}
},
]
}
AVATAR = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "player",
"stateConfigs": [
{"state": "player",
"layer": "upperPhysical",
"sprite": "Avatar",
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
{"state": "rowing",
"layer": "superOverlay",
"sprite": "Avatar",
"contact": "avatar",
"groups": ["players"]},
{"state": "landed",
"layer": "upperPhysical",
"sprite": "Avatar",
"contact": "avatar",
"groups": ["players"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Avatar"],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(colors.human_readable[0])],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": -1, # player index to be overwritten.
"aliveState": "player",
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": [
"move", "turn", "row", "flail"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"row": {"default": 0, "min": 0, "max": 1},
"flail": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
}
}
},
{
"component": "Rowing",
"kwargs": {
"cooldownTime": 5,
"playerRole": "none",
},
},
{
"component": "StrokesTracker",
"kwargs": {}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
AVATAR["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"floor": FLOOR,
"wall": WALL,
"spawn_point": SPAWN_POINT,
"water_blocking": get_water("upperPhysical"),
"water_background": get_water("background"),
"goal_north": get_goal(bank_side="N"),
"goal_south": get_goal(bank_side="S"),
"barrier_north": get_barrier(bank_side="N"),
"barrier_south": get_barrier(bank_side="S"),
"single_apple": SINGLE_APPLE,
"respawning_apple_north": get_respawning_apple(bank_side="N"),
"respawning_apple_south": get_respawning_apple(bank_side="S"),
"semaphore": SEMAPHORE,
"boat_FL": get_boat(front=True, left=True),
"boat_FR": get_boat(front=True, left=False),
"boat_RL": get_boat(front=False, left=True),
"boat_RR": get_boat(front=False, left=False),
"seat_L": get_seat(left=True),
"seat_R": get_seat(left=False),
"oar_L": get_oar(left=True),
"oar_R": get_oar(left=False),
"avatar": AVATAR,
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
# These correspond to the persistent agent colors, but are meaningless for the
# human player. They will be overridden by the environment_builder.
PLAYER_COLOR_PALETTES = [
shapes.get_palette(colors.human_readable[0]),
shapes.get_palette(colors.human_readable[1]),
shapes.get_palette(colors.human_readable[2]),
shapes.get_palette(colors.human_readable[3]),
shapes.get_palette(colors.human_readable[4]),
shapes.get_palette(colors.human_readable[5]),
]
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "row": 0, "flail": 0}
FORWARD = {"move": 1, "turn": 0, "row": 0, "flail": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "row": 0, "flail": 0}
BACKWARD = {"move": 3, "turn": 0, "row": 0, "flail": 0}
STEP_LEFT = {"move": 4, "turn": 0, "row": 0, "flail": 0}
TURN_LEFT = {"move": 0, "turn": -1, "row": 0, "flail": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "row": 0, "flail": 0}
ROW = {"move": 0, "turn": 0, "row": 1, "flail": 0}
FLAIL = {"move": 0, "turn": 0, "row": 0, "flail": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
ROW,
FLAIL,
)
def get_config():
"""Configuration for the boat_race substrate."""
config = configdict.ConfigDict()
# Specify the number of players to particate in each episode (optional).
config.recommended_num_players = MANDATED_NUM_PLAYERS
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(304, 208),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default", "target"})
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build boat_race substrate given player roles."""
assert len(roles) == MANDATED_NUM_PLAYERS, "Wrong number of players"
assert "num_races" in config, (
"Cannot build substrate without specifying the number of races. Try "
"using the specific config (e.g. `boat_race__eight_races`) instead.")
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="boat_race",
levelDirectory="meltingpot/lua/levels",
numPlayers=MANDATED_NUM_PLAYERS,
maxEpisodeLengthFrames=config.num_races * (PARTNER_DURATION +
RACE_DURATION),
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"scene": SCENE,
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
"playerPalettes": PLAYER_COLOR_PALETTES,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/boat_race.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Stag Hunt in the Matrix (two player, repeated version).
Example video: https://youtu.be/aDp_CArcb1Y
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Stag Hunt game. `K = 2`
resources represent "stag" and "hare" pure strategies.
Players have a `5 x 5` observation window.
The episode has a chance of ending stochastically on every 100 step interval
after step 1000. This usually allows time for 8 or more interactions.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is green.
RESOURCE1_COLOR = (30, 225, 185, 255)
RESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is red.
RESOURCE2_COLOR = (225, 30, 70, 255)
RESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn n nW
W 2WWW W W W WW2 W
W W 11a W 222 W W
Wn WW 11a W a22 WW nW
W 1aa 2 a22 W
W 2 2 W
Wn WW WW2 n WW WWW nW
W 2 2 W
W 22a 2 aa1 W
Wn W 22a W a11 W nW
W 2W 222 W a11 WW W
W WWWW W W W WWW2 W
Wn n nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 8
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
TARGET_SPRITE_OTHER = {
"name": "Other",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((200, 100, 50)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# row player chooses a row of this matrix.
# C D
[4, 0], # C
[2, 2], # D
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# C D
[4, 2], # C
[0, 2], # D
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue # violet
(0.0, 0.5), (0.5, 1.5), (1.5, 2.5), (2.5, 3.5), (3.5, 4.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(
resource_id: int,
resource_shape: str,
resource_palette: Dict[str, Tuple[int, int, int, int]]):
"""Creates resource prefab with provided resource_id, shape, and palette."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [resource_shape],
"palettes": [resource_palette],
"noRotates": [True]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.02,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_avatar_object(
player_idx: int,
all_source_sprite_names: Sequence[str],
target_sprite_self: Dict[str, Any],
target_sprite_other: Dict[str, Any],
turn_off_default_reward: bool = False) -> Dict[str, Any]:
"""Create an avatar object given self vs other sprite data."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
for name in all_source_sprite_names:
if name != source_sprite_self:
custom_sprite_map[name] = target_sprite_other["name"]
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": [source_sprite_self],
# A white square should never be displayed. It will always be
# remapped since this is self vs other observation mode.
"spriteRGBColors": [(255, 255, 255, 255)],
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"],
target_sprite_other["name"]],
"customSpriteShapes": [target_sprite_self["shape"],
target_sprite_other["shape"]],
"customPalettes": [target_sprite_self["palette"],
target_sprite_other["palette"]],
"customNoRotates": [target_sprite_self["noRotate"],
target_sprite_other["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 5,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "SpawnResourcesWhenAllPlayersZapped",
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": turn_off_default_reward,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_prefabs():
"""Returns a dictionary mapping names to template game objects."""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(
1, shapes.BUTTON, {"*": RESOURCE1_COLOR_DATA[0],
"#": RESOURCE1_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class2"] = create_resource_prefab(
2, shapes.BUTTON, {"*": RESOURCE2_COLOR_DATA[0],
"#": RESOURCE2_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
return prefabs
def get_all_source_sprite_names(num_players):
all_source_sprite_names = []
for player_idx in range(0, num_players):
# Lua is 1-indexed.
lua_index = player_idx + 1
all_source_sprite_names.append("Avatar" + str(lua_index))
return all_source_sprite_names
def create_avatar_objects(num_players,
turn_off_default_reward: bool = False):
"""Returns list of avatar objects of length 'num_players'."""
all_source_sprite_names = get_all_source_sprite_names(num_players)
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(
player_idx,
all_source_sprite_names,
TARGET_SPRITE_SELF,
TARGET_SPRITE_OTHER,
turn_off_default_reward=turn_off_default_reward)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(game_object)
avatar_objects.append(readiness_marker)
return avatar_objects
def create_world_sprite_map(
num_players: int, target_sprite_other: Dict[str, Any]) -> Dict[str, str]:
all_source_sprite_names = get_all_source_sprite_names(num_players)
world_sprite_map = {}
for name in all_source_sprite_names:
world_sprite_map[name] = target_sprite_other["name"]
return world_sprite_map
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Other parameters that are useful to override in training config files.
config.turn_off_default_reward = False
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=2500, # The maximum possible number of frames.
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
# worldSpriteMap is needed to make the global view used in videos be
# be informative in cases where individual avatar views have had
# sprites remapped to one another (example: self vs other mode).
"worldSpriteMap": create_world_sprite_map(num_players,
TARGET_SPRITE_OTHER),
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/stag_hunt_in_the_matrix__repeated.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Common functions to be used across multiple *_in_the_matrix substrates."""
import copy
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import shapes
def get_cumulant_metric_configs(
num_resources: int) -> Sequence[Mapping[str, Any]]:
"""Get metric configs to configure AvatarMetricReporter."""
cumulants = []
# One cumulant tracks from frame to frame whether the player participated in
# an interaction.
cumulants.append({
"name": "INTERACTED_THIS_STEP",
"type": "Doubles",
"shape": [],
"component": "GameInteractionZapper",
"variable": "interacted_this_step",
})
for py_idx in range(num_resources):
lua_idx = py_idx + 1
# Several cumulants track when resources are collected. There will be one
# such cumulant per resource type.
cumulants.append({
"name": f"COLLECTED_RESOURCE_{lua_idx}",
"type": "Doubles",
"shape": [],
"component": "GameInteractionZapper",
"variable": f"collected_resource_{lua_idx}",
})
# Several cumulants track when resources are destroyed. There will be one
# such cumulant per resource type.
cumulants.append({
"name": f"DESTROYED_RESOURCE_{lua_idx}",
"type": "Doubles",
"shape": [],
"component": "GameInteractionZapper",
"variable": f"destroyed_resource_{lua_idx}",
})
# Sevaral cumulants track which resource was maximal in the interaction on
# the current frame. There will be one such cumulant per resource type.
cumulants.append({
"name": f"ARGMAX_INTERACTION_INVENTORY_WAS_{lua_idx}",
"type": "Doubles",
"shape": [],
"component": "GameInteractionZapper",
"variable": f"argmax_interaction_inventory_was_{lua_idx}",
})
return cumulants
def get_indicator_color_palette(color_rgba):
indicator_palette = copy.deepcopy(shapes.GOLD_CROWN_PALETTE)
indicator_palette["#"] = color_rgba
slightly_darker_color = [round(value * 0.9) for value in color_rgba[:-1]]
slightly_darker_color.append(150) # Add a half transparent alpha channel.
indicator_palette["@"] = slightly_darker_color
return indicator_palette
def create_ready_to_interact_marker(player_idx: int) -> Dict[str, Any]:
"""Create a ready-to-interact marker overlay object."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
marking_object = {
"name": "avatarReadyToInteractMarker",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "avatarMarkingWait",
"stateConfigs": [
# Use `overlay` layer for ready and nonready states, both
# are used for live avatars and are always connected.
{"state": "ready",
"layer": "overlay",
"sprite": "Ready"},
{"state": "notReady",
"layer": "overlay"},
# Result indication colors.
{"state": "resultIndicatorColor1",
"layer": "overlay",
"sprite": "ResultIndicatorColor1"},
{"state": "resultIndicatorColor2",
"layer": "overlay",
"sprite": "ResultIndicatorColor2"},
{"state": "resultIndicatorColor3",
"layer": "overlay",
"sprite": "ResultIndicatorColor3"},
{"state": "resultIndicatorColor4",
"layer": "overlay",
"sprite": "ResultIndicatorColor4"},
{"state": "resultIndicatorColor5",
"layer": "overlay",
"sprite": "ResultIndicatorColor5"},
# Invisible inactive overlay type.
{"state": "avatarMarkingWait",
"groups": ["avatarMarkingWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [
"Ready",
"ResultIndicatorColor1",
"ResultIndicatorColor2",
"ResultIndicatorColor3",
"ResultIndicatorColor4",
"ResultIndicatorColor5",
],
"spriteShapes": [shapes.BRONZE_CAP,] * 6,
"palettes": [
shapes.SILVER_CROWN_PALETTE,
# Colors are in rainbow order (more or less).
get_indicator_color_palette((139, 0, 0, 255)), # red
get_indicator_color_palette((253, 184, 1, 255)), # yellow
get_indicator_color_palette((0, 102, 0, 255)), # green
get_indicator_color_palette((2, 71, 254, 255)), # blue
get_indicator_color_palette((127, 0, 255, 255)), # violet
],
"noRotates": [True,] * 6,
}
},
{
"component": "AvatarConnector",
"kwargs": {
"playerIndex": lua_idx,
"aliveState": "notReady", # state `notReady` is invisible.
"waitState": "avatarMarkingWait"
}
},
{
"component": "ReadyToInteractMarker",
"kwargs": {
"playerIndex": lua_idx,
}
},
]
}
return marking_object
|
meltingpot-main
|
meltingpot/configs/substrates/the_matrix.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Chemistry: Two Metabolic Cycles With Distractors.
Example video:
Individuals benefit from two different food generating reaction cycles or from
holding a distractor molecule in their vesicle. The cycles will run on their own
(autocatalytically), but require energy to continue.
Bringing together side products from the two cycles generates new energy
such that the cycles can continue. The population needs to keep both of these
cycles running to get high rewards.
Reactions are defined by a directed graph. Reactant nodes project into reaction
nodes, which project out to product nodes. Reactions occur stochastically when
all reactants are brought near one another. Agents can carry a single molecule
around the map with them at a time. Agents are rewarded when a specific reaction
occurs that involves the molecule they are currently carrying (as either a
reactant or a product).
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.configs.substrates import reaction_graph_utils as graph_utils
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import networkx as nx
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# Map reaction to rewards.
DEFAULT_REWARDING_REACTIONS = {"MetabolizeFood1": 1,
"MetabolizeFood2": 1,
"MetabolizeXY": 10,
"Holding": 0.1}
# Define the default reaction query configuration. It can be overridden on a per
# compount basis.
DEFAULT_REACTION_CONFIG = {"radius": 1, "query_type": "disc"}
REACTIVITY_LEVELS = {
"ground": {"background": 0.00001,
"low": 0.005,
"medium": 0.001,
"high": 0.9},
"vesicle": {"background": 0.0,
"low": 0.0025,
"medium": 0.25,
"high": 0.9},
}
def dissipate_when_paired(g: nx.MultiDiGraph, reaction_name: str,
compound: str):
g.add_node(reaction_name, reaction=True)
# Reactants:
g.add_edge(compound, reaction_name)
g.add_edge(compound, reaction_name)
# Products:
g.add_edge(reaction_name, "empty")
g.add_edge(reaction_name, "empty")
def cycle(g: nx.MultiDiGraph, reaction_prefix: str,
intermediates: Sequence[str], product: str,
secondary_product: str, food: str = "food"):
"""Add a reaction cycle."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "energy")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def null(g: nx.MultiDiGraph, reaction_name: str, compound: str):
"""Chemical state transition pattern."""
g.add_node(reaction_name, reaction=True)
g.add_edge(compound, reaction_name)
g.add_edge(reaction_name, compound)
def make_graph():
"""User defined graph construction function using networkx."""
# Note: You can copy-paste this function into colab to visualize the graph.
g = nx.MultiDiGraph()
# First add the "empty" and "activated" nodes, which are always present.
graph_utils.add_system_nodes(g)
cycle(g, "R",
intermediates=["ax", "bx", "cx"],
product="x",
secondary_product="iy",
food="food1")
cycle(g, "R",
intermediates=["ay", "by", "cy"],
product="y",
secondary_product="ix",
food="food2")
null(g, "Holding", "distractor") # Holding the distractor provides reward.
# Inhibit x with a product of the y-producing cycle.
g.add_node("InhibitX", reaction=True)
# Reactants:
g.add_edge("x", "InhibitX")
g.add_edge("ix", "InhibitX")
# Products:
g.add_edge("InhibitX", "empty")
g.add_edge("InhibitX", "empty")
# Inhibit y with a product of the x-producing cycle.
g.add_node("InhibitY", reaction=True)
# Reactants:
g.add_edge("y", "InhibitY")
g.add_edge("iy", "InhibitY")
# Products:
g.add_edge("InhibitY", "empty")
g.add_edge("InhibitY", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood1", reaction=True)
# Reactants:
g.add_edge("food1", "MetabolizeFood1")
# Products:
g.add_edge("MetabolizeFood1", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood2", reaction=True)
# Reactants:
g.add_edge("food2", "MetabolizeFood2")
# Products:
g.add_edge("MetabolizeFood2", "empty")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood1", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood1")
# Products:
g.add_edge("SpawnFood1", "food1")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood2", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood2")
# Products:
g.add_edge("SpawnFood2", "food2")
# x and y can be combined to produce energy.
g.add_node("MetabolizeXY", reaction=True)
# Reactants:
g.add_edge("x", "MetabolizeXY")
g.add_edge("y", "MetabolizeXY")
# Products:
g.add_edge("MetabolizeXY", "energy")
g.add_edge("MetabolizeXY", "energy")
# Energy spontaneously dissipates.
g.add_node("DissipateEnergy", reaction=True)
# Reactants:
g.add_edge("energy", "DissipateEnergy")
# Products:
g.add_edge("DissipateEnergy", "empty")
# Prevent inhibitors from accumulating by dissipating them whenever they pair.
dissipate_when_paired(g, "DissipateIX", "ix")
dissipate_when_paired(g, "DissipateIY", "iy")
# Properties of compounds
# Color:
g.nodes["ax"]["color"] = (153, 204, 255, 255) # blue 1
g.nodes["bx"]["color"] = (102, 204, 255, 255) # blue 2
g.nodes["cx"]["color"] = (51, 153, 255, 255) # blue 3
g.nodes["ay"]["color"] = (102, 255, 153, 255) # green 1
g.nodes["by"]["color"] = (102, 255, 102, 255) # green 2
g.nodes["cy"]["color"] = (0, 255, 0, 255) # green 3
g.nodes["x"]["color"] = (0, 51, 204, 255) # dark blue
g.nodes["y"]["color"] = (0, 51, 0, 255) # dark green
g.nodes["food1"]["color"] = (178, 151, 0, 255) # light gold
g.nodes["food1"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food2"]["color"] = (255, 215, 0, 255) # gold
g.nodes["food2"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["distractor"]["color"] = (75, 0, 130, 255) # indigo
g.nodes["distractor"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["energy"]["color"] = (255, 0, 0, 255) # red
g.nodes["energy"]["sprite"] = graph_utils.ENERGY_SHAPE
g.nodes["ix"]["color"] = (102, 153, 153, 255) # greyish green
g.nodes["iy"]["color"] = (51, 102, 153, 255) # greyish blue
# Reactivity:
g.nodes["ax"]["reactivity"] = "high"
g.nodes["bx"]["reactivity"] = "high"
g.nodes["cx"]["reactivity"] = "high"
g.nodes["ay"]["reactivity"] = "high"
g.nodes["by"]["reactivity"] = "high"
g.nodes["cy"]["reactivity"] = "high"
g.nodes["x"]["reactivity"] = "medium"
g.nodes["y"]["reactivity"] = "medium"
g.nodes["ix"]["reactivity"] = "high"
g.nodes["iy"]["reactivity"] = "high"
g.nodes["food1"]["reactivity"] = "medium"
g.nodes["food2"]["reactivity"] = "medium"
g.nodes["distractor"]["reactivity"] = "medium"
g.nodes["energy"]["reactivity"] = "low"
g.nodes["empty"]["reactivity"] = "background"
# The following commented line documents how to set the query config for a
# specific compound, overriding the default query configuration.
# g.nodes["food1"]["query_config"] = {"radius": 3, "queryType": "diamond"}
return g
ASCII_MAP = """
~~~~~~~~~~~a~~~~~~~~~~~~~
~~x~~~~~c~~~~~~~~~~~~~~~~
~~~~~~~~~~~b~~~~~~~x~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~1~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
1~~3~~~~hhhhhhh~~~~~3~~2~
~~~~~~~~~~~~~~~~~~~~~~~~~
~2~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~c~~~~~~~~~~~~~~~~~
~~x~~~~~~a~~~~~~~~~~~x~~~
~~~~~~~b~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# `prefab` determines which compound to use for each `char` in the ascii map.
CHAR_PREFAB_MAP = {
"~": "empty",
"a": "ax",
"b": "bx",
"c": "cx",
"1": "ay",
"2": "by",
"3": "cy",
"4": "az",
"5": "bz",
"6": "cz",
"x": "distractor",
"h": "energy",
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 60
PLAYER_COLOR_PALETTES = []
for i in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "ioAction": 0}
FORWARD = {"move": 1, "turn": 0, "ioAction": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "ioAction": 0}
BACKWARD = {"move": 3, "turn": 0, "ioAction": 0}
STEP_LEFT = {"move": 4, "turn": 0, "ioAction": 0}
TURN_LEFT = {"move": 0, "turn": -1, "ioAction": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "ioAction": 0}
IO_ACTION = {"move": 0, "turn": 0, "ioAction": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
IO_ACTION,
)
TARGET_SPRITE_SELF_EMPTY = {
"name": "SelfEmpty",
"shape": shapes.CYTOAVATAR_EMPTY,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
TARGET_SPRITE_SELF_HOLDS_ONE = {
"name": "SelfHoldsOne",
"shape": shapes.CYTOAVATAR_HOLDING_ONE,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
def create_avatar_objects(num_players, compounds):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
additional_game_objects = []
for player_idx in range(0, num_players):
game_object = graph_utils.create_avatar_constant_self_view(
rewarding_reactions=DEFAULT_REWARDING_REACTIONS,
player_idx=player_idx,
target_sprite_self_empty=TARGET_SPRITE_SELF_EMPTY,
target_sprite_self_holds_one=TARGET_SPRITE_SELF_HOLDS_ONE,
add_location_observer=_ENABLE_DEBUG_OBSERVATIONS)
avatar_objects.append(game_object)
# Add the overlaid avatar vesicle on top of each avatar.
avatar_vesicle = graph_utils.create_vesicle(
player_idx=player_idx,
compounds=compounds,
reactivity_levels=REACTIVITY_LEVELS["vesicle"],
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
additional_game_objects.append(avatar_vesicle)
return avatar_objects, additional_game_objects
def get_config():
"""Default configuration for this substrate."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(112, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate."""
del config
num_players = len(roles)
# Must create compounds and reactions.
compounds, reactions = graph_utils.graph_semantics(make_graph())
cell_prefabs = {}
cell_prefabs = graph_utils.add_compounds_to_prefabs_dictionary(
cell_prefabs, compounds, REACTIVITY_LEVELS["ground"], sprites=True,
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
avatar_objects, additional_objects = create_avatar_objects(num_players,
compounds)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="grid_land",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"].
simulation={
"map": ASCII_MAP,
"gameObjects": avatar_objects + additional_objects,
"scene": graph_utils.create_scene(reactions,
stochastic_episode_ending=True),
"prefabs": cell_prefabs,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/chemistry__two_metabolic_cycles_with_distractors.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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 substrates."""
from collections.abc import Mapping, Sequence, Set
import dataclasses
import functools
import importlib
from typing import Any
from ml_collections import config_dict
def _validated(build):
"""And adds validation checks to build function."""
def lab2d_settings_builder(
*,
config: config_dict.ConfigDict,
roles: Sequence[str],
) -> Mapping[str, Any]:
"""Builds the lab2d settings for the specified config and roles.
Args:
config: the meltingpot substrate config.
roles: the role for each corresponding player.
Returns:
The lab2d settings for the substrate.
"""
invalid_roles = set(roles) - config.valid_roles
if invalid_roles:
raise ValueError(f'Invalid roles: {invalid_roles!r}. Must be one of '
f'{config.valid_roles!r}')
return build(config=config, roles=roles)
return lab2d_settings_builder
def get_config(substrate: str) -> config_dict.ConfigDict:
"""Returns the specified config.
Args:
substrate: the name of the substrate. Must be in SUBSTRATES.
Raises:
ModuleNotFoundError: the config does not exist.
"""
if substrate not in SUBSTRATES:
raise ValueError(f'{substrate} not in {SUBSTRATES}.')
path = f'{__name__}.{substrate}'
module = importlib.import_module(path)
config = module.get_config()
with config.unlocked():
config.lab2d_settings_builder = _validated(module.build)
return config.lock()
SUBSTRATES: Set[str] = frozenset({
# keep-sorted start
'allelopathic_harvest__open',
'bach_or_stravinsky_in_the_matrix__arena',
'bach_or_stravinsky_in_the_matrix__repeated',
'boat_race__eight_races',
'chemistry__three_metabolic_cycles',
'chemistry__three_metabolic_cycles_with_plentiful_distractors',
'chemistry__two_metabolic_cycles',
'chemistry__two_metabolic_cycles_with_distractors',
'chicken_in_the_matrix__arena',
'chicken_in_the_matrix__repeated',
'clean_up',
'coins',
'collaborative_cooking__asymmetric',
'collaborative_cooking__circuit',
'collaborative_cooking__cramped',
'collaborative_cooking__crowded',
'collaborative_cooking__figure_eight',
'collaborative_cooking__forced',
'collaborative_cooking__ring',
'commons_harvest__closed',
'commons_harvest__open',
'commons_harvest__partnership',
'coop_mining',
'daycare',
'externality_mushrooms__dense',
'factory_commons__either_or',
'fruit_market__concentric_rivers',
'gift_refinements',
'hidden_agenda',
'paintball__capture_the_flag',
'paintball__king_of_the_hill',
'predator_prey__alley_hunt',
'predator_prey__open',
'predator_prey__orchard',
'predator_prey__random_forest',
'prisoners_dilemma_in_the_matrix__arena',
'prisoners_dilemma_in_the_matrix__repeated',
'pure_coordination_in_the_matrix__arena',
'pure_coordination_in_the_matrix__repeated',
'rationalizable_coordination_in_the_matrix__arena',
'rationalizable_coordination_in_the_matrix__repeated',
'running_with_scissors_in_the_matrix__arena',
'running_with_scissors_in_the_matrix__one_shot',
'running_with_scissors_in_the_matrix__repeated',
'stag_hunt_in_the_matrix__arena',
'stag_hunt_in_the_matrix__repeated',
'territory__inside_out',
'territory__open',
'territory__rooms',
# keep-sorted end
})
|
meltingpot-main
|
meltingpot/configs/substrates/__init__.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Pure Coordination in the Matrix (2 player, repeated).
Example video: https://youtu.be/biyhB378q58
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents a pure coordination game.
`K = 3`, three different resources corresponding to different coordination
outcomes.
Players have a `5 x 5` observation window.
The episode has a chance of ending stochastically on every 100 step interval
after step 1000. This usually allows time for 8 or more interactions.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 3
# This color is red.
RESOURCE1_COLOR = (150, 0, 0, 255)
RESOURCE1_HIGHLIGHT_COLOR = (200, 0, 0, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is green.
RESOURCE2_COLOR = (0, 150, 0, 255)
RESOURCE2_HIGHLIGHT_COLOR = (0, 200, 0, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# This color is blue.
RESOURCE3_COLOR = (0, 0, 150, 255)
RESOURCE3_HIGHLIGHT_COLOR = (0, 0, 200, 255)
RESOURCE3_COLOR_DATA = (RESOURCE3_COLOR, RESOURCE3_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn n nW
W WWW W W WW W
W W rra app W W
Wn WW rra app WW nW
W rra app W
W W
Wn WW n nW
W WWWW W
W ssa W W
Wn W ssa W aaa W nW
W W ssa W aaa WW W
W WWWW W W W WWW W
Wn n nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
"resource_class3",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"r": _resource_names[0],
"p": _resource_names[1],
"s": _resource_names[2],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 8
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
TARGET_SPRITE_OTHER = {
"name": "Other",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((200, 100, 50)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# 1 2 3
[1, 0, 0], # 1
[0, 1, 0], # 2
[0, 0, 1] # 3
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue # violet
(0.0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(
resource_id: int,
resource_shape: str,
resource_palette: Dict[str, Tuple[int, int, int, int]]):
"""Creates resource prefab with provided resource_id, shape, and palette."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [resource_shape],
"palettes": [resource_palette],
"noRotates": [True]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.02,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_avatar_object(
player_idx: int,
all_source_sprite_names: Sequence[str],
target_sprite_self: Dict[str, Any],
target_sprite_other: Dict[str, Any],
turn_off_default_reward: bool = False) -> Dict[str, Any]:
"""Create an avatar object given self vs other sprite data."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
for name in all_source_sprite_names:
if name != source_sprite_self:
custom_sprite_map[name] = target_sprite_other["name"]
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": [source_sprite_self],
# A white square should never be displayed. It will always be
# remapped since this is self vs other observation mode.
"spriteRGBColors": [(255, 255, 255, 255)],
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"],
target_sprite_other["name"]],
"customSpriteShapes": [target_sprite_self["shape"],
target_sprite_other["shape"]],
"customPalettes": [target_sprite_self["palette"],
target_sprite_other["palette"]],
"customNoRotates": [target_sprite_self["noRotate"],
target_sprite_other["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 5,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "SpawnResourcesWhenAllPlayersZapped",
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": turn_off_default_reward,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_prefabs():
"""Returns a dictionary mapping names to template game objects."""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(
1, shapes.BUTTON, {"*": RESOURCE1_COLOR_DATA[0],
"#": RESOURCE1_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class2"] = create_resource_prefab(
2, shapes.BUTTON, {"*": RESOURCE2_COLOR_DATA[0],
"#": RESOURCE2_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class3"] = create_resource_prefab(
3, shapes.BUTTON, {"*": RESOURCE3_COLOR_DATA[0],
"#": RESOURCE3_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
return prefabs
def get_all_source_sprite_names(num_players):
all_source_sprite_names = []
for player_idx in range(0, num_players):
# Lua is 1-indexed.
lua_index = player_idx + 1
all_source_sprite_names.append("Avatar" + str(lua_index))
return all_source_sprite_names
def create_avatar_objects(num_players,
turn_off_default_reward: bool = False):
"""Returns list of avatar objects of length 'num_players'."""
all_source_sprite_names = get_all_source_sprite_names(num_players)
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(
player_idx,
all_source_sprite_names,
TARGET_SPRITE_SELF,
TARGET_SPRITE_OTHER,
turn_off_default_reward=turn_off_default_reward)
avatar_objects.append(game_object)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def create_world_sprite_map(
num_players: int, target_sprite_other: Dict[str, Any]) -> Dict[str, str]:
all_source_sprite_names = get_all_source_sprite_names(num_players)
world_sprite_map = {}
for name in all_source_sprite_names:
world_sprite_map[name] = target_sprite_other["name"]
return world_sprite_map
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Other parameters that are useful to override in training config files.
config.turn_off_default_reward = False
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(3),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(3),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
# worldSpriteMap is needed to make the global view used in videos be
# be informative in cases where individual avatar views have had
# sprites remapped to one another (example: self vs other mode).
"worldSpriteMap": create_world_sprite_map(num_players,
TARGET_SPRITE_OTHER),
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/pure_coordination_in_the_matrix__repeated.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Prisoner's Dilemma in the Matrix.
Example video: https://youtu.be/81QrMpsP-HU
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Prisoner's Dilemma game.
`K = 2` resources represent "cooperate" and "defect" pure strategies.
Players have the default `11 x 11` (off center) observation window.
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is green.
RESOURCE1_COLOR = (30, 225, 185, 255)
RESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is red.
RESOURCE2_COLOR = (225, 30, 70, 255)
RESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# The procedural generator replaces all 'a' chars in the default map with chars
# representing specific resources, i.e. with either '1' or '2'.
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWW
WPPPP W W PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
W W
W 11 W
W 11 W
W aa W
W WW W 222 W
WW 1a W 222 W
WWW 1a WWWWWWWWW W
W 1a 111 WWW
W 111 W
W aa W W
W 22 W WW W
W 22 Waaa W
W 222 W
W W
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP W PPPPW
WWWWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"P": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 32
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# row player chooses a row of this matrix.
# C D
[3, 0], # C
[5, 1], # D
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# C D
[3, 5], # C
[0, 1], # D
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue # violet
(0.0, 1.0), (1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.15
}
}
]
}
return scene
def create_resource_prefab(resource_id, color_data):
"""Creates resource prefab with provided `resource_id` (num) and color."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": color_data[0],
"#": color_data[1],
"x": (0, 0, 0, 0)}],
"noRotates": [False]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.04,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)
prefabs["resource_class2"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)
return prefabs
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(colors.palette[player_idx])],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": False,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_avatar_objects(num_players: int) -> Sequence[PrefabConfig]:
"""Returns all game objects for the map.
Args:
num_players: number of players to create avatars for.
"""
avatar_objects = []
for player_idx in range(num_players):
avatar = create_avatar_object(player_idx, TARGET_SPRITE_SELF)
avatar_objects.append(avatar)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(192, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/prisoners_dilemma_in_the_matrix__arena.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Clean Up.
Example video: https://youtu.be/TqiJYxOwdxw
Clean Up is a seven player game. Players are rewarded for collecting apples. In
Clean Up, apples grow in an orchard at a rate inversely related to the
cleanliness of a nearby river. The river accumulates pollution at a constant
rate. The apple growth rate in the orchard drops to zero once the pollution
accumulates past a threshold value. Players have an additional action allowing
them to clean a small amount of pollution from the river in front of themselves.
They must physically leave the apple orchard to clean the river. Thus, players
must maintain a public good of high orchard regrowth rate through effortful
contributions. This is a public good provision problem because the benefit of a
healthy orchard is shared by all, but the costs incurred to ensure it exists are
born by individuals.
Players are also able to zap others with a beam that removes any player hit by
it from the game for 50 steps.
Clean Up was first described in Hughes et al. (2018).
Hughes, E., Leibo, J.Z., Phillips, M., Tuyls, K., Duenez-Guzman, E.,
Castaneda, A.G., Dunning, I., Zhu, T., McKee, K., Koster, R. and Roff, H., 2018,
Inequity aversion improves cooperation in intertemporal social dilemmas. In
Proceedings of the 32nd International Conference on Neural Information
Processing Systems (pp. 3330-3340).
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WHFFFHFFHFHFHFHFHFHFHHFHFFFHFW
WHFHFHFFHFHFHFHFHFHFHHFHFFFHFW
WHFFHFFHHFHFHFHFHFHFHHFHFFFHFW
WHFHFHFFHFHFHFHFHFHFHHFHFFFHFW
WHFFFFFFHFHFHFHFHFHFHHFHFFFHFW
W==============+~FHHHHHHf====W
W P P ===+~SSf W
W P P P <~Sf P W
W P P<~S> W
W P P <~S> P W
W P <~S>P W
W P P<~S> W
W P <~S> P W
W P P <~S> W
W^T^T^T^T^T^T^T^T^T;~S,^T^T^TW
WBBBBBBBBBBBBBBBBBBBssBBBBBBBW
WBBBBBBBBBBBBBBBBBBBBBBBBBBBBW
WBBBBBBBBBBBBBBBBBBBBBBBBBBBBW
WBBBBBBBBBBBBBBBBBBBBBBBBBBBBW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
"""
# Map a character to the prefab it represents in the ASCII map.
CHAR_PREFAB_MAP = {
"W": "wall",
" ": "sand",
"P": {"type": "all", "list": ["sand", "spawn_point"]},
"B": {"type": "all", "list": ["grass", "potential_apple"]},
"s": {"type": "all", "list": ["grass", "shadow_n"]},
"+": {"type": "all", "list": ["sand", "shadow_e", "shadow_n"]},
"f": {"type": "all", "list": ["sand", "shadow_w", "shadow_n"]},
";": {"type": "all", "list": ["sand", "grass_edge", "shadow_e"]},
",": {"type": "all", "list": ["sand", "grass_edge", "shadow_w"]},
"^": {"type": "all", "list": ["sand", "grass_edge",]},
"=": {"type": "all", "list": ["sand", "shadow_n",]},
">": {"type": "all", "list": ["sand", "shadow_w",]},
"<": {"type": "all", "list": ["sand", "shadow_e",]},
"~": {"type": "all", "list": ["river", "shadow_w",]},
"T": {"type": "all", "list": ["sand", "grass_edge", "potential_apple"]},
"S": "river",
"H": {"type": "all", "list": ["river", "potential_dirt"]},
"F": {"type": "all", "list": ["river", "actual_dirt"]},
}
_COMPASS = ["N", "E", "S", "W"]
SAND = {
"name": "sand",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sand",
"stateConfigs": [{
"state": "sand",
"layer": "background",
"sprite": "Sand",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Sand"],
"spriteShapes": [shapes.GRAINY_FLOOR],
"palettes": [{"+": (222, 221, 189, 255),
"*": (219, 218, 186, 255)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
GRASS = {
"name": "grass",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "grass",
"stateConfigs": [{
"state": "grass",
"layer": "background",
"sprite": "Grass",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Grass"],
"spriteShapes": [shapes.GRASS_STRAIGHT],
"palettes": [{"*": (164, 189, 75, 255),
"@": (182, 207, 95, 255),
"x": (0, 0, 0, 0)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
GRASS_EDGE = {
"name": "grass_edge",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "grass_edge",
"stateConfigs": [{
"state": "grass_edge",
"layer": "lowerPhysical",
"sprite": "GrassEdge",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["GrassEdge"],
"spriteShapes": [shapes.GRASS_STRAIGHT_N_EDGE],
"palettes": [{"*": (164, 189, 75, 255),
"@": (182, 207, 95, 255),
"x": (0, 0, 0, 0)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
SHADOW_W = {
"name": "shadow_w",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "shadow_w",
"stateConfigs": [{
"state": "shadow_w",
"layer": "upperPhysical",
"sprite": "ShadowW",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ShadowW"],
"spriteShapes": [shapes.SHADOW_W],
"palettes": [shapes.SHADOW_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
SHADOW_E = {
"name": "shadow_e",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "shadow_e",
"stateConfigs": [{
"state": "shadow_e",
"layer": "upperPhysical",
"sprite": "ShadowE",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ShadowE"],
"spriteShapes": [shapes.SHADOW_E],
"palettes": [shapes.SHADOW_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
SHADOW_N = {
"name": "shadow_n",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "shadow_n",
"stateConfigs": [{
"state": "shadow_n",
"layer": "overlay",
"sprite": "ShadowN",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ShadowN"],
"spriteShapes": [shapes.SHADOW_N],
"palettes": [shapes.SHADOW_PALETTE],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "superOverlay",
"sprite": "Wall",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "zapHit"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "cleanHit"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
POTENTIAL_APPLE = {
"name": "potentialApple",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "appleWait",
"stateConfigs": [
{
"state": "apple",
"sprite": "Apple",
"layer": "upperPhysical",
},
{
"state": "appleWait"
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Apple"],
"spriteShapes": [shapes.APPLE],
"palettes": [{
"x": (0, 0, 0, 0),
"*": (212, 80, 57, 255),
"#": (173, 66, 47, 255),
"o": (43, 127, 53, 255),
"|": (79, 47, 44, 255)}],
"noRotates": [True]
}
},
{
"component": "Edible",
"kwargs": {
"liveState": "apple",
"waitState": "appleWait",
"rewardForEating": 1.0,
}
},
{
"component": "AppleGrow",
"kwargs": {
"maxAppleGrowthRate": 0.05,
"thresholdDepletion": 0.4,
"thresholdRestoration": 0.0,
}
}
]
}
def create_dirt_prefab(initial_state):
"""Create a dirt prefab with the given initial state."""
dirt_prefab = {
"name": "DirtContainer",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{
"state": "dirtWait",
"layer": "logic",
},
{
"state": "dirt",
"layer": "upperPhysical",
"sprite": "Dirt",
},
],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"spriteNames": ["Dirt"],
# This color is greenish, and quite transparent to expose the
# animated water below.
"spriteRGBColors": [(2, 245, 80, 50)],
}
},
{
"component": "DirtTracker",
"kwargs": {
"activeState": "dirt",
"inactiveState": "dirtWait",
}
},
{
"component": "DirtCleaning",
"kwargs": {}
},
]
}
return dirt_prefab
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0, "fireClean": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0, "fireClean": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0, "fireClean": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0, "fireClean": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0, "fireClean": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0, "fireClean": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0, "fireClean": 0}
FIRE_ZAP = {"move": 0, "turn": 0, "fireZap": 1, "fireClean": 0}
FIRE_CLEAN = {"move": 0, "turn": 0, "fireZap": 0, "fireClean": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP,
FIRE_CLEAN
)
# Remove the first entry from human_readable_colors after using it for the self
# color to prevent it from being used again as another avatar color.
human_readable_colors = list(colors.human_readable)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette(human_readable_colors.pop(0)),
"noRotate": True,
}
def get_water():
"""Get an animated water game object."""
layer = "background"
water = {
"name": "water_{}".format(layer),
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "water_1",
"stateConfigs": [
{"state": "water_1",
"layer": layer,
"sprite": "water_1",
"groups": ["water"]},
{"state": "water_2",
"layer": layer,
"sprite": "water_2",
"groups": ["water"]},
{"state": "water_3",
"layer": layer,
"sprite": "water_3",
"groups": ["water"]},
{"state": "water_4",
"layer": layer,
"sprite": "water_4",
"groups": ["water"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["water_1", "water_2", "water_3", "water_4"],
"spriteShapes": [shapes.WATER_1, shapes.WATER_2,
shapes.WATER_3, shapes.WATER_4],
"palettes": [{
"@": (66, 173, 212, 255),
"*": (35, 133, 168, 255),
"o": (34, 129, 163, 255),
"~": (33, 125, 158, 255),}] * 4,
}
},
{
"component": "Animation",
"kwargs": {
"states": ["water_1", "water_2", "water_3", "water_4"],
"gameFramesPerAnimationFrame": 2,
"loop": True,
"randomStartFrame": True,
"group": "water",
}
},
]
}
return water
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"sand": SAND,
"grass": GRASS,
"grass_edge": GRASS_EDGE,
"shadow_w": SHADOW_W,
"shadow_e": SHADOW_E,
"shadow_n": SHADOW_N,
"spawn_point": SPAWN_POINT,
"potential_apple": POTENTIAL_APPLE,
"river": get_water(),
"potential_dirt": create_dirt_prefab("dirtWait"),
"actual_dirt": create_dirt_prefab("dirt"),
}
return prefabs
def create_scene():
"""Create the scene object, a non-physical object to hold global logic."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "RiverMonitor",
"kwargs": {},
},
{
"component": "DirtSpawner",
"kwargs": {
"dirtSpawnProbability": 0.5,
"delayStartOfDirtSpawning": 50,
},
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
},
{
"component": "GlobalData",
},
]
}
return scene
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": f"avatar{lua_index}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{"state": live_state_name,
"layer": "superOverlay",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
# Player wait type for times when they are zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(
human_readable_colors[player_idx])],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": ["move",
"turn",
"fireZap",
"fireClean"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 1},
"fireClean": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
}
},
{
"component": "Zapper",
"kwargs": {
"cooldownTime": 10,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"penaltyForBeingZapped": 0,
"rewardForZapping": 0,
"removeHitPlayer": True,
}
},
{
"component": "ReadyToShootObservation",
},
{
"component": "Cleaner",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
}
},
{
"component": "Taste",
"kwargs": {
"role": "free",
"rewardAmount": 1,
}
},
{
"component": "AllNonselfCumulants",
},
]
}
# Signals needed for puppeteers.
metrics = [
{
"name": "NUM_OTHERS_WHO_CLEANED_THIS_STEP",
"type": "Doubles",
"shape": [],
"component": "AllNonselfCumulants",
"variable": "num_others_who_cleaned_this_step",
},
]
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
# Debug metrics
metrics.append({
"name": "PLAYER_CLEANED",
"type": "Doubles",
"shape": [],
"component": "Cleaner",
"variable": "player_cleaned",
})
metrics.append({
"name": "PLAYER_ATE_APPLE",
"type": "Doubles",
"shape": [],
"component": "Taste",
"variable": "player_ate_apple",
})
metrics.append({
"name": "NUM_OTHERS_PLAYER_ZAPPED_THIS_STEP",
"type": "Doubles",
"shape": [],
"component": "Zapper",
"variable": "num_others_player_zapped_this_step",
})
metrics.append({
"name": "NUM_OTHERS_WHO_ATE_THIS_STEP",
"type": "Doubles",
"shape": [],
"component": "AllNonselfCumulants",
"variable": "num_others_who_ate_this_step",
})
# Add the metrics reporter.
avatar_object["components"].append({
"component": "AvatarMetricReporter",
"kwargs": {"metrics": metrics}
})
return avatar_object
def create_avatar_objects(num_players):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(player_idx,
TARGET_SPRITE_SELF)
avatar_objects.append(game_object)
return avatar_objects
def get_config():
"""Default configuration for the clean_up level."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
# Global switching signals for puppeteers.
"NUM_OTHERS_WHO_CLEANED_THIS_STEP",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Global switching signals for puppeteers.
"NUM_OTHERS_WHO_CLEANED_THIS_STEP": specs.float64(),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(168, 240),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 7
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build the clean_up substrate given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="clean_up",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/clean_up.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for the Fruit Market substrate.
This substrate is used to study the dynamics of trade and bargaining of goods
that have different value to different players.
The substrate consists of an open space where two types of trees exist: apple
trees and banana trees. Trees can be harvested by players by stepping on their
location and wait until they harvest the fruit from the tree. A harvested fruit
(apple or banana) goes into a player's inventory. Players can carry any number
of apples or bananas. Harvested fruit can be consumed for reward. Players have
two actions to consume fruit of the two types from their inventory.
Players can be of two types: apple farmer & banana farmer. Apple farmers have a
higher probability of harvesting from apple trees than banana trees, but receive
more reward for consuming bananas. Banana farmers are the opposite.
Players have a hunger meter which can be replenished by consuming a fruit.
Players have an action to consume an apple from their inventory, and another to
consume a banana. If the hunger meter reaches zero the player pays a
substantial cost in stamina.
Crossing water also imposes a cost in stamina.
Players also have trading actions of the form "I offer X apples for Y bananas"
and the converse "I offer Z bananas for W apples". When players are within a
trading radius of each other and have corresponding offers (`X = W` and `Y = Z`)
and enough fruit in their inventories to satisfy it, the trade occurs and the
appropriate number of apples and bananas are exchanged and placed in their
inventories.
"""
import copy
from typing import Any, Dict, Generator, Mapping, Sequence
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from ml_collections import config_dict as configdict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
MAX_OFFER_QUANTITY = 3
_COMPASS = ["N", "E", "S", "W"]
INVISIBLE = (0, 0, 0, 0)
NW_WALL_CORNER = {
"name": "nw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_wall_corner",
"stateConfigs": [{
"state": "nw_wall_corner",
"layer": "upperPhysical",
"sprite": "NwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwWallCorner"],
"spriteShapes": [shapes.FENCE_NW_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
NE_WALL_CORNER = {
"name": "ne_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_wall_corner",
"stateConfigs": [{
"state": "ne_wall_corner",
"layer": "upperPhysical",
"sprite": "NeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeWallCorner"],
"spriteShapes": [shapes.FENCE_NE_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
NE_INNER_WALL_CORNER = {
"name": "ne_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_inner_wall_corner",
"stateConfigs": [{
"state": "ne_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "ne_inner_wall_corner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ne_inner_wall_corner"],
"spriteShapes": [shapes.FENCE_INNER_NE_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
NW_INNER_WALL_CORNER = {
"name": "nw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_inner_wall_corner",
"stateConfigs": [{
"state": "nw_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "nw_inner_wall_corner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["nw_inner_wall_corner"],
"spriteShapes": [shapes.FENCE_INNER_NW_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
SE_WALL_CORNER = {
"name": "se_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_wall_corner",
"stateConfigs": [{
"state": "se_wall_corner",
"layer": "upperPhysical",
"sprite": "SeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeWallCorner"],
"spriteShapes": [shapes.FENCE_SE_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
SW_WALL_CORNER = {
"name": "sw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_wall_corner",
"stateConfigs": [{
"state": "sw_wall_corner",
"layer": "upperPhysical",
"sprite": "SwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwWallCorner"],
"spriteShapes": [shapes.FENCE_SW_CORNER],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_SHADOW_SW = {
"name": "wall_shadow_sw",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_sw",
"stateConfigs": [{
"state": "wall_shadow_sw",
"layer": "upperPhysical",
"sprite": "wall_shadow_sw",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_sw"],
"spriteShapes": [shapes.FENCE_SHADOW_SW],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_SHADOW_S = {
"name": "wall_shadow_s",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_s",
"stateConfigs": [{
"state": "wall_shadow_s",
"layer": "upperPhysical",
"sprite": "wall_shadow_s",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_s"],
"spriteShapes": [shapes.FENCE_SHADOW_S],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_SHADOW_SE = {
"name": "wall_shadow_se",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_se",
"stateConfigs": [{
"state": "wall_shadow_se",
"layer": "upperPhysical",
"sprite": "wall_shadow_se",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_se"],
"spriteShapes": [shapes.FENCE_SHADOW_SE],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_NORTH = {
"name": "wall_north",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_north",
"stateConfigs": [{
"state": "wall_north",
"layer": "upperPhysical",
"sprite": "WallNorth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallNorth"],
"spriteShapes": [shapes.FENCE_N],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_EAST = {
"name": "wall_east",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_east",
"stateConfigs": [{
"state": "wall_east",
"layer": "upperPhysical",
"sprite": "WallEast",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallEast"],
"spriteShapes": [shapes.FENCE_E],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_SOUTH = {
"name": "wall_south",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_south",
"stateConfigs": [{
"state": "wall_south",
"layer": "upperPhysical",
"sprite": "WallSouth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallSouth"],
"spriteShapes": [shapes.FENCE_S],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
WALL_WEST = {
"name": "wall_west",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_west",
"stateConfigs": [{
"state": "wall_west",
"layer": "upperPhysical",
"sprite": "WallWest",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallWest"],
"spriteShapes": [shapes.FENCE_W],
"palettes": [shapes.FENCE_PALETTE],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
STONE_WALL = {
"name": "stone_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "stoneWall",
"stateConfigs": [{
"state": "stoneWall",
"layer": "upperPhysical",
"sprite": "StoneWall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["StoneWall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "hold"}},
{"component": "BeamBlocker", "kwargs": {"beamType": "shove"}},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
def get_water():
"""Get an animated water game object."""
layer = "background"
water = {
"name": "water_{}".format(layer),
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "water_1",
"stateConfigs": [
{"state": "water_1",
"layer": layer,
"sprite": "water_1",
"groups": ["water"]},
{"state": "water_2",
"layer": layer,
"sprite": "water_2",
"groups": ["water"]},
{"state": "water_3",
"layer": layer,
"sprite": "water_3",
"groups": ["water"]},
{"state": "water_4",
"layer": layer,
"sprite": "water_4",
"groups": ["water"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["water_1", "water_2", "water_3", "water_4"],
"spriteShapes": [shapes.WATER_1, shapes.WATER_2,
shapes.WATER_3, shapes.WATER_4],
"palettes": [{
"@": (52, 193, 209, 255),
"*": (34, 166, 181, 255),
"o": (32, 155, 168, 255),
"~": (31, 148, 161, 255)}] * 4,
}
},
{
"component": "Animation",
"kwargs": {
"states": ["water_1", "water_2", "water_3", "water_4"],
"gameFramesPerAnimationFrame": 2,
"loop": True,
"randomStartFrame": True,
"group": "water",
}
},
{
"component": "TraversalCost",
"kwargs": {
"penaltyAmount": 0, # No reward cost from crossing water.
"alsoReduceStamina": True, # Crossing water depletes stamina.
"staminaPenaltyAmount": 1, # Stamina lost per step on water.
}
},
]
}
return water
GROUND = {
"name": "ground",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ground",
"stateConfigs": [{
"state": "ground",
"layer": "background",
"sprite": "groundSprite",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["groundSprite"],
"spriteShapes": [shapes.DIRT_PATTERN],
"palettes": [{"X": (207, 199, 184, 255),
"x": (199, 192, 177, 255),}],
"noRotates": [True]
}
},
]
}
def get_fruit_tree_palette(fruit_type):
"""Return a palette with the correct colored fruit."""
apple_palette = copy.deepcopy(shapes.APPLE_TREE_PALETTE)
banana_palette = copy.deepcopy(shapes.BANANA_TREE_PALETTE)
if fruit_type == "ripe_apple":
apple_palette["o"] = (199, 33, 8, 255)
return apple_palette
elif fruit_type == "ripe_banana":
banana_palette["o"] = (222, 222, 13, 255)
return banana_palette
elif fruit_type == "unripe_apple":
apple_palette["o"] = (124, 186, 58, 255)
return apple_palette
elif fruit_type == "unripe_banana":
banana_palette["o"] = (37, 115, 45, 255)
return banana_palette
def get_potential_tree(probability_empty: float = 0.9,
probability_apple: float = 0.05,
probability_banana: float = 0.05) -> PrefabConfig:
"""Return a prefab for a potential tree."""
assert probability_empty + probability_apple + probability_banana == 1.0, (
"Probabilities must sum to 1.0.")
spawn_probabilities = {"empty": probability_empty,
"apple": probability_apple,
"banana": probability_banana}
prefab = {
"name": "potential_tree",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "treeWait",
"stateConfigs": [
{"state": "treeWait"},
{
"state": "appleTreeHarvestable",
"layer": "lowerPhysical",
"sprite": "appleTreeHarvestableSprite",
},
{
"state": "bananaTreeHarvestable",
"layer": "lowerPhysical",
"sprite": "bananaTreeHarvestableSprite",
},
{
"state": "appleTreeUnripe",
"layer": "lowerPhysical",
"sprite": "appleTreeUnripeSprite",
},
{
"state": "bananaTreeUnripe",
"layer": "lowerPhysical",
"sprite": "bananaTreeUnripeSprite",
},
],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["appleTreeHarvestableSprite",
"bananaTreeHarvestableSprite",
"appleTreeUnripeSprite",
"bananaTreeUnripeSprite"],
"spriteShapes": [shapes.APPLE_TREE_STOUT,
shapes.BANANA_TREE,
shapes.APPLE_TREE_STOUT,
shapes.BANANA_TREE],
"palettes": [get_fruit_tree_palette("ripe_apple"),
get_fruit_tree_palette("ripe_banana"),
get_fruit_tree_palette("unripe_apple"),
get_fruit_tree_palette("unripe_banana")],
"noRotates": [True,
True,
True,
True]
}
},
{
"component": "FruitType",
"kwargs": {
"probabilities": spawn_probabilities,
}
},
{
"component": "Harvestable",
"kwargs": {
"regrowthTime": 50,
}
},
{
"component": "PreventStaminaRecoveryHere",
},
]
}
return prefab
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
FORWARD = {"move": 1, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
BACKWARD = {"move": 3, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
STEP_LEFT = {"move": 4, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
TURN_LEFT = {"move": 0, "turn": -1, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
EAT_APPLE = {"move": 0, "turn": 0, "eat_apple": 1, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
EAT_BANANA = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 1, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 0, "shove": 0}
HOLD = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 1, "shove": 0}
# Notice that SHOVE includes both `hold` and `shove` parts.
SHOVE = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 1, "shove": 1}
PULL = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0, "offer_apple": 0, "offer_banana": 0, "offer_cancel": 0, "hold": 1, "shove": -1}
# pyformat: enable
# pylint: enable=bad-whitespace
offer_actions = []
# Add the cancel action
cancel_action = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0,
"offer_apple": 0, "offer_banana": 0, "offer_cancel": 1,
"hold": 0, "shove": 0}
offer_actions.append(cancel_action)
for a in range(-MAX_OFFER_QUANTITY, MAX_OFFER_QUANTITY):
for b in range(-MAX_OFFER_QUANTITY, MAX_OFFER_QUANTITY):
offer_action = {"move": 0, "turn": 0, "eat_apple": 0, "eat_banana": 0,
"offer_apple": a, "offer_banana": b, "offer_cancel": 0,
"hold": 0, "shove": 0}
if a > 0 and b < 0:
offer_actions.append(offer_action)
elif a < 0 and b > 0:
offer_actions.append(offer_action)
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
EAT_APPLE,
EAT_BANANA,
HOLD,
SHOVE,
PULL,
*offer_actions,
)
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
# wall prefabs
"nw_wall_corner": NW_WALL_CORNER,
"nw_inner_wall_corner": NW_INNER_WALL_CORNER,
"ne_wall_corner": NE_WALL_CORNER,
"ne_inner_wall_corner": NE_INNER_WALL_CORNER,
"se_wall_corner": SE_WALL_CORNER,
"sw_wall_corner": SW_WALL_CORNER,
"wall_north": WALL_NORTH,
"wall_east": WALL_EAST,
"wall_south": WALL_SOUTH,
"wall_west": WALL_WEST,
"wall_shadow_sw": WALL_SHADOW_SW,
"wall_shadow_s": WALL_SHADOW_S,
"wall_shadow_se": WALL_SHADOW_SE,
"stone_wall": STONE_WALL,
# non-wall prefabs
"spawn_point": SPAWN_POINT,
"river": get_water(),
"ground": GROUND,
"potential_tree": get_potential_tree(),
"high_probability_tree": get_potential_tree(
probability_empty=0.1,
probability_apple=0.45,
probability_banana=0.45,
),
}
return prefabs
def create_scene():
"""Create the scene object, a non-physical object to hold global logic."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TradeManager",
},
]
}
return scene
def _create_stamina_overlay(player_idx: int,
max_stamina_bar_states: int,
) -> Generator[Dict[str, Any], None, None]:
"""Create stamina marker overlay objects."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
stamina_bar_state_configs = [
# Invisible inactive (dead) overlay type.
{"state": "staminaBarWait"},
]
stamina_bar_sprite_names = []
stamina_bar_sprite_shapes = []
# Each player's stamina bars must be in their own layer so they do not
# interact/collide with other players' stamina bars.
stamina_bar_layer = f"superOverlay_{player_idx}"
# Declare one state per level of the stamina bar.
for i in range(max_stamina_bar_states):
sprite_name = f"sprite_for_level_{i}"
stamina_bar_state_configs.append(
{"state": f"level_{i}",
"layer": stamina_bar_layer,
"sprite": sprite_name})
stamina_bar_sprite_names.append(sprite_name)
xs = "\nxxxxxxxx"
blank_space = xs * 7
number_of_rs = max(6 - i, 0)
number_of_ys = i if i < 7 else 12 - i
number_of_gs = max(i - 6, 0)
if i >= 13:
level = blank_space + xs
else:
level = (blank_space + "\nx" + "G" * number_of_gs + "Y" * number_of_ys +
"R" * number_of_rs + "x")
empty = "\n".join(["x" * 8] * 8)
# Replace the east/south/west sprites with invisible sprites so the only
# stamina bar rendered is the one in the direction that the current player
# is facing.
stamina_bar_sprite_shapes.append((level, empty, empty, empty))
# Create a stamina bar for each compass direction. Only the direction the
# current player is facing is visible.
for direction in ("N", "E", "S", "W"):
yield {
"name": "avatar_stamina_bar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "staminaBarWait",
"stateConfigs": stamina_bar_state_configs
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": stamina_bar_sprite_names,
"spriteShapes": stamina_bar_sprite_shapes,
"palettes": [{"G": (62, 137, 72, 255),
"Y": (255, 216, 97, 255),
"R": (162, 38, 51, 255),
"x": INVISIBLE,}] * max_stamina_bar_states,
"noRotates": [True] * max_stamina_bar_states
}
},
{
"component": "StaminaBar",
"kwargs": {
"playerIndex": lua_idx,
"waitState": "staminaBarWait",
"layer": stamina_bar_layer,
"direction": direction
}
},
]
}
def create_avatar_object(player_idx: int,
specialty: str,
max_stamina_bar_states: int) -> Dict[str, Any]:
"""Create an avatar object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
source_sprite_self = "Avatar" + str(lua_index)
grappling_sprite = "AvatarGrappling" + str(lua_index)
grappled_sprite = "AvatarGrappled" + str(lua_index)
live_state_name = "player{}".format(lua_index)
grappling_state_name = f"player{lua_index}_grappling"
grappled_state_name = f"player{lua_index}_grappled"
map_specialty_to_sprite_color = {
"apple": (199, 55, 47), # apple red
"banana": (255, 225, 53), # banana yellow
}
avatar_color = map_specialty_to_sprite_color[specialty]
avatar_palette = shapes.get_palette(avatar_color)
avatar_palette["P"] = (196, 77, 190, 200)
avatar_palette["p"] = (184, 72, 178, 150)
map_specialty_to_complement = {
"apple": "banana",
"banana": "apple"
}
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": grappling_state_name,
"layer": "upperPhysical",
"sprite": grappling_sprite,
"contact": "avatar",
"groups": ["players"]},
{"state": grappled_state_name,
"layer": "upperPhysical",
"sprite": grappled_sprite,
"contact": "avatar",
"groups": ["players"]},
# Player wait type for times when they are zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self, grappling_sprite,
grappled_sprite],
"spriteShapes": [shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR_ARMS_UP,
shapes.MAGIC_GRAPPLED_AVATAR],
"palettes": [avatar_palette] * 3,
"noRotates": [True] * 3,
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"additionalLiveStates": [grappled_state_name,
grappling_state_name],
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": [
# Basic movement actions
"move",
"turn",
# Trade actions
"eat_apple",
"eat_banana",
"offer_apple",
"offer_banana",
"offer_cancel",
# Grappling actions
"hold",
"shove",
],
"actionSpec": {
# Basic movement actions
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
# Trade actions
"eat_apple": {"default": 0, "min": 0, "max": 1},
"eat_banana": {"default": 0, "min": 0, "max": 1},
"offer_apple": {"default": 0, "min": -MAX_OFFER_QUANTITY,
"max": MAX_OFFER_QUANTITY},
"offer_banana": {"default": 0, "min": -MAX_OFFER_QUANTITY,
"max": MAX_OFFER_QUANTITY},
"offer_cancel": {"default": 0, "min": 0, "max": 1},
# Grappling actions
"hold": {"default": 0, "min": 0, "max": 1},
"shove": {"default": 0, "min": -1, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "Inventory",
},
{
"component": "Eating",
},
{
"component": "Specialization",
"kwargs": {
"specialty": specialty, # "apple" or "banana"
"strongAmount": 2,
"weakAmount": 2,
"strongProbability": 1,
"weakProbability": 0.04,
}
},
{
"component": "Trading",
"kwargs": {
"maxOfferQuantity": 3, # The highest possible offer.
"radius": 4, # Size of neighborhood where trade is possible.
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyFruit": map_specialty_to_complement[specialty],
"mostTastyReward": 8,
"defaultReward": 1,
}
},
{
"component": "PeriodicNeed", # The hunger mechanic
"kwargs": {
# Hunger threshold reached after `delay` steps without eating.
"delay": 50,
# No reward cost of hunger exceeding threshold.
"reward": 0,
},
},
{
"component": "Grappling",
"kwargs": {
"shape": shapes.MAGIC_BEAM,
"palette": shapes.MAGIC_BEAM_PALETTE,
"liveState": live_state_name,
"grappledState": grappled_state_name,
"grapplingState": grappling_state_name,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
# In this case READY_TO_SHOOT will be 1 if hold is allowed and
# will be 0 if not.
"zapperComponent": "Grappling",
}
},
{
"component": "Stamina",
"kwargs": {
"maxStamina": max_stamina_bar_states,
"classConfig": {
"name": "player",
"greenFreezeTime": 0,
"yellowFreezeTime": 2,
"redFreezeTime": 6,
# `decrementRate` = 0.5 means decrease stamina on every
# other costly step. `decrementRate` = 1 means decrease
# stamina on every costly step.
"decrementRate": 0.5,
},
"amountInvisible": 6,
"amountGreen": 6,
"amountYellow": 6,
"amountRed": 1,
"costlyActions": ["move"],
}
},
{
"component": "StaminaModulatedByNeed",
"kwargs": {
# Reduce stamina by `lossPerStepBeyondThreshold` per timestep
# after hunger exceeds its threshold.
"lossPerStepBeyondThreshold": 1,
}
},
{
"component": "StaminaObservation",
"kwargs": {
"staminaComponent": "Stamina",
}
},
{
"component": "InventoryObserver",
},
{
"component": "MyOfferObserver",
},
{
"component": "AllOffersObserver",
"kwargs": {
"flatten": True,
}
},
{
"component": "HungerObserver",
"kwargs": {
"needComponent": "PeriodicNeed",
},
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_avatar_objects(roles: Sequence[str],
max_stamina_bar_states: int = 19):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
for player_idx, role in enumerate(roles):
if role == "default":
# If no role was passed then set even numbered players to be banana
# farmers and odd numbered players to be apple farmers.
if player_idx % 2 == 1:
specialty = "apple"
elif player_idx % 2 == 0:
specialty = "banana"
else:
if role == "apple_farmer":
specialty = "apple"
elif role == "banana_farmer":
specialty = "banana"
game_object = create_avatar_object(player_idx,
specialty,
max_stamina_bar_states - 1)
stamina_bar_objects = _create_stamina_overlay(player_idx,
max_stamina_bar_states)
avatar_objects.append(game_object)
avatar_objects.extend(stamina_bar_objects)
return avatar_objects
def get_config():
"""Default configuration for the Fruit Market game."""
config = configdict.ConfigDict()
# Specify the number of players to particate in each episode (optional).
config.recommended_num_players = 16
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
"STAMINA",
"INVENTORY",
"MY_OFFER",
"OFFERS",
"HUNGER",
]
config.global_observation_names = [
"WORLD.RGB",
]
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate given player roles."""
substrate_definition = dict(
levelName="trade",
levelDirectory="meltingpot/lua/levels",
numPlayers=len(roles),
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": config.layout.ascii_map,
"gameObjects": create_avatar_objects(roles),
"prefabs": create_prefabs(),
"charPrefabMap": config.layout.char_prefab_map,
"scene": create_scene(),
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/fruit_market.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for hidden_agenda.
Example video: https://youtu.be/voJWckiOh5k
A social deduction (sometimes also called 'hidden role') game where players can
have one of two roles: crewmates and impostors. All players with the same role
are in the same team. The game is a zero-sum competitive game across teams, that
is, all players in the team get the same reward, and their reward is the
negative of the reward for the other team. The roles are hidden (hence the name)
and must be inferred from observations. The crewmates have a numeric advantage
(4 players), while the impostor (1 player) have an information advantage (they
know the roles of every player).
Players can move around a 2D world which contains gems that can be picked up by
walking over them, a deposit in the center of the map (a grate) where collected
gems can be dropped, and a voting room where rounds of deliberation occur (see
below).
Crewmates can carry up to two gems in their inventory at the same time. The gems
must be deposited in the grate before more gems can be collected. Impostors have
a freezing beam that they can use to freeze crewmates. Frozen crewmates are
unable to move or take any action for the rest of the episode.
After a predefined time (200 steps) or whenever an impostor fires its beam
within the field of view of another player (and is not frozen by it) a
deliberation phase starts. During deliberation, players are teleported to the
deliberation room, where they cannot take any movement or firing actions. Their
actions are limited to voting actions. Votes can be for any of the player
indices (0 to 4), 'abstain', or 'no-vote' (if the player is frozen or voted
out). The deliberation phase lasts 25 steps and players are able to change their
vote at any point. If there is a simple majority in the last step of the
deliberation, the player is voted out and removed from the game. Players can
observe the voting of every other player as a special observation called
`VOTING`. Episodes last up to 3000 steps.
The game has several win conditions:
1. The crewmembers deposit enough gems (32). Crewmates win.
2. The impostor is voted out during the deliberation phase. Crewmates win.
3. There is only one crewmate active (i.e. not voted out nor frozen). Impostor
wins.
If neither of the above conditions are met before the episode ends, the game is
considered a tie, and players get zero reward.
"""
import copy
from typing import Any, Mapping, Sequence
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# This substrate only makes sense with exactly five players.
MANDATED_NUM_PLAYERS = 5
# Hidden Agenda palette for player slots
HIDDEN_AGENDA_COLORS = [
(37, 133, 190), # light blue
(133, 37, 190), # indigo
(255, 95, 10), # orange
(37, 190, 133), # sea green
(220, 40, 110), # salmon pink
(180, 180, 0), # golden yellow
(133, 190, 37), # lime green
(135, 73, 124), # dark pink-purple
(140, 115, 105), # light brown
]
# Dictionary mapping the characters in the map with prefabs.
CHAR_PREFAB_MAP = {
"*": {"type": "all", "list": ["checkered_flooring", "spawn_point"]},
"V": {"type": "all", "list": ["tiled_flooring1", "voting_spawn_point"]},
"D": {"type": "all", "list": ["tiled_floor", "teleport_spawn_point"]},
"F": "nw_wall_corner",
"7": "ne_wall_corner",
"J": "se_wall_corner",
"L": "sw_wall_corner",
"[": "w_ship_solid_wall",
"]": "e_ship_solid_wall",
"^": "n_ship_solid_wall",
"v": "s_ship_solid_wall",
"-": "wall_north",
"T": "tcoupling_n",
"Z": "tcoupling_e",
"i": "tcoupling_s",
"t": "tcoupling_w",
"|": "wall_west",
"f": "fill",
",": {"type": "all", "list": ["nw_grate", "gem_deposit"]},
"_": {"type": "all", "list": ["n_grate", "gem_deposit"]},
";": {"type": "all", "list": ["ne_grate", "gem_deposit"]},
"!": {"type": "all", "list": ["w_grate", "gem_deposit"]},
"=": {"type": "all", "list": ["inner_grate", "gem_deposit"]},
"1": {"type": "all", "list": ["e_grate", "gem_deposit"]},
"+": {"type": "all", "list": ["se_grate", "gem_deposit"]},
"'": {"type": "all", "list": ["s_grate", "gem_deposit"]},
"`": {"type": "all", "list": ["sw_grate", "gem_deposit"]},
"/": {"type": "all", "list": ["tiled_floor", "glass_wall"]},
"n": "tiled_floor",
"U": "tiled_flooring1",
"u": "tiled_flooring2",
"m": "metal_flooring",
"e": "metal_panel_flooring",
"x": "checkered_flooring",
"w": "wood_flooring",
"~": "threshold",
"%": {"type": "all", "list": ["metal_panel_flooring", "gem"]},
"@": {"type": "all", "list": ["metal_flooring", "gem"]},
"&": {"type": "all", "list": ["wood_flooring", "gem"]},
"#": {"type": "all", "list": ["tiled_floor", "gem"]},
}
ASCII_MAP = """
F----------^^-------^^----------7
|@mmmmmmmmm[]DDDDDDD[]mmmmmmmmmm|
|mmmmmm@mmm[]///////[]mm@mmm@mmm|
|m@mmmm@mmm|UuVuVuVuU|mmmmm@mmm@|
|mmmm@mm@mm|uVuUuUuVu|mmmmm@mmmm|
|m@mmm@mmmm|UuVuUuVuU|mm@mmmmm@m|
|mm@m@mm@mm|uUuVuVuUu|mm@mm@mmmm|
t-~~~~~~~~-i---------i-~~~~~~~~-Z
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
|xxxxxxxxxx*xx,___;xx*xxxxxxxxxx|
|xxxxxxxxxx**x!===1x**xxxxxxxxxx|
|xxxxxxxxxx**x!===1x**xxxxxxxxxx|
|xxxxxxxxxx*xx`'''+xx*xxxxxxxxxx|
|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
t-~~~~~~~~-^^^^^^^^^^^-~~~~~~~~-Z
|mmmm@mm@mm[fffffffff]mm@mmmm@mm|
|mmmmmm@mmm[fffffffff]mm@m@mmmmm|
|m@mmmmmm@m[fffffffff]@mmmmm@mmm|
|mmmmm@mmmm[fffffffff]mm@mmmmmm@|
|m@mmmm@mm@[fffffffff]mm@mmmm@mm|
|mmm@mm@mmm[fffffffff]@mmmmmmmmm|
L----------vvvvvvvvvvv----------J
"""
COMPASS = ["N", "E", "S", "W"]
# Aesthetic components for Hidden Agenda
NW_WALL_CORNER = {
"name": "nw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_wall_corner",
"stateConfigs": [{
"state": "nw_wall_corner",
"layer": "upperPhysical",
"sprite": "NwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwWallCorner"],
"spriteShapes": [shapes.NW_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
NE_WALL_CORNER = {
"name": "ne_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_wall_corner",
"stateConfigs": [{
"state": "ne_wall_corner",
"layer": "upperPhysical",
"sprite": "NeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeWallCorner"],
"spriteShapes": [shapes.NE_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
SE_WALL_CORNER = {
"name": "se_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_wall_corner",
"stateConfigs": [{
"state": "se_wall_corner",
"layer": "upperPhysical",
"sprite": "SeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeWallCorner"],
"spriteShapes": [shapes.SE_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
SW_WALL_CORNER = {
"name": "sw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_wall_corner",
"stateConfigs": [{
"state": "sw_wall_corner",
"layer": "upperPhysical",
"sprite": "SwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwWallCorner"],
"spriteShapes": [shapes.SW_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_NORTH = {
"name": "wall_north",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_north",
"stateConfigs": [{
"state": "wall_north",
"layer": "upperPhysical",
"sprite": "WallNorth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallNorth"],
"spriteShapes": [shapes.NS_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
TCOUPLING_E = {
"name": "tcoupling_e",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tcoupling_e",
"stateConfigs": [{
"state": "tcoupling_e",
"layer": "upperPhysical",
"sprite": "TcouplingE",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["TcouplingE"],
"spriteShapes": [shapes.SHIP_WALL_TCOUPLING_E],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
TCOUPLING_W = {
"name": "tcoupling_w",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tcoupling_w",
"stateConfigs": [{
"state": "tcoupling_w",
"layer": "upperPhysical",
"sprite": "TcouplingW",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["TcouplingW"],
"spriteShapes": [shapes.SHIP_WALL_TCOUPLING_W],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
TCOUPLING_N = {
"name": "tcoupling_n",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tcoupling_n",
"stateConfigs": [{
"state": "tcoupling_n",
"layer": "upperPhysical",
"sprite": "TcouplingN",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["TcouplingN"],
"spriteShapes": [shapes.SHIP_WALL_TCOUPLING_N],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
TCOUPLING_S = {
"name": "tcoupling_s",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tcoupling_s",
"stateConfigs": [{
"state": "tcoupling_s",
"layer": "upperPhysical",
"sprite": "TcouplingS",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["TcouplingS"],
"spriteShapes": [shapes.SHIP_WALL_TCOUPLING_S],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
W_SHIP_SOLID_WALL = {
"name": "w_ship_solid_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "w_ship_solid_wall",
"stateConfigs": [{
"state": "w_ship_solid_wall",
"layer": "upperPhysical",
"sprite": "WShipSolidWall",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WShipSolidWall"],
"spriteShapes": [shapes.W_SHIP_SOLID_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
N_SHIP_SOLID_WALL = {
"name": "n_ship_solid_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "n_ship_solid_wall",
"stateConfigs": [{
"state": "n_ship_solid_wall",
"layer": "upperPhysical",
"sprite": "NShipSolidWall",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NShipSolidWall"],
"spriteShapes": [shapes.N_SHIP_SOLID_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
E_SHIP_SOLID_WALL = {
"name": "e_ship_solid_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "e_ship_solid_wall",
"stateConfigs": [{
"state": "e_ship_solid_wall",
"layer": "upperPhysical",
"sprite": "EShipSolidWall",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["EShipSolidWall"],
"spriteShapes": [shapes.E_SHIP_SOLID_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
S_SHIP_SOLID_WALL = {
"name": "s_ship_solid_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "s_ship_solid_wall",
"stateConfigs": [{
"state": "s_ship_solid_wall",
"layer": "upperPhysical",
"sprite": "SShipSolidWall",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SShipSolidWall"],
"spriteShapes": [shapes.S_SHIP_SOLID_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_WEST = {
"name": "wall_west",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_west",
"stateConfigs": [{
"state": "wall_west",
"layer": "upperPhysical",
"sprite": "WallWest",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallWest"],
"spriteShapes": [shapes.EW_SHIP_WALL],
"palettes": [shapes.SHIP_PALETTE],
"noRotates": [False]
}
},
]
}
NW_GRATE = {
"name": "nw_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_grate",
"stateConfigs": [{
"state": "nw_grate",
"layer": "background",
"sprite": "nw_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["nw_grate"],
"spriteShapes": [shapes.NW_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
N_GRATE = {
"name": "n_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "n_grate",
"stateConfigs": [{
"state": "n_grate",
"layer": "background",
"sprite": "n_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["n_grate"],
"spriteShapes": [shapes.N_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
NE_GRATE = {
"name": "ne_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_grate",
"stateConfigs": [{
"state": "ne_grate",
"layer": "background",
"sprite": "ne_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ne_grate"],
"spriteShapes": [shapes.NE_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
W_GRATE = {
"name": "w_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "w_grate",
"stateConfigs": [{
"state": "w_grate",
"layer": "background",
"sprite": "w_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["w_grate"],
"spriteShapes": [shapes.W_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
INNER_GRATE = {
"name": "inner_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inner_grate",
"stateConfigs": [{
"state": "inner_grate",
"layer": "background",
"sprite": "inner_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["inner_grate"],
"spriteShapes": [shapes.INNER_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
E_GRATE = {
"name": "e_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "e_grate",
"stateConfigs": [{
"state": "e_grate",
"layer": "background",
"sprite": "e_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["e_grate"],
"spriteShapes": [shapes.E_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
SE_GRATE = {
"name": "se_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_grate",
"stateConfigs": [{
"state": "se_grate",
"layer": "background",
"sprite": "se_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["se_grate"],
"spriteShapes": [shapes.SE_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
S_GRATE = {
"name": "s_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "s_grate",
"stateConfigs": [{
"state": "s_grate",
"layer": "background",
"sprite": "s_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["s_grate"],
"spriteShapes": [shapes.S_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
SW_GRATE = {
"name": "sw_grate",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_grate",
"stateConfigs": [{
"state": "sw_grate",
"layer": "background",
"sprite": "sw_grate",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["sw_grate"],
"spriteShapes": [shapes.SW_GRATE],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False]
}
},
]
}
GLASS_WALL = {
"name": "glass_wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "glass_wall",
"stateConfigs": [{
"state": "glass_wall",
"layer": "upperPhysical",
"sprite": "glass_wall",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["glass_wall"],
"spriteShapes": [shapes.GLASS_WALL],
"palettes": [shapes.GLASS_PALETTE],
"noRotates": [False]
}
},
]
}
FILL = {
"name": "fill",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "fill",
"stateConfigs": [{
"state": "fill",
"layer": "upperPhysical",
"sprite": "fill",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["fill"],
"spriteShapes": [shapes.FILL],
"palettes": [{"i": (58, 68, 102, 255),}],
"noRotates": [False]
}
},
]
}
TILED_FLOOR = {
"name": "tiled_floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tiled_floor",
"stateConfigs": [{
"state": "tiled_floor",
"layer": "background",
"sprite": "tiled_floor",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["tiled_floor"],
"spriteShapes": [shapes.TILED_FLOOR_GREY],
"palettes": [{"o": (204, 199, 192, 255),
"-": (194, 189, 182, 255),}],
"noRotates": [False]
}
},
]
}
WOOD_FLOOR = {
"name": "wood_floor",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wood_floor",
"stateConfigs": [{
"state": "wood_floor",
"layer": "background",
"sprite": "wood_floor",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wood_floor"],
"spriteShapes": [shapes.WOOD_FLOOR],
"palettes": [shapes.WOOD_FLOOR_PALETTE],
"noRotates": [False]
}
},
]
}
METAL_FLOORING = {
"name": "metal_flooring",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "metal_flooring",
"stateConfigs": [{
"state": "metal_flooring",
"layer": "background",
"sprite": "metal_flooring",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["metal_flooring"],
"spriteShapes": [shapes.METAL_TILE],
"palettes": [shapes.METAL_FLOOR_PALETTE],
"noRotates": [False]
}
},
]
}
METAL_PANEL_FLOORING = {
"name": "metal_panel_flooring",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "metal_panel_flooring",
"stateConfigs": [{
"state": "metal_panel_flooring",
"layer": "background",
"sprite": "metal_panel_flooring",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["metal_panel_flooring"],
"spriteShapes": [shapes.METAL_PANEL],
"palettes": [shapes.METAL_PANEL_FLOOR_PALETTE],
"noRotates": [False]
}
},
]
}
CHECKERED_FLOORING = {
"name": "checkered_flooring",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "checkered_flooring",
"stateConfigs": [{
"state": "checkered_flooring",
"layer": "background",
"sprite": "checkered_flooring",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["checkered_flooring"],
"spriteShapes": [shapes.CHECKERED_TILE],
"palettes": [{"X": (120, 108, 108, 255),
"x": (115, 103, 103, 255),}],
"noRotates": [False]
}
},
]
}
TILED_FLOORING1 = {
"name": "tiled_flooring1",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tiled_flooring1",
"stateConfigs": [{
"state": "tiled_flooring1",
"layer": "background",
"sprite": "tiled_flooring1",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["tiled_flooring1"],
"spriteShapes": [shapes.TILE1],
"palettes": [shapes.TILE_FLOOR_PALETTE],
"noRotates": [False]
}
},
]
}
TILED_FLOORING2 = {
"name": "tiled_flooring2",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tiled_flooring2",
"stateConfigs": [{
"state": "tiled_flooring2",
"layer": "background",
"sprite": "tiled_flooring2",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["tiled_flooring2"],
"spriteShapes": [shapes.TILE2],
"palettes": [shapes.TILE_FLOOR_PALETTE],
"noRotates": [False]
}
},
]
}
THRESHOLD = {
"name": "threshold",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "threshold",
"stateConfigs": [{
"state": "threshold",
"layer": "background",
"sprite": "threshold",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["threshold"],
"spriteShapes": [shapes.THRESHOLD],
"palettes": [{"X": (92, 95, 92, 255),
"x": (106, 108, 106, 255),}],
"noRotates": [False]
}
},
]
}
# Functional components for Hidden Agenda
SPAWN_POINT = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"groups": ["spawnPoints"],
}],
}
},
{
"component": "Transform",
},
]
}
VOTING_SPAWN_POINT = {
"name": "voting_spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "votingSpawnPoint",
"stateConfigs": [{
"state": "votingSpawnPoint",
"groups": ["votingSpawnPoints"],
}],
}
},
{
"component": "Transform",
},
]
}
TELEPORT_SPAWN_POINT = {
"name": "teleport_spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "teleportSpawnPoint",
"stateConfigs": [{
"state": "teleportSpawnPoint",
"groups": ["teleportSpawnPoints"],
}],
}
},
{
"component": "Transform",
},
]
}
def get_gem_prefab(crewmate_pseudoreward: float):
return {
"name": "gem",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "gem",
"stateConfigs": [{
"state": "gem",
"layer": "lowerPhysical",
"sprite": "Gem",
}, {
"state": "gemWait",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Gem",],
"spriteShapes": [shapes.SMALL_SPHERE],
"palettes": [shapes.MOULD_PALETTE],
"noRotates": [True],
}
},
{
"component": "Collectable",
"kwargs": {
"liveState": "gem",
"waitState": "gemWait",
"rewardForCollecting_crewmate": crewmate_pseudoreward,
"rewardForCollecting_impostor": 0.0,
"regrowRate": 0.001,
}
},
]
}
def get_gem_deposit_prefab(crewmate_pseudoreward: float):
return {
"name": "gem_deposit",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "gemDeposit",
"stateConfigs": [{
"state": "gemDeposit",
"layer": "lowerPhysical",
"sprite": "GemDeposit",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["GemDeposit"],
"spriteShapes": ["x"],
"palettes": [shapes.GRATE_PALETTE],
"noRotates": [False],
}
},
{
"component": "Deposit",
"kwargs": {
"crewmateReward": crewmate_pseudoreward,
"impostorReward": 0.0,
}
}
]
}
def create_player(player_idx: int, role: str, num_players: int,
pseudoreward_for_freezing: float,
pseudoreward_for_being_frozen: float):
"""Create a prefab for a Player (Impostor or Crewmate).
Args:
player_idx: The index of this player.
role: Whether this player will be a `crewmate` or an `impostor`.
num_players: The number of players in the environment.
pseudoreward_for_freezing: Peudoreward given when the impostor successfully
freezes a crewmate.
pseudoreward_for_being_frozen: Pseudoreward (usually negative) given to a
crewmate that was frozen by the impostor.
Returns:
A prefab (dictionary) for a Player.
"""
# Lua is 1-indexed.
lua_index = player_idx + 1
live_state_name = f"player{lua_index}"
avatar_sprite_name = f"avatarSprite{lua_index}"
if role == "impostor":
sprite_map = {avatar_sprite_name: f"Player_impostor{lua_index}"}
else:
sprite_map = {}
player = {
"name": "player",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar"},
{"state": "playerWait"},
{"state": "playerBody",
"layer": "upperPhysical",
"sprite": "Player_tagged"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name, "Player_tagged"],
"spriteShapes": [shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR_FROZEN],
"palettes": [
shapes.get_palette(HIDDEN_AGENDA_COLORS[player_idx]),
shapes.get_palette(HIDDEN_AGENDA_COLORS[player_idx])
],
"noRotates": [True]
}
},
{
"component": "AdditionalPlayerSprites",
"kwargs": {
"renderMode":
"ascii_shape",
"customSpriteNames": [
"Player_impostor" + str(i + 1) for i in range(num_players)
],
"customSpriteShapes": [shapes.CUTE_AVATAR_W_BUBBLE] *
num_players,
"customPalettes": [
shapes.get_palette(HIDDEN_AGENDA_COLORS[i])
for i in range(num_players)
],
"customNoRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"spawnGroup": "spawnPoints",
"aliveState": live_state_name,
"waitState": "playerWait",
"actionOrder": ["move", "turn", "tag", "vote"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"tag": {"default": 0, "min": 0, "max": 1},
"vote": {"default": 0, "min": 0, "max": num_players + 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": sprite_map,
},
},
{
"component": "Role",
"kwargs": {
"frozenState": "playerBody",
"role": role, # `crewmate` or `impostor`.
}
},
{
"component": "Inventory",
"kwargs": {
"max_gems": 1,
}
},
{
"component": "AdditionalObserver",
"kwargs": {
"num_players": num_players,
}
},
{
"component": "Tagger",
"kwargs": {
"cooldownTime": 50,
"beamLength": 2,
"beamRadius": 2,
"penaltyForBeingTagged": pseudoreward_for_being_frozen,
"rewardForTagging": pseudoreward_for_freezing,
"removeHitPlayer": "freeze",
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "Tagger",
},
},
{
"component": "Voting",
"kwargs": {
"spawnGroup": "votingSpawnPoints",
"votingActive": False,
"votingMethod": "deliberation",
"votingValues": {},
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
player["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return player
def create_prefabs(
crewmate_collect_pseudoreward: float,
crewmate_deposit_pseudoreward: float,
):
"""Create prefabs dictionary from individual prefabs.
Args:
crewmate_collect_pseudoreward: Pseudoreward given to crewmates when they
collect a gem.
crewmate_deposit_pseudoreward: Pseudoreward given to crewmates when they
deposit a gem.
Returns:
A dictionary of prefabs for components in the environment.
"""
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
prefabs = {
"nw_wall_corner": NW_WALL_CORNER,
"ne_wall_corner": NE_WALL_CORNER,
"sw_wall_corner": SW_WALL_CORNER,
"n_ship_solid_wall": N_SHIP_SOLID_WALL,
"e_ship_solid_wall": E_SHIP_SOLID_WALL,
"s_ship_solid_wall": S_SHIP_SOLID_WALL,
"w_ship_solid_wall": W_SHIP_SOLID_WALL,
"wall_north": WALL_NORTH,
"se_wall_corner": SE_WALL_CORNER,
"tcoupling_e": TCOUPLING_E,
"tcoupling_w": TCOUPLING_W,
"tcoupling_n": TCOUPLING_N,
"tcoupling_s": TCOUPLING_S,
"wall_west": WALL_WEST,
"nw_grate": NW_GRATE,
"n_grate": N_GRATE,
"ne_grate": NE_GRATE,
"w_grate": W_GRATE,
"inner_grate": INNER_GRATE,
"e_grate": E_GRATE,
"se_grate": SE_GRATE,
"s_grate": S_GRATE,
"sw_grate": SW_GRATE,
"glass_wall": GLASS_WALL,
"fill": FILL,
"tiled_floor": TILED_FLOOR,
"tiled_flooring1": TILED_FLOORING1,
"tiled_flooring2": TILED_FLOORING2,
"wood_flooring": WOOD_FLOOR,
"metal_flooring": METAL_FLOORING,
"metal_panel_flooring": METAL_PANEL_FLOORING,
"checkered_flooring": CHECKERED_FLOORING,
"threshold": THRESHOLD,
"gem": get_gem_prefab(crewmate_collect_pseudoreward),
"spawn_point": SPAWN_POINT,
"voting_spawn_point": VOTING_SPAWN_POINT,
"teleport_spawn_point": TELEPORT_SPAWN_POINT,
"gem_deposit": get_gem_deposit_prefab(crewmate_deposit_pseudoreward),
}
return prefabs
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "tag": 0, "vote": 0}
FORWARD = {"move": 1, "turn": 0, "tag": 0, "vote": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "tag": 0, "vote": 0}
BACKWARD = {"move": 3, "turn": 0, "tag": 0, "vote": 0}
STEP_LEFT = {"move": 4, "turn": 0, "tag": 0, "vote": 0}
TURN_LEFT = {"move": 0, "turn": -1, "tag": 0, "vote": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "tag": 0, "vote": 0}
TAG = {"move": 0, "turn": 0, "tag": 1, "vote": 0}
# pylint: enable=bad-whitespace
# pyformat: enable
def create_action_set(num_players):
"""Create the action set for the agents."""
action_set = [
NOOP,
FORWARD, BACKWARD,
STEP_LEFT, STEP_RIGHT,
TURN_LEFT, TURN_RIGHT,
TAG,
]
# vote for each player and no-vote.
for player in range(1, num_players+2):
vote = copy.deepcopy(NOOP)
vote["vote"] = player
action_set.append(vote)
return action_set
def get_config():
"""Default configuration for the Hidden Agenda level."""
config = config_dict.ConfigDict()
# Specify the number of players to particate in each episode (optional).
config.recommended_num_players = MANDATED_NUM_PLAYERS
# Configurable pseudorewards.
# The canonical substrate requires these pseudorewards to be 0. However,
# you can set them to something else to improve training. For example, you'd
# use `crewmate_collect_pseudoreward=0.25` and
# `crewmate_deposit_pseudoreward=0.25` to aid the crewmates in learning to
# collect and deposit gems. Also, you can set `pseudoreward_for_freezing=1`
# and `pseudoreward_for_being_frozen=-1` to help players learn about freezing
# mechanics.
config.pseudorewards = dict(
crewmate_collect_pseudoreward=0.0,
crewmate_deposit_pseudoreward=0.0,
pseudoreward_for_freezing=0.0,
pseudoreward_for_being_frozen=0.0,
)
config.scene_prefab = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component":
"Progress",
"kwargs":
config_dict.ConfigDict({
"num_players":
MANDATED_NUM_PLAYERS,
"goal": 32,
"potential_pseudorewards": False,
"crewmate_task_reward": 1,
"impostor_task_reward": -1,
"crewmate_tag_reward": -1,
"impostor_tag_reward": 1,
"crewmate_vote_reward": 1,
"impostor_vote_reward": -1,
"incorrect_vote_reward": 0,
"correct_vote_reward": 0,
"step_reward": 0,
"teleport_spawn_group":
"teleportSpawnPoints",
"voting_params": {
"type": "deliberation",
"votingPhaseCooldown": 25,
"votingFrameFrequency": 200,
"taggingTriggerVoting": True,
}
})
},
]
}
# The voting matrix metric is always used.
metrics = [{
"name": "VOTING",
"type": "tensor.DoubleTensor",
"shape": (MANDATED_NUM_PLAYERS, MANDATED_NUM_PLAYERS + 2),
"component": "Progress",
"variable": "votingMatrix",
}]
if _ENABLE_DEBUG_OBSERVATIONS:
config.scene_prefab["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
metrics.append({
"name": "GLOBAL_PROGRESS",
"type": "tensor.DoubleTensor",
"shape": (1,),
"component": "Progress",
"variable": "progress_bar",
})
metrics.append({
"name": "IDENTITIES",
"type": "tensor.DoubleTensor",
"shape": (MANDATED_NUM_PLAYERS,),
"component": "Progress",
"variable": "identity_tensor"
})
metrics.append({
"name": "VOTING",
"type": "tensor.DoubleTensor",
"shape": (MANDATED_NUM_PLAYERS, MANDATED_NUM_PLAYERS + 2),
"component": "Progress",
"variable": "votingMatrix"
})
# Add the global metrics reporter
config.scene_prefab["components"].append({
"component": "GlobalMetricReporter",
"kwargs": {
"metrics": metrics
}
})
# Action set configuration.
config.action_set = create_action_set(MANDATED_NUM_PLAYERS)
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
"VOTING",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(config.action_set))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"INVENTORY": specs.inventory(1),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
"VOTING": specs.float64(MANDATED_NUM_PLAYERS, MANDATED_NUM_PLAYERS + 2),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(176, 264),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"crewmate",
"impostor",})
config.default_player_roles = ("crewmate",) * 4 + ("impostor",)
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build the hidden_agenda substrate given player preferences."""
# Build avatars.
num_players = len(roles)
avatar_objects = []
for player_idx, role in enumerate(roles):
# Create an avatar with the correct role.
avatar_objects.append(create_player(
player_idx=player_idx,
role=role,
num_players=num_players,
pseudoreward_for_freezing=
config.pseudorewards.pseudoreward_for_freezing,
pseudoreward_for_being_frozen=
config.pseudorewards.pseudoreward_for_being_frozen))
substrate_definition = dict(
levelName="hidden_agenda",
levelDirectory="meltingpot/lua/levels",
maxEpisodeLengthFrames=3000,
spriteSize=8,
numPlayers=num_players,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": avatar_objects,
"prefabs": create_prefabs(
config.pseudorewards.crewmate_collect_pseudoreward,
config.pseudorewards.crewmate_deposit_pseudoreward,
),
"charPrefabMap": CHAR_PREFAB_MAP,
"scene": config.scene_prefab,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/hidden_agenda.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for boat_race__eight_races."""
from meltingpot.configs.substrates import boat_race as base_config
from ml_collections import config_dict as configdict
def get_config() -> configdict.ConfigDict:
"""Configuration for the boat_race substrate."""
config = base_config.get_config()
config.num_races = 8
config.default_player_roles = ("default",) * base_config.MANDATED_NUM_PLAYERS
return config
build = base_config.build
|
meltingpot-main
|
meltingpot/configs/substrates/boat_race__eight_races.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Config for Chemistry: Three Metabolic Cycles With Plentiful Distractors.
Example video: https://youtu.be/IjlJckwM1VE
Individuals benefit from three different food generating reaction cycles or from
holding a distractor molecule in their vesicle. The cycles will run on their own
(autocatalytically), but require energy to continue and one of them immediately
consumes the energy relied upon. Bringing together side products from the other
two cycles generates new energy such that the cycles can continue. The
population needs to keep both of these cycles running to get high rewards.
Reactions are defined by a directed graph. Reactant nodes project into reaction
nodes, which project out to product nodes. Reactions occur stochastically when
all reactants are brought near one another. Agents can carry a single molecule
around the map with them at a time. Agents are rewarded when a specific reaction
occurs that involves the molecule they are currently carrying (as either a
reactant or a product).
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.configs.substrates import reaction_graph_utils as graph_utils
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import networkx as nx
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# Map reaction to rewards.
DEFAULT_REWARDING_REACTIONS = {"MetabolizeFood1": 1,
"MetabolizeFood2": 1,
"MetabolizeFood3": 10,
"MetabolizeXY": 10,
"Holding": 0.1}
# Define the default reaction query configuration. It can be overridden on a per
# compount basis.
DEFAULT_REACTION_CONFIG = {"radius": 1, "query_type": "disc"}
REACTIVITY_LEVELS = {
"ground": {"background": 0.00001,
"low": 0.005,
"medium": 0.001,
"high": 0.9},
"vesicle": {"background": 0.0,
"low": 0.0025,
"medium": 0.25,
"high": 0.9},
}
def dissipate_when_paired(g: nx.MultiDiGraph, reaction_name: str,
compound: str):
g.add_node(reaction_name, reaction=True)
# Reactants:
g.add_edge(compound, reaction_name)
g.add_edge(compound, reaction_name)
# Products:
g.add_edge(reaction_name, "empty")
g.add_edge(reaction_name, "empty")
def cycle(g: nx.MultiDiGraph, reaction_prefix: str,
intermediates: Sequence[str], product: str,
secondary_product: str, food: str = "food"):
"""Add a reaction cycle."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "energy")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def null(g: nx.MultiDiGraph, reaction_name: str, compound: str):
"""Chemical state transition pattern."""
g.add_node(reaction_name, reaction=True)
g.add_edge(compound, reaction_name)
g.add_edge(reaction_name, compound)
def greedy_cycle(g: nx.MultiDiGraph, reaction_prefix: str,
intermediates: Sequence[str], product: str,
secondary_product: str, food: str = "food"):
"""Add a reaction cycle that consumes energy."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2. Takes and destroys one energy
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "empty")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def make_graph():
"""User defined graph construction function using networkx."""
# Note: You can copy-paste this function into colab to visualize the graph.
g = nx.MultiDiGraph()
# First add the "empty" and "activated" nodes, which are always present.
graph_utils.add_system_nodes(g)
cycle(g, "R",
intermediates=["ax", "bx", "cx"],
product="x",
secondary_product="iy",
food="food1")
cycle(g, "R",
intermediates=["ay", "by", "cy"],
product="y",
secondary_product="ix",
food="food2")
greedy_cycle(g, "R",
intermediates=["az", "bz", "cz"],
product="food1",
secondary_product="food2",
food="food3")
null(g, "Holding", "distractor") # Holding the distractor provides reward.
# Inhibit x with a product of the y-producing cycle.
g.add_node("InhibitX", reaction=True)
# Reactants:
g.add_edge("x", "InhibitX")
g.add_edge("ix", "InhibitX")
# Products:
g.add_edge("InhibitX", "empty")
g.add_edge("InhibitX", "empty")
# Inhibit y with a product of the x-producing cycle.
g.add_node("InhibitY", reaction=True)
# Reactants:
g.add_edge("y", "InhibitY")
g.add_edge("iy", "InhibitY")
# Products:
g.add_edge("InhibitY", "empty")
g.add_edge("InhibitY", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood1", reaction=True)
# Reactants:
g.add_edge("food1", "MetabolizeFood1")
# Products:
g.add_edge("MetabolizeFood1", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood2", reaction=True)
# Reactants:
g.add_edge("food2", "MetabolizeFood2")
# Products:
g.add_edge("MetabolizeFood2", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood3", reaction=True)
# Reactants:
g.add_edge("food3", "MetabolizeFood3")
# Products:
g.add_edge("MetabolizeFood3", "empty")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood1", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood1")
# Products:
g.add_edge("SpawnFood1", "food1")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood2", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood2")
# Products:
g.add_edge("SpawnFood2", "food2")
# x and y can be combined to produce energy.
g.add_node("MetabolizeXY", reaction=True)
# Reactants:
g.add_edge("x", "MetabolizeXY")
g.add_edge("y", "MetabolizeXY")
# Products:
g.add_edge("MetabolizeXY", "energy")
g.add_edge("MetabolizeXY", "energy")
# Energy spontaneously dissipates.
g.add_node("DissipateEnergy", reaction=True)
# Reactants:
g.add_edge("energy", "DissipateEnergy")
# Products:
g.add_edge("DissipateEnergy", "empty")
# Prevent inhibitors from accumulating by dissipating them whenever they pair.
dissipate_when_paired(g, "DissipateIX", "ix")
dissipate_when_paired(g, "DissipateIY", "iy")
# Properties of compounds
# Color:
g.nodes["ax"]["color"] = (153, 204, 255, 255) # blue 1
g.nodes["bx"]["color"] = (102, 204, 255, 255) # blue 2
g.nodes["cx"]["color"] = (51, 153, 255, 255) # blue 3
g.nodes["ay"]["color"] = (102, 255, 153, 255) # green 1
g.nodes["by"]["color"] = (102, 255, 102, 255) # green 2
g.nodes["cy"]["color"] = (0, 255, 0, 255) # green 3
g.nodes["az"]["color"] = (178, 34, 34, 255) # red 1
g.nodes["bz"]["color"] = (131, 38, 38, 255) # red 2
g.nodes["cz"]["color"] = (142, 27, 27, 255) # red 3
g.nodes["x"]["color"] = (0, 51, 204, 255) # dark blue
g.nodes["y"]["color"] = (0, 51, 0, 255) # dark green
g.nodes["food1"]["color"] = (178, 151, 0, 255) # light gold
g.nodes["food1"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food2"]["color"] = (255, 215, 0, 255) # gold
g.nodes["food2"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food3"]["color"] = (255, 100, 50, 255) # orange
g.nodes["food3"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["distractor"]["color"] = (75, 0, 130, 255) # indigo
g.nodes["distractor"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["energy"]["color"] = (255, 0, 0, 255) # red
g.nodes["energy"]["sprite"] = graph_utils.ENERGY_SHAPE
g.nodes["ix"]["color"] = (102, 153, 153, 255) # greyish green
g.nodes["iy"]["color"] = (51, 102, 153, 255) # greyish blue
# Reactivity:
g.nodes["ax"]["reactivity"] = "high"
g.nodes["bx"]["reactivity"] = "high"
g.nodes["cx"]["reactivity"] = "high"
g.nodes["ay"]["reactivity"] = "high"
g.nodes["by"]["reactivity"] = "high"
g.nodes["cy"]["reactivity"] = "high"
g.nodes["az"]["reactivity"] = "high"
g.nodes["bz"]["reactivity"] = "high"
g.nodes["cz"]["reactivity"] = "high"
g.nodes["x"]["reactivity"] = "medium"
g.nodes["y"]["reactivity"] = "medium"
g.nodes["ix"]["reactivity"] = "high"
g.nodes["iy"]["reactivity"] = "high"
g.nodes["food1"]["reactivity"] = "medium"
g.nodes["food2"]["reactivity"] = "medium"
g.nodes["food3"]["reactivity"] = "medium"
g.nodes["distractor"]["reactivity"] = "medium"
g.nodes["energy"]["reactivity"] = "low"
g.nodes["empty"]["reactivity"] = "background"
# The following commented line documents how to set the query config for a
# specific compound, overriding the default query configuration.
# g.nodes["food1"]["query_config"] = {"radius": 3, "queryType": "diamond"}
return g
ASCII_MAP = """
~~~~~~~~~~~a~x~~~~~~~~~~~
~~~~~~~~c~~~~~~~~~~~~x~~~
~~x~~~~~~~~b~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~x~~~~~~~~~~~~~1~~~
~~~~~~~~~~~~~~~~~~x~~~~~~
1~~3~~~~hhhhhhh~~~~~3~~2~
~~~x~~~~~~~~~~~~~~~~~~~~~
~2~~~~~~~~~~~x~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~x~~~~~
~~~~~~~c~~~~~~~~~~~~~~~~~
~x~~~~~~~a~~~~~~~~~~4~~~6
~~~~~~~b~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~x~~~~~~~~5~~
"""
# `prefab` determines which compound to use for each `char` in the ascii map.
CHAR_PREFAB_MAP = {
"~": "empty",
"a": "ax",
"b": "bx",
"c": "cx",
"1": "ay",
"2": "by",
"3": "cy",
"4": "az",
"5": "bz",
"6": "cz",
"x": "distractor",
"h": "energy",
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 60
PLAYER_COLOR_PALETTES = []
for i in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "ioAction": 0}
FORWARD = {"move": 1, "turn": 0, "ioAction": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "ioAction": 0}
BACKWARD = {"move": 3, "turn": 0, "ioAction": 0}
STEP_LEFT = {"move": 4, "turn": 0, "ioAction": 0}
TURN_LEFT = {"move": 0, "turn": -1, "ioAction": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "ioAction": 0}
IO_ACTION = {"move": 0, "turn": 0, "ioAction": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
IO_ACTION,
)
TARGET_SPRITE_SELF_EMPTY = {
"name": "SelfEmpty",
"shape": shapes.CYTOAVATAR_EMPTY,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
TARGET_SPRITE_SELF_HOLDS_ONE = {
"name": "SelfHoldsOne",
"shape": shapes.CYTOAVATAR_HOLDING_ONE,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
def create_avatar_objects(num_players, compounds):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
additional_game_objects = []
for player_idx in range(0, num_players):
game_object = graph_utils.create_avatar_constant_self_view(
rewarding_reactions=DEFAULT_REWARDING_REACTIONS,
player_idx=player_idx,
target_sprite_self_empty=TARGET_SPRITE_SELF_EMPTY,
target_sprite_self_holds_one=TARGET_SPRITE_SELF_HOLDS_ONE,
add_location_observer=_ENABLE_DEBUG_OBSERVATIONS)
avatar_objects.append(game_object)
# Add the overlaid avatar vesicle on top of each avatar.
avatar_vesicle = graph_utils.create_vesicle(
player_idx=player_idx,
compounds=compounds,
reactivity_levels=REACTIVITY_LEVELS["vesicle"],
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
additional_game_objects.append(avatar_vesicle)
return avatar_objects, additional_game_objects
def get_config():
"""Default configuration for this substrate."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(112, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate."""
del config
num_players = len(roles)
# Must create compounds and reactions.
compounds, reactions = graph_utils.graph_semantics(make_graph())
cell_prefabs = {}
cell_prefabs = graph_utils.add_compounds_to_prefabs_dictionary(
cell_prefabs, compounds, REACTIVITY_LEVELS["ground"], sprites=True,
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
avatar_objects, additional_objects = create_avatar_objects(num_players,
compounds)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="grid_land",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"].
simulation={
"map": ASCII_MAP,
"gameObjects": avatar_objects + additional_objects,
"scene": graph_utils.create_scene(reactions,
stochastic_episode_ending=True),
"prefabs": cell_prefabs,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/chemistry__three_metabolic_cycles_with_plentiful_distractors.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Config for Chemistry: Three Metabolic Cycles.
Example video: https://youtu.be/RlnojJHAoFI
Individuals benefit from three different food generating reaction cycles.
The cycles will run on their own (autocatalytically), but require energy to
continue and one of them immediately consumes the energy relied upon.
Bringing together side products from the other two cycles generates new energy
such that the cycles can continue. The population needs to keep both of these
cycles running to get high rewards.
Reactions are defined by a directed graph. Reactant nodes project into reaction
nodes, which project out to product nodes. Reactions occur stochastically when
all reactants are brought near one another. Agents can carry a single molecule
around the map with them at a time. Agents are rewarded when a specific reaction
occurs that involves the molecule they are currently carrying (as either a
reactant or a product).
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.configs.substrates import reaction_graph_utils as graph_utils
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import networkx as nx
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# Map reaction to rewards.
DEFAULT_REWARDING_REACTIONS = {"MetabolizeFood1": 1,
"MetabolizeFood2": 1,
"MetabolizeFood3": 10,
"MetabolizeXY": 10,}
# Define the default reaction query configuration. It can be overridden on a per
# compount basis.
DEFAULT_REACTION_CONFIG = {"radius": 1, "query_type": "disc"}
REACTIVITY_LEVELS = {
"ground": {"background": 0.00001,
"low": 0.005,
"medium": 0.001,
"high": 0.9},
"vesicle": {"background": 0.0,
"low": 0.0025,
"medium": 0.25,
"high": 0.9},
}
def dissipate_when_paired(g: nx.MultiDiGraph, reaction_name: str,
compound: str):
g.add_node(reaction_name, reaction=True)
# Reactants:
g.add_edge(compound, reaction_name)
g.add_edge(compound, reaction_name)
# Products:
g.add_edge(reaction_name, "empty")
g.add_edge(reaction_name, "empty")
def cycle(g, reaction_prefix: str, intermediates: Sequence[str], product: str,
secondary_product=None, food: str = "food"):
"""Add a reaction cycle."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "energy")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def greedy_cycle(g: nx.MultiDiGraph, reaction_prefix: str,
intermediates: Sequence[str], product: str,
secondary_product: str, food: str = "food"):
"""Add a reaction cycle that consumes energy."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2. Takes and destroys one energy
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "empty")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def make_graph():
"""User defined graph construction function using networkx."""
# Note: You can copy-paste this function into colab to visualize the graph.
g = nx.MultiDiGraph()
# First add the "empty" and "activated" nodes, which are always present.
graph_utils.add_system_nodes(g)
cycle(g, "R",
intermediates=["ax", "bx", "cx"],
product="x",
secondary_product="iy",
food="food1")
cycle(g, "R",
intermediates=["ay", "by", "cy"],
product="y",
secondary_product="ix",
food="food2")
greedy_cycle(g, "R",
intermediates=["az", "bz", "cz"],
product="food1",
secondary_product="food2",
food="food3")
# Inhibit x with a product of the y-producing cycle.
g.add_node("InhibitX", reaction=True)
# Reactants:
g.add_edge("x", "InhibitX")
g.add_edge("ix", "InhibitX")
# Products:
g.add_edge("InhibitX", "empty")
g.add_edge("InhibitX", "empty")
# Inhibit y with a product of the x-producing cycle.
g.add_node("InhibitY", reaction=True)
# Reactants:
g.add_edge("y", "InhibitY")
g.add_edge("iy", "InhibitY")
# Products:
g.add_edge("InhibitY", "empty")
g.add_edge("InhibitY", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood1", reaction=True)
# Reactants:
g.add_edge("food1", "MetabolizeFood1")
# Products:
g.add_edge("MetabolizeFood1", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood2", reaction=True)
# Reactants:
g.add_edge("food2", "MetabolizeFood2")
# Products:
g.add_edge("MetabolizeFood2", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood3", reaction=True)
# Reactants:
g.add_edge("food3", "MetabolizeFood3")
# Products:
g.add_edge("MetabolizeFood3", "empty")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood1", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood1")
# Products:
g.add_edge("SpawnFood1", "food1")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood2", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood2")
# Products:
g.add_edge("SpawnFood2", "food2")
# x and y can be combined to produce energy.
g.add_node("MetabolizeXY", reaction=True)
# Reactants:
g.add_edge("x", "MetabolizeXY")
g.add_edge("y", "MetabolizeXY")
# Products:
g.add_edge("MetabolizeXY", "energy")
g.add_edge("MetabolizeXY", "energy")
# Energy spontaneously dissipates.
g.add_node("DissipateEnergy", reaction=True)
# Reactants:
g.add_edge("energy", "DissipateEnergy")
# Products:
g.add_edge("DissipateEnergy", "empty")
# Prevent inhibitors from accumulating by dissipating them whenever they pair.
dissipate_when_paired(g, "DissipateIX", "ix")
dissipate_when_paired(g, "DissipateIY", "iy")
# Properties of compounds
# Color:
g.nodes["ax"]["color"] = (153, 204, 255, 255) # blue 1
g.nodes["bx"]["color"] = (102, 204, 255, 255) # blue 2
g.nodes["cx"]["color"] = (51, 153, 255, 255) # blue 3
g.nodes["ay"]["color"] = (102, 255, 153, 255) # green 1
g.nodes["by"]["color"] = (102, 255, 102, 255) # green 2
g.nodes["cy"]["color"] = (0, 255, 0, 255) # green 3
g.nodes["az"]["color"] = (178, 34, 34, 255) # red 1
g.nodes["bz"]["color"] = (131, 38, 38, 255) # red 2
g.nodes["cz"]["color"] = (142, 27, 27, 255) # red 3
g.nodes["x"]["color"] = (0, 51, 204, 255) # dark blue
g.nodes["y"]["color"] = (0, 51, 0, 255) # dark green
g.nodes["food1"]["color"] = (178, 151, 0, 255) # light gold
g.nodes["food1"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food2"]["color"] = (255, 215, 0, 255) # gold
g.nodes["food2"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food3"]["color"] = (255, 100, 50, 255) # orange
g.nodes["food3"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["energy"]["color"] = (255, 0, 0, 255) # red
g.nodes["energy"]["sprite"] = graph_utils.ENERGY_SHAPE
g.nodes["ix"]["color"] = (102, 153, 153, 255) # greyish green
g.nodes["iy"]["color"] = (51, 102, 153, 255) # greyish blue
# Reactivity:
g.nodes["ax"]["reactivity"] = "high"
g.nodes["bx"]["reactivity"] = "high"
g.nodes["cx"]["reactivity"] = "high"
g.nodes["ay"]["reactivity"] = "high"
g.nodes["by"]["reactivity"] = "high"
g.nodes["cy"]["reactivity"] = "high"
g.nodes["az"]["reactivity"] = "high"
g.nodes["bz"]["reactivity"] = "high"
g.nodes["cz"]["reactivity"] = "high"
g.nodes["x"]["reactivity"] = "medium"
g.nodes["y"]["reactivity"] = "medium"
g.nodes["ix"]["reactivity"] = "high"
g.nodes["iy"]["reactivity"] = "high"
g.nodes["food1"]["reactivity"] = "medium"
g.nodes["food2"]["reactivity"] = "medium"
g.nodes["food3"]["reactivity"] = "medium"
g.nodes["energy"]["reactivity"] = "low"
g.nodes["empty"]["reactivity"] = "background"
# The following commented line documents how to set the query config for a
# specific compound, overriding the default query configuration.
# g.nodes["food1"]["query_config"] = {"radius": 3, "queryType": "diamond"}
return g
ASCII_MAP = """
~~~~~~~~~~~a~~~~~~~~~~~~~
~~~~~~~~c~~~~~~~~~~~~~~~~
~~~~~~~~~~~b~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~1~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
1~~3~~~~hhhhhhh~~~~~3~~2~
~~~~~~~~~~~~~~~~~~~~~~~~~
~2~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~c~~~~~~~~~~~~~~~~~
~~~~~~~~~a~~~~~~~~~~4~~~6
~~~~~~~b~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~5~~
"""
# `prefab` determines which compound to use for each `char` in the ascii map.
CHAR_PREFAB_MAP = {
"~": "empty",
"a": "ax",
"b": "bx",
"c": "cx",
"1": "ay",
"2": "by",
"3": "cy",
"4": "az",
"5": "bz",
"6": "cz",
"h": "energy",
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 60
PLAYER_COLOR_PALETTES = []
for i in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "ioAction": 0}
FORWARD = {"move": 1, "turn": 0, "ioAction": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "ioAction": 0}
BACKWARD = {"move": 3, "turn": 0, "ioAction": 0}
STEP_LEFT = {"move": 4, "turn": 0, "ioAction": 0}
TURN_LEFT = {"move": 0, "turn": -1, "ioAction": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "ioAction": 0}
IO_ACTION = {"move": 0, "turn": 0, "ioAction": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
IO_ACTION,
)
TARGET_SPRITE_SELF_EMPTY = {
"name": "SelfEmpty",
"shape": shapes.CYTOAVATAR_EMPTY,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
TARGET_SPRITE_SELF_HOLDS_ONE = {
"name": "SelfHoldsOne",
"shape": shapes.CYTOAVATAR_HOLDING_ONE,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
def create_avatar_objects(num_players, compounds):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
additional_game_objects = []
for player_idx in range(0, num_players):
game_object = graph_utils.create_avatar_constant_self_view(
rewarding_reactions=DEFAULT_REWARDING_REACTIONS,
player_idx=player_idx,
target_sprite_self_empty=TARGET_SPRITE_SELF_EMPTY,
target_sprite_self_holds_one=TARGET_SPRITE_SELF_HOLDS_ONE,
add_location_observer=_ENABLE_DEBUG_OBSERVATIONS)
avatar_objects.append(game_object)
# Add the overlaid avatar vesicle on top of each avatar.
avatar_vesicle = graph_utils.create_vesicle(
player_idx=player_idx,
compounds=compounds,
reactivity_levels=REACTIVITY_LEVELS["vesicle"],
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
additional_game_objects.append(avatar_vesicle)
return avatar_objects, additional_game_objects
def get_config():
"""Default configuration for this substrate."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(112, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate."""
del config
num_players = len(roles)
# Must create compounds and reactions.
compounds, reactions = graph_utils.graph_semantics(make_graph())
cell_prefabs = {}
cell_prefabs = graph_utils.add_compounds_to_prefabs_dictionary(
cell_prefabs, compounds, REACTIVITY_LEVELS["ground"], sprites=True,
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
avatar_objects, additional_objects = create_avatar_objects(num_players,
compounds)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="grid_land",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"].
simulation={
"map": ASCII_MAP,
"gameObjects": avatar_objects + additional_objects,
"scene": graph_utils.create_scene(reactions,
stochastic_episode_ending=True),
"prefabs": cell_prefabs,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/chemistry__three_metabolic_cycles.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Bach or Stravinsky in the Matrix.
Example video: https://youtu.be/QstXaLjiqK4
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Bach or Stravinsky (battle
of the sexes) game. `K = 2` resources represent "Bach" and "Stravinsky" pure
strategies.
Bach or Stravinsky is an asymmetric game. Players are assigned by their slot
id to be either row players (blue) or column players (orange). Interactions are
only resolved when they are between a row player and a column player. Otherwise,
e.g. when a row player tries to interact with another row player, then nothing
happens.
Players have the default `11 x 11` (off center) observation window.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is light blue.
RESOURCE1_COLOR = (123, 231, 255, 255)
RESOURCE1_HIGHLIGHT_COLOR = (157, 217, 230, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is light orange.
RESOURCE2_COLOR = (255, 163, 123, 255)
RESOURCE2_HIGHLIGHT_COLOR = (230, 170, 157, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWW
WPPPP W W PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
W W
W 11 W
W 11 W
W aa W
W WW W 222 W
WW 1a W 222 W
WWW 1a WWWWWWWWW W
W 1a 111 WWW
W 111 W
W aa W W
W 22 W WW W
W 22 Waaa W
W 222 W
W W
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP W PPPPW
WWWWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"P": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 32
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"randomTieBreaking": True,
"matrix": [
# row player chooses a row of this matrix.
# B S
[3, 0], # B
[0, 2], # S
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# B S
[2, 0], # B
[0, 3], # S
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue
(0.0, 0.5), (0.5, 1.5), (1.5, 2.5), (2.5, 3.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
}
]
}
return scene
def create_resource_prefab(resource_id, color_data):
"""Creates resource prefab with provided `resource_id` (num) and color."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": color_data[0],
"#": color_data[1],
"x": (0, 0, 0, 0)}],
"noRotates": [False]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.04,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)
prefabs["resource_class2"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)
return prefabs
def create_avatar_object(player_idx: int,
color: Tuple[int, int, int],
row_player: bool) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(color)],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "DyadicRole",
"kwargs": {
"rowPlayer": row_player,
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 1.0,
"defaultTastinessReward": 0.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_avatar_objects(
roles: Sequence[str],
) -> Sequence[PrefabConfig]:
"""Returns all avatar game objects."""
avatar_objects = []
for player_idx, role in enumerate(roles):
if role == "default":
if player_idx % 2 == 0:
row_player = True
color = (50, 100, 200)
elif player_idx % 2 == 1:
row_player = False
color = (200, 100, 50)
else:
if role == "bach_fan":
row_player = True
color = (50, 100, 200)
elif role == "stravinsky_fan":
row_player = False
color = (200, 100, 50)
avatar = create_avatar_object(player_idx, color, row_player)
avatar_objects.append(avatar)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(192, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default", "bach_fan", "stravinsky_fan"})
config.default_player_roles = ("bach_fan",) * 4 + ("stravinsky_fan",) * 4
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(roles=roles),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/bach_or_stravinsky_in_the_matrix__arena.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for predator_prey__open.
Example video: https://youtu.be/0ZlrkWsWzMw
See predator_prey.py for a detailed description applicable to all predator_prey
substrates.
In this variant prey must forage over a large field of apples and acorns in the
center of the map. Since the space is so open it should be possible for the prey
to move together in larger groups so they can defend themselves from predators.
Another prey strategy focused on acorns instead of apples is also possible. In
this case prey collect acorns and bring them back to safe tall grass to consume
them.
"""
from meltingpot.configs.substrates import predator_prey as base_config
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
ASCII_MAP = """
/;___________________,/
;]*******************[,
!vvvvvvvvvvvvvvvvvvvvv|
!'''''''''''''''''''''|
!''XXXXXXXXXXXXXXXXX''|
!''XAaaaaaaaaaaAaaaX''|
!''Xaaaa&aaaAaaaaaaX''|
!'aaaaaaaaaaaaaaaaaaa'|
!Aaaaaaaaaaaaaaaaaaaaa|
!aaaaaaaaaaaaaaAaaaaaa|
!aAaaaaaaaaaaaaaaa&aaA|
!'aaaaaaAaaaaaaaaaAaa'|
!''Xaaaaaaa&aaaaaaaX''|
!''XaaaaaaaaAaaaaaaX''|
!''XXXXXXXXXXXXXXXXX''|
!'''''''''''''''''''''|
!^^^^^^^^^^^^^^^^^^^^^|
L+*******************=J
/L~~~~~~~~~~~~~~~~~~~J/
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"*": {"type": "all", "list": ["safe_grass", "spawn_point_prey"]},
"&": {"type": "all", "list": ["tiled_floor", "apple", "spawn_point_prey"]},
"X": {"type": "all", "list": ["tiled_floor", "spawn_point_predator"]},
"a": {"type": "all", "list": ["tiled_floor", "apple"]},
"A": {"type": "all", "list": ["tiled_floor", "floor_acorn"]},
";": "nw_wall_corner",
",": "ne_wall_corner",
"J": "se_wall_corner",
"L": "sw_wall_corner",
"_": "wall_north",
"|": "wall_east",
"~": "wall_south",
"!": "wall_west",
"=": "nw_inner_wall_corner",
"+": "ne_inner_wall_corner",
"]": "se_inner_wall_corner",
"[": "sw_inner_wall_corner",
"'": "tiled_floor",
"#": "safe_grass",
"<": "safe_grass_w_edge",
"^": "safe_grass_n_edge",
">": "safe_grass_e_edge",
"v": "safe_grass_s_edge",
"l": "safe_grass_ne_corner",
"j": "safe_grass_se_corner",
"z": "safe_grass_sw_corner",
"r": "safe_grass_nw_corner",
"/": "fill",
}
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
config.layout.char_prefab_map = CHAR_PREFAB_MAP
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"STAMINA": specs.float64(),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(152, 184),
})
# The roles assigned to each player.
config.default_player_roles = ("predator",) * 3 + ("prey",) * 10
return config
|
meltingpot-main
|
meltingpot/configs/substrates/predator_prey__open.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Chemistry: Two Metabolic Cycles.
Example video: https://youtu.be/kxMNAcJuXJE
Individuals benefit from two different food generating reaction cycles.
The cycles will run on their own (autocatalytically), but require energy to
continue. Bringing together side products from the two cycles generates new
energy such that the cycles can continue. The population needs to keep both of
these cycles running to get high rewards.
Reactions are defined by a directed graph. Reactant nodes project into reaction
nodes, which project out to product nodes. Reactions occur stochastically when
all reactants are brought near one another. Agents can carry a single molecule
around the map with them at a time. Agents are rewarded when a specific reaction
occurs that involves the molecule they are currently carrying (as either a
reactant or a product).
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.configs.substrates import reaction_graph_utils as graph_utils
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import networkx as nx
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# Map reaction to rewards.
DEFAULT_REWARDING_REACTIONS = {"MetabolizeFood1": 1,
"MetabolizeFood2": 1,
"MetabolizeXY": 10,}
# Define the default reaction query configuration. It can be overridden on a per
# compount basis.
DEFAULT_REACTION_CONFIG = {"radius": 1, "query_type": "disc"}
REACTIVITY_LEVELS = {
"ground": {"background": 0.00001,
"low": 0.005,
"medium": 0.001,
"high": 0.9},
"vesicle": {"background": 0.0,
"low": 0.0025,
"medium": 0.25,
"high": 0.9},
}
def dissipate_when_paired(g: nx.MultiDiGraph, reaction_name: str,
compound: str):
g.add_node(reaction_name, reaction=True)
# Reactants:
g.add_edge(compound, reaction_name)
g.add_edge(compound, reaction_name)
# Products:
g.add_edge(reaction_name, "empty")
g.add_edge(reaction_name, "empty")
def cycle(g: nx.MultiDiGraph, reaction_prefix: str,
intermediates: Sequence[str], product: str,
secondary_product: str, food: str = "food"):
"""Add a reaction cycle."""
# Reaction cycle x, reaction 1
reaction_1 = "{}1{}".format(reaction_prefix, product)
g.add_node(reaction_1, reaction=True)
# Reactants:
g.add_edge(intermediates[0], reaction_1)
g.add_edge(intermediates[1], reaction_1)
g.add_edge("empty", reaction_1)
# Products:
g.add_edge(reaction_1, intermediates[1])
g.add_edge(reaction_1, intermediates[2])
g.add_edge(reaction_1, food)
# Reaction cycle x, reaction 2
reaction_2 = "{}2{}".format(reaction_prefix, product)
g.add_node(reaction_2, reaction=True)
# Reactants:
g.add_edge(intermediates[1], reaction_2)
g.add_edge(intermediates[2], reaction_2)
g.add_edge("energy", reaction_2)
# Products:
g.add_edge(reaction_2, intermediates[2])
g.add_edge(reaction_2, intermediates[0])
g.add_edge(reaction_2, "energy")
# Reaction cycle x, reaction 3
reaction_3 = "{}3{}".format(reaction_prefix, product)
g.add_node(reaction_3, reaction=True)
# Reactants:
g.add_edge(intermediates[2], reaction_3)
g.add_edge(intermediates[0], reaction_3)
g.add_edge("empty", reaction_3)
if secondary_product is not None:
g.add_edge("empty", reaction_3)
# Products:
g.add_edge(reaction_3, intermediates[0])
g.add_edge(reaction_3, intermediates[1])
g.add_edge(reaction_3, product)
if secondary_product is not None:
g.add_edge(reaction_3, secondary_product)
def make_graph():
"""User defined graph construction function using networkx."""
# Note: You can copy-paste this function into colab to visualize the graph.
g = nx.MultiDiGraph()
# First add the "empty" and "activated" nodes, which are always present.
graph_utils.add_system_nodes(g)
cycle(g, "R",
intermediates=["ax", "bx", "cx"],
product="x",
secondary_product="iy",
food="food1")
cycle(g, "R",
intermediates=["ay", "by", "cy"],
product="y",
secondary_product="ix",
food="food2")
# Inhibit x with a product of the y-producing cycle.
g.add_node("InhibitX", reaction=True)
# Reactants:
g.add_edge("x", "InhibitX")
g.add_edge("ix", "InhibitX")
# Products:
g.add_edge("InhibitX", "empty")
g.add_edge("InhibitX", "empty")
# Inhibit y with a product of the x-producing cycle.
g.add_node("InhibitY", reaction=True)
# Reactants:
g.add_edge("y", "InhibitY")
g.add_edge("iy", "InhibitY")
# Products:
g.add_edge("InhibitY", "empty")
g.add_edge("InhibitY", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood1", reaction=True)
# Reactants:
g.add_edge("food1", "MetabolizeFood1")
# Products:
g.add_edge("MetabolizeFood1", "empty")
# Food can be metabolized in the vesicle.
g.add_node("MetabolizeFood2", reaction=True)
# Reactants:
g.add_edge("food2", "MetabolizeFood2")
# Products:
g.add_edge("MetabolizeFood2", "empty")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood1", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood1")
# Products:
g.add_edge("SpawnFood1", "food1")
# Food spontaneously appears from time to time.
g.add_node("SpawnFood2", reaction=True)
# Reactants:
g.add_edge("empty", "SpawnFood2")
# Products:
g.add_edge("SpawnFood2", "food2")
# x and y can be combined to produce energy.
g.add_node("MetabolizeXY", reaction=True)
# Reactants:
g.add_edge("x", "MetabolizeXY")
g.add_edge("y", "MetabolizeXY")
# Products:
g.add_edge("MetabolizeXY", "energy")
g.add_edge("MetabolizeXY", "energy")
# Energy spontaneously dissipates.
g.add_node("DissipateEnergy", reaction=True)
# Reactants:
g.add_edge("energy", "DissipateEnergy")
# Products:
g.add_edge("DissipateEnergy", "empty")
# Prevent inhibitors from accumulating by dissipating them whenever they pair.
dissipate_when_paired(g, "DissipateIX", "ix")
dissipate_when_paired(g, "DissipateIY", "iy")
# Properties of compounds
# Color:
g.nodes["ax"]["color"] = (153, 204, 255, 255) # blue 1
g.nodes["bx"]["color"] = (102, 204, 255, 255) # blue 2
g.nodes["cx"]["color"] = (51, 153, 255, 255) # blue 3
g.nodes["ay"]["color"] = (102, 255, 153, 255) # green 1
g.nodes["by"]["color"] = (102, 255, 102, 255) # green 2
g.nodes["cy"]["color"] = (0, 255, 0, 255) # green 3
g.nodes["x"]["color"] = (0, 51, 204, 255) # dark blue
g.nodes["y"]["color"] = (0, 51, 0, 255) # dark green
g.nodes["food1"]["color"] = (178, 151, 0, 255) # light gold
g.nodes["food1"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["food2"]["color"] = (255, 215, 0, 255) # gold
g.nodes["food2"]["sprite"] = graph_utils.FOOD_SHAPE
g.nodes["energy"]["color"] = (255, 0, 0, 255) # red
g.nodes["energy"]["sprite"] = graph_utils.ENERGY_SHAPE
g.nodes["ix"]["color"] = (102, 153, 153, 255) # greyish green
g.nodes["iy"]["color"] = (51, 102, 153, 255) # greyish blue
# Reactivity:
g.nodes["ax"]["reactivity"] = "high"
g.nodes["bx"]["reactivity"] = "high"
g.nodes["cx"]["reactivity"] = "high"
g.nodes["ay"]["reactivity"] = "high"
g.nodes["by"]["reactivity"] = "high"
g.nodes["cy"]["reactivity"] = "high"
g.nodes["x"]["reactivity"] = "medium"
g.nodes["y"]["reactivity"] = "medium"
g.nodes["ix"]["reactivity"] = "high"
g.nodes["iy"]["reactivity"] = "high"
g.nodes["food1"]["reactivity"] = "medium"
g.nodes["food2"]["reactivity"] = "medium"
g.nodes["energy"]["reactivity"] = "low"
g.nodes["empty"]["reactivity"] = "background"
# The following commented line documents how to set the query config for a
# specific compound, overriding the default query configuration.
# g.nodes["food1"]["query_config"] = {"radius": 3, "queryType": "diamond"}
return g
ASCII_MAP = """
~~~~~~~~~~~a~~~~~~~~~~~~~
~~~~~~~~c~~~~~~~~~~~~~~~~
~~~~~~~~~~~b~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~1~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
1~~3~~~~hhhhhhh~~~~~3~~2~
~~~~~~~~~~~~~~~~~~~~~~~~~
~2~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~c~~~~~~~~~~~~~~~~~
~~~~~~~~~a~~~~~~~~~~~~~~~
~~~~~~~b~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# `prefab` determines which compound to use for each `char` in the ascii map.
CHAR_PREFAB_MAP = {
"~": "empty",
"a": "ax",
"b": "bx",
"c": "cx",
"1": "ay",
"2": "by",
"3": "cy",
"4": "az",
"5": "bz",
"6": "cz",
"x": "food4",
"h": "energy",
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 60
PLAYER_COLOR_PALETTES = []
for i in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[i]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "ioAction": 0}
FORWARD = {"move": 1, "turn": 0, "ioAction": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "ioAction": 0}
BACKWARD = {"move": 3, "turn": 0, "ioAction": 0}
STEP_LEFT = {"move": 4, "turn": 0, "ioAction": 0}
TURN_LEFT = {"move": 0, "turn": -1, "ioAction": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "ioAction": 0}
IO_ACTION = {"move": 0, "turn": 0, "ioAction": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
IO_ACTION,
)
TARGET_SPRITE_SELF_EMPTY = {
"name": "SelfEmpty",
"shape": shapes.CYTOAVATAR_EMPTY,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
TARGET_SPRITE_SELF_HOLDS_ONE = {
"name": "SelfHoldsOne",
"shape": shapes.CYTOAVATAR_HOLDING_ONE,
"palette": shapes.CYTOAVATAR_PALETTE,
"noRotate": True,
}
def create_avatar_objects(num_players, compounds):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
additional_game_objects = []
for player_idx in range(0, num_players):
game_object = graph_utils.create_avatar_constant_self_view(
rewarding_reactions=DEFAULT_REWARDING_REACTIONS,
player_idx=player_idx,
target_sprite_self_empty=TARGET_SPRITE_SELF_EMPTY,
target_sprite_self_holds_one=TARGET_SPRITE_SELF_HOLDS_ONE,
add_location_observer=_ENABLE_DEBUG_OBSERVATIONS)
avatar_objects.append(game_object)
# Add the overlaid avatar vesicle on top of each avatar.
avatar_vesicle = graph_utils.create_vesicle(
player_idx=player_idx,
compounds=compounds,
reactivity_levels=REACTIVITY_LEVELS["vesicle"],
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
additional_game_objects.append(avatar_vesicle)
return avatar_objects, additional_game_objects
def get_config():
"""Default configuration for this substrate."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(112, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate."""
del config
num_players = len(roles)
# Must create compounds and reactions.
compounds, reactions = graph_utils.graph_semantics(make_graph())
cell_prefabs = {}
cell_prefabs = graph_utils.add_compounds_to_prefabs_dictionary(
cell_prefabs, compounds, REACTIVITY_LEVELS["ground"], sprites=True,
default_reaction_radius=DEFAULT_REACTION_CONFIG["radius"],
default_reaction_query_type=DEFAULT_REACTION_CONFIG["query_type"],
priority_mode=True)
avatar_objects, additional_objects = create_avatar_objects(num_players,
compounds)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="grid_land",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"].
simulation={
"map": ASCII_MAP,
"gameObjects": avatar_objects + additional_objects,
"scene": graph_utils.create_scene(reactions,
stochastic_episode_ending=True),
"prefabs": cell_prefabs,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/chemistry__two_metabolic_cycles.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Collaborative Cooking: Forced.
Example video: https://youtu.be/FV_xZuSCRmM
The recipe they must follow is for tomato soup:
1. Add three tomatoes to the cooking pot.
2. Wait for the soup to cook (status bar completion).
3. Bring a bowl to the pot and pour the soup from the pot into the bowl.
4. Deliver the bowl of soup at the goal location.
This substrate is a pure common interest game. All players share all rewards.
Players have a `5 x 5` observation window.
Map:
Forced Coordination: One player is in the left room and second player is in the
right room. Consequently, both players are forced to work together in order to
cook and deliver soup. The player in the left room can only pass tomatoes and
dishes, while the player on the right can only cook the soup and deliver it
(using the items provided by the first player).
"""
from meltingpot.configs.substrates import collaborative_cooking as base_config
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
# Forced Coordination: A two-room layout in which agents cannot complete the
# task alone and therefore must work together, with one player passing tomatoes
# and plates to the other, and the other player loading the pot and delivering
# soups.
ASCII_MAP = """
xx###C#xx
xxO #PCxx
xxOP# #xx
xxD # #xx
xx###T#xx
"""
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(40, 72),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
|
meltingpot-main
|
meltingpot/configs/substrates/collaborative_cooking__forced.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Factory of the Commons: Either Or."""
from meltingpot.configs.substrates import factory_commons as base_config
from meltingpot.utils.substrates import map_helpers
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
ASCII_MAP = """
;_____________________,
! c |
! cCc |
! ls ls C lt lt |
! Oj Oj O# O# |
! z z z z |
! x x x x |
! cCc |
! cCc |
! ls ls lt lt |
! Oj Oj O# O# |
! z z z z |
! x x C x x |
! cCc |
! c |
_______________________
"""
blue_cube_live = {
"type": "all", "list": ["tiled_floor", "blue_cube_wait", "blue_cube_live"]}
blue_cube_wait = {
"type": "all", "list": ["tiled_floor", "blue_cube_wait"]}
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
" ": {"type": "all", "list": ["tiled_floor", "apple", "spawn_point"]},
# Graspable objects.
"c": map_helpers.a_or_b_with_odds(blue_cube_wait,
blue_cube_live, odds=(1, 1)),
"C": blue_cube_live, # This blue cube will always be present.
# New dynamic components.
"l": {"type": "all", "list": ["tiled_floor", "hopper_body",
"hopper_indicator_blue_cube"]},
"O": {"type": "all", "list": ["tiled_floor", "hopper_mouth"]},
"D": {"type": "all", "list": ["tiled_floor", "dispenser_body",
"dispenser_indicator_apple"]},
"t": {"type": "all", "list": ["tiled_floor", "dispenser_body",
"dispenser_indicator_two_apples"]},
"s": {"type": "all", "list": ["tiled_floor", "dispenser_body",
"dispenser_indicator_cube_apple"]},
"#": {"type": "all", "list": ["tiled_floor", "dispenser_belt",
"apple_dispensing_animation"]},
"j": {"type": "all", "list": ["tiled_floor", "dispenser_belt",
"cube_apple_dispensing_animation"]},
"z": {"type": "all", "list": ["tiled_floor", "floor_marking_top"]},
"x": {"type": "all", "list": ["tiled_floor", "floor_marking_bottom"]},
# Static components.
";": {"type": "all", "list": ["tiled_floor", "nw_wall_corner"]},
",": {"type": "all", "list": ["tiled_floor", "ne_wall_corner"]},
"_": "wall_horizontal",
"T": "wall_t_coupling",
"|": {"type": "all", "list": ["tiled_floor", "wall_east"]},
"!": {"type": "all", "list": ["tiled_floor", "wall_west"]},
"i": {"type": "all", "list": ["tiled_floor", "wall_middle"]},
"~": {"type": "all", "list": ["tiled_floor", "threshold"]},
}
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Specify a recommended number of players to particate in each episode.
config.recommended_num_players = 3
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
config.layout.char_prefab_map = CHAR_PREFAB_MAP
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 3
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
"STAMINA": specs.float64(),
# Debug only.
"WORLD.RGB": specs.rgb(128, 184),
})
return config
|
meltingpot-main
|
meltingpot/configs/substrates/factory_commons__either_or.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Externality Mushrooms.
Externality mushrooms is an immediate feedback collective action problem and
social dilemma. Unlike the other sequential social dilemmas in this suite, there
is no delay between the time when an agent takes an antisocial (or prosocial)
action and when its effect is felt by all other players. Thus it is a
sequential social dilemma in the sense of Leibo et al. 2017, but not an
intertemporal social dilemma in the sense of Hughes et al. 2018.
Three types of mushrooms are spread around the map and can be consumed for a
reward. Eating a red mushroom gives a reward of 1 to the individual who
ate the mushroom. Eating a green mushroom gives a reward of 2 and it gets
divided equally among all individuals. Eating a blue mushroom gives a reward of
3 and it gets divided among the individuals except the individual who ate the
mushroom. Mushrooms regrowth depends on the type of the mushrooms eaten by
individuals. Red mushrooms regrow with a probability of 0.25 when a mushroom of
any color is eaten. Green mushrooms regrow with a probability of 0.4 when a
green or blue mushroom is eaten. Blue mushrooms regrow with a probability of 0.6
when a blue mushroom is eaten. Each mushroom has a time period that it takes to
digest it. An individual who ate a mushroom gets frozen during the time they are
digesting it. Red mushrooms get digested instantly, green and blue mushrooms
take 5 and 10 steps to digest respectively. In addition, unharvested mushrooms
spoil (and get removed from the game) after a period of time. Red, green and
blue mushrooms spoil after 75, 100 and 200 time steps respectively.
References:
Leibo JZ, Zambaldi V, Lanctot M, Marecki J, Graepel T. Multi-agent Reinforcement
Learning in Sequential Social Dilemmas (2017). AAMAS.
Hughes E, Leibo JZ, Phillips MG, Tuyls K, Duenez-Guzman EA, Garcia Castaneda A,
Dunning I, Zhu T, McKee KR, Koster R, Roff H, Graepel T. Inequity aversion
improves cooperation in intertemporal social dilemmas (2018). NeurIPS.
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ["N", "E", "S", "W"]
MARKING_SPRITE = """
oxxxxxxo
xoxxxxox
xxoxxoxx
xxxooxxx
xxxooxxx
xxoxxoxx
xoxxxxox
oxxxxxxo
"""
NW_WALL_CORNER = {
"name": "nw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_wall_corner",
"stateConfigs": [{
"state": "nw_wall_corner",
"layer": "upperPhysical",
"sprite": "NwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwWallCorner"],
"spriteShapes": [shapes.FENCE_NW_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
NE_WALL_CORNER = {
"name": "ne_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_wall_corner",
"stateConfigs": [{
"state": "ne_wall_corner",
"layer": "upperPhysical",
"sprite": "NeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeWallCorner"],
"spriteShapes": [shapes.FENCE_NE_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
NE_INNER_WALL_CORNER = {
"name": "ne_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_inner_wall_corner",
"stateConfigs": [{
"state": "ne_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "ne_inner_wall_corner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["ne_inner_wall_corner"],
"spriteShapes": [shapes.FENCE_INNER_NE_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
NW_INNER_WALL_CORNER = {
"name": "nw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_inner_wall_corner",
"stateConfigs": [{
"state": "nw_inner_wall_corner",
"layer": "upperPhysical",
"sprite": "nw_inner_wall_corner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["nw_inner_wall_corner"],
"spriteShapes": [shapes.FENCE_INNER_NW_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
SE_WALL_CORNER = {
"name": "se_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_wall_corner",
"stateConfigs": [{
"state": "se_wall_corner",
"layer": "upperPhysical",
"sprite": "SeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeWallCorner"],
"spriteShapes": [shapes.FENCE_SE_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
SW_WALL_CORNER = {
"name": "sw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_wall_corner",
"stateConfigs": [{
"state": "sw_wall_corner",
"layer": "upperPhysical",
"sprite": "SwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwWallCorner"],
"spriteShapes": [shapes.FENCE_SW_CORNER],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_SHADOW_SW = {
"name": "wall_shadow_sw",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_sw",
"stateConfigs": [{
"state": "wall_shadow_sw",
"layer": "upperPhysical",
"sprite": "wall_shadow_sw",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_sw"],
"spriteShapes": [shapes.FENCE_SHADOW_SW],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_SHADOW_S = {
"name": "wall_shadow_s",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_s",
"stateConfigs": [{
"state": "wall_shadow_s",
"layer": "upperPhysical",
"sprite": "wall_shadow_s",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_s"],
"spriteShapes": [shapes.FENCE_SHADOW_S],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_SHADOW_SE = {
"name": "wall_shadow_se",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_shadow_se",
"stateConfigs": [{
"state": "wall_shadow_se",
"layer": "upperPhysical",
"sprite": "wall_shadow_se",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["wall_shadow_se"],
"spriteShapes": [shapes.FENCE_SHADOW_SE],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_NORTH = {
"name": "wall_north",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_north",
"stateConfigs": [{
"state": "wall_north",
"layer": "upperPhysical",
"sprite": "WallNorth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallNorth"],
"spriteShapes": [shapes.FENCE_N],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_EAST = {
"name": "wall_east",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_east",
"stateConfigs": [{
"state": "wall_east",
"layer": "upperPhysical",
"sprite": "WallEast",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallEast"],
"spriteShapes": [shapes.FENCE_E],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_SOUTH = {
"name": "wall_south",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_south",
"stateConfigs": [{
"state": "wall_south",
"layer": "upperPhysical",
"sprite": "WallSouth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallSouth"],
"spriteShapes": [shapes.FENCE_S],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
WALL_WEST = {
"name": "wall_west",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_west",
"stateConfigs": [{
"state": "wall_west",
"layer": "upperPhysical",
"sprite": "WallWest",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallWest"],
"spriteShapes": [shapes.FENCE_W],
"palettes": [shapes.FENCE_PALETTE_BROWN],
"noRotates": [False]
}
},
{"component": "BeamBlocker", "kwargs": {"beamType": "zapHit"}},
]
}
def get_marking_palette(alpha: float) -> Mapping[str, Sequence[int]]:
alpha_uint8 = int(alpha * 255)
assert alpha_uint8 >= 0.0 and alpha_uint8 <= 255, "Color value out of range."
return {"x": shapes.ALPHA, "o": (0, 0, 0, alpha_uint8)}
DIRT = {
"name": "dirt",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "dirt",
"stateConfigs": [{
"state": "dirt",
"layer": "background",
"sprite": "Dirt",
}],
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Dirt"],
"spriteShapes": [shapes.DIRT_PATTERN],
"palettes": [{
"x": (81, 70, 32, 255),
"X": (89, 77, 36, 255),
}],
"noRotates": [False]
}
},
{
"component": "Transform",
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
def create_mushroom(initial_state: str = "wait"):
"""Create a mushroom prefab object."""
mushroom_prefab = {
"name": "mushroom",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{
"state": "fullInternalityZeroExternality",
"layer": "lowerPhysical",
"sprite": "FullInternalityZeroExternality",
"groups": ["fullInternalityZeroExternality"],
},
{
"state": "halfInternalityHalfExternality",
"layer": "lowerPhysical",
"sprite": "HalfInternalityHalfExternality",
"groups": ["halfInternalityHalfExternality"],
},
{
"state": "zeroInternalityFullExternality",
"layer": "lowerPhysical",
"sprite": "ZeroInternalityFullExternality",
"groups": ["zeroInternalityFullExternality"],
},
{
"state": "negativeInternalityNegativeExternality",
"layer": "lowerPhysical",
"sprite": "NegativeInternalityNegativeExternality",
"groups": ["negativeInternalityNegativeExternality"],
},
{
"state": "wait",
},
],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["FullInternalityZeroExternality",
"HalfInternalityHalfExternality",
"ZeroInternalityFullExternality",
"NegativeInternalityNegativeExternality"],
"spriteShapes": [shapes.MUSHROOM] * 4,
"palettes": [
shapes.MUSHROOM_RED_PALETTE,
shapes.MUSHROOM_GREEN_PALETTE,
shapes.MUSHROOM_BLUE_PALETTE,
shapes.MUSHROOM_ORANGE_PALETTE,
],
"noRotates": [True] * 4
}
},
{
"component": "MushroomEating",
"kwargs": {
"totalReward": {
"fullInternalityZeroExternality": 1,
"halfInternalityHalfExternality": 2,
"zeroInternalityFullExternality": 3,
"negativeInternalityNegativeExternality": -1.0,
},
"liveStates": ("fullInternalityZeroExternality",
"halfInternalityHalfExternality",
"zeroInternalityFullExternality",
"negativeInternalityNegativeExternality"),
"numSporesReleasedWhenEaten": {
"fullInternalityZeroExternality": 3,
"halfInternalityHalfExternality": 3,
"zeroInternalityFullExternality": 3,
"negativeInternalityNegativeExternality": 1,
},
"digestionTimes": {
"fullInternalityZeroExternality": 0,
"halfInternalityHalfExternality": 10,
"zeroInternalityFullExternality": 15,
"negativeInternalityNegativeExternality": 15,
},
"destroyOnEating": {
"negativeInternalityNegativeExternality": {
"typeToDestroy": "fullInternalityZeroExternality",
"percentToDestroy": 0.25},
},
},
},
{
"component": "MushroomGrowable",
"kwargs": {}
},
{
"component": "Destroyable",
"kwargs": {
"initialHealth": 1,
"waitState": "wait",
}
},
{
"component": "Perishable",
"kwargs": {
"waitState": "wait",
"delayPerState": {
"fullInternalityZeroExternality": 200,
"halfInternalityHalfExternality": 100,
"zeroInternalityFullExternality": 75,
"negativeInternalityNegativeExternality": 1e7,
}
}
},
]
}
return mushroom_prefab
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0}
FIRE_ZAP = {"move": 0, "turn": 0, "fireZap": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP,
)
# Remove the first entry from human_readable_colors after using it for the self
# color to prevent it from being used again as another avatar color.
light_desaturated_avatar_palette = list(
colors.light_desaturated_avatar_palette)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette(light_desaturated_avatar_palette.pop(0)),
"noRotate": True,
}
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"dirt": DIRT,
"spawn_point": SPAWN_POINT,
"red_mushroom": create_mushroom(
initial_state="fullInternalityZeroExternality"),
"green_mushroom": create_mushroom(
initial_state="halfInternalityHalfExternality"),
"blue_mushroom": create_mushroom(
initial_state="zeroInternalityFullExternality"),
"orange_mushroom": create_mushroom(
initial_state="negativeInternalityNegativeExternality"),
"potential_mushroom": create_mushroom(initial_state="wait"),
# fence prefabs
"nw_wall_corner": NW_WALL_CORNER,
"nw_inner_wall_corner": NW_INNER_WALL_CORNER,
"ne_wall_corner": NE_WALL_CORNER,
"ne_inner_wall_corner": NE_INNER_WALL_CORNER,
"se_wall_corner": SE_WALL_CORNER,
"sw_wall_corner": SW_WALL_CORNER,
"wall_north": WALL_NORTH,
"wall_east": WALL_EAST,
"wall_south": WALL_SOUTH,
"wall_west": WALL_WEST,
"wall_shadow_sw": WALL_SHADOW_SW,
"wall_shadow_s": WALL_SHADOW_S,
"wall_shadow_se": WALL_SHADOW_SE,
}
return prefabs
def create_scene():
"""Create the scene object, a non-physical object to hold global logic."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "MushroomRegrowth",
"kwargs": {
"mushroomsToProbabilities": {
"fullInternalityZeroExternality": {
"fullInternalityZeroExternality": 0.25,
"halfInternalityHalfExternality": 0.0,
"zeroInternalityFullExternality": 0.0,
"negativeInternalityNegativeExternality": 0.0,
},
"halfInternalityHalfExternality": {
"fullInternalityZeroExternality": 0.25,
"halfInternalityHalfExternality": 0.4,
"zeroInternalityFullExternality": 0.0,
"negativeInternalityNegativeExternality": 0.0,
},
"zeroInternalityFullExternality": {
"fullInternalityZeroExternality": 0.25,
"halfInternalityHalfExternality": 0.4,
"zeroInternalityFullExternality": 0.6,
"negativeInternalityNegativeExternality": 0.0,
},
"negativeInternalityNegativeExternality": {
"fullInternalityZeroExternality": 0.0,
"halfInternalityHalfExternality": 0.0,
"zeroInternalityFullExternality": 0.0,
"negativeInternalityNegativeExternality": 1.0,
},
},
"minPotentialMushrooms": 1,
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
},
]
}
return scene
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": f"avatar{lua_index}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
# Initial player state.
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
# Player wait type for times when they are zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [
shapes.get_palette(
light_desaturated_avatar_palette[player_idx])
],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": ["move",
"turn",
"fireZap"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
}
},
{
"component": "Zapper",
"kwargs": {
"cooldownTime": 3,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"penaltyForBeingZapped": 0,
"rewardForZapping": 0,
# GraduatedSanctionsMarking handles removal instead of Zapper.
"removeHitPlayer": False,
}
},
{
"component": "ReadyToShootObservation",
},
{
"component": "Cumulants",
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
avatar_object["components"].append({
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
"name": "ATE_MUSHROOM_FIZE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "ate_mushroom_fize",
},
{
"name": "ATE_MUSHROOM_HIHE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "ate_mushroom_hihe",
},
{
"name": "ATE_MUSHROOM_ZIFE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "ate_mushroom_zife",
},
{
"name": "ATE_MUSHROOM_NINE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "ate_mushroom_nine",
},
{
"name": "DESTROYED_MUSHROOM_FIZE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "destroyed_mushroom_fize",
},
{
"name": "DESTROYED_MUSHROOM_HIHE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "destroyed_mushroom_hihe",
},
{
"name": "DESTROYED_MUSHROOM_ZIFE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "destroyed_mushroom_zife",
},
{
"name": "DESTROYED_MUSHROOM_NINE",
"type": "Doubles",
"shape": [],
"component": "Cumulants",
"variable": "destroyed_mushroom_nine",
},
]
},
})
return avatar_object
def create_marking_overlay(player_idx: int) -> Mapping[str, Any]:
"""Create a graduated sanctions marking overlay object."""
# Lua is 1-indexed.
lua_idx = player_idx + 1
marking_object = {
"name": "avatar_marking",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "avatarMarkingWait",
"stateConfigs": [
# Declare one state per level of the hit logic.
{"state": "level_1",
"layer": "superOverlay",
"sprite": "sprite_for_level_1"},
{"state": "level_2",
"layer": "superOverlay",
"sprite": "sprite_for_level_2"},
# Invisible inactive (zapped out) overlay type.
{"state": "avatarMarkingWait",
"groups": ["avatarMarkingWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["sprite_for_level_1",
"sprite_for_level_2"],
"spriteShapes": [MARKING_SPRITE,
MARKING_SPRITE],
"palettes": [get_marking_palette(0.0),
get_marking_palette(1.0)],
"noRotates": [True] * 3
}
},
{
"component": "GraduatedSanctionsMarking",
"kwargs": {
"playerIndex": lua_idx,
"waitState": "avatarMarkingWait",
"hitName": "zapHit",
"recoveryTime": 50,
"hitLogic": [
{"levelIncrement": 1,
"sourceReward": 0,
"targetReward": 0,
"freeze": 25},
{"levelIncrement": -1,
"sourceReward": 0,
"targetReward": 0,
"remove": True}
],
}
},
]
}
return marking_object
def create_avatar_objects(num_players):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(player_idx,
TARGET_SPRITE_SELF)
avatar_objects.append(game_object)
marking_object = create_marking_overlay(player_idx)
avatar_objects.append(marking_object)
return avatar_objects
def get_config():
"""Default configuration for this substrate."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given player roles."""
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="externality_mushrooms",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": config.layout.ascii_map,
"gameObjects": create_avatar_objects(num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": config.layout.char_prefab_map,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/externality_mushrooms.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Territory: Open.
Example video: https://youtu.be/F1OO6LFIZHI
Players can claim a resource in two ways: (1) by touching it, and (2) by using a
"claiming beam", different from the zapping beam, which they also have.
Claimed resources are colored in the unique color of the player that claimed
them. Unclaimed resources are gray. Players cannot walk through resources, they
are like walls.
Once a resource has been claimed a countdown begins. After 100 timesteps, the
claimed resource becomes active. This is visualized by a white and gray plus
sign appearing on top. Active resources provide reward stochastically to the
player that claimed them at a rate of 0.01 per timestep. Thus the more resources
a player claims and can hold until they become active, the more reward they
obtain.
The claiming beam is of length 2. It can color through a resource to
simultaneously color a second resource on the other side. If two players stand
on opposite sides of a wall of resources of width 2 and one player claims all
the way across to the other side (closer to the other player than themselves)
then the player on the other side might reasonably perceive that as a somewhat
aggressive action. Less aggressive of course than the other option both players
have: using their zapping beam. If any resource is zapped twice then it gets
permanently destroyed. It no longer functions as a wall or a resource, allowing
players to pass through.
Like resources, when players are hit by a zapping beam they also get removed
from the game and never regenerate. Once a player has been zapped out it is
gone. All resources it claimed are immediately returned to the unclaimed state.
"""
from meltingpot.configs.substrates import territory as base_config
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
ASCII_MAP = """
F=====================================T
|,,RRRRR,,RR,,RR,,,,,,RR,,,,,,RR,,,,,,|
|,,,,,RR,,,,,,RR,,,,,,RR,,,,,,,,,,,,,,|
|,,,,,RR,,,,,,RR,,,,,,,,,,,,,,,,,,,,,,|
|,RR,,RR,,,,,,RR,,,,,,,,,,R,,,RR,,,RR,|
|,,,,,RR,,,,,,RR,,,,,,,,,,R,,,RR,,,,,,|
|,,,,,RR,,,,,,,,,,RRRR,,,,R,,,,,,,,,,,|
|,,RR,RR,,,,,,,,,,,,,,,,,,R,,,,,,,,,,,|
|,,,,,RR,,,,,,,RR,,,,,,,,,R,,,,,,,,,,,|
|,,,,,RRRR,,,,,,,,,,,,,,,,,,,,,RR,,,,,|
|,,,,,,,,,,,,,,,,,,,,RR,,,,,,,,,,,,,,,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,|
|,,RRRR,,,RRRRRR,,,,,,,,,,,RR,,,,R,,,,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,R,,,,|
|,,,,,,,,,,,,,,,,RR,,,,,,,,,,,,,,,,P,,|
|,,,,RR,,,,,,,,,,,,,,,,RR,,,,,,,P,,,,,|
|,,,,,,,,,RR,,,,,,,,,,,,,,,,,,,,,P,,P,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,P,,P,,,,,,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,,,P,,,P,,,|
|,,P,,,,P,,,P,,P,,,P,,,,P,P,,P,,P,,P,,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,|
|,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,|
L=====================================J
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
resource_associated_prefabs = ["floor", "resource_texture", "resource",
"reward_indicator", "damage_indicator"]
resource = {"type": "all", "list": resource_associated_prefabs}
spawn_point_associated_prefabs = ["floor", "spawn_point"]
spawn_point = {"type": "all", "list": spawn_point_associated_prefabs}
CHAR_PREFAB_MAP = {
"P": spawn_point,
",": "floor",
"F": {"type": "all", "list": ["wall", "wall_highlight_nw"]},
"|": {"type": "all", "list": ["wall", "wall_highlight_e_w"]},
"=": {"type": "all", "list": ["wall", "wall_highlight_n_s"]},
"T": {"type": "all", "list": ["wall", "wall_highlight_ne"]},
"J": {"type": "all", "list": ["wall", "wall_highlight_se"]},
"L": {"type": "all", "list": ["wall", "wall_highlight_sw"]},
"R": resource,
}
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
config.layout.char_prefab_map = CHAR_PREFAB_MAP
config.layout.topology = "BOUNDED"
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(184, 312),
})
# The roles assigned to each player.
config.default_player_roles = ("default",) * 9
return config
|
meltingpot-main
|
meltingpot/configs/substrates/territory__open.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for coop_mining substrate.
Example video: https://youtu.be/KvwGUinjIsk
Two different types of ore appear at random in empty spaces. Players are
equipped with a mining beam that attempts to extract the ore. Iron ore (gray)
can be mined by a single player and confers a reward of 1 when extracted. Gold
ore (yellow) has to be mined by exactly two players within a time window of 3
timesteps and confers a reward of 8 to each of them. When a player mines a gold
ore, it flashes to indicate that it is ready to be mined by another player. If
no other player, or if too many players try to mine within that time, it will
revert back to normal.
This games has some properties in common with Stag-Hunt. Mining iron is akin to
playing Hare, with a reliable payoff, without needing to coordinate with others.
Mining gold is akin to Stag because it has an opportunity cost (not mining
iron). If noone else helps, mining gold gives no reward. However, if two players
stick together (spatially) and go around mining gold, they will both receive
higher reward than if they were mining iron.
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
NUM_ORE_TYPES = 2
MAX_TOKENS_PER_TYPE = 6
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWWWW
WOOOOOOOOOOOOOOOOOOOOOOOOOW
WOPOOOOOOOOOPOOOOOPOOOOOPOW
WOOOOOOOOWOOOOOOOOOOOOOOOOW
WOOOOOOOOWOOOOOOOOOOWOOOOOW
WOOOOOOOOWOOOOOOOOOOWOOOOOW
WOOOOOOOOWWWWWWWOOOOWOOOPOW
WOPOWWOOOOWOOOOOOOOOWOOOOOW
WOOOOOOOOOWOOPOOOOOOOOOOOOW
WOOOOOOOOOWOOOOOWWWOOOOOOOW
WOOOOOOOOOWOOOOOOOOOOOOOOOW
WOOOOOOOOOOOOOOOOOOOOOOOPOW
WOPOOOWWWOOOOOOWWWWWWWWOOOW
WOOWWWWOOOOOOOOOOOOOOOOOOOW
WOOOOOWOOOOWOOOOOPOOOOOOOOW
WOOOOOWOOOOWOOOOOOOOOOOOPOW
WOOOOOWOOOOOWOOOOOOOOWOOOOW
WOOOOOOWOOOOOWWWWOOOOWOOOOW
WOPOOOOOWOOOOOOOOOOOOWOOOOW
WOOOOOOOOWOOOPOOOOOOOOOOPOW
WOOOOOOOOOWOOOOOOOOWOOOOOOW
WOOOOWOOOOOOOOOOOOOWOOOOOOW
WOOOOWOOOOOOOOOWWWWWWWWOOOW
WOOOOWOOOOOOOOOOOOWOOOOOOOW
WOPOOOOOOPOOOOOOOPOOOOOOPOW
WOOOOOOOOOOOOOOOOOOOOOOOOOW
WWWWWWWWWWWWWWWWWWWWWWWWWWW
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"P": "spawn_point",
"W": "wall",
"O": "ore",
}
_COMPASS = ["N", "E", "S", "W"]
SCENE = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "mine"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
RAW_ORE = """
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxx*&&@xxxxxx
xxxxx****&@xxxxx
xxxx**&@*&**xxxx
xxxx*&*&*&@@@xxx
xxx****@&***&@xx
xx****&&*****&&x
******&*****&**&
****************
"""
PARTIAL_ORE = """
xxxxxxxxxxxxxxxx
xxxxxx#xx##xxxxx
xxxxxxx##xxxxxxx
xxxxxx##x#xxxxxx
x##xxxxxxxxxxxxx
xx###xxxxxxxx##x
xxx###xxx####xxx
xxxx#######xxxxx
xxxx######xxxxxx
xx###***###xxxxx
##xx**&@*&###xxx
xxxx*&*&*&@@##xx
xxx****@&***&@xx
xx****&&*****&&x
******&*****&**&
****************
"""
IRON_PALETTE = {
"*": (70, 60, 70, 255),
"&": (140, 120, 140, 255),
"@": (170, 160, 170, 255),
"#": (255, 240, 255, 255),
"x": (0, 0, 0, 0)
}
GOLD_PALETTE = {
"*": (90, 90, 20, 255),
"&": (180, 180, 40, 255),
"@": (220, 220, 60, 255),
"#": (255, 255, 240, 255),
"x": (0, 0, 0, 0)
}
ORE = {
"name": "ore",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "oreWait",
"stateConfigs": [
{"state": "oreWait",
"layer": "lowerPhysical",
"sprite": "oreWait",
"groups": []},
{"state": "ironRaw",
"layer": "lowerPhysical",
"sprite": "ironRaw",
"groups": ["tokens"]},
{"state": "goldRaw",
"layer": "lowerPhysical",
"sprite": "goldRaw",
"groups": ["tokens"]},
{"state": "goldPartial",
"layer": "lowerPhysical",
"sprite": "goldPartial",
"groups": ["tokens"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["oreWait", "ironRaw", "goldRaw", "goldPartial"],
"spriteShapes": [RAW_ORE, RAW_ORE, RAW_ORE, PARTIAL_ORE],
"palettes": [shapes.INVISIBLE_PALETTE, IRON_PALETTE,
GOLD_PALETTE, GOLD_PALETTE],
"noRotates": [True] * 4,
}
},
{
"component": "Ore",
"kwargs": {
"waitState": "oreWait",
"rawState": "goldRaw",
"partialState": "goldPartial",
"minNumMiners": 2,
"miningWindow": 3,
}
},
{
"component": "Ore",
"kwargs": {
"waitState": "oreWait",
"rawState": "ironRaw",
"partialState": "ironRaw",
"minNumMiners": 1,
"miningWindow": 2,
}
},
{
"component": "FixedRateRegrow",
"kwargs": {
"liveStates": ["ironRaw", "goldRaw"],
"liveRates": [0.0002, 0.00008],
"waitState": "oreWait",
}
},
]
}
PLAYER_COLOR_PALETTES = []
for human_readable_color in colors.human_readable:
PLAYER_COLOR_PALETTES.append(shapes.get_palette(human_readable_color))
def get_avatar_object(num_players: int, player_index: int):
"""Construct an avatar object."""
lua_index = player_index + 1
color_palette = PLAYER_COLOR_PALETTES[player_index]
avatar_sprite_name = "avatarSprite{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "player",
"stateConfigs": [
{"state": "player",
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "MineBeam",
},
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [color_palette],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": "player",
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "mine"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"mine": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
}
}
},
{
"component": "MineBeam",
"kwargs": {
"cooldownTime": 3,
"beamLength": 3,
"beamRadius": 0,
"agentRole": "none",
"roleRewardForMining": {
"none": [0, 0],
"golddigger": [0, 0.2], "irondigger": [0, 0]},
"roleRewardForExtracting": {
"none": [1, 8],
"golddigger": [-1, 8], "irondigger": [8, -1]},
}
},
{
"component": "MiningTracker",
"kwargs": {
"numPlayers": num_players,
"numOreTypes": NUM_ORE_TYPES,
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def get_avatar_objects(num_players: int):
return [get_avatar_object(num_players, i) for i in range(num_players)]
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
"ore": ORE,
}
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "mine": 0}
FORWARD = {"move": 1, "turn": 0, "mine": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "mine": 0}
BACKWARD = {"move": 3, "turn": 0, "mine": 0}
STEP_LEFT = {"move": 4, "turn": 0, "mine": 0}
TURN_LEFT = {"move": 0, "turn": -1, "mine": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "mine": 0}
MINE = {"move": 0, "turn": 0, "mine": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
MINE,
)
def get_config():
"""Default configuration for the coop_mining level."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(216, 216),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default", "target"})
config.default_player_roles = ("default",) * 6
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate given player roles."""
del config
num_players = len(roles)
return dict(
levelName="coop_mining",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": get_avatar_objects(num_players),
"scene": SCENE,
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
|
meltingpot-main
|
meltingpot/configs/substrates/coop_mining.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Stag Hunt in the Matrix.
Example video: https://youtu.be/agOpo0MZmzs
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Stag Hunt game. `K = 2`
resources represent "stag" and "hare" pure strategies.
The map configuration is different from other "_in the Matrix_" games. In this
case there are more _hare_ resources than _stag_ resources.
Players have the default `11 x 11` (off center) observation window.
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is green.
RESOURCE1_COLOR = (30, 225, 185, 255)
RESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is red.
RESOURCE2_COLOR = (225, 30, 70, 255)
RESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# The procedural generator replaces all 'a' chars in the default map with chars
# representing specific resources, i.e. with either '1' or '2'.
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWW
WPPPPPPP W W PPPPPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP 2222 PPPPW
WP PW
WP 222222 222 PW
WP 2 11 11 PW
W 2 11 a 222 W
W WW W1 11a W
WW 21 11 W 11a 2 W
WWW 21 WWWWWWWWW 2 W
W 2 aa 111 1a WWW
W 2 111 1a W
W aa W 22 W
W 22 2a Waa WW W
WP 22 W222 PW
WP 222 PW
WP 222 PW
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPPPPP W PPPPPPPW
WWWWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"P": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# Remove the first entry from human_readable_colors after using it for the self
# color to prevent it from being used again as another avatar color.
human_readable_colors = list(colors.human_readable)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette(human_readable_colors.pop(0)),
"noRotate": True,
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
PLAYER_COLOR_PALETTES = []
for human_readable_color in human_readable_colors:
PLAYER_COLOR_PALETTES.append(shapes.get_palette(human_readable_color))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# row player chooses a row of this matrix.
# C D
[4, 0], # C
[2, 2], # D
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# C D
[4, 2], # C
[0, 2], # D
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue # violet
(0.0, 0.5), (0.5, 1.5), (1.5, 2.5), (2.5, 3.5), (3.5, 4.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(resource_id, color_data):
"""Creates resource prefab with provided `resource_id` (num) and color."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": color_data[0],
"#": color_data[1],
"x": (0, 0, 0, 0)}],
"noRotates": [False]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.04,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)
prefabs["resource_class2"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)
return prefabs
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(
human_readable_colors[player_idx])],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": False,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_avatar_objects(num_players: int) -> Sequence[PrefabConfig]:
"""Returns all game objects for the map.
Args:
num_players: number of players to create avatars for.
"""
avatar_objects = []
for player_idx in range(num_players):
avatar = create_avatar_object(player_idx, TARGET_SPRITE_SELF)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(avatar)
avatar_objects.append(readiness_marker)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(192, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/stag_hunt_in_the_matrix__arena.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for gift_refinements.
Example video: https://youtu.be/C1C2CJ__mhQ
Tokens randomly spawn in empty spaces. When collected, they are put in the
player's inventory where they can be consumed by for reward. Alternatively, a
token can be refined into three higher refinement tokens and gifted to another
player. This is akin to tokens initially being a raw material, like chunks of
metal, and then being split and shaped into more useful goods for added value.
A token can only be refined a finite number of times, after which it cannot be
split again, nor refined further; although they can still be gifted.
Gift Refinements is inspired by the Trust Game from behavioural economics where
the first player has an endowment and chooses how much to donate to a second
player who receives three times its value. Then the second player chooses how
much to give back to the first.
In Gift Refinements, tokens can only be refined twice (i.e. there are three
types of tokens). The token that spawn are always of the rawest type, and the
only way to create more refined tokens is to gift them to another player.
Players also have a limited inventory capacity of 15 tokens for each token type.
The special gifting is implemented as a beam that the players can fire. If they
hit another player with the beam while their inventory is not full, they lose
one token of the rawest type they currently hold, and the hit player receives
either three token of the next refinement (if the token gifted wasn't already
at maximum refinement), or the token gifted (otherwise).
The players have an action to consume tokens which takes all tokens of all types
currently in their inventory and converts them into reward. All tokens are worth
1 reward regardless of refinement level.
The game is set up in such a way that there are several ways players can form
mutually beneficial interactions, but all of them require trust. For instance,
A pair of players might have one player pick up a token and immediately gift it
to the other one who receives three. Then the second player returns one token
which leaves them with three and two tokens respectively. If they both consume
after this, they both benefitted from the interaction. A more extreme case would
have them take one token and refine it maximally to produce 9 tokens that they
can split five and four with 10 roughly alternating gifting actions.
"""
from collections.abc import Mapping, Sequence
from typing import Any
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
NUM_TOKEN_TYPES = 3
MAX_TOKENS_PER_TYPE = 15
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWWWW
WTTTTTTTTTTTTTTTTTTTTTTTTTW
WTPTTTTTTTTTPTTTTTPTTTTTPTW
WTTTTTTTTWTTTTTTTTTTTTTTTTW
WTTTTTTTTWTTTTTTTTTTWTTTTTW
WTTTTTTTTWTTTTTTTTTTWTTTTTW
WTTTTTTTTWWWWWWWTTTTWTTTPTW
WTPTWWTTTTWTTTTTTTTTWTTTTTW
WTTTTTTTTTWTTPTTTTTTTTTTTTW
WTTTTTTTTTWTTTTTWWWTTTTTTTW
WTTTTTTTTTWTTTTTTTTTTTTTTTW
WTTTTTTTTTTTTTTTTTTTTTTTPTW
WTPTTTWWWTTTTTTWWWWWWWWTTTW
WTTWWWWTTTTTTTTTTTTTTTTTTTW
WTTTTTWTTTTWTTTTTPTTTTTTTTW
WTTTTTWTTTTWTTTTTTTTTTTTPTW
WTTTTTWTTTTTWTTTTTTTTWTTTTW
WTTTTTTWTTTTTWWWWTTTTWTTTTW
WTPTTTTTWTTTTTTTTTTTTWTTTTW
WTTTTTTTTWTTTPTTTTTTTTTTPTW
WTTTTTTTTTWTTTTTTTTWTTTTTTW
WTTTTWTTTTTTTTTTTTTWTTTTTTW
WTTTTWTTTTTTTTTWWWWWWWWTTTW
WTTTTWTTTTTTTTTTTTWTTTTTTTW
WTPTTTTTTPTTTTTTTPTTTTTTPTW
WTTTTTTTTTTTTTTTTTTTTTTTTTW
WWWWWWWWWWWWWWWWWWWWWWWWWWW
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"P": "spawn_point",
"W": "wall",
"T": "token",
}
_COMPASS = ["N", "E", "S", "W"]
# The Scene objece is a non-physical object, it components implement global
# logic. In this case, that includes holding the global berry counters to
# implement the regrowth rate, as well as some of the observations.
SCENE = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
},
]
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gift"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
TOKEN = {
"name": "token",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "tokenWait",
"stateConfigs": [
{"state": "tokenWait",
"layer": "lowerPhysical",
"sprite": "coinWait",
"groups": []},
{"state": "token",
"layer": "lowerPhysical",
"sprite": "coin",
"groups": ["tokens"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["coin", "coinWait"],
"spriteShapes": [shapes.COIN, shapes.COIN],
"palettes": [
shapes.COIN_PALETTE, shapes.INVISIBLE_PALETTE],
}
},
{
"component": "Pickable",
"kwargs": {
"liveState": "token",
"waitState": "tokenWait",
"rewardForPicking": 0.0,
}
},
{
"component": "FixedRateRegrow",
"kwargs": {
"liveState": "token",
"waitState": "tokenWait",
"regrowRate": 0.0002,
}
},
]
}
PLAYER_COLOR_PALETTES = []
for human_readable_color in colors.human_readable:
PLAYER_COLOR_PALETTES.append(shapes.get_palette(human_readable_color))
def get_avatar_object(num_players: int, player_index: int):
"""Construct an avatar object."""
# Lua is 1-indexed.
lua_index = player_index + 1
color_palette = PLAYER_COLOR_PALETTES[player_index]
avatar_sprite_name = "avatarSprite{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "player",
"stateConfigs": [
{
"state": "player",
"layer": "upperPhysical",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
{
"state": "playerWait",
"groups": ["playerWaits"]
},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [color_palette],
"noRotates": [True],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": "player",
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": [
"move", "turn", "refineAndGift", "consumeTokens"
],
"actionSpec": {
"move": {
"default": 0,
"min": 0,
"max": len(_COMPASS)
},
"turn": {
"default": 0,
"min": -1,
"max": 1
},
"refineAndGift": {
"default": 0,
"min": 0,
"max": 1
},
"consumeTokens": {
"default": 0,
"min": 0,
"max": 1
},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
}
}
},
{
"component": "Inventory",
"kwargs": {
"capacityPerType": MAX_TOKENS_PER_TYPE,
"numTokenTypes": NUM_TOKEN_TYPES,
}
},
{
"component": "GiftBeam",
"kwargs": {
"cooldownTime": 3,
"beamLength": 5,
"beamRadius": 0,
"agentRole": "none",
"giftMultiplier": 5,
"successfulGiftReward": 10,
"roleRewardForGifting": {
"none": 0.0,
"gifter": 0.2,
"selfish": -2.0
},
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GiftBeam",
},
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
"name": "INVENTORY",
"type": "tensor.DoubleTensor",
"shape": [NUM_TOKEN_TYPES],
"component": "Inventory",
"variable": "inventory"
},
]
}
},
{
"component": "TokenTracker",
"kwargs": {
"numPlayers": num_players,
"numTokenTypes": NUM_TOKEN_TYPES,
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
"token": TOKEN,
}
def get_avatar_objects(num_players: int):
return [get_avatar_object(num_players, i) for i in range(num_players)]
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {
"move": 0, "turn": 0, "refineAndGift": 0, "consumeTokens": 0}
FORWARD = {
"move": 1, "turn": 0, "refineAndGift": 0, "consumeTokens": 0}
STEP_RIGHT = {
"move": 2, "turn": 0, "refineAndGift": 0, "consumeTokens": 0}
BACKWARD = {
"move": 3, "turn": 0, "refineAndGift": 0, "consumeTokens": 0}
STEP_LEFT = {
"move": 4, "turn": 0, "refineAndGift": 0, "consumeTokens": 0}
TURN_LEFT = {
"move": 0, "turn": -1, "refineAndGift": 0, "consumeTokens": 0}
TURN_RIGHT = {
"move": 0, "turn": 1, "refineAndGift": 0, "consumeTokens": 0}
REFINE_AND_GIFT = {
"move": 0, "turn": 0, "refineAndGift": 1, "consumeTokens": 0}
CONSUME_TOKENS = {
"move": 0, "turn": 0, "refineAndGift": 0, "consumeTokens": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
REFINE_AND_GIFT,
CONSUME_TOKENS,
)
def get_config():
"""Default configuration for the gift_refinements level."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
"INVENTORY",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
"INVENTORY": specs.inventory(3),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(216, 216),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default", "target"})
config.default_player_roles = ("default",) * 6
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate given player roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="gift_refinements",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": get_avatar_objects(num_players),
"scene": SCENE,
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/gift_refinements.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Library of functions for defining chemical motifs."""
from typing import Any, Dict
from meltingpot.utils.substrates import shapes
import networkx as nx
import numpy as np
EMPTY_COLOR = shapes.PETRI_DISH_PALETTE["@"]
WHITE_COLOR = (255, 255, 255, 255) # A white color.
DIAMOND_SHAPE = """
xxxabxxx
xxaabbxx
xaaabbbx
aaaabbbb
ddddcccc
xdddcccx
xxddccxx
xxxdcxxx
"""
SQUARE_SHAPE = """
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
"""
ENERGY_SHAPE = """
xxxxxxxx
xxxxxxxx
xxxabxxx
xxaabbxx
xxddccxx
xxxdcxxx
xxxxxxxx
xxxxxxxx
"""
FOOD_SHAPE = """
xxxxxxxx
xxxxxxxx
xdddbbxx
ddbbbxxx
xxbddbbx
xdddbbxx
xxbbddbb
xxxxxxxx
"""
def graph_semantics(g):
"""Convert a networkx.DiGraph to compounds and reactions for grid_land."""
compounds = {}
reactions = {}
for node, attributes in g.nodes.items():
if attributes.get("reaction"):
reactants = [e[0] for e in g.in_edges(node)]
products = [e[1] for e in g.out_edges(node)]
reactions[node] = create_reaction(reactants, products, attributes)
if not attributes.get("reaction"):
compounds[node] = create_compound(attributes)
return compounds, reactions
def create_reaction(reactants, products, attributes):
# TODO(b/192926758): support fixedSwapOrder = False, in that case, pass
# reactants# and products as a dictionary mapping to the number required (not
# a list with possibly repeated entries like the current version).
return {
"reactants": reactants,
"products": products,
"fixedSwapOrder": attributes.get("fixedSwapOrder", True),
"priority": attributes.get("priority", 1),
}
def create_compound(attributes):
"""Convert node attributes to dictionary structure needed for a compound."""
data = {
# Use black color if none provided.
"color": attributes.get("color", (0, 0, 0, 0)),
"properties": {
# Use (0, 0) for structure if none provided,
"structure": attributes.get("structure", (0, 0)),
},
}
for k, v in attributes.items():
data[k] = v
return data
def add_system_nodes(g: nx.DiGraph):
"""Add several nodes that must always be present for the system to function.
Args:
g: (nx.DiGraph): directed graph representing the reaction system.
"""
g.add_nodes_from([
# Add a node for the "empty" compound.
("empty", {"color": EMPTY_COLOR,
"reactivity": "low"}),
# Add a node for the "activated" compound.
("activated", {"color": WHITE_COLOR,
"immovable": True}),
# Add unused nodes that serve only to make all standard groups valid so
# their corresponding updater can be created.
("_unused_a", {"reactivity": "low"}),
("_unused_b", {"reactivity": "medium"}),
("_unused_c", {"reactivity": "high"})
])
def add_compounds_to_prefabs_dictionary(prefabs,
compounds,
reactivity_levels,
sprites=False,
default_reaction_radius=None,
default_reaction_query_type=None,
priority_mode=False):
"""Add compounds."""
for compound_name in compounds.keys():
prefabs[compound_name] = create_cell_prefab(
compound_name,
compounds,
reactivity_levels,
sprites=sprites,
default_reaction_radius=default_reaction_radius,
default_reaction_query_type=default_reaction_query_type,
priority_mode=priority_mode)
return prefabs
def multiply_tuple(color_tuple, factor):
if len(color_tuple) == 3:
return tuple([int(np.min([x * factor, 255])) for x in color_tuple])
elif len(color_tuple) == 4:
return tuple([int(np.min([x * factor])) for x in color_tuple])
def adjust_color_opacity(color_tuple, factor):
apply_opacity = tuple([color_tuple[0], color_tuple[1], color_tuple[2],
color_tuple[3] * factor])
return tuple([int(np.min([x])) for x in apply_opacity])
def get_matter_palette(sprite_color):
return {
"*": sprite_color,
"b": shapes.WHITE,
"x": shapes.ALPHA,
# Shades for liquid matter.
"L": shapes.adjust_color_brightness(sprite_color, 0.85),
"l": shapes.adjust_color_brightness(sprite_color, 0.90),
"w": shapes.adjust_color_brightness(sprite_color, 0.95),
}
def get_cytoavatar_palette(sprite_color):
return {
"*": (184, 61, 187, 255),
"&": (161, 53, 146, 255),
"o": sprite_color,
",": shapes.BLACK,
"x": shapes.ALPHA,
"#": shapes.WHITE,
}
def create_cell_prefab(compound_name, compounds, reactivity_levels,
sprites=False, default_reaction_radius=None,
default_reaction_query_type=None, priority_mode=False):
"""Create prefab for a cell object initially set to state=`compound_name`."""
state_configs = []
states_to_properties = {}
sprite_colors = []
query_configs = {}
special_sprites = {}
for compound, attributes in compounds.items():
groups = []
if "reactivity" in attributes:
reactivity_group = attributes["reactivity"]
groups.append(reactivity_group)
if "immovable" in attributes and attributes["immovable"]:
groups.append("immovables")
if "query_config" in attributes:
query_configs[compound] = attributes["query_config"]
if "sprite" in attributes:
special_sprites[compound] = attributes["sprite"]
state_config = {
"state": compound,
"sprite": compound,
"layer": "lowerPhysical",
"groups": groups + ["spawnPoints"],
}
state_configs.append(state_config)
states_to_properties[compound] = attributes["properties"]
sprite_colors.append(attributes["color"])
# Configure the Reactant component.
reactivities = {}
for key, value in reactivity_levels.items():
reactivities[key] = value
if sprites:
def get_palette(sprite_color):
if len(sprite_color) == 3:
x_color = EMPTY_COLOR[0:3]
a_color = (252, 252, 252)
elif len(sprite_color) == 4:
x_color = EMPTY_COLOR
a_color = (252, 252, 252, 255)
return {
"x": x_color,
"a": a_color,
"b": sprite_color,
"c": multiply_tuple(sprite_color, 0.2),
"d": sprite_color
}
appearance_kwargs = {
"renderMode": "ascii_shape",
"spriteNames": list(compounds.keys()),
"spriteShapes": [DIAMOND_SHAPE] * len(sprite_colors),
"palettes": [get_palette(color) for color in sprite_colors],
"noRotates": [True] * len(sprite_colors),
}
# Must ensure "empty" and "activated" are not given the diamond sprite.
for i, compound in enumerate(appearance_kwargs["spriteNames"]):
if compound in ["empty", "activated"]:
appearance_kwargs["spriteShapes"][i] = SQUARE_SHAPE
if compound in special_sprites:
appearance_kwargs["spriteShapes"][i] = special_sprites[compound]
else:
appearance_kwargs = {
"spriteNames": list(compounds.keys()),
"spriteRGBColors": sprite_colors,
}
prefab = {
"name": "cell",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": compound_name,
"stateConfigs": state_configs,
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": appearance_kwargs
},
{
"component": "Cell",
"kwargs": {
"numCellStates": len(state_configs),
"statesToProperties": states_to_properties,
# The radius over which to search for neighbors on every step.
"radius": default_reaction_radius,
# Query according to L1 (diamond) or L2 (disc) norm.
"queryType": default_reaction_query_type,
# Layers on which to search for neighbors on every step.
"interactionLayers": ["lowerPhysical", "overlay"],
# You can override query properties on a per state basis.
"stateSpecificQueryConfig": query_configs,
},
},
{
"component": "Reactant",
"kwargs": {
"name": "Reactant",
"reactivities": reactivities,
"priorityMode": priority_mode,
}
},
{
"component": "Product",
"kwargs": {
"name": "Product",
}
},
]
}
return prefab
def create_vesicle(player_idx: int,
compounds,
reactivity_levels,
default_reaction_radius=None,
default_reaction_query_type=None,
priority_mode=False):
"""Construct prefab for an avatar's vesicle object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
vesicle_prefix = "vesicle_"
state_configs = []
states_to_properties = {}
sprite_colors = []
sprite_shapes = []
query_configs = {}
for compound, attributes in compounds.items():
groups = []
sprite_shape = shapes.SINGLE_HOLDING_LIQUID
if "reactivity" in attributes:
reactivity_group = (vesicle_prefix +
attributes["reactivity"])
groups.append(reactivity_group)
if "immovable" in attributes and attributes["immovable"]:
groups.append("immovables")
if "query_config" in attributes:
query_configs[compound] = attributes["query_config"]
sprite_color = attributes["color"]
if compound == "empty":
sprite_shape = shapes.SQUARE
sprite_color = shapes.ALPHA
state_config = {
"state": compound,
"sprite": compound + "_vesicle",
"layer": "overlay",
"groups": groups,
}
state_configs.append(state_config)
states_to_properties[compound] = attributes["properties"]
sprite_colors.append(sprite_color)
sprite_shapes.append(sprite_shape)
# Configure the Reactant component.
reactivities = {}
for key, value in reactivity_levels.items():
reactivities[vesicle_prefix + key] = value
prefab = {
"name": f"avatar_vesicle_{lua_index}",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "preInit",
"stateConfigs": state_configs +
[{"state": "preInit"}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [key + "_vesicle" for key in compounds.keys()],
"spriteShapes": sprite_shapes,
"palettes": [get_matter_palette(sprite_colors[i])
for i in range(len(sprite_colors))],
"noRotates": [True] * len(sprite_colors)
},
},
{
"component": "AvatarVesicle",
"kwargs": {
"playerIndex": lua_index,
"preInitState": "preInit",
"initialState": "empty",
"waitState": "vesicleWait"
}
},
{
"component": "Cell",
"kwargs": {
"numCellStates": len(state_configs),
"statesToProperties": states_to_properties,
# The radius over which to search for neighbors on every step.
"radius": default_reaction_radius,
# Query according to L1 (diamond) or L2 (disc) norm.
"queryType": default_reaction_query_type,
# Layers on which to search for neighbors on every step.
"interactionLayers": ["lowerPhysical", "overlay"],
# You can override query properties on a per state basis.
"stateSpecificQueryConfig": query_configs,
},
},
{
"component": "Reactant",
"kwargs": {
"name": "Reactant",
"reactivities": reactivities,
"priorityMode": priority_mode,
}
},
{
"component": "Product",
"kwargs": {
"name": "Product",
}
},
]
}
return prefab
def create_avatar_constant_self_view(
rewarding_reactions,
player_idx: int,
target_sprite_self_empty: Dict[str, Any],
target_sprite_self_holds_one: Dict[str, Any],
randomize_initial_orientation: bool = True,
add_location_observer: bool = False) -> Dict[str, Any]:
"""Create an avatar prefab rewarded by reactions in `rewarding_reactions`."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self_empty = f"Avatar_{lua_index}_empty"
source_sprite_self_holds_one = f"Avatar_{lua_index}_holds_one"
custom_sprite_map = {
source_sprite_self_empty: target_sprite_self_empty["name"],
source_sprite_self_holds_one: target_sprite_self_holds_one["name"],
}
# Part of the avatar is partially transparent so molecules can be seen below.
cytoavatar_palette = get_cytoavatar_palette((0, 0, 0, 75))
live_state_name_empty = f"player{lua_index}_empty"
live_state_name_holds_one = f"player{lua_index}_holds_one"
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name_empty,
"stateConfigs": [
{"state": live_state_name_empty,
"layer": "upperPhysical",
"sprite": source_sprite_self_empty,
"contact": "avatar",
"groups": ["players"]},
{"state": live_state_name_holds_one,
"layer": "upperPhysical",
"sprite": source_sprite_self_holds_one,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self_empty,
source_sprite_self_holds_one],
"spriteShapes": [shapes.CYTOAVATAR_EMPTY,
shapes.CYTOAVATAR_HOLDING_ONE],
"palettes": [cytoavatar_palette] * 2,
"noRotates": [True] * 2
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [
target_sprite_self_empty["name"],
target_sprite_self_holds_one["name"],
],
"customSpriteShapes": [
target_sprite_self_empty["shape"],
target_sprite_self_holds_one["shape"],
],
"customPalettes": [
cytoavatar_palette,
cytoavatar_palette,
],
"customNoRotates": [
target_sprite_self_empty["noRotate"],
target_sprite_self_holds_one["noRotate"],
],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"spawnGroup": "spawnPoints",
"aliveState": live_state_name_empty,
"additionalLiveStates": [live_state_name_holds_one],
"waitState": "playerWait",
"actionOrder": ["move", "turn", "ioAction"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": 4},
"turn": {"default": 0, "min": -1, "max": 1},
"ioAction": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
"randomizeInitialOrientation": randomize_initial_orientation,
}
},
{
"component": "IOBeam",
"kwargs": {
"cooldownTime": 2,
}
},
{
"component": "VesicleManager",
"kwargs": {
"orderedVesicles": ["vesicleOne",],
"cytoavatarStates": {
"empty": live_state_name_empty,
"holdingOne": live_state_name_holds_one,
},
}
},
{
"component": "ReactionsToRewards",
"kwargs": {
# Specify rewards for specific reactions.
"rewardingReactions": rewarding_reactions
}
},
]
}
if add_location_observer:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_scene(reactions, stochastic_episode_ending=False):
"""Construct the global scene prefab."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "ReactionAlgebra",
"kwargs": {
"reactions": reactions
}
},
{
"component": "GlobalMetricTracker",
"kwargs": {
"name": "GlobalMetricTracker",
}
},
]
}
if stochastic_episode_ending:
scene["components"].append({
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
})
return scene
|
meltingpot-main
|
meltingpot/configs/substrates/reaction_graph_utils.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Prisoner's Dilemma in the Matrix (two player, repeated).
Example video: https://youtu.be/AAd9UcP0nk0
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Prisoner's Dilemma game.
`K = 2` resources represent "cooperate" and "defect" pure strategies.
Players have a `5 x 5` observation window.
The episode has a chance of ending stochastically on every 100 step interval
after step 1000. This usually allows time for 8 or more interactions.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is green.
RESOURCE1_COLOR = (30, 225, 185, 255)
RESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is red.
RESOURCE2_COLOR = (225, 30, 70, 255)
RESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn n nW
W WWW W W W WW W
W W 11a W a22 W W
Wn WW 11a W a22 WW nW
W 11a a22 W
W W
Wn WW WW n WW WWW nW
W W
W 22a W a11 W
Wn W 22a W a11 W nW
W W 22a W a11 WW W
W WWWW W W W WWW W
Wn n nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1", # Cooperate
"resource_class2", # Defect
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 8
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
TARGET_SPRITE_OTHER = {
"name": "Other",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((200, 100, 50)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# row player chooses a row of this matrix.
# C D
[3, 0], # C
[5, 1], # D
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# C D
[3, 5], # C
[0, 1], # D
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue # violet
(0.0, 1.0), (1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(
resource_id: int,
resource_shape: str,
resource_palette: Dict[str, Tuple[int, int, int, int]]):
"""Creates resource prefab with provided resource_id, shape, and palette."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [resource_shape],
"palettes": [resource_palette],
"noRotates": [True]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.02,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_avatar_object(
player_idx: int,
all_source_sprite_names: Sequence[str],
target_sprite_self: Dict[str, Any],
target_sprite_other: Dict[str, Any],
turn_off_default_reward: bool = False) -> Dict[str, Any]:
"""Create an avatar object given self vs other sprite data."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
for name in all_source_sprite_names:
if name != source_sprite_self:
custom_sprite_map[name] = target_sprite_other["name"]
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": [source_sprite_self],
# A white square should never be displayed. It will always be
# remapped since this is self vs other observation mode.
"spriteRGBColors": [(255, 255, 255, 255)],
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"],
target_sprite_other["name"]],
"customSpriteShapes": [target_sprite_self["shape"],
target_sprite_other["shape"]],
"customPalettes": [target_sprite_self["palette"],
target_sprite_other["palette"]],
"customNoRotates": [target_sprite_self["noRotate"],
target_sprite_other["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 5,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "SpawnResourcesWhenAllPlayersZapped",
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": turn_off_default_reward,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_prefabs():
"""Returns a dictionary mapping names to template game objects."""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(
1, shapes.BUTTON, {"*": RESOURCE1_COLOR_DATA[0],
"#": RESOURCE1_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class2"] = create_resource_prefab(
2, shapes.BUTTON, {"*": RESOURCE2_COLOR_DATA[0],
"#": RESOURCE2_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
return prefabs
def get_all_source_sprite_names(num_players):
all_source_sprite_names = []
for player_idx in range(0, num_players):
# Lua is 1-indexed.
lua_index = player_idx + 1
all_source_sprite_names.append("Avatar" + str(lua_index))
return all_source_sprite_names
def create_avatar_objects(num_players,
turn_off_default_reward: bool = False):
"""Returns list of avatar objects of length 'num_players'."""
all_source_sprite_names = get_all_source_sprite_names(num_players)
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(
player_idx,
all_source_sprite_names,
TARGET_SPRITE_SELF,
TARGET_SPRITE_OTHER,
turn_off_default_reward=turn_off_default_reward)
avatar_objects.append(game_object)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def create_world_sprite_map(
num_players: int, target_sprite_other: Dict[str, Any]) -> Dict[str, str]:
all_source_sprite_names = get_all_source_sprite_names(num_players)
world_sprite_map = {}
for name in all_source_sprite_names:
world_sprite_map[name] = target_sprite_other["name"]
return world_sprite_map
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Other parameters that are useful to override in training config files.
config.turn_off_default_reward = False
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
# worldSpriteMap is needed to make the global view used in videos be
# be informative in cases where individual avatar views have had
# sprites remapped to one another (example: self vs other mode).
"worldSpriteMap": create_world_sprite_map(num_players,
TARGET_SPRITE_OTHER),
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/prisoners_dilemma_in_the_matrix__repeated.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for running a Coins game in Melting Pot.
Example video: https://youtu.be/a_SYgt4tBsc
"""
from collections.abc import Mapping, Sequence
import random
from typing import Any
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict as configdict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
MANDATED_NUM_PLAYERS = 2
COIN_PALETTES = {
"coin_red": shapes.get_palette((238, 102, 119)), # Red.
"coin_blue": shapes.get_palette((68, 119, 170)), # Blue.
"coin_yellow": shapes.get_palette((204, 187, 68)), # Yellow.
"coin_green": shapes.get_palette((34, 136, 51)), # Green.
"coin_purple": shapes.get_palette((170, 51, 119)) # Purple.
}
def get_ascii_map(
min_width: int, max_width: int, min_height: int, max_height: int) -> str:
"""Procedurally generate ASCII map."""
assert min_width <= max_width
assert min_height <= max_height
# Sample random map width and height.
width = random.randint(min_width, max_width)
height = random.randint(min_height, max_height)
# Make top row (walls). Pad to max width to ensure all maps are same size.
ascii_map = ["W"] * (width + 2) + [" "] * (max_width - width)
# Make middle rows (navigable interior).
for row in range(height):
# Add walls and coins.
ascii_map += ["\nW"] + ["C"] * width + ["W"]
if row == 1:
# Add top-right spawn point.
ascii_map[-3] = "_"
elif row == height - 2:
# Add bottom-left spawn point.
ascii_map[-width] = "_"
# Pad to max width.
ascii_map += [" "] * (max_width - width)
# Make bottom row (walls). Pad to max width.
ascii_map += ["\n"] + ["W"] * (width + 2) + [" "] * (max_width - width)
# Pad with extra rows to reach max height.
for _ in range(max_height - height):
ascii_map += ["\n"] + [" "] * max_width
# Join list of strings into single string.
ascii_map = "".join(ascii_map)
return ascii_map
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"_": "spawn_point",
"W": "wall",
"C": "coin",
}
_COMPASS = ["N", "E", "S", "W"]
# The Scene objece is a non-physical object, it components implement global
# logic. In this case, that includes holding the global berry counters to
# implement the regrowth rate, as well as some of the observations.
SCENE = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "GlobalCoinCollectionTracker",
"kwargs": {
"numPlayers": MANDATED_NUM_PLAYERS,
},
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 300,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.05
}
}
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
SCENE["components"].append({
"component": "GlobalMetricReporter",
"kwargs": {
"metrics": [
{
"name": "COINS_COLLECTED",
"type": "tensor.Int32Tensor",
"shape": (MANDATED_NUM_PLAYERS, 2),
"component": "GlobalCoinCollectionTracker",
"variable": "coinsCollected",
},
]
},
})
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gift"
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "zap"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "logic",
"groups": ["spawnPoints"]
}],
}
},
{"component": "Transform",},
]
}
def get_coin(
coin_type_a: str,
coin_type_b: str,
regrow_rate: float,
reward_self_for_match: float,
reward_self_for_mismatch: float,
reward_other_for_match: float,
reward_other_for_mismatch: float,
) -> PrefabConfig:
"""Create `PrefabConfig` for coin component."""
return {
"name": "coin",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "coinWait",
"stateConfigs": [
{"state": coin_type_a,
"layer": "superOverlay",
"sprite": coin_type_a,
},
{"state": coin_type_b,
"layer": "superOverlay",
"sprite": coin_type_b,
},
{"state": "coinWait",
"layer": "logic",
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [coin_type_a, coin_type_b],
"spriteShapes": [shapes.COIN] * 2,
"palettes": [COIN_PALETTES[coin_type_a],
COIN_PALETTES[coin_type_b]],
"noRotates": [False] * 2,
}
},
{
"component": "Coin",
"kwargs": {
"waitState": "coinWait",
"rewardSelfForMatch": reward_self_for_match,
"rewardSelfForMismatch": reward_self_for_mismatch,
"rewardOtherForMatch": reward_other_for_match,
"rewardOtherForMismatch": reward_other_for_mismatch,
}
},
{
"component": "ChoiceCoinRegrow",
"kwargs": {
"liveStateA": coin_type_a,
"liveStateB": coin_type_b,
"waitState": "coinWait",
"regrowRate": regrow_rate,
}
},
]
}
def get_avatar(coin_type: str):
"""Create an avatar object."""
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "player",
"stateConfigs": [
{"state": "player",
"layer": "upperPhysical",
"sprite": "Avatar",
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Avatar"],
"spriteShapes": [shapes.CUTE_AVATAR],
# Palette to be overwritten.
"palettes": [shapes.get_palette(colors.palette[0])],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": -1, # Player index to be overwritten.
"aliveState": "player",
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn",],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
}
},
{
"component": "PlayerCoinType",
"kwargs": {
"coinType": coin_type,
},
},
{
"component": "Role",
"kwargs": {
# Role has no effect if all factors are 1.0.
"multiplyRewardSelfForMatch": 1.0,
"multiplyRewardSelfForMismatch": 1.0,
"multiplyRewardOtherForMatch": 1.0,
"multiplyRewardOtherForMismatch": 1.0,
},
},
{
"component": "PartnerTracker",
"kwargs": {}
},
]
}
# Signals needed for puppeteers.
metrics = [
{
"name": "MISMATCHED_COIN_COLLECTED_BY_PARTNER",
"type": "Doubles",
"shape": [],
"component": "PartnerTracker",
"variable": "partnerCollectedMismatch",
},
]
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
# Debug metrics
metrics.append({
"name": "MATCHED_COIN_COLLECTED",
"type": "Doubles",
"shape": [],
"component": "Role",
"variable": "cumulantCollectedMatch",
})
metrics.append({
"name": "MISMATCHED_COIN_COLLECTED",
"type": "Doubles",
"shape": [],
"component": "Role",
"variable": "cumulantCollectedMismatch",
})
metrics.append({
"name": "MATCHED_COIN_COLLECTED_BY_PARTNER",
"type": "Doubles",
"shape": [],
"component": "PartnerTracker",
"variable": "partnerCollectedMatch",
})
# Add the metrics reporter.
avatar_object["components"].append({
"component": "AvatarMetricReporter",
"kwargs": {"metrics": metrics}
})
return avatar_object
# `prefabs` is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
def get_prefabs(
coin_type_a: str,
coin_type_b: str,
regrow_rate: float = 0.0005,
reward_self_for_match: float = 1.0,
reward_self_for_mismatch: float = 1.0,
reward_other_for_match: float = 0.0,
reward_other_for_mismatch: float = -2.0,
) -> PrefabConfig:
"""Make `prefabs` (a dictionary mapping names to template game objects)."""
coin = get_coin(coin_type_a=coin_type_a,
coin_type_b=coin_type_b,
regrow_rate=regrow_rate,
reward_self_for_match=reward_self_for_match,
reward_self_for_mismatch=reward_self_for_mismatch,
reward_other_for_match=reward_other_for_match,
reward_other_for_mismatch=reward_other_for_mismatch)
return {"wall": WALL, "spawn_point": SPAWN_POINT, "coin": coin}
# `player_color_palettes` is a list with each entry specifying the color to use
# for the player at the corresponding index.
# These correspond to the persistent agent colors, but are meaningless for the
# human player. They will be overridden by the environment_builder.
def get_player_color_palettes(
coin_type_a: str, coin_type_b: str) -> Sequence[Mapping[str, shapes.Color]]:
return [COIN_PALETTES[coin_type_a], COIN_PALETTES[coin_type_b]]
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0,}
FORWARD = {"move": 1, "turn": 0,}
STEP_RIGHT = {"move": 2, "turn": 0,}
BACKWARD = {"move": 3, "turn": 0,}
STEP_LEFT = {"move": 4, "turn": 0,}
TURN_LEFT = {"move": 0, "turn": -1,}
TURN_RIGHT = {"move": 0, "turn": 1,}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
)
def get_config():
"""Default configuration for the Coins substrate."""
config = configdict.ConfigDict()
# Set the size of the map.
config.min_width = 10
config.max_width = 15
config.min_height = 10
config.max_height = 15
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
# Global switching signals for puppeteers.
"MISMATCHED_COIN_COLLECTED_BY_PARTNER",
]
config.global_observation_names = [
"WORLD.RGB"
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
# Switching signals for puppeteers.
"MISMATCHED_COIN_COLLECTED_BY_PARTNER": specs.float64(),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(136, 136),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * MANDATED_NUM_PLAYERS
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build the coins substrate given player roles."""
assert len(roles) == MANDATED_NUM_PLAYERS, "Wrong number of players"
# Randomly choose colors.
coin_type_a, coin_type_b = random.sample(tuple(COIN_PALETTES), k=2)
# Manually build avatar config.
num_players = len(roles)
player_color_palettes = get_player_color_palettes(
coin_type_a=coin_type_a, coin_type_b=coin_type_b)
avatar_objects = game_object_utils.build_avatar_objects(
num_players, {"avatar": get_avatar(coin_type_a)}, player_color_palettes) # pytype: disable=wrong-arg-types # allow-recursive-types
game_object_utils.get_first_named_component(
avatar_objects[1], "PlayerCoinType")["kwargs"]["coinType"] = coin_type_b
# Build the substrate definition.
substrate_definition = dict(
levelName="coins",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": get_ascii_map(min_width=config.min_width,
max_width=config.max_width,
min_height=config.min_height,
max_height=config.max_height),
"scene": SCENE,
"prefabs": get_prefabs(coin_type_a=coin_type_a,
coin_type_b=coin_type_b),
"charPrefabMap": CHAR_PREFAB_MAP,
"gameObjects": avatar_objects,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/coins.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Bach or Stravinsky in the Matrix (2player, repeated).
Example video: https://youtu.be/I2uYugpdffQ
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Bach or Stravinsky (battle
of the sexes) game. `K = 2` resources represent "Bach" and "Stravinsky" pure
strategies.
Bach or Stravinsky is an asymmetric game. Players are assigned by their slot
id to be either row players (blue) or column players (orange). Interactions are
only resolved when they are between a row player and a column player. Otherwise,
e.g. when a row player tries to interact with another row player, then nothing
happens.
Players have a `5 x 5` observation window.
The episode has a chance of ending stochastically on every 100 step interval
after step 1000. This usually allows time for 8 or more interactions.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is light blue.
RESOURCE1_COLOR = (123, 231, 255, 255)
RESOURCE1_HIGHLIGHT_COLOR = (157, 217, 230, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is light orange.
RESOURCE2_COLOR = (255, 163, 123, 255)
RESOURCE2_HIGHLIGHT_COLOR = (230, 170, 157, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn n nW
W WWW W W W WW W
W W 11a W a22 W W
Wn WW 11a W a22 WW nW
W 11a a22 W
W W
Wn WW WW n WW WWW nW
W W
W 22a W a11 W
Wn W 22a W a11 W nW
W W 22a W a11 WW W
W WWWW W W W WWW W
Wn n nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 32
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"randomTieBreaking": True,
"matrix": [
# row player chooses a row of this matrix.
# B S
[3, 0], # B
[0, 2], # S
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# B S
[2, 0], # B
[0, 3], # S
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue
(0.0, 0.5), (0.5, 1.5), (1.5, 2.5), (2.5, 3.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(resource_id, color_data):
"""Creates resource prefab with provided `resource_id` (num) and color."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": color_data[0],
"#": color_data[1],
"x": (0, 0, 0, 0)}],
"noRotates": [False]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.02,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)
prefabs["resource_class2"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)
return prefabs
def create_avatar_object(player_idx: int,
color: Tuple[int, int, int],
row_player: bool) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(color)],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 5,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "SpawnResourcesWhenAllPlayersZapped",
},
{
"component": "DyadicRole",
"kwargs": {
"rowPlayer": row_player,
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 1.0,
"defaultTastinessReward": 0.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_avatar_objects(
roles: Sequence[str],
) -> Sequence[PrefabConfig]:
"""Returns all avatar game objects."""
avatar_objects = []
for player_idx, role in enumerate(roles):
if role == "default":
if player_idx % 2 == 0:
row_player = True
color = (50, 100, 200)
elif player_idx % 2 == 1:
row_player = False
color = (200, 100, 50)
else:
if role == "bach_fan":
row_player = True
color = (50, 100, 200)
elif role == "stravinsky_fan":
row_player = False
color = (200, 100, 50)
avatar = create_avatar_object(player_idx, color, row_player)
avatar_objects.append(avatar)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default", "bach_fan", "stravinsky_fan"})
config.default_player_roles = ("bach_fan", "stravinsky_fan",)
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given player roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(roles=roles),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/bach_or_stravinsky_in_the_matrix__repeated.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for daycare."""
import copy
from typing import Any, Dict, Mapping, Sequence
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict as configdict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ["N", "E", "S", "W"]
ASCII_MAP = """
/__________________+
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~PPP~~~~~~~~|
!~~~~~~~PPP~~~~~~~~|
!~~~~~~~PPP~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
!~~~~~~~~~~~~~~~~~~|
(------------------)
"""
# Map a character to the prefab it represents in the ASCII map.
CHAR_PREFAB_MAP = {
# wall prefabs
"/": "nw_wall_corner",
"+": "ne_wall_corner",
")": "se_wall_corner",
"(": "sw_wall_corner",
"_": "wall_north",
"|": "wall_east",
"-": "wall_south",
"!": "wall_west",
# non-wall prefabs
"P": {"type": "all", "list": ["ground", "spawn_point"]},
"~": {"type": "all", "list": ["ground", "tree", "fruit"]},
}
INVISIBLE = (0, 0, 0, 0)
NW_WALL_CORNER = {
"name": "nw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_wall_corner",
"stateConfigs": [{
"state": "nw_wall_corner",
"layer": "superOverlay",
"sprite": "NwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_NW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NE_WALL_CORNER = {
"name": "ne_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_wall_corner",
"stateConfigs": [{
"state": "ne_wall_corner",
"layer": "superOverlay",
"sprite": "NeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_NE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SE_WALL_CORNER = {
"name": "se_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_wall_corner",
"stateConfigs": [{
"state": "se_wall_corner",
"layer": "superOverlay",
"sprite": "SeWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_SE_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
SW_WALL_CORNER = {
"name": "sw_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_wall_corner",
"stateConfigs": [{
"state": "sw_wall_corner",
"layer": "superOverlay",
"sprite": "SwWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_SW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NW_INNER_WALL_CORNER = {
"name": "nw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "nw_inner_wall_corner",
"stateConfigs": [{
"state": "nw_inner_wall_corner",
"layer": "superOverlay",
"sprite": "NwInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NwInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_NW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
NE_INNER_WALL_CORNER = {
"name": "ne_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ne_inner_wall_corner",
"stateConfigs": [{
"state": "ne_inner_wall_corner",
"layer": "superOverlay",
"sprite": "NeInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["NeInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_NE_CORNER],
"palettes": [{"b": (166, 162, 139, 255),
"c": (110, 108, 92, 255),
"o": (78, 78, 78, 255)}],
"noRotates": [False]
}
},
]
}
SE_INNER_WALL_CORNER = {
"name": "se_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "se_inner_wall_corner",
"stateConfigs": [{
"state": "se_inner_wall_corner",
"layer": "superOverlay",
"sprite": "SeInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SeInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_SE_CORNER],
"palettes": [{"b": (166, 162, 139, 255),
"c": (110, 108, 92, 255),
"o": (78, 78, 78, 255)}],
"noRotates": [False]
}
},
]
}
SW_INNER_WALL_CORNER = {
"name": "sw_inner_wall_corner",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "sw_inner_wall_corner",
"stateConfigs": [{
"state": "sw_inner_wall_corner",
"layer": "superOverlay",
"sprite": "SwInnerWallCorner",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["SwInnerWallCorner"],
"spriteShapes": [shapes.BRICK_WALL_INNER_SW_CORNER],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_NORTH = {
"name": "wall_north",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_north",
"stateConfigs": [{
"state": "wall_north",
"layer": "superOverlay",
"sprite": "WallNorth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallNorth"],
"spriteShapes": [shapes.BRICK_WALL_NORTH],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_EAST = {
"name": "wall_east",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_east",
"stateConfigs": [{
"state": "wall_east",
"layer": "superOverlay",
"sprite": "WallEast",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallEast"],
"spriteShapes": [shapes.BRICK_WALL_EAST],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_SOUTH = {
"name": "wall_south",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_south",
"stateConfigs": [{
"state": "wall_south",
"layer": "superOverlay",
"sprite": "WallSouth",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallSouth"],
"spriteShapes": [shapes.BRICK_WALL_SOUTH],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
WALL_WEST = {
"name": "wall_west",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall_west",
"stateConfigs": [{
"state": "wall_west",
"layer": "superOverlay",
"sprite": "WallWest",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["WallWest"],
"spriteShapes": [shapes.BRICK_WALL_WEST],
"palettes": [shapes.BRICK_WALL_PALETTE],
"noRotates": [False]
}
},
]
}
GROUND = {
"name": "ground",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "ground",
"stateConfigs": [{
"state": "ground",
"layer": "background",
"sprite": "groundSprite",
}],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["groundSprite"],
"spriteShapes": [shapes.DIRT_PATTERN],
"palettes": [{"X": (155, 118, 83, 255),
"x": (149, 114, 80, 255),}],
"noRotates": [True]
}
},
]
}
def get_fruit_tree_palette(fruit_type):
"""Return a palette with the correct colored fruit."""
palette = copy.deepcopy(shapes.TREE_PALETTE)
if fruit_type == "ripe_apple":
palette["Z"] = (255, 0, 0, 255)
elif fruit_type == "ripe_banana":
palette["Z"] = (255, 255, 53, 255)
elif fruit_type == "unripe_apple":
palette["Z"] = (128, 0, 0, 255)
elif fruit_type == "unripe_banana":
palette["Z"] = (153, 153, 0, 255)
return palette
TREE = {
"name": "tree",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "treeWait",
"stateConfigs": [
{"state": "treeWait"},
{
"state": "appleTree",
"layer": "lowerPhysical",
"sprite": "appleTreeSprite",
},
{
"state": "appleShrub",
"layer": "lowerPhysical",
"sprite": "appleShrubSprite",
},
{
"state": "bananaTree",
"layer": "lowerPhysical",
"sprite": "bananaTreeSprite",
},
{
"state": "bananaShrub",
"layer": "lowerPhysical",
"sprite": "bananaShrubSprite",
},
],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["appleTreeSprite",
"bananaTreeSprite",
"appleShrubSprite",
"bananaShrubSprite",],
"spriteShapes": [shapes.EMPTY_TREE,
shapes.EMPTY_TREE,
shapes.EMPTY_SHRUB,
shapes.EMPTY_SHRUB],
"palettes": [get_fruit_tree_palette("ripe_apple"),
get_fruit_tree_palette("ripe_banana"),
get_fruit_tree_palette("ripe_apple"),
get_fruit_tree_palette("ripe_banana")],
"noRotates": [True] * 4,
}
},
{
"component": "TreeType",
"kwargs": {
"probabilities": {
"empty": 0.8,
"appleTree": 0.15,
"appleShrub": 0.01,
"bananaTree": 0.03,
# lower probability that child can pick up what they like
"bananaShrub": 0.01,
}
}
},
]
}
FRUIT = {
"name": "fruit",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "fruitWait",
"stateConfigs": [
{"state": "fruitWait"},
{"state": "fruitEaten"},
{
"state": "applePicked",
"layer": "overlay",
"sprite": "appleSprite",
},
{
"state": "appleInTree",
"layer": "upperPhysical",
"sprite": "appleInTreeSprite",
},
{
"state": "appleInShrub",
"layer": "upperPhysical",
"sprite": "appleInShrubSprite",
},
{
"state": "bananaPicked",
"layer": "overlay",
"sprite": "bananaSprite",
},
{
"state": "bananaInTree",
"layer": "upperPhysical",
"sprite": "bananaInTreeSprite",
},
{
"state": "bananaInShrub",
"layer": "upperPhysical",
"sprite": "bananaInShrubSprite",
},
],
}
},
{"component": "Transform"},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["appleSprite",
"appleInTreeSprite",
"appleInShrubSprite",
"bananaSprite",
"bananaInTreeSprite",
"bananaInShrubSprite",
],
"spriteShapes": [shapes.HD_APPLE,
shapes.FRUIT_IN_TREE,
shapes.FRUIT_IN_SHRUB,
shapes.HD_APPLE,
shapes.FRUIT_IN_TREE,
shapes.FRUIT_IN_SHRUB,
],
"palettes": [shapes.get_palette((255, 0, 0, 255)),
get_fruit_tree_palette("ripe_apple"),
get_fruit_tree_palette("ripe_apple"),
shapes.get_palette((255, 255, 53, 255)),
get_fruit_tree_palette("ripe_banana"),
get_fruit_tree_palette("ripe_banana"),
],
"noRotates": [True] * 6,
}
},
{
"component": "Graspable",
},
{
"component": "FruitType",
"kwargs": {"framesTillAppleRespawn": 50}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{"component": "Transform"},
]
}
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"nw_wall_corner": NW_WALL_CORNER,
"ne_wall_corner": NE_WALL_CORNER,
"se_wall_corner": SE_WALL_CORNER,
"sw_wall_corner": SW_WALL_CORNER,
"nw_inner_wall_corner": NW_INNER_WALL_CORNER,
"ne_inner_wall_corner": NE_INNER_WALL_CORNER,
"se_inner_wall_corner": SE_INNER_WALL_CORNER,
"sw_inner_wall_corner": SW_INNER_WALL_CORNER,
"wall_north": WALL_NORTH,
"wall_east": WALL_EAST,
"wall_south": WALL_SOUTH,
"wall_west": WALL_WEST,
# non-wall prefabs
"spawn_point": SPAWN_POINT,
"ground": GROUND,
"tree": TREE,
"fruit": FRUIT,
}
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "eat": 0, "grasp": 0}
FORWARD = {"move": 1, "turn": 0, "eat": 0, "grasp": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "eat": 0, "grasp": 0}
BACKWARD = {"move": 3, "turn": 0, "eat": 0, "grasp": 0}
STEP_LEFT = {"move": 4, "turn": 0, "eat": 0, "grasp": 0}
TURN_LEFT = {"move": 0, "turn": -1, "eat": 0, "grasp": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "eat": 0, "grasp": 0}
EAT = {"move": 0, "turn": 0, "eat": 1, "grasp": 0}
GRASP = {"move": 0, "turn": 0, "eat": 0, "grasp": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
EAT,
GRASP,
)
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{"component": "Transform"},
]
}
return scene
def _create_avatar_object(player_idx: int, is_child: bool) -> Dict[str, Any]:
"""Create an avatar object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
live_state_name = "player{}".format(lua_index)
avatar_sprite_name = "avatarSprite{}".format(lua_index)
if is_child:
color_palette = shapes.get_palette(colors.palette[3])
sprite = shapes.CUTE_AVATAR_CHILD
can_grasp_tree = False
# child gets reward for eating bananas
apple_reward = 0
banana_reward = 1
grasp_success_probability = 0.3
# child sees trees as shrubs
custom_sprite_map = {"appleTreeSprite": "appleShrubSprite",
"appleInTreeSprite": "appleInShrubSprite",
"bananaTreeSprite": "bananaShrubSprite",
"bananaInTreeSprite": "bananaInShrubSprite"}
else:
color_palette = shapes.get_palette(colors.palette[0])
sprite = shapes.CUTE_AVATAR
can_grasp_tree = True
apple_reward = 1
banana_reward = 1
grasp_success_probability = 1
# parent sees bananas as apples
custom_sprite_map = {"bananaTreeSprite": "appleTreeSprite",
"bananaShrubSprite": "appleShrubSprite",
"bananaInTreeSprite": "appleInTreeSprite",
"bananaInShrubSprite": "appleInShrubSprite",
"bananaSprite": "appleSprite",}
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState":
live_state_name,
"stateConfigs": [
# Initial player state.
{
"state": live_state_name,
"layer": "superOverlay",
"sprite": avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]
},
# Player wait type for times when they are zapped out.
{
"state": "playerWait",
"groups": ["playerWaits"]
},
]
}
},
{
"component": "Transform"
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [avatar_sprite_name],
"spriteShapes": [sprite],
"palettes": [color_palette],
"noRotates": [True]
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"spawnGroup": "spawnPoints",
"actionOrder": ["move",
"turn",
"eat",
"grasp"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"eat": {"default": 0, "min": 0, "max": 1},
"grasp": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
}
},
{
"component": "Role",
"kwargs": {
"isChild": is_child,
}
},
{
"component": "Eating",
"kwargs": {
"bananaReward": banana_reward,
"appleReward": apple_reward,
}
},
{
"component": "PlayerGrasp",
"kwargs": {
"shape": shapes.GRASP_SHAPE,
"palette": color_palette,
"canGraspTree": can_grasp_tree,
"graspSuccessProbability": grasp_success_probability,
"attentiveParentPseudoreward": 0.0,
"droppingParentPseudoreward": 0.0,
"tryingChildPseudoreward": 0.0,
"tryingChildBananaPseudoreward": 0.0,
}
},
{
"component": "AvatarRespawn",
"kwargs": {
"framesTillRespawn": 100,
}
},
{
"component": "Hunger",
"kwargs": {
"framesTillHungry": 200,
}
},
{
"component": "HungerObserver",
"kwargs": {
"needComponent": "Hunger",
},
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def _build_child_objects(player_idx: int):
"""Build child avatar objects."""
avatar_object = _create_avatar_object(
player_idx, is_child=True)
game_objects = []
game_objects.append(avatar_object)
return game_objects
def _build_parent_objects(player_idx: int):
"""Build parent avatar objects."""
avatar_object = _create_avatar_object(
player_idx, is_child=False)
game_objects = []
game_objects.append(avatar_object)
return game_objects
def create_avatar_objects(roles: Sequence[str]):
"""Returns list of avatar objects of length 'num_players'."""
avatar_objects_and_helpers = []
for player_idx, role in enumerate(roles):
if role == "child":
avatar_objects_and_helpers.extend(_build_child_objects(player_idx))
elif role == "parent":
avatar_objects_and_helpers.extend(_build_parent_objects(player_idx))
elif role == "default":
# Parents and children are alternating, parents in even positions.
if player_idx % 2 == 0:
avatar_objects_and_helpers.extend(_build_parent_objects(player_idx))
else:
avatar_objects_and_helpers.extend(_build_child_objects(player_idx))
else:
raise ValueError(f"Unrecognized role: {role}")
return avatar_objects_and_helpers
def get_config():
"""Default configuration for the daycare substrate."""
config = configdict.ConfigDict()
# Specify the number of players to particate in each episode (optional).
config.recommended_num_players = 2
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"HUNGER",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"HUNGER": specs.float64(),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(104, 160,),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"child", "parent"})
config.default_player_roles = ("child", "parent")
return config
def build(
roles: Sequence[str],
config: configdict.ConfigDict,
) -> Mapping[str, Any]:
"""Build this substrate given player roles."""
del config
substrate_definition = dict(
levelName="daycare",
levelDirectory="meltingpot/lua/levels",
numPlayers=len(roles),
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation=dict(
map=ASCII_MAP,
gameObjects=create_avatar_objects(roles),
scene=create_scene(),
prefabs=PREFABS,
charPrefabMap=CHAR_PREFAB_MAP,
),
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/daycare.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Capture the Flag.
Example video: https://youtu.be/ECzevYpi1dM
This substrate a team based zero sum game. There are four players on each team.
There is a red team and blue team. Players can paint the ground anywhere by
using their zapping beam. If they stand on their own color then they gain health
up to a maximum of 3 (so they are more likely to win shootouts). They lose
health down to 1 from their default of 2 when standing on the opposing team's
color (so they are more likely to lose shootouts in that case). Health recovers
stochastically, at a fixed rate of 0.05 per frame. It cannot exceed its maximum,
determined by the current color of the ground the agent is standing on.
Players also cannot move over their opposing team's color. If the opposing team
paints the square underneath their feet then they get stuck in place until they
use their own zapping beam to re-paint the square underneath and in front of
themselves to break free. In practice this slows them down by one frame (which
may be critical if they are being chased).
Friendly fire is impossible; agents cannot zap their teammates.
In the _Capture the Flag_ substrate the final goal is capturing the opposing
team's flag. Payoffs are common to the entire winning team. Indicator tiles
around the edge of the map and in its very center display which teams have their
own flag on their base, allowing them the possibility of capturing their
opponent's flag by bringing it to their own base/flag. When indicator tiles are
red then only the red team can score. When indicator tiles are blue then only
the blue team can score. When the indicator tiles are purple then both teams
have the possibility of scoring (though neither is close to doing so) since both
flags are in their respective home bases.
"""
from typing import Any, Dict, Mapping, Optional, Sequence
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
import numpy as np
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
_COMPASS = ["N", "E", "S", "W"]
ASCII_MAP = """
IIIIIIIIIIIIIIIIIIIIIII
IWWWWWWWWWWWWWWWWWWWWWI
IWPPP,PPPP,F,PPPP,PPPWI
IWPPP,,PP,,,,,PP,,PPPWI
IWPPP,,,,,,,,,,,,,PPPWI
IWP,,WW,,,,,,,,,WW,,PWI
IWHHWWW,WWWWWWW,WWWHHWI
IWHHW,D,,,,,,,,,D,WHHWI
IWHH,,W,,,WWW,,,W,,HHWI
IW,,,,W,,,,,,,,,W,,,,WI
IW,,,,WWW,,,,,WWW,,,,WI
IW,,,,,,,,,I,,,,,,,,,WI
IW,,,,WWW,,,,,WWW,,,,WI
IW,,,,W,,,,,,,,,W,,,,WI
IWHH,,W,,,WWW,,,W,,HHWI
IWHHW,D,,,,,,,,,D,WHHWI
IWHHWWW,WWWWWWW,WWWHHWI
IWQ,,WW,,,,,,,,,WW,,QWI
IWQQQ,,,,,,,,,,,,,QQQWI
IWQQQ,,QQ,,,,,QQ,,QQQWI
IWQQQ,QQQQ,G,QQQQ,QQQWI
IWWWWWWWWWWWWWWWWWWWWWI
IIIIIIIIIIIIIIIIIIIIIII
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"P": {"type": "all", "list": ["spawn_point_red", "ground"]},
"Q": {"type": "all", "list": ["spawn_point_blue", "ground"]},
"W": "wall",
"D": {"type": "choice",
"list": ["destroyable_wall"] * 9 + ["destroyed_wall"]},
"H": {"type": "choice",
"list": ["destroyable_wall"] * 3 + ["destroyed_wall"]},
",": "ground",
"I": {"type": "all", "list": ["indicator", "indicator_frame"]},
"F": {"type": "all", "list": ["ground", "home_tile_red", "flag_red"]},
"G": {"type": "all", "list": ["ground", "home_tile_blue", "flag_blue"]},
}
RED_COLOR = (225, 55, 85, 255)
DARKER_RED_COLOR = (200, 35, 55, 255)
DARKEST_RED_COLOR = (160, 5, 25, 255)
BLUE_COLOR = (85, 55, 225, 255)
DARKER_BLUE_COLOR = (55, 35, 200, 255)
DARKEST_BLUE_COLOR = (25, 5, 160, 255)
PURPLE_COLOR = (107, 63, 160, 255)
def multiply_tuple(color_tuple, factor):
alpha = color_tuple[3]
return tuple([int(np.min([x * factor, alpha])) for x in color_tuple[0: 3]])
TEAMS_DATA = {
"red": {"color": RED_COLOR,
"spawn_group": "{}SpawnPoints".format("red")},
"blue": {"color": BLUE_COLOR,
"spawn_group": "{}SpawnPoints".format("blue")},
}
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall",],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [True]
}
},
{
"component": "AllBeamBlocker",
"kwargs": {}
},
]
}
INDICATOR_FRAME = {
"name": "indicator_frame",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inert",
"stateConfigs": [
{"state": "inert",
"layer": "superOverlay",
"sprite": "InertFrame"}
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["InertFrame"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": (0, 0, 0, 0),
"x": (55, 55, 55, 255),
"#": (0, 0, 0, 0)}],
"noRotates": [True]
}
},
]
}
INDICATOR = {
"name": "control_indicator",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "both",
"stateConfigs": [
{
"state": "neither",
"layer": "background",
"sprite": "NeitherIndicator",
},
{
"state": "red",
"layer": "background",
"sprite": "RedIndicator",
},
{
"state": "blue",
"layer": "background",
"sprite": "BlueIndicator",
},
{
"state": "both",
"layer": "background",
"sprite": "BothIndicator",
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"spriteNames": ["NeitherIndicator",
"RedIndicator",
"BlueIndicator",
"BothIndicator"],
"spriteRGBColors": [(0, 0, 0, 0),
DARKER_RED_COLOR,
DARKER_BLUE_COLOR,
PURPLE_COLOR]
}
},
{"component": "ControlIndicator",},
]
}
def create_home_tile_prefab(team: str):
"""Return a home tile prefab, where the flag starts and must be brought."""
sprite_name = "HomeTileFrame{}".format(team)
prefab = {
"name": "home_tile",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "inert",
"stateConfigs": [
{"state": "inert",
"layer": "background",
"sprite": sprite_name}
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [sprite_name],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": (0, 0, 0, 0),
"x": (0, 0, 0, 0),
"#": (218, 165, 32, 255)}],
"noRotates": [True]
}
},
{
"component": "HomeTile",
"kwargs": {
"team": team,
}
},
]
}
return prefab
def create_ground_prefab():
"""Return a prefab for a colorable ground prefab."""
sprite_names = ["RedGround", "BlueGround"]
sprite_colors = [DARKEST_RED_COLOR, DARKEST_BLUE_COLOR]
prefab = {
"name": "ground",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "clean",
"stateConfigs": [
{
"state": "clean",
"layer": "alternateLogic",
},
{
"state": "red",
"layer": "alternateLogic",
"sprite": sprite_names[0],
},
{
"state": "blue",
"layer": "alternateLogic",
"sprite": sprite_names[1],
},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"spriteNames": sprite_names,
"spriteRGBColors": sprite_colors
}
},
{
"component": "Ground",
"kwargs": {
"teamNames": ["red", "blue"],
}
},
]
}
return prefab
def create_destroyable_wall_prefab(initial_state):
"""Return destroyable wall prefab, potentially starting in destroyed state."""
if initial_state == "destroyed":
initial_health = 0
else:
initial_health = 5
prefab = {
"name": "destroyableWall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": initial_state,
"stateConfigs": [
{
"state": "destroyable",
"layer": "upperPhysical",
"sprite": "DestroyableWall",
},
{
"state": "damaged",
"layer": "upperPhysical",
"sprite": "DamagedWall",
},
{
"state": "destroyed",
"layer": "alternateLogic",
"sprite": "Rubble",
},
],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["DestroyableWall",
"DamagedWall",
"Rubble"],
"spriteShapes": [shapes.WALL,
shapes.WALL,
shapes.WALL],
"palettes": [{"*": (55, 55, 55, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)},
{"*": (55, 55, 55, 255),
"&": (100, 100, 100, 255),
"@": (79, 79, 79, 255),
"#": (152, 152, 152, 255)},
{"*": (0, 0, 0, 255),
"&": (0, 0, 0, 255),
"@": (29, 29, 29, 255),
"#": (0, 0, 0, 255)}],
"noRotates": [True] * 3
}
},
{
"component": "Destroyable",
"kwargs": {"hitNames": ["red", "blue"],
"initialHealth": initial_health,
"damagedHealthLevel": 2}
}
]
}
return prefab
def create_spawn_point_prefab(team):
"""Return a team-specific spawn-point prefab."""
prefab = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs": [{
"state": "playerSpawnPoint",
"layer": "logic",
"groups": [TEAMS_DATA[team]["spawn_group"]],
}],
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "invisible",
"spriteNames": [],
"spriteRGBColors": []
}
},
]
}
return prefab
def create_flag_prefab(team: str):
"""Return a team-specific flag prefab."""
dropped_sprite_name = "DroppedFlag_{}".format(team)
carried_sprite_name = "CarriedFlag_{}".format(team)
if team == "red":
flag_color = RED_COLOR
elif team == "blue":
flag_color = BLUE_COLOR
prefab = {
"name": "{}_flag".format(team),
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "dropped",
"stateConfigs": [
{
"state": "dropped",
"layer": "lowerPhysical",
"sprite": dropped_sprite_name,
},
{
"state": "carried",
"layer": "overlay",
"sprite": carried_sprite_name,
},
{
"state": "wait",
}
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [dropped_sprite_name, carried_sprite_name],
"spriteShapes": [shapes.FLAG,
shapes.FLAG_HELD],
"palettes": [shapes.get_palette(flag_color)] * 2,
"noRotates": [True, True]
}
},
{
"component": "Flag",
"kwargs": {
"team": team,
}
}
]
}
return prefab
# PREFABS is a dictionary mapping names to template game objects that can
# be cloned and placed in multiple locations accoring to an ascii map.
PREFABS = {
"wall": WALL,
"spawn_point_red": create_spawn_point_prefab("red"),
"spawn_point_blue": create_spawn_point_prefab("blue"),
"destroyable_wall": create_destroyable_wall_prefab("destroyable"),
"destroyed_wall": create_destroyable_wall_prefab("destroyed"),
"ground": create_ground_prefab(),
"indicator": INDICATOR,
"indicator_frame": INDICATOR_FRAME,
"flag_red": create_flag_prefab("red"),
"flag_blue": create_flag_prefab("blue"),
"home_tile_red": create_home_tile_prefab("red"),
"home_tile_blue": create_home_tile_prefab("blue"),
}
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "fireZap": 0}
FORWARD = {"move": 1, "turn": 0, "fireZap": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "fireZap": 0}
BACKWARD = {"move": 3, "turn": 0, "fireZap": 0}
STEP_LEFT = {"move": 4, "turn": 0, "fireZap": 0}
TURN_LEFT = {"move": 0, "turn": -1, "fireZap": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "fireZap": 0}
FIRE_ZAP_A = {"move": 0, "turn": 0, "fireZap": 1}
FIRE_ZAP_B = {"move": 0, "turn": 0, "fireZap": 2}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
FIRE_ZAP_A, # a short-range beam with a wide area of effect
FIRE_ZAP_B, # a longer range beam with a thin area of effect
)
# The Scene is a non-physical object, its components implement global logic.
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{"component": "Transform",},
{
"component": "FlagManager",
"kwargs": {}
},
]
}
return scene
def create_avatar_object(
player_idx: int,
team: str,
override_taste_kwargs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Create an avatar object."""
# Lua is 1-indexed.
lua_index = player_idx + 1
team_color = TEAMS_DATA[team]["color"]
health1_avatar_sprite_name = "avatarSprite{}Health1".format(lua_index)
health2_avatar_sprite_name = "avatarSprite{}Health2".format(lua_index)
health3_avatar_sprite_name = "avatarSprite{}Health3".format(lua_index)
health1_color_palette = shapes.get_palette(multiply_tuple(team_color, 0.35))
health2_color_palette = shapes.get_palette(team_color)
health3_color_palette = shapes.get_palette(multiply_tuple(team_color, 1.75))
taste_kwargs = {
"defaultTeamReward": 1.0,
"rewardForZapping": 0.0,
"extraRewardForZappingFlagCarrier": 0.0,
"rewardForReturningFlag": 0.0,
"rewardForPickingUpOpposingFlag": 0.0,
}
if override_taste_kwargs:
taste_kwargs.update(override_taste_kwargs)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "health2",
"stateConfigs": [
{"state": "health1",
"layer": "upperPhysical",
"sprite": health1_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
{"state": "health2",
"layer": "upperPhysical",
"sprite": health2_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
{"state": "health3",
"layer": "upperPhysical",
"sprite": health3_avatar_sprite_name,
"contact": "avatar",
"groups": ["players"]},
# Player wait state used when they have been zapped out.
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{"component": "Transform",},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [health1_avatar_sprite_name,
health2_avatar_sprite_name,
health3_avatar_sprite_name],
"spriteShapes": [shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR,
shapes.CUTE_AVATAR],
"palettes": [health1_color_palette,
health2_color_palette,
health3_color_palette],
"noRotates": [True] * 3
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": "health2",
"additionalLiveStates": ["health1", "health3"],
"waitState": "playerWait",
"spawnGroup": TEAMS_DATA[team]["spawn_group"],
"actionOrder": ["move",
"turn",
"fireZap"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"fireZap": {"default": 0, "min": 0, "max": 2},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
# The following kwarg makes it possible to get rewarded for
# team rewards even when an avatar is "dead".
"skipWaitStateRewards": False,
}
},
{
"component": "ColorZapper",
"kwargs": {
"team": team,
# The color zapper beam is somewhat transparent.
"color": (team_color[0], team_color[1], team_color[2], 150),
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"secondaryBeamCooldownTime": 4,
"secondaryBeamLength": 6,
"secondaryBeamRadius": 0,
"aliveStates": ["health1", "health2", "health3"],
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "ColorZapper",
}
},
{
"component": "ZappedByColor",
"kwargs": {
"team": team,
"allTeamNames": ["red", "blue"],
"framesTillRespawn": 80,
"penaltyForBeingZapped": 0,
"rewardForZapping": 0,
"healthRegenerationRate": 0.05,
"maxHealthOnGround": 2,
"maxHealthOnOwnColor": 3,
"maxHealthOnEnemyColor": 1,
"groundLayer": "alternateLogic",
}
},
{
"component": "TeamMember",
"kwargs": {"team": team}
},
{
"component": "Taste",
"kwargs": taste_kwargs
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def _even_vs_odd_team_assignment(num_players,
taste_kwargs: Optional[Any] = None):
"""Assign players with even ids to red team and odd ids to blue team."""
avatar_objects = []
for player_idx in range(0, num_players):
if player_idx % 2 == 0:
team = "red"
elif player_idx % 2 == 1:
team = "blue"
game_object = create_avatar_object(player_idx, team,
override_taste_kwargs=taste_kwargs)
avatar_objects.append(game_object)
return avatar_objects
def _low_vs_high_team_assignment(num_players,
taste_kwargs: Optional[Any] = None):
"""Assign players with id below the median id to blue and above it to red."""
median = np.median(range(num_players))
avatar_objects = []
for player_idx in range(0, num_players):
if player_idx < median:
team = "blue"
elif player_idx > median:
team = "red"
game_object = create_avatar_object(player_idx, team,
override_taste_kwargs=taste_kwargs)
avatar_objects.append(game_object)
return avatar_objects
def create_avatar_objects(num_players,
taste_kwargs: Optional[Any] = None,
fixed_teams: Optional[bool] = False):
"""Returns list of avatar objects of length 'num_players'."""
assert num_players % 2 == 0, "num players must be divisible by 2"
if fixed_teams:
avatar_objects = _low_vs_high_team_assignment(num_players,
taste_kwargs=taste_kwargs)
else:
avatar_objects = _even_vs_odd_team_assignment(num_players,
taste_kwargs=taste_kwargs)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# If shaping_kwargs are None then use the default reward structure in which
# the only positive rewards are those that are delivered when your team
# captures its opposing team's flag and the only negative rewards are those
# delivered when the opposing team captures your team's flag. The default
# reward structure is zero sum.
config.shaping_kwargs = None
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"READY_TO_SHOOT",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(184, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given player roles."""
num_players = len(roles)
substrate_definition = dict(
levelName="paintball__capture_the_flag",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(
num_players, taste_kwargs=config.shaping_kwargs),
"scene": create_scene(),
"prefabs": PREFABS,
"charPrefabMap": CHAR_PREFAB_MAP,
},
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/paintball__capture_the_flag.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Chicken (hawk - dove) in the Matrix.
Example video: https://youtu.be/94DHJ6BVEJM
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents the Chicken game. `K = 2`
resources represent "hawk" and "dove" pure strategies.
Players have the default `11 x 11` (off center) observation window.
"""
from typing import Any, Dict, Mapping, Sequence
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import game_object_utils
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
PrefabConfig = game_object_utils.PrefabConfig
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 2
# This color is green.
RESOURCE1_COLOR = (30, 225, 185, 255)
RESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is red.
RESOURCE2_COLOR = (225, 30, 70, 255)
RESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# The procedural generator replaces all 'a' chars in the default map with chars
# representing specific resources, i.e. with either '1' or '2'.
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWWWW
WPPPP W W PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
W W
W 11 W
W 11 W
W aa W
W WW W 222 W
WW 1a W 222 W
WWW 1a WWWWWWWWW W
W 1a 111 WWW
W 111 W
W aa W W
W 22 W WW W
W 22 Waaa W
W 222 W
W W
WPPPP PPPPW
WPPPP PPPPW
WPPPP PPPPW
WPPPP W PPPPW
WWWWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"1": _resource_names[0],
"2": _resource_names[1],
"P": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# Remove the first entry from human_readable_colors after using it for the self
# color to prevent it from being used again as another avatar color.
human_readable_colors = list(colors.human_readable)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette(human_readable_colors.pop(0)),
"noRotate": True,
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
PLAYER_COLOR_PALETTES = []
for human_readable_color in human_readable_colors:
PLAYER_COLOR_PALETTES.append(shapes.get_palette(human_readable_color))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# row player chooses a row of this matrix.
# D H (conventionally D = dove and H = hawk)
[3, 2], # D
[5, 0], # H
],
"columnPlayerMatrix": [
# column player chooses a column of this matrix.
# D H (conventionally D = dove and H = hawk)
[3, 5], # D
[2, 0], # H
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue
(0.0, 1.5), (1.5, 2.5), (2.5, 3.5), (3.5, 5.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.2
}
}
]
}
return scene
def create_resource_prefab(resource_id, color_data):
"""Creates resource prefab with provided `resource_id` (num) and color."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [shapes.BUTTON],
"palettes": [{"*": color_data[0],
"#": color_data[1],
"x": (0, 0, 0, 0)}],
"noRotates": [False]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.04,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_prefabs() -> PrefabConfig:
"""Returns the prefabs.
Prefabs are a dictionary mapping names to template game objects that can
be cloned and placed in multiple locations accoring to an ascii map.
"""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)
prefabs["resource_class2"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)
return prefabs
def create_avatar_object(player_idx: int,
target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:
"""Create an avatar object that always sees itself as blue."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [source_sprite_self],
"spriteShapes": [shapes.CUTE_AVATAR],
"palettes": [shapes.get_palette(
human_readable_colors[player_idx])],
"noRotates": [True]
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"]],
"customSpriteShapes": [target_sprite_self["shape"]],
"customPalettes": [target_sprite_self["palette"]],
"customNoRotates": [target_sprite_self["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 5,
"right": 5,
"forward": 9,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 50,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": False,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append(
{
"component": "LocationObserver",
"kwargs": {
"objectIsAvatar": True,
"alsoReportOrientation": True
}
},
)
return avatar_object
def create_avatar_objects(num_players: int) -> Sequence[PrefabConfig]:
"""Returns all game objects for the map.
Args:
num_players: number of players to create avatars for.
"""
avatar_objects = []
for player_idx in range(num_players):
avatar = create_avatar_object(player_idx, TARGET_SPRITE_SELF)
avatar_objects.append(avatar)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"INVENTORY": specs.inventory(2),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(2),
"WORLD.RGB": specs.rgb(192, 200),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 8
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/chicken_in_the_matrix__arena.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Config for Rationalizable Coordination in the Matrix (2 player, repeated).
Example video: https://youtu.be/3brwR7DtxEI
See _Running with Scissors in the Matrix_ for a general description of the
game dynamics. Here the payoff matrix represents a pure coordination game.
`K = 3`, three different resources corresponding to different coordination
outcomes.
Players have a `5 x 5` observation window.
The episode has a chance of ending stochastically on every 100 step interval
after step 1000. This usually allows time for 8 or more interactions.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 3
# This color is red.
RESOURCE1_COLOR = (150, 0, 0, 255)
RESOURCE1_HIGHLIGHT_COLOR = (200, 0, 0, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is green.
RESOURCE2_COLOR = (0, 150, 0, 255)
RESOURCE2_HIGHLIGHT_COLOR = (0, 200, 0, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# This color is blue.
RESOURCE3_COLOR = (0, 0, 150, 255)
RESOURCE3_HIGHLIGHT_COLOR = (0, 0, 200, 255)
RESOURCE3_COLOR_DATA = (RESOURCE3_COLOR, RESOURCE3_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn n nW
W WWW W W WW W
W W rra app W W
Wn WW rra app WW nW
W rra app W
W W
Wn WW n nW
W WWWW W
W ssa W W
Wn W ssa W aaa W nW
W W ssa W aaa WW W
W WWWW W W W WWW W
Wn n nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
"resource_class3",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"r": _resource_names[0],
"p": _resource_names[1],
"s": _resource_names[2],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 8
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
TARGET_SPRITE_OTHER = {
"name": "Other",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((200, 100, 50)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
# 1 2 3
[1, 0, 0], # 1
[0, 2, 0], # 2
[0, 0, 3] # 3
],
"resultIndicatorColorIntervals": [
# red # yellow # green # blue
(0.0, 0.5), (0.5, 1.5), (1.5, 2.5), (2.5, 3.0)
],
}
},
{
"component": "StochasticIntervalEpisodeEnding",
"kwargs": {
"minimumFramesPerEpisode": 1000,
"intervalLength": 100, # Set equal to unroll length.
"probabilityTerminationPerInterval": 0.1
}
}
]
}
return scene
def create_resource_prefab(
resource_id: int,
resource_shape: str,
resource_palette: Dict[str, Tuple[int, int, int, int]]):
"""Creates resource prefab with provided resource_id, shape, and palette."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [resource_shape],
"palettes": [resource_palette],
"noRotates": [True]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
"regenerationRate": 0.02,
"regenerationDelay": 10,
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It is possible to destroy resources but takes concerted
# effort to do so by zapping them `initialHealth` times.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_avatar_object(
player_idx: int,
all_source_sprite_names: Sequence[str],
target_sprite_self: Dict[str, Any],
target_sprite_other: Dict[str, Any],
turn_off_default_reward: bool = False) -> Dict[str, Any]:
"""Create an avatar object given self vs other sprite data."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
for name in all_source_sprite_names:
if name != source_sprite_self:
custom_sprite_map[name] = target_sprite_other["name"]
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": [source_sprite_self],
# A white square should never be displayed. It will always be
# remapped since this is self vs other observation mode.
"spriteRGBColors": [(255, 255, 255, 255)],
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"],
target_sprite_other["name"]],
"customSpriteShapes": [target_sprite_self["shape"],
target_sprite_other["shape"]],
"customPalettes": [target_sprite_self["palette"],
target_sprite_other["palette"]],
"customNoRotates": [target_sprite_self["noRotate"],
target_sprite_other["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 5,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": False,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "SpawnResourcesWhenAllPlayersZapped",
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": turn_off_default_reward,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_prefabs():
"""Returns a dictionary mapping names to template game objects."""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(
1, shapes.BUTTON, {"*": RESOURCE1_COLOR_DATA[0],
"#": RESOURCE1_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class2"] = create_resource_prefab(
2, shapes.BUTTON, {"*": RESOURCE2_COLOR_DATA[0],
"#": RESOURCE2_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class3"] = create_resource_prefab(
3, shapes.BUTTON, {"*": RESOURCE3_COLOR_DATA[0],
"#": RESOURCE3_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
return prefabs
def get_all_source_sprite_names(num_players):
all_source_sprite_names = []
for player_idx in range(0, num_players):
# Lua is 1-indexed.
lua_index = player_idx + 1
all_source_sprite_names.append("Avatar" + str(lua_index))
return all_source_sprite_names
def create_avatar_objects(num_players,
turn_off_default_reward: bool = False):
"""Returns list of avatar objects of length 'num_players'."""
all_source_sprite_names = get_all_source_sprite_names(num_players)
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(
player_idx,
all_source_sprite_names,
TARGET_SPRITE_SELF,
TARGET_SPRITE_OTHER,
turn_off_default_reward=turn_off_default_reward)
avatar_objects.append(game_object)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(readiness_marker)
return avatar_objects
def create_world_sprite_map(
num_players: int, target_sprite_other: Dict[str, Any]) -> Dict[str, str]:
all_source_sprite_names = get_all_source_sprite_names(num_players)
world_sprite_map = {}
for name in all_source_sprite_names:
world_sprite_map[name] = target_sprite_other["name"]
return world_sprite_map
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Other parameters that are useful to override in training config files.
config.turn_off_default_reward = False
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(3),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(3),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
# Define upper bound of episode length since episodes end stochastically.
maxEpisodeLengthFrames=5000,
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
# worldSpriteMap is needed to make the global view used in videos be
# be informative in cases where individual avatar views have had
# sprites remapped to one another (example: self vs other mode).
"worldSpriteMap": create_world_sprite_map(num_players,
TARGET_SPRITE_OTHER),
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/rationalizable_coordination_in_the_matrix__repeated.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Running with Scissors in the Matrix (one shot version).
Example video: https://youtu.be/gtemAx4XEcQ
Players can move around the map and collect resources of `K` discrete types. In
addition to movement, the agents have an action to fire an "interaction" beam.
All players carry an inventory with the count of resources picked up since last
respawn.
Players can observe their own inventory but not the inventories of their
coplayers. When another agent is zapped with the interaction beam, an
interaction occurs. The resolution of the interactions is determined by a
traditional matrix game, where there is a `K x K` payoff matrix describing the
reward produced by the pure strategies available to the two players. The
resources map one-to-one to the pure strategies of the matrix game. Unless
stated otherwise, for the purposes of resolving the interaction, the zapping
agent is considered the row player, and the zapped agent the column player. The
actual strategy played depends on the resources picked up before the
interaction. The more resources of a given type an agent picks up, the more
committed the agent becomes to the pure strategy corresponding to that resource.
In the case of running with scissors, `K = 3`, corresponding to rock, paper, and
scissors pure strategies respectively.
The payoff matrix is the traditional rock-paper-scissors game matrix.
Running with scissors was first described in Vezhnevets et al. (2020). Two
players gather rock, paper or scissor resources in the environment and can
challenge one another to a 'rock, paper scissor' game, the outcome of which
depends on the resources they collected. It is possible to observe the policy
that one's partner is starting to implement, either by watching them pick up
resources or by noting which resources are missing, and then take
countermeasures. This induces a wealth of possible feinting strategies.
Players can also zap resources with their interaction beam to destroy them. This
creates additional scope for feinting strategies.
Players have a `5 x 5` observation window.
The episode ends after a single interaction.
Vezhnevets, A., Wu, Y., Eckstein, M., Leblond, R. and Leibo, J.Z., 2020. OPtions
as REsponses: Grounding behavioural hierarchies in multi-agent reinforcement
learning. In International Conference on Machine Learning (pp. 9733-9742). PMLR.
"""
from typing import Any, Dict, Mapping, Sequence, Tuple
from meltingpot.configs.substrates import the_matrix
from meltingpot.utils.substrates import colors
from meltingpot.utils.substrates import shapes
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
# Warning: setting `_ENABLE_DEBUG_OBSERVATIONS = True` may cause slowdown.
_ENABLE_DEBUG_OBSERVATIONS = False
# The number of resources must match the (square) size of the matrix.
NUM_RESOURCES = 3
# This color is yellow.
RESOURCE1_COLOR = (255, 227, 11, 255)
RESOURCE1_HIGHLIGHT_COLOR = (255, 214, 91, 255)
RESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)
# This color is violet.
RESOURCE2_COLOR = (109, 42, 255, 255)
RESOURCE2_HIGHLIGHT_COLOR = (132, 91, 255, 255)
RESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)
# This color is cyan.
RESOURCE3_COLOR = (42, 188, 255, 255)
RESOURCE3_HIGHLIGHT_COLOR = (91, 214, 255, 255)
RESOURCE3_COLOR_DATA = (RESOURCE3_COLOR, RESOURCE3_HIGHLIGHT_COLOR)
ASCII_MAP = """
WWWWWWWWWWWWWWWWWWWWWWW
Wn r r a a p p nW
W W
Wn r r a a p p nW
W W
Wn r r a a p p nW
W W
W n n n W
W W
Wn s s a a a a nW
W W
Wn s s a a a a nW
W W
Wn s s a a a a nW
WWWWWWWWWWWWWWWWWWWWWWW
"""
_resource_names = [
"resource_class1",
"resource_class2",
"resource_class3",
]
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
CHAR_PREFAB_MAP = {
"a": {"type": "choice", "list": _resource_names},
"r": _resource_names[0],
"p": _resource_names[1],
"s": _resource_names[2],
"n": "spawn_point",
"W": "wall",
}
_COMPASS = ["N", "E", "S", "W"]
WALL = {
"name": "wall",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "wall",
"stateConfigs": [{
"state": "wall",
"layer": "upperPhysical",
"sprite": "Wall",
}],
}
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": ["Wall"],
"spriteShapes": [shapes.WALL],
"palettes": [{"*": (95, 95, 95, 255),
"&": (100, 100, 100, 255),
"@": (109, 109, 109, 255),
"#": (152, 152, 152, 255)}],
"noRotates": [False]
}
},
{
"component": "BeamBlocker",
"kwargs": {
"beamType": "gameInteraction"
}
},
]
}
SPAWN_POINT = {
"name": "spawnPoint",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "spawnPoint",
"stateConfigs": [{
"state": "spawnPoint",
"layer": "alternateLogic",
"groups": ["spawnPoints"]
}],
}
},
{
"component": "Transform",
},
]
}
# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use
# for the player at the corresponding index.
NUM_PLAYERS_UPPER_BOUND = 8
PLAYER_COLOR_PALETTES = []
for idx in range(NUM_PLAYERS_UPPER_BOUND):
PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))
# Primitive action components.
# pylint: disable=bad-whitespace
# pyformat: disable
NOOP = {"move": 0, "turn": 0, "interact": 0}
FORWARD = {"move": 1, "turn": 0, "interact": 0}
STEP_RIGHT = {"move": 2, "turn": 0, "interact": 0}
BACKWARD = {"move": 3, "turn": 0, "interact": 0}
STEP_LEFT = {"move": 4, "turn": 0, "interact": 0}
TURN_LEFT = {"move": 0, "turn": -1, "interact": 0}
TURN_RIGHT = {"move": 0, "turn": 1, "interact": 0}
INTERACT = {"move": 0, "turn": 0, "interact": 1}
# pyformat: enable
# pylint: enable=bad-whitespace
ACTION_SET = (
NOOP,
FORWARD,
BACKWARD,
STEP_LEFT,
STEP_RIGHT,
TURN_LEFT,
TURN_RIGHT,
INTERACT,
)
TARGET_SPRITE_SELF = {
"name": "Self",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((50, 100, 200)),
"noRotate": True,
}
TARGET_SPRITE_OTHER = {
"name": "Other",
"shape": shapes.CUTE_AVATAR,
"palette": shapes.get_palette((200, 100, 50)),
"noRotate": True,
}
def create_scene():
"""Creates the global scene."""
scene = {
"name": "scene",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "scene",
"stateConfigs": [{
"state": "scene",
}],
}
},
{
"component": "Transform",
},
{
"component": "TheMatrix",
"kwargs": {
# Prevent interaction before both interactors have collected
# at least one resource.
"disallowUnreadyInteractions": True,
"matrix": [
[0, -10, 10],
[10, 0, -10],
[-10, 10, 0]
],
"resultIndicatorColorIntervals": [
(-10.0, -5.0), # red
(-5.0, -2.5), # yellow
(-2.5, 2.5), # green
(2.5, 5.0), # blue
(5.0, 10.0) # violet
],
}
},
]
}
return scene
def create_resource_prefab(
resource_id: int,
resource_shape: str,
resource_palette: Dict[str, Tuple[int, int, int, int]]):
"""Creates resource prefab with provided resource_id, shape, and palette."""
resource_name = "resource_class{}".format(resource_id)
resource_prefab = {
"name": resource_name,
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": resource_name,
"stateConfigs": [
{"state": resource_name + "_wait",
"groups": ["resourceWaits"]},
{"state": resource_name,
"layer": "lowerPhysical",
"sprite": resource_name + "_sprite"},
]
},
},
{
"component": "Transform",
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "ascii_shape",
"spriteNames": [resource_name + "_sprite"],
"spriteShapes": [resource_shape],
"palettes": [resource_palette],
"noRotates": [True]
},
},
{
"component": "Resource",
"kwargs": {
"resourceClass": resource_id,
"visibleType": resource_name,
"waitState": resource_name + "_wait",
# Resources never regenerate since this substrate is one-shot.
"regenerationRate": 0,
"regenerationDelay": 1000
},
},
{
"component": "Destroyable",
"kwargs": {
"waitState": resource_name + "_wait",
# It takes concerted effort to destroy resources here because
# this substrate is one-shot.
"initialHealth": 3,
},
},
]
}
return resource_prefab
def create_avatar_object(
player_idx: int,
all_source_sprite_names: Sequence[str],
target_sprite_self: Dict[str, Any],
target_sprite_other: Dict[str, Any],
turn_off_default_reward: bool = False) -> Dict[str, Any]:
"""Create an avatar object given self vs other sprite data."""
# Lua is 1-indexed.
lua_index = player_idx + 1
# Setup the self vs other sprite mapping.
source_sprite_self = "Avatar" + str(lua_index)
custom_sprite_map = {source_sprite_self: target_sprite_self["name"]}
for name in all_source_sprite_names:
if name != source_sprite_self:
custom_sprite_map[name] = target_sprite_other["name"]
live_state_name = "player{}".format(lua_index)
avatar_object = {
"name": "avatar",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": live_state_name,
"stateConfigs": [
{"state": live_state_name,
"layer": "upperPhysical",
"sprite": source_sprite_self,
"contact": "avatar",
"groups": ["players"]},
{"state": "playerWait",
"groups": ["playerWaits"]},
]
}
},
{
"component": "Transform",
"kwargs": {
"position": (0, 0),
"orientation": "N"
}
},
{
"component": "Appearance",
"kwargs": {
"renderMode": "colored_square",
"spriteNames": [source_sprite_self],
# A white square should never be displayed. It will always be
# remapped since this is self vs other observation mode.
"spriteRGBColors": [(255, 255, 255, 255)],
}
},
{
"component": "AdditionalSprites",
"kwargs": {
"renderMode": "ascii_shape",
"customSpriteNames": [target_sprite_self["name"],
target_sprite_other["name"]],
"customSpriteShapes": [target_sprite_self["shape"],
target_sprite_other["shape"]],
"customPalettes": [target_sprite_self["palette"],
target_sprite_other["palette"]],
"customNoRotates": [target_sprite_self["noRotate"],
target_sprite_other["noRotate"]],
}
},
{
"component": "Avatar",
"kwargs": {
"index": lua_index,
"aliveState": live_state_name,
"waitState": "playerWait",
"speed": 1.0,
"spawnGroup": "spawnPoints",
"actionOrder": ["move", "turn", "interact"],
"actionSpec": {
"move": {"default": 0, "min": 0, "max": len(_COMPASS)},
"turn": {"default": 0, "min": -1, "max": 1},
"interact": {"default": 0, "min": 0, "max": 1},
},
"view": {
"left": 2,
"right": 2,
"forward": 3,
"backward": 1,
"centered": False
},
"spriteMap": custom_sprite_map,
# The following kwarg makes it possible to get rewarded even
# on frames when an avatar is "dead". It is needed for in the
# matrix games in order to correctly handle the case of two
# players getting hit simultaneously by the same beam.
"skipWaitStateRewards": False,
}
},
{
"component": "GameInteractionZapper",
"kwargs": {
"cooldownTime": 2,
"beamLength": 3,
"beamRadius": 1,
"framesTillRespawn": 100,
"numResources": NUM_RESOURCES,
"endEpisodeOnFirstInteraction": True,
# Reset both players' inventories after each interaction.
"reset_winner_inventory": True,
"reset_loser_inventory": True,
# Both players get removed after each interaction.
"losingPlayerDies": True,
"winningPlayerDies": True,
# `freezeOnInteraction` is the number of frames to display the
# interaction result indicator, freeze, and delay delivering
# all results of interacting.
"freezeOnInteraction": 16,
}
},
{
"component": "ReadyToShootObservation",
"kwargs": {
"zapperComponent": "GameInteractionZapper",
}
},
{
"component": "InventoryObserver",
"kwargs": {
}
},
{
"component": "Taste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
# No resource is most tasty when mostTastyResourceClass == -1.
"mostTastyReward": 0.1,
}
},
{
"component": "InteractionTaste",
"kwargs": {
"mostTastyResourceClass": -1, # -1 indicates no preference.
"zeroDefaultInteractionReward": turn_off_default_reward,
"extraReward": 1.0,
}
},
{
"component": "AvatarMetricReporter",
"kwargs": {
"metrics": [
{
# Report the inventories of both players involved in
# an interaction on this frame formatted as
# (self inventory, partner inventory).
"name": "INTERACTION_INVENTORIES",
"type": "tensor.DoubleTensor",
"shape": (2, NUM_RESOURCES),
"component": "GameInteractionZapper",
"variable": "latest_interaction_inventories",
},
*the_matrix.get_cumulant_metric_configs(NUM_RESOURCES),
]
}
},
]
}
if _ENABLE_DEBUG_OBSERVATIONS:
avatar_object["components"].append({
"component": "LocationObserver",
"kwargs": {"objectIsAvatar": True, "alsoReportOrientation": True},
})
return avatar_object
def create_prefabs():
"""Returns a dictionary mapping names to template game objects."""
prefabs = {
"wall": WALL,
"spawn_point": SPAWN_POINT,
}
prefabs["resource_class1"] = create_resource_prefab(
1, shapes.BUTTON, {"*": RESOURCE1_COLOR_DATA[0],
"#": RESOURCE1_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class2"] = create_resource_prefab(
2, shapes.BUTTON, {"*": RESOURCE2_COLOR_DATA[0],
"#": RESOURCE2_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
prefabs["resource_class3"] = create_resource_prefab(
3, shapes.BUTTON, {"*": RESOURCE3_COLOR_DATA[0],
"#": RESOURCE3_COLOR_DATA[1],
"x": (0, 0, 0, 0)})
return prefabs
def get_all_source_sprite_names(num_players):
all_source_sprite_names = []
for player_idx in range(0, num_players):
# Lua is 1-indexed.
lua_index = player_idx + 1
all_source_sprite_names.append("Avatar" + str(lua_index))
return all_source_sprite_names
def create_avatar_objects(num_players, turn_off_default_reward: bool = False):
"""Returns list of avatar objects of length 'num_players'."""
all_source_sprite_names = get_all_source_sprite_names(num_players)
avatar_objects = []
for player_idx in range(0, num_players):
game_object = create_avatar_object(
player_idx,
all_source_sprite_names,
TARGET_SPRITE_SELF,
TARGET_SPRITE_OTHER,
turn_off_default_reward=turn_off_default_reward)
readiness_marker = the_matrix.create_ready_to_interact_marker(player_idx)
avatar_objects.append(game_object)
avatar_objects.append(readiness_marker)
return avatar_objects
def create_world_sprite_map(
num_players: int, target_sprite_other: Dict[str, Any]) -> Dict[str, str]:
all_source_sprite_names = get_all_source_sprite_names(num_players)
world_sprite_map = {}
for name in all_source_sprite_names:
world_sprite_map[name] = target_sprite_other["name"]
return world_sprite_map
def get_config():
"""Default configuration."""
config = config_dict.ConfigDict()
# Other parameters that are useful to override in training config files.
config.turn_off_default_reward = False
# Action set configuration.
config.action_set = ACTION_SET
# Observation format configuration.
config.individual_observation_names = [
"RGB",
"INVENTORY",
"READY_TO_SHOOT",
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES",
]
config.global_observation_names = [
"WORLD.RGB",
]
# The specs of the environment (from a single-agent perspective).
config.action_spec = specs.action(len(ACTION_SET))
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
"INVENTORY": specs.inventory(3),
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"INTERACTION_INVENTORIES": specs.interaction_inventories(3),
"WORLD.RGB": specs.rgb(120, 184),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
def build(
roles: Sequence[str],
config: config_dict.ConfigDict,
) -> Mapping[str, Any]:
"""Build substrate definition given roles."""
del config
num_players = len(roles)
# Build the rest of the substrate definition.
substrate_definition = dict(
levelName="the_matrix",
levelDirectory="meltingpot/lua/levels",
numPlayers=num_players,
maxEpisodeLengthFrames=1000, # The maximum possible number of frames.
spriteSize=8,
topology="BOUNDED", # Choose from ["BOUNDED", "TORUS"],
simulation={
"map": ASCII_MAP,
"gameObjects": create_avatar_objects(num_players=num_players),
"scene": create_scene(),
"prefabs": create_prefabs(),
"charPrefabMap": CHAR_PREFAB_MAP,
# worldSpriteMap is needed to make the global view used in videos be
# be informative in cases where individual avatar views have had
# sprites remapped to one another (example: self vs other mode).
"worldSpriteMap": create_world_sprite_map(num_players,
TARGET_SPRITE_OTHER),
}
)
return substrate_definition
|
meltingpot-main
|
meltingpot/configs/substrates/running_with_scissors_in_the_matrix__one_shot.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Collaborative Cooking: Asymmetric.
Example video: https://youtu.be/4AN3e1lFuMo
The recipe they must follow is for tomato soup:
1. Add three tomatoes to the cooking pot.
2. Wait for the soup to cook (status bar completion).
3. Bring a bowl to the pot and pour the soup from the pot into the bowl.
4. Deliver the bowl of soup at the goal location.
This substrate is a pure common interest game. All players share all rewards.
Players have a `5 x 5` observation window.
Map:
Asymmetric Advantages: A two-room layout with an agent in each. In the left
room, the tomato station is far away from the cooking pots while the delivery
location is close. In the right room, the tomato station is next to the cooking
pots while the delivery station is far. This presents an asymmetric advantage of
responsibilities for optimally creating and delivering soups.
"""
from meltingpot.configs.substrates import collaborative_cooking as base_config
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
# Asymmetric Advantages: A two-room layout with an agent in each room where it
# is possible for agents to work independently but more efficient if they
# specialize due to asymmetric advantages in delivery vs tomato loading.
ASCII_MAP = """
#########
O #T#O# T
# P C P #
# C #
###D#D###
"""
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.rgb(40, 40),
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(40, 72),
})
# The roles assigned to each player.
config.valid_roles = frozenset({"default"})
config.default_player_roles = ("default",) * 2
return config
|
meltingpot-main
|
meltingpot/configs/substrates/collaborative_cooking__asymmetric.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Territory: Inside Out.
Example video: https://youtu.be/LdbIjnHaisU
See _Territory: Open_ for the general description of the mechanics at play in
this substrate.
In this substrate, _Territory: Inside Out_, players start on the outside of
a randomly generated maze of resources. They must move from their starting
locations inward toward the center of the map to claim territory. In so doing
they will quickly encounter their coplayers who will be doing the same thing
from their own starting locations. In order to get high scores, agents must be
able to rapidly negotiate tacit agreements with one another concerning the
borders between their respective territories. Since the spatial arrangement of
the resources differs from episode to episode, so too does the negotiation
problem to be solved.
"""
from meltingpot.configs.substrates import territory as base_config
from meltingpot.utils.substrates import map_helpers
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
ASCII_MAP = """
F=====================T
|,,,,,,,,,,P,,,,,,,,,,|
|,P,,,,QQ,,,,,QQ,,,,P,|
|,,RRR,,,,RRR,,,,RRR,,|
|,,R,RAAAAR,RAAAAR,R,,|
|,,RRR,BB,RRR,BB,RRR,,|
|,,,A,,BB,,A,,BB,,A,,,|
|,Q,ABBRRBBABBRRBBA,Q,|
|,Q,ABBRRBBABBRRBBA,Q,|
|,,,A,,BB,,A,,BB,,A,,,|
|,,RRR,BB,RRR,BB,RRR,,|
|P,R,RAAAAR,RAAAAR,R,P|
|,,RRR,BB,RRR,BB,RRR,,|
|,,,A,,BB,,A,,BB,,A,,,|
|,Q,ABBRRBBABBRRBBA,Q,|
|,Q,ABBRRBBABBRRBBA,Q,|
|,,,A,,BB,,A,,BB,,A,,,|
|,,RRR,BB,RRR,BB,RRR,,|
|,,R,RAAAAR,RAAAAR,R,,|
|,,RRR,,,,RRR,,,,RRR,,|
|,P,,,,QQ,,,,,QQ,,,,P,|
|,,,,,,,,,,P,,,,,,,,,,|
L=====================J
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
resource_associated_prefabs = ["floor", "resource_texture", "resource",
"reward_indicator", "damage_indicator"]
resource = {"type": "all", "list": resource_associated_prefabs}
spawn_point_associated_prefabs = ["floor", "spawn_point"]
spawn_point = {"type": "all", "list": spawn_point_associated_prefabs}
CHAR_PREFAB_MAP = {
"P": spawn_point,
"Q": map_helpers.a_or_b_with_odds(spawn_point, "floor", odds=(1, 6)),
",": "floor",
"F": {"type": "all", "list": ["wall", "wall_highlight_nw"]},
"|": {"type": "all", "list": ["wall", "wall_highlight_e_w"]},
"=": {"type": "all", "list": ["wall", "wall_highlight_n_s"]},
"T": {"type": "all", "list": ["wall", "wall_highlight_ne"]},
"J": {"type": "all", "list": ["wall", "wall_highlight_se"]},
"L": {"type": "all", "list": ["wall", "wall_highlight_sw"]},
"R": resource,
"A": map_helpers.a_or_b_with_odds(resource, "floor", odds=(2, 1)),
"B": map_helpers.a_or_b_with_odds(resource, "floor", odds=(1, 3)),
}
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
config.layout.char_prefab_map = CHAR_PREFAB_MAP
config.layout.topology = "BOUNDED"
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(184, 184),
})
# The roles assigned to each player.
config.default_player_roles = ("default",) * 5
return config
|
meltingpot-main
|
meltingpot/configs/substrates/territory__inside_out.py
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Configuration for Territory: Rooms.
Example video: https://youtu.be/4URkGR9iv9k
See _Territory: Open_ for the general description of the mechanics at play in
this substrate.
In this substrate, _Territory: Rooms_, individuals start in segregated rooms
that strongly suggest a partition individuals could adhere to. They can break
down the walls of these regions and invade each other's "natural territory", but
the destroyed resources are lost forever. A peaceful partition is possible at
the start of the episode, and the policy to achieve it is easy to implement. But
if any agent gets too greedy and invades, it buys itself a chance of large
rewards, but also chances inflicting significant chaos and deadweight loss on
everyone if its actions spark wider conflict. The reason it can spiral out of
control is that once an agent's neighbor has left their natural territory then
it becomes rational to invade the space, leaving one's own territory undefended,
creating more opportunity for mischief by others.
"""
from meltingpot.configs.substrates import territory as base_config
from meltingpot.utils.substrates import specs
from ml_collections import config_dict
build = base_config.build
ASCII_MAP = """
JRRRRRLJRRRRRLJRRRRRL
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
R,,P,,RR,,P,,RR,,P,,R
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
TRRRRRFTRRRRRFTRRRRRF
JRRRRRLJRRRRRLJRRRRRL
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
R,,P,,RR,,P,,RR,,P,,R
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
TRRRRRFTRRRRRFTRRRRRF
JRRRRRLJRRRRRLJRRRRRL
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
R,,P,,RR,,P,,RR,,P,,R
R,,,,,RR,,,,,RR,,,,,R
R,,,,,RR,,,,,RR,,,,,R
TRRRRRFTRRRRRFTRRRRRF
"""
# `prefab` determines which prefab game object to use for each `char` in the
# ascii map.
resource_associated_prefabs = ["floor", "resource_texture", "resource",
"reward_indicator", "damage_indicator"]
resource = {"type": "all", "list": resource_associated_prefabs}
spawn_point_associated_prefabs = ["floor", "spawn_point"]
spawn_point = {"type": "all", "list": spawn_point_associated_prefabs}
CHAR_PREFAB_MAP = {
"P": spawn_point,
",": "floor",
"W": "wall",
"F": {"type": "all", "list": ["wall", "wall_highlight_nw"]},
"T": {"type": "all", "list": ["wall", "wall_highlight_ne"]},
"J": {"type": "all", "list": ["wall", "wall_highlight_se"]},
"L": {"type": "all", "list": ["wall", "wall_highlight_sw"]},
"R": resource,
}
def get_config():
"""Default configuration."""
config = base_config.get_config()
# Override the map layout settings.
config.layout = config_dict.ConfigDict()
config.layout.ascii_map = ASCII_MAP
config.layout.char_prefab_map = CHAR_PREFAB_MAP
config.layout.topology = "TORUS"
# The specs of the environment (from a single-agent perspective).
config.timestep_spec = specs.timestep({
"RGB": specs.OBSERVATION["RGB"],
"READY_TO_SHOOT": specs.OBSERVATION["READY_TO_SHOOT"],
# Debug only (do not use the following observations in policies).
"WORLD.RGB": specs.rgb(168, 168),
})
# The roles assigned to each player.
config.default_player_roles = ("default",) * 9
return config
|
meltingpot-main
|
meltingpot/configs/substrates/territory__rooms.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Training loop for the primary DetCon-B pretraining experiment."""
import time
from typing import Type
from absl import app
from absl import flags
from absl import logging
import chex
import jax
import ml_collections
import numpy as np
from detcon import detcon_b
from detcon import detcon_b_config
flags.DEFINE_string('worker_mode', 'train', 'The mode, train or eval')
flags.DEFINE_string('worker_tpu_driver', '', 'The tpu driver to use')
flags.DEFINE_integer('pretrain_epochs', 1000, 'Number of pre-training epochs')
flags.DEFINE_integer('batch_size', 4096, 'Total batch size')
flags.DEFINE_integer('log_tensors_interval', 60, 'Print stats every n seconds')
flags.DEFINE_string('dataset_directory', '/tmp/imagenet-fh-train',
'Local directory with generated FH-ImageNet dataset')
flags.DEFINE_bool('is_test', False, 'Run the sanity test (pretrain for 1 step)')
FLAGS = flags.FLAGS
Experiment = Type[detcon_b.PretrainExperiment]
def train_loop(experiment_class: Experiment, config: ml_collections.ConfigDict):
"""The main training loop.
Args:
experiment_class: the constructor for the experiment (either byol_experiment
or eval_experiment).
config: the experiment config.
"""
experiment = experiment_class(**config.experiment_kwargs, mode='train')
logging.info('Setup pre-training experiment class!')
rng = jax.random.PRNGKey(0)
step = 0
host_id = jax.host_id()
last_logging = time.time()
local_device_count = jax.local_device_count()
while step < config['training_steps']:
step_rng, rng = tuple(jax.random.split(rng))
# Broadcast the random seeds across the devices
step_rng_device = jax.random.split(step_rng, num=jax.device_count())
step_rng_device = step_rng_device[
host_id * local_device_count:(host_id + 1) * local_device_count]
step_device = np.broadcast_to(step, [local_device_count])
logging.info('Setup RNGs!')
# Perform a training step and get scalars to log.
scalars = experiment.step(global_step=step_device, rng=step_rng_device,
writer=None)
logging.info('Finished pre-training step!')
# Logging metrics
current_time = time.time()
if current_time - last_logging > FLAGS.log_tensors_interval:
logging.info('Step %d: %s', step, scalars)
last_logging = current_time
step += 1
logging.info('Step %d: %s', step, scalars)
def main(_):
if FLAGS.is_test:
fake_pmap = chex.fake_pmap()
fake_pmap.start()
if FLAGS.worker_tpu_driver:
jax.config.update('jax_xla_backend', 'tpu_driver')
jax.config.update('jax_backend_target', FLAGS.worker_tpu_driver)
logging.info('Backend: %s %r', FLAGS.worker_tpu_driver, jax.devices())
experiment_class = detcon_b.PretrainExperiment
config = detcon_b_config.get_config(FLAGS.pretrain_epochs, FLAGS.batch_size)
loader_kwargs = config['experiment_kwargs']['config']['data']['loader_kwargs']
loader_kwargs['dataset_directory'] = FLAGS.dataset_directory
if FLAGS.is_test:
config['experiment_kwargs']['config']['mock_out_train_dataset'] = True
config['training_steps'] = 1
config['log_train_data_interval'] = None
config['save_checkpoint_interval'] = None
config['experiment_kwargs']['config']['training']['max_steps'] = 1
config['experiment_kwargs']['config']['training']['batch_size'] = 4
train_loop(experiment_class, config)
if FLAGS.is_test:
fake_pmap.stop()
logging.info('Finished running training loop!')
if __name__ == '__main__':
app.run(main)
|
detcon-main
|
main_loop.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Common experiment components for pre-training."""
import abc
from typing import Any, Dict, Generator, Mapping, NamedTuple, Optional, Text, Tuple
from absl import logging
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import experiment
from jaxline import utils
import ml_collections
import numpy as np
import optax
from detcon.datasets import image_dataset
from detcon.datasets import imagenet_with_fh
from detcon.utils import helpers as byol_helpers
from detcon.utils import optimizers as lars_optimizer
from detcon.utils import schedules
# Type declarations.
LogsDict = Dict[Text, jnp.ndarray]
class ExperimentState(NamedTuple):
"""Byol's model and optimization parameters and state."""
online_params: hk.Params
target_params: hk.Params
online_state: hk.State
target_state: hk.State
opt_state: lars_optimizer.LarsState
class BaseExperiment(experiment.AbstractExperiment):
"""Common training and evaluation component definition."""
# Holds a map from object properties that will be checkpointed to their name
# within a checkpoint. Currently it is assume that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {'_exp_state': 'exp_state'}
def __init__(self, mode: Text, config: ml_collections.ConfigDict):
"""Constructs the experiment.
Args:
mode: A string, equivalent to FLAGS.mode when running normally.
config: Experiment configuration.
"""
super().__init__(mode)
self.mode = mode
self.dataset_adapter = image_dataset.ImageDataset(
**config.data.loader_kwargs)
dataset_directory = config.data.loader_kwargs.dataset_directory
if not config.mock_out_train_dataset:
imagenet_with_fh.check_train_dataset_directory(dataset_directory)
config.training.images_per_epoch = self.dataset_adapter.num_train_examples
self.config = config
# Checkpointed experiment state.
self._exp_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
# build the transformed ops
self.forward = hk.without_apply_rng(hk.transform_with_state(self._forward))
# training can handle multiple devices, thus the pmap
self.update_pmap = jax.pmap(self._update_fn, axis_name='i',
donate_argnums=(0))
# evaluation can only handle single device
self.eval_batch_jit = jax.jit(self._eval_batch)
@abc.abstractmethod
def _forward(
self,
inputs: image_dataset.Batch,
is_training: bool,
) -> Mapping[Text, jnp.ndarray]:
"""Forward application of the network.
Args:
inputs: A batch of data, i.e. a dictionary, with either two keys,
(`images` and `labels`) or three keys (`view1`, `view2`, `labels`).
is_training: Training or evaluating the model? When True, inputs must
contain keys `view1` and `view2`. When False, inputs must contain key
`images`.
Returns:
All outputs of the model, i.e. a dictionary for either the two views, or
the image.
"""
pass
@abc.abstractmethod
def _update_fn(
self,
exp_state: ExperimentState,
global_step: jnp.ndarray,
rng: jnp.ndarray,
inputs: image_dataset.Batch,
) -> Tuple[ExperimentState, LogsDict]:
"""Update online and target parameters.
Args:
exp_state: current experiment state.
global_step: current training step.
rng: current random number generator
inputs: inputs, containing two batches of crops from the same images,
view1 and view2 and labels
Returns:
Tuple containing the updated exp state after processing the inputs, and
various logs.
"""
pass
@abc.abstractmethod
def _make_initial_state(
self,
rng: jnp.ndarray,
dummy_input: image_dataset.Batch,
) -> ExperimentState:
"""ExperimentState initialization.
Args:
rng: random number generator used to initialize parameters. If working in
a multi device setup, this need to be a ShardedArray.
dummy_input: a dummy image, used to compute intermediate outputs shapes.
Returns:
Initial experiment state.
"""
pass
def lr_schedule(self, step: jnp.ndarray) -> jnp.ndarray:
"""Cosine schedule wrapper."""
batch_size = self.config.training.batch_size
if self.config.optimizer.scale_by_batch:
bs = batch_size
else:
bs = 256 # cancels out batch scaling
return schedules.learning_schedule(
step,
batch_size=bs,
total_steps=self.config.training.max_steps,
base_learning_rate=self.config.optimizer.base_learning_rate,
warmup_steps=self.config.optimizer.warmup_steps)
def _optimizer(self, learning_rate: float) -> optax.GradientTransformation:
"""Build optimizer from config."""
if self.config.optimizer.name == 'lars':
return lars_optimizer.lars(
learning_rate,
weight_decay_filter=lars_optimizer.exclude_bias_and_norm,
lars_adaptation_filter=lars_optimizer.exclude_bias_and_norm,
**self.config.optimizer.lars_kwargs)
elif self.config.optimizer.name == 'adam':
return optax.chain(
optax.scale_by_adam(**self.config.optimizer.adam_kwargs),
lars_optimizer.add_weight_decay(
self.config.optimizer.adam_weight_decay,
filter_fn=lars_optimizer.exclude_bias_and_norm),
optax.scale(-learning_rate))
def _classifier_loss(
self,
logits: jnp.ndarray,
labels: jnp.ndarray) -> Tuple[jnp.ndarray, LogsDict]:
"""Computes the classification loss and corresponding logs.
Classification loss (with gradient flows stopped from flowing into the
ResNet). This is used to provide an evaluation of the representation
quality during training.
Args:
logits: the classifier logits.
labels: the labels.
Returns:
The classifier loss, and a dict of logs.
"""
# adapted from nfnets code
def _one_hot(value, num_classes):
"""One-hot encoding potentially over a sequence of labels."""
y = jax.nn.one_hot(value, num_classes)
if self.config.data.loader_kwargs.dataset_name == 'jft':
y = jnp.sum(y, -2)
y = y / jnp.sum(y, -1, keepdims=True) # Average one-hots
return y
one_hot_labels = _one_hot(labels, self.dataset_adapter.num_classes)
classif_loss = byol_helpers.softmax_cross_entropy(logits=logits,
labels=one_hot_labels)
classif_loss = jnp.mean(classif_loss)
logs = dict(
classif_loss=classif_loss,
)
return classif_loss, logs
def step(self, *, global_step: jnp.ndarray, rng: jnp.ndarray,
writer: Optional[Any]) -> Mapping[Text, np.ndarray]:
"""See base class."""
if self._train_input is None:
self._initialize_train()
inputs = next(self._train_input)
self._exp_state, scalars = self.update_pmap(
self._exp_state,
global_step=global_step,
rng=rng,
inputs=inputs,
)
return utils.get_first(scalars)
def _initialize_train(self):
"""Initialize train.
This includes initializing the input pipeline and experiment state.
"""
self._train_input = utils.py_prefetch(self._build_train_input)
# Check we haven't already restored params
if self._exp_state is None:
logging.info(
'Initializing parameters rather than restoring from checkpoint.')
# initialize params and optimizer state
inputs = next(self._train_input)
init_exp = jax.pmap(self._make_initial_state, axis_name='i')
# Init uses the same RNG key on all hosts+devices to ensure everyone
# computes the same initial state and parameters.
init_rng = jax.random.PRNGKey(self.config.random_seed)
init_rng = utils.bcast_local_devices(init_rng)
self._exp_state = init_exp(rng=init_rng, dummy_input=inputs)
def _fake_data_generator(self, image_shape: Tuple[int, int, int, int]):
mask1 = np.random.uniform(low=0, high=7, size=image_shape + (1,))
mask2 = np.random.uniform(low=0, high=7, size=image_shape + (1,))
while True:
yield {
'view1': jnp.ones(image_shape + (3,)) * 0.5,
'view2': jnp.ones(image_shape + (3,)) * 0.3,
'fh_segmentations1': jnp.array(np.round(mask1), dtype=jnp.uint8),
'fh_segmentations2': jnp.array(np.round(mask2), dtype=jnp.uint8),
'labels': jnp.ones([image_shape[0], image_shape[1], 1],
dtype=jnp.int64),
}
def _build_train_input(self) -> Generator[image_dataset.Batch, None, None]:
"""See base class."""
num_devices = jax.device_count()
global_batch_size = self.config.training.batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
if self.config.mock_out_train_dataset:
img_config = self.config.data.loader_kwargs.preprocessing_config.pretrain
return self._fake_data_generator(
image_shape=(
jax.local_device_count(), per_device_batch_size,
img_config.output_image_size, img_config.output_image_size),
)
else:
return self.dataset_adapter.load(
image_dataset.Split.from_string(self.config.data.training_subset),
dataset_mode=image_dataset.DatasetMode.PRETRAIN,
batch_dims=[jax.local_device_count(), per_device_batch_size])
def _eval_batch(
self,
params: hk.Params,
state: hk.State,
batch: image_dataset.Batch,
) -> Mapping[Text, jnp.ndarray]:
"""Evaluates a batch.
Args:
params: Parameters of the model to evaluate. Typically the online
parameters.
state: State of the model to evaluate. Typically the online state.
batch: Batch of data to evaluate (must contain keys images and labels).
Returns:
Unreduced evaluation loss on the batch.
"""
batch = self.dataset_adapter.maybe_transpose_on_device(batch)
outputs, _ = self.forward.apply(params, state, batch, is_training=False)
logits = outputs['logits']
labels = hk.one_hot(batch['labels'], self.dataset_adapter.num_classes)
loss = byol_helpers.softmax_cross_entropy(logits, labels, reduction=None)
# NOTE: Returned values will be summed and finally divided by num_samples.
return {
'eval_loss': loss,
}
def _build_eval_input(self) -> Generator[image_dataset.Batch, None, None]:
"""See base class."""
split = image_dataset.Split.from_string(
self.config.data.evaluation_subset)
return self.dataset_adapter.load(
split,
dataset_mode=image_dataset.DatasetMode.EVAL,
batch_dims=[self.config.evaluation.batch_size])
def _eval_epoch(self):
"""Evaluates an epoch."""
num_samples = 0.
summed_scalars = None
params = utils.get_first(self._exp_state.online_params)
state = utils.get_first(self._exp_state.online_state)
for inputs in self._build_eval_input():
num_samples += inputs['labels'].shape[0]
scalars = self.eval_batch_jit(params, state, inputs)
# Accumulate the sum of scalars for each step.
scalars = jax.tree_map(lambda x: jnp.sum(x, axis=0), scalars)
if summed_scalars is None:
summed_scalars = scalars
else:
summed_scalars = jax.tree_multimap(jnp.add, summed_scalars, scalars)
mean_scalars = jax.tree_map(lambda x: x / num_samples, summed_scalars)
return mean_scalars
def evaluate(self, global_step, **unused_args):
"""Thin wrapper around _eval_epoch."""
global_step = np.array(utils.get_first(global_step))
scalars = jax.device_get(self._eval_epoch())
logging.info('[Step %d] Eval scalars: %s', global_step, scalars)
return scalars
|
detcon-main
|
pretrain_common.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""DetCon-B implementation using Jaxline."""
import sys
from typing import Any, Mapping, Text, Tuple
from absl import flags
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import platform
import ml_collections
import numpy as np
import optax
from detcon import pretrain_common
from detcon.datasets import image_dataset
from detcon.utils import augmentations
from detcon.utils import helpers as byol_helpers
from detcon.utils import losses
from detcon.utils import networks
from detcon.utils import schedules
def featurewise_std(x: jnp.ndarray) -> jnp.ndarray:
"""Computes the featurewise standard deviation."""
return jnp.mean(jnp.std(x, axis=0))
class PretrainExperiment(pretrain_common.BaseExperiment):
"""DetCon-B's training component definition."""
def __init__(self, mode: Text, config: ml_collections.ConfigDict):
"""Constructs the experiment.
Args:
mode: A string, equivalent to FLAGS.mode when running normally.
config: Experiment configuration.
"""
super().__init__(mode, config)
assert config.training_mode in ['self-supervised', 'supervised', 'both']
if mode == 'train':
self.forward = hk.transform_with_state(self._forward)
def create_binary_mask(
self,
batch_size,
num_pixels,
masks,
max_mask_id=256,
downsample=(1, 32, 32, 1)):
"""Generates binary masks from the Felzenszwalb masks.
From a FH mask of shape [batch_size, H,W] (values in range
[0,max_mask_id], produces corresponding (downsampled) binary masks of
shape [batch_size, max_mask_id, H*W/downsample].
Args:
batch_size: batch size of the masks
num_pixels: Number of points on the spatial grid
masks: Felzenszwalb masks
max_mask_id: # unique masks in Felzenszwalb segmentation
downsample: rate at which masks must be downsampled.
Returns:
binary_mask: Binary mask with specification above
"""
fh_mask_to_use = self.config.model.fh_mask_to_use
mask = masks[..., fh_mask_to_use:(fh_mask_to_use+1)]
mask_ids = jnp.arange(max_mask_id).reshape(1, 1, 1, max_mask_id)
binary_mask = jnp.equal(mask_ids, mask).astype('float32')
binary_mask = hk.avg_pool(binary_mask, downsample, downsample, 'VALID')
binary_mask = binary_mask.reshape(batch_size, num_pixels, max_mask_id)
binary_mask = jnp.argmax(binary_mask, axis=-1)
binary_mask = jnp.eye(max_mask_id)[binary_mask]
binary_mask = jnp.transpose(binary_mask, [0, 2, 1])
return binary_mask
def sample_masks(self, binary_mask, batch_size, n_random_vectors=16):
"""Samples which binary masks to use in the loss."""
mask_exists = jnp.greater(binary_mask.sum(-1), 1e-3)
sel_masks = mask_exists.astype('float32') + 0.00000000001
sel_masks = sel_masks / sel_masks.sum(1, keepdims=True)
sel_masks = jnp.log(sel_masks)
mask_ids = jax.random.categorical(
hk.next_rng_key(), sel_masks, axis=-1,
shape=tuple([n_random_vectors, batch_size]))
mask_ids = jnp.transpose(mask_ids, [1, 0])
smpl_masks = jnp.stack(
[binary_mask[b][mask_ids[b]] for b in range(batch_size)])
return smpl_masks, mask_ids
def run_detcon_b_forward_on_view(
self,
view_encoder: Any,
projector: Any,
predictor: Any,
classifier: Any,
is_training: bool,
images: jnp.ndarray,
masks: jnp.ndarray,
suffix: Text = '',
):
outputs = {}
images = self.dataset_adapter.normalize_images(images)
embedding_local = view_encoder(images, is_training=is_training)
embedding = jnp.mean(embedding_local, axis=[1, 2])
bs, emb_h, emb_w, emb_d = embedding_local.shape
emb_a = emb_h * emb_w
if masks is not None and self.config.training_mode != 'supervised':
binary_mask = self.create_binary_mask(bs, emb_a, masks)
smpl_masks, mask_ids = self.sample_masks(binary_mask, bs)
smpl_masks_area = smpl_masks.sum(axis=-1, keepdims=True)
smpl_masks = smpl_masks / jnp.maximum(smpl_masks_area, 1.)
embedding_local = embedding_local.reshape([bs, emb_a, emb_d])
smpl_embedding = jnp.matmul(smpl_masks, embedding_local)
proj_out = projector(smpl_embedding, is_training)
pred_out = predictor(proj_out, is_training)
outputs['projection' + suffix] = proj_out
outputs['prediction' + suffix] = pred_out
outputs['mask_ids' + suffix] = mask_ids
# Note the stop_gradient: label information is not leaked into the
# main network.
if self.config.training_mode == 'self-supervised':
embedding = jax.lax.stop_gradient(embedding)
classif_out = classifier(embedding)
outputs['logits' + suffix] = classif_out
return outputs
def _forward(
self,
inputs: image_dataset.Batch,
is_training: bool,
) -> Mapping[Text, jnp.ndarray]:
"""Forward application of byol's architecture.
Args:
inputs: A batch of data, i.e. a dictionary, with either two keys,
(`images` and `labels`) or three keys (`view1`, `view2`, `labels`).
is_training: Training or evaluating the model? When True, inputs must
contain keys `view1` and `view2`. When False, inputs must contain key
`images`.
Returns:
All outputs of the model, i.e. a dictionary with projection, prediction
and logits keys, for either the two views, or the image.
"""
mlp_kwargs = dict(
hidden_size=self.config.model.mlp_hidden_size,
bn_config=self.config.model.norm_config,
output_size=self.config.model.projection_size)
encoder = getattr(networks, self.config.model.encoder)
view_encoder = encoder(
num_classes=None, # Don't build the final linear layer
resnet_v2=self.config.model.encoder_use_v2,
bn_config=self.config.model.norm_config,
width_multiplier=self.config.model.encoder_width_multiplier,
final_mean_pool=False)
projector = networks.MLP(name='projector', **mlp_kwargs)
predictor = networks.MLP(name='predictor', **mlp_kwargs)
classifier = hk.Linear(
output_size=self.dataset_adapter.num_classes, name='classifier')
if is_training:
outputs_view1 = self.run_detcon_b_forward_on_view(
view_encoder, projector, predictor, classifier, is_training,
inputs['view1'], inputs['fh_segmentations1'], '_view1')
outputs_view2 = self.run_detcon_b_forward_on_view(
view_encoder, projector, predictor, classifier, is_training,
inputs['view2'], inputs['fh_segmentations2'], '_view2')
return {**outputs_view1, **outputs_view2}
else:
return self.run_detcon_b_forward_on_view(
view_encoder, projector, predictor, classifier, is_training,
inputs['images'], None, '')
def loss_fn(
self,
online_params: hk.Params,
target_params: hk.Params,
online_state: hk.State,
target_state: hk.Params,
rng: jnp.ndarray,
inputs: image_dataset.Batch,
) -> Tuple[jnp.ndarray, Tuple[Mapping[Text, hk.State],
pretrain_common.LogsDict]]:
"""Compute BYOL's loss function.
Args:
online_params: parameters of the online network (the loss is later
differentiated with respect to the online parameters).
target_params: parameters of the target network.
online_state: internal state of online network.
target_state: internal state of target network.
rng: random number generator state.
inputs: inputs, containing two batches of crops from the same images,
view1 and view2 and labels
Returns:
BYOL's loss, a mapping containing the online and target networks updated
states after processing inputs, and various logs.
"""
inputs = self.dataset_adapter.maybe_transpose_on_device(inputs)
inputs = augmentations.postprocess(inputs, rng)
online_network_out, online_state = self.forward.apply(
params=online_params,
state=online_state,
rng=rng,
inputs=inputs,
is_training=True)
target_network_out, target_state = self.forward.apply(
params=target_params,
state=target_state,
rng=rng,
inputs=inputs,
is_training=True)
# Representation loss
# The stop_gradient is not necessary as we explicitly take the gradient with
# respect to online parameters only in `optax.apply_updates`. We leave it to
# indicate that gradients are not backpropagated through the target network.
repr_loss = 0.0
if self.config.training_mode != 'supervised':
repr_loss = losses.byol_nce_detcon(
online_network_out['prediction_view1'],
online_network_out['prediction_view2'],
jax.lax.stop_gradient(target_network_out['projection_view1']),
jax.lax.stop_gradient(target_network_out['projection_view2']),
online_network_out['mask_ids_view1'],
online_network_out['mask_ids_view2'],
target_network_out['mask_ids_view1'],
target_network_out['mask_ids_view2'],
temperature=self.config.training.nce_loss_temperature)
classif_loss, logs = self._classifier_loss(
logits=online_network_out['logits_view1'], labels=inputs['labels'])
loss = repr_loss + classif_loss
if self.config.training_mode != 'supervised':
logs.update(
dict(
loss=loss,
repr_loss=repr_loss,
proj_mean=online_network_out['projection_view1'].mean(),
proj_std=featurewise_std(
online_network_out['projection_view1']),
normalized_proj_std=featurewise_std(
byol_helpers.l2_normalize(
online_network_out['projection_view1'], axis=-1)),
pred_mean=online_network_out['prediction_view1'].mean(),
pred_std=featurewise_std(
online_network_out['prediction_view1']),
normalized_pred_std=featurewise_std(
byol_helpers.l2_normalize(
online_network_out['prediction_view1'], axis=-1),)))
else:
logs.update(dict(loss=loss, repr_loss=repr_loss))
return loss, (dict(online_state=online_state,
target_state=target_state), logs)
def _update_fn(
self,
byol_state: pretrain_common.ExperimentState,
global_step: jnp.ndarray,
rng: jnp.ndarray,
inputs: image_dataset.Batch,
) -> Tuple[pretrain_common.ExperimentState, pretrain_common.LogsDict]:
"""Update online and target parameters.
Args:
byol_state: current BYOL state.
global_step: current training step.
rng: current random number generator
inputs: inputs, containing two batches of crops from the same images,
view1 and view2 and labels
Returns:
Tuple containing the updated Byol state after processing the inputs, and
various logs.
"""
online_params = byol_state.online_params
target_params = byol_state.target_params
online_state = byol_state.online_state
target_state = byol_state.target_state
opt_state = byol_state.opt_state
# update online network
grad_fn = jax.grad(self.loss_fn, argnums=0, has_aux=True)
grads, (net_states, logs) = grad_fn(online_params, target_params,
online_state, target_state, rng, inputs)
# cross-device grad and logs reductions
grads = jax.tree_map(lambda v: jax.lax.pmean(v, axis_name='i'), grads)
logs = jax.tree_multimap(lambda x: jax.lax.pmean(x, axis_name='i'), logs)
lr = self.lr_schedule(global_step)
updates, opt_state = self._optimizer(lr).update(grads, opt_state,
online_params)
online_params = optax.apply_updates(online_params, updates)
# update target network
tau = schedules.target_ema(
global_step,
base_ema=self.config.training.base_target_ema,
max_steps=self.config.training.max_steps)
target_params = jax.tree_multimap(lambda x, y: x + (1 - tau) * (y - x),
target_params, online_params)
logs['tau'] = tau
logs['lr'] = lr
n_params = 0
for key in online_params:
for l in online_params[key]:
n_params += np.prod(online_params[key][l].shape)
logs['n_params'] = n_params
return pretrain_common.ExperimentState(
online_params=online_params,
target_params=target_params,
online_state=net_states['online_state'],
target_state=net_states['target_state'],
opt_state=opt_state), logs
def _make_initial_state(
self,
rng: jnp.ndarray,
dummy_input: image_dataset.Batch,
) -> pretrain_common.ExperimentState:
"""BYOL's _ExperimentState initialization.
Args:
rng: random number generator used to initialize parameters. If working in
a multi device setup, this need to be a ShardedArray.
dummy_input: a dummy image, used to compute intermediate outputs shapes.
Returns:
Initial Byol state.
"""
rng_online, rng_target = jax.random.split(rng)
dummy_input = self.dataset_adapter.maybe_transpose_on_device(dummy_input)
# Online and target parameters are initialized using different rngs,
# in our experiments we did not notice a significant different with using
# the same rng for both.
online_params, online_state = self.forward.init(
rng_online,
dummy_input,
is_training=True,
)
target_params, target_state = self.forward.init(
rng_target,
dummy_input,
is_training=True,
)
opt_state = self._optimizer(0).init(online_params)
return pretrain_common.ExperimentState(
online_params=online_params,
target_params=target_params,
opt_state=opt_state,
online_state=online_state,
target_state=target_state,
)
if __name__ == '__main__':
flags.mark_flag_as_required('config')
platform.main(PretrainExperiment, sys.argv[1:])
|
detcon-main
|
detcon_b.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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"""Converts raw ImageNet data to TFRecords with Felzenzwalb segmentations.
The raw ImageNet data set is expected to reside in JPEG files located in the
following directory structure.
data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
...
where 'n01440764' is the unique synset label associated with
these images.
The training data set consists of 1000 sub-directories (i.e. labels)
each containing 1200 JPEG images for a total of 1.2M JPEG images.
The evaluation data set consists of 1000 sub-directories (i.e. labels)
each containing 50 JPEG images for a total of 50K JPEG images.
This TensorFlow script converts the training and evaluation data into
a sharded data set consisting of 1024 and 128 TFRecord files, respectively.
train_directory/train-00000-of-01024
train_directory/train-00001-of-01024
...
train_directory/train-00127-of-01024
and
validation_directory/validation-00000-of-00128
validation_directory/validation-00001-of-00128
...
validation_directory/validation-00127-of-00128
Each validation TFRecord file contains ~390 records. Each training TFREcord
file contains ~1250 records. Each record within the TFRecord file is a
serialized Example proto. The Example proto contains the following fields:
image/encoded: string containing JPEG encoded image in RGB colorspace
image/height: integer, image height in pixels
image/width: integer, image width in pixels
image/colorspace: string, specifying the colorspace, always 'RGB'
image/channels: integer, specifying the number of channels, always 3
image/format: string, specifying the format, always'JPEG'
image/filename: string containing the basename of the image file
e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG'
image/class/label: integer specifying the index in a classification layer.
The label ranges from [1, 1000] where 0 is not used.
image/class/synset: string specifying the unique ID of the label,
e.g. 'n01440764'
image/class/text: string specifying the human-readable version of the label
e.g. 'red fox, Vulpes vulpes'
Note that the length of xmin is identical to the length of xmax, ymin and ymax
for each example.
Sample command to run:
python generate_fh_masks_for_imagenet.py -- \
--validation_directory=/tmp/imagenet-val \
--output_directory=/tmp/imagenet-val-fh
"""
from datetime import datetime # pylint: disable=g-importing-member
import os
import random
import sys
import threading
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import skimage.segmentation
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
tf.app.flags.DEFINE_string('train_directory', None,
'Training data directory')
tf.app.flags.DEFINE_string('validation_directory', None,
'Validation data directory')
tf.app.flags.DEFINE_string('output_directory', None,
'Output data directory')
tf.app.flags.DEFINE_integer('train_shards', 2048,
'Number of shards in training TFRecord files.')
tf.app.flags.DEFINE_integer('validation_shards', 256,
'Number of shards in validation TFRecord files.')
tf.app.flags.DEFINE_integer('num_threads', 16,
'Number of threads to preprocess the images.')
tf.app.flags.DEFINE_string('fh_scales', '1000',
'Felzenszwalb segment scales, comma separated.')
tf.app.flags.DEFINE_string('fh_min_sizes', '1000',
'Felzenszwalb group sizes.')
# The labels file contains a list of valid labels are held in this file.
# Assumes that the file contains entries as such:
# n01440764
# n01443537
# n01484850
# where each line corresponds to a label expressed as a synset. We map
# each synset contained in the file to an integer (based on the alphabetical
# ordering). See below for details.
tf.app.flags.DEFINE_string('labels_file',
'imagenet_lsvrc_2015_synsets.txt',
'Labels file')
# This file containing mapping from synset to human-readable label.
# Assumes each line of the file looks like:
#
# n02119247 black fox
# n02119359 silver fox
# n02119477 red fox, Vulpes fulva
#
# where each line corresponds to a unique mapping. Note that each line is
# formatted as <synset>\t<human readable label>.
tf.app.flags.DEFINE_string('imagenet_metadata_file',
'imagenet_metadata.txt',
'ImageNet metadata file')
FLAGS = tf.app.flags.FLAGS
def _int64_feature(value):
"""Wrapper for inserting int64 features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _float_feature(value):
"""Wrapper for inserting float features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _convert_to_example(filename, image_buffer, fh_masks, label, synset, human,
height, width):
"""Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
fh_masks: the Felzenzwalb image segmentations corresponding to the image.
label: integer, identifier for the ground truth for the network
synset: string, unique WordNet ID specifying the label, e.g., 'n02323233'
human: string, human-readable label, e.g., 'red fox, Vulpes vulpes'
height: integer, image height in pixels
width: integer, image width in pixels
Returns:
Example proto
"""
colorspace = b'RGB'
channels = 3
image_format = b'JPEG'
base_filename = os.path.basename(filename)
bytes_fh_masks = fh_masks.reshape([-1]).tobytes()
example = tf.train.Example(features=tf.train.Features(feature={
'image/height': _int64_feature(height),
'image/width': _int64_feature(width),
'image/colorspace': _bytes_feature(colorspace),
'image/channels': _int64_feature(channels),
'image/class/label': _int64_feature(label),
'image/class/synset': _bytes_feature(bytes(synset, 'utf-8')),
'image/class/text': _bytes_feature(bytes(human, 'utf-8')),
'image/format': _bytes_feature(image_format),
'image/filename': _bytes_feature(bytes(base_filename, 'utf-8')),
'image/encoded': _bytes_feature(image_buffer),
'image/felzenszwalb_segmentations': _bytes_feature(bytes_fh_masks),
}))
return example
class ImageCoder(object):
"""Helper class that provides TensorFlow image coding utilities."""
def __init__(self):
# Create a single Session to run all image coding calls.
self._sess = tf.Session()
# Initializes function that converts PNG to JPEG data.
self._png_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_png(self._png_data, channels=3)
self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that converts CMYK JPEG data to RGB JPEG data.
self._cmyk_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_jpeg(self._cmyk_data, channels=0)
self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that decodes RGB JPEG data.
self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
def png_to_jpeg(self, image_data):
return self._sess.run(self._png_to_jpeg,
feed_dict={self._png_data: image_data})
def cmyk_to_rgb(self, image_data):
return self._sess.run(self._cmyk_to_rgb,
feed_dict={self._cmyk_data: image_data})
def decode_jpeg(self, image_data):
image = self._sess.run(self._decode_jpeg,
feed_dict={self._decode_jpeg_data: image_data})
assert len(image.shape) == 3
assert image.shape[2] == 3
return image
def _is_png(filename):
"""Determine if a file contains a PNG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a PNG.
"""
# File list from:
# https://groups.google.com/forum/embed/?place=forum/torch7#!topic/torch7/fOSTXHIESSU
return 'n02105855_2933.JPEG' in filename
def _is_cmyk(filename):
"""Determine if file contains a CMYK JPEG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a JPEG encoded with CMYK color space.
"""
# File list from:
# https://github.com/cytsai/ilsvrc-cmyk-image-list
cmyk_excluded = ['n01739381_1309.JPEG', 'n02077923_14822.JPEG',
'n02447366_23489.JPEG', 'n02492035_15739.JPEG',
'n02747177_10752.JPEG', 'n03018349_4028.JPEG',
'n03062245_4620.JPEG', 'n03347037_9675.JPEG',
'n03467068_12171.JPEG', 'n03529860_11437.JPEG',
'n03544143_17228.JPEG', 'n03633091_5218.JPEG',
'n03710637_5125.JPEG', 'n03961711_5286.JPEG',
'n04033995_2932.JPEG', 'n04258138_17003.JPEG',
'n04264628_27969.JPEG', 'n04336792_7448.JPEG',
'n04371774_5854.JPEG', 'n04596742_4225.JPEG',
'n07583066_647.JPEG', 'n13037406_4650.JPEG']
return filename.split('/')[-1] in cmyk_excluded
def compute_fh_segmentation(image_np, scale, min_size):
"""Compute FSZ segmentation on image and record stats."""
segmented_image = skimage.segmentation.felzenszwalb(
image_np, scale=scale, min_size=min_size)
segmented_image = segmented_image.astype(np.dtype('<u1'))
return segmented_image
def _process_image(filename, coder, fh_scales, fh_min_sizes):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
fh_scales: Felzenzwalb-Huttenlocher segmentation scales.
fh_min_sizes: Felzenzwalb-Huttenlocher min segment sizes.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, image width in pixels.
"""
# Read the image file.
image_data = tf.gfile.GFile(filename, 'rb').read()
# Clean the dirty data.
if _is_png(filename):
# 1 image is a PNG.
print('Converting PNG to JPEG for %s' % filename)
image_data = coder.png_to_jpeg(image_data)
elif _is_cmyk(filename):
# 22 JPEG images are in CMYK colorspace.
print('Converting CMYK to RGB for %s' % filename)
image_data = coder.cmyk_to_rgb(image_data)
# Decode the RGB JPEG.
image = coder.decode_jpeg(image_data)
fh_segmentations = []
for i, fh_scale in enumerate(fh_scales):
fh = compute_fh_segmentation(image, fh_scale, fh_min_sizes[i])
fh_segmentations.append(fh)
fh_segmentations = np.stack(fh_segmentations)
# Check that image converted to RGB
assert len(image.shape) == 3
height = image.shape[0]
width = image.shape[1]
assert image.shape[2] == 3
return image_data, fh_segmentations, height, width
def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
synsets, labels, humans, num_shards,
fh_scales, fh_min_sizes):
"""Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique batch to run index is within [0, len(ranges)).
ranges: list of pairs of integers specifying ranges of each batches to
analyze in parallel.
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
synsets: list of strings; each string is a unique WordNet ID
labels: list of integer; each integer identifies the ground truth
humans: list of strings; each string is a human-readable label
num_shards: integer number of shards for this data set.
fh_scales: Felzenzwalb-Huttenlocher segmentation scales.
fh_min_sizes: Felzenzwalb-Huttenlocher min segment sizes.
"""
# Each thread produces N shards where N = int(num_shards / num_threads).
# For instance, if num_shards = 128, and the num_threads = 2, then the first
# thread would produce shards [0, 64).
num_threads = len(ranges)
assert not num_shards % num_threads
num_shards_per_batch = int(num_shards / num_threads)
shard_ranges = np.linspace(ranges[thread_index][0],
ranges[thread_index][1],
num_shards_per_batch + 1).astype(int)
num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]
counter = 0
for s in xrange(num_shards_per_batch):
# Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
shard = thread_index * num_shards_per_batch + s
output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)
output_file = os.path.join(FLAGS.output_directory, output_filename)
writer = tf.python_io.TFRecordWriter(output_file)
shard_counter = 0
files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
for i in files_in_shard:
filename = filenames[i]
label = labels[i]
synset = synsets[i]
human = humans[i]
image_buffer, fh_masks, height, width = _process_image(
filename, coder, fh_scales, fh_min_sizes)
example = _convert_to_example(filename, image_buffer, fh_masks, label,
synset, human, height, width)
writer.write(example.SerializeToString())
shard_counter += 1
counter += 1
if not counter % 1000:
print('%s [thread %d]: Processed %d of %d images in thread batch.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
writer.close()
print('%s [thread %d]: Wrote %d images to %s' %
(datetime.now(), thread_index, shard_counter, output_file))
sys.stdout.flush()
shard_counter = 0
print('%s [thread %d]: Wrote %d images to %d shards.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
def _process_image_files(name, filenames, synsets, labels, humans, num_shards,
fh_scales, fh_min_sizes):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
synsets: list of strings; each string is a unique WordNet ID
labels: list of integer; each integer identifies the ground truth
humans: list of strings; each string is a human-readable label
num_shards: integer number of shards for this data set.
fh_scales: Felzenzwalb-Huttenlocher segmentation scales.
fh_min_sizes: Felzenzwalb-Huttenlocher min segment sizes.
"""
assert len(filenames) == len(synsets)
assert len(filenames) == len(labels)
assert len(filenames) == len(humans)
# Break all images into batches with a [ranges[i][0], ranges[i][1]].
spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int)
ranges = []
threads = []
for i in xrange(len(spacing) - 1):
ranges.append([spacing[i], spacing[i+1]])
# Launch a thread for each batch.
print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
sys.stdout.flush()
# Create a mechanism for monitoring when all threads are finished.
coord = tf.train.Coordinator()
# Create a generic TensorFlow-based utility for converting all image codings.
coder = ImageCoder()
threads = []
for thread_index in xrange(len(ranges)):
args = (coder, thread_index, ranges, name, filenames,
synsets, labels, humans, num_shards, fh_scales, fh_min_sizes)
t = threading.Thread(target=_process_image_files_batch, args=args)
t.start()
threads.append(t)
# Wait for all the threads to terminate.
coord.join(threads)
print('%s: Finished writing all %d images in data set.' %
(datetime.now(), len(filenames)))
sys.stdout.flush()
def _find_image_files(data_dir, labels_file):
"""Build a list of all images files and labels in the data set.
Args:
data_dir: string, path to the root directory of images.
Assumes that the ImageNet data set resides in JPEG files located in
the following directory structure.
data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
where 'n01440764' is the unique synset label associated with these images.
labels_file: string, path to the labels file.
The list of valid labels are held in this file. Assumes that the file
contains entries as such:
n01440764
n01443537
n01484850
where each line corresponds to a label expressed as a synset. We map
each synset contained in the file to an integer (based on the alphabetical
ordering) starting with the integer 1 corresponding to the synset
contained in the first line.
The reason we start the integer labels at 1 is to reserve label 0 as an
unused background class.
Returns:
filenames: list of strings; each string is a path to an image file.
synsets: list of strings; each string is a unique WordNet ID.
labels: list of integer; each integer identifies the ground truth.
"""
print('Determining list of input files and labels from %s.' % data_dir)
challenge_synsets = [
l.strip() for l in tf.gfile.GFile(labels_file, 'r').readlines()
]
labels = []
filenames = []
synsets = []
# Leave label index 0 empty as a background class.
label_index = 1
# Construct the list of JPEG files and labels.
for synset in challenge_synsets:
jpeg_file_path = '%s/%s/*.JPEG' % (data_dir, synset)
matching_files = tf.gfile.Glob(jpeg_file_path)
labels.extend([label_index] * len(matching_files))
synsets.extend([synset] * len(matching_files))
filenames.extend(matching_files)
if not label_index % 100:
print('Finished finding files in %d of %d classes.' % (
label_index, len(challenge_synsets)))
label_index += 1
# Shuffle the ordering of all image files in order to guarantee
# random ordering of the images with respect to label in the
# saved TFRecord files. Make the randomization repeatable.
shuffled_index = range(len(filenames))
random.seed(12345)
random.shuffle(list(range(len(shuffled_index))))
filenames = [filenames[i] for i in shuffled_index]
synsets = [synsets[i] for i in shuffled_index]
labels = [labels[i] for i in shuffled_index]
print('Found %d JPEG files across %d labels inside %s.' %
(len(filenames), len(challenge_synsets), data_dir))
return filenames, synsets, labels
def _find_human_readable_labels(synsets, synset_to_human):
"""Build a list of human-readable labels.
Args:
synsets: list of strings; each string is a unique WordNet ID.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red fox, Vulpes vulpes'
Returns:
List of human-readable strings corresponding to each synset.
"""
humans = []
for s in synsets:
assert s in synset_to_human, ('Failed to find: %s' % s)
humans.append(synset_to_human[s])
return humans
def _process_dataset(name, directory, num_shards, synset_to_human,
fh_scales, fh_min_sizes):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red fox, Vulpes vulpes'
fh_scales: Felzenzwalb-Huttenlocher segmentation scales.
fh_min_sizes: Felzenzwalb-Huttenlocher min segment sizes.
"""
filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file)
humans = _find_human_readable_labels(synsets, synset_to_human)
_process_image_files(name, filenames, synsets, labels,
humans, num_shards, fh_scales, fh_min_sizes)
def _build_synset_lookup(imagenet_metadata_file):
"""Build lookup for synset to human-readable label.
Args:
imagenet_metadata_file: string, path to file containing mapping from
synset to human-readable label.
Assumes each line of the file looks like:
n02119247 black fox
n02119359 silver fox
n02119477 red fox, Vulpes fulva
where each line corresponds to a unique mapping. Note that each line is
formatted as <synset><tab><human readable label>.
Returns:
Dictionary of synset to human labels, such as:
'n02119022' --> 'red fox, Vulpes vulpes'
"""
lines = tf.gfile.GFile(imagenet_metadata_file, 'r').readlines()
synset_to_human = {}
for l in lines:
if l:
parts = l.strip().split('\t')
assert len(parts) == 2
synset = parts[0]
human = parts[1]
synset_to_human[synset] = human
return synset_to_human
def main(unused_argv):
assert not FLAGS.train_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards')
assert not FLAGS.validation_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with '
'FLAGS.validation_shards')
print('Saving results to %s' % FLAGS.output_directory)
# Build a map from synset to human-readable label.
synset_to_human = _build_synset_lookup(FLAGS.imagenet_metadata_file)
fh_scales = [int(n) for n in FLAGS.fh_scales.split(',')]
fh_min_sizes = [int(n) for n in FLAGS.fh_min_sizes.split(',')]
assert len(fh_scales) == len(fh_min_sizes)
# Run it!
if FLAGS.train_directory is not None:
_process_dataset('train', FLAGS.train_directory, FLAGS.train_shards,
synset_to_human, fh_scales, fh_min_sizes)
if FLAGS.validation_directory is not None:
_process_dataset('validation', FLAGS.validation_directory,
FLAGS.validation_shards, synset_to_human,
fh_scales, fh_min_sizes)
if __name__ == '__main__':
tf.app.run()
|
detcon-main
|
generate_fh_masks_for_imagenet.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Config file for pre-training with the DetCon-B experiment."""
from jaxline import base_config
from ml_collections import config_dict
def get_config(num_epochs: int = 100, train_batch_size: int = 4096):
"""Return config object, containing all hyperparameters for training."""
config = base_config.get_base_config()
config.eval_modes = ()
dataset_name = 'imagenet2012:5.*.*'
evaluation_subset = 'test'
fh_mask_to_use = 0
train_images_per_epoch = 1281167
warmup_epochs = int(num_epochs // 100)
warmup_steps = (warmup_epochs * train_images_per_epoch) // train_batch_size
max_steps = (num_epochs * train_images_per_epoch) // train_batch_size
config.encoder_type = 'ResNet50'
model_config = dict(
mlp_hidden_size=4096,
projection_size=256,
encoder='ResNet50',
encoder_width_multiplier=1,
encoder_use_v2=False,
fh_mask_to_use=fh_mask_to_use,
norm_config={
'decay_rate': .9, # BN specific
'eps': 1e-5,
# Accumulate batchnorm statistics across devices.
# This should be equal to the `axis_name` argument passed
# to jax.pmap.
'cross_replica_axis': 'i', # BN specific
'create_scale': True,
'create_offset': True,
})
# Experiment config.
config.experiment_kwargs = config_dict.ConfigDict(
dict(
config=dict(
mock_out_train_dataset=False,
training_mode='self-supervised',
random_seed=0,
model=model_config,
optimizer=dict(
name='lars',
base_learning_rate=0.2,
scale_by_batch=True,
warmup_epochs=10,
warmup_steps=warmup_steps,
lars_kwargs={
'weight_decay': 1.5e-6,
'eta': 1e-3,
'momentum': .9,
}),
training=dict(
batch_size=train_batch_size,
images_per_epoch=train_images_per_epoch,
base_target_ema=.996,
max_steps=max_steps,
num_epochs=num_epochs,
nce_loss_temperature=0.1,
),
data=dict(
loader_kwargs=dict(
dataset_directory=None,
dataset_name=dataset_name,
enable_double_transpose=True,
allow_caching=False,
use_tfds=False,
preprocessing_config=dict(
pretrain=dict(
spatial_crop='random',
output_image_size=224,
random_flip_left_right=True,),
eval=dict(
spatial_crop='center',
output_image_size=224,
random_flip_left_right=True,),
),
),
training_subset='train',
evaluation_subset=evaluation_subset,
),
evaluation=dict(
batch_size=100,
),
),))
# Training loop config.
config.training_steps = max_steps
config.log_train_data_interval = 60
config.log_tensors_interval = 60
config.save_checkpoint_interval = 300
config.eval_specific_checkpoint_dir = ''
# Prevents accidentally setting keys that aren't recognized (e.g. in tests).
config.lock()
return config
|
detcon-main
|
detcon_b_config.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Wrapper for image datasets with typical pre-processing."""
from typing import Any, Mapping, Text, Tuple
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from detcon.datasets import dataset_adapter
from detcon.datasets import imagenet_with_fh
Split = dataset_adapter.Split
Batch = dataset_adapter.Batch
Split = dataset_adapter.Split
DatasetMode = dataset_adapter.DatasetMode
_DATASET_METADATA = {
'imagenet2012:5.*.*': {
'num_examples': {
Split.TRAIN: 1281167,
Split.VALID: 0,
Split.TEST: 50000,
},
'num_classes': 1000,
'color_stats': {
'mean_rgb': (0.485, 0.456, 0.406),
'std_rgb': (0.229, 0.224, 0.225)
}
},
'coco': {
'num_examples': {
Split.TRAIN: 118287,
Split.VALID: 5000,
Split.TEST: 20228,
},
'num_classes': 80,
'color_stats': {
'mean_rgb': (0.485, 0.456, 0.406),
'std_rgb': (0.229, 0.224, 0.225)
},
},
'jft': {
'num_examples': {
Split.TRAIN: 302982257,
Split.VALID: 641676,
Split.TEST: 990221,
},
'num_classes': 18291,
'color_stats': {
'mean_rgb': (0.485, 0.456, 0.406),
'std_rgb': (0.229, 0.224, 0.225)
},
}
}
_DATASET_METADATA['coco_fh'] = _DATASET_METADATA['coco']
class ImageDataset(dataset_adapter.ImageDatasetAdapter):
"""Adapter for a dataset."""
def __init__(self,
dataset_directory: Text,
dataset_name: Text,
enable_double_transpose: bool,
allow_caching: bool,
preprocessing_config: Mapping[Text, Mapping[Text, Any]],
use_tfds: bool):
assert dataset_name in _DATASET_METADATA
super().__init__(
dataset_directory=dataset_directory,
dataset_name=dataset_name,
enable_double_transpose=enable_double_transpose,
preprocessing_config=preprocessing_config,
allow_caching=allow_caching,
use_tfds=use_tfds)
self._color_stats = _DATASET_METADATA[self._dataset_name]['color_stats']
metadata = _DATASET_METADATA[self._dataset_name]
self._num_examples = metadata['num_examples']
self._use_fh = 'fh' in dataset_name or 'coco' not in dataset_name
def _to_tfds_split(self, split: Split) -> tfds.Split:
"""Returns the TFDS split appropriately sharded."""
return {
Split.TRAIN: tfds.Split.TRAIN,
Split.VALID: tfds.Split.VALIDATION,
Split.TEST: tfds.Split.TEST
}[split]
def num_examples(self, split: Split) -> int:
return self._num_examples[split]
@property
def num_classes(self) -> int:
return _DATASET_METADATA[self._dataset_name]['num_classes']
def _shard(self,
split: Split,
shard_index: int,
num_shards: int) -> Tuple[int, int]:
"""Returns [start, end) for the given shard index."""
assert shard_index < num_shards
arange = np.arange(self.num_examples(split))
shard_range = np.array_split(arange, num_shards)[shard_index]
start, end = shard_range[0], (shard_range[-1] + 1)
return start, end
def normalize_images(self, images: jnp.ndarray) -> jnp.ndarray:
if self._dataset_name.lower().startswith('imagenet'):
mean_rgb = self._color_stats['mean_rgb']
stddev_rgb = self._color_stats['std_rgb']
normed_images = images - jnp.array(mean_rgb).reshape((1, 1, 1, 3))
stddev = jnp.array(stddev_rgb).reshape((1, 1, 1, 3))
normed_images = normed_images / stddev
else:
normed_images = images
return normed_images
def _load(self, split: Split) -> tf.data.Dataset:
"""Loads the given split of the dataset."""
if self._dataset_name.lower().startswith('imagenet'):
if self._use_tfds:
start, end = self._shard(split, jax.process_index(),
jax.process_count())
tfds_split = tfds.core.ReadInstruction(
self._to_tfds_split(split), from_=start, to=end, unit='abs')
ds = tfds.load(
self._dataset_name,
split=tfds_split,
decoders={'image': tfds.decode.SkipDecoding()})
else:
ds = imagenet_with_fh.load_dataset(
self._dataset_directory, split,
jax.process_index(), jax.process_count())
else:
raise ValueError
return ds
|
detcon-main
|
datasets/image_dataset.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""ImageNet dataset with typical pre-processing."""
import abc
import enum
from typing import Any, Generator, Mapping, Sequence
from absl import logging
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from detcon.utils import tf_image_ops
Batch = Mapping[str, np.ndarray]
JaxBatch = Mapping[str, jnp.ndarray]
TFBatch = Mapping[str, tf.Tensor]
class DatasetMode(enum.Enum):
"""Loading modes for the dataset."""
PRETRAIN = 1 # Generates two augmented views (random crop + augmentations).
LINEAR_TRAIN = 2 # Generates a single random crop.
EVAL = 3 # Generates a single center crop.
SEGMENT = 4 # Generates a single random crop with accompanying masks
class Split(enum.Enum):
"""Imagenet dataset split."""
TRAIN = 1
VALID = 2
TEST = 3
@classmethod
def from_string(cls, name: str) -> 'Split':
return {
'TRAIN': Split.TRAIN,
'VALID': Split.VALID,
'VALIDATION': Split.VALID,
'TEST': Split.TEST
}[name.upper()]
class DatasetAdapter(metaclass=abc.ABCMeta):
"""Adapter for a dataset."""
def __init__(self,
dataset_directory: str,
dataset_name: str,
enable_double_transpose: bool,
allow_caching: bool,
preprocessing_config: Mapping[str, Mapping[str, Any]],
use_tfds: bool):
self._dataset_directory = dataset_directory
self._dataset_name = dataset_name
self._preprocessing_config = preprocessing_config
self._use_double_transpose = (
enable_double_transpose and jax.local_devices()[0].platform == 'tpu')
self._allow_caching = allow_caching
self._use_tfds = use_tfds
if not self._use_tfds:
assert not self._allow_caching
self._use_fh = False
@abc.abstractmethod
def num_examples(self, split: Split) -> int:
"""Returns the number of examples for a given split."""
@abc.abstractproperty
def num_classes(self) -> int:
"""Returns the number of classes, used for the classifier."""
@property
def num_train_examples(self) -> int:
return self.num_examples(Split.TRAIN)
def normalize_images(self, images: jnp.ndarray) -> jnp.ndarray:
return images
@abc.abstractmethod
def _transpose_for_h2d(self, batch: TFBatch) -> TFBatch:
"""Transposes images for a batch of data."""
# We use the double-transpose-trick to improve performance for TPUs. Note
# that this (typically) requires a matching HWCN->NHWC transpose in your
# model code. The compiler cannot make this optimization for us since our
# data pipeline and model are compiled separately.
def load(
self,
split: Split,
*,
dataset_mode: DatasetMode,
batch_dims: Sequence[int]) -> Generator[Batch, None, None]:
"""A generator that returns Batches.
Args:
split: The split to load.
dataset_mode: How to preprocess the data.
batch_dims: The number of batch dimensions.
Yields:
Batches containing keys:
- (view1, view2, labels, masks) if preprocess_mode is PRETRAIN;
- (images, labels) if preprocess_mode is EVAL or LINEAR_TRAIN;
- (images, labels, masks) if preprocess_mode is SEGMENT.
"""
if (dataset_mode is DatasetMode.EVAL and
self.num_examples(split) % np.prod(batch_dims) != 0):
raise ValueError(f'Test/valid must be divisible by {np.prod(batch_dims)}')
ds = self._wrap(self._load(split), dataset_mode, batch_dims)
logging.info('Constructed dataset:')
logging.info(ds)
yield from tfds.as_numpy(ds)
@abc.abstractmethod
def _load(self, split: Split) -> tf.data.Dataset:
"""Returns a TF dataset for the correct split."""
@abc.abstractmethod
def _preprocess_pretrain(self, example: TFBatch) -> TFBatch:
pass
@abc.abstractmethod
def _preprocess_linear_train(self, example: TFBatch) -> TFBatch:
pass
@abc.abstractmethod
def _preprocess_segment(self, example: TFBatch) -> TFBatch:
pass
@abc.abstractmethod
def _preprocess_eval(self, example: TFBatch) -> TFBatch:
pass
def _wrap(
self,
ds: tf.data.Dataset,
dataset_mode: DatasetMode,
batch_dims: Sequence[int]) -> tf.data.Dataset:
"""Wraps a TF dataset with the correct preprocessing."""
total_batch_size = np.prod(batch_dims)
options = tf.data.Options()
options.experimental_threading.private_threadpool_size = 48
options.experimental_threading.max_intra_op_parallelism = 1
ds = ds.with_options(options)
if dataset_mode is not DatasetMode.EVAL:
options.experimental_deterministic = False
if jax.process_count() > 1 and self._allow_caching:
# Only cache if we are reading a subset of the dataset.
ds = ds.cache()
ds = ds.repeat()
ds = ds.shuffle(buffer_size=10 * total_batch_size, seed=0)
if dataset_mode is DatasetMode.PRETRAIN:
ds = ds.map(
self._preprocess_pretrain,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
elif dataset_mode is DatasetMode.LINEAR_TRAIN:
ds = ds.map(
self._preprocess_linear_train,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
elif dataset_mode is DatasetMode.SEGMENT:
ds = ds.map(
self._preprocess_segment,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
else:
ds = ds.map(
self._preprocess_eval,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
for i, batch_size in enumerate(reversed(batch_dims)):
ds = ds.batch(batch_size)
if i == 0 and self._use_double_transpose:
ds = ds.map(self._transpose_for_h2d)
ds = ds.prefetch(tf.data.experimental.AUTOTUNE)
return ds
@abc.abstractmethod
def maybe_transpose_on_device(self, batch: JaxBatch) -> JaxBatch:
"""Transpose images for TPU training.."""
pass
def _tf_transpose_helper(
self, batch: TFBatch, transpose_order: Sequence[int]) -> TFBatch:
new_batch = dict(batch)
if 'images' in batch:
new_batch['images'] = tf.transpose(batch['images'], transpose_order)
else:
new_batch['view1'] = tf.transpose(batch['view1'], transpose_order)
new_batch['view2'] = tf.transpose(batch['view2'], transpose_order)
return new_batch
def _jax_transpose_helper(
self, batch: JaxBatch, transpose_order: Sequence[int]) -> JaxBatch:
new_batch = dict(batch)
if 'images' in batch:
new_batch['images'] = jnp.transpose(batch['images'], transpose_order)
else:
new_batch['view1'] = jnp.transpose(batch['view1'], transpose_order)
new_batch['view2'] = jnp.transpose(batch['view2'], transpose_order)
return new_batch
class ImageDatasetAdapter(DatasetAdapter):
"""Adapter for a dataset containing single images."""
def _transpose_for_h2d(self, batch: TFBatch) -> TFBatch:
"""Transposes images for a batch of data."""
# NHWC -> HWCN
return self._tf_transpose_helper(batch, transpose_order=(1, 2, 3, 0))
def _get_segmentations(self, example: TFBatch) -> TFBatch:
"""Load segmentations from example."""
image_segmentations = {}
if self._use_fh:
image_bytes = example['image']
# Required because some images in COCO are PNGs
is_jpeg = tf.equal(tf.strings.substr(image_bytes, 0, 4),
b'\xff\xd8\xff\xe0')
image_shape = tf.cond(
is_jpeg,
true_fn=lambda: tf.image.extract_jpeg_shape(image_bytes),
false_fn=lambda: tf.shape( # pylint: disable=g-long-lambda
tf.image.decode_image(image_bytes, channels=3)))
n_fh_masks = 1
fh_shape = tf.concat([[n_fh_masks], image_shape[:2]], axis=0)
fh_masks = example['felzenszwalb_segmentations']
fh_masks = tf.reshape(fh_masks, fh_shape)
fh_masks = tf.transpose(fh_masks, perm=(1, 2, 0))
fh_masks.set_shape([None, None, n_fh_masks])
image_segmentations['fh'] = fh_masks
if 'groundtruth_instance_masks' in example:
max_gt_masks = 16
gt_masks = example['groundtruth_instance_masks']
gt_masks = tf_image_ops.clip_or_pad_to_fixed_size(
gt_masks, max_gt_masks, 0)
gt_masks = tf.transpose(gt_masks, [1, 2, 0]) # [H, W, n], n = #masks
image_segmentations['gt'] = gt_masks
return image_segmentations
def _preprocess_pretrain(self, example: TFBatch) -> TFBatch:
pretrain_config = self._preprocessing_config['pretrain']
label = tf.cast(example['label'], tf.int32)
if not self._use_tfds:
image_segmentations = self._get_segmentations(example)
view1, masks1 = tf_image_ops.preprocess_image(
example['image'], image_segmentations, **pretrain_config)
view2, masks2 = tf_image_ops.preprocess_image(
example['image'], image_segmentations, **pretrain_config)
pretrain_example = {'view1': view1, 'view2': view2, 'labels': label}
for name, mask in masks1.items():
pretrain_example[name + '_segmentations1'] = mask
for name, mask in masks2.items():
pretrain_example[name + '_segmentations2'] = mask
return pretrain_example
def _preprocess_segment(self, example: TFBatch) -> TFBatch:
pretrain_config = self._preprocessing_config['linear_train']
label = tf.cast(example['label'], tf.int32)
if not self._use_tfds:
image_segmentations = self._get_segmentations(example)
else:
image_segmentations = None
image, masks = tf_image_ops.preprocess_image(
example['image'], image_segmentations, **pretrain_config)
pretrain_example = {'images': image, 'labels': label}
for name, mask in masks.items():
pretrain_example[name] = mask
return pretrain_example
def _preprocess_linear_train(self, example: TFBatch) -> TFBatch:
preprocess_config = self._preprocessing_config['linear_train']
image, _ = tf_image_ops.preprocess_image(
image_bytes=example['image'],
image_segmentation=None,
**preprocess_config)
label = tf.cast(example['label'], tf.int32)
return {'images': image, 'labels': label}
def _preprocess_eval(self, example: TFBatch) -> TFBatch:
preprocess_config = self._preprocessing_config['eval']
image, _ = tf_image_ops.preprocess_image(
image_bytes=example['image'],
image_segmentation=None,
**preprocess_config)
label = tf.cast(example['label'], tf.int32)
return {'images': image, 'labels': label}
def maybe_transpose_on_device(self, batch: JaxBatch) -> JaxBatch:
"""Transpose images for TPU training.."""
if not self._use_double_transpose:
return batch
# HWCN -> NHWC
return self._jax_transpose_helper(batch, transpose_order=(3, 0, 1, 2))
|
detcon-main
|
datasets/dataset_adapter.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""ImageNet with associated Felzenzwalb-Huttenlocher masks for each image."""
import os
import numpy as np
import tensorflow.compat.v2 as tf
from detcon.datasets import dataset_adapter
def _parse_example_proto(value):
"""Parse an Imagenet record from value."""
keys_to_features = {
"image/encoded":
tf.io.FixedLenFeature((), tf.string, default_value=""),
"image/class/label":
tf.io.FixedLenFeature([], dtype=tf.int64, default_value=-1),
"image/felzenszwalb_segmentations":
tf.io.VarLenFeature(tf.string),
}
parsed = tf.io.parse_single_example(value, keys_to_features)
fs_segmentation = parsed["image/felzenszwalb_segmentations"]
fs_segmentation = tf.sparse.to_dense(fs_segmentation, default_value="")
fs_segmentation = tf.io.decode_raw(fs_segmentation, tf.uint8)
return {
"image": parsed["image/encoded"],
# ImageNet labels start at 1 but we want to start at 0.
"label": tf.cast(parsed["image/class/label"], tf.int64) - 1,
"felzenszwalb_segmentations": fs_segmentation,
}
def check_train_dataset_directory(dataset_directory):
basename_glob_expression = "train-*-of-02048"
paths = tf.io.gfile.glob(
os.path.join(dataset_directory, basename_glob_expression))
assert len(paths) >= 2048, ("Could not find 2048 TFRecord shards in data"
"directory.")
def load_dataset(data_dir, split, shard_index=0, num_shards=1):
"""Load dataset that reads from ImageNet-FH TFRecords."""
assert shard_index < num_shards
if split == dataset_adapter.Split.TRAIN:
shard_range = np.array_split(np.arange(2048), num_shards)[shard_index]
start, end = shard_range[0], (shard_range[-1] + 1)
files = [f"train-{i:05}-of-02048" for i in range(start, end)]
paths = [os.path.join(data_dir, file) for file in files]
elif split == dataset_adapter.Split.TEST:
basename_glob_expression = "validation-*-of-00256"
paths = tf.io.gfile.glob(
os.path.join(data_dir, basename_glob_expression))
else:
raise ValueError(f"No such split exists: {split}.")
assert paths, os.path.join(data_dir, basename_glob_expression)
ds = tf.data.Dataset.from_tensor_slices(paths)
ds = ds.interleave(
tf.data.TFRecordDataset,
cycle_length=tf.data.experimental.AUTOTUNE,
block_length=1,
num_parallel_calls=tf.data.experimental.AUTOTUNE,
)
ds = ds.map(
_parse_example_proto,
num_parallel_calls=tf.data.experimental.AUTOTUNE,
)
ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
options = tf.data.Options()
options.experimental_optimization.parallel_batch = True
options.experimental_optimization.map_parallelization = True
options.experimental_deterministic = False
ds = ds.with_options(options)
return ds
|
detcon-main
|
datasets/imagenet_with_fh.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""ImageNet dataset with typical pre-processing."""
from typing import Optional
import tensorflow.compat.v2 as tf
def is_jpeg(image_bytes):
return tf.equal(tf.strings.substr(image_bytes, 0, 4), b'\xff\xd8\xff\xe0')
decode_crop_jpeg = tf.io.decode_and_crop_jpeg
def decode_crop_nonjpeg(image_bytes, crop_window):
return tf.image.crop_to_bounding_box(
tf.io.decode_image(image_bytes, channels=3), crop_window[0],
crop_window[1], crop_window[2], crop_window[3])
def clip_or_pad_to_fixed_size(input_tensor, size, constant_values=0):
"""Pads data to a fixed length at the first dimension.
Args:
input_tensor: `Tensor` with any dimension.
size: `int` number for the first dimension of output Tensor.
constant_values: `int` value assigned to the paddings.
Returns:
`Tensor` with the first dimension padded to `size`.
"""
input_shape = input_tensor.get_shape().as_list()
padding_shape = []
# Computes the padding length on the first dimension, clip input tensor if it
# is longer than `size`.
input_length = tf.shape(input_tensor)[0]
input_length = tf.clip_by_value(input_length, 0, size)
input_tensor = input_tensor[:input_length]
padding_length = tf.maximum(0, size - input_length)
padding_shape.append(padding_length)
# Copies shapes of the rest of input shape dimensions.
for i in range(1, len(input_shape)):
padding_shape.append(tf.shape(input_tensor)[i])
# Pads input tensor to the fixed first dimension.
paddings = tf.cast(constant_values * tf.ones(padding_shape),
input_tensor.dtype)
padded_tensor = tf.concat([input_tensor, paddings], axis=0)
output_shape = input_shape
output_shape[0] = size
padded_tensor.set_shape(output_shape)
return padded_tensor
def preprocess_image(
image_bytes: tf.Tensor,
image_segmentation: tf.Tensor,
spatial_crop: str,
output_image_size: int,
random_flip_left_right: bool,
) -> tf.Tensor:
"""Returns processed and resized images and segmentation (if not None)."""
if spatial_crop == 'random':
crop_window = get_random_crop_window(image_bytes)
# Random horizontal flipping is optionally done in augmentations.preprocess.
elif spatial_crop == 'center':
crop_window = get_center_crop_window(image_bytes,
output_image_size=output_image_size)
else:
raise ValueError(f'Unknown spatial crop mode: {spatial_crop}')
image = tf.cond(
is_jpeg(image_bytes),
true_fn=lambda: decode_crop_jpeg(image_bytes, crop_window, channels=3),
false_fn=lambda: decode_crop_nonjpeg(image_bytes, crop_window)
)
output_segmentation = {}
if image_segmentation is not None:
for name, mask in image_segmentation.items():
output_segmentation[name] = tf.image.crop_to_bounding_box(
mask, crop_window[0], crop_window[1], crop_window[2], crop_window[3])
if random_flip_left_right:
flip_sample = tf.random.uniform([], minval=0, maxval=1, dtype=tf.float32)
flip = tf.less(flip_sample, 0.5)
image = tf.cond(flip,
lambda: tf.image.flip_left_right(image),
lambda: image)
# pylint: disable=undefined-loop-variable
for name, mask in output_segmentation.items():
output_segmentation[name] = tf.cond(
flip, lambda: tf.image.flip_left_right(mask), lambda: mask)
# pylint: enable=undefined-loop-variable
assert image.dtype == tf.uint8
image = tf.image.resize(
image, [output_image_size, output_image_size],
tf.image.ResizeMethod.BICUBIC)
# Clamp overshoots outside the range [0.0, 255.0] caused by interpolation
image = tf.clip_by_value(image / 255., 0., 1.)
for name, mask in output_segmentation.items():
output_segmentation[name] = tf.image.resize(
mask, [output_image_size, output_image_size],
tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return image, output_segmentation
def get_random_crop_window(image_bytes: tf.Tensor) -> tf.Tensor:
"""Makes a random crop."""
img_size = tf.cond(
is_jpeg(image_bytes),
true_fn=lambda: tf.image.extract_jpeg_shape(image_bytes),
false_fn=lambda: tf.shape(tf.image.decode_image(image_bytes, channels=3)))
area = tf.cast(img_size[1] * img_size[0], tf.float32)
target_area = tf.random.uniform([], 0.08, 1.0, dtype=tf.float32) * area
log_ratio = (tf.math.log(3 / 4), tf.math.log(4 / 3))
aspect_ratio = tf.math.exp(
tf.random.uniform([], *log_ratio, dtype=tf.float32))
w = tf.cast(tf.round(tf.sqrt(target_area * aspect_ratio)), tf.int32)
h = tf.cast(tf.round(tf.sqrt(target_area / aspect_ratio)), tf.int32)
w = tf.minimum(w, img_size[1])
h = tf.minimum(h, img_size[0])
offset_w = tf.random.uniform((),
minval=0,
maxval=img_size[1] - w + 1,
dtype=tf.int32)
offset_h = tf.random.uniform((),
minval=0,
maxval=img_size[0] - h + 1,
dtype=tf.int32)
crop_window = tf.stack([offset_h, offset_w, h, w])
return crop_window
def extract_nonjpeg_shape(image_bytes):
return tf.shape(tf.image.decode_image(image_bytes, channels=3))
def get_center_crop_window(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
output_image_size: int = 224,
) -> tf.Tensor:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
jpeg_shape = tf.cond(
is_jpeg(image_bytes),
true_fn=lambda: tf.image.extract_jpeg_shape(image_bytes),
false_fn=lambda: extract_nonjpeg_shape(image_bytes))
image_height = jpeg_shape[0]
image_width = jpeg_shape[1]
padded_center_crop_size = tf.cast(
((output_image_size / (output_image_size + 32)) *
tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32)
offset_height = ((image_height - padded_center_crop_size) + 1) // 2
offset_width = ((image_width - padded_center_crop_size) + 1) // 2
crop_window = tf.stack([
offset_height, offset_width, padded_center_crop_size,
padded_center_crop_size
])
return crop_window
|
detcon-main
|
utils/tf_image_ops.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Implementation of LARS Optimizer with optax."""
from typing import Any, Callable, List, NamedTuple, Optional, Tuple
import jax
import jax.numpy as jnp
import optax
import tree as nest
# A filter function takes a path and a value as input and outputs True for
# variable to apply update and False not to apply the update
FilterFn = Callable[[Tuple[Any], jnp.ndarray], jnp.ndarray]
def exclude_bias_and_norm(path: Tuple[Any], val: jnp.ndarray) -> jnp.ndarray:
"""Filter to exclude biaises and normalizations weights."""
del val
if path[-1] == "b" or "norm" in path[-2]:
return False
return True
def _partial_update(updates: optax.Updates,
new_updates: optax.Updates,
params: optax.Params,
filter_fn: Optional[FilterFn] = None) -> optax.Updates:
"""Returns new_update for params which filter_fn is True else updates."""
if filter_fn is None:
return new_updates
wrapped_filter_fn = lambda x, y: jnp.array(filter_fn(x, y))
params_to_filter = nest.map_structure_with_path(wrapped_filter_fn, params)
def _update_fn(g: jnp.ndarray, t: jnp.ndarray, m: jnp.ndarray) -> jnp.ndarray:
m = m.astype(g.dtype)
return g * (1. - m) + t * m
return jax.tree_multimap(_update_fn, updates, new_updates, params_to_filter)
class ScaleByLarsState(NamedTuple):
mu: jnp.ndarray
def scale_by_lars(
momentum: float = 0.9,
eta: float = 0.001,
filter_fn: Optional[FilterFn] = None) -> optax.GradientTransformation:
"""Rescales updates according to the LARS algorithm.
Does not include weight decay.
References:
[You et al, 2017](https://arxiv.org/abs/1708.03888)
Args:
momentum: momentum coeficient.
eta: LARS coefficient.
filter_fn: an optional filter function.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params: optax.Params) -> ScaleByLarsState:
mu = jax.tree_multimap(jnp.zeros_like, params) # momentum
return ScaleByLarsState(mu=mu)
def update_fn(updates: optax.Updates, state: ScaleByLarsState,
params: optax.Params) -> Tuple[optax.Updates, ScaleByLarsState]:
def lars_adaptation(
update: jnp.ndarray,
param: jnp.ndarray,
) -> jnp.ndarray:
param_norm = jnp.linalg.norm(param)
update_norm = jnp.linalg.norm(update)
return update * jnp.where(
param_norm > 0.,
jnp.where(update_norm > 0,
(eta * param_norm / update_norm), 1.0), 1.0)
adapted_updates = jax.tree_multimap(lars_adaptation, updates, params)
adapted_updates = _partial_update(updates, adapted_updates, params,
filter_fn)
mu = jax.tree_multimap(lambda g, t: momentum * g + t,
state.mu, adapted_updates)
return mu, ScaleByLarsState(mu=mu)
return optax.GradientTransformation(init_fn, update_fn)
class AddWeightDecayState(NamedTuple):
"""Stateless transformation."""
def add_weight_decay(
weight_decay: float,
filter_fn: Optional[FilterFn] = None) -> optax.GradientTransformation:
"""Adds a weight decay to the update.
Args:
weight_decay: weight_decay coeficient.
filter_fn: an optional filter function.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_) -> AddWeightDecayState:
return AddWeightDecayState()
def update_fn(
updates: optax.Updates,
state: AddWeightDecayState,
params: optax.Params,
) -> Tuple[optax.Updates, AddWeightDecayState]:
new_updates = jax.tree_multimap(lambda g, p: g + weight_decay * p, updates,
params)
new_updates = _partial_update(updates, new_updates, params, filter_fn)
return new_updates, state
return optax.GradientTransformation(init_fn, update_fn)
LarsState = List # Type for the lars optimizer
def lars(
learning_rate: float,
weight_decay: float = 0.,
momentum: float = 0.9,
eta: float = 0.001,
weight_decay_filter: Optional[FilterFn] = None,
lars_adaptation_filter: Optional[FilterFn] = None,
) -> optax.GradientTransformation:
"""Creates lars optimizer with weight decay.
References:
[You et al, 2017](https://arxiv.org/abs/1708.03888)
Args:
learning_rate: learning rate coefficient.
weight_decay: weight decay coefficient.
momentum: momentum coefficient.
eta: LARS coefficient.
weight_decay_filter: optional filter function to only apply the weight
decay on a subset of parameters. The filter function takes as input the
parameter path (as a tuple) and its associated update, and return a True
for params to apply the weight decay and False for params to not apply
the weight decay. When weight_decay_filter is set to None, the weight
decay is not applied to the bias, i.e. when the variable name is 'b', and
the weight decay is not applied to nornalization params, i.e. the
panultimate path contains 'norm'.
lars_adaptation_filter: similar to weight decay filter but for lars
adaptation
Returns:
An optax.GradientTransformation, i.e. a (init_fn, update_fn) tuple.
"""
if weight_decay_filter is None:
weight_decay_filter = lambda *_: True
if lars_adaptation_filter is None:
lars_adaptation_filter = lambda *_: True
return optax.chain(
add_weight_decay(
weight_decay=weight_decay, filter_fn=weight_decay_filter),
scale_by_lars(
momentum=momentum, eta=eta, filter_fn=lars_adaptation_filter),
optax.scale(-learning_rate),
)
|
detcon-main
|
utils/optimizers.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Networks used in BYOL."""
from typing import Any, Mapping, Optional, Sequence, Text
import haiku as hk
import jax
import jax.numpy as jnp
class MLP(hk.Module):
"""One hidden layer perceptron, with normalization."""
def __init__(
self,
name: Text,
hidden_size: int,
output_size: int,
bn_config: Mapping[Text, Any],
):
super().__init__(name=name)
self._hidden_size = hidden_size
self._output_size = output_size
self._bn_config = bn_config
def __call__(self, inputs: jnp.ndarray, is_training: bool) -> jnp.ndarray:
out = hk.Linear(output_size=self._hidden_size, with_bias=True)(inputs)
out = hk.BatchNorm(**self._bn_config)(out, is_training=is_training)
out = jax.nn.relu(out)
out = hk.Linear(output_size=self._output_size, with_bias=False)(out)
return out
def check_length(length, value, name):
if len(value) != length:
raise ValueError(f'`{name}` must be of length 4 not {len(value)}')
class ResNetTorso(hk.Module):
"""ResNet model."""
def __init__(
self,
blocks_per_group: Sequence[int],
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
bottleneck: bool = True,
channels_per_group: Sequence[int] = (256, 512, 1024, 2048),
use_projection: Sequence[bool] = (True, True, True, True),
width_multiplier: int = 1,
final_mean_pool: bool = True,
return_pyramid: bool = False,
name: Optional[str] = None,
):
"""Constructs a ResNet model.
Args:
blocks_per_group: A sequence of length 4 that indicates the number of
blocks created in each group.
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of three elements, `decay_rate`, `eps`, and
`cross_replica_axis`, to be passed on to the `BatchNorm` layers. By
default the `decay_rate` is `0.9` and `eps` is `1e-5`, and the axis is
`None`.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults to
False.
bottleneck: Whether the block should bottleneck or not. Defaults to True.
channels_per_group: A sequence of length 4 that indicates the number
of channels used for each block in each group.
use_projection: A sequence of length 4 that indicates whether each
residual block should use projection.
width_multiplier: An integer multiplying the number of channels per group.
final_mean_pool: Whether to mean pool at the end.
return_pyramid: Whether to return intermediate block activations.
name: Name of the module.
"""
super().__init__(name=name)
self.resnet_v2 = resnet_v2
self.return_pyramid = return_pyramid
self.final_mean_pool = final_mean_pool
bn_config = dict(bn_config or {})
bn_config.setdefault('decay_rate', 0.9)
bn_config.setdefault('eps', 1e-5)
bn_config.setdefault('create_scale', True)
bn_config.setdefault('create_offset', True)
# Number of blocks in each group for ResNet.
check_length(4, blocks_per_group, 'blocks_per_group')
check_length(4, channels_per_group, 'channels_per_group')
self.initial_conv = hk.Conv2D(
output_channels=64 * width_multiplier,
kernel_shape=7,
stride=2,
with_bias=False,
padding='SAME',
name='initial_conv')
if not self.resnet_v2:
self.initial_batchnorm = hk.BatchNorm(name='initial_batchnorm',
**bn_config)
self.block_groups = []
strides = (1, 2, 2, 2)
for i in range(4):
self.block_groups.append(
hk.nets.ResNet.BlockGroup(
channels=width_multiplier * channels_per_group[i],
num_blocks=blocks_per_group[i],
stride=strides[i],
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=bottleneck,
use_projection=use_projection[i],
name='block_group_%d' % (i)))
if self.resnet_v2:
self.final_batchnorm = hk.BatchNorm(name='final_batchnorm', **bn_config)
self.logits = hk.Linear(num_classes, w_init=jnp.zeros, name='logits')
def __call__(self, inputs, is_training, test_local_stats=False):
out = inputs
out = self.initial_conv(out)
if not self.resnet_v2:
out = self.initial_batchnorm(out, is_training, test_local_stats)
out = jax.nn.relu(out)
out = hk.max_pool(out,
window_shape=(1, 3, 3, 1),
strides=(1, 2, 2, 1),
padding='SAME')
pyramid = {}
for b, block_group in enumerate(self.block_groups):
out = block_group(out, is_training, test_local_stats)
pyramid[b+2] = out
if self.return_pyramid:
return pyramid
else:
if self.resnet_v2:
out = self.final_batchnorm(out, is_training, test_local_stats)
out = jax.nn.relu(out)
if self.final_mean_pool:
out = jnp.mean(out, axis=[1, 2])
return out
class TinyResNet(ResNetTorso):
"""Tiny resnet for local runs and tests."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(blocks_per_group=(1, 1, 1, 1),
channels_per_group=(8, 8, 8, 8),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
width_multiplier=width_multiplier,
name=name)
class ResNet18(ResNetTorso):
"""ResNet18."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(blocks_per_group=(2, 2, 2, 2),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
channels_per_group=(64, 128, 256, 512),
width_multiplier=width_multiplier,
name=name)
class ResNet34(ResNetTorso):
"""ResNet34."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
name: Name of the module.
"""
super().__init__(blocks_per_group=(3, 4, 6, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=False,
channels_per_group=(64, 128, 256, 512),
width_multiplier=width_multiplier,
name=name)
class ResNet50(ResNetTorso):
"""ResNet50."""
def __init__(self,
num_classes: Optional[int] = None,
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
final_mean_pool: bool = True,
return_pyramid: bool = False,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
final_mean_pool: Whether to mean pool at the end.
return_pyramid: Whether to return intermediate block activations.
name: Name of the module.
"""
super().__init__(blocks_per_group=(3, 4, 6, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
final_mean_pool=final_mean_pool,
return_pyramid=return_pyramid,
name=name)
class ResNet101(ResNetTorso):
"""ResNet101."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
final_mean_pool: bool = True,
return_pyramid: bool = False,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
final_mean_pool: Whether to mean pool at the end.
return_pyramid: Whether to return intermediate block activations.
name: Name of the module.
"""
super().__init__(blocks_per_group=(3, 4, 23, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
final_mean_pool=final_mean_pool,
return_pyramid=return_pyramid,
name=name)
class ResNet152(ResNetTorso):
"""ResNet152."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
final_mean_pool: bool = True,
return_pyramid: bool = False,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
final_mean_pool: Whether to mean pool at the end.
return_pyramid: Whether to return intermediate block activations.
name: Name of the module.
"""
super().__init__(blocks_per_group=(3, 8, 36, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
final_mean_pool=final_mean_pool,
return_pyramid=return_pyramid,
name=name)
class ResNet200(ResNetTorso):
"""ResNet200."""
def __init__(self,
num_classes: Optional[int],
bn_config: Optional[Mapping[str, float]] = None,
resnet_v2: bool = False,
width_multiplier: int = 1,
final_mean_pool: bool = True,
return_pyramid: bool = False,
name: Optional[str] = None):
"""Constructs a ResNet model.
Args:
num_classes: The number of classes to classify the inputs into.
bn_config: A dictionary of two elements, `decay_rate` and `eps` to be
passed on to the `BatchNorm` layers.
resnet_v2: Whether to use the v1 or v2 ResNet implementation. Defaults
to False.
width_multiplier: An integer multiplying the number of channels per group.
final_mean_pool: Whether to mean pool at the end.
return_pyramid: Whether to return intermediate block activations.
name: Name of the module.
"""
super().__init__(blocks_per_group=(3, 24, 36, 3),
num_classes=num_classes,
bn_config=bn_config,
resnet_v2=resnet_v2,
bottleneck=True,
width_multiplier=width_multiplier,
final_mean_pool=final_mean_pool,
return_pyramid=return_pyramid,
name=name)
|
detcon-main
|
utils/networks.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""DetCon/BYOL losses."""
import haiku as hk
import jax
import jax.numpy as jnp
from detcon.utils import helpers
def manual_cross_entropy(labels, logits, weight):
ce = - weight * jnp.sum(labels * jax.nn.log_softmax(logits), axis=-1)
return jnp.mean(ce)
def byol_nce_detcon(pred1, pred2, target1, target2,
pind1, pind2, tind1, tind2,
temperature=0.1, use_replicator_loss=True,
local_negatives=True):
"""Compute the NCE scores from pairs of predictions and targets.
This implements the batched form of the loss described in
Section 3.1, Equation 3 in https://arxiv.org/pdf/2103.10957.pdf.
Args:
pred1 (jnp.array): the prediction from first view.
pred2 (jnp.array): the prediction from second view.
target1 (jnp.array): the projection from first view.
target2 (jnp.array): the projection from second view.
pind1 (jnp.array): mask indices for first view's prediction.
pind2 (jnp.array): mask indices for second view's prediction.
tind1 (jnp.array): mask indices for first view's projection.
tind2 (jnp.array): mask indices for second view's projection.
temperature (float): the temperature to use for the NCE loss.
use_replicator_loss (bool): use cross-replica samples.
local_negatives (bool): whether to include local negatives
Returns:
A single scalar loss for the XT-NCE objective.
"""
batch_size = pred1.shape[0]
num_rois = pred1.shape[1]
feature_dim = pred1.shape[-1]
infinity_proxy = 1e9 # Used for masks to proxy a very large number.
def make_same_obj(ind_0, ind_1):
same_obj = jnp.equal(ind_0.reshape([batch_size, num_rois, 1]),
ind_1.reshape([batch_size, 1, num_rois]))
return jnp.expand_dims(same_obj.astype("float32"), axis=2)
same_obj_aa = make_same_obj(pind1, tind1)
same_obj_ab = make_same_obj(pind1, tind2)
same_obj_ba = make_same_obj(pind2, tind1)
same_obj_bb = make_same_obj(pind2, tind2)
# L2 normalize the tensors to use for the cosine-similarity
pred1 = helpers.l2_normalize(pred1, axis=-1)
pred2 = helpers.l2_normalize(pred2, axis=-1)
target1 = helpers.l2_normalize(target1, axis=-1)
target2 = helpers.l2_normalize(target2, axis=-1)
if jax.device_count() > 1 and use_replicator_loss:
# Grab tensor across replicas and expand first dimension
target1_large = jax.lax.all_gather(target1, axis_name="i")
target2_large = jax.lax.all_gather(target2, axis_name="i")
# Fold into batch dimension
target1_large = target1_large.reshape(-1, num_rois, feature_dim)
target2_large = target2_large.reshape(-1, num_rois, feature_dim)
# Create the labels by using the current replica ID and offsetting.
replica_id = jax.lax.axis_index("i")
labels_idx = jnp.arange(batch_size) + replica_id * batch_size
labels_idx = labels_idx.astype(jnp.int32)
enlarged_batch_size = target1_large.shape[0]
labels_local = hk.one_hot(labels_idx, enlarged_batch_size)
labels_ext = hk.one_hot(labels_idx, enlarged_batch_size * 2)
else:
target1_large = target1
target2_large = target2
labels_local = hk.one_hot(jnp.arange(batch_size), batch_size)
labels_ext = hk.one_hot(jnp.arange(batch_size), batch_size * 2)
labels_local = jnp.expand_dims(jnp.expand_dims(labels_local, axis=2), axis=1)
labels_ext = jnp.expand_dims(jnp.expand_dims(labels_ext, axis=2), axis=1)
# Do our matmuls and mask out appropriately.
logits_aa = jnp.einsum("abk,uvk->abuv", pred1, target1_large) / temperature
logits_bb = jnp.einsum("abk,uvk->abuv", pred2, target2_large) / temperature
logits_ab = jnp.einsum("abk,uvk->abuv", pred1, target2_large) / temperature
logits_ba = jnp.einsum("abk,uvk->abuv", pred2, target1_large) / temperature
labels_aa = labels_local * same_obj_aa
labels_ab = labels_local * same_obj_ab
labels_ba = labels_local * same_obj_ba
labels_bb = labels_local * same_obj_bb
logits_aa = logits_aa - infinity_proxy * labels_local * same_obj_aa
logits_bb = logits_bb - infinity_proxy * labels_local * same_obj_bb
labels_aa = 0. * labels_aa
labels_bb = 0. * labels_bb
if not local_negatives:
logits_aa = logits_aa - infinity_proxy * labels_local * (1 - same_obj_aa)
logits_ab = logits_ab - infinity_proxy * labels_local * (1 - same_obj_ab)
logits_ba = logits_ba - infinity_proxy * labels_local * (1 - same_obj_ba)
logits_bb = logits_bb - infinity_proxy * labels_local * (1 - same_obj_bb)
labels_abaa = jnp.concatenate([labels_ab, labels_aa], axis=2)
labels_babb = jnp.concatenate([labels_ba, labels_bb], axis=2)
labels_0 = jnp.reshape(labels_abaa, [batch_size, num_rois, -1])
labels_1 = jnp.reshape(labels_babb, [batch_size, num_rois, -1])
num_positives_0 = jnp.sum(labels_0, axis=-1, keepdims=True)
num_positives_1 = jnp.sum(labels_1, axis=-1, keepdims=True)
labels_0 = labels_0 / jnp.maximum(num_positives_0, 1)
labels_1 = labels_1 / jnp.maximum(num_positives_1, 1)
obj_area_0 = jnp.sum(make_same_obj(pind1, pind1), axis=[2, 3])
obj_area_1 = jnp.sum(make_same_obj(pind2, pind2), axis=[2, 3])
weights_0 = jnp.greater(num_positives_0[..., 0], 1e-3).astype("float32")
weights_0 = weights_0 / obj_area_0
weights_1 = jnp.greater(num_positives_1[..., 0], 1e-3).astype("float32")
weights_1 = weights_1 / obj_area_1
logits_abaa = jnp.concatenate([logits_ab, logits_aa], axis=2)
logits_babb = jnp.concatenate([logits_ba, logits_bb], axis=2)
logits_abaa = jnp.reshape(logits_abaa, [batch_size, num_rois, -1])
logits_babb = jnp.reshape(logits_babb, [batch_size, num_rois, -1])
loss_a = manual_cross_entropy(labels_0, logits_abaa, weights_0)
loss_b = manual_cross_entropy(labels_1, logits_babb, weights_1)
loss = loss_a + loss_b
return loss
|
detcon-main
|
utils/losses.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Utility functions."""
from typing import Optional, Text
from absl import logging
import jax
import jax.numpy as jnp
def topk_accuracy(
logits: jnp.ndarray,
labels: jnp.ndarray,
topk: int,
ignore_label_above: Optional[int] = None,
) -> jnp.ndarray:
"""Top-num_codes accuracy."""
assert len(labels.shape) == 1, 'topk expects 1d int labels.'
assert len(logits.shape) == 2, 'topk expects 2d logits.'
if ignore_label_above is not None:
logits = logits[labels < ignore_label_above, :]
labels = labels[labels < ignore_label_above]
prds = jnp.argsort(logits, axis=1)[:, ::-1]
prds = prds[:, :topk]
total = jnp.any(prds == jnp.tile(labels[:, jnp.newaxis], [1, topk]), axis=1)
return total
def softmax_cross_entropy(
logits: jnp.ndarray,
labels: jnp.ndarray,
reduction: Optional[Text] = 'mean',
) -> jnp.ndarray:
"""Computes softmax cross entropy given logits and one-hot class labels.
Args:
logits: Logit output values.
labels: Ground truth one-hot-encoded labels.
reduction: Type of reduction to apply to loss.
Returns:
Loss value. If `reduction` is `none`, this has the same shape as `labels`;
otherwise, it is scalar.
Raises:
ValueError: If the type of `reduction` is unsupported.
"""
loss = -jnp.sum(labels * jax.nn.log_softmax(logits), axis=-1)
if reduction == 'sum':
return jnp.sum(loss)
elif reduction == 'mean':
return jnp.mean(loss)
elif reduction == 'none' or reduction is None:
return loss
else:
raise ValueError(f'Incorrect reduction mode {reduction}')
def l2_normalize(
x: jnp.ndarray,
axis: Optional[int] = None,
epsilon: float = 1e-12,
) -> jnp.ndarray:
"""l2 normalize a tensor on an axis with numerical stability."""
square_sum = jnp.sum(jnp.square(x), axis=axis, keepdims=True)
x_inv_norm = jax.lax.rsqrt(jnp.maximum(square_sum, epsilon))
return x * x_inv_norm
def l2_weight_regularizer(params):
"""Helper to do lasso on weights.
Args:
params: the entire param set.
Returns:
Scalar of the l2 norm of the weights.
"""
l2_norm = 0.
for mod_name, mod_params in params.items():
if 'norm' not in mod_name:
for param_k, param_v in mod_params.items():
if param_k != 'b' not in param_k: # Filter out biases
l2_norm += jnp.sum(jnp.square(param_v))
else:
logging.warning('Excluding %s/%s from optimizer weight decay!',
mod_name, param_k)
else:
logging.warning('Excluding %s from optimizer weight decay!', mod_name)
return 0.5 * l2_norm
def regression_loss(x: jnp.ndarray, y: jnp.ndarray) -> jnp.ndarray:
"""Byol's regression loss. This is a simple cosine similarity."""
normed_x, normed_y = l2_normalize(x, axis=-1), l2_normalize(y, axis=-1)
return jnp.sum((normed_x - normed_y)**2, axis=-1)
def bcast_local_devices(value):
"""Broadcasts an object to all local devices."""
devices = jax.local_devices()
def _replicate(x):
"""Replicate an object on each device."""
x = jnp.array(x)
return jax.device_put_sharded(len(devices) * [x], devices)
return jax.tree_util.tree_map(_replicate, value)
def get_first(xs):
"""Gets values from the first device."""
return jax.tree_map(lambda x: x[0], xs)
|
detcon-main
|
utils/helpers.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Data preprocessing and augmentations."""
import functools
from typing import Any, Mapping, Text
import dm_pix as pix
import jax
import jax.numpy as jnp
# typing
JaxBatch = Mapping[Text, jnp.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
hue=0.1,
# Probability of applying color jittering
color_jitter_prob=0.8,
# Probability of converting to grayscale
to_grayscale_prob=0.2,
# Shuffle the order of color transforms
shuffle=True),
gaussian_blur=dict(
apply_prob=1.0,
# Kernel size ~ image_size / blur_divider
blur_divider=10.,
# Kernel distribution
sigma_min=0.1,
sigma_max=2.0),
solarize=dict(apply_prob=0.0, threshold=0.5),
),
view2=dict(
random_flip=False,
color_transform=dict(
apply_prob=1.0,
brightness=0.4,
contrast=0.4,
saturation=0.2,
hue=0.1,
color_jitter_prob=0.8,
to_grayscale_prob=0.2,
shuffle=True),
gaussian_blur=dict(
apply_prob=0.1, blur_divider=10., sigma_min=0.1, sigma_max=2.0),
solarize=dict(apply_prob=0.2, threshold=0.5),
))
def postprocess(inputs: JaxBatch, rng: jnp.ndarray):
"""Apply the image augmentations to crops in inputs (view1 and view2)."""
def _postprocess_image(
images: jnp.ndarray,
rng: jnp.ndarray,
presets: ConfigDict,
) -> JaxBatch:
"""Applies augmentations in post-processing.
Args:
images: an NHWC tensor (with C=3), with float values in [0, 1].
rng: a single PRNGKey.
presets: a dict of presets for the augmentations.
Returns:
A batch of augmented images with shape NHWC, with keys view1, view2
and labels.
"""
flip_rng, color_rng, blur_rng, solarize_rng = jax.random.split(rng, 4)
out = images
if presets['random_flip']:
out = random_flip(out, flip_rng)
if presets['color_transform']['apply_prob'] > 0:
out = color_transform(out, color_rng, **presets['color_transform'])
if presets['gaussian_blur']['apply_prob'] > 0:
out = gaussian_blur(out, blur_rng, **presets['gaussian_blur'])
if presets['solarize']['apply_prob'] > 0:
out = solarize(out, solarize_rng, **presets['solarize'])
out = jnp.clip(out, 0., 1.)
return jax.lax.stop_gradient(out)
rng1, rng2 = jax.random.split(rng, num=2)
view1 = _postprocess_image(inputs['view1'], rng1, augment_config['view1'])
view2 = _postprocess_image(inputs['view2'], rng2, augment_config['view2'])
outputs = dict(view1=view1, view2=view2, labels=inputs['labels'])
for k in ['fh_segmentations1', 'fh_segmentations2',
'gt_segmentations1', 'gt_segmentations2']:
if k in inputs:
outputs[k] = inputs[k]
return outputs
def _maybe_apply(apply_fn, inputs, rng, apply_prob):
should_apply = jax.random.uniform(rng, shape=()) <= apply_prob
return jax.lax.cond(should_apply, inputs, apply_fn, inputs, lambda x: x)
def _random_gaussian_blur(image, rng, kernel_size, padding, sigma_min,
sigma_max, apply_prob):
"""Applies a random gaussian blur."""
apply_rng, transform_rng = jax.random.split(rng)
def _apply(image):
sigma_rng, = jax.random.split(transform_rng, 1)
sigma = jax.random.uniform(
sigma_rng,
shape=(),
minval=sigma_min,
maxval=sigma_max,
dtype=jnp.float32)
return pix.gaussian_blur(image, sigma, kernel_size, padding=padding)
return _maybe_apply(_apply, image, apply_rng, apply_prob)
def _color_transform_single_image(image, rng, brightness, contrast, saturation,
hue, to_grayscale_prob, color_jitter_prob,
apply_prob, shuffle):
"""Applies color jittering to a single image."""
apply_rng, transform_rng = jax.random.split(rng)
perm_rng, b_rng, c_rng, s_rng, h_rng, cj_rng, gs_rng = jax.random.split(
transform_rng, 7)
# Whether the transform should be applied at all.
should_apply = jax.random.uniform(apply_rng, shape=()) <= apply_prob
# Whether to apply grayscale transform.
should_apply_gs = jax.random.uniform(gs_rng, shape=()) <= to_grayscale_prob
# Whether to apply color jittering.
should_apply_color = jax.random.uniform(cj_rng, shape=()) <= color_jitter_prob
# Decorator to conditionally apply fn based on an index.
def _make_cond(fn, idx):
def identity_fn(unused_rng, x):
return x
def cond_fn(args, i):
def clip(args):
return jax.tree_map(lambda arg: jnp.clip(arg, 0., 1.), args)
out = jax.lax.cond(should_apply & should_apply_color & (i == idx), args,
lambda a: clip(fn(*a)), args,
lambda a: identity_fn(*a))
return jax.lax.stop_gradient(out)
return cond_fn
random_brightness = functools.partial(
pix.random_brightness, max_delta=brightness)
random_contrast = functools.partial(
pix.random_contrast, lower=1-contrast, upper=1+contrast)
random_hue = functools.partial(pix.random_hue, max_delta=hue)
random_saturation = functools.partial(
pix.random_saturation, lower=1-saturation, upper=1+saturation)
to_grayscale = functools.partial(pix.rgb_to_grayscale, keep_dims=True)
random_brightness_cond = _make_cond(random_brightness, idx=0)
random_contrast_cond = _make_cond(random_contrast, idx=1)
random_saturation_cond = _make_cond(random_saturation, idx=2)
random_hue_cond = _make_cond(random_hue, idx=3)
def _color_jitter(x):
if shuffle:
order = jax.random.permutation(perm_rng, jnp.arange(4, dtype=jnp.int32))
else:
order = range(4)
for idx in order:
if brightness > 0:
x = random_brightness_cond((b_rng, x), idx)
if contrast > 0:
x = random_contrast_cond((c_rng, x), idx)
if saturation > 0:
x = random_saturation_cond((s_rng, x), idx)
if hue > 0:
x = random_hue_cond((h_rng, x), idx)
return x
out_apply = _color_jitter(image)
out_apply = jax.lax.cond(should_apply & should_apply_gs, out_apply,
to_grayscale, out_apply, lambda x: x)
return jnp.clip(out_apply, 0., 1.)
def random_flip(images, rng):
rngs = jax.random.split(rng, images.shape[0])
return jax.vmap(pix.random_flip_left_right)(rngs, images)
def color_transform(images,
rng,
brightness=0.8,
contrast=0.8,
saturation=0.8,
hue=0.2,
color_jitter_prob=0.8,
to_grayscale_prob=0.2,
apply_prob=1.0,
shuffle=True):
"""Applies color jittering and/or grayscaling to a batch of images.
Args:
images: an NHWC tensor, with C=3.
rng: a single PRNGKey.
brightness: the range of jitter on brightness.
contrast: the range of jitter on contrast.
saturation: the range of jitter on saturation.
hue: the range of jitter on hue.
color_jitter_prob: the probability of applying color jittering.
to_grayscale_prob: the probability of converting the image to grayscale.
apply_prob: the probability of applying the transform to a batch element.
shuffle: whether to apply the transforms in a random order.
Returns:
A NHWC tensor of the transformed images.
"""
rngs = jax.random.split(rng, images.shape[0])
jitter_fn = functools.partial(
_color_transform_single_image,
brightness=brightness,
contrast=contrast,
saturation=saturation,
hue=hue,
color_jitter_prob=color_jitter_prob,
to_grayscale_prob=to_grayscale_prob,
apply_prob=apply_prob,
shuffle=shuffle)
return jax.vmap(jitter_fn)(images, rngs)
def gaussian_blur(images,
rng,
blur_divider=10.,
sigma_min=0.1,
sigma_max=2.0,
apply_prob=1.0):
"""Applies gaussian blur to a batch of images.
Args:
images: an NHWC tensor, with C=3.
rng: a single PRNGKey.
blur_divider: the blurring kernel will have size H / blur_divider.
sigma_min: the minimum value for sigma in the blurring kernel.
sigma_max: the maximum value for sigma in the blurring kernel.
apply_prob: the probability of applying the transform to a batch element.
Returns:
A NHWC tensor of the blurred images.
"""
rngs = jax.random.split(rng, images.shape[0])
kernel_size = images.shape[1] / blur_divider
blur_fn = functools.partial(
_random_gaussian_blur,
kernel_size=kernel_size,
padding='SAME',
sigma_min=sigma_min,
sigma_max=sigma_max,
apply_prob=apply_prob)
return jax.vmap(blur_fn)(images, rngs)
def _solarize_single_image(image, rng, threshold, apply_prob):
solarize_fn = functools.partial(pix.solarize, threshold=threshold)
return _maybe_apply(solarize_fn, image, rng, apply_prob)
def solarize(images, rng, threshold=0.5, apply_prob=1.0):
"""Applies solarization.
Args:
images: an NHWC tensor (with C=3).
rng: a single PRNGKey.
threshold: the solarization threshold.
apply_prob: the probability of applying the transform to a batch element.
Returns:
A NHWC tensor of the transformed images.
"""
rngs = jax.random.split(rng, images.shape[0])
solarize_fn = functools.partial(
_solarize_single_image, threshold=threshold, apply_prob=apply_prob)
return jax.vmap(solarize_fn)(images, rngs)
|
detcon-main
|
utils/augmentations.py
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
# ==============================================================================
"""Learning rate schedules."""
import jax.numpy as jnp
def target_ema(global_step: jnp.ndarray,
base_ema: float,
max_steps: int) -> jnp.ndarray:
decay = _cosine_decay(global_step, max_steps, 1.)
return 1. - (1. - base_ema) * decay
def learning_schedule(global_step: jnp.ndarray,
batch_size: int,
base_learning_rate: float,
total_steps: int,
warmup_steps: int) -> float:
"""Cosine learning rate scheduler."""
# Compute LR & Scaled LR
scaled_lr = base_learning_rate * batch_size / 256.
learning_rate = (
global_step.astype(jnp.float32) / int(warmup_steps) *
scaled_lr if warmup_steps > 0 else scaled_lr)
# Cosine schedule after warmup.
return jnp.where(
global_step < warmup_steps, learning_rate,
_cosine_decay(global_step - warmup_steps, total_steps - warmup_steps,
scaled_lr))
def _cosine_decay(global_step: jnp.ndarray,
max_steps: int,
initial_value: float) -> jnp.ndarray:
"""Simple implementation of cosine decay from TF1."""
global_step = jnp.minimum(global_step, max_steps)
cosine_decay_value = 0.5 * (1 + jnp.cos(jnp.pi * global_step / max_steps))
decayed_learning_rate = initial_value * cosine_decay_value
return decayed_learning_rate
|
detcon-main
|
utils/schedules.py
|
# Copyright 2014 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.
"""Script for downloading and generating question/answer pairs.
"""
import argparse
from collections import namedtuple
import hashlib
from itertools import chain
from itertools import izip
from itertools import repeat
import math
from multiprocessing.pool import Pool
from multiprocessing.pool import ThreadPool
import os
import re
import sys
import time
import cchardet as chardet
from lxml import html
import requests
import socket
class Story(namedtuple('StoryBase', 'url content highlights')):
def ToString(self):
return self.content + ''.join([
'\n\n@highlight\n\n' + highlight
for highlight in
self.highlights])
AnonymizedStory = namedtuple(
'AnonymizedStory', 'url content highlights anonymization_info')
RawStory = namedtuple('RawStory', 'url html')
TokenizedStory = namedtuple('TokenizedStory', 'url tokens')
class QuestionContext(
namedtuple(
'QuestionContextBase',
'url context question answer anonymization_info')):
def ToString(self):
return '%s\n\n%s\n\n%s\n\n%s\n\n%s' % (
self.url, self.context, self.question, self.answer,
'\n'.join(
[
key + ':' + value
for key, value in self.anonymization_info.iteritems()]))
def ReadUrls(filename):
"""Reads a list of URLs.
Args:
filename: The filename containing the URLs.
Returns:
A list of URLs.
"""
with open(filename) as f:
return [line.strip('\n') for line in f]
def ReadMultipleUrls(filename):
"""Reads a list of URL lists.
Each line in the filename should contain a list of URLs separated by comma.
Args:
filename: The filename containing the URLs.
Returns:
A list of list of URLs.
"""
with open(filename) as f:
return [line.strip('\n').split(',') for line in f]
def WriteUrls(filename, urls):
"""Writes a list of URLs to a file.
Args:
filename: The filename to the file where the URLs should be written.
urls: The list of URLs to write.
"""
with open(filename, 'w') as f:
f.writelines(url + '\n' for url in urls)
def Hashhex(s):
"""Returns a heximal formated SHA1 hash of the input string.
Args:
s: The string to hash.
Returns:
A heximal formatted hash of the input string.
"""
h = hashlib.sha1()
h.update(s)
return h.hexdigest()
def ReadDownloadedUrl(url, corpus):
"""Reads a downloaded URL from disk.
Args:
url: The URL to read.
corpus: The corpus the URL belongs to.
Returns:
The content of the URL.
"""
try:
with open('%s/downloads/%s.html' % (corpus, Hashhex(url))) as f:
return f.read()
except IOError:
return None
wayback_pattern = re.compile(r'web/([^/]*)/')
def WaybackUrl(urls, max_attempts=6):
"""Retrieves the URL for the latest historic copy using Wayback Machine.
Args:
urls: The URL for a specific page (canonical URL + forwarding URL's).
max_attempts: The maximum attempts at requesting the URL.
Returns:
The URL or None if no copy is stored for the URL.
Raises:
RuntimeError: Failed to retrieve the URL.
"""
if not urls:
return None
url = urls[0]
index_collection_url = 'http://archive.org/wayback/available'
payload = {'url': url}
attempts = 0
while attempts < max_attempts:
try:
entry_req = requests.get(index_collection_url, params=payload,
allow_redirects=False)
if entry_req.status_code != requests.codes.ok:
return WaybackUrl(urls[1:], max_attempts)
entry = entry_req.json()
if 'closest' not in entry['archived_snapshots']:
return WaybackUrl(urls[1:], max_attempts)
wayback_url = entry['archived_snapshots']['closest']['url']
wayback_url = wayback_pattern.sub(r'web/\g<1>id_/', wayback_url, 1)
return wayback_url
except requests.exceptions.ConnectionError:
pass
# Exponential back-off.
time.sleep(math.pow(2, attempts))
attempts += 1
raise RuntimeError(
'Failed to download URL for %s after %d attempts. Please run the script '
'again.' %
(url, max_attempts))
def DownloadUrl(url, corpus, max_attempts=5, timeout=5):
"""Downloads a URL.
Args:
url: The URL.
corpus: The corpus of the URL.
max_attempts: Max attempts for downloading the URL.
timeout: Connection timeout in seconds for each attempt.
Returns:
The HTML at the URL or None if the request failed.
"""
try:
with open('%s/downloads/%s.html' % (corpus, Hashhex(url))) as f:
return f.read()
except IOError:
pass
attempts = 0
while attempts < max_attempts:
try:
req = requests.get(url, allow_redirects=False, timeout=timeout)
if req.status_code == requests.codes.ok:
content = req.text.encode(req.encoding)
with open('%s/downloads/%s.html' % (corpus, Hashhex(url)), 'w') as f:
f.write(content)
return content
elif (req.status_code in [301, 302, 404, 503]
and attempts == max_attempts - 1):
return None
except requests.exceptions.ConnectionError:
pass
except requests.exceptions.ContentDecodingError:
return None
except requests.exceptions.ChunkedEncodingError:
return None
except requests.exceptions.Timeout:
pass
except socket.timeout:
pass
# Exponential back-off.
time.sleep(math.pow(2, attempts))
attempts += 1
return None
def ParseHtml(story, corpus):
"""Parses the HTML of a news story.
Args:
story: The raw Story to be parsed.
corpus: Either 'cnn' or 'dailymail'.
Returns:
A Story containing URL, paragraphs and highlights.
"""
parser = html.HTMLParser(encoding=chardet.detect(story.html)['encoding'])
tree = html.document_fromstring(story.html, parser=parser)
# Elements to delete.
delete_selectors = {
'cnn': [
'//blockquote[contains(@class, "twitter-tweet")]',
'//blockquote[contains(@class, "instagram-media")]'
],
'dailymail': [
'//blockquote[contains(@class, "twitter-tweet")]',
'//blockquote[contains(@class, "instagram-media")]'
]
}
# Paragraph exclusions: ads, links, bylines, comments
cnn_exclude = (
'not(ancestor::*[contains(@class, "metadata")])'
' and not(ancestor::*[contains(@class, "pullquote")])'
' and not(ancestor::*[contains(@class, "SandboxRoot")])'
' and not(ancestor::*[contains(@class, "twitter-tweet")])'
' and not(ancestor::div[contains(@class, "cnnStoryElementBox")])'
' and not(contains(@class, "cnnTopics"))'
' and not(descendant::*[starts-with(text(), "Read:")])'
' and not(descendant::*[starts-with(text(), "READ:")])'
' and not(descendant::*[starts-with(text(), "Join us at")])'
' and not(descendant::*[starts-with(text(), "Join us on")])'
' and not(descendant::*[starts-with(text(), "Read CNNOpinion")])'
' and not(descendant::*[contains(text(), "@CNNOpinion")])'
' and not(descendant-or-self::*[starts-with(text(), "Follow us")])'
' and not(descendant::*[starts-with(text(), "MORE:")])'
' and not(descendant::*[starts-with(text(), "SPOILER ALERT:")])')
dm_exclude = (
'not(ancestor::*[contains(@id,"reader-comments")])'
' and not(contains(@class, "byline-plain"))'
' and not(contains(@class, "byline-section"))'
' and not(contains(@class, "count-number"))'
' and not(contains(@class, "count-text"))'
' and not(contains(@class, "video-item-title"))'
' and not(ancestor::*[contains(@class, "column-content")])'
' and not(ancestor::iframe)')
paragraph_selectors = {
'cnn': [
'//div[contains(@class, "cnnContentContainer")]//p[%s]' % cnn_exclude,
'//div[contains(@class, "l-container")]//p[%s]' % cnn_exclude,
'//div[contains(@class, "cnn_strycntntlft")]//p[%s]' % cnn_exclude
],
'dailymail': [
'//div[contains(@class, "article-text")]//p[%s]' % dm_exclude
]
}
# Highlight exclusions.
he = (
'not(contains(@class, "cnnHiliteHeader"))'
' and not(descendant::*[starts-with(text(), "Next Article in")])')
highlight_selectors = {
'cnn': [
'//*[contains(@class, "el__storyhighlights__list")]//li[%s]' % he,
'//*[contains(@class, "cnnStryHghLght")]//li[%s]' % he,
'//*[@id="cnnHeaderRightCol"]//li[%s]' % he
],
'dailymail': [
'//h1/following-sibling::ul//li'
]
}
def ExtractText(selector):
"""Extracts a list of paragraphs given a XPath selector.
Args:
selector: A XPath selector to find the paragraphs.
Returns:
A list of raw text paragraphs with leading and trailing whitespace.
"""
xpaths = map(tree.xpath, selector)
elements = list(chain.from_iterable(xpaths))
paragraphs = [e.text_content().encode('utf-8') for e in elements]
# Remove editorial notes, etc.
if corpus == 'cnn' and len(paragraphs) >= 2 and '(CNN)' in paragraphs[1]:
paragraphs.pop(0)
paragraphs = map(str.strip, paragraphs)
paragraphs = [s for s in paragraphs if s and not str.isspace(s)]
return paragraphs
for selector in delete_selectors[corpus]:
for bad in tree.xpath(selector):
bad.getparent().remove(bad)
paragraphs = ExtractText(paragraph_selectors[corpus])
highlights = ExtractText(highlight_selectors[corpus])
content = '\n\n'.join(paragraphs)
return Story(story.url, content, highlights)
def WriteStory(story, corpus):
"""Writes a news story to disk.
Args:
story: The news story to write.
corpus: The corpus the news story belongs to.
"""
story_string = story.ToString()
url_hash = Hashhex(story.url)
with open('%s/stories/%s.story' % (corpus, url_hash), 'w') as f:
f.write(story_string)
def LoadTokenMapping(filename):
"""Loads a token mapping from the given filename.
Args:
filename: The filename containing the token mapping.
Returns:
A list of (start, end) where start and
end (inclusive) are offsets into the content for a token. The list is
sorted.
"""
mapping = []
with open(filename) as f:
line = f.readline().strip()
for token_mapping in line.split(';'):
if not token_mapping:
continue
start, length = token_mapping.split(',')
mapping.append((int(start), int(start) + int(length)))
mapping.sort(key=lambda x: x[1]) # Sort by start.
return mapping
def Tokenize(story, corpus):
"""Tokenizes a news story.
Args:
story: The Story.
corpus: The corpus of the news story.
Returns:
A TokenizedStory containing the URL and the tokens or None if no token
mapping was found for the URL.
"""
s = story.ToString()
url_hash = Hashhex(story.url)
mapping_filename = '%s/tokens/%s.txt' % (corpus, url_hash)
if not os.path.exists(mapping_filename):
return None
mapping = LoadTokenMapping(mapping_filename)
tokens = []
for (start, end) in mapping:
tokens.append(s[start:end + 1])
return TokenizedStory(story.url, tokens)
def LoadEntityMapping(filename):
"""Loads an entity mapping from the given filename.
Args:
filename: The filename containing the entity mapping.
Returns:
A list of (entity_index, start, end)
where start and end (inclusive) are token offsets for an entity. The list
is sorted.
"""
mapping = []
with open(filename) as f:
line = f.readline().strip()
for entity_mapping in line.split(';'):
if not entity_mapping:
continue
entity_index, start, end = entity_mapping.split(',')
mapping.append((int(entity_index), int(start), int(end)))
mapping.sort(key=lambda x: x[2]) # Sort by start.
return mapping
def Anonymize(tokenized_story, corpus):
"""Anonymizes a tokenized news story.
Args:
tokenized_story: A TokenizedStory.
corpus: The corpus of the tokenized news story.
Returns:
A Story containing the URL, anonymized content and anonymized highlights or
None if no entity mapping exists for the news story.
"""
url_hash = Hashhex(tokenized_story.url)
mapping_filename = '%s/entities/%s.txt' % (corpus, url_hash)
if not os.path.exists(mapping_filename):
return None
mapping = LoadEntityMapping(mapping_filename)
mapping_index = 0
mapping_len = len(mapping)
new_tokens = []
anonymization_info = {}
i = 0
while i < len(tokenized_story.tokens):
if mapping_index < mapping_len and mapping[mapping_index][1] == i:
entity_index, start, end = mapping[mapping_index]
anonymized_entity_name = '@entity%d' % entity_index
new_tokens.append(anonymized_entity_name)
anonymization_info[anonymized_entity_name] = ' '.join(
tokenized_story.tokens[start: end + 1]).replace(' - ', '-')
mapping_index += 1
i = end + 1
else:
new_tokens.append(tokenized_story.tokens[i])
i += 1
parts = ' '.join(new_tokens).split(' @ highlight ')
content = parts[0]
highlights = parts[1:]
return AnonymizedStory(
tokenized_story.url, content, highlights, anonymization_info)
entity_pattern = re.compile(r'@entity\d+')
def GenerateQuestionContexts(anonymized_story, context_token_limit):
"""Generates a list of question/answer pairs given an anonymized news story.
One question/answer pair is generated for each anonymized entity appearing in
the question.
Args:
anonymized_story: The anonymized news story.
context_token_limit: If the context of a news story is above the limit, the
empty list will be returned.
Returns:
A list of QuestionContext containing questions and answers.
"""
result = []
if anonymized_story.content.count(' ') + 1 > context_token_limit:
return result
entities_in_context = set(entity_pattern.findall(anonymized_story.content))
for highlight in anonymized_story.highlights:
for match in entity_pattern.finditer(highlight):
start, end = match.span()
answer = highlight[start:end]
if answer not in entities_in_context:
# Ignore entities that doesn't appear in the content as these will be
# impossible (or very hard to answer).
continue
question = ('%s@placeholder%s' %
(highlight[0:start], highlight[end:])).lower()
context = anonymized_story.content.lower()
url = anonymized_story.url
anonymization_info = anonymized_story.anonymization_info
result.append(
QuestionContext(url, context, question, answer, anonymization_info))
return result
def WriteQuestionContext(question_context, corpus, dataset):
"""Writes a question/answer pair to disk.
Args:
question_context: The QuestionContext to write containing the question and
answer.
corpus: The corpus the question/answer belongs to.
dataset: One of 'training', 'validation' and 'test'.
"""
s = question_context.ToString()
h = Hashhex(s)
with open('%s/questions/%s/%s.question' % (corpus, dataset, h), 'w') as f:
f.write(s)
class ProgressBar(object):
"""Simple progress bar.
Output example:
100.00% [2152/2152]
"""
def __init__(self, total=100, stream=sys.stderr):
self.total = total
self.stream = stream
self.last_len = 0
self.curr = 0
def Increment(self):
self.curr += 1
self.PrintProgress(self.curr)
if self.curr == self.total:
print ''
def PrintProgress(self, value):
self.stream.write('\b' * self.last_len)
pct = 100 * self.curr / float(self.total)
out = '{:.2f}% [{}/{}]'.format(pct, value, self.total)
self.last_len = len(out)
self.stream.write(out)
self.stream.flush()
datasets = ['training', 'validation', 'test']
def UrlMode(corpus, request_parallelism):
"""Finds Wayback Machine URLs and writes them to disk.
Args:
corpus: A corpus.
request_parallelism: The number of concurrent requests.
"""
for dataset in datasets:
print 'Finding Wayback Machine URLs for the %s set:' % dataset
old_urls_filename = '%s/%s_urls.txt' % (corpus, dataset)
new_urls_filename = '%s/wayback_%s_urls.txt' % (corpus, dataset)
urls = ReadMultipleUrls(old_urls_filename)
p = ThreadPool(request_parallelism)
results = p.imap_unordered(WaybackUrl, urls)
progress_bar = ProgressBar(len(urls))
new_urls = []
for result in results:
if result:
new_urls.append(result)
progress_bar.Increment()
WriteUrls(new_urls_filename, new_urls)
def DownloadMapper(t):
"""Downloads an URL and checks that metadata is available for the URL.
Args:
t: a tuple (url, corpus).
Returns:
A pair of URL and content.
Raises:
RuntimeError: No metadata available.
"""
url, corpus = t
url_hash = Hashhex(url)
mapping_filename = '%s/entities/%s.txt' % (corpus, url_hash)
if not os.path.exists(mapping_filename):
raise RuntimeError('No metadata available for %s.' % url)
return url, DownloadUrl(url, corpus)
def DownloadMode(corpus, request_parallelism):
"""Downloads the URLs for the specified corpus.
Args:
corpus: A corpus.
request_parallelism: The number of concurrent download requests.
"""
missing_urls = []
for dataset in datasets:
print 'Downloading URLs for the %s set:' % dataset
urls_filename = '%s/wayback_%s_urls.txt' % (corpus, dataset)
urls = ReadUrls(urls_filename)
missing_urls_filename = '%s/missing_urls.txt' % corpus
if os.path.exists(missing_urls_filename):
print 'Only downloading missing URLs'
urls = list(set(urls).intersection(ReadUrls(missing_urls_filename)))
p = ThreadPool(request_parallelism)
results = p.imap_unordered(DownloadMapper, izip(urls, repeat(corpus)))
progress_bar = ProgressBar(len(urls))
collected_urls = []
try:
for url, story_html in results:
if story_html:
collected_urls.append(url)
progress_bar.Increment()
except KeyboardInterrupt:
print 'Interrupted by user'
missing_urls.extend(set(urls) - set(collected_urls))
WriteUrls('%s/missing_urls.txt' % corpus, missing_urls)
if missing_urls:
print ('%d URLs couldn\'t be downloaded, see %s/missing_urls.txt.'
% (len(missing_urls), corpus))
print 'Try and run the command again to download the missing URLs.'
def StoreMapper(t):
"""Reads an URL from disk and returns the parsed news story.
Args:
t: a tuple (url, corpus).
Returns:
A Story containing the parsed news story.
"""
url, corpus = t
story_html = ReadDownloadedUrl(url, corpus)
if not story_html:
return None
raw_story = RawStory(url, story_html)
return ParseHtml(raw_story, corpus)
def StoreMode(corpus):
for dataset in datasets:
print 'Storing news stories for the %s set:' % dataset
urls_filename = '%s/wayback_%s_urls.txt' % (corpus, dataset)
urls = ReadUrls(urls_filename)
p = Pool()
stories = p.imap_unordered(StoreMapper, izip(urls, repeat(corpus)))
progress_bar = ProgressBar(len(urls))
for story in stories:
if story:
WriteStory(story, corpus)
progress_bar.Increment()
def GenerateMapper(t):
"""Reads an URL from disk and returns a list of question/answer pairs.
Args:
t: a tuple (url, corpus).
Returns:
A list of QuestionContext containing a question and an answer.
"""
url, corpus, context_token_limit = t
story_html = ReadDownloadedUrl(url, corpus)
if not story_html:
return None
raw_story = RawStory(url, story_html)
story = ParseHtml(raw_story, corpus)
tokenized = Tokenize(story, corpus)
if not tokenized:
return None
anonymized = Anonymize(tokenized, corpus)
if not anonymized:
return None
return GenerateQuestionContexts(anonymized, context_token_limit)
def GenerateMode(corpus, context_token_limit):
for dataset in datasets:
print 'Generating questions for the %s set:' % dataset
urls_filename = '%s/wayback_%s_urls.txt' % (corpus, dataset)
urls = ReadUrls(urls_filename)
p = Pool()
question_context_lists = p.imap_unordered(
GenerateMapper, izip(urls, repeat(corpus), repeat(context_token_limit)))
progress_bar = ProgressBar(len(urls))
for question_context_list in question_context_lists:
if question_context_list:
for question_context in question_context_list:
WriteQuestionContext(question_context, corpus, dataset)
progress_bar.Increment()
def RemoveMode(corpus):
missing_urls = set(ReadUrls('%s/missing_urls.txt' % corpus))
for dataset in datasets:
urls_filename = '%s/wayback_%s_urls.txt' % (corpus, dataset)
urls = ReadUrls(urls_filename)
new_urls = []
for url in urls:
if url not in missing_urls:
new_urls.append(url)
WriteUrls(urls_filename, new_urls)
def main():
parser = argparse.ArgumentParser(
description='Generates question/answer pairs')
parser.add_argument('--corpus', choices=['cnn', 'dailymail'], default='cnn')
parser.add_argument(
'--mode', choices=['store', 'generate', 'download', 'urls', 'remove'],
default='generate')
parser.add_argument('--request_parallelism', type=int, default=200)
parser.add_argument('--context_token_limit', type=int, default=2000)
args = parser.parse_args()
stories_dir = '%s/stories' % args.corpus
if not os.path.exists(stories_dir):
os.mkdir(stories_dir)
downloads_dir = '%s/downloads' % args.corpus
if not os.path.exists(downloads_dir):
os.mkdir(downloads_dir)
questions_dir = '%s/questions' % args.corpus
if not os.path.exists(questions_dir):
os.mkdir(questions_dir)
for dataset in datasets:
dataset_dir = '%s/questions/%s' % (args.corpus, dataset)
if not os.path.exists(dataset_dir):
os.mkdir(dataset_dir)
if args.mode == 'store':
StoreMode(args.corpus)
elif args.mode == 'generate':
GenerateMode(args.corpus, args.context_token_limit)
elif args.mode == 'download':
DownloadMode(args.corpus, args.request_parallelism)
elif args.mode == 'urls':
UrlMode(args.corpus, args.request_parallelism)
elif args.mode == 'remove':
RemoveMode(args.corpus)
if __name__ == '__main__':
main()
|
rc-data-master
|
generate_questions.py
|
# Copyright 2021 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
"""Setup for pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = [
'absl-py',
'dataclasses; python_version < "3.7"',
'numpy',
]
EXTRA_PACKAGES = {
'jax': ['jax>=0.1.71'],
'jaxlib': ['jaxlib>=0.1.49'],
'tensorflow': ['tensorflow>=1.8.0'],
'tensorflow with gpu': ['tensorflow-gpu>=1.8.0'],
}
def einshape_test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('einshape/tests',
pattern='*_test.py')
return test_suite
setup(
name='einshape',
version='1.0',
description='DSL-based reshaping library for JAX and other frameworks',
url='https://github.com/deepmind/einshape',
author='DeepMind',
author_email='noreply@google.com',
# Contained modules and scripts.
packages=find_packages(),
install_requires=REQUIRED_PACKAGES,
extras_require=EXTRA_PACKAGES,
platforms=['any'],
license='Apache 2.0',
test_suite='setup.einshape_test_suite',
)
|
einshape-main
|
setup.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Einshape: DSL-based reshaping library for JAX and other frameworks.
The `jnp.einsum` op provides a DSL-based unified interface to matmul and
tensordot ops.
This `einshape` library is designed to offer a similar DSL-based approach
to unifying reshape, squeeze, expand_dims, and transpose operations.
See `src/jax/jax_ops.py` for the JAX implementation of the `einshape` function.
Alternatively, the parser and engine are exposed in `src/engine.py` allowing
analogous implementations in other frameworks; see TensorFlow implementation
at `src/tensorflow/tf_ops.py`.
"""
import typing
from typing import Any, Union
from einshape.src import abstract_ops
from einshape.src import backend
if typing.TYPE_CHECKING:
import jax.numpy as jnp
import numpy as np
import tensorflow as tf
def jax_einshape(
equation: str,
value: Union['jnp.ndarray', Any],
**index_sizes: int,
) -> 'jnp.ndarray':
"""Reshapes `value` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
value: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred from
`input_shape`.
Returns:
Tensor derived from `value` by reshaping as specified by `equation`.
"""
import einshape.src.jax.jax_ops # pylint:disable=g-import-not-at-top
global jax_einshape
jax_einshape = einshape.src.jax.jax_ops.einshape # pytype:disable=module-attr
return jax_einshape(equation, value, **index_sizes)
def numpy_einshape(
equation: str,
value: Union['np.ndarray', Any],
**index_sizes: int,
) -> 'np.ndarray':
"""Reshapes `value` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
value: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred from
`input_shape`.
Returns:
Tensor derived from `value` by reshaping as specified by `equation`.
"""
import einshape.src.numpy.numpy_ops # pylint:disable=g-import-not-at-top
global numpy_einshape
numpy_einshape = einshape.src.numpy.numpy_ops.einshape # pytype:disable=module-attr
return numpy_einshape(equation, value, **index_sizes)
def tf_einshape(
equation: str,
x: Union['tf.Tensor', Any],
**index_sizes: Union[int, 'tf.Tensor'],
) -> 'tf.Tensor':
"""Reshapes `x` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
x: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred from
`input_shape`.
Returns:
Tensor derived from `x` by reshaping as specified by `equation`.
"""
import einshape.src.tensorflow.tf_ops # pylint:disable=g-import-not-at-top
global tf_einshape
tf_einshape = einshape.src.tensorflow.tf_ops.einshape # pytype:disable=module-attr
return tf_einshape(equation, x, **index_sizes)
|
einshape-main
|
einshape/__init__.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the einshape engine's optimiser."""
from absl.testing import absltest
from einshape.src import abstract_ops
from einshape.src import optimizer
class OptimizerTest(absltest.TestCase):
def test_redundant_reshape_skipped(self):
ops = [abstract_ops.Reshape(shape=(2, 3)),
abstract_ops.Reshape(shape=(6,))]
input_shape = (3, 2)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[1])
def test_nonredundant_reshape_retained(self):
ops = [abstract_ops.Reshape(shape=(2, 3)),
abstract_ops.Transpose(perm=(1, 0)),
abstract_ops.Reshape(shape=(6,))]
input_shape = (3, 2)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 3)
self.assertEqual(opt_ops[0], ops[0])
self.assertEqual(opt_ops[1], ops[1])
self.assertEqual(opt_ops[2], ops[2])
def test_noop_reshape_skipped(self):
ops = [abstract_ops.Reshape(shape=(3, 5))]
input_shape = (3, 5)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertEmpty(opt_ops)
def test_op_reshape_retained(self):
ops = [abstract_ops.Reshape(shape=(5, 3))]
input_shape = (3, 5)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[0])
def test_noop_reshape_after_tanspose_skipped(self):
ops = [abstract_ops.Transpose(perm=(1, 0)),
abstract_ops.Reshape(shape=(5, 3))]
input_shape = (3, 5)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[0])
def test_noop_reshape_after_broadcast_skipped(self):
ops = [abstract_ops.Broadcast(axis_sizes={1: 3}),
abstract_ops.Reshape(shape=(5, 3))]
input_shape = (5,)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[0])
def test_nonstatic_reshape_retained(self):
ops = [abstract_ops.Reshape(shape=(5, None))]
input_shape = (5, None)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[0])
def test_transpose_same_shape_retained(self):
ops = [abstract_ops.Transpose(perm=(1, 0))]
input_shape = (3, 3)
opt_ops = optimizer.optimize(ops, input_shape)
self.assertLen(opt_ops, 1)
self.assertEqual(opt_ops[0], ops[0])
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/optimizer_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the einshape engine."""
from absl.testing import absltest
from einshape.src import abstract_ops
from einshape.src import engine
class _ShapeExpr(object):
"""Mock class to model a dynamic shape component.
The einshape engine will still perform simple arithmetic on such shapes
even though their value is not known at graph-time or JIT-time.
"""
def __add__(self, x):
return _ShapeExpr()
def __radd__(self, x):
return _ShapeExpr()
def __sub__(self, x):
return _ShapeExpr()
def __rsub__(self, x):
return _ShapeExpr()
def __mul__(self, x):
return _ShapeExpr()
def __rmul__(self, x):
return _ShapeExpr()
def __floordiv__(self, x):
return _ShapeExpr()
def __rfloordiv__(self, x):
return _ShapeExpr()
def __mod__(self, x):
return _ShapeExpr()
def __rmod__(self, x):
return _ShapeExpr()
class EngineTest(absltest.TestCase):
def test_rank_zero_noop(self):
preshape, reshape = engine.generate_ops('->', [])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([], list(reshape.shape))
def test_rank_one_noop(self):
preshape, reshape = engine.generate_ops('i->i', [3])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([3], list(reshape.shape))
def test_rank_four_noop(self):
preshape, reshape = engine.generate_ops(
'ijkl->ijkl', [2, 3, 5, 7])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([2, 3, 5, 7], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([2, 3, 5, 7], list(reshape.shape))
def test_simple_transpose(self):
preshape, transpose, reshape = engine.generate_ops('ij->ji', [3, 5])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([1, 0], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([5, 3], list(reshape.shape))
def test_nchw_transpose(self):
preshape, transpose, reshape = engine.generate_ops(
'nhwc->nchw', [5, 13, 17, 3])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([5, 13, 17, 3], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([0, 3, 1, 2], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([5, 3, 13, 17], list(reshape.shape))
def test_rejects_lhs_mismatch_with_input_shape(self):
with self.assertRaises(ValueError):
engine.generate_ops('i->i', [3, 5])
def test_rejects_lhs_with_duplicated_index(self):
with self.assertRaises(ValueError):
engine.generate_ops('ii->i', [3, 3])
def test_rejects_rhs_with_missing_index(self):
with self.assertRaises(ValueError):
engine.generate_ops('ij->j', [3, 5])
def test_rejects_rhs_with_duplicated_index(self):
with self.assertRaises(ValueError):
engine.generate_ops('ij->ii', [3, 5])
def test_expand_dim(self):
preshape, reshape = engine.generate_ops('k->1k', [2])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([2], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([1, 2], list(reshape.shape))
def test_expand_multiple_dims(self):
preshape, reshape = engine.generate_ops('n->n111', [5])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([5], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([5, 1, 1, 1], list(reshape.shape))
def test_transpose_and_expand_dim(self):
preshape, transpose, reshape = engine.generate_ops('ij->j1i', [5, 7])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([5, 7], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([1, 0], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([7, 1, 5], list(reshape.shape))
def test_squeeze(self):
preshape, reshape = engine.generate_ops('j1k->jk', [2, 1, 3])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([2, 3], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([2, 3], list(reshape.shape))
def test_rejects_squeezing_non_unitary(self):
with self.assertRaises(ValueError):
engine.generate_ops('i1->i', [2, 3])
def test_squeeze_transpose_expand(self):
preshape, transpose, reshape = engine.generate_ops(
'ij11k1->1k1ji', [3, 5, 1, 1, 7, 1])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5, 7], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([2, 1, 0], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([1, 7, 1, 5, 3], list(reshape.shape))
def test_group_dims(self):
preshape, reshape = engine.generate_ops('ij->(ij)', [3, 5])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([15], list(reshape.shape))
def test_ungroup_dims(self):
preshape, reshape = engine.generate_ops(
'(ij)->ij', [15], i=3, j=5)
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(reshape.shape))
def test_ungroup_dims_with_inferred_size(self):
preshape, reshape = engine.generate_ops(
'n(hwc)->nhwc', [5, 429], h=11, w=13)
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([5, 11, 13, 3], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([5, 11, 13, 3], list(reshape.shape))
def test_rejects_input_sizes_conflicting_with_input_shapes(self):
with self.assertRaises(ValueError):
engine.generate_ops('(ij)->ij', [15], i=2, j=7)
def test_rejects_ungroup_with_non_divisor_dimension_size(self):
with self.assertRaises(ValueError):
engine.generate_ops('(ij)->ij', [15], j=4)
def test_rejects_underspecified_ungroup_dimensions(self):
with self.assertRaises(ValueError):
engine.generate_ops('(ij)->ij', [15])
with self.assertRaises(ValueError):
engine.generate_ops('(ijk)->ijk', [15], i=3)
def test_regroup_with_transpose(self):
preshape, transpose, reshape = engine.generate_ops(
'i(jk)->k(ji)', [3, 35], j=5)
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5, 7], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([2, 1, 0], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([7, 15], list(reshape.shape))
def test_wildcard_identity(self):
preshape, reshape = engine.generate_ops('...->...', [3, 5])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([3, 5], list(reshape.shape))
def test_wildcard_transpose(self):
preshape, transpose, reshape = engine.generate_ops(
'i...j->j...i', [2, 3, 5, 7])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([2, 3, 5, 7], list(preshape.shape))
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([3, 1, 2, 0], list(transpose.perm))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([7, 3, 5, 2], list(reshape.shape))
def test_rejects_wildcard_lhs_mismatch_with_input_shape(self):
with self.assertRaises(ValueError):
engine.generate_ops('ijk...->ijk...', [3, 5])
def test_wildcard_flatten(self):
preshape, reshape = engine.generate_ops(
'n...->n(...)', [2, 3, 5])
self.assertIsInstance(preshape, abstract_ops.Reshape)
self.assertEqual([2, 3, 5], list(preshape.shape))
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertEqual([2, 15], list(reshape.shape))
def test_rejects_ungrouping_wildcard(self):
with self.assertRaises(ValueError):
engine.generate_ops('n(...)->n...', [3, 5])
def test_reshape_unknown_input_shape(self):
_, reshape = engine.generate_ops('i->1i', [_ShapeExpr()])
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertLen(reshape.shape, 2)
self.assertEqual(1, reshape.shape[0])
self.assertIsInstance(reshape.shape[1], _ShapeExpr)
def test_reshape_unknown_index_size(self):
_, reshape = engine.generate_ops('i->1i', [3], i=_ShapeExpr())
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertLen(reshape.shape, 2)
self.assertEqual(1, reshape.shape[0])
self.assertEqual(3, reshape.shape[1])
def test_smart_shape_inference(self):
_, _, reshape = engine.generate_ops('(ij)->(ji)', [6], j=_ShapeExpr())
self.assertIsInstance(reshape, abstract_ops.Reshape)
self.assertLen(reshape.shape, 1)
self.assertEqual(6, reshape.shape[0])
# Broadcast
def test_tile_leading_dim(self):
_, broadcast, _ = engine.generate_ops('j->nj', [5], n=3)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {0: 3})
def test_tile_trailing_dim(self):
_, broadcast, _ = engine.generate_ops('j->jk', [3], k=2)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {1: 2})
def test_tile_leading_dim_and_flatten(self):
_, broadcast, reshape = engine.generate_ops('j->(nj)', [5], n=3)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {0: 3})
self.assertLen(reshape.shape, 1)
self.assertEqual(15, reshape.shape[0])
def test_tile_trailing_dim_and_flatten(self):
_, broadcast, reshape = engine.generate_ops('j->(jk)', [3], k=2)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {1: 2})
self.assertLen(reshape.shape, 1)
self.assertEqual(6, reshape.shape[0])
def test_tile_rank_two_one_dim(self):
_, broadcast, _ = engine.generate_ops('ij->inj', [2, 5], n=3)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {1: 3})
def test_tile_rank_two_one_dim_and_flatten(self):
_, broadcast, reshape = engine.generate_ops('ij->i(nj)', [2, 5], n=3)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {1: 3})
self.assertLen(reshape.shape, 2)
self.assertEqual(2, reshape.shape[0])
self.assertEqual(15, reshape.shape[1])
def test_tile_rank_two_one_dim_with_transpose(self):
_, transpose, broadcast, _ = engine.generate_ops('ij->nji', [2, 5], n=3)
self.assertIsInstance(transpose, abstract_ops.Transpose)
self.assertEqual([1, 0], list(transpose.perm))
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {0: 3})
def test_tile_rank_two_two_dims(self):
_, broadcast, _ = engine.generate_ops('ij->nikj', [2, 5], n=3, k=4)
self.assertIsInstance(broadcast, abstract_ops.Broadcast)
self.assertDictEqual(broadcast.axis_sizes, {0: 3, 2: 4})
def test_rejcts_unknown_tile_multiples(self):
with self.assertRaises(ValueError):
engine.generate_ops('j->nj', [15])
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/engine_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 einshape.abstract_ops."""
from absl.testing import absltest
from einshape.src import abstract_ops
class AbstractOpsTest(absltest.TestCase):
def test_reshape_transform(self):
op = abstract_ops.Reshape(shape=[1, 2, 3])
input_shape = [3, 2]
output_shape = op.transform_shape(input_shape)
self.assertListEqual(output_shape, [1, 2, 3])
def test_transpose_transform(self):
op = abstract_ops.Transpose(perm=[1, 0, 2])
input_shape = [4, 5, 6]
output_shape = op.transform_shape(input_shape)
self.assertListEqual(output_shape, [5, 4, 6])
def test_broadcast_transform(self):
op = abstract_ops.Broadcast(axis_sizes={1: 5, 3: 6})
input_shape = [2, 2, 2]
output_shape = op.transform_shape(input_shape)
self.assertListEqual(output_shape, [2, 5, 2, 6, 2])
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/abstract_ops_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Common test cases."""
TEST_CASES = [
dict(
testcase_name='simple_reshape',
x=[3, 5],
equation='i->i1',
index_sizes={},
expected=[[3], [5]]),
dict(
testcase_name='simple_transpose',
x=[[7, 2, 4], [1, -3, 5]],
equation='ij->ji',
index_sizes={},
expected=[[7, 1], [2, -3], [4, 5]]),
dict(
testcase_name='ungroup',
x=[1, 4, 7, -2, 3, 2],
equation='(ij)->ij',
index_sizes=dict(j=3),
expected=[[1, 4, 7], [-2, 3, 2]]),
dict(
testcase_name='tile_leading_dim',
x=[3, 5],
equation='j->nj',
index_sizes=dict(n=3),
expected=[[3, 5], [3, 5], [3, 5]]),
dict(
testcase_name='tile_trailing_dim',
x=[3, 5],
equation='j->jk',
index_sizes=dict(k=3),
expected=[[3, 3, 3], [5, 5, 5]]),
dict(
testcase_name='tile_multiple_dims',
x=[3, 5],
equation='j->njm',
index_sizes=dict(n=3, m=4),
expected=[[[3] * 4, [5] * 4], [[3] * 4, [5] * 4], [[3] * 4, [5] * 4]],
)
]
|
einshape-main
|
einshape/tests/test_cases.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the einshape engine."""
from typing import Any, Mapping, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from einshape.src.numpy import numpy_ops
from einshape.tests import test_cases
import numpy as np
class EngineTest(parameterized.TestCase):
@parameterized.named_parameters(test_cases.TEST_CASES)
def test_common(self, x: Sequence[Any], equation: str,
index_sizes: Mapping[str, int], expected: Sequence[Any]):
x = np.array(x)
y = numpy_ops.einshape(equation, x, **index_sizes)
np.testing.assert_array_equal(np.array(expected), y)
def test_accepts_python_list(self):
x = [3, 5] # Python list, not a JAX tensor.
y = numpy_ops.einshape('i->i1', x)
np.testing.assert_array_equal(np.array([[3], [5]]), y)
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/numpy/numpy_ops_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the TensorFlow-specific preprocessing or einshape ops."""
from absl.testing import absltest
from einshape.src import abstract_ops
from einshape.src.tensorflow import preprocessing
class PreprocessingTest(absltest.TestCase):
def test_reshapes_and_transposes_preserved(self):
ops = [
abstract_ops.Reshape(shape=(2, 3)),
abstract_ops.Transpose(perm=[1, 0]),
abstract_ops.Reshape(shape=(6,))]
preproc_ops = preprocessing.preprocess(ops, [6])
self.assertLen(preproc_ops, 3)
for op, preproc_op in zip(ops, preproc_ops):
self.assertEqual(op, preproc_op)
def test_broadcast_expands_to_tile_then_reshape(self):
ops = [abstract_ops.Broadcast(axis_sizes={1: 5})]
preproc_ops = preprocessing.preprocess(ops, [2, 3])
self.assertLen(preproc_ops, 2)
self.assertIsInstance(preproc_ops[0], preprocessing.Tile)
self.assertEqual(preproc_ops[0].multiples, [1, 5])
self.assertIsInstance(preproc_ops[1], abstract_ops.Reshape)
self.assertEqual(preproc_ops[1].shape, [2, 5, 3])
def test_broadcast_trailing_dimension_generates_initial_reshape(self):
ops = [abstract_ops.Broadcast(axis_sizes={2: 5})]
preproc_ops = preprocessing.preprocess(ops, [2, 3])
self.assertLen(preproc_ops, 3)
self.assertIsInstance(preproc_ops[0], abstract_ops.Reshape)
self.assertEqual(preproc_ops[0].shape, [2, 3, 1])
self.assertIsInstance(preproc_ops[1], preprocessing.Tile)
self.assertEqual(preproc_ops[1].multiples, [1, 1, 5])
self.assertIsInstance(preproc_ops[2], abstract_ops.Reshape)
self.assertEqual(preproc_ops[2].shape, [2, 3, 5])
def test_broadcast_multiple_dimensions(self):
ops = [abstract_ops.Broadcast(
axis_sizes={0: 101, 2: 103, 3: 105, 5: 107, 6: 109})]
preproc_ops = preprocessing.preprocess(ops, [2, 3])
self.assertLen(preproc_ops, 3)
self.assertIsInstance(preproc_ops[0], abstract_ops.Reshape)
self.assertEqual(preproc_ops[0].shape, [2, 3, 1])
self.assertIsInstance(preproc_ops[1], preprocessing.Tile)
self.assertEqual(preproc_ops[1].multiples, [101, 103*105, 107*109])
self.assertIsInstance(preproc_ops[2], abstract_ops.Reshape)
self.assertEqual(preproc_ops[2].shape, [101, 2, 103, 105, 3, 107, 109])
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/tensorflow/preprocessing_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the TensorFlow einshape implementation."""
from absl.testing import absltest
from einshape.src.tensorflow import tf_ops
import tensorflow.compat.v1 as tf
class EinshapeTest(tf.test.TestCase):
def test_simple_reshape(self):
x = tf.constant([3, 5], dtype=tf.int64)
y = tf_ops.einshape('i->i1', x)
self.assertEqual([2, 1], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[3], [5]], y_val)
def test_simple_transpose(self):
x = tf.constant([[7, 2, 4], [1, -3, 5]], dtype=tf.int64)
y = tf_ops.einshape('ij->ji', x)
self.assertEqual([3, 2], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[7, 1], [2, -3], [4, 5]], y_val)
def test_ungroup(self):
x = tf.constant([1, 4, 7, -2, 3, 2], dtype=tf.int64)
y = tf_ops.einshape('(ij)->ij', x, j=3)
self.assertEqual([2, 3], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[1, 4, 7], [-2, 3, 2]], y_val)
def test_reshape_unknown_input_shape(self):
# Construct a tensor `x` whose shape is unknown at graph-time.
n = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([1, 4, 9])[:n]
y = tf_ops.einshape('i->1i', x)
self.assertEqual([1, None], y.shape.as_list())
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={n: 2})
self.assertAllEqual([[1, 4]], y_val)
self.assertAllEqual([1, 2], y_shape_val)
def test_reshape_unknown_index_size(self):
# Construct a shape hint whose value is unknown at graph-time.
i = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([1, 4, 9])
y = tf_ops.einshape('i->1i', x, i=i)
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={i: 3})
self.assertAllEqual([[1, 4, 9]], y_val)
self.assertAllEqual([1, 3], y_shape_val)
def test_transpose_unknown_input_shape(self):
# Construct a tensor `x` whose shape is unknown at graph-time.
n = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([[1, 2], [4, -5], [9, 8], [16, 13]])[:n]
y = tf_ops.einshape('ij->ji', x)
self.assertEqual([2, None], y.shape.as_list())
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={n: 3})
self.assertAllEqual([[1, 4, 9], [2, -5, 8]], y_val)
self.assertAllEqual([2, 3], y_shape_val)
def test_group_unknown_input_shape(self):
# Construct a tensor `x` whose shape is unknown at graph-time.
n = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([[1, 2], [4, -5], [9, 8], [16, 13]])[:n]
y = tf_ops.einshape('ij->(ij)', x)
self.assertEqual([None], y.shape.as_list())
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={n: 3})
self.assertAllEqual([1, 2, 4, -5, 9, 8], y_val)
self.assertAllEqual([6], y_shape_val)
def test_ungroup_unknown_input_shape(self):
# Construct a tensor `x` whose shape is unknown at graph-time.
n = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([1, 2, 4, -5, 9, 8, 16, 13])[:n]
y = tf_ops.einshape('(ij)->ij', x, j=2)
self.assertEqual([None, 2], y.shape.as_list())
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={n: 6})
self.assertAllEqual([[1, 2], [4, -5], [9, 8]], y_val)
self.assertAllEqual([3, 2], y_shape_val)
def test_ungroup_unknown_index_size(self):
# Construct a shape hint whose value is unknown at graph-time.
j = tf.placeholder(shape=(), dtype=tf.int64)
x = tf.constant([1, 2, 4, -5, 9, 8])
y = tf_ops.einshape('(ij)->ij', x, j=j)
self.assertEqual([None, None], y.shape.as_list())
y_shape = tf.shape(y)
with tf.Session() as session:
y_val, y_shape_val = session.run((y, y_shape), feed_dict={j: 3})
self.assertAllEqual([[1, 2, 4], [-5, 9, 8]], y_val)
self.assertAllEqual([2, 3], y_shape_val)
def test_tile_leading_dim(self):
x = tf.constant([3, 5], dtype=tf.int64)
y = tf_ops.einshape('j->nj', x, n=3)
self.assertEqual([3, 2], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[3, 5], [3, 5], [3, 5]], y_val)
def test_tile_trailing_dim(self):
x = tf.constant([3, 5], dtype=tf.int64)
y = tf_ops.einshape('j->jk', x, k=3)
self.assertEqual([2, 3], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[3, 3, 3], [5, 5, 5]], y_val)
def test_accepts_python_list(self):
x = [3, 5] # Python list, not a TensorFlow tensor.
y = tf_ops.einshape('i->i1', x)
self.assertEqual([2, 1], y.shape.as_list())
with tf.Session() as session:
y_val = session.run(y)
self.assertAllEqual([[3], [5]], y_val)
if __name__ == '__main__':
tf.disable_v2_behavior()
absltest.main()
|
einshape-main
|
einshape/tests/tensorflow/tf_ops_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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 the einshape engine."""
from typing import Any, Mapping, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from einshape.src.jax import jax_ops
from einshape.tests import test_cases
import jax.numpy as jnp
import numpy as np
class EngineTest(parameterized.TestCase):
@parameterized.named_parameters(test_cases.TEST_CASES)
def test_common(self, x: Sequence[Any], equation: str,
index_sizes: Mapping[str, int], expected: Sequence[Any]):
x = jnp.array(x)
y = jax_ops.einshape(equation, x, **index_sizes)
np.testing.assert_array_equal(np.array(expected), y)
def test_accepts_python_list(self):
x = [3, 5] # Python list, not a JAX tensor.
y = jax_ops.einshape('i->i1', x)
np.testing.assert_array_equal(np.array([[3], [5]]), y)
if __name__ == '__main__':
absltest.main()
|
einshape-main
|
einshape/tests/jax/jax_ops_test.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Abstract class of backend of einshape."""
import abc
from typing import Any, Generic, Sequence, TypeVar
from einshape.src import abstract_ops
from einshape.src import engine
from einshape.src import optimizer
T = TypeVar('T')
class Backend(Generic[T], metaclass=abc.ABCMeta):
"""The backend exec the einshape expression on a Tensor."""
@abc.abstractmethod
def reshape(self, x: T, op: abstract_ops.Reshape) -> T:
"""The realization of `abstract_ops.Reshape` in a defined backend."""
@abc.abstractmethod
def transpose(self, x: T, op: abstract_ops.Transpose) -> T:
"""The realization of `abstract_ops.Transpose` in a defined backend."""
@abc.abstractmethod
def broadcast(self, x: T, op: abstract_ops.Broadcast) -> T:
"""The realization of `abstract_ops.Broadcast` in a defined backend."""
def _preprocess(
self, ops: Sequence[abstract_ops.ShapeOp], input_shape: Sequence[Any]
) -> Sequence[abstract_ops.ShapeOp]:
"""Returns an amended copy of the given sequence of shaping ops.
This default implementation has no effect, but this is an opportunity for
backend-specific optimisation to be performed prior to the 'main'
optimisation.
Args:
ops: Sequence of shaping ops.
input_shape: Shape of the original inputs.
Returns: Amended sequence of shaping ops.
"""
return ops
def exec(
self,
equation: str,
value: T,
shape: Sequence[Any],
**index_sizes: Any) -> T:
"""Run the ops defined by the einshape equation.
Args:
equation: The Shape Equation specifying how to reshape.
value: Tensor to reshape.
shape: Shape of `value`. May be a mixture of `int`s (for statically known
shape components) and tensors (for dynamic shapes).
**index_sizes: Sizes of indices, where they cannot be
inferred from `shape`.
Returns:
Reshaped tensor.
"""
ops = engine.generate_ops(equation, shape, **index_sizes)
ops = self._preprocess(ops, shape)
ops = optimizer.optimize(ops, shape)
for op in ops:
value = op.execute(self, value)
return value
|
einshape-main
|
einshape/src/backend.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
|
einshape-main
|
einshape/src/__init__.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Einshape engine."""
import re
import string
from typing import Any, Sequence
from einshape.src import abstract_ops
Indices = str
def _group_dimensions(expr: str) -> Sequence[str]:
"""Splits an expression into its separate grouped dimensions.
An unqualified dimension index is a group by itself.
Parentheses are interpreted as demarcating a sequence of dimension indices
to be grouped into a single dimension.
'1' is an alias for '()', denoting a dimension of size 1 with no indices.
Nested parentheses are not permitted.
Examples:
'ijk' is grouped as ['i', 'j', 'k']
'(mn)hwc' is grouped as ['mn', 'h', 'w', 'c']
'n111' is grouped as ['n', '', '', '']
'n...' is grouped as ['n', '...'], where '...' stands for multiple groups.
Args:
expr: Shape expression to group.
Returns:
List of simple expressions, each consisting solely of dimension
indices, specifying the indices that constitute each grouped dimension.
"""
groups = []
i = 0
while i < len(expr):
if expr[i].isalpha():
# Top-level dimension index is a group by itself.
groups.append(expr[i])
i += 1
elif expr[i] == '1':
# Dimension of size 1 with no indices; equivalent to '()'.
i += 1
groups.append('')
elif expr[i] == '(':
# Sequence of indices to be grouped as a single dimension.
i += 1
group_begin = i
while i < len(expr) and expr[i].isalpha():
i += 1
group_end = i
if not(i < len(expr) and expr[i] == ')'):
raise ValueError('Unclosed parenthesis')
i += 1
groups.append(expr[group_begin:group_end])
elif expr[i:].startswith('...'):
# Wildcard sequence of dimensions.
i += len('...')
if '...' in groups:
raise ValueError('Wildcard "..." may only occur once')
groups.append('...')
else:
raise ValueError(f'Illegal character: {ord(expr[i])}')
return groups
def _expand_wildcard(expr: str, num_wildcard_dims: int) -> str:
"""Replaces a wildcard with the correct number of axes.
Args:
expr: Shape expression containing '...'.
num_wildcard_dims: Number of dimensions captured by the wildcard.
Returns:
Copy of `expr` with the wildcard '...' replaced by indices 'A', 'B', ...
"""
# Introduce indices A, B, C, ... for the wildcard.
if num_wildcard_dims > len(string.ascii_uppercase):
raise ValueError('Too many dimensions')
expanded_wildcard = string.ascii_uppercase[:num_wildcard_dims]
return expr.replace('...', expanded_wildcard)
def generate_ops(
equation: str, input_shape: Sequence[Any], **index_sizes: Any
) -> Sequence[abstract_ops.ShapeOp]:
"""Compiles a Shape Equation into Reshape/Transpose ops.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
input_shape: Shape of the input tensor. May be a mixture of `int`s (for
statically known shape components) and tensors (for dynamic shapes).
**index_sizes: Sizes of indices, where they cannot be inferred
from `input_shape`.
Returns:
Unoptimised list of `Reshape` and `Transpose` instructions that abstractly
specify what concrete tf/np/jax operations should be applied.
"""
# Upper-case indices are reserved for handling '...' wildcards.
if equation != equation.lower():
raise ValueError('Shape Equation may not use upper-case indices')
expression_list = equation.split('->')
if len(expression_list) != 2:
raise ValueError('Shape Equation requires a single "->"')
lhs, rhs = expression_list
# Understand how the input indices are grouped.
lhs_grouped = _group_dimensions(lhs)
if '...' in lhs_grouped:
if len(input_shape) < len(lhs_grouped) - 1:
raise ValueError(
'Input shape must have rank matching LHS. '
f'LHS expects rank >= {len(lhs_grouped) - 1} '
f'but actual input has rank {len(input_shape)}')
num_wildcard_dims = len(input_shape) - (len(lhs_grouped) - 1)
# Update the shape expressions, and parse afresh.
lhs = _expand_wildcard(lhs, num_wildcard_dims)
rhs = _expand_wildcard(rhs, num_wildcard_dims)
lhs_grouped = _group_dimensions(lhs)
else:
if len(input_shape) != len(lhs_grouped):
raise ValueError(
'Input shape must have rank matching LHS. '
f'LHS expects rank {len(lhs_grouped)} '
f'but actual input has rank {len(input_shape)}')
# Determine all indices' sizes, inferred from `input_shape` along with
# with additional hints from `input_sizes`.
inferred_index_sizes = {**index_sizes}
for j, group in enumerate(lhs_grouped):
# There is permitted to be one index in the group without a size specified.
known_size = 1
unknown_index = None
for a in group:
if a in index_sizes:
known_size *= index_sizes[a]
else:
if unknown_index:
raise ValueError(
'All but one of the indices must have their size specified '
f'when ungrouping dimensions. In group "({group})", '
f'"{unknown_index}" and "{a}" have unspecified size.')
unknown_index = a
if unknown_index:
# Infer the size of the remaining index, from the input shape information.
remainder = input_shape[j] % known_size
if isinstance(remainder, int) and remainder != 0:
known_indices = group.replace(unknown_index, '')
raise ValueError(
'Dimension to ungroup is not divisible by its index sizes. '
f'Group "({group})" expects size {input_shape[j]}, but its indices '
f'"{known_indices}" have combined specified size {known_size}.')
inferred_index_sizes[unknown_index] = input_shape[j] // known_size
else:
# All indices are fully specified. Check consistency with input shape,
# provided both are known statically.
discrepancy = input_shape[j] - known_size
if isinstance(discrepancy, int) and discrepancy != 0:
raise ValueError(
'Input shape incompatible with index sizes. '
f'Group "({group})" expects size {input_shape[j]}, '
f'but its indices have combined specified size {known_size}.')
ops = []
# Begin with a reshape op to ungroup everything.
ungrouped = ''.join(lhs_grouped)
ungrouped_shape = [inferred_index_sizes[a] for a in ungrouped]
ops.append(abstract_ops.Reshape(shape=ungrouped_shape))
# Infer the permutation, from the rhs expression with grouping removed.
transposed = ''
broadcast_axis_sizes = {}
for i, a in enumerate(re.sub('[1()]', '', rhs)):
if a in ungrouped:
transposed += a
else:
if a not in inferred_index_sizes:
raise ValueError(f'Broadcast multiples "{a}" must be specified.')
broadcast_axis_sizes[i] = inferred_index_sizes[a]
if transposed != ungrouped:
# Indices in RHS must occur once and only once in LHS, and vice versa.
if any(ungrouped.count(a) != 1 for a in transposed):
raise ValueError('Every index in RHS must occur exactly once in LHS')
if any(rhs.count(a) != 1 for a in ungrouped):
raise ValueError('Every index in LHS must occur exactly once in RHS')
perm = [ungrouped.index(a) for a in transposed]
ops.append(abstract_ops.Transpose(perm=perm))
if broadcast_axis_sizes:
ops.append(abstract_ops.Broadcast(axis_sizes=broadcast_axis_sizes))
# Now regroup as specified by the RHS expression.
rhs_grouped = _group_dimensions(rhs)
def alphabetical(group: Indices) -> Indices:
return ''.join(sorted(group))
group_size_dict = {alphabetical(group): size
for group, size in zip(lhs_grouped, input_shape)}
def group_size(group):
prod = 1
for a in group:
prod *= inferred_index_sizes[a]
# If prod is not a static value, check if the group size can be inferred
# from input_shape by matching LHS groups, e.g.
# einshape("(ij)->(ji)", x, j=n),
# where x.shape is static, but n is not.
if not isinstance(prod, int) and alphabetical(group) in group_size_dict:
return group_size_dict[alphabetical(group)]
return prod
output_shape = [group_size(group) for group in rhs_grouped]
ops.append(abstract_ops.Reshape(shape=output_shape))
# Return the ops in this "ungroup - transpose? - broadcast? - regroup"
# structure.
# Note that in many cases this will be less than optimal; the expectation
# is that a separate optimisation pass will be applied to this abstract
# representation.
return ops
|
einshape-main
|
einshape/src/engine.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Optimises a sequence of abstract `ShapeOp`s."""
from typing import Any, Sequence
from einshape.src import abstract_ops
def _are_contiguous_reshapes(ops):
return len(ops) > 1 and all(
isinstance(op, abstract_ops.Reshape) for op in ops)
def _elide_intermediate_reshapes(ops):
return [op for i, op in enumerate(ops)
if not _are_contiguous_reshapes(ops[i:i+2])]
def _is_static(seq):
return all(isinstance(x, int) for x in seq)
def _is_noop_reshape(op, input_shape):
if isinstance(op, abstract_ops.Reshape) and _is_static(input_shape):
output_shape = op.transform_shape(input_shape)
if _is_static(output_shape):
return list(output_shape) == list(input_shape)
return False
def _elide_noop_reshapes(ops, input_shape):
ops_filtered = []
for op in ops:
if not _is_noop_reshape(op, input_shape):
ops_filtered.append(op)
input_shape = op.transform_shape(input_shape)
return ops_filtered
def optimize(
ops: Sequence[abstract_ops.ShapeOp],
input_shape: Sequence[Any]
) -> Sequence[abstract_ops.ShapeOp]:
"""Returns an optimised copy of the given sequence of shaping ops.
For example, operations that have no effect are dropped.
Args:
ops: Sequence of shaping ops.
input_shape: Shape of tensor going into op sequence. May be a mixture of
`int`s (for statically known shape components) and tensors (for dynamic
shapes).
Returns: Optimised sequence of shaping ops.
"""
ops = _elide_intermediate_reshapes(ops)
ops = _elide_noop_reshapes(ops, input_shape)
return ops
|
einshape-main
|
einshape/src/optimizer.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Abstract reshape/transpose ops for einshape.
See `generate_ops()` in `engine.py`. An einshape expression is compiled into
a sequence of Reshape/Transpose operations in the abstract, represented by
the types defined here. Framework-specific back-ends will interpret these
operations into concrete ops such as `jnp.reshape`.
"""
import abc
from typing import Any, Dict, Sequence, TypeVar
import dataclasses
T = TypeVar('T')
class ShapeOp(metaclass=abc.ABCMeta):
"""Abstract base class for framework-neutral ops arising in einshape."""
@abc.abstractmethod
def transform_shape(self, input_shape: Sequence[Any]) -> Sequence[Any]:
"""Returns output shape of op given input shape."""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def execute(self, backend, x: T) -> T:
"""Evaluates this op on a framework-specific backend.
Args:
backend: Provides framework-specific implementations of all ops.
x: Tensor to reshape/transpose.
Returns:
Reshaped/transposed tensor.
"""
raise NotImplementedError('Should be implemented by subclasses')
@dataclasses.dataclass
class Reshape(ShapeOp):
"""Operation to reshape a tensor without reordering its elements.
Attributes:
shape: New shape for the tensor.
"""
shape: Sequence[Any]
def transform_shape(self, input_shape: Sequence[Any]) -> Sequence[Any]:
del input_shape
return self.shape
def execute(self, backend, x: T) -> T:
return backend.reshape(x, self)
@dataclasses.dataclass
class Transpose(ShapeOp):
"""Operation to reorder the axes of a tensor.
Attributes:
perm: Expresses the permutation to be applied to the axes of a tensor.
For example, `[0, 2, 1]` denotes transposing the inner-most two axes of
a 3D tensor.
"""
perm: Sequence[int]
def transform_shape(self, input_shape: Sequence[Any]) -> Sequence[Any]:
return [input_shape[i] for i in self.perm]
def execute(self, backend, x: T) -> T:
return backend.transpose(x, self)
@dataclasses.dataclass
class Broadcast(ShapeOp):
"""Operation to broadcast (tile) over new axes.
Attributes:
axis_sizes: Sizes of the new axes to insert, keyed by the position of the
axis in the resulting tensor.
For example, applying `{1: 5, 3: 6}` to a tensor of shape [2, 2, 2]
results in a tensor of shape [2, 5, 2, 6, 2].
"""
axis_sizes: Dict[int, Any]
def transform_shape(self, input_shape: Sequence[Any]) -> Sequence[Any]:
output_shape = list(input_shape)
for axis_position, axis_size in sorted(self.axis_sizes.items()):
output_shape.insert(axis_position, axis_size)
return output_shape
def execute(self, backend, x: T) -> T:
return backend.broadcast(x, self)
|
einshape-main
|
einshape/src/abstract_ops.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
|
einshape-main
|
einshape/src/numpy/__init__.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Einshape implementation for JAX."""
from typing import Any, Union
from einshape.src import abstract_ops
from einshape.src import backend
import numpy as np
class _NumpyBackend(backend.Backend[np.ndarray]):
"""Numpy implementation of reshaping ops."""
def reshape(self, x: np.ndarray, op: abstract_ops.Reshape) -> np.ndarray:
return np.reshape(x, op.shape)
def transpose(
self, x: np.ndarray, op: abstract_ops.Transpose)-> np.ndarray:
return np.transpose(x, axes=op.perm)
def broadcast(
self, x: np.ndarray, op: abstract_ops.Broadcast) -> np.ndarray:
desired_shape = op.transform_shape(x.shape)
new_axis_indices = tuple(sorted(op.axis_sizes.keys()))
x = np.expand_dims(x, axis=new_axis_indices)
return np.broadcast_to(x, desired_shape)
def einshape(
equation: str,
value: Union[np.ndarray, Any],
**index_sizes: int
) -> np.ndarray:
"""Reshapes `value` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
value: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred
from `input_shape`.
Returns:
Tensor derived from `value` by reshaping as specified by `equation`.
"""
if not isinstance(value, np.ndarray):
value = np.array(value)
return _NumpyBackend().exec(equation, value, value.shape, **index_sizes)
|
einshape-main
|
einshape/src/numpy/numpy_ops.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
|
einshape-main
|
einshape/src/tensorflow/__init__.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""TensorFlow-specific preprocessing of the Broadcast op."""
from typing import Any, Sequence, TypeVar
import dataclasses
from einshape.src import abstract_ops
T = TypeVar('T')
@dataclasses.dataclass
class Tile(abstract_ops.ShapeOp):
"""Operation to tile over existing axes.
Attributes:
multiples: Multiple by which tile each axis.
"""
multiples: Sequence[Any]
@property
def is_static(self) -> bool:
return all(isinstance(mult, int) for mult in self.multiples)
def transform_shape(self, input_shape: Sequence[Any]) -> Sequence[Any]:
return [mult * size for size, mult in zip(input_shape, self.multiples)]
def execute(self, backend, x: T) -> T:
return backend.tile(x, self)
def preprocess(
ops: Sequence[abstract_ops.ShapeOp], input_shape: Sequence[Any]
) -> Sequence[abstract_ops.ShapeOp]:
"""Returns a copy of the shaping op sequence, adjusted for TensorFlow.
Specifically, a `Broadcast` op are replaced with a `Tile` with `Reshape`s.
Args:
ops: Sequence of shaping ops.
input_shape: Shape of the original inputs.
Returns: Updated sequence of shaping ops.
"""
preproc_ops = []
shape = input_shape
for op in ops:
next_shape = op.transform_shape(shape)
if isinstance(op, abstract_ops.Broadcast):
# Replace the Broadcast op with an equivalent Tile op (plus Reshapes).
# Overall we need to insert a dimension for each broadcast axis.
# However, as far as possible, we tile over "next existing" dimension
# instead, and reshape to the desired shape at the end.
# This gives the greatest opportunity to avoid redundant reshapes.
# Note that multiple new dimensions may share the same "next existing".
# Special case: If the Broadcast op appends one or more dimensions, then
# there is no "next existing" dimension. Here we do need to append one.
if len(next_shape) - 1 in op.axis_sizes:
# Insert trailing '1' dimension to tile.
shape = list(shape) + [1]
preproc_ops.append(abstract_ops.Reshape(shape))
# Tile the original dimensions to achieve the broadcasting.
tile_multiples = [1] * len(shape)
for j, (axis, axis_size) in enumerate(sorted(op.axis_sizes.items())):
original_axis = axis - j
tile_multiples[original_axis] *= axis_size
preproc_ops.append(Tile(tile_multiples))
# Reshape to the desired shape.
preproc_ops.append(abstract_ops.Reshape(next_shape))
else:
preproc_ops.append(op)
shape = next_shape
return preproc_ops
|
einshape-main
|
einshape/src/tensorflow/preprocessing.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Einshape implementation for TensorFlow."""
from typing import Any, Sequence, Union
from einshape.src import abstract_ops
from einshape.src import backend
from einshape.src.tensorflow import preprocessing
import tensorflow as tf
class _TFBackend(backend.Backend[tf.Tensor]):
"""TensorFlow implementation of reshaping ops."""
def reshape(self, x: tf.Tensor, op: abstract_ops.Reshape) -> tf.Tensor:
return tf.reshape(x, op.shape)
def transpose(self, x: tf.Tensor, op: abstract_ops.Transpose) -> tf.Tensor:
return tf.transpose(x, op.perm)
def broadcast(self, x: tf.Tensor, op: abstract_ops.Broadcast) -> tf.Tensor:
# Pre-processing will have removed these.
raise NotImplementedError()
def tile(self, x: tf.Tensor, op: preprocessing.Tile) -> tf.Tensor:
return tf.tile(x, op.multiples)
def _preprocess(
self, ops: Sequence[abstract_ops.ShapeOp], input_shape: Sequence[Any]
) -> Sequence[abstract_ops.ShapeOp]:
return preprocessing.preprocess(ops, input_shape)
def einshape(
equation: str,
x: Union[tf.Tensor, Any],
**index_sizes: Union[int, tf.Tensor],
) -> tf.Tensor:
"""Reshapes `x` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
x: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred
from `input_shape`.
Returns:
Tensor derived from `x` by reshaping as specified by `equation`.
"""
x = tf.convert_to_tensor(x)
# Use components of the static shape of `x` where known, falling back on
# the dynamic shape.
static_shape = x.shape.as_list()
dynamic_shape = tf.shape(x)
known_shape = [
static_shape[i] if static_shape[i] is not None else dynamic_shape[i]
for i in range(x.shape.ndims)]
return _TFBackend().exec(equation, x, known_shape, **index_sizes)
|
einshape-main
|
einshape/src/tensorflow/tf_ops.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
"""Einshape implementation for JAX."""
from typing import Any, Union
from einshape.src import abstract_ops
from einshape.src import backend
from jax import lax
import jax.numpy as jnp
class _JaxBackend(backend.Backend[jnp.ndarray]):
"""Jax implementation of reshaping ops."""
def reshape(self, x: jnp.ndarray, op: abstract_ops.Reshape) -> jnp.ndarray:
return jnp.reshape(x, op.shape)
def transpose(
self, x: jnp.ndarray, op: abstract_ops.Transpose)-> jnp.ndarray:
return jnp.transpose(x, axes=op.perm)
def broadcast(
self, x: jnp.ndarray, op: abstract_ops.Broadcast) -> jnp.ndarray:
shape = op.transform_shape(x.shape)
# For each input dimension, lax needs to know which output dimension it
# corresponds to.
broadcast_dims = [j for j in range(len(shape)) if j not in op.axis_sizes]
return lax.broadcast_in_dim(x, shape, broadcast_dims)
def einshape(
equation: str,
value: Union[jnp.ndarray, Any],
**index_sizes: int
) -> jnp.ndarray:
"""Reshapes `value` according to the given Shape Equation.
Args:
equation: The Shape Equation specifying the index regrouping and reordering.
value: Input tensor, or tensor-like object.
**index_sizes: Sizes of indices, where they cannot be inferred
from `input_shape`.
Returns:
Tensor derived from `value` by reshaping as specified by `equation`.
"""
if not isinstance(value, jnp.ndarray):
value = jnp.array(value)
return _JaxBackend().exec(equation, value, value.shape, **index_sizes)
|
einshape-main
|
einshape/src/jax/jax_ops.py
|
# coding=utf-8
# Copyright 2022 DeepMind Technologies Limited.
#
# 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.
|
einshape-main
|
einshape/src/jax/__init__.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Setup for pip package."""
import os
from setuptools import find_namespace_packages
from setuptools import setup
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def _get_version():
with open(os.path.join(_CURRENT_DIR, 'dm_pix', '__init__.py')) as fp:
for line in fp:
if line.startswith('__version__') and '=' in line:
version = line[line.find('=') + 1:].strip(' \'"\n')
if version:
return version
raise ValueError('`__version__` not defined in `dm_pix/__init__.py`')
def _parse_requirements(requirements_txt_path):
with open(requirements_txt_path) as f:
return [
line.rstrip()
for line in f
if not (line.isspace() or line.startswith('#'))
]
_VERSION = _get_version()
_EXTRA_PACKAGES = {
'jax': ['jax>=0.2.17'],
'jaxlib': ['jaxlib>=0.1.69'],
}
setup(
name='dm_pix',
version=_VERSION,
url='https://github.com/deepmind/dm_pix',
license='Apache 2.0',
author='DeepMind',
description='PIX is an image processing library in JAX, for JAX.',
long_description=open(os.path.join(_CURRENT_DIR, 'README.md')).read(),
long_description_content_type='text/markdown',
author_email='pix-dev@google.com',
# Contained modules and scripts.
packages=find_namespace_packages(exclude=['*_test.py', 'examples']),
install_requires=_parse_requirements(
os.path.join(_CURRENT_DIR, 'requirements.txt')),
extras_require=_EXTRA_PACKAGES,
tests_require=_parse_requirements(
os.path.join(_CURRENT_DIR, 'requirements_tests.txt')),
requires_python='>=3.8',
include_package_data=True,
zip_safe=False,
# PyPI package information.
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Image Processing',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
dm_pix-master
|
setup.py
|
# Copyright 2020 DeepMind Technologies Limited. 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.
"""PIX public APIs."""
from dm_pix._src import augment
from dm_pix._src import color_conversion
from dm_pix._src import depth_and_space
from dm_pix._src import interpolation
from dm_pix._src import metrics
from dm_pix._src import patch
__version__ = "0.4.1"
# Augmentations.
adjust_brightness = augment.adjust_brightness
adjust_contrast = augment.adjust_contrast
adjust_gamma = augment.adjust_gamma
adjust_hue = augment.adjust_hue
adjust_saturation = augment.adjust_saturation
affine_transform = augment.affine_transform
center_crop = augment.center_crop
elastic_deformation = augment.elastic_deformation
flip_left_right = augment.flip_left_right
flip_up_down = augment.flip_up_down
gaussian_blur = augment.gaussian_blur
pad_to_size = augment.pad_to_size
random_brightness = augment.random_brightness
random_contrast = augment.random_contrast
random_crop = augment.random_crop
random_flip_left_right = augment.random_flip_left_right
random_flip_up_down = augment.random_flip_up_down
random_gamma = augment.random_gamma
random_hue = augment.random_hue
random_saturation = augment.random_saturation
resize_with_crop_or_pad = augment.resize_with_crop_or_pad
rotate = augment.rotate
rot90 = augment.rot90
solarize = augment.solarize
# Color conversions.
hsl_to_rgb = color_conversion.hsl_to_rgb
hsv_to_rgb = color_conversion.hsv_to_rgb
rgb_to_hsl = color_conversion.rgb_to_hsl
rgb_to_hsv = color_conversion.rgb_to_hsv
rgb_to_grayscale = color_conversion.rgb_to_grayscale
# Depth and space transformations.
depth_to_space = depth_and_space.depth_to_space
space_to_depth = depth_and_space.space_to_depth
# Interpolation functions.
flat_nd_linear_interpolate = interpolation.flat_nd_linear_interpolate
flat_nd_linear_interpolate_constant = (
interpolation.flat_nd_linear_interpolate_constant)
# Metrics.
mae = metrics.mae
mse = metrics.mse
psnr = metrics.psnr
rmse = metrics.rmse
simse = metrics.simse
ssim = metrics.ssim
# Patch extraction functions.
extract_patches = patch.extract_patches
del augment, color_conversion, depth_and_space, interpolation, metrics, patch
__all__ = (
"adjust_brightness",
"adjust_contrast",
"adjust_gamma",
"adjust_hue",
"adjust_saturation",
"affine_transform",
"center_crop",
"depth_to_space",
"elastic_deformation",
"extract_patches",
"flat_nd_linear_interpolate",
"flat_nd_linear_interpolate_constant",
"flip_left_right",
"flip_up_down",
"gaussian_blur",
"hsl_to_rgb",
"hsv_to_rgb",
"mae",
"mse",
"pad_to_size",
"psnr",
"random_brightness",
"random_contrast",
"random_crop",
"random_flip_left_right",
"random_flip_up_down",
"random_gamma",
"random_hue",
"random_saturation",
"resize_with_crop_or_pad",
"rotate",
"rgb_to_hsl",
"rgb_to_hsv",
"rgb_to_grayscale",
"rmse",
"rot90",
"simse",
"ssim",
"solarize",
"space_to_depth",
)
# _________________________________________
# / Please don't use symbols in `_src` they \
# \ are not part of the PIX public API. /
# -----------------------------------------
# \ ^__^
# \ (oo)\_______
# (__)\ )\/\
# ||----w |
# || ||
#
try:
del _src # pylint: disable=undefined-variable
except NameError:
pass
|
dm_pix-master
|
dm_pix/__init__.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""This module provides image patching functionality."""
from typing import Sequence
import chex
import jax
import jax.numpy as jnp
def extract_patches(
images: chex.Array,
sizes: Sequence[int],
strides: Sequence[int],
rates: Sequence[int],
*,
padding: str = 'VALID',
) -> jnp.ndarray:
"""Extract patches from images.
This function is a wrapper for `jax.lax.conv_general_dilated_patches`
to conform to the same interface as `tf.image.extract_patches`, except for
this function supports arbitrary-dimensional `images`, not only 4D as in
`tf.image.extract_patches`.
The function extracts patches of shape `sizes` from `images` in the same
manner as a convolution with kernel of shape `sizes`, stride equal to
`strides`, and the given `padding` scheme. The patches are stacked in the
channel dimension.
Args:
images: input batch of images of shape [B, H, W, ..., C].
sizes: size of the extracted patches.
Must be [1, size_rows, size_cols, ..., 1].
strides: how far the centers of two consecutive patches are in the images.
Must be [1, stride_rows, stride_cols, ..., 1].
rates: sampling rate. Must be [1, rate_rows, rate_cols, ..., 1]. This is the
input stride, specifying how far two consecutive patch samples are in the
input. Equivalent to extracting patches with `patch_sizes_eff =
patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling
them spatially by a factor of rates. This is equivalent to rate in dilated
(a.k.a. Atrous) convolutions.
padding: the type of padding algorithm to use.
Returns:
Tensor of shape
[B, patch_rows, patch_cols, ..., size_rows * size_cols * ... * C].
"""
ndim = images.ndim
if len(sizes) != ndim or sizes[0] != 1 or sizes[-1] != 1:
raise ValueError('Input `sizes` must be [1, size_rows, size_cols, ..., 1] '
f'and same length as `images.ndim` {ndim}. Got {sizes}.')
if len(strides) != ndim or strides[0] != 1 or strides[-1] != 1:
raise ValueError('Input `strides` must be [1, size_rows, size_cols, ..., 1]'
f'and same length as `images.ndim` {ndim}. Got {strides}.')
if len(rates) != ndim or rates[0] != 1 or rates[-1] != 1:
raise ValueError('Input `rates` must be [1, size_rows, size_cols, ..., 1] '
f'and same length as `images.ndim` {ndim}. Got {rates}.')
channels = images.shape[-1]
lhs_spec = out_spec = (0, ndim - 1) + tuple(range(1, ndim - 1))
rhs_spec = tuple(range(ndim))
patches = jax.lax.conv_general_dilated_patches(
lhs=images,
filter_shape=sizes[1:-1],
window_strides=strides[1:-1],
padding=padding,
rhs_dilation=rates[1:-1],
dimension_numbers=jax.lax.ConvDimensionNumbers(
lhs_spec, rhs_spec, out_spec)
)
# `conv_general_dilated_patches` returns `patches` in channel-major order,
# rearrange to match interface of `tf.image.extract_patches`.
patches = jnp.reshape(patches, patches.shape[:-1] + (channels, -1))
patches = jnp.moveaxis(patches, -2, -1)
patches = jnp.reshape(patches, patches.shape[:-2] + (-1,))
return patches
|
dm_pix-master
|
dm_pix/_src/patch.py
|
# Copyright 2020 DeepMind Technologies Limited. 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_pix._src.depth_and_space."""
from absl.testing import parameterized
import chex
from dm_pix._src import depth_and_space
import numpy as np
import tensorflow as tf
class DepthAndSpaceTest(chex.TestCase, parameterized.TestCase):
@chex.all_variants
@parameterized.parameters(([1, 1, 1, 9], 3), ([2, 2, 2, 8], 2))
def test_depth_to_space(self, input_shape, block_size):
depth_to_space_fn = self.variant(
depth_and_space.depth_to_space, static_argnums=1)
inputs = np.arange(np.prod(input_shape), dtype=np.int32)
inputs = np.reshape(inputs, input_shape)
output_tf = tf.nn.depth_to_space(inputs, block_size).numpy()
output_jax = depth_to_space_fn(inputs, block_size)
np.testing.assert_array_equal(output_tf, output_jax)
@chex.all_variants
@parameterized.parameters(([1, 3, 3, 1], 3), ([2, 4, 4, 2], 2))
def test_space_to_depth(self, input_shape, block_size):
space_to_depth_fn = self.variant(
depth_and_space.space_to_depth, static_argnums=1)
inputs = np.arange(np.prod(input_shape), dtype=np.int32)
inputs = np.reshape(inputs, input_shape)
output_tf = tf.nn.space_to_depth(inputs, block_size).numpy()
output_jax = space_to_depth_fn(inputs, block_size)
np.testing.assert_array_equal(output_tf, output_jax)
if __name__ == "__main__":
tf.test.main()
|
dm_pix-master
|
dm_pix/_src/depth_and_space_test.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Functions to compare image pairs.
All functions expect float-encoded images, with values in [0, 1], with NHWC
shapes. Each image metric function returns a scalar for each image pair.
"""
from typing import Callable, Optional
import chex
import jax
import jax.numpy as jnp
def mae(a: chex.Array, b: chex.Array) -> chex.Numeric:
"""Returns the Mean Absolute Error between `a` and `b`.
Args:
a: First image (or set of images).
b: Second image (or set of images).
Returns:
MAE between `a` and `b`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
return jnp.abs(a - b).mean(axis=(-3, -2, -1))
def mse(a: chex.Array, b: chex.Array) -> chex.Numeric:
"""Returns the Mean Squared Error between `a` and `b`.
Args:
a: First image (or set of images).
b: Second image (or set of images).
Returns:
MSE between `a` and `b`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
return jnp.square(a - b).mean(axis=(-3, -2, -1))
def psnr(a: chex.Array, b: chex.Array) -> chex.Numeric:
"""Returns the Peak Signal-to-Noise Ratio between `a` and `b`.
Assumes that the dynamic range of the images (the difference between the
maximum and the minimum allowed values) is 1.0.
Args:
a: First image (or set of images).
b: Second image (or set of images).
Returns:
PSNR in decibels between `a` and `b`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
return -10.0 * jnp.log(mse(a, b)) / jnp.log(10.0)
def rmse(a: chex.Array, b: chex.Array) -> chex.Numeric:
"""Returns the Root Mean Squared Error between `a` and `b`.
Args:
a: First image (or set of images).
b: Second image (or set of images).
Returns:
RMSE between `a` and `b`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
return jnp.sqrt(mse(a, b))
def simse(a: chex.Array, b: chex.Array) -> chex.Numeric:
"""Returns the Scale-Invariant Mean Squared Error between `a` and `b`.
For each image pair, a scaling factor for `b` is computed as the solution to
the following problem:
min_alpha || vec(a) - alpha * vec(b) ||_2^2
where `a` and `b` are flattened, i.e., vec(x) = np.flatten(x). The MSE between
the optimally scaled `b` and `a` is returned: mse(a, alpha*b).
This is a scale-invariant metric, so for example: simse(x, y) == sims(x, y*5).
This metric was used in "Shape, Illumination, and Reflectance from Shading" by
Barron and Malik, TPAMI, '15.
Args:
a: First image (or set of images).
b: Second image (or set of images).
Returns:
SIMSE between `a` and `b`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
a_dot_b = (a * b).sum(axis=(-3, -2, -1), keepdims=True)
b_dot_b = (b * b).sum(axis=(-3, -2, -1), keepdims=True)
alpha = a_dot_b / b_dot_b
return mse(a, alpha * b)
def ssim(
a: chex.Array,
b: chex.Array,
*,
max_val: float = 1.0,
filter_size: int = 11,
filter_sigma: float = 1.5,
k1: float = 0.01,
k2: float = 0.03,
return_map: bool = False,
precision=jax.lax.Precision.HIGHEST,
filter_fn: Optional[Callable[[chex.Array], chex.Array]] = None,
) -> chex.Numeric:
"""Computes the structural similarity index (SSIM) between image pairs.
This function is based on the standard SSIM implementation from:
Z. Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli,
"Image quality assessment: from error visibility to structural similarity",
in IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, 2004.
This function was modeled after tf.image.ssim, and should produce comparable
output.
Note: the true SSIM is only defined on grayscale. This function does not
perform any colorspace transform. If the input is in a color space, then it
will compute the average SSIM.
Args:
a: First image (or set of images).
b: Second image (or set of images).
max_val: The maximum magnitude that `a` or `b` can have.
filter_size: Window size (>= 1). Image dims must be at least this small.
filter_sigma: The bandwidth of the Gaussian used for filtering (> 0.).
k1: One of the SSIM dampening parameters (> 0.).
k2: One of the SSIM dampening parameters (> 0.).
return_map: If True, will cause the per-pixel SSIM "map" to be returned.
precision: The numerical precision to use when performing convolution.
filter_fn: An optional argument for overriding the filter function used by
SSIM, which would otherwise be a 2D Gaussian blur specified by filter_size
and filter_sigma.
Returns:
Each image's mean SSIM, or a tensor of individual values if `return_map`.
"""
chex.assert_rank([a, b], {3, 4})
chex.assert_type([a, b], float)
chex.assert_equal_shape([a, b])
if filter_fn is None:
# Construct a 1D Gaussian blur filter.
hw = filter_size // 2
shift = (2 * hw - filter_size + 1) / 2
f_i = ((jnp.arange(filter_size) - hw + shift) / filter_sigma) ** 2
filt = jnp.exp(-0.5 * f_i)
filt /= jnp.sum(filt)
# Construct a 1D convolution.
def filter_fn_1(z):
return jnp.convolve(z, filt, mode="valid", precision=precision)
filter_fn_vmap = jax.vmap(filter_fn_1)
# Apply the vectorized filter along the y axis.
def filter_fn_y(z):
z_flat = jnp.moveaxis(z, -3, -1).reshape((-1, z.shape[-3]))
z_filtered_shape = ((z.shape[-4],) if z.ndim == 4 else ()) + (
z.shape[-2],
z.shape[-1],
-1,
)
z_filtered = jnp.moveaxis(
filter_fn_vmap(z_flat).reshape(z_filtered_shape), -1, -3
)
return z_filtered
# Apply the vectorized filter along the x axis.
def filter_fn_x(z):
z_flat = jnp.moveaxis(z, -2, -1).reshape((-1, z.shape[-2]))
z_filtered_shape = ((z.shape[-4],) if z.ndim == 4 else ()) + (
z.shape[-3],
z.shape[-1],
-1,
)
z_filtered = jnp.moveaxis(
filter_fn_vmap(z_flat).reshape(z_filtered_shape), -1, -2
)
return z_filtered
# Apply the blur in both x and y.
filter_fn = lambda z: filter_fn_y(filter_fn_x(z))
mu0 = filter_fn(a)
mu1 = filter_fn(b)
mu00 = mu0 * mu0
mu11 = mu1 * mu1
mu01 = mu0 * mu1
sigma00 = filter_fn(a**2) - mu00
sigma11 = filter_fn(b**2) - mu11
sigma01 = filter_fn(a * b) - mu01
# Clip the variances and covariances to valid values.
# Variance must be non-negative:
epsilon = jnp.finfo(jnp.float32).eps ** 2
sigma00 = jnp.maximum(epsilon, sigma00)
sigma11 = jnp.maximum(epsilon, sigma11)
sigma01 = jnp.sign(sigma01) * jnp.minimum(
jnp.sqrt(sigma00 * sigma11), jnp.abs(sigma01)
)
c1 = (k1 * max_val) ** 2
c2 = (k2 * max_val) ** 2
numer = (2 * mu01 + c1) * (2 * sigma01 + c2)
denom = (mu00 + mu11 + c1) * (sigma00 + sigma11 + c2)
ssim_map = numer / denom
ssim_value = jnp.mean(ssim_map, list(range(-3, 0)))
return ssim_map if return_map else ssim_value
|
dm_pix-master
|
dm_pix/_src/metrics.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Testing utilities for PIX."""
import inspect
import types
from typing import Sequence, Tuple
def get_public_functions(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(function_name, function)` for all functions of `root_module`."""
fns = []
for name in dir(root_module):
o = getattr(root_module, name)
if inspect.isfunction(o):
fns.append((name, o))
return fns
def get_public_symbols(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(symbol_name, symbol)` for all symbols of `root_module`."""
fns = []
for name in getattr(root_module, '__all__'):
o = getattr(root_module, name)
fns.append((name, o))
return fns
|
dm_pix-master
|
dm_pix/_src/test_utils.py
|
# Copyright 2020 DeepMind Technologies Limited. 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.
"""This module provides functions for rearranging blocks of spatial data."""
import chex
import jax
import jax.numpy as jnp
def depth_to_space(inputs: chex.Array, block_size: int) -> chex.Array:
"""Rearranges data from depth into blocks of spatial data.
Args:
inputs: Array of shape [H, W, C] or [N, H, W, C]. The number of channels
(depth dimension) must be divisible by block_size ** 2.
block_size: Size of spatial blocks >= 2.
Returns:
For inputs of shape [H, W, C] the output is a reshaped array of shape
[H * B, W * B, C / (B ** 2)], where B is `block_size`. If there's a leading
batch dimension, it stays unchanged.
"""
chex.assert_rank(inputs, {3, 4})
if inputs.ndim == 4: # Batched case.
return jax.vmap(depth_to_space, in_axes=(0, None))(inputs, block_size)
height, width, depth = inputs.shape
if depth % (block_size**2) != 0:
raise ValueError(
f'Number of channels {depth} must be divisible by block_size ** 2 {block_size**2}.'
)
new_depth = depth // (block_size**2)
outputs = jnp.reshape(inputs,
[height, width, block_size, block_size, new_depth])
outputs = jnp.transpose(outputs, [0, 2, 1, 3, 4])
outputs = jnp.reshape(outputs,
[height * block_size, width * block_size, new_depth])
return outputs
def space_to_depth(inputs: chex.Array, block_size: int) -> chex.Array:
"""Rearranges data from blocks of spatial data into depth.
This is the reverse of depth_to_space.
Args:
inputs: Array of shape [H, W, C] or [N, H, W, C]. The height and width must
each be divisible by block_size.
block_size: Size of spatial blocks >= 2.
Returns:
For inputs of shape [H, W, C] the output is a reshaped array of shape
[H / B, W / B, C * (B ** 2)], where B is `block_size`. If there's a leading
batch dimension, it stays unchanged.
"""
chex.assert_rank(inputs, {3, 4})
if inputs.ndim == 4: # Batched case.
return jax.vmap(space_to_depth, in_axes=(0, None))(inputs, block_size)
height, width, depth = inputs.shape
if height % block_size != 0:
raise ValueError(
f'Height {height} must be divisible by block size {block_size}.')
if width % block_size != 0:
raise ValueError(
f'Width {width} must be divisible by block size {block_size}.')
new_depth = depth * (block_size**2)
new_height = height // block_size
new_width = width // block_size
outputs = jnp.reshape(inputs,
[new_height, block_size, new_width, block_size, depth])
outputs = jnp.transpose(outputs, [0, 2, 1, 3, 4])
outputs = jnp.reshape(outputs, [new_height, new_width, new_depth])
return outputs
|
dm_pix-master
|
dm_pix/_src/depth_and_space.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""This module provides functions for interpolating ND images.
All functions expect float-encoded images, with values in [0, 1].
"""
import itertools
from typing import Optional, Sequence, Tuple
import chex
from jax import lax
import jax.numpy as jnp
def _round_half_away_from_zero(a: chex.Array) -> chex.Array:
return a if jnp.issubdtype(a.dtype, jnp.integer) else lax.round(a)
def _make_linear_interpolation_indices_nd(
coordinates: chex.Array,
shape: chex.Array,
) -> Tuple[chex.Array, chex.Array, chex.Array]:
"""Creates linear interpolation indices and weights for ND coordinates.
Args:
coordinates: An array of shape (N, M_coordinates).
shape: The shape of the ND volume, e.g. if N=3 shape=(dim_z, dim_y, dim_x).
Returns:
The lower and upper indices of `coordinates` and their weights.
"""
lower = jnp.floor(coordinates).astype(jnp.int32)
upper = jnp.ceil(coordinates).astype(jnp.int32)
weights = coordinates - lower
# Expand dimensions for `shape` to allow broadcasting it to every coordinate.
# Expansion size is equal to the number of dimensions of `coordinates` - 1.
shape = shape.reshape(shape.shape + (1,) * (coordinates.ndim - 1))
lower = jnp.clip(lower, 0, shape - 1)
upper = jnp.clip(upper, 0, shape - 1)
return lower, upper, weights
def _make_linear_interpolation_indices_flat_nd(
coordinates: chex.Array,
shape: Sequence[int],
) -> Tuple[chex.Array, chex.Array]:
"""Creates flat linear interpolation indices and weights for ND coordinates.
Args:
coordinates: An array of shape (N, M_coordinates).
shape: The shape of the ND volume, e.g. if N=3 shape=(dim_z, dim_y, dim_x).
Returns:
The indices into the flattened input and their weights.
"""
coordinates = jnp.asarray(coordinates)
shape = jnp.asarray(shape)
if shape.shape[0] != coordinates.shape[0]:
raise ValueError(
(f'{coordinates.shape[0]}-dimensional coordinates provided for '
f'{shape.shape[0]}-dimensional input'))
lower_nd, upper_nd, weights_nd = _make_linear_interpolation_indices_nd(
coordinates, shape)
# Here we want to translate e.g. a 3D-disposed indices to linear ones, since
# we have to index on the flattened source, so:
# flat_idx = shape[1] * shape[2] * z_idx + shape[2] * y_idx + x_idx
# The `strides` of a `shape`-sized array tell us how many elements we have to
# skip to move to the next position along a certain axis in that array.
# For example, for a shape=(5,4,2) we have to skip 1 value to move to the next
# column (3rd axis), 2 values to move to get to the same position in the next
# row (2nd axis) and 4*2=8 values to move to get to the same position on the
# 1st axis.
strides = jnp.concatenate([jnp.cumprod(shape[:0:-1])[::-1], jnp.array([1])])
# Array of 2^n rows where the ith row is the binary representation of i.
binary_array = jnp.array(
list(itertools.product([0, 1], repeat=shape.shape[0])))
# Expand dimensions to allow broadcasting `strides` and `binary_array` to
# every coordinate.
# Expansion size is equal to the number of dimensions of `coordinates` - 1.
strides = strides.reshape(strides.shape + (1,) * (coordinates.ndim - 1))
binary_array = binary_array.reshape(binary_array.shape + (1,) *
(coordinates.ndim - 1))
lower_1d = lower_nd * strides
upper_1d = upper_nd * strides
point_weights = []
point_indices = []
for r in binary_array:
# `point_indices` is defined as:
# `jnp.matmul(binary_array, upper) + jnp.matmul(1-binary_array, lower)`
# however, to date, that implementation turns out to be slower than the
# equivalent following one.
point_indices.append(jnp.sum(upper_1d * r + lower_1d * (1 - r), axis=0))
point_weights.append(
jnp.prod(r * weights_nd + (1 - r) * (1 - weights_nd), axis=0))
return jnp.stack(point_indices, axis=0), jnp.stack(point_weights, axis=0)
def _linear_interpolate_using_indices_nd(
volume: chex.Array,
indices: chex.Array,
weights: chex.Array,
) -> chex.Array:
"""Interpolates linearly on `volume` using `indices` and `weights`."""
target = jnp.sum(weights * volume[indices], axis=0)
if jnp.issubdtype(volume.dtype, jnp.integer):
target = _round_half_away_from_zero(target)
return target.astype(volume.dtype)
def flat_nd_linear_interpolate(
volume: chex.Array,
coordinates: chex.Array,
*,
unflattened_vol_shape: Optional[Sequence[int]] = None,
) -> chex.Array:
"""Maps the input ND volume to coordinates by linear interpolation.
Args:
volume: A volume (flat if `unflattened_vol_shape` is provided) where to
query coordinates.
coordinates: An array of shape (N, M_coordinates). Where M_coordinates can
be M-dimensional. If M_coordinates == 1, then `coordinates.shape` can
simply be (N,), e.g. if N=3 and M_coordinates=1, this has the form (z, y,
x).
unflattened_vol_shape: The shape of the `volume` before flattening. If
provided, then `volume` must be pre-flattened.
Returns:
The resulting mapped coordinates. The shape of the output is `M_coordinates`
(derived from `coordinates` by dropping the first axis).
"""
if unflattened_vol_shape is None:
unflattened_vol_shape = volume.shape
volume = volume.flatten()
indices, weights = _make_linear_interpolation_indices_flat_nd(
coordinates, shape=unflattened_vol_shape)
return _linear_interpolate_using_indices_nd(
jnp.asarray(volume), indices, weights)
def flat_nd_linear_interpolate_constant(
volume: chex.Array,
coordinates: chex.Array,
*,
cval: Optional[float] = 0.,
unflattened_vol_shape: Optional[Sequence[int]] = None,
) -> chex.Array:
"""Maps volume by interpolation and returns a constant outside boundaries.
Maps the input ND volume to coordinates by linear interpolation, but returns
a constant value if the coordinates fall outside the volume boundary.
Args:
volume: A volume (flat if `unflattened_vol_shape` is provided) where to
query coordinates.
coordinates: An array of shape (N, M_coordinates). Where M_coordinates can
be M-dimensional. If M_coordinates == 1, then `coordinates.shape` can
simply be (N,), e.g. if N=3 and M_coordinates=1, this has the form (z, y,
x).
cval: A constant value to map to for coordinates that fall outside
the volume boundaries.
unflattened_vol_shape: The shape of the `volume` before flattening. If
provided, then `volume` must be pre-flattened.
Returns:
The resulting mapped coordinates. The shape of the output is `M_coordinates`
(derived from `coordinates` by dropping the first axis).
"""
volume_shape = volume.shape
if unflattened_vol_shape is not None:
volume_shape = unflattened_vol_shape
# Initialize considering all coordinates within the volume and loop through
# boundaries.
is_in_bounds = jnp.full(coordinates.shape[1:], True)
for dim, dim_size in enumerate(volume_shape):
is_in_bounds = jnp.logical_and(is_in_bounds, coordinates[dim] >= 0)
is_in_bounds = jnp.logical_and(is_in_bounds,
coordinates[dim] <= dim_size - 1)
return flat_nd_linear_interpolate(
volume,
coordinates,
unflattened_vol_shape=unflattened_vol_shape
) * is_in_bounds + (1. - is_in_bounds) * cval
|
dm_pix-master
|
dm_pix/_src/interpolation.py
|
# Copyright 2020 DeepMind Technologies Limited. 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_pix._src.color_conversion."""
import colorsys
import enum
import functools
from typing import Sequence
from absl.testing import parameterized
import chex
from dm_pix._src import augment
from dm_pix._src import color_conversion
import jax
import jax.numpy as jnp
import numpy as np
import tensorflow as tf
_NUM_IMAGES = 100
_IMG_SHAPE = (16, 16, 3)
_FLAT_IMG_SHAPE = (_IMG_SHAPE[0] * _IMG_SHAPE[1], _IMG_SHAPE[2])
_QUANTISATIONS = (None, 16, 2)
@enum.unique
class TestImages(enum.Enum):
"""Enum classes representing random images with (low, high, num_images)."""
RAND_FLOATS_IN_RANGE = (0., 1., _NUM_IMAGES)
RAND_FLOATS_OUT_OF_RANGE = (-0.5, 1.5, _NUM_IMAGES)
ALL_ONES = (1., 1., 1)
ALL_ZEROS = (0., 0., 1)
def generate_test_images(
low: float,
high: float,
num_images: int,
) -> Sequence[chex.Array]:
images = np.random.uniform(
low=low,
high=high,
size=(num_images,) + _IMG_SHAPE,
)
return list(images.astype(np.float32))
class ColorConversionTest(
chex.TestCase,
parameterized.TestCase,
):
@chex.all_variants
@parameterized.product(
test_images=[
TestImages.RAND_FLOATS_IN_RANGE,
TestImages.RAND_FLOATS_OUT_OF_RANGE,
TestImages.ALL_ONES,
TestImages.ALL_ZEROS,
],
channel_last=[True, False],
)
def test_hsv_to_rgb(self, test_images, channel_last):
channel_axis = -1 if channel_last else -3
hsv_to_rgb = self.variant(
functools.partial(
color_conversion.hsv_to_rgb, channel_axis=channel_axis))
for hsv in generate_test_images(*test_images.value):
hsv = np.clip(hsv, 0., 1.)
rgb_tf = tf.image.hsv_to_rgb(hsv).numpy()
if not channel_last:
hsv = hsv.swapaxes(-1, -3)
rgb_jax = hsv_to_rgb(hsv)
if not channel_last:
rgb_jax = rgb_jax.swapaxes(-1, -3)
np.testing.assert_allclose(rgb_jax, rgb_tf, rtol=1e-3, atol=1e-3)
# Check that taking gradients through the conversion function does not
# create NaNs, which might happen due to some division by zero.
# We're only testing the gradients of a single image rather than all test
# images to avoid making the tests run too slow.
jacobian = jax.jacrev(hsv_to_rgb)(hsv)
self.assertFalse(jnp.isnan(jacobian).any(), "NaNs in HSV to RGB gradients")
@chex.all_variants
@parameterized.product(
test_images=[
TestImages.RAND_FLOATS_IN_RANGE,
TestImages.RAND_FLOATS_OUT_OF_RANGE,
TestImages.ALL_ONES,
TestImages.ALL_ZEROS,
],
channel_last=[True, False],
)
def test_rgb_to_hsv(self, test_images, channel_last):
channel_axis = -1 if channel_last else -3
rgb_to_hsv = self.variant(
functools.partial(
color_conversion.rgb_to_hsv, channel_axis=channel_axis))
for rgb in generate_test_images(*test_images.value):
hsv_tf = tf.image.rgb_to_hsv(rgb).numpy()
if not channel_last:
rgb = rgb.swapaxes(-1, -3)
hsv_jax = rgb_to_hsv(rgb)
if not channel_last:
hsv_jax = hsv_jax.swapaxes(-1, -3)
np.testing.assert_allclose(hsv_jax, hsv_tf, rtol=1e-3, atol=1e-3)
# Check that taking gradients through the conversion function does not
# create NaNs, which might happen due to some division by zero.
# We're only testing the gradients of a single image rather than all test
# images to avoid making the tests run too slow.
rgb = generate_test_images(*test_images.value)[0]
if not channel_last:
rgb = rgb.swapaxes(-1, -3)
jacobian = jax.jacrev(rgb_to_hsv)(rgb)
self.assertFalse(jnp.isnan(jacobian).any(), "NaNs in RGB to HSV gradients")
def test_rgb_to_hsv_subnormals(self):
# Create a tensor that will contain some subnormal floating points.
img = jnp.zeros((5, 5, 3))
img = img.at[2, 2, 1].set(1)
blurred_img = augment.gaussian_blur(img, sigma=0.08, kernel_size=5.)
fun = lambda x: color_conversion.rgb_to_hsv(x).sum()
grad_fun = jax.grad(fun)
grad = grad_fun(blurred_img)
self.assertFalse(jnp.isnan(grad).any(), "NaNs in RGB to HSV gradients")
@chex.all_variants
def test_vmap_roundtrip(self):
images = generate_test_images(*TestImages.RAND_FLOATS_IN_RANGE.value)
rgb_init = np.stack(images, axis=0)
rgb_to_hsv = self.variant(jax.vmap(color_conversion.rgb_to_hsv))
hsv_to_rgb = self.variant(jax.vmap(color_conversion.hsv_to_rgb))
hsv = rgb_to_hsv(rgb_init)
rgb_final = hsv_to_rgb(hsv)
np.testing.assert_allclose(rgb_init, rgb_final, rtol=1e-3, atol=1e-3)
def test_jit_roundtrip(self):
images = generate_test_images(*TestImages.RAND_FLOATS_IN_RANGE.value)
rgb_init = np.stack(images, axis=0)
hsv = jax.jit(color_conversion.rgb_to_hsv)(rgb_init)
rgb_final = jax.jit(color_conversion.hsv_to_rgb)(hsv)
np.testing.assert_allclose(rgb_init, rgb_final, rtol=1e-3, atol=1e-3)
@chex.all_variants
@parameterized.named_parameters(
("black", 0, 0),
("gray", 0.000001, 0.999999),
("white", 1, 1),
)
def test_rgb_to_hsl_golden(self, minval, maxval):
"""Compare against colorsys.rgb_to_hls as a golden implementation."""
key = jax.random.PRNGKey(0)
for quantization in (None, 16, 2):
key_rand_uni, key = jax.random.split(key)
image_rgb = jax.random.uniform(
key=key_rand_uni,
shape=_FLAT_IMG_SHAPE,
dtype=np.float32,
minval=minval,
maxval=maxval,
)
# Use quantization to probe the corners of the color cube.
if quantization is not None:
image_rgb = jnp.round(image_rgb * quantization) / quantization
hsl_true = np.zeros_like(image_rgb)
for i in range(image_rgb.shape[0]):
h, l, s = colorsys.rgb_to_hls(*image_rgb[i, :])
hsl_true[i, :] = [h, s, l]
image_rgb = np.reshape(image_rgb, _IMG_SHAPE)
hsl_true = np.reshape(hsl_true, _IMG_SHAPE)
rgb_to_hsl = self.variant(color_conversion.rgb_to_hsl)
np.testing.assert_allclose(
rgb_to_hsl(image_rgb), hsl_true, atol=1E-5, rtol=1E-5)
@chex.all_variants
@parameterized.named_parameters(
("black", 0, 0.000001),
("white", 0.999999, 1),
)
def test_rgb_to_hsl_stable(self, minval, maxval):
"""rgb_to_hsl's output near the black+white corners should be in [0, 1]."""
key_rand_uni = jax.random.PRNGKey(0)
image_rgb = jax.random.uniform(
key=key_rand_uni,
shape=_FLAT_IMG_SHAPE,
dtype=np.float32,
minval=minval,
maxval=maxval,
)
rgb_to_hsl = self.variant(color_conversion.rgb_to_hsl)
hsl = rgb_to_hsl(image_rgb)
self.assertTrue(jnp.all(jnp.isfinite(hsl)))
self.assertLessEqual(jnp.max(hsl), 1.)
self.assertGreaterEqual(jnp.min(hsl), 0.)
@chex.all_variants
def test_hsl_to_rgb_golden(self):
"""Compare against colorsys.rgb_to_hls as a golden implementation."""
key = jax.random.PRNGKey(0)
for quantization in _QUANTISATIONS:
key_rand_uni, key = jax.random.split(key)
image_hsl = (
jax.random.uniform(key_rand_uni, _FLAT_IMG_SHAPE).astype(np.float32))
# Use quantization to probe the corners of the color cube.
if quantization is not None:
image_hsl = jnp.round(image_hsl * quantization) / quantization
rgb_true = np.zeros_like(image_hsl)
for i in range(image_hsl.shape[0]):
h, s, l = image_hsl[i, :]
rgb_true[i, :] = colorsys.hls_to_rgb(h, l, s)
rgb_true = np.reshape(rgb_true, _IMG_SHAPE)
image_hsl = np.reshape(image_hsl, _IMG_SHAPE)
hsl_to_rgb = self.variant(color_conversion.hsl_to_rgb)
np.testing.assert_allclose(
hsl_to_rgb(image_hsl), rgb_true, atol=1E-5, rtol=1E-5)
@chex.all_variants
def test_hsl_rgb_roundtrip(self):
key = jax.random.PRNGKey(0)
for quantization in _QUANTISATIONS:
key_rand_uni, key = jax.random.split(key)
image_rgb = jax.random.uniform(key_rand_uni, _IMG_SHAPE)
# Use quantization to probe the corners of the color cube.
if quantization is not None:
image_rgb = jnp.round(image_rgb * quantization) / quantization
rgb_to_hsl = self.variant(color_conversion.rgb_to_hsl)
hsl_to_rgb = self.variant(color_conversion.hsl_to_rgb)
np.testing.assert_allclose(
image_rgb, hsl_to_rgb(rgb_to_hsl(image_rgb)), atol=1E-5, rtol=1E-5)
@chex.all_variants
@parameterized.product(
test_images=[
TestImages.RAND_FLOATS_IN_RANGE,
TestImages.RAND_FLOATS_OUT_OF_RANGE,
TestImages.ALL_ONES,
TestImages.ALL_ZEROS,
],
keep_dims=[True, False],
channel_last=[True, False],
)
def test_grayscale(self, test_images, keep_dims, channel_last):
channel_axis = -1 if channel_last else -3
rgb_to_grayscale = self.variant(
functools.partial(
color_conversion.rgb_to_grayscale,
keep_dims=keep_dims,
channel_axis=channel_axis))
for rgb in generate_test_images(*test_images.value):
grayscale_tf = tf.image.rgb_to_grayscale(rgb).numpy()
if not channel_last:
rgb = rgb.swapaxes(-1, -3)
grayscale_jax = rgb_to_grayscale(rgb)
if not channel_last:
grayscale_jax = grayscale_jax.swapaxes(-1, -3)
if keep_dims:
for i in range(_IMG_SHAPE[-1]):
np.testing.assert_allclose(
grayscale_jax[..., [i]], grayscale_tf, atol=1E-5, rtol=1E-5)
else:
np.testing.assert_allclose(
grayscale_jax, grayscale_tf, atol=1E-5, rtol=1E-5)
if __name__ == "__main__":
tf.test.main()
|
dm_pix-master
|
dm_pix/_src/color_conversion_test.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
|
dm_pix-master
|
dm_pix/_src/__init__.py
|
# Copyright 2020 DeepMind Technologies Limited. 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.
"""This module provides functions to convert color spaces.
All functions expect float-encoded images, with values in [0, 1].
"""
from typing import Tuple
import chex
import jax.numpy as jnp
def split_channels(
image: chex.Array,
channel_axis: int,
) -> Tuple[chex.Array, chex.Array, chex.Array]:
"""Splits an image into its channels.
Args:
image: an image, with float values in range [0, 1]. Behavior outside of
these bounds is not guaranteed.
channel_axis: the channel axis. image should have 3 layers along this axis.
Returns:
A tuple of 3 images, with float values in range [0, 1], stacked
along channel_axis.
"""
chex.assert_axis_dimension(image, axis=channel_axis, expected=3)
split_axes = jnp.split(image, 3, axis=channel_axis)
return tuple(map(lambda x: jnp.squeeze(x, axis=channel_axis), split_axes))
def rgb_to_hsv(
image_rgb: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Converts an image from RGB to HSV.
Args:
image_rgb: an RGB image, with float values in range [0, 1]. Behavior outside
of these bounds is not guaranteed.
channel_axis: the channel axis. image_rgb should have 3 layers along this
axis.
Returns:
An HSV image, with float values in range [0, 1], stacked along channel_axis.
"""
eps = jnp.finfo(image_rgb.dtype).eps
image_rgb = jnp.where(jnp.abs(image_rgb) < eps, 0., image_rgb)
red, green, blue = split_channels(image_rgb, channel_axis)
return jnp.stack(
rgb_planes_to_hsv_planes(red, green, blue), axis=channel_axis)
def hsv_to_rgb(
image_hsv: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Converts an image from HSV to RGB.
Args:
image_hsv: an HSV image, with float values in range [0, 1]. Behavior outside
of these bounds is not guaranteed.
channel_axis: the channel axis. image_hsv should have 3 layers along this
axis.
Returns:
An RGB image, with float values in range [0, 1], stacked along channel_axis.
"""
hue, saturation, value = split_channels(image_hsv, channel_axis)
return jnp.stack(
hsv_planes_to_rgb_planes(hue, saturation, value), axis=channel_axis)
def rgb_planes_to_hsv_planes(
red: chex.Array,
green: chex.Array,
blue: chex.Array,
) -> Tuple[chex.Array, chex.Array, chex.Array]:
"""Converts red, green, blue color planes to hue, saturation, value planes.
All planes should have the same shape, with float values in range [0, 1].
Behavior outside of these bounds is not guaranteed.
Reference implementation: http://shortn/_DjPmiAOWSQ
Args:
red: the red color plane.
green: the green color plane.
blue: the blue color plane.
Returns:
A tuple of (hue, saturation, value) planes, as float values in range [0, 1].
"""
value = jnp.maximum(jnp.maximum(red, green), blue)
minimum = jnp.minimum(jnp.minimum(red, green), blue)
range_ = value - minimum
# Avoid divisions by zeros by using safe values for the division. Even if the
# results are masked by jnp.where and the function would give correct results,
# this would produce NaNs when computing gradients.
safe_value = jnp.where(value > 0, value, 1.)
safe_range = jnp.where(range_ > 0, range_, 1.)
saturation = jnp.where(value > 0, range_ / safe_value, 0.)
norm = 1. / (6. * safe_range)
hue = jnp.where(value == green,
norm * (blue - red) + 2. / 6.,
norm * (red - green) + 4. / 6.)
hue = jnp.where(value == red, norm * (green - blue), hue)
hue = jnp.where(range_ > 0, hue, 0.) + (hue < 0.)
return hue, saturation, value
def hsv_planes_to_rgb_planes(
hue: chex.Array,
saturation: chex.Array,
value: chex.Array,
) -> Tuple[chex.Array, chex.Array, chex.Array]:
"""Converts hue, saturation, value planes to red, green, blue color planes.
All planes should have the same shape, with float values in range [0, 1].
Behavior outside of these bounds is not guaranteed.
Reference implementation: http://shortn/_NvL2jK8F87
Args:
hue: the hue plane (wrapping).
saturation: the saturation plane.
value: the value plane.
Returns:
A tuple of (red, green, blue) planes, as float values in range [0, 1].
"""
dh = (hue % 1.0) * 6. # Wrap when hue >= 360°.
dr = jnp.clip(jnp.abs(dh - 3.) - 1., 0., 1.)
dg = jnp.clip(2. - jnp.abs(dh - 2.), 0., 1.)
db = jnp.clip(2. - jnp.abs(dh - 4.), 0., 1.)
one_minus_s = 1. - saturation
red = value * (one_minus_s + saturation * dr)
green = value * (one_minus_s + saturation * dg)
blue = value * (one_minus_s + saturation * db)
return red, green, blue
def rgb_to_hsl(
image_rgb: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Converts an image from RGB to HSL.
Args:
image_rgb: an RGB image, with float values in range [0, 1]. Behavior outside
of these bounds is not guaranteed.
channel_axis: the channel axis. image_rgb should have 3 layers along this
axis.
Returns:
An HSL image, with float values in range [0, 1], stacked along channel_axis.
"""
red, green, blue = split_channels(image_rgb, channel_axis)
c_max = jnp.maximum(red, jnp.maximum(green, blue))
c_min = jnp.minimum(red, jnp.minimum(green, blue))
c_sum = c_max + c_min
c_diff = c_max - c_min
mask = c_min == c_max
rc = (c_max - red) / c_diff
gc = (c_max - green) / c_diff
bc = (c_max - blue) / c_diff
eps = jnp.finfo(jnp.float32).eps
h = jnp.where(
mask, 0,
(jnp.where(red == c_max, bc - gc,
jnp.where(green == c_max, 2 + rc - bc, 4 + gc - rc)) / 6) % 1)
s = jnp.where(mask, 0, (c_diff + eps) /
(2 * eps + jnp.where(c_sum <= 1, c_sum, 2 - c_sum)))
l = c_sum / 2
return jnp.stack([h, s, l], axis=-1)
def hsl_to_rgb(
image_hsl: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Converts an image from HSL to RGB.
Args:
image_hsl: an HSV image, with float values in range [0, 1]. Behavior outside
of these bounds is not guaranteed.
channel_axis: the channel axis. image_hsv should have 3 layers along this
axis.
Returns:
An RGB image, with float values in range [0, 1], stacked along channel_axis.
"""
h, s, l = split_channels(image_hsl, channel_axis)
m2 = jnp.where(l <= 0.5, l * (1 + s), l + s - l * s)
m1 = 2 * l - m2
def _f(hue):
hue = hue % 1.0
return jnp.where(
hue < 1 / 6, m1 + 6 * (m2 - m1) * hue,
jnp.where(
hue < 0.5, m2,
jnp.where(hue < 2 / 3, m1 + 6 * (m2 - m1) * (2 / 3 - hue), m1)))
image_rgb = jnp.stack([_f(h + 1 / 3), _f(h), _f(h - 1 / 3)], axis=-1)
return jnp.where(s[..., jnp.newaxis] == 0, l[..., jnp.newaxis], image_rgb)
def rgb_to_grayscale(
image: chex.Array,
*,
keep_dims: bool = False,
luma_standard="rec601",
channel_axis: int = -1,
) -> chex.Array:
"""Converts an image to a grayscale image using the luma value.
This is equivalent to `tf.image.rgb_to_grayscale` (when keep_channels=False).
Args:
image: an RGB image, given as a float tensor in [0, 1].
keep_dims: if False (default), returns a tensor with a single channel. If
True, will tile the resulting channel.
luma_standard: the luma standard to use, either "rec601", "rec709" or
"bt2001". The default rec601 corresponds to TensorFlow's.
channel_axis: the index of the channel axis.
Returns:
The grayscale image.
"""
assert luma_standard in ["rec601", "rec709", "bt2001"]
if luma_standard == "rec601":
# TensorFlow's default.
rgb_weights = jnp.array([0.2989, 0.5870, 0.1140], dtype=image.dtype)
elif luma_standard == "rec709":
rgb_weights = jnp.array([0.2126, 0.7152, 0.0722], dtype=image.dtype)
else:
rgb_weights = jnp.array([0.2627, 0.6780, 0.0593], dtype=image.dtype)
grayscale = jnp.tensordot(image, rgb_weights, axes=(channel_axis, -1))
# Add back the channel axis.
grayscale = jnp.expand_dims(grayscale, axis=channel_axis)
if keep_dims:
if channel_axis < 0:
channel_axis += image.ndim
reps = [(1 if axis != channel_axis else 3) for axis in range(image.ndim)]
return jnp.tile(grayscale, reps) # Tile to 3 along the channel axis.
else:
return grayscale
|
dm_pix-master
|
dm_pix/_src/color_conversion.py
|
# Copyright 2020 DeepMind Technologies Limited. 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_pix._src.augment."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
from dm_pix._src import augment
import jax
import jax.numpy as jnp
import numpy as np
import scipy
import tensorflow as tf
_IMG_SHAPE = (131, 111, 3)
_RAND_FLOATS_IN_RANGE = list(
np.random.uniform(0., 1., size=(10,) + _IMG_SHAPE).astype(np.float32))
_RAND_FLOATS_OUT_OF_RANGE = list(
np.random.uniform(-0.5, 1.5, size=(10,) + _IMG_SHAPE).astype(np.float32))
_KERNEL_SIZE = _IMG_SHAPE[0] / 10.
class _ImageAugmentationTest(parameterized.TestCase):
"""Runs tests for the various augments with the correct arguments."""
def _test_fn_with_random_arg(self, images_list, jax_fn, reference_fn,
**kw_range):
pass
def _test_fn(self, images_list, jax_fn, reference_fn):
pass
def assertAllCloseTolerant(self, x, y):
# Increase tolerance on TPU due to lower precision.
tol = 1e-2 if jax.local_devices()[0].platform == "tpu" else 1e-4
np.testing.assert_allclose(x, y, rtol=tol, atol=tol)
self.assertEqual(x.dtype, y.dtype)
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_adjust_brightness(self, images_list):
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.adjust_brightness,
reference_fn=tf.image.adjust_brightness,
delta=(-0.5, 0.5))
key = jax.random.PRNGKey(0)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_brightness, key),
reference_fn=None,
max_delta=(0, 0.5))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_adjust_contrast(self, images_list):
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.adjust_contrast,
reference_fn=tf.image.adjust_contrast,
factor=(0.5, 1.5))
key = jax.random.PRNGKey(0)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_contrast, key, upper=1),
reference_fn=None,
lower=(0, 0.9))
# Doesn't make sense outside of [0, 1].
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE))
def test_adjust_gamma(self, images_list):
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.adjust_gamma,
reference_fn=tf.image.adjust_gamma,
gamma=(0.5, 1.5))
key = jax.random.PRNGKey(0)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_gamma, key, min_gamma=1),
reference_fn=None,
max_gamma=(1.5, 1.9))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_adjust_saturation(self, images_list):
# tf.image.adjust_saturation has a buggy implementation when the green and
# blue channels have very close values that don't match the red channel.
# This is due to a rounding error in http://shortn/_ETSJsEwUj5
# if (g - b) < 0 but small enough that (hh + 1) == 1.
# Eg: tf.image.adjust_saturation([[[0.75, 0.0369078, 0.0369079]]], 1.0)
# -> [[[0.03690779, 0.03690779, 0.03690779]]]
# Perturb the inputs slightly so that this doesn't happen.
def perturb(rgb):
rgb_new = np.copy(rgb)
rgb_new[..., 1] += 0.001 * (np.abs(rgb[..., 2] - rgb[..., 1]) < 1e-3)
return rgb_new
images_list = list(map(perturb, images_list))
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.adjust_saturation,
reference_fn=tf.image.adjust_saturation,
factor=(0.5, 1.5))
key = jax.random.PRNGKey(0)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_saturation, key, upper=1),
reference_fn=None,
lower=(0, 0.9))
# CPU TF uses a different hue adjustment method outside of the [0, 1] range.
# Disable out-of-range tests.
@parameterized.named_parameters(
("in_range", _RAND_FLOATS_IN_RANGE),)
def test_adjust_hue(self, images_list):
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.adjust_hue,
reference_fn=tf.image.adjust_hue,
delta=(-0.5, 0.5))
key = jax.random.PRNGKey(0)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_hue, key),
reference_fn=None,
max_delta=(0, 0.5))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_rot90(self, images_list):
self._test_fn(
images_list,
jax_fn=lambda img: augment.rot90(img, k=1),
reference_fn=lambda img: tf.image.rot90(img, k=1))
self._test_fn(
images_list,
jax_fn=lambda img: augment.rot90(img, k=2),
reference_fn=lambda img: tf.image.rot90(img, k=2))
self._test_fn(
images_list,
jax_fn=lambda img: augment.rot90(img, k=3),
reference_fn=lambda img: tf.image.rot90(img, k=3))
# The functions below don't have a TF equivalent to compare to, we just check
# that they run.
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_flip(self, images_list):
self._test_fn(
images_list,
jax_fn=augment.flip_left_right,
reference_fn=tf.image.flip_left_right)
self._test_fn(
images_list,
jax_fn=augment.flip_up_down,
reference_fn=tf.image.flip_up_down)
key = jax.random.PRNGKey(0)
self._test_fn(
images_list,
jax_fn=functools.partial(augment.random_flip_left_right, key),
reference_fn=None)
self._test_fn(
images_list,
jax_fn=functools.partial(augment.random_flip_up_down, key),
reference_fn=None)
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_flip_left_right, key),
reference_fn=None,
probability=(0., 1.))
self._test_fn_with_random_arg(
images_list,
jax_fn=functools.partial(augment.random_flip_up_down, key),
reference_fn=None,
probability=(0., 1.))
# Due to a bug in scipy we cannot test all available modes, refer to these
# issues for more information: https://github.com/google/jax/issues/11097,
# https://github.com/google/jax/issues/11097
@parameterized.named_parameters(
("in_range_nearest_0", _RAND_FLOATS_IN_RANGE, "nearest", 0),
("in_range_nearest_1", _RAND_FLOATS_IN_RANGE, "nearest", 1),
("in_range_mirror_1", _RAND_FLOATS_IN_RANGE, "mirror", 1),
("out_of_range_nearest_0", _RAND_FLOATS_OUT_OF_RANGE, "nearest", 0),
("out_of_range_nearest_1", _RAND_FLOATS_OUT_OF_RANGE, "nearest", 1),
("out_of_range_mirror_1", _RAND_FLOATS_OUT_OF_RANGE, "mirror", 1),
)
def test_affine_transform(self, images_list, mode, order):
# (ndim, ndim) no offset
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.affine_transform, matrix=np.eye(3), mode=mode, order=order),
reference_fn=functools.partial(
scipy.ndimage.affine_transform,
matrix=np.eye(3),
order=order,
mode=mode))
# (ndim, ndim) with offset
matrix = jnp.array([[-0.5, 0.2, 0.], [0.8, 0.5, 0.], [0., 0., 1.]])
offset = jnp.array([40., 32., 0.])
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.affine_transform,
matrix=matrix,
mode=mode,
offset=offset,
order=order),
reference_fn=functools.partial(
scipy.ndimage.affine_transform,
matrix=matrix,
offset=offset,
order=order,
mode=mode))
# (ndim + 1, ndim + 1)
matrix = jnp.array([[0.4, 0.2, 0, -10], [0.2, -0.5, 0, 5], [0, 0, 1, 0],
[0, 0, 0, 1]])
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.affine_transform, matrix=matrix, mode=mode, order=order),
reference_fn=functools.partial(
scipy.ndimage.affine_transform,
matrix=matrix,
order=order,
mode=mode))
# (ndim, ndim + 1)
matrix = jnp.array([[0.4, 0.2, 0, -10], [0.2, -0.5, 0, 5], [0, 0, 1, 0]])
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.affine_transform, matrix=matrix, mode=mode, order=order),
reference_fn=functools.partial(
scipy.ndimage.affine_transform,
matrix=matrix,
order=order,
mode=mode))
# (ndim,)
matrix = jnp.array([0.4, 0.2, 1])
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.affine_transform, matrix=matrix, mode=mode, order=order),
reference_fn=functools.partial(
scipy.ndimage.affine_transform,
matrix=matrix,
order=order,
mode=mode))
@parameterized.product(
parameters_base=[
("in_range", "nearest", 0),
("in_range", "nearest", 1),
("in_range", "mirror", 1),
("in_range", "constant", 1),
("out_of_range", "nearest", 0),
("out_of_range", "nearest", 1),
("out_of_range", "mirror", 1),
("out_of_range", "constant", 1),
],
cval=(0.0, 1.0, -2.0),
angle=(0.0, np.pi / 4, -np.pi / 4),
)
def test_rotate(self, parameters_base, cval, angle):
images_list_type, mode, order = parameters_base
if images_list_type == "in_range":
images_list = _RAND_FLOATS_IN_RANGE
elif images_list_type == "out_of_range":
images_list = _RAND_FLOATS_OUT_OF_RANGE
else:
raise ValueError(f"{images_list_type} not a valid image list for tests.")
self._test_fn(
images_list,
jax_fn=functools.partial(
augment.rotate, angle=angle, mode=mode, order=order, cval=cval),
reference_fn=functools.partial(
scipy.ndimage.rotate,
angle=angle * 180 / np.pi, # SciPy uses degrees.
order=order,
mode=mode,
cval=cval,
reshape=False))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_solarize(self, images_list):
self._test_fn_with_random_arg(
images_list,
jax_fn=augment.solarize,
reference_fn=None,
threshold=(0., 1.))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_gaussian_blur(self, images_list):
blur_fn = functools.partial(augment.gaussian_blur, kernel_size=_KERNEL_SIZE)
self._test_fn_with_random_arg(
images_list, jax_fn=blur_fn, reference_fn=None, sigma=(0.1, 2.0))
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_random_crop(self, images_list):
key = jax.random.PRNGKey(43)
crop_fn = lambda img: augment.random_crop(key, img, (100, 100, 3))
self._test_fn(images_list, jax_fn=crop_fn, reference_fn=None)
@parameterized.named_parameters(("in_range", _RAND_FLOATS_IN_RANGE),
("out_of_range", _RAND_FLOATS_OUT_OF_RANGE))
def test_elastic_deformation(self, images_list):
key = jax.random.PRNGKey(43)
alpha = 10.
sigma = 5.
elastic_deformation = functools.partial(
augment.elastic_deformation,
key,
alpha=alpha,
sigma=sigma,
)
# Due to the difference between random number generation in numpy (in
# reference function) and JAX's for the displacement fields we cannot test
# this against some of the available functions. At the time of writing open
# source options are either unmaintained or are not readily available.
self._test_fn(
images_list,
jax_fn=elastic_deformation,
reference_fn=None,
)
elastic_deformation = functools.partial(
augment.elastic_deformation,
key,
sigma=sigma)
# Sigma has to be constant for jit since kernel_size is derived from it.
self._test_fn_with_random_arg(
images_list,
jax_fn=elastic_deformation,
reference_fn=None,
alpha=(40, 80))
@parameterized.product(
images_list=(_RAND_FLOATS_IN_RANGE, _RAND_FLOATS_OUT_OF_RANGE),
height=(131, 111, 1, 88),
width=(111, 105, 1, 40),
)
def test_center_crop(self, images_list, height, width):
center_crop = functools.partial(
augment.center_crop,
height=height,
width=width,
)
# Using layer as reference as other tf utility functions are not exactly
# this same center crop:
# - tf.image.crop_and_resize
# - tf.image.central_crop
reference = tf.keras.layers.CenterCrop(
height=height,
width=width,
)
self._test_fn(images_list, jax_fn=center_crop, reference_fn=reference)
@parameterized.product(
images_list=(_RAND_FLOATS_IN_RANGE, _RAND_FLOATS_OUT_OF_RANGE),
target_height=(156, 131, 200, 251),
target_width=(156, 111, 200, 251),
)
def test_pad_to_size(self, images_list, target_height, target_width):
pad_fn = functools.partial(
augment.pad_to_size,
target_height=target_height,
target_width=target_width,
mode="constant",
pad_kwargs={"constant_values": 0},
)
# We have to rely on `resize_with_crop_or_pad` as there are no pad to size
# equivalents.
reference_fn = functools.partial(
tf.image.resize_with_crop_or_pad,
target_height=target_height,
target_width=target_width,
)
self._test_fn(images_list, jax_fn=pad_fn, reference_fn=reference_fn)
@parameterized.product(
images_list=(_RAND_FLOATS_IN_RANGE, _RAND_FLOATS_OUT_OF_RANGE),
target_height=(156, 138, 200, 251),
target_width=(156, 138, 200, 251),
)
def test_resize_with_crop_or_pad(
self, images_list, target_height, target_width
):
resize_crop_or_pad = functools.partial(
augment.resize_with_crop_or_pad,
target_height=target_height,
target_width=target_width,
pad_mode="constant",
pad_kwargs={"constant_values": 0},
)
reference_fn = functools.partial(
tf.image.resize_with_crop_or_pad,
target_height=target_height,
target_width=target_width,
)
self._test_fn(
images_list, jax_fn=resize_crop_or_pad, reference_fn=reference_fn
)
class TestMatchReference(_ImageAugmentationTest):
def _test_fn_with_random_arg(
self, images_list, jax_fn, reference_fn, **kw_range
):
if reference_fn is None:
return
assert len(kw_range) == 1
kw_name, (random_min, random_max) = list(kw_range.items())[0]
for image_rgb in images_list:
argument = np.random.uniform(random_min, random_max, size=())
adjusted_jax = jax_fn(image_rgb, **{kw_name: argument})
adjusted_reference = reference_fn(image_rgb, argument)
if hasattr(adjusted_reference, "numpy"):
adjusted_reference = adjusted_reference.numpy()
self.assertAllCloseTolerant(adjusted_jax, adjusted_reference)
def _test_fn(self, images_list, jax_fn, reference_fn):
if reference_fn is None:
return
for image_rgb in images_list:
adjusted_jax = jax_fn(image_rgb)
adjusted_reference = reference_fn(image_rgb)
if hasattr(adjusted_reference, "numpy"):
adjusted_reference = adjusted_reference.numpy()
self.assertAllCloseTolerant(adjusted_jax, adjusted_reference)
class TestVmap(_ImageAugmentationTest):
def _test_fn_with_random_arg(self, images_list, jax_fn, reference_fn,
**kw_range):
del reference_fn # unused.
assert len(kw_range) == 1
kw_name, (random_min, random_max) = list(kw_range.items())[0]
arguments = [
np.random.uniform(random_min, random_max, size=()) for _ in images_list
]
fn_vmap = jax.vmap(jax_fn)
outputs_vmaped = list(
fn_vmap(
np.stack(images_list, axis=0),
**{kw_name: np.stack(arguments, axis=0)}))
assert len(images_list) == len(outputs_vmaped)
assert len(images_list) == len(arguments)
for image_rgb, argument, adjusted_vmap in zip(images_list, arguments,
outputs_vmaped):
adjusted_jax = jax_fn(image_rgb, **{kw_name: argument})
self.assertAllCloseTolerant(adjusted_jax, adjusted_vmap)
def _test_fn(self, images_list, jax_fn, reference_fn):
del reference_fn # unused.
fn_vmap = jax.vmap(jax_fn)
outputs_vmaped = list(fn_vmap(np.stack(images_list, axis=0)))
assert len(images_list) == len(outputs_vmaped)
for image_rgb, adjusted_vmap in zip(images_list, outputs_vmaped):
adjusted_jax = jax_fn(image_rgb)
self.assertAllCloseTolerant(adjusted_jax, adjusted_vmap)
class TestJit(_ImageAugmentationTest):
def _test_fn_with_random_arg(self, images_list, jax_fn, reference_fn,
**kw_range):
del reference_fn # unused.
assert len(kw_range) == 1
kw_name, (random_min, random_max) = list(kw_range.items())[0]
jax_fn_jitted = jax.jit(jax_fn)
for image_rgb in images_list:
argument = np.random.uniform(random_min, random_max, size=())
adjusted_jax = jax_fn(image_rgb, **{kw_name: argument})
adjusted_jit = jax_fn_jitted(image_rgb, **{kw_name: argument})
self.assertAllCloseTolerant(adjusted_jax, adjusted_jit)
def _test_fn(self, images_list, jax_fn, reference_fn):
del reference_fn # unused.
jax_fn_jitted = jax.jit(jax_fn)
for image_rgb in images_list:
adjusted_jax = jax_fn(image_rgb)
adjusted_jit = jax_fn_jitted(image_rgb)
self.assertAllCloseTolerant(adjusted_jax, adjusted_jit)
class TestCustom(parameterized.TestCase):
"""Tests custom logic that is not covered by reference functions."""
@parameterized.product(
images_list=(_RAND_FLOATS_IN_RANGE, _RAND_FLOATS_OUT_OF_RANGE),
height=(250, 200),
width=(250, 200),
expected_height=(131, 131),
expected_width=(111, 111),
)
def test_center_crop_size_bigger_than_original(
self,
images_list,
height,
width,
expected_height,
expected_width,
):
output = augment.center_crop(
image=jnp.array(images_list),
height=height,
width=width,
)
self.assertEqual(output.shape[1], expected_height)
self.assertEqual(output.shape[2], expected_width)
@parameterized.product(
images_list=(_RAND_FLOATS_IN_RANGE, _RAND_FLOATS_OUT_OF_RANGE),
target_height=(55, 84),
target_width=(55, 84),
expected_height=(131, 131),
expected_width=(111, 111),
)
def test_pad_to_size_when_target_size_smaller_than_original(
self,
images_list,
target_height,
target_width,
expected_height,
expected_width,
):
output = augment.pad_to_size(
image=jnp.array(images_list),
target_height=target_height,
target_width=target_width,
)
self.assertEqual(output.shape[1], expected_height)
self.assertEqual(output.shape[2], expected_width)
if __name__ == "__main__":
jax.config.update("jax_default_matmul_precision", "float32")
absltest.main()
|
dm_pix-master
|
dm_pix/_src/augment_test.py
|
# Copyright 2021 DeepMind Technologies Limited. 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_pix._src.patch."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import chex
from dm_pix._src import patch
import numpy as np
import tensorflow as tf
def _create_test_images(shape):
images = np.arange(np.prod(np.array(shape)), dtype=np.float32)
return np.reshape(images, shape)
class PatchTest(chex.TestCase, parameterized.TestCase):
@chex.all_variants
@parameterized.named_parameters(
('padding_valid', 'VALID'),
('padding_same', 'SAME'),
)
def test_extract_patches(self, padding):
image_shape = (2, 5, 7, 3)
images = _create_test_images(image_shape)
sizes = (1, 2, 3, 1)
strides = (1, 1, 2, 1)
rates = (1, 2, 1, 1)
extract_patches = self.variant(
functools.partial(patch.extract_patches, padding=padding),
static_argnums=(1, 2, 3))
jax_patches = extract_patches(
images,
sizes,
strides,
rates,
)
tf_patches = tf.image.extract_patches(
images,
sizes=sizes,
strides=strides,
rates=rates,
padding=padding,
)
np.testing.assert_array_equal(jax_patches, tf_patches.numpy())
@chex.all_variants
@parameterized.named_parameters(
('padding_valid', 'VALID'),
('padding_same', 'SAME'),
)
def test_extract_patches_0d(self, padding):
image_shape = (2, 3)
images = _create_test_images(image_shape)
sizes = (1, 1)
strides = (1, 1)
rates = (1, 1)
extract_patches = self.variant(
functools.partial(patch.extract_patches, padding=padding),
static_argnums=(1, 2, 3))
jax_patches = extract_patches(
images,
sizes,
strides,
rates,
)
# 0D patches is a no-op.
np.testing.assert_array_equal(jax_patches, images)
@chex.all_variants
@parameterized.named_parameters(
('padding_valid', 'VALID'),
('padding_same', 'SAME'),
)
def test_extract_patches_1d(self, padding):
image_shape = (2, 7, 3)
images = _create_test_images(image_shape)
sizes = (1, 2, 1)
strides = (1, 1, 1)
rates = (1, 2, 1)
extract_patches = self.variant(
functools.partial(patch.extract_patches, padding=padding),
static_argnums=(1, 2, 3))
jax_patches = extract_patches(
images,
sizes,
strides,
rates,
)
jax_patches = np.expand_dims(jax_patches, -2)
# Reference patches are computed over an image with an extra singleton dim.
tf_patches = tf.image.extract_patches(
np.expand_dims(images, 2),
sizes=sizes + (1,),
strides=strides + (1,),
rates=rates + (1,),
padding=padding,
)
np.testing.assert_array_equal(jax_patches, tf_patches.numpy())
@chex.all_variants
def test_extract_patches_3d(self):
image_shape = (2, 4, 9, 6, 3)
images = _create_test_images(image_shape)
sizes = (1, 2, 3, 2, 1)
strides = (1, 2, 3, 2, 1)
rates = (1, 1, 1, 1, 1)
extract_patches = self.variant(
functools.partial(patch.extract_patches, padding='VALID'),
static_argnums=(1, 2, 3))
jax_patches = extract_patches(
images,
sizes,
strides,
rates,
)
# Reconstructing the original from non-overlapping patches.
images_reconstructed = np.reshape(
jax_patches,
jax_patches.shape[:-1] + sizes[1:-1] + images.shape[-1:]
)
images_reconstructed = np.moveaxis(images_reconstructed,
(-4, -3, -2),
(2, 4, 6))
images_reconstructed = images_reconstructed.reshape(image_shape)
np.testing.assert_allclose(images_reconstructed, images, rtol=5e-3)
@chex.all_variants
@parameterized.product(
({
'sizes': (1, 2, 3),
'strides': (1, 1, 2, 1),
'rates': (1, 2, 1, 1),
}, {
'sizes': (1, 2, 3, 1),
'strides': (1, 1, 2),
'rates': (1, 2, 1, 1),
}, {
'sizes': (1, 2, 3, 1),
'strides': (1, 1, 2, 1),
'rates': (1, 2, 1),
}, {
'sizes': (1, 2, 1),
'strides': (1, 2, 1),
'rates': (1, 1),
}, {
'sizes': (1, 1),
'strides': (1, 2),
'rates': (1, 1),
}, {
'sizes': (1, 1),
'strides': (1,),
'rates': (1, 1),
}, {
'sizes': (1, 2, 3, 4, 1),
'strides': (1, 2, 3, 4, 2),
'rates': (1, 1, 1, 1, 1),
}, {
'sizes': (1, 2, 3, 1),
'strides': (1, 2, 3, 4, 1),
'rates': (1, 1, 1, 1, 1),
}),
padding=('VALID', 'SAME'),
)
def test_extract_patches_raises(self, sizes, strides, rates, padding):
image_shape = (2, 5, 7, 3)
images = _create_test_images(image_shape)
extract_patches = self.variant(
functools.partial(patch.extract_patches, padding=padding),
static_argnums=(1, 2, 3))
with self.assertRaises(ValueError):
extract_patches(
images,
sizes,
strides,
rates,
)
if __name__ == '__main__':
absltest.main()
|
dm_pix-master
|
dm_pix/_src/patch_test.py
|
# Copyright 2021 DeepMind Technologies Limited. 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_pix._src.metrics."""
import functools
from absl.testing import absltest
import chex
from dm_pix._src import metrics
import jax
import numpy as np
import tensorflow as tf
class MSETest(chex.TestCase, absltest.TestCase):
def setUp(self):
super().setUp()
key = jax.random.PRNGKey(0)
key1, key2 = jax.random.split(key)
self._img1 = jax.random.uniform(
key1,
shape=(4, 32, 32, 3),
minval=0.,
maxval=1.,
)
self._img2 = jax.random.uniform(
key2,
shape=(4, 32, 32, 3),
minval=0.,
maxval=1.,
)
@chex.all_variants
def test_psnr_match(self):
psnr = self.variant(metrics.psnr)
values_jax = psnr(self._img1, self._img2)
values_tf = tf.image.psnr(self._img1, self._img2, max_val=1.).numpy()
np.testing.assert_allclose(values_jax, values_tf, rtol=1e-3, atol=1e-3)
@chex.all_variants
def test_simse_invariance(self):
simse = self.variant(metrics.simse)
simse_jax = simse(self._img1, self._img1 * 2.0)
np.testing.assert_allclose(simse_jax, np.zeros(4), rtol=1e-6, atol=1e-6)
class SSIMTests(chex.TestCase, absltest.TestCase):
@chex.all_variants
def test_ssim_golden(self):
"""Test that the SSIM implementation matches the Tensorflow version."""
key = jax.random.PRNGKey(0)
for shape in ((2, 12, 12, 3), (12, 12, 3), (2, 12, 15, 3), (17, 12, 3)):
for _ in range(4):
(max_val_key, img0_key, img1_key, filter_size_key, filter_sigma_key,
k1_key, k2_key, key) = jax.random.split(key, 8)
max_val = jax.random.uniform(max_val_key, minval=0.1, maxval=3.)
img0 = max_val * jax.random.uniform(img0_key, shape=shape)
img1 = max_val * jax.random.uniform(img1_key, shape=shape)
filter_size = jax.random.randint(
filter_size_key, shape=(), minval=1, maxval=10)
filter_sigma = jax.random.uniform(
filter_sigma_key, shape=(), minval=0.1, maxval=10.)
k1 = jax.random.uniform(k1_key, shape=(), minval=0.001, maxval=0.1)
k2 = jax.random.uniform(k2_key, shape=(), minval=0.001, maxval=0.1)
ssim_gt = tf.image.ssim(
img0,
img1,
max_val,
filter_size=filter_size,
filter_sigma=filter_sigma,
k1=k1,
k2=k2).numpy()
for return_map in [False, True]:
ssim_fn = self.variant(
functools.partial(
metrics.ssim,
max_val=max_val,
filter_size=filter_size,
filter_sigma=filter_sigma,
k1=k1,
k2=k2,
return_map=return_map,
))
ssim = ssim_fn(img0, img1)
if not return_map:
np.testing.assert_allclose(ssim, ssim_gt, atol=1e-5, rtol=1e-5)
else:
np.testing.assert_allclose(
np.mean(ssim, list(range(-3, 0))),
ssim_gt,
atol=1e-5,
rtol=1e-5)
self.assertLessEqual(np.max(ssim), 1.)
self.assertGreaterEqual(np.min(ssim), -1.)
@chex.all_variants
def test_ssim_lowerbound(self):
"""Test the unusual corner case where SSIM is -1."""
filter_size = 11
grid_coords = [np.linspace(-1, 1, filter_size)] * 2
img = np.meshgrid(*grid_coords)[0][np.newaxis, ..., np.newaxis]
eps = 1e-5
ssim_fn = self.variant(
functools.partial(
metrics.ssim,
max_val=1.,
filter_size=filter_size,
filter_sigma=1.5,
k1=eps,
k2=eps,
))
ssim = ssim_fn(img, -img)
np.testing.assert_allclose(ssim, -np.ones_like(ssim), atol=1E-5, rtol=1E-5)
@chex.all_variants
def test_ssim_finite_grad(self):
"""Test that SSIM produces a finite gradient on large flat regions."""
img = np.zeros((64, 64, 3))
grad = self.variant(jax.grad(metrics.ssim))(img, img)
np.testing.assert_equal(grad, np.zeros_like(grad))
if __name__ == "__main__":
absltest.main()
|
dm_pix-master
|
dm_pix/_src/metrics_test.py
|
# Copyright 2020 DeepMind Technologies Limited. 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.
"""This module provides image augmentation functions.
All functions expect float-encoded images, with values in [0, 1].
Do not clip their outputs to this range to allow chaining without losing
information. The outside-of-bounds behavior is (as much as possible) similar to
that of TensorFlow.
"""
import functools
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import chex
from dm_pix._src import color_conversion
from dm_pix._src import interpolation
import jax
import jax.numpy as jnp
def adjust_brightness(image: chex.Array, delta: chex.Numeric) -> chex.Array:
"""Shifts the brightness of an RGB image by a given amount.
This is equivalent to tf.image.adjust_brightness.
Args:
image: an RGB image, given as a float tensor in [0, 1].
delta: the (additive) amount to shift each channel by.
Returns:
The brightness-adjusted image. May be outside of the [0, 1] range.
"""
return image + jnp.asarray(delta, image.dtype)
def adjust_contrast(
image: chex.Array,
factor: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Adjusts the contrast of an RGB image by a given multiplicative amount.
This is equivalent to `tf.image.adjust_contrast`.
Args:
image: an RGB image, given as a float tensor in [0, 1].
factor: the (multiplicative) amount to adjust contrast by.
channel_axis: the index of the channel axis.
Returns:
The contrast-adjusted image. May be outside of the [0, 1] range.
"""
if _channels_last(image, channel_axis):
spatial_axes = (-3, -2)
else:
spatial_axes = (-2, -1)
mean = jnp.mean(image, axis=spatial_axes, keepdims=True)
return jnp.asarray(factor, image.dtype) * (image - mean) + mean
def adjust_gamma(
image: chex.Array,
gamma: chex.Numeric,
*,
gain: chex.Numeric = 1.,
assume_in_bounds: bool = False,
) -> chex.Array:
"""Adjusts the gamma of an RGB image.
This is equivalent to `tf.image.adjust_gamma`, i.e. returns
`gain * image ** gamma`.
Args:
image: an RGB image, given as a [0-1] float tensor.
gamma: the exponent to apply.
gain: the (multiplicative) gain to apply.
assume_in_bounds: whether the input image should be assumed to have all
values within [0, 1]. If False (default), the inputs will be clipped to
that range avoid NaNs.
Returns:
The gamma-adjusted image.
"""
if not assume_in_bounds:
image = jnp.clip(image, 0., 1.) # Clip image for safety.
return jnp.asarray(gain, image.dtype) * (
image**jnp.asarray(gamma, image.dtype))
def adjust_hue(
image: chex.Array,
delta: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Adjusts the hue of an RGB image by a given multiplicative amount.
This is equivalent to `tf.image.adjust_hue` when TF is running on GPU. When
running on CPU, the results will be different if all RGB values for a pixel
are outside of the [0, 1] range.
Args:
image: an RGB image, given as a [0-1] float tensor.
delta: the (additive) angle to shift hue by.
channel_axis: the index of the channel axis.
Returns:
The saturation-adjusted image.
"""
rgb = color_conversion.split_channels(image, channel_axis)
hue, saturation, value = color_conversion.rgb_planes_to_hsv_planes(*rgb)
rgb_adjusted = color_conversion.hsv_planes_to_rgb_planes((hue + delta) % 1.0,
saturation, value)
return jnp.stack(rgb_adjusted, axis=channel_axis)
def adjust_saturation(
image: chex.Array,
factor: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Adjusts the saturation of an RGB image by a given multiplicative amount.
This is equivalent to `tf.image.adjust_saturation`.
Args:
image: an RGB image, given as a [0-1] float tensor.
factor: the (multiplicative) amount to adjust saturation by.
channel_axis: the index of the channel axis.
Returns:
The saturation-adjusted image.
"""
rgb = color_conversion.split_channels(image, channel_axis)
hue, saturation, value = color_conversion.rgb_planes_to_hsv_planes(*rgb)
factor = jnp.asarray(factor, image.dtype)
rgb_adjusted = color_conversion.hsv_planes_to_rgb_planes(
hue, jnp.clip(saturation * factor, 0., 1.), value)
return jnp.stack(rgb_adjusted, axis=channel_axis)
def elastic_deformation(
key: chex.PRNGKey,
image: chex.Array,
alpha: chex.Numeric,
sigma: chex.Numeric,
*,
order: int = 1,
mode: str = "nearest",
cval: float = 0.,
channel_axis: int = -1,
) -> chex.Array:
"""Applies an elastic deformation to the given image.
Introduced by [Simard, 2003] and popularized by [Ronneberger, 2015]. Deforms
images by moving pixels locally around using displacement fields.
Small sigma values (< 1.) give pixelated images while higher values result
in water like results. Alpha should be in the between x5 and x10 the value
given for sigma for sensible resutls.
Args:
key: key: a JAX RNG key.
image: a JAX array representing an image. Assumes that the image is
either HWC or CHW.
alpha: strength of the distortion field. Higher values mean that pixels are
moved further with respect to the distortion field's direction.
sigma: standard deviation of the gaussian kernel used to smooth the
distortion fields.
order: the order of the spline interpolation, default is 1. The order has
to be in the range [0, 1]. Note that PIX interpolation will only be used
for order=1, for other values we use `jax.scipy.ndimage.map_coordinates`.
mode: the mode parameter determines how the input array is extended beyond
its boundaries. Default is 'nearest'. Modes 'nearest and 'constant' use
PIX interpolation, which is very fast on accelerators (especially on
TPUs). For all other modes, 'wrap', 'mirror' and 'reflect', we rely
on `jax.scipy.ndimage.map_coordinates`, which however is slow on
accelerators, so use it with care.
cval: value to fill past edges of input if mode is 'constant'. Default is
0.0.
channel_axis: the index of the channel axis.
Returns:
The transformed image.
"""
chex.assert_rank(image, 3)
if channel_axis != -1:
image = jnp.moveaxis(image, source=channel_axis, destination=-1)
single_channel_shape = (*image.shape[:-1], 1)
key_i, key_j = jax.random.split(key)
noise_i = jax.random.uniform(key_i, shape=single_channel_shape) * 2 - 1
noise_j = jax.random.uniform(key_j, shape=single_channel_shape) * 2 - 1
# ~3 sigma on each side of the kernel's center covers ~99.7% of the
# probability mass. There is some fiddling for smaller values. Source:
# https://docs.opencv.org/3.1.0/d4/d86/group__imgproc__filter.html#gac05a120c1ae92a6060dd0db190a61afa
kernel_size = ((sigma - 0.8) / 0.3 + 1) / 0.5 + 1
shift_map_i = gaussian_blur(
image=noise_i,
sigma=sigma,
kernel_size=kernel_size) * alpha
shift_map_j = gaussian_blur(
image=noise_j,
sigma=sigma,
kernel_size=kernel_size) * alpha
meshgrid = jnp.meshgrid(*[jnp.arange(size) for size in single_channel_shape],
indexing="ij")
meshgrid[0] += shift_map_i
meshgrid[1] += shift_map_j
interpolate_function = _get_interpolate_function(
mode=mode,
order=order,
cval=cval,
)
transformed_image = jnp.concatenate([
interpolate_function(
image[..., channel, jnp.newaxis], jnp.asarray(meshgrid))
for channel in range(image.shape[-1])
], axis=-1)
if channel_axis != -1: # Set channel axis back to original index.
transformed_image = jnp.moveaxis(
transformed_image, source=-1, destination=channel_axis)
return transformed_image
def center_crop(
image: chex.Array,
height: chex.Numeric,
width: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Crops an image to the given size keeping the same center of the original.
Target height/width given can be greater than the current size of the image
which results in being a no-op for that dimension.
In case of odd size along any dimension the bottom/right side gets the extra
pixel.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
height: target height to crop the image to.
width: target width to crop the image to.
channel_axis: the index of the channel axis.
Returns:
The cropped image(s).
"""
chex.assert_rank(image, {3, 4})
batch, current_height, current_width, channel = _get_dimension_values(
image=image, channel_axis=channel_axis
)
center_h, center_w = current_height // 2, current_width // 2
left = max(center_w - (width // 2), 0)
right = min(left + width, current_width)
top = max(center_h - (height // 2), 0)
bottom = min(top + height, current_height)
if _channels_last(image, channel_axis):
start_indices = (top, left, 0)
limit_indices = (bottom, right, channel)
else:
start_indices = (0, top, left)
limit_indices = (channel, bottom, right)
if batch is not None: # In case batch of images is given.
start_indices = (0, *start_indices)
limit_indices = (batch, *limit_indices)
return jax.lax.slice(
image, start_indices=start_indices, limit_indices=limit_indices
)
def pad_to_size(
image: chex.Array,
target_height: int,
target_width: int,
*,
mode: str = "constant",
pad_kwargs: Optional[Any] = None,
channel_axis: int = -1,
) -> chex.Array:
"""Pads an image to the given size keeping the original image centered.
For different padding methods and kwargs please see:
https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.pad.html
In case of odd size difference along any dimension the bottom/right side gets
the extra padding pixel.
Target size can be smaller than original size which results in a no-op for
such dimension.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
target_height: target height to pad the image to.
target_width: target width to pad the image to.
mode: Mode for padding the images, see jax.numpy.pad for details. Default is
`constant`.
pad_kwargs: Keyword arguments to pass jax.numpy.pad, see documentation for
options.
channel_axis: the index of the channel axis.
Returns:
The padded image(s).
"""
chex.assert_rank(image, {3, 4})
batch, height, width, _ = _get_dimension_values(
image=image, channel_axis=channel_axis
)
delta_width = max(target_width - width, 0)
delta_height = max(target_height - height, 0)
if delta_width == 0 and delta_height == 0:
return image
left = delta_width // 2
right = max(target_width - (left + width), 0)
top = delta_height // 2
bottom = max(target_height - (top + height), 0)
pad_width = ((top, bottom), (left, right), (0, 0))
if batch:
pad_width = ((0, 0), *pad_width)
return jnp.pad(image, pad_width=pad_width, mode=mode, **pad_kwargs or {})
def resize_with_crop_or_pad(
image: chex.Array,
target_height: chex.Numeric,
target_width: chex.Numeric,
*,
pad_mode: str = "constant",
pad_kwargs: Optional[Any] = None,
channel_axis: int = -1,
) -> chex.Array:
"""Crops and/or pads an image to a target width and height.
Equivalent in functionality to tf.image.resize_with_crop_or_pad but allows for
different padding methods as well beyond zero padding.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
target_height: target height to crop or pad the image to.
target_width: target width to crop or pad the image to.
pad_mode: mode for padding the images, see jax.numpy.pad for details.
Default is `constant`.
pad_kwargs: keyword arguments to pass jax.numpy.pad, see documentation for
options.
channel_axis: the index of the channel axis.
Returns:
The image(s) resized by crop or pad to the desired target size.
"""
chex.assert_rank(image, {3, 4})
image = center_crop(
image,
height=target_height,
width=target_width,
channel_axis=channel_axis,
)
return pad_to_size(
image,
target_height=target_height,
target_width=target_width,
channel_axis=channel_axis,
mode=pad_mode,
pad_kwargs=pad_kwargs,
)
def flip_left_right(
image: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Flips an image along the horizontal axis.
Assumes that the image is either ...HWC or ...CHW and flips the W axis.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
channel_axis: the index of the channel axis.
Returns:
The flipped image.
"""
if _channels_last(image, channel_axis):
flip_axis = -2 # Image is ...HWC
else:
flip_axis = -1 # Image is ...CHW
return jnp.flip(image, axis=flip_axis)
def flip_up_down(
image: chex.Array,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Flips an image along the vertical axis.
Assumes that the image is either ...HWC or ...CHW, and flips the H axis.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
channel_axis: the index of the channel axis.
Returns:
The flipped image.
"""
if _channels_last(image, channel_axis):
flip_axis = -3 # Image is ...HWC
else:
flip_axis = -2 # Image is ...CHW
return jnp.flip(image, axis=flip_axis)
def gaussian_blur(
image: chex.Array,
sigma: float,
kernel_size: float,
*,
padding: str = "SAME",
channel_axis: int = -1,
) -> chex.Array:
"""Applies gaussian blur (convolution with a Gaussian kernel).
Args:
image: the input image, as a [0-1] float tensor. Should have 3 or 4
dimensions with two spatial dimensions.
sigma: the standard deviation (in pixels) of the gaussian kernel.
kernel_size: the size (in pixels) of the square gaussian kernel. Will be
"rounded" to the next odd integer.
padding: either "SAME" or "VALID", passed to the underlying convolution.
channel_axis: the index of the channel axis.
Returns:
The blurred image.
"""
chex.assert_rank(image, {3, 4})
data_format = "NHWC" if _channels_last(image, channel_axis) else "NCHW"
dimension_numbers = (data_format, "HWIO", data_format)
num_channels = image.shape[channel_axis]
radius = int(kernel_size / 2)
kernel_size_ = 2 * radius + 1
x = jnp.arange(-radius, radius + 1).astype(jnp.float32)
blur_filter = jnp.exp(-x**2 / (2. * sigma**2))
blur_filter = blur_filter / jnp.sum(blur_filter)
blur_v = jnp.reshape(blur_filter, [kernel_size_, 1, 1, 1])
blur_h = jnp.reshape(blur_filter, [1, kernel_size_, 1, 1])
blur_h = jnp.tile(blur_h, [1, 1, 1, num_channels])
blur_v = jnp.tile(blur_v, [1, 1, 1, num_channels])
expand_batch_dim = image.ndim == 3
if expand_batch_dim:
image = image[jnp.newaxis, ...]
blurred = _depthwise_conv2d(
image,
kernel=blur_h,
strides=(1, 1),
padding=padding,
channel_axis=channel_axis,
dimension_numbers=dimension_numbers)
blurred = _depthwise_conv2d(
blurred,
kernel=blur_v,
strides=(1, 1),
padding=padding,
channel_axis=channel_axis,
dimension_numbers=dimension_numbers)
if expand_batch_dim:
blurred = jnp.squeeze(blurred, axis=0)
return blurred
def rot90(
image: chex.Array,
k: int = 1,
*,
channel_axis: int = -1,
) -> chex.Array:
"""Rotates an image counter-clockwise by 90 degrees.
This is equivalent to tf.image.rot90. Assumes that the image is either
...HWC or ...CHW.
Args:
image: an RGB image, given as a float tensor in [0, 1].
k: the number of times the rotation is applied.
channel_axis: the index of the channel axis.
Returns:
The rotated image.
"""
if _channels_last(image, channel_axis):
spatial_axes = (-3, -2) # Image is ...HWC
else:
spatial_axes = (-2, -1) # Image is ...CHW
return jnp.rot90(image, k, spatial_axes)
def solarize(image: chex.Array, threshold: chex.Numeric) -> chex.Array:
"""Applies solarization to an image.
All values above a given threshold will be inverted.
Args:
image: an RGB image, given as a [0-1] float tensor.
threshold: the threshold for inversion.
Returns:
The solarized image.
"""
return jnp.where(image < threshold, image, 1. - image)
def affine_transform(
image: chex.Array,
matrix: chex.Array,
*,
offset: Union[chex.Array, chex.Numeric] = 0.,
order: int = 1,
mode: str = "nearest",
cval: float = 0.0,
) -> chex.Array:
"""Applies an affine transformation given by matrix.
Given an output image pixel index vector o, the pixel value is determined from
the input image at position jnp.dot(matrix, o) + offset.
This does 'pull' (or 'backward') resampling, transforming the output space to
the input to locate data. Affine transformations are often described in the
'push' (or 'forward') direction, transforming input to output. If you have a
matrix for the 'push' transformation, use its inverse (jax.numpy.linalg.inv)
in this function.
Args:
image: a JAX array representing an image. Assumes that the image is
either HWC or CHW.
matrix: the inverse coordinate transformation matrix, mapping output
coordinates to input coordinates. If ndim is the number of dimensions of
input, the given matrix must have one of the following shapes:
- (ndim, ndim): the linear transformation matrix for each output
coordinate.
- (ndim,): assume that the 2-D transformation matrix is diagonal, with the
diagonal specified by the given value.
- (ndim + 1, ndim + 1): assume that the transformation is specified using
homogeneous coordinates [1]. In this case, any value passed to offset is
ignored.
- (ndim, ndim + 1): as above, but the bottom row of a homogeneous
transformation matrix is always [0, 0, 0, 1], and may be omitted.
offset: the offset into the array where the transform is applied. If a
float, offset is the same for each axis. If an array, offset should
contain one value for each axis.
order: the order of the spline interpolation, default is 1. The order has
to be in the range [0-1]. Note that PIX interpolation will only be used
for order=1, for other values we use `jax.scipy.ndimage.map_coordinates`.
mode: the mode parameter determines how the input array is extended beyond
its boundaries. Default is 'nearest'. Modes 'nearest and 'constant' use
PIX interpolation, which is very fast on accelerators (especially on
TPUs). For all other modes, 'wrap', 'mirror' and 'reflect', we rely
on `jax.scipy.ndimage.map_coordinates`, which however is slow on
accelerators, so use it with care.
cval: value to fill past edges of input if mode is 'constant'. Default is
0.0.
Returns:
The input image transformed by the given matrix.
Example transformations:
- Rotation:
>>> angle = jnp.pi / 4
>>> matrix = jnp.array([
... [jnp.cos(rotation), -jnp.sin(rotation), 0],
... [jnp.sin(rotation), jnp.cos(rotation), 0],
... [0, 0, 1],
... ])
>>> result = dm_pix.affine_transform(image=image, matrix=matrix)
- Translation: Translation can be expressed through either the matrix itself
or the offset parameter.
>>> matrix = jnp.array([
... [1, 0, 0, 25],
... [0, 1, 0, 25],
... [0, 0, 1, 0],
... ])
>>> result = dm_pix.affine_transform(image=image, matrix=matrix)
>>> # Or with offset:
>>> matrix = jnp.array([
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> offset = jnp.array([25, 25, 0])
>>> result = dm_pix.affine_transform(
image=image, matrix=matrix, offset=offset)
- Reflection:
>>> matrix = jnp.array([
... [-1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> result = dm_pix.affine_transform(image=image, matrix=matrix)
- Scale:
>>> matrix = jnp.array([
... [2, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> result = dm_pix.affine_transform(image=image, matrix=matrix)
- Shear:
>>> matrix = jnp.array([
... [1, 0.5, 0],
... [0.5, 1, 0],
... [0, 0, 1],
... ])
>>> result = dm_pix.affine_transform(image=image, matrix=matrix)
One can also combine different transformations matrices:
>>> matrix = rotation_matrix.dot(translation_matrix)
"""
chex.assert_rank(image, 3)
chex.assert_rank(matrix, {1, 2})
chex.assert_rank(offset, {0, 1})
if matrix.ndim == 1:
matrix = jnp.diag(matrix)
if matrix.shape not in [(3, 3), (4, 4), (3, 4)]:
error_msg = (
"Expected matrix shape must be one of (ndim, ndim), (ndim,)"
"(ndim + 1, ndim + 1) or (ndim, ndim + 1) being ndim the image.ndim. "
f"The affine matrix provided has shape {matrix.shape}.")
raise ValueError(error_msg)
meshgrid = jnp.meshgrid(*[jnp.arange(size) for size in image.shape],
indexing="ij")
indices = jnp.concatenate(
[jnp.expand_dims(x, axis=-1) for x in meshgrid], axis=-1)
if matrix.shape == (4, 4) or matrix.shape == (3, 4):
offset = matrix[:image.ndim, image.ndim]
matrix = matrix[:image.ndim, :image.ndim]
coordinates = indices @ matrix.T
coordinates = jnp.moveaxis(coordinates, source=-1, destination=0)
# Alter coordinates to account for offset.
offset = jnp.full((3,), fill_value=offset)
coordinates += jnp.reshape(a=offset, newshape=(*offset.shape, 1, 1, 1))
interpolate_function = _get_interpolate_function(
mode=mode,
order=order,
cval=cval,
)
return interpolate_function(image, coordinates)
def rotate(
image: chex.Array,
angle: float,
*,
order: int = 1,
mode: str = "nearest",
cval: float = 0.0,
) -> chex.Array:
"""Rotates an image around its center using interpolation.
Args:
image: a JAX array representing an image. Assumes that the image is
either HWC or CHW.
angle: the counter-clockwise rotation angle in units of radians.
order: the order of the spline interpolation, default is 1. The order has
to be in the range [0,1]. See `affine_transform` for details.
mode: the mode parameter determines how the input array is extended beyond
its boundaries. Default is 'nearest'. See `affine_transform` for details.
cval: value to fill past edges of input if mode is 'constant'. Default is
0.0.
Returns:
The rotated image.
"""
# Calculate inverse transform matrix assuming clockwise rotation.
c = jnp.cos(angle)
s = jnp.sin(angle)
matrix = jnp.array([[c, s, 0], [-s, c, 0], [0, 0, 1]])
# Use the offset to place the rotation at the image center.
image_center = (jnp.asarray(image.shape) - 1.) / 2.
offset = image_center - matrix @ image_center
return affine_transform(image, matrix, offset=offset, order=order, mode=mode,
cval=cval)
def random_flip_left_right(
key: chex.PRNGKey,
image: chex.Array,
*,
probability: chex.Numeric = 0.5,
) -> chex.Array:
"""Applies `flip_left_right` with a given probability.
Args:
key: a JAX RNG key.
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
probability: the probability of applying flip_left_right transform. Must be
a value in [0, 1].
Returns:
A left-right flipped image if condition is met, otherwise original image.
"""
should_transform = jax.random.bernoulli(key=key, p=probability)
return jax.lax.cond(should_transform, flip_left_right, lambda x: x, image)
def random_flip_up_down(
key: chex.PRNGKey,
image: chex.Array,
*,
probability: chex.Numeric = 0.5,
) -> chex.Array:
"""Applies `flip_up_down` with a given probability.
Args:
key: a JAX RNG key.
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
probability: the probability of applying flip_up_down transform. Must be a
value in [0, 1].
Returns:
An up-down flipped image if condition is met, otherwise original image.
"""
should_transform = jax.random.bernoulli(key=key, p=probability)
return jax.lax.cond(should_transform, flip_up_down, lambda x: x, image)
def random_brightness(
key: chex.PRNGKey,
image: chex.Array,
max_delta: chex.Numeric,
) -> chex.Array:
"""`adjust_brightness(...)` with random delta in `[-max_delta, max_delta)`."""
delta = jax.random.uniform(key, (), minval=-max_delta, maxval=max_delta)
return adjust_brightness(image, delta)
def random_gamma(
key: chex.PRNGKey,
image: chex.Array,
min_gamma: chex.Numeric,
max_gamma: chex.Numeric,
*,
gain: chex.Numeric = 1,
assume_in_bounds: bool = False,
) -> chex.Array:
"""`adjust_gamma(...)` with random gamma in [min_gamma, max_gamma)`."""
gamma = jax.random.uniform(key, (), minval=min_gamma, maxval=max_gamma)
return adjust_gamma(
image, gamma, gain=gain, assume_in_bounds=assume_in_bounds)
def random_hue(
key: chex.PRNGKey,
image: chex.Array,
max_delta: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""`adjust_hue(...)` with random delta in `[-max_delta, max_delta)`."""
delta = jax.random.uniform(key, (), minval=-max_delta, maxval=max_delta)
return adjust_hue(image, delta, channel_axis=channel_axis)
def random_contrast(
key: chex.PRNGKey,
image: chex.Array,
lower: chex.Numeric,
upper: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""`adjust_contrast(...)` with random factor in `[lower, upper)`."""
factor = jax.random.uniform(key, (), minval=lower, maxval=upper)
return adjust_contrast(image, factor, channel_axis=channel_axis)
def random_saturation(
key: chex.PRNGKey,
image: chex.Array,
lower: chex.Numeric,
upper: chex.Numeric,
*,
channel_axis: int = -1,
) -> chex.Array:
"""`adjust_saturation(...)` with random factor in `[lower, upper)`."""
factor = jax.random.uniform(key, (), minval=lower, maxval=upper)
return adjust_saturation(image, factor, channel_axis=channel_axis)
def random_crop(
key: chex.PRNGKey,
image: chex.Array,
crop_sizes: Sequence[int],
) -> chex.Array:
"""Crop images randomly to specified sizes.
Given an input image, it crops the image to the specified `crop_sizes`. If
`crop_sizes` are lesser than the image's sizes, the offset for cropping is
chosen at random. To deterministically crop an image,
please use `jax.lax.dynamic_slice` and specify offsets and crop sizes.
Args:
key: key for pseudo-random number generator.
image: a JAX array which represents an image.
crop_sizes: a sequence of integers, each of which sequentially specifies the
crop size along the corresponding dimension of the image. Sequence length
must be identical to the rank of the image and the crop size should not be
greater than the corresponding image dimension.
Returns:
A cropped image, a JAX array whose shape is same as `crop_sizes`.
"""
image_shape = image.shape
assert len(image_shape) == len(crop_sizes), (
f"Number of image dims {len(image_shape)} and number of crop_sizes "
f"{len(crop_sizes)} do not match.")
assert image_shape >= crop_sizes, (
f"Crop sizes {crop_sizes} should be a subset of image size {image_shape} "
"in each dimension .")
random_keys = jax.random.split(key, len(crop_sizes))
slice_starts = [
jax.random.randint(k, (), 0, img_size - crop_size + 1)
for k, img_size, crop_size in zip(random_keys, image_shape, crop_sizes)
]
out = jax.lax.dynamic_slice(image, slice_starts, crop_sizes)
return out
def _channels_last(image: chex.Array, channel_axis: int):
last = channel_axis == -1 or channel_axis == (image.ndim - 1)
if not last:
assert channel_axis == -3 or channel_axis == range(image.ndim)[-3]
return last
def _depthwise_conv2d(
inputs: chex.Array,
kernel: chex.Array,
*,
strides: Tuple[int, int],
padding: str,
channel_axis: int,
dimension_numbers: Tuple[str, str, str],
) -> chex.Array:
"""Computes a depthwise conv2d in Jax.
Reference implementation: http://shortn/_oEpb0c2V3l
Args:
inputs: an NHWC or NCHW tensor (depending on dimension_numbers), with N=1.
kernel: a [H', W', 1, C] tensor.
strides: optional stride for the kernel.
padding: "SAME" or "VALID".
channel_axis: the index of the channel axis.
dimension_numbers: see jax.lax.conv_general_dilated.
Returns:
The depthwise convolution of inputs with kernel, with the same
dimension_numbers as the input.
"""
return jax.lax.conv_general_dilated(
inputs,
kernel,
strides,
padding,
feature_group_count=inputs.shape[channel_axis],
dimension_numbers=dimension_numbers)
def _get_interpolate_function(
mode: str,
order: int,
cval: float = 0.,
) -> Callable[[chex.Array, chex.Array], chex.Array]:
"""Selects the interpolation function to use based on the given parameters.
PIX interpolations are preferred given they are faster on accelerators. For
the cases where such interpolation is not implemented by PIX we relly on
jax.scipy.ndimage.map_coordinates. See specifics below.
Args:
mode: the mode parameter determines how the input array is extended beyond
its boundaries. Modes 'nearest and 'constant' use PIX interpolation, which
is very fast on accelerators (especially on TPUs). For all other modes,
'wrap', 'mirror' and 'reflect', we rely on
`jax.scipy.ndimage.map_coordinates`, which however is slow on
accelerators, so use it with care.
order: the order of the spline interpolation. The order has to be in the
range [0, 1]. Note that PIX interpolation will only be used for order=1,
for other values we use `jax.scipy.ndimage.map_coordinates`.
cval: value to fill past edges of input if mode is 'constant'.
Returns:
The selected interpolation function.
"""
if mode == "nearest" and order == 1:
interpolate_function = interpolation.flat_nd_linear_interpolate
elif mode == "constant" and order == 1:
interpolate_function = functools.partial(
interpolation.flat_nd_linear_interpolate_constant, cval=cval)
else:
interpolate_function = functools.partial(
jax.scipy.ndimage.map_coordinates, mode=mode, order=order, cval=cval)
return interpolate_function
def _get_dimension_values(
image: chex.Array,
channel_axis: int,
) -> Tuple[Optional[int], int, int, int]:
"""Gets shape values in BHWC order.
If single image is given B is None.
Small utility to get dimension values regardless of channel axis and single
image or batch of images are passed.
Args:
image: a JAX array representing an image. Assumes that the image is either
...HWC or ...CHW.
channel_axis: channel_axis: the index of the channel axis.
Returns:
A tuple with the values of each dimension in order BHWC.
"""
chex.assert_rank(image, {3, 4})
if image.ndim == 4:
if _channels_last(image=image, channel_axis=channel_axis):
batch, height, width, channel = image.shape
else:
batch, channel, height, width = image.shape
else:
if _channels_last(image=image, channel_axis=channel_axis):
batch, (height, width, channel) = None, image.shape
else:
batch, (channel, height, width) = None, image.shape
return batch, height, width, channel
|
dm_pix-master
|
dm_pix/_src/augment.py
|
# Copyright 2021 DeepMind Technologies Limited. 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_pix._src.interpolation."""
import itertools
from typing import Sequence, Tuple
from absl.testing import absltest
from absl.testing import parameterized
import chex
from dm_pix._src import interpolation
import jax.numpy as jnp
import numpy as np
_SHAPE_COORDS = ((1, 1), (1, 3), (3, 2), (4, 4), (4, 1, 4), (4, 2, 2))
_CVALS = (0.0, 1.0, -2.0)
def _prepare_inputs(
shape_output_coordinates: Tuple[int]) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""Returns the volume and coordinates to be used in the function under test.
Args:
shape_output_coordinates: [N, M] shape for the output coordinates, where N
is a scalar that determines also the number of dimensions in the volume
and M is either a scalar (output coordinates will be a 1D array) or a
vector.
"""
template_coords = jnp.array([(2, 0, 3, 2.9), (1, 0, 4.3, 1), (1, 0.5, 8.4, 1),
(21, 0.5, 4, 1)])
template_volume = jnp.array(
[[[[1.6583091, 2.0139587, 2.4636955, 0.11345804, 4.044214],
[4.538101, 4.3030543, 0.6967968, 2.0311975, 2.5746036],
[0.52024364, 4.767304, 2.3863382, 2.496363, 3.7334495],
[1.367867, 4.18175, 0.38294435, 3.9395797, 2.6097183]],
[[0.7470304, 3.8882136, 0.42186677, 1.9224191, 2.3947673],
[4.859208, 2.7876246, 0.7796812, 3.234911, 2.0911336],
[3.9205093, 4.027418, 2.9367173, 4.367462, 0.5682403],
[3.32689, 0.5056447, 1.3147497, 3.549356, 0.57163835]]],
[[[4.6056757, 3.0942523, 4.809611, 0.6062186, 4.1184435],
[1.0862654, 1.0130441, 0.24880886, 2.9144812, 2.831624],
[0.8990741, 4.6315174, 3.490876, 3.997823, 3.166548],
[2.2909844, 2.1135485, 0.7603508, 1.7530066, 3.3882804]],
[[2.2388606, 0.62632084, 0.39939642, 1.2361205, 4.4961414],
[1.3705498, 4.6373777, 2.2974424, 2.9484348, 1.8847889],
[4.856637, 3.4407651, 1.5632284, 0.30945182, 4.8406916],
[4.10108, 0.44603765, 3.893259, 2.656221, 4.652004]]],
[[[1.8670297, 4.1097646, 3.9615297, 0.9295058, 3.9903827],
[3.3507752, 1.4316595, 4.0365667, 2.3517795, 2.7806897],
[1.245628, 4.8092294, 3.3148618, 3.6758037, 2.4036856],
[4.2023296, 0.6232512, 2.2606378, 2.1633143, 3.019858]],
[[3.6607206, 0.26809275, 0.43593287, 0.3059131, 0.5254775],
[0.27680695, 0.88441014, 4.8790736, 4.796288, 4.922847],
[3.3822608, 2.5350225, 3.771946, 0.46694577, 4.0173407],
[4.835033, 4.4530325, 1.4543611, 4.67758, 3.4009826]]]])
if shape_output_coordinates[0] == 1:
volume = template_volume[0, 0, 0, :]
elif shape_output_coordinates[0] == 3:
volume = template_volume[0, :, :, :]
elif shape_output_coordinates[0] == template_volume.ndim:
volume = template_volume
else:
raise ValueError("Unsupported shape_output_coordinates[0] = "
f"{shape_output_coordinates[0]}")
if len(shape_output_coordinates) == 2:
if shape_output_coordinates <= template_coords.shape:
# Get a slice of the `template_coords`.
coordinates = template_coords[0:shape_output_coordinates[0],
0:shape_output_coordinates[1]]
if shape_output_coordinates[1] == 1:
# Do [[ num ]] -> [ num ] to test special case.
coordinates = coordinates.squeeze(axis=-1)
else:
raise ValueError("Unsupported shape_output_coordinates[1] = "
f"{shape_output_coordinates[1]}")
else:
try:
# In this case, try reshaping the _TEMPLATE_COORDS to the desired shape.
coordinates = jnp.reshape(template_coords, shape_output_coordinates)
except TypeError as e:
raise ValueError(f"Unsupported shape_output_coordinates = "
f"{shape_output_coordinates}") from e
return volume, coordinates
def _prepare_expected(shape_coordinates: Sequence[int]) -> jnp.ndarray:
if len(shape_coordinates) == 2:
if tuple(shape_coordinates) == (1, 1):
out = jnp.array(2.4636955)
elif tuple(shape_coordinates) == (1, 3):
out = jnp.array([2.4636955, 1.6583091, 0.11345804])
elif tuple(shape_coordinates) == (3, 2):
out = jnp.array([2.7876246, 1.836134])
elif shape_coordinates[0] == 4:
out = jnp.array([4.922847, 3.128356, 3.4009826, 0.88441014])
else:
raise ValueError(f"Unsupported shape_coordinates = {shape_coordinates}")
elif shape_coordinates[0] == 4:
try:
out = jnp.array([4.922847, 3.128356, 3.4009826, 0.88441014])
out = jnp.reshape(out, shape_coordinates[1:])
except TypeError as e:
raise ValueError(
f"Unsupported shape_coordinates = {shape_coordinates}") from e
else:
raise ValueError(f"Unsupported shape_coordinates = {shape_coordinates}")
return out
def _prepare_expected_const(shape_coordinates: Sequence[int],
cval: float) -> jnp.ndarray:
if len(shape_coordinates) == 2:
if tuple(shape_coordinates) == (3, 2):
out = jnp.array([cval, 1.836134])
elif shape_coordinates[0] == 4:
out = jnp.array([cval, 3.128356, cval, cval])
else:
return _prepare_expected(shape_coordinates)
elif shape_coordinates[0] == 4:
try:
out = jnp.array([cval, 3.128356, cval, cval])
out = jnp.reshape(out, shape_coordinates[1:])
except TypeError as e:
raise ValueError(
f"Unsupported shape_coordinates = {shape_coordinates}") from e
else:
raise ValueError(f"Unsupported shape_coordinates = {shape_coordinates}")
return out
class InterpolationTest(chex.TestCase, parameterized.TestCase):
@chex.all_variants
@parameterized.named_parameters([
dict(testcase_name=f"_{shape}_coords", shape_coordinates=shape)
for shape in _SHAPE_COORDS
])
def test_flat_nd_linear_interpolate(self, shape_coordinates):
volume, coords = _prepare_inputs(shape_coordinates)
expected = _prepare_expected(shape_coordinates)
flat_nd_linear_interpolate = self.variant(
interpolation.flat_nd_linear_interpolate)
np.testing.assert_allclose(
flat_nd_linear_interpolate(volume, coords), expected)
np.testing.assert_allclose(
flat_nd_linear_interpolate(
volume.flatten(), coords, unflattened_vol_shape=volume.shape),
expected)
@chex.all_variants
@parameterized.named_parameters([
(f"_{shape}_coords_{cval}_cval", shape, cval)
for cval, shape in itertools.product(_CVALS, _SHAPE_COORDS)
])
def test_flat_nd_linear_interpolate_constant(self, shape_coordinates, cval):
volume, coords = _prepare_inputs(shape_coordinates)
expected = _prepare_expected_const(shape_coordinates, cval)
flat_nd_linear_interpolate_constant = self.variant(
interpolation.flat_nd_linear_interpolate_constant)
np.testing.assert_allclose(
flat_nd_linear_interpolate_constant(volume, coords, cval=cval),
expected)
np.testing.assert_allclose(
flat_nd_linear_interpolate_constant(
volume.flatten(),
coords,
cval=cval,
unflattened_vol_shape=volume.shape), expected)
if __name__ == "__main__":
absltest.main()
|
dm_pix-master
|
dm_pix/_src/interpolation_test.py
|
# Copyright 2020 DeepMind Technologies Limited. 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_pix API."""
import inspect
from absl.testing import absltest
from absl.testing import parameterized
import dm_pix as pix
from dm_pix._src import test_utils
class ApiTest(parameterized.TestCase):
@parameterized.named_parameters(*test_utils.get_public_functions(pix))
def test_key_argument(self, f):
sig = inspect.signature(f)
param_names = tuple(sig.parameters)
self.assertNotIn("rng", param_names,
"Prefer `key` to `rng` in PIX (following JAX).")
if "key" in param_names:
self.assertLess(
param_names.index("key"), param_names.index("image"),
"RNG `key` argument should be before `image` in PIX.")
@parameterized.named_parameters(*test_utils.get_public_functions(pix))
def test_kwarg_only_defaults(self, f):
argspec = inspect.getfullargspec(f)
if f.__name__ == "rot90":
# Special case for `k` in rot90.
self.assertLen(argspec.defaults, 1)
return
self.assertEmpty(
argspec.defaults or (),
"Optional keyword arguments in PIX should be keyword "
"only. Prefer `f(x, *, axis=-1)` to `f(x, axis=-1)`.")
if __name__ == "__main__":
absltest.main()
|
dm_pix-master
|
dm_pix/_src/api_test.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Configuration file for the Sphinx documentation builder."""
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# pylint: disable=g-bad-import-order
# pylint: disable=g-import-not-at-top
import inspect
import os
import sys
import typing
def _add_annotations_import(path):
"""Appends a future annotations import to the file at the given path."""
with open(path) as f:
contents = f.read()
if contents.startswith('from __future__ import annotations'):
# If we run sphinx multiple times then we will append the future import
# multiple times too.
return
assert contents.startswith('#'), (path, contents.split('\n')[0])
with open(path, 'w') as f:
# NOTE: This is subtle and not unit tested, we're prefixing the first line
# in each Python file with this future import. It is important to prefix
# not insert a newline such that source code locations are accurate (we link
# to GitHub). The assertion above ensures that the first line in the file is
# a comment so it is safe to prefix it.
f.write('from __future__ import annotations ')
f.write(contents)
def _recursive_add_annotations_import():
for path, _, files in os.walk('../dm_pix/'):
for file in files:
if file.endswith('.py'):
_add_annotations_import(os.path.abspath(os.path.join(path, file)))
if 'READTHEDOCS' in os.environ:
_recursive_add_annotations_import()
# We remove `None` type annotations as this breaks Sphinx under Python 3.7 and
# 3.8 with error `AssertionError: Invalid annotation [...] None is not a class.`
filter_nones = lambda x: dict((k, v) for k, v in x.items() if v is not None)
typing.get_type_hints = lambda obj, *unused: filter_nones(obj.__annotations__)
sys.path.insert(0, os.path.abspath('../'))
sys.path.append(os.path.abspath('ext'))
import dm_pix as pix
import sphinxcontrib.katex as katex
# -- Project information -----------------------------------------------------
project = 'PIX'
copyright = '2021, DeepMind' # pylint: disable=redefined-builtin
author = 'PIX Contributors'
# -- General configuration ---------------------------------------------------
master_doc = 'index'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.intersphinx',
'sphinx.ext.linkcode',
'sphinx.ext.napoleon',
'sphinxcontrib.bibtex',
'sphinxcontrib.katex',
'sphinx_autodoc_typehints',
'sphinx_rtd_theme',
'coverage_check',
'myst_nb', # This is used for the .ipynb notebooks
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for autodoc -----------------------------------------------------
autodoc_default_options = {
'member-order': 'bysource',
'special-members': True,
'exclude-members': '__repr__, __str__, __weakref__',
}
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# html_favicon = '_static/favicon.ico'
# -- Options for bibtex ------------------------------------------------------
bibtex_bibfiles = []
# -- Options for myst -------------------------------------------------------
jupyter_execute_notebooks = 'force'
execution_allow_errors = False
# -- Options for katex ------------------------------------------------------
# See: https://sphinxcontrib-katex.readthedocs.io/en/0.4.1/macros.html
latex_macros = r"""
\def \d #1{\operatorname{#1}}
"""
# Translate LaTeX macros to KaTeX and add to options for HTML builder
katex_macros = katex.latex_defs_to_katex_macros(latex_macros)
katex_options = 'macros: {' + katex_macros + '}'
# Add LaTeX macros for LATEX builder
latex_elements = {'preamble': latex_macros}
# -- Source code links -------------------------------------------------------
def linkcode_resolve(domain, info):
"""Resolve a GitHub URL corresponding to Python object."""
if domain != 'py':
return None
try:
mod = sys.modules[info['module']]
except ImportError:
return None
obj = mod
try:
for attr in info['fullname'].split('.'):
obj = getattr(obj, attr)
except AttributeError:
return None
else:
obj = inspect.unwrap(obj)
try:
filename = inspect.getsourcefile(obj)
except TypeError:
return None
try:
source, lineno = inspect.getsourcelines(obj)
except OSError:
return None
return 'https://github.com/deepmind/dm_pix/tree/master/dm_pix/%s#L%d#L%d' % (
os.path.relpath(filename, start=os.path.dirname(
pix.__file__)), lineno, lineno + len(source) - 1)
# -- Intersphinx configuration -----------------------------------------------
intersphinx_mapping = {
'jax': ('https://jax.readthedocs.io/en/latest/', None),
}
source_suffix = ['.rst', '.md', '.ipynb']
|
dm_pix-master
|
docs/conf.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Asserts all public symbols are covered in the docs."""
from typing import Any, Mapping, Set
import dm_pix as pix
from dm_pix._src import test_utils
from sphinx import application
from sphinx import builders
from sphinx import errors
class PixCoverageCheck(builders.Builder):
"""Builder that checks all public symbols are included."""
name = "coverage_check"
def get_outdated_docs(self) -> str:
return "coverage_check"
def write(self, *ignored: Any) -> None:
pass
def finish(self) -> None:
def dm_pix_public_symbols() -> Set[str]:
symbols = set()
for symbol_name, _ in test_utils.get_public_symbols(pix):
symbols.add("dm_pix." + symbol_name)
return symbols
documented_objects = frozenset(self.env.domaindata["py"]["objects"])
undocumented_objects = dm_pix_public_symbols() - documented_objects
if undocumented_objects:
undocumented_objects = tuple(sorted(undocumented_objects))
raise errors.SphinxError(
"All public symbols must be included in our documentation, did you "
"forget to add an entry to `api.rst`?\n"
f"Undocumented symbols: {undocumented_objects}.")
def setup(app: application.Sphinx) -> Mapping[str, Any]:
app.add_builder(PixCoverageCheck)
return dict(version=pix.__version__, parallel_read_safe=True)
|
dm_pix-master
|
docs/ext/coverage_check.py
|
# Copyright 2021 DeepMind Technologies Limited. 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.
"""Examples of image augmentations with Pix."""
from absl import app
import dm_pix as pix
import jax.numpy as jnp
import numpy as np
import PIL.Image as pil
_KERNEL_SIGMA = 5
_KERNEL_SIZE = 5
_MAGIC_VALUE = 0.42
def main(_) -> None:
# Load an image.
image = _get_image()
# Flip up-down the image and visual it.
flip_up_down_image = pix.flip_up_down(image=image)
_imshow(flip_up_down_image)
# Apply a Gaussian filter to the image and visual it.
gaussian_blur_image = pix.gaussian_blur(
image=image,
sigma=_KERNEL_SIGMA,
kernel_size=_KERNEL_SIZE,
)
_imshow(gaussian_blur_image)
# Change image brightness and visual it.
adjust_brightness_image = pix.adjust_brightness(
image=image,
delta=_MAGIC_VALUE,
)
_imshow(adjust_brightness_image)
# Change image contrast and visual it.
adjust_contrast_image = pix.adjust_contrast(
image=image,
factor=_MAGIC_VALUE,
)
_imshow(adjust_contrast_image)
# Change image gamma and visual it.
adjust_gamma_image = pix.adjust_gamma(
image=image,
gamma=_MAGIC_VALUE,
)
_imshow(adjust_gamma_image)
# Change image hue and visual it.
adjust_hue_image = pix.adjust_hue(
image=image,
delta=_MAGIC_VALUE,
)
_imshow(adjust_hue_image)
def _get_image():
return jnp.array(pil.open("./assets/jax_logo.jpg"), dtype=jnp.float32) / 255.
def _imshow(image: jnp.ndarray) -> None:
"""Showes the input image using PIL/Pillow backend."""
image = pil.fromarray(np.asarray(image * 255.).astype(np.uint8), "RGB")
image.show()
if __name__ == "__main__":
app.run(main)
|
dm_pix-master
|
examples/image_augmentation.py
|
# Copyright 2020 DeepMind Technologies Limited.
#
# 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
#
# https://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.
# ============================================================================
"""Setup for pip package."""
import unittest
import setuptools
REQUIRED_PACKAGES = [
'absl-py>=0.12.0',
'chex>=0.0.7',
'dm-haiku>=0.0.4',
'jax>=0.2.16',
'jaxlib>=0.1.68',
'matplotlib>=3.4.2',
'ml-collections>=0.1.0',
'numpy>=1.19.5',
'optax>=0.0.8',
'pytest>=6.2.4',
'scipy>=1.7.0',
'tensorflow>=2.5.0',
'tensorflow_probability>=0.13.0',
'tensorflow_datasets>=4.3.0',
]
def aft_test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover(
'annealed_flow_transport', pattern='*_test.py')
return test_suite
setuptools.setup(
name='annealed_flow_transport',
version='1.0',
description='Implementation of Annealed Flow Transport Monte Carlo',
url='https://github.com/deepmind/annealed_flow_transport',
author='DeepMind',
author_email='alexmatthews@google.com',
# Contained modules and scripts.
packages=setuptools.find_packages(),
install_requires=REQUIRED_PACKAGES,
platforms=['any'],
license='Apache 2.0',
test_suite='setup.aft_test_suite',
)
|
annealed_flow_transport-master
|
setup.py
|
# Copyright 2021 DeepMind Technologies Limited.
#
# 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
#
# https://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.
"""Entry point for evaluation algorithms."""
from typing import Sequence
from absl import app
from absl import flags
from annealed_flow_transport import evaluation
from ml_collections.config_flags import config_flags
FLAGS = flags.FLAGS
config_flags.DEFINE_config_file('config',
'./configs/single_normal.py',
'Evaluate configuration.')
def main(argv: Sequence[str]) -> None:
config = FLAGS.config
if len(argv) > 1:
raise app.UsageError('Too many command-line arguments.')
evaluation.run_experiment(config)
if __name__ == '__main__':
app.run(main)
|
annealed_flow_transport-master
|
evaluate.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.