• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

paulmthompson / WhiskerToolbox / 18389801194

09 Oct 2025 09:35PM UTC coverage: 71.943% (+0.1%) from 71.826%
18389801194

push

github

paulmthompson
add correlation matrix to filtering interface

207 of 337 new or added lines in 5 files covered. (61.42%)

867 existing lines in 31 files now uncovered.

49964 of 69449 relevant lines covered (71.94%)

1103.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

65.19
/src/DataManager/DataManager.cpp
1
#include "DataManager.hpp"
2

3
#include "AnalogTimeSeries/Analog_Time_Series.hpp"
4
#include "ConcreteDataFactory.hpp"
5
#include "DigitalTimeSeries/Digital_Event_Series.hpp"
6
#include "DigitalTimeSeries/Digital_Interval_Series.hpp"
7
#include "IO/LoaderRegistration.hpp"
8
#include "IO/LoaderRegistry.hpp"
9
#include "Lines/Line_Data.hpp"
10
#include "Masks/Mask_Data.hpp"
11
#include "Media/MediaDataFactory.hpp"
12
#include "Points/Point_Data.hpp"
13
#include "Tensors/Tensor_Data.hpp"
14

15
// Media includes - now from separate MediaData library
16
//#include "Media/Image_Data.hpp"
17
#include "Media/Media_Data.hpp"
18
//#include "Media/Video_Data.hpp"
19

20
#include "AnalogTimeSeries/IO/JSON/Analog_Time_Series_JSON.hpp"
21
#include "DigitalTimeSeries/IO/CSV/Digital_Interval_Series_CSV.hpp"
22
#include "DigitalTimeSeries/IO/JSON/Digital_Event_Series_JSON.hpp"
23
#include "DigitalTimeSeries/IO/JSON/Digital_Interval_Series_JSON.hpp"
24
#include "Lines/IO/JSON/Line_Data_JSON.hpp"
25
#include "Masks/IO/JSON/Mask_Data_JSON.hpp"
26
#ifdef ENABLE_OPENCV
27
#include "Media/IO/JSON/Image_Data_JSON.hpp"
28
#endif
29
#include "Points/IO/JSON/Point_Data_JSON.hpp"
30
#include "Tensors/IO/numpy/Tensor_Data_numpy.hpp"
31
#include "utils/TableView/TableRegistry.hpp"
32

33
#include "loaders/binary_loaders.hpp"
34

35
#include "TimeFrame/TimeFrame.hpp"
36

37
#include "nlohmann/json.hpp"
38

39
#include "transforms/TransformPipeline.hpp"
40
#include "transforms/TransformRegistry.hpp"
41
#include "utils/string_manip.hpp"
42

43
#include "Entity/EntityGroupManager.hpp"
44
#include "Entity/EntityRegistry.hpp"
45

46
#include <filesystem>
47
#include <fstream>
48
#include <iostream>
49
#include <optional>
50
#include <regex>
51

52
using namespace nlohmann;
53

54
/**
55
 * @brief Try loading data using new registry system first, fallback to legacy if needed
56
 */
57
bool tryRegistryThenLegacyLoad(
4✔
58
        DataManager * dm,
59
        std::string const & file_path,
60
        DM_DataType data_type,
61
        nlohmann::json const & item,
62
        std::string const & name,
63
        std::vector<DataInfo> & data_info_list,
64
        DataFactory * factory) {
65
    // Extract format if available
66
    if (item.contains("format")) {
4✔
67
        std::string const format = item["format"];
4✔
68

69
        // Try registry system first
70
        LoaderRegistry & registry = LoaderRegistry::getInstance();
4✔
71
        if (registry.isFormatSupported(format, toIODataType(data_type))) {
4✔
72
            std::cout << "Using registry loader for " << name << " (format: " << format << ")" << std::endl;
4✔
73

74
            LoadResult result = registry.tryLoad(format, toIODataType(data_type), file_path, item, factory);
4✔
75
            if (result.success) {
4✔
76
                // Handle data setting and post-loading setup based on data type
77
                switch (data_type) {
3✔
78
                    case DM_DataType::Line: {
2✔
79
                        // Set the LineData in DataManager
80
                        if (std::holds_alternative<std::shared_ptr<LineData>>(result.data)) {
2✔
81
                            auto line_data = std::get<std::shared_ptr<LineData>>(result.data);
2✔
82

83
                            // Set up identity context
84
                            if (line_data) {
2✔
85
                                line_data->setIdentityContext(name, dm->getEntityRegistry());
2✔
86
                                line_data->rebuildAllEntityIds();
2✔
87
                            }
88

89
                            dm->setData<LineData>(name, line_data, TimeKey("time"));
2✔
90

91
                            std::string const color = item.value("color", "0000FF");
2✔
92
                            data_info_list.push_back({name, "LineData", color});
6✔
93
                        }
2✔
94
                        break;
2✔
95
                    }
96
                    case DM_DataType::Mask: {
1✔
97
                        // Set the MaskData in DataManager
98
                        if (std::holds_alternative<std::shared_ptr<MaskData>>(result.data)) {
1✔
99
                            auto mask_data = std::get<std::shared_ptr<MaskData>>(result.data);
1✔
100

101
                            dm->setData<MaskData>(name, mask_data, TimeKey("time"));
1✔
102

103
                            std::string const color = item.value("color", "0000FF");
1✔
104
                            data_info_list.push_back({name, "MaskData", color});
3✔
105
                        }
1✔
106
                        break;
1✔
107
                    }
108
                    // Add other data types as they get plugin support...
109
                    default:
×
110
                        std::cerr << "Registry loaded unsupported data type: " << static_cast<int>(data_type) << std::endl;
×
111
                        return false;
×
112
                }
113

114
                return true;
3✔
115
            } else {
116
                std::cout << "Registry loading failed for " << name << ": " << result.error_message
117
                          << ", falling back to legacy loader" << std::endl;
1✔
118
            }
119
        }
4✔
120
    }
4✔
121

122
    return false;// Indicates we should use legacy loading
1✔
123
}
9✔
124

