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

paulmthompson / WhiskerToolbox / 18117112849

30 Sep 2025 02:44AM UTC coverage: 70.161% (+0.03%) from 70.132%
18117112849

push

github

paulmthompson
hungarian algorithm is actually used

60 of 77 new or added lines in 2 files covered. (77.92%)

352 existing lines in 12 files now uncovered.

45125 of 64316 relevant lines covered (70.16%)

1116.85 hits per line

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

65.0
/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...
UNCOV
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() {
377✔
126
    _times[TimeKey("time")] = std::make_shared<TimeFrame>();
377✔
127
    _data["media"] = std::make_shared<EmptyMediaData>();
1,131✔
128

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

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

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

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

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

149
DataManager::~DataManager() = default;
377✔
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) {
430✔
191

192
    if (!timeframe) {
430✔
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()) {
429✔
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);
409✔
205

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

219
    return true;
409✔
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
    }
UNCOV
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✔
UNCOV
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,411✔
252
    if (_data.find(data_key) == _data.end()) {
1,411✔
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,408✔
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,406✔
263

264
    if (_data.find(data_key) != _data.end()) {
1,406✔
265
        auto data = _data[data_key];
1,406✔
266
        std::visit([this, time_key](auto & x) {
2,812✔
267
            x->setTimeFrame(this->_times[time_key]);
1,406✔
268
        },
1,406✔
269
                   data);
270
    }
1,406✔
271
    return true;
1,406✔
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
UNCOV
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✔
UNCOV
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,043✔
338
    for (auto & observer: _observers) {
1,099✔
339
        observer();
56✔
340
    }
341
}
1,043✔
342

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

UNCOV
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

UNCOV
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✔
UNCOV
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
    }
UNCOV
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
UNCOV
409
                      << "' already exists; not setting duplicate under key '" << key << "'."
×
UNCOV
410
                      << std::endl;
×
UNCOV
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
    }
431

432
    _notifyObservers();
75✔
433
}
434

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

442
    // Remove the time frame mapping if it exists
443
    _time_frames.erase(key);
15✔
444

445
    // Remove the data from storage
446
    _data.erase(key);
15✔
447

448
    // Notify all observers that data has changed
449
    _notifyObservers();
15✔
450

451
    std::cout << "DataManager: Successfully deleted data with key: " << key << std::endl;
15✔
452
    return true;
15✔
453
}
454

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

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

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

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

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

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

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

527
    // Iterate through JSON array
528
    for (auto const & item: j) {
146✔
529

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

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

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

546
        std::string const name = item["name"];
14✔
547

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

554
        std::string const file_path = file_exists.value();
8✔
555

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

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

587
                    // For DLC data, let Media_Window assign colors automatically via getColorForIndex
588
                    // Don't use a single color for all bodyparts
589

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

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

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

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

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

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

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

627
                // Legacy loading fallback
UNCOV
628
                auto mask_data = load_into_MaskData(file_path, item);
×
629

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

UNCOV
633
                data_info_list.push_back({name, "MaskData", color});
×
634

UNCOV
635
                break;
×
UNCOV
636
            }
×
637
            case DM_DataType::Line: {
3✔
638

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

644
                // Legacy loading fallback
645
                auto line_data = load_into_LineData(file_path, item);
1✔
646

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

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

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

657
                data_info_list.push_back({name, "LineData", color});
3✔
658

659
                break;
1✔
660
            }
1✔
661
            case DM_DataType::Analog: {
1✔
662

663
                auto analog_time_series = load_into_AnalogTimeSeries(file_path, item);
1✔
664

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

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

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

680
                auto digital_event_series = load_into_DigitalEventSeries(file_path, item);
×
681

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

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

UNCOV
691
                    dm->setData<DigitalEventSeries>(channel_name, digital_event_series[channel], TimeKey("time"));
×
692

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

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

710
                break;
1✔
711
            }
1✔
UNCOV
712
            case DM_DataType::Tensor: {
×
713

UNCOV
714
                if (item["format"] == "numpy") {
×
715

716
                    TensorData tensor_data;
×
717
                    loadNpyToTensorData(file_path, tensor_data);
×
718

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

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

728
                if (item["format"] == "uint16") {
×
729

730
                    int const channel = item["channel"];
×
731
                    std::string const transition = item["transition"];
×
732

UNCOV
733
                    int const header_size = item.value("header_size", 0);
×
734

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

739
                    auto digital_data = Loader::extractDigitalData(data, channel);
×
740
                    auto events = Loader::extractEvents(digital_data, transition);
×
741

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

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

754
                if (item["format"] == "uint16_length") {
×
755

UNCOV
756
                    int const header_size = item.value("header_size", 0);
×
757

758
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
759
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
760
                    auto data = Loader::readBinaryFile<uint16_t>(opts);
×
761

UNCOV
762
                    std::vector<int> t(data.size());
×
763
                    std::iota(std::begin(t), std::end(t), 0);
×
764

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

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

771
                if (item["format"] == "filename") {
×
772

773
                    // Get required parameters
774
                    std::string const folder_path = file_path;// file path is required argument
×
775
                    std::string const regex_pattern = item["regex_pattern"];
×
776

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

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

790
                    // Create options
791
                    FilenameTimeFrameOptions options;
×
792
                    options.folder_path = folder_path;
×
793
                    options.file_extension = file_extension;
×
794
                    options.regex_pattern = regex_pattern;
×
UNCOV
795
                    options.mode = mode;
×
796
                    options.sort_ascending = sort_ascending;
×
797

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

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

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

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

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

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

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

859
    return data_info_list;
73✔
860
}
171✔
861

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

870
    // Parse JSON
871
    json j;
73✔
872
    ifs >> j;
73✔
873

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

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

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

943
template std::shared_ptr<AnalogTimeSeries> DataManager::getData<AnalogTimeSeries>(std::string const & key);
944
template void DataManager::setData<AnalogTimeSeries>(std::string const & key, TimeKey const & time_key);
945
template void DataManager::setData<AnalogTimeSeries>(std::string const & key, std::shared_ptr<AnalogTimeSeries> data, TimeKey const & time_key);
946

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

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

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

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

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

965
template std::shared_ptr<PointData> DataManager::getData<PointData>(std::string const & key);
966
template void DataManager::setData<PointData>(std::string const & key, TimeKey const & time_key);
967
template void DataManager::setData<PointData>(std::string const & key, std::shared_ptr<PointData> data, TimeKey const & time_key);
968

969
template std::shared_ptr<TensorData> DataManager::getData<TensorData>(std::string const & key);
970
template void DataManager::setData<TensorData>(std::string const & key, TimeKey const & time_key);
971
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