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

paulmthompson / WhiskerToolbox / 14456034071

14 Apr 2025 09:22PM UTC coverage: 13.068% (+0.008%) from 13.06%
14456034071

push

github

paulmthompson
fix changed function names

210 of 1607 relevant lines covered (13.07%)

1.26 hits per line

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

4.29
/src/WhiskerToolbox/DataManager/DataManager.cpp
1

2
#include "DataManager.hpp"
3
#include "AnalogTimeSeries/Analog_Time_Series.hpp"
4
#include "DigitalTimeSeries/Digital_Event_Series.hpp"
5
#include "DigitalTimeSeries/Digital_Interval_Series.hpp"
6
#include "Lines/Line_Data.hpp"
7
#include "Masks/Mask_Data.hpp"
8
#include "Media/Video_Data.hpp"
9
#include "Points/Point_Data.hpp"
10
#include "Tensors/Tensor_Data.hpp"
11

12
#include "AnalogTimeSeries/Analog_Time_Series_Loader.hpp"
13
#include "DigitalTimeSeries/Digital_Event_Series_Loader.hpp"
14
#include "DigitalTimeSeries/Digital_Interval_Series_Loader.hpp"
15
#include "Masks/Mask_Data_Loader.hpp"
16
#include "Media/Video_Data_Loader.hpp"
17
#include "Points/Point_Data_Loader.hpp"
18

19
#include "loaders/binary_loaders.hpp"
20
#include "transforms/data_transforms.hpp"
21

22
#include "TimeFrame.hpp"
23

24
#include "nlohmann/json.hpp"
25
#include "utils/string_manip.hpp"
26

27
#include <filesystem>
28
#include <fstream>
29
#include <iostream>
30
#include <optional>
31
#include <regex>
32

33
using namespace nlohmann;
34

35
DataManager::DataManager() {
2✔
36
    _times["time"] = std::make_shared<TimeFrame>();
6✔
37
    _data["media"] = std::make_shared<MediaData>();
6✔
38

39
    setTimeFrame("media", "time");
10✔
40
    _output_path = std::filesystem::current_path();
2✔
41
}
2✔
42

43
void DataManager::setTimeFrame(std::string const & data_key, std::string const & time_key) {
2✔
44
    //Check that data_key is in _data
45
    if (_data.find(data_key) == _data.end()) {
2✔
46
        std::cerr << "Data key not found in DataManager: " << data_key << std::endl;
×
47
        return;
×
48
    }
49

50
    //Check that time_key is in _times
51
    if (_times.find(time_key) == _times.end()) {
2✔
52
        std::cerr << "Time key not found in DataManager: " << time_key << std::endl;
×
53
        return;
×
54
    }
55

56
    _time_frames[data_key] = time_key;
2✔
57
}
58

59
enum class DataType {
60
    Video,
61
    Points,
62
    Mask,
63
    Line,
64
    Analog,
65
    DigitalEvent,
66
    DigitalInterval,
67
    Tensor,
68
    Time,
69
    Unknown
70
};
71

72
DataType stringToDataType(std::string const & data_type_str) {
×
73
    if (data_type_str == "video") return DataType::Video;
×
74
    if (data_type_str == "points") return DataType::Points;
×
75
    if (data_type_str == "mask") return DataType::Mask;
×
76
    if (data_type_str == "line") return DataType::Line;
×
77
    if (data_type_str == "analog") return DataType::Analog;
×
78
    if (data_type_str == "digital_event") return DataType::DigitalEvent;
×
79
    if (data_type_str == "digital_interval") return DataType::DigitalInterval;
×
80
    if (data_type_str == "tensor") return DataType::Tensor;
×
81
    if (data_type_str == "time") return DataType::Time;
×
82
    return DataType::Unknown;
×
83
}
84

