Skip to main content

src/DataObjects/DigitalTimeSeries/Digital_Event_Series.hpp

src/DataObjects/DigitalTimeSeries/Digital_Event_Series.hpp

DigitalEventSeries class for managing time-stamped discrete events. More…

Classes

Name
class DigitalEventSeries
A sorted collection of discrete time events with entity tracking.
struct DigitalEventSeries::DataTraits

Detailed Description

DigitalEventSeries class for managing time-stamped discrete events.

This file provides the DigitalEventSeries class, which represents a sorted collection of discrete events, where each event is defined by a TimeFrameIndex (an index into an accompanying TimeFrame) and an EntityId (a unique identifier for the event).

Storage Backends

DigitalEventSeries supports three storage backends via a type-erased wrapper:

Owning Storage (DigitalEventStorageType::Owning)

  • Default storage type for newly created series
  • Owns event data in Structure-of-Arrays (SoA) layout for cache efficiency
  • Supports all mutation operations (addEvent, removeEvent, clear)
  • Events are always maintained in sorted order by time
  • O(log n) lookups by time, O(1) lookups by EntityId via hash map

View Storage (DigitalEventStorageType::View)

  • Zero-copy filtered view of another series
  • Created via createView() factory methods
  • References source data via index vector; no data copying
  • Supports filtering by time range or EntityId set
  • Read-only: mutation operations throw std::runtime_error
  • Returns valid cache if view indices are contiguous

Lazy Storage (DigitalEventStorageType::Lazy)

  • On-demand computation from transform views
  • Created via createFromView() template method
  • Stores a C++20 ranges view that computes EventWithId on access
  • Useful for transform pipelines without materializing intermediate results
  • Read-only: mutation operations throw std::runtime_error
  • Always returns invalid cache (forces virtual dispatch)

TimeFrame Integration

Each event’s time is stored as a TimeFrameIndex, which is an index into the series’ associated TimeFrame. This enables:

  • Different data sources to use different sampling rates
  • Automatic time conversion when querying across timeframes
  • Efficient range queries using binary search on indices

Entity System Integration

Each event can have an associated EntityId for tracking across the application. When setIdentityContext() is called with an EntityRegistry, new events are automatically assigned unique EntityIds. This enables:

  • Linking events to analysis results
  • Group-based selection and filtering
  • Cross-data-type entity tracking

DigitalEventStorage.hpp for storage implementation details

ClockTicksWithId for the element type returned by view()

TimeFrame for time base management

EntityRegistry for entity ID management

Source code

#ifndef BEHAVIORTOOLBOX_DIGITAL_EVENT_SERIES_HPP
#define BEHAVIORTOOLBOX_DIGITAL_EVENT_SERIES_HPP


#include "DigitalTimeSeries/EventWithId.hpp"
#include "Entity/EntityTypes.hpp"
#include "Observer/Observer_Data.hpp"
#include "TimeFrame/ClockTicks.hpp"
#include "TimeFrame/TimeFrame.hpp"
#include "TypeTraits/DataTypeTraits.hpp"
#include "storage/DigitalEventStorage.hpp"

#include <cassert>
#include <compare>
#include <memory>
#include <ranges>
#include <stdexcept>
#include <unordered_set>
#include <utility>
#include <vector>

class EntityRegistry;


class DigitalEventSeries : public ObserverData {
public:
    struct DataTraits : Neuralyzer::TypeTraits::DataTypeTraitsBase<DigitalEventSeries, ClockTicks> {
        static constexpr bool is_ragged = false;
        static constexpr bool is_temporal = true;
        static constexpr bool has_entity_ids = true;
    };

    DigitalEventSeries();

    explicit DigitalEventSeries(std::vector<TimeFrameIndex> event_vector);

    // =============================================================
    // ==================== RANGES INTERFACE =======================
    // =============================================================

    [[nodiscard]] auto view() const {
        return std::views::iota(size_t{0}, size()) | std::views::transform([this](size_t idx) -> ClockTicksWithId {
                   if (storesRelativeTimes()) {
                       if (_cached_storage.isValid() &&
                           _cached_storage.time_domain == DigitalEventTimeDomain::RelativeClockTicks) {
                           return ClockTicksWithId(
                                   _cached_storage.getRelativeEvent(idx),
                                   _cached_storage.getEntityId(idx));
                       }
                       return ClockTicksWithId(
                               _storage.getRelativeEvent(idx),
                               _storage.getEntityId(idx));
                   }

                   TimeFrame const * time_frame = _time_frame.get();
                   assert(time_frame != nullptr && "view() requires series time frame");
                   if (_cached_storage.isValid() &&
                       _cached_storage.time_domain == DigitalEventTimeDomain::TimeFrameIndex) {
                       return ClockTicksWithId(
                               time_frame->getTimeAtIndex(_cached_storage.getEvent(idx)),
                               _cached_storage.getEntityId(idx));
                   }
                   return ClockTicksWithId(
                           time_frame->getTimeAtIndex(_storage.getEvent(idx)),
                           _storage.getEntityId(idx));
               });
    }

    [[nodiscard]] TimeFrameIndex getStoredEvent(size_t index) const {
        if (storesRelativeTimes()) {
            throw std::runtime_error(
                    "getStoredEvent() is not valid for relative-time series; use getStoredRelativeEvent()");
        }
        return _storage.getEvent(index);
    }

    [[nodiscard]] ClockTicks getStoredRelativeEvent(size_t index) const {
        return _storage.getRelativeEvent(index);
    }

    [[nodiscard]] EntityId getStoredEntityId(size_t index) const {
        return _storage.getEntityId(index);
    }

    void addEvent(TimeFrameIndex event_time);

    bool removeEvent(TimeFrameIndex event_time);

    [[nodiscard]] size_t size() const { return _storage.size(); }

    void addEvent(TimeFrameIndex event_time, EntityId entity_id, NotifyObservers notify);

    void clear();

    // ========== Entity-Based Bulk Operations ==========

    std::size_t moveByEntityIds(DigitalEventSeries & target,
                                std::unordered_set<EntityId> const & entity_ids,
                                NotifyObservers notify);

    std::size_t copyByEntityIds(DigitalEventSeries & target,
                                std::unordered_set<EntityId> const & entity_ids,
                                NotifyObservers notify);

    std::size_t deleteByEntityIds(std::unordered_set<EntityId> const & entity_ids,
                                  NotifyObservers notify);

    // ========== Range Queries (Public - Require TimeFrame) ==========

    [[nodiscard]] auto viewInRange(TimeFrameIndex start_index,
                                   TimeFrameIndex stop_index,
                                   TimeFrame const & source_time_frame) const {
        if (storesRelativeTimes()) {
            throw std::runtime_error(
                    "viewInRange() requires absolute-time series; use viewInRelativeRange()");
        }
        assert(_time_frame != nullptr && "viewInRange requires series time frame");
        auto [start_idx, end_idx] = _getTimeRangeIndices(start_index, stop_index, source_time_frame);
        TimeFrame const * time_frame = _time_frame.get();
        return std::views::iota(start_idx, end_idx) | std::views::transform([this, time_frame](size_t idx) {
                   return ClockTicksWithId(
                           time_frame->getTimeAtIndex(_storage.getEvent(idx)),
                           _storage.getEntityId(idx));
               });
    }

    [[nodiscard]] auto viewInRelativeRange(ClockTicks start, ClockTicks end) const {
        auto [start_idx, end_idx] = _storage.getRelativeTimeRange(start, end);
        return std::views::iota(start_idx, end_idx) | std::views::transform([this](size_t idx) {
                   if (_cached_storage.isValid() &&
                       _cached_storage.time_domain == DigitalEventTimeDomain::RelativeClockTicks) {
                       return ClockTicksWithId(
                               _cached_storage.getRelativeEvent(idx),
                               _cached_storage.getEntityId(idx));
                   }
                   return ClockTicksWithId(
                           _storage.getRelativeEvent(idx),
                           _storage.getEntityId(idx));
               });
    }

