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

paulmthompson / WhiskerToolbox / 14228144741

02 Apr 2025 07:21PM UTC coverage: 14.524% (-0.04%) from 14.564%
14228144741

push

github

paulmthompson
can load in CSV file of events and it displays with analog data frame

0 of 11 new or added lines in 1 file covered. (0.0%)

209 of 1439 relevant lines covered (14.52%)

1.41 hits per line

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

3.46
/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 "loaders/CSV_Loaders.hpp"
13
#include "loaders/binary_loaders.hpp"
14
#include "transforms/data_transforms.hpp"
15

16
#include "TimeFrame.hpp"
17

18
#include "utils/container.hpp"
19
#include "utils/glob.hpp"
20
#include "utils/hdf5_mask_load.hpp"
21

22
#include "nlohmann/json.hpp"
23
#include "utils/string_manip.hpp"
24

25
#include <filesystem>
26
#include <fstream>
27
#include <iostream>
28
#include <optional>
29
#include <regex>
30

31
using namespace nlohmann;
32

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

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

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

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

54
    _time_frames[data_key] = time_key;
2✔
55
}
56

57
std::vector<std::vector<float>> read_ragged_hdf5(std::string const & filepath, std::string const & key) {
×
58
    auto myvector = load_ragged_array<float>(filepath, key);
×
59
    return myvector;
×
60
}
61

62
std::vector<int> read_array_hdf5(std::string const & filepath, std::string const & key) {
×
63
    auto myvector = load_array<int>(filepath, key);
×
64
    return myvector;
×
65
}
66

67
std::optional<std::string> processFilePath(
×
68
        std::string const & file_path,
69
        std::filesystem::path const & base_path) {
70
    std::filesystem::path full_path = file_path;
×
71

72
    // Check for wildcard character
73
    if (file_path.find('*') != std::string::npos) {
×
74
        // Convert wildcard pattern to regex
75
        std::string const pattern = std::regex_replace(full_path.string(), std::regex("\\*"), ".*");
×
76
        std::regex const regex_pattern(pattern);
×
77

78
        // Iterate through the directory to find matching files
79
        for (auto const & entry: std::filesystem::directory_iterator(base_path)) {
×
80
            std::cout << "Checking " << entry.path().string() << " with full path " << full_path << std::endl;
×
81
            if (std::regex_match(entry.path().string(), regex_pattern)) {
×
82
                std::cout << "Loading file " << entry.path().string() << std::endl;
×
83
                return entry.path().string();
×
84
            }
85
        }
×
86
        return std::nullopt;
×
87
    } else {
×
88
        // Check if the file path is relative
89
        if (!std::filesystem::path(file_path).is_absolute()) {
×
90
            full_path = base_path / file_path;
×
91
        }
92
        // Check for the presence of the file
93
        if (std::filesystem::exists(full_path)) {
×
94
            std::cout << "Loading file " << full_path.string() << std::endl;
×
95
            return full_path.string();
×
96
        } else {
97
            return std::nullopt;
×
98
        }
99
    }
100
}
×
101

102
bool checkRequiredFields(json const & item, std::vector<std::string> const & requiredFields) {
×
103
    for (auto const & field: requiredFields) {
×
104
        if (!item.contains(field)) {
×
105
            std::cerr << "Error: Missing required field \"" << field << "\" in JSON item." << std::endl;
×
106
            return false;
×
107
        }
108
    }
109
    return true;
×
110
}
111

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

114
    int id = -1;
×
115

116
    if (_data.find(key) != _data.end()) {
×
117
        auto data = _data[key];
×
118

119
        id = std::visit([callback](auto & x) {
×
120
            return x.get()->addObserver(callback);
×
121
        },
122
                        data);
123
    }
×
124

125
    return id;
×
126
}
127

128
void DataManager::removeCallbackFromData(std::string const & key, int callback_id) {
×
129
    if (_data.find(key) != _data.end()) {
×
130
        auto data = _data[key];
×
131

132
        std::visit([callback_id](auto & x) {
×
133
            x.get()->removeObserver(callback_id);
×
134
        },
×
135
                   data);
136
    }
×
137
}
×
138

139
void checkOptionalFields(json const & item, std::vector<std::string> const & optionalFields) {
×
140
    for (auto const & field: optionalFields) {
×
141
        if (!item.contains(field)) {
×
142
            std::cout << "Warning: Optional field \"" << field << "\" is missing in JSON item." << std::endl;
×
143
        }
144
    }
145
}
×
146