85
std::optional<std::string> processFilePath(
×
86
        std::string const & file_path,
87
        std::filesystem::path const & base_path) {
88
    std::filesystem::path full_path = file_path;
×
89

90
    // Check for wildcard character
91
    if (file_path.find('*') != std::string::npos) {
×
92
        // Convert wildcard pattern to regex
93
        std::string const pattern = std::regex_replace(full_path.string(), std::regex("\\*"), ".*");
×
94
        std::regex const regex_pattern(pattern);
×
95

96
        // Iterate through the directory to find matching files
97
        for (auto const & entry: std::filesystem::directory_iterator(base_path)) {
×
98
            std::cout << "Checking " << entry.path().string() << " with full path " << full_path << std::endl;
×
99
            if (std::regex_match(entry.path().string(), regex_pattern)) {
×
100
                std::cout << "Loading file " << entry.path().string() << std::endl;
×
101
                return entry.path().string();
×
102
            }
103
        }
×
104
        return std::nullopt;
×
105
    } else {
×
106
        // Check if the file path is relative
107
        if (!std::filesystem::path(file_path).is_absolute()) {
×
108
            full_path = base_path / file_path;
×
109
        }
110
        // Check for the presence of the file
111
        if (std::filesystem::exists(full_path)) {
×
112
            std::cout << "Loading file " << full_path.string() << std::endl;
×
113
            return full_path.string();
×
114
        } else {
115
            return std::nullopt;
×
116
        }
117
    }
118
}
×
119

120
bool checkRequiredFields(json const & item, std::vector<std::string> const & requiredFields) {
×
121
    for (auto const & field: requiredFields) {
×
122
        if (!item.contains(field)) {
×
123
            std::cerr << "Error: Missing required field \"" << field << "\" in JSON item." << std::endl;
×
124
            return false;
×
125
        }
126
    }
127
    return true;
×
128
}
129

130
int DataManager::addCallbackToData(std::string const & key, ObserverCallback callback) {
×
131

132
    int id = -1;
×
133

134
    if (_data.find(key) != _data.end()) {
×
135
        auto data = _data[key];
×
136

137
        id = std::visit([callback](auto & x) {
×
138
            return x.get()->addObserver(callback);
×
139
        },
140
                        data);
141
    }
×
142

143
    return id;
×
144
}
145

146
void DataManager::removeCallbackFromData(std::string const & key, int callback_id) {
×
147
    if (_data.find(key) != _data.end()) {
×
148
        auto data = _data[key];
×
149

150
        std::visit([callback_id](auto & x) {
×
151
            x.get()->removeObserver(callback_id);
×
152
        },
×
153
                   data);
154
    }
×
155
}
×
156

157
void checkOptionalFields(json const & item, std::vector<std::string> const & optionalFields) {
×
158
    for (auto const & field: optionalFields) {
×
159
        if (!item.contains(field)) {
×
160
            std::cout << "Warning: Optional field \"" << field << "\" is missing in JSON item." << std::endl;
×
161
        }
162
    }
163
}
×
164

