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

paulmthompson / WhiskerToolbox / 17282283436

28 Aug 2025 12:35AM UTC coverage: 66.075% (-0.2%) from 66.266%
17282283436

push

github

web-flow
Merge pull request #104 from paulmthompson/feature/analog-filter

feat: Implement Analog Filter transform

152 of 179 new or added lines in 4 files covered. (84.92%)

25 existing lines in 3 files now uncovered.

26703 of 40413 relevant lines covered (66.08%)

1115.66 hits per line

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

47.85
/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
#include "transforms/Masks/mask_area.hpp"
35

36
#include "TimeFrame/TimeFrame.hpp"
37

38
#include "nlohmann/json.hpp"
39

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

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

106
                            // Handle operations if present (same as legacy)
107
                            if (item.contains("operations")) {
1✔
108
                                for (auto const & operation: item["operations"]) {
×
109
                                    std::string const operation_type = operation["type"];
×
110
                                    if (operation_type == "area") {
×
111
                                        std::cout << "Calculating area for mask: " << name << std::endl;
×
112
                                        auto area_data = area(dm->getData<MaskData>(name).get());
×
113
                                        std::string const output_name = name + "_area";
×
114
                                        dm->setData<AnalogTimeSeries>(output_name, area_data, TimeKey("time"));
×
115
                                    }
×
116
                                }
×
117
                            }
118
                        }
1✔
119
                        break;
1✔
120
                    }
121
                    // Add other data types as they get plugin support...
122
                    default:
×
123
                        std::cerr << "Registry loaded unsupported data type: " << static_cast<int>(data_type) << std::endl;
×
124
                        return false;
×
125
                }
126

127
                return true;
3✔
128
            } else {
129
                std::cout << "Registry loading failed for " << name << ": " << result.error_message
130
                          << ", falling back to legacy loader" << std::endl;
1✔
131
            }
132
        }
4✔
133
    }
4✔
134

135
    return false;// Indicates we should use legacy loading
1✔
136
}
9✔
137

138
DataManager::DataManager() {
192✔
139
    _times[TimeKey("time")] = std::make_shared<TimeFrame>();
192✔
140
    _data["media"] = std::make_shared<EmptyMediaData>();
576✔
141

142
    setTimeKey("media", TimeKey("time"));
576✔
143
    _output_path = std::filesystem::current_path();
192✔
144

145
    // Initialize TableRegistry
146
    _table_registry = std::make_unique<TableRegistry>(*this);
192✔
147

148
    // Initialize EntityRegistry
149
    _entity_registry = std::make_unique<EntityRegistry>();
192✔
150

151
    // Register all available loaders
152
    static bool loaders_registered = false;
153
    if (!loaders_registered) {
192✔
154
        registerAllLoaders();
91✔
155
        loaders_registered = true;
91✔
156
    }
157
}
192✔
158

159
DataManager::~DataManager() = default;
192✔
160

161
void DataManager::reset() {
×
162
    std::cout << "DataManager: Resetting to initial state..." << std::endl;
×
163

164
    // Clear all data objects except media (which we'll reset)
165
    _data.clear();
×
166

167
    // Reset media to a fresh empty MediaData object
168
    _data["media"] = std::make_shared<EmptyMediaData>();
×
169

170
    // Clear all TimeFrame objects except the default "time" frame
171
    _times.clear();
×
172

173
    // Recreate the default "time" TimeFrame
174
    _times[TimeKey("time")] = std::make_shared<TimeFrame>();
×
175

176
    // Clear all data-to-timeframe mappings and recreate the default media mapping
177
    _time_frames.clear();
×
178
    setTimeKey("media", TimeKey("time"));
×
179

180

181
    // Reset current time
182
    _current_time = 0;
×
183

184
    // Notify observers that the state has changed
185
    _notifyObservers();
×
186

187
    std::cout << "DataManager: Reset complete. Default 'time' frame and 'media' data restored." << std::endl;
×
188

189
    // Reset entity registry for a new session context
190
    if (_entity_registry) {
×
NEW
191
        _entity_registry->clear();
×
192
    }
193
}
×
194

