Skip to content

unaiverse.stats

This module records the statistics of a world. A world keeps the number of its members, the connectivity graph between them and what each member is doing (its state, its action, its last completed action). Members measure their own values and send them to the world. The world stores them in memory and in a SQLite database and answers the members that ask for them. The same class Stats serves both sides with two modes:

  • agent mode (is_world=False): the object buffers the values measured by the agent until the node sends them to the world. It also keeps the view of the world statistics received in answer to a request.
  • world mode (is_world=True): the object keeps a hot cache of the recent values, writes every value to the database and answers queries over the whole history.

The node drives both modes. An agent in a world calls collect_and_store_own_stats() and sends the buffer every Custom.SEND_STATS_EVERY seconds (30 by default). The world merges each batch with World.add_peer_stats() and saves to disk every Custom.SAVE_STATS_EVERY seconds. The module also holds two small builders of Plotly figures (UIPlot and DefaultBaseDash) that Stats.plot() uses to draw the default dashboard.

Kinds of statistics

Every statistic has a name declared in a schema with its Python type and its default value. Two properties classify it.

Property Values Effect
Static or dynamic static: one current value. dynamic: a time series of values indexed by a timestamp in milliseconds. A static value replaces the previous one. A dynamic value is appended to the series.
Grouped or ungrouped ungrouped: a statistic of the world itself. grouped: a statistic of one peer, stored under a group key (the peer id). From the point of view of the world, its own schemas are ungrouped and the schemas of the agents and of other peers are grouped.

The schemas that ship with the SDK define these statistics.

Name Schema Type, default Meaning
graph world, static dict, {'nodes': {}, 'edges': {}} The connectivity graph of the world: nodes maps each peer id to its display fields and edges maps each peer id to the set of peers connected to it.
world_masters, world_agents, human_agents, artificial_agents world, dynamic int, 0 The number of members of each kind.
connected_peers agent, static list, [] The peer ids connected to the agent in the world.
state, action, last_action agent, static str, None The current state, the running action and the last completed action of the world behavior of the agent.

A world adds its own statistics with a subclass that fills the CUSTOM_* schemas. The subclass is named WStats and lives in stats.py in the world folder. The world ships this file to every member. It must also use the same class itself because it logs and drops every value whose name is missing from its own schemas.

# stats.py in the world folder
from unaiverse.stats import Stats

class WStats(Stats):
    CUSTOM_AGENT_STATS_DYNAMIC_SCHEMA = {"accuracy": (float, 0.0)}
    CUSTOM_WORLD_STATS_STATIC_SCHEMA = {"leaderboard": (list, [])}
# the world
import os
from unaiverse.world import World
from .stats import WStats

class Classroom(World):
    def __init__(self, **kwargs):
        folder = os.path.dirname(os.path.abspath(__file__))
        stats = WStats(is_world=True, db_path=os.path.join(folder, "stats", "world_stats.db"))
        super().__init__(world_folder=folder, stats=stats, **kwargs)
# an action of a member
_, own_private_pid = self.get_peer_ids()
self.stats.store_stat("accuracy", 0.92, group_key=own_private_pid, timestamp=clock.get_time_ms())

The view format

get_view() and query_history() return a dictionary of the following shape and update_view() merges one into the local view:

{
    "world": {"world_agents": [[1732350000000, 12], [1732350010000, 13]], "graph": {...}},
    "peers": {"12D3KooW...": {"state": "studying", "last_action": "learn"}}
}

A static value appears unchanged. A dynamic value appears as a list of [timestamp, value] pairs in increasing time order.

THEMES module-attribute

THEMES = {'dark': {'bg_paper': 'rgba(0,0,0,0)', 'bg_plot': 'rgba(0,0,0,0)', 'text_main': '#C8CDD3', 'text_light': '#677385', 'grid': '#222A36', 'edge': '#495464', 'node_border': '#F5F6F8', 'main': '#1A5CFF', 'main_light': '#4D7FFF', 'table': {'header_bg': '#16171C', 'header_txt': '#F5F6F8', 'cell_bg': '#0E0F14', 'cell_txt': '#C8CDD3', 'line': '#222A36'}, 'peers': ['#1A5CFF', '#FF3B30', '#00D4AA', '#FFB347', '#4D7FFF', '#00B391', '#FF6692', '#33EABD', '#FFD080', '#6B9BFF']}, 'light': {'bg_paper': 'rgba(255,255,255,0)', 'bg_plot': 'rgba(255,255,255,0)', 'text_main': '#0A1628', 'text_light': '#677385', 'grid': '#DBE1EB', 'edge': '#909CB0', 'node_border': '#0A1628', 'main': '#1A5CFF', 'main_light': '#4D7FFF', 'table': {'header_bg': '#F6F8FA', 'header_txt': '#0A1628', 'cell_bg': '#FFFFFF', 'cell_txt': '#0A1628', 'line': '#C0C8D6'}, 'peers': ['#1A5CFF', '#FF3B30', '#00D4AA', '#FFB347', '#4D7FFF', '#00B391', '#FF6692', '#33EABD', '#FFD080', '#6B9BFF']}}

The two color palettes of the figures, "dark" and "light". Each palette is a dictionary with the keys bg_paper, bg_plot, text_main, text_light, grid, edge, node_border, main and main_light (CSS colors), table (a dictionary with header_bg, header_txt, cell_bg, cell_txt and line) and peers (a list of ten colors assigned to peers and categories).

THEME module-attribute

THEME = THEMES['dark']

The palette THEMES["dark"] used by UIPlot, DefaultBaseDash and Stats.plot(). The builders read the module attribute at each call. Assigning unaiverse.stats.THEME = unaiverse.stats.THEMES["light"] therefore switches the figures built afterwards to the light palette.

UIPlot

