graph TB
subgraph Entity["Entity Library"]
ET["EntityTypes.hpp<br/>(EntityId, EntityKind, etc.)"]
ER["EntityRegistry<br/>(ID allocation)"]
EGM["EntityGroupManager<br/>(grouping)"]
subgraph Lineage["Lineage Subsystem"]
LT["LineageTypes.hpp<br/>(variant types)"]
LReg["LineageRegistry<br/>(metadata storage)"]
LRes["LineageResolver<br/>(resolution logic)"]
IDS["IEntityDataSource<br/>(abstract interface)"]
end
end
ET --> ER
ET --> EGM
LT --> LReg
IDS --> LRes
LReg --> LRes
Entity Library
Entity Library
The Entity library provides core functionality for entity identification, registration, grouping, and lineage tracking in WhiskerToolbox. It is designed as a DataManager-independent library, enabling reuse across different data management systems.
Architecture Overview
Core Components
EntityTypes
Located in Entity/EntityTypes.hpp, defines the fundamental types:
EntityId: Strongly-typed identifier for entities (wrapsuint64_t)EntityKind: Enumeration of entity categories (Point, Line, Event, Interval, Mask)EntityDescriptor: Combines data_key, kind, time_value, and local_indexEntityTupleKey: Composite key for entity registry lookupsDataEntry<T>: Template wrapper pairing data with EntityId
#include "Entity/EntityTypes.hpp"
// EntityId requires explicit construction
EntityId id(42);
// EntityIds are comparable and hashable
if (id == EntityId(42)) { /* ... */ }
// Use in unordered containers (std::hash specialization provided)
std::unordered_set<EntityId> entity_set;
entity_set.insert(id);
// EntityKind enumeration
EntityKind kind = EntityKind::MaskEntity;EntityRegistry
Thread-safe registry that maps (data_key, kind, time, local_index) tuples to unique EntityIds:
#include "Entity/EntityRegistry.hpp"
EntityRegistry registry;
// Get or create an EntityId for the tuple (idempotent)
EntityId id = registry.ensureId("masks", EntityKind::MaskEntity,
TimeFrameIndex(10), 0);
// Lookup descriptor for an EntityId
auto desc = registry.get(id);
if (desc) {
std::cout << "Data key: " << desc->data_key << "\n";
std::cout << "Time: " << desc->time_value << "\n";
}
// Clear all entities (session reset)
registry.clear();Thread Safety: EntityRegistry uses std::mutex internally and is safe to use from multiple threads.
Interval entities
For EntityKind::IntervalEntity, the registry tuple is (data_key, start, end):
time/time_value— interval start (TimeFrameIndex)local_index— interval end (not a storage index)
DigitalIntervalSeries keys new intervals this way via ensureId. When intervals merge (for example, extending an interval end in the DataInspector), the EntityId from the earliest-start merged interval is preserved and the registry entry is rebound to the new bounds via rebindKey. Reverse lookup uses the EntityId stored on the interval (findByEntityId), not the registry index.
EntityGroupManager
Manages user-defined groups of entities with observer notification support:
#include "Entity/EntityGroupManager.hpp"
EntityGroupManager manager;
// Create a group (returns unique GroupId)
GroupId group = manager.createGroup("whisker_1", "First whisker entities");
// Add single entity
manager.addEntityToGroup(group, EntityId(100));
// Add multiple entities efficiently
std::vector<EntityId> ids = {EntityId(101), EntityId(102), EntityId(103)};
std::size_t added = manager.addEntitiesToGroup(group, ids);
// Query group contents
auto members = manager.getEntitiesInGroup(group);
bool in_group = manager.isEntityInGroup(group, EntityId(100));
// Reverse lookup: which groups contain an entity?
auto groups = manager.getGroupsContainingEntity(EntityId(100));
// Get group metadata
auto descriptor = manager.getGroupDescriptor(group);
if (descriptor) {
std::cout << "Name: " << descriptor->name << "\n";
std::cout << "Size: " << descriptor->entity_count << "\n";
}
// Observe changes (for UI updates)
manager.getGroupObservers().addObserver([]() {
// Refresh UI when groups change
});
manager.notifyGroupsChanged(); // Call after bulk updatesThread Safety: EntityGroupManager is not thread-safe. Callers must synchronize access when using from multiple threads.
Lineage Subsystem
The Lineage subsystem tracks data provenance—how derived data relates to source data. This enables features like:
- Tracing computed values back to original entities
- Invalidating derived data when sources change
- Visualizing data relationships in the UI
- Remembering filesystem provenance for loaded source data
Container Classification
Not all container types carry EntityIds. The table below summarises which containers can have their own identity and which can record parent lineage:
| Container Type | Has Own EntityIds | Can Have Parent Lineage | Notes |
|---|---|---|---|
MaskData |
✅ Yes | ✅ Yes | Ragged, entity-bearing |
LineData |
✅ Yes | ✅ Yes | Ragged, entity-bearing |
PointData |
✅ Yes | ✅ Yes | Ragged, entity-bearing |
DigitalEventSeries |
✅ Yes | ✅ Yes | Dense, entity-bearing |
DigitalIntervalSeries |
✅ Yes | ✅ Yes | Dense, entity-bearing |
AnalogTimeSeries |
❌ No | ✅ Yes | Dense, no entities |
TensorData |
❌ No | ✅ Yes | Dense, no entities |
MediaData |
❌ No | ❌ No | Special case |
Entity-bearing derived containers hold both their own EntityIds and parent lineage, which serve distinct purposes:
- Own EntityId: answers “what is this element’s identity?” — used for grouping, selection, and element-specific operations.
- Parent lineage: answers “where did this element come from?” — used for provenance, data-flow visualisation, and tracing.
// Example: LineData created by skeletonizing MaskData
// MaskData "masks" — Time T0: Mask (EntityId=100)
// LineData "skeleton_lines" — Time T0: Line (EntityId=200)
//
// skeleton_lines.getEntityIdsAtTime(T0) → [200] (line's own identity)
// resolver.resolveToSource("skeleton_lines", T0) → [100] (originating mask)
Lineage Types
Located in Entity/Lineage/LineageTypes.hpp, defines 8 lineage strategies as a std::variant:
| Type | Description | Use Case |
|---|---|---|
Source |
Root data with no parent | Raw loaded data |
OneToOneByTime |
1:1 mapping at each time point | MaskData → Area values |
AllToOneByTime |
N:1 aggregation at each time | Sum of all areas at time T |
SubsetLineage |
Filtered subset of source | Excluded/selected entities |
MultiSourceLineage |
Multiple sources combined | Merged datasets |
ExplicitLineage |
Manual per-element mapping | Custom transformations |
EntityMappedLineage |
EntityId → EntityId mapping | Persistent entity relationships |
ImplicitEntityMapping |
Cardinality-based inference | Broadcast/reduce operations |
#include "Entity/Lineage/LineageTypes.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
// One-to-one relationship: derived[T, i] ← source[T, i]
OneToOneByTime lineage{"source_masks"};
// Aggregation: derived[T] ← ALL source[T, *]
AllToOneByTime agg_lineage{"mask_areas"};
// Subset with specific entities
SubsetLineage subset;
subset.source_key = "masks";
subset.included_entities = {EntityId(100), EntityId(102)};
// Entity-to-entity mapping for entity-bearing derived containers
EntityMappedLineage mapped;
mapped.source_key = "masks";
mapped.entity_mapping = {
{EntityId(200), {EntityId(100)}}, // Line 200 from Mask 100
{EntityId(201), {EntityId(100), EntityId(101)}} // Line 201 from Masks 100 & 101
};
// Type-erased descriptor for storage
Descriptor desc = lineage;
// Query helpers
bool is_source = isSource(desc); // false
auto keys = getSourceKeys(desc); // {"source_masks"}
std::string name = getLineageTypeName(desc); // "OneToOneByTime"LineageRegistry
Stores lineage metadata for data containers with staleness tracking:
#include "Entity/Lineage/LineageRegistry.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
LineageRegistry registry;
// Register source data (no parent)
registry.setLineage("masks", Source{});
// Register derived data chain
registry.setLineage("mask_areas", OneToOneByTime{"masks"});
registry.setLineage("total_area", AllToOneByTime{"mask_areas"});
// Query lineage
if (registry.hasLineage("mask_areas")) {
auto lineage = registry.getLineage("mask_areas");
// Use std::visit to dispatch on lineage type
}
// Get full chain from derived to root
auto chain = registry.getLineageChain("total_area");
// Returns: ["total_area", "mask_areas", "masks"]
// Find dependents (reverse lookup)
auto dependents = registry.getDependentKeys("masks");
// Returns: ["mask_areas"]
// Check if source
bool is_src = registry.isSource("masks"); // true
// Staleness tracking for cache invalidation
registry.markStale("mask_areas");
bool stale = registry.isStale("mask_areas"); // true
registry.propagateStale("masks"); // Marks masks and all dependents stale
registry.markValid("mask_areas"); // After recomputationLineageEntry can also carry optional FileOrigin metadata for source data loaded from disk. This metadata is not used by LineageResolver; it records where a source key entered the session so save workflows can default back to the original file when the output format matches.
FileOrigin origin{
.m_path = "/data/session/points.csv",
.m_format = "csv",
.m_data_type = "PointData"
};
registry.setLineageWithFileOrigin("points", Source{}, origin);
auto loaded_from = registry.getFileOrigin("points");Thread Safety: LineageRegistry is not thread-safe. Callers must synchronize access.
LineageResolver
Resolves lineage to find source EntityIds. Uses the abstract IEntityDataSource interface to decouple from specific data storage implementations:
#include "Entity/Lineage/LineageResolver.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
// IEntityDataSource implementation provides data access
// (e.g., DataManagerEntityDataSource in DataManager library)
MyDataSource data_source;
LineageRegistry registry;
// Resolver takes non-owning pointers (caller must ensure lifetime)
LineageResolver resolver(&data_source, ®istry);
// Resolve single step: derived → immediate source EntityIds
auto source_ids = resolver.resolveToSource("mask_areas", TimeFrameIndex(10), 0);
// Resolve full chain: derived → root source(s)
// Handles multi-level derivations like: masks → areas → peaks
auto root_ids = resolver.resolveToRoot("total_area", TimeFrameIndex(10));
// For EntityMappedLineage: resolve by derived EntityId
auto parent_ids = resolver.resolveByEntityId("derived_lines", EntityId(200));
// Query helpers
bool has_lin = resolver.hasLineage("mask_areas"); // true
bool is_src = resolver.isSource("masks"); // true
auto chain = resolver.getLineageChain("total_area");
auto all_sources = resolver.getAllSourceEntities("mask_areas");Resolution Semantics by Lineage Type:
| Lineage Type | resolveToSource() Returns |
|---|---|
Source |
EntityIds from the container itself |
OneToOneByTime |
EntityId at same (time, index) in source |
AllToOneByTime |
All EntityIds at that time in source |
SubsetLineage |
Filtered EntityIds from source |
EntityMappedLineage |
Use resolveByEntityId() instead |
IEntityDataSource Interface
Abstract interface for data source access, enabling lineage resolution without DataManager dependency:
class IEntityDataSource {
public:
virtual ~IEntityDataSource() = default;
// Get EntityId at specific time and index
[[nodiscard]] virtual std::vector<EntityId> getEntityIds(
std::string const& data_key,
TimeFrameIndex time,
std::size_t local_index) const = 0;
// Get all EntityIds at a time point
[[nodiscard]] virtual std::vector<EntityId> getAllEntityIdsAtTime(
std::string const& data_key,
TimeFrameIndex time) const = 0;
// Get all EntityIds across all times
[[nodiscard]] virtual std::unordered_set<EntityId> getAllEntityIds(
std::string const& data_key) const = 0;
// Get element count at time
[[nodiscard]] virtual std::size_t getElementCount(
std::string const& data_key,
TimeFrameIndex time) const = 0;
};Integration with DataManager
Three concrete components in DataManager/Lineage/ bridge the abstract Entity/Lineage system to the DataManager storage layer. None of them are part of the Entity library itself; they live in the DataManager library and depend on it.
DataManagerEntityDataSource
DataManagerEntityDataSource (in DataManager/Lineage/DataManagerEntityDataSource.hpp) implements IEntityDataSource by dispatching on the container’s runtime type. All DataManager-specific type knowledge is encapsulated here, keeping LineageResolver free of DataManager dependencies.
Supported container types: MaskData, LineData, PointData, DigitalEventSeries, DigitalIntervalSeries, AnalogTimeSeries (RaggedAnalog backend), and TensorData.
#include "DataManager.hpp"
#include "Lineage/DataManagerEntityDataSource.hpp"
DataManager dm;
WhiskerToolbox::Lineage::DataManagerEntityDataSource data_source(&dm);
// Use directly with LineageResolver when you don't need the EntityResolver wrapper
auto* registry = dm.getLineageRegistry();
WhiskerToolbox::Entity::Lineage::LineageResolver resolver(&data_source, registry);
auto ids = resolver.resolveToSource("mask_areas", TimeFrameIndex(10));DataManagerEntityDataSource is non-copyable and non-movable. The DataManager pointer it holds is non-owning; callers must ensure the DataManager outlives the data source.
EntityResolver
EntityResolver (in DataManager/Lineage/EntityResolver.hpp) is a high-level convenience wrapper that composes DataManagerEntityDataSource and LineageResolver internally. It exposes the same resolution API as LineageResolver without requiring callers to manage intermediate objects.
#include "DataManager.hpp"
#include "Lineage/EntityResolver.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
DataManager dm;
EntityResolver resolver(&dm);
// Single-step resolution: derived → immediate source EntityIds
auto ids = resolver.resolveToSource("mask_areas", TimeFrameIndex(5));
// Full-chain resolution: derived → root source(s)
// Handles multi-level chains: MaskData → areas → peaks
auto root_ids = resolver.resolveToRoot("peaks", TimeFrameIndex(5));
// Entity-bearing derived containers: resolve by EntityId
auto parent_ids = resolver.resolveByEntityId("skeleton_lines", EntityId(200));
auto root_entity_ids = resolver.resolveByEntityIdToRoot("skeleton_lines", EntityId(200));
// Bulk queries
auto all_sources = resolver.getAllSourceEntities("mask_areas");
std::vector<std::string> chain = resolver.getLineageChain("peaks");
// chain: ["peaks", "mask_areas", "masks"]
// Metadata queries
bool has_lin = resolver.hasLineage("mask_areas"); // true
bool is_src = resolver.isSource("masks"); // trueEntityResolver is the preferred entry point for lineage resolution in code that already holds a DataManager*.
LineageRecorder
LineageRecorder (in DataManager/Lineage/LineageRecorder.hpp) is a static-method helper that bridges the transform-centric TransformLineageType enum (declared in TransformsV2) to the storage-centric Lineage::Descriptor. It is used after executing a v2 transform pipeline to record what lineage relationship was created.
#include "DataManager.hpp"
#include "Entity/Lineage/LineageRegistry.hpp"
#include "Lineage/LineageRecorder.hpp"
#include "TransformsV2/extension/TransformTypes.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
using namespace WhiskerToolbox::Transforms::V2;
// After executing a transform and storing the result:
LineageRecorder::record(
*dm->getLineageRegistry(),
"mask_areas", // output key
"masks", // input key
TransformLineageType::OneToOneByTime
);
// For multi-input transforms (e.g., LineMinPointDistance):
LineageRecorder::recordMultiInput(
*dm->getLineageRegistry(),
"line_distances",
{"lines", "points"},
TransformLineageType::OneToOneByTime
);
// For original/loaded data:
LineageRecorder::recordSource(*dm->getLineageRegistry(), "masks");
// For source data loaded from disk:
LineageRecorder::recordFileSource(*dm->getLineageRegistry(), "masks", origin);Every v2 transform registered in TransformsV2/core/RegisteredTransforms.cpp carries a lineage_type field in its TransformMetadata. Callers can query this field and pass it directly to LineageRecorder::record() to avoid hard-coding the lineage type at call sites.
The separation allows the Entity library to be tested and used without DataManager dependency.
Dependencies
The Entity library has minimal dependencies:
- TimeFrame: For
TimeFrameIndextype - Observer: For
EntityGroupManagerchange notifications
graph LR
Observer["Observer<br/>(no deps)"]
TimeFrame["TimeFrame<br/>(no deps)"]
Entity["Entity"]
Observer --> Entity
TimeFrame --> Entity
Thread Safety Summary
| Component | Thread Safety | Notes |
|---|---|---|
EntityRegistry |
✅ Thread-safe | Uses internal mutex |
EntityGroupManager |
❌ Not thread-safe | Caller must synchronize |
LineageRegistry |
❌ Not thread-safe | Caller must synchronize |
LineageResolver |
✅ Thread-safe* | *If data source is thread-safe |
DataManagerEntityDataSource |
❌ Not thread-safe | Shares DataManager’s thread-safety constraints |
EntityResolver |
❌ Not thread-safe | Inherits DataManager constraints |
Testing
Unit tests are co-located with source files in src/Entity/:
EntityRegistry.test.cpp- ID allocation and lookupEntityGroupManager.test.cpp- Group CRUD and queriesLineage/LineageRegistry.test.cpp- Lineage storage and stalenessLineage/LineageResolver.test.cpp- Resolution with mock data source (40+ test cases)
DataManager-layer unit tests are co-located in src/DataManager/Lineage/:
EntityResolver.test.cpp- Resolution strategies with real DataManagerDataManagerEntityDataSource.test.cpp- Type dispatch across all supported container types (200+ tests)
Integration tests live in tests/DataManager/Lineage/:
test_transform_lineage_integration.test.cpp- Full pipeline tests (700+ lines): MaskData → MaskArea → SumReduction → EntityResolvertest_lineage_recorder.test.cpp- LineageRecorder mapping from TransformLineageType to descriptors
Run entity tests:
ctest --preset linux-clang-release -R EntityRun all lineage-related tests:
ctest --preset linux-clang-release -R "[Ll]ineage"Migration Guide
From DataManager/Lineage to Entity/Lineage
If you have code using the old locations (pre-January 2026):
// OLD (no longer available)
#include "DataManager/Lineage/LineageTypes.hpp"
#include "DataManager/Lineage/LineageRegistry.hpp"
using namespace WhiskerToolbox::Lineage;
// NEW
#include "Entity/Lineage/LineageTypes.hpp"
#include "Entity/Lineage/LineageRegistry.hpp"
using namespace WhiskerToolbox::Entity::Lineage;Key API Changes
| Old | New |
|---|---|
WhiskerToolbox::Lineage namespace |
WhiskerToolbox::Entity::Lineage |
| Lineage types in DataManager | Lineage types in Entity |
| Direct DataManager coupling | Abstract IEntityDataSource interface |
EntityResolver Backward Compatibility
The EntityResolver class in DataManager/Lineage/ maintains its public API. Existing code using EntityResolver with DataManager should continue to work without changes.
Example: Custom Data Source
To use lineage resolution with a custom data backend, implement IEntityDataSource:
#include "Entity/Lineage/LineageResolver.hpp"
using namespace WhiskerToolbox::Entity::Lineage;
class MyCustomDataSource : public IEntityDataSource {
public:
std::vector<EntityId> getEntityIds(
std::string const& data_key,
TimeFrameIndex time,
std::size_t local_index) const override
{
// Return EntityId at specific position
// Return empty vector if not found
auto it = _data.find({data_key, time.getValue()});
if (it == _data.end() || local_index >= it->second.size()) {
return {};
}
return {it->second[local_index]};
}
std::vector<EntityId> getAllEntityIdsAtTime(
std::string const& data_key,
TimeFrameIndex time) const override
{
auto it = _data.find({data_key, time.getValue()});
if (it == _data.end()) return {};
return it->second;
}
std::unordered_set<EntityId> getAllEntityIds(
std::string const& data_key) const override
{
std::unordered_set<EntityId> result;
for (auto const& [key, ids] : _data) {
if (key.first == data_key) {
result.insert(ids.begin(), ids.end());
}
}
return result;
}
std::size_t getElementCount(
std::string const& data_key,
TimeFrameIndex time) const override
{
auto it = _data.find({data_key, time.getValue()});
return it != _data.end() ? it->second.size() : 0;
}
private:
// Example storage: (data_key, time) → vector of EntityIds
std::map<std::pair<std::string, int64_t>, std::vector<EntityId>> _data;
};
// Use with LineageResolver
MyCustomDataSource data_source;
LineageRegistry registry;
LineageResolver resolver(&data_source, ®istry);
// Now resolution works with your custom backend
auto ids = resolver.resolveToSource("derived", TimeFrameIndex(10));Performance Considerations
- EntityRegistry: O(1) lookup and insertion via hash maps
- EntityGroupManager: O(1) for membership queries; O(n) for batch operations
- LineageRegistry: O(1) for single-key queries; O(n) for chain traversal
- LineageResolver: Resolution cost depends on lineage depth and data source implementation;
resolveAllToOneToRootis O(n × depth) for n elements at a time point
See Also
- Transform Pipeline - Data transformation system
- DataManager - Central data storage