API Reference¶
Squiggy provides both a simple functional API and an object-oriented API for working with Oxford Nanopore sequencing data.
Quick Start¶
from squiggy import load_pod5, load_bam, plot_read, get_read_ids
# Load POD5 file (populates global kernel state)
reader, read_ids = load_pod5("data.pod5")
# Optionally load BAM for base annotations
load_bam("alignments.bam")
# Generate plot (routes to Positron Plots pane automatically)
html = plot_read(read_ids[0])
File I/O¶
load_pod5 ¶
Load a POD5 file into the global kernel session (OPTIMIZED)
This function mutates the global squiggy_kernel object, making POD5 data available for subsequent plotting and analysis calls.
Performance optimizations: - Lazy read ID loading (O(1) memory vs. O(n)) - Optional index building for O(1) lookups - Persistent caching for instant subsequent loads
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to POD5 file |
required |
build_index
|
bool
|
Whether to build read ID index (default: True) |
True
|
use_cache
|
bool
|
Whether to use persistent cache (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
None
|
None (mutates global squiggy_kernel) |
Examples:
>>> from squiggy import load_pod5
>>> from squiggy.io import squiggy_kernel
>>> load_pod5('data.pod5')
>>> print(f"Loaded {len(squiggy_kernel._read_ids)} reads")
>>> # Session is available as squiggy_kernel in kernel
>>> first_read = next(squiggy_kernel._reader.reads())
Source code in squiggy/io.py
load_bam ¶
Load a BAM file into the global kernel session (OPTIMIZED)
This function mutates the global squiggy_kernel object, making BAM alignment data available for subsequent plotting and analysis calls.
Performance optimizations: - Single-pass metadata collection (3-4x faster than old 4-scan approach) - Eager reference mapping (transparent cost, eliminates UI freezes) - Persistent caching for instant subsequent loads
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to BAM file |
required |
build_ref_mapping
|
bool
|
Whether to build reference→reads mapping (default: True) |
True
|
use_cache
|
bool
|
Whether to use persistent cache (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
None
|
None (mutates global squiggy_kernel) |
Examples:
>>> from squiggy import load_bam
>>> from squiggy.io import squiggy_kernel
>>> load_bam('alignments.bam')
>>> print(squiggy_kernel._bam_info['references'])
>>> if squiggy_kernel._bam_info['has_modifications']:
... print(f"Modifications: {squiggy_kernel._bam_info['modification_types']}")
>>> if squiggy_kernel._bam_info['has_event_alignment']:
... print("Event alignment data available")
Source code in squiggy/io.py
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 | |
load_fasta ¶
Load a FASTA file into the global kernel session
This function mutates the global squiggy_kernel object, making FASTA reference sequences available for subsequent motif search and analysis calls.
If a FASTA index (.fai) doesn't exist, it will be automatically created using pysam.faidx().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to FASTA file (index will be created if missing) |
required |
Returns:
| Type | Description |
|---|---|
None
|
None (mutates global squiggy_kernel) |
Examples:
>>> from squiggy import load_fasta
>>> from squiggy.io import squiggy_kernel
>>> load_fasta('genome.fa') # Creates .fai index if needed
>>> print(squiggy_kernel._fasta_info['references'])
>>> # Use with motif search
>>> from squiggy.motif import search_motif
>>> matches = list(search_motif(squiggy_kernel._fasta_path, "DRACH"))
Source code in squiggy/io.py
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 | |
close_pod5 ¶
Close the currently open POD5 reader
Call this to free resources when done.
Examples:
>>> from squiggy import load_pod5, close_pod5
>>> load_pod5('data.pod5')
>>> # ... work with data ...
>>> close_pod5()
Source code in squiggy/io.py
close_bam ¶
Clear the currently loaded BAM file state
Call this to free BAM-related resources when done. Unlike close_pod5(), this doesn't need to close a file handle since BAM files are opened and closed per-operation.
Examples:
>>> from squiggy import load_bam, close_bam
>>> load_bam('alignments.bam')
>>> # ... work with alignments ...
>>> close_bam()
Source code in squiggy/io.py
close_fasta ¶
Clear the currently loaded FASTA file state
Call this to free FASTA-related resources when done. Unlike close_pod5(), this doesn't need to close a file handle since FASTA files are opened and closed per-operation.
Examples:
>>> from squiggy import load_fasta, close_fasta
>>> load_fasta('genome.fa')
>>> # ... work with sequences ...
>>> close_fasta()
Source code in squiggy/io.py
get_current_files ¶
Get paths of currently loaded files
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
Dict with pod5_path and bam_path (may be None) |
Source code in squiggy/io.py
get_read_ids ¶
Get list of read IDs from currently loaded POD5 file
Returns:
| Type | Description |
|---|---|
list[str]
|
List of read ID strings (materialized from lazy list if needed) |
Source code in squiggy/io.py
get_bam_modification_info ¶
Check if BAM file contains base modification tags (MM/ML)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to BAM file |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict with: - has_modifications: bool - modification_types: list of modification codes (e.g., ['m', 'h']) - sample_count: number of reads checked |
Examples:
>>> from squiggy import get_bam_modification_info
>>> mod_info = get_bam_modification_info('alignments.bam')
>>> if mod_info['has_modifications']:
... print(f"Found modifications: {mod_info['modification_types']}")
Source code in squiggy/io.py
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 | |
get_bam_event_alignment_status ¶
Check if BAM file contains event alignment data (mv tag)
The mv tag contains the move table from basecalling, which maps nanopore signal events to basecalled nucleotides. This is required for event-aligned plotting mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to BAM file |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if mv tag is found in sampled reads |
Examples:
>>> from squiggy import get_bam_event_alignment_status
>>> has_events = get_bam_event_alignment_status('alignments.bam')
>>> if has_events:
... print("BAM contains event alignment data")
Source code in squiggy/io.py
get_read_to_reference_mapping ¶
Get mapping of reference names to read IDs from currently loaded BAM
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
Dict mapping reference name to list of read IDs |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no BAM file is loaded |
Examples:
>>> from squiggy import load_bam, get_read_to_reference_mapping
>>> load_bam('alignments.bam')
>>> mapping = get_read_to_reference_mapping()
>>> print(f"References: {list(mapping.keys())}")
Source code in squiggy/io.py
Plotting Functions¶
Single File Plotting¶
plot_read ¶
plot_read(
read_id: str,
mode: str = "SINGLE",
normalization: str = "ZNORM",
theme: str = "LIGHT",
downsample: int = None,
show_dwell_time: bool = False,
show_labels: bool = True,
position_label_interval: int = None,
scale_dwell_time: bool = False,
min_mod_probability: float = 0.5,
enabled_mod_types: list = None,
show_signal_points: bool = False,
clip_x_to_alignment: bool = True,
sample_name: str | None = None,
coordinate_space: str = "signal",
) -> str
Generate a Bokeh HTML plot for a single read
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read ID to plot |
required |
mode
|
str
|
Plot mode (SINGLE, EVENTALIGN) |
'SINGLE'
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) |
'ZNORM'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
downsample
|
int
|
Downsampling factor (1 = no downsampling, 10 = every 10th point) |
None
|
show_dwell_time
|
bool
|
Color bases by dwell time (requires event-aligned mode) |
False
|
show_labels
|
bool
|
Show base labels on plot (event-aligned mode) |
True
|
position_label_interval
|
int
|
Interval for position labels |
None
|
scale_dwell_time
|
bool
|
Scale x-axis by cumulative dwell time instead of regular time |
False
|
min_mod_probability
|
float
|
Minimum probability threshold for displaying modifications (0-1) |
0.5
|
enabled_mod_types
|
list
|
List of modification type codes to display (None = all) |
None
|
show_signal_points
|
bool
|
Show individual signal points as circles |
False
|
clip_x_to_alignment
|
bool
|
If True, x-axis shows only aligned region (default True). If False, x-axis extends to include soft-clipped regions. |
True
|
sample_name
|
str | None
|
(Multi-sample mode) Name of the sample to plot from. If provided, plots from that specific sample instead of the global session. |
None
|
coordinate_space
|
str
|
X-axis coordinate system ('signal' or 'sequence'). 'signal' uses sample indices, 'sequence' uses genomic positions (requires BAM). |
'signal'
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string |
Examples:
>>> html = plot_read('read_001', mode='EVENTALIGN')
>>> # Extension displays this automatically
>>> # Or save to file:
>>> with open('plot.html', 'w') as f:
>>> f.write(html)
Source code in squiggy/plotting.py
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 | |
plot_reads ¶
plot_reads(
read_ids: list,
mode: str = "OVERLAY",
normalization: str = "ZNORM",
theme: str = "LIGHT",
downsample: int = None,
show_dwell_time: bool = False,
show_labels: bool = True,
scale_dwell_time: bool = False,
min_mod_probability: float = 0.5,
enabled_mod_types: list = None,
show_signal_points: bool = False,
sample_name: str | None = None,
read_sample_map: dict[str, str] | None = None,
read_colors: dict[str, str] | None = None,
coordinate_space: str = "signal",
) -> str
Generate a Bokeh HTML plot for multiple reads
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_ids
|
list
|
List of read IDs to plot |
required |
mode
|
str
|
Plot mode (OVERLAY, STACKED, EVENTALIGN) |
'OVERLAY'
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) |
'ZNORM'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
downsample
|
int
|
Downsampling factor (1 = no downsampling, 10 = every 10th point) |
None
|
show_dwell_time
|
bool
|
Color bases by dwell time (EVENTALIGN mode only) |
False
|
show_labels
|
bool
|
Show base labels on plot (EVENTALIGN mode only) |
True
|
scale_dwell_time
|
bool
|
Scale x-axis by cumulative dwell time (EVENTALIGN mode only) |
False
|
min_mod_probability
|
float
|
Minimum probability threshold for displaying modifications |
0.5
|
enabled_mod_types
|
list
|
List of modification type codes to display |
None
|
show_signal_points
|
bool
|
Show individual signal points as circles |
False
|
sample_name
|
str | None
|
(Single-sample mode) Name of the sample to plot from. If provided, plots from that specific sample instead of the global session. |
None
|
read_sample_map
|
dict[str, str] | None
|
(Multi-sample mode) Dict mapping read_id → sample_name. If provided, reads are loaded from their respective samples. Takes precedence over sample_name parameter. |
None
|
read_colors
|
dict[str, str] | None
|
(Multi-sample mode) Dict mapping read_id → color hex string. If provided, each read uses its specified color instead of the default color cycling. Useful for sample-based coloring. |
None
|
coordinate_space
|
str
|
Coordinate system for x-axis ('signal' or 'sequence'). 'signal' uses raw sample points, 'sequence' uses BAM alignment positions. |
'signal'
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string |
Examples:
>>> # Single sample
>>> html = plot_reads(['read_001', 'read_002'], mode='OVERLAY')
>>>
>>> # Multi-sample with custom colors
>>> read_map = {'read_001': 'sample_A', 'read_002': 'sample_B'}
>>> colors = {'read_001': '#E69F00', 'read_002': '#56B4E9'}
>>> html = plot_reads(['read_001', 'read_002'], mode='OVERLAY',
... read_sample_map=read_map, read_colors=colors)
Source code in squiggy/plotting.py
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 | |
plot_aggregate ¶
plot_aggregate(
reference_name: str,
max_reads: int = 100,
normalization: str = "ZNORM",
theme: str = "LIGHT",
show_modifications: bool = True,
mod_filter: dict | None = None,
min_mod_frequency: float = 0.0,
min_modified_reads: int = 1,
show_pileup: bool = True,
show_dwell_time: bool = True,
show_signal: bool = True,
show_quality: bool = True,
clip_x_to_alignment: bool = True,
transform_coordinates: bool = True,
sample_name: str | None = None,
) -> str
Generate aggregate multi-read visualization for a reference sequence
Creates up to five synchronized tracks: 1. Modifications heatmap (optional, if BAM has MM/ML tags) 2. Base pileup (IGV-style stacked bar chart) 3. Dwell time per base (mean ± std dev) 4. Aggregate signal (mean ± std dev across reads) 5. Quality scores by position
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference_name
|
str
|
Name of reference sequence from BAM file |
required |
max_reads
|
int
|
Maximum number of reads to sample for aggregation (default 100) |
100
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) |
'ZNORM'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
show_modifications
|
bool
|
Show modifications heatmap panel (default True) |
True
|
mod_filter
|
dict | None
|
Dictionary mapping modification codes to minimum probability thresholds (e.g., {'m': 0.8, 'a': 0.7}). If None, all modifications shown. |
None
|
min_mod_frequency
|
float
|
Minimum fraction of reads that must be modified at a position (0.0-1.0). Positions with lower modification frequency are excluded (default 0.0). |
0.0
|
min_modified_reads
|
int
|
Minimum number of reads that must have the modification at a position. Positions with fewer modified reads are excluded (default 1). |
1
|
show_pileup
|
bool
|
Show base pileup panel (default True) |
True
|
show_dwell_time
|
bool
|
Show dwell time panel (default True) |
True
|
show_signal
|
bool
|
Show signal panel (default True) |
True
|
show_quality
|
bool
|
Show quality panel (default True) |
True
|
clip_x_to_alignment
|
bool
|
If True, x-axis shows only aligned region (default True). If False, x-axis extends to include soft-clipped regions. |
True
|
transform_coordinates
|
bool
|
If True, transform to 1-based coordinates anchored to first reference base (default True). If False, use raw genomic coordinates. |
True
|
sample_name
|
str | None
|
(Multi-sample mode) Name of the sample to plot from. If provided, plots from that specific sample instead of the global session. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string with synchronized tracks |
Examples:
>>> import squiggy
>>> squiggy.load_pod5('data.pod5')
>>> squiggy.load_bam('alignments.bam')
>>> html = squiggy.plot_aggregate('chr1', max_reads=50)
>>> # Filter modifications by type and probability
>>> html = squiggy.plot_aggregate('chr1', mod_filter={'m': 0.8, 'a': 0.7})
>>> # Extension displays this automatically
Raises:
| Type | Description |
|---|---|
ValueError
|
If POD5 or BAM files not loaded |
Source code in squiggy/plotting.py
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 | |
Multi-Sample Plotting¶
plot_motif_aggregate_all ¶
plot_motif_aggregate_all(
fasta_file: str,
motif: str,
upstream: int = None,
downstream: int = None,
max_reads_per_motif: int = 100,
normalization: str = "ZNORM",
theme: str = "LIGHT",
strand: str = "both",
) -> str
Generate aggregate multi-read visualization across ALL motif matches
Creates a three-track plot showing aggregate statistics from reads aligned to ALL instances of the motif in the genome. The x-axis is centered on the motif position with configurable upstream/downstream windows.
This function combines reads from all motif matches into one aggregate view, providing a genome-wide perspective on signal patterns around the motif.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fasta_file
|
str
|
Path to indexed FASTA file (.fai required) |
required |
motif
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH", "YGCY") |
required |
upstream
|
int
|
Number of bases upstream (5') of motif center (default=10) |
None
|
downstream
|
int
|
Number of bases downstream (3') of motif center (default=10) |
None
|
max_reads_per_motif
|
int
|
Maximum reads per motif match (default=100) |
100
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) |
'ZNORM'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
strand
|
str
|
Which strand to search ('+', '-', or 'both') |
'both'
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string with three synchronized tracks showing aggregate |
str
|
statistics across all motif instances |
Examples:
>>> import squiggy
>>> squiggy.load_pod5('data.pod5')
>>> squiggy.load_bam('alignments.bam')
>>> html = squiggy.plot_motif_aggregate_all(
... fasta_file='genome.fa',
... motif='DRACH',
... upstream=20,
... downstream=50
... )
>>> # Extension displays this automatically
Raises:
| Type | Description |
|---|---|
ValueError
|
If POD5/BAM not loaded or no motif matches found |
Source code in squiggy/plotting.py
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 | |
plot_signal_overlay_comparison ¶
plot_signal_overlay_comparison(
sample_names: list[str],
reference_name: str | None = None,
normalization: str = "ZNORM",
theme: str = "LIGHT",
max_reads: int | None = None,
) -> str
Generate signal overlay comparison plot for multiple samples
Creates a visualization overlaying raw signals from 2+ samples, each with distinct color from Okabe-Ito palette. Includes: 1. Signal Overlay Track: All sample signals overlaid with color per sample 2. Coverage Track: Read count per position for each sample 3. Reference Display: Nucleotide sequence annotations below signal track
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_names
|
list[str]
|
List of sample names to compare (minimum 2 required) |
required |
reference_name
|
str | None
|
Optional reference name (auto-detected from first sample's BAM) |
None
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) - default ZNORM |
'ZNORM'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
max_reads
|
int | None
|
Maximum reads per sample to load (default: min of available reads, capped at 100) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string with signal overlay comparison visualization |
Examples:
>>> import squiggy
>>> squiggy.load_sample('alanine', 'ala_subset.pod5', 'ala_subset.aln.bam')
>>> squiggy.load_sample('arginine', 'arg_subset.pod5', 'arg_subset.aln.bam')
>>> html = squiggy.plot_signal_overlay_comparison(
... ['alanine', 'arginine'],
... normalization='ZNORM'
... )
>>> # Extension displays this automatically
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 samples provided, samples not found, or missing BAM files |
Source code in squiggy/plotting.py
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 | |
plot_delta_comparison ¶
plot_delta_comparison(
sample_names: list[str],
reference_name: str = "Default",
normalization: str = "NONE",
theme: str = "LIGHT",
max_reads: int | None = None,
) -> str
Generate delta comparison plot between two or more samples
Creates a visualization showing differences in aggregate statistics between samples. Shows: 1. Delta Signal Track: Mean signal differences (B - A) 2. Delta Stats Track: Coverage comparisons
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_names
|
list[str]
|
List of sample names to compare (minimum 2 required) |
required |
reference_name
|
str
|
Optional reference name for plot title (default: "Default") |
'Default'
|
normalization
|
str
|
Normalization method (NONE, ZNORM, MEDIAN, MAD) |
'NONE'
|
theme
|
str
|
Color theme (LIGHT, DARK) |
'LIGHT'
|
max_reads
|
int | None
|
Maximum reads per sample to load (default: min of available reads, capped at 100) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Bokeh HTML string with delta comparison visualization |
Examples:
>>> import squiggy
>>> squiggy.load_sample('v4.2', 'data_v4.2.pod5', 'align_v4.2.bam')
>>> squiggy.load_sample('v5.0', 'data_v5.0.pod5', 'align_v5.0.bam')
>>> html = squiggy.plot_delta_comparison(['v4.2', 'v5.0'])
>>> # Extension displays this automatically
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 samples provided or samples not found |
Source code in squiggy/plotting.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 | |
Multi-Sample Management¶
load_sample ¶
load_sample(
name: str,
pod5_path: str,
bam_path: str | None = None,
fasta_path: str | None = None,
) -> Sample
Load a POD5/BAM/FASTA sample set into the global session
Convenience function that loads a named sample into the global squiggy_kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this sample (e.g., 'model_v4.2') |
required |
pod5_path
|
str
|
Path to POD5 file |
required |
bam_path
|
str | None
|
Path to BAM file (optional) |
None
|
fasta_path
|
str | None
|
Path to FASTA file (optional) |
None
|
Returns:
| Type | Description |
|---|---|
Sample
|
The created Sample object |
Examples:
>>> from squiggy import load_sample
>>> sample = load_sample('v4.2', 'data_v4.2.pod5', 'align_v4.2.bam')
>>> print(f"Loaded {len(sample._read_ids)} reads")
Source code in squiggy/io.py
get_sample ¶
Get a loaded sample by name from the global session
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Sample name |
required |
Returns:
| Type | Description |
|---|---|
Sample | None
|
Sample object or None if not found |
Examples:
Source code in squiggy/io.py
list_samples ¶
remove_sample ¶
Unload a sample from the global session and free its resources
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Sample name to remove |
required |
Examples:
Source code in squiggy/io.py
close_all_samples ¶
Close all samples and clear the global session
Examples:
get_common_reads ¶
Get reads that are present in all specified samples
Finds the intersection of read IDs across multiple samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_names
|
list[str]
|
List of sample names to compare |
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
Set of read IDs present in all samples |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any sample name not found |
Examples:
>>> from squiggy import get_common_reads
>>> common = get_common_reads(['model_v4.2', 'model_v5.0'])
>>> print(f"Common reads: {len(common)}")
Source code in squiggy/io.py
get_unique_reads ¶
Get reads unique to a sample (not in other samples)
Finds reads that are only in the specified sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_name
|
str
|
Sample to find unique reads for |
required |
exclude_samples
|
list[str] | None
|
Samples to exclude from (default: all other samples) |
None
|
Returns:
| Type | Description |
|---|---|
set[str]
|
Set of read IDs unique to the sample |
Raises:
| Type | Description |
|---|---|
ValueError
|
If sample not found |
Examples:
>>> from squiggy import get_unique_reads
>>> unique_a = get_unique_reads('model_v4.2')
>>> unique_b = get_unique_reads('model_v5.0')
Source code in squiggy/io.py
compare_samples ¶
Compare multiple samples and return analysis
Generates a comprehensive comparison of samples including read overlap, reference validation, and model provenance information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_names
|
list[str]
|
List of sample names to compare |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict with comparison results: - samples: List of sample names - read_overlap: Read ID overlap analysis - reference_validation: Reference compatibility (if BAM files loaded) - sample_info: Basic info about each sample |
Examples:
>>> from squiggy import compare_samples
>>> result = compare_samples(['model_v4.2', 'model_v5.0'])
>>> print(result['read_overlap'])
Source code in squiggy/io.py
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 | |
Session Management¶
SquiggyKernel ¶
Manages kernel state for loaded POD5 and BAM files, supporting multiple samples
This kernel state manager handles multiple POD5/BAM pairs (samples) simultaneously, enabling comparison workflows. Maintains backward compatibility with single-sample API by delegating to the first loaded sample.
Attributes:
| Name | Type | Description |
|---|---|---|
samples |
dict[str, Sample]
|
Dict of Sample objects, keyed by sample name |
reader |
dict[str, Sample]
|
POD5 file reader (first sample, for backward compat) |
pod5_path |
dict[str, Sample]
|
Path to loaded POD5 file (first sample, for backward compat) |
read_ids |
dict[str, Sample]
|
List of read IDs (first sample, for backward compat) |
bam_path |
dict[str, Sample]
|
Path to loaded BAM file (first sample, for backward compat) |
bam_info |
dict[str, Sample]
|
Metadata about loaded BAM file (first sample, for backward compat) |
ref_mapping |
dict[str, Sample]
|
Mapping of reference names to read IDs |
fasta_path |
dict[str, Sample]
|
Path to loaded FASTA file (first sample, for backward compat) |
fasta_info |
dict[str, Sample]
|
Metadata about loaded FASTA file (first sample, for backward compat) |
Examples:
>>> from squiggy import load_pod5, load_bam, load_sample
>>> # Single sample (backward compatible)
>>> load_pod5('data.pod5')
>>> # Multiple samples
>>> load_sample('model_v4.2', 'data_v4.2.pod5', 'align_v4.2.bam')
>>> load_sample('model_v5.0', 'data_v5.0.pod5', 'align_v5.0.bam')
>>> # Access
>>> sample = get_sample('model_v5.0')
>>> print(sample)
Source code in squiggy/io.py
__dir__ ¶
Control what appears in Variables pane - only show public API
Source code in squiggy/io.py
__repr__ ¶
Return informative summary of loaded files
Source code in squiggy/io.py
load_sample ¶
load_sample(
name: str,
pod5_path: str,
bam_path: str | None = None,
fasta_path: str | None = None,
) -> Sample
Load a POD5/BAM/FASTA sample set into this session
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this sample (e.g., 'model_v4.2') |
required |
pod5_path
|
str
|
Path to POD5 file |
required |
bam_path
|
str | None
|
Path to BAM file (optional) |
None
|
fasta_path
|
str | None
|
Path to FASTA file (optional) |
None
|
Returns:
| Type | Description |
|---|---|
Sample
|
The created Sample object |
Examples:
>>> sk = SquiggyKernel()
>>> sample = sk.load_sample('v4.2', 'data_v4.2.pod5', 'align_v4.2.bam')
>>> print(f"Loaded {len(sample._read_ids)} reads")
Source code in squiggy/io.py
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 | |
get_sample ¶
Get a loaded sample by name
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Sample name |
required |
Returns:
| Type | Description |
|---|---|
Sample | None
|
Sample object or None if not found |
Examples:
Source code in squiggy/io.py
list_samples ¶
List all loaded sample names
Returns:
| Type | Description |
|---|---|
list[str]
|
List of sample names in order they were loaded |
Examples:
Source code in squiggy/io.py
remove_sample ¶
Unload a sample and free its resources
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Sample name to remove |
required |
Examples:
Source code in squiggy/io.py
close_pod5 ¶
Close POD5 reader and clear POD5 state (backward compat mode)
Source code in squiggy/io.py
close_bam ¶
close_fasta ¶
close_all ¶
Close all resources and clear all state
Source code in squiggy/io.py
Sample ¶
Represents a single POD5/BAM file pair (sample/experiment)
This class encapsulates all data for one sequencing run or basecalling model, allowing multiple samples to be loaded and compared simultaneously.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Unique identifier for this sample (e.g., 'basecaller_v4.2') |
|
pod5_path |
Path to POD5 file |
|
pod5_reader |
Open POD5 file reader |
|
read_ids |
List of read IDs in this sample |
|
bam_path |
Path to BAM file (optional) |
|
bam_info |
Metadata about BAM file |
|
model_provenance |
Model/basecaller information extracted from BAM header |
|
fasta_path |
Path to FASTA reference file (optional) |
|
fasta_info |
Metadata about FASTA file |
Examples:
>>> sample = Sample('model_v4.2')
>>> sample.load_pod5('data_v4.2.pod5')
>>> sample.load_bam('align_v4.2.bam')
>>> print(f"{sample.name}: {len(sample._read_ids)} reads")
Initialize a new sample with the given name
Source code in squiggy/io.py
__repr__ ¶
Return informative summary of sample state
Source code in squiggy/io.py
close ¶
Close all resources and clear sample state
Source code in squiggy/io.py
LazyReadList ¶
Virtual list of read IDs - only materializes requested slices
Provides O(1) memory overhead instead of O(n) by lazily loading read IDs from POD5 file on demand. Works seamlessly with TypeScript's pagination pattern (offset/limit slicing).
Attributes:
| Name | Type | Description |
|---|---|---|
_reader |
POD5 Reader instance |
|
_cached_length |
int | None
|
Cached total read count (computed once) |
_materialized_ids |
list[str] | None
|
Optional fully materialized list (for caching) |
Examples:
>>> reader = pod5.Reader('file.pod5')
>>> lazy_list = LazyReadList(reader)
>>> len(lazy_list) # Computes length once
1000000
>>> lazy_list[0:100] # Only loads first 100 IDs
['read1', 'read2', ...]
>>> lazy_list[500000] # Loads single ID at position 500000
'read500001'
Source code in squiggy/io.py
__len__ ¶
Compute total read count (cached after first call)
Source code in squiggy/io.py
__getitem__ ¶
Get read ID(s) at index/slice - lazy loading
Source code in squiggy/io.py
__iter__ ¶
materialize ¶
Fully materialize the list (for caching)
Returns:
| Type | Description |
|---|---|
list[str]
|
Complete list of all read IDs |
Source code in squiggy/io.py
__repr__ ¶
Return informative summary of lazy read list
Pod5Index ¶
Fast O(1) read lookup via read_id → file position mapping
Builds an index mapping read IDs to their position in the POD5 file, enabling constant-time lookups instead of O(n) linear scans.
Attributes:
| Name | Type | Description |
|---|---|---|
_index |
dict[str, int]
|
Dict mapping read_id (str) to file position (int) |
Examples:
>>> reader = pod5.Reader('file.pod5')
>>> index = Pod5Index()
>>> index.build(reader)
>>> position = index.get_position('read_abc123')
>>> if position is not None:
... # Use position for fast retrieval
... pass
build ¶
Build index by scanning file once
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader
|
Reader
|
POD5 Reader to index |
required |
get_position ¶
Get file position for read_id (O(1) lookup)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read ID to look up |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
File position or None if not found |
has_read ¶
Check if read exists (O(1))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read ID to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if read exists in index |
__len__ ¶
get_reads_batch ¶
get_reads_batch(
read_ids: list[str], sample_name: str | None = None
) -> dict[str, pod5.ReadRecord]
Fetch multiple reads in a single pass (O(n) instead of O(m×n))
This replaces the nested loop pattern where each read_id triggers a full file scan. Instead, we scan the file once and collect all requested reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_ids
|
list[str]
|
List of read IDs to fetch |
required |
sample_name
|
str | None
|
(Multi-sample mode) Name of sample to get reads from. If None, uses global session reader. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, ReadRecord]
|
Dict mapping read_id to ReadRecord for found reads |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no POD5 file is loaded |
Examples:
>>> from squiggy import load_pod5
>>> from squiggy.io import get_reads_batch
>>> load_pod5('file.pod5')
>>> reads = get_reads_batch(['read1', 'read2', 'read3'])
>>> for read_id, read_obj in reads.items():
... print(f"{read_id}: {len(read_obj.signal)} samples")
Source code in squiggy/io.py
get_read_by_id ¶
Get a single read by ID using index if available
Uses Pod5Index for O(1) lookup if index is built, otherwise falls back to linear scan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read ID to fetch |
required |
sample_name
|
str | None
|
(Multi-sample mode) Name of sample to get read from. If None, uses global session reader. |
None
|
Returns:
| Type | Description |
|---|---|
ReadRecord | None
|
ReadRecord or None if not found |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no POD5 file is loaded |
Examples:
>>> from squiggy import load_pod5
>>> from squiggy.io import get_read_by_id
>>> load_pod5('file.pod5')
>>> read = get_read_by_id('read_abc123')
>>> if read:
... print(f"Signal length: {len(read.signal)}")
Source code in squiggy/io.py
get_reads_for_reference_paginated ¶
get_reads_for_reference_paginated(
reference_name: str,
offset: int = 0,
limit: int | None = None,
) -> list[str]
Get reads for a specific reference with pagination support
This function enables lazy loading of reads by reference for the UI. Returns a slice of read IDs for the specified reference, supporting incremental data fetching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference_name
|
str
|
Name of reference sequence (e.g., 'chr1', 'contig_42') |
required |
offset
|
int
|
Starting index in the read list (default: 0) |
0
|
limit
|
int | None
|
Maximum number of reads to return (default: None = all remaining) |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of read IDs for the specified reference, sliced by offset/limit |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no BAM file is loaded in the session |
KeyError
|
If reference_name is not found in the BAM file |
Examples:
>>> from squiggy import load_bam, load_pod5
>>> from squiggy.io import get_reads_for_reference_paginated
>>> load_pod5('reads.pod5')
>>> load_bam('alignments.bam')
>>> # Get first 500 reads for chr1
>>> reads = get_reads_for_reference_paginated('chr1', offset=0, limit=500)
>>> len(reads)
500
>>> # Get next 500 reads
>>> more_reads = get_reads_for_reference_paginated('chr1', offset=500, limit=500)
Source code in squiggy/io.py
Object-Oriented API¶
Pod5File ¶
POD5 file reader with lazy loading
Provides object-oriented interface to POD5 files without global state. Supports context manager protocol for automatic cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to POD5 file |
required |
Examples:
>>> with Pod5File('data.pod5') as pod5:
... for read in pod5.iter_reads(limit=5):
... print(read.read_id)
Open POD5 file for reading
Source code in squiggy/api.py
__len__ ¶
get_read ¶
Get a single read by ID
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read identifier |
required |
Returns:
| Type | Description |
|---|---|
Read
|
Read object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If read ID not found |
Source code in squiggy/api.py
iter_reads ¶
Iterate over reads (lazy loading)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int | None
|
Maximum number of reads to return (None = all) |
None
|
Yields:
| Type | Description |
|---|---|
Read
|
Read objects |
Examples:
>>> for read in pod5.iter_reads(limit=100):
... print(f"{read.read_id}: {len(read.signal)} samples")
Source code in squiggy/api.py
close ¶
__enter__ ¶
BamFile ¶
BAM alignment file reader
Provides access to alignments, references, and base modifications. Supports context manager protocol for automatic cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to BAM file (must be indexed with .bai) |
required |
Examples:
>>> with BamFile('alignments.bam') as bam:
... alignment = bam.get_alignment('read_001')
... print(alignment.sequence)
Open BAM file for reading
Source code in squiggy/api.py
get_alignment ¶
Get alignment for a specific read
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_id
|
str
|
Read identifier |
required |
Returns:
| Type | Description |
|---|---|
AlignedRead | None
|
AlignedRead object or None if not found or no move table |
Examples:
>>> alignment = bam.get_alignment('read_001')
>>> if alignment:
... for base in alignment.bases:
... print(f"{base.base} at signal {base.signal_start}-{base.signal_end}")
Source code in squiggy/api.py
iter_region ¶
iter_region(
chrom: str,
start: int | None = None,
end: int | None = None,
) -> Iterator[AlignedRead]
Iterate over alignments in a genomic region
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chrom
|
str
|
Chromosome/reference name |
required |
start
|
int | None
|
Start position (0-based, inclusive) |
None
|
end
|
int | None
|
End position (0-based, exclusive) |
None
|
Yields:
| Type | Description |
|---|---|
AlignedRead
|
AlignedRead objects that have move tables |
Examples:
>>> for alignment in bam.iter_region('chr1', 1000, 2000):
... print(f"{alignment.read_id} at {alignment.genomic_start}")
Source code in squiggy/api.py
get_modifications_info ¶
Check if BAM contains base modification tags
Returns:
| Type | Description |
|---|---|
dict
|
Dict with: - has_modifications: bool - modification_types: list of modification codes - sample_count: number of reads checked - has_probabilities: bool (ML tag present) |
Examples:
>>> mod_info = bam.get_modifications_info()
>>> if mod_info['has_modifications']:
... print(f"Found modifications: {mod_info['modification_types']}")
Source code in squiggy/api.py
get_reads_overlapping_motif ¶
get_reads_overlapping_motif(
fasta_file: FastaFile | str | Path,
motif: str,
region: str | None = None,
strand: str = "both",
) -> dict[str, list[AlignedRead]]
Find reads overlapping motif positions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fasta_file
|
FastaFile | str | Path
|
FastaFile object or path to indexed FASTA file |
required |
motif
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH") |
required |
region
|
str | None
|
Optional region filter ("chrom:start-end") |
None
|
strand
|
str
|
Motif search strand ('+', '-', or 'both') |
'both'
|
Returns:
| Type | Description |
|---|---|
dict[str, list[AlignedRead]]
|
Dict mapping motif position keys to lists of AlignedRead objects |
dict[str, list[AlignedRead]]
|
Position key format: "chrom:position:strand" |
Examples:
>>> bam = BamFile('alignments.bam')
>>> fasta = FastaFile('genome.fa')
>>> overlaps = bam.get_reads_overlapping_motif(fasta, 'DRACH', region='chr1:1000-2000')
>>> for position, reads in overlaps.items():
... print(f"{position}: {len(reads)} reads")
... for read in reads:
... print(f" {read.read_id}")
Source code in squiggy/api.py
close ¶
__enter__ ¶
FastaFile ¶
FASTA reference file reader with motif search capabilities
Provides access to reference sequences and motif searching. Requires indexed FASTA file (.fai).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to FASTA file (must be indexed with .fai) |
required |
Examples:
>>> with FastaFile('genome.fa') as fasta:
... # Search for DRACH motif
... for match in fasta.search_motif('DRACH', region='chr1:1000-2000'):
... print(f"{match.chrom}:{match.position} {match.sequence}")
Open FASTA file for reading
Source code in squiggy/api.py
fetch ¶
Fetch sequence from reference
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chrom
|
str
|
Chromosome/reference name |
required |
start
|
int | None
|
Start position (0-based, inclusive) |
None
|
end
|
int | None
|
End position (0-based, exclusive) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
DNA sequence string |
Examples:
>>> fasta = FastaFile('genome.fa')
>>> seq = fasta.fetch('chr1', 1000, 1100)
>>> print(seq) # 100 bp sequence
Source code in squiggy/api.py
search_motif ¶
search_motif(
motif: str,
region: str | None = None,
strand: str = "both",
) -> Iterator[MotifMatch]
Search for motif matches in FASTA file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
motif
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH", "YGCY") |
required |
region
|
str | None
|
Optional region filter ("chrom", "chrom:start", "chrom:start-end") Positions are 1-based in input |
None
|
strand
|
str
|
Search strand ('+', '-', or 'both') |
'both'
|
Yields:
| Type | Description |
|---|---|
MotifMatch
|
MotifMatch objects for each match found |
Examples:
>>> fasta = FastaFile('genome.fa')
>>> matches = list(fasta.search_motif('DRACH', region='chr1:1000-2000'))
>>> for match in matches:
... print(f"{match.chrom}:{match.position+1} {match.sequence} ({match.strand})")
Source code in squiggy/api.py
count_motifs ¶
Count total motif matches
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
motif
|
str
|
IUPAC nucleotide pattern |
required |
region
|
str | None
|
Optional region filter |
None
|
strand
|
str
|
Search strand ('+', '-', or 'both') |
'both'
|
Returns:
| Type | Description |
|---|---|
int
|
Total number of matches |
Examples:
>>> fasta = FastaFile('genome.fa')
>>> count = fasta.count_motifs('DRACH', region='chr1')
>>> print(f"Found {count} DRACH motifs")
Source code in squiggy/api.py
close ¶
__enter__ ¶
Read ¶
A single POD5 read with signal data
Provides access to raw signal, normalization, alignment, and plotting.
Attributes:
| Name | Type | Description |
|---|---|---|
read_id |
str
|
Read identifier |
signal |
ndarray
|
Raw signal data (numpy array) |
sample_rate |
int
|
Sampling rate in Hz |
Initialize Read from pod5.Read object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pod5_read
|
ReadRecord
|
pod5.ReadRecord object |
required |
parent_file
|
Pod5File
|
Parent Pod5File object |
required |
Source code in squiggy/api.py
get_normalized ¶
Get normalized signal
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | NormalizationMethod
|
Normalization method ('NONE', 'ZNORM', 'MEDIAN', 'MAD') |
'ZNORM'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized signal as numpy array |
Examples:
>>> read = pod5.get_read('read_001')
>>> znorm_signal = read.get_normalized('ZNORM')
>>> mad_signal = read.get_normalized('MAD')
Source code in squiggy/api.py
get_alignment ¶
get_alignment(
bam_file: BamFile | None = None,
bam_path: str | Path | None = None,
) -> AlignedRead | None
Get alignment information from BAM file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
BamFile | None
|
BamFile object (recommended) |
None
|
bam_path
|
str | Path | None
|
Path to BAM file (alternative to bam_file) |
None
|
Returns:
| Type | Description |
|---|---|
AlignedRead | None
|
AlignedRead object or None if not found or no move table |
Examples:
>>> bam = BamFile('alignments.bam')
>>> alignment = read.get_alignment(bam)
>>> if alignment:
... print(f"Aligned to {alignment.chromosome}:{alignment.genomic_start}")
Source code in squiggy/api.py
plot ¶
plot(
mode: str = "SINGLE",
normalization: str = "ZNORM",
theme: str = "LIGHT",
downsample: int = None,
show_dwell_time: bool = False,
show_labels: bool = True,
position_label_interval: int = None,
scale_dwell_time: bool = False,
min_mod_probability: float = 0.5,
enabled_mod_types: list | None = None,
show_signal_points: bool = False,
bam_file: BamFile | None = None,
) -> BokehFigure
Generate Bokeh plot for this read
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
Plot mode ('SINGLE', 'EVENTALIGN') |
'SINGLE'
|
normalization
|
str
|
Normalization method ('NONE', 'ZNORM', 'MEDIAN', 'MAD') |
'ZNORM'
|
theme
|
str
|
Color theme ('LIGHT', 'DARK') |
'LIGHT'
|
downsample
|
int
|
Downsampling factor (1 = no downsampling) |
None
|
show_dwell_time
|
bool
|
Color bases by dwell time (EVENTALIGN mode) |
False
|
show_labels
|
bool
|
Show base labels (EVENTALIGN mode) |
True
|
position_label_interval
|
int
|
Interval for position labels |
None
|
scale_dwell_time
|
bool
|
Scale x-axis by cumulative dwell time |
False
|
min_mod_probability
|
float
|
Minimum probability for showing modifications |
0.5
|
enabled_mod_types
|
list | None
|
List of modification types to show (None = all) |
None
|
show_signal_points
|
bool
|
Show individual signal points |
False
|
bam_file
|
BamFile | None
|
BamFile object (required for EVENTALIGN mode) |
None
|
Returns:
| Type | Description |
|---|---|
figure
|
Bokeh Figure object (can be customized before display) |
Examples:
>>> fig = read.plot(mode='EVENTALIGN', bam_file=bam)
>>> fig.title.text = "My Custom Title"
>>> from bokeh.plotting import show
>>> show(fig)
Source code in squiggy/api.py
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 | |
figure_to_html ¶
Convert Bokeh Figure to HTML string
Utility function for converting Bokeh figures to standalone HTML. Useful when you need HTML output instead of interactive display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
figure
|
Bokeh Figure object |
required |
title
|
str
|
HTML document title |
'Squiggy Plot'
|
Returns:
| Type | Description |
|---|---|
str
|
HTML string with embedded Bokeh plot |
Examples:
>>> fig = read.plot()
>>> html = figure_to_html(fig)
>>> with open('plot.html', 'w') as f:
... f.write(html)
Source code in squiggy/api.py
Alignment¶
BaseAnnotation
dataclass
¶
BaseAnnotation(
base: str,
position: int,
signal_start: int,
signal_end: int,
genomic_pos: int | None = None,
quality: int | None = None,
)
Single base annotation with signal alignment information
AlignedRead
dataclass
¶
AlignedRead(
read_id: str,
sequence: str,
bases: list[BaseAnnotation],
chromosome: str | None = None,
genomic_start: int | None = None,
genomic_end: int | None = None,
strand: str | None = None,
is_reverse: bool = False,
modifications: list = list(),
)
POD5 read with base call annotations
extract_alignment_from_bam ¶
Extract alignment information for a read from BAM file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_path
|
Path
|
Path to BAM file |
required |
read_id
|
str
|
Read identifier to search for |
required |
Returns:
| Type | Description |
|---|---|
AlignedRead | None
|
AlignedRead object or None if not found |
Source code in squiggy/alignment.py
get_base_to_signal_mapping ¶
Extract sequence and signal mapping from AlignedRead
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aligned_read
|
AlignedRead
|
AlignedRead object with base annotations |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[str, ndarray]
|
(sequence, seq_to_sig_map) compatible with existing plotter |
Source code in squiggy/alignment.py
Modifications¶
ModificationAnnotation
dataclass
¶
ModificationAnnotation(
position: int,
genomic_pos: int | None,
mod_code: str | int,
canonical_base: str,
probability: float,
signal_start: int,
signal_end: int,
)
Single base modification annotation with probability and signal alignment
extract_modifications_from_alignment ¶
extract_modifications_from_alignment(
alignment: AlignedSegment, bases: list
) -> list[ModificationAnnotation]
Extract modification annotations from a BAM alignment
Parses MM/ML tags via pysam's modified_bases property and maps modifications to signal positions using base annotations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alignment
|
AlignedSegment
|
pysam AlignmentSegment object |
required |
bases
|
list
|
List of BaseAnnotation objects with signal mappings |
required |
Returns:
| Type | Description |
|---|---|
list[ModificationAnnotation]
|
List of ModificationAnnotation objects (empty if no modifications) |
Note
The modified_bases property returns a dict with format: {(canonical_base, strand, mod_code): [(position, quality), ...]} where: - canonical_base: str (e.g., 'C', 'A') - strand: int (0=forward, 1=reverse) - mod_code: str or int (e.g., 'm' for 5mC, 17596 for inosine) - position: int (base position in read, 0-indexed) - quality: int (encoded as 256*probability, or -1 if unknown)
Examples:
>>> from squiggy.alignment import extract_alignment_from_bam
>>> aligned_read = extract_alignment_from_bam(bam_path, read_id)
>>> mods = extract_modifications_from_alignment(alignment, aligned_read.bases)
>>> for mod in mods:
... print(f"{mod.mod_code} at pos {mod.position}: p={mod.probability}")
Source code in squiggy/modifications.py
detect_modification_provenance ¶
Detect modification calling provenance from BAM header
Parses @PG (program) header lines to extract basecaller information, version, and model details. Useful for displaying metadata and understanding modification calling parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path
|
Path to BAM file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with keys: - basecaller: str (e.g., "dorado", "remora", "guppy", or "Unknown") - version: str (e.g., "0.8.0" or "Unknown") - model: str (model name or "Unknown") - full_info: str (complete @PG command line for reference) - unknown: bool (True if provenance could not be determined) |
Examples:
>>> provenance = detect_modification_provenance(bam_path)
>>> if not provenance["unknown"]:
... print(f"Basecaller: {provenance['basecaller']} v{provenance['version']}")
... print(f"Model: {provenance['model']}")
Source code in squiggy/modifications.py
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 | |
Motif Search¶
MotifMatch
dataclass
¶
Represents a single motif match in a genomic sequence
Attributes:
| Name | Type | Description |
|---|---|---|
chrom |
str
|
Chromosome/reference name |
position |
int
|
0-based genomic position of match start |
sequence |
str
|
Matched sequence |
strand |
Literal['+', '-']
|
Strand ('+' or '-') |
length |
int
|
Length of matched sequence |
iupac_to_regex ¶
Convert IUPAC nucleotide pattern to regular expression
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH", "YGCY") |
required |
Returns:
| Type | Description |
|---|---|
str
|
Regular expression pattern string |
Examples:
Raises:
| Type | Description |
|---|---|
ValueError
|
If pattern contains invalid IUPAC codes |
Source code in squiggy/motif.py
search_motif ¶
search_motif(
fasta_file: str | Path,
motif: str,
region: str | None = None,
strand: Literal["+", "-", "both"] = "both",
) -> Iterator[MotifMatch]
Search for motif matches in FASTA file
Lazy iteration over matches for memory efficiency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fasta_file
|
str | Path
|
Path to indexed FASTA file (.fai required) |
required |
motif
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH", "YGCY") |
required |
region
|
str | None
|
Optional region filter ("chrom", "chrom:start", "chrom:start-end") Positions are 1-based in input, converted to 0-based internally |
None
|
strand
|
Literal['+', '-', 'both']
|
Search strand ('+', '-', or 'both') |
'both'
|
Yields:
| Type | Description |
|---|---|
MotifMatch
|
MotifMatch objects for each match found |
Examples:
>>> matches = list(search_motif("genome.fa", "DRACH", region="chr1:1000-2000"))
>>> for match in matches:
... print(f"{match.chrom}:{match.position+1} {match.sequence} ({match.strand})")
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If FASTA file or index not found |
ValueError
|
If motif contains invalid IUPAC codes or region format is invalid |
Source code in squiggy/motif.py
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 | |
count_motifs ¶
count_motifs(
fasta_file: str | Path,
motif: str,
region: str | None = None,
strand: Literal["+", "-", "both"] = "both",
) -> int
Count total motif matches in FASTA file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fasta_file
|
str | Path
|
Path to indexed FASTA file (.fai required) |
required |
motif
|
str
|
IUPAC nucleotide pattern (e.g., "DRACH", "YGCY") |
required |
region
|
str | None
|
Optional region filter ("chrom:start-end") |
None
|
strand
|
Literal['+', '-', 'both']
|
Search strand ('+', '-', or 'both') |
'both'
|
Returns:
| Type | Description |
|---|---|
int
|
Total number of matches |
Examples:
>>> count = count_motifs("genome.fa", "DRACH", region="chr1")
>>> print(f"Found {count} DRACH motifs on chr1")
Source code in squiggy/motif.py
IUPAC_CODES
module-attribute
¶
IUPAC_CODES = {
"A": "A",
"C": "C",
"G": "G",
"T": "T",
"U": "T",
"R": "[AG]",
"Y": "[CT]",
"S": "[GC]",
"W": "[AT]",
"K": "[GT]",
"M": "[AC]",
"B": "[CGT]",
"D": "[AGT]",
"H": "[ACT]",
"V": "[ACG]",
"N": "[ACGT]",
}
Normalization¶
normalize_signal ¶
Normalize signal data using specified method
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ndarray
|
Raw signal array (numpy array) |
required |
method
|
NormalizationMethod
|
Normalization method to apply |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized signal array |
Source code in squiggy/normalization.py
NormalizationMethod ¶
Bases: Enum
Signal normalization methods
Constants¶
PlotMode ¶
Bases: Enum
Available plotting modes for signal visualization
Theme ¶
Bases: Enum
Application theme modes
BASE_COLORS
module-attribute
¶
BASE_COLORS = {
"A": "#009E73",
"C": "#F0E442",
"G": "#0072B2",
"T": "#D55E00",
"U": "#D55E00",
"N": "#808080",
}
BASE_COLORS_DARK
module-attribute
¶
BASE_COLORS_DARK = {
"A": "#00d9a3",
"C": "#fff34d",
"G": "#4da6ff",
"T": "#ff8c42",
"U": "#ff8c42",
"N": "#999999",
}
Plot Strategies¶
create_plot_strategy ¶
Factory function to create the appropriate plot strategy
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plot_mode
|
PlotMode
|
PlotMode enum specifying which plot type to create |
required |
theme
|
Theme
|
Theme enum (LIGHT or DARK) |
required |
Returns:
| Type | Description |
|---|---|
PlotStrategy
|
PlotStrategy instance for the specified mode |
Raises:
| Type | Description |
|---|---|
ValueError
|
If plot_mode is not recognized |
Examples:
>>> from squiggy.plot_factory import create_plot_strategy
>>> from squiggy.constants import PlotMode, Theme
>>>
>>> strategy = create_plot_strategy(PlotMode.SINGLE, Theme.LIGHT)
>>> html, fig = strategy.create_plot(data, options)
Source code in squiggy/plot_factory.py
Utilities¶
Signal Processing¶
get_basecall_data ¶
Extract basecall sequence and signal mapping from BAM file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path
|
Path to BAM file |
required |
read_id
|
str
|
Read identifier to search for |
required |
Returns:
| Type | Description |
|---|---|
tuple[str | None, ndarray | None]
|
(sequence, seq_to_sig_map) or (None, None) if not available |
Source code in squiggy/utils.py
downsample_signal ¶
Downsample signal array by taking every Nth point
Reduces the number of data points for faster plotting while preserving the overall shape of the signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ndarray
|
Raw signal array (numpy array) |
required |
downsample_factor
|
int
|
Factor by which to downsample (None = use default, 1 = no downsampling) |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Downsampled signal array |
Source code in squiggy/utils.py
BAM/Alignment Utilities¶
get_bam_references ¶
Get list of reference sequences from BAM file with read counts
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path
|
Path to BAM file |
required |
Returns:
| Type | Description |
|---|---|
list[dict]
|
List of dicts with keys: - name: Reference name - length: Reference sequence length - read_count: Number of aligned reads (requires index) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If BAM file doesn't exist |
Source code in squiggy/utils.py
get_reads_in_region ¶
get_reads_in_region(
bam_file: Path,
chromosome: str,
start: int | None = None,
end: int | None = None,
) -> dict
Query BAM file for reads aligning to a specific region
Requires BAM file to be indexed (.bai file must exist).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path
|
Path to BAM file |
required |
chromosome
|
str
|
Chromosome/reference name |
required |
start
|
int | None
|
Start position (0-based, inclusive) or None for entire chromosome |
None
|
end
|
int | None
|
End position (0-based, exclusive) or None for entire chromosome |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary mapping read_id -> alignment_info with keys: - read_id: Read identifier - chromosome: Reference name - start: Alignment start position - end: Alignment end position - strand: '+' or '-' - is_reverse: Boolean |
Raises:
| Type | Description |
|---|---|
ValueError
|
If BAM file is not indexed or region is invalid |
FileNotFoundError
|
If BAM file doesn't exist |
Source code in squiggy/utils.py
get_reference_sequence_for_read ¶
Extract the reference sequence for a given aligned read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path to BAM file |
required | |
read_id
|
Read identifier |
required |
Returns:
| Type | Description |
|---|---|
|
Tuple of (reference_sequence, reference_start, aligned_read) |
|
|
Returns (None, None, None) if read not found or not aligned |
Source code in squiggy/utils.py
open_bam_safe ¶
Context manager for safely opening and closing BAM files
This utility eliminates duplicate BAM file handling code by providing a consistent pattern for opening BAM files with proper resource cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_path
|
str | Path
|
Path to BAM file (string or Path object) |
required |
Yields:
| Type | Description |
|---|---|
|
pysam.AlignmentFile: Opened BAM file handle |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If BAM file doesn't exist |
IOError
|
If BAM file cannot be opened |
Examples:
>>> from squiggy.utils import open_bam_safe
>>> with open_bam_safe("alignments.bam") as bam:
... for read in bam:
... print(read.query_name)
>>> # Automatically closes even on error
>>> with open_bam_safe("alignments.bam") as bam:
... references = list(bam.references)
Source code in squiggy/utils.py
validate_sq_headers ¶
Validate that two BAM files have matching reference sequences
Compares the SQ (sequence) headers from two BAM files to ensure they have the same references. This is important for comparison analysis to ensure reads can be meaningfully compared.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file_a
|
str
|
Path to first BAM file |
required |
bam_file_b
|
str
|
Path to second BAM file |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict with validation results: - is_valid (bool): True if references match - references_a (list): References in file A - references_b (list): References in file B - missing_in_b (list): References in A but not B - missing_in_a (list): References in B but not A - matching_count (int): Number of matching references |
Examples:
>>> from squiggy.utils import validate_sq_headers
>>> result = validate_sq_headers('align_a.bam', 'align_b.bam')
>>> if result['is_valid']:
... print("References match!")
... else:
... print(f"Missing in B: {result['missing_in_b']}")
Source code in squiggy/utils.py
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 | |
index_bam_file ¶
Generate BAM index file (.bai)
Creates a .bai index file for the given BAM file using pysam.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
Path to BAM file |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If BAM file doesn't exist |
Exception
|
If indexing fails |
Source code in squiggy/utils.py
General Utilities¶
parse_region ¶
Parse a genomic region string into components
Supports formats: - "chr1" (entire chromosome) - "chr1:1000" (single position) - "chr1:1000-2000" (range) - "chr1:1,000-2,000" (with commas)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
region_str
|
str
|
Region string to parse |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
(chromosome, start, end) where start/end are None if not specified. |
int | None
|
Returns (None, None, None) if parsing fails |
Examples:
>>> parse_region("chr1")
("chr1", None, None)
>>> parse_region("chr1:1000-2000")
("chr1", 1000, 2000)
Source code in squiggy/utils.py
reverse_complement ¶
Return the reverse complement of a DNA sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq
|
str
|
DNA sequence string (A, C, G, T, N) |
required |
Returns:
| Type | Description |
|---|---|
str
|
Reverse complement sequence |
Source code in squiggy/utils.py
get_test_data_path ¶
Get the path to the bundled test data directory
Returns the path to the squiggy/data directory which contains test/demo files: - yeast_trna_reads.pod5 - yeast_trna_mappings.bam - yeast_trna_mappings.bam.bai - yeast_trna.fa - yeast_trna.fa.fai
Returns:
| Name | Type | Description |
|---|---|---|
str |
Path to the squiggy/data directory |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If data directory cannot be found |
Examples:
>>> from pathlib import Path
>>> data_dir = Path(get_test_data_path())
>>> pod5_file = data_dir / 'yeast_trna_reads.pod5'
Source code in squiggy/utils.py
extract_model_provenance ¶
Extract basecalling model information from BAM file @PG headers
The @PG header record contains information about the program used to generate the alignments. For ONT sequencing, this typically includes basecalling information from guppy or dorado.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bam_file
|
str
|
Path to BAM file |
required |
Returns:
| Type | Description |
|---|---|
ModelProvenance
|
ModelProvenance object with extracted metadata |
Examples:
>>> from squiggy.utils import extract_model_provenance
>>> provenance = extract_model_provenance('alignments.bam')
>>> print(provenance.model_name)
>>> print(provenance.basecalling_model)
Source code in squiggy/utils.py
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 | |
ModelProvenance
dataclass
¶
ModelProvenance(
model_name: str | None = None,
model_version: str | None = None,
flow_cell_kit: str | None = None,
basecalling_model: str | None = None,
command_line: str | None = None,
)
Metadata about the basecalling model used to generate a dataset
Extracted from BAM file @PG headers, which contain information about the basecalling process and model version.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str | None
|
Name of the basecalling model (e.g., "guppy", "dorado") |
model_version |
str | None
|
Version of the basecalling model |
flow_cell_kit |
str | None
|
Sequencing kit used |
basecalling_model |
str | None
|
Specific basecalling model identifier |
command_line |
str | None
|
Full command line used for basecalling |
__repr__ ¶
Return informative summary of model provenance
Source code in squiggy/utils.py
matches ¶
Check if two ModelProvenance instances describe the same model
Source code in squiggy/utils.py
parse_plot_parameters ¶
parse_plot_parameters(
mode: str | None = None,
normalization: str = "ZNORM",
theme: str = "LIGHT",
)
Parse and validate plot parameters (mode, normalization, theme)
This utility function eliminates duplicate parameter parsing code across plotting functions by centralizing the conversion from string parameters to enum values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str | None
|
Plot mode string (e.g., "SINGLE", "OVERLAY", "EVENTALIGN", "AGGREGATE"). If None, only normalization and theme are parsed. |
None
|
normalization
|
str
|
Normalization method string (default: "ZNORM"). Valid values: "NONE", "ZNORM", "MEDIAN", "MAD" |
'ZNORM'
|
theme
|
str
|
Color theme string (default: "LIGHT"). Valid values: "LIGHT", "DARK" |
'LIGHT'
|
Returns:
| Type | Description |
|---|---|
|
Dictionary with parsed enum values: |
|
|
|
|
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If invalid mode, normalization, or theme string provided |
Examples:
>>> params = parse_plot_parameters(mode="SINGLE", normalization="ZNORM", theme="LIGHT")
>>> params["mode"]
<PlotMode.SINGLE: 'SINGLE'>
>>> params = parse_plot_parameters(normalization="MEDIAN", theme="DARK")
>>> params["normalization"]
<NormalizationMethod.MEDIAN: 'MEDIAN'>