unaiverse.world¶
This module holds World, the class of a world. A world is a community of agents with rules: it decides who may enter and gives each member a role. Together with the role it sends the behavior of that role and the Python code of its actions. It also collects the statistics of its members and assigns badges. Technically a world is an agent (a subclass of AgentBasics) without processor and without behavior of its own, hosted by a Node like any agent:
from unaiverse.world import World
from unaiverse.networking.node.node import Node
world = World(world_folder="classroom/")
Node(world, node_name="Classroom", hidden=False).run()
A world with its own rules is a subclass of World that overrides assign_role, create_behav_files or answer_stats_request. The node calls every other public method of this class when it receives messages from the members. A world program rarely calls them itself.
The world folder¶
The folder passed as world_folder defines the roles and their code.
classroom/
├── teacher.json # behavior of the role "teacher"
├── teacher.py # class WAgent(Agent) with the actions of the teacher
├── student.json
├── student.py
├── grading.py # optional, imported by the role files with "from .grading import ..."
├── stats.py # optional, class WStats(Stats)
├── pdf/ # written by the world: one drawing per role
└── stats/ # written by the world: world_stats.db
When the World object is created, the constructor of AgentBasics prepares the folder in five steps.
- It calls the hook
create_behav_files(). The base hook does nothing and a subclass overrides it to write the JSON files in code. - It lists in alphabetical order the files of the folder whose extension is
.json(case-insensitive). The names without extension becomeCUSTOM_ROLESand their order becomes the order of the roles. A folder without JSON files raisesGenException. More than 30 roles raiseGenException. - It reads every
.pyfile of the folder and of its subfolders other thanpdf/andstats/. Each role needs a file<role>.pythat defines a classWAgent. When a role has no<role>.pyand the folder holds anagent.py, the content ofagent.pybecomes the code of every role and the existing<role>.pyfiles are ignored. A folder with neither raisesGenException. - For each role it creates a test instance of
WAgentwithproc=Noneand loads the JSON file into aHybridStateMachineof that instance. An action named in the behavior and missing fromWAgentstops the world withGenException. AWAgentthat declares a non-emptyCUSTOM_ROLESdifferent from the roles of the folder stops it too. The normalized behavior is stored as a JSON string inrole_to_behav[role]. - It saves each behavior back to
<role>.jsonand draws it inpdf/<role>.pdfwhen the content changed or when a JSON file of the folder changed since the previous run. Drawing needs the Graphviz program.
The roles then combine with the two base roles into the role names of the world (see Roles).
The code shipped to members¶
A member does not install the code of the world. When the world admits an agent, the grant it sends holds a bundle with two fields: agent_files (the packed Python sources) and roles_fsm (the dictionary role_to_behav). agent_files holds the role files, every file that they reach through relative imports (from .grading import score, followed until nothing new appears) and stats.py. Absolute imports are not followed. Every other file of the folder stays on the world machine. Code that only the world needs (for example the code that computes the grades) therefore never leaves the world machine. The packed sources are in packed_agent_files.
The joining node checks the sources with a static analysis before running them and then replaces its agent with an instance of the WAgent of its role. stats.py runs on the member in a bare module where relative imports do not resolve. The member uses the class WStats of that file. When the class is missing or the file raises an exception, the member logs an error and uses the default Stats. The checks and the swap of the agent are described in Worlds.
Roles¶
A role is stored as an integer used as a bit mask. The two lowest bits are the base role: 0 is public_agent, 1 is world_agent and 3 is world_master. Each role of the folder takes one higher bit in the order of CUSTOM_ROLES: the first one is 4, the second 8 and so on. A member has a base role and at most one custom role. Its full name joins the two with ~: world_agent~student is 1 | 8 = 9 and world_master~teacher is 3 | 4 = 7. The dictionaries ROLE_BITS_TO_STR and ROLE_STR_TO_BITS of the world map the integers to the names and back.
| Event | What decides the role |
|---|---|
| An agent asks to join | assign_role(profile, is_world_master) returns the name of the custom role (or of a base role). The node adds the base bits of a world master or of a world agent. None refuses the agent. |
| A world master suggests a change | The member runs the action suggest_role_to_world(agent, role). The world accepts suggestions from world masters alone and applies each one with set_role(peer_id, role). |
| The world changes a role itself | The world program awaits set_role(peer_id, role). |
An agent is a world master when its node id (or node name) is in the list world_masters_node_ids (world_masters_node_names) of the node of the world or in the online profile of the world. The base policy places no limit on the number of masters.
World
¶
World(world_folder: str, merge_flat_stream_labels: bool = False, stats: Stats | None = None)
Bases: AgentBasics
Source code in unaiverse/world.py
The world. Creating it reads and normalizes the world folder as described above and opens the statistics database.
| Argument | Type | Default | Meaning |
|---|---|---|---|
world_folder |
str |
required | The path of the world folder. |
merge_flat_stream_labels |
bool |
False |
The option of AgentBasics that merges the labels of flat streams across the streams owned by the world. |
stats |
Stats \| None |
None |
The object that records the statistics. None creates Stats(is_world=True, db_path=f"{world_folder}/stats/world_stats.db", cache_window_hours=2.0). A world with a custom WStats passes an instance of it here. |
Errors of the world folder raise GenException (see The world folder).
| Attribute | Type | Meaning |
|---|---|---|
world_folder |
str |
The world folder. |
stats |
Stats |
The statistics of the world (see unaiverse.stats). |
CUSTOM_ROLES |
list[str] |
The roles of the folder in alphabetical order. |
ROLE_BITS_TO_STR, ROLE_STR_TO_BITS |
dict |
The role names by integer and the integers by name for the base, custom and combined roles. |
role_to_behav |
dict[str, str] |
The normalized behavior of each role as a JSON string. |
packed_agent_files |
str |
The packed Python sources shipped to the members. |
all_agents |
dict[str, NodeProfile] |
The profiles of the connected members by private peer id. |
world_masters, world_agents |
dict[str, NodeProfile] |
The members by base role. |
human_agents, artificial_agents |
dict[str, NodeProfile] |
The members by kind. |
private_peer_of |
dict[str, str] |
The private peer id of each member by its public peer id. |
agent_badges |
dict[str, list[dict]] |
The badges not yet sent to the server grouped by peer id. |
BADGE_TYPES |
set[str] |
{'completed', 'attended', 'intermediate', 'pro'}. |
proc, proc_inputs, proc_outputs, proc_opts |
Always None, [], [] and {}: a world has no processor. |
create_behav_files
¶
Source code in unaiverse/agent_basics.py
A hook that the world calls at creation before reading the folder (step 1 of The world folder). The base method does nothing and returns None. A subclass overrides it to build the behaviors of its roles in code and write them as <role>.json. The method is defined in AgentBasics and World inherits it.
import os
from unaiverse.world import World
from unaiverse.hsm import HybridStateMachine
class Classroom(World):
def create_behav_files(self):
from .teacher import WAgent as Teacher
teacher = Teacher(proc=None)
behav = HybridStateMachine(teacher)
behav.add_transit("init", "engaged", action="find_agents", args={"role": "student", "engage": True})
behav.add_transit("engaged", "init", action="disengage_all", timeout=30.)
behav.add_wildcards({"<exam_steps>": 30})
behav.set_role("teacher")
behav.save(os.path.join(self.world_folder, "teacher.json"), only_if_changed=teacher)
With only_if_changed the file stays untouched when its content did not change and the drawings in pdf/ are not rebuilt at every start.
assign_role
¶
assign_role(profile: NodeProfile, is_world_master: bool) -> str | None
Source code in unaiverse/world.py
Chooses the role of an agent that asks to join and returns its name as a string. The node calls it during the admission of each agent. The base method returns "world_master" when is_world_master is True and "world_agent" otherwise. A subclass returns one of CUSTOM_ROLES to give a custom role or None to refuse the agent.
| Argument | Type | Meaning |
|---|---|---|
profile |
NodeProfile |
The profile of the joining agent. Its dynamic part holds the options of the join request as temporary keys tmp_<option>: an agent started with node.run(join_world="Classroom", role_preference="student") arrives with profile.get_dynamic_profile()["tmp_role_preference"] == "student". The node removes these keys after the call. |
is_world_master |
bool |
Whether the node of the agent is on the list of world masters. |
class Classroom(World):
def assign_role(self, profile, is_world_master):
if is_world_master:
return "teacher"
wanted = profile.get_dynamic_profile().get("tmp_role_preference")
return "student" if wanted in (None, "student") else None
A returned name missing from ROLE_STR_TO_BITS raises KeyError in the node. The node then adds the base bits of a world master or of a world agent to the custom bits of the returned role.
set_role
async
¶
Source code in unaiverse/world.py
Changes the custom role of the member peer_id and sends it the behavior of the new role. Asynchronous. role is a role bit mask whose two lowest bits are ignored: the member keeps its base role and takes the custom bits of role. Nothing happens when the resulting role equals the current one.
When the role changes, the world records it, marks role_changed_by_world and sends the member a message with the new role and role_to_behav of the new custom role. The member then swaps its agent for the WAgent of the new role. A send refused by a full queue is logged and the member keeps its old role on its side. Any other send failure removes the member from the world. Because role_to_behav has no entry for a base role, a role without custom bits raises KeyError when the member had a custom role.
add_badge
¶
add_badge(peer_id: str, score: float, badge_type: str, agent_token: str, badge_description: str | None = None) -> None
Source code in unaiverse/world.py
Records a badge for the member peer_id in agent_badges and returns None. The node calls it for every badge that a member suggests with the action suggest_badges_to_world. In the current version the node accepts the badges suggested by any member.
| Argument | Type | Default | Meaning |
|---|---|---|---|
peer_id |
str |
required | The private peer id of the member. A peer id missing from all_agents raises KeyError. |
score |
float |
required | A value in [0, 1]. Any other value raises ValueError. |
badge_type |
str |
required | One of completed, attended, intermediate and pro. Any other value raises ValueError. |
agent_token |
str |
required | The token of the member that the server needs to assign the badge. |
badge_description |
str \| None |
None |
A free text. None becomes "". |
The stored badge is a dictionary with the keys agent_node_id, agent_token, badge_type, score, badge_description and last_edit_utc (the ISO time of the clock). The node sends the collected badges to the UNaIVERSE server, tells each rewarded member to download its updated profile and then empties the list with clear_badges().
get_all_badges
¶
Source code in unaiverse/world.py
Returns agent_badges, the dictionary from peer id to the list of badges not yet sent. The dictionary is not a copy.
clear_badges
¶
Empties the list of badges not yet sent. The node calls it after a successful round with the server. Returns None.
add_agent
async
¶
add_agent(peer_id: str, profile: NodeProfile, add_proc_streams: bool = True, add_env_streams: bool = True, add_pubsub_streams: bool = True) -> bool
Source code in unaiverse/world.py
Adds a member through AgentBasics.add_agent() and records the mapping from its public peer id (read from profile) to its private peer id peer_id in private_peer_of. Asynchronous. Returns the result of AgentBasics.add_agent(). The three flags about streams are part of the signature of the parent and the world ignores them. The node calls it when a member completes the handshake.
remove_agent
async
¶
Source code in unaiverse/world.py
Removes the member peer_id through AgentBasics.remove_agent(). Asynchronous. The parent method removes the member from every list, drops its streams and interactions and returns None. This method therefore always returns False and never deletes the entry of the member from private_peer_of. The node calls it when a member leaves.
set_addresses_in_profile
¶
Source code in unaiverse/world.py
Replaces the private addresses in the profile of the member peer_id with addresses and marks received_address_update. The list object in the profile is emptied and refilled in place because other parts of the node hold a reference to it. An unknown peer_id is logged as an error. The node calls it when a member announces new addresses. Returns None.
Statistics¶
Every member sends its statistics to the world every Custom.SEND_STATS_EVERY seconds (30 by default, changed by the argument send_stats_every of Node). The world merges them into stats and saves them to disk every Custom.SAVE_STATS_EVERY seconds. The format of the statistics and the database are described in unaiverse.stats.
collect_and_store_own_stats
¶
Source code in unaiverse/world.py
Stores the four counters of the world (world_masters, world_agents, human_agents and artificial_agents) in stats with the current time of the clock in milliseconds. The group key is the private peer id of the world. Errors are logged. add_peer_stats() calls it before processing each batch. Returns None.
add_peer_stats
¶
Source code in unaiverse/world.py
Processes one batch of statistics received from a member and returns None. The node calls it for every statistics message. Each element of peer_stats_batch is a dictionary with the keys group_key (the peer id the value refers to), stat_name, timestamp (milliseconds) and value. The method works in four steps.
- It stores the counters of the world with
collect_and_store_own_stats(). - It offers each update to the protected hook
_process_custom_stat(stat_name, value, group_key, timestamp). A subclass overrides the hook and returnsTrueto take over an update. The base hook returnsFalse. - It keeps the updates named
connected_peersfor the graph and stores every other update whose name is known tostats. An unknown name and a malformed update are logged and skipped. - It updates the connectivity graph (the static statistic
graph) with theconnected_peersof the batch and removes from the graph the peers that are no longer members.
The method ignores sender_peer_id.
answer_stats_request
¶
Source code in unaiverse/world.py
Answers a statistics request of a member and returns a dictionary shaped like Stats.get_view(). The node calls it when a member runs the action ask_world_stats(filters) with a non-empty stat_names. Without stat_names the node answers with the HTML of stats.plot() instead and this method is not called. The base method passes the filters to Stats.query_history().
Key of filters |
Default | Meaning |
|---|---|---|
stat_names |
[] |
The names of the statistics to return. |
group_keys |
[] |
The peer ids to return. An empty list means all. |
time_range |
0 |
An integer t keeps the values from t on and a pair [start, end] keeps the closed interval. Both forms are in milliseconds. |
value_range |
None |
A pair [min, max] that keeps the numeric values in the closed interval. |
limit |
None |
The maximum number of time-series rows. Values above 5000 are lowered to 5000. |
asker is the peer id of the member that asked. The base method only asserts that it is not None. A subclass uses it to decide what each member may see:
class Classroom(World):
def answer_stats_request(self, filters, asker):
if asker not in self.world_masters:
filters = {**filters, "group_keys": [asker]} # a student sees only itself
return super().answer_stats_request(filters, asker)
debug_stats_dashboard
¶
Source code in unaiverse/world.py
Renders stats.plot() to a temporary HTML file and opens it in the default web browser. It is meant for development on a machine with a browser and returns None. Nothing opens when plot() returns None.