Skip to main content

src/DataManager/utils/TableView/computers/IntervalOverlapComputer.h

src/DataManager/utils/TableView/computers/IntervalOverlapComputer.h

Classes

Name
class IntervalOverlapComputer
Templated computer for analyzing overlaps between row intervals and column intervals.

Types

Name
enum class std::uint8_t IntervalOverlapOperation { AssignID, CountOverlaps, AssignID_Start, AssignID_End}
Enumeration of operations that can be performed on interval overlaps.

Functions

Name
bool intervalsOverlap(TimeFrameInterval const & a, TimeFrameInterval const & b)
Checks if two intervals overlap.
bool intervalsOverlapInAbsoluteTime(TimeFrameInterval const & rowInterval, TimeFrameInterval const & columnInterval, TimeFrame const * sourceTimeFrame, TimeFrame const * destinationTimeFrame)
Helper function to check if a column interval overlaps with a row interval using absolute time coordinates.
int64_t findContainingInterval(TimeFrameInterval const & rowInterval, std::ranges::range auto & columnIntervals)
Finds the index of the column interval that contains the given row interval.
int64_t countOverlappingIntervals(TimeFrameInterval const & rowInterval, std::ranges::range auto && columnIntervals, TimeFrame const & destinationTimeFrame)
Counts the number of column intervals that overlap with the given row interval.
std::pair< int64_t, std::vector< EntityId > > countOverlappingIntervalsWithIds(TimeFrameInterval const & rowInterval, std::ranges::range auto && columnIntervalsWithIds, TimeFrame const & destinationTimeFrame)
Counts the number of column intervals that overlap with the given row interval and returns their EntityIDs.

Types Documentation

enum IntervalOverlapOperation

Enumerator Value Description
AssignID Assigns the index of the column interval that contains/overlaps with the row interval.
CountOverlaps Counts the number of column intervals that overlap with each row interval.
AssignID_Start Finds the start index of the column interval that contains/overlaps with the row interval.
AssignID_End Finds the end index of the column interval that contains/overlaps with the row interval.

Enumeration of operations that can be performed on interval overlaps.

Functions Documentation

function intervalsOverlap

bool intervalsOverlap(
    TimeFrameInterval const & a,
    TimeFrameInterval const & b
)

Checks if two intervals overlap.

Parameters:

  • a First interval.
  • b Second interval.

Return: True if intervals overlap, false otherwise.

function intervalsOverlapInAbsoluteTime

bool intervalsOverlapInAbsoluteTime(
    TimeFrameInterval const & rowInterval,
    TimeFrameInterval const & columnInterval,
    TimeFrame const * sourceTimeFrame,
    TimeFrame const * destinationTimeFrame
)

Helper function to check if a column interval overlaps with a row interval using absolute time coordinates.

Parameters:

  • rowInterval The row interval to check against.
  • columnInterval The column interval to check.
  • sourceTimeFrame The timeframe for the column interval.
  • destinationTimeFrame The timeframe for the row interval.

Return: True if intervals overlap, false otherwise.

function findContainingInterval

int64_t findContainingInterval(
    TimeFrameInterval const & rowInterval,
    std::ranges::range auto & columnIntervals
)

Finds the index of the column interval that contains the given row interval.

Parameters:

  • rowInterval The row interval to find a container for.
  • columnIntervals The column intervals to search through.

Return: Index of the containing column interval, or -1 if none found.

function countOverlappingIntervals

int64_t countOverlappingIntervals(
    TimeFrameInterval const & rowInterval,
    std::ranges::range auto && columnIntervals,
    TimeFrame const & destinationTimeFrame
)

Counts the number of column intervals that overlap with the given row interval.

Parameters:

  • rowInterval The row interval to check overlaps for.
  • columnIntervals Column intervals in absolute clock ticks.
  • destinationTimeFrame The timeframe for the row interval.

Return: Number of overlapping column intervals.

function countOverlappingIntervalsWithIds

std::pair< int64_t, std::vector< EntityId > > countOverlappingIntervalsWithIds(
    TimeFrameInterval const & rowInterval,
    std::ranges::range auto && columnIntervalsWithIds,
    TimeFrame const & destinationTimeFrame
)