125
DataManager::DataManager() {
413✔
126
    _times[TimeKey("time")] = std::make_shared<TimeFrame>();
413✔
127
    _data["media"] = std::make_shared<EmptyMediaData>();
1,239✔
128

129
    setTimeKey("media", TimeKey("time"));
1,239✔
130
    _output_path = std::filesystem::current_path();
413✔
131

132
    // Initialize TableRegistry
133
    _table_registry = std::make_unique<TableRegistry>(*this);
413✔
134

135
    // Initialize EntityRegistry
136
    _entity_registry = std::make_unique<EntityRegistry>();
413✔
137

138
    // Initialize EntityGroupManager
139
    _entity_group_manager = std::make_unique<EntityGroupManager>();
413✔
140

141
    // Register all available loaders
142
    static bool loaders_registered = false;
143
    if (!loaders_registered) {
413✔
144
        registerAllLoaders();
233✔
145
        loaders_registered = true;
233✔
146
    }
147
}
413✔
148

149
DataManager::~DataManager() = default;
413✔
150

151
void DataManager::reset() {
1✔
152
    std::cout << "DataManager: Resetting to initial state..." << std::endl;
1✔
153

154
    // Clear all data objects except media (which we'll reset)
155
    _data.clear();
1✔
156

157
    // Reset media to a fresh empty MediaData object
158
    _data["media"] = std::make_shared<EmptyMediaData>();
3✔
159

160
    // Clear all TimeFrame objects except the default "time" frame
161
    _times.clear();
1✔
162

163
    // Recreate the default "time" TimeFrame
164
    _times[TimeKey("time")] = std::make_shared<TimeFrame>();
1✔
165

166
    // Clear all data-to-timeframe mappings and recreate the default media mapping
167
    _time_frames.clear();
1✔
168
    setTimeKey("media", TimeKey("time"));
3✔
169

170

171
    // Reset current time
172
    _current_time = 0;
1✔
173

174
    // Notify observers that the state has changed
175
    _notifyObservers();
1✔
176

177
    std::cout << "DataManager: Reset complete. Default 'time' frame and 'media' data restored." << std::endl;
1✔
178

179
    // Reset entity registry for a new session context
180
    if (_entity_registry) {
1✔
181
        _entity_registry->clear();
1✔
182
    }
183

184
    // Reset entity group manager for a new session context
185
    if (_entity_group_manager) {
1✔
186
        _entity_group_manager->clear();
1✔
187
    }
188
}
1✔
189

190
bool DataManager::setTime(TimeKey const & key, std::shared_ptr<TimeFrame> timeframe, bool overwrite) {
454✔
191

192
    if (!timeframe) {
454✔
193
        std::cerr << "Error: Cannot register a nullptr TimeFrame for key: " << key << std::endl;
1✔
194
        return false;
1✔
195
    }
196

197
    if (_times.find(key) != _times.end()) {
453✔
198
        if (!overwrite) {
25✔
199
            std::cerr << "Error: Time key already exists in DataManager: " << key << std::endl;
20✔
200
            return false;
20✔
201
        }
202
    }
203

204
    _times[key] = std::move(timeframe);
433✔
205

206
    // Move ptr to new time frame to all data that hold
207
    for (auto const & [data_key, data]: _data) {
885✔
208
        if (_time_frames.find(data_key) != _time_frames.end()) {
452✔
209
            auto time_key = _time_frames[data_key];
452✔
210
            if (time_key == key) {
452✔
211
                std::visit([this, key](auto & x) {
54✔
212
                    x->setTimeFrame(_times[key]);
27✔
213
                },
27✔
214
                           data);
215
            }
216
        }
452✔
217
    }
218

219
    return true;
433✔
220
}
221

222
std::shared_ptr<TimeFrame> DataManager::getTime() {
7✔
223
    return _times[TimeKey("time")];
7✔
224
};
225

226
std::shared_ptr<TimeFrame> DataManager::getTime(TimeKey const & key) {
579✔
227
    if (_times.find(key) != _times.end()) {
579✔
228
        return _times[key];
577✔
229
    }
230
    return nullptr;
2✔
231
};
232

233
TimeIndexAndFrame DataManager::getCurrentIndexAndFrame(TimeKey const & key) {
8✔
234
    if (_times.find(key) != _times.end()) {
8✔
235
        return {TimeFrameIndex(_current_time), _times[key]};
8✔
236
    }
237
    return {TimeFrameIndex(_current_time), nullptr};
×
238
}
8✔
239

240
bool DataManager::removeTime(TimeKey const & key) {
22✔
241
    if (_times.find(key) == _times.end()) {
22✔
242
        std::cerr << "Error: could not find time key in DataManager: " << key << std::endl;
×
243
        return false;
×
244
    }
245

246
    auto it = _times.find(key);
22✔
247
    _times.erase(it);
22✔
248
    return true;
22✔
249
}
250