UIPlot(title: str = '', height: int = 400)
Source code in unaiverse/stats.py
def __init__(self, title: str = '', height: int = 400):
    """Initializes a UIPlot with an empty data list and a pre-configured dark-theme layout.

    Args:
        title: Title text shown at the top of the plot.
        height: Height of the plot in pixels.
    """
    self._data: list[dict[str, Any]] = []

    # Define the standard axis style for a "boxed" look
    axis_style = {
        'gridcolor': THEME['grid'],
        'gridwidth': 1,
        'griddash': 'dot',
        'color': THEME['text_light'],
        'showline': True,  # Draw the axis line
        'mirror': True,  # Mirror it on top/right (creates the box)
        'linewidth': 2,  # Width of the box border
        'linecolor': THEME['grid'],  # Color of the box border
        'zeroline': False,  # Prevents double-thick borderlines at 0
        'layer': 'below traces'  # Key fix: puts grid BEHIND the box border
    }

    self._layout: dict[str, Any] = {
        'title': title,
        'height': height,
        'xaxis': {**axis_style, 'title': 'Time'},
        'yaxis': {**axis_style, 'title': 'Value'},
        'margin': {'l': 50, 'r': 50, 'b': 50, 't': 50},
        # Default dark theme friendly styling
        'paper_bgcolor': THEME['bg_paper'],
        'plot_bgcolor': THEME['bg_plot'],
        'font': {'color': THEME['text_main']}
    }

A builder of one Plotly figure (a panel) that collects traces in data and options in layout. The layout starts with transparent backgrounds, dotted grid lines, a box around the plot area and the axis titles Time and Value.

Argument Type Default Meaning
title str '' The title of the panel.
height int 400 The height in pixels.
from unaiverse.stats import UIPlot

panel = UIPlot(title="Accuracy", height=300)
panel.add_line([1, 2, 3], [0.71, 0.80, 0.86], name="student A")
panel.set_y_range(0., 1.)
figure_json = panel.to_json()

add_line

add_line(x: list[Any], y: list[Any], name: str, color: str | None = None, legend_group: str | None = None, show_legend: bool = True)
Source code in unaiverse/stats.py
def add_line(self, x: list[Any], y: list[Any], name: str, color: str | None = None,
             legend_group: str | None = None, show_legend: bool = True):
    """Adds a standard time-series line.

    Args:
        x: Sequence of x-axis values (e.g., timestamps).
        y: Sequence of y-axis values.
        name: Label shown in the legend.
        color: CSS color string for the line. Defaults to the primary theme color.
        legend_group: Plotly legend group name for toggling related traces together.
        show_legend: Whether to display this trace in the legend.
    """
    if color is None:
        color = THEME['main']
    trace = {
        'x': x, 'y': y,
        'name': name,
        'type': 'scatter',
        'mode': 'lines+markers',
        'line': {'color': color},
        "legendgroup": legend_group,
        "showlegend": show_legend
    }
    self._data.append(trace)

Appends a scatter trace drawn with lines and markers from the points x and y. name labels it in the legend and color gives its CSS color (THEME['main'] by default). Traces with the same legend_group are shown and hidden together from the legend. show_legend=False hides the trace from the legend. Returns None.

add_area

add_area(x: list[Any], y: list[Any], name: str, color: str | None = None)
Source code in unaiverse/stats.py
def add_area(self, x: list[Any], y: list[Any], name: str, color: str | None = None):
    """Adds a filled area chart.

    Args:
        x: Sequence of x-axis values.
        y: Sequence of y-axis values.
        name: Label shown in the legend.
        color: CSS color string for the fill/line. Defaults to the primary theme color.
    """
    if color is None:
        color = THEME['main']
    trace = {
        'x': x, 'y': y, 'name': name,
        'type': 'scatter', 'fill': 'tozeroy',
        'line': {'color': color}
    }
    self._data.append(trace)

Appends a scatter trace filled down to zero from the points x and y with the legend label name and the CSS color color (THEME['main'] by default). Returns None.

add_indicator

add_indicator(value: Any, title: str)
Source code in unaiverse/stats.py
def add_indicator(self, value: Any, title: str):
    """Adds a big number indicator.

    Args:
        value: Numeric (or any) value to display prominently.
        title: Subtitle text rendered below the number.
    """
    self._data.append({
        'type': 'indicator',
        'mode': 'number',
        'value': value,
        'title': {'text': title}
    })
    self._layout['height'] = 300  # Indicators usually need less height

Appends a big-number indicator that shows value with title below it and lowers the height of the panel to 300 pixels. Returns None.

add_table

add_table(headers: list[str] | None, columns: list[list[Any]])
Source code in unaiverse/stats.py
def add_table(self, headers: list[str] | None, columns: list[list[Any]]):
    """Adds a data table.

    Args:
        headers: Column header labels, or ``None`` to hide the header row.
        columns: Column data as a list of lists, one inner list per column.
    """
    num_columns = len(columns) if columns else 0
    if headers:
        header_cfg = {
            'values': headers,
            'fill': {'color': THEME['table']['header_bg']},
            'font': {'color': THEME['table']['header_txt']},
            'line': {'color': THEME['table']['line']}
        }
    else:
        header_cfg = {
            'values': [''] * num_columns,
            'height': 0,  # Hide it
            'fill': {'color': 'rgba(0,0,0,0)'},  # Transparent just in case
            'line': {'width': 0}  # No border
        }

    trace = {
        'type': 'table',
        'header': header_cfg,
        'cells': {
            'values': columns,
            'fill': {'color': THEME['table']['cell_bg']},
            'font': {'color': THEME['table']['cell_txt']},
            'line': {'color': THEME['table']['line']}
        }
    }
    self._data.append(trace)

Appends a table. columns is a list of columns and each column is a list of cells. headers gives the column titles and None (or an empty list) hides the header row. The colors come from THEME['table']. Returns None.

add_bar

add_bar(xs: list[Any], ys: list[Any], names: list[str], colors: list[str] | str | None = None)
Source code in unaiverse/stats.py
def add_bar(self, xs: list[Any], ys: list[Any], names: list[str],
            colors: list[str] | str | None = None):
    """Adds a bar chart trace.

    Args:
        xs: Category labels for the x-axis.
        ys: Numeric values for bar heights.
        names: Text annotations placed on top of each bar.
        colors: Single CSS color string or a list of per-bar color strings.
            Defaults to the primary theme color.
    """
    if colors is None:
        colors = THEME['main']
    trace = {
        'type': 'bar',
        'x': xs,
        'y': ys,
        'marker': {'color': colors},
        'showlegend': False,
        'text': names,
        'textposition': 'auto'
    }
    self._data.append(trace)
    self._layout['yaxis'].update({'title': 'Value'})

Appends a bar chart with the categories xs and the heights ys. names gives the text written on each bar. colors is one CSS color or a list with one color per bar (THEME['main'] by default). The trace is hidden from the legend. Returns None.

add_trace