195
bool DataManager::setTime(TimeKey const & key, std::shared_ptr<TimeFrame> timeframe, bool overwrite) {
202✔
196

197
    if (!timeframe) {
202✔
198
        std::cerr << "Error: Cannot register a nullptr TimeFrame for key: " << key << std::endl;
1✔
199
        return false;
1✔
200
    }
201

202
    if (_times.find(key) != _times.end()) {
201✔
203
        if (!overwrite) {
6✔
204
            std::cerr << "Error: Time key already exists in DataManager: " << key << std::endl;
2✔
205
            return false;
2✔
206
        }
207
    }
208

209
    _times[key] = std::move(timeframe);
199✔
210

211
    // Move ptr to new time frame to all data that hold
212
    for (auto const & [data_key, data]: _data) {
399✔
213
        if (_time_frames.find(data_key) != _time_frames.end()) {
200✔
214
            auto time_key = _time_frames[data_key];
200✔
215
            if (time_key == key) {
200✔
216
                std::visit([this, timeframe](auto & x) {
8✔
217
                    x->setTimeFrame(timeframe);
4✔
218
                },
4✔
219
                           data);
220
            }
221
        }
200✔
222
    }
223

224
    return true;
199✔
225
}
226

227
std::shared_ptr<TimeFrame> DataManager::getTime() {
8✔
228
    return _times[TimeKey("time")];
8✔
229
};
230

231
std::shared_ptr<TimeFrame> DataManager::getTime(TimeKey const & key) {
179✔
232
    if (_times.find(key) != _times.end()) {
179✔
233
        return _times[key];
177✔
234
    }
235
    return nullptr;
2✔
236
};
237

238
TimeIndexAndFrame DataManager::getCurrentIndexAndFrame(TimeKey const & key) {
×
239
    if (_times.find(key) != _times.end()) {
×
240
        return {TimeFrameIndex(_current_time), _times[key]};
×
241
    }
242
    return {TimeFrameIndex(_current_time), nullptr};
×
243
}
×
244

245
bool DataManager::removeTime(TimeKey const & key) {
×
246
    if (_times.find(key) == _times.end()) {
×
247
        std::cerr << "Error: could not find time key in DataManager: " << key << std::endl;
×
248
        return false;
×
249
    }
250

251
    auto it = _times.find(key);
×
252
    _times.erase(it);
×
253
    return true;
×
254
}
255

256
bool DataManager::setTimeKey(std::string const & data_key, TimeKey const & time_key) {
632✔
257
    if (_data.find(data_key) == _data.end()) {
632✔
258
        std::cerr << "Error: Data key not found in DataManager: " << data_key << std::endl;
3✔
259
        return false;
3✔
260
    }
261

262
    if (_times.find(time_key) == _times.end()) {
629✔
263
        std::cerr << "Error: Time key not found in DataManager: " << time_key << std::endl;
1✔
264
        return false;
1✔
265
    }
266

267
    _time_frames[data_key] = time_key;
628✔
268

269
    if (_data.find(data_key) != _data.end()) {
628✔
270
        auto data = _data[data_key];
628✔
271
        std::visit([this, time_key](auto & x) {
1,256✔
272
            x->setTimeFrame(this->_times[time_key]);
628✔
273
        },
628✔
274
                   data);
275
    }
628✔
276
    return true;
628✔
277
}
278

279
TimeKey DataManager::getTimeKey(std::string const & data_key) {
132✔
280
    // check if data_key exists
281
    if (_data.find(data_key) == _data.end()) {
132✔
282
        std::cerr << "Error: Data key not found in DataManager: " << data_key << std::endl;
1✔
283
        return TimeKey("");
1✔
284
    }
285

286
    // check if data key has time frame
287
    if (_time_frames.find(data_key) == _time_frames.end()) {
131✔
288
        std::cerr << "Error: Data key "
289
                  << data_key
290
                  << " exists, but not assigned to a TimeFrame" << std::endl;
×
291
        return TimeKey("");
×
292
    }
293

294
    return _time_frames[data_key];
131✔
295
}
296

