Agent-based modeling¶
When a storm reaches a watershed, which field observer receives the warning? You can model that interaction in a digital twin. A k.IM declaration gives the observer its identity, meaning and location. A k.Actors behavior gives that individual something to do. Each observer has its own memory, so two people created by the same model can have different experiences.
In this example the twin's coordinator watches for the modeled start of a storm. It finds one field observer, sends the warning and records the observer's acknowledgement. Use a project you can publish to Resources and a worldview that defines society:HumanIndividual and classifies earth:Storm as a kind of earth:MeteorologicalEvent. Use the Services revision of 2 December 2026 or a later build with the same communication support, together with its matching language bundles. Agent communication contract
Give a field observer a behavior¶
Publish this k.Actors document as watershed.spotter. The two message classes are names chosen by the author. A caller can use one to warn the observer and the other to read what it remembers.
behavior watershed.spotter
"Remember the last storm warning acknowledged by this field observer."
version 1.0
action init:
def last_warning "none"
@handle(STORM_WARNING)
action record_warning(event_id):
set last_warning event_id
return last_warning
@handle(LAST_WARNING)
action report_warning:
return last_warning
In a k.IM namespace, bind that behavior to the observation definition. The polygon gives the individual a location in the study.
private namespace watershed.observations;
@bind(watershed.spotter)
define observer spotter as {
semantics: society:HumanIndividual
space: { shape: "EPSG:4326 POLYGON((33 -7,33.02 -7,33.02 -7.02,33 -7.02,33 -7))" }
};
Submitting the definition creates the observation and records the binding together. The actor starts after commit. To give every individual produced by an instantiator model its own actor, put @bind on that model. A binding on an explicit define observer or define observation takes precedence over the producing model's binding.
An individual with agent semantics can host a full behavior. Any observation can host a task, including a passive observation such as river temperature. A task can remember events and answer messages through a read-only view of its host. The twin itself can have one root behavior or task, selected at creation.
Send a warning at modeled storm onset¶
Publish the following behavior as watershed.coordinator. Its self is the Context peer for the whole twin. The semantic literal matches individual meteorological events, including storms. Selecting phase = START makes the warning follow the storm's modeled start. Omitting the phase would send it when the event is first registered, which can be much earlier.
behavior watershed.coordinator
"Warn a field observer when a meteorological event begins."
version 1.0
using core.console as console
action init:
def last_ack "none"
@handle({{ earth:MeteorologicalEvent }}, phase = START)
action storm_started(event):
people <- self.agents(:semantics {{ society:HumanIndividual }} :handles STORM_WARNING :limit 1)
for hit in [people.items] (
peer <- self.agent([hit.ref])
if [peer != null] (
receipt <- peer.ask(STORM_WARNING, [event.eventId] :timeout 5.s)
set last_ack receipt
console.println(["Observer " + hit.observationId + " acknowledged storm " + event.data.observationId])
)
)
@handle(LAST_ACK)
action report_ack:
return last_ack
agents returns a page of visible, running peers. The filter selects a person who handles STORM_WARNING. The loop also handles an empty page. agent turns a stable reference into a handle for the current actor, which may have stopped since discovery. ask waits up to five seconds for the handler's return value. When a reply is unnecessary, peer.tell(STORM_WARNING, [event.eventId]) sends the same payload without waiting for acknowledgement.
To warn the nearest visible spotter, add :near station :radius 2.km to the search, where station is an observation with a known location. Keeping :limit 1 selects the closest match within two kilometres. A model of a social or transport network can also select peers along a visible relationship using :relatedTo, :relationship and :direction.
Try it in a twin¶
Publish both behaviors and the namespace. Run this k.Actors script once to create the study with its coordinator. It prints the twin ID you can reopen in Modeler. Run a k.Actors document
script watershed.start
"Create the storm study."
version 1.0
using core.context as context, core.console as console
action main:
ctx <- context.new("Storm watch" :persistence EXPLICIT_ACTION :behavior "watershed.coordinator")
study <- ctx.scope()
console.println([study.id])
- Open Storm watch on that Runtime. Submit the project's
spotterdefinition to the focal twin and wait for its observation and actor to start. For the first run use a single bound spotter under the identity that created the twin. Submit a project definition - Submit an individual
earth:Stormwith a future modeled interval in the study area. At registration,LAST_ACKis still"none". Advance modeled time to the start. In a k.Actors action with access to the twin,clock <- ctx.scheduler()obtains the scheduler andreturn [clock.advanceTo(start_ms)]advances it to the supplied instant in epoch milliseconds. The coordinator prints the observer ID and storm observation ID after the spotter replies. - Ask the coordinator for
LAST_ACKand the spotter forLAST_WARNING. Both return the same event ID after delivery. A bound observation actor can importcore.context as context, callctx <- context.current()and resolve the coordinator withctx.agent(CONTEXT). From the Java client the creating user can reach the active bindings throughscope.getAgent()andscope.within(spotter).getAgent(). If no spotter is contacted, check the selected twin, actor startup, handler name and contact rights.
Decide what an agent can perceive¶
A context behavior can receive matching facts visible to its original user. An observation agent normally receives facts about itself and within its committed perception. Its occupied geometry describes where it is. Its perceived extent describes what it can observe. A passive task normally receives facts about its own host. Select an observer and its extent
Use a semantic handler for a particular kind of event. In addition to registration and START, it can select END, BOTH, or an offset in modeled time such as phase = BEFORE_START, offset = 1.hour. Use a canonical @handle name when the rule concerns a change to the twin itself.
| When the agent should react | Canonical handler |
|---|---|
| An observation appears or its visible state changes | CONTEXT_OBSERVATION_COMMITTED |
| An observation ceases | CONTEXT_OBSERVATION_CEASED |
| The twin's modeled clock moves forward | CONTEXT_TIME_ADVANCED |
| A member joins or leaves a cohort | CONTEXT_COHORT_MEMBERSHIP_CHANGED |
| An observer's perceived extent changes | CONTEXT_PERCEPTION_CHANGED |
| An individual modeled event starts or ends | CONTEXT_OCCURRENCE_BOUNDARY |
Declaring a handler subscribes the binding to that type. To watch a specific observation, refine the subscription with ctx.subscribe(CONTEXT_OBSERVATION_COMMITTED :subject id). The twin owner can assign a wider monitor for a declared type with self.monitor(ref, TYPE) in the root behavior, within the original user's read rights. Rolled-back changes produce no notification.
Direct contact normally requires the same authenticated principal and issuer. Contact across principals requires a grant from the receiving binding for the relevant message classes. A discovery handle grants messaging access. To look for a contactable passive task, request :kind TASK explicitly.
Resume a study¶
On a preserving stop the Runtime saves portable actor state and the position in its event stream. On an authorized reopen with matching behavior sources, the Runtime restores state and invokes resume, if declared, before releasing retained events. init and main run on first activation. A changed source can pause the binding, and lost access can leave it waiting for the original principal. Twin access and lifetime
A retained event may be delivered more than once. The example sends the same eventId on every attempt, so recording it twice leaves the spotter with the same value. Use that ID to deduplicate external effects such as sending a field alert. For direct contact after reopening, resolve the saved peer reference again. The new actor has a fresh handle, and an outstanding ask belonged to the old one.