add_trace(trace: dict[str, Any])
Source code in unaiverse/stats.py
def add_trace(self, trace: dict[str, Any]):
    """Generic method to add any raw Plotly trace.

    Args:
        trace: A Plotly trace dictionary (e.g., ``{'type': 'scatter', ...}``).
    """
    self._data.append(trace)

Appends the Plotly trace trace given as a dictionary. Returns None.

set_y_range

set_y_range(min_val: float, max_val: float)
Source code in unaiverse/stats.py
def set_y_range(self, min_val: float, max_val: float):
    """Force Y-axis limits.

    Args:
        min_val: Lower bound of the Y-axis.
        max_val: Upper bound of the Y-axis.
    """
    self._layout.setdefault('yaxis', {})['range'] = [min_val, max_val]

Fixes the range of the y axis to [min_val, max_val]. Returns None.

set_layout_opt

set_layout_opt(key: str, value: Any)
Source code in unaiverse/stats.py
def set_layout_opt(self, key: str, value: Any):
    """Generic setter for advanced layout options.

    Args:
        key: Top-level Plotly layout key (e.g., ``'xaxis'``, ``'legend'``).
        value: Value to assign. If the key already holds a dict and ``value`` is also
            a dict, the existing dict is updated (merged) rather than replaced.
    """
    if isinstance(value, dict) and key in self._layout:
        self._layout[key].update(value)
    else:
        self._layout[key] = value

Writes value under the layout key key. When both the existing value and value are dictionaries, the existing one is updated with the entries of value instead of being replaced. Returns None.

panel.set_layout_opt("xaxis", {"title": None, "showticklabels": False})

set_legend

set_legend(orientation: str = 'v', x: float = 1.0, y: float = 1.0, xanchor: str = 'left', yanchor: str = 'top')
Source code in unaiverse/stats.py
def set_legend(self, orientation: str = 'v', x: float = 1.0, y: float = 1.0,
               xanchor: str = 'left', yanchor: str = 'top'):
    """Configures the legend position and orientation.

    Args:
        orientation: Legend orientation. ``'v'`` for vertical, ``'h'`` for horizontal.
        x: Horizontal position of the legend anchor in paper coordinates (0–1).
        y: Vertical position of the legend anchor in paper coordinates (0–1).
        xanchor: Horizontal alignment of the legend box relative to ``x``.
            One of ``'left'``, ``'center'``, ``'right'``.
        yanchor: Vertical alignment of the legend box relative to ``y``.
            One of ``'top'``, ``'middle'``, ``'bottom'``.
    """
    self._layout['showlegend'] = True
    self._layout['legend'] = {
        'orientation': orientation,
        'x': x,
        'y': y,
        'xanchor': xanchor,
        'yanchor': yanchor,
        'bgcolor': THEME['bg_paper'],
        'bordercolor': THEME['edge'],
        'borderwidth': 1
    }

Shows the legend and places it. orientation is 'v' or 'h'. x and y are the position of the anchor in paper coordinates between 0 and 1. xanchor ('left', 'center', 'right') and yanchor ('top', 'middle', 'bottom') align the box to the anchor. Returns None.

to_json

to_json() -> str
Source code in unaiverse/stats.py
def to_json(self) -> str:
    """Serializes the panel to the format the Frontend expects.

    Returns:
        JSON string with ``'data'`` and ``'layout'`` keys ready for Plotly.
    """
    return json.dumps({'data': self._data, 'layout': self._layout})

Returns the panel as a JSON string with the keys data and layout, ready for Plotly.newPlot or for render_plotly_html.

layout property

layout

The layout dictionary of the panel. The property returns the dictionary itself (not a copy) and every change made to it changes the figure.

data property

data

The list of traces of the panel. The property returns the list itself.

DefaultBaseDash

DefaultBaseDash(title: str = 'Network Overview')
Source code in unaiverse/stats.py
def __init__(self, title: str = "Network Overview"):
    """Initializes the 2x2 grid dashboard with default dark-theme layout.

    Args:
        title: Main title displayed at the top of the dashboard.
    """
    self.traces = []
    self.layout = {
        "title": title,
        "height": 800,
        "template": "plotly_dark",
        "paper_bgcolor": THEME['bg_paper'],
        "grid": {"rows": 2, "columns": 2, "pattern": "independent"},

        # --- ROW 1 ---
        # Top Left (Graph)
        "xaxis1": {"domain": [0, 0.48]},
        "yaxis1": {"domain": [0.56, 1]},
        # "xaxis1": {"domain": [0, 0.48], "visible": False}, 
        # "yaxis1": {"domain": [0.58, 1], "visible": False},
        # Top Right (Timeseries)
        "xaxis2": {"domain": [0.52, 1]},
        "yaxis2": {"domain": [0.56, 1]},

        # --- ROW 2 ---
        # Bot Left (Bar)
        "xaxis3": {"domain": [0, 0.48]},
        "yaxis3": {"domain": [0, 0.44]},
        # Bot Right (Bar)
        "xaxis4": {"domain": [0.52, 1]},
        "yaxis4": {"domain": [0, 0.44]},

        "showlegend": True,
        "legend": {
            "orientation": "h",
            "y": 0.55,
            "x": 0.55,
            "xanchor": "left",
            "yanchor": "top",
            "bgcolor": "rgba(0,0,0,0)",
            "font": {"color": THEME['text_main']}
        },
        "margin": {"l": 50, "r": 50, "t": 80, "b": 50}
    }
    self._map = {
        "top_left": ("xaxis1", "yaxis1"),
        "top_right": ("xaxis2", "yaxis2"),
        "bot_left": ("xaxis3", "yaxis3"),
        "bot_right": ("xaxis4", "yaxis4")
    }

A dashboard of four panels in a 2 by 2 grid with a total height of 800 pixels. The positions are top_left, top_right, bot_left and bot_right. Each position has its own pair of axes and the panels merged into it keep their traces, their axis options and their title.

Argument Type Default Meaning
title str "Network Overview" The title of the dashboard.
Attribute Type Meaning
traces list[dict] The traces of all panels.
layout dict The layout of the grid with one pair of axes per position.

add_panel

