-
Notifications
You must be signed in to change notification settings - Fork 40
/
protocol.py
8518 lines (7479 loc) · 304 KB
/
protocol.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
"""
Module containing the main `Protocol` object and associated functions
:copyright: 2021 by The Autoprotocol Development Team, see AUTHORS
for more details.
:license: BSD, see LICENSE for more details
"""
import json
import warnings
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from numbers import Number
from typing import Any, Dict, List, Optional, Tuple, Union
from .builders import LiquidHandleBuilders
from .compound import Compound
from .constants import AGAR_CLLD_THRESHOLD, SPREAD_PATH
from .container import COVER_TYPES, SEAL_TYPES, Container, Well, WellGroup
from .container_type import _CONTAINER_TYPES, ContainerType
from .informatics import AttachCompounds, Informatics
from .instruction import (
SPE,
Absorbance,
AcousticTransfer,
Agitate,
Autopick,
CountCells,
Cover,
Dispense,
Evaporate,
FlashFreeze,
FlowAnalyze,
FlowCytometry,
Fluorescence,
GelPurify,
GelSeparate,
IlluminaSeq,
Image,
ImagePlate,
Incubate,
Instruction,
LiquidHandle,
Luminescence,
MagneticTransfer,
MeasureConcentration,
MeasureMass,
MeasureVolume,
Oligosynthesize,
Provision,
SangerSeq,
Seal,
Sonicate,
Spectrophotometry,
Spin,
Thermocycle,
Uncover,
Unseal,
)
from .liquid_handle import Dispense as DispenseMethod
from .liquid_handle import LiquidClass, Mix, Transfer
from .types.protocol import (
ACCELERATION,
AMOUNT_CONCENTRATION,
DENSITY,
FLOW_RATE,
FREQUENCY,
TEMPERATURE,
TIME,
VOLUME,
WAVELENGTH,
AgitateMode,
AgitateModeParams,
AgitateModeParamsBarShape,
AutopickGroup,
DispenseColumn,
DispenseNozzlePosition,
DispenseShakeAfter,
DispenseShape,
EvaporateMode,
EvaporateModeParams,
FlowAnalyzeChannel,
FlowAnalyzeColors,
FlowAnalyzeNegControls,
FlowAnalyzePosControls,
FlowAnalyzeSample,
FlowCytometryCollectionCondition,
FlowCytometryLaser,
GelPurifyExtract,
IlluminaSeqLane,
ImageExposure,
ImageMode,
IncubateShakingParams,
OligosynthesizeOligo,
PlateReaderIncubateBefore,
PlateReaderPositionZCalculated,
PlateReaderPositionZManual,
SonicateMode,
SonicateModeParamsBath,
SonicateModeParamsHorn,
SpectrophotometryShakeBefore,
SpeElute,
SpeLoadSample,
SpeParams,
ThermocycleTemperature,
ThermocycleTemperatureGradient,
TimeConstraint,
TimeConstraintFromToDict,
WellParam,
)
from .types.ref import Ref, RefOpts, StorageLocation
from .unit import Unit, UnitError
from .util import (
_check_container_type_with_shape,
_validate_as_instance,
is_valid_well,
parse_unit,
)
@dataclass
class Protocol:
refs: Optional[Dict[str, Ref]] = None
instructions: List[Instruction] = field(default_factory=list)
propagate_properties: bool = False
time_constraints: List[TimeConstraint] = field(default_factory=list)
"""
A Protocol is a sequence of instructions to be executed, and a set of
containers on which those instructions act.
Parameters
----------
refs : list(Ref)
Pre-existing refs that the protocol should be populated with.
instructions : list(Instruction)
Pre-existing instructions that the protocol should be populated with.
propagate_properties : bool, optional
Whether liquid handling operations should propagate aliquot properties
from source to destination wells.
time_constraints : List(time_constraints)
Pre-existing time_constraints that the protocol should be populated with.
Examples
--------
Initially, a Protocol has an empty sequence of instructions and no
referenced containers. To add a reference to a container, use the ref()
method, which returns a Container.
.. code-block:: python
p = Protocol()
my_plate = p.ref("my_plate", id="ct1xae8jabbe6",
cont_type="96-pcr", storage="cold_4")
To add instructions to the protocol, use the helper methods in this class
.. code-block:: python
p.transfer(source=my_plate.well("A1"),
dest=my_plate.well("B4"),
volume="50:microliter")
p.thermocycle(my_plate, groups=[
{ "cycles": 1,
"steps": [
{ "temperature": "95:celsius",
"duration": "1:hour"
}]
}])
Autoprotocol Output:
.. code-block:: json
{
"refs": {
"my_plate": {
"id": "ct1xae8jabbe6",
"store": {
"where": "cold_4"
}
}
},
"instructions": [
{
"groups": [
{
"transfer": [
{
"volume": "50.0:microliter",
"to": "my_plate/15",
"from": "my_plate/0"
}
]
}
],
"op": "pipette"
},
{
"volume": "10:microliter",
"dataref": null,
"object": "my_plate",
"groups": [
{
"cycles": 1,
"steps": [
{
"duration": "1:hour",
"temperature": "95:celsius"
}
]
}
],
"op": "thermocycle"
}
]
}
"""
def __post_init__(self):
if not self.refs:
self.refs: Dict[str, Ref] = {}
def __repr__(self):
return f"Protocol({self.__dict__})"
def container_type(self, shortname: str):
"""
Convert a ContainerType shortname into a ContainerType object.
Parameters
----------
shortname : str
String representing one of the ContainerTypes in the
_CONTAINER_TYPES dictionary.
Returns
-------
ContainerType
Returns a Container type object corresponding to the shortname
passed to the function. If a ContainerType object is passed,
that same ContainerType is returned.
Raises
------
ValueError
If an unknown ContainerType shortname is passed as a parameter.
"""
if isinstance(shortname, ContainerType):
return shortname
elif shortname in _CONTAINER_TYPES:
return _CONTAINER_TYPES[shortname]
else:
raise ValueError(
f"Unknown container type {shortname}"
f"(known types={str(_CONTAINER_TYPES.keys())})"
)
# pragma pylint: disable=redefined-builtin
def ref(
self,
name: str,
id: Optional[str] = None,
cont_type: Optional[Union[str, ContainerType]] = None,
storage: Optional[str] = None,
discard: Optional[bool] = None,
cover: Optional[str] = None,
properties: Optional[Dict[str, str]] = None,
ctx_properties: Optional[Dict[str, str]] = None,
):
"""
Add a Ref object to the dictionary of Refs associated with this protocol
and return a Container with the id, container type and storage or
discard conditions specified.
Example Usage:
.. code-block:: python
p = Protocol()
# ref a new container (no id specified)
sample_ref_1 = p.ref("sample_plate_1",
cont_type="96-pcr",
discard=True)
# ref an existing container with a known id
sample_ref_2 = p.ref("sample_plate_2",
id="ct1cxae33lkj",
cont_type="96-pcr",
storage="ambient")
Autoprotocol Output:
.. code-block:: json
{
"refs": {
"sample_plate_1": {
"new": "96-pcr",
"discard": true
},
"sample_plate_2": {
"id": "ct1cxae33lkj",
"store": {
"where": "ambient"
}
}
},
"instructions": []
}
Parameters
----------
name : str
name of the container/ref being created.
id : str, optional
id of the container being created, from your organization's
inventory on http://secure.transcriptic.com. Strings representing
ids begin with "ct".
cont_type : str or ContainerType
container type of the Container object that will be generated.
storage : Enum({"ambient", "cold_20", "cold_4", "warm_37"}), optional
temperature the container being referenced should be stored at
after a run is completed. Either a storage condition must be
specified or discard must be set to True.
discard : bool, optional
if no storage condition is specified and discard is set to True,
the container being referenced will be discarded after a run.
cover: str, optional
name of the cover which will be on the container/ref
properties : dict, optional
mapping of key value properties associated to the Container
ctx_properties : dict, optional
mapping of key value properties associated to the Container
Returns
-------
Container
Container object generated from the id and container type provided
Raises
------
RuntimeError
If a container previously referenced in this protocol (existent
in refs section) has the same name as the one specified.
RuntimeError
If no container type is specified.
RuntimeError
If no valid storage or discard condition is specified.
"""
if name in self.refs.keys():
raise RuntimeError(
"Two containers within the same protocol cannot have the same " "name."
)
opts: RefOpts = RefOpts()
# Check container type
try:
cont_type = self.container_type(cont_type)
if id and cont_type:
opts.id = id
elif cont_type:
opts.new = cont_type.shortname
except ValueError as e:
raise RuntimeError(
f"{cont_type} is not a recognized container type."
) from e
if storage:
opts.store = StorageLocation(**{"where": storage})
elif discard and not storage:
opts.discard = discard
else:
raise RuntimeError(
"You must specify either a valid storage condition or set "
"discard=True for a Ref."
)
if cover:
opts.cover = cover
container = Container(
id=id,
container_type=cont_type,
name=name,
storage=storage if storage else None,
cover=cover if cover else None,
properties=properties,
ctx_properties=ctx_properties,
)
self.refs[name] = Ref(name, opts, container)
return container
# pragma pylint: enable=redefined-builtin
def add_time_constraint(
self,
from_dict: TimeConstraintFromToDict,
to_dict: TimeConstraintFromToDict,
less_than: Optional[TIME] = None,
more_than: Optional[TIME] = None,
mirror: bool = False,
ideal: Optional[TIME] = None,
optimization_cost: Optional[str] = None,
):
"""Constraint the time between two instructions
Add time constraints from `from_dict` to `to_dict`. Time constraints
guarantee that the time from the `from_dict` to the `to_dict` is less
than or greater than some specified duration. Care should be taken when
applying time constraints as constraints may make some protocols
impossible to schedule or run.
Though autoprotocol orders instructions in a list, instructions do
not need to be run in the order they are listed and instead depend on
the preceding dependencies. Time constraints should be added with such
limitations in mind.
Constraints are directional; use `mirror=True` if the time constraint
should be added in both directions. Note that mirroring is only applied
to the less_than constraint, as the more_than constraint implies both a
minimum delay betweeen two timing points and also an explicit ordering
between the two timing points.
Ideal time constraints are sometimes helpful for ensuring that a certain
set of operations happen within some specified time. This can be specified
by using the `ideal` parameter. There is an optional `optimization_cost`
parameter associated with `ideal` time constraints for specifying the
penalization system used for calculating deviations from the `ideal` time.
When left unspecified, the `optimization_cost` function defaults to linear.
Please refer to the ASC for more details on how this is implemented.
Example Usage:
.. code-block:: python
plate_1 = protocol.ref("plate_1", id=None, cont_type="96-flat",
discard=True)
plate_2 = protocol.ref("plate_2", id=None, cont_type="96-flat",
discard=True)
protocol.cover(plate_1)
time_point_1 = protocol.get_instruction_index()
protocol.cover(plate_2)
time_point_2 = protocol.get_instruction_index()
protocol.add_time_constraint(
{"mark": plate_1, "state": "start"},
{"mark": time_point_1, "state": "end"},
less_than = "1:minute")
protocol.add_time_constraint(
{"mark": time_point_2, "state": "start"},
{"mark": time_point_1, "state": "start"},
less_than = "1:minute", mirror=True)
# Ideal time constraint
protocol.add_time_constraint(
{"mark": time_point_1, "state": "start"},
{"mark": time_point_2, "state": "end"},
ideal = "30:second",
optimization_cost = "squared")
Autoprotocol Output:
.. code-block:: json
{
"refs": {
"plate_1": {
"new": "96-flat",
"discard": true
},
"plate_2": {
"new": "96-flat",
"discard": true
}
},
"time_constraints": [
{
"to": {
"instruction_end": 0
},
"less_than": "1.0:minute",
"from": {
"ref_start": "plate_1"
}
},
{
"to": {
"instruction_start": 0
},
"less_than": "1.0:minute",
"from": {
"instruction_start": 1
}
},
{
"to": {
"instruction_start": 1
},
"less_than": "1.0:minute",
"from": {
"instruction_start": 0
}
},
{
"from": {
"instruction_start": 0
},
"to": {
"instruction_end": 1
},
"ideal": {
"value": "5:minute",
"optimization_cost": "squared"
}
}
],
"instructions": [
{
"lid": "standard",
"object": "plate_1",
"op": "cover"
},
{
"lid": "standard",
"object": "plate_2",
"op": "cover"
}
]
}
Parameters
----------
from_dict: dict
Dictionary defining the initial time constraint condition.
Composed of keys: "mark" and "state"
mark: int or Container
instruction index of container
state: "start" or "end"
specifies either the start or end of the "mark" point
to_dict: dict
Dictionary defining the end time constraint condition.
Specified in the same format as from_dict
less_than: str or Unit, optional
max time between from_dict and to_dict
more_than: str or Unit, optional
min time between from_dict and to_dict
mirror: bool, optional
choice to mirror the from and to positions when time constraints
should be added in both directions
(only applies to the less_than constraint)
ideal: str or Unit, optional
ideal time between from_dict and to_dict
optimization_cost: Enum({"linear", "squared", "exponential"}), optional
cost function used for calculating the penalty for missing the
`ideal` timing
Raises
------
ValueError
If an instruction mark is less than 0
TypeError
If mark is not container or integer
TypeError
If state not in ['start', 'end']
TypeError
If any of `ideal`, `more_than`, `less_than` is not a
Unit of the 'time' dimension
KeyError
If `to_dict` or `from_dict` does not contain 'mark'
KeyError
If `to_dict` or `from_dict` does not contain 'state'
ValueError
If time is less than '0:second'
ValueError
If `optimization_cost` is specified but `ideal` is not
ValueError
If `more_than` is greater than `less_than`
ValueError
If `ideal` is smaller than `more_than` or greater than
`less_than`
RuntimeError
If `from_dict` and `to_dict` are equal
RuntimeError
If from_dict["marker"] and to_dict["marker"] are equal and
from_dict["state"] = "end"
"""
inst_string = "instruction_"
cont_string = "ref_"
state_strings = ["start", "end"]
keys = []
# Move the 4th param to mirror if the caller used the syntax
# add_time_constraint(a, b, 1:minute, True)
if type(more_than) == bool:
mirror = more_than
more_than = None
# Validate input types
def validate_timing(constraint):
if constraint is not None:
constraint = parse_unit(constraint, "minute")
if constraint < Unit(0, "second"):
raise ValueError(
f"The timing constraint {constraint} cannot be "
"less than '0:second'"
)
return constraint
more_than = validate_timing(more_than)
less_than = validate_timing(less_than)
ideal = validate_timing(ideal)
if ideal and optimization_cost is None:
optimization_cost = "linear"
if optimization_cost is not None:
if ideal is None:
raise ValueError(
"'optimization_cost' can only be specified if 'ideal'"
"is also specified"
)
ACCEPTED_COST_FUNCTIONS = ["linear", "squared", "exponential"]
if optimization_cost not in ACCEPTED_COST_FUNCTIONS:
raise ValueError(
f"'optimization_cost': {optimization_cost} has to be a "
f"member of {ACCEPTED_COST_FUNCTIONS}"
)
if more_than and less_than and more_than > less_than:
raise ValueError(
f"'more_than': {more_than} cannot be greater than 'less_than': "
f"{less_than}"
)
if ideal and more_than and ideal < more_than:
raise ValueError(
f"'ideal': {ideal} cannot be smaller than 'more_than': " f"{more_than}"
)
if ideal and less_than and ideal > less_than:
raise ValueError(
f"'ideal': {ideal} cannot be greater than 'less_than': " f"{less_than}"
)
for m in [from_dict, to_dict]:
if "mark" in m:
if isinstance(m["mark"], Container):
k = cont_string
elif isinstance(m["mark"], int):
k = inst_string
if m["mark"] < 0:
raise ValueError(
f"The instruction 'mark' in {m} must be greater "
f"than and equal to 0"
)
else:
raise TypeError(f"The 'mark' in {m} must be Container or Integer")
else:
raise KeyError(f"The {m} dict must contain `mark`")
if "state" in m:
if m["state"] in state_strings:
k += m["state"]
else:
raise TypeError(
f"The 'state' in {m} must be in " f"{', '.join(state_strings)}"
)
else:
raise KeyError(f"The {m} dict must contain 'state'")
keys.append(k)
if from_dict["mark"] == to_dict["mark"]:
if from_dict["state"] == to_dict["state"]:
raise RuntimeError(
f"The from_dict: {from_dict} and to_dict: {to_dict} are "
f"the same"
)
if from_dict["state"] == "end":
raise RuntimeError(
f"The from_dict: {from_dict} cannot come before the "
f"to_dict {to_dict}"
)
from_time_point = {keys[0]: from_dict["mark"]}
to_time_point = {keys[1]: to_dict["mark"]}
if less_than is not None:
self.time_constraints += [
{"from": from_time_point, "to": to_time_point, "less_than": less_than}
]
if mirror:
self.add_time_constraint(to_dict, from_dict, less_than, mirror=False)
if more_than is not None:
self.time_constraints += [
{"from": from_time_point, "to": to_time_point, "more_than": more_than}
]
if ideal is not None:
ideal_dict = dict(value=ideal)
if optimization_cost is not None:
ideal_dict["optimization_cost"] = optimization_cost
self.time_constraints += [
{"from": from_time_point, "to": to_time_point, "ideal": ideal_dict}
]
def get_instruction_index(self):
"""Get index of the last appended instruction
Example Usage:
.. code-block:: python
p = Protocol()
plate_1 = p.ref("plate_1", id=None, cont_type="96-flat",
discard=True)
p.cover(plate_1)
time_point_1 = p.get_instruction_index() # time_point_1 = 0
Raises
------
ValueError
If an instruction index is less than 0
Returns
-------
int
Index of the preceding instruction
"""
instruction_index = len(self.instructions) - 1
if instruction_index < 0:
raise ValueError("Instruction index less than 0")
return instruction_index
def _append_and_return(self, instructions: Union[Instruction, List[Instruction]]):
"""
Append instruction(s) to the Protocol list and returns the
Instruction(s).
The other functions on Protocol() should be used
in lieu of doing this directly.
Example Usage:
.. code-block:: python
p = Protocol()
p._append_and_return(
Incubate("sample_plate", "ambient", "1:hour")
)
Autoprotocol Output:
.. code-block:: none
"instructions": [
{
"duration": "1:hour",
"where": "ambient",
"object": "sample_plate",
"shaking": false,
"op": "incubate"
}
]
Parameters
----------
instructions : Instruction or list(Instruction)
Instruction object(s) to be appended.
Returns
-------
Instruction or list(Instruction)
Instruction object(s) to be appended and returned
"""
if isinstance(instructions, list):
self.instructions.extend(instructions)
else:
self.instructions.append(instructions)
return instructions
def batch_containers(
self,
containers: List[Container],
batch_in: bool = True,
batch_out: bool = False,
):
"""
Batch containers such that they all enter or exit together.
Example Usage:
.. code-block:: python
plate_1 = protocol.ref("p1", None, "96-pcr", storage="cold_4")
plate_2 = protocol.ref("p2", None, "96-pcr", storage="cold_4")
protocol.batch_containers([plate_1, plate_2])
Autoprotocol Output:
.. code-block:: json
{
"refs": {
"p1": {
"new": "96-pcr",
"store": {
"where": "cold_4"
}
},
"p2": {
"new": "96-pcr",
"store": {
"where": "cold_4"
}
}
},
"time_constraints": [
{
"from": {
"ref_start": "p1"
},
"less_than": "0:second",
"to": {
"ref_start": "p2"
}
},
{
"from": {
"ref_start": "p1"
},
"more_than": "0:second",
"to": {
"ref_start": "p2"
}
}
]
}
Parameters
----------
containers : list(Container)
Containers to batch
batch_in : bool, optional
Batch the entry of containers, default True
batch_out: bool, optional
Batch the exit of containers, default False
Raises
------
TypeError
If containers is not a list
TypeError
If containers is not a list of Container object
"""
time = Unit(0, "second")
if not isinstance(containers, list):
raise TypeError("batch_containers containers must be a list")
if not all(isinstance(cont, Container) for cont in containers):
raise TypeError("batch_containers containers must be a list of containers.")
if not batch_in and not batch_out or len(containers) < 2:
warnings.warn("batch_containers is used but has no effect")
reference_container = containers[0]
remainder_containers = containers[1:]
states = []
if batch_in:
states.append("start")
if batch_out:
states.append("end")
for container in remainder_containers:
for state in states:
from_dict = {"mark": reference_container, "state": state}
to_dict = {"mark": container, "state": state}
self.add_time_constraint(
from_dict=from_dict, to_dict=to_dict, less_than=time, more_than=time
)
def as_dict(self):
"""
Return the entire protocol as a dictionary.
Example Usage:
.. code-block:: python
from autoprotocol.protocol import Protocol
import json
p = Protocol()
sample_ref_2 = p.ref("sample_plate_2",
id="ct1cxae33lkj",
cont_type="96-pcr",
storage="ambient")
p.seal(sample_ref_2)
p.incubate(sample_ref_2, "warm_37", "20:minute")
print json.dumps(p.as_dict(), indent=2)
Autoprotocol Output:
.. code-block:: json
{
"refs": {
"sample_plate_2": {
"id": "ct1cxae33lkj",
"store": {
"where": "ambient"
}
}
},
"instructions": [
{
"object": "sample_plate_2",
"op": "seal"
},
{
"duration": "20:minute",
"where": "warm_37",
"object": "sample_plate_2",
"shaking": false,
"op": "incubate"
}
]
}
Returns
-------
dict
dict with keys "refs" and "instructions" and optionally
"time_constraints" and "outs", each of which contain the
"refified" contents of their corresponding Protocol attribute.
Raises
------
RuntimeError
If either refs or instructions attribute is empty
"""
outs = defaultdict(lambda: defaultdict(dict))
# pragma pylint: disable=protected-access
for n, ref in self.refs.items():
# assign any storage or discard condition changes to ref
if ref.opts.store:
ref.opts.store.where = ref.container.storage
if not ref.container.storage and not ref.opts.discard:
ref.opts.discard = True
ref.opts.store = None
elif ref.container.storage and ref.opts.discard:
ref.opts.store = StorageLocation(**{"where": ref.container.storage})
ref.opts.discard = None
if ref.container.properties:
outs[n]["properties"] = ref.container.properties
if ref.container.ctx_properties:
outs[n]["contextual_custom_properties"] = ref.container.ctx_properties
for well in ref.container._wells:
if well.name or len(well.properties) > 0:
if well.name:
outs[n][str(well.index)]["name"] = well.name
if len(well.properties) > 0:
outs[n][str(well.index)]["properties"] = well.properties
if well.ctx_properties:
outs[n][str(well.index)][
"contextual_custom_properties"
] = well.ctx_properties
# pragma pylint: enable=protected-access
if outs:
setattr(self, "outs", json.loads(json.dumps(outs)))