Skip to main content

src/DataObjects/DigitalTimeSeries/Digital_Interval_Series.hpp

src/DataObjects/DigitalTimeSeries/Digital_Interval_Series.hpp

DigitalIntervalSeries class for managing time interval data with entity tracking. More…

Classes

Name
class DigitalIntervalSeries
A sorted collection of time intervals with entity tracking.
struct DigitalIntervalSeries::DataTraits

Types

Name
enum class IntervalLayout { Disjoint, Overlapping}
Controls whether intervals in a series may overlap in time.

Functions

Name
int find_closest_preceding_event(DigitalIntervalSeries * digital_series, TimeFrameIndex time)

Attributes

Name
bool always_false_v

Detailed Description

DigitalIntervalSeries class for managing time interval data with entity tracking.

This file provides the DigitalIntervalSeries class, which represents a sorted collection of time intervals, where each interval is defined by a start and end TimeFrameIndex (indices into an accompanying TimeFrame) and an EntityId (a unique identifier).

Storage Backends

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

Owning Storage (DigitalIntervalStorageType::Owning)

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

View Storage (DigitalIntervalStorageType::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 will materialize to owning storage first
  • Returns valid cache if view indices are contiguous

Lazy Storage (DigitalIntervalStorageType::Lazy)

  • On-demand computation from transform views
  • Created via createFromView() template method
  • Stores a C++20 ranges view that computes interval elements on access
  • Useful for transform pipelines without materializing intermediate results
  • Read-only: mutation operations will materialize to owning storage first
  • Always returns invalid cache (forces virtual dispatch)

TimeFrame Integration

Each interval’s start/end 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 interval can have an associated EntityId for tracking across the application. When setIdentityContext() is called with an EntityRegistry, new intervals are automatically assigned unique EntityIds. This enables:

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

DigitalIntervalStorage.hpp for storage implementation details

ClockTicksIntervalWithId for the element type returned by view()

IntervalWithId for index-based lazy-pipeline element type

TimeFrame for time base management

EntityRegistry for entity ID management

Types Documentation

enum IntervalLayout

Enumerator Value Description
Disjoint Non-overlapping intervals; addEvent merges on insert.
Overlapping Overlapping intervals allowed; addEvent does not merge.

Controls whether intervals in a series may overlap in time.

  • Disjoint: intervals are merged on insert via addEvent(); suitable for user annotations.
  • Overlapping: intervals are inserted without merging; suitable for transform intermediates.

Layout is fixed at construction and exposed via layout() only (no setter).

Range-query behavior in storage backends depends on layout; see OwningDigitalIntervalStorage::assumeDisjointIntervals(), ViewDigitalIntervalStorage::filterByOverlappingRange(), and LazyDigitalIntervalStorage::getOverlappingRangeImpl().

Functions Documentation

function find_closest_preceding_event

int find_closest_preceding_event(
    DigitalIntervalSeries * digital_series,
    TimeFrameIndex time
)

Attributes Documentation

variable always_false_v

bool always_false_v = false;

Source code

#ifndef DIGITAL_INTERVAL_SERIES_HPP
#define DIGITAL_INTERVAL_SERIES_HPP


#include "DigitalTimeSeries/IntervalWithId.hpp"// IntervalWithId struct for element access
#include "Entity/EntityTypes.hpp"              // EntityId
#include "Observer/Observer_Data.hpp"          // ObserverData base class
#include "TimeFrame/TimeFrame.hpp"             // TimeFrame and TimeFrameIndex
#include "TimeFrame/interval_data.hpp"         // Interval struct
#include "TypeTraits/DataTypeTraits.hpp"
#include "storage/DigitalIntervalStorage.hpp"

#include <cassert>
#include <cstdint>
#include <memory>       // std::shared_ptr
#include <optional>     // std::optional
#include <ranges>       // std::ranges::views
#include <unordered_set>// std::unordered_set
#include <utility>      // std::pair
#include <vector>       // std::vector


class EntityRegistry;
template<typename T>
inline constexpr bool always_false_v = false;

enum class IntervalLayout {
    Disjoint,   
    Overlapping,
};

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

    // ========== Constructors ==========
    DigitalIntervalSeries() = default;

    explicit DigitalIntervalSeries(std::vector<TimeFrameInterval> digital_vector);

    explicit DigitalIntervalSeries(std::vector<std::pair<float, float>> const & digital_vector);

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

    [[nodiscard]] auto view() const {
        assert(_time_frame != nullptr && "view() requires series time frame");
        TimeFrame const * time_frame = _time_frame.get();
        return std::views::iota(size_t{0}, size()) | std::views::transform([this, time_frame](size_t idx) {
                   return ClockTicksIntervalWithId(
                           toClockTicksInterval(_storage.getInterval(idx), *time_frame),
                           _storage.getEntityId(idx));
               });
    }

    [[nodiscard]] TimeFrameInterval getStoredInterval(size_t index) const {
        return _storage.getInterval(index);
    }

    [[nodiscard]] auto viewInRange(TimeFrameIndex start_index,
                                   TimeFrameIndex stop_index,
                                   TimeFrame const & source_time_frame) const {
        assert(_time_frame != nullptr && "viewInRange requires series time frame");
        auto const time_range = _getConvertedTimeRange(start_index, stop_index, source_time_frame);
        TimeFrame const * time_frame = _time_frame.get();
        auto const [lo, hi] = _storage.getOverlappingRange(time_range.first, time_range.second);
        return std::views::iota(lo, hi) |
               std::views::transform([this, time_frame](size_t idx) {
                   return ClockTicksIntervalWithId(
                           toClockTicksInterval(_storage.getInterval(idx), *time_frame),
                           _storage.getEntityId(idx));
               });
    }

    [[nodiscard]] auto viewIntervalsInRange(TimeFrameIndex start_index,
                                            TimeFrameIndex stop_index,
                                            TimeFrame const & source_time_frame) const {
        assert(_time_frame != nullptr && "viewIntervalsInRange requires series time frame");
        auto const time_range = _getConvertedTimeRange(start_index, stop_index, source_time_frame);
        TimeFrame const * time_frame = _time_frame.get();
        auto const [lo, hi] = _storage.getOverlappingRange(time_range.first, time_range.second);
        return std::views::iota(lo, hi) |
               std::views::transform([this, time_frame](size_t idx) {
                   return toClockTicksInterval(_storage.getInterval(idx), *time_frame);
               });
    }

    [[nodiscard]] bool hasIntervalAtTime(TimeFrameIndex time, TimeFrame const & source_time_frame) const {
        auto converted_time = _getConvertedTime(time, source_time_frame);
        return _hasIntervalAtTime(converted_time);
    }

    // ========== Setters ==========

    void addEvent(TimeFrameInterval new_interval);

    void addEvent(TimeFrameIndex start, TimeFrameIndex end);

    void setEventAtTime(TimeFrameIndex time, bool event);

    bool removeInterval(TimeFrameInterval const & interval);

    size_t removeIntervals(std::vector<TimeFrameInterval> const & intervals);

    template<typename T, typename B>
    void setEventsAtTimes(std::vector<T> times, std::vector<B> events) {
        for (size_t i = 0; i < times.size(); ++i) {
            _setEventAtTimeInternal(TimeFrameIndex(times[i]), events[i]);
        }
        _cacheOptimizationPointers();
        notifyObservers();
    }

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

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

    // NOTE: moveByEntityIds is intentionally NOT implemented for DigitalIntervalSeries.
    //
    // Moving intervals between series has unresolved edge cases due to interval merging:
    //   - Disjoint-layout series merge overlapping intervals on insert.
    //   - If a moved interval overlaps with an existing interval in the target, the two
    //     will be merged into a single new interval.
    //   - The original EntityId of the moved interval is lost during merging, but any
    //     group memberships tied to that EntityId are NOT automatically cleaned up.
    //   - The merged interval in the target gets a new EntityId that is not associated
    //     with any group, leaving group state inconsistent.
    //   - Similarly, removing the source interval may orphan group references.
    //
    // A proper implementation would need to define merging semantics for EntityIds and
    // group memberships. Until those semantics are decided, move operations should be
    // done manually at the UI level where the user can handle conflicts.

    // ========== Getters ==========

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

    [[nodiscard]] IntervalLayout layout() const noexcept { return _layout; }

    // ========== Range-Mode Interval Queries ==========

    enum class RangeMode {
        CONTAINED,  
        OVERLAPPING,
        CLIP        
    };

    template<RangeMode mode = RangeMode::CONTAINED>
    auto getIntervalsInRange(
            TimeFrameIndex start_time,
            TimeFrameIndex stop_time,
            TimeFrame const & source_timeframe) const {
        assert(_time_frame != nullptr && "getIntervalsInRange requires series time frame");

        TimeFrameIndex query_start = start_time;
        TimeFrameIndex query_stop = stop_time;
        if (&source_timeframe != _time_frame.get()) {
            auto converted = convertTimeFrameRange(start_time,
                                                   stop_time,
                                                   source_timeframe,
                                                   *_time_frame);
            query_start = converted.first;
            query_stop = converted.second;
        }

        if constexpr (mode == RangeMode::CLIP) {
            return _getClockTicksIntervalsClipped(query_start, query_stop);
        } else {
            return _getIntervalsInRangeLazy<mode>(query_start, query_stop);
        }
    }

    // ========== 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();

    // ========== Entity Lookup Methods ==========

    [[nodiscard]] std::optional<ClockTicksInterval> getIntervalByEntityId(EntityId entity_id) const;

    [[nodiscard]] std::vector<std::pair<EntityId, ClockTicksInterval>> getIntervalsByEntityIds(std::vector<EntityId> const & entity_ids) const;

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

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

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

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

    // ========== Factory Methods ==========

    [[nodiscard]] static std::shared_ptr<DigitalIntervalSeries> createOverlapping(
            std::vector<TimeFrameInterval> intervals,
            std::shared_ptr<TimeFrame> time_frame = nullptr);

    [[nodiscard]] static std::shared_ptr<DigitalIntervalSeries> createView(
            std::shared_ptr<DigitalIntervalSeries const> const & source,
            TimeFrameIndex start,
            TimeFrameIndex end);

    [[nodiscard]] static std::shared_ptr<DigitalIntervalSeries> createView(
            std::shared_ptr<DigitalIntervalSeries const> const & source,
            std::unordered_set<EntityId> const & entity_ids);

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

    template<typename ViewType>
    [[nodiscard]] static std::shared_ptr<DigitalIntervalSeries> createFromView(
            ViewType view,
            size_t num_elements,
            std::shared_ptr<TimeFrame> time_frame = nullptr,
            IntervalLayout layout = IntervalLayout::Overlapping);

    [[nodiscard]] DigitalIntervalStorageCache getStorageCache() const { return _storage.tryGetCache(); }

private:
    DigitalIntervalStorageWrapper _storage;
    DigitalIntervalStorageCache _cached_storage;// Fast-path cache
    std::shared_ptr<TimeFrame> _time_frame{nullptr};
    IntervalLayout _layout{IntervalLayout::Disjoint};

    // Cache management
    void _cacheOptimizationPointers();

    void _syncStorageDisjointHint();

    std::optional<TimeFrameInterval> _addEventInternal(TimeFrameInterval new_interval);
    void _setEventAtTimeInternal(TimeFrameIndex time, bool event);
    void _removeEventAtTimeInternal(TimeFrameIndex time);

    template<RangeMode mode>
    auto _getIntervalsInRangeLazy(
            TimeFrameIndex start_time,
            TimeFrameIndex stop_time) const {
        static_assert(mode == RangeMode::CONTAINED || mode == RangeMode::OVERLAPPING,
                      "_getIntervalsInRangeLazy supports CONTAINED and OVERLAPPING only");

        TimeFrame const * time_frame = _time_frame.get();
        assert(time_frame != nullptr && "_getIntervalsInRangeLazy requires series time frame");

        auto const [lo, hi] = (mode == RangeMode::OVERLAPPING)
                                      ? _storage.getOverlappingRange(start_time, stop_time)
                                      : _storage.getContainedRange(start_time, stop_time);

        return std::views::iota(lo, hi) |
               std::views::transform([this, time_frame](size_t idx) {
                   return toClockTicksInterval(_storage.getInterval(idx), *time_frame);
               });
    }

    [[nodiscard]] std::vector<ClockTicksInterval> _getClockTicksIntervalsClipped(
            TimeFrameIndex start_time,
            TimeFrameIndex stop_time) const;

    // Helper method to handle clipping intervals at range boundaries
    std::vector<TimeFrameInterval> _getIntervalsAsVectorClipped(
            TimeFrameIndex start_time,
            TimeFrameIndex stop_time) const {

        std::vector<TimeFrameInterval> result;

        for (size_t i = 0; i < _storage.size(); ++i) {
            TimeFrameInterval const interval = _storage.getInterval(i);

            // Skip if not overlapping
            if (interval.end < start_time || interval.start > stop_time)
                continue;

            // Create a new clipped interval based on original interval values
            // but clipped at the transformed boundaries
            TimeFrameIndex clipped_start = interval.start;
            if (clipped_start < start_time) {
                // Binary search or interpolation to find the original value
                // that transforms to start_time would be ideal here
                // For now, use a simple approach:
                while (clipped_start < start_time && clipped_start < interval.end)
                    clipped_start++;
            }

            TimeFrameIndex clipped_end = interval.end;
            if (clipped_end > stop_time) {
                while (clipped_end > interval.start && clipped_end > stop_time)
                    clipped_end = clipped_end - TimeFrameIndex{1};
            }

            result.push_back(TimeFrameInterval{clipped_start, clipped_end});
        }

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

    [[nodiscard]] std::pair<ClockTicks, ClockTicks> _getTimeRangeFromIndices(
            TimeFrameIndex start_index,
            TimeFrameIndex stop_index) const;

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

    [[nodiscard]] std::pair<TimeFrameIndex, TimeFrameIndex> _getConvertedTimeRange(
            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 {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 {target_start, target_stop};
    }

    [[nodiscard]] TimeFrameIndex _getConvertedTime(
            TimeFrameIndex time_index,
            TimeFrame const & source_time_frame) const {
        if (&source_time_frame == _time_frame.get() || !_time_frame.get()) {
            return time_index;
        }
        // Convert using the same logic as range conversion
        auto [target, _] = convertTimeFrameRange(
                time_index, time_index, source_time_frame, *_time_frame);
        return target;
    }

    [[nodiscard]] bool _hasIntervalAtTime(TimeFrameIndex time) const {
        for (size_t i = 0; i < _storage.size(); ++i) {
            TimeFrameInterval const & interval = _storage.getInterval(i);
            if (interval.start <= time && time <= interval.end) {
                return true;
            }
        }
        return false;
    }
};

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

template<typename ViewType>
std::shared_ptr<DigitalIntervalSeries> DigitalIntervalSeries::createFromView(
        ViewType view,
        size_t num_elements,
        std::shared_ptr<TimeFrame> time_frame,
        IntervalLayout layout) {
    auto result = std::make_shared<DigitalIntervalSeries>();
    result->_layout = layout;
    result->_time_frame = time_frame;
    result->_storage = DigitalIntervalStorageWrapper{
            LazyDigitalIntervalStorage<ViewType>{std::move(view), num_elements, time_frame}};
    result->_cacheOptimizationPointers();
    return result;
}

int find_closest_preceding_event(DigitalIntervalSeries * digital_series, TimeFrameIndex time);

#endif// DIGITAL_INTERVAL_SERIES_HPP

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