etho-python 0.22.0__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.
Files changed (47) hide show
  1. etho/__init__.py +9 -0
  2. etho/app.py +569 -0
  3. etho/assets/etho_icon1_pipeline_dark.svg +23 -0
  4. etho/assets/etho_icon1_pipeline_light.svg +30 -0
  5. etho/cli.py +215 -0
  6. etho/client.py +384 -0
  7. etho/services/ANAZeroService.py +123 -0
  8. etho/services/BLTZeroService.py +108 -0
  9. etho/services/DAQZeroService.py +326 -0
  10. etho/services/DLPZeroService.py +240 -0
  11. etho/services/GCMZeroService.py +271 -0
  12. etho/services/GOVZeroService.py +231 -0
  13. etho/services/NICounterZeroService.py +92 -0
  14. etho/services/NITriggerZeroService.py +120 -0
  15. etho/services/TemplateZeroService.py +98 -0
  16. etho/services/ZeroService.py +272 -0
  17. etho/services/__init__.py +0 -0
  18. etho/services/callbacks/__init__.py +19 -0
  19. etho/services/callbacks/_base.py +92 -0
  20. etho/services/callbacks/_image.py +798 -0
  21. etho/services/callbacks/_trace.py +456 -0
  22. etho/services/camera/__init__.py +13 -0
  23. etho/services/camera/base.py +164 -0
  24. etho/services/camera/basler.py +201 -0
  25. etho/services/camera/dummy.py +139 -0
  26. etho/services/camera/hamamatsu.py +133 -0
  27. etho/services/camera/spinnaker.py +317 -0
  28. etho/services/camera/ximea.py +167 -0
  29. etho/services/daq/IOTask.py +311 -0
  30. etho/services/daq/ai.py +174 -0
  31. etho/services/dlp/dlp_make_warpfiles.py +131 -0
  32. etho/services/dlp/dlp_runners.py +238 -0
  33. etho/services/utils/__init__.py +0 -0
  34. etho/services/utils/concurrent_task.py +236 -0
  35. etho/services/utils/log_exceptions.py +39 -0
  36. etho/utils/__init__.py +0 -0
  37. etho/utils/calibration.py +88 -0
  38. etho/utils/config.py +41 -0
  39. etho/utils/runner.py +121 -0
  40. etho/utils/shuffled_cycle.py +45 -0
  41. etho/utils/sound.py +336 -0
  42. etho/utils/tui.py +105 -0
  43. etho/utils/zeroclient.py +95 -0
  44. etho_python-0.22.0.dist-info/METADATA +49 -0
  45. etho_python-0.22.0.dist-info/RECORD +47 -0
  46. etho_python-0.22.0.dist-info/WHEEL +4 -0
  47. etho_python-0.22.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,311 @@
