Skip to content

API Reference

Complete reference for the Chora library.

Core Module

Graph Structure

chora.core.graph

Platial Graph Container

The core representation is a typed, temporal, heterogeneous graph that enables multiple, even conflicting experiences to coexist.

PlatialGraph dataclass

A typed, temporal, heterogeneous graph for platial modelling.

The graph stores nodes (entities) and edges (relations) with full temporal validity, uncertainty, and provenance tracking.

Attributes

name : str Optional name for the graph. description : str Optional description.

Examples

from chora.core import PlatialGraph, Agent, SpatialExtent graph = PlatialGraph(name="Urban Mobility Study") agent = Agent(name="Alice") graph.add_node(agent) graph.node_count 1

all_node_ids property

Get all node IDs.

edge_count property

Total number of edges.

node_count property

Total number of nodes.

add_edge(edge)

Add an edge to the graph.

Both source and target nodes must exist.

Raises

NodeNotFoundError If source or target node doesn't exist.

add_node(node)

Add a node to the graph.

Parameters

node : PlatialNode The node to add.

Returns

NodeId The ID of the added node.

Raises

DuplicateNodeError If a node with this ID already exists.

clear()

Remove all nodes and edges.

edge_count_by_type(edge_type)

Count edges of a specific type.

edges(edge_type=None)

Iterate over edges, optionally filtered by type.

get_edge(edge_id)

Get an edge by ID.

get_node(node_id)

Get a node by ID.

Raises

NodeNotFoundError If the node does not exist.

has_edge(edge_id)

Check if an edge exists.

has_node(node_id)

Check if a node exists.

incoming_edges(node_id, edge_type=None)

Get edges pointing to a node.

neighbors(node_id, edge_type=None)

Get neighboring nodes (via outgoing edges).

node_count_by_type(node_type)

Count nodes of a specific type.

nodes(node_type=None)

Iterate over nodes, optionally filtered by type.

Parameters

node_type : NodeType | None If provided, only yield nodes of this type.

nodes_valid_at(timestamp, node_type=None)

Iterate over nodes valid at a given timestamp.

outgoing_edges(node_id, edge_type=None)

Get edges originating from a node.

predecessors(node_id, edge_type=None)

Get predecessor nodes (via incoming edges).

remove_edge(edge_id)

Remove an edge from the graph.

remove_node(node_id)

Remove a node and all its edges.

Returns

PlatialNode The removed node.

snapshot(timestamp)

Create a snapshot of the graph at a specific time.

Only includes nodes and edges valid at that timestamp.

subgraph(node_ids)

Extract a subgraph containing only the specified nodes.

Includes all edges where both endpoints are in the subgraph.

Types & Enumerations

chora.core.types

Core Type Definitions for Chora

This module defines the foundational types, enumerations, and type aliases used throughout the Chora library. These types encode the ontological structure of platial modelling.

Type Categories

  1. Node Types — classify entities in the platial graph
  2. Edge Types — classify relations between entities
  3. Epistemic Levels — distinguish data provenance and certainty
  4. Context Types — categorise situational modifiers
  5. Affect Dimensions — model experiential response
  6. Practice Types — classify emergent patterns

Design Rationale

Types are defined as string-backed enums to ensure: - Serialization compatibility across backends - Human-readable graph inspection - Extension without breaking existing data

Examples

from chora.core.types import NodeType, EpistemicLevel NodeType.ENCOUNTER EpistemicLevel.OBSERVED.value 'observed'

NodeType

Bases: str, Enum

Classification of node types in the platial graph.

Each type represents a distinct ontological category in platial modelling. Place is notably absent because it emerges as a subgraph, not a primitive.

Attributes

AGENT : str An entity with situated experience (human, group, or proxy). SPATIAL_EXTENT : str A weakly semanticised spatial support (geometry with minimal semantics). ENCOUNTER : str A spatio-temporal relation between an agent and a spatial extent. CONTEXT : str Situational modifiers that affect the character of an encounter. PRACTICE : str An emergent, patterned structure over repeated encounters. AFFECT : str An experiential response distribution attached to an encounter or place. FAMILIARITY : str An evolving state variable representing accumulated experience. LIMINALITY : str A conditional, transitional quality at spatial or experiential boundaries. MEANING : str A structured symbolic interpretation attached to place.

Examples