297
std::vector<TimeKey> DataManager::getTimeFrameKeys() {
8✔
298
    std::vector<TimeKey> keys;
8✔
299
    keys.reserve(_times.size());
8✔
300
    for (auto const & [key, value]: _times) {
24✔
301

302
        keys.push_back(key);
16✔
303
    }
304
    return keys;
8✔
305
}
×
306

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

309
    int id = -1;
7✔
310

311
    if (_data.find(key) != _data.end()) {
7✔
312
        auto data = _data[key];
6✔
313

314
        id = std::visit([callback](auto & x) {
12✔
315
            return x.get()->addObserver(callback);
6✔
316
        },
317
                        data);
318
    }
6✔
319

320
    return id;
7✔
321
}
322

323
bool DataManager::removeCallbackFromData(std::string const & key, int callback_id) {
4✔
324
    if (_data.find(key) != _data.end()) {
4✔
325
        auto data = _data[key];
3✔
326

327
        std::visit([callback_id](auto & x) {
6✔
328
            x.get()->removeObserver(callback_id);
3✔
329
        },
3✔
330
                   data);
331

332
        return true;
3✔
333
    }
3✔
334

335
    return false;
1✔
336
}
337

338
void DataManager::addObserver(ObserverCallback callback) {
6✔
339
    _observers.push_back(std::move(callback));
6✔
340
}
6✔
341

342
void DataManager::_notifyObservers() {
434✔
343
    for (auto & observer: _observers) {
442✔
344
        observer();
8✔
345
    }
346
}
434✔
347

348
// ===== Table Registry accessors =====
349
TableRegistry * DataManager::getTableRegistry() {
47✔
350
    return _table_registry.get();
47✔
351
}
352

353
TableRegistry const * DataManager::getTableRegistry() const {
×
354
    return _table_registry.get();
×
355
}
356

357
// ===== Table observer channel =====
358
int DataManager::addTableObserver(TableObserver callback) {
×
359
    if (!callback) return -1;
×
360
    int id = _next_table_observer_id++;
×
361
    _table_observers[id] = std::move(callback);
×
362
    return id;
×
363
}
364

365
bool DataManager::removeTableObserver(int callback_id) {
×
366
    return _table_observers.erase(callback_id) > 0;
×
367
}
368

369
void DataManager::notifyTableObservers(TableEvent const & ev) {
43✔
370
    for (auto const & [id, cb]: _table_observers) {
43✔
371
        (void) id;
UNCOV
372
        cb(ev);
×
373
    }
374
}
43✔
375

376
// Provide C-style bridge for TableRegistry to call
377
void DataManager__NotifyTableObservers(DataManager & dm, TableEvent const & ev) {
43✔
378
    dm.notifyTableObservers(ev);
43✔
379
}
43✔
380

381
std::vector<std::string> DataManager::getAllKeys() {
5✔
382
    std::vector<std::string> keys;
5✔
383
    keys.reserve(_data.size());
5✔
384
    for (auto const & [key, value]: _data) {
17✔
385

386
        keys.push_back(key);
12✔
387
    }
388
    return keys;
5✔
389
}
×
390

391
std::optional<DataTypeVariant> DataManager::getDataVariant(std::string const & key) {
1✔
392
    if (_data.find(key) != _data.end()) {
1✔
393
        return _data[key];
1✔
394
    }
395
    return std::nullopt;
×
396
}
397

398
void DataManager::setData(std::string const & key, DataTypeVariant data, TimeKey const & time_key) {
2✔
399
    _data[key] = data;
2✔
400
    setTimeKey(key, time_key);
2✔
401
    _notifyObservers();
2✔
402
}
2✔
403

404
std::optional<std::string> processFilePath(
12✔
405
        std::string const & file_path,
406
        std::filesystem::path const & base_path) {
407
    std::filesystem::path full_path = file_path;
12✔
408

409
    // Check for wildcard character
410
    if (file_path.find('*') != std::string::npos) {
12✔
411
        // Convert wildcard pattern to regex
412
        std::string const pattern = std::regex_replace(full_path.string(), std::regex("\\*"), ".*");
×
413
        std::regex const regex_pattern(pattern);
×
414

415
        // Iterate through the directory to find matching files
416
        for (auto const & entry: std::filesystem::directory_iterator(base_path)) {
×
417
            std::cout << "Checking " << entry.path().string() << " with full path " << full_path << std::endl;
×
418
            if (std::regex_match(entry.path().string(), regex_pattern)) {
×
419
                std::cout << "Loading file " << entry.path().string() << std::endl;
×
420
                return entry.path().string();
×
421
            }
422
        }
×
423
        return std::nullopt;
×
424
    } else {
×
425
        // Check if the file path is relative
426
        if (!std::filesystem::path(file_path).is_absolute()) {
12✔
427
            full_path = base_path / file_path;
×
428
        }
429
        // Check for the presence of the file
430
        if (std::filesystem::exists(full_path)) {
12✔
431
            std::cout << "Loading file " << full_path.string() << std::endl;
6✔
432
            return full_path.string();
6✔
433
        } else {
434
            return std::nullopt;
6✔
435
        }
436
    }
437
}
12✔
438

439
bool checkRequiredFields(json const & item, std::vector<std::string> const & requiredFields) {
12✔
440
    for (auto const & field: requiredFields) {
48✔
441
        if (!item.contains(field)) {
36✔
442
            std::cerr << "Error: Missing required field \"" << field << "\" in JSON item." << std::endl;
×
443
            return false;
×
444
        }
445
    }
446
    return true;
12✔
447
}
448

449
void checkOptionalFields(json const & item, std::vector<std::string> const & optionalFields) {
×
450
    for (auto const & field: optionalFields) {
×
451
        if (!item.contains(field)) {
×
452
            std::cout << "Warning: Optional field \"" << field << "\" is missing in JSON item." << std::endl;
×
453
        }
454
    }
455
}
×
456

457
DM_DataType stringToDataType(std::string const & data_type_str) {
12✔
458
    if (data_type_str == "video") return DM_DataType::Video;
12✔
459
    if (data_type_str == "images") return DM_DataType::Images;
12✔
460
    if (data_type_str == "points") return DM_DataType::Points;
12✔
461
    if (data_type_str == "mask") return DM_DataType::Mask;
12✔
462
    if (data_type_str == "line") return DM_DataType::Line;
10✔
463
    if (data_type_str == "analog") return DM_DataType::Analog;
4✔
464
    if (data_type_str == "digital_event") return DM_DataType::DigitalEvent;
2✔
465
    if (data_type_str == "digital_interval") return DM_DataType::DigitalInterval;
2✔
466
    if (data_type_str == "tensor") return DM_DataType::Tensor;
×
467
    if (data_type_str == "time") return DM_DataType::Time;
×
468
    return DM_DataType::Unknown;
×
469
}
470

