-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperations.py
More file actions
2295 lines (2096 loc) · 87.6 KB
/
operations.py
File metadata and controls
2295 lines (2096 loc) · 87.6 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
"""Minimal LabCraft operations for the Transform-01 task."""
from __future__ import annotations
import math
import re
from pathlib import Path
from typing import Dict, List
from .state import (
AssemblyReaction,
DigestReaction,
DnaFragment,
GelRun,
GibsonReaction,
GrowthCulture,
GrowthMeasurement,
LabState,
LigationReaction,
MiniprepSample,
NtaPurification,
PcrReaction,
PlatedSample,
PreparedPlate,
ProteinExpression,
ScreeningColony,
ScreeningPlate,
TransformationCulture,
)
from .stochastic import (
load_cloning_parameters,
load_expression_parameters,
load_gibson_parameters,
load_golden_gate_parameters,
load_growth_parameters,
load_miniprep_parameters,
load_pcr_parameters,
load_purification_parameters,
load_screening_parameters,
sample_poisson,
)
_GROWTH_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "growth.json"
_GROWTH_BUNDLE = None
_PCR_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "pcr.json"
_PCR_BUNDLE = None
_SCREENING_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "screening.json"
_SCREENING_BUNDLE = None
_CLONING_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "cloning.json"
_CLONING_BUNDLE = None
_GOLDEN_GATE_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "golden_gate.json"
_GOLDEN_GATE_BUNDLE = None
_GIBSON_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "gibson.json"
_GIBSON_BUNDLE = None
_MINIPREP_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "miniprep.json"
_MINIPREP_BUNDLE = None
_EXPRESSION_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "expression.json"
_EXPRESSION_BUNDLE = None
_PURIFICATION_PARAMETERS_PATH = Path(__file__).resolve().parents[2] / "data" / "parameters" / "purification.json"
_PURIFICATION_BUNDLE = None
def _require_finite_float(value: object, field_name: str) -> float:
try:
parsed = float(value)
except (TypeError, ValueError) as exc:
raise ValueError("{} must be numeric.".format(field_name)) from exc
if not math.isfinite(parsed):
raise ValueError("{} must be finite.".format(field_name))
return parsed
def _require_positive_float(value: object, field_name: str) -> float:
parsed = _require_finite_float(value, field_name)
if parsed <= 0.0:
raise ValueError("{} must be positive.".format(field_name))
return parsed
def _require_integer(value: object, field_name: str) -> int:
try:
parsed_float = float(value)
except (TypeError, ValueError) as exc:
raise ValueError("{} must be an integer.".format(field_name)) from exc
if not math.isfinite(parsed_float) or not parsed_float.is_integer():
raise ValueError("{} must be an integer.".format(field_name))
return int(parsed_float)
def _require_positive_integer(value: object, field_name: str) -> int:
parsed = _require_integer(value, field_name)
if parsed <= 0:
raise ValueError("{} must be positive.".format(field_name))
return parsed
def _require_nonnegative_integer(value: object, field_name: str) -> int:
parsed = _require_integer(value, field_name)
if parsed < 0:
raise ValueError("{} must be non-negative.".format(field_name))
return parsed
def _growth_bundle():
global _GROWTH_BUNDLE
if _GROWTH_BUNDLE is None:
_GROWTH_BUNDLE = load_growth_parameters(_GROWTH_PARAMETERS_PATH)
return _GROWTH_BUNDLE
def _pcr_bundle():
global _PCR_BUNDLE
if _PCR_BUNDLE is None:
_PCR_BUNDLE = load_pcr_parameters(_PCR_PARAMETERS_PATH)
return _PCR_BUNDLE
def _screening_bundle():
global _SCREENING_BUNDLE
if _SCREENING_BUNDLE is None:
_SCREENING_BUNDLE = load_screening_parameters(_SCREENING_PARAMETERS_PATH)
return _SCREENING_BUNDLE
def _cloning_bundle():
global _CLONING_BUNDLE
if _CLONING_BUNDLE is None:
_CLONING_BUNDLE = load_cloning_parameters(_CLONING_PARAMETERS_PATH)
return _CLONING_BUNDLE
def _golden_gate_bundle():
global _GOLDEN_GATE_BUNDLE
if _GOLDEN_GATE_BUNDLE is None:
_GOLDEN_GATE_BUNDLE = load_golden_gate_parameters(_GOLDEN_GATE_PARAMETERS_PATH)
return _GOLDEN_GATE_BUNDLE
def _gibson_bundle():
global _GIBSON_BUNDLE
if _GIBSON_BUNDLE is None:
_GIBSON_BUNDLE = load_gibson_parameters(_GIBSON_PARAMETERS_PATH)
return _GIBSON_BUNDLE
def _miniprep_bundle():
global _MINIPREP_BUNDLE
if _MINIPREP_BUNDLE is None:
_MINIPREP_BUNDLE = load_miniprep_parameters(_MINIPREP_PARAMETERS_PATH)
return _MINIPREP_BUNDLE
def _expression_bundle():
global _EXPRESSION_BUNDLE
if _EXPRESSION_BUNDLE is None:
_EXPRESSION_BUNDLE = load_expression_parameters(_EXPRESSION_PARAMETERS_PATH)
return _EXPRESSION_BUNDLE
def _purification_bundle():
global _PURIFICATION_BUNDLE
if _PURIFICATION_BUNDLE is None:
_PURIFICATION_BUNDLE = load_purification_parameters(_PURIFICATION_PARAMETERS_PATH)
return _PURIFICATION_BUNDLE
def _normalize_choice(value: str) -> str:
return re.sub(r"\s+", " ", value).strip().lower()
def _resolve_pcr_reaction_id(state: LabState, reaction_id: str) -> str:
"""Resolve exact or shorthand PCR reaction identifiers to a canonical id."""
requested = str(reaction_id).strip()
if requested in state.pcr_reactions:
return requested
candidates: List[str] = []
normalized_requested = _normalize_choice(requested)
if normalized_requested:
candidates.extend(
existing_id
for existing_id in state.pcr_reactions
if _normalize_choice(existing_id) == normalized_requested
)
suffix_match = re.search(r"(\d+)$", requested)
if suffix_match:
suffix = int(suffix_match.group(1))
canonical = "pcr_{:03d}".format(suffix)
if canonical in state.pcr_reactions and canonical not in candidates:
candidates.append(canonical)
if len(candidates) == 1:
return candidates[0]
available = sorted(state.pcr_reactions)
if not candidates:
raise ValueError(
"Unknown reaction_id '{:s}'. Available reaction IDs: {:s}".format(
requested,
", ".join(available) if available else "none",
)
)
raise ValueError(
"Ambiguous reaction_id '{:s}'. Matching reaction IDs: {:s}".format(
requested,
", ".join(sorted(candidates)),
)
)
def _ensure_screening_plate(state: LabState) -> ScreeningPlate:
existing = next(iter(state.screening_plates.values()), None)
if existing is not None:
return existing
bundle = _screening_bundle()
plate_id = state.next_screening_plate_id()
recombinant_band_bp = bundle.integer("screening_recombinant_colony_pcr_band_bp")
empty_vector_band_bp = bundle.integer("screening_empty_vector_colony_pcr_band_bp")
plate = ScreeningPlate(
plate_id=plate_id,
historical_positive_rate_among_white=bundle.value("historical_positive_rate_among_white_colonies"),
target_confidence=bundle.value("screening_target_confidence"),
recombinant_band_bp=recombinant_band_bp,
empty_vector_band_bp=empty_vector_band_bp,
)
recombinant_white_ids = {"white_002", "white_005", "white_006", "white_011"}
for idx in range(1, 13):
colony_id = "white_{:03d}".format(idx)
is_recombinant = colony_id in recombinant_white_ids
plate.colonies[colony_id] = ScreeningColony(
colony_id=colony_id,
color="white",
is_recombinant=is_recombinant,
expected_band_bp=recombinant_band_bp if is_recombinant else empty_vector_band_bp,
notes=[
"White colony from blue-white screening.",
"Expected insert-positive band near {:d} bp.".format(recombinant_band_bp)
if is_recombinant
else "White false positive with empty-vector-like colony PCR band.",
],
)
for idx in range(1, 19):
colony_id = "blue_{:03d}".format(idx)
plate.colonies[colony_id] = ScreeningColony(
colony_id=colony_id,
color="blue",
is_recombinant=False,
expected_band_bp=empty_vector_band_bp,
notes=["Blue colony retaining lacZ alpha activity; treat as vector-only background."],
)
state.screening_plates[plate_id] = plate
return plate
def prepare_media(
state: LabState,
medium: str,
antibiotic: str,
antibiotic_concentration_ug_ml: float,
plate_count: int = 1,
) -> Dict[str, object]:
"""Prepare one or more selection plates."""
antibiotic_concentration = _require_positive_float(
antibiotic_concentration_ug_ml,
"antibiotic_concentration_ug_ml",
)
plate_count_int = _require_positive_integer(plate_count, "plate_count")
plates = []
for _ in range(plate_count_int):
plate_id = state.next_plate_id()
plate = PreparedPlate(
plate_id=plate_id,
medium=medium,
antibiotic=antibiotic,
antibiotic_concentration_ug_ml=antibiotic_concentration,
)
state.prepared_plates[plate_id] = plate
plates.append(
{
"plate_id": plate_id,
"medium": medium,
"antibiotic": antibiotic,
"antibiotic_concentration_ug_ml": antibiotic_concentration,
}
)
payload = {
"status": "prepared",
"plates": plates,
}
state.log_event("prepare_media", payload)
return payload
def transform(
state: LabState,
plasmid_mass_pg: float,
heat_shock_seconds: int,
recovery_minutes: int,
outgrowth_media: str = "SOC",
shaking: bool = True,
ice_incubation_minutes: int = 30,
) -> Dict[str, object]:
"""Simulate a chemical transformation and return a culture identifier."""
plasmid_mass = _require_positive_float(plasmid_mass_pg, "plasmid_mass_pg")
heat_shock = _require_positive_integer(heat_shock_seconds, "heat_shock_seconds")
recovery = _require_nonnegative_integer(recovery_minutes, "recovery_minutes")
ice_incubation = _require_nonnegative_integer(
ice_incubation_minutes,
"ice_incubation_minutes",
)
notes: List[str] = []
efficiency = state.base_efficiency_cfu_per_ug
efficiency *= state.parameters.ice_incubation_penalty(ice_incubation)
efficiency *= state.parameters.recovery_penalty(recovery)
if outgrowth_media.upper() == "SOC":
efficiency *= state.parameters.soc_multiplier()
else:
efficiency *= state.parameters.lb_multiplier()
notes.append("SOC was not used for outgrowth.")
if shaking:
efficiency *= state.parameters.shaking_multiplier()
else:
efficiency *= state.parameters.static_multiplier()
notes.append("Outgrowth was not shaken.")
if heat_shock != int(state.parameters.get("heat_shock_duration_seconds")["parameters"]["optimal"]):
notes.append("Heat shock duration deviated from the protocol optimum.")
expected_total_transformants = efficiency * (plasmid_mass / 1_000_000.0)
culture_id = state.next_culture_id()
culture = TransformationCulture(
culture_id=culture_id,
plasmid_mass_pg=plasmid_mass,
base_efficiency_cfu_per_ug=state.base_efficiency_cfu_per_ug,
adjusted_efficiency_cfu_per_ug=efficiency,
recovery_minutes=recovery,
outgrowth_media=outgrowth_media,
shaking=bool(shaking),
heat_shock_seconds=heat_shock,
ice_incubation_minutes=ice_incubation,
expected_total_transformants=expected_total_transformants,
notes=notes,
)
state.cultures[culture_id] = culture
payload = {
"status": "transformed",
"culture_id": culture_id,
"plasmid_mass_pg": plasmid_mass,
"heat_shock_seconds": heat_shock,
"recovery_minutes": recovery,
"outgrowth_media": outgrowth_media,
"notes": notes,
}
state.log_event("transform", payload)
return payload
def plate(
state: LabState,
culture_id: str,
plate_id: str,
dilution_factor: float,
volume_ul: float,
) -> Dict[str, object]:
"""Plate a transformed culture onto a prepared plate."""
culture = state.cultures[culture_id]
prepared_plate = state.prepared_plates[plate_id]
dilution = float(dilution_factor)
volume = float(volume_ul)
if dilution <= 0.0:
raise ValueError("dilution_factor must be positive.")
if volume <= 0.0:
raise ValueError("volume_ul must be positive.")
warnings: List[str] = []
countable_min, countable_max = state.parameters.countable_colony_range()
recommended = state.parameters.recommended_antibiotic_concentration(prepared_plate.antibiotic or "")
if recommended is None:
status = "plated_without_reference"
expected = culture.expected_total_transformants * (volume / 1000.0) / dilution
observed = sample_poisson(state.rng, expected)
elif float(prepared_plate.antibiotic_concentration_ug_ml) != float(recommended):
status = "selection_failed"
expected = None
observed = None
warnings.append("Selection plate concentration does not match the cited working concentration.")
else:
status = "plated"
expected = culture.expected_total_transformants * (volume / 1000.0) / dilution
observed = sample_poisson(state.rng, expected)
if observed < countable_min or observed > countable_max:
status = "count_out_of_range"
warnings.append(
"Observed colonies fall outside the cited countable range of "
"{:d}-{:d} colonies per plate.".format(countable_min, countable_max)
)
plating_id = state.next_plating_id()
plated_sample = PlatedSample(
plating_id=plating_id,
culture_id=culture_id,
plate_id=plate_id,
dilution_factor=dilution,
volume_ul=volume,
expected_colonies=expected,
observed_colonies=observed,
status=status,
warnings=warnings,
)
state.plated_samples[plating_id] = plated_sample
payload = {
"status": status,
"plating_id": plating_id,
"plate_id": plate_id,
"culture_id": culture_id,
"dilution_factor": dilution,
"volume_ul": volume,
"countable_range_colonies": {"min": countable_min, "max": countable_max},
"warnings": warnings,
}
state.log_event("plate", payload)
return payload
def count_colonies(state: LabState, plating_id: str) -> Dict[str, object]:
"""Return the observed colony count for a plated sample."""
plated_sample = state.plated_samples[plating_id]
countable_min, countable_max = state.parameters.countable_colony_range()
payload = {
"status": plated_sample.status,
"plating_id": plating_id,
"observed_colonies": plated_sample.observed_colonies,
"dilution_factor": plated_sample.dilution_factor,
"volume_ul": plated_sample.volume_ul,
"countable_range_colonies": {"min": countable_min, "max": countable_max},
"warnings": plated_sample.warnings,
}
state.log_event("count_colonies", payload)
return payload
def inoculate_growth(
state: LabState,
condition: str,
starting_od600: float,
) -> Dict[str, object]:
"""Start a growth-characterization culture under a named condition."""
bundle = _growth_bundle()
doubling_time_map = {
"LB": bundle.value("lb_doubling_time_minutes"),
"M9 + glucose": bundle.value("m9_glucose_doubling_time_minutes"),
"LB + chloramphenicol (1.8 uM)": (
bundle.value("lb_doubling_time_minutes")
/ bundle.fraction("chloramphenicol_1_8uM_relative_growth_rate")
),
}
medium_map = {
"LB": "LB",
"M9 + glucose": "M9 + glucose",
"LB + chloramphenicol (1.8 uM)": "LB + chloramphenicol (1.8 uM)",
}
if condition not in doubling_time_map:
raise ValueError("Unknown growth condition: {:s}".format(condition))
starting_od = _require_positive_float(starting_od600, "starting_od600")
growth_id = state.next_growth_id()
culture = GrowthCulture(
growth_id=growth_id,
condition=condition,
medium=medium_map[condition],
starting_od600=starting_od,
doubling_time_minutes=float(doubling_time_map[condition]),
)
state.growth_cultures[growth_id] = culture
payload = {
"status": "inoculated",
"growth_id": growth_id,
"condition": condition,
"starting_od600": starting_od,
"doubling_time_minutes": float(doubling_time_map[condition]),
}
state.log_event("inoculate_growth", payload)
return payload
def incubate(
state: LabState,
growth_id: str,
duration_minutes: int,
) -> Dict[str, object]:
"""Advance a growth culture in time."""
culture = state.growth_cultures[growth_id]
duration = _require_positive_integer(duration_minutes, "duration_minutes")
culture.current_time_minutes += duration
payload = {
"status": "incubated",
"growth_id": growth_id,
"condition": culture.condition,
"duration_minutes": duration,
"elapsed_minutes": int(culture.current_time_minutes),
}
state.log_event("incubate", payload)
return payload
def _true_growth_od600(culture: GrowthCulture) -> float:
return culture.starting_od600 * math.pow(2.0, culture.current_time_minutes / culture.doubling_time_minutes)
def measure_od600(
state: LabState,
growth_id: str,
dilution_factor: float = 1.0,
) -> Dict[str, object]:
"""Measure OD600 for a growth culture, optionally after dilution."""
culture = state.growth_cultures[growth_id]
dilution = _require_positive_float(dilution_factor, "dilution_factor")
true_od600 = _true_growth_od600(culture)
observed_od600 = true_od600 / dilution
measurement = GrowthMeasurement(
elapsed_minutes=int(culture.current_time_minutes),
dilution_factor=dilution,
observed_od600=float(observed_od600),
estimated_undiluted_od600=float(observed_od600 * dilution),
)
culture.measurements.append(measurement)
payload = {
"status": "measured",
"growth_id": growth_id,
"condition": culture.condition,
"elapsed_minutes": int(culture.current_time_minutes),
"dilution_factor": dilution,
"observed_od600": float(observed_od600),
"estimated_undiluted_od600": float(measurement.estimated_undiluted_od600),
}
state.log_event("measure_od600", payload)
return payload
def fit_growth_curve(
state: LabState,
growth_id: str,
) -> Dict[str, object]:
"""Estimate doubling time from the measured OD600 trajectory."""
bundle = _growth_bundle()
culture = state.growth_cultures[growth_id]
lower_fraction = bundle.fraction("growth_fit_lower_fraction_of_max_observed_od600")
upper_fraction = bundle.fraction("growth_fit_upper_fraction_of_max_observed_od600")
if not culture.measurements:
payload = {
"status": "insufficient_points",
"growth_id": growth_id,
"condition": culture.condition,
"qualifying_points": 0,
"warnings": ["No OD600 measurements were collected before attempting the fit."],
}
state.log_event("fit_growth_curve", payload)
return payload
max_observed = max(m.estimated_undiluted_od600 for m in culture.measurements)
lower_bound = lower_fraction * max_observed
upper_bound = upper_fraction * max_observed
qualifying = [
m for m in culture.measurements if lower_bound <= m.estimated_undiluted_od600 <= upper_bound
]
if len(qualifying) < 3:
payload = {
"status": "insufficient_points",
"growth_id": growth_id,
"condition": culture.condition,
"qualifying_points": len(qualifying),
"lower_bound_od600": float(lower_bound),
"upper_bound_od600": float(upper_bound),
"warnings": [
"Fewer than three OD600 measurements fell inside the cited fitting window."
],
}
state.log_event("fit_growth_curve", payload)
return payload
first = qualifying[0]
last = qualifying[-1]
elapsed_span = last.elapsed_minutes - first.elapsed_minutes
if elapsed_span <= 0:
payload = {
"status": "insufficient_points",
"growth_id": growth_id,
"condition": culture.condition,
"qualifying_points": len(qualifying),
"lower_bound_od600": float(lower_bound),
"upper_bound_od600": float(upper_bound),
"warnings": [
"Qualifying OD600 measurements did not span positive elapsed time."
],
}
state.log_event("fit_growth_curve", payload)
return payload
slope_per_minute = (
math.log(last.estimated_undiluted_od600) - math.log(first.estimated_undiluted_od600)
) / float(elapsed_span)
if slope_per_minute <= 0.0:
payload = {
"status": "insufficient_points",
"growth_id": growth_id,
"condition": culture.condition,
"qualifying_points": len(qualifying),
"lower_bound_od600": float(lower_bound),
"upper_bound_od600": float(upper_bound),
"warnings": [
"Qualifying OD600 measurements did not show positive exponential growth."
],
}
state.log_event("fit_growth_curve", payload)
return payload
estimated_doubling_time = math.log(2.0) / slope_per_minute
payload = {
"status": "analyzable",
"growth_id": growth_id,
"condition": culture.condition,
"qualifying_points": len(qualifying),
"lower_bound_od600": float(lower_bound),
"upper_bound_od600": float(upper_bound),
"estimated_doubling_time_minutes": float(estimated_doubling_time),
"max_observed_od600": float(max_observed),
"warnings": [],
}
state.log_event("fit_growth_curve", payload)
return payload
def run_pcr(
state: LabState,
polymerase_name: str,
additive: str,
extension_seconds: int,
cycle_count: int,
) -> Dict[str, object]:
"""Run a single PCR attempt for the GC-rich LabCraft PCR task."""
bundle = _pcr_bundle()
target_size_bp = 2000
high_fidelity_polymerases = {
_normalize_choice(name) for name in bundle.values("gc_rich_high_fidelity_polymerases")
}
helpful_additives = {_normalize_choice(name) for name in bundle.values("gc_rich_additives")}
extension_min, extension_max = bundle.range("gc_rich_extension_seconds_for_2kb_amplicon")
cycles_min, cycles_max = bundle.range("genomic_pcr_cycle_count_range")
normalized_polymerase = _normalize_choice(polymerase_name)
normalized_additive = _normalize_choice(additive)
status = "clean_target_band"
visible_bands_bp = [target_size_bp]
smear_present = False
notes: List[str] = []
if normalized_polymerase not in high_fidelity_polymerases:
status = "nonspecific_amplification"
visible_bands_bp = [850, target_size_bp]
smear_present = True
notes.append("A non-proofreading polymerase was used for a GC-rich genomic amplicon.")
elif normalized_additive not in helpful_additives:
status = "gc_rich_failure"
visible_bands_bp = []
notes.append("No GC-resolving additive was used for the GC-rich template.")
elif float(extension_seconds) < extension_min:
status = "truncated_product"
visible_bands_bp = [1200]
notes.append("Extension time was shorter than the cited range for a 2 kb amplicon.")
elif float(cycle_count) < cycles_min:
status = "low_yield_target_band"
visible_bands_bp = [target_size_bp]
notes.append("Cycle count was below the recommended range for genomic PCR.")
elif float(cycle_count) > cycles_max:
status = "nonspecific_amplification"
visible_bands_bp = [1400, target_size_bp]
smear_present = True
notes.append("Cycle count exceeded the recommended range for genomic PCR.")
elif float(extension_seconds) > extension_max * 2.0:
status = "nonspecific_amplification"
visible_bands_bp = [target_size_bp]
smear_present = True
notes.append("Extension time was excessively long for the 2 kb target.")
reaction_id = state.next_pcr_id()
reaction = PcrReaction(
reaction_id=reaction_id,
polymerase_name=polymerase_name,
additive=additive,
extension_seconds=int(extension_seconds),
cycle_count=int(cycle_count),
target_size_bp=target_size_bp,
status=status,
visible_bands_bp=visible_bands_bp,
smear_present=smear_present,
notes=notes,
)
state.pcr_reactions[reaction_id] = reaction
payload = {
"status": status,
"reaction_id": reaction_id,
"polymerase_name": polymerase_name,
"normalized_polymerase_name": (
"Q5 High-Fidelity DNA polymerase"
if "q5" in normalized_polymerase
else "Phusion High-Fidelity DNA polymerase"
if "phusion" in normalized_polymerase
else "Taq DNA polymerase"
if "taq" in normalized_polymerase
else polymerase_name
),
"additive": additive,
"normalized_additive": (
"DMSO"
if "dmso" in normalized_additive
else "Betaine"
if "betaine" in normalized_additive
else "none"
if normalized_additive in {"none", "no additive", "not used"}
else additive
),
"extension_seconds": int(extension_seconds),
"cycle_count": int(cycle_count),
"target_size_bp": target_size_bp,
"visible_bands_bp": visible_bands_bp,
"smear_present": smear_present,
"notes": notes,
}
state.log_event("run_pcr", payload)
return payload
def run_gel(
state: LabState,
reaction_id: str,
agarose_percent: float = 1.0,
ladder_name: str = "1 kb DNA Ladder",
) -> Dict[str, object]:
"""Run a simple agarose-gel readout for a PCR reaction."""
canonical_reaction_id = _resolve_pcr_reaction_id(state, reaction_id)
reaction = state.pcr_reactions[canonical_reaction_id]
status_map = {
"clean_target_band": "single_clean_target_band",
"low_yield_target_band": "faint_target_band",
"truncated_product": "wrong_size_band",
"gc_rich_failure": "no_visible_product",
"nonspecific_amplification": "multiple_bands_or_smear",
}
status = status_map[reaction.status]
notes = list(reaction.notes)
if reaction.status == "clean_target_band":
notes.append("A single strong band is visible near 2 kb.")
elif reaction.status == "low_yield_target_band":
notes.append("A faint band is visible near 2 kb.")
elif reaction.status == "truncated_product":
notes.append("A shorter-than-expected band is visible.")
elif reaction.status == "gc_rich_failure":
notes.append("No visible PCR product is present.")
elif reaction.status == "nonspecific_amplification":
notes.append("Multiple bands and/or smear are visible.")
gel_id = state.next_gel_id()
gel = GelRun(
gel_id=gel_id,
reaction_id=canonical_reaction_id,
ladder_name=ladder_name,
agarose_percent=float(agarose_percent),
status=status,
visible_bands_bp=list(reaction.visible_bands_bp),
smear_present=bool(reaction.smear_present),
notes=notes,
)
state.gel_runs[gel_id] = gel
payload = {
"status": status,
"gel_id": gel_id,
"reaction_id": canonical_reaction_id,
"polymerase_name": reaction.polymerase_name,
"normalized_polymerase_name": (
"Q5 High-Fidelity DNA polymerase"
if "q5" in _normalize_choice(reaction.polymerase_name)
else "Phusion High-Fidelity DNA polymerase"
if "phusion" in _normalize_choice(reaction.polymerase_name)
else "Taq DNA polymerase"
if "taq" in _normalize_choice(reaction.polymerase_name)
else reaction.polymerase_name
),
"additive": reaction.additive,
"normalized_additive": (
"DMSO"
if "dmso" in _normalize_choice(reaction.additive)
else "Betaine"
if "betaine" in _normalize_choice(reaction.additive)
else "none"
if _normalize_choice(reaction.additive) in {"none", "no additive", "not used"}
else reaction.additive
),
"extension_seconds": int(reaction.extension_seconds),
"cycle_count": int(reaction.cycle_count),
"target_size_bp": int(reaction.target_size_bp),
"visible_bands_bp": list(reaction.visible_bands_bp),
"smear_present": bool(reaction.smear_present),
"agarose_percent": float(agarose_percent),
"ladder_name": ladder_name,
"notes": notes,
}
state.log_event("run_gel", payload)
return payload
def inspect_screening_plate(state: LabState) -> Dict[str, object]:
"""Return the fixed blue-white screening plate for Screen-01."""
plate = _ensure_screening_plate(state)
white_ids = sorted(colony_id for colony_id, colony in plate.colonies.items() if colony.color == "white")
blue_ids = sorted(colony_id for colony_id, colony in plate.colonies.items() if colony.color == "blue")
payload = {
"status": "screening_plate_ready",
"plate_id": plate.plate_id,
"white_colony_ids": white_ids,
"blue_colony_ids": blue_ids,
"white_colony_count": len(white_ids),
"blue_colony_count": len(blue_ids),
"historical_positive_rate_among_white": float(plate.historical_positive_rate_among_white),
"target_confidence": float(plate.target_confidence),
"recombinant_band_bp": int(plate.recombinant_band_bp),
"empty_vector_band_bp": int(plate.empty_vector_band_bp),
"notes": [
"White colonies are enriched for inserts but may include false positives.",
"Blue colonies should be treated as vector-only background in this task.",
],
}
state.log_event("inspect_screening_plate", payload)
return payload
def run_colony_pcr(
state: LabState,
colony_ids: List[str],
primer_pair: str = "M13/pUC flank primers",
) -> Dict[str, object]:
"""Run colony PCR on the requested blue-white screening colonies."""
if not colony_ids:
raise ValueError("run_colony_pcr requires at least one colony_id.")
plate = _ensure_screening_plate(state)
results = []
batch_screening_strategy = "white_only"
batch_confirmed = []
for colony_id in colony_ids:
if colony_id not in plate.colonies:
raise ValueError(
"Unknown colony_id '{:s}'. Available colony IDs: {:s}".format(
colony_id,
", ".join(sorted(plate.colonies)),
)
)
colony = plate.colonies[colony_id]
if colony.color != "white":
batch_screening_strategy = "includes_blue"
if colony_id not in plate.screened_colony_ids:
plate.screened_colony_ids.append(colony_id)
result = {
"colony_id": colony.colony_id,
"color": colony.color,
"status": "recombinant_positive" if colony.is_recombinant else "empty_vector_or_background",
"visible_bands_bp": [int(colony.expected_band_bp)],
"notes": list(colony.notes),
}
results.append(result)
if colony.is_recombinant:
batch_confirmed.append(colony.colony_id)
cumulative_white_ids = [
colony_id
for colony_id in plate.screened_colony_ids
if plate.colonies[colony_id].color == "white"
]
confidence = 1.0 - math.pow(
1.0 - float(plate.historical_positive_rate_among_white),
len(cumulative_white_ids),
)
cumulative_confirmed = sorted(
colony_id
for colony_id in plate.screened_colony_ids
if plate.colonies[colony_id].is_recombinant
)
payload = {
"status": "screened",
"plate_id": plate.plate_id,
"primer_pair": primer_pair,
"screened_colony_ids": list(colony_ids),
"screened_colony_count": len(colony_ids),
"screening_strategy": batch_screening_strategy,
"colony_pcr_used": True,
"results": results,
"confirmed_recombinant_ids_in_batch": sorted(batch_confirmed),
"confirmed_recombinant_ids_cumulative": cumulative_confirmed,
"cumulative_screened_white_colony_count": len(cumulative_white_ids),
"cumulative_confidence_pct": round(confidence * 100.0, 1),
"recombinant_band_bp": int(plate.recombinant_band_bp),
"empty_vector_band_bp": int(plate.empty_vector_band_bp),
}
state.log_event("run_colony_pcr", payload)
return payload
def _normalize_enzyme_pair(enzyme_names: List[str]) -> List[str]:
return sorted(_normalize_choice(name).replace(" ", "").lower() for name in enzyme_names)
def _ensure_cloning_substrates(state: LabState) -> None:
if state.cloning_substrates_initialized:
return
bundle = _cloning_bundle()
vector = DnaFragment(
fragment_id="puc19_vector",
name="pUC19 vector",
length_bp=bundle.integer("vector_plasmid_length_bp"),
concentration_ng_ul=50.0,
is_circular=True,
end_5_prime="circular",
end_3_prime="circular",
recognition_sites=["EcoRI", "BamHI", "HindIII"],
notes=["Circular pUC19 cloning vector with EcoRI, BamHI, and HindIII sites in the MCS."],
)
insert = DnaFragment(
fragment_id="insert_raw",
name="Benign 950 bp PCR insert",
length_bp=bundle.integer("insert_length_bp"),
concentration_ng_ul=20.0,
is_circular=False,
end_5_prime="flanking_EcoRI_site",
end_3_prime="flanking_BamHI_site",
recognition_sites=["EcoRI", "BamHI"],
notes=[
"Linear PCR product with EcoRI and BamHI recognition sequences in the flanking primers."
],
)
state.dna_fragments[vector.fragment_id] = vector
state.dna_fragments[insert.fragment_id] = insert
state.cloning_substrates_initialized = True
def list_cloning_substrates(state: LabState) -> Dict[str, object]:
_ensure_cloning_substrates(state)
fragments = [
{
"fragment_id": fragment.fragment_id,
"name": fragment.name,
"length_bp": int(fragment.length_bp),
"concentration_ng_ul": float(fragment.concentration_ng_ul),
"is_circular": bool(fragment.is_circular),
"end_5_prime": fragment.end_5_prime,
"end_3_prime": fragment.end_3_prime,
"recognition_sites": list(fragment.recognition_sites),
}
for fragment in state.dna_fragments.values()
]
payload = {
"status": "cloning_substrates_ready",
"fragments": fragments,
}
state.log_event("list_cloning_substrates", payload)
return payload
def restriction_digest(
state: LabState,
fragment_id: str,
enzyme_names: List[str],
buffer: str,
temperature_c: float,
duration_minutes: int,
heat_inactivate_after: bool,
heat_inactivation_temperature_c: float = 65.0,
) -> Dict[str, object]:
"""Simulate a restriction digest on a DNA fragment."""
_ensure_cloning_substrates(state)
if fragment_id not in state.dna_fragments:
raise ValueError(
"Unknown fragment_id '{:s}'. Available fragment IDs: {:s}".format(
fragment_id, ", ".join(sorted(state.dna_fragments))
)
)
bundle = _cloning_bundle()
substrate = state.dna_fragments[fragment_id]
compatible_buffers = {b.lower() for b in bundle.choices("compatible_double_digest_buffers")}
normalized_enzymes = _normalize_enzyme_pair(enzyme_names)
optimal_duration = bundle.integer("digest_minimum_duration_minutes")
optimal_temperature = bundle.value("digest_temperature_c")
heat_inactivation_target = bundle.value("digest_heat_inactivation_temperature_c")
notes: List[str] = []
status = "digested"
if len(enzyme_names) != 2 or normalized_enzymes != ["bamhi", "ecori"]:
status = "wrong_enzyme_pair"
notes.append(