NodeType.ENCOUNTER NodeType.ENCOUNTER.value 'encounter' NodeType('encounter')

EdgeType

Bases: str, Enum

Classification of edge types in the platial graph.

Edges encode relations, transitions, derivations, and interpretations. Platial qualities are primarily encoded on edges, not nodes.

Attributes

PARTICIPATES_IN : str Agent ─participates_in─▶ Encounter OCCURS_AT : str Encounter ─occurs_at─▶ SpatialExtent HAS_CONTEXT : str Encounter ─has_context─▶ Context DERIVES_FROM : str Derived entity ─derives_from─▶ Source entity (provenance) TRANSITIONS_TO : str Encounter ─transitions_to─▶ Encounter (temporal sequence) REINFORCES : str Encounter ─reinforces─▶ Familiarity (strengthening relation) DECAYS : str Time ─decays─▶ Familiarity (weakening relation) EXPRESSES : str Encounter ─expresses─▶ Affect INTERPRETS_AS : str Agent ─interprets_as─▶ Meaning (subjective interpretation) BELONGS_TO : str Encounter ─belongs_to─▶ Practice (pattern membership) BOUNDS : str SpatialExtent ─bounds─▶ Liminality (boundary relation) CROSSES : str Encounter ─crosses─▶ Liminality (threshold crossing) SIMILAR_TO : str Entity ─similar_to─▶ Entity (similarity relation) CONFLICTS_WITH : str Meaning ─conflicts_with─▶ Meaning (interpretive conflict)

Examples

EdgeType.PARTICIPATES_IN

EpistemicLevel

Bases: str, Enum

Classification of data by epistemic status.

This is a core design principle: observed, derived, and interpreted data are explicitly distinguished throughout the library.

Attributes

OBSERVED : str Direct observation or measurement from sensors, surveys, or traces. Highest confidence, lowest interpretation. DERIVED : str Computed from observed data using deterministic or probabilistic methods. Provenance to source data is preserved. INTERPRETED : str Semantic or symbolic interpretation involving subjective judgement. Lowest confidence, highest interpretation.

Examples

from chora.core.types import EpistemicLevel level = EpistemicLevel.OBSERVED level.is_more_certain_than(EpistemicLevel.DERIVED) True

Notes

The ordering OBSERVED > DERIVED > INTERPRETED represents decreasing epistemic certainty and increasing interpretive content.

certainty_order property

Return numeric ordering for certainty comparisons.

is_more_certain_than(other)

Compare epistemic certainty levels.

Parameters

other : EpistemicLevel The level to compare against.

Returns

bool True if this level is epistemically more certain.

Examples

EpistemicLevel.OBSERVED.is_more_certain_than(EpistemicLevel.DERIVED) True EpistemicLevel.INTERPRETED.is_more_certain_than(EpistemicLevel.OBSERVED) False

PracticeType

Bases: str, Enum

Classification of emergent practices over encounters.

Practices are patterned structures that emerge from repeated encounters and form the basis of routines and habits.

Attributes

ROUTINE : str Regularly repeated pattern with consistent timing. HABIT : str Automatic, often unconscious repeated behaviour. RITUAL : str Symbolically meaningful repeated practice. EXPLORATION : str Pattern of novelty-seeking and discovery. AVOIDANCE : str Consistent pattern of avoiding certain places. DWELLING : str Extended presence in a place. TRAVERSAL : str Movement through places without dwelling.

Examples

PracticeType.ROUTINE

Spatial Extent

chora.core.spatial_extent

SpatialExtent Domain Object

A SpatialExtent is a weakly semanticised spatial support — geometry with minimal semantics, allowing platial meaning to emerge from encounters.

SpatialExtent dataclass

Bases: PlatialNode

A weakly semanticised spatial support.

SpatialExtent represents the spatial dimension of place without imposing strong semantic categories. Place meaning emerges through encounters rather than being predefined.

Parameters

name : str Human-readable name (optional, minimal semantics). geometry : BaseGeometry | None Shapely geometry representing the spatial extent. extent_type : str Loose classification (e.g., "area", "path", "point"). semantic_hints : dict[str, Any] Optional weak semantic hints (not definitive categories).

Examples

from shapely.geometry import Point, Polygon

A location point

cafe = SpatialExtent( ... name="Corner Cafe", ... geometry=Point(-0.1276, 51.5074), ... extent_type="point" ... )

