Behavioral Events Guide

View Source

This guide explains how to use the behavioral event system in macula-neuroevolution. Events capture domain-specific actions using evolutionary biology terminology, enabling event sourcing, auditing, and inter-component communication.

Design Principles

Behavioral, Not CRUD

Events describe what happened in domain language:

Good (Behavioral)Bad (CRUD)
offspring_bornindividual_created
individual_culledindividual_deleted
lineage_divergedspecies_created
knowledge_transferredknowledge_updated

Past Tense

Events are immutable facts that already happened:

GoodBad
mutation_appliedapply_mutation
episode_completedcomplete_episode

Quick Start

Emitting Events

%% Include the event definitions
-include_lib("macula_neuroevolution/include/lc_temporal_events.hrl").

%% Emit an episode completion event
lc_temporal_events:emit_episode_completed(
    IndividualId,
    EpisodeNumber,
    DurationMs,
    success,      % outcome
    0.15,         % fitness_delta
    1000          % steps_taken
).

Subscribing to Events

%% Subscribe to temporal events
neuroevolution_behavioral_events:subscribe(temporal, self()),

%% Handle events in your process
handle_info({lc_event, temporal, #episode_completed{} = Event}, State) ->
    Duration = Event#episode_completed.duration_ms,
    %% Process the event...
    {noreply, State}.

Querying Event History

%% Get recent events for a silo
Events = neuroevolution_behavioral_events:get_events(temporal, #{
    since => erlang:system_time(millisecond) - 60000,  % Last minute
    limit => 100
}).

Event Categories by Silo

Temporal Silo (9 events)

Episode and timing management.

EventDescription
episode_startedNew evaluation episode begins
episode_completedEpisode finished with outcome
timing_adjustedEvaluation timeout changed
learning_rate_adaptedLearning rate modified
patience_exhaustedStagnation limit reached
early_termination_triggeredEpisode stopped early
convergence_detectedFitness improvement slowed
checkpoint_reachedTraining milestone achieved
cohort_completedPopulation cohort finished
%% Example: Episode completion
#episode_completed{
    meta = #lc_event_meta{...},
    individual_id = <<"ind_123">>,
    episode_number = 42,
    duration_ms = 1500,
    outcome = success,           % success | failure | timeout | early_termination
    fitness_delta = 0.05,
    steps_taken = 1000
}

Economic Silo (10 events)

Resource allocation and budgeting.

EventDescription
budget_allocatedCompute budget assigned
budget_exhaustedBudget fully consumed
energy_consumedEnergy used for operation
energy_replenishedEnergy restored
trade_executedResource exchange completed
wealth_redistributedResources rebalanced
bankruptcy_declaredIndividual out of resources
investment_madeResources allocated for future
efficiency_rewardedBonus for efficient use
waste_penalizedPenalty for inefficiency

Morphological Silo (9 events)

Network structure changes.

EventDescription
network_grownNeurons/connections added
network_prunedUnused structures removed
complexity_increasedNetwork became more complex
complexity_reducedNetwork simplified
efficiency_improvedBetter performance/size ratio
modularity_detectedFunctional modules found
symmetry_brokenAsymmetric structure emerged
bottleneck_identifiedStructural limitation found
capacity_reachedMaximum size hit

Competitive Silo (10 events)

Adversarial dynamics.

EventDescription
match_playedCompetition completed
elo_updatedRating changed
champion_crownedNew best individual
champion_dethronedPrevious champion beaten
archive_updatedOpponent archive changed
strategy_emergedNew behavior pattern
counter_strategy_foundExploit discovered
arms_race_detectedEscalating competition
diversity_collapsedStrategies converging
equilibrium_reachedStable competition state

Social Silo (9 events)

Cooperation and reputation.

EventDescription
reputation_gainedStanding improved
reputation_lostStanding decreased
coalition_formedGroup created
coalition_dissolvedGroup disbanded
cooperation_offeredHelp extended
cooperation_acceptedHelp received
defection_detectedTrust broken
mentoring_providedKnowledge shared
social_rank_changedHierarchy position moved