251
bool DataManager::setTimeKey(std::string const & data_key, TimeKey const & time_key) {
1,495✔
252
    if (_data.find(data_key) == _data.end()) {
1,495✔
253
        std::cerr << "Error: Data key not found in DataManager: " << data_key << std::endl;
3✔
254
        return false;
3✔
255
    }
256

257
    if (_times.find(time_key) == _times.end()) {
1,492✔
258
        std::cerr << "Error: Time key not found in DataManager: " << time_key << std::endl;
2✔
259
        return false;
2✔
260
    }
261

262
    _time_frames[data_key] = time_key;
1,490✔
263

264
    if (_data.find(data_key) != _data.end()) {
1,490✔
265
        auto data = _data[data_key];
1,490✔
266
        std::visit([this, time_key](auto & x) {
2,980✔
267
            x->setTimeFrame(this->_times[time_key]);
1,490✔
268
        },
1,490✔
269
                   data);
270
    }
1,490✔
271
    return true;
1,490✔
272
}
273

274
TimeKey DataManager::getTimeKey(std::string const & data_key) {
940✔
275
    // check if data_key exists
276
    if (_data.find(data_key) == _data.end()) {
940✔
277
        std::cerr << "Error: Data key not found in DataManager: " << data_key << std::endl;
1✔
278
        return TimeKey("");
1✔
279
    }
280

281
    // check if data key has time frame
282
    if (_time_frames.find(data_key) == _time_frames.end()) {
939✔
283
        std::cerr << "Error: Data key "
284
                  << data_key
285
                  << " exists, but not assigned to a TimeFrame" << std::endl;
×
286
        return TimeKey("");
×
287
    }
288

289
    return _time_frames[data_key];
939✔
290
}
291

292
std::vector<TimeKey> DataManager::getTimeFrameKeys() {
134✔
293
    std::vector<TimeKey> keys;
134✔
294
    keys.reserve(_times.size());
134✔
295
    for (auto const & [key, value]: _times) {
603✔
296

297
        keys.push_back(key);
469✔
298
    }
299
    return keys;
134✔
300
}
×
301

302
int DataManager::addCallbackToData(std::string const & key, ObserverCallback callback) {
7✔
303

304
    int id = -1;
7✔
305

306
    if (_data.find(key) != _data.end()) {
7✔
307
        auto data = _data[key];
6✔
308

309
        id = std::visit([callback](auto & x) {
12✔
310
            return x.get()->addObserver(callback);
6✔
311
        },
312
                        data);
313
    }
6✔
314

315
    return id;
7✔
316
}
317

318
bool DataManager::removeCallbackFromData(std::string const & key, int callback_id) {
4✔
319
    if (_data.find(key) != _data.end()) {
4✔
320
        auto data = _data[key];
3✔
321

322
        std::visit([callback_id](auto & x) {
6✔
323
            x.get()->removeObserver(callback_id);
3✔
324
        },
3✔
325
                   data);
326

327
        return true;
3✔
328
    }
3✔
329

330
    return false;
1✔
331
}
332

333
void DataManager::addObserver(ObserverCallback callback) {
96✔
334
    _observers.push_back(std::move(callback));
96✔
335
}
96✔
336

337
void DataManager::_notifyObservers() {
1,091✔
338
    for (auto & observer: _observers) {
1,147✔
339
        observer();
56✔
340
    }
341
}
1,091✔
342

343
// ===== Table Registry accessors =====
344
TableRegistry * DataManager::getTableRegistry() {
507✔
345
    return _table_registry.get();
507✔
346
}
347

348
TableRegistry const * DataManager::getTableRegistry() const {
×
349
    return _table_registry.get();
×
350
}
351

352
// ===== Table observer channel =====
353
int DataManager::addTableObserver(TableObserver callback) {
18✔
354
    if (!callback) return -1;
18✔
355
    int id = _next_table_observer_id++;
18✔
356
    _table_observers[id] = std::move(callback);
18✔
357
    return id;
18✔
358
}
359

360
bool DataManager::removeTableObserver(int callback_id) {
×
361
    return _table_observers.erase(callback_id) > 0;
×
362
}
363

364
void DataManager::notifyTableObservers(TableEvent const & ev) {
79✔
365
    for (auto const & [id, cb]: _table_observers) {
109✔
366
        (void) id;
367
        cb(ev);
30✔
368
    }
369
}
79✔
370

371
// Provide C-style bridge for TableRegistry to call
372
void DataManager__NotifyTableObservers(DataManager & dm, TableEvent const & ev) {
79✔
373
    dm.notifyTableObservers(ev);
79✔
374
}
79✔
375

376
std::vector<std::string> DataManager::getAllKeys() {
120✔
377
    std::vector<std::string> keys;
120✔
378
    keys.reserve(_data.size());
120✔
379
    for (auto const & [key, value]: _data) {
710✔
380

381
        keys.push_back(key);
590✔
382
    }
383
    return keys;
120✔
384
}
×
385

386
std::optional<DataTypeVariant> DataManager::getDataVariant(std::string const & key) {
74✔
387
    if (_data.find(key) != _data.end()) {
74✔
388
        return _data[key];
74✔
389
    }
390
    return std::nullopt;
×
391
}
392

