# How to Implement Temporal Reasoning with Semantica's TemporalReasoningEngine

> Implement temporal reasoning with Semantica's TemporalReasoningEngine. Leverage versioned knowledge graphs, bitemporal facts, and Allen interval algebra for powerful time-aware queries.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-09

---

**Semantica's TemporalReasoningEngine enables versioned knowledge graph snapshots, bitemporal fact modeling, and Allen interval algebra queries through the `TemporalVersionManager` class in [`semantica/kg/temporal_query.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/temporal_query.py).**

The open-source `semantica-agi/semantica` repository provides a robust Temporal Reasoning Engine for modeling time-varying knowledge graphs. This engine allows you to implement temporal reasoning with Semantica's TemporalReasoningEngine to track how facts evolve over both valid-time and transaction-time dimensions. By leveraging the three-layer architecture—spanning data models, query APIs, and visualization tools—you can build sophisticated "as-of-time" analytics pipelines.

## Understanding the Three-Layer Architecture

The Temporal Reasoning Engine organizes functionality into distinct layers, each handling specific aspects of temporal data management.

### Temporal Model Layer

Located in [`semantica/kg/temporal_model.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/temporal_model.py), this layer defines core data structures including `BiTemporalFact`, `TemporalBound`, and validation utilities like `parse_temporal_value` and `parse_temporal_bound`. These classes represent instants, intervals, and bitemporal facts that combine valid-time (when a fact holds in reality) with transaction-time (when it was recorded in the system).

### Temporal Query API Layer

The `TemporalVersionManager` class in [`semantica/kg/temporal_query.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/temporal_query.py) provides the high-level interface for creating versioned snapshots and querying temporal relations. This layer supports as-of-queries without mutating the underlying knowledge graph.

### Temporal Visualization Layer

Found in [`semantica/visualization/temporal_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/temporal_visualizer.py), this layer renders interactive timelines and metric evolution charts using Plotly, with fallback support for static PNG output.

## Modeling Temporal Data Structures

Semantica represents temporal information within a knowledge graph payload that includes entities, relationships, timestamps, and events.

```json
{
  "entities": [...],
  "relationships": [...],
  "timestamps": {
    "entity_id": ["2020-01-01", "2023-07-15"]
  },
  "events": [
    {"timestamp": "2023-01-01", "type": "create", "label": "E1"},
    {"timestamp": "2023-02-15", "type": "update", "label": "E2"}
  ]
}

```

The engine handles three temporal primitives:

- **Instants**: ISO-8601 strings such as `"2023-01-01"`
- **Intervals**: Pairs of instants defining start and end bounds
- **Bitemporal facts**: Objects wrapping both valid-time and transaction-time dimensions, validated by `parse_temporal_bound` to raise `TemporalValidationError` for malformed inputs

## Creating Versioned Snapshots with TemporalVersionManager

To implement temporal reasoning with point-in-time analysis, use the `TemporalVersionManager` to create immutable snapshots of your knowledge graph at specific transaction-times.

```python
from semantica.kg.temporal_query import TemporalVersionManager

# kg is a dict following the Semantica schema

version_mgr = TemporalVersionManager(kg)

# Create versioned snapshots

v2020 = version_mgr.create_version(timestamp="2020-01-01", version_label="v2020")
v2023 = version_mgr.create_version(timestamp="2023-01-01", version_label="v2023")

```

Each version contains a **temporal slice** retaining only facts whose valid-time intersects the chosen transaction-time. This enables efficient as-of-query semantics while preserving the original knowledge graph state.

## Querying Temporal Relations and Distances

The `TemporalVersionManager` provides convenience methods for temporal reasoning beyond simple snapshotting.

**Calculate temporal distance** between two events using the `distance` method, which returns the numeric difference in days:

```python
days = version_mgr.distance(event1="2020-02-01", event2="2021-05-15")
print(f"Distance: {days} days")

```

**Compute Allen interval relations** using the `allen` method to determine topological relationships like `before`, `meets`, `overlaps`, or `contains`:

```python
relation = version_mgr.allen(event1="2023-01-01", event2="2023-01-15")
print(relation)  # Output: "overlaps"

```

**Retrieve entity evolution** with the `history` method, which returns the complete temporal trajectory for a specific entity ID.

## Visualizing Temporal Data

The `TemporalVisualizer` class in [`semantica/visualization/temporal_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/temporal_visualizer.py) transforms temporal slices into interactive visualizations.

```python
from semantica.visualization.temporal_visualizer import TemporalVisualizer

viz = TemporalVisualizer()

# Interactive timeline

timeline = viz.visualize_timeline(kg, output="interactive")

# Compare snapshots

comparison = viz.visualize_snapshot_comparison(
    snapshots=[v2020, v2023],
    output="interactive"
)

```

