babylon.models.entities

Entity models for the Babylon simulation.

Entities are the objects that make up the simulation: - SocialClass: Phase 1 node - a social class in the world system - Territory: Phase 3.5 node - a strategic sector in the world system - Effect: Atomic state modifications - ContradictionState: Dialectical tension state - ResolutionOutcome: Result of contradiction resolution - Contradiction: Full contradiction with entities and methods - Trigger: Event triggering conditions - TriggerCondition: Individual condition within a trigger

Finance models (Political Economy of Liquidity - Epoch 1): - StateFinance: Financial state of sovereign entities - RevolutionaryFinance: Financial state of revolutionary organizations - PrecarityState: Economic precarity metrics for social classes

All models use Pydantic v2 with Sprint 1 constrained types.

class babylon.models.entities.SocialClass(**data)[source]

Bases: BaseModel

A social class in the world system.

The fundamental unit of the simulation. Classes are defined by their relationship to production and their position in the imperial hierarchy.

This model uses Sprint 1 constrained types for automatic validation: - Currency: [0, inf) for wealth, subsistence_threshold - IdeologicalProfile: Multi-dimensional consciousness model (Sprint 3.4.3) - Probability: [0, 1] for survival probabilities and organization/repression

Parameters:
id

Unique identifier matching pattern ^C[0-9]{3}$

name

Human-readable name for the class

role

Position in the world system (SocialRole enum)

description

Optional detailed description

wealth

Economic resources (Currency, default 10.0)

ideology

Multi-dimensional ideological profile (IdeologicalProfile)

p_acquiescence

P(S|A) - survival probability through acquiescence (Probability)

p_revolution

P(S|R) - survival probability through revolution (Probability)

subsistence_threshold

Minimum wealth for survival (Currency, default 5.0)

organization

Collective cohesion/class consciousness (Probability, default 0.1)

repression_faced

State violence directed at this class (Probability, default 0.5)

Legacy Compatibility:

If a float value is passed for ideology, it will be automatically converted to an IdeologicalProfile using from_legacy_ideology().

property consumption_needs: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=quantize)]

Total consumption required per tick (Wealth-independent demand).

property economic: EconomicComponent

Return economic component view (computed, not live).

property material_conditions: MaterialConditionsComponent

Return material conditions component view (computed, not live).

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'str_strip_whitespace': True, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property survival: SurvivalComponent

Return survival component view (computed, not live).

classmethod unpack_components_and_convert_legacy(data)[source]

Unpack component objects and convert legacy ideology to IdeologicalProfile.

Return type:

Any

Parameters:

data (Any)

id: str
name: str
role: SocialRole
description: str
wealth: Annotated[float]
ideology: IdeologicalProfile
p_acquiescence: Annotated[float]
p_revolution: Annotated[float]
subsistence_threshold: Annotated[float]
organization: Annotated[float]
repression_faced: Annotated[float]
effective_wealth: Annotated[float]
unearned_increment: Annotated[float]
ppp_multiplier: float
active: bool
s_bio: Annotated[float]
s_class: Annotated[float]
subsistence_multiplier: float
population: int
inequality: Annotated[float]
community_memberships: list[Any]
community_cost_modifier: float
class babylon.models.entities.Territory(**data)[source]

Bases: BaseModel

A strategic sector in the world system.

Territories are the spatial nodes of the simulation. Unlike SocialClass nodes which represent abstract class positions, Territory nodes represent physical locations that can be occupied, contested, and liberated.

The “Host/Parasite Stack” defines territorial control: - Host (Legal Sovereign): Recognized by State, collects rent/taxes - Occupant (De Facto User): Actually uses the space, may be revolutionary

The “Operational Profile” trades visibility for recruitment: - LOW_PROFILE: Safe from eviction, low recruitment - HIGH_PROFILE: High recruitment, high heat (state attention)