393
void DataManager::setData(std::string const & key, DataTypeVariant data, TimeKey const & time_key) {
75✔
394
    // Loop through all _data. If shared_ptr data is already in _data, return
395
    for (auto const & [existing_key, existing_variant]: _data) {
303✔
396
        // Safely compare only when the variant alternatives match; avoid std::bad_variant_access
397
        bool found = std::visit([
456✔
398
            &data
399
        ](auto const & existing_ptr) -> bool {
400
            using PtrT = std::decay_t<decltype(existing_ptr)>;
401
            if (auto const * incoming_ptr = std::get_if<PtrT>(&data)) {
228✔
402
                return existing_ptr == *incoming_ptr; // shared_ptr comparison (same pointee address)
101✔
403
            }
404
            return false;
127✔
405
        }, existing_variant);
228✔
406

407
        if (found) {
228✔
408
            std::cerr << "Data with key '" << existing_key
409
                      << "' already exists; not setting duplicate under key '" << key << "'."
×
410
                      << std::endl;
×
411
            return; // Data already exists, do not set again
×
412
        }
413
    }
414

415
    _data[key] = data;
75✔
416
    setTimeKey(key, time_key);
75✔
417

418
    if (std::holds_alternative<std::shared_ptr<LineData>>(_data[key])) {
75✔
419
        std::get<std::shared_ptr<LineData>>(_data[key])->setIdentityContext(key, getEntityRegistry());
21✔
420
        std::get<std::shared_ptr<LineData>>(_data[key])->rebuildAllEntityIds();
21✔
421
    } else if (std::holds_alternative<std::shared_ptr<PointData>>(_data[key])) {
54✔
422
        std::get<std::shared_ptr<PointData>>(_data[key])->setIdentityContext(key, getEntityRegistry());
7✔
423
        std::get<std::shared_ptr<PointData>>(_data[key])->rebuildAllEntityIds();
7✔
424
    } else if (std::holds_alternative<std::shared_ptr<DigitalEventSeries>>(_data[key])) {
47✔
425
        std::get<std::shared_ptr<DigitalEventSeries>>(_data[key])->setIdentityContext(key, getEntityRegistry());
4✔
426
        std::get<std::shared_ptr<DigitalEventSeries>>(_data[key])->rebuildAllEntityIds();
4✔
427
    } else if (std::holds_alternative<std::shared_ptr<DigitalIntervalSeries>>(_data[key])) {
43✔
428
        std::get<std::shared_ptr<DigitalIntervalSeries>>(_data[key])->setIdentityContext(key, getEntityRegistry());
8✔
429
        std::get<std::shared_ptr<DigitalIntervalSeries>>(_data[key])->rebuildAllEntityIds();
8✔
430
    } else if (std::holds_alternative<std::shared_ptr<MaskData>>(_data[key])) {
35✔
431
        std::get<std::shared_ptr<MaskData>>(_data[key])->setIdentityContext(key, getEntityRegistry());
12✔
432
        std::get<std::shared_ptr<MaskData>>(_data[key])->rebuildAllEntityIds();
12✔
433
    }
434

435
    _notifyObservers();
75✔
436
}
437

438
bool DataManager::deleteData(std::string const & key) {
15✔
439
    // Check if the key exists
440
    if (_data.find(key) == _data.end()) {
15✔
UNCOV
441
        std::cerr << "Error: Data key not found in DataManager: " << key << std::endl;
×
UNCOV
442
        return false;
×
443
    }
444

445
    // Remove the time frame mapping if it exists
446
    _time_frames.erase(key);
15✔
447

448
    // Remove the data from storage
449
    _data.erase(key);
15✔
450

451
    // Notify all observers that data has changed
452
    _notifyObservers();
15✔
453

454
    std::cout << "DataManager: Successfully deleted data with key: " << key << std::endl;
15✔
455
    return true;
15✔
456
}
457

458
std::optional<std::string> processFilePath(
14✔
459
        std::string const & file_path,
460
        std::filesystem::path const & base_path) {
461
    std::filesystem::path full_path = file_path;
14✔
462

463
    // Check for wildcard character
464
    if (file_path.find('*') != std::string::npos) {
14✔
465
        // Convert wildcard pattern to regex
UNCOV
466
        std::string const pattern = std::regex_replace(full_path.string(), std::regex("\\*"), ".*");
×
467
        std::regex const regex_pattern(pattern);
×
468

469
        // Iterate through the directory to find matching files
470
        for (auto const & entry: std::filesystem::directory_iterator(base_path)) {
×
471
            std::cout << "Checking " << entry.path().string() << " with full path " << full_path << std::endl;
×
UNCOV
472
            if (std::regex_match(entry.path().string(), regex_pattern)) {
×
473
                std::cout << "Loading file " << entry.path().string() << std::endl;
×
474
                return entry.path().string();
×
475
            }
UNCOV
476
        }
×
UNCOV
477
        return std::nullopt;
×
UNCOV
478
    } else {
×
479
        // Check if the file path is relative
480
        if (!std::filesystem::path(file_path).is_absolute()) {
14✔
481
            full_path = base_path / file_path;
2✔
482
        }
483
        // Check for the presence of the file
484
        if (std::filesystem::exists(full_path)) {
14✔
485
            std::cout << "Loading file " << full_path.string() << std::endl;
8✔
486
            return full_path.string();
8✔
487
        } else {
488
            return std::nullopt;
6✔
489
        }
490
    }
491
}
14✔
492

493
bool checkRequiredFields(json const & item, std::vector<std::string> const & requiredFields) {
14✔
494
    for (auto const & field: requiredFields) {
56✔
495
        if (!item.contains(field)) {
42✔
UNCOV
496
            std::cerr << "Error: Missing required field \"" << field << "\" in JSON item." << std::endl;
×
UNCOV
497
            return false;
×
498
        }
499
    }
500
    return true;
14✔
501
}
502

503
void checkOptionalFields(json const & item, std::vector<std::string> const & optionalFields) {
×
UNCOV
504
    for (auto const & field: optionalFields) {
×
UNCOV
505
        if (!item.contains(field)) {
×
506
            std::cout << "Warning: Optional field \"" << field << "\" is missing in JSON item." << std::endl;
×
507
        }
508
    }
UNCOV
509
}
×
510

