forked from Cephla-Lab/Squid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
4686 lines (3981 loc) · 196 KB
/
core.py
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
from control.microcontroller import Microcontroller
from squid.abc import AbstractStage
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 *
if DO_FLUORESCENCE_RTP:
from control.processing_handler import ProcessingHandler
from control.processing_pipeline import *
from control.multipoint_built_in_functionalities import malaria_rtp
import control.utils as utils
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
from queue import Queue
from threading import Thread, Lock
from pathlib import Path
from datetime import datetime
import time
import subprocess
import shutil
import itertools
from lxml import etree
import json
import math
import random
import numpy as np
import pandas as pd
import scipy.signal
import cv2
import imageio as iio
import squid.abc
class ObjectiveStore:
def __init__(self, objectives_dict=OBJECTIVES, default_objective=DEFAULT_OBJECTIVE, parent=None):
self.objectives_dict = objectives_dict
self.default_objective = default_objective
self.current_objective = default_objective
self.tube_lens_mm = TUBE_LENS_MM
self.sensor_pixel_size_um = CAMERA_PIXEL_SIZE_UM[CAMERA_SENSOR]
self.pixel_binning = self.get_pixel_binning()
self.pixel_size_um = self.calculate_pixel_size(self.current_objective)
def get_pixel_size(self):
return self.pixel_size_um
def calculate_pixel_size(self, objective_name):
objective = self.objectives_dict[objective_name]
magnification = objective["magnification"]
objective_tube_lens_mm = objective["tube_lens_f_mm"]
pixel_size_um = self.sensor_pixel_size_um / (magnification / (objective_tube_lens_mm / self.tube_lens_mm))
pixel_size_um *= self.pixel_binning
return pixel_size_um
def set_current_objective(self, objective_name):
if objective_name in self.objectives_dict:
self.current_objective = objective_name
self.pixel_size_um = self.calculate_pixel_size(objective_name)
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]
def get_pixel_binning(self):
try:
highest_res = max(self.parent.camera.res_list, key=lambda res: res[0] * res[1])
resolution = self.parent.camera.resolution
pixel_binning = max(1, highest_res[0] / resolution[0])
except AttributeError:
pixel_binning = 1
return pixel_binning
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, crop_width=Acquisition.CROP_WIDTH, crop_height=Acquisition.CROP_HEIGHT, display_resolution_scaling=1
):
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.crop_width = crop_width
self.crop_height = crop_height
self.display_resolution_scaling = display_resolution_scaling
self.save_image_flag = False
self.track_flag = False
self.handler_busy = False
# for fps measurement
self.timestamp_last = 0
self.counter = 0
self.fps_real = 0
def start_recording(self):
self.save_image_flag = True
def stop_recording(self):
self.save_image_flag = False
def start_tracking(self):
self.tracking_flag = True
def stop_tracking(self):
self.tracking_flag = False
def set_display_fps(self, fps):
self.fps_display = fps
def set_save_fps(self, fps):
self.fps_save = fps
def set_crop(self, crop_width, crop_height):
self.crop_width = crop_width
self.crop_height = crop_height
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, camera):
if camera.is_live:
camera.image_locked = True
self.handler_busy = True
self.signal_new_frame_received.emit() # self.liveController.turn_off_illumination()
# 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))
# moved down (so that it does not modify the camera.current_frame, which causes minor problems for simulation) - 1/30/2022
# # rotate and flip - eventually these should be done in the camera
# camera.current_frame = utils.rotate_and_flip_image(camera.current_frame,rotate_image_angle=camera.rotate_image_angle,flip_image=camera.flip_image)
# crop image
image_cropped = utils.crop_image(camera.current_frame, self.crop_width, self.crop_height)
image_cropped = np.squeeze(image_cropped)
# # rotate and flip - moved up (1/10/2022)
# image_cropped = utils.rotate_and_flip_image(image_cropped,rotate_image_angle=ROTATE_IMAGE_ANGLE,flip_image=FLIP_IMAGE)
# added on 1/30/2022
# @@@ to move to camera
image_cropped = utils.rotate_and_flip_image(
image_cropped, rotate_image_angle=camera.rotate_image_angle, flip_image=camera.flip_image
)
# send image to display
time_now = time.time()
if time_now - self.timestamp_last_display >= 1 / self.fps_display:
# self.image_to_display.emit(cv2.resize(image_cropped,(round(self.crop_width*self.display_resolution_scaling), round(self.crop_height*self.display_resolution_scaling)),cv2.INTER_LINEAR))
self.image_to_display.emit(
utils.crop_image(
image_cropped,
round(self.crop_width * self.display_resolution_scaling),
round(self.crop_height * 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 camera.is_color:
image_cropped = cv2.cvtColor(image_cropped, cv2.COLOR_RGB2BGR)
self.packet_image_to_write.emit(image_cropped, camera.frame_ID, camera.timestamp)
self.timestamp_last_save = time_now
# send image to track
if self.track_flag and time_now - self.timestamp_last_track >= 1 / self.fps_track:
# track is a blocking operation - it needs to be
# @@@ will cropping before emitting the signal lead to speedup?
self.packet_image_for_tracking.emit(image_cropped, camera.frame_ID, camera.timestamp)
self.timestamp_last_track = time_now
self.handler_busy = False
camera.image_locked = False
"""
def on_new_frame_from_simulation(self,image,frame_ID,timestamp):
# check whether image is a local copy or pointer, if a pointer, needs to prevent the image being modified while this function is being executed
self.handler_busy = True
# crop image
image_cropped = utils.crop_image(image,self.crop_width,self.crop_height)
# send image to display
time_now = time.time()
if time_now-self.timestamp_last_display >= 1/self.fps_display:
self.image_to_display.emit(cv2.resize(image_cropped,(round(self.crop_width*self.display_resolution_scaling), round(self.crop_height*self.display_resolution_scaling)),cv2.INTER_LINEAR))
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:
self.packet_image_to_write.emit(image_cropped,frame_ID,timestamp)
self.timestamp_last_save = time_now
# send image to track
if time_now-self.timestamp_last_display >= 1/self.fps_track:
# track emit
self.timestamp_last_track = 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)
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)
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)
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
# 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 Configuration:
def __init__(
self,
mode_id=None,
name=None,
color=None,
camera_sn=None,
exposure_time=None,
analog_gain=None,
illumination_source=None,
illumination_intensity=None,
z_offset=None,
pixel_format=None,
_pixel_format_options=None,
emission_filter_position=None,
):
self.id = mode_id
self.name = name
self.color = color
self.exposure_time = exposure_time
self.analog_gain = analog_gain
self.illumination_source = illumination_source
self.illumination_intensity = illumination_intensity
self.camera_sn = camera_sn
self.z_offset = z_offset
self.pixel_format = pixel_format
if self.pixel_format is None:
self.pixel_format = "default"
self._pixel_format_options = _pixel_format_options
if _pixel_format_options is None:
self._pixel_format_options = self.pixel_format
self.emission_filter_position = emission_filter_position
class LiveController(QObject):
def __init__(
self,
camera,
microcontroller,
configurationManager,
illuminationController,
parent=None,
control_illumination=True,
use_internal_timer_for_hardware_trigger=True,
for_displacement_measurement=False,
):
QObject.__init__(self)
self.microscope = parent
self.camera = camera
self.microcontroller = microcontroller
self.configurationManager = configurationManager
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 = DEFAULT_DISPLAY_CROP / 100
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 self.illuminationController is not None and not "LED matrix" in self.currentConfiguration.name:
self.illuminationController.turn_on_illumination(
int(self.configurationManager.extract_wavelength(self.currentConfiguration.name))
)
elif SUPPORT_SCIMICROSCOPY_LED_ARRAY and "LED matrix" in self.currentConfiguration.name:
self.led_array.turn_on_illumination()
else:
self.microcontroller.turn_on_illumination()
self.illumination_on = True
def turn_off_illumination(self):
if self.illuminationController is not None and not "LED matrix" in self.currentConfiguration.name:
self.illuminationController.turn_off_illumination(
int(self.configurationManager.extract_wavelength(self.currentConfiguration.name))
)
elif SUPPORT_SCIMICROSCOPY_LED_ARRAY and "LED matrix" in self.currentConfiguration.name:
self.led_array.turn_off_illumination()
else:
self.microcontroller.turn_off_illumination()
self.illumination_on = False
def set_illumination(self, illumination_source, intensity, update_channel_settings=True):
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
if self.illuminationController is not None:
self.illuminationController.set_intensity(
int(self.configurationManager.extract_wavelength(self.currentConfiguration.name)), intensity
)
elif ENABLE_NL5 and NL5_USE_DOUT and "Fluorescence" in self.currentConfiguration.name:
wavelength = int(self.currentConfiguration.name[13:16])
self.microscope.nl5.set_active_channel(NL5_WAVENLENGTH_MAP[wavelength])
if NL5_USE_AOUT and update_channel_settings:
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))
else:
self.microcontroller.set_illumination(illumination_source, 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.strobe_delay_us / 1e6)
)
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.strobe_delay_us / 1e6)
)
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.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_callback() # 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
self.camera.is_live = False
if hasattr(self.camera, "stop_exposure"):
self.camera.stop_exposure()
if self.trigger_mode == TriggerMode.SOFTWARE:
self._stop_triggerred_acquisition()
# self.camera.stop_streaming() # 20210113 this line seems to cause problems when using af with multipoint
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 self.trigger_mode == TriggerMode.SOFTWARE:
if self.control_illumination and self.illumination_on == False:
self.turn_on_illumination()
self.trigger_ID = self.trigger_ID + 1
self.camera.send_trigger()
# 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
# print('real trigger fps is ' + str(self.fps_real))
elif self.trigger_mode == TriggerMode.HARDWARE:
self.trigger_ID = self.trigger_ID + 1
if ENABLE_NL5 and NL5_USE_DOUT:
self.microscope.nl5.start_acquisition()
else:
self.microcontroller.send_hardware_trigger(
control_illumination=True, illumination_on_time_us=self.camera.exposure_time * 1000
)
def _start_triggerred_acquisition(self):
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_software_triggered_acquisition()
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.reset_camera_acquisition_counter()
self.camera.set_hardware_triggered_acquisition()
self.reset_strobe_arugment()
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_continuous_acquisition()
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
print("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)
self.camera.set_analog_gain(self.currentConfiguration.analog_gain)
# set illumination
if self.control_illumination:
self.set_illumination(
self.currentConfiguration.illumination_source, self.currentConfiguration.illumination_intensity
)
# restart live
if self.is_live is True:
if self.control_illumination:
self.turn_on_illumination()
self.timer_trigger.start()
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
def reset_strobe_arugment(self):
# re-calculate the strobe_delay_us value
try:
self.camera.calculate_hardware_trigger_arguments()
except AttributeError:
pass
self.microcontroller.set_strobe_delay_us(self.camera.strobe_delay_us)
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 self.slidePositionController.homing_done == False:
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(y=True)
self.stage.home(x=True)
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)
self.stage.move_x_to(SLIDE_POSITION.LOADING_X_MM)
self.stage.home(y=True)
self.stage.move_y_to(SLIDE_POSITION.LOADING_Y_MM)
else:
self.stage.home(x=True, y=True)
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 self.slidePositionController.homing_done == False:
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(y=True)
# home x
self.stage.home(x=True)
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(y=True)
self.stage.move_y_to(SLIDE_POSITION.SCANNING_Y_MM)
self.stage.home(x=True)
self.stage.move_x_to(SLIDE_POSITION.SCANNING_X_MM)
else:
self.stage.home(x=True, y=True)
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:
# NOTE(imo): We want to move backlash compensation down to the firmware level. Also, before the Stage
# migration, we only compensated for backlash in the case that we were using PID control. Since that
# info isn't plumbed through yet (or ever from now on?), we just always compensate now. It doesn't hurt
# in the case of not needing it, except that it's a little slower because we need 2 moves.
mm_to_clear_backlash = self.stage.get_config().Z_AXIS.convert_to_real_units(
max(160, 20 * self.stage.get_config().Z_AXIS.MICROSTEPS_PER_STEP)
)
self.stage.move_z_to(self.slidePositionController.z_pos - mm_to_clear_backlash)
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