From ad7949468a1632884689387565d2a7c445c7b067 Mon Sep 17 00:00:00 2001 From: Sasha Vezhnevets Date: Thu, 14 Nov 2024 04:27:57 -0800 Subject: [PATCH] Move pub closure probability and friendship matrix to time and place module into the time and place module. PiperOrigin-RevId: 696472872 Change-Id: Ia4e940afe7a906350592abf80bb05341f9df2e6c --- .../pub_coordination_london_closures.py | 66 +++++++++++++++++++ .../modular/environment/pub_coordination.py | 50 +++++++------- .../environment/pub_coordination_closures.py | 38 ----------- .../pub_coordination_closures_friendships.py | 40 ----------- .../pub_coordination_friendships.py | 35 ---------- examples/modular/scenario/scenarios.py | 16 +---- 6 files changed, 93 insertions(+), 152 deletions(-) create mode 100644 examples/modular/environment/modules/pub_coordination_london_closures.py delete mode 100644 examples/modular/environment/pub_coordination_closures.py delete mode 100644 examples/modular/environment/pub_coordination_closures_friendships.py delete mode 100644 examples/modular/environment/pub_coordination_friendships.py diff --git a/examples/modular/environment/modules/pub_coordination_london_closures.py b/examples/modular/environment/modules/pub_coordination_london_closures.py new file mode 100644 index 00000000..b2317b9f --- /dev/null +++ b/examples/modular/environment/modules/pub_coordination_london_closures.py @@ -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 diff --git a/examples/modular/environment/pub_coordination.py b/examples/modular/environment/pub_coordination.py index 57cbf64b..fcbff2dd 100644 --- a/examples/modular/environment/pub_coordination.py +++ b/examples/modular/environment/pub_coordination.py @@ -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( @@ -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, @@ -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, @@ -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. @@ -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: @@ -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, @@ -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, @@ -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} @@ -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]], @@ -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 @@ -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): @@ -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.' @@ -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 @@ -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. @@ -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 @@ -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, ) ) diff --git a/examples/modular/environment/pub_coordination_closures.py b/examples/modular/environment/pub_coordination_closures.py deleted file mode 100644 index 18b3b1ab..00000000 --- a/examples/modular/environment/pub_coordination_closures.py +++ /dev/null @@ -1,38 +0,0 @@ -# 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 Concordia Environment Configuration.""" - -from examples.modular.environment import pub_coordination - - -class Simulation(pub_coordination.Simulation): - """Simulation with pub closures.""" - - def __init__( - self, - **kwargs, - ): - """Initialize the simulation object. - - The launch script assumes this API object has a run() method. - - Args: - **kwargs: arguments to pass to the base class. - """ - - super().__init__( - pub_closed_probability=0.7, - **kwargs, - ) diff --git a/examples/modular/environment/pub_coordination_closures_friendships.py b/examples/modular/environment/pub_coordination_closures_friendships.py deleted file mode 100644 index 83f2928b..00000000 --- a/examples/modular/environment/pub_coordination_closures_friendships.py +++ /dev/null @@ -1,40 +0,0 @@ -# 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 Concordia Environment Configuration.""" - - -from examples.modular.environment import pub_coordination - - -class Simulation(pub_coordination.Simulation): - """Simulation with pub closures.""" - - def __init__( - self, - **kwargs, - ): - """Initialize the simulation object. - - The launch script assumes this API object has a run() method. - - Args: - **kwargs: arguments to pass to the base class. - """ - - super().__init__( - pub_closed_probability=0.7, - use_relational_matrix=True, - **kwargs, - ) diff --git a/examples/modular/environment/pub_coordination_friendships.py b/examples/modular/environment/pub_coordination_friendships.py deleted file mode 100644 index 61650ff6..00000000 --- a/examples/modular/environment/pub_coordination_friendships.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 Concordia Environment Configuration.""" - -from examples.modular.environment import pub_coordination - - -class Simulation(pub_coordination.Simulation): - """Simulation with pub closures.""" - - def __init__(self, **kwargs): - """Initialize the simulation object. - - The launch script assumes this API object has a run() method. - - Args: - **kwargs: arguments to pass to the base class. - """ - - super().__init__( - use_relational_matrix=True, - **kwargs, - ) diff --git a/examples/modular/scenario/scenarios.py b/examples/modular/scenario/scenarios.py index 9818dece..c274c574 100644 --- a/examples/modular/scenario/scenarios.py +++ b/examples/modular/scenario/scenarios.py @@ -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', @@ -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'), ),