511
DM_DataType stringToDataType(std::string const & data_type_str) {
14✔
512
    if (data_type_str == "video") return DM_DataType::Video;
14✔
513
    if (data_type_str == "images") return DM_DataType::Images;
14✔
514
    if (data_type_str == "points") return DM_DataType::Points;
14✔
515
    if (data_type_str == "mask") return DM_DataType::Mask;
12✔
516
    if (data_type_str == "line") return DM_DataType::Line;
10✔
517
    if (data_type_str == "analog") return DM_DataType::Analog;
4✔
518
    if (data_type_str == "digital_event") return DM_DataType::DigitalEvent;
2✔
519
    if (data_type_str == "digital_interval") return DM_DataType::DigitalInterval;
2✔
UNCOV
520
    if (data_type_str == "tensor") return DM_DataType::Tensor;
×
UNCOV
521
    if (data_type_str == "time") return DM_DataType::Time;
×
UNCOV
522
    return DM_DataType::Unknown;
×
523
}
524

525
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, json const & j, std::filesystem::path const & base_path) {
73✔
526
    std::vector<DataInfo> data_info_list;
73✔
527
    // Create factory for plugin system
528
    ConcreteDataFactory factory;
73✔
529

530
    // Iterate through JSON array
531
    for (auto const & item: j) {
146✔
532

533
        // Skip transformation objects - they will be processed separately
534
        if (item.contains("transformations")) {
73✔
535
            continue;
59✔
536
        }
537

538
        if (!checkRequiredFields(item, {"data_type", "name", "filepath"})) {
42✔
UNCOV
539
            continue;// Exit if any required field is missing
×
540
        }
541

542
        std::string const data_type_str = item["data_type"];
14✔
543
        auto const data_type = stringToDataType(data_type_str);
14✔
544
        if (data_type == DM_DataType::Unknown) {
14✔
UNCOV
545
            std::cout << "Unknown data type: " << data_type_str << std::endl;
×
UNCOV
546
            continue;
×
547
        }
548

549
        std::string const name = item["name"];
14✔
550

551
        auto file_exists = processFilePath(item["filepath"], base_path);
14✔
552
        if (!file_exists) {
14✔
553
            std::cerr << "File does not exist: " << item["filepath"] << std::endl;
6✔
554
            continue;
6✔
555
        }
556

557
        std::string const file_path = file_exists.value();
8✔
558

559
        switch (data_type) {
8✔
560
            case DM_DataType::Video: {
×
561
                auto media_data = MediaDataFactory::loadMediaData(data_type, file_path, item);
×
562
                if (media_data) {
×
563
                    auto item_key = item.value("name", "media");
×
564
                    dm->setData<MediaData>(item_key, media_data, TimeKey("time"));
×
UNCOV
565
                    data_info_list.push_back({name, "VideoData", ""});
×
566
                } else {
×
567
                    std::cerr << "Failed to load video data: " << file_path << std::endl;
×
568
                }
569
                break;
×
570
            }
×
571
#ifdef ENABLE_OPENCV
572
            case DM_DataType::Images: {
×
573
                auto media_data = MediaDataFactory::loadMediaData(data_type, file_path, item);
×
574
                if (media_data) {
×
575
                    auto item_key = item.value("name", "media");
×
576
                    dm->setData<MediaData>(item_key, media_data, TimeKey("time"));
×
UNCOV
577
                    data_info_list.push_back({name, "ImageData", ""});
×
578
                } else {
×
579
                    std::cerr << "Failed to load image data: " << file_path << std::endl;
×
580
                }
UNCOV
581
                break;
×
UNCOV
582
            }
×
583
#endif
584
            case DM_DataType::Points: {
2✔
585

586
                // Check if this is a DLC CSV format that needs special handling
587
                if (item.contains("format") && item["format"] == "dlc_csv") {
2✔
588
                    auto multi_point_data = load_multiple_PointData_from_dlc(file_path, item);
2✔
589

590
                    // For DLC data, let Media_Window assign colors automatically via getColorForIndex
591
                    // Don't use a single color for all bodyparts
592

593
                    for (auto const & [bodypart, point_data]: multi_point_data) {
21✔
594
                        std::string const bodypart_name = name + "_" + bodypart;
19✔
595

596
                        // Attach identity context and generate EntityIds
597
                        if (point_data) {
19✔
598
                            point_data->setIdentityContext(bodypart_name, dm->getEntityRegistry());
19✔
599
                            point_data->rebuildAllEntityIds();
19✔
600
                        }
601

602
                        dm->setData<PointData>(bodypart_name, point_data, TimeKey("time"));
19✔
603
                        // Use empty color string to let Media_Window auto-assign colors
604
                        data_info_list.push_back({bodypart_name, "PointData", ""});
57✔
605
                    }
19✔
606
                } else {
2✔
607
                    // Regular point data loading
608
                    auto point_data = load_into_PointData(file_path, item);
×
609

610
                    // Attach identity context and generate EntityIds
UNCOV
611
                    if (point_data) {
×
UNCOV
612
                        point_data->setIdentityContext(name, dm->getEntityRegistry());
×
613
                        point_data->rebuildAllEntityIds();
×
614
                    }
615

616
                    dm->setData<PointData>(name, point_data, TimeKey("time"));
×
617

UNCOV
618
                    std::string const color = item.value("color", "#0000FF");
×
UNCOV
619
                    data_info_list.push_back({name, "PointData", color});
×
UNCOV
620
                }
×
621
                break;
2✔
622
            }
623
            case DM_DataType::Mask: {
1✔
624

625
                // Try registry system first, then fallback to legacy
626
                if (tryRegistryThenLegacyLoad(dm, file_path, data_type, item, name, data_info_list, &factory)) {
1✔
627
                    break;// Successfully loaded with plugin
1✔
628
                }
629

630
                // Legacy loading fallback
631
                auto mask_data = load_into_MaskData(file_path, item);
×
632

633
                std::string const color = item.value("color", "0000FF");
×
UNCOV
634
                dm->setData<MaskData>(name, mask_data, TimeKey("time"));
×
635

636
                data_info_list.push_back({name, "MaskData", color});
×
637

UNCOV
638
                break;
×
UNCOV
639
            }
×
640
            case DM_DataType::Line: {
3✔
641

642
                // Try registry system first, then fallback to legacy
643
                if (tryRegistryThenLegacyLoad(dm, file_path, data_type, item, name, data_info_list, &factory)) {
3✔
644
                    break;// Successfully loaded with plugin
2✔
645
                }
646

647
                // Legacy loading fallback
648
                auto line_data = load_into_LineData(file_path, item);
1✔
649

650
                // Attach identity context and generate EntityIds
651
                if (line_data) {
1✔
652
                    line_data->setIdentityContext(name, dm->getEntityRegistry());
1✔
653
                    line_data->rebuildAllEntityIds();
1✔
654
                }
655

656
                dm->setData<LineData>(name, line_data, TimeKey("time"));
1✔
657

658
                std::string const color = item.value("color", "0000FF");
1✔
659

660
                data_info_list.push_back({name, "LineData", color});
3✔
661

662
                break;
1✔
663
            }
1✔
664
            case DM_DataType::Analog: {
1✔
665

666
                auto analog_time_series = load_into_AnalogTimeSeries(file_path, item);
1✔
667

668
                for (size_t channel = 0; channel < analog_time_series.size(); channel++) {
2✔
669
                    std::string const channel_name = name + "_" + std::to_string(channel);
1✔
670

671
                    dm->setData<AnalogTimeSeries>(channel_name, analog_time_series[channel], TimeKey("time"));
1✔
672

673
                    if (item.contains("clock")) {
1✔
674
                        std::string const clock_str = item["clock"];
×
UNCOV
675
                        auto const clock = TimeKey(clock_str);
×
UNCOV
676
                        dm->setTimeKey(channel_name, clock);
×
UNCOV
677
                    }
×
678
                }
1✔
679
                break;
1✔
680
            }
1✔
UNCOV
681
            case DM_DataType::DigitalEvent: {
×
682

683
                auto digital_event_series = load_into_DigitalEventSeries(file_path, item);
×
684

UNCOV
685
                for (size_t channel = 0; channel < digital_event_series.size(); channel++) {
×
686
                    std::string const channel_name = name + "_" + std::to_string(channel);
×
687

688
                    // Attach identity context and generate EntityIds
UNCOV
689
                    if (digital_event_series[channel]) {
×
UNCOV
690
                        digital_event_series[channel]->setIdentityContext(channel_name, dm->getEntityRegistry());
×
691
                        digital_event_series[channel]->rebuildAllEntityIds();
×
692
                    }
693

694
                    dm->setData<DigitalEventSeries>(channel_name, digital_event_series[channel], TimeKey("time"));
×
695

696
                    if (item.contains("clock")) {
×
697
                        std::string const clock_str = item["clock"];
×
698
                        auto const clock = TimeKey(clock_str);
×
699
                        dm->setTimeKey(channel_name, clock);
×
700
                    }
×
UNCOV
701
                }
×
UNCOV
702
                break;
×
UNCOV
703
            }
×
704
            case DM_DataType::DigitalInterval: {
1✔
705

706
                auto digital_interval_series = load_into_DigitalIntervalSeries(file_path, item);
1✔
707
                if (digital_interval_series) {
1✔
708
                    digital_interval_series->setIdentityContext(name, dm->getEntityRegistry());
1✔
709
                    digital_interval_series->rebuildAllEntityIds();
1✔
710
                }
711
                dm->setData<DigitalIntervalSeries>(name, digital_interval_series, TimeKey("time"));
1✔
712

713
                break;
1✔
714
            }
1✔
UNCOV
715
            case DM_DataType::Tensor: {
×
716

717
                if (item["format"] == "numpy") {
×
718

719
                    TensorData tensor_data;
×
UNCOV
720
                    loadNpyToTensorData(file_path, tensor_data);
×
721

722
                    dm->setData<TensorData>(name, std::make_shared<TensorData>(tensor_data), TimeKey("time"));
×
723

724
                } else {
×
UNCOV
725
                    std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
726
                }
UNCOV
727
                break;
×
728
            }
UNCOV
729
            case DM_DataType::Time: {
×
730

731
                if (item["format"] == "uint16") {
×
732

733
                    int const channel = item["channel"];
×
UNCOV
734
                    std::string const transition = item["transition"];
×
735

736
                    int const header_size = item.value("header_size", 0);
×
737

UNCOV
738
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
739
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
740
                    auto data = Loader::readBinaryFile<uint16_t>(opts);
×
741

UNCOV
742
                    auto digital_data = Loader::extractDigitalData(data, channel);
×
743
                    auto events = Loader::extractEvents(digital_data, transition);
×
744

745
                    // convert to int with std::transform
746
                    std::vector<int> events_int;
×
UNCOV
747
                    events_int.reserve(events.size());
×
748
                    for (auto e: events) {
×
UNCOV
749
                        events_int.push_back(static_cast<int>(e));
×
750
                    }
751
                    std::cout << "Loaded " << events_int.size() << " events for " << name << std::endl;
×
752

UNCOV
753
                    auto timeframe = std::make_shared<TimeFrame>(events_int);
×
754
                    dm->setTime(TimeKey(name), timeframe, true);
×
UNCOV
755
                }
×
756

UNCOV
757
                if (item["format"] == "uint16_length") {
×
758

759
                    int const header_size = item.value("header_size", 0);
×
760

UNCOV
761
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
762
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
763
                    auto data = Loader::readBinaryFile<uint16_t>(opts);
×
764

765
                    std::vector<int> t(data.size());
×
UNCOV
766
                    std::iota(std::begin(t), std::end(t), 0);
×
767

768
                    std::cout << "Total of " << t.size() << " timestamps for " << name << std::endl;
×
769

UNCOV
770
                    auto timeframe = std::make_shared<TimeFrame>(t);
×
771
                    dm->setTime(TimeKey(name), timeframe, true);
×
UNCOV
772
                }
×
773

774
                if (item["format"] == "filename") {
×
775

776
                    // Get required parameters
UNCOV
777
                    std::string const folder_path = file_path;// file path is required argument
×
778
                    std::string const regex_pattern = item["regex_pattern"];
×
779

780
                    // Get optional parameters with defaults
UNCOV
781
                    std::string const file_extension = item.value("file_extension", "");
×
UNCOV
782
                    std::string const mode_str = item.value("mode", "found_values");
×
783
                    bool const sort_ascending = item.value("sort_ascending", true);
×
784

785
                    // Convert mode string to enum
786
                    FilenameTimeFrameMode mode = FilenameTimeFrameMode::FOUND_VALUES;
×
787
                    if (mode_str == "zero_to_max") {
×
UNCOV
788
                        mode = FilenameTimeFrameMode::ZERO_TO_MAX;
×
UNCOV
789
                    } else if (mode_str == "min_to_max") {
×
UNCOV
790
                        mode = FilenameTimeFrameMode::MIN_TO_MAX;
×
791
                    }
792

793
                    // Create options
794
                    FilenameTimeFrameOptions options;
×
795
                    options.folder_path = folder_path;
×
796
                    options.file_extension = file_extension;
×
UNCOV
797
                    options.regex_pattern = regex_pattern;
×
UNCOV
798
                    options.mode = mode;
×
799
                    options.sort_ascending = sort_ascending;
×
800

801
                    // Create TimeFrame from filenames
UNCOV
802
                    auto timeframe = createTimeFrameFromFilenames(options);
×
803
                    if (timeframe) {
×
UNCOV
804
                        dm->setTime(TimeKey(name), timeframe, true);
×
805
                        std::cout << "Created TimeFrame '" << name << "' from filenames in "
806
                                  << folder_path << std::endl;
×
807
                    } else {
808
                        std::cerr << "Error: Failed to create TimeFrame from filenames for "
809
                                  << name << std::endl;
×
810
                    }
811
                }
×
812
                break;
×
813
            }
814
            default:
×
UNCOV
815
                std::cout << "Unsupported data type: " << data_type_str << std::endl;
×
816
                continue;
×
817
        }
×
818
        if (item.contains("clock")) {
8✔
819
            std::string clock_str = item["clock"];
×
820
            auto clock = TimeKey(clock_str);
×
UNCOV
821
            std::cout << "Setting time for " << name << " to " << clock << std::endl;
×
UNCOV
822
            dm->setTimeKey(name, clock);
×
UNCOV
823
        }
×
824
    }
26✔
825

826
    // Process all transformation objects found in the JSON array
827
    for (auto const & item: j) {
146✔
828
        if (item.contains("transformations")) {
73✔
829
            std::cout << "Found transformations section, executing pipeline..." << std::endl;
59✔
830

831
            try {
832
                // Create registry and pipeline with proper constructors
833
                auto registry = std::make_unique<TransformRegistry>();
59✔
834
                TransformPipeline pipeline(dm, registry.get());
59✔
835

836
                // Load the pipeline configuration from JSON
837
                if (!pipeline.loadFromJson(item["transformations"])) {
59✔
UNCOV
838
                    std::cerr << "Failed to load pipeline configuration from JSON" << std::endl;
×
UNCOV
839
                    continue;
×
840
                }
841

842
                // Execute the pipeline with a progress callback
843
                auto result = pipeline.execute([](int step_index, std::string const & step_name, int step_progress, int overall_progress) {
118✔
844
                    std::cout << "Step " << step_index << " ('" << step_name << "'): "
324✔
845
                              << step_progress << "% (Overall: " << overall_progress << "%)" << std::endl;
324✔
846
                });
118✔
847

848
                if (result.success) {
59✔
849
                    std::cout << "Pipeline executed successfully!" << std::endl;
59✔
850
                    std::cout << "Steps completed: " << result.steps_completed << "/" << result.total_steps << std::endl;
59✔
851
                    std::cout << "Total execution time: " << result.total_execution_time_ms << " ms" << std::endl;
59✔
852
                } else {
UNCOV
853
                    std::cerr << "Pipeline execution failed: " << result.error_message << std::endl;
×
854
                }
855

856
            } catch (std::exception const & e) {
59✔
UNCOV
857
                std::cerr << "Exception during pipeline execution: " << e.what() << std::endl;
×
UNCOV
858
            }
×
859
        }
860
    }
861

862
    return data_info_list;
73✔
863
}
171✔
864

