-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtest_imaging_interfaces.py
More file actions
1533 lines (1276 loc) · 77.4 KB
/
test_imaging_interfaces.py
File metadata and controls
1533 lines (1276 loc) · 77.4 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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import platform
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pytest
from dateutil.tz import tzoffset
from numpy.testing import assert_array_equal
from pynwb import NWBHDF5IO
from neuroconv.datainterfaces import (
BrukerTiffMultiPlaneImagingInterface,
BrukerTiffSinglePlaneImagingInterface,
FemtonicsImagingInterface,
Hdf5ImagingInterface,
InscopixImagingInterface,
MicroManagerTiffImagingInterface,
MiniscopeImagingInterface,
SbxImagingInterface,
ScanImageImagingInterface,
ScanImageLegacyImagingInterface,
ThorImagingInterface,
TiffImagingInterface,
)
from neuroconv.datainterfaces.ophys.miniscope.miniscopeimagingdatainterface import (
_MiniscopeMultiRecordingInterface,
)
from neuroconv.tools.testing.data_interface_mixins import (
DataInterfaceTestMixin,
ImagingExtractorInterfaceTestMixin,
MiniscopeImagingInterfaceMixin,
TemporalAlignmentMixin,
)
try:
from ..setup_paths import OPHYS_DATA_PATH, OUTPUT_PATH
except ImportError:
from setup_paths import OPHYS_DATA_PATH, OUTPUT_PATH
class TestTiffImagingInterface(ImagingExtractorInterfaceTestMixin):
data_interface_cls = TiffImagingInterface
interface_kwargs = dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Tif" / "demoMovie.tif"),
sampling_frequency=15.0, # typically provided by user
)
save_directory = OUTPUT_PATH
class TestTiffImagingInterfaceMultiFile(ImagingExtractorInterfaceTestMixin):
"""Test TiffImagingInterface with multi-file TIFF data using file_paths parameter."""
data_interface_cls = TiffImagingInterface
interface_kwargs = dict(
file_paths=[
str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20240320_multifile_00001.tif"),
str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20240320_multifile_00002.tif"),
str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20240320_multifile_00003.tif"),
],
sampling_frequency=30.0,
dimension_order="CZT",
num_channels=2,
channel_name="0",
)
save_directory = OUTPUT_PATH
class TestScanImageImagingInterfaceMultiPlaneChannel1(DataInterfaceTestMixin, TemporalAlignmentMixin):
data_interface_cls = ScanImageImagingInterface
interface_kwargs = dict(
file_paths=[OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"],
channel_name="Channel 1",
interleave_slice_samples=True,
)
save_directory = OUTPUT_PATH
photon_series_name = "TwoPhotonSeriesChannel1"
imaging_plane_name = "ImagingPlaneChannel1"
expected_two_photon_series_data_shape = (6, 256, 528, 2)
expected_rate = None # This is interleaved data so the timestamps are written
expected_starting_time = None
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2023, 9, 22, 12, 51, 34, 124000)
def check_read_nwb(self, nwbfile_path: str):
"""Test reading the NWB file for multi-plane ScanImage data."""
with NWBHDF5IO(nwbfile_path, "r") as io:
nwbfile = io.read()
assert self.imaging_plane_name in nwbfile.imaging_planes
assert self.photon_series_name in nwbfile.acquisition
two_photon_series = nwbfile.acquisition[self.photon_series_name]
assert two_photon_series.data.shape == self.expected_two_photon_series_data_shape
assert two_photon_series.unit == "n.a."
assert two_photon_series.data.dtype == np.int16
assert two_photon_series.rate == self.expected_rate
assert two_photon_series.starting_time == self.expected_starting_time
imaging_extractor = self.interface.imaging_extractor
data_from_extractor = imaging_extractor.get_series()
assert_array_equal(two_photon_series.data[:], data_from_extractor.transpose(0, 2, 1, 3))
optical_channels = nwbfile.imaging_planes[self.imaging_plane_name].optical_channel
assert len(optical_channels) == 1
class TestScanImageImagingInterfaceMultiPlaneChannel4(DataInterfaceTestMixin, TemporalAlignmentMixin):
data_interface_cls = ScanImageImagingInterface
interface_kwargs = dict(
file_paths=[OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"],
channel_name="Channel 4",
interleave_slice_samples=True,
)
save_directory = OUTPUT_PATH
photon_series_name = "TwoPhotonSeriesChannel4"
imaging_plane_name = "ImagingPlaneChannel4"
expected_two_photon_series_data_shape = (6, 256, 528, 2)
expected_rate = None # This is interleaved data so the timestamps are written
expected_starting_time = None
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2023, 9, 22, 12, 51, 34, 124000)
def check_read_nwb(self, nwbfile_path: str):
"""Test reading the NWB file for multi-plane ScanImage data."""
with NWBHDF5IO(nwbfile_path, "r") as io:
nwbfile = io.read()
assert self.imaging_plane_name in nwbfile.imaging_planes
assert self.photon_series_name in nwbfile.acquisition
two_photon_series = nwbfile.acquisition[self.photon_series_name]
assert two_photon_series.data.shape == self.expected_two_photon_series_data_shape
assert two_photon_series.unit == "n.a."
assert two_photon_series.data.dtype == np.int16
assert two_photon_series.rate == self.expected_rate
assert two_photon_series.starting_time == self.expected_starting_time
imaging_extractor = self.interface.imaging_extractor
data_from_extractor = imaging_extractor.get_series()
assert_array_equal(two_photon_series.data[:], data_from_extractor.transpose(0, 2, 1, 3))
optical_channels = nwbfile.imaging_planes[self.imaging_plane_name].optical_channel
assert len(optical_channels) == 1
class TestScanImageImagingInterfaceSinglePlaneCase(DataInterfaceTestMixin, TemporalAlignmentMixin):
data_interface_cls = ScanImageImagingInterface
save_directory = OUTPUT_PATH
expected_two_photon_series_data_shape = (6, 256, 528)
@pytest.fixture(
params=[
dict(
interface_kwargs=dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"),
channel_name="Channel 1",
plane_index=0,
interleave_slice_samples=True,
),
expected_photon_series_name="TwoPhotonSeriesChannel1Plane0",
expected_imaging_plane_name="ImagingPlaneChannel1Plane0",
),
dict(
interface_kwargs=dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"),
channel_name="Channel 1",
plane_index=1,
interleave_slice_samples=True,
),
expected_photon_series_name="TwoPhotonSeriesChannel1Plane1",
expected_imaging_plane_name="ImagingPlaneChannel1Plane1",
),
dict(
interface_kwargs=dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"),
channel_name="Channel 4",
plane_index=0,
interleave_slice_samples=True,
),
expected_photon_series_name="TwoPhotonSeriesChannel4Plane0",
expected_imaging_plane_name="ImagingPlaneChannel4Plane0",
),
dict(
interface_kwargs=dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif"),
channel_name="Channel 4",
plane_index=1,
interleave_slice_samples=True,
),
expected_photon_series_name="TwoPhotonSeriesChannel4Plane1",
expected_imaging_plane_name="ImagingPlaneChannel4Plane1",
),
],
ids=[
"Channel1Plane0",
"Channel1Plane1",
"Channel4Plane0",
"Channel4Plane1",
],
)
def setup_interface(self, request):
test_id = request.node.callspec.id
self.test_name = test_id
self.interface_kwargs = request.param["interface_kwargs"]
self.photon_series_name = request.param["expected_photon_series_name"]
self.imaging_plane_name = request.param["expected_imaging_plane_name"]
self.interface = self.data_interface_cls(**self.interface_kwargs)
return self.interface, self.test_name
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2023, 9, 22, 12, 51, 34, 124000)
def check_read_nwb(self, nwbfile_path: str):
"""Test reading the NWB file for single-plane ScanImage data."""
with NWBHDF5IO(nwbfile_path, "r") as io:
nwbfile = io.read()
assert self.imaging_plane_name in nwbfile.imaging_planes
assert self.photon_series_name in nwbfile.acquisition
two_photon_series = nwbfile.acquisition[self.photon_series_name]
assert two_photon_series.data.shape == self.expected_two_photon_series_data_shape
assert two_photon_series.unit == "n.a."
assert two_photon_series.data.dtype == np.int16
assert two_photon_series.rate is None
assert two_photon_series.starting_time is None
imaging_extractor = self.interface.imaging_extractor
times_from_extractor = imaging_extractor._times
assert_array_equal(two_photon_series.timestamps[:], times_from_extractor)
data_from_extractor = imaging_extractor.get_series()
assert_array_equal(two_photon_series.data[:], data_from_extractor.transpose(0, 2, 1))
optical_channels = nwbfile.imaging_planes[self.imaging_plane_name].optical_channel
assert len(optical_channels) == 1
class TestScanImageImagingInterfacesAssertions:
def test_not_recognized_scanimage_version(self):
"""Test that ValueError is returned when ScanImage version could not be determined from metadata."""
file_path = str(OPHYS_DATA_PATH / "imaging_datasets" / "Tif" / "demoMovie.tif")
with pytest.raises(
ValueError,
match="Unsupported ScanImage version 65536. Supported versions are 3, 4, and 5.Most likely this is a legacy version, use ScanImageLegacyImagingInterface instead.",
):
ScanImageImagingInterface(file_path=file_path)
def test_channel_name_not_specified(self):
"""Test that ValueError is raised when channel_name is not specified for data with multiple channels."""
file_path = str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20240320_multifile_00001.tif")
with pytest.raises(ValueError, match="Multiple channels available in the data"):
ScanImageImagingInterface(file_path=file_path)
def test_incorrect_channel_name(self):
"""Test that ValueError is raised when incorrect channel name is specified."""
file_path = str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220923_roi.tif")
channel_name = "Channel 2"
with pytest.raises(
ValueError,
match=r"Channel name \(Channel 2\) not found in available channels \(\['Channel 1', 'Channel 4'\]\)\. Please specify a valid channel name\.",
):
ScanImageImagingInterface(file_path=file_path, channel_name=channel_name, interleave_slice_samples=True)
def test_incorrect_plane_index(self):
"""Test that ValueError is raised when incorrect plane index is specified."""
file_path = str(OPHYS_DATA_PATH / "imaging_datasets" / "ScanImage" / "scanimage_20220801_volume.tif")
with pytest.raises(ValueError, match=r"plane_index \(20\) must be between 0 and 19"):
ScanImageImagingInterface(file_path=file_path, plane_index=20, interleave_slice_samples=True)
@pytest.mark.skipif(platform.machine() == "arm64", reason="Interface not supported on arm64 architecture")
class TestScanImageLegacyImagingInterface(ImagingExtractorInterfaceTestMixin):
data_interface_cls = ScanImageLegacyImagingInterface
interface_kwargs = dict(file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Tif" / "sample_scanimage.tiff"))
save_directory = OUTPUT_PATH
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2017, 10, 9, 16, 57, 7, 967000)
assert (
metadata["Ophys"]["TwoPhotonSeries"][0]["description"]
== '{"state.configPath": "\'C:\\\\Users\\\\Kishore Kuchibhotla\\\\Desktop\\\\FromOld2P_params\\\\ScanImage_cfgfiles\'", "state.configName": "\'Behavior_2channel\'", "state.software.version": "3.8", "state.software.minorRev": "0", "state.software.beta": "1", "state.software.betaNum": "4", "state.acq.externallyTriggered": "0", "state.acq.startTrigInputTerminal": "1", "state.acq.startTrigEdge": "\'Rising\'", "state.acq.nextTrigInputTerminal": "[]", "state.acq.nextTrigEdge": "\'Rising\'", "state.acq.nextTrigAutoAdvance": "0", "state.acq.nextTrigStopImmediate": "1", "state.acq.nextTrigAdvanceGap": "0", "state.acq.pureNextTriggerMode": "0", "state.acq.numberOfZSlices": "1", "state.acq.zStepSize": "187", "state.acq.numAvgFramesSaveGUI": "1", "state.acq.numAvgFramesSave": "1", "state.acq.numAvgFramesDisplay": "1", "state.acq.averaging": "1", "state.acq.averagingDisplay": "0", "state.acq.numberOfFrames": "1220", "state.acq.numberOfRepeats": "Inf", "state.acq.repeatPeriod": "10", "state.acq.stackCenteredOffset": "[]", "state.acq.stackParkBetweenSlices": "0", "state.acq.linesPerFrame": "256", "state.acq.pixelsPerLine": "256", "state.acq.pixelTime": "3.2e-06", "state.acq.binFactor": "16", "state.acq.frameRate": "3.90625", "state.acq.zoomFactor": "2", "state.acq.scanAngleMultiplierFast": "1", "state.acq.scanAngleMultiplierSlow": "1", "state.acq.scanRotation": "0", "state.acq.scanShiftFast": "1.25", "state.acq.scanShiftSlow": "-0.75", "state.acq.xstep": "0.5", "state.acq.ystep": "0.5", "state.acq.staircaseSlowDim": "0", "state.acq.slowDimFlybackFinalLine": "1", "state.acq.slowDimDiscardFlybackLine": "0", "state.acq.msPerLine": "1", "state.acq.fillFraction": "0.8192", "state.acq.samplesAcquiredPerLine": "4096", "state.acq.acqDelay": "8.32e-05", "state.acq.scanDelay": "9e-05", "state.acq.bidirectionalScan": "1", "state.acq.baseZoomFactor": "1", "state.acq.outputRate": "100000", "state.acq.inputRate": "5000000", "state.acq.inputBitDepth": "12", "state.acq.pockelsClosedOnFlyback": "1", "state.acq.pockelsFillFracAdjust": "4e-05", "state.acq.pmtOffsetChannel1": "0.93603515625", "state.acq.pmtOffsetChannel2": "-0.106689453125", "state.acq.pmtOffsetChannel3": "-0.789306640625", "state.acq.pmtOffsetChannel4": "-1.0419921875", "state.acq.pmtOffsetAutoSubtractChannel1": "0", "state.acq.pmtOffsetAutoSubtractChannel2": "0", "state.acq.pmtOffsetAutoSubtractChannel3": "0", "state.acq.pmtOffsetAutoSubtractChannel4": "0", "state.acq.pmtOffsetStdDevChannel1": "0.853812996333255", "state.acq.pmtOffsetStdDevChannel2": "0.87040286645618", "state.acq.pmtOffsetStdDevChannel3": "0.410833641563274", "state.acq.pmtOffsetStdDevChannel4": "0.20894370294704", "state.acq.rboxZoomSetting": "0", "state.acq.acquiringChannel1": "1", "state.acq.acquiringChannel2": "0", "state.acq.acquiringChannel3": "0", "state.acq.acquiringChannel4": "0", "state.acq.savingChannel1": "1", "state.acq.savingChannel2": "0", "state.acq.savingChannel3": "0", "state.acq.savingChannel4": "0", "state.acq.imagingChannel1": "1", "state.acq.imagingChannel2": "0", "state.acq.imagingChannel3": "0", "state.acq.imagingChannel4": "0", "state.acq.maxImage1": "0", "state.acq.maxImage2": "0", "state.acq.maxImage3": "0", "state.acq.maxImage4": "0", "state.acq.inputVoltageRange1": "10", "state.acq.inputVoltageRange2": "10", "state.acq.inputVoltageRange3": "10", "state.acq.inputVoltageRange4": "10", "state.acq.inputVoltageInvert1": "0", "state.acq.inputVoltageInvert2": "0", "state.acq.inputVoltageInvert3": "0", "state.acq.inputVoltageInvert4": "0", "state.acq.numberOfChannelsSave": "1", "state.acq.numberOfChannelsAcquire": "1", "state.acq.maxMode": "0", "state.acq.fastScanningX": "1", "state.acq.fastScanningY": "0", "state.acq.framesPerFile": "Inf", "state.acq.clockExport.frameClockPolarityHigh": "1", "state.acq.clockExport.frameClockPolarityLow": "0", "state.acq.clockExport.frameClockGateSource": "0", "state.acq.clockExport.frameClockEnable": "1", "state.acq.clockExport.frameClockPhaseShiftUS": "0", "state.acq.clockExport.frameClockGated": "0", "state.acq.clockExport.lineClockPolarityHigh": "1", "state.acq.clockExport.lineClockPolarityLow": "0", "state.acq.clockExport.lineClockGatedEnable": "0", "state.acq.clockExport.lineClockGateSource": "0", "state.acq.clockExport.lineClockAutoSource": "1", "state.acq.clockExport.lineClockEnable": "0", "state.acq.clockExport.lineClockPhaseShiftUS": "0", "state.acq.clockExport.lineClockGated": "0", "state.acq.clockExport.pixelClockPolarityHigh": "1", "state.acq.clockExport.pixelClockPolarityLow": "0", "state.acq.clockExport.pixelClockGateSource": "0", "state.acq.clockExport.pixelClockAutoSource": "1", "state.acq.clockExport.pixelClockEnable": "0", "state.acq.clockExport.pixelClockPhaseShiftUS": "0", "state.acq.clockExport.pixelClockGated": "0", "state.init.eom.powerTransitions.timeString": "\'\'", "state.init.eom.powerTransitions.powerString": "\'\'", "state.init.eom.powerTransitions.transitionCountString": "\'\'", "state.init.eom.uncagingPulseImporter.pathnameText": "\'\'", "state.init.eom.uncagingPulseImporter.powerConversionFactor": "1", "state.init.eom.uncagingPulseImporter.lineConversionFactor": "2", "state.init.eom.uncagingPulseImporter.enabled": "0", "state.init.eom.uncagingPulseImporter.currentPosition": "0", "state.init.eom.uncagingPulseImporter.syncToPhysiology": "0", "state.init.eom.powerBoxStepper.pbsArrayString": "\'[]\'", "state.init.eom.uncagingMapper.enabled": "0", "state.init.eom.uncagingMapper.perGrab": "1", "state.init.eom.uncagingMapper.perFrame": "0", "state.init.eom.uncagingMapper.numberOfPixels": "4", "state.init.eom.uncagingMapper.pixelGenerationUserFunction": "\'\'", "state.init.eom.uncagingMapper.currentPixels": "[]", "state.init.eom.uncagingMapper.currentPosition": "[]", "state.init.eom.uncagingMapper.syncToPhysiology": "0", "state.init.eom.numberOfBeams": "0", "state.init.eom.focusLaserList": "\'PockelsCell-1\'", "state.init.eom.grabLaserList": "\'PockelsCell-1\'", "state.init.eom.snapLaserList": "\'PockelsCell-1\'", "state.init.eom.maxPhotodiodeVoltage": "0", "state.init.eom.boxWidth": "[]", "state.init.eom.powerBoxWidthsInMs": "[]", "state.init.eom.min": "[]", "state.init.eom.maxPower": "[]", "state.init.eom.usePowerArray": "0", "state.init.eom.showBoxArray": "[]", "state.init.eom.boxPowerArray": "[]", "state.init.eom.boxPowerOffArray": "[]", "state.init.eom.startFrameArray": "[]", "state.init.eom.endFrameArray": "[]", "state.init.eom.powerBoxNormCoords": "[]", "state.init.eom.powerVsZEnable": "1", "state.init.eom.powerLzArray": "[]", "state.init.eom.powerLzOverride": "0", "state.cycle.cycleOn": "0", "state.cycle.cycleName": "\'\'", "state.cycle.cyclePath": "\'\'", "state.cycle.cycleLength": "2", "state.cycle.numCycleRepeats": "1", "state.motor.motorZEnable": "0", "state.motor.absXPosition": "659.6", "state.motor.absYPosition": "-10386.6", "state.motor.absZPosition": "-8068.4", "state.motor.absZZPosition": "NaN", "state.motor.relXPosition": "0", "state.motor.relYPosition": "0", "state.motor.relZPosition": "-5.99999999999909", "state.motor.relZZPosition": "NaN", "state.motor.distance": "5.99999999999909", "state.internal.averageSamples": "0", "state.internal.highPixelValue1": "16384", "state.internal.lowPixelValue1": "0", "state.internal.highPixelValue2": "16384", "state.internal.lowPixelValue2": "0", "state.internal.highPixelValue3": "500", "state.internal.lowPixelValue3": "0", "state.internal.highPixelValue4": "500", "state.internal.lowPixelValue4": "0", "state.internal.figureColormap1": "\'$scim_colorMap(\'\'gray\'\',8,5)\'", "state.internal.figureColormap2": "\'$scim_colorMap(\'\'gray\'\',8,5)\'", "state.internal.figureColormap3": "\'$scim_colorMap(\'\'gray\'\',8,5)\'", "state.internal.figureColormap4": "\'$scim_colorMap(\'\'gray\'\',8,5)\'", "state.internal.repeatCounter": "0", "state.internal.startupTimeString": "\'10/9/2017 14:38:30.957\'", "state.internal.triggerTimeString": "\'10/9/2017 16:57:07.967\'", "state.internal.softTriggerTimeString": "\'10/9/2017 16:57:07.970\'", "state.internal.triggerTimeFirstString": "\'10/9/2017 16:57:07.967\'", "state.internal.triggerFrameDelayMS": "0", "state.init.eom.powerConversion1": "10", "state.init.eom.rejected_light1": "0", "state.init.eom.photodiodeOffset1": "0", "state.init.eom.powerConversion2": "10", "state.init.eom.rejected_light2": "0", "state.init.eom.photodiodeOffset2": "0", "state.init.eom.powerConversion3": "10", "state.init.eom.rejected_light3": "0", "state.init.eom.photodiodeOffset3": "0", "state.init.voltsPerOpticalDegree": "0.333", "state.init.scanOffsetAngleX": "0", "state.init.scanOffsetAngleY": "0"}'
)
class TestHdf5ImagingInterface(ImagingExtractorInterfaceTestMixin):
data_interface_cls = Hdf5ImagingInterface
interface_kwargs = dict(file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "hdf5" / "demoMovie.hdf5"))
save_directory = OUTPUT_PATH
class TestSbxImagingInterfaceMat(ImagingExtractorInterfaceTestMixin):
data_interface_cls = SbxImagingInterface
interface_kwargs = dict(file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Scanbox" / "sample.mat"))
save_directory = OUTPUT_PATH
class TestSbxImagingInterfaceSBX(ImagingExtractorInterfaceTestMixin):
data_interface_cls = SbxImagingInterface
interface_kwargs = dict(file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Scanbox" / "sample.sbx"))
save_directory = OUTPUT_PATH
class TestBrukerTiffImagingInterface(ImagingExtractorInterfaceTestMixin):
data_interface_cls = BrukerTiffSinglePlaneImagingInterface
interface_kwargs = dict(
folder_path=str(
OPHYS_DATA_PATH / "imaging_datasets" / "BrukerTif" / "NCCR32_2023_02_20_Into_the_void_t_series_baseline-000"
)
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(cls, request):
cls = request.cls
cls.device_metadata = dict(name="BrukerFluorescenceMicroscope", description="Version 5.6.64.400")
cls.optical_channel_metadata = dict(
name="Ch2",
emission_lambda=np.nan,
description="An optical channel of the microscope.",
)
cls.imaging_plane_metadata = dict(
name="ImagingPlane",
description="The imaging plane origin_coords units are in the microscope reference frame.",
excitation_lambda=np.nan,
indicator="unknown",
location="unknown",
device=cls.device_metadata["name"],
optical_channel=[cls.optical_channel_metadata],
imaging_rate=29.873732099062256,
grid_spacing=[1.1078125e-06, 1.1078125e-06],
origin_coords=[0.0, 0.0],
)
cls.two_photon_series_metadata = dict(
name="TwoPhotonSeries",
description="Imaging data acquired from the Bruker Two-Photon Microscope.",
unit="n.a.",
dimension=[512, 512],
imaging_plane=cls.imaging_plane_metadata["name"],
scan_line_rate=15840.580398865815,
field_of_view=[0.0005672, 0.0005672],
)
cls.ophys_metadata = dict(
Device=[cls.device_metadata],
ImagingPlane=[cls.imaging_plane_metadata],
TwoPhotonSeries=[cls.two_photon_series_metadata],
)
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2023, 2, 20, 15, 58, 25)
assert metadata["Ophys"] == self.ophys_metadata
def check_read_nwb(self, nwbfile_path: str):
"""Check the ophys metadata made it to the NWB file"""
with NWBHDF5IO(nwbfile_path, "r") as io:
nwbfile = io.read()
assert self.device_metadata["name"] in nwbfile.devices
assert nwbfile.devices[self.device_metadata["name"]].description == self.device_metadata["description"]
assert self.imaging_plane_metadata["name"] in nwbfile.imaging_planes
imaging_plane = nwbfile.imaging_planes[self.imaging_plane_metadata["name"]]
optical_channel = imaging_plane.optical_channel[0]
assert optical_channel.name == self.optical_channel_metadata["name"]
assert optical_channel.description == self.optical_channel_metadata["description"]
assert imaging_plane.description == self.imaging_plane_metadata["description"]
assert imaging_plane.imaging_rate == self.imaging_plane_metadata["imaging_rate"]
assert_array_equal(imaging_plane.grid_spacing[:], self.imaging_plane_metadata["grid_spacing"])
assert self.two_photon_series_metadata["name"] in nwbfile.acquisition
two_photon_series = nwbfile.acquisition[self.two_photon_series_metadata["name"]]
assert two_photon_series.description == self.two_photon_series_metadata["description"]
assert two_photon_series.unit == self.two_photon_series_metadata["unit"]
assert two_photon_series.scan_line_rate == self.two_photon_series_metadata["scan_line_rate"]
assert_array_equal(two_photon_series.field_of_view[:], self.two_photon_series_metadata["field_of_view"])
super().check_read_nwb(nwbfile_path=nwbfile_path)
class TestBrukerTiffImagingInterfaceDualPlaneCase(ImagingExtractorInterfaceTestMixin):
data_interface_cls = BrukerTiffMultiPlaneImagingInterface
interface_kwargs = dict(
folder_path=str(
OPHYS_DATA_PATH / "imaging_datasets" / "BrukerTif" / "NCCR32_2022_11_03_IntoTheVoid_t_series-005"
),
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(self, request):
cls = request.cls
cls.photon_series_name = "TwoPhotonSeries"
cls.num_samples = 5
cls.image_shape = (512, 512, 2)
cls.device_metadata = dict(name="BrukerFluorescenceMicroscope", description="Version 5.6.64.400")
cls.available_streams = dict(channel_streams=["Ch2"], plane_streams=dict(Ch2=["Ch2_000001"]))
cls.optical_channel_metadata = dict(
name="Ch2",
emission_lambda=np.nan,
description="An optical channel of the microscope.",
)
cls.imaging_plane_metadata = dict(
name="ImagingPlane",
description="The imaging plane origin_coords units are in the microscope reference frame.",
excitation_lambda=np.nan,
indicator="unknown",
location="unknown",
device=cls.device_metadata["name"],
optical_channel=[cls.optical_channel_metadata],
imaging_rate=20.629515014336377,
grid_spacing=[1.1078125e-06, 1.1078125e-06, 0.00026],
origin_coords=[56.215, 14.927, 260.0],
)
cls.two_photon_series_metadata = dict(
name="TwoPhotonSeries",
description="The volumetric imaging data acquired from the Bruker Two-Photon Microscope.",
unit="n.a.",
dimension=[512, 512, 2],
imaging_plane=cls.imaging_plane_metadata["name"],
scan_line_rate=15842.086085895791,
field_of_view=[0.0005672, 0.0005672, 0.00026],
)
cls.ophys_metadata = dict(
Device=[cls.device_metadata],
ImagingPlane=[cls.imaging_plane_metadata],
TwoPhotonSeries=[cls.two_photon_series_metadata],
)
def run_custom_checks(self):
# check stream names
streams = self.data_interface_cls.get_streams(
folder_path=self.interface_kwargs["folder_path"], plane_separation_type="contiguous"
)
assert streams == self.available_streams
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2022, 11, 3, 11, 20, 34)
assert metadata["Ophys"] == self.ophys_metadata
def check_read_nwb(self, nwbfile_path: str):
with NWBHDF5IO(path=nwbfile_path) as io:
nwbfile = io.read()
photon_series = nwbfile.acquisition[self.photon_series_name]
assert photon_series.data.shape == (self.num_samples, *self.image_shape)
np.testing.assert_array_equal(photon_series.dimension[:], self.image_shape)
assert photon_series.rate == 20.629515014336377
class TestBrukerTiffImagingInterfaceDualPlaneDisjointCase(ImagingExtractorInterfaceTestMixin):
data_interface_cls = BrukerTiffSinglePlaneImagingInterface
interface_kwargs = dict(
folder_path=str(
OPHYS_DATA_PATH / "imaging_datasets" / "BrukerTif" / "NCCR32_2022_11_03_IntoTheVoid_t_series-005"
),
stream_name="Ch2_000002",
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(cls, request):
cls = request.cls
cls.photon_series_name = "TwoPhotonSeriesCh2000002"
cls.num_samples = 5
cls.image_shape = (512, 512)
cls.device_metadata = dict(name="BrukerFluorescenceMicroscope", description="Version 5.6.64.400")
cls.available_streams = dict(channel_streams=["Ch2"], plane_streams=dict(Ch2=["Ch2_000001", "Ch2_000002"]))
cls.optical_channel_metadata = dict(
name="Ch2",
emission_lambda=np.nan,
description="An optical channel of the microscope.",
)
cls.imaging_plane_metadata = dict(
name="ImagingPlaneCh2000002",
description="The imaging plane origin_coords units are in the microscope reference frame.",
excitation_lambda=np.nan,
indicator="unknown",
location="unknown",
device=cls.device_metadata["name"],
optical_channel=[cls.optical_channel_metadata],
imaging_rate=10.314757507168189,
grid_spacing=[1.1078125e-06, 1.1078125e-06, 0.00013],
origin_coords=[56.215, 14.927, 130.0],
)
cls.two_photon_series_metadata = dict(
name=cls.photon_series_name,
description="Imaging data acquired from the Bruker Two-Photon Microscope.",
unit="n.a.",
dimension=[512, 512],
imaging_plane=cls.imaging_plane_metadata["name"],
scan_line_rate=15842.086085895791,
field_of_view=[0.0005672, 0.0005672, 0.00013],
)
cls.ophys_metadata = dict(
Device=[cls.device_metadata],
ImagingPlane=[cls.imaging_plane_metadata],
TwoPhotonSeries=[cls.two_photon_series_metadata],
)
def run_custom_checks(self):
# check stream names
streams = self.data_interface_cls.get_streams(folder_path=self.interface_kwargs["folder_path"])
assert streams == self.available_streams
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2022, 11, 3, 11, 20, 34)
assert metadata["Ophys"] == self.ophys_metadata
def check_nwbfile_temporal_alignment(self):
nwbfile_path = str(
self.save_directory
/ f"{self.data_interface_cls.__name__}_{self.test_name}_test_starting_time_alignment.nwb"
)
interface = self.data_interface_cls(**self.interface_kwargs)
aligned_starting_time = 1.23
interface.set_aligned_starting_time(aligned_starting_time=aligned_starting_time)
metadata = interface.get_metadata()
interface.run_conversion(nwbfile_path=nwbfile_path, overwrite=True, metadata=metadata)
with NWBHDF5IO(path=nwbfile_path) as io:
nwbfile = io.read()
assert nwbfile.acquisition[self.photon_series_name].starting_time == aligned_starting_time
def check_read_nwb(self, nwbfile_path: str):
with NWBHDF5IO(path=nwbfile_path) as io:
nwbfile = io.read()
photon_series = nwbfile.acquisition[self.photon_series_name]
assert photon_series.data.shape == (self.num_samples, *self.image_shape)
np.testing.assert_array_equal(photon_series.dimension[:], self.image_shape)
assert photon_series.rate == 10.314757507168189
class TestBrukerTiffImagingInterfaceDualColorCase(ImagingExtractorInterfaceTestMixin):
data_interface_cls = BrukerTiffSinglePlaneImagingInterface
interface_kwargs = dict(
folder_path=str(
OPHYS_DATA_PATH / "imaging_datasets" / "BrukerTif" / "NCCR62_2023_07_06_IntoTheVoid_t_series_Dual_color-000"
),
stream_name="Ch2",
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(cls, request):
cls = request.cls
cls.photon_series_name = "TwoPhotonSeriesCh2"
cls.num_samples = 10
cls.image_shape = (512, 512)
cls.device_metadata = dict(name="BrukerFluorescenceMicroscope", description="Version 5.8.64.200")
cls.available_streams = dict(channel_streams=["Ch1", "Ch2"], plane_streams=dict())
cls.optical_channel_metadata = dict(
name="Ch2",
emission_lambda=np.nan,
description="An optical channel of the microscope.",
)
cls.imaging_plane_metadata = dict(
name="ImagingPlaneCh2",
description="The imaging plane origin_coords units are in the microscope reference frame.",
excitation_lambda=np.nan,
indicator="unknown",
location="unknown",
device=cls.device_metadata["name"],
optical_channel=[cls.optical_channel_metadata],
imaging_rate=29.873615189896864,
grid_spacing=[1.1078125e-06, 1.1078125e-06],
origin_coords=[0.0, 0.0],
)
cls.two_photon_series_metadata = dict(
name=cls.photon_series_name,
description="Imaging data acquired from the Bruker Two-Photon Microscope.",
unit="n.a.",
dimension=[512, 512],
imaging_plane=cls.imaging_plane_metadata["name"],
scan_line_rate=15835.56350852745,
field_of_view=[0.0005672, 0.0005672],
)
cls.ophys_metadata = dict(
Device=[cls.device_metadata],
ImagingPlane=[cls.imaging_plane_metadata],
TwoPhotonSeries=[cls.two_photon_series_metadata],
)
def run_custom_checks(self):
# check stream names
streams = self.data_interface_cls.get_streams(folder_path=self.interface_kwargs["folder_path"])
assert streams == self.available_streams
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2023, 7, 6, 15, 13, 58)
assert metadata["Ophys"] == self.ophys_metadata
def check_read_nwb(self, nwbfile_path: str):
with NWBHDF5IO(path=nwbfile_path) as io:
nwbfile = io.read()
photon_series = nwbfile.acquisition[self.photon_series_name]
assert photon_series.data.shape == (self.num_samples, *self.image_shape)
np.testing.assert_array_equal(photon_series.dimension[:], self.image_shape)
assert photon_series.rate == 29.873615189896864
def check_nwbfile_temporal_alignment(self):
nwbfile_path = str(
self.save_directory
/ f"{self.data_interface_cls.__name__}_{self.test_name}_test_starting_time_alignment.nwb"
)
interface = self.data_interface_cls(**self.interface_kwargs)
aligned_starting_time = 1.23
interface.set_aligned_starting_time(aligned_starting_time=aligned_starting_time)
metadata = interface.get_metadata()
interface.run_conversion(nwbfile_path=nwbfile_path, overwrite=True, metadata=metadata)
with NWBHDF5IO(path=nwbfile_path) as io:
nwbfile = io.read()
assert nwbfile.acquisition[self.photon_series_name].starting_time == aligned_starting_time
class TestMicroManagerTiffImagingInterface(ImagingExtractorInterfaceTestMixin):
data_interface_cls = MicroManagerTiffImagingInterface
interface_kwargs = dict(
folder_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "MicroManagerTif" / "TS12_20220407_20hz_noteasy_1")
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(self, request):
cls = request.cls
cls.device_metadata = dict(name="Microscope")
cls.optical_channel_metadata = dict(
name="OpticalChannelDefault",
emission_lambda=np.nan,
description="An optical channel of the microscope.",
)
cls.imaging_plane_metadata = dict(
name="ImagingPlane",
description="The plane or volume being imaged by the microscope.",
excitation_lambda=np.nan,
indicator="unknown",
location="unknown",
device=cls.device_metadata["name"],
optical_channel=[cls.optical_channel_metadata],
imaging_rate=20.0,
)
cls.two_photon_series_metadata = dict(
name="TwoPhotonSeries",
description="Imaging data from two-photon excitation microscopy.",
unit="px",
dimension=[1024, 1024],
format="tiff",
imaging_plane=cls.imaging_plane_metadata["name"],
)
cls.ophys_metadata = dict(
Device=[cls.device_metadata],
ImagingPlane=[cls.imaging_plane_metadata],
TwoPhotonSeries=[cls.two_photon_series_metadata],
)
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(
2022, 4, 7, 15, 6, 56, 842000, tzinfo=tzoffset(None, -18000)
)
assert metadata["Ophys"] == self.ophys_metadata
def check_read_nwb(self, nwbfile_path: str):
"""Check the ophys metadata made it to the NWB file"""
# Assuming you would create and write an NWB file here before reading it back
with NWBHDF5IO(str(nwbfile_path), "r") as io:
nwbfile = io.read()
assert self.imaging_plane_metadata["name"] in nwbfile.imaging_planes
imaging_plane = nwbfile.imaging_planes[self.imaging_plane_metadata["name"]]
optical_channel = imaging_plane.optical_channel[0]
assert optical_channel.name == self.optical_channel_metadata["name"]
assert optical_channel.description == self.optical_channel_metadata["description"]
assert imaging_plane.description == self.imaging_plane_metadata["description"]
assert imaging_plane.imaging_rate == self.imaging_plane_metadata["imaging_rate"]
assert self.two_photon_series_metadata["name"] in nwbfile.acquisition
two_photon_series = nwbfile.acquisition[self.two_photon_series_metadata["name"]]
assert two_photon_series.description == self.two_photon_series_metadata["description"]
assert two_photon_series.unit == self.two_photon_series_metadata["unit"]
assert two_photon_series.format == self.two_photon_series_metadata["format"]
assert_array_equal(two_photon_series.dimension[:], self.two_photon_series_metadata["dimension"])
super().check_read_nwb(nwbfile_path=nwbfile_path)
class TestThorImagingInterface(ImagingExtractorInterfaceTestMixin):
"""Test ThorImagingInterface."""
channel_name = "ChanA"
optical_series_name: str = f"TwoPhotonSeries{channel_name}"
data_interface_cls = ThorImagingInterface
interface_kwargs = dict(
file_path=str(
OPHYS_DATA_PATH
/ "imaging_datasets"
/ "ThorlabsTiff"
/ "single_channel_single_plane"
/ "20231018-002"
/ "ChanA_001_001_001_001.tif"
),
channel_name="ChanA",
)
save_directory = OUTPUT_PATH
def check_extracted_metadata(self, metadata: dict):
"""Check that the metadata was extracted correctly."""
# Check session start time
assert isinstance(metadata["NWBFile"]["session_start_time"], datetime)
assert metadata["NWBFile"]["session_start_time"].year == 2023
assert metadata["NWBFile"]["session_start_time"].month == 10
assert metadata["NWBFile"]["session_start_time"].day == 18
assert metadata["NWBFile"]["session_start_time"].hour == 17
assert metadata["NWBFile"]["session_start_time"].minute == 39
assert metadata["NWBFile"]["session_start_time"].second == 19
# Check device metadata
assert len(metadata["Ophys"]["Device"]) == 1
device = metadata["Ophys"]["Device"][0]
assert device["name"] == "ThorMicroscope"
assert device["description"] == "ThorLabs 2P Microscope running ThorImageLS 5.0.2023.10041"
# Check imaging plane metadata
assert len(metadata["Ophys"]["ImagingPlane"]) == 1
imaging_plane = metadata["Ophys"]["ImagingPlane"][0]
assert imaging_plane["name"] == f"ImagingPlane{self.channel_name}"
assert imaging_plane["description"] == "2P Imaging Plane"
assert imaging_plane["device"] == "ThorMicroscope"
assert "grid_spacing" in imaging_plane
assert "grid_spacing_unit" in imaging_plane
# Check optical channel metadata
assert len(imaging_plane["optical_channel"]) == 1
optical_channel = imaging_plane["optical_channel"][0]
assert optical_channel["name"] == self.channel_name
# Check two photon series metadata
assert len(metadata["Ophys"]["TwoPhotonSeries"]) == 1
two_photon_series = metadata["Ophys"]["TwoPhotonSeries"][0]
assert two_photon_series["name"] == self.optical_series_name
class Test_MiniscopeMultiRecordingInterface(MiniscopeImagingInterfaceMixin):
data_interface_cls = _MiniscopeMultiRecordingInterface
interface_kwargs = dict(folder_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Miniscope" / "C6-J588_Disc5"))
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(cls, request):
cls = request.cls
cls.device_name = "Miniscope"
cls.device_metadata = dict(
name=cls.device_name,
compression="FFV1",
deviceType="Miniscope_V3",
frameRate="15FPS",
framesPerFile=1000,
gain="High",
led0=47,
)
cls.imaging_plane_name = "ImagingPlane"
cls.imaging_plane_metadata = dict(
name=cls.imaging_plane_name,
device=cls.device_name,
imaging_rate=15.037593984962406, # Actual rate calculated from timestamps
)
cls.photon_series_name = "OnePhotonSeries"
cls.photon_series_metadata = dict(
name=cls.photon_series_name,
unit="px",
)
def check_extracted_metadata(self, metadata: dict):
assert metadata["NWBFile"]["session_start_time"] == datetime(2021, 10, 7, 15, 3, 28, 635)
assert metadata["Ophys"]["Device"][0] == self.device_metadata
imaging_plane_metadata = metadata["Ophys"]["ImagingPlane"][0]
assert imaging_plane_metadata["name"] == self.imaging_plane_metadata["name"]
assert imaging_plane_metadata["device"] == self.imaging_plane_metadata["device"]
assert imaging_plane_metadata["imaging_rate"] == self.imaging_plane_metadata["imaging_rate"]
one_photon_series_metadata = metadata["Ophys"]["OnePhotonSeries"][0]
assert one_photon_series_metadata["name"] == self.photon_series_metadata["name"]
assert one_photon_series_metadata["unit"] == self.photon_series_metadata["unit"]
def test_incorrect_folder_structure_raises(self):
folder_path = Path(self.interface_kwargs["folder_path"]) / "15_03_28/BehavCam_2/"
with pytest.raises(
AssertionError, match="The main folder should contain at least one subfolder named 'Miniscope'."
):
self.data_interface_cls(folder_path=folder_path)
class TestMiniscopeImagingInterface(MiniscopeImagingInterfaceMixin):
data_interface_cls = MiniscopeImagingInterface
interface_kwargs = dict(
folder_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "Miniscope" / "C6-J588_Disc5" / "15_03_28" / "Miniscope")
)
save_directory = OUTPUT_PATH
@pytest.fixture(scope="class", autouse=True)
def setup_metadata(cls, request):
cls = request.cls
cls.device_name = "Miniscope"
cls.imaging_plane_name = "ImagingPlane"
cls.photon_series_name = "OnePhotonSeries"
cls.optical_series_name = "OnePhotonSeries"
def check_read_nwb(self, nwbfile_path: str):
"""Override check_read_nwb for single-recording interface expectations."""
import numpy as np
from ndx_miniscope import Miniscope
from pynwb import NWBHDF5IO
with NWBHDF5IO(nwbfile_path, "r") as io:
nwbfile = io.read()
assert self.device_name in nwbfile.devices
device = nwbfile.devices[self.device_name]
assert isinstance(device, Miniscope)
imaging_plane = nwbfile.imaging_planes[self.imaging_plane_name]
assert imaging_plane.device.name == self.device_name
# Check OnePhotonSeries - updated for single recording (5 frames, not 15)
assert self.photon_series_name in nwbfile.acquisition
one_photon_series = nwbfile.acquisition[self.photon_series_name]
assert one_photon_series.unit == "px"
assert one_photon_series.data.shape == (5, 752, 480) # Single recording has 5 frames
assert one_photon_series.data.dtype == np.uint8
# After roiextractors #509, MiniscopeImagingExtractor provides native timestamps
# from timeStamps.csv, so the photon series uses timestamps instead of rate
assert one_photon_series.rate is None # Uses timestamps instead of rate
assert one_photon_series.timestamps is not None # Now uses hardware timestamps
assert len(one_photon_series.timestamps) == 5
assert one_photon_series.starting_frame is None
# Verify that interface can get original timestamps
interface_times = self.interface.get_original_timestamps()
assert interface_times is not None
assert len(interface_times) == 5
# Verify timestamps match between interface and NWB
np.testing.assert_array_almost_equal(one_photon_series.timestamps[:], interface_times)
def test_file_paths_parameter(self):
"""Test using file_paths parameter for non-standard structures."""
miniscope_folder = (
OPHYS_DATA_PATH / "imaging_datasets" / "Miniscope" / "C6-J588_Disc5" / "15_03_28" / "Miniscope"
)
file_paths = [str(miniscope_folder / "0.avi")]
configuration_file_path = str(miniscope_folder / "metaData.json")
timestamps_path = str(miniscope_folder / "timeStamps.csv")
interface = self.data_interface_cls(
file_paths=file_paths,
configuration_file_path=configuration_file_path,
timeStamps_file_path=timestamps_path,
)
# Test that metadata extraction works
metadata = interface.get_metadata()
assert metadata["Ophys"]["Device"][0]["name"] == "Miniscope"
# Test that it has timestamps
timestamps = interface.get_original_timestamps()
assert timestamps is not None
assert len(timestamps) > 0
def test_parameter_validation(self):
"""Test parameter validation for mutually exclusive parameters."""
miniscope_folder = (
OPHYS_DATA_PATH / "imaging_datasets" / "Miniscope" / "C6-J588_Disc5" / "15_03_28" / "Miniscope"
)
# Test missing required parameters
with pytest.raises(ValueError, match="Either 'folder_path' must be provided"):
self.data_interface_cls()
# Test missing configuration_file_path when using file_paths
with pytest.raises(ValueError, match="Either 'folder_path' must be provided"):
self.data_interface_cls(file_paths=[str(miniscope_folder / "0.avi")])
# Test conflicting parameters
with pytest.raises(
ValueError,
match="When 'folder_path' is provided, 'file_paths' and 'configuration_file_path' cannot be specified",
):
self.data_interface_cls(
folder_path=str(miniscope_folder),
file_paths=[str(miniscope_folder / "0.avi")],
)
def test_session_start_time_extraction(self):
"""Test that session_start_time is extracted from parent folder metaData.json."""
from datetime import datetime
miniscope_folder = (
OPHYS_DATA_PATH / "imaging_datasets" / "Miniscope" / "C6-J588_Disc5" / "15_03_28" / "Miniscope"
)
interface = self.data_interface_cls(folder_path=str(miniscope_folder))
metadata = interface.get_metadata()
# Check that session_start_time was extracted
assert "session_start_time" in metadata["NWBFile"]
session_start_time = metadata["NWBFile"]["session_start_time"]
# Verify it's a datetime object
assert isinstance(session_start_time, datetime)
# Verify it matches the expected value from metaData.json
expected_start_time = datetime(2021, 10, 7, 15, 3, 28, 635000)
assert session_start_time == expected_start_time
skip_on_darwin_arm64 = pytest.mark.skipif(
platform.system() == "Darwin" and platform.machine() == "arm64",
reason="The isx package is currently not natively supported on macOS with Apple Silicon. "
"Installation instructions can be found at: "
"https://github.com/inscopix/pyisx?tab=readme-ov-file#install",
)
skip_on_python_313 = pytest.mark.skipif(
sys.version_info >= (3, 13),
reason="Tests are skipped on Python 3.13 because of incompatibility with the 'isx' module "
"Requires: Python <3.13, >=3.9)"
"See:https://github.com/inscopix/pyisx/issues",
)
@skip_on_python_313
@skip_on_darwin_arm64
class TestInscopixImagingInterfaceMovie128x128x100Part1(ImagingExtractorInterfaceTestMixin):
"""Test InscopixImagingInterface with movie_128x128x100_part1.isxd (minimal metadata file)."""
data_interface_cls = InscopixImagingInterface
save_directory = OUTPUT_PATH
interface_kwargs = dict(
file_path=str(OPHYS_DATA_PATH / "imaging_datasets" / "inscopix" / "movie_128x128x100_part1.isxd")
)
optical_series_name = "OnePhotonSeries"
def check_extracted_metadata(self, metadata: dict):
"""Test metadata extraction for file with minimal acquisition info."""
# NWBFile checks
nwbfile = metadata["NWBFile"]
assert nwbfile["session_start_time"] == datetime(1970, 1, 1, 0, 0, 0)
assert "session_id" not in nwbfile
assert "experimenter" not in nwbfile
# Device checks
device = metadata["Ophys"]["Device"][0]
assert device["name"] == "Microscope" # Default metadata because this was not included in the source metadata
assert "description" not in device or device.get("description", "") == ""
# ImagingPlane checks
imaging_plane = metadata["Ophys"]["ImagingPlane"][0]
assert imaging_plane["name"] == "ImagingPlane"
assert (
imaging_plane["device"] == "Microscope"
) # Default metadata because this was not included in the source metadata
assert (