-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCalibration.py
More file actions
1507 lines (1281 loc) · 50.7 KB
/
Calibration.py
File metadata and controls
1507 lines (1281 loc) · 50.7 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
import numpy as np
import matplotlib.pyplot as plt
import time
from iohub import open_ome_zarr
from recOrder.io.core_functions import *
from recOrder.calib.Optimization import BrentOptimizer, MinScalarOptimizer
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from napari.utils.notifications import show_warning
from scipy.interpolate import interp1d
from scipy.stats import linregress
from scipy.optimize import least_squares
import json
import os
import logging
import warnings
from recOrder.io.utils import MockEmitter
from datetime import datetime
from importlib_metadata import version
LC_DEVICE_NAME = "MeadowlarkLC"
class QLIPP_Calibration:
def __init__(
self,
mmc,
mm,
group="Channel",
lc_control_mode="MM-Retardance",
interp_method="schnoor_fit",
wavelength=532,
optimization="min_scalar",
print_details=True,
):
"""
Parameters
----------
mmc : object
MicroManager core instance
mm : object
MicroManager Studio instance
group : str
Name of the MicroManager channel group used defining LC states [State0, State1, State2, ...]
lc_control_mode : str
Defined the control mode of the liquid crystals. One of the following:
* MM-Retardance: The retardance of the LC is set directly through the MicroManager LC device adapter. The
MicroManager device adapter determines the corresponding voltage which is sent to the LC.
* MM-Voltage: The CalibrationData class in recOrder uses the LC calibration data to determine the correct
LC voltage for a given retardance. The LC voltage is set through the MicroManager LC device adapter.
* DAC: The CalibrationData class in recOrder uses the LC calibration data to determine the correct
LC voltage for a given retardance. The voltage is applied to the IO port of the LC controller through the
TriggerScope DAC outputs.
interp_method : str
Method of interpolating the LC retardance-to-voltage calibration curve. One of the following:
* linear: linear interpolation of retardance as a function of voltage and wavelength
* schnoor_fit: Schnoor fit interpolation as described in https://doi.org/10.1364/AO.408383
wavelength : float
Measurement wavelength
optimization : str
LC retardance optimization method, 'min_scalar' (default) or 'brent'
print_details : bool
Set verbose option
"""
# Micromanager API
self.mm = mm
self.mmc = mmc
self.snap_manager = mm.getSnapLiveManager()
# Meadowlark LC Device Adapter Property Names
self.PROPERTIES = {
"LCA": (LC_DEVICE_NAME, "Retardance LC-A [in waves]"),
"LCB": (LC_DEVICE_NAME, "Retardance LC-B [in waves]"),
"LCA-Voltage": (LC_DEVICE_NAME, "Voltage (V) LC-A"),
"LCB-Voltage": (LC_DEVICE_NAME, "Voltage (V) LC-B"),
"LCA-DAC": ("TS1_DAC01", "Volts"),
"LCB-DAC": ("TS1_DAC02", "Volts"),
"State0": (
LC_DEVICE_NAME,
"Pal. elem. 00; enter 0 to define; 1 to activate",
),
"State1": (
LC_DEVICE_NAME,
"Pal. elem. 01; enter 0 to define; 1 to activate",
),
"State2": (
LC_DEVICE_NAME,
"Pal. elem. 02; enter 0 to define; 1 to activate",
),
"State3": (
LC_DEVICE_NAME,
"Pal. elem. 03; enter 0 to define; 1 to activate",
),
"State4": (
LC_DEVICE_NAME,
"Pal. elem. 04; enter 0 to define; 1 to activate",
),
}
self.group = group
# GUI Emitter
self.intensity_emitter = MockEmitter()
self.plot_sequence_emitter = MockEmitter()
# Set Mode
# TODO: make sure LC or TriggerScope are loaded in the respective modes
allowed_modes = ["MM-Retardance", "MM-Voltage", "DAC"]
if lc_control_mode not in allowed_modes:
raise ValueError(f"LC control mode must be one of {allowed_modes}")
self.mode = lc_control_mode
self.LC_DAC_conversion = 4 # convert between the input range of LCs (0-20V) and the output range of the DAC (0-5V)
# Initialize calibration class
allowed_interp_methods = ["schnoor_fit", "linear"]
if interp_method not in allowed_interp_methods:
raise ValueError(
"LC calibration data interpolation method must be one of "
f"{allowed_interp_methods}"
)
dir_path = mmc.getDeviceAdapterSearchPaths().get(
0
) # MM device adapter directory
self.calib = CalibrationData(
os.path.join(dir_path, "mmgr_dal_MeadowlarkLC.csv"),
interp_method=interp_method,
wavelength=wavelength,
)
# Optimizer
if optimization == "min_scalar":
self.optimizer = MinScalarOptimizer(self)
elif optimization == "brent":
self.optimizer = BrentOptimizer(self)
else:
raise ModuleNotFoundError(f"No optimizer named {optimization}")
# User / Calculated Parameters
self.swing = None
self.wavelength = None
self.lc_bound = None
self.I_Black = None
self.ratio = 1.793
self.print_details = print_details
self.calib_scheme = "4-State"
# LC States
self.lca_ext = None
self.lcb_ext = None
self.lca_0 = None
self.lcb_0 = None
self.lca_45 = None
self.lcb_45 = None
self.lca_60 = None
self.lcb_60 = None
self.lca_90 = None
self.lcb_90 = None
self.lca_120 = None
self.lcb_120 = None
self.lca_135 = None
self.lcb_135 = None
# Calibration Outputs
self.I_Ext = None
self.I_Ref = None
self.I_Elliptical = None
self.inten = []
self.swing0 = None
self.swing45 = None
self.swing60 = None
self.swing90 = None
self.swing120 = None
self.swing135 = None
self.height = None
self.width = None
self.directory = None
self.inst_mat = None
# Shutter
self.shutter_device = self.mmc.getShutterDevice()
self._auto_shutter_state = None
self._shutter_state = None
def set_dacs(self, lca_dac, lcb_dac):
self.PROPERTIES["LCA-DAC"] = (f"TS1_{lca_dac}", "Volts")
self.PROPERTIES["LCB-DAC"] = (f"TS1_{lcb_dac}", "Volts")
def set_wavelength(self, wavelength):
self.calib.set_wavelength(wavelength)
self.wavelength = self.calib.wavelength
def set_lc(self, retardance, LC: str):
"""
Set LC state to given retardance in waves
Parameters
----------
retardance : float
Retardance in waves
LC : str
LCA or LCB
Returns
-------
"""
if self.mode == "MM-Retardance":
set_lc_waves(self.mmc, self.PROPERTIES[f"{LC}"], retardance)
elif self.mode == "MM-Voltage":
volts = self.calib.get_voltage(retardance)
set_lc_voltage(self.mmc, self.PROPERTIES[f"{LC}-Voltage"], volts)
elif self.mode == "DAC":
volts = self.calib.get_voltage(retardance)
dac_volts = volts / self.LC_DAC_conversion
set_lc_daq(self.mmc, self.PROPERTIES[f"{LC}-DAC"], dac_volts)
def get_lc(self, LC: str):
"""
Get LC retardance in waves
Parameters
----------
LC : str
LCA or LCB
Returns
-------
LC retardance in waves
"""
if self.mode == "MM-Retardance":
retardance = get_lc(self.mmc, self.PROPERTIES[f"{LC}"])
elif self.mode == "MM-Voltage":
volts = get_lc(
self.mmc, self.PROPERTIES[f"{LC}-Voltage"]
) # returned value is in volts
retardance = self.calib.get_retardance(volts)
elif self.mode == "DAC":
dac_volts = get_lc(self.mmc, self.PROPERTIES[f"{LC}-DAC"])
volts = dac_volts * self.LC_DAC_conversion
retardance = self.calib.get_retardance(volts)
return retardance
def define_lc_state(self, state, lca_retardance, lcb_retardance):
"""
Define of the two LCs after calibration
Parameters
----------
state: str
Polarization stage (e.g. State0)
lca_retardance: float
LCA retardance in waves
lcb_retardance: float
LCB retardance in waves
Returns
-------
"""
if self.mode == "MM-Retardance":
self.set_lc(lca_retardance, "LCA")
self.set_lc(lcb_retardance, "LCB")
define_meadowlark_state(self.mmc, self.PROPERTIES[state])
elif self.mode == "DAC":
lca_volts = (
self.calib.get_voltage(lca_retardance) / self.LC_DAC_conversion
)
lcb_volts = (
self.calib.get_voltage(lcb_retardance) / self.LC_DAC_conversion
)
define_config_state(
self.mmc,
self.group,
state,
[self.PROPERTIES["LCA-DAC"], self.PROPERTIES["LCB-DAC"]],
[lca_volts, lcb_volts],
)
elif self.mode == "MM-Voltage":
lca_volts = self.calib.get_voltage(lca_retardance)
lcb_volts = self.calib.get_voltage(lcb_retardance)
define_config_state(
self.mmc,
self.group,
state,
[
self.PROPERTIES["LCA-Voltage"],
self.PROPERTIES["LCB-Voltage"],
],
[lca_volts, lcb_volts],
)
def opt_lc(self, x, device_property, reference, normalize=False):
if isinstance(x, list) or isinstance(x, tuple):
x = x[0]
self.set_lc(x, device_property)
mean = snap_and_average(self.snap_manager)
if normalize:
max_ = 65335
min_ = self.I_Black
val = (mean - min_) / (max_ - min_)
ref = (reference - min_) / (max_ - min_)
logging.debug(f"LC-Value: {x}")
logging.debug(f"F-Value:{val - ref}\n")
return val - ref
else:
logging.debug(str(mean))
self.intensity_emitter.emit(mean)
self.inten.append(mean - reference)
return np.abs(mean - reference)
def opt_lc_cons(self, x, device_property, reference, mode):
self.set_lc(x, device_property)
swing = (self.lca_ext - x) * self.ratio
if mode == "60":
self.set_lc(self.lcb_ext + swing, "LCB")
if mode == "120":
self.set_lc(self.lcb_ext - swing, "LCB")
mean = snap_and_average(self.snap_manager)
logging.debug(str(mean))
# append to intensity array for plotting later
self.intensity_emitter.emit(mean)
self.inten.append(mean - reference)
return np.abs(mean - reference)
def opt_lc_grid(self, a_min, a_max, b_min, b_max, step):
"""
Exhaustive Search method
Finds the minimum intensity value for a given
grid of LCA,LCB values
:param a_min: float
Minimum value of LCA
:param a_max: float
Maximum value of LCA
:param b_min: float
Minimum value of LCB
:param b_max: float
Maximum value of LCB
:param step: float
step size of the grid between max/min values
:return best_lca: float
LCA value corresponding to lowest mean Intensity
:return best_lcb: float
LCB value corresponding to lowest mean Intensity
:return min_int: float
Lowest value of mean Intensity
"""
min_int = 65536
better_lca = -1
better_lcb = -1
# coarse search
for lca in np.arange(a_min, a_max, step):
for lcb in np.arange(b_min, b_max, step):
self.set_lc(lca, "LCA")
self.set_lc(lcb, "LCB")
# current_int = np.mean(snap_image(calib.mmc))
current_int = snap_and_average(self.snap_manager)
self.intensity_emitter.emit(current_int)
if current_int < min_int:
better_lca = lca
better_lcb = lcb
min_int = current_int
logging.debug(
"update (%f, %f, %f)"
% (min_int, better_lca, better_lcb)
)
logging.debug("coarse search done")
logging.debug("better lca = " + str(better_lca))
logging.debug("better lcb = " + str(better_lcb))
logging.debug("better int = " + str(min_int))
best_lca = better_lca
best_lcb = better_lcb
return best_lca, best_lcb, min_int
# ========== Optimization wrappers =============
# ==============================================
def opt_Iext(self):
self.plot_sequence_emitter.emit("Coarse")
logging.info("Calibrating State0 (Extinction)...")
logging.debug("Calibrating State0 (Extinction)...")
set_lc_state(self.mmc, self.group, "State0")
time.sleep(2)
# Perform exhaustive search with step 0.1 over range:
# 0.01 < LCA < 0.5
# 0.25 < LCB < 0.75
step = 0.1
logging.debug(f"================================")
logging.debug(f"Starting first grid search, step = {step}")
logging.debug(f"================================")
best_lca, best_lcb, i_ext_ = self.opt_lc_grid(
0.01, 0.5, 0.25, 0.75, step
)
logging.debug("grid search done")
logging.debug("lca = " + str(best_lca))
logging.debug("lcb = " + str(best_lcb))
logging.debug("intensity = " + str(i_ext_))
self.set_lc(best_lca, "LCA")
self.set_lc(best_lcb, "LCB")
logging.debug(f"================================")
logging.debug(f"Starting fine search")
logging.debug(f"================================")
# Perform brent optimization around results of 2nd grid search
# threshold not very necessary here as intensity value will
# vary between exposure/lamp intensities
self.plot_sequence_emitter.emit("Fine")
lca, lcb, I_ext = self.optimizer.optimize(
state="ext",
lca_bound=0.1,
lcb_bound=0.1,
reference=self.I_Black,
thresh=1,
n_iter=5,
)
# Set the Extinction state to values output from optimization
self.define_lc_state("State0", lca, lcb)
self.lca_ext = lca
self.lcb_ext = lcb
self.I_Ext = I_ext
logging.debug("fine search done")
logging.info(f"LCA State0 (Extinction) = {lca:.3f}")
logging.debug(f"LCA State0 (Extinction) = {lca:.5f}")
logging.info(f"LCB State0 (Extinction) = {lcb:.3f}")
logging.debug(f"LCB State0 (Extinction) = {lcb:.5f}")
logging.info(f"Intensity (Extinction) = {I_ext:.0f}")
logging.debug(f"Intensity (Extinction) = {I_ext:.3f}")
logging.debug("--------done--------")
logging.info("--------done--------")
def opt_I0(self):
"""
no optimization performed for this. Simply apply swing and read intensity
This is the same as "Ielliptical". Used for both schemes.
:return: float
mean of image
"""
logging.info("Calibrating State1 (I0)...")
logging.debug("Calibrating State1 (I0)...")
self.lca_0 = self.lca_ext - self.swing
self.lcb_0 = self.lcb_ext
self.set_lc(self.lca_0, "LCA")
self.set_lc(self.lcb_0, "LCB")
self.define_lc_state("State1", self.lca_0, self.lcb_0)
intensity = snap_and_average(self.snap_manager)
self.I_Elliptical = intensity
self.swing0 = np.sqrt(
(self.lcb_0 - self.lcb_ext) ** 2 + (self.lca_0 - self.lca_ext) ** 2
)
logging.info(f"LCA State1 (I0) = {self.lca_0:.3f}")
logging.debug(f"LCA State1 (I0) = {self.lca_0:.5f}")
logging.info(f"LCB State1 (I0) = {self.lcb_0:.3f}")
logging.debug(f"LCB State1 (I0) = {self.lcb_0:.5f}")
logging.info(f"Intensity (I0) = {intensity:.0f}")
logging.debug(f"Intensity (I0) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def opt_I45(self, lca_bound, lcb_bound):
"""
optimized relative to Ielliptical (opt_I90)
Parameters
----------
lca_bound
lcb_bound
Returns
-------
lca, lcb value at optimized state
intensity value at optimized state
"""
self.inten = []
logging.info("Calibrating State2 (I45)...")
logging.debug("Calibrating State2 (I45)...")
self.set_lc(self.lca_ext, "LCA")
self.set_lc(self.lcb_ext - self.swing, "LCB")
self.lca_45, self.lcb_45, intensity = self.optimizer.optimize(
"45",
lca_bound,
lcb_bound,
reference=self.I_Elliptical,
n_iter=5,
thresh=0.01,
)
self.define_lc_state("State2", self.lca_45, self.lcb_45)
self.swing45 = np.sqrt(
(self.lcb_45 - self.lcb_ext) ** 2
+ (self.lca_45 - self.lca_ext) ** 2
)
logging.info(f"LCA State2 (I45) = {self.lca_45:.3f}")
logging.debug(f"LCA State2 (I45) = {self.lca_45:.5f}")
logging.info(f"LCB State2 (I45) = {self.lcb_45:.3f}")
logging.debug(f"LCB State2 (I45) = {self.lcb_45:.5f}")
logging.info(f"Intensity (I45) = {intensity:.0f}")
logging.debug(f"Intensity (I45) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def opt_I60(self, lca_bound, lcb_bound):
"""
optimized relative to Ielliptical (opt_I0_4State)
Parameters
----------
lca_bound
lcb_bound
Returns
-------
lca, lcb value at optimized state
intensity value at optimized state
"""
self.inten = []
logging.info("Calibrating State2 (I60)...")
logging.debug("Calibrating State2 (I60)...")
# Calculate Initial Swing for initial guess to optimize around
# Based on ratio calculated from ellpiticity/orientation of LC simulation
swing_ell = np.sqrt(
(self.lca_ext - self.lca_0) ** 2 + (self.lcb_ext - self.lcb_0) ** 2
)
lca_swing = np.sqrt(swing_ell**2 / (1 + self.ratio**2))
lcb_swing = self.ratio * lca_swing
# Optimization
self.set_lc(self.lca_ext + lca_swing, "LCA")
self.set_lc(self.lcb_ext + lcb_swing, "LCB")
self.lca_60, self.lcb_60, intensity = self.optimizer.optimize(
"60",
lca_bound,
lcb_bound,
reference=self.I_Elliptical,
n_iter=5,
thresh=0.01,
)
self.define_lc_state("State2", self.lca_60, self.lcb_60)
self.swing60 = np.sqrt(
(self.lcb_60 - self.lcb_ext) ** 2
+ (self.lca_60 - self.lca_ext) ** 2
)
# Print comparison of target swing, target ratio
# Ratio determines the orientation of the elliptical state
# should be close to target. Swing will vary to optimize ellipticity
logging.debug(
f"ratio: swing_LCB / swing_LCA = {(self.lcb_ext - self.lcb_60) / (self.lca_ext - self.lca_60):.4f} \
| target ratio: {-self.ratio}"
)
logging.debug(
f"total swing = {self.swing60:.4f} | target = {swing_ell}"
)
logging.info(f"LCA State2 (I60) = {self.lca_60:.3f}")
logging.debug(f"LCA State2 (I60) = {self.lca_60:.5f}")
logging.info(f"LCB State2 (I60) = {self.lcb_60:.3f}")
logging.debug(f"LCB State2 (I60) = {self.lcb_60:.5f}")
logging.info(f"Intensity (I60) = {intensity:.0f}")
logging.debug(f"Intensity (I60) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def opt_I90(self, lca_bound, lcb_bound):
"""
optimized relative to Ielliptical (opt_I90)
Parameters
----------
lca_bound
lcb_bound
Returns
-------
lca, lcb value at optimized state
intensity value at optimized state
"""
logging.info("Calibrating State3 (I90)...")
logging.debug("Calibrating State3 (I90)...")
self.inten = []
self.set_lc(self.lca_ext + self.swing, "LCA")
self.set_lc(self.lcb_ext, "LCB")
self.lca_90, self.lcb_90, intensity = self.optimizer.optimize(
"90",
lca_bound,
lcb_bound,
reference=self.I_Elliptical,
n_iter=5,
thresh=0.01,
)
self.define_lc_state("State3", self.lca_90, self.lcb_90)
self.swing90 = np.sqrt(
(self.lcb_90 - self.lcb_ext) ** 2
+ (self.lca_90 - self.lca_ext) ** 2
)
logging.info(f"LCA State3 (I90) = {self.lca_90:.3f}")
logging.debug(f"LCA State3 (I90) = {self.lca_90:.5f}")
logging.info(f"LCB State3 (I90) = {self.lcb_90:.3f}")
logging.debug(f"LCB State3 (I90) = {self.lcb_90:.5f}")
logging.info(f"Intensity (I90) = {intensity:.0f}")
logging.debug(f"Intensity (I90) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def opt_I120(self, lca_bound, lcb_bound):
"""
optimized relative to Ielliptical (opt_I0_4State)
Parameters
----------
lca_bound
lcb_bound
Returns
-------
lca, lcb value at optimized state
intensity value at optimized state
"""
logging.info("Calibrating State3 (I120)...")
logging.debug("Calibrating State3 (I120)...")
# Calculate Initial Swing for initial guess to optimize around
# Based on ratio calculated from ellpiticity/orientation of LC simulation
swing_ell = np.sqrt(
(self.lca_ext - self.lca_0) ** 2 + (self.lcb_ext - self.lcb_0) ** 2
)
lca_swing = np.sqrt(swing_ell**2 / (1 + self.ratio**2))
lcb_swing = self.ratio * lca_swing
# Brent Optimization
self.set_lc(self.lca_ext + lca_swing, "LCA")
self.set_lc(self.lcb_ext - lcb_swing, "LCB")
self.lca_120, self.lcb_120, intensity = self.optimizer.optimize(
"120",
lca_bound,
lcb_bound,
reference=self.I_Elliptical,
n_iter=5,
thresh=0.01,
)
self.define_lc_state("State3", self.lca_120, self.lcb_120)
self.swing120 = np.sqrt(
(self.lcb_120 - self.lcb_ext) ** 2
+ (self.lca_120 - self.lca_ext) ** 2
)
# Print comparison of target swing, target ratio
# Ratio determines the orientation of the elliptical state
# should be close to target. Swing will vary to optimize ellipticity
logging.debug(
f"ratio: swing_LCB / swing_LCA = {(self.lcb_ext - self.lcb_120) / (self.lca_ext - self.lca_120):.4f}\
| target ratio: {self.ratio}"
)
logging.debug(
f"total swing = {self.swing120:.4f} | target = {swing_ell}"
)
logging.info(f"LCA State3 (I120) = {self.lca_120:.3f}")
logging.debug(f"LCA State3 (I120) = {self.lca_120:.5f}")
logging.info(f"LCB State3 (I120) = {self.lcb_120:.3f}")
logging.debug(f"LCB State3 (I120) = {self.lcb_120:.5f}")
logging.info(f"Intensity (I120) = {intensity:.0f}")
logging.debug(f"Intensity (I120) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def opt_I135(self, lca_bound, lcb_bound):
"""
optimized relative to Ielliptical (opt_I0)
Parameters
----------
lca_bound
lcb_bound
Returns
-------
lca, lcb value at optimized state
intensity value at optimized state
"""
logging.info("Calibrating State4 (I135)...")
logging.debug("Calibrating State4 (I135)...")
self.inten = []
self.set_lc(self.lca_ext, "LCA")
self.set_lc(self.lcb_ext + self.swing, "LCB")
self.lca_135, self.lcb_135, intensity = self.optimizer.optimize(
"135",
lca_bound,
lcb_bound,
reference=self.I_Elliptical,
n_iter=5,
thresh=0.01,
)
self.define_lc_state("State4", self.lca_135, self.lcb_135)
self.swing135 = np.sqrt(
(self.lcb_135 - self.lcb_ext) ** 2
+ (self.lca_135 - self.lca_ext) ** 2
)
logging.info(f"LCA State4 (I135) = {self.lca_135:.3f}")
logging.debug(f"LCA State4 (I135) = {self.lca_135:.5f}")
logging.info(f"LCB State4 (I135) = {self.lcb_135:.3f}")
logging.debug(f"LCB State4 (I135) = {self.lcb_135:.5f}")
logging.info(f"Intensity (I135) = {intensity:.0f}")
logging.debug(f"Intensity (I135) = {intensity:.3f}")
logging.info("--------done--------")
logging.debug("--------done--------")
def open_shutter(self):
if self.shutter_device == "": # no shutter
input("Please manually open the shutter and press <Enter>")
else:
self.mmc.setShutterOpen(True)
def reset_shutter(self):
"""
Return autoshutter to its original state before closing
Returns
-------
"""
if self.shutter_device == "": # no shutter
input(
"Please reset the shutter to its original state and press <Enter>"
)
logging.info(
"This is the end of the command-line instructions. You can return to the napari window."
)
else:
self.mmc.setAutoShutter(self._auto_shutter_state)
self.mmc.setShutterOpen(self._shutter_state)
def close_shutter_and_calc_blacklevel(self):
self._auto_shutter_state = self.mmc.getAutoShutter()
self._shutter_state = self.mmc.getShutterOpen()
if self.shutter_device == "": # no shutter
show_warning(
"No shutter found. Please follow the command-line instructions..."
)
shutter_warning_msg = """
recOrder could not find an automatic shutter configured through Micro-Manager.
>>> If you would like manually enter the black level, enter an integer or float and press <Enter>
>>> If you would like to estimate the black level, please close the shutter and press <Enter>
"""
in_string = input(shutter_warning_msg)
if in_string.isdigit(): # True if positive integer
self.I_Black = float(in_string)
return
else:
self.mmc.setAutoShutter(False)
self.mmc.setShutterOpen(False)
n_avg = 20
avgs = []
for i in range(n_avg):
mean = snap_and_average(self.snap_manager)
self.intensity_emitter.emit(mean)
avgs.append(mean)
blacklevel = np.mean(avgs)
self.I_Black = blacklevel
def calculate_extinction(
self, swing, black_level, intensity_extinction, intensity_elliptical
):
"""
Returns the extinction ratio, the ratio of the largest and smallest intensities that the imaging system can transmit above background.
See `/docs/calibration-guide.md` for a derivation of this expressions.
"""
return np.round(
(1 / np.sin(np.pi * swing) ** 2)
* (intensity_elliptical - intensity_extinction)
/ (intensity_extinction - black_level)
+ 1,
2,
)
def calc_inst_matrix(self):
if self.calib_scheme == "4-State":
chi = self.swing
inst_mat = np.array(
[
[1, 0, 0, -1],
[1, np.sin(2 * np.pi * chi), 0, -np.cos(2 * np.pi * chi)],
[
1,
-0.5 * np.sin(2 * np.pi * chi),
np.sqrt(3) * np.cos(np.pi * chi) * np.sin(np.pi * chi),
-np.cos(2 * np.pi * chi),
],
[
1,
-0.5 * np.sin(2 * np.pi * chi),
-np.sqrt(3) / 2 * np.sin(2 * np.pi * chi),
-np.cos(2 * np.pi * chi),
],
]
)
return inst_mat
if self.calib_scheme == "5-State":
chi = self.swing * 2 * np.pi
inst_mat = np.array(
[
[1, 0, 0, -1],
[1, np.sin(chi), 0, -np.cos(chi)],
[1, 0, np.sin(chi), -np.cos(chi)],
[1, -np.sin(chi), 0, -np.cos(chi)],
[1, 0, -np.sin(chi), -np.cos(chi)],
]
)
return inst_mat
def write_metadata(self, notes=None):
inst_mat = self.calc_inst_matrix()
inst_mat = np.around(inst_mat, decimals=5).tolist()
metadata = {
"Summary": {
"Timestamp": str(datetime.now()),
"recOrder-napari version": version("recOrder-napari"),
"waveorder version": version("waveorder"),
},
"Calibration": {
"Calibration scheme": self.calib_scheme,
"Swing (waves)": self.swing,
"Wavelength (nm)": self.wavelength,
"Retardance to voltage interpolation method": self.calib.interp_method,
"LC control mode": self.mode,
"Black level": np.round(self.I_Black, 2),
"Extinction ratio": self.extinction_ratio,
},
"Notes": notes,
}
if self.calib_scheme == "4-State":
metadata["Calibration"].update(
{
"Channel names": [f"State{i}" for i in range(4)],
"LC retardance": {
f"LC{i}_{j}": np.around(
getattr(self, f"lc{i.lower()}_{j}"), decimals=6
)
for j in ["ext", "0", "60", "120"]
for i in ["A", "B"]
},
"LC voltage": {
f"LC{i}_{j}": np.around(
self.calib.get_voltage(
getattr(self, f"lc{i.lower()}_{j}")
),
decimals=4,
)
for j in ["ext", "0", "60", "120"]
for i in ["A", "B"]
},
"Swing_0": np.around(self.swing0, decimals=3),
"Swing_60": np.around(self.swing60, decimals=3),
"Swing_120": np.around(self.swing120, decimals=3),
"Instrument matrix": inst_mat,
}
)
elif self.calib_scheme == "5-State":
metadata["Calibration"].update(
{
"Channel names": [f"State{i}" for i in range(5)],
"LC retardance": {
f"LC{i}_{j}": np.around(
getattr(self, f"lc{i.lower()}_{j}"), decimals=6
)
for j in ["ext", "0", "45", "90", "135"]
for i in ["A", "B"]
},
"LC voltage": {
f"LC{i}_{j}": np.around(
self.calib.get_voltage(
getattr(self, f"lc{i.lower()}_{j}")
),
decimals=4,
)
for j in ["ext", "0", "45", "90", "135"]
for i in ["A", "B"]
},
"Swing_0": np.around(self.swing0, decimals=3),
"Swing_45": np.around(self.swing45, decimals=3),
"Swing_90": np.around(self.swing90, decimals=3),
"Swing_135": np.around(self.swing135, decimals=3),
"Instrument matrix": inst_mat,
}
)
if not self.meta_file.endswith(".txt"):
self.meta_file += ".txt"
with open(self.meta_file, "w") as metafile:
json.dump(metadata, metafile, indent=1)
def _add_colorbar(self, mappable):
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = fig.colorbar(mappable, cax=cax)
plt.sca(last_axes)
return cbar
def _capture_state(self, state: str, n_avg: int):
"""Set the LCs to a certain state, then snap and average over a number of images.
Parameters
----------
state : str
Name of the LC config, e.g. `"State0"`
n_avg : int
Number of images to capture and average
Returns
-------
ndarray
Average of N images
"""
with suspend_live_sm(self.snap_manager) as sm:
set_lc_state(self.mmc, self.group, state)
imgs = []
for i in range(n_avg):
imgs.append(snap_and_get_image(sm))
return np.mean(imgs, axis=0)
def _plot_bg_images(self, imgs):
img_names = (
["Extinction", "0", "60", "120"]
if len(imgs) == 4
else ["Extinction", "0", "45", "90", 135]
)
fig, ax = (
plt.subplots(2, 2, figsize=(20, 20))
if len(imgs) == 4
else plt.subplots(3, 2, figsize=(20, 20))
)
img_idx = 0
for ax1 in range(len(ax[:, 0])):