865
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, std::string const & json_filepath) {
73✔
866
    // Open JSON file
867
    std::ifstream ifs(json_filepath);
73✔
868
    if (!ifs.is_open()) {
73✔
UNCOV
869
        std::cerr << "Failed to open JSON file: " << json_filepath << std::endl;
×
UNCOV
870
        return {};
×
871
    }
872

873
    // Parse JSON
874
    json j;
73✔
875
    ifs >> j;
73✔
876

877
    // get base path of filepath
878
    std::filesystem::path const base_path = std::filesystem::path(json_filepath).parent_path();
73✔
879
    return load_data_from_json_config(dm, j, base_path);
73✔
880
}
73✔
881

882
DM_DataType DataManager::getType(std::string const & key) const {
939✔
883
    auto it = _data.find(key);
939✔
884
    if (it != _data.end()) {
939✔
885
        if (std::holds_alternative<std::shared_ptr<MediaData>>(it->second)) {
936✔
886
            auto media_data = std::get<std::shared_ptr<MediaData>>(it->second);
140✔
887
            switch (media_data->getMediaType()) {
140✔
888
                case MediaData::MediaType::Video:
133✔
889
                    return DM_DataType::Video;
133✔
890
                case MediaData::MediaType::Images:
7✔
891
                    return DM_DataType::Images;
7✔
892
                case MediaData::MediaType::HDF5:
×
893
                    // For HDF5, we might need additional logic to determine if it's video or images
894
                    // For now, defaulting to Video (old behavior)
UNCOV
895
                    return DM_DataType::Video;
×
UNCOV
896
                default:
×
UNCOV
897
                    return DM_DataType::Video;// Old behavior for unknown types
×
898
            }
899
        } else if (std::holds_alternative<std::shared_ptr<PointData>>(it->second)) {
936✔
900
            return DM_DataType::Points;
114✔
901
        } else if (std::holds_alternative<std::shared_ptr<LineData>>(it->second)) {
682✔
902
            return DM_DataType::Line;
82✔
903
        } else if (std::holds_alternative<std::shared_ptr<MaskData>>(it->second)) {
600✔
904
            return DM_DataType::Mask;
16✔
905
        } else if (std::holds_alternative<std::shared_ptr<AnalogTimeSeries>>(it->second)) {
584✔
906
            return DM_DataType::Analog;
368✔
907
        } else if (std::holds_alternative<std::shared_ptr<DigitalEventSeries>>(it->second)) {
216✔
908
            return DM_DataType::DigitalEvent;
187✔
909
        } else if (std::holds_alternative<std::shared_ptr<DigitalIntervalSeries>>(it->second)) {
29✔
910
            return DM_DataType::DigitalInterval;
29✔
911
        } else if (std::holds_alternative<std::shared_ptr<TensorData>>(it->second)) {
×
UNCOV
912
            return DM_DataType::Tensor;
×
913
        }
UNCOV
914
        return DM_DataType::Unknown;
×
915
    }
916
    return DM_DataType::Unknown;
3✔
917
}
918

