forked from open-ephys/plugin-GUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecordNodeTests.cpp
More file actions
524 lines (441 loc) · 20.8 KB
/
RecordNodeTests.cpp
File metadata and controls
524 lines (441 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#include <stdio.h>
#include "gtest/gtest.h"
#include <Processors/RecordNode/RecordNode.h>
#include <ModelProcessors.h>
#include <ModelApplication.h>
#include <TestFixtures.h>
#include <chrono>
#include <thread>
#include <iterator>
#include <iostream>
#include <filesystem>
#include <algorithm>
class RecordNodeTests : public testing::Test {
protected:
void SetUp() override {
numChannels = 8;
tester = std::make_unique<ProcessorTester>(TestSourceNodeBuilder
(FakeSourceNodeParams{
numChannels,
sampleRate,
bitVolts
}));
parentRecordingDir = std::filesystem::temp_directory_path() / "record_node_tests";
if (std::filesystem::exists(parentRecordingDir)) {
std::filesystem::remove_all(parentRecordingDir);
}
std::filesystem::create_directory(parentRecordingDir);
// Set this before creating the record node
tester->setRecordingParentDirectory(parentRecordingDir.string());
processor = tester->createProcessor<RecordNode>(Plugin::Processor::RECORD_NODE);
}
void TearDown() override {
// Swallow errors
std::error_code ec;
std::filesystem::remove_all(parentRecordingDir, ec);
}
AudioBuffer<float> createBuffer(float startingVal, float step, int numChannels, int numSamples) {
AudioBuffer<float> inputBuffer(numChannels, numSamples);
// in microvolts
float currVal = startingVal;
for (int chidx = 0; chidx < numChannels; chidx++) {
for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) {
inputBuffer.setSample(chidx, sampleIdx, currVal);
currVal += step;
}
}
return inputBuffer;
}
void writeBlock(AudioBuffer<float> &buffer, TTLEvent* maybeTtlEvent = nullptr) {
auto outBuffer = tester->processBlock(processor, buffer, maybeTtlEvent);
// Assert the buffer hasn't changed after process()
ASSERT_EQ(outBuffer.getNumSamples(), buffer.getNumSamples());
ASSERT_EQ(outBuffer.getNumChannels(), buffer.getNumChannels());
for (int chidx = 0; chidx < outBuffer.getNumChannels(); chidx++) {
for (int sampleIdx = 0; sampleIdx < outBuffer.getNumSamples(); ++sampleIdx) {
ASSERT_EQ(
outBuffer.getSample(chidx, sampleIdx),
buffer.getSample(chidx, sampleIdx));
}
}
}
bool subRecordingPathFor(
const std::string& subrecording_dirname,
const std::string& basename,
std::filesystem::path* path) {
// Do verifications:
auto recordingDir = std::filesystem::directory_iterator(parentRecordingDir)->path();
std::stringstream ss;
ss << "Record Node " << processor->getNodeId();
auto recordingDir2 = recordingDir / ss.str() / "experiment1" / "recording1" / subrecording_dirname;
if (!std::filesystem::exists(recordingDir2)) {
return false;
}
std::filesystem::path recordingDir3;
for (const auto &subdir : std::filesystem::directory_iterator(recordingDir2)) {
auto subDirBaseName = subdir.path().filename().string();
if (subDirBaseName.find("FakeSourceNode") != std::string::npos) {
recordingDir3 = subdir.path();
}
}
if (!std::filesystem::exists(recordingDir3)) {
return false;
}
auto ret = recordingDir3 / basename;
if (!std::filesystem::exists(ret)) {
return false;
}
*path = ret;
return true;
}
bool continuousPathFor(const std::string& basename, std::filesystem::path* path) {
return subRecordingPathFor("continuous", basename, path);
}
bool eventsPathFor(const std::string& basename, std::filesystem::path* path) {
std::filesystem::path partialPath;
auto success = subRecordingPathFor("events", "TTL", &partialPath);
if (!success) {
return false;
}
auto ret = partialPath / basename;
if (std::filesystem::exists(ret)) {
*path = ret;
return true;
} else {
return false;
}
}
void maybeLoadContinuousDatFile(std::vector<int16_t> *output, bool *success) {
// Do verifications:
std::filesystem::path continuousDatPath;
*success = continuousPathFor("continuous.dat", &continuousDatPath);
if (!*success) {
return;
}
std::ifstream continuousIfStream(continuousDatPath.string(), std::ios::binary | std::ios::in);
continuousIfStream.seekg(0, std::ios::end);
std::streampos fileSize = continuousIfStream.tellg();
continuousIfStream.seekg(0, std::ios::beg);
if (fileSize % sizeof(int16_t) != 0) {
*success = false;
return;
}
std::vector<int16_t> persistedData(fileSize / sizeof(int16_t));
continuousIfStream.read((char *) persistedData.data(), fileSize);
*success = true;
*output = persistedData;
}
void loadContinuousDatFile(std::vector<int16_t> *output) {
bool success = false;
maybeLoadContinuousDatFile(output, &success);
ASSERT_TRUE(success);
}
std::vector<char> loadNpyFileBinaryFullpath(const std::string& fullPath) {
std::ifstream dataIfStream(fullPath, std::ios::binary | std::ios::in);
dataIfStream.seekg(0, std::ios::end);
std::streampos fileSize = dataIfStream.tellg();
dataIfStream.seekg(0, std::ios::beg);
std::vector<char> persistedData(fileSize);
dataIfStream.read(persistedData.data(), fileSize);
return persistedData;
}
void loadNpyFileBinary(const std::string &basename, std::vector<char> *output, bool *success) {
// Do verifications:
std::filesystem::path npyFilePath;
*success = continuousPathFor(basename, &npyFilePath);
if (!*success) {
return;
}
*success = true;
*output = loadNpyFileBinaryFullpath(npyFilePath.string());
}
void compareBinaryFilesHex(const std::string& filename, const std::vector<char> binData, const std::string& expectedBinDataHex) {
std::vector<char> expectedBinData;
for (int i = 0; i < expectedBinDataHex.length(); i += 2) {
std::string byteString = expectedBinDataHex.substr(i, 2);
char byte = (char) strtol(byteString.c_str(), nullptr, 16);
expectedBinData.push_back(byte);
}
// Create a string rep of the actual sample numbers bin in case it fails, to help debugging
std::stringstream binDataHexSs;
binDataHexSs << "Expected data for " << filename << " in hex to be=" << expectedBinDataHex
<< " but received=";
binDataHexSs << std::hex;
for (int i = 0; i < binData.size(); i++) {
binDataHexSs << std::setw(2) << std::setfill('0') << (int)binData[i];
}
std::string err_msg = binDataHexSs.str();
ASSERT_EQ(binData.size(), expectedBinData.size()) << err_msg;
for (int i = 0; i < binData.size(); i++) {
ASSERT_EQ(binData[i], expectedBinData[i])
<< err_msg
<< " (error on index " << i << ")";
}
}
static int16_t minValPossible() {
// The min value is actually -32767 in the math in RecordNode, not -32768 like the "true" min for int16_t
return (std::numeric_limits<int16_t>::min)() + 1;
}
static int16_t maxValPossible() {
return (std::numeric_limits<int16_t>::max)();
}
RecordNode *processor;
int numChannels;
float bitVolts = 1.0;
std::unique_ptr<ProcessorTester> tester;
std::filesystem::path parentRecordingDir;
float sampleRate = 1.0;
};
TEST_F(RecordNodeTests, TestInputOutput_Continuous_Single) {
int numSamples = 100;
processor->startAcquisition();
auto inputBuffer = createBuffer(1000.0, 20.0, numChannels, numSamples);
writeBlock(inputBuffer);
// The record node always flushes its pending writes when stopping acquisition, so we don't need to sleep before
// stopping.
processor->stopAcquisition();
std::vector<int16_t> persistedData;
loadContinuousDatFile(&persistedData);
ASSERT_EQ(persistedData.size(), numChannels * numSamples);
int persistedDataIdx = 0;
// File is channel-interleaved, so ensure we iterate in the correct order:
for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) {
for (int chidx = 0; chidx < numChannels; chidx++) {
auto expectedMicroVolts = inputBuffer.getSample(chidx, sampleIdx);
ASSERT_EQ(persistedData[persistedDataIdx], expectedMicroVolts);
persistedDataIdx++;
}
}
}
TEST_F(RecordNodeTests, TestInputOutput_Continuous_Multiple) {
processor->startAcquisition();
int numSamplesPerBlock = 100;
int numBlocks = 8;
std::vector<AudioBuffer<float>> inputBuffers;
for (int i = 0; i < numBlocks; i++) {
auto inputBuffer = createBuffer(1000.0f * i, 20.0, numChannels, numSamplesPerBlock);
writeBlock(inputBuffer);
inputBuffers.push_back(inputBuffer);
}
processor->stopAcquisition();
std::vector<int16_t> persistedData;
loadContinuousDatFile(&persistedData);
ASSERT_EQ(persistedData.size(), numChannels * numSamplesPerBlock * numBlocks);
int persistedDataIdx = 0;
// File is channel-interleaved, so ensure we iterate in the correct order:
for (int blockIdx = 0; blockIdx < numBlocks; blockIdx++) {
const auto& inputBuffer = inputBuffers[blockIdx];
for (int sampleIdx = 0; sampleIdx < numSamplesPerBlock; sampleIdx++) {
for (int chidx = 0; chidx < numChannels; chidx++) {
auto expectedMicroVolts = inputBuffer.getSample(chidx, sampleIdx);
ASSERT_EQ(persistedData[persistedDataIdx], expectedMicroVolts);
persistedDataIdx++;
}
}
}
}
TEST_F(RecordNodeTests, TestEmpty) {
processor->startAcquisition();
processor->stopAcquisition();
std::vector<int16_t> persistedData;
loadContinuousDatFile(&persistedData);
ASSERT_EQ(persistedData.size(), 0);
}
TEST_F(RecordNodeTests, TestClipsProperly) {
int numSamples = 100;
processor->startAcquisition();
// The min value is actually -32767, not -32768 like the "true" min
std::vector<AudioBuffer<float>> inputBuffers;
// Write numbers both underflowing and overflowing
auto inputBuffer = createBuffer((float) minValPossible() + 1, -1, numChannels, numSamples);
writeBlock(inputBuffer);
inputBuffers.push_back(inputBuffer);
inputBuffer = createBuffer((float) maxValPossible() - 1, 1, numChannels, numSamples);
writeBlock(inputBuffer);
inputBuffers.push_back(inputBuffer);
processor->stopAcquisition();
std::vector<int16_t> persistedData;
loadContinuousDatFile(&persistedData);
ASSERT_EQ(persistedData.size(), numChannels * numSamples * 2);
int persistedDataIdx = 0;
for (int blockIdx = 0; blockIdx < 2; blockIdx++) {
auto inputBuffer = inputBuffers[blockIdx];
for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) {
for (int chidx = 0; chidx < numChannels; chidx++) {
auto expectedMicroVolts = inputBuffer.getSample(chidx, sampleIdx);
// Per the logic above, only the very first sample/channel is within the normal bounds; the rest will
// be clipped at the upper or lower possible values.
int16_t expectedPersisted;
if (sampleIdx == 0 && chidx == 0) {
expectedPersisted = expectedMicroVolts;
} else if (expectedMicroVolts > 0) {
expectedPersisted = maxValPossible();
} else {
expectedPersisted = minValPossible();
}
ASSERT_EQ(persistedData[persistedDataIdx], expectedPersisted);
persistedDataIdx++;
}
}
}
}
class CustomBitVolts_RecordNodeTests : public RecordNodeTests {
void SetUp() override {
bitVolts = 0.195;
RecordNodeTests::SetUp();
}
};
TEST_F(CustomBitVolts_RecordNodeTests, Test_RespectsBitVolts) {
int numSamples = 100;
processor->startAcquisition();
auto inputBuffer = createBuffer(1000.0, 20.0, numChannels, numSamples);
writeBlock(inputBuffer);
processor->stopAcquisition();
std::vector<int16_t> persistedData;
loadContinuousDatFile(&persistedData);
ASSERT_EQ(persistedData.size(), numChannels * numSamples);
int persistedDataIdx = 0;
// File is channel-interleaved, so ensure we iterate in the correct order:
for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) {
for (int chidx = 0; chidx < numChannels; chidx++) {
auto expectedMicroVolts = inputBuffer.getSample(chidx, sampleIdx);
auto expected_converted = expectedMicroVolts / bitVolts;
// Rounds to nearest int, like BinaryRecording does, and clamp within bounds
int expected_rounded = juce::roundToInt(expected_converted);
int16_t expectedPersisted = (int16_t) std::clamp(
expected_rounded,
(int) minValPossible(),
(int) maxValPossible());
ASSERT_EQ(persistedData[persistedDataIdx], expectedPersisted);
persistedDataIdx++;
}
}
}
TEST_F(RecordNodeTests, Test_PersistsSampleNumbersAndTimestamps) {
processor->startAcquisition();
int numSamples = 5;
for (int i = 0; i < 3; i++) {
auto inputBuffer = createBuffer(1000.0, 20.0, numChannels, numSamples);
writeBlock(inputBuffer);
}
tester->stopAcquisition();
bool success = false;
std::vector<char> sampleNumbersBin;
loadNpyFileBinary("sample_numbers.npy", &sampleNumbersBin, &success);
ASSERT_TRUE(success);
/**
* Since NpyFile in OpenEphys doesn't include any facility to read .npy files, we've generated the expected
* .npy file output in Python directly, and hardcode its binary value in this test. That python command was:
* # For sample_numbers:
* import numpy as np, io, binascii; b = io.BytesIO(); np.save(b, np.arange(15, dtype=np.int64)); b.seek(0); print(binascii.hexlify(b.read()))
*/
std::string expectedSampleNumbersHex =
"934e554d5059010076007b276465736372273a20273c6938272c2027666f727472616e5f6f72646572273a2046616c73652c2027736861"
"7065273a202831352c292c207d202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
"20202020202020202020202020202020200a00000000000000000100000000000000020000000000000003000000000000000400000000"
"000000050000000000000006000000000000000700000000000000080000000000000009000000000000000a000000000000000b000000"
"000000000c000000000000000d000000000000000e00000000000000";
compareBinaryFilesHex("sample_numbers.npy", sampleNumbersBin, expectedSampleNumbersHex);
success = false;
std::vector<char> timeStampsBin;
loadNpyFileBinary("timestamps.npy", &timeStampsBin, &success);
ASSERT_TRUE(success);
/**
* Same logic as above (note the timestamps are just converted from the sample numbers according to sampling rate)
* import numpy as np, io, binascii; b = io.BytesIO(); np.save(b, np.arange(15, dtype=np.double)); b.seek(0); print(binascii.hexlify(b.read()))
*/
std::string expectedTimeStampsHex =
"934e554d5059010076007b276465736372273a20273c6638272c2027666f727472616e5f6f72646572273a2046616c73652c2027736861"
"7065273a202831352c292c207d202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
"20202020202020202020202020202020200a0000000000000000000000000000f03f000000000000004000000000000008400000000000"
"001040000000000000144000000000000018400000000000001c4000000000000020400000000000002240000000000000244000000000"
"0000264000000000000028400000000000002a400000000000002c40";
compareBinaryFilesHex("timestamps.npy", timeStampsBin, expectedTimeStampsHex);
}
TEST_F(RecordNodeTests, Test_PersistsStructureOeBin) {
processor->startAcquisition();
int numSamples = 5;
for (int i = 0; i < 3; i++) {
auto inputBuffer = createBuffer(1000.0, 20.0, numChannels, numSamples);
writeBlock(inputBuffer);
}
tester->stopAcquisition();
// Do verifications:
auto recordingDir = std::filesystem::directory_iterator(parentRecordingDir)->path();
std::stringstream ss;
ss << "Record Node " << processor->getNodeId();
auto recordingDir2 = recordingDir / ss.str() / "experiment1" / "recording1";
ASSERT_TRUE(std::filesystem::exists(recordingDir2));
auto structureOeBinFn = recordingDir2 / "structure.oebin";
ASSERT_TRUE(std::filesystem::exists(structureOeBinFn));
auto f = juce::File(structureOeBinFn.string());
// FileInputStream input(f);
// std::cout << input.readEntireStreamAsString() << std::endl;
auto jsonParsed = JSON::parse(f);
ASSERT_TRUE(jsonParsed.hasProperty("GUI version"));
ASSERT_TRUE(jsonParsed["GUI version"].toString().length() > 0);
ASSERT_TRUE(jsonParsed.hasProperty("continuous"));
const auto& jsonContinuousList = jsonParsed["continuous"];
ASSERT_TRUE(jsonContinuousList.isArray());
// 1 per stream, so just 1
ASSERT_EQ(jsonContinuousList.getArray()->size(), 1);
auto jsonContinuous = (*jsonContinuousList.getArray())[0];
// Spot check some fields
ASSERT_TRUE(jsonContinuous.hasProperty("folder_name"));
ASSERT_TRUE(jsonContinuous["folder_name"].toString().contains("Record_Node"));
ASSERT_TRUE(jsonContinuous.hasProperty("sample_rate"));
ASSERT_FLOAT_EQ((float) jsonContinuous["sample_rate"], sampleRate);
ASSERT_TRUE(jsonContinuous.hasProperty("sample_rate"));
ASSERT_FLOAT_EQ((float) jsonContinuous["sample_rate"], sampleRate);
ASSERT_TRUE(jsonContinuous.hasProperty("num_channels"));
ASSERT_FLOAT_EQ((int) jsonContinuous["num_channels"], numChannels);
ASSERT_TRUE(jsonContinuous.hasProperty("channels"));
ASSERT_TRUE(jsonContinuous["channels"].isArray());
ASSERT_EQ(jsonContinuous["channels"].getArray()->size(), numChannels);
auto jsonContinuousChannel = (*jsonContinuous["channels"].getArray())[0];
ASSERT_TRUE(jsonContinuousChannel.hasProperty("bit_volts"));
ASSERT_FLOAT_EQ((float) jsonContinuousChannel["bit_volts"], bitVolts);
ASSERT_TRUE(jsonContinuousChannel.hasProperty("channel_name"));
ASSERT_EQ(jsonContinuousChannel["channel_name"].toString(), juce::String("CH0"));
}
TEST_F(RecordNodeTests, Test_PersistsEvents) {
processor->setRecordEvents(true);
processor->updateSettings();
processor->startAcquisition();
int numSamples = 5;
auto streamId = processor->getDataStreams()[0]->getStreamId();
auto eventChannels = tester->getSourceNodeDataStream(streamId)->getEventChannels();
ASSERT_GE(eventChannels.size(), 1);
TTLEventPtr eventPtr = TTLEvent::createTTLEvent(
eventChannels[0],
1,
2,
true);
auto inputBuffer = createBuffer(1000.0, 20.0, numChannels, numSamples);
writeBlock(inputBuffer, eventPtr.get());
processor->stopAcquisition();
std::filesystem::path sampleNumbersPath;
ASSERT_TRUE(eventsPathFor("sample_numbers.npy", &sampleNumbersPath));
auto sampleNumbersBin = loadNpyFileBinaryFullpath(sampleNumbersPath.string());
/**
* Same logic as above:
* import numpy as np, io, binascii; b = io.BytesIO(); np.save(b, np.array([1], dtype=np.int64)); b.seek(0); print(binascii.hexlify(b.read()))
*/
std::string expectedSampleNumbersHex =
"934e554d5059010076007b276465736372273a20273c6938272c2027666f727472616e5f6f72646572273a2046616c73652c2027736861"
"7065273a2028312c292c207d20202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
"20202020202020202020202020202020200a0100000000000000";
compareBinaryFilesHex("sample_numbers.npy", sampleNumbersBin, expectedSampleNumbersHex);
std::filesystem::path fullWordsPath;
ASSERT_TRUE(eventsPathFor("full_words.npy", &fullWordsPath));
auto fullWordsBin = loadNpyFileBinaryFullpath(fullWordsPath.string());
/**
* Same logic as above:
* import numpy as np, io, binascii; b = io.BytesIO(); np.save(b, np.array([4], dtype=np.uint64)); b.seek(0); print(binascii.hexlify(b.read()))
*/
std::string expectedFullWordsHex =
"934e554d5059010076007b276465736372273a20273c7538272c2027666f727472616e5f6f72646572273a2046616c73652c2027736861"
"7065273a2028312c292c207d20202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
"20202020202020202020202020202020200a0400000000000000";
compareBinaryFilesHex("full_words.npy", fullWordsBin, expectedFullWordsHex);
}