Cultural Silo (9 events)

Innovation and tradition.

EventDescription
innovation_discoveredNew behavior found
innovation_spreadBehavior adopted by others
tradition_establishedPattern became standard
tradition_abandonedPattern fell out of use
imitation_attemptedCopy of behavior tried
imitation_succeededCopy was successful
meme_createdTransmissible unit formed
cultural_drift_detectedGradual change observed
conformity_pressure_appliedNorm enforcement

Developmental Silo (9 events)

Ontogeny and plasticity.

EventDescription
development_startedGrowth phase begun
milestone_reachedDevelopment checkpoint
critical_period_openedLearning window active
critical_period_closedLearning window ended
plasticity_changedAdaptability modified
maturation_advancedDevelopment progressed
metamorphosis_triggeredMajor restructuring
canalization_detectedDevelopment constrained
heterochrony_observedTiming variation

Regulatory Silo (9 events)

Gene expression control.

EventDescription
gene_activatedGene turned on
gene_silencedGene turned off
module_enabledFunctional unit active
module_disabledFunctional unit inactive
context_switchedEnvironmental response
expression_pattern_changedRegulation modified
epigenetic_mark_setHeritable marker added
regulatory_cascade_triggeredChain reaction started
dormant_capability_awakenedHidden feature activated

Ecological Silo (9 events)

Environmental dynamics.

EventDescription
niche_occupiedEcological role filled
niche_vacatedRole abandoned
resource_discoveredNew resource found
resource_depletedResource exhausted
stress_appliedEnvironmental pressure
adaptation_successfulStress response worked
carrying_capacity_reachedPopulation limit hit
extinction_risk_elevatedDanger level increased
ecosystem_stabilizedBalance achieved

Communication Silo (6 events)

Signaling and coordination.

EventDescription
signal_sentMessage transmitted
signal_receivedMessage received
vocabulary_expandedNew signal learned
coordination_achievedGroup synchronization
deception_attemptedFalse signal sent
deception_detectedFalse signal identified

Distribution Silo (4 events)

Population structure.

EventDescription
migration_completedIndividual moved islands
island_formedNew subpopulation created
island_mergedSubpopulations combined
load_rebalancedWork redistributed

Event Metadata

All events include standard metadata:

-record(lc_event_meta, {
    event_id :: binary(),           % Unique event identifier
    timestamp :: integer(),         % Unix milliseconds
    realm :: binary(),              % Multi-tenancy realm
    population_id :: binary(),      % Population context
    generation :: non_neg_integer(),% Generation number
    source_silo :: atom()           % Emitting silo type
}).

Event Storage

Events can be stored for replay and analysis:

%% Configure event storage
neuroevolution_behavioral_events:configure(#{
    storage => ets,              % ets | dets | custom
    max_events => 100000,        % Ring buffer size
    persistence => false         % Write to disk
}).

Integration with Silos

Each silo's event module provides typed emission functions:

%% Temporal silo
lc_temporal_events:emit_episode_started(IndId, EpisodeNum, ExpectedDuration, Gen).
lc_temporal_events:emit_learning_rate_adapted(PopId, OldRate, NewRate, Reason, Gen).

%% Economic silo
lc_economic_events:emit_budget_allocated(IndId, Amount, Source, Gen).
lc_economic_events:emit_trade_executed(FromId, ToId, ResourceType, Amount, Gen).

%% Competitive silo
lc_competitive_events:emit_match_played(Player1, Player2, Result, EloDelta, Gen).
lc_competitive_events:emit_champion_crowned(IndId, Fitness, PreviousChampion, Gen).

Best Practices

  1. Subscribe Early: Set up subscriptions before evolution starts
  2. Handle Async: Events may arrive out of order
  3. Batch Processing: Process events in batches for efficiency
  4. Selective Subscription: Only subscribe to events you need
  5. Idempotent Handlers: Design handlers to handle duplicates

See Also