/
builders.py
2767 lines (2361 loc) · 88.4 KB
/
builders.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
"""Builders
Module containing builders, which help build inputs for Instruction parameters
:copyright: 2020 by The Autoprotocol Development Team, see AUTHORS
for more details.
:license: BSD, see LICENSE for more details
Summary
-------
These builder methods are used to generate and validate complex data
structures used in Autoprotocol specification. Each of them is capable of
using their own output as input. Therefore these builders are also used as
inline checks in Protocol methods.
Notes
-----
Generally these builders should not be called from this file directly.
They're more easily accessible by referencing a specific Instruction's
builders attribute (e.g. `Spectrophotometry.Builders.mode_params`).
See Also
--------
Instruction
Instructions corresponding to each of the builders
"""
from collections import defaultdict
from numbers import Number
from collections.abc import Iterable # pylint: disable=no-name-in-module
from functools import reduce
from .constants import SBS_FORMAT_SHAPES
from .container import WellGroup, Well, Container
from .unit import Unit
from .util import parse_unit, is_valid_well
class InstructionBuilders(object): # pylint: disable=too-few-public-methods
"""General builders that apply to multiple instructions
"""
def __init__(self):
self.sbs_shapes = ["SBS96", "SBS384"]
@staticmethod
def _merge_param_dicts(left=None, right=None):
"""Finds the union of two dicts of params and checks for duplicates
Parameters
----------
left : dict or None
Parameters to be merged
right : dict or None
Parameters to be merged
Returns
-------
dict
A merged set of parameters from the left and right dicts
Raises
------
ValueError
if multiple values are specified for the same parameter
"""
left = left or dict()
right = right or dict()
union = defaultdict(list)
for params in (left, right):
for key, value in params.items():
if value is not None:
union[key].append(value)
unique = dict()
for key, value in union.items():
if len(value) == 1:
unique[key] = value[0]
else:
raise ValueError(
f"Parameter: {key} had multiple values: {value} specified."
)
return unique
# pylint: disable=redefined-builtin
def shape(self, rows=1, columns=1, format=None):
"""
Helper function for building a shape dictionary
Parameters
----------
rows : int, optional
Number of rows to be concurrently transferred
columns : int, optional
Number of columns to be concurrently transferred
format : str, optional
Plate format in String form. e.g. "SBS96" or "SBS384"
Returns
-------
dict
shape parameters
Raises
------
TypeError
If rows/columns aren't ints
ValueError
If an invalid row/column count is given
ValueError
If an invalid shape is given
ValueError
If rows/columns are greater than what is allowed for the format
"""
if not isinstance(rows, int) or not isinstance(columns, int):
raise TypeError("Rows/columns have to be of type integer")
if format is None:
for shape in self.sbs_shapes:
valid_rows = rows <= SBS_FORMAT_SHAPES[shape]["rows"]
valid_columns = columns <= SBS_FORMAT_SHAPES[shape]["columns"]
if valid_rows and valid_columns:
format = shape
break
if not format:
raise ValueError("Invalid number of rows and/or columns specified")
if format not in self.sbs_shapes:
raise ValueError(
f"Invalid shape format; format has to be in {self.sbs_shapes}"
)
valid_rows = rows <= SBS_FORMAT_SHAPES[format]["rows"]
valid_columns = columns <= SBS_FORMAT_SHAPES[format]["columns"]
if not (valid_rows and valid_columns):
raise ValueError(
f"rows: {rows} and columns: {columns} are not possible with "
f"format: {format}."
)
return {"rows": rows, "columns": columns, "format": format}
class ThermocycleBuilders(InstructionBuilders):
"""
These builders are meant for helping to construct the `groups`
argument in the `Protocol.thermocycle` method
"""
def __init__(self):
super(ThermocycleBuilders, self).__init__()
self.valid_dyes = {
"FAM",
"SYBR", # channel 1
"VIC",
"HEX",
"TET",
"CALGOLD540", # channel 2
"ROX",
"TXR",
"CALRED610", # channel 3
"CY5",
"QUASAR670", # channel 4
"QUASAR705", # channel 5
"FRET", # channel 6
}
def dyes(self, **kwargs):
"""Helper function for creating a dye parameter
Parameters
----------
**kwargs : dict(str: int or list(int))
A mapping from a dye (str) to the index of a well
Returns
-------
dict
A thermocycling dye to well mapping
Raises
------
ValueError
If any of the specified dyes are not valid
ValueError
If wells is not an int, str, list(int), or list(str)
"""
dyes = {}
for dye, wells in kwargs.items():
if dye not in self.valid_dyes:
raise ValueError(
f"dye {dye} is not in the set of valid dyes " f"{self.valid_dyes}"
)
if not isinstance(wells, list):
wells = [wells]
if not all(isinstance(_, (int, str)) for _ in wells):
raise ValueError(
f"dye {dye} had wells {wells} that were not an int, str " "or list"
)
dyes[dye] = wells
return dyes
def dyes_from_well_map(self, well_map):
"""Helper function for creating a dye parameter from a well_map
Take a map of wells to the dyes it contains and returns a map of dyes to
the list of wells that contain it.
Parameters
----------
well_map : dict(well, str)
A thermocycling well to dye mapping
Returns
-------
dict
A thermocycling dye to well mapping
See Also
--------
Thermocycle.Builders.dyes : standard constructor for the dyes parameter
"""
dyes = reduce(lambda x, y: x.union(y), [set(well_map[k]) for k in well_map])
dye_map = {dye: [] for dye in dyes}
for well in well_map:
dyes = well_map[well]
for dye in dyes:
dye_map[dye] += [well]
return self.dyes(**dyes)
@staticmethod
def melting(start=None, end=None, increment=None, rate=None):
"""Helper function for creating melting parameters
Generates melt curve parameters for Thermocycle Instructions.
Parameters
----------
start : str or Unit
The starting temperature for the melt curve
end : str or Unit
The ending temperature for the melt curve
increment : str or Unit
The temperature increment of the melt curve
rate : str or Unit
The duration the individual increments
Returns
-------
dict
A thermocycling melt curve specification
Raises
------
ValueError
If some, but not all melt curve parameters are specified
"""
melting_params = [start, end, increment, rate]
if any(melting_params) and not all(melting_params):
raise ValueError(
"To specify a melt curve, you must specify values for "
"start, end, increment, and rate"
)
if start:
start = parse_unit(start, "celsius")
if end:
end = parse_unit(end, "celsius")
if increment:
increment = parse_unit(increment, "celsius")
if rate:
rate = parse_unit(rate, "second")
return {"start": start, "end": end, "increment": increment, "rate": rate}
def group(self, steps, cycles=1):
"""
Helper function for creating a thermocycle group, which is a series of
steps repeated for the number of cycles
Parameters
----------
steps: list(ThermocycleBuilders.step)
Steps to be carried out. At least one step has to be specified.
See `ThermocycleBuilders.step` for more information
cycles: int, optional
Number of cycles to repeat the specified steps. Defaults to 1
Returns
-------
dict
A thermocycling group
Raises
------
TypeError
Invalid input types, i.e. `cycles` is not of type int and `steps`
is not of type list
ValueError
`cycles` is not positive
ValueError
`steps` does not contain any elements
"""
if not isinstance(cycles, int):
raise TypeError(f"`cycles` {cycles} has to be of type int")
if not isinstance(steps, list):
raise TypeError(f"`steps` {steps} has to be of type list")
if cycles <= 0:
raise ValueError(f"`cycles` {cycles} has to be positive")
if not steps:
raise ValueError("`steps` has to contain at least one element")
# Reformatting to use temperature for gradient input
def reformat_gradient(**kwargs):
if "gradient" in kwargs:
kwargs["temperature"] = kwargs.pop("gradient")
return kwargs
group_dict = dict(
cycles=cycles, steps=[self.step(**reformat_gradient(**_)) for _ in steps]
)
return group_dict
@staticmethod
def step(temperature, duration, read=None):
"""
Helper function for creating a thermocycle step.
Parameters
----------
temperature: Unit or dict(str, Unit)
Block temperature which the contents should be thermocycled at.
If a gradient thermocycle is desired, specifying a dict with
"top" and "bottom" keys will control the desired temperature
at the top and bottom rows of the block, creating a gradient
along the column.
..code-block:: python
temperature = {"top": "50:celsius", "bottom": "45:celsius"}
duration: str or Unit
Duration where the specified temperature parameters will be applied
read: Boolean, optional
Determines if a read at wavelengths specified by the dyes in the
parent `thermocycle` instruction will be enabled for this particular
step. Useful for qPCR applications.
Returns
-------
dict
A thermocycling step
Raises
------
TypeError
Invalid input types, e.g. `read` is not of type bool
ValueError
Invalid format specified for `temperature` dict
ValueError
Duration is not greater than 0 second
"""
step_dict = dict()
if isinstance(temperature, dict):
if set(temperature.keys()) != {"top", "bottom"}:
raise ValueError(
f"{temperature} was specified, but only 'top' and 'bottom' "
f"keys are allowed for a temperature dictionary"
)
step_dict["gradient"] = dict(
top=parse_unit(temperature["top"], "celsius"),
bottom=parse_unit(temperature["bottom"], "celsius"),
)
else:
step_dict["temperature"] = parse_unit(temperature, "celsius")
duration = parse_unit(duration, "second")
if duration <= Unit("0:second"):
raise ValueError("Step `duration` has to be at least 1 second")
step_dict["duration"] = duration
if read is not None:
if not isinstance(read, bool):
raise TypeError(f"`read` {read} has to be of type bool")
step_dict["read"] = read
return step_dict
class SPEBuilders(InstructionBuilders):
"""
These builders are meant for helping to construct arguments for the
`SPE` instruction.
"""
def spe_params(self, params, is_elute=False):
if not isinstance(params, list):
raise ValueError("SPE mobile phase parameters {} must be a list.")
parsed_params = []
for param in params:
parsed_params.append(self.mobile_phase_params(is_elute=is_elute, **param))
return parsed_params
def mobile_phase_params(
self,
volume,
loading_flowrate,
settle_time,
processing_time,
flow_pressure,
resource_id=None,
is_sample=False,
destination_well=None,
is_elute=False,
):
"""
Create a dictionary with mobile phase parameters which can be
used as input for instructions.
Parameters
----------
volume: str or Unit
the duration to shake the plate for
loading_flowrate: str or Unit, optional
amplitude of shaking between 1 and 6:millimeter
settle_time: bool, optional
True for orbital and False for linear shaking
processing_time: str or Unit
Duration for which pressure is applied to the cartridge
after `settle_time` has elapsed.
flow_pressure: str or Unit
Pressure applied to the column.
resource_id: str
Resource ID of desired solvent.
is_sample: bool
If a sample is processed.
destination_well: Well
Destination well for eluate. Required parameter for
each `elute` mobile phase parameter
is_elute: bool
If an elute is processed.
Returns
-------
dict
spe mobile_phase_params
Raises
------
ValueError
if shake `flow_pressure` is not positive
ValueError
if mobile phase solvent and resource_id not included
TypeError
if `resource_id` is not a string
ValueError
if `settle_time` is not positive
ValueError
if `processing_time` is not positive
"""
volume = parse_unit(volume, "milliliter")
settle_time = parse_unit(settle_time, "second")
if settle_time <= Unit(0, "second"):
raise ValueError(f"settle_time: {settle_time} is not positive")
processing_time = parse_unit(processing_time, "second")
if processing_time <= Unit(0, "second"):
raise ValueError(f"processing_time: {processing_time} is not " "positive")
flow_pressure = parse_unit(flow_pressure, "bar")
if flow_pressure <= Unit(0, "bar"):
raise ValueError(f"flow_pressure: {flow_pressure} must be " f"positive.")
loading_flowrate = parse_unit(loading_flowrate, "ul/s")
if not is_sample:
if not resource_id:
raise ValueError(
"A 'resource_id' must be included " "for mobile_phase_params."
)
if not isinstance(resource_id, str):
raise TypeError("'resource_id' {} must be a string")
if is_elute:
if not destination_well:
raise ValueError(
"A 'destination_well' must be included " "for elute parameter."
)
if not isinstance(destination_well, Well):
raise TypeError("'destination_well' {} must be of type Well")
mode_params = {
"volume": volume,
"settle_time": settle_time,
"processing_time": processing_time,
"flow_pressure": flow_pressure,
"loading_flowrate": loading_flowrate,
"resource_id": resource_id,
"destination_well": destination_well,
}
mode_params = {k: v for k, v in mode_params.items() if v is not None}
return mode_params
class DispenseBuilders(InstructionBuilders):
"""
These builders are meant for helping to construct arguments in the
`Protocol.dispense` method.
"""
def __init__(self):
super(DispenseBuilders, self).__init__()
self.SHAKE_PATHS = ["landscape_linear"]
@staticmethod
# pragma pylint: disable=unused-argument
def nozzle_position(position_x=None, position_y=None, position_z=None):
"""
Generates a validated nozzle_position parameter.
Parameters
----------
position_x : Unit, optional
position_y : Unit, optional
position_z : Unit, optional
Returns
-------
dict
Dictionary of nozzle position parameters
"""
position_dict = {
name: parse_unit(position, "mm")
for name, position in locals().items()
if position is not None
}
return position_dict
# pragma pylint: enable=unused-argument
@staticmethod
def column(column, volume):
"""
Generates a validated column parameter.
Parameters
----------
column : int
volume : str, Unit
Returns
-------
dict
Column parameter of type {"column": int, "volume": Unit}
"""
return {"column": int(column), "volume": parse_unit(volume, "uL")}
def columns(self, columns):
"""
Generates a validated columns parameter.
Parameters
----------
columns : list({"column": int, "volume": str, Unit})
Returns
-------
list
List of columns of type ({"column": int, "volume": str, Unit})
Raises
------
ValueError
No `column` specified for columns
ValueError
Non-unique column indices
"""
if not len(columns) > 0:
raise ValueError("There must be at least one column specified for columns.")
column_list = [self.column(**_) for _ in columns]
if len(column_list) != len(set([_["column"] for _ in column_list])):
raise ValueError(
f"Column indices must be unique, but there were duplicates "
f"in {column_list}."
)
return column_list
def shake_after(self, duration, frequency=None, path=None, amplitude=None):
"""
Generates a validated shake_after parameter.
Parameters
----------
duration : Unit, str
frequency : Unit, str, optional
path : str, optional
amplitude : Unit, str, optional
Returns
-------
dict
Shake after dictionary of type {"duration": Unit,
"frequency": Unit, "path": str, "amplitude": Unit}
Raises
------
ValueError
Invalid shake path specified
"""
if path and path not in self.SHAKE_PATHS:
raise ValueError(
f"Invalid shake path {path} specified, must be one of "
f"{self.SHAKE_PATHS}"
)
shake_after = {
"duration": parse_unit(duration, "seconds"),
"frequency": parse_unit(frequency, "hertz") if frequency else None,
"path": path,
"amplitude": parse_unit(amplitude, "mm") if amplitude else None,
}
return {k: v for k, v in shake_after.items() if v is not None}
class SpectrophotometryBuilders(InstructionBuilders):
"""
These builders are meant for helping to construct arguments for the
`Spectrophotometry` instruction.
"""
def __init__(self):
super(SpectrophotometryBuilders, self).__init__()
self.MODES = {
"absorbance": self.absorbance_mode_params,
"fluorescence": self.fluorescence_mode_params,
"luminescence": self.luminescence_mode_params,
"shake": self.shake_mode_params,
}
self.READ_POSITIONS = ["top", "bottom"]
self.SHAKE_PATHS = [
"portrait_linear",
"landscape_linear",
"cw_orbital",
"ccw_orbital",
"portrait_down_double_orbital",
"landscape_down_double_orbital",
"portrait_up_double_orbital",
"landscape_up_double_orbital",
"cw_diamond",
"ccw_diamond",
]
self.Z_REFERENCES = ["plate_bottom", "plate_top", "well_bottom", "well_top"]
self.Z_HEURISTICS = [
"max_mean_read_without_saturation",
"closest_distance_without_saturation",
]
@staticmethod
def wavelength_selection(shortpass=None, longpass=None, ideal=None):
"""
Generates a representation of a wavelength selection by either
filters (using shortpass/longpass) or monochromators (using ideal)
Parameters
----------
shortpass : Unit, str, optional
longpass : Unit, str, optional
ideal : Unit, str, optional
Returns
-------
dict
Wavelength selection parameters.
"""
selection = {
"shortpass": parse_unit(shortpass, "nanometer") if shortpass else None,
"longpass": parse_unit(longpass, "nanometer") if longpass else None,
"ideal": parse_unit(ideal, "nanometer") if ideal else None,
}
selection = {k: v for k, v in selection.items() if v is not None}
return selection
def groups(self, groups):
"""
Parameters
----------
groups : list(dict)
A list of spectrophotometry groups.
Returns
-------
list(dict)
A list of spectrophotometry groups.
"""
return [self.group(_["mode"], _["mode_params"]) for _ in groups]
def group(self, mode, mode_params):
"""
Parameters
----------
mode : str
A string representation of a valid spectrophotometry mode.
mode_params : dict
A dict of mode_params corresponding to the mode.
Returns
-------
dict
A spectrophotometry group.
Raises
------
ValueError
Invalid mode specified
"""
if mode not in self.MODES.keys():
raise ValueError(
f"Invalid mode {mode}, must be in valid modes " f"{self.MODES.keys()}."
)
return {"mode": mode, "mode_params": self.MODES[mode](**mode_params)}
def absorbance_mode_params(
self,
wells,
wavelength,
num_flashes=None,
settle_time=None,
read_position=None,
position_z=None,
):
"""
Parameters
----------
wells : iterable(Well) or WellGroup
Wells to be read.
wavelength : Unit or str
The wavelengths at which to make absorbance measurements.
num_flashes : int, optional
The number of discrete reads to be taken and then averaged.
settle_time : Unit or str, optional
The time to wait between moving to a well and reading it.
read_position: Enum("top", "bottom"), optional
The position of the probe relative to the plate for the read
position_z: dict, optional
This should be specified with either `position_z_manual` or
`position_z_calculated`
Returns
-------
dict
Formatted mode_params for an absorbance mode.
Raises
------
TypeError
Invalid type specified for input parameters, e.g. `num_flashes`
not of type int
ValueError
Invalid wells specified
"""
if not is_valid_well(wells):
raise ValueError(
f"Invalid wells {wells}, must be an iterable of wells or a "
f"WellGroup."
)
if isinstance(wells, Well):
wells = WellGroup([wells])
if not isinstance(wavelength, list):
wavelength = [wavelength]
wavelength = [parse_unit(_, "nanometer") for _ in wavelength]
if num_flashes is not None and not isinstance(num_flashes, int):
raise TypeError(f"Invalid num_flashes {num_flashes}, must be an int")
if settle_time is not None:
settle_time = parse_unit(settle_time, "second")
if read_position is not None and read_position not in self.READ_POSITIONS:
raise ValueError(
f"Invalid read_position {read_position}, must be in "
f"{self.READ_POSITIONS}."
)
if position_z is not None:
position_z = self._position_z(position_z)
mode_params = {
"wells": wells,
"wavelength": wavelength,
"num_flashes": num_flashes,
"settle_time": settle_time,
"read_position": read_position,
"position_z": position_z,
}
mode_params = {k: v for k, v in mode_params.items() if v is not None}
return mode_params
def fluorescence_mode_params(
self,
wells,
excitation,
emission,
num_flashes=None,
settle_time=None,
lag_time=None,
integration_time=None,
gain=None,
read_position=None,
position_z=None,
):
"""
Parameters
----------
wells : iterable(Well) or WellGroup
Wells to be read.
excitation : list(dict)
A list of SpectrophotometryBuilders.wavelength_selection to
determine the wavelegnth(s) of excitation light used.
emission : list(dict)
A list of SpectrophotometryBuilders.wavelength_selection to
determine the wavelegnth(s) of emission light used.
num_flashes : int, optional
The number of discrete reads to be taken and then combined.
settle_time : Unit or str, optional
The time to wait between moving to a well and reading it.
lag_time : Unit or str, optional
The time to wait between excitation and reading.
integration_time : Unit or str, optional
Time over which the data should be collected and integrated.
gain : int, optional
The amount of gain to be applied to the readings.
read_position : str, optional
The position from which the wells should be read.
position_z: dict, optional
This should be specified with either `position_z_manual` or
`position_z_calculated`
Returns
-------
dict
Formatted mode_params for a fluorescence mode.
Raises
------
TypeError
Invalid input types, e.g. settle_time is not of type Unit(second)
ValueError
Invalid wells specified
ValueError
Gain is not between 0 and 1
"""
if not is_valid_well(wells):
raise ValueError(
f"Invalid wells {wells}, must be an iterable of wells or a "
f"WellGroup."
)
if isinstance(wells, Well):
wells = WellGroup([wells])
if not isinstance(excitation, list):
raise ValueError("Excitation {} must be a list")
if not isinstance(emission, list):
raise ValueError("Emission {} must be a list")
excitation = [self.wavelength_selection(**_) for _ in excitation]
emission = [self.wavelength_selection(**_) for _ in emission]
if num_flashes is not None and not isinstance(num_flashes, int):
raise ValueError(f"Invalid num_flashes {num_flashes}, must be an int")
if settle_time is not None:
settle_time = parse_unit(settle_time, "second")
if lag_time is not None:
lag_time = parse_unit(lag_time, "second")
if integration_time is not None:
integration_time = parse_unit(integration_time, "second")
if gain is not None:
if not isinstance(gain, (int, float)):
raise TypeError(f"Invalid gain {gain}, must be an int")
gain = float(gain)
if not 0 <= gain <= 1:
raise ValueError(
f"Invalid gain {gain}, must be between 0 and 1 (inclusive)."
)
if read_position is not None and read_position not in self.READ_POSITIONS:
raise ValueError(
f"Invalid read_position {read_position}, must be in "
f"{self.READ_POSITIONS}."
)
if position_z is not None:
position_z = self._position_z(position_z)
mode_params = {
"wells": wells,
"excitation": excitation,
"emission": emission,
"num_flashes": num_flashes,
"settle_time": settle_time,
"lag_time": lag_time,
"integration_time": integration_time,
"gain": gain,
"read_position": read_position,
"position_z": position_z,
}
mode_params = {k: v for k, v in mode_params.items() if v is not None}
return mode_params
def luminescence_mode_params(
self,
wells,
num_flashes=None,
settle_time=None,
integration_time=None,
gain=None,
read_position=None,
position_z=None,
):
"""
Parameters
----------
wells : iterable(Well) or WellGroup
Wells to be read.
num_flashes : int, optional
The number of discrete reads to be taken and then combined.
settle_time : Unit or str, optional
The time to wait between moving to a well and reading it.
integration_time : Unit or str, optional
Time over which the data should be collected and integrated.
gain : int, optional
The amount of gain to be applied to the readings.
read_position: Enum("top", "bottom"), optional
The position of the probe relative to the plate for the read
position_z: dict, optional
This should be specified with either `position_z_manual` or
`position_z_calculated`
Returns
-------
dict
Formatted mode_params for a luminescence mode.
Raises
------
TypeError
Invalid input types, e.g. settle_time is not of type Unit(second)
ValueError
Gain is not between 0 and 1
"""
if not is_valid_well(wells):
raise ValueError(
f"Invalid wells {wells}, must be an iterable of wells or a "
f"WellGroup."
)
if isinstance(wells, Well):