add_panel(ui_plot: UIPlot, position: str)
Source code in unaiverse/stats.py
def add_panel(self, ui_plot: UIPlot, position: str):
    """Merges a UIPlot into one of the four fixed grid positions.

    Args:
        ui_plot: The UIPlot instance whose traces and layout settings are merged in.
        position: Grid cell to target. One of ``'top_left'``, ``'top_right'``,
            ``'bot_left'``, ``'bot_right'``.
    """
    if position not in self._map:
        return

    xa, ya = self._map[position]
    x_dom = self.layout[xa]["domain"]
    y_dom = self.layout[ya]["domain"]

    # Merge Traces
    # noinspection PyProtectedMember
    for t in ui_plot._data:
        nt = t.copy()
        if nt.get("type") == "table":
            nt["domain"] = {"x": x_dom, "y": y_dom}
        else:
            # Cartesian plots use axis references
            nt["xaxis"] = xa.replace("xaxis", "x")
            nt["yaxis"] = ya.replace("yaxis", "y")
        self.traces.append(nt)

    # Merge Layout
    src_l = ui_plot.layout
    dest_x = self.layout.setdefault(xa, {})
    dest_y = self.layout.setdefault(ya, {})
    if "xaxis" in src_l:
        dest_x.update({k: v for k, v in src_l["xaxis"].items() if k != "domain"})
    if "yaxis" in src_l:
        dest_y.update({k: v for k, v in src_l["yaxis"].items() if k != "domain"})

    # Add Title via Annotation
    if src_l.get("title"):
        assert isinstance(x_dom, list)
        assert isinstance(y_dom, list)
        self.layout: dict[str, list]
        self.layout.setdefault("annotations", []).append({
            "text": f"<b>{src_l['title']}</b>",
            "x": (x_dom[0] + x_dom[1]) / 2,
            "y": y_dom[1] + 0.02,
            "xref": "paper", "yref": "paper",
            "showarrow": False, "xanchor": "center", "yanchor": "bottom",
            "font": {"size": 14, "color": THEME['text_main']}
        })

Merges ui_plot into the cell position. With any other position the method returns without changes and raises no error. Table traces receive the domain of the cell. Every other trace is bound to the axes of the cell. The axis options of the panel are copied to the axes of the cell and the title of the panel becomes a bold annotation above the cell. Returns None.

to_json

to_json() -> str
Source code in unaiverse/stats.py
def to_json(self) -> str:
    """Serializes the dashboard to the format the Frontend expects.

    Returns:
        JSON string with ``'data'`` and ``'layout'`` keys ready for Plotly.
    """
    return json.dumps({"data": self.traces, "layout": self.layout})

Returns the dashboard as a JSON string with the keys data and layout.

Stats

Stats(is_world: bool, db_path: str | None = None, cache_window_hours: float = 2.0)
Source code in unaiverse/stats.py
def __init__(self, is_world: bool,
             db_path: str | None = None,  # only needed by the world
             cache_window_hours: float = 2.0):  # only needed by the world
    """Initializes the Stats engine in either World or Agent mode.

    Args:
        is_world: When ``True``, initializes the full World-side engine including the
            SQLite database, hot cache, and persistence buffers. When ``False``,
            initializes a lightweight Agent-side buffer.
        db_path: Filesystem path for the SQLite database file. Required when
            ``is_world`` is ``True``; ignored otherwise.
        cache_window_hours: Duration (in hours) of the in-memory rolling window kept
            by the World hot cache. Older dynamic data is evicted from RAM while
            remaining on disk.
    """
    self.is_world: bool = is_world
    self.max_seen_timestamp: int = 0

    # --- Integrate custom statistics ---
    self.WORLD_STATS_STATIC_SCHEMA = self.CORE_WORLD_STATS_STATIC_SCHEMA | self.CUSTOM_WORLD_STATS_STATIC_SCHEMA
    self.WORLD_STATS_DYNAMIC_SCHEMA = self.CORE_WORLD_STATS_DYNAMIC_SCHEMA | self.CUSTOM_WORLD_STATS_DYNAMIC_SCHEMA
    self.AGENT_STATS_STATIC_SCHEMA = self.CORE_AGENT_STATS_STATIC_SCHEMA | self.CUSTOM_AGENT_STATS_STATIC_SCHEMA
    self.AGENT_STATS_DYNAMIC_SCHEMA = self.CORE_AGENT_STATS_DYNAMIC_SCHEMA | self.CUSTOM_AGENT_STATS_DYNAMIC_SCHEMA
    self.OUTER_STATS_STATIC_SCHEMA = self.CORE_OUTER_STATS_STATIC_SCHEMA | self.CUSTOM_OUTER_STATS_STATIC_SCHEMA
    self.OUTER_STATS_DYNAMIC_SCHEMA = self.CORE_OUTER_STATS_DYNAMIC_SCHEMA | self.CUSTOM_OUTER_STATS_DYNAMIC_SCHEMA

    # --- Master key sets for easier lookup ---
    self.all_static_keys: set[str] = set()
    self.all_dynamic_keys: set[str] = set()
    self.all_keys: set[str] = set()
    self.world_grouped_keys: set[str] = set()
    self.world_ungrouped_keys: set[str] = set()
    self.agent_grouped_keys: set[str] = set()
    self.agent_ungrouped_keys: set[str] = set()
    self.stat_types: dict[str, type] = {}
    self._stat_defaults: dict[str, Any] = {}
    self._initialize_key_sets()

    if self.is_world:
        # --- World Configuration ---
        self._stats: dict[str, Any] = {self.GROUP_KEY: {}}
        self.min_window_duration = timedelta(hours=cache_window_hours)
        self.db_path = db_path
        self._db_conn: sqlite3.Connection | None = None
        self._static_db_buffer = []
        self._dynamic_db_buffer = []

        # --- World Initialization ---
        self._init_db()  # Connect and create tables
        self._initialize_cache_structure()  # Ensures all keys exist
        self._load_existing_stats()  # Hydrates _stats from disk
    else:
        # --- Agent Initialization (Simple Buffer) ---
        self._world_view: dict[str, Any] = {}
        self._update_batch: list[dict[str, Any]] = []

The statistics of a world or of an agent. The world creates one in world mode (see World) and every Agent creates one in agent mode. When the bundle received from the world contains stats.py, a member replaces its Stats object with an instance of WStats.

Argument Type Default Meaning
is_world bool required True for world mode and False for agent mode.
db_path str \| None None World mode only. The path of the SQLite file. The parent folder is created when missing.
cache_window_hours float 2.0 World mode only. The span of the hot cache in hours. Older time-series values leave memory and stay in the database.