471
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, json const & j, std::filesystem::path const & base_path) {
12✔
472
    std::vector<DataInfo> data_info_list;
12✔
473
    // Create factory for plugin system
474
    ConcreteDataFactory factory;
12✔
475

476
    // Iterate through JSON array
477
    for (auto const & item: j) {
24✔
478

479
        // Skip transformation objects - they will be processed separately
480
        if (item.contains("transformations")) {
12✔
481
            continue;
×
482
        }
483

484
        if (!checkRequiredFields(item, {"data_type", "name", "filepath"})) {
36✔
485
            continue;// Exit if any required field is missing
×
486
        }
487

488
        std::string const data_type_str = item["data_type"];
12✔
489
        auto const data_type = stringToDataType(data_type_str);
12✔
490
        if (data_type == DM_DataType::Unknown) {
12✔
491
            std::cout << "Unknown data type: " << data_type_str << std::endl;
×
492
            continue;
×
493
        }
494

495
        std::string const name = item["name"];
12✔
496

497
        auto file_exists = processFilePath(item["filepath"], base_path);
12✔
498
        if (!file_exists) {
12✔
499
            std::cerr << "File does not exist: " << item["filepath"] << std::endl;
6✔
500
            continue;
6✔
501
        }
502

503
        std::string const file_path = file_exists.value();
6✔
504

505
        switch (data_type) {
6✔
506
            case DM_DataType::Video: {
×
507
                auto media_data = MediaDataFactory::loadMediaData(data_type, file_path, item);
×
508
                if (media_data) {
×
509
                    dm->setData<MediaData>("media", media_data, TimeKey("time"));
×
510
                    data_info_list.push_back({name, "VideoData", ""});
×
511
                } else {
512
                    std::cerr << "Failed to load video data: " << file_path << std::endl;
×
513
                }
514
                break;
×
515
            }
×
516
#ifdef ENABLE_OPENCV
517
            case DM_DataType::Images: {
×
518
                auto media_data = MediaDataFactory::loadMediaData(data_type, file_path, item);
×
519
                if (media_data) {
×
520
                    dm->setData<MediaData>("media", media_data, TimeKey("time"));
×
521
                    data_info_list.push_back({name, "ImageData", ""});
×
522
                } else {
523
                    std::cerr << "Failed to load image data: " << file_path << std::endl;
×
524
                }
525
                break;
×
526
            }
×
527
#endif
528
            case DM_DataType::Points: {
×
529

530
                auto point_data = load_into_PointData(file_path, item);
×
531

532
                // Attach identity context and generate EntityIds
533
                if (point_data) {
×
534
                    point_data->setIdentityContext(name, dm->getEntityRegistry());
×
535
                    point_data->rebuildAllEntityIds();
×
536
                }
537

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

540
                std::string const color = item.value("color", "#0000FF");
×
541
                data_info_list.push_back({name, "PointData", color});
×
542
                break;
×
543
            }
×
544
            case DM_DataType::Mask: {
1✔
545

546
                // Try registry system first, then fallback to legacy
547
                if (tryRegistryThenLegacyLoad(dm, file_path, data_type, item, name, data_info_list, &factory)) {
1✔
548
                    break;// Successfully loaded with plugin
1✔
549
                }
550

551
                // Legacy loading fallback
552
                auto mask_data = load_into_MaskData(file_path, item);
×
553

554
                std::string const color = item.value("color", "0000FF");
×
555
                dm->setData<MaskData>(name, mask_data, TimeKey("time"));
×
556

557
                data_info_list.push_back({name, "MaskData", color});
×
558

559
                if (item.contains("operations")) {
×
560

561
                    for (auto const & operation: item["operations"]) {
×
562

563
                        std::string const operation_type = operation["type"];
×
564

565
                        if (operation_type == "area") {
×
566
                            std::cout << "Calculating area for mask: " << name << std::endl;
×
567
                            auto area_data = area(dm->getData<MaskData>(name).get());
×
568
                            std::string const output_name = name + "_area";
×
569
                            dm->setData<AnalogTimeSeries>(output_name, area_data, TimeKey("time"));
×
570
                        }
×
571
                    }
×
572
                }
573
                break;
×
574
            }
×
575
            case DM_DataType::Line: {
3✔
576

577
                // Try registry system first, then fallback to legacy
578
                if (tryRegistryThenLegacyLoad(dm, file_path, data_type, item, name, data_info_list, &factory)) {
3✔
579
                    break;// Successfully loaded with plugin
2✔
580
                }
581

582
                // Legacy loading fallback
583
                auto line_data = load_into_LineData(file_path, item);
1✔
584

585
                // Attach identity context and generate EntityIds
586
                if (line_data) {
1✔
587
                    line_data->setIdentityContext(name, dm->getEntityRegistry());
1✔
588
                    line_data->rebuildAllEntityIds();
1✔
589
                }
590

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

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

595
                data_info_list.push_back({name, "LineData", color});
3✔
596

597
                break;
1✔
598
            }
1✔
599
            case DM_DataType::Analog: {
1✔
600

601
                auto analog_time_series = load_into_AnalogTimeSeries(file_path, item);
1✔
602

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

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

608
                    if (item.contains("clock")) {
1✔
609
                        std::string const clock_str = item["clock"];
×
610
                        auto const clock = TimeKey(clock_str);
×
611
                        dm->setTimeKey(channel_name, clock);
×
612
                    }
×
613
                }
1✔
614
                break;
1✔
615
            }
1✔
616
            case DM_DataType::DigitalEvent: {
×
617

618
                auto digital_event_series = load_into_DigitalEventSeries(file_path, item);
×
619

620
                for (size_t channel = 0; channel < digital_event_series.size(); channel++) {
×
621
                    std::string const channel_name = name + "_" + std::to_string(channel);
×
622

623
                    // Attach identity context and generate EntityIds
624
                    if (digital_event_series[channel]) {
×
625
                        digital_event_series[channel]->setIdentityContext(channel_name, dm->getEntityRegistry());
×
626
                        digital_event_series[channel]->rebuildAllEntityIds();
×
627
                    }
628

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

631
                    if (item.contains("clock")) {
×
632
                        std::string const clock_str = item["clock"];
×
633
                        auto const clock = TimeKey(clock_str);
×
634
                        dm->setTimeKey(channel_name, clock);
×
635
                    }
×
636
                }
×
637
                break;
×
638
            }
×
639
            case DM_DataType::DigitalInterval: {
1✔
640

641
                auto digital_interval_series = load_into_DigitalIntervalSeries(file_path, item);
1✔
642
                if (digital_interval_series) {
1✔
643
                    digital_interval_series->setIdentityContext(name, dm->getEntityRegistry());
1✔
644
                    digital_interval_series->rebuildAllEntityIds();
1✔
645
                }
646
                dm->setData<DigitalIntervalSeries>(name, digital_interval_series, TimeKey("time"));
1✔
647

648
                break;
1✔
649
            }
1✔
650
            case DM_DataType::Tensor: {
×
651

652
                if (item["format"] == "numpy") {
×
653

654
                    TensorData tensor_data;
×
655
                    loadNpyToTensorData(file_path, tensor_data);
×
656

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

659
                } else {
×
660
                    std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
661
                }
662
                break;
×
663
            }
664
            case DM_DataType::Time: {
×
665

666
                if (item["format"] == "uint16") {
×
667

668
                    int const channel = item["channel"];
×
669
                    std::string const transition = item["transition"];
×
670

671
                    int const header_size = item.value("header_size", 0);
×
672

673
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
674
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
675
                    auto data = Loader::readBinaryFile<uint16_t>(opts);
×
676

677
                    auto digital_data = Loader::extractDigitalData(data, channel);
×
678
                    auto events = Loader::extractEvents(digital_data, transition);
×
679

680
                    // convert to int with std::transform
681
                    std::vector<int> events_int;
×
682
                    events_int.reserve(events.size());
×
683
                    for (auto e: events) {
×
684
                        events_int.push_back(static_cast<int>(e));
×
685
                    }
686
                    std::cout << "Loaded " << events_int.size() << " events for " << name << std::endl;
×
687

688
                    auto timeframe = std::make_shared<TimeFrame>(events_int);
×
689
                    dm->setTime(TimeKey(name), timeframe, true);
×
690
                }
×
691

692
                if (item["format"] == "uint16_length") {
×
693

694
                    int const header_size = item.value("header_size", 0);
×
695

696
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
697
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
698
                    auto data = Loader::readBinaryFile<uint16_t>(opts);
×
699

700
                    std::vector<int> t(data.size());
×
701
                    std::iota(std::begin(t), std::end(t), 0);
×
702

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

705
                    auto timeframe = std::make_shared<TimeFrame>(t);
×
706
                    dm->setTime(TimeKey(name), timeframe, true);
×
707
                }
×
708

709
                if (item["format"] == "filename") {
×
710

711
                    // Get required parameters
712
                    std::string const folder_path = file_path;// file path is required argument
×
713
                    std::string const regex_pattern = item["regex_pattern"];
×
714

715
                    // Get optional parameters with defaults
716
                    std::string const file_extension = item.value("file_extension", "");
×
717
                    std::string const mode_str = item.value("mode", "found_values");
×
718
                    bool const sort_ascending = item.value("sort_ascending", true);
×
719

720
                    // Convert mode string to enum
721
                    FilenameTimeFrameMode mode = FilenameTimeFrameMode::FOUND_VALUES;
×
722
                    if (mode_str == "zero_to_max") {
×
723
                        mode = FilenameTimeFrameMode::ZERO_TO_MAX;
×
724
                    } else if (mode_str == "min_to_max") {
×
725
                        mode = FilenameTimeFrameMode::MIN_TO_MAX;
×
726
                    }
727

728
                    // Create options
729
                    FilenameTimeFrameOptions options;
×
730
                    options.folder_path = folder_path;
×
731
                    options.file_extension = file_extension;
×
732
                    options.regex_pattern = regex_pattern;
×
733
                    options.mode = mode;
×
734
                    options.sort_ascending = sort_ascending;
×
735

736
                    // Create TimeFrame from filenames
737
                    auto timeframe = createTimeFrameFromFilenames(options);
×
738
                    if (timeframe) {
×
739
                        dm->setTime(TimeKey(name), timeframe, true);
×
740
                        std::cout << "Created TimeFrame '" << name << "' from filenames in "
741
                                  << folder_path << std::endl;
×
742
                    } else {
743
                        std::cerr << "Error: Failed to create TimeFrame from filenames for "
744
                                  << name << std::endl;
×
745
                    }
746
                }
×
747
                break;
×
748
            }
749
            default:
×
750
                std::cout << "Unsupported data type: " << data_type_str << std::endl;
×
751
                continue;
×
752
        }
×
753
        if (item.contains("clock")) {
6✔
754
            std::string clock_str = item["clock"];
×
755
            auto clock = TimeKey(clock_str);
×
756
            std::cout << "Setting time for " << name << " to " << clock << std::endl;
×
757
            dm->setTimeKey(name, clock);
×
758
        }
×
759
    }