An area polygon

park = SpatialExtent( ... name="Hyde Park", ... geometry=Polygon([...]), ... extent_type="area", ... semantic_hints={"land_use": "recreation"} ... )

area_m2 property

Get area in square meters (approximate for geographic coords).

bounds property

Get bounding box (minx, miny, maxx, maxy).

centroid property

Get the centroid coordinates (lon, lat).

has_geometry property

Check if geometry is defined.

buffer(distance)

Create a new extent buffered by the given distance.

contains_point(lon, lat)

Check if a point is within this extent.

distance_to(other)

Calculate distance to another extent (in geometry units).

from_bounds(minx, miny, maxx, maxy, name='') classmethod

Create an extent from bounding box.

from_geojson(geojson) classmethod

Create from GeoJSON feature.

from_point(lon, lat, name='') classmethod

Create a point extent. Alias for point() method.

get_hint(key, default=None)

Get a semantic hint.

intersects(other)

Check if this extent intersects another.

point(lon, lat, name='') classmethod

Create a point extent.

set_hint(key, value)

Set a semantic hint.

to_geojson()

Export geometry as GeoJSON.

Agent

chora.core.agent

Agent Domain Object

An Agent is an entity with situated experience — a human, group, or proxy that can participate in encounters with spatial extents.

Agent dataclass

Bases: PlatialNode

An entity with situated experience.

Agents are the experiential subjects in platial modelling. They participate in encounters, develop familiarity, express affect, and interpret meaning.

Parameters

name : str Human-readable name for this agent. agent_id : AgentId | None Optional domain-specific identifier. agent_type : str Type of agent (e.g., "individual", "group", "proxy"). attributes : dict[str, Any] Agent attributes (demographics, preferences, etc.).

Examples

alice = Agent(name="Alice", agent_type="individual") alice.node_type

With custom attributes

walker = Agent( ... name="Walker 001", ... agent_type="individual", ... attributes={"mobility": "walking", "age_group": "adult"} ... )

display_name property

Return display name, falling back to ID if no name.

get_attribute(key, default=None)

Get an agent attribute.

group(name, members=None, **attributes) classmethod

Create a group agent.

individual(name, **attributes) classmethod

Create an individual agent.

proxy(name, represented_by, **attributes) classmethod

Create a proxy agent (representing another entity).

set_attribute(key, value)

Set an agent attribute.

Temporal Functions

chora.core.temporal

Temporal Semantics for Chora

This module implements temporal representation and functions for platial modelling. All nodes and edges have explicit lifetimes; decay and reinforcement functions govern familiarity, affect, and practice stability.

Temporal

Bases: Protocol

Protocol for objects with temporal validity.

TemporalValidity dataclass

Tracks temporal validity with creation and modification timestamps.

Attributes

created_at : Timestamp When this entity was created. valid_from : Timestamp | None Start of validity period. valid_to : Timestamp | None End of validity period (None = still valid). modified_at : Timestamp | None When this entity was last modified.

interval property

Return the validity as a TimeInterval.

is_current property

Check if currently valid (valid_to is None or in future).

invalidate(at=None)

Mark as no longer valid.

is_valid_at(timestamp)

Check if valid at the given timestamp.

TimeInterval dataclass

Represents a time interval with optional open bounds.

A time interval [start, end] where either bound may be None (open-ended). Supports containment, overlap, and duration queries.

Parameters

start : Timestamp | None Start of interval (inclusive). None means unbounded past. end : Timestamp | None End of interval (inclusive). None means unbounded future.

Examples

from datetime import datetime interval = TimeInterval( ... start=datetime(2024, 1, 1), ... end=datetime(2024, 12, 31) ... ) interval.contains(datetime(2024, 6, 15)) True interval.duration datetime.timedelta(days=365)

duration property

Return the duration of this interval, or None if unbounded.

is_bounded property

Check if both bounds are defined.

is_instant property

Check if this represents a single point in time.

contains(timestamp)

Check if timestamp falls within this interval.

from_now(duration) classmethod

Create an interval from now for the given duration.

instant(timestamp) classmethod

Create an interval representing a single instant.

overlaps(other)

Check if this interval overlaps with another.

unbounded() classmethod

Create an unbounded interval (all time).

compute_decay(initial_value, start, end, decay_fn=exponential_decay)