1
+ # -*- coding: utf-8 -*-
2
+ import threading
3
+ import time
4
+ import numpy as np
5
+ import logging
6
+ from ..utils.log_exceptions import for_all_methods, log_exceptions
7
+ from typing import Optional, List
8
+
9
+ try:
10
+ import PyDAQmx as daq
11
+ from PyDAQmx.DAQmxCallBack import *
12
+ from PyDAQmx.DAQmxConstants import *
13
+ from PyDAQmx.DAQmxFunctions import *
14
+
15
+ pydaqmx_import_error = None
16
+ except (ImportError, NotImplementedError) as pydaqmx_import_error:
17
+ pass
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @for_all_methods(log_exceptions(logger))
24
+ class IOTask(daq.Task):
25
+ def __init__(
26
+ self,
27
+ dev_name="Dev1",
28
+ cha_name=["ai0"],
29
+ limits=None,
30
+ rate=10000.0,
31
+ nb_inputsamples_per_cycle=None,
32
+ clock_source=None,
33
+ terminals: Optional[List[str]] = None,
34
+ duration: Optional[float] = None,
35
+ logger=None,
36
+ ):
37
+ """[summary]
38
+
39
+ Args:
40
+ dev_name (str, optional): [description]. Defaults to "Dev1".
41
+ cha_name (list, optional): [description]. Defaults to ["ai0"].
42
+ limits (float, optional): [description]. Defaults to 10.0.
43
+ rate (float, optional): [description]. Defaults to 10000.0.
44
+ nb_inputsamples_per_cycle ([type], optional): [description]. Defaults to None (fs samples=1 second).
45
+ clock_source (str, optional): None for AI-synced clock.
46
+ Use 'OnboardClock' for boards that don't support this (USB-DAQ).
47
+ Defaults to None.
48
+ terminals (List[str], optional):
49
+
50
+
51
+ Raises:
52
+ TypeError: [description]
53
+ ValueError: [description]
54
+ """
55
+ if pydaqmx_import_error is not None:
56
+ raise pydaqmx_import_error
57
+
58
+ self.log = logger
59
+
60
+ # check inputs
61
+ daq.Task.__init__(self)
62
+ if not isinstance(cha_name, (list, tuple)):
63
+ raise TypeError(f"`cha_name` is {type(cha_name)}. Should be `list` or `tuple`")
64
+
65
+ self.samples_read = daq.int32()
66
+
67
+ # channels
68
+ cha_types = {
69
+ "ai": "analog_input",
70
+ "ao": "analog_output",
71
+ "po": "digital_output",
72
+ }
73
+ self.cha_type = [cha_types[cha[:2]] for cha in cha_name]
74
+ if len(set(self.cha_type)) > 1:
75
+ raise ValueError("channels should all be of the same type but are {0}.".format(set(self.cha_type)))
76
+
77
+ # TODO: expand "ai0:2" to ["ai0", "ai1", "ai2"]
78
+
79
+ self.cha_names = [dev_name + "/" + ch for ch in cha_name] # prepend device name
80
+ self.cha_string = ", ".join(self.cha_names)
81
+ self.num_channels = len(self.cha_names)
82
+ if nb_inputsamples_per_cycle is None:
83
+ nb_inputsamples_per_cycle = int(rate)
84
+
85
+ # terminals
86
+ terminal_types = {
87
+ "RSE": daq.DAQmx_Val_RSE,
88
+ "NRSE": daq.DAQmx_Val_NRSE,
89
+ "Diff": daq.DAQmx_Val_Diff,
90
+ None: daq.DAQmx_Val_RSE, # default
91
+ }
92
+ if terminals is None: # default
93
+ terminals = ["RSE" for _ in self.cha_names]
94
+ elif len(terminals) != len(self.cha_names):
95
+ raise ValueError("need term for each channel")
96
+ self.cha_terminals = [terminal_types[terminal] for terminal in terminals]
97
+
98
+ # limits
99
+ if limits is None: # default
100
+ self.cha_limits = [[-10.0, 10.0] for _ in self.cha_names]
101
+ elif isinstance(limits, (float, int)): # single number
102
+ self.cha_limits = [[-limits, limits] for _ in self.cha_names]
103
+ else:
104
+ self.cha_limits = limits
105
+
106
+ if len(self.cha_limits) != len(self.cha_names) or not all([len(limit) == 2 for limit in self.cha_limits]):
107
+ raise ValueError("need term for each channel")
108
+
109
+ # FIX: input and output tasks can have different sizes
110
+ self.callback = None
111
+ self.data_gen = None # called at start of callback
112
+ self.data_rec = None # called at end of callback
113
+
114
+ if len(set(self.cha_type)) != 1:
115
+ raise ValueError("Mixed channel types (AI, AO, DI, DO).")
116
+
117
+ if self.cha_type[0] == "analog_input":
118
+ # add all channels
119
+ for name, terminal, limit in zip(self.cha_names, self.cha_terminals, self.cha_limits):
120
+ self.CreateAIVoltageChan(
121
+ name,
122
+ "",
123
+ terminal,
124
+ limit[0],
125
+ limit[1],
126
+ daq.DAQmx_Val_Volts,
127
+ None,
128
+ )
129
+ self.num_samples_per_chan = nb_inputsamples_per_cycle
130
+ self.num_samples_per_event = nb_inputsamples_per_cycle # self.num_samples_per_chan*self.num_channels
131
+ self.AutoRegisterEveryNSamplesEvent(daq.DAQmx_Val_Acquired_Into_Buffer, self.num_samples_per_event, 0)
132
+ self.CfgInputBuffer(self.num_samples_per_chan * self.num_channels * 4)
133
+ elif self.cha_type[0] == "analog_output":
134
+ for name, terminal, limit in zip(self.cha_names, self.cha_terminals, self.cha_limits):
135
+ self.CreateAOVoltageChan(
136
+ name,
137
+ "",
138
+ limit[0],
139
+ limit[1],
140
+ daq.DAQmx_Val_Volts,
141
+ None,
142
+ )
143
+ self.num_samples_per_chan = 5000
144
+ self.num_samples_per_event = 1000 # determines shortest interval at which new data can be generated
145
+ self.AutoRegisterEveryNSamplesEvent(daq.DAQmx_Val_Transferred_From_Buffer, self.num_samples_per_event, 0)
146
+ self.CfgOutputBuffer(self.num_samples_per_chan * self.num_channels * 2)
147
+ # ensures continuous output and avoids collision of old and new data in buffer
148
+ self.SetWriteRegenMode(daq.DAQmx_Val_DoNotAllowRegen)
149
+ elif self.cha_type[0] == "digital_output":
150
+ for name in self.cha_names:
151
+ self.CreateDOChan(name, "", daq.DAQmx_Val_ChanPerLine)
152
+ self.num_samples_per_chan = 5000
153
+ self.num_samples_per_event = 1000 # determines shortest interval at which new data can be generated
154
+ self.AutoRegisterEveryNSamplesEvent(daq.DAQmx_Val_Transferred_From_Buffer, self.num_samples_per_event, 0)
155
+ self.CfgOutputBuffer(self.num_samples_per_chan * self.num_channels * 2)
156
+ # ensures continuous output and avoids collision of old and new data in buffer
157
+ self.SetWriteRegenMode(daq.DAQmx_Val_DoNotAllowRegen)
158
+
159
+ if "digital" in self.cha_type[0]:
160
+ self._data = np.zeros((self.num_samples_per_chan, self.num_channels), dtype=np.uint8) # init empty data array
161
+ else:
162
+ self._data = np.zeros((self.num_samples_per_chan, self.num_channels), dtype=np.float64) # init empty data array
163
+
164
+ # set up trigger for output channels and clock
165
+ if "output" in self.cha_type[0]:
166
+ if clock_source is None:
167
+ clock_source = "ai/SampleClock" # use clock of analog input
168
+ self.CfgDigEdgeStartTrig("ai/StartTrigger", daq.DAQmx_Val_Rising)
169
+ else: # software trigger
170
+ clock_source = None # weird, but necessary to make it work with cheap NI USB interfaces
171
+ self.DisableStartTrig()
172
+ else: # analog input
173
+ clock_source = "OnboardClock" # use internal clock
174
+
175
+ self.CfgSampClkTiming(
176
+ clock_source,
177
+ rate,
178
+ daq.DAQmx_Val_Rising,
179
+ daq.DAQmx_Val_ContSamps,
180
+ self.num_samples_per_chan,
181
+ )
182
+
183
+ self.AutoRegisterDoneEvent(0)
184
+ self._data_lock = threading.Lock()
185
+ self._newdata_event = threading.Event()
186
+ if "output" in self.cha_type[0]:
187
+ self.EveryNCallback()
188
+
189
+ def __repr__(self):
190
+ return "{0}: {1}".format(self.cha_type[0], self.cha_string)
191
+
192
+ def stop(self):
193
+ """Stop DAQ."""
194
+ if self.data_gen is not None:
195
+ self._data = self.data_gen.close() # close data generator
196
+ if self.data_rec is not None:
197
+ for data_rec in self.data_rec:
198
+ data_rec.send(None)
199
+ data_rec.finish(verbose=True, sleepcycletimeout=2)
200
+ data_rec.close()
201
+
202
+ def EveryNCallback(self):
203
+ """Call whenever there is data to be read/written from/to the buffer.
204
+
205
+ Calls `self.data_gen` or `self.data_rec` for requesting/processing data.
206
+ """
207
+ # for clean teardown, catch PyDAQmx.DAQmxFunctions.GenStoppedToPreventRegenOfOldSamplesError
208
+ with self._data_lock:
209
+ systemtime = time.time()
210
+ if self.data_gen is not None:
211
+ try:
212
+ self._data = next(self.data_gen) # get data from data generator
213
+ self.log.warning(f"datagen {self.data_gen}")
214
+ except StopIteration as e:
215
+ self.log.warning(f"datagen {self.data_gen} StopIteration {e}")
216
+ self._data = None
217
+
218
+ if self.cha_type[0] == "analog_input":
219
+ # should only read self.num_samples_per_event!! otherwise recordings will be zeropadded for each chunk
220
+ self.ReadAnalogF64(
221
+ daq.DAQmx_Val_Auto,
222
+ 1.0,
223
+ daq.DAQmx_Val_GroupByScanNumber,
224
+ self._data,
225
+ self.num_samples_per_chan * self.num_channels,
226
+ daq.byref(self.samples_read),
227
+ None,
228
+ )
229
+ # only keep samples that were actually read, .value converts c_long to int
230
+ self._data = self._data[: self.samples_read.value, :]
231
+
232
+ elif self.cha_type[0] == "analog_output" and self._data is not None:
233
+ self.WriteAnalogF64(
234
+ self._data.shape[0],
235
+ 0,
236
+ daq.DAQmx_Val_WaitInfinitely,
237
+ daq.DAQmx_Val_GroupByScanNumber,
238
+ self._data,
239
+ daq.byref(self.samples_read),
240
+ None,
241
+ )
242
+ elif self.cha_type[0] == "digital_output" and self._data is not None:
243
+ self.WriteDigitalLines(
244
+ self._data.shape[0],
245
+ 0,
246
+ daq.DAQmx_Val_WaitInfinitely,
247
+ daq.DAQmx_Val_GroupByScanNumber,
248
+ self._data,
249
+ daq.byref(self.samples_read),
250
+ None,
251
+ )
252
+
253
+ if self.data_rec is not None:
254
+ for data_rec in self.data_rec:
255
+ if self._data is not None:
256
+ self.log.warning(f"{data_rec} {systemtime}")
257
+ data_rec.send((self._data, systemtime))
258
+ self._newdata_event.set()
259
+
260
+ return 0 # The function should return an integer
261
+
262
+ def DoneCallback(self, status):
263
+ """Call when Task is stopped/done."""
264
+ self.log.warning("Done status", status)
265
+ return 0 # The function should return an integer
266
+
267
+
268
+ def coroutine(func):
269
+ """decorator that auto-initializes (calls `next(None)`) coroutines"""
270
+
271
+ def start(*args, **kwargs):
272
+ cr = func(*args, **kwargs)
273
+ next(cr)
274
+ return cr
275
+
276
+ return start
277
+
278
+
279
+ @coroutine
280
+ def data_playlist(sounds, play_order, playlist_info=None, logger=None, name="standard"):
281
+ """sounds - list of nparrays"""
282
+ first_run = True
283
+ run_cnt = 0
284
+ playlist_cnt = 0
285
+
286
+ try:
287
+ while play_order:
288
+ run_cnt += 1
289
+ # duplicate first stim - otherwise we miss the first in the playlist
290
+ if first_run:
291
+ pp = 0
292
+ first_run = False
293
+ else:
294
+ pp = next(play_order)
295
+ playlist_cnt += 1
296
+ if playlist_info is not None:
297
+ msg = _format_playlist(playlist_info.loc[pp], playlist_cnt)
298
+ if logger:
299
+ logger.warning(msg)
300
+ stim = sounds[pp]
301
+ yield stim
302
+ except (GeneratorExit, StopIteration):
303
+ if logger is not None:
304
+ logger.warning(f" {name} cleaning up datagen.")
305
+
306
+
307
+ def _format_playlist(playlist, cnt):
308
+ string = f"cnt: {cnt}; "
309
+ for key, val in playlist.items():
310
+ string += f"{key}: {val}; "
311
+ return string
@@ -0,0 +1,174 @@
1
+ # -*- coding: utf-8 -*-
2
+ import threading
3
+ import time
4
+ import numpy as np
5
+ import logging
6
+ from ..utils.log_exceptions import for_all_methods, log_exceptions
7
+ from typing import Optional, List
8
+
9
+ try:
10
+ import PyDAQmx as daq
11
+ from PyDAQmx.DAQmxCallBack import *
12
+ from PyDAQmx.DAQmxConstants import *
13
+ from PyDAQmx.DAQmxFunctions import *
14
+
15
+ pydaqmx_import_error = None
16
+ except (ImportError, NotImplementedError) as pydaqmx_import_error:
17
+ pass
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @for_all_methods(log_exceptions(logger))
24
+ class AI(daq.Task):
25
+ def __init__(
26
+ self,
27
+ dev_name="Dev1",
28
+ cha_name=["ai0"],
29
+ limits=None,
30
+ rate=10000.0,
31
+ nb_inputsamples_per_cycle=None,
32
+ clock_source=None,
33
+ terminals: Optional[List[str]] = None,
34
+ logger=None,
35
+ ):
36
+ """[summary]
37
+
38
+ Args:
39
+ dev_name (str, optional): [description]. Defaults to "Dev1".
40
+ cha_name (list, optional): [description]. Defaults to ["ai0"].
41
+ limits (float, optional): [description]. Defaults to 10.0.
42
+ rate (float, optional): [description]. Defaults to 10000.0.
43
+ nb_inputsamples_per_cycle ([type], optional): [description]. Defaults to None.
44
+ clock_source (str, optional): None for AI-synced clock.
45
+ Use 'OnboardClock' for boards that don't support this (USB-DAQ).
46
+ Defaults to None.
47
+ terminals (List[str], optional):
48
+
49
+ Raises:
50
+ TypeError: [description]
51
+ ValueError: [description]
52
+ """
53
+ if pydaqmx_import_error is not None:
54
+ raise pydaqmx_import_error
55
+
56
+ self.log = logger
57
+
58
+ # check inputs
59
+ super().__init__()
60
+ if not isinstance(cha_name, (list, tuple)):
61
+ raise TypeError(f"`cha_name` is {type(cha_name)}. Should be `list` or `tuple`")
62
+
63
+ self.samples_read = daq.int32()
64
+
65
+ self.cha_names = [dev_name + "/" + ch for ch in cha_name] # append device name
66
+ self.cha_string = ", ".join(self.cha_names)
67
+ self.num_channels = len(cha_name) # need to fix this if we want to use blocks "ai0:8"
68
+ if nb_inputsamples_per_cycle is None:
69
+ nb_inputsamples_per_cycle = int(rate)
70
+
71
+ # terminals
72
+ terminal_types = {
73
+ "RSE": daq.DAQmx_Val_RSE,
74
+ "NRSE": daq.DAQmx_Val_NRSE,
75
+ "Diff": daq.DAQmx_Val_Diff,
76
+ None: daq.DAQmx_Val_RSE, # default
77
+ }
78
+ if terminals is None: # default
79
+ terminals = ["RSE" for _ in self.cha_names]
80
+ elif len(terminals) != len(self.cha_names):
81
+ raise ValueError("need term for each channel")
82
+ self.cha_terminals = [terminal_types[terminal] for terminal in terminals]
83
+
84
+ # limits
85
+ if limits is None: # default
86
+ self.cha_limits = [[-10.0, 10.0] for _ in self.cha_names]
87
+ elif isinstance(limits, (float, int)): # single number
88
+ self.cha_limits = [[-limits, limits] for _ in self.cha_names]
89
+ else:
90
+ self.cha_limits = limits
91
+
92
+ if len(self.cha_limits) != len(self.cha_names) or not all([len(limit) == 2 for limit in self.cha_limits]):
93
+ raise ValueError("need term for each channel")
94
+
95
+ # FIX: input and output tasks can have different sizes
96
+ self.callback = None
97
+ self.data_rec = None # called at end of callback
98
+
99
+ # add all channels
100
+ for name, terminal, limit in zip(self.cha_names, self.cha_terminals, self.cha_limits):
101
+ self.CreateAIVoltageChan(
102
+ name,
103
+ "",
104
+ terminal,
105
+ limit[0],
106
+ limit[1],
107
+ daq.DAQmx_Val_Volts,
108
+ None,
109
+ )
110
+ self.num_samples_per_chan = nb_inputsamples_per_cycle
111
+ self.num_samples_per_event = nb_inputsamples_per_cycle # self.num_samples_per_chan*self.num_channels
112
+ self.AutoRegisterEveryNSamplesEvent(daq.DAQmx_Val_Acquired_Into_Buffer, self.num_samples_per_event, 0)
113
+ self.CfgInputBuffer(self.num_samples_per_chan * self.num_channels * 4)
114
+
115
+ self._data = np.zeros((self.num_samples_per_chan, self.num_channels), dtype=np.float64) # init empty data array
116
+
117
+ clock_source = "OnboardClock" # use internal clock
118
+
119
+ self.CfgSampClkTiming(
120
+ clock_source,
121
+ rate,
122
+ daq.DAQmx_Val_Rising,
123
+ daq.DAQmx_Val_ContSamps,
124
+ self.num_samples_per_chan,
125
+ )
126
+
127
+ self.AutoRegisterDoneEvent(0)
128
+ self._data_lock = threading.Lock()
129
+ self._newdata_event = threading.Event()
130
+
131
+ def __repr__(self):
132
+ return "{0}: {1}".format(self.cha_type[0], self.cha_string)
133
+
134
+ def stop(self):
135
+ """Stop DAQ."""
136
+ if self.data_rec is not None:
137
+ for data_rec in self.data_rec:
138
+ data_rec.send(None)
139
+ data_rec.finish(verbose=True, sleepcycletimeout=2)
140
+ data_rec.close()
141
+
142
+ def EveryNCallback(self):
143
+ """Call whenever there is data to be read from the buffer.
144
+
145
+ Calls `self.data_rec` for processing data.
146
+ """
147
+ # for clean teardown, catch PyDAQmx.DAQmxFunctions.GenStoppedToPreventRegenOfOldSamplesError
148
+ with self._data_lock:
149
+ systemtime = time.time()
150
+ self.ReadAnalogF64(
151
+ daq.DAQmx_Val_Auto,
152
+ 1.0,
153
+ daq.DAQmx_Val_GroupByScanNumber,
154
+ self._data,
155
+ self.num_samples_per_chan * self.num_channels,
156
+ daq.byref(self.samples_read),
157
+ None,
158
+ )
159
+ # only keep samples that were actually read, .value converts c_long to int
160
+ self._data = self._data[: self.samples_read.value, :]
161
+
162
+ if self.data_rec is not None:
163
+ for data_rec in self.data_rec:
164
+ if self._data is not None:
165
+ self.log.warning(f"{data_rec} {systemtime}")
166
+ data_rec.send((self._data, systemtime))
167
+ self._newdata_event.set()
168
+
169
+ return 0 # The function should return an integer
170
+
171
+ def DoneCallback(self, status):
172
+ """Call when Task is stopped/done."""
173
+ self.log.warning("Done status", status)
174
+ return 0 # The function should return an integer
@@ -0,0 +1,131 @@
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+
5
+
6
+ def get_transformation_matrices(image_height, image_width, proj_rois):
7
+ """
8
+ Get transformation matrices from normalized projection coordinates
9
+ to normalized image coordinates
10
+
11
+ Parameters
12
+ ----------
13
+ image_height : int
14
+ Normalized height of the image (0 to 1).
15
+ image_width : int
16
+ Normalized width of the image (0 to 1).
17
+ proj_rois : numpy.ndarray
18
+ Normalized coordinates of the corners of the roi in the projection.
19
+ Should be nb_screens x 4(corners - clockwise from top-left) x 2(coordinates: y,x)
20
+ Returns
21
+ -------
22
+ transformation_matrices : numpy.ndarray
23
+ Homography matrices which transform normalized projection coordinates
24
+ to normalized image coordinates. Will be of shape nb_screensx3x3
25
+
26
+ """
27
+ nb_screens = proj_rois.shape[0]
28
+ transformation_matrices = np.empty((nb_screens, 3, 3))
29
+ screen_image_height = image_height
30
+ screen_image_width = image_width / nb_screens
31
+ for iscreen in range(nb_screens):
32
+ screen_image_corners = (
33
+ np.array(
34
+ [
35
+ [0.0, 0.0], # top left
36
+ [screen_image_width, 0.0], # top right
37
+ [screen_image_width, -screen_image_height], # bottom right
38
+ [0.0, -screen_image_height],
39
+ ] # bottom left
40
+ )
41
+ + np.array([screen_image_width * iscreen, 2 * screen_image_height])
42
+ )
43
+ H, _ = cv2.findHomography(proj_rois[iscreen], screen_image_corners)
44
+ transformation_matrices[iscreen] = H
45
+ return transformation_matrices
46
+
47
+
48
+ def create_warpfile(projection_height: int, projection_width: int, projector_dir: str):
49
+ """
50
+ Function to create and save a warp mesh file
51
+
52
+ Parameters
53
+ ----------
54
+ projection_height : int
55
+ Height of the projection in pixels (eg. 1080).
56
+ projection_width : int
57
+ Width of the projection in pixels (eg. 1920).
58
+ projector_dir : str
59
+ Directory where the roi file is stored and
60
+ where the warp file will be stored
61
+
62
+ Returns
63
+ -------
64
+ warpfile : str
65
+ Absolute path to the created warp file.
66
+ The name of the warpfile will be
67
+ "warpmesh_{projection_height}x{projection_width}.data"
68
+ and will be stored under projector_dir
69
+
70
+ """
71
+
72
+ # get the rois
73
+ roi_filename = "rois_{}x{}.npy".format(projection_height, projection_width)
74
+ if not os.path.exists(os.path.join(projector_dir, roi_filename)):
75
+ raise FileNotFoundError("ROI file not found: %s" % os.path.join(projector_dir, roi_filename))
76
+ rois = np.load(os.path.join(projector_dir, roi_filename))
77
+ # scale the rois such that bottom left is [-1, -1], top right is [1, 1]
78
+ rois_scaled = np.array(rois, dtype=float)
79
+ rois_scaled[:, :, 0] = (rois[:, :, 0] - (projection_width / 2)) / (projection_width / 2)
80
+ rois_scaled[:, :, 1] = ((projection_height / 2) - rois[:, :, 1]) / (projection_height / 2)
81
+ nb_screens = rois.shape[0]
82
+ frame_height, frame_width = 1 / nb_screens, 1
83
+ # get the transformation matrices
84
+ transformation_matrices = get_transformation_matrices(
85
+ image_height=frame_height, image_width=frame_width, proj_rois=rois_scaled
86
+ )
87
+
88
+ # create a warping mesh
89
+ # http://paulbourke.net/dome/warpingfisheye/
90
+ # warped image coordinates: (x,y) varies from [-1,-1] (bottom left) to [1,1] (top right)
91
+ # Note: in Paul Bourke's website, warped coordinates varied from
92
+ # [-aspect_ratio, -1] (bottom left) to [aspect_ratio,1] (top right),
93
+ # but for psychpy [-1,-1] to [1,1] works
94
+ # original image coordinates: (u,v) varies from [0,0] (bottom left) to [1,1] (top right)
95
+ # intensities i varies from 0 to 1
96
+ node_x = np.linspace(-1, 1, projection_width, dtype="float32")
97
+ node_y = np.linspace(-1, 1, projection_height, dtype="float32")
98
+ node_grid_x, node_grid_y = np.meshgrid(node_x, node_y)
99
+ node_positions_xy = np.concatenate((node_grid_x.reshape(-1, 1), node_grid_y.reshape(-1, 1)), axis=1)
100
+ mesh_coordinates_uv = np.zeros(node_positions_xy.shape, dtype="float32")
101
+ intensities = np.zeros((node_positions_xy.shape[0], 1), dtype="float32")
102
+ projection_image = np.zeros((projection_height, projection_width), dtype="uint8")
103
+ for iscreen in range(rois_scaled.shape[0]):
104
+ projection_mask = projection_image.copy()
105
+ # get the pixel ids in the roi
106
+ roi_mask = cv2.fillConvexPoly(projection_mask, rois[iscreen], 1)
107
+ roi_node_idx = np.vstack(np.where(roi_mask)).T
108
+ # flip y
109
+ roi_node_idx[:, 0] = projection_height - roi_node_idx[:, 0]
110
+ roi_node_idx_flat = roi_node_idx[:, 0] * projection_width + roi_node_idx[:, 1]
111
+ # get node positions in roi
112
+ roi_node_xy = node_positions_xy[roi_node_idx_flat]
113
+ # convert from euclidean to homogeneous coordinates
114
+ roi_node_xy_h = np.concatenate((roi_node_xy, np.ones((roi_node_xy.shape[0], 1))), axis=1)
115
+ # apply transformation to mesh coordinates
116
+ roi_mesh_uv_h = roi_node_xy_h @ transformation_matrices[iscreen].T
117
+ # convert back to euclidean coordinates
118
+ roi_mesh_uv = roi_mesh_uv_h[:, [0, 1]] / roi_mesh_uv_h[:, [2]]
119
+ mesh_coordinates_uv[roi_node_idx_flat] = roi_mesh_uv
120
+ intensities[roi_node_idx_flat] = 1
121
+ # xyuvi coordinates
122
+ warp_mesh_coordinates = np.concatenate((node_positions_xy, mesh_coordinates_uv, intensities), axis=1)
123
+ # save to file
124
+ warpfile = os.path.join(projector_dir, "warpmesh_{}x{}.data".format(projection_height, projection_width))
125
+ filetype = 2
126
+ with open(os.path.join(projector_dir, warpfile), "w+") as f:
127
+ f.write("%d\n" % (filetype))
128
+ f.write("%d %d\n" % (projection_width, projection_height))
129
+ np.savetxt(f, warp_mesh_coordinates, fmt="%0.5f")
130
+
131
+ return warpfile