24✔
760

761
    // Process all transformation objects found in the JSON array
762
    for (auto const & item: j) {
24✔
763
        if (item.contains("transformations")) {
12✔
764
            std::cout << "Found transformations section, executing pipeline..." << std::endl;
×
765

766
            try {
767
                // Create registry and pipeline with proper constructors
768
                auto registry = std::make_unique<TransformRegistry>();
×
769
                TransformPipeline pipeline(dm, registry.get());
×
770

771
                // Load the pipeline configuration from JSON
772
                if (!pipeline.loadFromJson(item["transformations"])) {
×
773
                    std::cerr << "Failed to load pipeline configuration from JSON" << std::endl;
×
774
                    continue;
×
775
                }
776

777
                // Execute the pipeline with a progress callback
NEW
778
                auto result = pipeline.execute([](int step_index, std::string const & step_name, int step_progress, int overall_progress) {
×
NEW
779
                    std::cout << "Step " << step_index << " ('" << step_name << "'): "
×
780
                              << step_progress << "% (Overall: " << overall_progress << "%)" << std::endl;
×
781
                });
×
782

783
                if (result.success) {
×
784
                    std::cout << "Pipeline executed successfully!" << std::endl;
×
785
                    std::cout << "Steps completed: " << result.steps_completed << "/" << result.total_steps << std::endl;
×
786
                    std::cout << "Total execution time: " << result.total_execution_time_ms << " ms" << std::endl;
×
787
                } else {
788
                    std::cerr << "Pipeline execution failed: " << result.error_message << std::endl;
×
789
                }
790

NEW
791
            } catch (std::exception const & e) {
×
792
                std::cerr << "Exception during pipeline execution: " << e.what() << std::endl;
×
793
            }
×
794
        }
795
    }