Compute decayed value between two timestamps.

Parameters

initial_value : float Value at start time. start : Timestamp Starting timestamp. end : Timestamp Ending timestamp. decay_fn : DecayFunction Decay function to apply.

Returns

float Decayed value at end time.

exponential_decay(initial_value, time_delta, half_life=7.0)

Exponential decay function for familiarity and affect.

Parameters

initial_value : float Starting value (typically in [0, 1]). time_delta : float Time elapsed (in days). half_life : float Time for value to decay to half (in days). Default 7 days.

Returns

float Decayed value.

Examples

exponential_decay(1.0, 7.0, half_life=7.0) # After one half-life 0.5 exponential_decay(1.0, 14.0, half_life=7.0) # After two half-lives 0.25

linear_decay(initial_value, time_delta, rate=0.1)

Linear decay function.

Parameters

initial_value : float Starting value. time_delta : float Time elapsed (in days). rate : float Decay rate per day. Default 0.1.

Returns

float Decayed value, clamped to [0, initial_value].

linear_reinforcement(current_value, increment=0.1, maximum=1.0)

Linear reinforcement with saturation.

Parameters

current_value : float Current value before reinforcement. increment : float Amount to add. Default 0.1. maximum : float Maximum allowed value. Default 1.0.

Returns

float Reinforced value, clamped to maximum.

power_law_decay(initial_value, time_delta, exponent=0.5, offset=1.0)

Power law decay: value = initial / (offset + time)^exponent

Models slower decay over time, often observed in memory research.

Parameters

initial_value : float Starting value. time_delta : float Time elapsed (in days). exponent : float Power law exponent. Default 0.5. offset : float Time offset to avoid division by zero. Default 1.0.

Returns

float Decayed value.

saturating_reinforcement(current_value, increment=0.1, maximum=1.0)

Saturating reinforcement: diminishing returns near maximum.

Uses formula: new = current + increment * (1 - current/maximum)

Parameters

current_value : float Current value before reinforcement. increment : float Base increment amount. Default 0.1. maximum : float Asymptotic maximum. Default 1.0.

Returns

float Reinforced value approaching but never exceeding maximum.

Uncertainty

chora.core.uncertainty

Uncertainty Representation for Chora

This module provides probabilistic and fuzzy representation of uncertainty. Vagueness is modelled, not suppressed. This is a core design principle.

CategoricalDistribution dataclass

Bases: ProbabilityDistribution

Categorical distribution over discrete outcomes.

Parameters

categories : Sequence[str] Category labels. probabilities : Sequence[float] Probability for each category (must sum to 1).

entropy property

Shannon entropy of the distribution.

mode property

Return the most likely category.

pdf(x)

Not applicable for categorical; raises error.

probability(category)

Get probability of a specific category.

sample()

Draw a random category.

ConfidenceInterval dataclass

Represents a confidence interval.

Parameters

lower : float Lower bound of the interval. upper : float Upper bound of the interval. confidence : float Confidence level (e.g., 0.95 for 95%).

midpoint property

Return the midpoint of the interval.

width property

Return the width of the interval.

contains(value)

Check if a value falls within the interval.

FuzzyMembership

Bases: ABC

Abstract base class for fuzzy membership functions.

membership(x) abstractmethod

Return membership degree in [0, 1] for value x.

GaussianDistribution dataclass

Bases: ProbabilityDistribution

Gaussian (normal) distribution.

Parameters

mu : float Mean of the distribution. sigma : float Standard deviation (must be positive).

confidence_interval(confidence=0.95)

Return confidence interval for given level.

pdf(x)

Probability density at x.

sample()

Draw a random sample using Box-Muller transform.

ProbabilityDistribution

Bases: ABC

Abstract base class for probability distributions.

mean abstractmethod property

Expected value.

variance abstractmethod property

Variance.

pdf(x) abstractmethod

Probability density function.

sample() abstractmethod

Draw a random sample from the distribution.

TrapezoidalFuzzy dataclass

Bases: FuzzyMembership

Trapezoidal fuzzy membership function.

Parameters

left_foot : float Left foot (membership = 0). left_shoulder : float Start of flat top (membership = 1). right_shoulder : float End of flat top (membership = 1). right_foot : float Right foot (membership = 0).

TriangularFuzzy dataclass

Bases: FuzzyMembership

Triangular fuzzy membership function.