147
std::vector<DataInfo> load_data_from_json_config(DataManager * dm, std::string const & json_filepath) {
×
148
    std::vector<DataInfo> data_info_list;
×
149
    // Open JSON file
150
    std::ifstream ifs(json_filepath);
×
151
    if (!ifs.is_open()) {
×
152
        std::cerr << "Failed to open JSON file: " << json_filepath << std::endl;
×
153
        return data_info_list;
×
154
    }
155

156
    // Parse JSON
157
    json j;
×
158
    ifs >> j;
×
159

160
    // get base path of filepath
161
    std::filesystem::path const base_path = std::filesystem::path(json_filepath).parent_path();
×
162

163
    // Iterate through JSON array
164
    for (auto const & item: j) {
×
165

166
        if (!checkRequiredFields(item, {"data_type", "name", "filepath"})) {
×
167
            continue;// Exit if any required field is missing
×
168
        }
169

170
        std::string const data_type = item["data_type"];
×
171
        std::string const name = item["name"];
×
172

173
        auto file_exists = processFilePath(item["filepath"], base_path);
×
174
        if (!file_exists) {
×
175
            std::cerr << "File does not exist: " << item["filepath"] << std::endl;
×
176
            continue;
×
177
        }
178

179
        std::string const file_path = file_exists.value();
×
180

181
        if (data_type == "video") {
×
182
            // Create VideoData object
183
            auto video_data = std::make_shared<VideoData>();
×
184

185
            video_data->LoadMedia(file_path);
×
186

187
            std::cout << "Video has " << video_data->getTotalFrameCount() << " frames" << std::endl;
×
188
            // Add VideoData to DataManager
189
            dm->setMedia(video_data);
×
190

191
            data_info_list.push_back({name, "VideoData", ""});
×
192

193
        } else if (data_type == "points") {
×
194

195
            int const frame_column = item["frame_column"];
×
196
            int const x_column = item["x_column"];
×
197
            int const y_column = item["y_column"];
×
198

199
            std::string const color = item.value("color", "#0000FF");
×
200
            std::string const delim = item.value("delim", " ");
×
201

202
            int const height = item.value("height", -1);
×
203
            int const width = item.value("width", -1);
×
204

205
            int const scaled_height = item.value("scale_to_height", -1);
×
206
            int const scaled_width = item.value("scale_to_width", -1);
×
207

208
            auto keypoints = load_points_from_csv(
×
209
                    file_path,
210
                    frame_column,
211
                    x_column,
212
                    y_column,
213
                    delim.c_str()[0]);
×
214

215
            std::cout << "There are " << keypoints.size() << " keypoints " << std::endl;
×
216

217
            auto point_data = std::make_shared<PointData>(keypoints);
×
218
            point_data->setImageSize(ImageSize{width, height});
×
219

220
            if (scaled_height > 0 && scaled_width > 0) {
×
221
                scale(point_data, ImageSize{scaled_width, scaled_height});
×
222
            }
223

224
            dm->setData<PointData>(name, point_data);
×
225

226
            data_info_list.push_back({name, "PointData", color});
×
227

228
        } else if (data_type == "mask") {
×
229

230
            std::string const frame_key = item["frame_key"];
×
231
            std::string const prob_key = item["probability_key"];
×
232
            std::string const x_key = item["x_key"];
×
233
            std::string const y_key = item["y_key"];
×
234

235
            int const height = item.value("height", -1);
×
236
            int const width = item.value("width", -1);
×
237

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

240
            auto frames = read_array_hdf5(file_path, frame_key);
×
241
            auto probs = read_ragged_hdf5(file_path, prob_key);
×
242
            auto y_coords = read_ragged_hdf5(file_path, y_key);
×
243
            auto x_coords = read_ragged_hdf5(file_path, x_key);
×
244

245
            auto mask_data = std::make_shared<MaskData>();
×
246
            mask_data->setImageSize(ImageSize{width, height});
×
247

248
            for (std::size_t i = 0; i < frames.size(); i++) {
×
249
                auto frame = frames[i];
×
250
                auto prob = probs[i];
×
251
                auto x = x_coords[i];
×
252
                auto y = y_coords[i];
×
253
                mask_data->addMaskAtTime(frame, x, y);
×
254
            }
×
255

256
            dm->setData<MaskData>(name, mask_data);
×
257

258
            data_info_list.push_back({name, "MaskData", color});
×
259

260
            if (item.contains("operations")) {
×
261

262
                for (auto const & operation: item["operations"]) {
×
263

264
                    std::string const operation_type = operation["type"];
×
265

266
                    if (operation_type == "area") {
×
267
                        std::cout << "Calculating area for mask: " << name << std::endl;
×
268
                        auto area_data = area(dm->getData<MaskData>(name));
×
269
                        std::string const output_name = name + "_area";
×
270
                        dm->setData<AnalogTimeSeries>(output_name, area_data);
×
271
                    }
×
272
                }
×
273
            }
274
        } else if (data_type == "line") {
×
275

276
            auto line_map = load_line_csv(file_path);
×
277

278
            //Get the whisker name from the filename using filesystem
279
            auto whisker_filename = std::filesystem::path(file_path).filename().string();
×
280

281
            //Remove .csv suffix from filename
282
            auto whisker_name = remove_extension(whisker_filename);
×
283

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

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

288
            data_info_list.push_back({name, "LineData", color});
×
289

290
        } else if (data_type == "analog") {
×
291

292
            if (item["format"] == "int16") {
×
293

294
                int const header_size = item.value("header_size", 0);
×
295
                int const channel_count = item.value("channel_count", 1);
×
296

297
                if (channel_count > 1) {
×
298

NEW
299
                    auto data = readBinaryFileMultiChannel<int16_t>(file_path, channel_count, header_size);
×
300

301
                    std::cout << "Read " << data.size() << " channels" << std::endl;
×
302

303
                    for (int channel = 0; channel < data.size(); channel++) {
×
304
                        // convert to float with std::transform
305
                        std::vector<float> data_float;
×
306
                        std::transform(
×
NEW
307
                                data[channel].begin(),
×
NEW
308
                                data[channel].end(),
×
NEW
309
                                std::back_inserter(data_float), [](int16_t i) { return i; });
×
310

311
                        auto analog_time_series = std::make_shared<AnalogTimeSeries>();
×
312
                        analog_time_series->setData(data_float);
×
313

314
                        std::string const channel_name = name + "_" + std::to_string(channel);
×
315

316
                        dm->setData<AnalogTimeSeries>(channel_name, analog_time_series);
×
317

318
                        if (item.contains("clock")) {
×
319
                            std::string const clock = item["clock"];
×
320
                            dm->setTimeFrame(channel_name, clock);
×
321
                        }
×
322
                    }
×
323

324
                } else {
×
325

326
                    auto data = readBinaryFile<int16_t>(file_path, header_size);
×
327

328
                    // convert to float with std::transform
329
                    std::vector<float> data_float;
×
330
                    std::transform(
×
331
                            data.begin(),
332
                            data.end(),
NEW
333
                            std::back_inserter(data_float), [](int16_t i) { return i; });
×
334

335
                    auto analog_time_series = std::make_shared<AnalogTimeSeries>();
×
336
                    analog_time_series->setData(data_float);
×
337
                    dm->setData<AnalogTimeSeries>(name, analog_time_series);
×
338
                }
×
339

340
            } else {
341
                std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
342
            }
343

344
        } else if (data_type == "digital_event") {
×
345

346
            if (item["format"] == "uint16") {
×
347

348
                int const channel = item["channel"];
×
349
                std::string const transition = item["transition"];
×
350
                int const header_size = item.value("header_size", 0);
×
351

352
                auto data = readBinaryFile<uint16_t>(file_path, header_size);
×
353

354
                auto digital_data = extractDigitalData(data, channel);
×
355
                auto events = extractEvents(digital_data, transition);
×
356
                std::cout << "Loaded " << events.size() << " events for " << name << std::endl;
×
357

358
                auto digital_event_series = std::make_shared<DigitalEventSeries>();
×
359
                digital_event_series->setData(events);
×
360
                dm->setData<DigitalEventSeries>(name, digital_event_series);
×
361
            } else if (item["format"] == "csv") {
×
362

363
                auto events = CSVLoader::loadSingleColumnCSV(file_path);
×
364
                std::cout << "Loaded " << events.size() << " events for " << name << std::endl;
×
365

366
                float const scale = item.value("scale", 1.0f);
×
NEW
367
                float const scale_divide = item.value("scale_divide", false);
×
368

NEW
369
                if (scale_divide) {
×
NEW
370
                    for (auto & e: events) {
×
NEW
371
                        e /= scale;
×
372
                    }
373
                } else {
NEW
374
                    for (auto & e: events) {
×
NEW
375
                        e *= scale;
×
376
                    }
377
                }
378

379
                auto digital_event_series = std::make_shared<DigitalEventSeries>();
×
380
                digital_event_series->setData(events);
×
381
                dm->setData<DigitalEventSeries>(name, digital_event_series);
×
382

383
            } else {
×
384
                std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
385
            }
386
        } else if (data_type == "digital_interval") {
×
387

388
            if (item["format"] == "uint16") {
×
389

390
                int const channel = item["channel"];
×
391
                std::string const transition = item["transition"];
×
392
                int const header_size = item.value("header_size", 0);
×
393

394
                auto data = readBinaryFile<uint16_t>(file_path, header_size);
×
395

396
                auto digital_data = extractDigitalData(data, channel);
×
397

398
                auto intervals = extractIntervals(digital_data, transition);
×
399
                std::cout << "Loaded " << intervals.size() << " intervals for " << name << std::endl;
×
400

401
                auto digital_interval_series = std::make_shared<DigitalIntervalSeries>();
×
402
                digital_interval_series->setData(intervals);
×
403
                dm->setData<DigitalIntervalSeries>(name, digital_interval_series);
×
404

405
            } else if (item["format"] == "csv") {
×
406

407
                auto intervals = CSVLoader::loadPairColumnCSV(file_path);
×
408
                std::cout << "Loaded " << intervals.size() << " intervals for " << name << std::endl;
×
409
                auto digital_interval_series = std::make_shared<DigitalIntervalSeries>();
×
410
                digital_interval_series->setData(intervals);
×
411
                dm->setData<DigitalIntervalSeries>(name, digital_interval_series);
×
412
            } else {
×
413
                std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
414
            }
415
        } else if (data_type == "tensor") {
×
416

417
            if (item["format"] == "numpy") {
×
418

419
                TensorData tensor_data;
×
420
                loadNpyToTensorData(file_path, tensor_data);
×
421

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

424
            } else {
×
425
                std::cout << "Format " << item["format"] << " not found for " << name << std::endl;
×
426
            }
427

428
        } else if (data_type == "time") {
×
429

430
            if (item["format"] == "uint16") {
×
431

432
                int const channel = item["channel"];
×
433
                std::string const transition = item["transition"];
×
434
                int const header_size = item.value("header_size", 0);
×
435

436
                auto data = readBinaryFile<uint16_t>(file_path, header_size);
×
437

438
                auto digital_data = extractDigitalData(data, channel);
×
439
                auto events = extractEvents(digital_data, transition);
×
440

441
                // convert to int with std::transform
442
                std::vector<int> events_int;
×
443
                events_int.reserve(events.size());
×
444
                for (auto e: events) {
×
445
                    events_int.push_back(static_cast<int>(e));
×
446
                }
447
                std::cout << "Loaded " << events_int.size() << " events for " << name << std::endl;
×
448

449
                auto timeframe = std::make_shared<TimeFrame>(events_int);
×
450
                dm->setTime(name, timeframe);
×
451
            }
×
452

453
            if (item["format"] == "uint16_length") {
×
454

455
                int const header_size = item.value("header_size", 0);
×
456

457
                auto data = readBinaryFile<uint16_t>(file_path, header_size);
×
458

459
                std::vector<int> t(data.size());
×
460
                std::iota(std::begin(t), std::end(t), 0);
×
461

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

464
                auto timeframe = std::make_shared<TimeFrame>(t);
×
465
                dm->setTime(name, timeframe);
×
466
            }
×
467
        }
468
        if (item.contains("clock")) {
×
469
            std::string const clock = item["clock"];
×
470
            std::cout << "Setting time for " << name << " to " << clock << std::endl;
×
471
            dm->setTimeFrame(name, clock);
×
472
        }
×
473
    }
×
474

475
    return data_info_list;
476
}
×
477