Counts the number of column intervals that overlap with the given row interval and returns their EntityIDs.

Parameters:

  • rowInterval The row interval to check overlaps for.
  • columnIntervalsWithIds Column intervals with EntityIds in absolute clock ticks.
  • destinationTimeFrame The timeframe for the row interval.

Return: Pair of count and vector of EntityIDs of overlapping intervals.

Note: Takes range by forwarding reference because filter_view/transform_view cache begin() internally

Source code

#ifndef INTERVAL_OVERLAP_COMPUTER_H
#define INTERVAL_OVERLAP_COMPUTER_H

#include "DigitalTimeSeries/Digital_Interval_Series.hpp"
#include "utils/TableView/core/ExecutionPlan.h"
#include "utils/TableView/interfaces/IColumnComputer.h"

#include <cstdint>
#include <memory>
#include <string>
#include <vector>

enum class IntervalOverlapOperation : std::uint8_t {
    AssignID,      
    CountOverlaps, 
    AssignID_Start,
    AssignID_End   
};

[[nodiscard]] bool intervalsOverlap(TimeFrameInterval const & a, TimeFrameInterval const & b);

[[nodiscard]] bool intervalsOverlapInAbsoluteTime(TimeFrameInterval const & rowInterval,
                                                  TimeFrameInterval const & columnInterval,
                                                  TimeFrame const * sourceTimeFrame,
                                                  TimeFrame const * destinationTimeFrame);

[[nodiscard]] int64_t findContainingInterval(TimeFrameInterval const & rowInterval,
                                             std::ranges::range auto & columnIntervals) {
    for (size_t i = 0; i < columnIntervals.size(); ++i) {
        auto const & colInterval = columnIntervals[i];

        // Check if column interval contains the row interval
        // Column interval contains row interval if: colInterval.start <= rowInterval.start && rowInterval.end <= colInterval.end
        if (colInterval.start <= rowInterval.start && rowInterval.end <= colInterval.end) {
            return static_cast<int64_t>(i);
        }
    }
    return -1;// No containing interval found
}

[[nodiscard]] int64_t countOverlappingIntervals(TimeFrameInterval const & rowInterval,
                                                std::ranges::range auto && columnIntervals,
                                                TimeFrame const & destinationTimeFrame) {
    auto const rowTicks = toClockTicksInterval(rowInterval, destinationTimeFrame);
    int64_t count = 0;

    for (auto const & colInterval: columnIntervals) {
        if (is_overlapping(rowTicks, colInterval)) {
            ++count;
        }
    }

    return count;
}

[[nodiscard]] std::pair<int64_t, std::vector<EntityId>> countOverlappingIntervalsWithIds(TimeFrameInterval const & rowInterval,
                                                                                         std::ranges::range auto && columnIntervalsWithIds,
                                                                                         TimeFrame const & destinationTimeFrame) {
    auto const rowTicks = toClockTicksInterval(rowInterval, destinationTimeFrame);
    int64_t count = 0;
    std::vector<EntityId> overlappingEntityIds;

    for (auto const & colIntervalWithId: columnIntervalsWithIds) {
        if (is_overlapping(rowTicks, colIntervalWithId.interval)) {
            ++count;
            overlappingEntityIds.push_back(colIntervalWithId.entity_id);
        }
    }

    return {count, overlappingEntityIds};
}


template<typename T>
class IntervalOverlapComputer : public IColumnComputer<T> {
public:
    IntervalOverlapComputer(std::shared_ptr<DigitalIntervalSeries> source,
                            IntervalOverlapOperation operation,
                            std::string sourceName)
        : m_source(std::move(source)),
          m_operation(operation),
          m_sourceName(std::move(sourceName)) {}