In world mode the constructor opens the database in WAL mode, creates the tables dynamic_stats and static_stats when missing and reloads the time-series values of the last cache_window_hours into the cache. Static values are not reloaded. A failure to open the database is printed to standard output and leaves the object without persistence.

Class attribute Default Meaning
CORE_WORLD_STATS_STATIC_SCHEMA, CORE_WORLD_STATS_DYNAMIC_SCHEMA see Kinds of statistics The statistics of the world shipped with the SDK.
CORE_AGENT_STATS_STATIC_SCHEMA, CORE_AGENT_STATS_DYNAMIC_SCHEMA see above The statistics of each agent shipped with the SDK.
CORE_OUTER_STATS_STATIC_SCHEMA, CORE_OUTER_STATS_DYNAMIC_SCHEMA {} Statistics that a peer records on behalf of other peers.
CUSTOM_WORLD_STATS_STATIC_SCHEMA, CUSTOM_WORLD_STATS_DYNAMIC_SCHEMA, CUSTOM_AGENT_STATS_STATIC_SCHEMA, CUSTOM_AGENT_STATS_DYNAMIC_SCHEMA, CUSTOM_OUTER_STATS_STATIC_SCHEMA, CUSTOM_OUTER_STATS_DYNAMIC_SCHEMA {} The schemas that a subclass fills. Each maps a name to (type, default) and is merged with the matching core schema at construction.
STORE_DYNAMIC_IF_CHANGED False With True a dynamic value equal to the last one is not stored. Because the comparison reads the ungrouped value of the name, the option affects only the statistics of the world.
GROUP_KEY 'peer_stats' The key of the cache that holds the grouped statistics.
DEBUG False Deprecated and not read.
Attribute Type Meaning
is_world bool The mode.
max_seen_timestamp int The largest timestamp in milliseconds stored or received.
WORLD_STATS_STATIC_SCHEMA, WORLD_STATS_DYNAMIC_SCHEMA, AGENT_STATS_STATIC_SCHEMA, AGENT_STATS_DYNAMIC_SCHEMA, OUTER_STATS_STATIC_SCHEMA, OUTER_STATS_DYNAMIC_SCHEMA dict The merged core and custom schemas.
all_static_keys, all_dynamic_keys, all_keys set[str] The names of the static, dynamic and all statistics.
world_ungrouped_keys, world_grouped_keys set[str] The names of the world schemas and of the agent and outer schemas.
agent_ungrouped_keys, agent_grouped_keys set[str] The names of the agent schemas and of the outer schemas.
stat_types dict[str, type] The type of each name.
min_window_duration datetime.timedelta World mode only. The span of the hot cache.
db_path str \| None World mode only. The path of the database.

store_stat

store_stat(stat_name: str, value: Any, group_key: str, timestamp: int)
Source code in unaiverse/stats.py
def store_stat(self, stat_name: str, value: Any, group_key: str, timestamp: int):
    """Unified API to store a stat. Dispatches to static or dynamic storage.

    Args:
        stat_name: Name of the statistic as defined in one of the schema dicts.
        value: Value to store. Type-validated and cast according to the schema.
        group_key: Grouping key for this stat (e.g. the sender's peer id, or any
            arbitrary identifier used to bucket related records together).
        timestamp: Millisecond Unix timestamp associated with the measurement.
    """
    if stat_name not in self.all_keys:
        log.error(f'Stat "{stat_name}" is not defined')
        return

    # disambiguate between static and dynamic stats
    if stat_name in self.all_static_keys:
        self._store_static(stat_name, value, group_key, timestamp)
    else:
        self._store_dynamic(stat_name, value, group_key, timestamp)

Stores one value and returns None. An unknown stat_name is logged as an error and ignored. The value is first converted to the type of the schema. A value of another type goes through the type constructor (float("0.5") gives 0.5) and a value rejected by the constructor is logged and stored as str(value). group_key is the peer the value refers to and timestamp is the time of the measurement in milliseconds (clock.get_time_ms()).

In agent mode the value goes to the buffer that the node sends to the world. A static value replaces the buffered value with the same name and group key and a dynamic value is appended. In world mode a static value replaces the cached one and a dynamic value enters the time series of its name (ungrouped) or of its group key (grouped). Values more than cache_window_hours older than the new one are removed from the series. An ungrouped series keeps one value at the edge of the window so that the line stays continuous. Every value is also queued for the next save_to_disk().

get_last_value

get_last_value(stat_name: str, group_key: str | None = None) -> Any | None
Source code in unaiverse/stats.py
def get_last_value(self, stat_name: str, group_key: str | None = None) -> Any | None:
    """Returns the most recent value of any stat, whether static or dynamic.

    Args:
        stat_name: Name of the statistic to retrieve.
        group_key: When ``None``, looks up an ungrouped (world-level) stat. When
            provided, looks up the grouped stat under that key.

    Returns:
        The most recent value, or ``None`` if the stat is unknown or has no data.
    """
    if stat_name in self.all_static_keys:
        return self._get_last_static_value(stat_name, group_key)
    elif stat_name in self.all_dynamic_keys:
        return self._get_last_dynamic_value(stat_name, group_key)
    else:
        log.error(f'get_last_value: Unknown stat_name "{stat_name}"')
        return None

Returns the last value of stat_name for group_key (None for an ungrouped statistic) and None when there is none. In world mode the value comes from the cache. In agent mode the method reads a dynamic value from the buffer not yet sent and always returns None for a static statistic. An unknown name is logged as an error.

get_stats

get_stats() -> dict[str, Any]
Source code in unaiverse/stats.py
def get_stats(self) -> dict[str, Any]:
    """Returns the raw internal stats dictionary (World-only).

    Returns:
        The ``_stats`` hot-cache dictionary containing ungrouped world stats and
        the peer-grouped stats keyed by ``GROUP_KEY``.
    """
    return self._stats

World mode only. Returns the cache itself (not a copy). The cache maps the name of each ungrouped statistic to its value and holds under the key GROUP_KEY a dictionary from group key to the grouped statistics. Time series are sortedcontainers.SortedDict objects keyed by timestamp. In agent mode the call raises AttributeError.

get_payload_for_world