478
std::string DataManager::getType(std::string const & key) const {
×
479
    auto it = _data.find(key);
×
480
    if (it != _data.end()) {
×
481
        if (std::holds_alternative<std::shared_ptr<MediaData>>(it->second)) {
×
482
            return "MediaData";
×
483
        } else if (std::holds_alternative<std::shared_ptr<PointData>>(it->second)) {
×
484
            return "PointData";
×
485
        } else if (std::holds_alternative<std::shared_ptr<LineData>>(it->second)) {
×
486
            return "LineData";
×
487
        } else if (std::holds_alternative<std::shared_ptr<MaskData>>(it->second)) {
×
488
            return "MaskData";
×
489
        } else if (std::holds_alternative<std::shared_ptr<AnalogTimeSeries>>(it->second)) {
×
490
            return "AnalogTimeSeries";
×
491
        } else if (std::holds_alternative<std::shared_ptr<DigitalEventSeries>>(it->second)) {
×
492
            return "DigitalEventSeries";
×
493
        } else if (std::holds_alternative<std::shared_ptr<DigitalIntervalSeries>>(it->second)) {
×
494
            return "DigitalIntervalSeries";
×
495
        } else if (std::holds_alternative<std::shared_ptr<TensorData>>(it->second)) {
×
496
            return "TensorData";
×
497
        }
498
        return "Unknown";
×
499
    }
500
}
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