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
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
1042
1043
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
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! Unified IGD (Integrated Genome Database) implementation.
//!
//! Provides a single `Igd` struct that supports both construction and querying
//! in-memory, with optional disk persistence. This replaces the split between
//! `igd_t` (creation-only) and `igd_t_from_disk` (query-only) in the legacy API.
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write as IoWrite};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt};
use gtars_core::consts::{BED_FILE_EXTENSION, GZ_FILE_EXTENSION};
use gtars_core::models::RegionSet;
use gtars_core::utils::get_dynamic_reader;
use crate::create::MAX_CHROM_NAME_LEN;
/// A single genomic interval record within the IGD index.
#[derive(Default, Clone, Debug)]
pub struct Record {
/// Index of the source file (DB set) this interval came from.
pub file_idx: u32,
/// Region start position (0-based).
pub start: i32,
/// Region end position (exclusive).
pub end: i32,
/// BED score value (preserved for backward compat; LOLA ignores this).
pub value: i32,
}
/// A tile (bin) within a contig, holding records that start in this tile's range.
#[derive(Default, Clone, Debug)]
pub struct Tile {
/// Genomic interval records in this tile, sorted by start position after finalization.
pub records: Vec<Record>,
}
/// A contig (chromosome) within the IGD index.
#[derive(Default, Clone, Debug)]
pub struct Contig {
/// Chromosome name (e.g., "chr1").
pub name: String,
/// Tiles for this contig. Tile i covers positions [i*nbp, (i+1)*nbp).
pub tiles: Vec<Tile>,
}
/// Metadata about a source file indexed into the IGD.
#[derive(Default, Clone, Debug)]
pub struct FileInfo {
/// Filename of the source BED file.
pub filename: String,
/// Number of regions from this file.
pub num_regions: u32,
/// Average region width in base pairs.
pub avg_region_width: f64,
}
/// Unified IGD index: can be built in memory or loaded from disk, and queried directly.
#[derive(Debug)]
pub struct Igd {
/// Tile/bin size in base pairs (default 16384 = 2^14).
pub nbp: i32,
/// Per-chromosome data.
pub(crate) contigs: Vec<Contig>,
/// Per-file metadata (filename, region count, avg width).
pub file_info: Vec<FileInfo>,
/// Chromosome name → index into `contigs`.
chrom_index: HashMap<String, usize>,
/// Whether tiles have been sorted (required before querying).
finalized: bool,
}
impl Igd {
// -----------------------------------------------------------------------
// Construction
// -----------------------------------------------------------------------
/// Create a new empty IGD with default tile size (16384bp).
pub fn new() -> Self {
Self::with_tile_size(16384)
}
/// Create a new empty IGD with a custom tile size.
pub fn with_tile_size(nbp: i32) -> Self {
Igd {
nbp,
contigs: Vec::new(),
file_info: Vec::new(),
chrom_index: HashMap::new(),
finalized: false,
}
}
/// Access the per-chromosome contig data.
pub fn contigs(&self) -> &[Contig] {
&self.contigs
}
/// Add a single interval from a given file index. The IGD must not yet be finalized.
///
/// Intervals with `start >= end` or negative coordinates are silently skipped.
/// Note: coordinates are stored as `i32`, limiting effective range to ~2.1 Gbp.
/// Values exceeding `i32::MAX` should not be passed.
///
/// # Panics
///
/// Panics if called after [`finalize`](Self::finalize).
pub fn add(&mut self, chrom: &str, start: i32, end: i32, value: i32, file_idx: u32) {
assert!(
!self.finalized,
"Cannot add intervals after finalization"
);
if start < 0 || end < 0 || start >= end {
return;
}
let n1 = start / self.nbp;
let n2 = (end - 1) / self.nbp;
let needed_tiles = (n2 + 1) as usize;
// Get or create contig
let ctg_idx = if let Some(&idx) = self.chrom_index.get(chrom) {
idx
} else {
let idx = self.contigs.len();
self.contigs.push(Contig {
name: chrom.to_string(),
tiles: Vec::new(),
});
self.chrom_index.insert(chrom.to_string(), idx);
idx
};
let contig = &mut self.contigs[ctg_idx];
// Expand tiles if needed
if contig.tiles.len() < needed_tiles {
contig.tiles.resize_with(needed_tiles, Tile::default);
}
// Add record to each spanned tile
let record = Record {
file_idx,
start,
end,
value,
};
for i in n1..=n2 {
contig.tiles[i as usize].records.push(record.clone());
}
}
/// Finalize the IGD: sort all tile records by start position.
/// Must be called after all intervals are added and before any queries.
pub fn finalize(&mut self) {
if self.finalized {
return;
}
for contig in &mut self.contigs {
for tile in &mut contig.tiles {
tile.records.sort_by_key(|r| r.start);
}
}
self.finalized = true;
}
/// Build an IGD from a directory of BED files.
pub fn from_bed_dir(path: &Path) -> anyhow::Result<Self> {
let mut bed_files: Vec<PathBuf> = Vec::new();
// Collect BED/gz files (validation happens during the parse pass)
for entry in fs::read_dir(path)? {
let p = entry?.path();
if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
if (ext == BED_FILE_EXTENSION.trim_start_matches('.')
|| ext == GZ_FILE_EXTENSION.trim_start_matches('.'))
&& p.is_file()
{
bed_files.push(p);
}
}
}
bed_files.sort(); // deterministic order
Self::from_bed_files(bed_files)
}
/// Build an IGD from an explicit list of BED file paths.
pub fn from_bed_files(paths: impl IntoIterator<Item = PathBuf>) -> anyhow::Result<Self> {
let mut igd = Igd::new();
let mut file_infos: Vec<FileInfo> = Vec::new();
for bed_path in paths {
let reader = match get_dynamic_reader(&bed_path) {
Ok(r) => r,
Err(_) => continue,
};
let mut count: u32 = 0;
let mut total_width: u64 = 0;
let mut has_valid_line = false;
let file_idx = file_infos.len();
for line in reader.lines() {
let line = match line {
Ok(l) => l,
Err(_) => continue,
};
if let Some((chrom, start, end, score)) = Self::parse_bed_line(&line) {
has_valid_line = true;
if start >= 0 {
igd.add(&chrom, start, end, score, file_idx as u32);
count += 1;
total_width += (end - start) as u64;
}
}
}
// Skip files with no parseable BED lines
if !has_valid_line {
continue;
}
let filename = bed_path
.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default();
file_infos.push(FileInfo {
filename,
num_regions: count,
avg_region_width: if count > 0 {
total_width as f64 / count as f64
} else {
0.0
},
});
}
igd.file_info = file_infos;
igd.finalize();
Ok(igd)
}
/// Build an IGD from an iterator of (filename, regions) pairs.
/// Each region is (chrom, start, end). For BEDbase integration where
/// regions come from an API rather than disk.
pub fn from_region_sets<I>(sets: I) -> Self
where
I: IntoIterator<Item = (String, Vec<(String, i32, i32)>)>,
{
let mut igd = Igd::new();
let mut file_infos: Vec<FileInfo> = Vec::new();
for (file_idx, (filename, regions)) in sets.into_iter().enumerate() {
let mut count: u32 = 0;
let mut total_width: u64 = 0;
for (chrom, start, end) in ®ions {
if *start < *end {
igd.add(chrom, *start, *end, 0, file_idx as u32);
count += 1;
total_width += (*end - *start) as u64;
}
}
file_infos.push(FileInfo {
filename,
num_regions: count,
avg_region_width: if count > 0 {
total_width as f64 / count as f64
} else {
0.0
},
});
}
igd.file_info = file_infos;
igd.finalize();
igd
}
/// Build an IGD from a vec of gtars-core RegionSets with associated filenames.
pub fn from_named_region_sets(sets: &[(String, &RegionSet)]) -> Self {
let mut igd = Igd::new();
let mut file_infos: Vec<FileInfo> = Vec::with_capacity(sets.len());
for (file_idx, (filename, region_set)) in sets.iter().enumerate() {
let mut count: u32 = 0;
let mut total_width: u64 = 0;
for region in ®ion_set.regions {
if region.start < region.end {
let start = region.start as i32;
let end = region.end as i32;
igd.add(®ion.chr, start, end, 0, file_idx as u32);
count += 1;
total_width += (end - start) as u64;
}
}
file_infos.push(FileInfo {
filename: filename.clone(),
num_regions: count,
avg_region_width: if count > 0 {
total_width as f64 / count as f64
} else {
0.0
},
});
}
igd.file_info = file_infos;
igd.finalize();
igd
}
/// Load an IGD from a pre-built `.igd` file on disk.
pub fn from_igd_file(path: &Path) -> anyhow::Result<Self> {
let file = File::open(path)?;
let mut reader = BufReader::new(file);
// Read header
let mut buf4 = [0u8; 4];
reader.read_exact(&mut buf4)?;
let nbp = i32::from_le_bytes(buf4);
reader.read_exact(&mut buf4)?;
let g_type = i32::from_le_bytes(buf4);
reader.read_exact(&mut buf4)?;
let n_ctg = i32::from_le_bytes(buf4);
// Read tiles-per-contig
let mut n_tiles: Vec<i32> = Vec::with_capacity(n_ctg as usize);
for _ in 0..n_ctg {
reader.read_exact(&mut buf4)?;
n_tiles.push(i32::from_le_bytes(buf4));
}
// Read region counts per tile
let mut n_cnts: Vec<Vec<i32>> = Vec::with_capacity(n_ctg as usize);
for i in 0..n_ctg as usize {
let k = n_tiles[i];
let mut counts = Vec::with_capacity(k as usize);
for _ in 0..k {
counts.push(reader.read_i32::<LittleEndian>()?);
}
n_cnts.push(counts);
}
// Read chromosome names
let mut chrom_names: Vec<String> = Vec::with_capacity(n_ctg as usize);
for _ in 0..n_ctg {
let mut buf = [0u8; MAX_CHROM_NAME_LEN];
reader.read_exact(&mut buf)?;
let name = String::from_utf8_lossy(&buf)
.trim_matches('\0')
.to_string();
chrom_names.push(name);
}
// Determine record size
let rec_size: usize = if g_type == 0 { 12 } else { 16 };
// Read region data into tiles
let mut contigs: Vec<Contig> = Vec::with_capacity(n_ctg as usize);
let mut chrom_index: HashMap<String, usize> = HashMap::new();
for i in 0..n_ctg as usize {
let mut tiles: Vec<Tile> = Vec::with_capacity(n_tiles[i] as usize);
for j in 0..n_tiles[i] as usize {
let count = n_cnts[i][j];
let mut records = Vec::with_capacity(count as usize);
for _ in 0..count {
let idx = reader.read_i32::<LittleEndian>()?;
let start = reader.read_i32::<LittleEndian>()?;
let end = reader.read_i32::<LittleEndian>()?;
let value = if rec_size == 16 {
reader.read_i32::<LittleEndian>()?
} else {
0
};
records.push(Record {
file_idx: idx as u32,
start,
end,
value,
});
}
tiles.push(Tile { records });
}
chrom_index.insert(chrom_names[i].clone(), i);
contigs.push(Contig {
name: chrom_names[i].clone(),
tiles,
});
}
// Load file info from the companion .tsv file
let tsv_path = path.with_extension("tsv");
let file_info = if tsv_path.exists() {
Self::load_file_info_tsv(&tsv_path)?
} else {
Vec::new()
};
Ok(Igd {
nbp,
contigs,
file_info,
chrom_index,
finalized: true, // disk data is already sorted
})
}
/// Save the IGD to a `.igd` binary file and companion `.tsv` metadata.
///
/// # Panics
///
/// Panics if called before [`finalize`](Self::finalize).
pub fn save(&self, path: &Path) -> anyhow::Result<()> {
assert!(self.finalized, "Must finalize before saving");
// Write main .igd file
let mut buffer = Vec::new();
let g_type: i32 = 1; // gType=1 means 16-byte records with value field
// Header
buffer.write_all(&self.nbp.to_le_bytes())?;
buffer.write_all(&g_type.to_le_bytes())?;
buffer.write_all(&(self.contigs.len() as i32).to_le_bytes())?;
// Tiles per contig
for contig in &self.contigs {
buffer.write_all(&(contig.tiles.len() as i32).to_le_bytes())?;
}
// Region counts per tile
for contig in &self.contigs {
for tile in &contig.tiles {
buffer.write_all(&(tile.records.len() as i32).to_le_bytes())?;
}
}
// Chromosome names (40 bytes each, null-padded)
for contig in &self.contigs {
let mut name_bytes = contig.name.as_bytes().to_vec();
name_bytes.resize(MAX_CHROM_NAME_LEN, 0);
buffer.write_all(&name_bytes)?;
}
// Region data (sorted within each tile)
for contig in &self.contigs {
for tile in &contig.tiles {
for rec in &tile.records {
buffer.write_all(&(rec.file_idx as i32).to_le_bytes())?;
buffer.write_all(&rec.start.to_le_bytes())?;
buffer.write_all(&rec.end.to_le_bytes())?;
buffer.write_all(&rec.value.to_le_bytes())?;
}
}
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, &buffer)?;
// Write companion .tsv
let tsv_path = path.with_extension("tsv");
let mut tsv = String::new();
tsv.push_str("Index\tFile\tNumber of Regions\tAvg size\n");
for (i, fi) in self.file_info.iter().enumerate() {
tsv.push_str(&format!(
"{}\t{}\t{}\t{:.2}\n",
i, fi.filename, fi.num_regions, fi.avg_region_width
));
}
fs::write(tsv_path, tsv)?;
Ok(())
}
// -----------------------------------------------------------------------
// Querying
// -----------------------------------------------------------------------
/// Query a single interval, incrementing hit counts per file.
/// Returns the number of overlaps found.
///
/// `hits` must have length >= `self.file_info.len()`.
/// `min_overlap` is the minimum number of overlapping base pairs required (default 1).
///
/// Intervals with `start >= end` or `end <= 0` return 0 immediately.
/// Negative `start` is clamped to 0.
///
/// # Panics
///
/// Panics if called before [`finalize`](Self::finalize).
pub fn count_overlaps(
&self,
chrom: &str,
start: i32,
end: i32,
min_overlap: i32,
hits: &mut [u64],
) -> u32 {
assert!(self.finalized, "Must finalize before querying");
if start >= end || end <= 0 {
return 0;
}
let start = start.max(0);
let ctg_idx = match self.chrom_index.get(chrom) {
Some(&idx) => idx,
None => return 0,
};
debug_assert!(hits.len() >= self.file_info.len(), "hits buffer too small");
let mut total_overlaps: u32 = 0;
Self::walk_tile_overlaps(
&self.contigs[ctg_idx],
start,
end,
min_overlap,
self.nbp,
|rec| {
hits[rec.file_idx as usize] += 1;
total_overlaps += 1;
},
);
total_overlaps
}
/// Query all regions in a set, returning total pairwise hit counts per file.
/// Each query region can contribute multiple hits to the same file.
pub fn count_set_overlaps(&self, regions: &RegionSet, min_overlap: i32) -> Vec<u64> {
let mut hits = vec![0u64; self.file_info.len()];
for region in ®ions.regions {
self.count_overlaps(
®ion.chr,
region.start as i32,
region.end as i32,
min_overlap,
&mut hits,
);
}
hits
}
/// Count the number of query regions that overlap each file (binary per query).
///
/// Unlike `count_set_overlaps` which counts total pairwise overlaps,
/// this counts at most 1 per query region per file. This matches
/// R LOLA's `countOverlaps()` semantics where `support = sum(countOverlaps > 0)`.
pub fn count_region_hits(&self, regions: &RegionSet, min_overlap: i32) -> Vec<u64> {
let n_files = self.file_info.len();
let mut totals = vec![0u64; n_files];
let mut per_region = vec![0u64; n_files];
for region in ®ions.regions {
// Zero out per-region hits
for h in per_region.iter_mut() {
*h = 0;
}
self.count_overlaps(
®ion.chr,
region.start as i32,
region.end as i32,
min_overlap,
&mut per_region,
);
// Binary: if this region hit file i at all, count it once
for i in 0..n_files {
if per_region[i] > 0 {
totals[i] += 1;
}
}
}
totals
}
/// Query all regions given as (chrom, start, end) tuples.
pub fn count_regions_overlaps(
&self,
regions: &[(String, i32, i32)],
min_overlap: i32,
) -> Vec<u64> {
let mut hits = vec![0u64; self.file_info.len()];
for (chrom, start, end) in regions {
self.count_overlaps(chrom, *start, *end, min_overlap, &mut hits);
}
hits
}
/// Build an IGD from a single RegionSet (for two-set overlap queries).
///
/// Stores the original region index in the `value` field of each record,
/// enabling `find_overlaps_regionset` to return subject indices.
pub fn from_single_region_set(rs: &RegionSet) -> Self {
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: String::new(),
num_regions: rs.regions.len() as u32,
avg_region_width: if rs.regions.is_empty() {
0.0
} else {
rs.regions.iter().map(|r| (r.end - r.start) as f64).sum::<f64>()
/ rs.regions.len() as f64
},
}];
for (i, region) in rs.regions.iter().enumerate() {
igd.add(
®ion.chr,
region.start as i32,
region.end as i32,
i as i32, // store original index in value field
0,
);
}
igd.finalize();
igd
}
/// Find all overlapping (query_idx, subject_idx) pairs between a query
/// RegionSet and the subject indexed in this IGD.
///
/// The IGD must have been built with `from_single_region_set` so that
/// `record.value` stores the original subject region index.
///
/// # Panics
///
/// Panics if called before [`finalize`](Self::finalize).
pub fn find_overlaps_regionset(
&self,
query: &RegionSet,
min_overlap: i32,
) -> Vec<(u32, u32)> {
assert!(self.finalized, "Must finalize before querying");
let mut pairs: Vec<(u32, u32)> = Vec::new();
for (q_idx, region) in query.regions.iter().enumerate() {
let ctg_idx = match self.chrom_index.get(®ion.chr) {
Some(&idx) => idx,
None => continue,
};
// Deduplicate subject hits (records span multiple tiles)
let mut seen_subjects = std::collections::HashSet::new();
Self::walk_tile_overlaps(
&self.contigs[ctg_idx],
region.start as i32,
region.end as i32,
min_overlap,
self.nbp,
|rec| {
if seen_subjects.insert(rec.value as u32) {
pairs.push((q_idx as u32, rec.value as u32));
}
},
);
}
pairs
}
/// Count the number of subject regions overlapping each query region.
///
/// Returns a `Vec<u32>` of length `query.regions.len()` where each entry
/// is the number of distinct subject regions overlapping that query region.
///
/// The IGD must have been built with `from_single_region_set`.
///
/// # Panics
///
/// Panics if called before [`finalize`](Self::finalize).
pub fn count_overlaps_per_query(
&self,
query: &RegionSet,
min_overlap: i32,
) -> Vec<u32> {
assert!(self.finalized, "Must finalize before querying");
let mut counts = vec![0u32; query.regions.len()];
for (q_idx, region) in query.regions.iter().enumerate() {
let ctg_idx = match self.chrom_index.get(®ion.chr) {
Some(&idx) => idx,
None => continue,
};
let mut seen = std::collections::HashSet::new();
Self::walk_tile_overlaps(
&self.contigs[ctg_idx],
region.start as i32,
region.end as i32,
min_overlap,
self.nbp,
|rec| {
if seen.insert(rec.value) {
counts[q_idx] += 1;
}
},
);
}
counts
}
/// Number of source files indexed.
pub fn num_files(&self) -> usize {
self.file_info.len()
}
/// Number of contigs (chromosomes).
pub fn num_contigs(&self) -> usize {
self.contigs.len()
}
/// Total number of records across all tiles.
/// Note: intervals spanning multiple tiles are counted once per tile.
pub fn total_records(&self) -> usize {
self.contigs
.iter()
.flat_map(|c| &c.tiles)
.map(|t| t.records.len())
.sum()
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
/// Walk all overlapping records for a query interval on a single contig.
///
/// Calls `on_hit(&Record)` for each record that overlaps `[start, end)` by
/// at least `min_overlap` base pairs. Handles the first-tile binary search,
/// subsequent-tile boundary dedup, and min_overlap filtering.
fn walk_tile_overlaps<F>(
contig: &Contig,
start: i32,
end: i32,
min_overlap: i32,
nbp: i32,
mut on_hit: F,
) where
F: FnMut(&Record),
{
let n_tiles = contig.tiles.len() as i32;
let n1 = start / nbp;
let mut n2 = (end - 1) / nbp;
if n1 >= n_tiles {
return;
}
n2 = n2.min(n_tiles - 1);
// First tile (n1): binary search + backward scan
let tile = &contig.tiles[n1 as usize];
if !tile.records.is_empty() && end > tile.records[0].start {
let mut tl: i32 = 0;
let mut tr: i32 = tile.records.len() as i32 - 1;
while tl < tr - 1 {
let tm = (tl + tr) / 2;
if tile.records[tm as usize].start < end {
tl = tm;
} else {
tr = tm;
}
}
if tile.records[tr as usize].start < end {
tl = tr;
}
for i in (0..=tl).rev() {
let rec = &tile.records[i as usize];
let overlap_bp = rec.end.min(end) - rec.start.max(start);
if overlap_bp >= min_overlap {
on_hit(rec);
}
}
}
// Subsequent tiles (n1+1 through n2)
if n2 > n1 {
let mut bd = nbp * (n1 + 1);
for j in (n1 + 1)..=n2 {
let tile = &contig.tiles[j as usize];
if tile.records.is_empty() {
bd += nbp;
continue;
}
if end > tile.records[0].start {
// Skip records starting before this tile's boundary (already counted)
let mut ts: i32 = 0;
while ts < tile.records.len() as i32
&& tile.records[ts as usize].start < bd
{
ts += 1;
}
// Binary search for rightmost record with start < end
let mut tl: i32 = 0;
let mut tr: i32 = tile.records.len() as i32 - 1;
while tl < tr - 1 {
let tm = (tl + tr) / 2;
if tile.records[tm as usize].start < end {
tl = tm;
} else {
tr = tm;
}
}
if tile.records[tr as usize].start < end {
tl = tr;
}
for i in (ts..=tl).rev() {
let rec = &tile.records[i as usize];
let overlap_bp = rec.end.min(end) - rec.start.max(start);
if overlap_bp >= min_overlap {
on_hit(rec);
}
}
}
bd += nbp;
}
}
}
/// Parse a BED line into (chrom, start, end, score).
fn parse_bed_line(line: &str) -> Option<(String, i32, i32, i32)> {
let mut fields = line.split('\t');
let chrom = fields.next()?;
let start: i32 = fields.next()?.parse().ok()?;
let end: i32 = fields.next()?.parse().ok()?;
if chrom.len() >= 40 || end <= 0 {
return None;
}
let _ = fields.next(); // skip col4 (name)
let score: i32 = fields
.next()
.and_then(|s| s.parse().ok())
.unwrap_or(-1);
Some((chrom.to_string(), start, end, score))
}
/// Load file info from a companion .tsv file.
fn load_file_info_tsv(tsv_path: &Path) -> anyhow::Result<Vec<FileInfo>> {
let file = File::open(tsv_path)?;
let reader = BufReader::new(file);
let mut infos = Vec::new();
for (i, line) in reader.lines().enumerate() {
if i == 0 {
continue; // skip header
}
let line = line?;
let fields: Vec<&str> = line.split('\t').collect();
if fields.len() < 4 {
continue;
}
infos.push(FileInfo {
filename: fields[1].trim().to_string(),
num_regions: fields[2].trim().parse().unwrap_or(0),
avg_region_width: fields[3].trim().parse().unwrap_or(0.0),
});
}
Ok(infos)
}
}
impl Default for Igd {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn test_data_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.join("tests/data")
}
#[test]
fn test_igd_build_and_query_basic() {
// Build IGD manually with known intervals
let mut igd = Igd::new();
igd.file_info = vec![
FileInfo {
filename: "file0.bed".into(),
num_regions: 2,
avg_region_width: 100.0,
},
FileInfo {
filename: "file1.bed".into(),
num_regions: 1,
avg_region_width: 50.0,
},
];
// file0: two regions on chr1
igd.add("chr1", 100, 200, 0, 0);
igd.add("chr1", 300, 400, 0, 0);
// file1: one region on chr1 overlapping file0's first region
igd.add("chr1", 150, 250, 0, 1);
igd.finalize();
// Query region that overlaps file0[0] and file1[0]
let mut hits = vec![0u64; 2];
let n = igd.count_overlaps("chr1", 120, 180, 1, &mut hits);
assert_eq!(n, 2);
assert_eq!(hits[0], 1); // file0
assert_eq!(hits[1], 1); // file1
// Query region that overlaps only file0[1]
let mut hits = vec![0u64; 2];
let n = igd.count_overlaps("chr1", 350, 380, 1, &mut hits);
assert_eq!(n, 1);
assert_eq!(hits[0], 1);
assert_eq!(hits[1], 0);
// Query region that overlaps nothing
let mut hits = vec![0u64; 2];
let n = igd.count_overlaps("chr1", 500, 600, 1, &mut hits);
assert_eq!(n, 0);
assert_eq!(hits[0], 0);
assert_eq!(hits[1], 0);
}
#[test]
fn test_igd_min_overlap() {
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: "file0.bed".into(),
num_regions: 1,
avg_region_width: 100.0,
}];
// file0: region [100, 200)
igd.add("chr1", 100, 200, 0, 0);
igd.finalize();
// Query [190, 250) — only 10bp overlap with [100,200)
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 190, 250, 1, &mut hits);
assert_eq!(hits[0], 1); // 10bp >= 1bp
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 190, 250, 10, &mut hits);
assert_eq!(hits[0], 1); // 10bp >= 10bp
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 190, 250, 11, &mut hits);
assert_eq!(hits[0], 0); // 10bp < 11bp
}
#[test]
fn test_igd_multi_tile_spanning() {
// Test an interval that spans multiple tiles
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: "file0.bed".into(),
num_regions: 1,
avg_region_width: 20000.0,
}];
// Interval spanning tiles 0 and 1 (tile size = 16384)
igd.add("chr1", 10000, 20000, 0, 0);
igd.finalize();
// Query in tile 0
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 11000, 12000, 1, &mut hits);
assert_eq!(hits[0], 1);
// Query in tile 1
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 17000, 18000, 1, &mut hits);
assert_eq!(hits[0], 1);
// Query spanning both tiles
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 15000, 19000, 1, &mut hits);
assert_eq!(hits[0], 1); // should count only once per file
}
#[test]
fn test_igd_unknown_chrom() {
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: "file0.bed".into(),
num_regions: 1,
avg_region_width: 100.0,
}];
igd.add("chr1", 100, 200, 0, 0);
igd.finalize();
let mut hits = vec![0u64; 1];
let n = igd.count_overlaps("chrZ", 100, 200, 1, &mut hits);
assert_eq!(n, 0);
}
#[test]
fn test_igd_from_bed_dir() {
let bed_dir = test_data_dir().join("igd_file_list_01");
let igd = Igd::from_bed_dir(&bed_dir).unwrap();
assert_eq!(igd.num_files(), 1);
assert_eq!(igd.num_contigs(), 3); // chr1, chr2, chr3
// Query all 8 regions from the file against itself — each should hit
let mut hits = vec![0u64; 1];
// chr1: [1,100), [200,300), [32768,32868), [49152,49352)
igd.count_overlaps("chr1", 1, 100, 1, &mut hits);
igd.count_overlaps("chr1", 200, 300, 1, &mut hits);
igd.count_overlaps("chr1", 32768, 32868, 1, &mut hits);
igd.count_overlaps("chr1", 49152, 49352, 1, &mut hits);
// chr2: [1,100), [200,300)
igd.count_overlaps("chr2", 1, 100, 1, &mut hits);
igd.count_overlaps("chr2", 200, 300, 1, &mut hits);
// chr3: [32768,32868), [49152,49352)
igd.count_overlaps("chr3", 32768, 32868, 1, &mut hits);
igd.count_overlaps("chr3", 49152, 49352, 1, &mut hits);
assert_eq!(hits[0], 8); // all 8 regions overlap
}
#[test]
fn test_igd_from_region_sets() {
let sets = vec![
(
"set1.bed".to_string(),
vec![
("chr1".to_string(), 100, 200),
("chr1".to_string(), 300, 400),
],
),
(
"set2.bed".to_string(),
vec![("chr1".to_string(), 150, 350)],
),
];
let igd = Igd::from_region_sets(sets);
assert_eq!(igd.num_files(), 2);
let mut hits = vec![0u64; 2];
igd.count_overlaps("chr1", 160, 170, 1, &mut hits);
assert_eq!(hits[0], 1); // set1: [100,200) overlaps
assert_eq!(hits[1], 1); // set2: [150,350) overlaps
}
#[test]
fn test_igd_save_and_reload() {
let mut igd = Igd::new();
igd.file_info = vec![
FileInfo {
filename: "file0.bed".into(),
num_regions: 2,
avg_region_width: 100.0,
},
FileInfo {
filename: "file1.bed".into(),
num_regions: 1,
avg_region_width: 100.0,
},
];
igd.add("chr1", 100, 200, 5, 0);
igd.add("chr1", 300, 400, 10, 0);
igd.add("chr2", 50, 150, 0, 1);
igd.finalize();
// Save
let tmpdir = tempfile::tempdir().unwrap();
let igd_path = tmpdir.path().join("test.igd");
igd.save(&igd_path).unwrap();
// Reload
let igd2 = Igd::from_igd_file(&igd_path).unwrap();
assert_eq!(igd2.num_contigs(), 2);
assert_eq!(igd2.num_files(), 2);
// Query reloaded IGD should match original
let mut hits_orig = vec![0u64; 2];
let mut hits_reload = vec![0u64; 2];
igd.count_overlaps("chr1", 150, 350, 1, &mut hits_orig);
igd2.count_overlaps("chr1", 150, 350, 1, &mut hits_reload);
assert_eq!(hits_orig, hits_reload);
}
#[test]
fn test_igd_disk_roundtrip_matches_legacy() {
// Build IGD from test data using new API, save, reload, and verify
// query results match what the legacy create+search pipeline produces
let bed_dir = test_data_dir().join("igd_file_list_01");
let igd = Igd::from_bed_dir(&bed_dir).unwrap();
let tmpdir = tempfile::tempdir().unwrap();
let igd_path = tmpdir.path().join("demo.igd");
igd.save(&igd_path).unwrap();
let igd2 = Igd::from_igd_file(&igd_path).unwrap();
// Query from the query file and compare
let mut hits1 = vec![0u64; igd.num_files()];
let mut hits2 = vec![0u64; igd2.num_files()];
let query_regions = vec![
("chr1", 1, 100),
("chr1", 200, 300),
("chr1", 32768, 32868),
("chr1", 49152, 49352),
("chr2", 1, 100),
("chr2", 200, 300),
("chr3", 32768, 32868),
("chr3", 49152, 49352),
];
for (c, s, e) in &query_regions {
igd.count_overlaps(c, *s, *e, 1, &mut hits1);
igd2.count_overlaps(c, *s, *e, 1, &mut hits2);
}
assert_eq!(hits1, hits2);
}
#[test]
fn test_igd_count_set_overlaps() {
let sets = vec![
(
"db1.bed".to_string(),
vec![
("chr1".to_string(), 100, 200),
("chr1".to_string(), 500, 600),
],
),
(
"db2.bed".to_string(),
vec![("chr1".to_string(), 150, 250)],
),
];
let igd = Igd::from_region_sets(sets);
// Create a query RegionSet
let query = RegionSet::from(vec![
gtars_core::models::Region {
chr: "chr1".to_string(),
start: 120,
end: 180,
rest: None,
},
gtars_core::models::Region {
chr: "chr1".to_string(),
start: 520,
end: 560,
rest: None,
},
]);
let hits = igd.count_set_overlaps(&query, 1);
assert_eq!(hits[0], 2); // db1: both [100,200) and [500,600) hit
assert_eq!(hits[1], 1); // db2: only [150,250) hits first query region
}
#[test]
fn test_igd_pairwise_overlap_counting() {
// Verify that IGD counts pairwise overlaps (not binary per query region).
// If one query region overlaps 3 DB regions in the same file, that's 3 hits.
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: "file0.bed".into(),
num_regions: 3,
avg_region_width: 50.0,
}];
// Three overlapping DB regions in same file
igd.add("chr1", 100, 200, 0, 0);
igd.add("chr1", 120, 220, 0, 0);
igd.add("chr1", 140, 240, 0, 0);
igd.finalize();
// One query region overlapping all three
let mut hits = vec![0u64; 1];
igd.count_overlaps("chr1", 150, 190, 1, &mut hits);
assert_eq!(hits[0], 3); // pairwise: 3 overlaps, not 1
}
#[test]
fn test_igd_empty() {
let igd = Igd::new();
// Can't query unfinalized IGD — but an empty one should work after finalize
let mut igd = igd;
igd.finalize();
assert_eq!(igd.num_files(), 0);
assert_eq!(igd.num_contigs(), 0);
}
fn make_region(chr: &str, start: u32, end: u32) -> gtars_core::models::Region {
gtars_core::models::Region {
chr: chr.to_string(),
start,
end,
rest: None,
}
}
#[test]
fn test_from_single_region_set() {
let subject = RegionSet::from(vec![
make_region("chr1", 100, 200),
make_region("chr1", 300, 400),
make_region("chr2", 50, 150),
]);
let igd = Igd::from_single_region_set(&subject);
assert_eq!(igd.num_files(), 1);
assert_eq!(igd.file_info[0].num_regions, 3);
}
#[test]
fn test_find_overlaps_regionset_basic() {
let subject = RegionSet::from(vec![
make_region("chr1", 100, 200),
make_region("chr1", 300, 400),
make_region("chr1", 500, 600),
]);
let query = RegionSet::from(vec![
make_region("chr1", 150, 350), // overlaps subject 0 and 1
make_region("chr1", 550, 650), // overlaps subject 2
make_region("chr1", 700, 800), // no overlap
]);
let igd = Igd::from_single_region_set(&subject);
let mut pairs = igd.find_overlaps_regionset(&query, 1);
pairs.sort();
assert_eq!(pairs, vec![(0, 0), (0, 1), (1, 2)]);
}
#[test]
fn test_find_overlaps_regionset_no_overlap() {
let subject = RegionSet::from(vec![make_region("chr1", 100, 200)]);
let query = RegionSet::from(vec![make_region("chr1", 300, 400)]);
let igd = Igd::from_single_region_set(&subject);
let pairs = igd.find_overlaps_regionset(&query, 1);
assert!(pairs.is_empty());
}
#[test]
fn test_find_overlaps_regionset_min_overlap() {
let subject = RegionSet::from(vec![make_region("chr1", 100, 200)]);
let query = RegionSet::from(vec![make_region("chr1", 190, 300)]); // 10bp overlap
let igd = Igd::from_single_region_set(&subject);
let pairs1 = igd.find_overlaps_regionset(&query, 1);
assert_eq!(pairs1.len(), 1);
let pairs50 = igd.find_overlaps_regionset(&query, 50);
assert!(pairs50.is_empty());
}
#[test]
fn test_find_overlaps_regionset_multi_chrom() {
let subject = RegionSet::from(vec![
make_region("chr1", 100, 200),
make_region("chr2", 100, 200),
]);
let query = RegionSet::from(vec![
make_region("chr1", 150, 180),
make_region("chr2", 150, 180),
make_region("chr3", 150, 180), // no subject on chr3
]);
let igd = Igd::from_single_region_set(&subject);
let mut pairs = igd.find_overlaps_regionset(&query, 1);
pairs.sort();
assert_eq!(pairs, vec![(0, 0), (1, 1)]);
}
#[test]
fn test_count_overlaps_per_query_basic() {
let subject = RegionSet::from(vec![
make_region("chr1", 100, 200),
make_region("chr1", 150, 250),
make_region("chr1", 500, 600),
]);
let query = RegionSet::from(vec![
make_region("chr1", 160, 180), // overlaps subject 0 and 1
make_region("chr1", 550, 580), // overlaps subject 2
make_region("chr1", 700, 800), // no overlap
]);
let igd = Igd::from_single_region_set(&subject);
let counts = igd.count_overlaps_per_query(&query, 1);
assert_eq!(counts, vec![2, 1, 0]);
}
#[test]
fn test_count_overlaps_per_query_empty() {
let subject = RegionSet::from(vec![make_region("chr1", 100, 200)]);
let query = RegionSet::from(vec![]);
let igd = Igd::from_single_region_set(&subject);
let counts = igd.count_overlaps_per_query(&query, 1);
assert!(counts.is_empty());
}
#[test]
fn test_find_overlaps_multi_tile_dedup() {
// Subject region spans multiple tiles — should only appear once per query
let subject = RegionSet::from(vec![
make_region("chr1", 10000, 40000), // spans tiles 0, 1, 2
]);
let query = RegionSet::from(vec![
make_region("chr1", 15000, 35000), // also spans tiles
]);
let igd = Igd::from_single_region_set(&subject);
let pairs = igd.find_overlaps_regionset(&query, 1);
assert_eq!(pairs.len(), 1);
assert_eq!(pairs[0], (0, 0));
let counts = igd.count_overlaps_per_query(&query, 1);
assert_eq!(counts, vec![1]);
}
#[test]
fn test_from_region_sets_skips_invalid_intervals() {
// Mix of valid and invalid intervals — invalid should be skipped in count/width
let sets = vec![(
"test.bed".to_string(),
vec![
("chr1".to_string(), 100, 200), // valid: 100bp
("chr1".to_string(), 300, 300), // invalid: start == end
("chr1".to_string(), 500, 400), // invalid: start > end
("chr1".to_string(), 600, 700), // valid: 100bp
],
)];
let igd = Igd::from_region_sets(sets);
assert_eq!(igd.file_info.len(), 1);
assert_eq!(igd.file_info[0].num_regions, 2, "Only 2 valid intervals");
assert!(
(igd.file_info[0].avg_region_width - 100.0).abs() < 1e-6,
"avg width should be 100.0, got {}",
igd.file_info[0].avg_region_width
);
}
#[test]
fn test_add_negative_coordinates_no_panic() {
let mut igd = Igd::new();
igd.file_info = vec![FileInfo {
filename: "test.bed".into(),
num_regions: 0,
avg_region_width: 0.0,
}];
// These should all be silently skipped, no panic
igd.add("chr1", -100, 200, 0, 0);
igd.add("chr1", 100, -200, 0, 0);
igd.add("chr1", -100, -50, 0, 0);
// Add one valid interval to verify the IGD still works
igd.add("chr1", 100, 200, 0, 0);
igd.finalize();
// Query should find the one valid interval
let mut hits = vec![0u64; 1];
let count = igd.count_overlaps("chr1", 150, 160, 1, &mut hits);
assert_eq!(count, 1);
}
#[test]
fn test_query_negative_coordinates() {
let sets = vec![(
"test.bed".to_string(),
vec![("chr1".to_string(), 100, 200)],
)];
let igd = Igd::from_region_sets(sets);
let mut hits = vec![0u64; 1];
// Negative start, positive end — should clamp start to 0 and still work
let count = igd.count_overlaps("chr1", -50, 150, 1, &mut hits);
assert_eq!(count, 1, "Should find overlap after clamping negative start");
// Both negative — should return 0
hits[0] = 0;
let count = igd.count_overlaps("chr1", -100, -50, 1, &mut hits);
assert_eq!(count, 0, "Both negative should return 0");
}
#[test]
fn test_parse_bed_line_no_chr_prefix() {
// Non-UCSC chromosome names should now be accepted
let result = Igd::parse_bed_line("1\t100\t200\tname\t500");
assert!(result.is_some(), "Should parse non-chr-prefixed chromosomes");
let (chrom, start, end, score) = result.unwrap();
assert_eq!(chrom, "1");
assert_eq!(start, 100);
assert_eq!(end, 200);
assert_eq!(score, 500);
}
#[test]
fn test_from_bed_dir_large_coordinates() {
// Intervals with coordinates > 321M should now be accepted
let sets = vec![(
"test.bed".to_string(),
vec![("chr1".to_string(), 400_000_000, 400_001_000)],
)];
let igd = Igd::from_region_sets(sets);
let mut hits = vec![0u64; 1];
let count = igd.count_overlaps("chr1", 400_000_500, 400_000_600, 1, &mut hits);
assert_eq!(count, 1, "Should find overlap at coordinates > 321M");
}
}