ephys-link 2.0.0b6__py3-none-any.whl → 2.0.0b10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,278 +1,315 @@
1
- """Bindings for New Scale Pathfinder MPM HTTP server platform.
2
-
3
- MPM works slightly differently than the other platforms since it operates in stereotactic coordinates.
4
- This means exceptions need to be made for its API.
5
-
6
- Usage: Instantiate MPMBindings to interact with the New Scale Pathfinder MPM HTTP server platform.
7
- """
8
-
9
- from asyncio import get_running_loop, sleep
10
- from json import dumps
11
- from typing import Any
12
-
13
- from requests import JSONDecodeError, get, put
14
- from vbl_aquarium.models.unity import Vector3, Vector4
15
-
16
- from ephys_link.util.base_bindings import BaseBindings
17
- from ephys_link.util.common import scalar_mm_to_um, vector4_to_array
18
-
19
-
20
- class MPMBinding(BaseBindings):
21
- """Bindings for New Scale Pathfinder MPM HTTP server platform."""
22
-
23
- # Valid New Scale manipulator IDs
24
- VALID_MANIPULATOR_IDS = (
25
- "A",
26
- "B",
27
- "C",
28
- "D",
29
- "E",
30
- "F",
31
- "G",
32
- "H",
33
- "I",
34
- "J",
35
- "K",
36
- "L",
37
- "M",
38
- "N",
39
- "O",
40
- "P",
41
- "Q",
42
- "R",
43
- "S",
44
- "T",
45
- "U",
46
- "V",
47
- "W",
48
- "X",
49
- "Y",
50
- "Z",
51
- "AA",
52
- "AB",
53
- "AC",
54
- "AD",
55
- "AE",
56
- "AF",
57
- "AG",
58
- "AH",
59
- "AI",
60
- "AJ",
61
- "AK",
62
- "AL",
63
- "AM",
64
- "AN",
65
- )
66
-
67
- # Movement polling preferences.
68
- UNCHANGED_COUNTER_LIMIT = 10
69
- POLL_INTERVAL = 0.1
70
-
71
- # Speed preferences (mm/s to use coarse mode).
72
- COARSE_SPEED_THRESHOLD = 0.1
73
- INSERTION_SPEED_LIMIT = 9_000
74
-
75
- def __init__(self, port: int) -> None:
76
- """Initialize connection to MPM HTTP server.
77
-
78
- :param port: Port number for MPM HTTP server.
79
- :type port: int
80
- """
81
- self._url = f"http://localhost:{port}"
82
- self._movement_stopped = False
83
-
84
- async def get_manipulators(self) -> list[str]:
85
- return [manipulator["Id"] for manipulator in (await self._query_data())["ProbeArray"]]
86
-
87
- async def get_axes_count(self) -> int:
88
- return 3
89
-
90
- def get_dimensions(self) -> Vector4:
91
- return Vector4(x=15, y=15, z=15, w=15)
92
-
93
- async def get_position(self, manipulator_id: str) -> Vector4:
94
- manipulator_data = await self._manipulator_data(manipulator_id)
95
- stage_z = manipulator_data["Stage_Z"]
96
-
97
- await sleep(self.POLL_INTERVAL) # Wait for the stage to stabilize.
98
-
99
- return Vector4(
100
- x=manipulator_data["Stage_X"],
101
- y=manipulator_data["Stage_Y"],
102
- z=stage_z,
103
- w=stage_z,
104
- )
105
-
106
- async def get_angles(self, manipulator_id: str) -> Vector3:
107
- manipulator_data = await self._manipulator_data(manipulator_id)
108
-
109
- # Apply PosteriorAngle to Polar to get the correct angle.
110
- adjusted_polar = manipulator_data["Polar"] - (await self._query_data())["PosteriorAngle"]
111
-
112
- return Vector3(
113
- x=adjusted_polar if adjusted_polar > 0 else 360 + adjusted_polar,
114
- y=manipulator_data["Pitch"],
115
- z=manipulator_data["ShankOrientation"],
116
- )
117
-
118
- async def get_shank_count(self, manipulator_id: str) -> int:
119
- return int((await self._manipulator_data(manipulator_id))["ShankCount"])
120
-
121
- def get_movement_tolerance(self) -> float:
122
- return 0.01
123
-
124
- async def set_position(self, manipulator_id: str, position: Vector4, speed: float) -> Vector4:
125
- # Keep track of the previous position to check if the manipulator stopped advancing.
126
- current_position = await self.get_position(manipulator_id)
127
- previous_position = current_position
128
- unchanged_counter = 0
129
-
130
- # Set step mode based on speed.
131
- await self._put_request(
132
- {
133
- "PutId": "ProbeStepMode",
134
- "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
135
- "StepMode": 0 if speed > self.COARSE_SPEED_THRESHOLD else 1,
136
- }
137
- )
138
-
139
- # Send move request.
140
- await self._put_request(
141
- {
142
- "PutId": "ProbeMotion",
143
- "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
144
- "Absolute": 1,
145
- "Stereotactic": 0,
146
- "AxisMask": 7,
147
- "X": position.x,
148
- "Y": position.y,
149
- "Z": position.z,
150
- }
151
- )
152
-
153
- # Wait for the manipulator to reach the target position or be stopped or stuck.
154
- while (
155
- not self._movement_stopped
156
- and not self._is_vector_close(current_position, position)
157
- and unchanged_counter < self.UNCHANGED_COUNTER_LIMIT
158
- ):
159
- # Wait for a short time before checking again.
160
- await sleep(self.POLL_INTERVAL)
161
-
162
- # Update current position.
163
- current_position = await self.get_position(manipulator_id)
164
-
165
- # Check if manipulator is not moving.
166
- if self._is_vector_close(previous_position, current_position):
167
- # Position did not change.
168
- unchanged_counter += 1
169
- else:
170
- # Position changed.
171
- unchanged_counter = 0
172
- previous_position = current_position
173
-
174
- # Reset movement stopped flag.
175
- self._movement_stopped = False
176
-
177
- # Return the final position.
178
- return await self.get_position(manipulator_id)
179
-
180
- async def set_depth(self, manipulator_id: str, depth: float, speed: float) -> float:
181
- # Keep track of the previous depth to check if the manipulator stopped advancing unexpectedly.
182
- current_depth = (await self.get_position(manipulator_id)).w
183
- previous_depth = current_depth
184
- unchanged_counter = 0
185
-
186
- # Send move request.
187
- # Convert mm/s to um/min and cap speed at the limit.
188
- await self._put_request(
189
- {
190
- "PutId": "ProbeInsertion",
191
- "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
192
- "Distance": scalar_mm_to_um(current_depth - depth),
193
- "Rate": min(scalar_mm_to_um(speed) * 60, self.INSERTION_SPEED_LIMIT),
194
- }
195
- )
196
-
197
- # Wait for the manipulator to reach the target depth or be stopped or get stuck.
198
- while not self._movement_stopped and not abs(current_depth - depth) <= self.get_movement_tolerance():
199
- # Wait for a short time before checking again.
200
- await sleep(self.POLL_INTERVAL)
201
-
202
- # Get the current depth.
203
- current_depth = (await self.get_position(manipulator_id)).w
204
-
205
- # Check if manipulator is not moving.
206
- if abs(previous_depth - current_depth) <= self.get_movement_tolerance():
207
- # Depth did not change.
208
- unchanged_counter += 1
209
- else:
210
- # Depth changed.
211
- unchanged_counter = 0
212
- previous_depth = current_depth
213
-
214
- # Reset movement stopped flag.
215
- self._movement_stopped = False
216
-
217
- # Return the final depth.
218
- return float((await self.get_position(manipulator_id)).w)
219
-
220
- async def stop(self, manipulator_id: str) -> None:
221
- request = {"PutId": "ProbeStop", "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id)}
222
- await self._put_request(request)
223
- self._movement_stopped = True
224
-
225
- def platform_space_to_unified_space(self, platform_space: Vector4) -> Vector4:
226
- # unified <- platform
227
- # +x <- -x
228
- # +y <- +z
229
- # +z <- +y
230
- # +w <- -w
231
-
232
- return Vector4(
233
- x=self.get_dimensions().x - platform_space.x,
234
- y=platform_space.z,
235
- z=platform_space.y,
236
- w=self.get_dimensions().w - platform_space.w,
237
- )
238
-
239
- def unified_space_to_platform_space(self, unified_space: Vector4) -> Vector4:
240
- # platform <- unified
241
- # +x <- -x
242
- # +y <- +z
243
- # +z <- +y
244
- # +w <- -w
245
-
246
- return Vector4(
247
- x=self.get_dimensions().x - unified_space.x,
248
- y=unified_space.z,
249
- z=unified_space.y,
250
- w=self.get_dimensions().w - unified_space.w,
251
- )
252
-
253
- # Helper functions.
254
- async def _query_data(self) -> Any:
255
- try:
256
- return (await get_running_loop().run_in_executor(None, get, self._url)).json()
257
- except ConnectionError as connectionError:
258
- error_message = f"Unable to connect to MPM HTTP server: {connectionError}"
259
- raise RuntimeError(error_message) from connectionError
260
- except JSONDecodeError as jsonDecodeError:
261
- error_message = f"Unable to decode JSON response from MPM HTTP server: {jsonDecodeError}"
262
- raise ValueError(error_message) from jsonDecodeError
263
-
264
- async def _manipulator_data(self, manipulator_id: str) -> Any:
265
- probe_data = (await self._query_data())["ProbeArray"]
266
- for probe in probe_data:
267
- if probe["Id"] == manipulator_id:
268
- return probe
269
-
270
- # If we get here, that means the manipulator doesn't exist.
271
- error_message = f"Manipulator {manipulator_id} not found."
272
- raise ValueError(error_message)
273
-
274
- async def _put_request(self, request: dict[str, Any]) -> None:
275
- await get_running_loop().run_in_executor(None, put, self._url, dumps(request))
276
-
277
- def _is_vector_close(self, target: Vector4, current: Vector4) -> bool:
278
- return all(abs(axis) <= self.get_movement_tolerance() for axis in vector4_to_array(target - current)[:3])
1
+ """Bindings for New Scale Pathfinder MPM HTTP server platform.
2
+
3
+ Usage: Instantiate MPMBindings to interact with the New Scale Pathfinder MPM HTTP server platform.
4
+ """
5
+
6
+ from asyncio import get_running_loop, sleep
7
+ from json import dumps
8
+ from typing import Any, final, override
9
+
10
+ from requests import JSONDecodeError, get, put
11
+ from vbl_aquarium.models.unity import Vector3, Vector4
12
+
13
+ from ephys_link.utils.base_binding import BaseBinding
14
+ from ephys_link.utils.converters import scalar_mm_to_um, vector4_to_array
15
+
16
+
17
+ @final
18
+ class MPMBinding(BaseBinding):
19
+ """Bindings for New Scale Pathfinder MPM HTTP server platform."""
20
+
21
+ # Valid New Scale manipulator IDs
22
+ VALID_MANIPULATOR_IDS = (
23
+ "A",
24
+ "B",
25
+ "C",
26
+ "D",
27
+ "E",
28
+ "F",
29
+ "G",
30
+ "H",
31
+ "I",
32
+ "J",
33
+ "K",
34
+ "L",
35
+ "M",
36
+ "N",
37
+ "O",
38
+ "P",
39
+ "Q",
40
+ "R",
41
+ "S",
42
+ "T",
43
+ "U",
44
+ "V",
45
+ "W",
46
+ "X",
47
+ "Y",
48
+ "Z",
49
+ "AA",
50
+ "AB",
51
+ "AC",
52
+ "AD",
53
+ "AE",
54
+ "AF",
55
+ "AG",
56
+ "AH",
57
+ "AI",
58
+ "AJ",
59
+ "AK",
60
+ "AL",
61
+ "AM",
62
+ "AN",
63
+ )
64
+
65
+ # Server cache lifetime (60 FPS).
66
+ CACHE_LIFETIME = 1 / 60
67
+
68
+ # Movement polling preferences.
69
+ UNCHANGED_COUNTER_LIMIT = 10
70
+ POLL_INTERVAL = 0.1
71
+
72
+ # Speed preferences (mm/s to use coarse mode).
73
+ COARSE_SPEED_THRESHOLD = 0.1
74
+ INSERTION_SPEED_LIMIT = 9_000
75
+
76
+ def __init__(self, port: int = 8080) -> None:
77
+ """Initialize connection to MPM HTTP server.
78
+
79
+ Args:
80
+ port: Port number for MPM HTTP server.
81
+ """
82
+ self._url = f"http://localhost:{port}"
83
+ self._movement_stopped = False
84
+
85
+ # Data cache.
86
+ self.cache: dict[str, Any] = {} # pyright: ignore [reportExplicitAny]
87
+ self.cache_time = 0
88
+
89
+ @staticmethod
90
+ @override
91
+ def get_display_name() -> str:
92
+ return "Pathfinder MPM Control v2.8.8+"
93
+
94
+ @staticmethod
95
+ @override
96
+ def get_cli_name() -> str:
97
+ return "pathfinder-mpm"
98
+
99
+ @override
100
+ async def get_manipulators(self) -> list[str]:
101
+ return [manipulator["Id"] for manipulator in (await self._query_data())["ProbeArray"]] # pyright: ignore [reportAny]
102
+
103
+ @override
104
+ async def get_axes_count(self) -> int:
105
+ return 3
106
+
107
+ @override
108
+ def get_dimensions(self) -> Vector4:
109
+ return Vector4(x=15, y=15, z=15, w=15)
110
+
111
+ @override
112
+ async def get_position(self, manipulator_id: str) -> Vector4:
113
+ manipulator_data: dict[str, float] = await self._manipulator_data(manipulator_id)
114
+ stage_z: float = manipulator_data["Stage_Z"]
115
+
116
+ await sleep(self.POLL_INTERVAL) # Wait for the stage to stabilize.
117
+
118
+ return Vector4(
119
+ x=manipulator_data["Stage_X"],
120
+ y=manipulator_data["Stage_Y"],
121
+ z=stage_z,
122
+ w=stage_z,
123
+ )
124
+
125
+ @override
126
+ async def get_angles(self, manipulator_id: str) -> Vector3:
127
+ manipulator_data: dict[str, float] = await self._manipulator_data(manipulator_id)
128
+
129
+ # Apply PosteriorAngle to Polar to get the correct angle.
130
+ adjusted_polar: int = manipulator_data["Polar"] - (await self._query_data())["PosteriorAngle"]
131
+
132
+ return Vector3(
133
+ x=adjusted_polar if adjusted_polar > 0 else 360 + adjusted_polar,
134
+ y=manipulator_data["Pitch"],
135
+ z=manipulator_data["ShankOrientation"],
136
+ )
137
+
138
+ @override
139
+ async def get_shank_count(self, manipulator_id: str) -> int:
140
+ return int((await self._manipulator_data(manipulator_id))["ShankCount"]) # pyright: ignore [reportAny]
141
+
142
+ @override
143
+ def get_movement_tolerance(self) -> float:
144
+ return 0.01
145
+
146
+ @override
147
+ async def set_position(self, manipulator_id: str, position: Vector4, speed: float) -> Vector4:
148
+ # Keep track of the previous position to check if the manipulator stopped advancing.
149
+ current_position = await self.get_position(manipulator_id)
150
+ previous_position = current_position
151
+ unchanged_counter = 0
152
+
153
+ # Set step mode based on speed.
154
+ await self._put_request(
155
+ {
156
+ "PutId": "ProbeStepMode",
157
+ "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
158
+ "StepMode": 0 if speed > self.COARSE_SPEED_THRESHOLD else 1,
159
+ }
160
+ )
161
+
162
+ # Send move request.
163
+ await self._put_request(
164
+ {
165
+ "PutId": "ProbeMotion",
166
+ "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
167
+ "Absolute": 1,
168
+ "Stereotactic": 0,
169
+ "AxisMask": 7,
170
+ "X": position.x,
171
+ "Y": position.y,
172
+ "Z": position.z,
173
+ }
174
+ )
175
+
176
+ # Wait for the manipulator to reach the target position or be stopped or stuck.
177
+ while (
178
+ not self._movement_stopped
179
+ and not self._is_vector_close(current_position, position)
180
+ and unchanged_counter < self.UNCHANGED_COUNTER_LIMIT
181
+ ):
182
+ # Wait for a short time before checking again.
183
+ await sleep(self.POLL_INTERVAL)
184
+
185
+ # Update current position.
186
+ current_position = await self.get_position(manipulator_id)
187
+
188
+ # Check if manipulator is not moving.
189
+ if self._is_vector_close(previous_position, current_position):
190
+ # Position did not change.
191
+ unchanged_counter += 1
192
+ else:
193
+ # Position changed.
194
+ unchanged_counter = 0
195
+ previous_position = current_position
196
+
197
+ # Reset movement stopped flag.
198
+ self._movement_stopped = False
199
+
200
+ # Return the final position.
201
+ return await self.get_position(manipulator_id)
202
+
203
+ @override
204
+ async def set_depth(self, manipulator_id: str, depth: float, speed: float) -> float:
205
+ # Keep track of the previous depth to check if the manipulator stopped advancing unexpectedly.
206
+ current_depth = (await self.get_position(manipulator_id)).w
207
+ previous_depth = current_depth
208
+ unchanged_counter = 0
209
+
210
+ # Send move request.
211
+ # Convert mm/s to um/min and cap speed at the limit.
212
+ await self._put_request(
213
+ {
214
+ "PutId": "ProbeInsertion",
215
+ "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
216
+ "Distance": scalar_mm_to_um(current_depth - depth),
217
+ "Rate": min(scalar_mm_to_um(speed) * 60, self.INSERTION_SPEED_LIMIT),
218
+ }
219
+ )
220
+
221
+ # Wait for the manipulator to reach the target depth or be stopped or get stuck.
222
+ while not self._movement_stopped and not abs(current_depth - depth) <= self.get_movement_tolerance():
223
+ # Wait for a short time before checking again.
224
+ await sleep(self.POLL_INTERVAL)
225
+
226
+ # Get the current depth.
227
+ current_depth = (await self.get_position(manipulator_id)).w
228
+
229
+ # Check if manipulator is not moving.
230
+ if abs(previous_depth - current_depth) <= self.get_movement_tolerance():
231
+ # Depth did not change.
232
+ unchanged_counter += 1
233
+ else:
234
+ # Depth changed.
235
+ unchanged_counter = 0
236
+ previous_depth = current_depth
237
+
238
+ # Reset movement stopped flag.
239
+ self._movement_stopped = False
240
+
241
+ # Return the final depth.
242
+ return float((await self.get_position(manipulator_id)).w)
243
+
244
+ @override
245
+ async def stop(self, manipulator_id: str) -> None:
246
+ request: dict[str, str | int | float] = {
247
+ "PutId": "ProbeStop",
248
+ "Probe": self.VALID_MANIPULATOR_IDS.index(manipulator_id),
249
+ }
250
+ await self._put_request(request)
251
+ self._movement_stopped = True
252
+
253
+ @override
254
+ def platform_space_to_unified_space(self, platform_space: Vector4) -> Vector4:
255
+ # unified <- platform
256
+ # +x <- -x
257
+ # +y <- +z
258
+ # +z <- +y
259
+ # +w <- -w
260
+
261
+ return Vector4(
262
+ x=self.get_dimensions().x - platform_space.x,
263
+ y=platform_space.z,
264
+ z=platform_space.y,
265
+ w=self.get_dimensions().w - platform_space.w,
266
+ )
267
+
268
+ @override
269
+ def unified_space_to_platform_space(self, unified_space: Vector4) -> Vector4:
270
+ # platform <- unified
271
+ # +x <- -x
272
+ # +y <- +z
273
+ # +z <- +y
274
+ # +w <- -w
275
+
276
+ return Vector4(
277
+ x=self.get_dimensions().x - unified_space.x,
278
+ y=unified_space.z,
279
+ z=unified_space.y,
280
+ w=self.get_dimensions().w - unified_space.w,
281
+ )
282
+
283
+ # Helper functions.
284
+ async def _query_data(self) -> dict[str, Any]: # pyright: ignore [reportExplicitAny]
285
+ try:
286
+ # Update cache if it's expired.
287
+ if get_running_loop().time() - self.cache_time > self.CACHE_LIFETIME:
288
+ # noinspection PyTypeChecker
289
+ self.cache = (await get_running_loop().run_in_executor(None, get, self._url)).json()
290
+ self.cache_time = get_running_loop().time()
291
+ except ConnectionError as connectionError:
292
+ error_message = f"Unable to connect to MPM HTTP server: {connectionError}"
293
+ raise RuntimeError(error_message) from connectionError
294
+ except JSONDecodeError as jsonDecodeError:
295
+ error_message = f"Unable to decode JSON response from MPM HTTP server: {jsonDecodeError}"
296
+ raise ValueError(error_message) from jsonDecodeError
297
+ else:
298
+ # Return cached data.
299
+ return self.cache
300
+
301
+ async def _manipulator_data(self, manipulator_id: str) -> dict[str, Any]: # pyright: ignore [reportExplicitAny]
302
+ probe_data: list[dict[str, Any]] = (await self._query_data())["ProbeArray"] # pyright: ignore [reportExplicitAny]
303
+ for probe in probe_data:
304
+ if probe["Id"] == manipulator_id:
305
+ return probe
306
+
307
+ # If we get here, that means the manipulator doesn't exist.
308
+ error_message = f"Manipulator {manipulator_id} not found."
309
+ raise ValueError(error_message)
310
+
311
+ async def _put_request(self, request: dict[str, Any]) -> None: # pyright: ignore [reportExplicitAny]
312
+ _ = await get_running_loop().run_in_executor(None, put, self._url, dumps(request))
313
+
314
+ def _is_vector_close(self, target: Vector4, current: Vector4) -> bool:
315
+ return all(abs(axis) <= self.get_movement_tolerance() for axis in vector4_to_array(target - current)[:3])