919
std::string convert_data_type_to_string(DM_DataType type) {
823✔
920
    switch (type) {
823✔
921
        case DM_DataType::Video:
88✔
922
            return "video";
264✔
UNCOV
923
        case DM_DataType::Images:
×
UNCOV
924
            return "images";
×
925
        case DM_DataType::Points:
137✔
926
            return "points";
411✔
927
        case DM_DataType::Mask:
6✔
928
            return "mask";
18✔
929
        case DM_DataType::Line:
117✔
930
            return "line";
351✔
931
        case DM_DataType::Analog:
238✔
932
            return "analog";
714✔
933
        case DM_DataType::DigitalEvent:
179✔
934
            return "digital_event";
537✔
935
        case DM_DataType::DigitalInterval:
58✔
936
            return "digital_interval";
174✔
937
        case DM_DataType::Tensor:
×
938
            return "tensor";
×
939
        case DM_DataType::Time:
×
UNCOV
940
            return "time";
×
UNCOV
941
        default:
×
UNCOV
942
            return "unknown";
×
943
    }
944
}
945

946
template std::shared_ptr<AnalogTimeSeries> DataManager::getData<AnalogTimeSeries>(std::string const & key);
947
template void DataManager::setData<AnalogTimeSeries>(std::string const & key, TimeKey const & time_key);
948
template void DataManager::setData<AnalogTimeSeries>(std::string const & key, std::shared_ptr<AnalogTimeSeries> data, TimeKey const & time_key);
949

