-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathcore.py
More file actions
4984 lines (4181 loc) · 208 KB
/
Copy pathcore.py
File metadata and controls
4984 lines (4181 loc) · 208 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
# set QT_API environment variable
import os
import sys
import tempfile
import control._def
from control.microcontroller import Microcontroller
from control.piezo import PiezoStage
from squid.abc import AbstractStage, AbstractCamera, CameraAcquisitionMode
import squid.logging
# qt libraries
os.environ["QT_API"] = "pyqt5"
import qtpy
import pyqtgraph as pg
from qtpy.QtCore import *
from qtpy.QtWidgets import *
from qtpy.QtGui import *
# control
from control._def import *
from control.core.multi_point_worker import MultiPointWorker
from control.core import job_processing
import control.utils as utils
import control.utils_acquisition as utils_acquisition
import control.utils_channel as utils_channel
import control.utils_config as utils_config
import control.tracking as tracking
import control.serial_peripherals as serial_peripherals
try:
from control.multipoint_custom_script_entry_v2 import *
print("custom multipoint script found")
except:
pass
from typing import List, Tuple, Optional, Dict, Any, Callable
from queue import Queue
from threading import Thread, Lock
from pathlib import Path
from datetime import datetime
from enum import Enum
from control.utils_config import ChannelConfig, ChannelMode, LaserAFConfig
import time
import itertools
import json
import math
import numpy as np
import pandas as pd
import cv2
import imageio as iio
import squid.abc
import scipy.ndimage
class ObjectiveStore:
def __init__(self, objectives_dict=OBJECTIVES, default_objective=DEFAULT_OBJECTIVE):
self.objectives_dict = objectives_dict
self.default_objective = default_objective
self.current_objective = default_objective
objective = self.objectives_dict[self.current_objective]
self.pixel_size_factor = ObjectiveStore.calculate_pixel_size_factor(objective, TUBE_LENS_MM)
def get_pixel_size_factor(self):
return self.pixel_size_factor
@staticmethod
def calculate_pixel_size_factor(objective, tube_lens_mm):
"""pixel_size_um = sensor_pixel_size * binning_factor * lens_factor"""
magnification = objective["magnification"]
objective_tube_lens_mm = objective["tube_lens_f_mm"]
lens_factor = objective_tube_lens_mm / magnification / tube_lens_mm
return lens_factor
def set_current_objective(self, objective_name):
if objective_name in self.objectives_dict:
self.current_objective = objective_name
objective = self.objectives_dict[objective_name]
self.pixel_size_factor = ObjectiveStore.calculate_pixel_size_factor(objective, TUBE_LENS_MM)
else:
raise ValueError(f"Objective {objective_name} not found in the store.")
def get_current_objective_info(self):
return self.objectives_dict[self.current_objective]
class StreamHandler(QObject):
image_to_display = Signal(np.ndarray)
packet_image_to_write = Signal(np.ndarray, int, float)
packet_image_for_tracking = Signal(np.ndarray, int, float)
signal_new_frame_received = Signal()
def __init__(
self,
display_resolution_scaling=1,
accept_new_frame_fn: Callable[[], bool] = lambda: True,
):
QObject.__init__(self)
self.fps_display = 1
self.fps_save = 1
self.fps_track = 1
self.timestamp_last_display = 0
self.timestamp_last_save = 0
self.timestamp_last_track = 0
self.display_resolution_scaling = display_resolution_scaling
self.save_image_flag = False
self.handler_busy = False
# for fps measurement
self.timestamp_last = 0
self.counter = 0
self.fps_real = 0
# Only accept new frames if this user defined function returns true
self._accept_new_frames_fn = accept_new_frame_fn
def start_recording(self):
self.save_image_flag = True
def stop_recording(self):
self.save_image_flag = False
def set_display_fps(self, fps):
self.fps_display = fps
def set_save_fps(self, fps):
self.fps_save = fps
def set_display_resolution_scaling(self, display_resolution_scaling):
self.display_resolution_scaling = display_resolution_scaling / 100
print(self.display_resolution_scaling)
def on_new_frame(self, frame: squid.abc.CameraFrame):
if not self._accept_new_frames_fn():
return
self.handler_busy = True
self.signal_new_frame_received.emit()
# measure real fps
timestamp_now = round(time.time())
if timestamp_now == self.timestamp_last:
self.counter = self.counter + 1
else:
self.timestamp_last = timestamp_now
self.fps_real = self.counter
self.counter = 0
if PRINT_CAMERA_FPS:
print("real camera fps is " + str(self.fps_real))
# crop image
image = np.squeeze(frame.frame)
# send image to display
time_now = time.time()
if time_now - self.timestamp_last_display >= 1 / self.fps_display:
self.image_to_display.emit(
utils.crop_image(
image,
round(image.shape[1] * self.display_resolution_scaling),
round(image.shape[0] * self.display_resolution_scaling),
)
)
self.timestamp_last_display = time_now
# send image to write
if self.save_image_flag and time_now - self.timestamp_last_save >= 1 / self.fps_save:
if frame.is_color():
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
self.packet_image_to_write.emit(image, frame.frame_id, frame.timestamp)
self.timestamp_last_save = time_now
self.handler_busy = False
class ImageSaver(QObject):
stop_recording = Signal()
def __init__(self, image_format=Acquisition.IMAGE_FORMAT):
QObject.__init__(self)
self.base_path = "./"
self.experiment_ID = ""
self.image_format = image_format
self.max_num_image_per_folder = 1000
self.queue = Queue(10) # max 10 items in the queue
self.image_lock = Lock()
self.stop_signal_received = False
self.thread = Thread(target=self.process_queue, daemon=True)
self.thread.start()
self.counter = 0
self.recording_start_time = 0
self.recording_time_limit = -1
def process_queue(self):
while True:
# stop the thread if stop signal is received
if self.stop_signal_received:
return
# process the queue
try:
[image, frame_ID, timestamp] = self.queue.get(timeout=0.1)
self.image_lock.acquire(True)
folder_ID = int(self.counter / self.max_num_image_per_folder)
file_ID = int(self.counter % self.max_num_image_per_folder)
# create a new folder
if file_ID == 0:
utils.ensure_directory_exists(os.path.join(self.base_path, self.experiment_ID, str(folder_ID)))
if image.dtype == np.uint16:
# need to use tiff when saving 16 bit images
saving_path = os.path.join(
self.base_path, self.experiment_ID, str(folder_ID), str(file_ID) + "_" + str(frame_ID) + ".tiff"
)
iio.imwrite(saving_path, image)
else:
saving_path = os.path.join(
self.base_path,
self.experiment_ID,
str(folder_ID),
str(file_ID) + "_" + str(frame_ID) + "." + self.image_format,
)
cv2.imwrite(saving_path, image)
self.counter = self.counter + 1
self.queue.task_done()
self.image_lock.release()
except:
pass
def enqueue(self, image, frame_ID, timestamp):
try:
self.queue.put_nowait([image, frame_ID, timestamp])
if (self.recording_time_limit > 0) and (
time.time() - self.recording_start_time >= self.recording_time_limit
):
self.stop_recording.emit()
# when using self.queue.put(str_), program can be slowed down despite multithreading because of the block and the GIL
except:
print("imageSaver queue is full, image discarded")
def set_base_path(self, path):
self.base_path = path
def set_recording_time_limit(self, time_limit):
self.recording_time_limit = time_limit
def start_new_experiment(self, experiment_ID, add_timestamp=True):
if add_timestamp:
# generate unique experiment ID
self.experiment_ID = experiment_ID + "_" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f")
else:
self.experiment_ID = experiment_ID
self.recording_start_time = time.time()
# create a new folder
try:
utils.ensure_directory_exists(os.path.join(self.base_path, self.experiment_ID))
# to do: save configuration
except:
pass
# reset the counter
self.counter = 0
def close(self):
self.queue.join()
self.stop_signal_received = True
self.thread.join()
class ImageSaver_Tracking(QObject):
def __init__(self, base_path, image_format="bmp"):
QObject.__init__(self)
self.base_path = base_path
self.image_format = image_format
self.max_num_image_per_folder = 1000
self.queue = Queue(100) # max 100 items in the queue
self.image_lock = Lock()
self.stop_signal_received = False
self.thread = Thread(target=self.process_queue, daemon=True)
self.thread.start()
def process_queue(self):
while True:
# stop the thread if stop signal is received
if self.stop_signal_received:
return
# process the queue
try:
[image, frame_counter, postfix] = self.queue.get(timeout=0.1)
self.image_lock.acquire(True)
folder_ID = int(frame_counter / self.max_num_image_per_folder)
file_ID = int(frame_counter % self.max_num_image_per_folder)
# create a new folder
if file_ID == 0:
utils.ensure_directory_exists(os.path.join(self.base_path, str(folder_ID)))
if image.dtype == np.uint16:
saving_path = os.path.join(
self.base_path,
str(folder_ID),
str(file_ID) + "_" + str(frame_counter) + "_" + postfix + ".tiff",
)
iio.imwrite(saving_path, image)
else:
saving_path = os.path.join(
self.base_path,
str(folder_ID),
str(file_ID) + "_" + str(frame_counter) + "_" + postfix + "." + self.image_format,
)
cv2.imwrite(saving_path, image)
self.queue.task_done()
self.image_lock.release()
except:
pass
def enqueue(self, image, frame_counter, postfix):
try:
self.queue.put_nowait([image, frame_counter, postfix])
except:
print("imageSaver queue is full, image discarded")
def close(self):
self.queue.join()
self.stop_signal_received = True
self.thread.join()
class ImageDisplay(QObject):
image_to_display = Signal(np.ndarray)
def __init__(self):
QObject.__init__(self)
self.queue = Queue(10) # max 10 items in the queue
self.image_lock = Lock()
self.stop_signal_received = False
self.thread = Thread(target=self.process_queue, daemon=True)
self.thread.start()
def process_queue(self):
while True:
# stop the thread if stop signal is received
if self.stop_signal_received:
return
# process the queue
try:
[image, frame_ID, timestamp] = self.queue.get(timeout=0.1)
self.image_lock.acquire(True)
self.image_to_display.emit(image)
self.image_lock.release()
self.queue.task_done()
except:
pass
time.sleep(0)
# def enqueue(self,image,frame_ID,timestamp):
def enqueue(self, image):
try:
self.queue.put_nowait([image, None, None])
# when using self.queue.put(str_) instead of try + nowait, program can be slowed down despite multithreading because of the block and the GIL
pass
except:
print("imageDisplay queue is full, image discarded")
def emit_directly(self, image):
self.image_to_display.emit(image)
def close(self):
self.queue.join()
self.stop_signal_received = True
self.thread.join()
class LiveController(QObject):
def __init__(
self,
camera: AbstractCamera,
microcontroller,
illuminationController,
parent=None,
control_illumination=True,
use_internal_timer_for_hardware_trigger=True,
for_displacement_measurement=False,
):
QObject.__init__(self)
self._log = squid.logging.get_logger(self.__class__.__name__)
self.microscope = parent
self.camera: AbstractCamera = camera
self.microcontroller = microcontroller
self.currentConfiguration = None
self.trigger_mode = TriggerMode.SOFTWARE # @@@ change to None
self.is_live = False
self.control_illumination = control_illumination
self.illumination_on = False
self.illuminationController = illuminationController
self.use_internal_timer_for_hardware_trigger = (
use_internal_timer_for_hardware_trigger # use QTimer vs timer in the MCU
)
self.for_displacement_measurement = for_displacement_measurement
self.fps_trigger = 1
self.timer_trigger_interval = (1 / self.fps_trigger) * 1000
self.timer_trigger = QTimer()
self.timer_trigger.setInterval(int(self.timer_trigger_interval))
self.timer_trigger.timeout.connect(self.trigger_acquisition)
self.trigger_ID = -1
self.fps_real = 0
self.counter = 0
self.timestamp_last = 0
self.display_resolution_scaling = 1
self.enable_channel_auto_filter_switching = True
if SUPPORT_SCIMICROSCOPY_LED_ARRAY:
# to do: add error handling
self.led_array = serial_peripherals.SciMicroscopyLEDArray(
SCIMICROSCOPY_LED_ARRAY_SN, SCIMICROSCOPY_LED_ARRAY_DISTANCE, SCIMICROSCOPY_LED_ARRAY_TURN_ON_DELAY
)
self.led_array.set_NA(SCIMICROSCOPY_LED_ARRAY_DEFAULT_NA)
# illumination control
def turn_on_illumination(self):
if not "LED matrix" in self.currentConfiguration.name:
self.illuminationController.turn_on_illumination(
int(utils_channel.extract_wavelength_from_config_name(self.currentConfiguration.name))
)
elif SUPPORT_SCIMICROSCOPY_LED_ARRAY and "LED matrix" in self.currentConfiguration.name:
self.led_array.turn_on_illumination()
# LED matrix
else:
self.microcontroller.turn_on_illumination() # to wrap microcontroller in Squid_led_array
self.illumination_on = True
def turn_off_illumination(self):
if not "LED matrix" in self.currentConfiguration.name:
self.illuminationController.turn_off_illumination(
int(utils_channel.extract_wavelength_from_config_name(self.currentConfiguration.name))
)
elif SUPPORT_SCIMICROSCOPY_LED_ARRAY and "LED matrix" in self.currentConfiguration.name:
self.led_array.turn_off_illumination()
# LED matrix
else:
self.microcontroller.turn_off_illumination() # to wrap microcontroller in Squid_led_array
self.illumination_on = False
def update_illumination(self):
illumination_source = self.currentConfiguration.illumination_source
intensity = self.currentConfiguration.illumination_intensity
if illumination_source < 10: # LED matrix
if SUPPORT_SCIMICROSCOPY_LED_ARRAY:
# set color
if "BF LED matrix full_R" in self.currentConfiguration.name:
self.led_array.set_color((1, 0, 0))
elif "BF LED matrix full_G" in self.currentConfiguration.name:
self.led_array.set_color((0, 1, 0))
elif "BF LED matrix full_B" in self.currentConfiguration.name:
self.led_array.set_color((0, 0, 1))
else:
self.led_array.set_color(SCIMICROSCOPY_LED_ARRAY_DEFAULT_COLOR)
# set intensity
self.led_array.set_brightness(intensity)
# set mode
if "BF LED matrix left half" in self.currentConfiguration.name:
self.led_array.set_illumination("dpc.l")
if "BF LED matrix right half" in self.currentConfiguration.name:
self.led_array.set_illumination("dpc.r")
if "BF LED matrix top half" in self.currentConfiguration.name:
self.led_array.set_illumination("dpc.t")
if "BF LED matrix bottom half" in self.currentConfiguration.name:
self.led_array.set_illumination("dpc.b")
if "BF LED matrix full" in self.currentConfiguration.name:
self.led_array.set_illumination("bf")
if "DF LED matrix" in self.currentConfiguration.name:
self.led_array.set_illumination("df")
else:
if "BF LED matrix full_R" in self.currentConfiguration.name:
self.microcontroller.set_illumination_led_matrix(illumination_source, r=(intensity / 100), g=0, b=0)
elif "BF LED matrix full_G" in self.currentConfiguration.name:
self.microcontroller.set_illumination_led_matrix(illumination_source, r=0, g=(intensity / 100), b=0)
elif "BF LED matrix full_B" in self.currentConfiguration.name:
self.microcontroller.set_illumination_led_matrix(illumination_source, r=0, g=0, b=(intensity / 100))
else:
self.microcontroller.set_illumination_led_matrix(
illumination_source,
r=(intensity / 100) * LED_MATRIX_R_FACTOR,
g=(intensity / 100) * LED_MATRIX_G_FACTOR,
b=(intensity / 100) * LED_MATRIX_B_FACTOR,
)
else:
# update illumination
wavelength = int(utils_channel.extract_wavelength_from_config_name(self.currentConfiguration.name))
self.illuminationController.set_intensity(wavelength, intensity)
if ENABLE_NL5 and NL5_USE_DOUT and "Fluorescence" in self.currentConfiguration.name:
self.microscope.nl5.set_active_channel(NL5_WAVENLENGTH_MAP[wavelength])
if NL5_USE_AOUT:
self.microscope.nl5.set_laser_power(NL5_WAVENLENGTH_MAP[wavelength], int(intensity))
if ENABLE_CELLX:
self.microscope.cellx.set_laser_power(NL5_WAVENLENGTH_MAP[wavelength], int(intensity))
# set emission filter position
if ENABLE_SPINNING_DISK_CONFOCAL:
try:
self.microscope.xlight.set_emission_filter(
XLIGHT_EMISSION_FILTER_MAPPING[illumination_source],
extraction=False,
validate=XLIGHT_VALIDATE_WHEEL_POS,
)
except Exception as e:
print("not setting emission filter position due to " + str(e))
if USE_ZABER_EMISSION_FILTER_WHEEL and self.enable_channel_auto_filter_switching:
try:
if (
self.currentConfiguration.emission_filter_position
!= self.microscope.emission_filter_wheel.current_index
):
if ZABER_EMISSION_FILTER_WHEEL_BLOCKING_CALL:
self.microscope.emission_filter_wheel.set_emission_filter(
self.currentConfiguration.emission_filter_position, blocking=True
)
else:
self.microscope.emission_filter_wheel.set_emission_filter(
self.currentConfiguration.emission_filter_position, blocking=False
)
if self.trigger_mode == TriggerMode.SOFTWARE:
time.sleep(ZABER_EMISSION_FILTER_WHEEL_DELAY_MS / 1000)
else:
time.sleep(
max(
0, ZABER_EMISSION_FILTER_WHEEL_DELAY_MS / 1000 - self.camera.get_strobe_time() / 1e3
)
)
except Exception as e:
print("not setting emission filter position due to " + str(e))
if (
USE_OPTOSPIN_EMISSION_FILTER_WHEEL
and self.enable_channel_auto_filter_switching
and OPTOSPIN_EMISSION_FILTER_WHEEL_TTL_TRIGGER == False
):
try:
if (
self.currentConfiguration.emission_filter_position
!= self.microscope.emission_filter_wheel.current_index
):
self.microscope.emission_filter_wheel.set_emission_filter(
self.currentConfiguration.emission_filter_position
)
if self.trigger_mode == TriggerMode.SOFTWARE:
time.sleep(OPTOSPIN_EMISSION_FILTER_WHEEL_DELAY_MS / 1000)
elif self.trigger_mode == TriggerMode.HARDWARE:
time.sleep(
max(0, OPTOSPIN_EMISSION_FILTER_WHEEL_DELAY_MS / 1000 - self.camera.get_strobe_time() / 1e3)
)
except Exception as e:
print("not setting emission filter position due to " + str(e))
if USE_SQUID_FILTERWHEEL and self.enable_channel_auto_filter_switching:
try:
self.microscope.squid_filter_wheel.set_emission(self.currentConfiguration.emission_filter_position)
except Exception as e:
print("not setting emission filter position due to " + str(e))
def start_live(self):
self.is_live = True
self.camera.start_streaming()
if self.trigger_mode == TriggerMode.SOFTWARE or (
self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger
):
self.camera.enable_callbacks(True) # in case it's disabled e.g. by the laser AF controller
self._start_triggerred_acquisition()
# if controlling the laser displacement measurement camera
if self.for_displacement_measurement:
self.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 1)
def stop_live(self):
if self.is_live:
self.is_live = False
if self.trigger_mode == TriggerMode.SOFTWARE:
self._stop_triggerred_acquisition()
if self.trigger_mode == TriggerMode.CONTINUOUS:
self.camera.stop_streaming()
if (self.trigger_mode == TriggerMode.SOFTWARE) or (
self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger
):
self._stop_triggerred_acquisition()
if self.control_illumination:
self.turn_off_illumination()
# if controlling the laser displacement measurement camera
if self.for_displacement_measurement:
self.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 0)
# software trigger related
def trigger_acquisition(self):
if not self.camera.get_ready_for_trigger():
# TODO(imo): Before, send_trigger would pass silently for this case. Now
# we do the same here. Should this warn? I didn't add a warning because it seems like
# we over-trigger as standard practice (eg: we trigger at our exposure time frequency, but
# the cameras can't give us images that fast so we essentially always have at least 1 skipped trigger)
self._log.debug("Not ready for trigger, skipping.")
return
if self.trigger_mode == TriggerMode.SOFTWARE and self.control_illumination:
if not self.illumination_on:
self.turn_on_illumination()
self.trigger_ID = self.trigger_ID + 1
self.camera.send_trigger(self.camera.get_exposure_time())
if self.trigger_mode == TriggerMode.SOFTWARE:
if self.control_illumination and self.illumination_on == False:
self.turn_on_illumination()
def _start_triggerred_acquisition(self):
if not self.timer_trigger.isActive():
self.timer_trigger.start()
def _set_trigger_fps(self, fps_trigger):
self.fps_trigger = fps_trigger
self.timer_trigger_interval = (1 / self.fps_trigger) * 1000
self.timer_trigger.setInterval(int(self.timer_trigger_interval))
def _stop_triggerred_acquisition(self):
self.timer_trigger.stop()
# trigger mode and settings
def set_trigger_mode(self, mode):
if mode == TriggerMode.SOFTWARE:
if self.is_live and (
self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger
):
self._stop_triggerred_acquisition()
self.camera.set_acquisition_mode(CameraAcquisitionMode.SOFTWARE_TRIGGER)
if self.is_live:
self._start_triggerred_acquisition()
if mode == TriggerMode.HARDWARE:
if self.trigger_mode == TriggerMode.SOFTWARE and self.is_live:
self._stop_triggerred_acquisition()
self.camera.set_acquisition_mode(CameraAcquisitionMode.HARDWARE_TRIGGER)
self.camera.set_exposure_time(self.currentConfiguration.exposure_time)
if self.is_live and self.use_internal_timer_for_hardware_trigger:
self._start_triggerred_acquisition()
if mode == TriggerMode.CONTINUOUS:
if (self.trigger_mode == TriggerMode.SOFTWARE) or (
self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger
):
self._stop_triggerred_acquisition()
self.camera.set_acquisition_mode(CameraAcquisitionMode.CONTINUOUS)
self.trigger_mode = mode
def set_trigger_fps(self, fps):
if (self.trigger_mode == TriggerMode.SOFTWARE) or (
self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger
):
self._set_trigger_fps(fps)
# set microscope mode
# @@@ to do: change softwareTriggerGenerator to TriggerGeneratror
def set_microscope_mode(self, configuration):
self.currentConfiguration = configuration
self._log.info("setting microscope mode to " + self.currentConfiguration.name)
# temporarily stop live while changing mode
if self.is_live is True:
self.timer_trigger.stop()
if self.control_illumination:
self.turn_off_illumination()
# set camera exposure time and analog gain
self.camera.set_exposure_time(self.currentConfiguration.exposure_time)
try:
self.camera.set_analog_gain(self.currentConfiguration.analog_gain)
except NotImplementedError:
pass
# set illumination
if self.control_illumination:
self.update_illumination()
# restart live
if self.is_live is True:
if self.control_illumination:
self.turn_on_illumination()
self.timer_trigger.start()
self._log.info("Done setting microscope mode.")
def get_trigger_mode(self):
return self.trigger_mode
# slot
def on_new_frame(self):
if self.fps_trigger <= 5:
if self.control_illumination and self.illumination_on == True:
self.turn_off_illumination()
def set_display_resolution_scaling(self, display_resolution_scaling):
self.display_resolution_scaling = display_resolution_scaling / 100
class SlidePositionControlWorker(QObject):
finished = Signal()
signal_stop_live = Signal()
signal_resume_live = Signal()
def __init__(self, slidePositionController, stage: AbstractStage, home_x_and_y_separately=False):
QObject.__init__(self)
self.slidePositionController = slidePositionController
self.stage = stage
self.liveController = self.slidePositionController.liveController
self.home_x_and_y_separately = home_x_and_y_separately
def move_to_slide_loading_position(self):
was_live = self.liveController.is_live
if was_live:
self.signal_stop_live.emit()
# retract z
self.slidePositionController.z_pos = self.stage.get_pos().z_mm # zpos at the beginning of the scan
self.stage.move_z_to(OBJECTIVE_RETRACTED_POS_MM, blocking=False)
self.stage.wait_for_idle(SLIDE_POTISION_SWITCHING_TIMEOUT_LIMIT_S)
print("z retracted")
self.slidePositionController.objective_retracted = True
# move to position
# for well plate
if self.slidePositionController.is_for_wellplate:
# So we can home without issue, set our limits to something large. Then later reset them back to
# the safe values.
a_large_limit_mm = 100
self.stage.set_limits(
x_pos_mm=a_large_limit_mm,
x_neg_mm=-a_large_limit_mm,
y_pos_mm=a_large_limit_mm,
y_neg_mm=-a_large_limit_mm,
)
# home for the first time
if not self.slidePositionController.homing_done:
print("running homing first")
timestamp_start = time.time()
# x needs to be at > + 20 mm when homing y
self.stage.move_x(20)
self.stage.home(x=False, y=True, z=False, theta=False)
self.stage.home(x=True, y=False, z=False, theta=False)
self.slidePositionController.homing_done = True
# homing done previously
else:
self.stage.move_x_to(20)
self.stage.move_y_to(SLIDE_POSITION.LOADING_Y_MM)
self.stage.move_x_to(SLIDE_POSITION.LOADING_X_MM)
# set limits again
self.stage.set_limits(
x_pos_mm=self.stage.get_config().X_AXIS.MAX_POSITION,
x_neg_mm=self.stage.get_config().X_AXIS.MIN_POSITION,
y_pos_mm=self.stage.get_config().Y_AXIS.MAX_POSITION,
y_neg_mm=self.stage.get_config().Y_AXIS.MIN_POSITION,
)
else:
# for glass slide
if self.slidePositionController.homing_done == False or SLIDE_POTISION_SWITCHING_HOME_EVERYTIME:
if self.home_x_and_y_separately:
self.stage.home(x=True, y=False, z=False, theta=False)
self.stage.move_x_to(SLIDE_POSITION.LOADING_X_MM)
self.stage.home(x=False, y=True, z=False, theta=False)
self.stage.move_y_to(SLIDE_POSITION.LOADING_Y_MM)
else:
self.stage.home(x=True, y=True, z=False, theta=False)
self.stage.move_x_to(SLIDE_POSITION.LOADING_X_MM)
self.stage.move_y_to(SLIDE_POSITION.LOADING_Y_MM)
self.slidePositionController.homing_done = True
else:
self.stage.move_y_to(SLIDE_POSITION.LOADING_Y_MM)
self.stage.move_x_to(SLIDE_POSITION.LOADING_X_MM)
if was_live:
self.signal_resume_live.emit()
self.slidePositionController.slide_loading_position_reached = True
self.finished.emit()
def move_to_slide_scanning_position(self):
was_live = self.liveController.is_live
if was_live:
self.signal_stop_live.emit()
# move to position
# for well plate
if self.slidePositionController.is_for_wellplate:
# home for the first time
if not self.slidePositionController.homing_done:
timestamp_start = time.time()
# x needs to be at > + 20 mm when homing y
self.stage.move_x_to(20)
# home y
self.stage.home(x=False, y=True, z=False, theta=False)
# home x
self.stage.home(x=True, y=False, z=False, theta=False)
self.slidePositionController.homing_done = True
# move to scanning position
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
else:
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
else:
if self.slidePositionController.homing_done == False or SLIDE_POTISION_SWITCHING_HOME_EVERYTIME:
if self.home_x_and_y_separately:
self.stage.home(x=False, y=True, z=False, theta=False)
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
self.stage.home(x=True, y=False, z=False, theta=False)
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
else:
self.stage.home(x=True, y=True, z=False, theta=False)
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
self.slidePositionController.homing_done = True
else:
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
# restore z
if self.slidePositionController.objective_retracted:
self.stage.move_z_to(self.slidePositionController.z_pos)
self.slidePositionController.objective_retracted = False
print("z position restored")
if was_live:
self.signal_resume_live.emit()
self.slidePositionController.slide_scanning_position_reached = True
self.finished.emit()
class SlidePositionController(QObject):
signal_slide_loading_position_reached = Signal()
signal_slide_scanning_position_reached = Signal()
signal_clear_slide = Signal()
def __init__(self, stage: AbstractStage, liveController, is_for_wellplate=False):
QObject.__init__(self)
self.stage = stage
self.liveController = liveController
self.slide_loading_position_reached = False
self.slide_scanning_position_reached = False
self.homing_done = False
self.is_for_wellplate = is_for_wellplate
self.retract_objective_before_moving = RETRACT_OBJECTIVE_BEFORE_MOVING_TO_LOADING_POSITION
self.objective_retracted = False
self.thread = None
def move_to_slide_loading_position(self):
# create a QThread object
self.thread = QThread()
# create a worker object
self.slidePositionControlWorker = SlidePositionControlWorker(self, self.stage)
# move the worker to the thread
self.slidePositionControlWorker.moveToThread(self.thread)
# connect signals and slots
self.thread.started.connect(self.slidePositionControlWorker.move_to_slide_loading_position)
self.slidePositionControlWorker.signal_stop_live.connect(self.slot_stop_live, type=Qt.BlockingQueuedConnection)
self.slidePositionControlWorker.signal_resume_live.connect(
self.slot_resume_live, type=Qt.BlockingQueuedConnection
)
self.slidePositionControlWorker.finished.connect(self.signal_slide_loading_position_reached.emit)
self.slidePositionControlWorker.finished.connect(self.slidePositionControlWorker.deleteLater)
self.slidePositionControlWorker.finished.connect(self.thread.quit)
self.thread.finished.connect(self.thread.quit)
# self.slidePositionControlWorker.finished.connect(self.threadFinished,type=Qt.BlockingQueuedConnection)
# start the thread
self.thread.start()
def move_to_slide_scanning_position(self):
# create a QThread object
self.thread = QThread()
# create a worker object
self.slidePositionControlWorker = SlidePositionControlWorker(self, self.stage)
# move the worker to the thread
self.slidePositionControlWorker.moveToThread(self.thread)
# connect signals and slots
self.thread.started.connect(self.slidePositionControlWorker.move_to_slide_scanning_position)
self.slidePositionControlWorker.signal_stop_live.connect(self.slot_stop_live, type=Qt.BlockingQueuedConnection)
self.slidePositionControlWorker.signal_resume_live.connect(
self.slot_resume_live, type=Qt.BlockingQueuedConnection
)
self.slidePositionControlWorker.finished.connect(self.signal_slide_scanning_position_reached.emit)
self.slidePositionControlWorker.finished.connect(self.slidePositionControlWorker.deleteLater)
self.slidePositionControlWorker.finished.connect(self.thread.quit)
self.thread.finished.connect(self.thread.quit)
# self.slidePositionControlWorker.finished.connect(self.threadFinished,type=Qt.BlockingQueuedConnection)
# start the thread
print("before thread.start()")
self.thread.start()
self.signal_clear_slide.emit()
def slot_stop_live(self):
self.liveController.stop_live()
def slot_resume_live(self):
self.liveController.start_live()
class AutofocusWorker(QObject):
finished = Signal()
image_to_display = Signal(np.ndarray)
def __init__(self, autofocusController):
QObject.__init__(self)
self.autofocusController = autofocusController
self.camera: AbstractCamera = self.autofocusController.camera
self.microcontroller = self.autofocusController.microcontroller
self.stage = self.autofocusController.stage
self.liveController = self.autofocusController.liveController
self.N = self.autofocusController.N
self.deltaZ = self.autofocusController.deltaZ
self.crop_width = self.autofocusController.crop_width
self.crop_height = self.autofocusController.crop_height
def run(self):
self.run_autofocus()
self.finished.emit()
def wait_till_operation_is_completed(self):
while self.microcontroller.is_busy():
time.sleep(SLEEP_TIME_S)
def run_autofocus(self):
# @@@ to add: increase gain, decrease exposure time
# @@@ can move the execution into a thread - done 08/21/2021
focus_measure_vs_z = [0] * self.N
focus_measure_max = 0
z_af_offset = self.deltaZ * round(self.N / 2)
self.stage.move_z(-z_af_offset)
steps_moved = 0
for i in range(self.N):
self.stage.move_z(self.deltaZ)
steps_moved = steps_moved + 1
# trigger acquisition (including turning on the illumination) and read frame
if self.liveController.trigger_mode == TriggerMode.SOFTWARE:
self.liveController.turn_on_illumination()
self.wait_till_operation_is_completed()
self.camera.send_trigger()
image = self.camera.read_frame()
elif self.liveController.trigger_mode == TriggerMode.HARDWARE:
if "Fluorescence" in self.liveController.currentConfiguration.name and ENABLE_NL5 and NL5_USE_DOUT:
self.microscope.nl5.start_acquisition()
# TODO(imo): This used to use the "reset_image_ready_flag=False" arg, but oinly the toupcam camera implementation had the
# "reset_image_ready_flag" arg, so this is broken for all other cameras.
image = self.camera.read_frame()
else:
self.microcontroller.send_hardware_trigger(
control_illumination=True, illumination_on_time_us=self.camera.get_exposure_time() * 1000
)
image = self.camera.read_frame()
if image is None:
continue
# tunr of the illumination if using software trigger
if self.liveController.trigger_mode == TriggerMode.SOFTWARE:
self.liveController.turn_off_illumination()
image = utils.crop_image(image, self.crop_width, self.crop_height)
self.image_to_display.emit(image)
QApplication.processEvents()
timestamp_0 = time.time()
focus_measure = utils.calculate_focus_measure(image, FOCUS_MEASURE_OPERATOR)
timestamp_1 = time.time()
print(" calculating focus measure took " + str(timestamp_1 - timestamp_0) + " second")
focus_measure_vs_z[i] = focus_measure
print(i, focus_measure)
focus_measure_max = max(focus_measure, focus_measure_max)
if focus_measure < focus_measure_max * AF.STOP_THRESHOLD: