Skip to content

Commit

Permalink
Move pub closure probability and friendship matrix to time and place …
Browse files Browse the repository at this point in the history
…module into the time and place module.

PiperOrigin-RevId: 696472872
Change-Id: Ia4e940afe7a906350592abf80bb05341f9df2e6c
  • Loading branch information
vezhnick authored and copybara-github committed Nov 14, 2024
1 parent bfde374 commit ad79494
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 152 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Copyright 2024 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.

"""A set of pub names and reasons to like them."""

import random
from examples.modular.environment import pub_coordination
from examples.modular.environment.modules import pub_coordination_london

YEAR = pub_coordination_london.YEAR
MONTH = pub_coordination_london.MONTH
DAY = pub_coordination_london.DAY

NUM_PUBS = pub_coordination_london.NUM_PUBS


def sample_parameters(seed: int | None = None):
"""Samples a set of parameters for the world configuration."""
seed = seed if seed is not None else random.getrandbits(63)
rng = random.Random(seed)

pubs = rng.sample(
list(pub_coordination_london.PUB_PREFERENCES.keys()),
pub_coordination_london.NUM_PUBS,
)
pub_preferences = {
k: pub_coordination_london.PUB_PREFERENCES[k] for k in pubs
}

config = pub_coordination.WorldConfig(
year=pub_coordination_london.YEAR,
location="London",
event="European football cup",
game_countries=pub_coordination_london.EURO_CUP_COUNTRIES,
venues=pubs,
venue_preferences=pub_preferences,
social_context=pub_coordination_london.SOCIAL_CONTEXT,
random_seed=seed,
pub_closed_probability=0.7
)

all_names = list(pub_coordination_london.MALE_NAMES) + list(
pub_coordination_london.FEMALE_NAMES
)

rng.shuffle(all_names)
config.people = all_names

for _, name in enumerate(pub_coordination_london.MALE_NAMES):
config.person_data[name] = {"gender": "male"}
for _, name in enumerate(pub_coordination_london.FEMALE_NAMES):
config.person_data[name] = {"gender": "female"}
config.player_who_knows_closed_pub = all_names[0]

return config
50 changes: 25 additions & 25 deletions examples/modular/environment/pub_coordination.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ class WorldConfig:
num_supporting_players: int = 1
num_games: int = 3
random_seed: int = 42
pub_closed_probability: float = 0.0
player_who_knows_closed_pub: str | None = None
relationship_matrix: Mapping[str, Mapping[str, float]] | None = None


def get_shared_memories_and_context(
Expand Down Expand Up @@ -208,7 +211,11 @@ def configure_players(sampled_settings: Any, rng: random.Random) -> tuple[

for i in range(sampled_settings.num_main_players):
name = names[i]
favorite_pub = sampled_settings.venues[i % num_pubs]
if 'favorite_pub' in sampled_settings.person_data[name]:
favorite_pub = sampled_settings.person_data[name]['favorite_pub']
else:
favorite_pub = sampled_settings.venues[i % num_pubs]

gender = sampled_settings.person_data[name]['gender']
config = configure_player(
name,
Expand All @@ -225,7 +232,10 @@ def configure_players(sampled_settings: Any, rng: random.Random) -> tuple[
for i in range(sampled_settings.num_supporting_players):
name = names[sampled_settings.num_main_players + i]
gender = sampled_settings.person_data[name]['gender']
favorite_pub = sampled_settings.venues[1]
if 'favorite_pub' in sampled_settings.person_data[name]:
favorite_pub = sampled_settings.person_data[name]['favorite_pub']
else:
favorite_pub = sampled_settings.venues[1]
config = configure_player(
name,
gender,
Expand Down Expand Up @@ -334,7 +344,7 @@ def add_choice_scene_spec(
scene_type_name: str,
pubs: Sequence[str],
rng: random.Random,
use_relational_matrix: bool = False,
relationship_matrix: Mapping[str, Mapping[str, float]] | None,
verbose: bool = False,
) -> tuple[scene_lib.SceneTypeSpec, CoordinationPayoffs]:
"""Add a minigame scene spec.
Expand All @@ -350,7 +360,7 @@ def add_choice_scene_spec(
scene_type_name: the name of the scene type.
pubs: the pubs to use.
rng: the random number generator to use.
use_relational_matrix: whether to use relational matrix or not.
relationship_matrix: whether to use relational matrix or not.
verbose: whether to print verbose output or not.
Returns:
Expand All @@ -366,10 +376,6 @@ def add_choice_scene_spec(
}

names = [cfg.name for cfg in player_configs]
if use_relational_matrix:
relational_matrix = sample_symmetric_relationship_matrix(names, rng)
else:
relational_matrix = None

coordination_payoffs = CoordinationPayoffs(
model=model,
Expand All @@ -380,7 +386,7 @@ def add_choice_scene_spec(
players=players,
acting_player_names=[cfg.name for cfg in player_configs],
outcome_summarization_fn=outcome_summary_fn,
relational_matrix=relational_matrix,
relational_matrix=relationship_matrix,
clock_now=clock.now,
name='scoring function',
verbose=verbose,
Expand All @@ -400,9 +406,9 @@ def add_choice_scene_spec(
verbose=verbose,
)

if use_relational_matrix:
if relationship_matrix:
friendship_statements = generate_relationship_statements(
names, relational_matrix, rng
names, relationship_matrix, rng
)
else:
friendship_statements = {name: [''] for name in names}
Expand Down Expand Up @@ -431,10 +437,8 @@ def configure_scenes(
main_player_configs: Sequence[formative_memories.AgentConfig],
supporting_player_configs: Sequence[formative_memories.AgentConfig],
start_time: datetime.datetime,
pub_closed_probability: float,
sampled_settings: Any,
rng: random.Random,
use_relational_matrix: bool = False,
) -> tuple[
Sequence[scene_lib.SceneSpec],
Callable[[], Mapping[str, float]],
Expand All @@ -450,10 +454,8 @@ def configure_scenes(
main_player_configs: configs for the main characters
supporting_player_configs: configs for the supporting characters
start_time: the start time/date in the game world for the first scene
pub_closed_probability: the probability that a pub is closed
sampled_settings: the sampled settings for the world configuration
rng: the random number generator to use
use_relational_matrix: whether to use relational matrix or not
Returns:
scenes: a sequence of scene specifications
Expand All @@ -465,6 +467,8 @@ def configure_scenes(
scenes = []
pubs = sampled_settings.venues

pub_closed_probability = sampled_settings.pub_closed_probability

secondary_environments = []

for i in range(sampled_settings.num_games):
Expand Down Expand Up @@ -492,8 +496,11 @@ def configure_scenes(
}

if closed_pub:
players_in_the_know = player_configs[0]
player_name = players_in_the_know.name
if sampled_settings.player_who_knows_closed_pub:
player_name = sampled_settings.player_who_knows_closed_pub
else:
player_name = rng.choice(player_configs).name

per_player_premise[player_name].append(
f'{player_name} have learnt that {closed_pub} is closed today. Going'
' there would be a bad idea.'
Expand Down Expand Up @@ -521,7 +528,7 @@ def configure_scenes(
scene_type_name=DECISION_SCENE_TYPE,
pubs=pubs,
rng=rng,
use_relational_matrix=use_relational_matrix,
relationship_matrix=sampled_settings.relationship_matrix,
)
coordination_payoffs.append(this_coordination_payoff)
scene_specs[DECISION_SCENE_TYPE] = choice_scene_spec
Expand Down Expand Up @@ -685,8 +692,6 @@ def __init__(
resident_visitor_modules: Sequence[types.ModuleType] | None = None,
supporting_agent_module: types.ModuleType | None = None,
time_and_place_module: str | None = None,
pub_closed_probability: float = 0.0,
use_relational_matrix: bool = False,
seed: int | None = None,
):
"""Initialize the simulation object.
Expand All @@ -711,9 +716,6 @@ def __init__(
time_and_place_module: optionally, specify a module containing settings
that create a sense of setting in a specific time and place. If not
specified, a random module will be chosen from the default options.
pub_closed_probability: the probability that a pub is closed. Zero by
default.
use_relational_matrix: whether to use relational matrix or not.
seed: the random seed to use.
"""
# Support for these parameters will be added in a future addition coming
Expand Down Expand Up @@ -905,9 +907,7 @@ def __init__(
supporting_player_configs=supporting_player_configs,
sampled_settings=sampled_settings,
start_time=start_time,
pub_closed_probability=pub_closed_probability,
rng=self._rng,
use_relational_matrix=use_relational_matrix,
)
)

Expand Down
38 changes: 0 additions & 38 deletions examples/modular/environment/pub_coordination_closures.py

This file was deleted.

This file was deleted.

35 changes: 0 additions & 35 deletions examples/modular/environment/pub_coordination_friendships.py

This file was deleted.

16 changes: 2 additions & 14 deletions examples/modular/scenario/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,6 @@ class ScenarioConfig:
environment='pub_coordination',
supporting_agent_module='basic_puppet_agent',
),
pub_coordination_closures=SubstrateConfig(
description=(
'pub attendance coordination with one pub sometimes being closed'
),
environment='pub_coordination_closures',
supporting_agent_module='basic_puppet_agent',
),
pub_coordination_friendships=SubstrateConfig(
description='pub attendance coordination with friendship network',
environment='pub_coordination_friendships',
supporting_agent_module='basic_puppet_agent',
),
haggling=SubstrateConfig(
description='haggling over a price',
environment='haggling',
Expand Down Expand Up @@ -218,9 +206,9 @@ class ScenarioConfig:
' with a chance of a pub being closed and a'
' rational visitor agent and a stubborn on supporting agent.'
),
substrate_config=SUBSTRATE_CONFIGS['pub_coordination_closures'],
substrate_config=SUBSTRATE_CONFIGS['pub_coordination'],
background_agent_module='rational_agent',
time_and_place_module='pub_coordination_london',
time_and_place_module='pub_coordination_london_closures',
focal_is_resident=False,
tags=('coordination', 'persuasion', 'social networks'),
),
Expand Down

0 comments on commit ad79494

Please sign in to comment.