796

797
    return data_info_list;
12✔
798
}
15✔
799

800
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, std::string const & json_filepath) {
12✔
801
    // Open JSON file
802
    std::ifstream ifs(json_filepath);
12✔
803
    if (!ifs.is_open()) {
12✔
NEW
804
        std::cerr << "Failed to open JSON file: " << json_filepath << std::endl;
×
NEW
805
        return {};
×
806
    }
807

808
    // Parse JSON
809
    json j;
12✔
810
    ifs >> j;
12✔
811

812
    // get base path of filepath
813
    std::filesystem::path const base_path = std::filesystem::path(json_filepath).parent_path();
12✔
814
    return load_data_from_json_config(dm, j, base_path);
12✔
815
}
12✔
816

817
DM_DataType DataManager::getType(std::string const & key) const {
25✔
818
    auto it = _data.find(key);
25✔
819
    if (it != _data.end()) {
25✔
820
        if (std::holds_alternative<std::shared_ptr<MediaData>>(it->second)) {
22✔
821
            auto media_data = std::get<std::shared_ptr<MediaData>>(it->second);
18✔
822
            switch (media_data->getMediaType()) {
18✔
823
                case MediaData::MediaType::Video:
11✔
824
                    return DM_DataType::Video;
11✔
825
                case MediaData::MediaType::Images:
7✔
826
                    return DM_DataType::Images;
7✔
827
                case MediaData::MediaType::HDF5:
×
828
                    // For HDF5, we might need additional logic to determine if it's video or images
829
                    // For now, defaulting to Video (old behavior)
830
                    return DM_DataType::Video;
×
831
                default:
×
NEW
832
                    return DM_DataType::Video;// Old behavior for unknown types
×
833
            }
834
        } else if (std::holds_alternative<std::shared_ptr<PointData>>(it->second)) {
22✔
835
            return DM_DataType::Points;
2✔
836
        } else if (std::holds_alternative<std::shared_ptr<LineData>>(it->second)) {
2✔
837
            return DM_DataType::Line;
1✔
838
        } else if (std::holds_alternative<std::shared_ptr<MaskData>>(it->second)) {
1✔
839
            return DM_DataType::Mask;
1✔
840
        } else if (std::holds_alternative<std::shared_ptr<AnalogTimeSeries>>(it->second)) {
×
841
            return DM_DataType::Analog;
×
842
        } else if (std::holds_alternative<std::shared_ptr<DigitalEventSeries>>(it->second)) {
×
843
            return DM_DataType::DigitalEvent;
×
844
        } else if (std::holds_alternative<std::shared_ptr<DigitalIntervalSeries>>(it->second)) {
×
845
            return DM_DataType::DigitalInterval;
×
846
        } else if (std::holds_alternative<std::shared_ptr<TensorData>>(it->second)) {
×
847
            return DM_DataType::Tensor;
×
848
        }
849
        return DM_DataType::Unknown;
×
850
    }
851
    return DM_DataType::Unknown;
3✔
852
}
853

854
std::string convert_data_type_to_string(DM_DataType type) {
×
855
    switch (type) {
×
856
        case DM_DataType::Video:
×
857
            return "video";
×
858
        case DM_DataType::Images:
×
859
            return "images";
×
860
        case DM_DataType::Points:
×
861
            return "points";
×
862
        case DM_DataType::Mask:
×
863
            return "mask";
×
864
        case DM_DataType::Line:
×
865
            return "line";
×
866
        case DM_DataType::Analog:
×
867
            return "analog";
×
868
        case DM_DataType::DigitalEvent:
×
869
            return "digital_event";
×
870
        case DM_DataType::DigitalInterval:
×
871
            return "digital_interval";
×
872
        case DM_DataType::Tensor:
×
873
            return "tensor";
×
874
        case DM_DataType::Time:
×
875
            return "time";
×
876
        default:
×
877
            return "unknown";
×
878
    }
879
}
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