950
template std::shared_ptr<DigitalEventSeries> DataManager::getData<DigitalEventSeries>(std::string const & key);
951
template void DataManager::setData<DigitalEventSeries>(std::string const & key, TimeKey const & time_key);
952
template void DataManager::setData<DigitalEventSeries>(std::string const & key, std::shared_ptr<DigitalEventSeries> data, TimeKey const & time_key);
953

954
template std::shared_ptr<DigitalIntervalSeries> DataManager::getData<DigitalIntervalSeries>(std::string const & key);
955
template void DataManager::setData<DigitalIntervalSeries>(std::string const & key, TimeKey const & time_key);
956
template void DataManager::setData<DigitalIntervalSeries>(std::string const & key, std::shared_ptr<DigitalIntervalSeries> data, TimeKey const & time_key);
957

958
template std::shared_ptr<LineData> DataManager::getData<LineData>(std::string const & key);
959
template void DataManager::setData<LineData>(std::string const & key, TimeKey const & time_key);
960
template void DataManager::setData<LineData>(std::string const & key, std::shared_ptr<LineData> data, TimeKey const & time_key);
961

962
template std::shared_ptr<MaskData> DataManager::getData<MaskData>(std::string const & key);
963
template void DataManager::setData<MaskData>(std::string const & key, TimeKey const & time_key);
964
template void DataManager::setData<MaskData>(std::string const & key, std::shared_ptr<MaskData> data, TimeKey const & time_key);
965

966
template std::shared_ptr<MediaData> DataManager::getData<MediaData>(std::string const & key);
967

968
template std::shared_ptr<PointData> DataManager::getData<PointData>(std::string const & key);
969
template void DataManager::setData<PointData>(std::string const & key, TimeKey const & time_key);
970
template void DataManager::setData<PointData>(std::string const & key, std::shared_ptr<PointData> data, TimeKey const & time_key);
971

972
template std::shared_ptr<TensorData> DataManager::getData<TensorData>(std::string const & key);
973
template void DataManager::setData<TensorData>(std::string const & key, TimeKey const & time_key);
974
template void DataManager::setData<TensorData>(std::string const & key, std::shared_ptr<TensorData> data, TimeKey const & time_key);
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc