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
// Copyright (C) 2024 Philipp Benner
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use std::collections::HashMap;
use crate::granges::GRanges;
use crate::granges_find_endpoint::{EndPoint, EndPointList};
/* -------------------------------------------------------------------------- */
impl GRanges {
/// Merges overlapping or contiguous genomic ranges from the given `GRanges` object.
///
/// This function processes an `EndPointList` for a specific sequence name, combining
/// overlapping and contiguous intervals into larger ranges. The resulting ranges are appended
/// to the provided `GRanges` object.
///
/// # Arguments
/// - `r`: A reference to a `GRanges` object where the merged ranges will be appended.
/// - `seqname`: A string representing the name of the genomic sequence being processed.
/// - `entry`: A reference to an `EndPointList`, which contains the start and end points of genomic ranges.
///
/// # Returns
/// A `GRanges` object containing the merged ranges from the specified sequence name.
///
/// # Panics
/// This function will panic if it encounters an invalid state in the `EndPointList`,
/// specifically if it does not start with a start position.
fn merge_impl(r: &GRanges, seqname: String, entry: &EndPointList) -> GRanges {
let mut seqnames = vec![];
let mut from = vec![];
let mut to = vec![];
let mut i = 0;
while i < entry.len() {
// next item must be a start position
assert!(entry[i].is_start());
let r_from = entry[i].get_position();
let mut r_to = entry[i].get_position() + 1;
// k: number open intervals
let mut k = 1;
while k > 0 {
// go to next item
i += 1;
if entry[i].is_start() {
// start of an interval
k += 1;
r_to = entry[i].get_position();
} else {
// end of an interval
k -= 1;
r_to = entry[i].get_position() + 1;
}
}
seqnames.push(seqname.clone());
from .push(r_from);
to .push(r_to);
// go to next item
i += 1;
}
r.append(&GRanges::new(seqnames, from, to, vec![])).unwrap()
}
/// Merges a collection of `GRanges` objects into a single `GRanges` object.
///
/// This function iterates through a slice of `GRanges`, collects start and end points for each range,
/// and merges overlapping or contiguous ranges. The resulting merged ranges are returned.
///
/// # Arguments
/// - `granges`: A slice of `GRanges` objects to be merged.
///
/// # Returns
/// A new `GRanges` object containing the merged ranges.
///
/// # Example
/// ```
/// use rustynetics::granges::GRanges;
///
/// let seqnames = vec!["chr1", "chr1", "chr1", "chr2", "chr2"].iter().map(|&x| x.into()).collect();
/// let from = vec![6, 10, 24, 6, 10];
/// let to = vec![21, 31, 81, 21, 31];
/// let strand = vec![];
///
/// let granges = GRanges::new(seqnames, from, to, strand);
/// let merged = GRanges::merge(&[&granges]);
/// ```
pub fn merge(granges: &[&GRanges]) -> GRanges {
let mut r = GRanges::default();
let mut rmap: HashMap<String, EndPointList> = HashMap::new();
for g in granges.iter() {
for i in 0..g.num_rows() {
let start = EndPoint::new(g.ranges[i].from, i, true);
let end = EndPoint::new(g.ranges[i].to-1, i, true);
end.borrow_mut().start = Some(start.clone());
let entry = rmap.entry(g.seqnames[i].clone()).or_insert_with(EndPointList::new);
entry.push(start);
entry.push(end);
}
}
let mut seqnames: Vec<String> = rmap.keys().cloned().collect();
seqnames.sort();
for entry in rmap.values_mut() {
entry.sort();
}
for seqname in seqnames {
r = GRanges::merge_impl(&r, seqname.clone(), &rmap[&seqname]);
}
r
}
}
/* -------------------------------------------------------------------------- */
#[cfg(test)]
mod tests {
use crate::granges::GRanges;
#[test]
fn test_merge() {
let seqnames = vec!["chr1", "chr1", "chr1", "chr2", "chr2"].iter().map(|&x| x.into()).collect();
let from = vec![ 6, 10, 24, 6, 10];
let to = vec![21, 31, 81, 21, 31];
let strand = vec![];
let granges = GRanges::new(seqnames, from, to, strand);
let r = GRanges::merge(&[&granges]);
assert!(r.num_rows() == 2);
assert!(r.ranges[0].from == 6);
assert!(r.ranges[0].to == 81);
assert!(r.ranges[1].from == 6);
assert!(r.ranges[1].to == 31);
}
}