-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblindkit.py
More file actions
2007 lines (1718 loc) · 85.1 KB
/
blindkit.py
File metadata and controls
2007 lines (1718 loc) · 85.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2026 Windsor Kwan-Chun Ting, PhD.
# This file is part of BlindKit.
# BlindKit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
# BlindKit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
"""
BlindKit — Integrated two-root blinding and randomization toolkit with comprehensive audit logging,
legacy-aware planning, and `init-dual --only` mode.
Features
- Two-root model: BLINDER (keys, maps) and EXPERIMENTER (blinded artifacts).
- Append-only audit logs in each root (machine JSONL + human-readable text).
- Behavior planning (A/B per animal with 4 sessions → 2xA/2xB randomized per animal).
- Physiology planning (50/50 cohort; legacy-aware via --legacy-csv/--legacy-json).
- Label overlays for behavior/physiology/aliquot; optional QR payloads.
- Injection receipts; reconcile back to overlays.
- Post-hoc unblinding bundle with manifest & reconciliation report
"""
import argparse, csv, datetime, hashlib, json, os, pathlib, random, re, shutil, sys, zipfile, glob
import pandas as pd
from pathlib import Path
from collections import Counter
from PIL import Image, ImageDraw, ImageFont
import math
import secrets, string
from typing import Any, Dict, Iterable, Set
# ---------- Optional deps ----------
try:
import qrcode
HAS_QR = True
except Exception:
HAS_QR = False
try:
from PIL import Image, ImageOps
HAS_PIL = True
except Exception:
HAS_PIL = False
# ---------- Utils ----------
def iso_now():
return datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
def sha256_str(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def sha256_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def sha256_file(p: pathlib.Path) -> str:
h = hashlib.sha256()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(1<<20), b""):
h.update(chunk)
return h.hexdigest()
def ensure_dirs(root: pathlib.Path, subs):
for s in subs: os.makedirs(root / s, exist_ok=True)
def safe_rel(base: pathlib.Path, p: pathlib.Path) -> str:
try: return str(p.relative_to(base))
except Exception: return str(p)
# ---------- Audit logging ----------
def _audit_paths(root: pathlib.Path):
os.makedirs(root / "audit", exist_ok=True)
return root / "audit" / "actions.jsonl", root / "audit" / "actions.log"
def _audit_write(root: pathlib.Path, action: str, **fields):
jsonl, logtxt = _audit_paths(root)
rec = {"ts": iso_now(), "action": action}
rec.update({k:v for k,v in fields.items()})
with open(jsonl, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
line = f"{rec['ts']} | {action.upper()} | " + " | ".join(f"{k}={v}" for k,v in fields.items())
with open(logtxt, "a", encoding="utf-8") as f:
f.write(line + "\n")
# ---------- Init (two roots) ----------
def _init_blinder(br: pathlib.Path, study_id: str):
ensure_dirs(br, ["configs","labels","logs","media/photos","archives","audit"])
(br / "study_meta.json").write_text(json.dumps({"study_id": study_id, "role":"BLINDER","created": iso_now()}, indent=2))
(br / "labels" / "registry.json").write_text(json.dumps({"entries":[]}, indent=2))
def _init_experimenter(er: pathlib.Path, study_id: str):
ensure_dirs(er, ["receipts","logs","media/photos","anatomy_blinded","anatomy_working","provenance","configs","audit"])
(er / "study_meta.json").write_text(json.dumps({"study_id": study_id, "role":"EXPERIMENTER","created": iso_now()}, indent=2))
def cmd_init_dual(a):
study_id = a.study_id
only = (a.only or "").lower().strip() or None
if only == "blinder":
if not a.blinder_root:
raise SystemExit("[!] --blinder-root is required when --only blinder")
br = pathlib.Path(a.blinder_root).resolve()
_init_blinder(br, study_id)
_audit_write(br, "init-dual", study_id=study_id, role="BLINDER", mode="only")
print("[+] Initialized BLINDER root only →", br)
return
if only == "experimenter":
if not a.experimenter_root:
raise SystemExit("[!] --experimenter-root is required when --only experimenter")
er = pathlib.Path(a.experimenter_root).resolve()
_init_experimenter(er, study_id)
_audit_write(er, "init-dual", study_id=study_id, role="EXPERIMENTER", mode="only")
print("[+] Initialized EXPERIMENTER root only →", er)
return
# Default: create both
if not a.blinder_root or not a.experimenter_root:
raise SystemExit("[!] When --only is not used, both --blinder-root and --experimenter-root are required.")
br = pathlib.Path(a.blinder_root).resolve()
er = pathlib.Path(a.experimenter_root).resolve()
_init_blinder(br, study_id)
_init_experimenter(er, study_id)
_audit_write(br, "init-dual", study_id=study_id, peer_experimenter_root=str(er), role="BLINDER", mode="both")
_audit_write(er, "init-dual", study_id=study_id, peer_blinder_root=str(br), role="EXPERIMENTER", mode="both")
print("[+] Initialized two roots")
print(" BLINDER →", br)
print(" EXPERIMENTER→", er)
# ---------- Animals ----------
def animals_path(br: pathlib.Path): return br / "configs" / "animals.jsonl"
def animals_list(br: pathlib.Path):
ans=[]; p=animals_path(br)
if p.exists():
for line in p.read_text().splitlines():
try: ans.append(json.loads(line)["animal"])
except: pass
return ans
def cmd_register_animal(a):
br = pathlib.Path(a.blinder_root).resolve()
ensure_dirs(br, ["configs", "audit"])
animals_file = animals_path(br)
# 1. Load existing animals if file exists
existing_ids = set()
if animals_file.exists():
with open(animals_file, "r", encoding="utf-8") as f:
for line in f:
try:
record = json.loads(line)
existing_ids.add(record.get("animal"))
except json.JSONDecodeError:
continue # skip bad lines
# 2. Check for duplicate
if a.animal_id in existing_ids:
print(f"[!] Animal {a.animal_id} is already registered.")
print("[!] If you're certain this is a new animal please recheck for typos.")
return
# 3. Append new entry
new_entry = {
"animal": a.animal_id,
"sex": a.sex,
"weight": a.weight,
"ts": iso_now(),
}
with open(animals_file, "a", encoding="utf-8") as f:
f.write(json.dumps(new_entry) + "\n")
# 4. Audit + print
_audit_write(br, "register-animal", animal_id=a.animal_id, sex=a.sex, weight=a.weight)
print("[+] Registered animal", a.animal_id, "in BLINDER configs")
# ---------- Planning ----------
def seeded_rng(date_seed: str, animal: str):
base = int(date_seed)
ah = int(sha256_str(animal)[:8], 16)
import random
return random.Random(base ^ ah)
# def cmd_plan_behavior(a):
# br = pathlib.Path(a.blinder_root).resolve()
# ensure_dirs(br, ["configs","audit"])
# ans = animals_list(br)
# if not ans: raise SystemExit("[!] No animals registered (BLINDER).")
# A,B = a.agents
# plan = {"date_seed": a.date_seed, "agents":[A,B], "sessions":4, "assignments":{}}
# for an in sorted(ans):
# seq=[A,A,B,B]; seeded_rng(a.date_seed, an).shuffle(seq)
# plan["assignments"][an] = [{"session": i+1, "agent": seq[i]} for i in range(4)]
# out_json = br / "configs" / "behavior_plan.json"
# out_csv = br / "configs" / "behavior_plan.csv"
# out_json.write_text(json.dumps(plan, indent=2))
# with open(out_csv, "w", newline="", encoding="utf-8") as f:
# w=csv.writer(f); w.writerow(["animal","session","agent"])
# for an in sorted(plan["assignments"]):
# for r in plan["assignments"][an]:
# w.writerow([an, r["session"], r["agent"]])
# _audit_write(br, "plan-behavior", date_seed=a.date_seed, agents=",".join(a.agents), animals=len(ans))
# print("[+] Behavior plan saved at BLINDER configs")
def load_all_labels(registry_path: Path) -> set[str]:
with registry_path.open("r") as f:
data = json.load(f)
used = set()
assignments = data.get("assignments", {})
for domain in ["viral_aliquot", "physiology"]:
for entry in assignments.get(domain, {}).values():
if isinstance(entry, dict) and "label" in entry:
used.add(entry["label"])
return used
def unique_label(used: set[str], prefix="syr", length=6, max_tries=100) -> str:
for _ in range(max_tries):
lbl = new_label(prefix, length)
if lbl not in used:
used.add(lbl) # reserve immediately
return lbl
raise RuntimeError("Could not generate a unique label; expand namespace")
def cmd_plan_behavior(a): # needs stress testing
blinder_dir = Path(a.blinder_root)
planning_dir = blinder_dir / "configs"
plan_path = blinder_dir / "configs"
planning_dir.mkdir(parents=True, exist_ok=True)
# # Load registered animals
# registered_df = pd.read_json(a.reg_animals, lines=True)
# registered_animals = set(registered_df["animal"])
# Load registered animals with the latest data structure
registered_df = pd.read_json(a.reganimals_list, lines=True)
registered_animals = set(registered_df["animal"])
# Load agent list from text file (one agent per line)
agent_list = a.agents
seed = a.date_seed
unique_agents = sorted(set(agent_list))
if len(unique_agents) != 2 :
print("Error: you must provide exactly two agents for 2x2 design. Please rerun the command.")
return
# # Load agent list
# with open(a.agents) as f:
# agent_list = [line.strip() for line in f if line.strip()]
# unique_agents = sorted(set(agent_list))
# seed = a.seed
# if len(unique_agents) != 2:
# print("Error: You must provide exactly two agents for 2x2 design.")
# return
# Compose versioned output path based on seed
versioned_json = planning_dir / f"behavior_plan_{seed}.json"
# # Load previous assigned animals
# existing_animals = set()
# for plan_file in planning_dir.glob("behavior_plan_*.json"):
# with open(plan_file) as f:
# plan = json.load(f)
# existing_animals.update(plan.get("assignments", {}).keys())
# # Filter only unassigned animals
# unassigned_animals = sorted(registered_animals - existing_animals)
# if not unassigned_animals:
# print("No unassigned animals found. All have been previously planned.")
# return
# print(f"Planning {len(unassigned_animals)} new animals for seed {seed}: {unassigned_animals}")
# Load assigned animal list from versioned jsons if available
if os.path.exists(planning_dir):
existing_animals = set()
for plan_file in plan_path.glob("behavior_plan_*.json"):
with open(plan_file) as f:
plan = json.load(f)
existing_animals.update(plan.get("assignments", {}).keys())
print(f"Loaded existing plan with {len(existing_animals)} assigned animals.")
else:
existing_df = pd.DataFrame()
existing_animals = set()
print("No existing plan found. Starting fresh.")
# Determine unassigned animals
unassigned_animals = sorted(registered_animals - existing_animals)
if not unassigned_animals:
print("No unassigned animals found. Plan is up to date.")
return
print(f"Found {len(unassigned_animals)} unassigned animals: {unassigned_animals}")
# Hash-based seed
hash_input = "".join(sorted(unassigned_animals)) + "".join(unique_agents) + str(seed)
hashed_seed = int(hashlib.sha256(hash_input.encode()).hexdigest(), 16) % (10 ** 8)
random.seed(hashed_seed)
# 4 sessions per animal, 2 of each agent in random order
assignments = {}
for animal in unassigned_animals:
sessions = [unique_agents[0]] * 2 + [unique_agents[1]] * 2
random.shuffle(sessions)
assignments[animal] = {
f"session_{i+1}": agent for i, agent in enumerate(sessions)
}
# Save
output = {
"seed": seed,
"assignments": assignments
}
versioned_json.write_text(json.dumps(output, indent=2))
print(f"Saved to {versioned_json}")
all_agents = sum([list(s.values()) for s in assignments.values()], [])
print(f"Final session distribution: {Counter(all_agents)}")
def _load_legacy_assignments(path: str, allowed_agents):
p = pathlib.Path(path)
if not p.exists():
raise SystemExit(f"[!] Legacy file not found: {p}")
legacy = {}
if p.suffix.lower() == ".json":
try:
data = json.loads(p.read_text())
items = data.get("assignments", data)
for k,v in items.items():
ag = str(v).strip()
if ag not in allowed_agents:
raise SystemExit(f"[!] Legacy agent for {k} must be one of {allowed_agents}, got {ag}")
legacy[str(k).strip()] = ag
except Exception as e:
raise SystemExit(f"[!] Could not parse legacy JSON: {e}")
else:
with open(p, "r", encoding="utf-8") as f:
r = csv.reader(f)
rows = list(r)
start = 1 if rows and rows[0] and rows[0][0].lower().startswith("animal") else 0
for row in rows[start:]:
if not row:
continue
an = row[0].strip()
if not an:
continue
ag = row[1].strip() if len(row)>1 else ""
if ag not in allowed_agents:
raise SystemExit(f"[!] Legacy agent for {an} must be one of {allowed_agents}, got {ag}")
legacy[an] = ag
return legacy
# DOMAINS = ("viral_aliquot", "physiology")
def _extract_domain_labels(assignment: Dict[str, Any]) -> Iterable[str]:
"""Yield labels from known domains inside an 'assignment' block."""
for d in DOMAINS:
sub = assignment.get(d)
if isinstance(sub, dict):
lbl = sub.get("label")
if isinstance(lbl, str):
yield lbl
DOMAINS = ("physiology", "behavior", "virus")
def get_universe_labels(registry_path: Path) -> set[str]:
"""
Return the full universe of labels across aliquot, behavior, and physiology
by scanning every *.json / *.jsonl file under registry_path (recursively).
"""
labels: Set[str] = set()
if not registry_path.exists():
print("[!] Registry Path Not Found. Collision Resistance May not be Accurate.")
return labels
files = (
list(registry_path.rglob("*.json")) +
list(registry_path.rglob("*.jsonl"))
if registry_path.is_dir() else [registry_path]
)
for fpath in files:
try:
if fpath.suffix.lower() == ".jsonl":
with fpath.open("r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
_extract_labels_from_obj(obj, labels)
else:
with fpath.open("r", encoding="utf-8") as fh:
try:
data = json.load(fh)
except json.JSONDecodeError:
continue
_extract_labels_from_obj(data, labels)
except OSError:
# unreadable file; skip
continue
return labels
def _extract_labels_from_obj(obj: Any, labels: Set[str]) -> None:
"""
Handle a few realistic shapes:
- {"assignments": { "WT-123": { "physiology": {"label": "...."}, ... }, ... } }
- {"entries": [ { "assignments": {...}}, ... ] }
- And tolerate list-at-top structures.
"""
if isinstance(obj, dict):
# Direct assignments block
if "assignments" in obj and isinstance(obj["assignments"], dict):
_extract_labels_from_assignments(obj["assignments"], labels)
# Some files wrap in "entries": [...]
if "entries" in obj and isinstance(obj["entries"], list):
for entry in obj["entries"]:
if isinstance(entry, dict) and "assignments" in entry and isinstance(entry["assignments"], dict):
_extract_labels_from_assignments(entry["assignments"], labels)
# Fallthrough: sometimes the whole file *is* the assignments dict
# e.g., { "WT-123": { "physiology": {...} }, ... }
if all(isinstance(v, dict) for v in obj.values()):
if any(k in DOMAINS for v in obj.values() for k in (v.keys() if isinstance(v, dict) else [])):
_extract_labels_from_assignments(obj, labels)
elif isinstance(obj, list):
for item in obj:
_extract_labels_from_obj(item, labels)
def _extract_labels_from_assignments(assignments: Dict[str, Any], labels: Set[str]) -> None:
"""
assignments: { animal_id: { domain: { ... "label": "XXXX", ... }, ... }, ... }
"""
for animal_id, per_animal in assignments.items():
if not isinstance(per_animal, dict):
continue
for domain in DOMAINS:
block = per_animal.get(domain)
if not isinstance(block, dict):
continue
# Common key names for labels
for key in ("label", "syringe_label", "agent_label"):
val = block.get(key)
if isinstance(val, str) and val:
labels.add(val)
def unique_label(used: set[str], length=4, max_tries=100) -> str:
for _ in range(max_tries):
lbl = new_label(length)
if lbl not in used:
used.add(lbl) # reserve immediately
return lbl
raise RuntimeError("Could not generate a unique label; expand namespace")
def cmd_plan_physiology(a):
seed = a.date_seed
blinder_dir = Path(a.blinder_root)
plan_path = blinder_dir / "configs"
registry_path = blinder_dir / "configs"
planning_dir = plan_path.parent
versioned_json = blinder_dir / "configs" / f"physiology_plan_{seed}.json"
planning_dir.mkdir(parents=True, exist_ok=True)
# Load registered animal list from JSONL file
registered_df = pd.read_json(a.reganimals_list, lines=True)
registered_animals = set(registered_df["animal"])
# Load agent list from text file (one agent per line)
agent_list = a.agents
seed = a.date_seed
unique_agents = sorted(set(agent_list))
if len(unique_agents) <2:
print("Error: you must provide at least two unique agents.")
return
# Load assigned animal list from versioned jsons if available
if os.path.exists(planning_dir):
existing_animals = set()
for plan_file in plan_path.glob("physiology_plan_*.json"):
with open(plan_file) as f:
plan = json.load(f)
existing_animals.update(plan.get("assignments", {}).keys())
print(f"Loaded existing plan with {len(existing_animals)} assigned animals.")
else:
existing_df = pd.DataFrame()
existing_animals = set()
print("No existing plan found. Starting fresh.")
# Determine unassigned animals
unassigned_animals = sorted(registered_animals - existing_animals)
if not unassigned_animals:
print("No unassigned animals found. Plan is up to date.")
return
print(f"Found {len(unassigned_animals)} unassigned animals: {unassigned_animals}")
# Hash inputs to generate deterministic seed
hash_input = "".join(sorted(unassigned_animals)) + "".join(sorted(unique_agents)) + str(seed)
hashed_seed = int(hashlib.sha256(hash_input.encode()).hexdigest(), 16) % (10 ** 8)
random.seed(hashed_seed)
# # Create balanced group assignment
# n = len(unassigned_animals)
# n_agents = len(unique_agents)
# base_count = n // n_agents
# remainder = n % n_agents
# # Create balanced agent list
# agent_counts = [base_count + (1 if i < remainder else 0) for i in range(n_agents)]
# balanced_agents = []
# for agent, count in zip(unique_agents, agent_counts):
# balanced_agents.extend([agent] * count)
# random.shuffle(balanced_agents)
# # --- Ratio-based assignment with explicit favored agent and minimum safeguard ---
# favored_agent = "CNO"
# ratio = (3, 1)
# n = len(unassigned_animals)
# favored_weight, other_weight = ratio
# total_parts = favored_weight + other_weight
# # Count for favored agent (initial calculation)
# # Use floor so rounding favors the non-favored group (e.g., N=10 → 7/3, not 8/2)
# n_favored = (n * favored_weight) // total_parts
# n_other = n - n_favored
# # Safeguard: ensure at least 1 non-favored animal if N >= 4
# if n >= 4 and n_other == 0:
# n_other = 1
# n_favored = n - n_other
# # Build counts dict
# agent_counts = {favored_agent: n_favored}
# other_agents = [a for a in unique_agents if a != favored_agent]
# # If only one other agent, assign all remainder to it
# if len(other_agents) == 1:
# agent_counts[other_agents[0]] = n_other
# else:
# # Distribute across multiple non-favored agents
# per_other = n_other // len(other_agents)
# remainder = n_other % len(other_agents)
# for i, agent in enumerate(other_agents):
# agent_counts[agent] = per_other + (1 if i < remainder else 0)
# # Build assignment list
# balanced_agents = []
# for agent, count in agent_counts.items():
# balanced_agents.extend([agent] * count)
# # Shuffle for randomness
# random.shuffle(balanced_agents)
# ---------- v6 cross-stage PHYSIOLOGY dependency on VIRAL ALIQUOT IDENTITY via CONFIGS SCAN ----------
favored_agent = "CNO"
ratio = (3, 1) # keep your existing 3:1 logic
# Build viral map from *all* configs/*.json
viral_map = _collect_viral_map_from_configs(blinder_dir)
# Require viral assignment for every unassigned animal; otherwise exit gracefully
missing = [an for an in unassigned_animals if an not in viral_map]
if missing:
print("[!] Some registered animals lack viral aliquot assignments in configs/*.json:")
print(" ", missing)
print("[i] Please run cmd_plan_aliquot for these animals before cmd_plan_physiology.")
return
# Partition by viral agent
dread = [an for an in unassigned_animals if viral_map.get(an) == "Cre-DREADD-mCherry"]
cre = [an for an in unassigned_animals if viral_map.get(an) == "Cre-mCherry"]
other = [an for an in unassigned_animals if an not in dread and an not in cre]
def _counts_for_ratio(N: int, favored: str, others: list[str], ratio_pair=(3,1)) -> Dict[str,int]:
if N <= 0:
return {}
fw, ow = ratio_pair
total = fw + ow
n_fav = (N * fw) // total
n_oth = N - n_fav
# safeguard: ≥1 non-favored when cohort >= 4 (preserves existing rule)
if N >= 4 and n_oth == 0 and others:
n_oth = 1
n_fav = N - 1
counts = {favored: n_fav}
if not others:
return counts
if len(others) == 1:
counts[others[0]] = n_oth
return counts
per = n_oth // len(others)
rem = n_oth % len(others)
for i, ag in enumerate(others):
counts[ag] = per + (1 if i < rem else 0)
return counts
def _expand(counts: Dict[str,int]) -> list[str]:
bag = []
for ag, c in counts.items():
bag.extend([ag] * max(0, int(c)))
return bag
other_agents = [ag for ag in unique_agents if ag != favored_agent]
# Per-animal agent decisions, honoring cross-stage rules
chosen_agent: Dict[str, str] = {}
# (1) Cre-DREADD-mCherry → 3:1 randomization
if dread:
counts = _counts_for_ratio(len(dread), favored_agent, other_agents, ratio)
bag = _expand(counts)
random.shuffle(bag)
random.shuffle(dread)
for an, ag in zip(dread, bag):
chosen_agent[an] = ag
# (2) Cre-mCherry → always CNO
for an in cre:
chosen_agent[an] = favored_agent
# (3) Any other viral agent string → fall back to existing 3:1 behavior
if other:
counts = _counts_for_ratio(len(other), favored_agent, other_agents, ratio)
bag = _expand(counts)
random.shuffle(bag)
random.shuffle(other)
for an, ag in zip(other, bag):
chosen_agent[an] = ag
used_labels = get_universe_labels(registry_path)
print("Current Universe Set of Used Labels: " + str(used_labels))
# assignments = {
# animal: {
# "physiology": {
# "agent": agent,
# "label": unique_label(used_labels, length=4, max_tries=100)
# }
# }
# for animal, agent in zip(unassigned_animals, balanced_agents)
# }
# Attach blinded labels and emit final structure
assignments = {}
for animal in unassigned_animals:
agent = chosen_agent[animal]
assignments[animal] = {
"physiology": {
"agent": agent,
"label": unique_label(used_labels, length=4, max_tries=100)
}
}
print("New Blinded Labels Generated with Collision Resistance and Cross-Stage Dependency between Viral Aliquot and Physiology.")
output = {
"seed": seed,
"assignments": assignments
}
# new_df = pd.DataFrame(new_rows)
# full_plan = pd.concat([existing_df, new_df], ignore_index=True)
# full_plan.to_csv(plan_path, index=False)
versioned_json.write_text(json.dumps(output, indent=2))
print(f"New animal assignments saved to {versioned_json}")
# print(f"Agent distribution for this planning run: {Counter([a['agent'] for a in assignments.values()])}")
# full_plan_for_json = dict(zip(full_plan["animal"], full_plan["agent"]))
# plan_json = {"date_seed": a.date_seed, "agents": ["CNO, Saline"], "assignments": full_plan_for_json,
# "final_counts": full_plan['agent'].value_counts().to_dict()}
# (blinder_dir/"configs"/"physiology_plan.json").write_text(json.dumps(plan_json, indent=2))
# print(f"Appended {len(new_df)} new assignments. Total now: {len(full_plan)} animals.")
# print(f"Appended {len(new_df)} new assignments.")
# print(f"Final agent distribution: {dict(Counter(full_plan['agent']))}")
ALPHABET = "ABCDEF0123456789"
def new_label(length=4):
return "".join(secrets.choice(ALPHABET) for _ in range(length))
# ---------- v6: cross-stage helpers ----------
def _collect_viral_map_from_configs(br: Path) -> Dict[str, str]:
"""
Scan ALL configs/*.json for viral assignments.
Later files (by mtime) override earlier ones.
Accepts shapes like:
{"assignments":{"rat001":{"virus":{"agent":"Cre-DREADD-mCherry","label":"AB12"}}}}
{"assignments":{"rat001":{"viral_aliquot":{"agent":"Cre-mCherry","label":"CD34"}}}}
Returns { animal_id: agent_string }.
"""
cfg = br / "configs"
if not cfg.exists():
return {}
files = sorted(cfg.glob("*.json"), key=lambda p: p.stat().st_mtime)
vmap: Dict[str, str] = {}
for p in files:
try:
with p.open("r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
continue
assignments = data.get("assignments", {})
if not isinstance(assignments, dict):
continue
for an, rec in assignments.items():
if not isinstance(rec, dict):
continue
block = rec.get("virus") or rec.get("viral_aliquot") or {}
agent = None
if isinstance(block, dict):
agent = block.get("agent")
# tolerate flat form (rare): {"assignments":{"rat001":{"agent":"..."}}}
if agent is None:
agent = rec.get("agent")
if isinstance(agent, str) and agent.strip():
vmap[str(an)] = agent.strip()
return vmap
def new_label(length=4):
return "".join(secrets.choice(ALPHABET) for _ in range(length))
def cmd_plan_aliquot(a):
seed = a.date_seed
blinder_dir = Path(a.blinder_root)
plan_path = blinder_dir / "configs"
registry_path = blinder_dir / "configs"
planning_dir = plan_path.parent
versioned_json = blinder_dir / "configs" / f"brainstem_viral_aliquot_plan_{seed}.json"
planning_dir.mkdir(parents=True, exist_ok=True)
# Load registered animal list from JSONL file
registered_df = pd.read_json(a.reganimals_list, lines=True)
registered_animals = set(registered_df["animal"])
# Load agent list from text file (one agent per line)
virus_list = a.brainstem_virus
seed = a.date_seed
unique_virus = sorted(set(virus_list))
if len(unique_virus) <2:
print("Error: you must provide at least two brainstem viral agents. Please rerun the command.")
return
# Load assigned animal list from versioned jsons if available
if os.path.exists(planning_dir):
existing_animals = set()
for plan_file in plan_path.glob("brainstem_viral_aliquot_plan_*.json"):
with open(plan_file) as f:
plan = json.load(f)
existing_animals.update(plan.get("assignments", {}).keys())
print(f"Loaded existing viral plan with {len(existing_animals)} assigned animals.")
else:
existing_df = pd.DataFrame()
existing_animals = set()
print("No existing plan found. Starting fresh.")
# Determine unassigned animals
# unassigned_animals = sorted(registered_animals - assigned_animals)
unassigned_animals = sorted(registered_animals - existing_animals)
if not unassigned_animals:
print("No unassigned animals found. Plan is up to date.")
return
print(f"Found {len(unassigned_animals)} unassigned animals: {unassigned_animals}")
# Hash inputs to generate deterministic seed
hash_input = "".join(sorted(unassigned_animals)) + "".join(sorted(unique_virus)) + str(seed)
hashed_seed = int(hashlib.sha256(hash_input.encode()).hexdigest(), 16) % (10 ** 8)
random.seed(hashed_seed)
# # Create balanced group assignment
# n = len(unassigned_animals)
# n_virus = len(unique_virus)
# base_count = n // n_virus
# remainder = n % n_virus
# # Create balanced virus list
# virus_counts = [base_count + (1 if i < remainder else 0) for i in range(n_virus)]
# balanced_virus = []
# for virus, count in zip(unique_virus, virus_counts):
# balanced_virus.extend([virus] * count)
# random.shuffle(balanced_virus)
# --- Ratio-based assignment with explicit favored agent and minimum safeguard ---
favored_virus = "Cre-DREADD-mCherry"
ratio = (3, 1)
n = len(unassigned_animals)
favored_weight, other_weight = ratio
total_parts = favored_weight + other_weight
# Count for favored agent (initial calculation)
# Use floor so rounding favors the non-favored group (e.g., N=10 → 7/3, not 8/2)
# n_favored = (n * favored_weight) // total_parts
# n_other = n - n_favored
# Count for favored agent (rounding up instead of flooring)
n_favored = math.ceil(n * favored_weight / total_parts)
n_other = n - n_favored
# Safeguard: ensure at least 1 non-favored animal if N >= 4
if n >= 4 and n_other == 0:
n_other = 1
n_favored = n - n_other
# Build counts dict
virus_counts = {favored_virus: n_favored}
other_virus = [a for a in unique_virus if a != favored_virus]
# If only one other agent, assign all remainder to it
if len(other_virus) == 1:
virus_counts[other_virus[0]] = n_other
else:
# Distribute across multiple non-favored agents
per_other = n_other // len(other_virus)
remainder = n_other % len(other_virus)
for i, virus in enumerate(other_virus):
virus_counts[virus] = per_other + (1 if i < remainder else 0)
# Build assignment list
balanced_virus = []
for virus, count in virus_counts.items():
balanced_virus.extend([virus] * count)
# Shuffle for randomness
random.shuffle(balanced_virus)
used_labels = get_universe_labels(registry_path)
print("Current Universe Set of Used Labels: " + str(used_labels))
assignments = {
animal: {
"virus": {
"agent": virus,
# "label": f"{''.join(random.choices('ABCDEF0123456789', k=4))}"
"label": unique_label(used_labels, length=4, max_tries=100)
}
}
for animal, virus in zip(unassigned_animals, balanced_virus)
}
print("New Blinded Labels Generated with Collision Resistance.")
output = {
"seed": seed,
"assignments": assignments
}
versioned_json.write_text(json.dumps(output, indent=2))
print(f"Saved virus aliquot assignments to {versioned_json}")
# print(f"Viral aliquot distribution for this planning run: {Counter([a['virus'] for a in assignments.values()])}")
# ---------- Overlays (BLINDER) ----------
_MICRO_ALPH="23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
def micro_code(k=4):
import random
return "".join(random.choice(_MICRO_ALPH) for _ in range(k))
def compute_checks(dummy: str, animal: str, stage: str):
base=f"{dummy}{animal}{stage}"
c1=hashlib.sha256(base.encode()).hexdigest().upper()
c2=hashlib.sha1(base.encode()).hexdigest().upper()
if stage=="VIRAL": return c1[:2], c2[:2]
if stage=="BEHAVIOR": return c1[:4], c2[:4]
return c1[:2], c2[:2]
def append_blinder_registry(br: pathlib.Path, rec: dict):
reg_path = br / "labels" / "registry.json"
try:
reg = json.loads(reg_path.read_text())
except Exception:
reg={"entries":[]}
reg["entries"].append(rec)
reg_path.write_text(json.dumps(reg, indent=2))
def overlay_common(animal: str, stage: str, base_id: str):
if stage=="VIRAL":
dummy=f"VIR-{micro_code(4)}"
elif stage=="BEHAVIOR":
dummy=f"BEH-{os.urandom(2).hex().upper()}"
else:
dummy=f"PHY-{os.urandom(2).hex().upper()}"
c1,c2 = compute_checks(dummy, animal, stage)
label_id = os.urandom(3).hex().upper()
return dummy,c1,c2,label_id
def cmd_overlay_behavior(a):
br = pathlib.Path(a.blinder_root).resolve()
ensure_dirs(br, ["labels","media/photos","logs","audit"])
animal = input("Animal ID: ").strip()
session = int(input("Behavior SESSION (1-4): ").strip())
syringe_id = input("Base SYRINGE_ID (preparer sticker): ").strip()
dummy,c1,c2,label = overlay_common(animal,"BEHAVIOR",syringe_id)
ts0 = iso_now()
lbl = br/"labels"/f"{animal}_BEH{session}_{label}.txt"
lbl.write_text(f"ANIMAL:{animal}\nSTAGE:BEHAVIOR\nSESSION:{session}\nDUMMY:{dummy}\nCHECK1:{c1}\nCHECK2:{c2}\nSYRINGE:{syringe_id}\nLABEL:{label}\nTS:{ts0}\n")
if HAS_QR:
payload=json.dumps({"animal":animal,"stage":"BEHAVIOR","session":session,"dummy":dummy,"check1":c1,"check2":c2,"syringe_id":syringe_id,"label_id":label,"ts":ts0}, sort_keys=True)
qrcode.make(label).save(br/"labels"/f"{animal}_BEH{session}_{label}.png")
append_blinder_registry(br, {"ts_overlay": ts0,"animal":animal,"stage":"BEHAVIOR","session":session,
"dummy":dummy,"check1":c1,"check2":c2,"syringe_id":syringe_id,
"label_id":label,"status":"issued"})
_audit_write(br, "overlay-behavior", animal_id=animal, session=session, label_id=label, syringe_id=syringe_id)
print("[+] BEHAVIOR overlay issued at BLINDER root.")
def cm_to_px(cm, dpi):
return int(round((cm / 2.54) * dpi))
def load_font(paths, size_px):
for p in paths:
if Path(p).exists():
try:
return ImageFont.truetype(p, size_px)
except Exception:
pass
return ImageFont.load_default()
def make_qr(data, version, box_size, border):
qr = qrcode.QRCode(
version=version, # will be increased by fit=True if needed
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=box_size,
border=border,
)
qr.add_data(data)
qr.make(fit=True)
return qr.make_image(fill_color="black", back_color="white").convert("RGBA")
def text_sprite(label, font, bleed=2):
"""Tight text sprite with baseline offset (no clipping)."""
tmp = Image.new("RGBA", (1, 1))
d = ImageDraw.Draw(tmp)
left, top, right, bottom = d.textbbox((0, 0), label, font=font)
w = (right - left) + 2 * bleed
h = (bottom - top) + 2 * bleed
img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.text((bleed - left, bleed - top), label, font=font, fill=(0, 0, 0, 255))
return img
def tile_horizontal(canvas, sprite, y, gap_px=12, x_start=0, x_end=None):
"""Repeat sprite left→right across [x_start, x_end). Corner-safe via bounds."""
W, _ = canvas.size
if x_end is None:
x_end = W
step = sprite.width + gap_px
origin = 0
first = x_start + ((-(x_start - origin)) % step)
x = first
while x + sprite.width <= x_end:
canvas.alpha_composite(sprite, (x, y))
x += step
def tile_vertical(canvas, sprite_rot, x, gap_px=12, y_start=0, y_end=None):
"""Repeat sprite top→bottom across [y_start, y_end). Corner-safe via bounds."""
_, H = canvas.size
if y_end is None:
y_end = H
step = sprite_rot.height + gap_px
origin = 0
first = y_start + ((-(y_start - origin)) % step)
y = first
while y + sprite_rot.height <= y_end:
canvas.alpha_composite(sprite_rot, (x, y))
y += step
def build_qr_with_border_labels(
data, label, font,
inner_gap, outer_gap, repeat_gap, corner_gap,
qr_version, box_size, quiet_border
):