    [[nodiscard]] std::pair<std::vector<T>, ColumnEntityIds> compute(ExecutionPlan const & plan) const override {
        if (!plan.hasIntervals()) {
            throw std::runtime_error("IntervalOverlapComputer requires an ExecutionPlan with intervals");
        }

        auto rowIntervals = plan.getIntervals();
        auto destinationTimeFrame = plan.getTimeFrame();

        std::vector<T> results;
        results.reserve(rowIntervals.size());

        //entity_ids.reserve(rowIntervals.size());
        if (m_operation == IntervalOverlapOperation::AssignID ||
            m_operation == IntervalOverlapOperation::AssignID_Start ||
            m_operation == IntervalOverlapOperation::AssignID_End) {

            std::vector<EntityId> entity_ids;
            for (auto const & rowInterval: rowIntervals) {
                // Get view and materialize to vector since we need .empty() and indexed access
                auto columnIntervalsView = m_source->viewInRange(TimeFrameIndex(0),
                                                                 rowInterval.end,
                                                                 *destinationTimeFrame);
                std::vector<ClockTicksIntervalWithId> columnIntervalsWithIds;
                for (auto && interval: columnIntervalsView) {
                    columnIntervalsWithIds.push_back(interval);
                }

                if (columnIntervalsWithIds.empty()) {
                    results.push_back(static_cast<T>(-1));
                    entity_ids.push_back(EntityId(0));
                    continue;
                }

                auto const rowTicks = toClockTicksInterval(rowInterval, *destinationTimeFrame);

                bool found = false;
                size_t found_idx = 0;
                for (size_t i = 0; i < columnIntervalsWithIds.size(); ++i) {
                    auto const & colInterval = columnIntervalsWithIds[i];
                    if (is_overlapping(rowTicks, colInterval.interval)) {
                        found = true;
                        found_idx = i;
                        break;// Take the first overlapping interval
                    }
                }

                if (!found) {
                    results.push_back(static_cast<T>(-1));
                    entity_ids.push_back(EntityId(0));
                    continue;
                }

                auto const & matchedInterval = columnIntervalsWithIds[found_idx];

                if (m_operation == IntervalOverlapOperation::AssignID_Start) {
                    auto source_start_index = destinationTimeFrame->getIndexAtTime(matchedInterval.interval.start);
                    results.push_back(static_cast<T>(source_start_index.getValue()));
                    entity_ids.push_back(matchedInterval.entity_id);
                } else if (m_operation == IntervalOverlapOperation::AssignID_End) {
                    auto source_end_index = destinationTimeFrame->getIndexAtTime(matchedInterval.interval.end);
                    results.push_back(static_cast<T>(source_end_index.getValue()));
                    entity_ids.push_back(matchedInterval.entity_id);
                } else {
                    // AssignID: return the index of the first overlapping interval
                    results.push_back(static_cast<T>(found_idx));
                    entity_ids.push_back(matchedInterval.entity_id);
                }
            }

            return {results, entity_ids};// std::vector<EntityId>

        } else if (m_operation == IntervalOverlapOperation::CountOverlaps) {

            std::vector<std::vector<EntityId>> entity_ids;

            for (auto const & rowInterval: rowIntervals) {
                auto columnIntervalsWithIds = m_source->viewInRange(rowInterval.start,
                                                                    rowInterval.end,
                                                                    *destinationTimeFrame);

                auto [count, overlappingEntityIds] = countOverlappingIntervalsWithIds(rowInterval,
                                                                                      columnIntervalsWithIds,
                                                                                      *destinationTimeFrame);

                results.push_back(static_cast<T>(count));
                entity_ids.push_back(overlappingEntityIds);
            }

            return {results, entity_ids};// std::vector<std::vector<EntityId>>
        }

        // This should never be reached, but provide a default return
        return {results, std::vector<EntityId>()};
    }

    [[nodiscard]] auto getSourceDependency() const -> std::string override {
        return m_sourceName;
    }

    [[nodiscard]] EntityIdStructure getEntityIdStructure() const override {
        switch (m_operation) {
            case IntervalOverlapOperation::AssignID:
            case IntervalOverlapOperation::AssignID_Start:
            case IntervalOverlapOperation::AssignID_End:
                return EntityIdStructure::Simple;// One EntityID per row (the assigned interval)
                break;
            case IntervalOverlapOperation::CountOverlaps:
                return EntityIdStructure::Complex;// Multiple EntityIDs per row (all overlapping intervals)
                break;
            default:
                return EntityIdStructure::None;
        }
    }

private:
    std::shared_ptr<DigitalIntervalSeries> m_source;
    IntervalOverlapOperation m_operation;
    std::string m_sourceName;
};


#endif// INTERVAL_OVERLAP_COMPUTER_H

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