-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfluidiscopeToolbox.py.8858d843f29c304d3ce80cbf8d306313.py
1715 lines (1499 loc) · 75 KB
/
fluidiscopeToolbox.py.8858d843f29c304d3ce80cbf8d306313.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
# Fluidiscope Toolbox
import fluidiscopeGlobVar as fg
import fluidiscopeIO
import fluidiscopeInit
import fluidiscopeAutofocus as af
# python packages
import warnings
from datetime import datetime
import time
import re
import glob
import os
import io
import sys
import unipath as uni
from distutils.dir_util import copy_tree
import shutil
if os.name == 'nt':
pass
else:
import usb
#import cv2 as cv
from PIL import Image
import numpy as np
from fractions import Fraction
from kivy.clock import Clock
from functools import partial
from math import floor
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.utils import platform
from kivy.uix.listview import ListView
from kivy.uix.listview import ListItemButton
from kivy.adapters.listadapter import ListAdapter
if not (fg.my_dev_flag):
from I2CDevice import I2CDevice
from picamera.array import PiRGBArray
from picamera import PiCamera
# define color variables
button_color_active = [0.0, 4.0, 0.0, 1.0]
button_color_inactive = [0.5, 0.5, 0.5, 1.0] #, [1.0, 1.0, 1.0, 1.0]]
button_color_disabled = [0.1, 0.1, 0.1, 1.0]
button_color_caution = [0.6, 0.0, 0.0, 1.0]
button_fontcolor_inactive = [1.0, 1.0, 1.0, 1.0]
button_fontcolor_active = [0.0, 0.0, 0.0, 1.0]
# TODO: FIX IT!
fg.expt_num = 1
##########################
# #
# == SCREEN BEHAVIOUR == #
# #
##########################
# Switch Screen behaviour
def scr_switch(self, instance):
# switch to Screen_Imaging
if self.ids["btn_start_expt"].uid == instance.uid:
self.ids["sm"].current = 'scr_imaging'
self.ids["btn_scr_name"].text = 'IMA\nGING'
fg.started_first_exp = 1
elif self.ids["btn_new_expt"].uid == instance.uid:
self.ids["sm"].current = 'scr_start'
self.ids["btn_scr_name"].text = 'STA\nRT'
# switch to Screen_Options
elif self.ids["btn_menu_opt"].uid == instance.uid:
#jumped over, because unnecessary extra click (!!)
self.ids["sm"].current = 'scr_opt' #'scr_opt_check'
self.ids["btn_scr_name"].text = 'OPT\nIONS\n:D' # 'OPT\nIONS\n?'
elif self.ids["btn_menu_opt_checked"].uid == instance.uid:
self.ids["sm"].current = 'scr_opt'
self.ids["btn_scr_name"].text = 'OPT\nIONS\n:D'
self.ids["btn_menu_opt_checked"].disabled = True
self.ids['btn_menu_opt_enable'].disabled = False
self.ids['btn_menu_opt_back_to_main'].disabled = False
# switch to Screen_Imaging
elif (self.ids["btn_menu_main"].uid == instance.uid or self.ids["btn_menu_opt_back_to_main"].uid == instance.uid or
self.ids['scr_copy_2_back_main'].uid == instance.uid):
if fg.started_first_exp:
self.ids["sm"].current = 'scr_imaging'
self.ids["btn_scr_name"].text = 'IMA\nGING'
else:
self.ids["sm"].current = 'scr_start'
self.ids["btn_scr_name"].text = 'STA\nRT'
elif self.ids["btn_menu_help"].uid == instance.uid:
self.ids["sm"].current = 'scr_help'
self.ids["btn_scr_name"].text = 'HE\nLP'
# menu-buttons
##
###
elif self.ids["btn_light_set_1"].uid == instance.uid:
self.ids["sm"].current = 'scr_light_set_1'
self.ids["btn_scr_name"].text = 'LI\nGHT\nOPT\n1'
elif self.ids["btn_light_set_2"].uid == instance.uid:
self.ids["sm"].current = 'scr_light_set_2'
self.ids["btn_scr_name"].text = 'LI\nGHT\nOPT\n2'
fluidiscopeIO.settings_save_restore(self, instance, True)
elif self.ids["btn_cam_set_1"].uid == instance.uid:
self.ids["sm"].current = 'scr_cam_set_1'
self.ids["btn_scr_name"].text = 'CAM\nERA\nOPT\n1'
fluidiscopeIO.settings_save_restore(self, instance, True)
elif self.ids["btn_cam_set_2"].uid == instance.uid:
self.ids["sm"].current = 'scr_cam_set_2'
self.ids["btn_scr_name"].text = 'CAM\nERA\nOPT\n2'
fluidiscopeIO.settings_save_restore(self, instance, True)
elif self.ids["btn_imaging_set"].uid == instance.uid:
self.ids["sm"].current = 'scr_imaging_set'
self.ids["btn_scr_name"].text = 'IMA\nGIN\nG\nOPT'
fluidiscopeIO.settings_save_restore(self, instance, True)
elif self.ids["btn_motor_set"].uid == instance.uid:
self.ids["sm"].current = 'scr_motor_set'
self.ids["btn_scr_name"].text = 'MO\nTOR\nOPT'
fluidiscopeIO.settings_save_restore(self, instance, True)
elif self.ids["btn_autofocus_set"].uid == instance.uid or self.ids["btn_autofocus_opt"].uid == instance.uid:
if self.ids["sm"].current == 'scr_autofocus_set':
self.ids["sm"].current = 'scr_autofocus_set'
else:
self.ids["sm"].current = 'scr_autofocus_set'
self.ids["btn_scr_name"].text = 'AUT\nOFO\nCUS'
fluidiscopeIO.settings_save_restore(self, instance, True)
# special buttons
##
###
elif self.ids["btn_copy"].uid == instance.uid:
#self.ids["sm"].current = 'scr_copy_1'
#self.ids["btn_scr_name"].text = 'COPY\nDATA\n1'
pass
elif self.ids["btn_copy_1"].uid == instance.uid:
#self.ids["sm"].current = 'scr_copy_2'
#self.ids['scr_copy_2_progressbar'].value = 0
#self.ids['scr_copy_2_status_lbl'].text = ''
#self.ids["btn_scr_name"].text = 'COPY\nDATA\n2'
#self.ids['scr_copy_2_delete_check'].active = False
# print(self.ids['show_selected_path'].text)
#if len(self.ids['scr_copy_1_filechooser'].selection) > 0:
# fg.copy_path = self.ids['scr_copy_1_filechooser'].selection[0]
#else:
# pass
pass
elif self.ids["scr_copy_2_back_copy"].uid == instance.uid:
#self.ids["sm"].current = 'scr_copy_1'
#self.ids["btn_scr_name"].text = 'COPY\nDATA\n1'
pass
def unlock_options(self, instance):
if self.ids['btn_menu_opt_enable'].uid == instance.uid:
self.ids['btn_menu_opt_checked'].disabled = False
self.ids['btn_menu_opt_enable'].disabled = True
self.ids['btn_menu_opt_back_to_main'].disabled = True
def settings_back(self):
self.ids["sm"].current = 'scr_opt'
self.ids["btn_scr_name"].text = 'OPT\nIONS\n:D'
##########################
# #
# == SCREEN BUILD == #
# #
##########################
##########################
# #
# == BUTTON MANAGEMENT == #
# #
##########################
# checks, whether actual button is active
def check_active(instance):
try:
if instance.fl_active:
return True
else:
return False
except:
print("{0} has no fl_active".format(instance.uid))
# activates [1] and deactivates [0] an element
def change_activation_status(instance):
if check_active(instance):
change_color(instance,status=instance.fl_active)
instance.fl_active = False
else:
change_color(instance, status=instance.fl_active)
instance.fl_active = True
def change_color(instance,status=True):
# define color
if status:
instance.background_color = button_color_inactive
instance.color = button_fontcolor_inactive
else:
if sum(instance.fl_value) > 0:
instance.background_color = instance.fl_value
else:
instance.background_color = button_color_active
instance.color = button_fontcolor_active
def activate(instance):
if not check_active(instance):
change_activation_status(instance)
def deactivate(instance):
if check_active(instance):
try:
print("Is active. Deactivating Button: {0}".format.instance.text)
except Exception as e:
pass
change_activation_status(instance)
# chain of activation commands
def change_activation_status_chain(self, *args):
for myC in range(len(args)):
change_activation_status(self.ids[args[myC]])
def warn_dev_mode(self):
msg = "APP IS RUNNING IN DEV-MODE!"
self.ids['lbl_warning'].text = msg
self.ids['user_notify_expt'].text = msg
# enable [1] / disable [0] button
def change_enable_status(instance, enable):
# try:
# if enable is True and instance.disabled is False:
# msg = "Button: {0} forced to be enabled although already enabled.".format(instance.text)
# warnings.warn(msg)
# elif enable is False and instance.disabled is True:
# msg = "Button: {0} forced to be disabled although already disabled.".format(instance.text)
# warnings.warn(msg)
# except Exception as e:
# pass
if enable is True:
instance.disabled = False
else:
instance.disabled = True
def change_enable_status_chain(self, activate, change_elements): # *args
# for myC in range(len(args)):
for fluidElement in change_elements:
change_enable_status(self.ids[fluidElement], activate)
##########################
# #
# == BUTTON FUNCTIONS == #
# #
##########################
def end_fluidiscope(app):
# save data to config
# gather_last_state(app)
fluidiscopeIO.write_config()
try:
if not fg.my_dev_flag:
fg.ledarr.send("CLEAR")
fg.camera.close()
finally:
print("Closed camera")
app.get_running_app().stop()
def select_method(self, instance, aimed_component_group):
if aimed_component_group == "light_buttons":
method_dictionary = {'FULL': 0, 'PRE': 1, 'CUS': 2, 'FLUO': 3} #instance.text: 0,
switch_entries = ["btn_light_full", "btn_light_preset_pattern", "btn_light_custom_pattern", "btn_light_fluo"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
if instance.uid == self.ids['btn_light_preset_pattern'].uid:
counter_active_methods = ['btn_light_set_2_clear','btn_light_set_2_fill','slider_light_set_2_NA','btn_light_set_2_pattern_run','btn_light_set_2_pattern_1','btn_light_set_2_pattern_2','btn_light_set_2_pattern_3','btn_light_set_2_pattern_4']
for idx in range(1, 5):
if fg.config['light_patterns']['active_p'+str(idx)] == 1:
active_pattern = str(idx)
break
print("Select_method: active_pattern={0}".format(active_pattern))
active_method = [active_method, 'btn_light_set_2_pattern_' + active_pattern]
elif instance.uid == self.ids['btn_light_custom_pattern'].uid:
counter_active_methods = ['btn_light_set_2_clear', 'btn_light_set_2_fill','slider_light_set_2_NA']
inactive_methods.append('btn_light_set_2_pattern_off')
inactive_methods.append('btn_light_set_2_pattern_run')
inactive_methods.append('btn_light_set_2_pattern_1')
inactive_methods.append('btn_light_set_2_pattern_2')
inactive_methods.append('btn_light_set_2_pattern_3')
inactive_methods.append('btn_light_set_2_pattern_4')
else:
counter_active_methods = []
elif aimed_component_group == "light_patterns":
method_dictionary = {'P1': 0, 'P2': 1, 'P3': 2, 'P4': 3, 'RUN': 4} #instance.text: 0,
switch_entries = ["btn_light_set_2_pattern_1","btn_light_set_2_pattern_2", "btn_light_set_2_pattern_3", "btn_light_set_2_pattern_4",'btn_light_set_2_pattern_run']
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = []
elif aimed_component_group == "motor_buttons":
method_dictionary = {"x": 0, "y": 1, "z": 2}
fg.config["motor"]["active_motor"] = method_dictionary[instance.text]
switch_entries = ["btn_motor_dir_x", "btn_motor_dir_y", "btn_motor_dir_z"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = ["btn_motor_up", "btn_motor_down", "btn_motor_stepsize_plus", "lbl_motor_stepsize",
"btn_motor_stepsize_minus"]
elif aimed_component_group == "motor_mov_buttons":
method_dictionary = {"<<": 0, ">>": 1}
switch_entries = ["btn_motor_down", "btn_motor_up"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = []
elif aimed_component_group == "motor_calibration_buttons":
method_dictionary = {"Cal.": 0}
switch_entries = ["scr_motor_set_cal_min", "scr_motor_set_cal_zero","scr_motor_set_cal_max"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = ["scr_motor_set_cal_min", "scr_motor_set_cal_zero","scr_motor_set_cal_max"]
elif aimed_component_group == "imaging_method":
method_dictionary = {"Bright": 0, "qDPC": 1, "Custom": 2, "Fluor": 3}
#hswitch_entries = ["btn_imaging_technique_1", "btn_imaging_technique_2", "btn_imaging_technique_3", "btn_imaging_technique_fluor"]
switch_entries = ["btn_imaging_technique_1", "btn_imaging_technique_2", "btn_imaging_technique_3", "btn_imaging_technique_fluor"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
inactive_methods = [] # implemented to allow for multiple selection
if len(fg.config['experiment']['active_methods']) == 0:
inactive_methods.extend(["btn_imaging_measiter", "btn_imaging_totaldurat","btn_imaging_dplus", "btn_imaging_dminus","btn_imaging_hplus", "btn_imaging_hminus",
"btn_imaging_mplus", "btn_imaging_mminus","btn_imaging_splus", "btn_imaging_sminus",])
counter_active_methods = ["btn_take_image", "btn_snap", "btn_take_foreground", "btn_take_background"]
elif len(fg.config['experiment']['active_methods']) == 1 and check_active(instance):
inactive_methods.extend(["btn_imaging_measiter", "btn_imaging_totaldurat","btn_imaging_dplus", "btn_imaging_dminus","btn_imaging_hplus", "btn_imaging_hminus",
"btn_imaging_mplus", "btn_imaging_mminus","btn_imaging_splus", "btn_imaging_sminus",])
counter_active_methods = ["btn_take_image", "btn_snap", "btn_take_foreground", "btn_take_background"]
imaging_methods_change(self, instance)
#elif aimed_component_group == "imaging_method_fluo":
# active_method = "btn_imaging_technique_fluo"
# switch_entries = ["btn_imaging_technique_1", "btn_imaging_technique_2", "btn_imaging_technique_3"]
# if not any([self.ids[x].fl_active for x in switch_entries]):
# inactive_methods =["btn_imaging_measiter", "btn_imaging_totaldurat","btn_imaging_dplus", "btn_imaging_dminus","btn_imaging_hplus", "btn_imaging_hminus",
# "btn_imaging_mplus", "btn_imaging_mminus","btn_imaging_splus", "btn_imaging_sminus",]
# counter_active_methods = ["btn_take_image", "btn_snap", "btn_take_foreground", "btn_take_background"]
# else:
# inactive_methods = None
# counter_active_methods = None
elif aimed_component_group == "select_imaging_time_entry":
method_dictionary = {"MEAS\nITER": 0, "TOTAL\nDURAT": 1}
switch_entries = ["btn_imaging_measiter", "btn_imaging_totaldurat"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = ["btn_imaging_dplus", "btn_imaging_dminus","btn_imaging_hplus", "btn_imaging_hminus",
"btn_imaging_mplus", "btn_imaging_mminus","btn_imaging_splus", "btn_imaging_sminus",]
elif aimed_component_group == "take_image":
if fg.config['experiment']['active']:
method_dictionary = {"SNAP": 0, "Stop Measurement": 1, "BG": 2, "FG": 3}
else:
method_dictionary = {"SNAP": 0, "Start Measurement": 1, "BG": 2, "FG": 3}
switch_entries = ["btn_snap", "btn_take_image", "btn_take_foreground", "btn_take_background", "btn_copy"]
[active_method, inactive_methods] = select_method_switches(instance, method_dictionary, switch_entries)
counter_active_methods = []
else:
pass
# if list inactive_methods is not empty
try:
if inactive_methods:
change_enable_status_chain(self, check_active(instance), inactive_methods[:])
# if list counter_active_methods is not empty
if counter_active_methods:
change_enable_status_chain(self, not check_active(instance), counter_active_methods[:])
except Exception as exc:
print("Had exception: __{}__, but continued".format(exc))
# change activation status of clicked instance (button)
change_activation_status(instance)
clear_notification_labels(self)
if isinstance(active_method, list):
if active_method[1] == 'btn_light_set_2_pattern_1':
light_set_patterns(self,self.ids[active_method[1]])
if fg.my_dev_flag:
warn_dev_mode(self)
print('Selected methods: {}.'.format(fg.config['experiment']['active_methods']))
print('this time selected method: {}.'.format(active_method))
return active_method
def imaging_methods_change(self, instance):
if instance.text in fg.config['experiment']['active_methods']:
fg.config['experiment']['active_methods'].remove(instance.text)
else:
fg.config['experiment']['active_methods'].append(instance.text)
def show_notification_labels(self, instance):
is_snapshot = instance.text in ['SNAP', 'BG', 'FG']
if is_snapshot:
if instance.text == "BG":
msg = "Background image taken ({0})".format(fg.config['experiment']['imaging_method'])
elif instance.text == "FG":
msg = "Foreground image taken ({0})".format(fg.config['experiment']['imaging_method'])
else:
msg = "Snapshot image taken ({0})".format(fg.config['experiment']['imaging_method'])
else:
if fg.config['experiment']['success']:
print("Notification: " + str(fg.expt_num))
switch_notify_color(self, button_color_active)
msg = "Experiment #{0} completed successfully.".format(fg.expt_num)
else:
switch_notify_color(self, button_color_caution)
msg = "Experiment #{0} aborted by user.".format(fg.expt_num)
self.ids['user_notify_expt'].text = msg
def clear_notification_labels(self):
switch_notify_color(self, button_fontcolor_inactive)
self.ids['user_notify_expt'].text = ""
self.ids['status_images_left'].text = ""
self.ids['status_time_left'].text = ""
self.ids['status_images_taken'].text = ""
self.ids['status_time_passed'].text = ""
self.ids['lbl_warning'].text = ""
def select_method_switches(instance, method_dictionary, switch_entries):
popped_entry = switch_entries.pop(method_dictionary[instance.text])
return [popped_entry, switch_entries]
def get_imaging_method(self):
if check_active(self.ids['btn_imaging_technique_1']):
imaging_technique = self.ids['btn_imaging_technique_1'].text
elif check_active(self.ids['btn_imaging_technique_2']):
imaging_technique = self.ids['btn_imaging_technique_2'].text
elif check_active(self.ids['btn_imaging_technique_3']):
imaging_technique = self.ids['btn_imaging_technique_3'].text
elif check_active(self.ids['btn_imaging_technique_fluor']):
imaging_technique = self.ids['btn_imaging_technique_fluor'].text
elif check_active(self.ids['btn_take_background']):
imaging_technique = self.ids['btn_take_background'].text
elif check_active(self.ids['btn_take_foreground']):
imaging_technique = self.ids['btn_imaging_technique_3'].text
else:
imaging_technique = None
return imaging_technique
def experiment_duration_format(value,direction):
# format time values -> biggest: d
if direction == 'forward':
result = [0,0,0,0]
result[0] = int(value/86400)
producth = result[0]*86400
result[1] = int((value-producth)/3600)
producth += result[1]*3600
result[2] = int((value-producth)/60)
producth += result[2] * 60
result[3] = value - producth
else:
result = sum(a*b for a,b in zip(value, [86400,3600,60,1]))
return result
def imaging_set_time(self,instance,value):
if check_active(self.ids['btn_imaging_measiter']):
p_lbl = self.ids['lbl_imaging_measiter']
p_supp = imaging_set_time_chkbound_and_update(fg.config['experiment']['interval'], value)
if (p_supp <= fg.config['experiment']['duration'] ):
fg.config['experiment']['interval'] = p_supp
else:
fg.config['experiment']['interval'] = fg.config['experiment']['duration']
p_op = fg.config['experiment']['interval']
else:
p_lbl = self.ids['lbl_imaging_totaldurat']
fg.config['experiment']['duration'] = imaging_set_time_chkbound_and_update(fg.config['experiment']['duration'], value)
p_op = fg.config['experiment']['duration']
if (fg.config['experiment']['duration'] < fg.config['experiment']['interval'] ):
fg.config['experiment']['interval'] = fg.config['experiment']['duration']
self.ids['lbl_imaging_measiter'].text = imaging_set_time_write(p_op)
p_lbl.text = imaging_set_time_write(p_op)
def imaging_set_time_chkbound_and_update(p_op,value):
if value[1] > 0 or (p_op + value[1] * [86400, 3600, 60, 1][value[0]] >= 0):
p_op += value[1]*[86400,3600,60,1][value[0]]
return p_op
def imaging_set_time_write(p_op):
val = experiment_duration_format(p_op,'forward')
return str(val[0]) + "d " + str(val[1]) + "h " + str(val[2]) + "m " + str(val[3]) + "s"
def imaging_set_time_init(self):
self.ids['lbl_imaging_measiter'].text = imaging_set_time_write(fg.config['experiment']['interval'])
self.ids['lbl_imaging_totaldurat'].text = imaging_set_time_write(fg.config['experiment']['duration'])
self.ids['lbl_imaging_totaldurat'].canvas.ask_update()
self.ids['lbl_imaging_measiter'].canvas.ask_update()
def slider_change(self,instance):
print('%s value has changed to %s' % (instance.name, str(instance.value)))
#fg.ledarr.send("RECT+0+0+8+8+1", int(instance.value), int(instance.value), int(instance.value))
if check_active(self.ids['btn_light_fluo']):
fg.fluo.send("FLUO", int(instance.value))
print('Fluo active, sent FLUO+{}.'.format(int(instance.value)))
fg.config['light']['intensity'] = int(instance.value)
def buttons_light(self,instance):
if fg.my_dev_flag:
print 'I am delivering data to the arduino by pidgeon. Takes a while...'
light_change_status(self, instance)
select_method(self, instance, "light_buttons")
#############################
# #
# == Imaging Methods == #
# #
#############################
def chk_experiment_created(self,instance,name):
if instance.text == name:
if fg.started_first_exp:
self.ids["sm"].current = 'scr_imaging'
self.ids["btn_scr_name"].text = 'IMA\nGING'
else:
self.ids["sm"].current = 'scr_start'
self.ids["btn_scr_name"].text = 'STA\nRT'
def run_measurement(self, instance):
# prepare folder
fluidiscopeIO.prepareFolder()
# put data into config-dictionary
set_measurement_parameter(self)
# clear arduino and set to flyby (= do not save patterns)
if not fg.my_dev_flag:
fg.ledarr.send("CLEAR")
time.sleep(0.04)
fg.ledarr.send("FLYBY", 1)
# set status of autofocus to False
#fg.config['experiment']['is_autofocus_request'] = False
#fg.config['experiment']['is_autofocus_busy'] = False
if instance.uid == self.ids['btn_snap'].uid:
select_method(self, instance, "take_image")
activate(instance)
take_image(self)
abort_measurement(self, instance)
else:
# rewrite button-text if necessary
if instance.text == "Start Measurement":
instance.text = "Stop Measurement"
# put values into display:
update_measurement_status_display(self)
# activate and deactivate according buttons
select_method(self, instance, "take_image")
activate(instance)
# let the device settle for a bit
time.sleep(0.2)
# schedule callback-function
#if imaging_callback(self, instance):
if 'meas' in fg.EVENT:
pass
event_delete(fg.EVENT['meas'])
event_delete(fg.EVENT['meas_disp'])
else:
# fg.EVENT = Clock.schedule_interval(partial(autofocus_callback, self, instance), fg.config['experiment']['interval_autofocus'])
update_interval = 1 # for timer display refresh
fg.EVENT['meas'] = Clock.schedule_interval(partial(imaging_callback, self, instance),fg.config['experiment']['interval'])# in seconds
fg.EVENT['meas_disp'] = Clock.schedule_interval(partial(update_measurement_status_display_timer, self, update_interval),update_interval) # in seconds
#if 'autofocus' in fg.EVENT:
# print("autofocus_measure angelegt mit time {}".format(fg.config['autofocus']['time_interval_min']*60))
# fg.EVENT['autofocus_measure'] = Clock.schedule_interval(partial(run_autofocus,instance),fg.config['autofocus']['time_interval_min']*60) # in seconds
#if 'autofocus' in fg.EVENT:
# fg.EVENT['autofocus_measure'].cancel()
# Clock.unschedule(fg.EVENT['autofocus_measure'])
#print("not implemented yet")
def set_measurement_parameter(self):
fg.config['light']['intensity_expt'] = fg.config['light']['intensity']
if fg.config['experiment']['imaging_cause'] == 'SNAP':
fg.config['experiment']['snap_num'] += 1
else:
fg.config['experiment']['imaging_method'] = get_imaging_method(self)
fg.config['experiment']['imaging_num'] = 0
fg.config['experiment']['time_left'] = fg.config['experiment']['duration']
fg.config['experiment']['time_passed'] = 0
fg.config['experiment']['images_total'] = int(
fg.config['experiment']['duration'] / fg.config['experiment']['interval'] + 1) # 1 image directly taken on start
fg.config['experiment']['images_left'] = fg.config['experiment']['images_total']
fg.config['experiment']['images_taken'] = 0
fg.config['experiment']['success'] = False
def update_measurement_parameters(self):
fg.config['experiment']['images_left'] -= 1
#if (fg.config['experiment']['images_taken'] > 0):
# fg.config['experiment']['time_left'] -= fg.config['experiment']['interval']
# fg.config['experiment']['time_passed'] += fg.config['experiment']['interval']
fg.config['experiment']['images_taken'] += 1
if fg.config['experiment']['images_left'] == 0:
fg.config['experiment']['time_left'] = 0
fg.config['experiment']['time_passed'] = fg.config['experiment']['duration']
def update_measurement_status_display(self):
self.ids['status_images_left'].text = str(fg.config['experiment']['images_left'])
self.ids['status_time_left'].text = imaging_set_time_write(
fg.config['experiment']['time_left']) # str(int(fg.config['experiment']['time_left'] / 60)) + 'm'
self.ids['status_images_taken'].text = str(fg.config['experiment']['images_taken'])
self.ids['status_time_passed'].text = imaging_set_time_write(
fg.config['experiment']['time_passed']) # str(int(fg.config['experiment']['time_passed'] / 60)) + 'm'
#if 'meas' in fg.EVENT:
# print(fg.EVENT['meas'])
def update_measurement_status_display_timer(self, interval, *rargs):
if not fg.config['experiment']['is_autofocus_busy']:
fg.config['experiment']['time_left'] -= interval
fg.config['experiment']['time_passed'] += interval
update_measurement_status_display(self)
def abort_measurement(self, instance):
deactivate(instance)
imaging_method_dic = {"Bright": 'btn_imaging_technique_1', "qDPC": "btn_imaging_technique_2",
"Custom": "btn_imaging_technique_3", "Fluor": "btn_imaging_technique_fluor"}
change_enable_status(instance, False)
while not fg.config['experiment']['active_methods'] == []:
key = fg.config['experiment']['active_methods'].pop(0)
deactivate(self.ids[imaging_method_dic[key]])
for key in imaging_method_dic:
change_enable_status(self.ids[imaging_method_dic[key]], True)
activate_methods = ["btn_imaging_measiter", "btn_imaging_totaldurat","btn_imaging_dplus", "btn_imaging_dminus","btn_imaging_hplus", "btn_imaging_hminus",
"btn_imaging_mplus", "btn_imaging_mminus","btn_imaging_splus", "btn_imaging_sminus",]
change_enable_status_chain(self, True, activate_methods)
if not instance.uid == self.ids['btn_snap'].uid:
event_delete('meas')
event_delete('meas_disp')
fg.config['experiment']['last_expt_num'] = fg.expt_num
show_notification_labels(self, instance)
def event_delete(event_name):
fg.EVENT[event_name].cancel()
Clock.unschedule(fg.EVENT[event_name])
fg.EVENT.pop(event_name,None)
print("Event: ~{0}~ was canceled and safely deleted.".format(event_name))
# not used anymore?? ---------------------------------------
#def take_snapshot(self, instance):
# take_image(self, instance.text)
#
# if instance.text in ["SNAP", "BG", "FG"]: # switch color
# imaging_method_dic = {"Bright": 'btn_imaging_technique_1', "qDPC": "btn_imaging_technique_2",
# "Custom": "btn_imaging_technique_3"}
# select_method(self, instance, "take_image")
# change_enable_status(self.ids[imaging_method_dic[fg.config['experiment']['imaging_method']]], True)
#
# fg.ledarr.send("CLEAR")
# ----------------------------------------------------------
def filename_take_image_now_refine(filename='',imaging_cause='MEAS', file_format='.jpg'):
if imaging_cause == 'MEAS':
filename += '-' + str(fg.config['experiment']['imaging_num'])
elif imaging_cause == 'SNAP':
filename += '-' + str(fg.config['experiment']['snap_num'])
else:
filename += '-' + str(fg.config['experiment']['autofocus_num'])
return filename + file_format
#really just takes an image
def take_image_now(self,imaging_cause='MEAS', filename='', method='CUS'):
# get correct filename
filename = filename_take_image_now_refine(filename=filename,imaging_cause=imaging_cause, file_format='.jpg')
# start
print("This is _take_image_now_-Func saving to: {}".format(filename))
if fg.my_dev_flag:
print("Image taken -- DEV-MODE --.")
else:
# prepare camera
camera_set_parameter(method=method)
# select for imaging cause ->
if imaging_cause == 'AF':
fg.camera.capture(rawCapture,'rgb')
image=rawCapture.array[:,:,fg.config['autofocus']['use_channel']]
return image
else:
fg.camera.capture(filename)
return True
def take_image(self, *args):
'''
Method that switches through different imaging modalities. Does hold the respective algorithms.
'''
set_active_again = False
active_modes = []
if fg.config['experiment']['imaging_cause'] == 'AF': # case of autofocus
image_name = set_image_name(im_cause='AF',method='CUS')
file_name_write = uni.Path(fg.expt_path, image_name)
time.sleep(0.1)
fluidiscopeIO.update_matrix(self, ignore_NA=True, sync_only=False)
time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self, 'AF', file_name_write)
fg.ledarr.send("CLEAR")
else:
for myl in range(0,len(fg.config['experiment']['active_methods'])):
active_method = fg.config['experiment']['active_methods'][myl] # active method
print("Using method {} of {}: {}.".format(myl,len(fg.config['experiment']['active_methods'])-1,active_method))
image_name = set_image_name(im_cause=fg.config['experiment']['imaging_cause'],method=active_method)
file_name_write = uni.Path(fg.expt_path, image_name)
#print("file_name_write = " + file_name_write)
# make sure preview is off
set_active_again = False
if check_active(self.ids['btn_preview']):
camera_preview(False)
set_active_again = True
for x in ['btn_light_full','btn_light_preset_pattern','btn_light_custom_pattern','btn_light_fluo']:
if check_active(self.ids[x]):
buttons_light(self, self.ids[x])
active_modes.append(x)
try:
if active_method == 'Fluor':
# swith to customized LED field
fg.fluo.send("FLUO",fg.config['light']['intensity_expt'])
file_name_write_fluo = file_name_write + '-INT_' + str(fg.config['light']['intensity_expt'])
time.sleep(fg.config['experiment']['i2c_send_delay'])
#time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write_fluo)
fg.fluo.send("FLUO",0)
time.sleep(fg.config['experiment']['i2c_send_delay'])
else:
fg.ledarr.send("CLEAR")
# 2) Decide what images to take
col = int(fg.config['light']['intensity_expt'])
#print("Color: " + str(col))
if active_method in ["BG", "FG"]:
# imaging
if active_method == "BG":
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write)
else:
fg.ledarr.send("NA+2")
fg.ledarr.send("RECT+0+0+8+8+1", col, col, col)
time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write)
else:
if active_method == 'Bright':
fg.ledarr.send("NA+3")
fg.ledarr.send("RECT+0+0+8+8+1", col, col, col)
time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write)
elif active_method == "qDPC":
pattern_list = prepare_illu_pattern_list()
#Clock.schedule_once(partial(
tin_returnval = pattern_disp_func(self,pattern_list,True,file_name_write,fg.config['imaging']['speed'])
elif active_method== "Custom":
# swith to customized LED field
time.sleep(0.1)
fluidiscopeIO.update_matrix(self, ignore_NA=True, sync_only=False)
time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write)
fg.ledarr.send("CLEAR")
else:
# set now with small NA image
file_name_write = uni.Path(fg.expt_path, image_name)
# fluidiscopeIO.update_matrix(self, instance, ignoreNA=True, sync_only=False)
# time.sleep(0.5)
fg.ledarr.send("RECT+3+3+2+2+1", col, col, col)
time.sleep(fg.config['imaging']['speed'])
tin_returnval = take_image_now(self,fg.config['experiment']['imaging_cause'], file_name_write)
fg.ledarr.send("RECT+3+3+2+2+1+0+0+0")
finally:
pass
if active_method in ['Bright','qDPC','Custom','Fluor']:
fg.config['experiment']['imaging_num'] += 1
fg.config['experiment']['expt_last_image'] = file_name_write + fg.config['imaging']['extension']
fg.ledarr.send("CLEAR")
if set_active_again:
camera_preview(True)
for x in active_modes:
buttons_light(self, self.ids[x])
# True -> normal images taken;
# image -> case of autofocus
return tin_returnval
#print("fg.config['experiment']['expt_last_image']" + fg.config['experiment']['expt_last_image'])
def set_image_name(im_cause=None,method=None,mytime=None):
'''
Creating the image_name for the used method.
:param:
-------
:im_cause: <STRING> defines the reason for the image
-> AF, SNAP, MEAS, BG
:method: <STRING> that sets the input method
-> FULL, PRE, CUS, FLUO
:mytime: <STRING> that gives the time of start of the experiment
-> hhmmss
'''
now = str(datetime.now().strftime("%H%M%S"))
image_name = "{}-".format(fg.today)
if not im_cause == None:
image_name += "{}-".format(im_cause)
if not method == None:
image_name += "{}-".format(method)
if not mytime == None:
image_name += "{}-".format(now)
return image_name
def resizeImage(infile, resize_factor=5): # used to show image in preview
if not fg.my_dev_flag:
#path = uni.Path(infile).parent()
im = cv.LoadImage(infile)
thumbnail = cv.CreateMat(im.rows / resize_factor, im.cols / resize_factor, cv.CV_8UC3) #inherently rounds
cv.Resize(im, thumbnail)
fname = infile + "_thumbnail.jpg" #path
cv.imwrite(fname, thumbnail)
# fg.config['experiment']['expt_last_image'] = fname
return fname
def camera_set_parameter(method='CUS'):
if not fg.my_dev_flag:
print("Autofocus is set to False!")
if method in ['CUS','qDPC','Bright','BG','FG']:
method_key = 'cam'
fg.camera.resolution = tuple(fg.config[method_key]['resolution'])
fg.camera.contrast = fg.config[method_key]['contrast']
fg.camera.sharpness = fg.config[method_key]['sharpness']
fg.camera.brightness = fg.config[method_key]['brightness']
fg.camera.saturation = fg.config[method_key]['saturation']
fg.camera.ISO = fg.config[method_key]['iso']
fg.camera.video_stabilization = fg.config[method_key]['videoStabilization']
fg.camera.exposure_compensation = fg.config[method_key]['exposureCompensation']
fg.camera.exposure_mode = fg.config[method_key]['exposureMode']
fg.camera.meter_mode = fg.config[method_key]['meterMode']
fg.camera.awb_mode = fg.config[method_key]['awbMode']
if fg.config[method_key]['awbMode'] == 'off':
fg.camera.awb_gains = (Fraction(200, 128), Fraction(200, 128)) # (red, blue) [0..8] TODO: Get values from YAML, Only some randomly chosen values! fg.config[method_key]['awbGain']
fg.camera.image_effect = fg.config[method_key]['imageEffects']
fg.camera.color_effects = fg.config[method_key]['colorEffects']
fg.camera.rotation = fg.config[method_key]['rotation']
fg.camera.hflip = fg.config[method_key]['hflip']
fg.camera.vflip = fg.config[method_key]['vflip']
fg.camera.crop = tuple(fg.config[method_key]['crop'])
fg.camera.shutter_speed = fg.config[method_key]['shutterSpeed']
elif method == 'Fluor':
method_key = 'cam_fluo'
fg.camera.resolution = tuple(fg.config[method_key]['resolution'])
fg.camera.contrast = fg.config[method_key]['contrast']
fg.camera.sharpness = fg.config[method_key]['sharpness']
fg.camera.brightness = fg.config[method_key]['brightness']
fg.camera.saturation = fg.config[method_key]['saturation']
fg.camera.ISO = fg.config[method_key]['iso']
fg.camera.video_stabilization = fg.config[method_key]['videoStabilization']
fg.camera.exposure_compensation = fg.config[method_key]['exposureCompensation']
fg.camera.exposure_mode = fg.config[method_key]['exposureMode']
fg.camera.meter_mode = fg.config[method_key]['meterMode']
fg.camera.awb_mode = fg.config[method_key]['awbMode']
if fg.config[method_key]['awbMode'] == 'off':
fg.camera.awb_gains = (Fraction(200, 128), Fraction(200, 128)) # (red, blue) [0..8] TODO: Get values from YAML, Only some randomly chosen values! fg.config[method_key]['awbGain']
fg.camera.image_effect = fg.config[method_key]['imageEffects']
fg.camera.color_effects = fg.config[method_key]['colorEffects']
fg.camera.rotation = fg.config[method_key]['rotation']
fg.camera.hflip = fg.config[method_key]['hflip']
fg.camera.vflip = fg.config[method_key]['vflip']
fg.camera.crop = tuple(fg.config[method_key]['crop'])
fg.camera.shutter_speed = fg.config[method_key]['shutterSpeed']
print("Camera shutter_speed={}, exposure_speed={} at ISO=.".format(fg.camera.shutter_speed, fg.camera.exposure_speed, fg.camera.iso))
print("Camera preparation done for method=".format(method))
return True
def crop_image():
pass
def camera_capture(filename,*rargs):
if not fg.my_dev_flag:
print("Camera capture: " + filename)
filename = filename + fg.config['imaging']['extension']
if len(rargs) > 0:
if rargs[0] == 'autofocus':
rawCapture = PiRGBArray(fg.camera)
fg.camera.capture(rawCapture,'rgb')
return rawCapture
else:
fg.camera.capture(filename)
return True
# fg.ledarr.send("CLEAR")
def imaging_callback(self, *largs):
print '\nThis is the imaging callback speaking !\n<> Images are now taken!'
# skip imaging step during autofocus
if not fg.config['experiment']['is_autofocus_busy']:
# take image
fg.config['experiment']['imaging_method']='MEAS'
take_image(self)
deact_me = False
if (fg.config['experiment']['time_left']-fg.config['experiment']['interval']) >= 0:
# update config entries
update_measurement_parameters(self)
# update display entries
update_measurement_status_display(self)
return True
elif any([fg.config['experiment']['time_left'] == 0,fg.config['experiment']['time_left']-fg.config['experiment']['interval'] < 0]):
update_measurement_parameters(self)
update_measurement_status_display(self)
deact_me = True
else:
deact_me = True
if deact_me:
fg.config['experiment']['success'] = True
imaging_method_dic = {"Bright": 'btn_imaging_technique_1', "qDPC": "btn_imaging_technique_2",
"Custom": "btn_imaging_technique_3","Fluor":"btn_imaging_technique_fluor"}
switch_start_condition(self, instance)
deactivate(self.ids[imaging_method_dic[fg.config['experiment']['imaging_method']]])
keys=['meas_disp','autofocus_measure']
if keys[0] in fg.EVENT:
event_delete(keys[0])
if keys[1] in fg.EVENT:
event_delete(keys[1])
return False
def autofocus(self, instance):
'''
Autofocus to be called from main-routine on button click.
:param self:
:param instance:
:return:
'''
set_autofocus(self,instance)
change_activation_status(instance)
key = 'autofocus_now' if (instance.uid == self.ids['btn_autofocus_now'].uid) else 'autofocus'
if not key in fg.EVENT:
run_autofocus(self,instance,key)
else:
event_delete(key)
def set_autofocus(self, instance):
'''
Button logic for autofocus.
:param self:
:param instance:
:return:
'''
print("Autofocus-00a2- DevFlag={}".format(fg.my_dev_flag))
#if not (fg.my_dev_flag):
if check_active(instance):
print("Autofocus-00a2- now deactivating autofocus")
fg.config['experiment']['is_autofocus'] = False
if instance.uid==self.ids['btn_autofocus'].uid:
refresh_text_entry(instance, "Autofocus disabled!")
print("Autofocus-00a4- Autofocus disabled")
else:
print("Autofocus-00a2- now setting autofocus")
fg.config['experiment']['is_autofocus'] = True
if instance.uid==self.ids['btn_autofocus'].uid:
refresh_text_entry(instance, "Autofocus enabled!")
print("Autofocus-00a4- Autofocus enabled")
def run_autofocus(self,instance,key):
'''
Always runs autofocus only once!
'''
if key == 'autofocus_now':
if not fg.config['experiment']['is_autofocus_busy']:
fg.EVENT['autofocus_now'] = Clock.schedule_once(partial(af.autofocus_callback, self,instance),1)#start direct after 1 sec
else:#auto-deactivate autofocus
set_autofocus(self, instance)
change_activation_status(instance)
else:
fg.EVENT['autofocus_measure'] = Clock.schedule_interval(partial(run_autofocus, instance),fg.config['autofocus']['time_interval_min']*60)
print('Autofocus-01-Started autofocus routine.')
def autofocus_callback(self, instance, *rargs):
# start autofocus if necessary and only if it is not already in progress
print("Autofocus-02-callback started.")