    [[nodiscard]] auto viewTimesInRange(TimeFrameIndex start_index,
                                        TimeFrameIndex stop_index,
                                        TimeFrame const & source_time_frame) const {
        if (storesRelativeTimes()) {
            throw std::runtime_error(
                    "viewTimesInRange() requires absolute-time series; use viewInRelativeRange()");
        }
        assert(_time_frame != nullptr && "viewTimesInRange requires series time frame");
        auto [start_idx, end_idx] = _getTimeRangeIndices(start_index, stop_index, source_time_frame);
        TimeFrame const * time_frame = _time_frame.get();
        return std::views::iota(start_idx, end_idx) | std::views::transform([this, time_frame](size_t idx) {
                   return time_frame->getTimeAtIndex(_storage.getEvent(idx));
               });
    }

    // ========== Time Frame ==========

    void setTimeFrame(std::shared_ptr<TimeFrame> time_frame) { _time_frame = time_frame; }

    [[nodiscard]] std::shared_ptr<TimeFrame> getTimeFrame() const { return _time_frame; }

    // ========== Identity ==========

    void setIdentityContext(std::string const & data_key, EntityRegistry * registry) {
        _identity_data_key = data_key;
        _identity_registry = registry;
    }

    void rebuildAllEntityIds();

    // ========== Storage Type Queries ==========

    [[nodiscard]] bool isView() const { return _storage.isView(); }

    [[nodiscard]] bool isLazy() const { return _storage.isLazy(); }

    [[nodiscard]] bool storesRelativeTimes() const { return _storage.isRelative(); }

    [[nodiscard]] DigitalEventStorageType getStorageType() const { return _storage.getStorageType(); }

    // ========== View and Lazy Factory Methods ==========

    static std::shared_ptr<DigitalEventSeries> createFromRelativeClockTicks(
            std::vector<ClockTicks> events,
            std::vector<EntityId> entity_ids = {});

    static std::shared_ptr<DigitalEventSeries> createView(
            std::shared_ptr<DigitalEventSeries const> const & source,
            TimeFrameIndex start,
            TimeFrameIndex end);

    static std::shared_ptr<DigitalEventSeries> createView(
            std::shared_ptr<DigitalEventSeries const> const & source,
            std::unordered_set<EntityId> const & entity_ids);

    template<typename ViewType>
    static std::shared_ptr<DigitalEventSeries> createFromView(
            ViewType view,
            size_t num_elements,
            std::shared_ptr<TimeFrame> time_frame = nullptr);

    [[nodiscard]] std::shared_ptr<DigitalEventSeries> materialize() const;

private:
    DigitalEventStorageWrapper _storage;
    DigitalEventStorageCache _cached_storage;// Fast-path cache
    std::shared_ptr<TimeFrame> _time_frame{nullptr};

    // ========== Private Range Query Helpers ==========

    [[nodiscard]] std::pair<size_t, size_t> _getTimeRangeIndices(
            TimeFrameIndex start_index,
            TimeFrameIndex stop_index,
            TimeFrame const & source_time_frame) const {
        // Fast path: same time frame or no conversion needed
        if (&source_time_frame == _time_frame.get() || !_time_frame.get()) {
            return _storage.getTimeRange(start_index, stop_index);
        }
        // Convert to our time frame
        auto [target_start, target_stop] = convertTimeFrameRange(
                start_index, stop_index, source_time_frame, *_time_frame);
        return _storage.getTimeRange(target_start, target_stop);
    }

    // Cache management
    void _cacheOptimizationPointers();

    // Identity
    std::string _identity_data_key;
    EntityRegistry * _identity_registry{nullptr};
};

// =============================================================================
// Template Implementation
// =============================================================================

template<typename ViewType>
std::shared_ptr<DigitalEventSeries> DigitalEventSeries::createFromView(
        ViewType view,
        size_t num_elements,
        std::shared_ptr<TimeFrame> time_frame) {
    auto result = std::make_shared<DigitalEventSeries>();
    result->_storage = DigitalEventStorageWrapper{
            LazyDigitalEventStorage<ViewType>{std::move(view), num_elements}};
    result->_time_frame = std::move(time_frame);
    result->_cacheOptimizationPointers();
    return result;
}

#endif//BEHAVIORTOOLBOX_DIGITAL_EVENT_SERIES_HPP

Updated on 2026-11-13 at 20:25:43 +0000