Parameters

left : float Left foot (membership = 0). peak : float Peak (membership = 1). right : float Right foot (membership = 0).

UncertaintyValue dataclass

A value with associated uncertainty.

Parameters

value : float Central/expected value. uncertainty : float Uncertainty measure (interpretation depends on context). confidence : float | None Optional confidence level.

Examples

uv = UncertaintyValue(value=0.75, uncertainty=0.1) uv.as_interval(confidence=0.95) ConfidenceInterval(lower=0.55, upper=0.95, confidence=0.95)

as_interval(confidence=0.95)

Convert to confidence interval (assuming ±uncertainty).


Derivation Module

chora.derive

Chora Derive Module

Theory-encoded derivation operators for transforming raw data into platial structures. These operators embody platial theory, not ad-hoc heuristics.

Operators include: - Encounter extraction from traces - Familiarity update functions - Practice detection via sequence analysis - Liminality inference from transitions - Affect and meaning attachment with provenance - Place emergence as subgraph extraction

attach_affect(encounter, valence, arousal, source='external', uncertainty=0.1)

Attach affect to an encounter with explicit values.

Parameters

encounter : Encounter The encounter to attach affect to. valence : float Valence value [-1, 1]. arousal : float Arousal value [0, 1]. source : str Source of affect data ("self_report", "derived", "external"). uncertainty : float Uncertainty in the affect values.

Returns

Affect The created affect node.

attach_meaning(agent_id, extent_id, content, meaning_type=MeaningType.PERSONAL, symbols=None, strength=1.0)

Attach meaning to a place.

Parameters

agent_id : AgentId | None Who holds this meaning (None for shared). extent_id : ExtentId Which place. content : str The meaning content. meaning_type : MeaningType Type of meaning. symbols : Sequence[str] | None Symbolic labels. strength : float How strongly held [0, 1].

Returns

Meaning The created meaning node.

compute_familiarity_trajectory(encounters, agent_id, extent_id, decay_half_life_days=14.0)

Compute familiarity trajectory over time.

Returns a time series of (timestamp, familiarity_value) pairs showing how familiarity evolved through the encounters.

Parameters

encounters : Sequence[Encounter] Encounters for this agent-extent pair. agent_id : AgentId Agent ID. extent_id : ExtentId Extent ID. decay_half_life_days : float Half-life for familiarity decay.

Returns

list[tuple[datetime, float]] Time series of familiarity values.

decay_all_familiarities(graph, to_time=None)

Apply decay to all familiarity nodes in the graph.

Returns the number of familiarities updated.

derive_affect_from_context(encounter, contexts)

Derive affect from encounter context.

Uses contextual information to infer likely affect. This is a theory-encoded heuristic based on environmental psychology.

Parameters

encounter : Encounter The encounter. contexts : list[Context] Associated contexts.

Returns

Affect | None Derived affect, or None if insufficient context.

derive_meaning_from_practices(practices, agent_id, extent_id)

Derive meaning from observed practices.

Practices reveal how a place is used and experienced, which gives rise to functional and personal meanings.

Parameters

practices : Sequence[Practice] Practices involving this place. agent_id : AgentId Agent whose practices to analyze. extent_id : ExtentId The place to derive meaning for.

Returns

list[Meaning] Derived meanings.

detect_boundary_crossings(encounters, extents)

Detect boundary crossings between adjacent encounters.

Returns list of (boundary_extent_id, from_type, to_type) tuples.

detect_practices(encounters, agent_id, config=None)

Detect practices from encounter sequences.

Identifies routines, habits, and other patterns based on spatial, temporal, and sequential regularities.

Parameters

encounters : Sequence[Encounter] Encounters to analyze. agent_id : AgentId Agent to detect practices for. config : PracticeDetectionConfig | None Detection configuration.

Returns

list[Practice] Detected practices.

detect_routines(encounters, config=None)

Detect location-time routines.

A routine is a repeated pattern of visiting the same location at similar times.

extract_encounters(trace, agent_id, extents, config=None)

Extract encounters from a location trace.

An encounter is detected when the agent dwells within a spatial extent for a minimum duration.

Parameters

trace : Sequence[TracePoint] Ordered sequence of location points. agent_id : AgentId ID of the agent being tracked. extents : Sequence[SpatialExtent] Spatial extents to match against. config : EncounterExtractionConfig | None Extraction configuration.

Returns

list[Encounter] Extracted encounters.

Examples

trace = [ ... TracePoint(datetime(2024, 1, 1, 10, 0), -0.127, 51.507), ... TracePoint(datetime(2024, 1, 1, 10, 30), -0.127, 51.507), ... TracePoint(datetime(2024, 1, 1, 11, 0), -0.128, 51.508), ... ] park = SpatialExtent.from_bounds(-0.13, 51.50, -0.12, 51.51, "Park") encounters = extract_encounters(trace, AgentId("a1"), [park])

extract_encounters_from_trace(trace, agent_id, config=None)

Extract encounters by clustering a trace without predefined extents.

Detects dwell locations by finding spatial clusters of points that exceed the minimum duration threshold.

extract_place(graph, extent_id, agent_id=None)

Extract an emergent place centered on a spatial extent.

Gathers all encounters, affects, meanings, and familiarities related to the specified extent, optionally filtered by agent.

Parameters

graph : PlatialGraph The platial graph. extent_id : ExtentId ID of the central spatial extent. agent_id : AgentId | None Optional agent filter.

Returns

EmergentPlace The emergent place structure.

find_emergent_places(graph, agent_id=None, min_encounters=3)

Find all emergent places in the graph.

Returns places that have sufficient activity to be meaningful.

find_sequence_patterns(encounters, config=None)

Find sequential patterns (A → B → C).

Returns list of (pattern_name, encounter_ids, regularity).

infer_liminality(encounters, extents, config=None)

Infer liminal zones from transition patterns.

Identifies spatial extents that frequently serve as transition points between other places.

Parameters

encounters : Sequence[Encounter] Ordered encounters. extents : dict[str, SpatialExtent] Mapping of extent IDs to SpatialExtent objects. config : LiminalityInferenceConfig | None Inference configuration.

Returns

list[Liminality] Inferred liminal zones.

merge_nearby_encounters(encounters, max_time_gap=timedelta(minutes=5))

Merge temporally adjacent encounters at the same extent.

update_familiarity(graph, encounter)

Update familiarity based on a new encounter.

Finds or creates a Familiarity node for the agent-extent pair and reinforces it based on the encounter.

Parameters

graph : PlatialGraph The platial graph. encounter : Encounter The encounter to process.

Returns

Familiarity The updated familiarity node.


Query Module

chora.query

Chora Query Module

High-level platial queries and graph traversal operations. Queries compile down to graph traversals with temporal filtering.

PlatialQuery dataclass

Fluent query builder for platial queries.

Examples

query = (PlatialQuery(graph) ... .for_agent("walker_001") ... .with_familiarity(min_value=0.5) ... .with_positive_affect() ... .valid_at(datetime.now())) places = query.execute()

add_filter(predicate)

Add custom filter.

at_extents(extent_ids)

Filter to specific extents.

execute()

Execute query and return matching places.

for_agent(agent_id)

Filter to a specific agent.

valid_at(timestamp)

Filter to nodes valid at timestamp.

with_familiarity(min_value=None, max_value=None)

Filter by familiarity range.

with_negative_affect()

Filter to negative affect.

with_positive_affect()

Filter to positive affect.

find_connected(graph, node_id, edge_types=None)

Find all nodes connected to the given node.

find_familiar_places(graph, agent_id, min_familiarity=0.5)

Find places where agent has high familiarity.

find_path(graph, start_id, end_id, edge_types=None)

Find shortest path between two nodes.

Returns list of node IDs or None if no path exists.

find_positive_places(graph, agent_id)

Find places with positive affect for agent.

find_practices_like(graph, template, min_similarity=0.5)

Find practices similar to a template.

find_routine_places(graph, agent_id, min_encounters=5)

Find places that are part of routines.

match_pattern(graph, pattern_type, **kwargs)

Match a named pattern against the graph.

place_similarity(p1, p2)

Compute similarity between two emergent places.

Considers familiarity, affect, and encounter patterns.

practice_similarity(p1, p2)

Compute similarity between two practices.

query_encounters(graph, agent_id=None, extent_id=None, start_time=None, end_time=None)

Query encounters with filters.

snapshot_query(graph, at)

Get a snapshot of the graph at a specific time.

Returns a new graph containing only nodes and edges valid at the given timestamp.

temporal_range_query(graph, start, end)