get_payload_for_world(clear_buffer: bool = True) -> list[dict[str, Any]]
Source code in unaiverse/stats.py
def get_payload_for_world(self, clear_buffer: bool = True) -> list[dict[str, Any]]:
    """(Agent-only) Gathers, returns, and clears all pending stats to be sent to the world.

    Args:
        clear_buffer: Whether to clear the stats buffer after the get operation (default True).

    Returns:
        List of stat update dicts, each with ``'peer_id'``, ``'stat_name'``,
        ``'timestamp'``, and ``'value'`` keys. Returns an empty list on the World side.
    """
    if self.is_world:
        return []

    # self._update_agent_static()  # Ensure static stats are fresh in the batch
    payload = self._update_batch
    if clear_buffer:
        self._update_batch = []  # Clear after getting
    return payload

Agent mode. Returns the buffer of values to send to the world as a list of dictionaries with the keys group_key, stat_name, timestamp and value. The default clear_buffer=True empties the buffer. In world mode the result is []. The agent calls it in send_stats_to_world().

update_view

update_view(view_data: dict[str, Any] | None = None, overwrite: bool = False)
Source code in unaiverse/stats.py
def update_view(self, view_data: dict[str, Any] | None = None, overwrite: bool = False):
    """(Agent-side) Merges a snapshot received from the World into the local view.

    This is 'dumb' storage: the data is kept as-is for later plotting without further
    parsing. Dynamic stats are extended (appended) rather than replaced unless
    ``overwrite`` is set.

    Expected ``view_data`` structure::

        {
            "world": { "stat_name": value_or_timeseries },
            "peers": { "peer_id": { "stat_name": value_or_timeseries } }
        }

    For dynamic stats, each ``value_or_timeseries`` is a list of ``[timestamp, value]``
    pairs for efficient JSON/Plotly usage.

    Args:
        view_data: The snapshot received from the world.
        overwrite: If ``True``, discards the current view before merging the new data.
    """
    if self.is_world:
        return

    # Initialize empty structure if needed
    if not self._world_view or overwrite:
        self._world_view = {'world': {}, 'peers': {}}

    def _update_max_ts(ts):
        """Helper to update the max seen timestamp from a time-series."""
        # Dynamic stats come as [[ts, val], [ts, val]...]
        if isinstance(ts, list) and len(ts) > 0 and isinstance(ts[0], list):
            # The last item is usually the newest in sorted time-series
            last_ts = ts[-1][0]
            if last_ts > self.max_seen_timestamp:
                self.max_seen_timestamp = int(last_ts)

    def _merge_dict(target: dict, source: dict):
        """
        Helper to merge source into target with special handling for dynamic stats.
        Copies a source dict { "stat_name": value_or_timeseries } into target.
        """
        for stat_name, val_or_ts in source.items():
            if stat_name in self.all_dynamic_keys:
                _update_max_ts(val_or_ts)
                if stat_name not in target:
                    target[stat_name] = []
                target[stat_name].extend(val_or_ts)
            else:
                target[stat_name] = val_or_ts

    # 1. Merge World (Ungrouped) Stats
    assert view_data is not None
    if 'world' in view_data:
        _merge_dict(self._world_view.setdefault('world', {}), view_data['world'])

    # 2. Merge Peer (Grouped) Stats
    if 'peers' in view_data:
        target_peers = self._world_view.setdefault('peers', {})
        for peer_id, peer_data in view_data['peers'].items():
            target_peer = target_peers.setdefault(peer_id, {})
            _merge_dict(target_peer, peer_data)

Agent mode. Merges into the local view the dictionary view_data that the world sent in the view format. The pairs of a dynamic statistic are appended to the pairs already present and any other value replaces the previous one. overwrite=True discards the local view first. In world mode the call does nothing. The agent calls it when an answer to ask_world_stats arrives. Returns None.

get_view

get_view(since_timestamp: int = 0) -> dict[str, Any]
Source code in unaiverse/stats.py
def get_view(self, since_timestamp: int = 0) -> dict[str, Any]:
    """(World-side) Returns a JSON-serializable snapshot of the current in-memory cache.

    Used for initial handshakes or lightweight polling. Dynamic stats are filtered to
    only include entries newer than ``since_timestamp``.

    Args:
        since_timestamp: Millisecond Unix timestamp. Only dynamic data points with a
            timestamp strictly greater than this value are included. Pass ``0`` to
            include all cached data.

    Returns:
        Dictionary with the structure::

            {
                "world": { "stat_name": value_or_timeseries },
                "peers": { "peer_id": { "stat_name": value_or_timeseries } }
            }

        For dynamic stats, ``value_or_timeseries`` is a list of ``[timestamp, value]``
        pairs. Returns an empty dict when called on the Agent side.
    """
    if not self.is_world:
        return {}
    snapshot = {'world': {}, 'peers': {}}

    # 1. Process World (Ungrouped) Stats
    for stat_name in self.world_ungrouped_keys:
        val = self._stats.get(stat_name)
        if val is not None:
            snapshot['world'][stat_name] = self._serialize_value(val, since_timestamp)

    # 2. Process Peer (Grouped) Stats
    peer_groups = self._stats.get(self.GROUP_KEY, {})

    for pid in peer_groups.keys():
        peer_data = {}
        for stat_name, val in peer_groups[pid].items():
            serialized = self._serialize_value(val, since_timestamp)
            # Optimize: Don't send empty lists if polling
            if isinstance(serialized, list) and len(serialized) == 0:
                continue
            peer_data[stat_name] = serialized

        if peer_data:
            snapshot['peers'][pid] = peer_data

    return snapshot

World mode. Returns the content of the cache in the view format. Only the time-series values with a timestamp greater than or equal to since_timestamp are included (all of them with the default 0) and a peer whose series are all empty after this filter is omitted. In agent mode the result is {}.

query_history

query_history(stat_names: list[str] | None = None, group_keys: list[str] | None = None, time_range: tuple[int, int] | int | None = None, value_range: tuple[float, float] | None = None, limit: int | None = None) -> dict[str, Any]
Source code in unaiverse/stats.py
def query_history(self,
                  stat_names: list[str] | None = None,
                  group_keys: list[str] | None = None,
                  time_range: tuple[int, int] | int | None = None,
                  value_range: tuple[float, float] | None = None,
                  limit: int | None = None) -> dict[str, Any]:
    """(World-only) Queries the SQLite DB for historical stats with optional filters.

    Automatically flushes the current memory buffers to the DB before querying to
    ensure "read-your-writes" consistency. Returns the same structure as
    ``get_view()``, so the Agent can ingest it seamlessly.

    Args:
        stat_names: Restrict results to these stat names. Pass ``None`` or ``[]``
            to include all stats.
        group_keys: Restrict results to these group keys. Pass ``None`` or ``[]``
            to include all groups.
        time_range: Time filter for dynamic stats. An ``int`` is treated as a
            "since X" lower bound; a ``(start, end)`` tuple filters to the closed
            interval ``[start, end]``. Pass ``None`` for no time filter.
        value_range: ``(min, max)`` numeric range filter applied to ``val_num``.
            Rows without a numeric value are excluded when this filter is active.
        limit: Maximum number of dynamic-stat rows to return. Defaults to 5000.

    Returns:
        Dictionary with the same structure as ``get_view()``. Returns an empty dict
        when called on the Agent side or when the DB connection is unavailable.
    """
    if not self.is_world or not self._db_conn:
        return {}

    def _as_str_list(v):
        """Filters arrive from the network: accept only lists of non-empty strings."""
        return [s for s in v if isinstance(s, str) and len(s) > 0] \
            if isinstance(v, (list, tuple)) else []

    stat_names = _as_str_list(stat_names)
    group_keys = _as_str_list(group_keys)
    if not (isinstance(time_range, int) and not isinstance(time_range, bool)) and \
            not (isinstance(time_range, (tuple, list)) and len(time_range) == 2 and
                 all(isinstance(t, (int, float)) and not isinstance(t, bool) for t in time_range)):
        time_range = None
    if not (isinstance(value_range, (tuple, list)) and len(value_range) == 2 and
            all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in value_range)):
        value_range = None

    # Flush the cached updates to db before querying
    self._save_static_to_db()
    self._save_dynamic_to_db()
    self._db_conn.commit()

    snapshot = {'world': {}, 'peers': {}}

    # A. Query the static stats
    query_static = ['SELECT peer_id, stat_name, val_json FROM static_stats']
    params_static = []

    where_added = False
    if stat_names:
        query_static.append("WHERE")
        where_added = True
        query_static.append(f"stat_name IN ({','.join(['?'] * len(stat_names))})")
        params_static.extend(stat_names)
    if group_keys:
        if not where_added:
            query_static.append("WHERE")
        else:
            query_static.append(f"AND")
        query_static.append(f"peer_id IN ({','.join(['?'] * len(group_keys))})")
        params_static.extend(group_keys)

    try:
        rows = self._db_conn.execute(' '.join(query_static), params_static).fetchall()
    except Exception as e:
        log.error(f'Query history (static) failed: {e}')
        rows = []
    for pid, sname, vjson in rows:
        try:
            val = self._validate_type(sname, json.loads(vjson))
            # Handle special Graph reconstruction if needed (legacy format support)
            if sname == 'graph':
                # Handle both legacy format (just edges) and new format (nodes+edges) safely
                if isinstance(val, dict) and 'edges' in val:
                    # Convert the edge lists back to sets
                    val['edges'] = {k: set(v) for k, v in val['edges'].items()}
                    # Ensure nodes dict exists
                    if 'nodes' not in val:
                        val['nodes'] = {}
                else:
                    val: dict
                    # Convert entire dict to sets (as it was before)
                    edges_set = {k: set(v) for k, v in val.items()}
                    # Migrate to new structure on the fly
                    val = {'nodes': {}, 'edges': edges_set}

            # Static stats format: value (direct)
            if pid in (None, 'None', ''):
                snapshot['world'][sname] = val
            else:
                snapshot['peers'].setdefault(pid, {})[sname] = val
        except Exception as e:
            log.error(f'Query history: skipping static row ({sname}, {pid}): {e}')

    # B. Query the dynamic stats
    conditions, params_dyn = [], []
    if stat_names:
        conditions.append(f"stat_name IN ({','.join(['?'] * len(stat_names))})")
        params_dyn.extend(stat_names)
    if group_keys:
        conditions.append(f"peer_id IN ({','.join(['?'] * len(group_keys))})")
        params_dyn.extend(group_keys)
    if time_range is not None:
        if isinstance(time_range, int):
            conditions.append("timestamp >= ?")
            params_dyn.append(time_range)
        elif isinstance(time_range, (tuple, list)) and len(time_range) == 2:
            conditions.append("timestamp >= ? AND timestamp <= ?")
            params_dyn.extend([time_range[0], time_range[1]])
    if value_range:
        conditions.append("val_num IS NOT NULL AND val_num >= ? AND val_num <= ?")
        params_dyn.extend([value_range[0], value_range[1]])
    query_dyn = ['SELECT timestamp, peer_id, stat_name, val_num, val_str, val_json FROM dynamic_stats']
    if conditions:
        query_dyn.append("WHERE " + " AND ".join(conditions))
    query_dyn.append("ORDER BY timestamp ASC")
    try:
        limit = max(1, min(int(limit), 5000)) if limit is not None else 5000
    except (ValueError, TypeError):
        limit = 5000
    query_dyn.append(f"LIMIT {limit}")

    try:
        rows = self._db_conn.execute(' '.join(query_dyn), params_dyn).fetchall()
    except Exception as e:
        log.error(f'Query history (dynamic) failed: {e}')
        rows = []
    for ts, pid, sname, vnum, vstr, vjson in rows:
        try:
            val = vnum if vnum is not None else \
                (vstr if vstr is not None else (json.loads(vjson) if vjson is not None else None))
            if val is None:
                continue  # Row with no value in any of the three columns: nothing to report
            val = self._validate_type(sname, val)
            if pid in (None, 'None', ''):
                target_ts = snapshot['world'].setdefault(sname, [])
            else:
                target_ts = snapshot['peers'].setdefault(pid, {}).setdefault(sname, [])
            target_ts.append([int(ts), val])
        except Exception as e:
            log.error(f'Query history: skipping dynamic row ({sname}, {pid}, {ts}): {e}')

    return snapshot

World mode. Queries the database and returns a dictionary in the view format. The method first writes the pending values to the database. Because the filters arrive from the network, the method validates them and drops every filter of the wrong type.

Argument Type Default Meaning
stat_names list[str] \| None None The names to return. None or an empty list means all. Elements that are not non-empty strings are dropped.
group_keys list[str] \| None None The group keys to return. The rules of stat_names apply.
time_range int \| tuple[int, int] \| None None Keeps the time-series rows from an instant on (int) or within a closed interval (pair). Both forms are in milliseconds.
value_range tuple[float, float] \| None None Keeps the time-series rows with a numeric value in the closed interval and drops the others.
limit int \| None None The maximum number of time-series rows, between 1 and 5000. None and invalid values mean 5000. Because the rows are sorted by increasing time, the limit keeps the oldest ones.

Static rows are filtered by name and group key alone. A row whose group key is empty or None goes under world and any other row goes under peers. The counters of the world are stored with the private peer id of the world as group key and therefore come back under peers. On the other hand get_view() puts them under world. The edges of graph come back as sets. In agent mode or without database the result is {}.

world.stats.query_history(stat_names=["state"], group_keys=[peer_id],
                          time_range=(t0, t1), limit=100)

save_to_disk

save_to_disk()
Source code in unaiverse/stats.py
def save_to_disk(self):
    """(World-only) Saves the static snapshot and dynamic buffer to SQLite."""
    if not self.is_world or not self._db_conn:
        return
    log.debug('Saving world stats to DB...')
    try:
        self._save_static_to_db()
        self._save_dynamic_to_db()
        self._prune_cache()
        self._prune_db()

        self._db_conn.commit()
        log.debug('Save complete.')
    except Exception as e:
        log.error(f'CRITICAL: Save_to_disk failed: {e}')
        if self._db_conn:
            self._db_conn.rollback()

World mode. Writes the pending values to the database and commits the transaction. Static values are upserted by group key and name. Time-series values are inserted and a value with the same group key, name and timestamp as a stored one is ignored. The method then prunes the cache in two steps: (1) the time series lose the values older than the window ending at max_seen_timestamp and (2) every peer whose time series are all empty leaves memory. A peer with static statistics alone (the default case for members) leaves memory too. Its state and actions return to the cache only when it sends its next batch. An error rolls the transaction back and is logged. The node calls it every Custom.SAVE_STATS_EVERY seconds. Returns None.

shutdown

shutdown() -> None
Source code in unaiverse/stats.py
def shutdown(self) -> None:
    """Flushes pending stats and closes the SQLite connection.

    Call this explicitly when the application is shutting down to ensure all
    buffered data is persisted. On the Agent side this is a no-op.
    """
    if self.is_world and self._db_conn:
        log.debug('Shutdown: Saving final stats...')
        try:
            self.save_to_disk()
        except Exception as e:
            log.error(f'Shutdown save failed: {e}')
        self._db_conn.close()
        self._db_conn = None
        log.debug('SQLite connection closed.')

World mode. Calls save_to_disk() and closes the database. The node calls it when it stops. In agent mode the call does nothing. Returns None. When the database is still open, the destructor of the object also saves the pending values and closes it.

plot

plot(since_timestamp: int = 0) -> str | None
Source code in unaiverse/stats.py
def plot(self, since_timestamp: int = 0) -> str | None:
    """Builds and returns the default 2x2 dashboard as a self-contained HTML document.

    Visualizes core stats: network topology, agent-count history, state distribution,
    and last-action distribution. Plotly.js is loaded from CDN; Python never imports
    the plotly package.

    Args:
        since_timestamp: Millisecond Unix timestamp. Only dynamic data points newer
            than this value are included in the time-series panels. Pass ``0`` to
            include all cached data.

    Returns:
        HTML string (``<!DOCTYPE html>`` document), or ``None`` if no view data
        is available.
    """
    from .stats_html_renderer import render_plotly_html

    # 1. Get Data view
    view = self.get_view(since_timestamp) if self.is_world else self._world_view
    if not view:
        return None

    dash = DefaultBaseDash("World Overview")

    # --- Panel 1: Network Topology (Top Left) ---
    p1 = UIPlot(title="World Topology")
    self._populate_graph(p1, view, "graph")
    clean_axis = {'showgrid': False, 'showticklabels': False, 'zeroline': False}
    p1.set_layout_opt('xaxis', clean_axis)
    p1.set_layout_opt('yaxis', clean_axis)
    dash.add_panel(p1, "top_left")

    # --- Panel 2: System Counters (Table) ---
    p2 = UIPlot(title="World Agents History")
    metrics = [
        ("world_masters", "World Masters", THEME['peers'][0]),
        ("world_agents", "World Agents", THEME['peers'][1]),
        ("human_agents", "Human Agents", THEME['peers'][2]),
        ("artificial_agents", "Artificial Agents", THEME['peers'][3]),
    ]
    for stat_key, label, color in metrics:
        self._populate_time_series(
            panel=p2,
            view=view,
            stat_name=stat_key,
            color_override=color,
            title_override=label
        )
    p2.set_layout_opt('xaxis', {'title': None, 'showticklabels': False})
    p2.set_layout_opt('yaxis', {'title': None})
    dash.add_panel(p2, "top_right")

    # --- Panel 3: State Distribution (Bar) ---
    p3 = UIPlot(title="State Distribution")
    self._populate_graph(p3, view, "graph")
    clean_axis = {'showgrid': False, 'showticklabels': False, 'zeroline': False}
    p3.set_layout_opt('xaxis', clean_axis)
    p3.set_layout_opt('yaxis', clean_axis)
    p3.set_layout_opt("xaxis", {"title": None})
    dash.add_panel(p3, "bot_left")

    # --- Panel 4: Action Distribution (Bar) ---
    p4 = UIPlot(title="Last Action Distribution")
    self._populate_distribution(p4, view, "last_action")
    p4.set_layout_opt("xaxis", {"title": None})
    dash.add_panel(p4, "bot_right")

    return render_plotly_html(dash.to_json())

Builds the default dashboard and returns it as a complete HTML document (see render_plotly_html). In world mode the data come from get_view(since_timestamp). In agent mode they come from the local view and since_timestamp is ignored. The result is None when the local view of an agent is empty.

Position Title Content
top left World Topology The connectivity graph with the peers on a circle. Hovering a node shows its name, owner, role, type, number of badges, current action and current state.
top right World Agents History The time series of world_masters, world_agents, human_agents and artificial_agents.
bottom left State Distribution The connectivity graph again. In the current version this content does not match the title because it shows no distribution of states.
bottom right Last Action Distribution A bar chart with the number of peers whose last_action has each value.

The node of a world sends this HTML in answer to a statistics request without stat_names and to a person who joins the world. A WStats subclass may override the method to draw its own dashboard with UIPlot and DefaultBaseDash.