All visualization methods accept an `output` parameter set to `"interactive"` for Plotly figures or `"static"` for PNG images. The class raises `ProcessingError` if optional dependencies like Plotly are unavailable.

## Complete Implementation Example

This end-to-end example demonstrates the full workflow to implement temporal reasoning with Semantica's TemporalReasoningEngine:

```python
from semantica.kg.temporal_query import TemporalVersionManager
from semantica.visualization.temporal_visualizer import TemporalVisualizer

# 1. Load or construct a knowledge graph with temporal fields

kg = {
    "entities": [{"id": "E1", "type": "Person", "name": "Alice"}],
    "relationships": [
        {
            "source": "E1",
            "target": "E2",
            "type": "knows",
            "valid_time": {"start": "2021-01-01", "end": "2022-12-31"},
            "transaction_time": {"instant": "2021-01-10"}
        }
    ],
    "timestamps": {"E1": ["2021-01-01", "2022-01-01"]},
    "events": [
        {"timestamp": "2021-01-05", "type": "create", "label": "E1_created"},
        {"timestamp": "2022-06-20", "type": "update", "label": "E1_name_change"}
    ]
}

# 2. Initialize the temporal engine

tv_mgr = TemporalVersionManager(kg)

# 3. Create versioned snapshots

v_start = tv_mgr.create_version(timestamp="2020-01-01", version_label="start")
v_end = tv_mgr.create_version(timestamp="2023-12-31", version_label="end")

# 4. Query temporal relations

days = tv_mgr.distance(event1="2020-02-01", event2="2021-05-15")
print(f"Temporal distance: {days} days")

# 5. Visualize the evolution

viz = TemporalVisualizer()
viz.visualize_version_history(
    version_history=[v_start, v_end],
    output="interactive"
)

```

## Summary

- **Semantica's TemporalReasoningEngine** provides three layers: data models ([`temporal_model.py`](https://github.com/semantica-agi/semantica/blob/main/temporal_model.py)), query APIs ([`temporal_query.py`](https://github.com/semantica-agi/semantica/blob/main/temporal_query.py)), and visualization ([`temporal_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/temporal_visualizer.py)).
- **Bitemporal facts** combine valid-time and transaction-time dimensions, validated by `parse_temporal_value` and `parse_temporal_bound`.
- **TemporalVersionManager** creates immutable snapshots via `create_version` and supports Allen algebra queries via the `allen` method.
- **TemporalVisualizer** generates interactive Plotly charts or static PNG outputs, raising `ProcessingError` for missing dependencies.
- **Test coverage** for these features is available in [`tests/kg/test_temporal_query_rewriter.py`](https://github.com/semantica-agi/semantica/blob/main/tests/kg/test_temporal_query_rewriter.py) and [`tests/visualization/test_visualization_comprehensive.py`](https://github.com/semantica-agi/semantica/blob/main/tests/visualization/test_visualization_comprehensive.py).

## Frequently Asked Questions

### What is the difference between valid-time and transaction-time in Semantica?

Valid-time represents when a fact actually holds true in the real world, while transaction-time records when that fact was stored in the knowledge graph. The `BiTemporalFact` class in [`semantica/kg/temporal_model.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/temporal_model.py) encapsulates both dimensions, enabling historical audit trails alongside semantic validity periods.

### How does TemporalVersionManager handle invalid date formats?

The `TemporalVersionManager` relies on validation utilities in [`temporal_model.py`](https://github.com/semantica-agi/semantica/blob/main/temporal_model.py) including `parse_temporal_value` and `parse_temporal_bound`. These helpers raise a `TemporalValidationError` immediately when encountering malformed ISO-8601 strings or unsupported temporal types, preventing corrupt data from entering the versioned snapshot pipeline.

### Can I use the temporal reasoning features without installing Plotly?

Yes. The `TemporalVisualizer` in [`semantica/visualization/temporal_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/temporal_visualizer.py) supports an `output="static"` parameter that generates PNG images instead of interactive Plotly figures. If Plotly is not installed and you request interactive output, the class raises a `ProcessingError` with instructions for installing the optional dependency.

### Which Allen interval relations does the allen method support?

The `allen` method in `TemporalVersionManager` computes all thirteen Allen interval algebra relations including `before`, `meets`, `overlaps`, `starts`, `contains`, `finished`, and `equals`. These topological relationships enable sophisticated temporal reasoning about how events and intervals relate to one another across the knowledge graph timeline.