Query nodes active during a time range.

Yields nodes whose validity overlaps with [start, end].

traverse_from(graph, start_id, edge_types=None, max_depth=3)

Breadth-first traversal from a starting node.

Yields (node, depth) tuples.


Adapters

Base Adapter

chora.adapters.base

Base Adapter Interface

Abstract interface for graph storage backends.

GraphAdapter

Bases: ABC

Abstract base class for graph storage adapters.

Adapters provide persistence and querying for platial graphs, abstracting over different backend technologies.

add_edge(edge) abstractmethod

Add or update a single edge.

add_node(node) abstractmethod

Add or update a single node.

connect(**kwargs) abstractmethod

Establish connection to the backend.

delete_edge(edge_id) abstractmethod

Delete an edge. Returns True if deleted.

delete_node(node_id) abstractmethod

Delete a node. Returns True if deleted.

disconnect() abstractmethod

Close connection to the backend.

get_edge(edge_id) abstractmethod

Retrieve an edge by ID.

get_node(node_id) abstractmethod

Retrieve a node by ID.

load_graph(name) abstractmethod

Load a graph by name from the backend.

query_edges(edge_type=None, source_id=None, target_id=None, **filters) abstractmethod

Query edges with optional filters.

query_nodes(node_type=None, **filters) abstractmethod

Query nodes with optional filters.

save_graph(graph) abstractmethod

Save entire graph to the backend.

snapshot(at)

Get temporal snapshot (default: load and filter).

In-Memory Adapter

chora.adapters.memory

In-Memory Adapter

Default adapter that stores graphs in memory. Suitable for development, testing, and small datasets.

InMemoryAdapter

Bases: GraphAdapter

In-memory graph storage adapter.

Stores graphs in dictionaries. Supports multiple named graphs. Data is lost when the adapter is garbage collected.

Examples

adapter = InMemoryAdapter() adapter.connect() adapter.save_graph(my_graph) loaded = adapter.load_graph("my_graph")

add_edge(edge)

Add edge to active graph.

add_node(node)

Add node to active graph.

clear()

Clear all stored graphs.

connect(**kwargs)

Connect (no-op for in-memory).

delete_edge(edge_id)

Delete edge from active graph.

delete_graph(name)

Delete a graph. Returns True if deleted.

delete_node(node_id)

Delete node from active graph.

disconnect()

Disconnect (no-op for in-memory).

get_edge(edge_id)

Get edge from active graph.

get_node(node_id)

Get node from active graph.

list_graphs()

List all stored graph names.

load_graph(name)

Load graph from memory.

query_edges(edge_type=None, source_id=None, target_id=None, **filters)

Query edges in active graph.

query_nodes(node_type=None, **filters)

Query nodes in active graph.

save_graph(graph)

Save graph to memory.

set_active_graph(graph)

Set the active graph for node/edge operations.

snapshot(at)

Get temporal snapshot of active graph.


CLI

chora.cli

Chora CLI — Command-line interface for the platial modelling library.

Usage

chora load gpx --agent chora load geojson chora derive familiarity --agent chora derive practices --agent chora query familiar --agent --min chora viz export --format d3 --output

cli()

Chora — A platial modelling library for Python.

Model human experience of place with encounters, familiarity, affect, and practices.

derive()

Derive platial qualities from data.

derive_familiarity(agent)

Update familiarity scores for an agent.

derive_practices(agent, min_occurrences)

Detect practices and routines for an agent.

export_d3(graph)

Export graph to D3.js-compatible JSON.

export_dot(graph)

Export graph to GraphViz DOT format.

generate_timeline_html(encounters, agent)

Generate simple HTML timeline.

get_graph()

Get or create the active graph.

load()

Load data into Chora graph.

load_csv(file, lon_col, lat_col, name_col)

Load CSV as spatial extents.

load_geojson(file, name_field)

Load GeoJSON as spatial extents.

load_gpx(file, agent, activity)

Load GPX trace as encounters.

Each trackpoint becomes an encounter at the corresponding location.

main()

CLI entry point.

query()

Query the platial graph.

query_familiar(agent, min_val)

Find places where agent has high familiarity.

query_stats()

Show graph statistics.

viz()

Visualization and export commands.

viz_export(fmt, output)

Export graph for visualization.

viz_timeline(agent, output)

Generate timeline visualization for an agent.