Parameters:
  • id (str)

  • h3_index (str | None)

  • name (str)

  • sector_type (SectorType)

  • territory_type (TerritoryType)

  • host_id (str | None)

  • occupant_id (str | None)

  • profile (OperationalProfile)

  • heat (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Contradiction intensity from dormant (0) to rupture (1)', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • rent_level (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • population (int)

  • under_eviction (bool)

  • biocapacity (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • max_biocapacity (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • regeneration_rate (float)

  • extraction_intensity (float)

id

Unique identifier matching pattern ^T[0-9]{3}$

name

Human-readable sector name

sector_type

Economic/social character of the territory

territory_type

Classification in settler-colonial hierarchy (Sprint 3.7)

host_id

Optional ID of the Legal Sovereign (collects rent)

occupant_id

Optional ID of the De Facto Occupant (uses space)

profile

Operational profile (visibility stance)

heat

State attention level [0, 1]

rent_level

Economic pressure on occupants [0, inf)

population

Human shield count (sympathizers)

under_eviction

Whether eviction pipeline is active

property clarity_bonus: float

Recruitment bonus from profile visibility.

HIGH_PROFILE attracts cadre through ideological clarity. LOW_PROFILE is safe but boring.

Returns:

0.3 if HIGH_PROFILE, 0.0 if LOW_PROFILE

property is_liberated: bool

Whether territory is a Liberated Zone.

A territory is liberated when there is an occupant but no host (legal sovereign). This represents successful transition from parasitic to sovereign tenure.

Returns:

True if occupant exists and host does not

property is_sink_node: bool

Whether territory is a sink node in the displacement graph.

Sprint 3.7: The Carceral Geography - Necropolitical Triad.

Sink nodes are territories where displaced populations are routed. They have no economic value - only containment/elimination function. Population flows INTO these territories but does not flow OUT easily.

The three sink node types form the Necropolitical Triad: - RESERVATION: Containment (warehousing surplus population) - PENAL_COLONY: Extraction (forced labor, suppresses organization) - CONCENTRATION_CAMP: Elimination (population decay, generates terror)

Returns:

True if territory_type is RESERVATION, PENAL_COLONY, or CONCENTRATION_CAMP

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'str_strip_whitespace': True, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
h3_index: str | None
name: str
sector_type: SectorType
territory_type: TerritoryType
host_id: str | None
occupant_id: str | None
profile: OperationalProfile
heat: Annotated[float]
rent_level: Annotated[float]
population: int
under_eviction: bool
biocapacity: Annotated[float]
max_biocapacity: Annotated[float]
regeneration_rate: float
extraction_intensity: float
class babylon.models.entities.GlobalEconomy(**data)[source]

Bases: BaseModel

System-wide economic state for dynamic balance mechanics.

The GlobalEconomy model tracks the “Gas Tank” (imperial rent pool) and the “Driver” parameters (wage rate, repression level) that the bourgeoisie can adjust based on pool levels and tension.

Parameters:
imperial_rent_pool

Accumulated imperial rent available for redistribution. Fed by TRIBUTE inflows, depleted by WAGES and CLIENT_STATE outflows. Default: 100.0 Currency.

current_super_wage_rate

Dynamic wage rate for WAGES edges. Adjusts based on pool level and tension via decision heuristics. Range: [0.05, 0.35]. Default: 0.20 (20%).

current_repression_level

System-wide repression modifier. Blended with per-class repression_faced values. Increases during austerity/crisis periods. Range: [0.0, 1.0]. Default: 0.5.

Pool Flow Logic:

inflow = sum(tribute reaching Core Bourgeoisie after comprador cut) outflow = wages_paid + subsidy_paid delta = inflow - outflow new_pool = old_pool + delta

Decision Thresholds (Aggressive):

pool_ratio >= 0.7: PROSPERITY (can increase wages) pool_ratio < 0.3: AUSTERITY (cut wages or increase repression) pool_ratio < 0.1: CRISIS (emergency measures, emit event)

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

imperial_rent_pool: Annotated[float]
current_super_wage_rate: Annotated[float]
current_repression_level: Annotated[float]
class babylon.models.entities.Relationship(**data)[source]

Bases: BaseModel

A directed edge between two entities.

Represents flows of value, solidarity, or repression between classes. In Phase 1, the primary relationship is exploitation: value flows from the periphery worker (source) to the core owner (target).

This model uses Sprint 1 constrained types for automatic validation: - Currency: [0, inf) for value_flow - Intensity: [0, 1] for tension

Parameters:
source_id

Origin entity ID (value/action flows FROM here)

target_id

Destination entity ID (value/action flows TO here)

edge_type

Nature of the relationship (EdgeType enum)

value_flow

Imperial rent or value transfer amount (Currency, default 0.0)

tension

Dialectical tension/contradiction intensity (Intensity, default 0.0)

description

Optional description of the relationship

property edge_data: dict[str, object]

Return edge attributes dict for NetworkX, excluding IDs.

Usage:

G.add_edge(*relationship.edge_tuple, **relationship.edge_data)
property edge_tuple: tuple[str, str]

Return (source_id, target_id) tuple for NetworkX edge creation.

Usage:

G.add_edge(*relationship.edge_tuple, **relationship.edge_data)
property flow: FlowComponent

Return flow component view (computed, not live).

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'str_strip_whitespace': True, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod unpack_flow_component(data)[source]

Unpack flow component into flat fields if provided.

Return type:

Any

Parameters:

data (Any)

validate_no_self_loop()[source]

Ensure entities cannot have a relationship with themselves.

Return type:

Relationship

source_id: str
target_id: str
edge_type: EdgeType
value_flow: Annotated[float]
tension: Annotated[float]
description: str
subsidy_cap: Annotated[float]
solidarity_strength: Annotated[float]
class babylon.models.entities.Effect(**data)[source]

Bases: BaseModel

A modification to game state.

Effects are the atoms of change - they modify single attributes on single targets by specific amounts. Every state change in the simulation should be expressible as one or more Effects.

Parameters:
  • target_id (str)

  • attribute (str)

  • operation (Literal['increase', 'decrease', 'set', 'multiply'])

  • magnitude (float)

  • description (str)

target_id

ID of the entity to modify

attribute

Name of the attribute to change

operation

How to modify the value

magnitude

Amount of change (interpretation depends on operation)

description

Human-readable explanation of why this effect occurs

apply_to(current_value)[source]

Calculate the new value after applying this effect.

Parameters:

current_value (float) – The current value of the attribute

Return type:

float

Returns:

The new value after the effect is applied

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

target_id: str
attribute: str
operation: Literal['increase', 'decrease', 'set', 'multiply']
magnitude: float
description: str
class babylon.models.entities.ContradictionFrame(**data)[source]

Bases: BaseModel

The 2x2 contradiction matrix at a given scale and moment.

Models the principal and secondary contradictions for a specific scope.

Parameters:
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

principal: Contradiction
secondary: Contradiction
class babylon.models.entities.Contradiction(**data)[source]

Bases: BaseModel

A structural contradiction at a specific scale.

Instead of hardcoding the fractal, this uses a dynamic aspect mapping.

Parameters:
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
type: ContradictionType
aspect_a: str
aspect_b: str
principal_aspect: Literal['a', 'b']
identity: Annotated[float]
intensity: Annotated[float]
aspect_balance: float
form_of_struggle: EdgeMode
is_antagonistic: bool
class babylon.models.entities.Trigger(**data)[source]

Bases: BaseModel

A condition that can trigger game events.

Triggers define when events should occur based on game state. They can have multiple conditions that must all be met (AND logic) or any one met (OR logic).

Parameters:
id

Unique identifier

description

Human-readable description

trigger_type

Category of trigger (economic, political, social, etc.)

conditions

List of conditions to evaluate

logic

How to combine conditions (all must pass or any must pass)

parameters

Optional parameters for condition evaluation

cooldown_turns

Minimum turns between activations (0 = no cooldown)

last_triggered_turn

Turn when this was last triggered

evaluate(game_state, current_turn=0)[source]

Evaluate if the trigger condition is met.

Parameters:
  • game_state (dict[str, Any]) – The current game state to evaluate against

  • current_turn (int) – The current turn number (for cooldown checking)

Return type:

bool

Returns:

True if the trigger condition is met, False otherwise

mark_triggered(current_turn)[source]

Mark this trigger as having been triggered.

Parameters:

current_turn (int) – The current turn number

Return type:

None

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
description: str
trigger_type: str | None
conditions: list[TriggerCondition]
logic: Literal['all', 'any']
parameters: dict[str, Any]
cooldown_turns: int
last_triggered_turn: int | None
class babylon.models.entities.TriggerCondition(**data)[source]

Bases: BaseModel

A single condition that can be evaluated against game state.

Conditions specify what to check, how to compare, and what threshold to use. Multiple conditions can be combined in a Trigger.

Parameters:
  • path (str)

  • operator (Literal['>=', '<=', '>', '<', '==', '!='])

  • threshold (float)

  • description (str)

path

Dot-notation path to the value in game state (e.g., “economy.gini_coefficient”)

operator

Comparison operator

threshold

Value to compare against

description

Human-readable explanation

evaluate(game_state)[source]

Evaluate this condition against the game state.

Parameters:

game_state (dict[str, Any]) – The current game state dictionary

Return type:

bool

Returns:

True if the condition is met, False otherwise

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: str
operator: Literal['>=', '<=', '>', '<', '==', '!=']
threshold: float
description: str
class babylon.models.entities.EventTemplate(**data)[source]

Bases: BaseModel

A declarative template for recurring game events.

EventTemplates are the Paradox Pattern for events - data-driven definitions that the EventTemplateSystem evaluates against WorldState.

When preconditions are satisfied, the first matching resolution’s effects are applied and events are emitted for the narrative layer.

Parameters:
id

Unique identifier (EVT_* pattern).

name

Human-readable name.

description

Detailed explanation.

category

System domain category.

preconditions

Conditions that must be met to trigger.

resolutions

Ordered list of resolution paths.

narrative

Hooks for AI narrative generation.

cooldown_ticks

Minimum ticks between activations.

priority

Higher priority templates evaluate first.

is_on_cooldown(current_tick)[source]

Check if this template is on cooldown.

Parameters:

current_tick (int) – The current simulation tick.

Return type:

bool

Returns:

True if still on cooldown, False otherwise.

mark_triggered(tick)[source]

Mark this template as having been triggered.

Parameters:

tick (int) – The tick at which this was triggered.

Return type:

None

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

validate_resolutions_have_effects_or_events()[source]

Ensure each resolution has at least one effect or event emission.

Return type:

EventTemplate

id: str
name: str
description: str
category: Literal['economic', 'consciousness', 'struggle', 'contradiction', 'territory']
preconditions: PreconditionSet
resolutions: list[Resolution]
narrative: NarrativeHooks | None
cooldown_ticks: int
priority: int
last_triggered_tick: int | None
class babylon.models.entities.Resolution(**data)[source]

Bases: BaseModel

A resolution path with condition and effects.

When an EventTemplate’s preconditions are met, resolutions are evaluated in order. The first resolution whose condition matches (or has no condition) is selected.

Parameters:
id

Resolution identifier (snake_case).

name

Human-readable name.

condition

Optional condition for this resolution path.

effects

Effects to apply when this resolution is selected.

emit_event

Optional event to emit.

narrative

Narrative hooks specific to this resolution.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str | None
condition: PreconditionSet | None
effects: list[TemplateEffect]
emit_event: EventEmission | None
narrative: NarrativeHooks | None
class babylon.models.entities.PreconditionSet(**data)[source]

Bases: BaseModel

A set of conditions that must be satisfied for an event to trigger.

Combines node, edge, and graph-level conditions with specified logic.

Parameters:
node_conditions

Conditions on node attributes.

edge_conditions

Conditions on edge types/counts.

graph_conditions

Conditions on graph-level metrics.

logic

How to combine conditions (all = AND, any = OR).

is_empty()[source]

Check if precondition set has no conditions.

Return type:

bool

Returns:

True if no conditions are defined, False otherwise.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

node_conditions: list[NodeCondition]
edge_conditions: list[EdgeCondition]
graph_conditions: list[GraphCondition]
logic: Literal['all', 'any']
class babylon.models.entities.NodeCondition(**data)[source]

Bases: BaseModel

Condition on node attributes with optional filtering and aggregation.

Evaluates a dot-notation path on nodes, optionally filtered by NodeFilter, then aggregates results and compares to threshold.

Parameters:
  • path (str)

  • operator (Literal['>=', '<=', '>', '<', '==', '!='])

  • threshold (float)

  • node_filter (NodeFilter | None)

  • aggregation (Literal['any', 'all', 'count', 'sum', 'avg', 'max', 'min'])

path

Dot-notation path to node attribute (e.g., ideology.agitation).

operator

Comparison operator.

threshold

Value to compare against.

node_filter

Optional filter to select which nodes to check.

aggregation

How to aggregate across matched nodes.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: str
operator: Literal['>=', '<=', '>', '<', '==', '!=']
threshold: float
node_filter: NodeFilter | None
aggregation: Literal['any', 'all', 'count', 'sum', 'avg', 'max', 'min']
class babylon.models.entities.EdgeCondition(**data)[source]

Bases: BaseModel

Condition on edge types/counts with optional node filtering.

Counts or aggregates edges of a specific type, optionally restricted to edges connected to nodes matching the filter.

Parameters:
edge_type

Type of edge to check.

metric

What to measure (count, sum_strength, avg_strength).

operator

Comparison operator.

threshold

Value to compare against.

node_filter

Optional filter to select nodes whose edges to count.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

edge_type: EdgeType
metric: Literal['count', 'sum_strength', 'avg_strength']
operator: Literal['>=', '<=', '>', '<', '==', '!=']
threshold: float
node_filter: NodeFilter | None
class babylon.models.entities.GraphCondition(**data)[source]

Bases: BaseModel

Condition on graph-level aggregate metrics.

Evaluates aggregate properties of the entire graph rather than individual nodes or edges.

Parameters:
  • metric (Literal['solidarity_density', 'exploitation_density', 'average_agitation', 'average_consciousness', 'total_wealth', 'gini_coefficient'])

  • operator (Literal['>=', '<=', '>', '<', '==', '!='])

  • threshold (float)

metric

Graph-level metric to evaluate.

operator

Comparison operator.

threshold

Value to compare against.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

metric: Literal['solidarity_density', 'exploitation_density', 'average_agitation', 'average_consciousness', 'total_wealth', 'gini_coefficient']
operator: Literal['>=', '<=', '>', '<', '==', '!=']
threshold: float
class babylon.models.entities.NodeFilter(**data)[source]

Bases: BaseModel

Filter to select which nodes a condition applies to.

Used to restrict condition evaluation to specific node types, roles, or ID patterns. All specified filters must match (AND logic).

Parameters:
role

Filter by SocialRole values.

node_type

Filter by _node_type attribute (social_class or territory).

id_pattern

Regex pattern for node IDs.

matches(node_id, node_data)[source]

Check if a node matches this filter.

Parameters:
  • node_id (str) – The node’s identifier.

  • node_data (dict[str, Any]) – The node’s data dictionary.

Return type:

bool

Returns:

True if all specified criteria match, False otherwise.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

role: list[SocialRole] | None
node_type: Literal['social_class', 'territory'] | None
id_pattern: str | None
class babylon.models.entities.TemplateEffect(**data)[source]

Bases: BaseModel

Effect specification within an event template.

Similar to the Effect model but supports ${var} substitution for dynamic target resolution at runtime.

Parameters:
  • target_id (str)

  • attribute (str)

  • operation (Literal['increase', 'decrease', 'set', 'multiply'])

  • magnitude (float)

  • description (str)

target_id

Entity ID to modify (supports ${node_id} substitution).

attribute

Attribute name to change.

operation

How to modify the value.

magnitude

Amount of change.

description

Human-readable explanation.

apply_to(current_value)[source]

Calculate the new value after applying this effect.

Parameters:

current_value (float) – The current value of the attribute.

Return type:

float

Returns:

The new value after the effect is applied.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

target_id: str
attribute: str
operation: Literal['increase', 'decrease', 'set', 'multiply']
magnitude: float
description: str
class babylon.models.entities.EventEmission(**data)[source]

Bases: BaseModel

Specification for emitting an EventBus event.

Defines what event to emit when a resolution is selected.

Parameters:
event_type

EventType name to emit.

payload_template

Template for event payload with ${var} substitution.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

event_type: str
payload_template: dict[str, Any]
class babylon.models.entities.NarrativeHooks(**data)[source]

Bases: BaseModel

Hooks for AI observer narrative generation.

Provides context for Persephone to generate narrative around events.

Parameters:
  • motif (str | None)

  • historical_echoes (list[str])

  • flavor_text_key (str | None)

  • entity_refs (list[str])

motif

Narrative motif key (e.g., bifurcation, betrayal).

historical_echoes

References to historical parallels.

flavor_text_key

Key for localized flavor text lookup.

entity_refs

Entity IDs to reference in narrative.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

motif: str | None
historical_echoes: list[str]
flavor_text_key: str | None
entity_refs: list[str]
class babylon.models.entities.EconomicComponent(**data)[source]

Bases: BaseModel

Economic material conditions of a social class.

Parameters:
  • wealth (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • subsistence_threshold (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

wealth: Annotated[float]
subsistence_threshold: Annotated[float]
class babylon.models.entities.IdeologicalProfile(**data)[source]

Bases: BaseModel

Multi-dimensional ideological state of a social class.

Sprint 3.4.3 (George Jackson Refactor): This model replaces the scalar ideology field with a multi-dimensional consciousness model.

The key insight: “Fascism is the defensive form of capitalism.” - Agitation + Solidarity -> Class Consciousness (Revolutionary Path) - Agitation + No Solidarity -> National Identity (Fascist Path)

Parameters:
class_consciousness

Relationship to Capital [0.0=False, 1.0=Revolutionary] How clearly the class understands its position relative to capital.

national_identity

Relationship to State/Tribe [0.0=Internationalist, 1.0=Fascist] How strongly the class identifies with nation/race over class.

agitation

Raw political energy from crisis [0.0, inf) Accumulated energy from falling wages, crisis conditions. Routes to either axis based on solidarity_pressure.

classmethod from_legacy_ideology(ideology_value)[source]

Convert legacy scalar ideology [-1, 1] to IdeologicalProfile.

Legacy mapping: - ideology=-1 (revolutionary) -> class_consciousness=1.0, national_identity=0.0 - ideology=0 (neutral) -> class_consciousness=0.5, national_identity=0.5 - ideology=+1 (reactionary) -> class_consciousness=0.0, national_identity=1.0

Parameters:

ideology_value (float) – Legacy ideology scalar in range [-1.0, 1.0]

Return type:

IdeologicalProfile

Returns:

IdeologicalProfile with mapped values

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

to_legacy_ideology()[source]

Convert IdeologicalProfile back to legacy scalar ideology [-1, 1].

This provides backward compatibility for systems still using the scalar ideology representation.

Return type:

float

Returns:

Legacy ideology scalar in range [-1.0, 1.0]

class_consciousness: Annotated[float]
national_identity: Annotated[float]
agitation: Annotated[float]
class babylon.models.entities.SurvivalComponent(**data)[source]

Bases: BaseModel

Survival calculus outputs for a social class.

Parameters:
  • p_acquiescence (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • p_revolution (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

p_acquiescence: Annotated[float]
p_revolution: Annotated[float]
class babylon.models.entities.MaterialConditionsComponent(**data)[source]

Bases: BaseModel

Material conditions affecting a social class.

Parameters:

repression_faced (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

repression_faced: Annotated[float]
class babylon.models.entities.FlowComponent(**data)[source]

Bases: BaseModel

Value flow and tension state of a relationship.

Parameters:
  • value_flow (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • tension (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Contradiction intensity from dormant (0) to rupture (1)', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

value_flow: Annotated[float]
tension: Annotated[float]
class babylon.models.entities.StateFinance(**data)[source]

Bases: BaseModel

Financial state of a sovereign entity (nation-state, client state).

Tracks treasury, budgets, taxation, and debt for state-level fiscal mechanics. Part of the Political Economy of Liquidity (Epoch 1: The Ledger).

Parameters:
  • treasury (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • police_budget (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • social_reproduction_budget (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • tax_rate (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Formula parameter in range [0, 1]', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • tribute_income (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • debt_level (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • debt_ceiling (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

treasury

Available liquid funds for deployment. Defaults to 100.0.

police_budget

Repression cost per tick. Defaults to 10.0.

social_reproduction_budget

Welfare cost per tick. Defaults to 15.0.

tax_rate

Extraction rate from bourgeoisie [0, 1]. Defaults to 0.3.

tribute_income

Imperial rent from CLIENT_STATE relationships. Defaults to 0.0.

debt_level

Accumulated liabilities. Defaults to 0.0.

debt_ceiling

Maximum sustainable debt. Defaults to 500.0.

Example

>>> finance = StateFinance(treasury=200.0, police_budget=20.0)
>>> finance.burn_rate
35.0
property burn_rate: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=quantize)]

Calculate total spending per tick.

Returns:

Sum of police_budget and social_reproduction_budget.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

treasury: Annotated[float]
police_budget: Annotated[float]
social_reproduction_budget: Annotated[float]
tax_rate: Annotated[float]
tribute_income: Annotated[float]
debt_level: Annotated[float]
debt_ceiling: Annotated[float]
class babylon.models.entities.RevolutionaryFinance(**data)[source]

Bases: BaseModel

Financial state of a revolutionary organization.

Tracks war chest, operational costs, and corruption metrics (heat, drift). Part of the Political Economy of Liquidity (Epoch 1: The Ledger).

Parameters:
  • war_chest (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • operational_burn (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • dues_income (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • expropriation_income (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • donor_income (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • heat (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Contradiction intensity from dormant (0) to rupture (1)', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • reformist_drift (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Ideological position from revolutionary (-1) to reactionary (+1)', metadata=[Ge(ge=-1.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

war_chest

Available liquid funds for revolutionary activity. Defaults to 5.0.

operational_burn

Minimum cost to maintain organization per tick. Defaults to 2.0.

dues_income

Member contributions per tick. Defaults to 1.0.

expropriation_income

Income from direct action. Defaults to 0.0.

donor_income

Liberal funding income. Defaults to 0.0.

heat

State attention level [0, 1]. Higher = more surveillance. Defaults to 0.0.

reformist_drift

Ideological corruption [-1, 1]. Positive = reformist. Defaults to 0.0.

Example

>>> finance = RevolutionaryFinance(war_chest=50.0, heat=0.7)
>>> finance.heat >= 0.8  # Check if in danger zone
False
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

war_chest: Annotated[float]
operational_burn: Annotated[float]
dues_income: Annotated[float]
expropriation_income: Annotated[float]
donor_income: Annotated[float]
heat: Annotated[float]
reformist_drift: Annotated[float]
class babylon.models.entities.PrecarityState(**data)[source]

Bases: BaseModel

Economic precarity metrics for a social class.

Tracks nominal wages, PPP, inflation and computes real wages and precarity. Part of the Political Economy of Liquidity (Epoch 1: The Ledger).

Parameters:
  • nominal_wage (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • ppp_factor (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Formula parameter in range [0, 1]', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • inflation_index (float)

  • subsistence_threshold (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • organization (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

nominal_wage

Raw wage in currency units. Defaults to 10.0.

ppp_factor

Purchasing power parity adjustment [0, 1]. Defaults to 1.0.

inflation_index

Price level multiplier (>= 1.0). Defaults to 1.0.

subsistence_threshold

Minimum for survival. Defaults to 5.0.

organization

Collective capacity to resist [0, 1]. Defaults to 0.5.

Example

>>> precarity = PrecarityState(nominal_wage=3.0, subsistence_threshold=5.0)
>>> precarity.real_wage
3.0
>>> precarity.precarity_index > 0.5  # Below subsistence = precarious
True
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property precarity_index: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=quantize)]

Calculate precarity based on wage-subsistence gap.

Uses sigmoid function to map gap to probability: - precarity = 1 - sigmoid(real_wage - subsistence_threshold) - At subsistence threshold: precarity = 0.5 - Above subsistence: precarity < 0.5 (secure) - Below subsistence: precarity > 0.5 (precarious)

Returns:

Probability [0, 1] where 1 is maximum precarity.

property proletarianization_risk: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=quantize)]

Calculate risk of class falling into precarious proletariat.

Risk is modulated by organization: organized classes can resist proletarianization even under precarious conditions.

  • proletarianization_risk = precarity_index * (1 - organization)

  • High organization provides protection (multiplier near 0)

  • Low organization means full exposure to precarity

Returns:

Probability [0, 1] where 1 is maximum risk.

property real_wage: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=quantize)]

Calculate real wage adjusted for PPP and inflation.

Returns:

(nominal_wage * ppp_factor) / inflation_index

nominal_wage: Annotated[float]
ppp_factor: Annotated[float]
inflation_index: float
subsistence_threshold: Annotated[float]
organization: Annotated[float]
class babylon.models.entities.Organization(**data)[source]

Bases: BaseModel

Base organization entity for the Babylon simulation.

All four subtypes (StateApparatus, Business, PoliticalFaction, CivilSocietyOrg) inherit these 15 fields. Frozen and immutable.

Parameters:
  • id (str)

  • name (str)

  • org_type (OrgType)

  • class_character (ClassCharacter)

  • cohesion (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • cadre_level (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • budget (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Non-negative economic value (wealth, wages, rent, GDP)', metadata=[Ge(ge=0.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • legal_standing (LegalStanding)

  • consciousness_tendency (ConsciousnessTendency)

  • territory_ids (list[str])

  • headquarters_id (str | None)

  • heat (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • is_institution (bool)

  • institutional_persistence (float | None)

  • member_node_ids (list[str])

id

Unique organization identifier.

name

Human-readable name.

org_type

Discriminator for subtype dispatch.

class_character

Which class this org serves.

cohesion

Internal unity and coordination [0, 1].

cadre_level

Leadership quality [0, 1].

budget

Available resources [0, inf).

legal_standing

Legal status of the organization.

consciousness_tendency

Ideological tendency pushed on communities.

territory_ids

Territories where org operates.

headquarters_id

Primary location (must be in territory_ids).

heat

State attention level [0, 1].

is_institution

Has crystallized into institution.

institutional_persistence

Resistance to dissolution (institutions only).

member_node_ids

Individual key figures and cadre.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
org_type: OrgType
class_character: ClassCharacter
cohesion: Probability
cadre_level: Probability
budget: Currency
legal_standing: LegalStanding
consciousness_tendency: ConsciousnessTendency
territory_ids: list[str]
headquarters_id: str | None
heat: Probability
is_institution: bool
institutional_persistence: float | None
member_node_ids: list[str]
class babylon.models.entities.StateApparatus(**data)[source]

Bases: Organization

State apparatus organization (Feature 031).

Wields state violence and surveillance. Default legal standing is SOVEREIGN.

Parameters:
jurisdiction

Scope of authority.

violence_capacity

Capacity for coercive force [0, 1].

surveillance_capacity

Capacity for surveillance [0, 1].

legal_authority

Specific authorities wielded.

intel_methodology

Intelligence capabilities (Sparrow-grounded).

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

org_type: Literal[OrgType.STATE_APPARATUS]
legal_standing: LegalStanding
jurisdiction: JurisdictionLevel
violence_capacity: Probability
surveillance_capacity: Probability
legal_authority: list[str]
intel_methodology: IntelMethodology
factional_alignment: StateFaction
class babylon.models.entities.Business(**data)[source]

Bases: Organization

Business organization (Feature 031).

Accumulates capital and employs labor.

Parameters:
sector

NAICS sector description.

employment_count

Number of employees.

surplus_extraction_rate

Rate of surplus value extraction [0, 1].

revenue

Annual revenue [0, inf).

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

org_type: Literal[OrgType.BUSINESS]
sector: str
naics_2digit: str | None
employment_count: int
surplus_extraction_rate: Coefficient
revenue: Currency
constant_capital: Currency
variable_capital: Currency
surplus_value: Currency
class babylon.models.entities.PoliticalFaction(**data)[source]

Bases: Organization

Political faction organization (Feature 031).

Contests political power. The player’s faction is marked with is_player.

Parameters:
ideology

Ideological label (e.g., “Marxism-Leninism”).

is_player

Whether this is the player’s faction.

relationship_to_player

Relationship state.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

org_type: Literal[OrgType.POLITICAL_FACTION]
ideology: str
is_player: bool
relationship_to_player: str
class babylon.models.entities.CivilSocietyOrg(**data)[source]

Bases: Organization

Civil society organization (Feature 031).

Non-state, non-business collective providing community services. legitimacy doubles as the credibility factor in the consciousness effect formula.

Parameters:
service_type

Domain of service provision.

legitimacy

Community trust/credibility [0, 1].

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

org_type: Literal[OrgType.CIVIL_SOCIETY]
service_type: ServiceType
legitimacy: Probability
class babylon.models.entities.IntelMethodology(**data)[source]

Bases: BaseModel

Intelligence methodology capabilities (Sparrow-grounded).

Defines which social network analysis techniques an intelligence agency can employ and the maximum fraction of true topology observable.

Parameters:
  • centrality_analysis (bool)

  • equivalence_analysis (bool)

  • template_matching (bool)

  • temporal_analysis (bool)

  • observation_ceiling (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

centrality_analysis

Can identify hub nodes and bridges.

equivalence_analysis

Can find structurally equivalent positions.

template_matching

Can match against known org templates.

temporal_analysis

Can detect activation pattern changes over time.

observation_ceiling

Max fraction of true topology observable [0, 1].

classmethod fbi(defines=None)[source]

FBI preset: all capabilities, FBI-level ceiling.

Parameters:

defines (OrganizationDefines | None) – Optional OrganizationDefines for tunable ceiling value.

Return type:

IntelMethodology

classmethod fusion_center(defines=None)[source]

Fusion Center preset: centrality + temporal, medium ceiling.

Parameters:

defines (OrganizationDefines | None) – Optional OrganizationDefines for tunable ceiling value.

Return type:

IntelMethodology

classmethod local_pd(defines=None)[source]

Local PD preset: centrality only, low ceiling.

Parameters:

defines (OrganizationDefines | None) – Optional OrganizationDefines for tunable ceiling value.

Return type:

IntelMethodology

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

centrality_analysis: bool
equivalence_analysis: bool
template_matching: bool
temporal_analysis: bool
observation_ceiling: Probability
class babylon.models.entities.KeyFigure(**data)[source]

Bases: BaseModel

Individual node within organizational topology (Feature 031).

Stored as a separate graph node (_node_type="key_figure"). COMMAND edges connect KeyFigure nodes within the same organization.

Parameters:
  • id (str)

  • name (str)

  • organization_id (str)

  • role (str)

  • structural_importance (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • is_singleton (bool)

id

Unique key figure identifier.

name

Name.

organization_id

Parent organization.

role

Position title/function.

structural_importance

Topological criticality [0, 1].

is_singleton

No structural equivalent (Sparrow).

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
organization_id: str
role: str
structural_importance: Probability
is_singleton: bool
class babylon.models.entities.TernaryConsciousness(**data)[source]

Bases: BaseModel

A point in the 2-simplex representing community consciousness.

Three components (r, l, f) sum to 1.0: - r: Revolutionary consciousness (distance from assimilation). - l: Liberal consciousness (reform within existing order). - f: Fascist consciousness (exclusionary reaction).

Supports two construction paths: 1. Native: TernaryConsciousness(r=0.5, l=0.3, f=0.2) 2. Legacy: ``TernaryConsciousness(collective_identity=0.5,

dominant_tendency=LIBERAL, ideological_contestation=0.4)``

Both produce valid simplex points with backward-compatible properties.

Parameters:
  • r (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Revolutionary component [0, 1].

  • l (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Liberal component [0, 1].

  • f (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Fascist component [0, 1].

  • contestation_stored (float | None) – Preserved legacy contestation value, or None for natively constructed instances (uses Shannon entropy).

property assimilation_ratio: float

f / (l + f).

Measures how much of the non-revolutionary consciousness is fascist. When l + f is near zero (fully revolutionary), returns 0.5 (neutral).

Returns:

Ratio in [0, 1]. 0 = pure liberal, 1 = pure fascist.

Type:

Position along the liberal-fascist base

property collective_identity: float

Oppositional consciousness [0, 1]. Equals r component.

Returns:

The revolutionary component, semantically identical to the old CommunityConsciousness.collective_identity.

property dominant_tendency: ConsciousnessTendency

Prevailing ideological direction (argmax of r, l, f).

Ties are broken in favor of liberal (structural advantage of the status quo — you have to actively organize to leave liberalism).

Returns:

ConsciousnessTendency corresponding to the largest component.

property ideological_contestation: float

Active debate between tendencies [0, 1].

If contestation_stored is set (legacy construction), returns that value for backward compatibility. Otherwise computes normalized Shannon entropy of (r, l, f): H(r,l,f) / log(3).

Returns:

Contestation level. 0 = monopoly, 1 = maximum contestation.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

r: Probability
l: Probability
f: Probability
contestation_stored: float | None
class babylon.models.entities.SubstrateFloor(**data)[source]

Bases: BaseModel

Per-community-type minimum revolutionary consciousness with provenance.

The substrate floor is consciousness that persists even when all organizations are destroyed — the grandmother teaching not to talk to cops, survival knowledge transmitted through socialization.

Parameters:
  • community_type (CommunityType) – Which community this floor applies to.

  • floor_value (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Minimum r regardless of org landscape [0, 1].

  • confidence (ProvenanceLevel) – Data quality indicator.

  • data_sources (list[str]) – Named data sources used.

  • computation_method (str) – How floor was derived from proxies.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

community_type: CommunityType
floor_value: Probability
confidence: ProvenanceLevel
data_sources: list[str]
computation_method: str
class babylon.models.entities.ProvenanceLevel(*values)[source]

Bases: StrEnum

Data quality indicator for substrate floor computation.

Values:

HIGH: Derived from 2+ independent proxy data sources. MEDIUM: Derived from 1 proxy data source. LOW: Estimated from related data, not direct proxy. SYNTHETIC: Stipulated placeholder with no data path.

HIGH = 'high'
MEDIUM = 'medium'
LOW = 'low'
SYNTHETIC = 'synthetic'
class babylon.models.entities.OrgContribution(**data)[source]

Bases: BaseModel

An organization’s weighted contribution to community consciousness.

Used as input to the compute_ternary_consciousness function.

Parameters:
  • tendency (ConsciousnessTendency) – Which vertex this org pulls toward.

  • membership_density (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Members in community / community population [0, 1].

  • cadre_level (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Organizational development level [0, 1].

  • cohesion (Annotated[float, Ge(ge=0.0), Le(le=1.0), AfterValidator(func=~babylon.utils.math.quantize)]) – Internal organizational cohesion [0, 1].

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tendency: ConsciousnessTendency
membership_density: Probability
cadre_level: Probability
cohesion: Probability
class babylon.models.entities.FactionBalance(**data)[source]

Bases: BaseModel

Power distribution among ruling-class factions (Feature 039).

The weight vector determines the state’s objective function for verb selection. Shifts based on player actions (FR-C04) and material conditions (FR-C05). Fascist convergence is detected when specific threshold conditions hold (FR-C06).

Primitive state: finance_capital, security_state, settler_populist, stability, legitimacy (stored). Derived state: dominant_faction (computed). Constitution II.2.

Parameters:
  • finance_capital (float)

  • security_state (float)

  • settler_populist (float)

  • stability (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • legitimacy (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

finance_capital

Weight of Finance-Capital faction [0.0, 1.0].

security_state

Weight of Security-State faction [0.0, 1.0].

settler_populist

Weight of Settler-Populist faction [0.0, 1.0].

stability

How stable the current balance is [0=turbulent, 1=settled].

legitimacy

Overall state legitimacy [0=delegitimized, 1=fully legitimate].

Reference: FR-C02, R-003.

property dominant_faction: StateFaction

Faction with highest weight.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

finance_capital: float
security_state: float
settler_populist: float
stability: Probability
legitimacy: Probability
class babylon.models.entities.StateBudget(**data)[source]

Bases: BaseModel

State budget constraint for verb execution (Feature 039).

Revenue derives from tax revenue, federal transfers, and imperial rent pool. Allocation across verb categories is computed each tick as the dot product of faction weights and faction verb preferences.

Budget is finite – the fundamental constraint making state behavior strategic rather than omnipotent.

Parameters:
revenue

Total income this tick.

available

Unallocated funds remaining this tick.

allocated

Budget allocated per top-level verb category.

imperial_rent_pool

Discretionary capacity from imperial rent.

Reference: FR-D05, R-004.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

revenue: float
available: float
allocated: dict[StateActionType, float]
imperial_rent_pool: float
class babylon.models.entities.StateAction(**data)[source]

Bases: BaseModel

State verb execution instance (Feature 039).

Parallel to the player Action model (Feature 032) but with different resource profiles. Budget constrains non-REPRESS verbs; attention threads constrain REPRESS verbs (Assumption A-004).

Parameters:
verb

Top-level verb category.

sub_verb

Specific sub-verb within the verb category.

target_id

Target entity ID (None for self-targeting).

budget_cost

Budget consumed by this action.

thread_cost

Attention threads required (for REPRESS verbs).

legitimacy_cost

Legitimacy impact (negative = delegitimizing).

faction_alignment

Which faction benefits from this action.

parameters

Sub-verb-specific parameters.

Reference: FR-B01 through FR-B11, FR-D05, R-005.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

verb: StateActionType
sub_verb: StateActionType
target_id: str | None
budget_cost: float
thread_cost: int
legitimacy_cost: float
faction_alignment: StateFaction
parameters: dict[str, Any]
class babylon.models.entities.LegalFramework(**data)[source]

Bases: BaseModel

Active legislation modifying game rules in a jurisdiction (Feature 039).

Created by LEGISLATE sub-action, removed by REVOKE sub-action. No automatic expiry – legislation persists until explicitly revoked. Revocation carries its own legitimacy cost/gain depending on context.

Parameters:
  • framework_id (str)

  • law_type (str)

  • scope (str)

  • severity (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • effects (dict[str, float])

  • created_tick (int)

  • creating_apparatus_id (str)

framework_id

Unique framework identifier.

law_type

Legislation category.

scope

Jurisdiction scope (JurisdictionLevel value).

severity

How extreme the legislation is [0=mild, 1=extreme].

effects

Rule modifications applied (varies by law_type).

created_tick

Tick when enacted.

creating_apparatus_id

Apparatus that enacted this.

Reference: FR-B09, R-011.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

framework_id: str
law_type: str
scope: str
severity: Probability
effects: dict[str, float]
created_tick: int
creating_apparatus_id: str
class babylon.models.entities.AttentionThread(**data)[source]

Bases: BaseModel

State intelligence resource tracking a specific target (Feature 039).

Each thread maintains a growing G_observed subgraph (always incomplete, always distorted) of the target. Thread pool size derives from the sum of surveillance_capacity across all StateApparatus nodes. Sparrow analysis operates on G_observed per thread.

Parameters:
  • thread_id (str)

  • target_type (str)

  • target_id (str)

  • phase (ThreadPhase)

  • intensity (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • intel_completeness (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • surveillance_methods (list[SurveillanceMethod])

  • observed_node_ids (frozenset[str])

  • observed_edge_ids (frozenset[tuple[str, str]])

  • stickiness (Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Value in range [0.0, 1.0] representing likelihood', metadata=[Ge(ge=0.0), Le(le=1.0)]), AfterValidator(func=~babylon.utils.math.quantize)])

  • ticks_active (int)

  • owning_apparatus_id (str)

thread_id

Unique identifier for this attention thread.

target_type

Type of target entity.

target_id

ID of target entity.

phase

Current intelligence phase.

intensity

Resource allocation intensity [0,1].

intel_completeness

Accumulated intelligence [0,1].

surveillance_methods

Active collection methods.

observed_node_ids

Node IDs discovered in G_observed.

observed_edge_ids

Edge ID pairs discovered in G_observed.

stickiness

Resistance to reallocation by meta-OODA [0,1].

ticks_active

Ticks since thread allocation.

owning_apparatus_id

StateApparatus that owns this thread.

Reference: FR-A01 through FR-A08, R-002, R-007.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

thread_id: str
target_type: str
target_id: str
phase: ThreadPhase
intensity: Probability
intel_completeness: Probability
surveillance_methods: list[SurveillanceMethod]
observed_node_ids: frozenset[str]
observed_edge_ids: frozenset[tuple[str, str]]
stickiness: Probability
ticks_active: int
owning_apparatus_id: str
class babylon.models.entities.SparrowAnalysis(**data)[source]

Bases: BaseModel

Network vulnerability analysis results on G_observed (Feature 039).

Implements Sparrow’s framework: centrality computation, equivalence class identification, singleton detection, and minimal cutset analysis. All results are contingent on G_observed quality – they may be wrong because the state’s view is always incomplete.

This is a COMPUTED artifact – derived from G_observed, not stored in the graph. Constitution II.2: derived state, not primitive.

Parameters:
thread_id

Source thread ID.

tick

Tick of computation.

centrality_rankings

Per-node centrality scores.

equivalence_classes

Groups of structurally equivalent nodes.

identified_singletons

Nodes in singleton equivalence classes.

known_cutsets

Minimal node cutsets in G_observed.

confidence

Analysis confidence based on intel_completeness [0,1].

Reference: FR-A03, R-002.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

thread_id: str
tick: int
centrality_rankings: dict[str, dict[str, float]]
equivalence_classes: list[frozenset[str]]
identified_singletons: frozenset[str]
known_cutsets: list[frozenset[str]]
confidence: Probability
babylon.models.entities.get_parent_verb(sub_verb)[source]

Look up the parent verb of a sub-verb.

Parameters:

sub_verb (StateActionType) – A StateActionType that may be a sub-verb.

Return type:

StateActionType | None

Returns:

The top-level parent verb, or None if the input is itself a top-level verb or not found in any parent’s children.

class babylon.models.entities.Institution(**data)[source]

Bases: BaseModel

Third-layer entity representing crystallized social relations (Feature 040).

Institutions are the layer between substrate (SocialClass, Territory, Community) and agents (Organizations). They persist through member turnover, generate and constrain Organizations, maintain internal balance of forces, and serve as sites of class struggle.

Graph node type: _node_type="institution"

Parameters:
id

Unique institution identifier.

name

Human-readable name.

apparatus_type

Althusserian classification.

social_function

Population need served.

class_inscription

Which class the institution serves.

internal_balance

Factional weight distribution.

action_modifiers

Override structural selectivity modifiers.

budget

Available resources.

fixed_asset_territory_ids

Territories with fixed infrastructure.

legal_authorities

Legal powers held.

personnel_capacity

Maximum personnel count.

formalization_level

Degree of bureaucratic formalization [0, 1].

institutional_inertia

Resistance to rapid change [0, 1].

legitimacy

Public perceived legitimacy [0, 1].

housed_org_ids

Organizations housed within.

territory_ids

Territories where institution operates.

jurisdiction

Jurisdiction scope (RSA types only).

lifecycle_function

D-P-D’ phase assignment.

reproduction

Self-perpetuation mechanisms.

spawning_blueprints

Templates for replacement orgs.

Reference: FR-001 through FR-016.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
apparatus_type: ApparatusType
social_function: SocialFunction
class_inscription: ClassInscription
internal_balance: InternalBalanceOfForces
action_modifiers: dict[str, float]
budget: float
fixed_asset_territory_ids: list[str]
legal_authorities: frozenset[str]
personnel_capacity: int
formalization_level: float
institutional_inertia: float
legitimacy: float
housed_org_ids: list[str]
territory_ids: list[str]
jurisdiction: frozenset[str] | None
lifecycle_function: LifecyclePhase | None
reproduction: ReproductionMechanism
spawning_blueprints: list[SpawningBlueprint]
class babylon.models.entities.InternalBalanceOfForces(**data)[source]

Bases: BaseModel

Factional weight distribution within an institution (Feature 040).

Three ruling-class fractions compete for hegemony within each institution. Weights always sum to 1.0 (tolerance +/- 0.01). The hegemonic fraction (highest weight) modulates housed Organization OODA orientation.

Parameters:
  • liberal_technocratic (float)

  • revanchist_fascist (float)

  • institutionalist_bonapartist (float)

  • internal_contestation (float)

liberal_technocratic

Weight of consent-based rule faction [0, 1].

revanchist_fascist

Weight of naked repression faction [0, 1].

institutionalist_bonapartist

Weight of self-preservation faction [0, 1].

internal_contestation

How actively factional warfare is occurring [0, 1].

Reference: FR-005, FR-006.

property hegemonic_fraction: RulingClassFraction

Faction with highest weight.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

liberal_technocratic: float
revanchist_fascist: float
institutionalist_bonapartist: float
internal_contestation: float
class babylon.models.entities.ReproductionMechanism(**data)[source]

Bases: BaseModel

Self-perpetuation capacity of an institution (Feature 040).

Tracks the formal mechanisms that allow an institution to reproduce itself: recruitment, training, succession, budget independence, and legal self-perpetuation. The computed reproduction_capacity score determines how effectively an institution replaces lost members.

Parameters:
  • recruitment_pipeline (bool)

  • training_program (bool)

  • succession_protocol (bool)

  • budget_independence (float)

  • legal_self_perpetuation (bool)

recruitment_pipeline

Has formal member intake process.

training_program

Has formal training/socialization.

succession_protocol

Has leadership succession plan.

budget_independence

Fraction of budget from own sources [0, 1].

legal_self_perpetuation

Has legal mandate to exist.

Reference: FR-012.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property reproduction_capacity: float

Composite reproduction capacity score.

Formula: (sum(bools) / 4) * 0.7 + budget_independence * 0.3

The four boolean mechanisms contribute 70% of capacity, budget independence contributes 30%.

recruitment_pipeline: bool
training_program: bool
succession_protocol: bool
budget_independence: float
legal_self_perpetuation: bool
class babylon.models.entities.SpawningBlueprint(**data)[source]

Bases: BaseModel

Template for replacement Organization creation (Feature 040).

Stored by institutions to define how replacement Organizations are created when housed ones are destroyed. Spawned orgs inherit from the blueprint, modified by the institution’s current state.

Parameters:
org_type

Organization category to spawn.

default_class_character

Initial class character for spawned org.

base_attributes

Additional attributes for spawned org.

Reference: FR-016.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

org_type: OrgType
default_class_character: ClassCharacter
base_attributes: dict[str, Any]
class babylon.models.entities.InstitutionOrgRelation(**data)[source]

Bases: BaseModel

Relationship between institution and housed Organization (Feature 040).

Tracks the material and political dimensions of how an institution houses and shapes an Organization.

Parameters:
institution_id

Parent institution ID.

organization_id

Housed organization ID.

resource_provision

Fraction of institution resources provided [0, 1].

legal_cover

Whether institution provides legal protection.

legitimacy_transfer

How much institutional legitimacy transfers [0, 1].

action_oversight

How much institution constrains org actions [0, 1].

factional_alignment

Which faction the org aligns with, if any.

Reference: FR-011.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

institution_id: str
organization_id: str
resource_provision: float
legal_cover: bool
legitimacy_transfer: float
action_oversight: float
factional_alignment: RulingClassFraction | None
class babylon.models.entities.FactionShiftEvent(**data)[source]

Bases: BaseModel

Returned when update_internal_balance changes the hegemonic fraction.

Reference: FR-019, EventType.INSTITUTION_FACTION_SHIFT.

Parameters:
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

institution_id: str
old_fraction: RulingClassFraction
new_fraction: RulingClassFraction
weights: dict[str, float]
class babylon.models.entities.ReproductionEvent(**data)[source]

Bases: BaseModel

Returned when an institution spawns a replacement Organization.

Reference: FR-019, EventType.INSTITUTION_REPRODUCTION.

Parameters:
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

institution_id: str
spawned_org_type: OrgType
blueprint: SpawningBlueprint
class babylon.models.entities.BonapartistModeEvent(**data)[source]

Bases: BaseModel

Returned when BONAPARTIST weight crosses the Bonapartist threshold.

Reference: FR-019, EventType.INSTITUTION_BONAPARTIST_MODE.

Parameters:
  • institution_id (str)

  • bonapartist_weight (float)

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

institution_id: str
bonapartist_weight: float

Modules

attention_thread

Attention thread and Sparrow analysis entity models (Feature 039).

community

Community membership models for the hypergraph layer (Feature 022).

consciousness

Ternary consciousness model (Feature 034).

contradiction

Contradiction models for dialectical simulation.

economy

GlobalEconomy entity model for Sprint 3.4.4: Dynamic Balance.

effect

Effect model for state modifications.

event_template

Event Template model for declarative game events.

industry

institution

Institution entity models for the Babylon simulation (Feature 040).

organization

Organization entity models for the Babylon simulation (Feature 031).

precarity_state

Precarity state model for social class economic conditions.

relationship

Relationship entity model.

revolutionary_finance

Revolutionary finance model for revolutionary organizations.

social_class

SocialClass entity model.

state_apparatus_ai

State Apparatus AI entity models (Feature 039).

state_finance

State finance model for sovereign entities.

territory

Territory entity model.

trigger

Trigger model for event conditions.