-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtraitinheritanceexplorer.py
More file actions
6306 lines (5519 loc) · 272 KB
/
traitinheritanceexplorer.py
File metadata and controls
6306 lines (5519 loc) · 272 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
"""
Trait Inheritance Explorer Module
Provides the Trait Inheritance Explorer interface for browsing plant breeding
history, visualizing family trees, and detecting Mendelian laws.
Features:
- Plant archive browsing and visualization
- Family tree rendering with trait inheritance
- Mendelian law detection (Dominance, Segregation, Independent Assortment)
- Pedigree analysis and sibling comparison
- CSV export of breeding experiments
- Genotype-phenotype relationship exploration
The module contains:
1. Standalone law-testing functions for integration with main app
2. TraitInheritanceExplorer class for the visual interface
"""
# ============================================================================
# Imports
# ============================================================================
# Standard library
import functools
import math
import os
import platform
import re
import traceback
from collections import Counter
from itertools import combinations
# Third-party
import tkinter as tk
from tkinter import messagebox, ttk
try:
from PIL import Image, ImageOps, ImageTk as _PILImageTk
_PIL_AVAILABLE = True
except ImportError:
_PIL_AVAILABLE = False
# Local
from icon_loader import *
# ============================================================================
# Configuration
# ============================================================================
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
EXPORT_DIR = os.path.join(ROOT_DIR, "export")
# Create export directory
try:
os.makedirs(EXPORT_DIR, exist_ok=True)
except Exception:
pass
# ============================================================================
# Standalone Mendelian Law Testing Functions
# ============================================================================
import functools
import math
import os
import re
import traceback
from collections import Counter
from itertools import combinations
import platform
import tkinter as tk
from tkinter import messagebox, ttk
from icon_loader import *
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
EXPORT_DIR = os.path.join(ROOT_DIR, "export")
try:
os.makedirs(EXPORT_DIR, exist_ok=True)
except Exception:
pass
def _test_mendelian_laws_now(self):
try:
# keep archive in sync (same prep as TIE)
if hasattr(self, "_seed_archive_safe"):
self._seed_archive_safe()
# backfill helper exists on TraitInheritanceExplorer, not on the dict archive
try:
if hasattr(self, "_archive_backfill_cross_parents"):
self._archive_backfill_cross_parents()
except Exception:
pass
# call the shared law-testing function
from traitinheritanceexplorer import test_mendelian_laws
test_mendelian_laws(self, archive=getattr(self, "archive", None), pid=getattr(self, "law_context_pid", None), allow_credit=True, toast=True)
except Exception as e:
try:
self._toast(f"Law test failed: {e}", level="warn")
except Exception:
print("Law test failed:", e)
def test_mendelian_laws(app, archive=None, pid=None, allow_credit=True, toast=True, target_law=None):
"""Run Mendelian-law detection using the *exact same rules* as the Trait Inheritance Explorer.
This is the single shared entry point used by:
- the main UI "Unlock" button (GardenApp)
- the Trait Inheritance Explorer export/test button
Returns: {"law1": bool, "law2": bool, "law3": bool, "new": ["law1","law2","law3"]}
Also updates app.law*_ever_discovered and app.law2_ratio_ui / app.law3_ratio_ui, and refreshes
app._update_law_status_label() when present.
"""
# Use existing archive unless provided
archive = archive if archive is not None else getattr(app, "archive", None)
if not isinstance(archive, dict):
return {"law1": False, "law2": False, "law3": False, "new": []}
plants = archive.get("plants", {})
if not isinstance(plants, dict) or not plants:
return {"law1": False, "law2": False, "law3": False, "new": []}
# Respect genotype reveal session rule (no credit once alleles were revealed)
revealed = bool(getattr(app, "_genotype_revealed", False))
if revealed and allow_credit:
# Genotype was peeked — can still detect for display but don't credit
allow_credit = False
# If pid wasn't provided, try to infer it like the main UI would.
if pid in (None, "", -1):
pid = getattr(app, "law_context_pid", None)
# Robust snapshot fetch (string/int keys)
def _get_snap_local(pid_):
if pid_ in (None, "", -1):
return None
# try exact
if pid_ in plants:
return plants.get(pid_)
# try str/int forms
try:
si = str(pid_)
if si in plants:
return plants.get(si)
except Exception:
pass
try:
ii = int(pid_)
if ii in plants:
return plants.get(ii)
except Exception:
pass
return None
snap = _get_snap_local(pid)
if not snap:
return {"law1": False, "law2": False, "law3": False, "new": []}
# ---- helper: parent extraction (same as TraitInheritanceExplorer._parents_from_snapshot) ----
def _parents_from_snapshot(snap_obj):
if not isinstance(snap_obj, dict):
return (getattr(snap_obj, "mother_id", None), getattr(snap_obj, "father_id", None))
MOTHER_KEYS = [
"mother_id","mother","maternal_id","mom_id",
"female_parent","female_id","dam_id",
"seed_parent_id","seed_parent","maternal_pid","female",
]
FATHER_KEYS = [
"father_id","father","paternal_id","dad_id",
"male_parent","male_id","sire_id",
"pollen_donor_id","pollen_source_id","pollen_parent_id","pollinator_id",
"pollen_donor","pollen_source","pollen",
]
NESTED = ["pollination","cross","cross_info","seed_source","source_pod","source_cross","repro","reproduction"]
def pick(dct, keys):
for k in keys:
if isinstance(dct, dict) and k in dct and dct[k] not in (None, "", -1):
return dct[k]
return None
mid_ = pick(snap_obj, MOTHER_KEYS)
fid_ = pick(snap_obj, FATHER_KEYS)
if mid_ is None or fid_ is None:
for nk in NESTED:
nd = snap_obj.get(nk)
if isinstance(nd, dict):
if mid_ is None:
mid_ = pick(nd, MOTHER_KEYS)
if fid_ is None:
fid_ = pick(nd, FATHER_KEYS)
return (mid_, fid_)
# ---- helpers used by the TIE law logic ----
def _g(s, key, default=None):
if isinstance(s, dict):
return s.get(key, default)
try:
return getattr(s, key, default)
except Exception:
return default
try:
mid, fid = _parents_from_snapshot(snap)
except Exception:
mid, fid = (_g(snap, "mother_id", None), _g(snap, "father_id", None))
try:
traits = dict(snap.get("traits", {}) or {}) if isinstance(snap, dict) else dict(getattr(snap, "traits", {}) or {})
except Exception:
traits = {}
# Snapshot lookup helper for IDs
def _get_arch_snap(pid_):
return _get_snap_local(pid_)
# ---------------------- BEGIN: copied TIE law-test logic ----------------------
# (This block is intentionally mirrored from TraitInheritanceExplorer._export_selected_traits)
def _geno_from_snap_law2(s):
try:
if isinstance(s, dict):
g = s.get("genotype") or {}
else:
g = getattr(s, "genotype", None) or {}
except Exception:
g = {}
return dict(g) if isinstance(g, dict) else {}
def _law1_cross_signature_for_trait(m_snap, f_snap, locus):
"""Canonical cross signature (order-independent) for Law 1 tests."""
m_geno = _geno_from_snap_law2(m_snap)
f_geno = _geno_from_snap_law2(f_snap)
if not isinstance(m_geno, dict) or not isinstance(f_geno, dict):
return None
m_pair = m_geno.get(locus)
f_pair = f_geno.get(locus)
if not (isinstance(m_pair, (list, tuple)) and len(m_pair) >= 2):
return None
if not (isinstance(f_pair, (list, tuple)) and len(f_pair) >= 2):
return None
m_a1, m_a2 = m_pair[0], m_pair[1]
f_a1, f_a2 = f_pair[0], f_pair[1]
if not (m_a1 == m_a2 and f_a1 == f_a2):
return None
if m_a1 == f_a1:
return None
def _canon(pair):
a1, a2 = pair[0], pair[1]
return "".join(sorted([str(a1), str(a2)]))
return tuple(sorted([_canon(m_pair), _canon(f_pair)]))
revealed = bool(getattr(app, "_genotype_revealed", False))
law1_discovered = False
law1_reason = ""
law1_trait_name = ""
law1_dominant_value = "" # the phenotype value that is dominant
law1_all_valid = [] # all (trait_key, dominant_value) pairs that qualify
law2_discovered = False
law2_reason = ""
law2_ratio_str = ""
law2_trait_name = ""
law2_dominant_value = "" # the phenotype value that appears ~75% of the time
law2_all_valid = [] # all (trait_key, dominant_value) pairs that qualify
law2_all_valid_ratios = {} # trait_key -> ratio_str for the qualifying traits
law3_discovered = False
law3_reason = ""
law3_ratio_str = ""
law3_trait_pair = ()
law3_all_valid_pairs = [] # all (tk1, tk2) pairs that pass the chi-square test
law3_all_valid_pairs_ratios = {} # frozenset({tk1,tk2}) -> ratio string
trait_to_locus = {
"flower_color": "A",
"pod_color": "Gp",
"seed_color": "I",
"seed_shape": "R",
"plant_height": "Le",
}
law_trait_keys = ["flower_color", "pod_color", "seed_color", "seed_shape", "plant_height"]
arch_plants = plants
# ---------------- Law 1 (Dominance) ----------------
if not revealed:
mother_snap = _get_arch_snap(mid)
father_snap = _get_arch_snap(fid)
if mother_snap and father_snap and mid not in (None, "", -1) and fid not in (None, "", -1) and str(mid) != str(fid):
try:
m_traits = dict(mother_snap.get("traits", {}) or {}) if isinstance(mother_snap, dict) else dict(getattr(mother_snap, "traits", {}) or {})
except Exception:
m_traits = {}
try:
f_traits = dict(father_snap.get("traits", {}) or {}) if isinstance(father_snap, dict) else dict(getattr(father_snap, "traits", {}) or {})
except Exception:
f_traits = {}
m_geno = _geno_from_snap_law2(mother_snap)
f_geno = _geno_from_snap_law2(father_snap)
dominant_candidates = []
for tk in law_trait_keys:
cv = str(traits.get(tk, "")).strip()
mv = str(m_traits.get(tk, "")).strip()
fv = str(f_traits.get(tk, "")).strip()
if not (cv and mv and fv and mv != fv and (cv == mv or cv == fv)):
continue
loc = trait_to_locus.get(tk)
if not loc:
continue
cross_sig = _law1_cross_signature_for_trait(mother_snap, father_snap, loc)
if cross_sig is None:
continue
m_pair = m_geno.get(loc)
f_pair = f_geno.get(loc)
if not (isinstance(m_pair, (list, tuple)) and len(m_pair) >= 2 and isinstance(f_pair, (list, tuple)) and len(f_pair) >= 2):
continue
m_a1, m_a2 = m_pair[0], m_pair[1]
f_a1, f_a2 = f_pair[0], f_pair[1]
if not (m_a1 == m_a2 and f_a1 == f_a2):
continue
if m_a1 == f_a1:
continue
same_pheno_total = 0
for _cid, csnap in arch_plants.items():
if isinstance(csnap, dict) and not csnap.get("alive", True):
continue
smid, sfid = _parents_from_snapshot(csnap if isinstance(csnap, dict) else {})
if smid in (None, "", -1) or sfid in (None, "", -1):
continue
m_snap2 = _get_arch_snap(smid)
f_snap2 = _get_arch_snap(sfid)
if not m_snap2 or not f_snap2:
continue
sig2 = _law1_cross_signature_for_trait(m_snap2, f_snap2, loc)
if sig2 is None or sig2 != cross_sig:
continue
try:
s_traits = csnap.get("traits", {}) if isinstance(csnap, dict) else getattr(csnap, "traits", {}) or {}
except Exception:
s_traits = {}
sv = str(s_traits.get(tk, "")).strip()
if sv == cv:
same_pheno_total += 1
if same_pheno_total < LAW1_MIN_F1:
continue
dominant_candidates.append((tk, cv, mv, fv, same_pheno_total))
if dominant_candidates:
law1_discovered = True
tk, cv, mv, fv, sib_count = dominant_candidates[0]
law1_trait_name = tk
law1_dominant_value = cv # cv is the child's phenotype = the dominant value
# store ALL valid (trait_key, dominant_value) pairs for wizard validation
law1_all_valid = [(t, c) for t, c, *_ in dominant_candidates]
trait_label = tk.replace("_", " ")
law1_reason = (
f"Observed in cross #{mid} × #{fid} for trait '{trait_label}': "
f"parents {mv} × {fv} → offspring {cv} "
f"in at least {sib_count + 1} F1 plants (including this plant), "
f"from true-breeding parental lines."
)
# ---------------- Law 2 (Segregation) ----------------
try:
has_parents = (mid not in (None, "", -1) and fid not in (None, "", -1))
except Exception:
has_parents = False
parent_snap_m = _get_arch_snap(mid) if has_parents else None
parent_snap_f = _get_arch_snap(fid) if has_parents else None
def _law2_family_signature(parent_snap, gp_m, gp_f, locus):
parent_geno = _geno_from_snap_law2(parent_snap)
if not isinstance(parent_geno, dict):
return None
p_pair = parent_geno.get(locus)
if not (isinstance(p_pair, (list, tuple)) and len(p_pair) >= 2):
return None
pa1, pa2 = p_pair[0], p_pair[1]
if pa1 == pa2:
return None
gm_geno = _geno_from_snap_law2(gp_m)
gf_geno = _geno_from_snap_law2(gp_f)
if not isinstance(gm_geno, dict) or not isinstance(gf_geno, dict):
return None
m_pair = gm_geno.get(locus)
f_pair = gf_geno.get(locus)
if not (isinstance(m_pair, (list, tuple)) and len(m_pair) >= 2):
return None
if not (isinstance(f_pair, (list, tuple)) and len(f_pair) >= 2):
return None
m_a1, m_a2 = m_pair[0], m_pair[1]
f_a1, f_a2 = f_pair[0], f_pair[1]
if not (m_a1 == m_a2 and f_a1 == f_a2):
return None
# REMOVED: if m_a1 == f_a1: return None
# This check was too restrictive - it rejected selfed true-breeding lines.
# Mendel used selfing to establish homozygous lines, then crossed them.
# As long as grandparents are homozygous and parent is heterozygous,
# we have valid Mendelian segregation regardless of whether grandparents
# came from AA × aa or from selfed AA × AA lines.
def _canon(pair):
a1, a2 = pair[0], pair[1]
return "".join(sorted([str(a1), str(a2)]))
return tuple(sorted([_canon(m_pair), _canon(f_pair)]))
def _get_grandparents_for_parent(parent_snap):
try:
pmid, pfid = _parents_from_snapshot(parent_snap)
except Exception:
pmid, pfid = (_g(parent_snap, "mother_id", None), _g(parent_snap, "father_id", None))
gp_m = _get_arch_snap(pmid)
gp_f = _get_arch_snap(pfid)
return gp_m, gp_f
gp_m = gp_f = None
parent_snap = None
parent_traits = None
# Choose a representative "F1 parent" for Law2/3: prefer selfing if possible else sib-mating
if not revealed and parent_snap_m and parent_snap_f:
# If selfed: mother==father -> parent is that plant
if str(mid) == str(fid):
parent_snap = parent_snap_m
else:
# otherwise pick mother as "parent" reference; Law2/3 code uses family signatures anyway
parent_snap = parent_snap_m
try:
parent_traits = dict(parent_snap.get("traits", {}) or {}) if isinstance(parent_snap, dict) else dict(getattr(parent_snap, "traits", {}) or {})
except Exception:
parent_traits = {}
gp_m, gp_f = _get_grandparents_for_parent(parent_snap)
if not revealed and parent_snap and gp_m and gp_f:
parent_geno = _geno_from_snap_law2(parent_snap)
# need a valid heterozygous locus with opposite homozygous grandparents and enough F2
for tk in law_trait_keys:
loc = trait_to_locus.get(tk)
if not loc:
continue
fam_sig = _law2_family_signature(parent_snap, gp_m, gp_f, loc)
if fam_sig is None:
continue
# collect F2 offspring for this family
dom_pheno = str(parent_traits.get(tk, "")).strip().lower()
counts = {"dom": 0, "rec": 0}
total = 0
for _cid2, csnap2 in arch_plants.items():
if isinstance(csnap2, dict) and not csnap2.get("alive", True):
continue
smid2, sfid2 = _parents_from_snapshot(csnap2 if isinstance(csnap2, dict) else {})
if smid2 in (None, "", -1) or sfid2 in (None, "", -1):
continue
# F2 must come from Aa×Aa parents belonging to this family signature
pm = _get_arch_snap(smid2)
pf = _get_arch_snap(sfid2)
if not pm or not pf:
continue
# parent pair must be heterozygous at loc
pgm = _geno_from_snap_law2(pm)
pgf = _geno_from_snap_law2(pf)
pair_m = pgm.get(loc)
pair_f = pgf.get(loc)
if not (isinstance(pair_m, (list, tuple)) and len(pair_m) >= 2 and isinstance(pair_f, (list, tuple)) and len(pair_f) >= 2):
continue
if len(set(pair_m[:2])) != 2 or len(set(pair_f[:2])) != 2:
continue
# grandparents for each parent must match family signature
gp_m2, gp_f2 = _get_grandparents_for_parent(pm)
gp_m3, gp_f3 = _get_grandparents_for_parent(pf)
sig_m = _law2_family_signature(pm, gp_m2, gp_f2, loc) if (gp_m2 and gp_f2) else None
sig_f = _law2_family_signature(pf, gp_m3, gp_f3, loc) if (gp_m3 and gp_f3) else None
if sig_m != fam_sig or sig_f != fam_sig:
continue
# classify phenotype
try:
ctraits2 = csnap2.get("traits", {}) if isinstance(csnap2, dict) else getattr(csnap2, "traits", {}) or {}
except Exception:
ctraits2 = {}
ph = str(ctraits2.get(tk, "")).strip().lower()
if not ph:
continue
total += 1
if ph == dom_pheno:
counts["dom"] += 1
else:
counts["rec"] += 1
if total < LAW2_MIN_N:
continue
dom_frac = counts["dom"] / float(total) if total else 0.0
if LAW2_DOM_FRAC_MIN <= dom_frac <= LAW2_DOM_FRAC_MAX:
law2_discovered = True
trait_label = tk.replace("_", " ")
law2_trait_name = tk # store raw key so wizard can compare directly
law2_dominant_value = dom_pheno
# ratio string: dominant:recessive, scaled so recessive=1 if possible
try:
d = counts["dom"]
r = counts["rec"]
if r > 0:
x = d / float(r)
x_str = (f"{x:.2f}").replace(".", ",")
law2_ratio_str = f"{x_str}:1"
else:
law2_ratio_str = f"{d}:{r}"
except Exception:
law2_ratio_str = ""
law2_reason = (
f"Observed in F2 offspring (N = {total}) for trait '{trait_label}': "
f"dominant vs recessive phenotypes appear close to 3:1."
)
law2_all_valid.append((tk, dom_pheno))
law2_all_valid_ratios[tk] = law2_ratio_str
# don't break — collect all valid traits
# ---------------- Law 3 (Independent Assortment) ----------------
if not revealed and parent_snap and gp_m and gp_f and arch_plants and not law3_discovered:
parent_geno = _geno_from_snap_law2(parent_snap)
def _law3_family_signature(parent_snap_, gp_m_, gp_f_, loc1, loc2):
parent_geno_ = _geno_from_snap_law2(parent_snap_)
if not isinstance(parent_geno_, dict):
return None
p1 = parent_geno_.get(loc1)
p2 = parent_geno_.get(loc2)
if not (isinstance(p1, (list, tuple)) and len(p1) >= 2 and isinstance(p2, (list, tuple)) and len(p2) >= 2):
return None
if len(set(p1[:2])) != 2 or len(set(p2[:2])) != 2:
return None
gm = _geno_from_snap_law2(gp_m_)
gf = _geno_from_snap_law2(gp_f_)
if not isinstance(gm, dict) or not isinstance(gf, dict):
return None
def _canon(pair):
a1, a2 = pair[0], pair[1]
return "".join(sorted([str(a1), str(a2)]))
key1 = tuple(sorted([_canon(gm.get(loc1, ('?','?'))), _canon(gf.get(loc1, ('?','?')))]))
key2 = tuple(sorted([_canon(gm.get(loc2, ('?','?'))), _canon(gf.get(loc2, ('?','?')))]))
return tuple(sorted([(loc1, key1), (loc2, key2)]))
from itertools import combinations
from collections import Counter
candidate_traits = [tk for tk in law_trait_keys if tk in (parent_traits or {}) and trait_to_locus.get(tk)]
for tk1, tk2 in combinations(candidate_traits, 2):
if {"pod_color", "seed_shape"} == {tk1, tk2}:
continue
loc1 = trait_to_locus.get(tk1)
loc2 = trait_to_locus.get(tk2)
if not loc1 or not loc2:
continue
pair1 = parent_geno.get(loc1)
pair2 = parent_geno.get(loc2)
if not (isinstance(pair1, (list, tuple)) and len(pair1) >= 2 and isinstance(pair2, (list, tuple)) and len(pair2) >= 2):
continue
if len(set(pair1[:2])) != 2 or len(set(pair2[:2])) != 2:
continue
fam_sig = _law3_family_signature(parent_snap, gp_m, gp_f, loc1, loc2)
if fam_sig is None:
continue
combo_counts = Counter()
dom1 = str((parent_traits or {}).get(tk1, "")).strip().lower()
dom2 = str((parent_traits or {}).get(tk2, "")).strip().lower()
for _cid2, csnap2 in arch_plants.items():
if isinstance(csnap2, dict) and not csnap2.get("alive", True):
continue
smid2, sfid2 = _parents_from_snapshot(csnap2 if isinstance(csnap2, dict) else {})
if smid2 in (None, "", -1) or sfid2 in (None, "", -1):
continue
pm = _get_arch_snap(smid2)
pf = _get_arch_snap(sfid2)
if not pm or not pf:
continue
# both parents must belong to same dihybrid family signature
gp_m2, gp_f2 = _get_grandparents_for_parent(pm)
gp_m3, gp_f3 = _get_grandparents_for_parent(pf)
sig_m = _law3_family_signature(pm, gp_m2, gp_f2, loc1, loc2) if (gp_m2 and gp_f2) else None
sig_f = _law3_family_signature(pf, gp_m3, gp_f3, loc1, loc2) if (gp_m3 and gp_f3) else None
if sig_m != fam_sig or sig_f != fam_sig:
continue
try:
ctraits2 = csnap2.get("traits", {}) if isinstance(csnap2, dict) else getattr(csnap2, "traits", {}) or {}
except Exception:
ctraits2 = {}
ph1 = str(ctraits2.get(tk1, "")).strip().lower()
ph2 = str(ctraits2.get(tk2, "")).strip().lower()
if not ph1 or not ph2:
continue
a = "D" if ph1 == dom1 else "r"
b = "D" if ph2 == dom2 else "r"
combo_counts[(a, b)] += 1
needed_keys = [("D","D"), ("D","r"), ("r","D"), ("r","r")]
total = sum(combo_counts.values())
if total < LAW3_MIN_N:
continue
if any(combo_counts[k] == 0 for k in needed_keys):
continue
expected_ratios = {("D","D"): 9, ("D","r"): 3, ("r","D"): 3, ("r","r"): 1}
chi2 = 0.0
for k in needed_keys:
obs = combo_counts[k]
exp = expected_ratios[k] * (total / 16.0)
if exp <= 0:
continue
diff = obs - exp
chi2 += (diff * diff) / exp
if chi2 <= LAW3_CHI2_MAX:
law3_discovered = True
trait_label1 = tk1.replace("_", " ")
trait_label2 = tk2.replace("_", " ")
try:
vals = [combo_counts[k] for k in needed_keys]
total2 = sum(vals)
if total2 > 0:
scaled = [(v / total2) * 16.0 for v in vals]
pretty_parts = [f"{x:.1f}".replace(".", ",") for x in scaled]
law3_ratio_str = " : ".join(pretty_parts) + " (scaled to 16)"
else:
law3_ratio_str = ""
law3_trait_pair = (trait_label1, trait_label2)
except Exception:
law3_ratio_str = ""
law3_trait_pair = (trait_label1, trait_label2)
# accumulate ALL valid pairs (for wizard validation)
law3_all_valid_pairs.append((tk1, tk2))
law3_all_valid_pairs_ratios[frozenset({tk1, tk2})] = law3_ratio_str
try:
cross_label = f"selfed F1 plant #{mid}" if str(mid) == str(fid) else f"F1 cross #{mid}×{fid}"
except Exception:
cross_label = "F1 cross #?"
law3_reason = (
f"Observed in dihybrid F2 offspring of {cross_label} "
f"for traits '{trait_label1}' and '{trait_label2}': "
f"the four phenotype combinations appear in an approximately 9:3:3:1 ratio (N = {total})."
)
# don't break — keep scanning to collect all valid pairs
# ---------------- Apply discoveries to app + UI ----------------
new = []
if not revealed:
if law1_discovered and not getattr(app, "law1_ever_discovered", False) \
and (target_law is None or target_law == 1):
setattr(app, "law1_ever_discovered", True)
setattr(app, "law1_first_plant", pid)
new.append("law1")
if toast and hasattr(app, "_toast"):
try:
app._toast(f"Law 1 (Dominance) discovered from plant #{pid}!", level="info")
except Exception:
pass
if law2_discovered and not getattr(app, "law2_ever_discovered", False) \
and (target_law is None or target_law == 2):
setattr(app, "law2_ever_discovered", True)
setattr(app, "law2_first_plant", pid)
new.append("law2")
if toast and hasattr(app, "_toast"):
try:
app._toast(f"Law 2 (Segregation) discovered from plant #{pid}!", level="info")
except Exception:
pass
if law3_discovered and not getattr(app, "law3_ever_discovered", False) \
and (target_law is None or target_law == 3):
setattr(app, "law3_ever_discovered", True)
setattr(app, "law3_first_plant", pid)
new.append("law3")
if toast and hasattr(app, "_toast"):
try:
app._toast(f"Law 3 (Independent Assortment) discovered from plant #{pid}!", level="info")
except Exception:
pass
# Push ratio info to the main app for the top-bar UI
try:
if not revealed:
if law2_discovered:
if not law2_ratio_str:
# best-effort fallback
law2_ratio_str = "Ratio __:__"
setattr(app, "law2_ratio_ui", law2_ratio_str)
if law3_discovered and law3_ratio_str:
setattr(app, "law3_ratio_ui", law3_ratio_str)
if hasattr(app, "_update_law_status_label"):
app._update_law_status_label()
except Exception:
pass
# Stash law ratio info into the archive snapshot
try:
if isinstance(snap, dict):
if law2_discovered and law2_ratio_str:
snap["law2_ratio"] = law2_ratio_str
if law2_trait_name:
snap["law2_trait"] = law2_trait_name
if law3_discovered and law3_ratio_str:
snap["law3_ratio"] = law3_ratio_str
if law3_trait_pair:
snap["law3_traits"] = f"{law3_trait_pair[0]} × {law3_trait_pair[1]}"
except Exception:
pass
return {
"law1": bool(law1_discovered),
"law2": bool(law2_discovered),
"law3": bool(law3_discovered),
"new": new,
# expose which specific trait/pair triggered each law (used by wizard)
"law1_trait": law1_trait_name if law1_discovered else None,
"law1_dominant_value": law1_dominant_value if law1_discovered else None,
"law1_all_valid": law1_all_valid if law1_discovered else [],
"law2_trait": law2_trait_name if law2_discovered else None,
"law2_dominant_value": law2_dominant_value if law2_discovered else None,
"law2_all_valid": law2_all_valid if law2_discovered else [],
"law2_all_valid_ratios": law2_all_valid_ratios if law2_discovered else {},
"law3_traits": tuple(law3_trait_pair) if (law3_discovered and law3_trait_pair) else None,
"law3_all_valid_pairs": law3_all_valid_pairs if law3_discovered else [],
"law3_all_valid_pairs_ratios": law3_all_valid_pairs_ratios if law3_discovered else {},
}
# =============================================================================
# Mendelian law unlock thresholds (single source of truth)
# =============================================================================
# Law 1 (Dominance): how many phenotype-only F1 offspring (same phenotype) needed
LAW1_MIN_F1 = 16
# Law 2 (Segregation, ~3:1): minimum F2 sample size and acceptable dominant fraction band
LAW2_MIN_N = 65
LAW2_DOM_FRAC_MIN = 0.677 # 2.1:1 (2.1/3.1)
LAW2_DOM_FRAC_MAX = 0.796 # 3.9:1 (3.9/4.9)
# Law 3 (Independent Assortment, ~9:3:3:1): minimum dihybrid F2 sample size and chi-square threshold
LAW3_MIN_N = 80
LAW3_CHI2_MAX = 4.0
class TraitInheritanceExplorer(tk.Toplevel):
BG = "#0c1a21"
PANEL = "#0f2230"
CARD = "#102633"
FG = "#e8f0f5"
MUTED = "#a8bcc9"
ACCENT = "#1f6aa5"
PAD = 10
# --- Background tints for pods (applied to whole pod card) ---
POD_TINT_GREEN = "#2d5145" # slightly less green
POD_TINT_YELLOW = "#6a5a16" # strong yellow/olive
def _pod_tint_from_color(self, color_str):
s = str(color_str or "").lower()
if "green" in s:
return self.POD_TINT_GREEN
if "yellow" in s:
return self.POD_TINT_YELLOW
return self.CARD
def _on_canvas_node_click(self, event=None, source_canvas=None):
c = source_canvas if source_canvas is not None else self.canvas
try:
item = c.find_closest(event.x, event.y)
tags = c.gettags(item)
except Exception:
return
pid = None
for t in tags:
if t.startswith("node_"):
pid = t.split("_", 12)[1]
break
if pid is None:
return
# sync list selection
try:
ids = [str(x) for x in self._ids]
if str(pid) in ids:
idx = ids.index(str(pid))
self.listbox.selection_clear(0, "end")
self.listbox.selection_set(idx)
self.listbox.see(idx)
except Exception:
pass
if str(pid) == str(getattr(self, 'current_pid', None)):
self._render_pid(str(pid))
else:
self._render_preview(str(pid))
def __init__(self, parent_window, app, default_pid=None):
tk.Toplevel.__init__(self, parent_window)
self.app = app
self.title("Trait Inheritance Explorer")
self.configure(bg=self.BG)
self.minsize(1024, 600)
if not hasattr(self.app, "archive") or not isinstance(getattr(self.app, "archive", None), dict):
self.app.archive = {"plants": {}}
elif "plants" not in self.app.archive or not isinstance(self.app.archive["plants"], dict):
self.app.archive["plants"] = dict(self.app.archive.get("plants") or {})
tb = tk.Frame(self, bg=self.BG)
tb.pack(fill="x", padx=self.PAD, pady=(self.PAD, 4))
# --- Cross-platform button styling: macOS Aqua ignores tk.Button colors ---
IS_MAC = (platform.system() == "Darwin")
self._is_mac = IS_MAC
# Force a theme that allows us to control button colors on macOS
self._style = ttk.Style(self)
if IS_MAC:
try:
self._style.theme_use("clam")
except tk.TclError:
pass
# Toolbar button style (neutral, matches dark panel)
self._style.configure(
"Toolbar.TButton",
padding=(10, 4),
foreground=self.FG,
background=self.CARD
)
self._style.map(
"Toolbar.TButton",
foreground=[("active", self.FG), ("pressed", self.FG)],
background=[("active", self.CARD), ("pressed", self.CARD)],
)
# Action button style (blue accent — Best Fit, etc.)
self._style.configure(
"Action.TButton",
padding=(10, 4),
foreground=self.FG,
background="#1e4d6b",
)
self._style.map(
"Action.TButton",
foreground=[("active", self.FG), ("pressed", self.FG)],
background=[("active", "#2a6080"), ("pressed", "#163c55")],
)
# Nav button style (slightly lighter blue — pagination ◀ ▶)
self._style.configure(
"Nav.TButton",
padding=(8, 3),
foreground="#ffffff",
background="#2a5a7a",
)
self._style.map(
"Nav.TButton",
foreground=[("active", "#ffffff"), ("pressed", "#ffffff"),
("disabled", "#607090")],
background=[("active", "#3a6e8e"), ("pressed", "#1e4a62"),
("disabled", "#1a3040")],
)
def _mkbtn(parent, text, command, **extra):
if IS_MAC:
# On macOS use ttk + styled theme (reliable)
style = extra.pop("style", "Toolbar.TButton")
return ttk.Button(parent, text=text, command=command, style=style)
else:
# On Windows/Linux classic tk.Button styling is fine
kw = dict(bg=self.CARD, fg=self.FG, relief="groove")
kw.update(extra)
kw.pop("style", None)
return tk.Button(parent, text=text, command=command, **kw)
_mkbtn(tb, "Export Plant", self._export_selected_traits).pack(side="left")
tk.Label(tb, text=" Find #", bg=self.BG, fg=self.FG).pack(side="left", padx=(12,4))
self.find_entry = tk.Entry(tb, width=5)
self.find_entry.pack(side="left", ipadx=3)
_mkbtn(tb, "Go", self._find_and_select).pack(side="left", padx=(4,0))
pw = ttk.Panedwindow(self, orient="horizontal")
pw.pack(fill="both", expand=True, padx=self.PAD, pady=(4, self.PAD))
left = tk.Frame(pw, bg=self.PANEL, highlightthickness=1, highlightbackground="#153242")
pw.add(left, weight=1)
left_header = tk.Frame(left, bg=self.PANEL)
left_header.pack(fill="x", padx=self.PAD, pady=(self.PAD, 6))
self.lbl_left_title = tk.Label(left_header, text="—", bg=self.PANEL, fg=self.FG, font=("Segoe UI", 14, "bold"))
self.lbl_left_title.pack(anchor="w")
self.lbl_left_parents = tk.Label(left_header, text="", bg=self.PANEL, fg=self.MUTED, font=("Segoe UI", 12))
self.lbl_left_parents.pack(anchor="w", pady=(2,0))
# ✅ Proper traits box for the explorer
traits_box = tk.LabelFrame(left, text="Traits", bg=self.PANEL, fg=self.FG, labelanchor="nw")
traits_box.pack(fill="both", expand=True, padx=self.PAD, pady=(0, self.PAD))
self.traits_container = tk.Frame(traits_box, bg=self.PANEL)
self.traits_container.pack(fill="both", expand=True, padx=6, pady=6)
list_box = tk.LabelFrame(left, text="Archived plants", bg=self.PANEL, fg=self.FG, labelanchor="nw")
list_box.pack(fill="both", expand=False, padx=self.PAD, pady=(0, self.PAD))
list_wrap = tk.Frame(list_box, bg=self.PANEL)
list_wrap.pack(fill="both", expand=True, padx=6, pady=6)
self.listbox = tk.Listbox(list_wrap, height=10)
self.listbox.pack(side="left", fill="both", expand=True)
self.listbox.bind("<<ListboxSelect>>", self._on_select)
sb = tk.Scrollbar(list_wrap, command=self.listbox.yview)
sb.pack(side="right", fill="y")
self.listbox.config(yscrollcommand=sb.set)
# ── Right pane: fixed lineage (left) + switching tabs (right) ───────
right_pane = tk.Frame(pw, bg=self.PANEL, highlightthickness=1, highlightbackground="#153242")
pw.add(right_pane, weight=5)
# Horizontal split: lineage always-visible on left, tab switcher on right
right_split = tk.PanedWindow(right_pane, orient="horizontal", bg=self.PANEL,
sashwidth=4, sashrelief="flat", handlesize=0)
right_split.pack(fill="both", expand=True)
self._right_split = right_split # saved so _auto_resize_window can adjust sash
# ── Fixed lineage pane (left — always visible) ────────────────────────
lineage_pane = tk.Frame(right_split, bg="#0b1a22", highlightthickness=0)
right_split.add(lineage_pane, width=500)
canvas_frame = tk.Frame(lineage_pane, bg="#0b1a22", highlightthickness=0)
canvas_frame.pack(fill="both", expand=True, padx=self.PAD, pady=self.PAD)
self.canvas = tk.Canvas(canvas_frame, bg="#0b1a22", highlightthickness=0)
_tree_vscroll = tk.Scrollbar(canvas_frame, orient="vertical", command=self.canvas.yview)
_tree_hscroll = tk.Scrollbar(canvas_frame, orient="horizontal", command=self.canvas.xview)
self.canvas.configure(yscrollcommand=_tree_vscroll.set, xscrollcommand=_tree_hscroll.set)
_tree_vscroll.pack(side="right", fill="y")