-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsplicecraft.py
More file actions
10305 lines (9176 loc) · 432 KB
/
splicecraft.py
File metadata and controls
10305 lines (9176 loc) · 432 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
"""
splicecraft.py
==============
SpliceCraft — terminal circular plasmid map viewer.
Features:
- Fetch any GenBank record by accession (pUC19 = L09137)
- Load local .gb / .gbk (GenBank) or .dna (SnapGene) files
- Circular map with per-strand feature rings and arrowheads
- Rotate origin freely with ← → keys or mouse scroll
- Click map to select feature; click sidebar row to highlight on map
- Feature detail panel
- Plasmid library panel (left, SnapGene-style collection, persistent JSON)
- DNA sequence viewer / editor (bottom, press e to edit, Ctrl+S to save)
- CDS amino acid translation shown on feature selection
Run standalone:
python3 splicecraft.py
python3 splicecraft.py L09137 # fetch pUC19 on launch
python3 splicecraft.py myplasmid.gb # open local file
"""
import json
import logging
import math
import os
import platform
import re
import sys
import uuid as _uuid
from io import StringIO
from logging.handlers import RotatingFileHandler
from pathlib import Path
__version__ = "0.3.0"
# ── User data directory ────────────────────────────────────────────────────────
# All user-writable state (library, parts bin, primers, .bak files) lives in
# the platform-appropriate data dir:
# Linux: ~/.local/share/splicecraft/
# macOS: ~/Library/Application Support/splicecraft/
# Windows: %APPDATA%\splicecraft\
# Override with $SPLICECRAFT_DATA_DIR (useful for tests and portable installs).
def _user_data_dir() -> Path:
override = os.environ.get("SPLICECRAFT_DATA_DIR")
if override:
p = Path(override).expanduser()
else:
try:
from platformdirs import user_data_dir
p = Path(user_data_dir("splicecraft", appauthor=False, roaming=False))
except ImportError:
p = Path.home() / ".local" / "share" / "splicecraft"
p.mkdir(parents=True, exist_ok=True)
return p
_DATA_DIR = _user_data_dir()
def _migrate_legacy_data() -> None:
"""One-shot migration from Path(__file__).parent → _DATA_DIR.
Idempotent: only copies files whose destination doesn't already exist.
Preserves the source files (copy, not move) so a dev running from the
repo checkout can still use them via $SPLICECRAFT_DATA_DIR."""
import shutil
legacy_root = Path(__file__).parent
if legacy_root.resolve() == _DATA_DIR.resolve():
return # running from the data dir itself (no migration needed)
names = [
"plasmid_library.json", "parts_bin.json", "primers.json",
"plasmid_library.json.bak", "parts_bin.json.bak", "primers.json.bak",
]
migrated = []
for name in names:
src = legacy_root / name
dst = _DATA_DIR / name
if src.exists() and not dst.exists():
try:
shutil.copy2(src, dst)
migrated.append(name)
except OSError:
pass
if migrated:
try:
(_DATA_DIR / ".migrated").write_text("\n".join(migrated))
except OSError:
pass
_migrate_legacy_data()
# ── Dependency check ───────────────────────────────────────────────────────────
_REQUIRED = {
"textual": "textual",
"Bio": "biopython",
}
def _check_deps():
missing = []
for module, package in _REQUIRED.items():
try:
__import__(module)
except ImportError:
missing.append(package)
if missing:
print("Missing dependencies — install with:")
print(f" pip install {' '.join(missing)}")
sys.exit(1)
_check_deps()
# ── Logging ────────────────────────────────────────────────────────────────────
# Borrowed from ScriptoScope: rotating file log with an 8-char session ID prefix
# on every line so multi-run logs are greppable. Default path /tmp/splicecraft.log,
# overridable via $SPLICECRAFT_LOG. UI never sees raw tracebacks — they go here.
_LOG_PATH = os.environ.get("SPLICECRAFT_LOG") or "/tmp/splicecraft.log"
_SESSION_ID = _uuid.uuid4().hex[:8]
class _SessionFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
record.session = _SESSION_ID
return True
_log = logging.getLogger("splicecraft")
_log.setLevel(logging.INFO)
_log.propagate = False
if not _log.handlers:
try:
_handler = RotatingFileHandler(
_LOG_PATH, maxBytes=2 * 1024 * 1024, backupCount=2, encoding="utf-8"
)
_handler.setFormatter(logging.Formatter(
fmt="%(asctime)s [%(session)s] %(levelname)-5s "
"%(name)s.%(funcName)s:%(lineno)d %(message)s"
))
_handler.addFilter(_SessionFilter())
_log.addHandler(_handler)
except OSError:
# Fall back to a no-op handler if /tmp is read-only (rare; shouldn't crash UI)
_log.addHandler(logging.NullHandler())
def _log_startup_banner() -> None:
def _ver(import_name: str) -> str:
try:
mod = __import__(import_name)
return getattr(mod, "__version__", "unknown")
except ImportError:
return "NOT INSTALLED"
_log.info("=" * 60)
_log.info("SpliceCraft session %s starting", _SESSION_ID)
_log.info("python : %s", sys.version.split()[0])
_log.info("platform : %s", platform.platform())
_log.info("textual : %s", _ver("textual"))
_log.info("biopython : %s", _ver("Bio"))
_log.info("log path : %s", _LOG_PATH)
_log.info("=" * 60)
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical, ScrollableContainer
from textual.events import Click, MouseDown, MouseMove, MouseUp, MouseScrollDown, MouseScrollUp
from textual.message import Message
from textual.reactive import reactive
from textual.screen import ModalScreen, Screen
from textual.widget import Widget
from textual.widgets import (
Button, DataTable, Footer, Header, Input, Label, ListItem, ListView,
RadioButton, RadioSet, Select, Static, TabbedContent, TabPane, TextArea,
)
from rich.text import Text
# ── Feature appearance ─────────────────────────────────────────────────────────
# Visually distinct per-feature palette (assigned by feature index, not type)
_FEATURE_PALETTE: list[str] = [
"color(39)", "color(118)", "color(208)", "color(213)", "color(51)",
"color(220)", "color(196)", "color(46)", "color(201)", "color(129)",
"color(166)", "color(33)", "color(226)", "color(160)", "color(87)",
"color(105)", "color(154)", "color(203)", "color(81)", "color(185)",
]
# ── Safe JSON persistence ──────────────────────────────────────────────────────
#
# All user data (plasmid library, parts bin, primer library) goes through
# _safe_save_json which:
# 1. Backs up the existing file to *.bak BEFORE overwriting
# 2. Writes via tempfile + os.replace (atomic on POSIX — the file is either
# fully written or not at all; no partial-write corruption)
# 3. Logs every write with entry count for post-mortem debugging
#
# _safe_load_json handles the read side:
# - Missing file → [] (first run, not an error)
# - Corrupt file → attempt restore from .bak; if .bak also corrupt → []
# - Returns (entries, warning_message_or_None)
def _safe_save_json(path: Path, entries: list, label: str) -> None:
"""Atomically write `entries` as JSON to `path`, backing up first.
The .bak file is the user's safety net — if a write goes wrong or the
app crashes mid-save, the previous version survives as path.bak.
**Shrink guard**: if the file currently has N entries and we're about to
write M < N, we still write (the user may have legitimately deleted
entries) BUT we log a loud warning so accidental nukes are visible in
/tmp/splicecraft.log for post-mortem debugging. The .bak always preserves
the pre-write state regardless.
"""
import os
import tempfile
# 1. Back up the existing file (if it has content)
existing_count = 0
if path.exists():
try:
existing = path.read_bytes()
if existing.strip():
bak = path.with_suffix(path.suffix + ".bak")
bak.write_bytes(existing)
# Count existing entries for the shrink guard
try:
existing_count = len(json.loads(existing))
except Exception:
pass
except OSError:
_log.warning("Could not create backup for %s", path)
# Shrink guard: log a loud warning if we're about to lose entries.
# Any shrink is logged so accidental nukes are auditable; going to zero
# from a populated file is almost always a bug (user never legitimately
# empties the whole library at once) so the .bak is explicitly preserved
# and the warning cites the path for recovery.
if existing_count > 0 and len(entries) < existing_count:
_log.warning(
"SHRINK GUARD: %s is being overwritten with %d entries "
"(was %d). If this is unexpected, restore from %s.bak",
label, len(entries), existing_count, path,
)
# 2. Atomic write: tempfile in same dir → os.replace
try:
fd, tmp_name = tempfile.mkstemp(
prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent),
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(entries, fh, indent=2)
fh.flush()
try:
os.fsync(fh.fileno())
except OSError:
pass
os.replace(tmp_name, str(path))
_log.info("Saved %s: %d entries to %s", label, len(entries), path)
except Exception:
# Clean up the temp file on failure
try:
os.unlink(tmp_name)
except OSError:
pass
raise
except Exception:
_log.exception("Failed to save %s to %s", label, path)
def _safe_load_json(path: Path, label: str) -> "tuple[list, str | None]":
"""Load a JSON array from `path`. Returns (entries, warning_or_None).
- Missing file → ([], None) — normal first run, no warning.
- Valid file → (entries, None).
- Corrupt file → attempt .bak restore; if .bak is valid →
(bak_entries, warning). If .bak also corrupt → ([], warning).
"""
if not path.exists():
return [], None
# Try the main file
try:
entries = json.loads(path.read_text(encoding="utf-8"))
if isinstance(entries, list):
return entries, None
_log.warning("%s: expected list, got %s", path, type(entries).__name__)
except Exception:
_log.exception("Corrupt %s file: %s", label, path)
# Main file is corrupt — try the .bak
bak = path.with_suffix(path.suffix + ".bak")
if bak.exists():
try:
entries = json.loads(bak.read_text(encoding="utf-8"))
if isinstance(entries, list):
_log.info("Restored %s from backup %s (%d entries)",
label, bak, len(entries))
# Overwrite the corrupt main file with the good backup
try:
import shutil
shutil.copy2(str(bak), str(path))
except OSError:
pass
return entries, (
f"{label} was corrupt — restored {len(entries)} entries "
f"from backup."
)
except Exception:
_log.exception("Backup %s also corrupt: %s", label, bak)
return [], f"{label} is corrupt and no valid backup was found. Starting empty."
# ── Library persistence ────────────────────────────────────────────────────────
_LIBRARY_FILE = _DATA_DIR / "plasmid_library.json"
_library_cache: "list | None" = None
def _load_library() -> list[dict]:
global _library_cache
if _library_cache is not None:
return list(_library_cache)
entries, warning = _safe_load_json(_LIBRARY_FILE, "Plasmid library")
if warning:
_log.warning(warning)
_library_cache = entries
return list(_library_cache)
def _save_library(entries: list[dict]) -> None:
global _library_cache
_safe_save_json(_LIBRARY_FILE, entries, "Plasmid library")
_library_cache = list(entries)
# ── Restriction sites ──────────────────────────────────────────────────────────
# Comprehensive NEB enzyme catalog.
# Each entry maps enzyme name → (recognition_sequence, fwd_cut, rev_cut).
#
# Cut position convention (0-based, relative to start of recognition sequence):
# 0 = before first base of recognition seq
# len(seq) = after last base of recognition seq
# >len(seq) = downstream of recognition seq (Type IIS)
# negative = upstream of recognition seq
#
# IUPAC ambiguity codes used in recognition sequences:
# R=A/G Y=C/T W=A/T S=G/C M=A/C K=G/T
# B=not-A D=not-C H=not-G V=not-T N=any
#
# Examples:
# EcoRI G^AATTC / CTTAA^G → fwd=1, rev=5
# BamHI G^GATCC / CCTAG^G → fwd=1, rev=5
# SmaI CCC^GGG / GGG^CCC → fwd=3, rev=3 (blunt)
# BsaI GGTCTC(1/5) → recognition=6bp, fwd=6+1=7, rev=6+5=11
#
_NEB_ENZYMES: dict[str, tuple[str, int, int]] = {
# ── Common Type IIP — 6-bp palindromic cutters ─────────────────────────────
"EcoRI": ("GAATTC", 1, 5), # G^AATTC / CTTAA^G 5' overhang
"EcoRV": ("GATATC", 3, 3), # GAT^ATC / GAT^ATC blunt
"BamHI": ("GGATCC", 1, 5), # G^GATCC / CCTAG^G 5' overhang
"HindIII": ("AAGCTT", 1, 5), # A^AGCTT / TTCGA^A 5' overhang
"NcoI": ("CCATGG", 1, 5), # C^CATGG / GGTAC^C 5' overhang
"NdeI": ("CATATG", 2, 4), # CA^TATG / GTAT^AC 5' overhang
"XhoI": ("CTCGAG", 1, 5), # C^TCGAG / GAGCT^C 5' overhang
"SalI": ("GTCGAC", 1, 5), # G^TCGAC / CAGCT^G 5' overhang
"KpnI": ("GGTACC", 5, 1), # GGTAC^C / G^GTACC 3' overhang
"SacI": ("GAGCTC", 5, 1), # GAGCT^C / G^AGCTC 3' overhang
"SacII": ("CCGCGG", 4, 2), # CCGC^GG / CC^GCGG 3' overhang
"SpeI": ("ACTAGT", 1, 5), # A^CTAGT / TGATC^A 5' overhang
"XbaI": ("TCTAGA", 1, 5), # T^CTAGA / AGATC^T 5' overhang
"NotI": ("GCGGCCGC", 2, 6), # GC^GGCCGC / CGCCGG^CG 5' overhang (8-cutter)
"PstI": ("CTGCAG", 5, 1), # CTGCA^G / G^CTGCA 3' overhang
"SphI": ("GCATGC", 5, 1), # GCATG^C / C^GCATG 3' overhang
"ClaI": ("ATCGAT", 2, 4), # AT^CGAT / CGAT^AT 5' overhang
"NheI": ("GCTAGC", 1, 5), # G^CTAGC / CGATC^G 5' overhang
"AvaI": ("CYCGRG", 1, 5), # C^YCGRG 5' overhang (degenerate)
"AvaII": ("GGWCC", 1, 4), # G^GWCC / CCWG^G 5' overhang
"AvrII": ("CCTAGG", 1, 5), # C^CTAGG / GGATC^C 5' overhang
"BclI": ("TGATCA", 1, 5), # T^GATCA / AGTCA^T 5' overhang (dam-sensitive)
"BglII": ("AGATCT", 1, 5), # A^GATCT / TCTAG^A 5' overhang
"BsiWI": ("CGTACG", 1, 5), # C^GTACG / GCATG^C 5' overhang
"BspEI": ("TCCGGA", 1, 5), # T^CCGGA / AGGCC^T 5' overhang
"BsrGI": ("TGTACA", 1, 5), # T^GTACA / ACATG^T 5' overhang
"BssHII": ("GCGCGC", 1, 5), # G^CGCGC / CGCGC^G 5' overhang
"BstBI": ("TTCGAA", 2, 4), # TT^CGAA / AAGC^TT 5' overhang
"BstEII": ("GGTNACC", 1, 5), # G^GTNACC / CCANT^GG 5' overhang
"BstXI": ("CCANNNNNTGG", 8, 4), # CCANN4^TGG/ CCA^N5TGG 3' overhang
"BstYI": ("RGATCY", 1, 5), # R^GATCY / YCTAG^R 5' overhang
"CpoI": ("CGGWCCG", 2, 5), # CG^GWCCG / CGCC^WGG 5' overhang
"DraI": ("TTTAAA", 3, 3), # TTT^AAA / TTT^AAA blunt
"DraIII": ("CACNNNGTG", 6, 3), # CACNNN^GTG/ GTG^NNNGTG 3' overhang
"EagI": ("CGGCCG", 1, 5), # C^GGCCG / GCCGG^C 5' overhang (NotI subset)
"Eco47III": ("AGCGCT", 3, 3), # AGC^GCT blunt
"Eco53kI": ("GAGCTC", 5, 1), # GAGCT^C 3' overhang (SacI isoschizomer)
"EcoNI": ("CCTNNNNNAGG", 5, 6), # CCTNN^NNNAGG 5' overhang
"FseI": ("GGCCGGCC", 6, 2), # GGCCGG^CC / CC^GGCCGG 3' overhang (8-cutter)
"FspI": ("TGCGCA", 3, 3), # TGC^GCA blunt
"HaeII": ("RGCGCY", 5, 1), # RGCGC^Y / R^GCGCY 3' overhang
"HaeIII": ("GGCC", 2, 2), # GG^CC blunt (4-cutter)
"HincII": ("GTYRAC", 3, 3), # GTY^RAC blunt
"HindII": ("GTYRAC", 3, 3), # GTY^RAC blunt (HincII isoschizomer)
"HpaI": ("GTTAAC", 3, 3), # GTT^AAC blunt
"HpaII": ("CCGG", 1, 3), # C^CGG / CGG^C 5' overhang (4-cutter)
"MfeI": ("CAATTG", 1, 5), # C^AATTG / GTTAA^C EcoRI-compatible ends
"MluI": ("ACGCGT", 1, 5), # A^CGCGT / TGCGC^A 5' overhang
"MscI": ("TGGCCA", 3, 3), # TGG^CCA blunt
"MspI": ("CCGG", 1, 3), # C^CGG / CGG^C 5' overhang (HpaII isoschizomer)
"MunI": ("CAATTG", 1, 5), # C^AATTG MfeI isoschizomer
"NarI": ("GGCGCC", 2, 4), # GG^CGCC / CGCG^CC 3' overhang
"NruI": ("TCGCGA", 3, 3), # TCG^CGA blunt
"NsiI": ("ATGCAT", 5, 1), # ATGCA^T / T^ATGCA PstI-compatible ends
"NspI": ("RCATGY", 5, 1), # RCATG^Y / R^CATGY 3' overhang
"PacI": ("TTAATTAA", 5, 3), # TTAAT^TAA / TTA^ATTAA 3' overhang (8-cutter)
"PaeR7I": ("CTCGAG", 1, 5), # C^TCGAG XhoI isoschizomer
"PciI": ("ACATGT", 1, 5), # A^CATGT / TGTAC^A 5' overhang
"PmeI": ("GTTTAAAC", 4, 4), # GTTT^AAAC blunt (8-cutter)
"PmlI": ("CACGTG", 3, 3), # CAC^GTG blunt
"PscI": ("ACATGT", 1, 5), # A^CATGT PciI isoschizomer
"PvuI": ("CGATCG", 4, 2), # CGATC^G / G^CGATC 3' overhang
"PvuII": ("CAGCTG", 3, 3), # CAG^CTG blunt
"RsrII": ("CGGWCCG", 2, 5), # CG^GWCCG CpoI isoschizomer
"SbfI": ("CCTGCAGG", 6, 2), # CCTGCA^GG / CC^TGCAGG PstI-compatible (8-cutter)
"ScaI": ("AGTACT", 3, 3), # AGT^ACT blunt
"SfiI": ("GGCCNNNNNGGCC",8, 4), # GGCCN4^NGGCC 3' overhang (13-bp)
"SgrAI": ("CRCCGGYG", 2, 6), # CR^CCGGYG / GCCGGR^C 5' overhang
"SmaI": ("CCCGGG", 3, 3), # CCC^GGG blunt
"SnaBI": ("TACGTA", 3, 3), # TAC^GTA blunt
"SrfI": ("GCCCGGGC", 4, 4), # GCCC^GGGC blunt (8-cutter)
"StuI": ("AGGCCT", 3, 3), # AGG^CCT blunt
"SwaI": ("ATTTAAAT", 4, 4), # ATTT^AAAT blunt (8-cutter)
"Tth111I": ("GACNNNGTC", 4, 5), # GACN^NNGTC 1-base 3' overhang
"XmaI": ("CCCGGG", 1, 5), # C^CCGGG / GGGCC^C 5' overhang (SmaI isoschizomer)
"XmnI": ("GAANNNNTTC", 5, 5), # GAANN^NNTTC blunt
# ── Rare 8-cutters ─────────────────────────────────────────────────────────
"AscI": ("GGCGCGCC", 2, 6), # GG^CGCGCC / CGCGCC^GG 5' overhang
"AsiSI": ("GCGATCGC", 5, 3), # GCGAT^CGC / GCG^ATCGC 3' overhang
# ── Degenerate / IUPAC recognition sequences ───────────────────────────────
"AccI": ("GTYRAC", 2, 4), # GT^YRAC 3' overhang
"AclI": ("AACGTT", 2, 4), # AA^CGTT 3' overhang
"AfeI": ("AGCGCT", 3, 3), # AGC^GCT blunt (Eco47III isoschizomer)
"AflII": ("CTTAAG", 1, 5), # C^TTAAG MfeI-compatible ends
"AflIII": ("ACRYGT", 1, 5), # A^CRYGT MluI-compatible ends
"AgeI": ("ACCGGT", 1, 5), # A^CCGGT / TGGCC^A 5' overhang
"AhdI": ("GACNNNNNGTC", 6, 5), # GACNNNN^NGTC 1-base 3' overhang
"AluI": ("AGCT", 2, 2), # AG^CT blunt (4-cutter)
"ApaI": ("GGGCCC", 5, 1), # GGGCC^C / G^GGCCC 3' overhang
"ApaLI": ("GTGCAC", 1, 5), # G^TGCAC SphI-compatible ends
"ApoI": ("RAATTY", 1, 5), # R^AATTY EcoRI isoschizomer (degenerate)
"AatII": ("GACGTC", 5, 1), # GACGT^C / G^ACGTC 3' overhang
"BaeGI": ("GKGCMC", 5, 1), # GKGCM^C / G^KGCMC 3' overhang
"BglI": ("GCCNNNNNGGC", 7, 4), # GCCNNNN^NGGC 3' overhang
"BmgBI": ("CACGTC", 3, 3), # CAC^GTC blunt
"BsaAI": ("YACGTR", 3, 3), # YAC^GTR blunt
"BsaBI": ("GATNNNNATC", 5, 5), # GATN4^ATC blunt
"BsaHI": ("GRCGYC", 2, 4), # GR^CGYC 3' overhang
"BsaWI": ("WCCGGW", 1, 5), # W^CCGGW 5' overhang
"BseYI": ("CCCAGC", 5, 1), # CCCAG^C / C^CCAGC 3' overhang
"BsiEI": ("CGRYCG", 4, 2), # CGRY^CG 3' overhang
"BsiHKAI": ("GWGCWC", 5, 1), # GWGCW^C 3' overhang
"BsrFI": ("RCCGGY", 1, 5), # R^CCGGY 5' overhang
"Bsp1286I": ("GDGCHC", 5, 1), # GDGCH^C 3' overhang
"BspHI": ("TCATGA", 1, 5), # T^CATGA NcoI-compatible ends
"BsrI": ("ACTGG", 1, 1), # ACT^GG degenerate Type IIS-like
"BstAPI": ("GCANNNNNTGC", 7, 5), # GCANNNN^NTGC 3' overhang
"BstNI": ("CCWGG", 2, 3), # CC^WGG / WGG^CC 3' overhang
"BstUI": ("CGCG", 2, 2), # CG^CG blunt (4-cutter; methylation-sensitive)
"BstZ17I": ("GTATAC", 3, 3), # GTA^TAC blunt
"BtgI": ("CCRYGG", 1, 5), # C^CRYGG 5' overhang
"Cac8I": ("GCNNGC", 3, 3), # GCN^NGC blunt
"CviAII": ("CATG", 1, 3), # C^ATG NcoI-compatible ends (4-cutter)
"CviQI": ("GTAC", 1, 3), # G^TAC KpnI subset (4-cutter)
"DpnI": ("GATC", 2, 2), # GA^TC blunt; cuts only methylated
"DpnII": ("GATC", 0, 4), # ^GATC / GATC^ 5' overhang (4-cutter)
"DrdI": ("GACNNNNNNGTC", 7, 5), # GACNNNNN^NGTC 3' overhang
"EcoO109I": ("RGGNCCY", 2, 5), # RG^GNCCY 5' overhang
"HphI": ("GGTGA", 8, 12), # GGTGA(8/7) downstream Type IIS
"KasI": ("GGCGCC", 1, 5), # G^GCGCC 5' overhang (NarI isoschizomer)
"MboI": ("GATC", 0, 4), # ^GATC DpnII isoschizomer
"MboII": ("GAAGA", 8, 12), # GAAGA(8/7) downstream Type IIS
"MlyI": ("GAGTC", 10, 10), # GAGTC(5/5) downstream blunt, Type IIS
"MmeI": ("TCCRAC", 20, 18), # TCCRAC(20/18) Type IIS far-cutter
"MspA1I": ("CMGCKG", 3, 3), # CMG^CKG blunt
"NgoMIV": ("GCCGGC", 1, 5), # G^CCGGC 5' overhang (EagI-compatible)
"NmeAIII": ("GCCGAG", 21, 19), # GCCGAG(15/13) Type IIS far-cutter
"PflMI": ("CCANNNNNTGG", 7, 4), # CCANN4^NTGG 3' overhang (BstXI isoschizomer)
"PspOMI": ("GGGCCC", 1, 5), # G^GGCCC ApaI isoschizomer (5' overhang)
"Sau3AI": ("GATC", 0, 4), # ^GATC BamHI-compatible ends (4-cutter)
"SfcI": ("CTRYAG", 1, 5), # C^TRYAG 5' overhang
"SspI": ("AATATT", 3, 3), # AAT^ATT blunt
"TaqI": ("TCGA", 1, 3), # T^CGA / CGT^A 5' overhang (heat-stable)
"Van91I": ("CCANNNNNTGG", 7, 4), # PflMI isoschizomer
"ZraI": ("GACGTC", 3, 3), # GAC^GTC blunt (AatII-related)
# ── Type IIS — cut outside recognition sequence ────────────────────────────
# fwd/rev positions are still offsets from start of recognition seq.
# For an n-bp recognition sequence cutting d1/d2 downstream:
# fwd = n + d1, rev = n + d2
"BaeI": ("ACNNNNGTAYYC",-10, -7), # cuts 10/15 upstream (negative = upstream)
"BbsI": ("GAAGAC", 8, 12), # GAAGAC(2/6) BpiI isoschizomer
"BcoDI": ("GTCTC", 6, 10), # GTCTC(1/5) BsaI 5-bp variant
"BceAI": ("ACGGC", 9, 11), # ACGGC(4/6)
"BciVI": ("GTATCC", 12, 6), # GTATCC(6/5) asymmetric
"BfuAI": ("ACCTGC", 10, 14), # ACCTGC(4/8) BspMI isoschizomer
"BmrI": ("ACTGGN", 6, 5), # cuts 1 past end of recog
"BpiI": ("GAAGAC", 8, 12), # BbsI isoschizomer
"BsaI": ("GGTCTC", 7, 11), # GGTCTC(1/5) Golden Gate workhorse
"BsaXI": ("ACNNNNNCTCC", 3, 12), # cuts upstream and downstream (unusual)
"BsbI": ("CAACAC", 17, 15), # far-cutter
"BseJI": ("GAAGAC", 8, 12), # BbsI isoschizomer
"BseLI": ("CCNNNNNNNGG", 7, 4), # 3' overhang
"BseMII": ("CTCAG", 10, 8), # CTCAG(5/3)
"BseRI": ("GAGGAG", 10, 14), # GAGGAG(10/8)
"BsgI": ("GTGCAG", 22, 20), # GTGCAG(16/14) far-cutter
"BslI": ("CCNNNNNNNGG", 7, 4), # 3' overhang (BseLI variant)
"BsmAI": ("GTCTC", 6, 10), # GTCTC(1/5) BsaI isoschizomer (5-bp)
"BsmBI": ("CGTCTC", 7, 11), # CGTCTC(1/5) Esp3I isoschizomer
"BsmFI": ("GGGAC", 15, 19), # GGGAC(10/14)
"BsmI": ("GAATGC", 7, 1), # GAATGC(1/-1) asymmetric Type IIS
"BspLU11III":("ACATGT", 1, 5), # PciI isoschizomer (not strictly IIS)
"BspMI": ("ACCTGC", 10, 14), # ACCTGC(4/8)
"BspQI": ("GCTCTTC", 8, 11), # SapI isoschizomer
"BspTNI": ("GGTCTC", 7, 11), # BsaI isoschizomer
"BsrBI": ("CCGCTC", 3, 3), # cuts within recog (special case)
"BsrDI": ("GCAATG", 8, 6), # GCAATG(2/0)
"BssSI": ("CACGAG", -5, -1), # cuts upstream of recognition
"BtgZI": ("GCGATG", 16, 20), # GCGATG(10/14)
"BtsCI": ("GGATG", 5, 3), # GGATG(2/0)
"BtsI": ("GCAGTG", 8, 6), # GCAGTG(2/0)
"BtsImutI": ("CAGTG", 5, 3), # BtsCI variant
"EarI": ("CTCTTC", 10, 6), # CTCTTC(4/1) SapI-related
"Esp3I": ("CGTCTC", 7, 11), # BsmBI isoschizomer
"PaqCI": ("CACCTGC", 11, 15), # CACCTGC(4/8)
"SapI": ("GCTCTTC", 8, 11), # GCTCTTC(1/4)
"BsmBI-v2": ("CGTCTC", 7, 11), # v2/HF variant
# ── High-Fidelity (HF) and v2 variants — same recognition/cut as canonical ─
"AgeI-HF": ("ACCGGT", 1, 5),
"BamHI-HF": ("GGATCC", 1, 5),
"BclI-HF": ("TGATCA", 1, 5),
"BmtI": ("GCTAGC", 1, 5), # NheI isoschizomer / HF variant
"BsiWI-HF": ("CGTACG", 1, 5),
"BsrFI-v2": ("RCCGGY", 1, 5),
"BsrGI-HF": ("TGTACA", 1, 5),
"BssSI-v2": ("CACGAG", -5, -1),
"BstEII-HF": ("GGTNACC", 1, 5),
"BstZ17I-HF":("GTATAC", 3, 3),
"DraIII-HF": ("CACNNNGTG", 6, 3),
"EcoRI-HF": ("GAATTC", 1, 5),
"EcoRV-HF": ("GATATC", 3, 3),
"HindIII-HF":("AAGCTT", 1, 5),
"KpnI-HF": ("GGTACC", 5, 1),
"MfeI-HF": ("CAATTG", 1, 5),
"MluI-HF": ("ACGCGT", 1, 5),
"MunI-HF": ("CAATTG", 1, 5),
"NcoI-HF": ("CCATGG", 1, 5),
"NheI-HF": ("GCTAGC", 1, 5),
"NotI-HF": ("GCGGCCGC", 2, 6),
"NruI-HF": ("TCGCGA", 3, 3),
"NsiI-HF": ("ATGCAT", 5, 1),
"PstI-HF": ("CTGCAG", 5, 1),
"PvuI-HF": ("CGATCG", 4, 2),
"PvuII-HF": ("CAGCTG", 3, 3),
"SacI-HF": ("GAGCTC", 5, 1),
"SalI-HF": ("GTCGAC", 1, 5),
"SbfI-HF": ("CCTGCAGG", 6, 2),
"ScaI-HF": ("AGTACT", 3, 3),
"SpeI-HF": ("ACTAGT", 1, 5),
"SphI-HF": ("GCATGC", 5, 1),
"TaqI-v2": ("TCGA", 1, 3),
"XhoI-HF": ("CTCGAG", 1, 5),
}
# Flat recognition-sequence-only dict derived from _NEB_ENZYMES (used by
# _scan_restriction_sites and _RESTR_COLOR below).
_RESTRICTION_SITES: dict[str, str] = {
name: seq for name, (seq, _, _) in _NEB_ENZYMES.items()
}
_RESTR_PALETTE: list[str] = [
"color(220)", "color(208)", "color(196)", "color(160)",
"color(105)", "color(129)", "color(57)", "color(21)",
"color(33)", "color(39)", "color(51)", "color(87)",
"color(118)", "color(154)", "color(190)", "color(226)",
"color(185)", "color(180)",
]
_RESTR_COLOR: dict[str, str] = {
name: _RESTR_PALETTE[i % len(_RESTR_PALETTE)]
for i, name in enumerate(_RESTRICTION_SITES)
}
_IUPAC_RE: dict[str, str] = {
"A": "A", "C": "C", "G": "G", "T": "T",
"R": "[AG]", "Y": "[CT]", "W": "[AT]", "S": "[CG]",
"M": "[AC]", "K": "[GT]", "B": "[CGT]", "D": "[AGT]",
"H": "[ACT]", "V": "[ACG]", "N": "[ACGT]",
}
_PATTERN_CACHE: dict[str, "re.Pattern[str]"] = {}
def _iupac_pattern(site: str) -> "re.Pattern[str]":
if site not in _PATTERN_CACHE:
_PATTERN_CACHE[site] = re.compile(
"".join(_IUPAC_RE.get(c, c) for c in site.upper())
)
return _PATTERN_CACHE[site]
_IUPAC_COMP = str.maketrans(
"ACGTRYWSMKBDHVN",
"TGCAYRWSKMVHDBN",
)
def _rc(seq: str) -> str:
return seq.upper().translate(_IUPAC_COMP)[::-1]
def _feat_len(start: int, end: int, total: int) -> int:
"""Circular-aware feature length. A wrap feature (end < start) is
(total - start) + end bp long; a linear feature is end - start."""
return (total - start) + end if end < start else end - start
def _slice_circular(seq: str, start: int, end: int) -> str:
"""Circular-aware slice. If end > start this is a normal slice; if
end < start the slice wraps the origin and returns seq[start:] + seq[:end].
end == start is treated as empty (not "wrap whole plasmid") — callers
that want the latter should pass explicit boundaries. Used by the
primer-design helpers so a region straddling the origin can be
primer-designed without special casing at every call site.
"""
if end >= start:
return seq[start:end]
return seq[start:] + seq[:end]
# Pre-built per-enzyme scan records: immutable derived values (compiled pattern,
# palindrome flag, RC pattern, color) computed once at import time rather than
# on every _scan_restriction_sites call. Iterating the pre-built list avoids
# ~200 per-call _iupac_pattern + _rc + dict-lookup + len calls per scan.
#
# Each entry is a tuple:
# (name, site, site_len, fwd_cut, rev_cut, color, pat, is_palindrome, rc_pat)
# rc_pat is None for palindromic enzymes (no reverse scan needed).
_SCAN_CATALOG: "list[tuple]" = []
def _rebuild_scan_catalog() -> None:
"""(Re)populate `_SCAN_CATALOG` from `_NEB_ENZYMES`. Called at import
time; also exposed so tests / future catalog edits can refresh it."""
_SCAN_CATALOG.clear()
for name, (site, fwd_cut, rev_cut) in _NEB_ENZYMES.items():
site_u = site.upper()
pat = _iupac_pattern(site_u)
rc_site = _rc(site_u)
is_pal = (rc_site == site_u)
rc_pat = None if is_pal else _iupac_pattern(rc_site)
_SCAN_CATALOG.append((
name, site_u, len(site_u), fwd_cut, rev_cut,
_RESTR_COLOR[name], pat, is_pal, rc_pat,
))
_rebuild_scan_catalog()
def _scan_restriction_sites(
seq: str,
min_recognition_len: int = 6,
unique_only: bool = True,
circular: bool = True,
) -> list[dict]:
"""Scan both strands; return resite + recut dicts for every hit.
resite — the recognition sequence span (colored bar)
recut — the cut position (single-bp marker: ↓ above or ↑ below DNA)
min_recognition_len — skip enzymes whose recognition site is shorter than this
(default 6 to reduce noise from 4-cutters)
unique_only — if True, only include enzymes that cut exactly once
(forward + reverse strand combined; default True)
circular — if True (default), recognition sequences that span
the origin (bp n-1 → bp 0) are also found. SpliceCraft
is a plasmid viewer, so circularity is on by default.
Wrap-around resites are emitted as TWO pieces so the existing linear-span
rendering in the map / sequence panel stays correct: one piece on the
"tail" (start..n) with the enzyme label, one unlabeled piece on the
"head" (0..tail_len). The single-bp recut marker is placed at its real
absolute position modulo n.
"""
seq_u = seq.upper()
n = len(seq_u)
# Per-enzyme results collected first so we can filter to unique cutters
by_enzyme: dict[str, list[dict]] = {}
seen: set[tuple[str, int, int]] = set() # deduplicate palindromes
# For circular sequences, scan an augmented copy that includes up to
# site_len-1 bp re-attached from the beginning so matches starting near
# the end (that would otherwise be truncated) are found too.
max_site_len = max((e[2] for e in _SCAN_CATALOG), default=0)
scan_seq = (seq_u + seq_u[: max_site_len - 1]) if (circular and n > 0) else seq_u
def _emit_resite(hits, p, site_len, strand, color, name,
cut_col, ext_cut_bp):
"""Emit one or two resite dicts depending on wrap. Labels only on the
first piece so the map doesn't double-print. For wrapped sites, the
cut_col / ext_cut_bp fields are only meaningful on the piece that
actually contains the cut; we attach them to the tail piece by default
and clear them on the head piece."""
if p + site_len <= n:
hits.append({
"type": "resite",
"start": p,
"end": p + site_len,
"strand": strand,
"color": color,
"label": name,
"cut_col": cut_col,
"ext_cut_bp": ext_cut_bp,
})
return
# Wraps origin: tail [p, n) + head [0, (p + site_len) - n).
tail_len = n - p
head_len = (p + site_len) - n
# cut_col (bar-relative) maps to whichever piece actually contains the
# cut. ext_cut_bp (absolute) is unrelated to the tail/head split — it's
# only meaningful when cut_col is None (Type IIS cuts outside the
# recognition sequence). Attach it to both pieces so the cut arrow is
# drawn regardless of which chunk contains the external cut position;
# the chunk-level `chunk_start <= ext_cut_bp < chunk_end` test makes
# the render idempotent. Regression guard added 2026-04-13.
tail_cut_col = cut_col if (cut_col is not None and cut_col < tail_len) else None
head_cut_col = ((cut_col - tail_len) if (cut_col is not None and cut_col >= tail_len)
else None)
hits.append({
"type": "resite",
"start": p,
"end": n,
"strand": strand,
"color": color,
"label": name,
"cut_col": tail_cut_col,
"ext_cut_bp": ext_cut_bp,
})
hits.append({
"type": "resite",
"start": 0,
"end": head_len,
"strand": strand,
"color": color,
"label": "", # unlabeled continuation
"cut_col": head_cut_col,
"ext_cut_bp": ext_cut_bp,
})
for entry in _SCAN_CATALOG:
name, site, site_len, fwd_cut, rev_cut, color, pat, is_palindrome, rc_pat = entry
if site_len < min_recognition_len:
continue
hits: list[dict] = []
# Forward strand scan (over augmented sequence if circular)
for m in pat.finditer(scan_seq):
p = m.start()
if p >= n:
continue # duplicate of match already found at p - n
key = (name, p, 1)
if key in seen:
continue
seen.add(key)
# ext_cut_bp: absolute cut position when cut falls outside recognition
_ext = ((p + fwd_cut) % n) if (fwd_cut <= 0 or fwd_cut >= site_len) else None
_cc = fwd_cut if 0 < fwd_cut < site_len else None
_emit_resite(hits, p, site_len, 1, color, name, _cc, _ext)
cut_bp = (p + fwd_cut) % n if n > 0 else 0
hits.append({
"type": "recut",
"start": cut_bp,
"end": cut_bp + 1,
"strand": 1,
"color": color,
"label": name,
})
# Reverse strand handling — uses precomputed is_palindrome and rc_pat
# from _SCAN_CATALOG (no per-call _rc / _iupac_pattern work).
if not is_palindrome:
# Non-palindromic: scan for RC on forward strand to find
# reverse-strand binding sites at their correct positions.
for m in rc_pat.finditer(scan_seq):
p = m.start()
if p >= n:
continue # duplicate of match already found at p - n
key = (name, p, -1)
if key in seen:
continue
seen.add(key)
# Cut column within the bar: enzyme's fwd_cut mapped to
# the reversed orientation displayed on the forward strand
rev_cut_col = site_len - 1 - fwd_cut
_top_cut_bp = (p + site_len - 1 - rev_cut) % n # top-strand cut in fwd coords
_top_cut_outside = ((_top_cut_bp - p) % n) >= site_len
_cc = rev_cut_col if 0 <= rev_cut_col < site_len else None
_ext = _top_cut_bp if _top_cut_outside else None
_emit_resite(hits, p, site_len, -1, color, name, _cc, _ext)
# Bottom-strand cut (enzyme's fwd_cut mapped to fwd coords)
cut_bp = (p + site_len - 1 - fwd_cut) % n if n > 0 else 0
hits.append({
"type": "recut",
"start": cut_bp,
"end": cut_bp + 1,
"strand": -1,
"color": color,
"label": name,
})
if hits:
by_enzyme[name] = hits
feats: list[dict] = []
placed: set[tuple[int, int]] = set() # (start, end) of resites already shown
for name, hits in by_enzyme.items():
# Count LABELED resites only — a wrap-around hit is emitted as one
# labeled piece + one unlabeled continuation, but counts as 1 site.
if unique_only:
n_sites = sum(
1 for h in hits if h["type"] == "resite" and h.get("label")
)
if n_sites != 1:
continue
# Skip isoschizomers / HF-variants that land on an already-placed site
positions = {
(h["start"], h["end"]) for h in hits
if h["type"] == "resite" and h.get("label")
}
if positions & placed:
continue
placed |= positions
feats.extend(hits)
return feats
def _assign_chunk_features(
chunk_feats: list[dict], chunk_start: int, chunk_end: int
) -> tuple[list[list[dict]], list[list[dict]]]:
"""
Forward-strand features always go above DNA; reverse-strand always below.
Within each group, overlapping features are stacked into greedy lanes
(each lane is a list of non-overlapping features). Capped at 3 lanes/side.
"""
def _greedy_lanes(feats: list[dict]) -> list[list[dict]]:
sorted_f = sorted(feats, key=lambda f: max(f["start"], chunk_start))
lanes: list[list[dict]] = []
lane_ends: list[int] = []
for f in sorted_f:
bar_s = max(f["start"], chunk_start)
bar_e = min(f["end"], chunk_end)
if bar_e - bar_s <= 0:
continue
placed = False
for i, end in enumerate(lane_ends):
if bar_s >= end:
lanes[i].append(f)
lane_ends[i] = bar_e
placed = True
break
if not placed:
lanes.append([f])
lane_ends.append(bar_e)
return lanes[:3]
fwd = [f for f in chunk_feats if f["strand"] >= 0]
rev = [f for f in chunk_feats if f["strand"] < 0]
return _greedy_lanes(fwd), _greedy_lanes(rev)
def _render_feature_row_pair(
result: "Text",
feats: list[dict],
chunk_start: int,
chunk_end: int,
prefix_w: int,
is_below_dna: bool,
show_connectors: bool,
flip_label_bar: bool = False,
single_row: bool = False,
) -> None:
"""
Append one label row + optional connector row + one feature-bar row to result.
For above-DNA: label / [connector] / bar.
For below-DNA: bar / [connector] / label.
Feature bars use ▒ (medium-shade / dither) as the fill glyph so the bar
reads as a single flat coloured tone rather than a pattern of distinct dots.
This is DELIBERATELY different from PlasmidMap, which still uses braille
sub-character rendering (U+2800–U+28FF) for the circular-map feature arcs —
only the sequence panel switched off braille.
When single_row=True (RE lanes), collapse to one content row: the cut arrow is
placed just outside the bracket (left of '(' above DNA, right of ')' below) only
if that cell is a space, so it never overwrites another character.
Multiple non-overlapping features share the same pair of rows horizontally.
"""
content_w = chunk_end - chunk_start
label_arr: list[tuple[str, str]] = [(" ", "")] * content_w
bar_arr: list[tuple[str, str]] = [(" ", "")] * content_w
conn_arr: list[tuple[str, str]] = [(" ", "")] * content_w
for f in feats:
bar_s = max(f["start"], chunk_start) - chunk_start
bar_e = min(f["end"], chunk_end) - chunk_start
bar_len = bar_e - bar_s
if bar_len <= 0:
continue
starts_here = f["start"] >= chunk_start
ends_here = f["end"] <= chunk_end
strand = f["strand"]
color = f["color"]
label = f.get("label", f.get("type", ""))
feat_type = f.get("type", "")
if feat_type == "resite":
# ── Parenthesis-style RE site: ( EnzymeName ) ─────────────────
# Bar row: ( EnzymeName ) — bold white name, colored parens
# Label row: ↓ or ↑ at the intra-site cut column (if cut is
# within the recognition site; Type IIS cuts elsewhere)
cut_col = f.get("cut_col") # 0-based offset from f["start"], or None
# Opening / closing parens
if starts_here and bar_len >= 1:
bar_arr[bar_s] = ("(", color)
if ends_here and bar_len >= 1:
bar_arr[bar_s + bar_len - 1] = (")", color)
# Enzyme name: bold white, centered in the interior
interior_start = (1 if starts_here else 0)
interior_end = (bar_len - 1 if ends_here else bar_len)
interior_len = interior_end - interior_start
if interior_len > 0:
name_str = label[:interior_len]
name_pad = interior_len - len(name_str)
name_lpad = name_pad // 2
for j, ch in enumerate(name_str):
pos = bar_s + interior_start + name_lpad + j
if 0 <= pos < content_w:
bar_arr[pos] = (ch, "bold white")
# Cut marker in the label row so it doesn't obscure the name
cut_ch = "↑" if is_below_dna else "↓"
if cut_col is not None:
visible_offset = cut_col - max(0, chunk_start - f["start"])
cut_pos = bar_s + visible_offset
if 0 <= cut_pos < content_w:
label_arr[cut_pos] = (cut_ch, "bold " + color)
# Type IIS: dashed bridge from recognition bar to cut site
ext_cut_bp = f.get("ext_cut_bp")
if ext_cut_bp is not None and chunk_start <= ext_cut_bp < chunk_end:
cut_abs = ext_cut_bp - chunk_start
if 0 <= cut_abs < content_w:
label_arr[cut_abs] = (cut_ch, "bold " + color)
# Bridge in bar_arr: from recognition end rightward, or from
# cut leftward to recognition start (upstream cutters)
if cut_abs >= bar_s + bar_len: # downstream cut
for j in range(bar_s + bar_len, cut_abs):
if 0 <= j < content_w and bar_arr[j][0] == " ":
bar_arr[j] = ("╌", color)
elif cut_abs < bar_s: # upstream cut
for j in range(cut_abs + 1, bar_s):
if 0 <= j < content_w and bar_arr[j][0] == " ":
bar_arr[j] = ("╌", color)
# Connector tick at midpoint
mid = bar_s + bar_len // 2
if 0 <= mid < content_w:
conn_arr[mid] = ("┊", color)
continue # skip the regular label/bar/conn logic below
elif feat_type == "recut":
continue # cut position is rendered inside the resite bar; skip here
# ── Standard feature (non-RE) ──────────────────────────────────────
# Label (centered in feature span)
lbl = label[:bar_len]
pad = bar_len - len(lbl)
pl = pad // 2
lbl_str = " " * pl + lbl + " " * (pad - pl)
for i, ch in enumerate(lbl_str):
if 0 <= bar_s + i < content_w:
label_arr[bar_s + i] = (ch, color)
# Dithered feature bar — medium-shade fill + directional arrowhead at
# the feature end (strand direction preserved). 1 bp features get a
# triangle pointing toward the DNA row.