165
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, std::string const & json_filepath) {
×
166
    std::vector<DataInfo> data_info_list;
×
167
    // Open JSON file
168
    std::ifstream ifs(json_filepath);
×
169
    if (!ifs.is_open()) {
×
170
        std::cerr << "Failed to open JSON file: " << json_filepath << std::endl;
×
171
        return data_info_list;
×
172
    }
173

174
    // Parse JSON
175
    json j;
×
176
    ifs >> j;
×
177

178
    // get base path of filepath
179
    std::filesystem::path const base_path = std::filesystem::path(json_filepath).parent_path();
×
180

181
    // Iterate through JSON array
182
    for (auto const & item: j) {
×
183

184
        if (!checkRequiredFields(item, {"data_type", "name", "filepath"})) {
×
185
            continue;// Exit if any required field is missing
×
186
        }
187

188
        std::string const data_type_str = item["data_type"];
×
189
        DataType const data_type = stringToDataType(data_type_str);
×
190
        if (data_type == DataType::Unknown) {
×
191
            std::cout << "Unknown data type: " << data_type_str << std::endl;
×
192
            continue;
×
193
        }
194

195
        std::string const name = item["name"];
×
196

197
        auto file_exists = processFilePath(item["filepath"], base_path);
×
198
        if (!file_exists) {
×
199
            std::cerr << "File does not exist: " << item["filepath"] << std::endl;
×
200
            continue;
×
201
        }
202

203
        std::string const file_path = file_exists.value();
×
204

205
        switch (data_type) {
×
206
            case DataType::Video: {
×
207
                // Create VideoData object
208
                auto video_data = load_video_into_VideoData(file_path);
×
209

210
                // Add VideoData to DataManager
211
                dm->setMedia(video_data);
×
212

213
                data_info_list.push_back({name, "VideoData", ""});
×
214
                break;
×
215
            }
×
216
            case DataType::Points: {
×
217

218
                auto point_data = load_into_PointData(file_path, item);
×
219

220
                dm->setData<PointData>(name, point_data);
×
221

222
                std::string const color = item.value("color", "#0000FF");
×
223
                data_info_list.push_back({name, "PointData", color});
×
224
                break;
×
225
            }
×
226
            case DataType::Mask: {
×
227

228
                auto mask_data = load_into_MaskData(file_path, item);
×
229

230
                std::string const color = item.value("color", "0000FF");
×
231
                dm->setData<MaskData>(name, mask_data);
×
232

233
                data_info_list.push_back({name, "MaskData", color});
×
234

235
                if (item.contains("operations")) {
×
236

237
                    for (auto const & operation: item["operations"]) {
×
238

239
                        std::string const operation_type = operation["type"];
×
240

241
                        if (operation_type == "area") {
×
242
                            std::cout << "Calculating area for mask: " << name << std::endl;
×
243
                            auto area_data = area(dm->getData<MaskData>(name));
×
244
                            std::string const output_name = name + "_area";
×
245
                            dm->setData<AnalogTimeSeries>(output_name, area_data);
×
246
                        }
×
247
                    }
×
248
                }
249
                break;
×
250
            }
×
251
            case DataType::Line: {
×
252

253
                auto line_map = load_line_csv(file_path);
×
254

255
                //Get the whisker name from the filename using filesystem
256
                auto whisker_filename = std::filesystem::path(file_path).filename().string();
×
257

258
                //Remove .csv suffix from filename
259
                auto whisker_name = remove_extension(whisker_filename);
×
260

261
                dm->setData<LineData>(whisker_name, std::make_shared<LineData>(line_map));
×
262

263
                std::string const color = item.value("color", "0000FF");
×
264

265
                data_info_list.push_back({name, "LineData", color});
×
266

267
                break;
×
268
            }
×
269
            case DataType::Analog: {
×
270

271
                auto analog_time_series = load_into_AnalogTimeSeries(file_path, item);
×
272

273
                for (int channel = 0; channel < analog_time_series.size(); channel++) {
×
274
                    std::string const channel_name = name + "_" + std::to_string(channel);
×
275

276
                    dm->setData<AnalogTimeSeries>(channel_name, analog_time_series[channel]);
×
277

278
                    if (item.contains("clock")) {
×
279
                        std::string const clock = item["clock"];
×
280
                        dm->setTimeFrame(channel_name, clock);
×
281
                    }
×
282
                }
×
283
                break;
×
284
            }
×
285
            case DataType::DigitalEvent: {
×
286

287
                auto digital_event_series = load_into_DigitalEventSeries(file_path, item);
×
288

289
                for (int channel = 0; channel < digital_event_series.size(); channel++) {
×
290
                    std::string const channel_name = name + "_" + std::to_string(channel);
×
291

292
                    dm->setData<DigitalEventSeries>(channel_name, digital_event_series[channel]);
×
293

294
                    if (item.contains("clock")) {
×
295
                        std::string const clock = item["clock"];
×
296
                        dm->setTimeFrame(channel_name, clock);
×
297
                    }
×
298
                }
×
299
                break;
×
300
            }
×
301
            case DataType::DigitalInterval: {
×
302

303
                auto digital_interval_series = load_into_DigitalIntervalSeries(file_path, item);
×
304
                dm->setData<DigitalIntervalSeries>(name, digital_interval_series);
×
305

306
                break;
×
307
            }
×
308
            case DataType::Tensor: {
×
309

310
                if (item["format"] == "numpy") {
×
311

312
                    TensorData tensor_data;
×
313
                    loadNpyToTensorData(file_path, tensor_data);
×
314

315
                    dm->setData<TensorData>(name, std::make_shared<TensorData>(tensor_data));
×
316

317
                } else {
×
318
                    std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
319
                }
320
                break;
×
321
            }
322
            case DataType::Time: {
×
323

324
                if (item["format"] == "uint16") {
×
325

326
                    int const channel = item["channel"];
×
327
                    std::string const transition = item["transition"];
×
328

329
                    int const header_size = item.value("header_size", 0);
×
330

331
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
332
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
333
                    auto data = readBinaryFile<uint16_t>(opts);
×
334

335
                    auto digital_data = Loader::extractDigitalData(data, channel);
×
336
                    auto events = Loader::extractEvents(digital_data, transition);
×
337

338
                    // convert to int with std::transform
339
                    std::vector<int> events_int;
×
340
                    events_int.reserve(events.size());
×
341
                    for (auto e: events) {
×
342
                        events_int.push_back(static_cast<int>(e));
×
343
                    }
344
                    std::cout << "Loaded " << events_int.size() << " events for " << name << std::endl;
×
345

346
                    auto timeframe = std::make_shared<TimeFrame>(events_int);
×
347
                    dm->setTime(name, timeframe);
×
348
                }
×
349

350
                if (item["format"] == "uint16_length") {
×
351

352
                    int const header_size = item.value("header_size", 0);
×
353

354
                    auto opts = Loader::BinaryAnalogOptions{.file_path = file_path,
×
355
                                                            .header_size_bytes = static_cast<size_t>(header_size)};
×
356
                    auto data = readBinaryFile<uint16_t>(opts);
×
357

358
                    std::vector<int> t(data.size());
×
359
                    std::iota(std::begin(t), std::end(t), 0);
×
360

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

363
                    auto timeframe = std::make_shared<TimeFrame>(t);
×
364
                    dm->setTime(name, timeframe);
×
365
                }
×
366
                break;
×
367
            }
368
            default:
×
369
                std::cout << "Unsupported data type: " << data_type_str << std::endl;
×
370
                continue;
×
371
        }
×
372
        if (item.contains("clock")) {
×
373
            std::string const clock = item["clock"];
×
374
            std::cout << "Setting time for " << name << " to " << clock << std::endl;
×
375
            dm->setTimeFrame(name, clock);
×
376
        }
×
377
    }
×
378

379
    return data_info_list;
380
}
×
381

