Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test_io.py 7.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. Tests for the Suite2p IO module
  3. """
  4. import pathlib
  5. import platform
  6. import re
  7. from pathlib import Path
  8. import numpy as np
  9. import pytest
  10. from natsort import natsorted
  11. from pynwb import NWBHDF5IO
  12. from suite2p import io
  13. from suite2p.io.nwb import read_nwb, save_nwb
  14. from suite2p.io.utils import get_suite2p_path
  15. @pytest.fixture()
  16. def binfile1500(test_ops):
  17. test_ops["tiff_list"] = ["input_1500.tif"]
  18. op = io.tiff_to_binary(test_ops)
  19. bin_filename = str(Path(op["save_path0"]).joinpath("suite2p/plane0/data.bin"))
  20. with io.BinaryFile(
  21. Ly=op["Ly"], Lx=op["Lx"], filename=bin_filename
  22. ) as bin_file:
  23. yield bin_file
  24. @pytest.fixture(scope="function")
  25. def replace_ops_save_path_with_local_path(request):
  26. """
  27. This fixture replaces the `save_path` variable in the `ops.npy` file
  28. by its local path version
  29. """
  30. # Workaround to load pickled NPY files on Windows containing
  31. # `PosixPath` objects
  32. if platform.system() == "Windows":
  33. pathlib.PosixPath = pathlib.WindowsPath
  34. # Get the `data_folder` variable from the running test name
  35. data_folder = re.search(r"\[(.*?)(-.*?)?\]", request.node.name).group(1)
  36. save_folder = Path("data").joinpath("test_outputs", data_folder, "suite2p")
  37. save_path = {}
  38. plane_folders = [
  39. dir
  40. for dir in natsorted(save_folder.iterdir())
  41. if dir.is_dir() and "plane" in dir.name
  42. ]
  43. for plane_idx, plane_dir in enumerate(plane_folders):
  44. # Temporarily change the `save_folder` variable in the NumPy file
  45. ops1 = np.load(plane_dir.joinpath("ops.npy"), allow_pickle=True)
  46. save_path[plane_dir] = ops1.item(0)["save_path"]
  47. ops1.item(0)["save_path"] = str(plane_dir.absolute())
  48. np.save(plane_dir.joinpath("ops.npy"), ops1)
  49. def concat_npy(name: str) -> np.ndarray:
  50. """Concatenate arrays from NUmPy files."""
  51. for plane_idx, plane_dir in enumerate(plane_folders):
  52. if plane_idx == 0:
  53. array_npy = np.load(
  54. plane_dir.joinpath(f"{name}.npy"), allow_pickle=True
  55. )
  56. else:
  57. array_npy = np.append(
  58. array_npy,
  59. np.load(plane_dir.joinpath(f"{name}.npy"), allow_pickle=True),
  60. axis=0,
  61. )
  62. return array_npy
  63. iscell_npy = concat_npy("iscell")
  64. F_npy = concat_npy("F")
  65. Fneu_npy = concat_npy("Fneu")
  66. spks_npy = concat_npy("spks")
  67. yield save_folder, iscell_npy, F_npy, Fneu_npy, spks_npy
  68. # Teardown the fixture
  69. for plane_dir in plane_folders:
  70. # Undo the changes made in the NumPy file
  71. ops1 = np.load(plane_dir.joinpath("ops.npy"), allow_pickle=True)
  72. ops1.item(0)["save_path"] = save_path[plane_dir]
  73. np.save(plane_dir.joinpath("ops.npy"), ops1)
  74. def test_h5_to_binary_produces_nonnegative_output_data(test_ops):
  75. test_ops["h5py"] = Path(test_ops["data_path"][0]).joinpath("input.h5")
  76. test_ops["nplanes"] = 3
  77. test_ops["nchannels"] = 2
  78. test_ops["data_path"] = []
  79. op = io.h5py_to_binary(test_ops)
  80. output_data = io.BinaryFile(
  81. filename=Path(op["save_path0"], "suite2p/plane0/data.bin"),
  82. Ly=op["Ly"],
  83. Lx=op["Lx"],
  84. ).data
  85. assert np.all(output_data >= 0)
  86. def test_that_bin_movie_without_badframes_results_in_a_same_size_array(binfile1500):
  87. mov = binfile1500.bin_movie(bin_size=1)
  88. assert mov.shape == (1500, binfile1500.Ly, binfile1500.Lx)
  89. def test_that_bin_movie_with_badframes_results_in_a_smaller_array(binfile1500):
  90. np.random.seed(42)
  91. bad_frames = np.random.randint(2, size=binfile1500.n_frames, dtype=bool)
  92. mov = binfile1500.bin_movie(bin_size=1, bad_frames=bad_frames, reject_threshold=0)
  93. assert len(mov) < binfile1500.n_frames, "bin_movie didn't produce a smaller array."
  94. assert len(mov) == len(bad_frames) - sum(
  95. bad_frames
  96. ), "bin_movie didn't produce the right size array."
  97. def test_that_binaryfile_data_is_repeatable(binfile1500):
  98. data1 = binfile1500.data
  99. assert data1.shape == (1500, binfile1500.Ly, binfile1500.Lx)
  100. data2 = binfile1500.data
  101. assert data2.shape == (1500, binfile1500.Ly, binfile1500.Lx)
  102. assert np.allclose(data1, data2)
  103. @pytest.mark.parametrize(
  104. "data_folder",
  105. [
  106. ("1plane1chan1500"),
  107. ("2plane2chan1500"),
  108. ("bruker"),
  109. ],
  110. )
  111. def test_nwb_round_trip(replace_ops_save_path_with_local_path, data_folder):
  112. # Get expected data already saved as NumPy files
  113. (
  114. save_folder,
  115. expected_iscell,
  116. expected_F,
  117. expected_Fneu,
  118. expected_spks,
  119. ) = replace_ops_save_path_with_local_path
  120. # Save as NWB file
  121. save_nwb(save_folder)
  122. # Check (some of) the structure of the NWB file saved
  123. nwb_path = save_folder.joinpath("ophys.nwb")
  124. assert nwb_path.exists()
  125. with NWBHDF5IO(str(nwb_path), "r") as io:
  126. read_nwbfile = io.read()
  127. assert read_nwbfile.processing
  128. ophys = read_nwbfile.processing["ophys"]
  129. assert ophys.data_interfaces["Deconvolved"]
  130. Fluorescence = ophys.data_interfaces["Fluorescence"]
  131. assert Fluorescence
  132. if "2plane" in data_folder:
  133. assert Fluorescence["plane0"]
  134. assert Fluorescence["plane1"]
  135. assert ophys.data_interfaces["Neuropil"]
  136. if "2chan" in data_folder:
  137. Fluorescence_chan2 = ophys.data_interfaces["Fluorescence_chan2"]
  138. assert Fluorescence_chan2
  139. assert ophys.data_interfaces["Neuropil_chan2"]
  140. iscell_nwb = (
  141. ophys.data_interfaces["ImageSegmentation"]
  142. .plane_segmentations["PlaneSegmentation"]
  143. .columns[2]
  144. .data[:]
  145. )
  146. np.testing.assert_array_equal(iscell_nwb, expected_iscell)
  147. # Extract Suite2p info from NWB file
  148. stat, ops, F, Fneu, spks, iscell, probcell, redcell, probredcell = read_nwb(
  149. nwb_path
  150. )
  151. # Check we get the same data back as the original data
  152. # after saving to NWB + reading
  153. np.testing.assert_array_equal(F, expected_F)
  154. np.testing.assert_array_equal(Fneu, expected_Fneu)
  155. np.testing.assert_array_equal(spks, expected_spks)
  156. np.testing.assert_array_equal(
  157. np.transpose(np.array([iscell, probcell])), expected_iscell
  158. )
  159. # TODO: assert round trip for `stat` and `ops`
  160. # Probably need to recreate the data files as some fields are missing in the dict
  161. # expected_stat = np.load(save_folder.joinpath("plane0", "stat.npy"), allow_pickle=True)
  162. # expected_ops = np.load(save_folder.joinpath("plane0", "ops.npy"), allow_pickle=True)
  163. # np.testing.assert_equal(stat, expected_stat)
  164. # np.testing.assert_equal(ops, expected_ops)
  165. # Remove NWB file
  166. nwb_path.unlink()
  167. @pytest.mark.parametrize(
  168. "input_path, expected_path, success",
  169. [
  170. (
  171. "D:/kjkcc/jodendopn/suite2p/ncconoc/onowcno",
  172. "D:/kjkcc/jodendopn/suite2p",
  173. True,
  174. ),
  175. (
  176. "/home/bla/kjkcc/jodendopn/suite2p/ops.npy",
  177. "/home/bla/kjkcc/jodendopn/suite2p",
  178. True,
  179. ),
  180. ("/etc/bla/kjkcc/jodendopn/suite2p", "/etc/bla/kjkcc/jodendopn/suite2p", True),
  181. ("/etc/bla/kjkcc/jodendopn/", "", False),
  182. ],
  183. )
  184. def test_get_suite2p_path(input_path, expected_path, success):
  185. if success:
  186. res_path = get_suite2p_path(input_path)
  187. assert res_path == Path(expected_path)
  188. else:
  189. with pytest.raises(FileNotFoundError):
  190. get_suite2p_path(Path(input_path))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...