| 1 | // Streaming relation (overlap, distance, KNN) testing of (any number of) sorted files of intervals. |
| 2 | package irelate |
| 3 | |
| 4 | import ( |
| 5 | "container/heap" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "log" |
| 9 | "os" |
| 10 | |
| 11 | . "github.com/brentp/irelate/interfaces" |
| 12 | ) |
| 13 | |
| 14 | // Set relativeTo so SelfRelations constant to allow reporting overlaps within a stream |
| 15 | const SelfRelations = -2 |
| 16 | |
| 17 | func relate(a Relatable, b Relatable, relativeTo int) { |
| 18 | if relativeTo == SelfRelations { |
| 19 | a.AddRelated(b) |
| 20 | b.AddRelated(a) |
| 21 | return |
| 22 | } |
| 23 | if a.Source() != b.Source() { |
| 24 | if relativeTo == -1 { |
| 25 | a.AddRelated(b) |
| 26 | b.AddRelated(a) |
| 27 | } else { |
| 28 | if uint32(relativeTo) == a.Source() { |
| 29 | a.AddRelated(b) |
| 30 | } |
| 31 | if uint32(relativeTo) == b.Source() { |
| 32 | b.AddRelated(a) |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func Less(a Relatable, b Relatable) bool { |
| 39 | if a.Chrom() != b.Chrom() { |
| 40 | return a.Chrom() < b.Chrom() |
| 41 | } |
| 42 | return a.Start() < b.Start() // || (a.Start() == b.Start() && a.End() < b.End()) |
| 43 | } |
| 44 | |
| 45 | // 1, 2, 3 ... 9, 10, 11... |
| 46 | func NaturalLessPrefix(a Relatable, b Relatable) bool { |
| 47 | if !SameChrom(a.Chrom(), b.Chrom()) { |
| 48 | return NaturalLess(StripChr(a.Chrom()), StripChr(b.Chrom())) |
| 49 | } |
| 50 | return a.Start() < b.Start() || (a.Start() == b.Start() && a.End() < b.End()) |
| 51 | |
| 52 | } |
| 53 | |
| 54 | // 1, 10, 11... 19, 2, 20, 21 ... |
| 55 | func LessPrefix(a Relatable, b Relatable) bool { |
| 56 | if !SameChrom(a.Chrom(), b.Chrom()) { |
| 57 | return StripChr(a.Chrom()) < StripChr(b.Chrom()) |
| 58 | } |
| 59 | return a.Start() < b.Start() || (a.Start() == b.Start() && a.End() < b.End()) |
| 60 | } |
| 61 | |
| 62 | // CheckRelatedByOverlap returns true if Relatables overlap. |
| 63 | func CheckRelatedByOverlap(a Relatable, b Relatable) bool { |
| 64 | return (b.Start() < a.End()) && (b.Chrom() == a.Chrom()) |
| 65 | // note with distance == 0 this just overlap. |
| 66 | //distance := uint32(0) |
| 67 | //return (b.Start()-distance < a.End()) && (b.Chrom() == a.Chrom()) |
| 68 | } |
| 69 | |
| 70 | // handles chromomomes like 'chr1' from one org and '1' from another. |
| 71 | func CheckOverlapPrefix(a Relatable, b Relatable) bool { |
| 72 | if b.Start() < a.End() { |
| 73 | return SameChrom(a.Chrom(), b.Chrom()) |
| 74 | } |
| 75 | return false |
| 76 | } |
| 77 | |
| 78 | // CheckKNN relates an interval to its k-nearest neighbors. |
| 79 | // The reporting function will have to do some filtering since this is only |
| 80 | // guaranteed to associate *at least* k neighbors, but it could be returning extra. |
| 81 | func CheckKNN(a Relatable, b Relatable) bool { |
| 82 | // the first n checked would be the n_closest, but need to consider ties |
| 83 | // the report function can decide what to do with them. |
| 84 | k := 4 |
| 85 | r := a.Related() |
| 86 | if len(r) >= k { |
| 87 | // TODO: double-check this. |
| 88 | return r[len(r)-1].Start()-a.End() < b.Start()-a.End() |
| 89 | } |
| 90 | return true |
| 91 | } |
| 92 | |
| 93 | // filter rewrites the input-slice to remove nils. |
| 94 | func filter(s []Relatable, nils int) []Relatable { |
| 95 | j := 0 |
| 96 | if len(s) != nils { |
| 97 | |
| 98 | for _, v := range s { |
| 99 | if v != nil { |
| 100 | s[j] = v |
| 101 | j++ |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | for k := j; k < len(s); k++ { |
| 106 | s[k] = nil |
| 107 | } |
| 108 | return s[:j] |
| 109 | } |
| 110 | |
| 111 | type irelate struct { |
| 112 | checkRelated func(a, b Relatable) bool |
| 113 | // relativeTo indicates which stream is the query stream. A value of -1 means |
| 114 | // all vs all. A value of -2 reports overlaps even within the same stream. |
| 115 | relativeTo int |
| 116 | less func(a, b Relatable) bool |
| 117 | // cache holds the set of Relatables we must test for overlap. A Relatable |
| 118 | // is ejected from the cache when it is not related to the interval that's |
| 119 | // about to be added. |
| 120 | cache []Relatable |
| 121 | // an item eject from the cache gets put on the sendQ if it's from the query |
| 122 | // stream. |
| 123 | sendQ *relatableQueue |
| 124 | // mergeStream creates a single (sorted) stream of all incoming intervals. |
| 125 | mergeStream RelatableIterator |
| 126 | //merger RelatableChannel |
| 127 | nils int |
| 128 | } |
| 129 | |
| 130 | // IRelate provides the basis for flexible overlap/proximity/k-nearest neighbor |
| 131 | // testing. IRelate receives merged, ordered Relatables via stream and takes |
| 132 | // function that checks if they are related (see CheckRelatedByOverlap). |
| 133 | // It is guaranteed that !Less(b, a) is true (we can't guarantee that Less(a, b) |
| 134 | // is true since they may have the same start). Once checkRelated returns false, |
| 135 | // it is assumed that no other `b` Relatables could possibly be related to `a` |
| 136 | // and so `a` is sent to the returnQ. |
| 137 | // streams are a variable number of iterators that send intervals. |
| 138 | func IRelate(checkRelated func(a, b Relatable) bool, |
| 139 | relativeTo int, |
| 140 | less func(a, b Relatable) bool, |
| 141 | streams ...RelatableIterator) RelatableIterator { |
| 142 | |
| 143 | mergeStream := newMerger(less, relativeTo, streams...) |
| 144 | |
| 145 | ir := &irelate{checkRelated: checkRelated, relativeTo: relativeTo, |
| 146 | mergeStream: mergeStream, |
| 147 | cache: make([]Relatable, 0, 1024), sendQ: &relatableQueue{make([]Relatable, 0, 1024), less}, |
| 148 | less: less} |
| 149 | return ir |
| 150 | } |
| 151 | |
| 152 | func (ir *irelate) Close() error { |
| 153 | return nil |
| 154 | } |
| 155 | |
| 156 | func (ir *irelate) Next() (Relatable, error) { |
| 157 | |
| 158 | for { |
| 159 | interval, err := ir.mergeStream.Next() |
| 160 | if err == io.EOF { |
| 161 | break |
| 162 | } |
| 163 | // check the interval against everything in the cache. |
| 164 | for i, c := range ir.cache { |
| 165 | if c == nil { |
| 166 | continue |
| 167 | } |
| 168 | if ir.checkRelated(c, interval) { |
| 169 | relate(c, interval, ir.relativeTo) |
| 170 | } else { |
| 171 | // if it's not related, we remove it from the cache |
| 172 | // if it's a query interval, we push it onto the sendQ. |
| 173 | if ir.relativeTo < 0 || int(c.Source()) == ir.relativeTo { |
| 174 | heap.Push(ir.sendQ, c) |
| 175 | } |
| 176 | ir.cache[i] = nil |
| 177 | ir.nils++ |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // only do this when we have a lot of nils as it's expensive to create a new slice. |
| 182 | // nils are spaces that we've removed from the cache. |
| 183 | if ir.nils < 2 { |
| 184 | ir.cache = append(ir.cache, interval) |
| 185 | continue |
| 186 | } |
| 187 | // remove nils from the cache (must do this before sending) |
| 188 | ir.cache, ir.nils = filter(ir.cache, ir.nils), 0 |
| 189 | var o Relatable |
| 190 | if len(ir.sendQ.rels) > 0 { |
| 191 | o = ir.sendQ.rels[0] |
| 192 | } |
| 193 | // if the first thing in the sendQ is less than the first thing in the cache |
| 194 | // then we can send Pop the lowest thing off the sendQ. |
| 195 | // otherwise, we continue to read from the stream. |
| 196 | if o != nil && (len(ir.cache) == 0 || ir.less(o, ir.cache[0])) { |
| 197 | ir.cache = append(ir.cache, interval) |
| 198 | return heap.Pop(ir.sendQ).(Relatable), nil |
| 199 | } |
| 200 | ir.cache = append(ir.cache, interval) |
| 201 | } |
| 202 | // stream is done so we empty the cache by pushing onto the sendQ |
| 203 | if len(ir.cache) > 0 { |
| 204 | ir.cache, ir.nils = filter(ir.cache, ir.nils), 0 |
| 205 | for _, c := range ir.cache { |
| 206 | if ir.relativeTo < 0 || int(c.Source()) == ir.relativeTo { |
| 207 | heap.Push(ir.sendQ, c) |
| 208 | } |
| 209 | } |
| 210 | ir.cache = ir.cache[:0] |
| 211 | } |
| 212 | // ... then we clear the sendQ |
| 213 | if len(ir.sendQ.rels) > 0 { |
| 214 | return heap.Pop(ir.sendQ).(Relatable), nil |
| 215 | } |
| 216 | return nil, io.EOF |
| 217 | } |
| 218 | |
| 219 | type merger struct { |
| 220 | less func(a, b Relatable) bool |
| 221 | relativeTo int |
| 222 | streams []RelatableIterator |
| 223 | q relatableQueue |
| 224 | seen map[string]struct{} |
| 225 | j int |
| 226 | lastChrom string |
| 227 | verbose bool |
| 228 | } |
| 229 | |
| 230 | func newMerger(less func(a, b Relatable) bool, relativeTo int, streams ...RelatableIterator) *merger { |
| 231 | q := relatableQueue{make([]Relatable, 0, len(streams)), less} |
| 232 | verbose := os.Getenv("IRELATE_VERBOSE") == "TRUE" |
| 233 | |
| 234 | for i, stream := range streams { |
| 235 | interval, err := stream.Next() |
| 236 | if err != nil && err != io.EOF { |
| 237 | panic(err) |
| 238 | } |
| 239 | if interval != nil { |
| 240 | interval.SetSource(uint32(i)) |
| 241 | heap.Push(&q, interval) |
| 242 | } |
| 243 | if err == io.EOF { |
| 244 | stream.Close() |
| 245 | } |
| 246 | } |
| 247 | m := &merger{less: less, relativeTo: relativeTo, streams: streams, q: q, seen: make(map[string]struct{}), j: -1000, lastChrom: "", verbose: verbose} |
| 248 | |
| 249 | return m |
| 250 | } |
| 251 | |
| 252 | func (m *merger) Close() error { |
| 253 | return nil |
| 254 | } |
| 255 | |
| 256 | func (m *merger) Next() (Relatable, error) { |
| 257 | if len(m.q.rels) == 0 { |
| 258 | return nil, io.EOF |
| 259 | } |
| 260 | interval := heap.Pop(&m.q).(Relatable) |
| 261 | source := interval.Source() |
| 262 | if !SameChrom(interval.Chrom(), m.lastChrom) { |
| 263 | if m.verbose && m.lastChrom != "" { |
| 264 | log.Printf("on chromosome: %s\n", m.lastChrom) |
| 265 | } |
| 266 | m.lastChrom = StripChr(interval.Chrom()) |
| 267 | if _, ok := m.seen[m.lastChrom]; ok { |
| 268 | log.Println("warning: chromosomes must be in different order between files or the chromosome sort order is not as expected.") |
| 269 | log.Printf("warning: overlaps will likely be missed after this chrom: %s from source: %d\n", m.lastChrom, interval.Source()) |
| 270 | } |
| 271 | m.seen[m.lastChrom] = struct{}{} |
| 272 | } |
| 273 | // pull the next interval from the same source. |
| 274 | next_interval, err := m.streams[source].Next() |
| 275 | if err == nil { |
| 276 | if next_interval.Start() < interval.Start() { |
| 277 | if SameChrom(next_interval.Chrom(), interval.Chrom()) { |
| 278 | panic(fmt.Sprintf("intervals out of order within file: starts at: %d and %d from source: %d", interval.Start(), next_interval.Start(), source)) |
| 279 | } |
| 280 | } |
| 281 | next_interval.SetSource(source) |
| 282 | heap.Push(&m.q, next_interval) |
| 283 | m.j-- |
| 284 | if m.j == 0 { |
| 285 | return nil, io.EOF |
| 286 | } |
| 287 | } else { |
| 288 | if int(source) == m.relativeTo { |
| 289 | // we pull in 200K more records and then stop. to make sure we get anything that might |
| 290 | // relate to last query |
| 291 | m.j = 200000 |
| 292 | } |
| 293 | } |
| 294 | if err == io.EOF { |
| 295 | m.streams[source].Close() |
| 296 | } |
| 297 | return interval, nil |
| 298 | } |