382
std::string DataManager::getType(std::string const & key) const {
×
383
    auto it = _data.find(key);
×
384
    if (it != _data.end()) {
×
385
        if (std::holds_alternative<std::shared_ptr<MediaData>>(it->second)) {
×
386
            return "MediaData";
×
387
        } else if (std::holds_alternative<std::shared_ptr<PointData>>(it->second)) {
×
388
            return "PointData";
×
389
        } else if (std::holds_alternative<std::shared_ptr<LineData>>(it->second)) {
×
390
            return "LineData";
×
391
        } else if (std::holds_alternative<std::shared_ptr<MaskData>>(it->second)) {
×
392
            return "MaskData";
×
393
        } else if (std::holds_alternative<std::shared_ptr<AnalogTimeSeries>>(it->second)) {
×
394
            return "AnalogTimeSeries";
×
395
        } else if (std::holds_alternative<std::shared_ptr<DigitalEventSeries>>(it->second)) {
×
396
            return "DigitalEventSeries";
×
397
        } else if (std::holds_alternative<std::shared_ptr<DigitalIntervalSeries>>(it->second)) {
×
398
            return "DigitalIntervalSeries";
×
399
        } else if (std::holds_alternative<std::shared_ptr<TensorData>>(it->second)) {
×
400
            return "TensorData";
×
401
        }
402
        return "Unknown";
×
403
    }
404
}
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