| 1 | package irelate |
| 2 | |
| 3 | // parallel implements a parallel chrom-sweep. |
| 4 | // broad design is covered in design.md in the irelate package directory. |
| 5 | // In actual fact, there are a number of complexities; most of them relate to |
| 6 | // maintaining intervals in sorted order (and keeping chunks in sorted order) |
| 7 | // while allowing a good level of parallelism. |
| 8 | |
| 9 | // more detailed explanations are provided whenever a channel is initialized |
| 10 | // as channels are our main means of keeping order. |
| 11 | // For example |
| 12 | // tochannels := make(chan chan chan []interfaces.Relatable, 2+nprocs/2) |
| 13 | // Seems to have excessive use of channels, but we actually do need this since |
| 14 | // we have 2 levels of parallelization. |
| 15 | // One level is by chunk of query intervals. |
| 16 | // The next is by sub-chunk within the query chunks. |
| 17 | // The 3rd chan is a place-holder so that the work() function, which calls |
| 18 | // the user-defined fn() can be done concurrently (in a go routine). |
| 19 | |
| 20 | // The broad pattern used throughout is to send a channel (K) into another |
| 21 | // channel (PARENT) to keep order and then send K into a worker goroutine |
| 22 | // that sends intervals or []intervals into K. |
| 23 | |
| 24 | // I have done much tuning; the areas that affect performance are how the work() |
| 25 | // is parallelized (see the code-block that calls work()). And how the query |
| 26 | // chunks are determined. If the query chunks are too small (< 100 intervals), |
| 27 | // we have a lot of overhead in tracking that chunk that only requires a little |
| 28 | // computation. Unless the databases are very dense, then having the query chunks |
| 29 | // quite large helps parallelization. This is an area of potential optimization, |
| 30 | // though no obvious candidates have emerged. |
| 31 | |
| 32 | import ( |
| 33 | "fmt" |
| 34 | "io" |
| 35 | "log" |
| 36 | "os" |
| 37 | "runtime" |
| 38 | "sort" |
| 39 | |
| 40 | "github.com/brentp/irelate/interfaces" |
| 41 | ) |
| 42 | |
| 43 | func getStart(v interfaces.Relatable, s int) int { |
| 44 | if ci, ok := v.(interfaces.CIFace); ok { |
| 45 | a, _, ok := ci.CIPos() |
| 46 | if ok && int(a) < s { |
| 47 | return int(a) |
| 48 | } |
| 49 | } |
| 50 | return s |
| 51 | } |
| 52 | |
| 53 | func getEnd(v interfaces.Relatable, e int) int { |
| 54 | if ci, ok := v.(interfaces.CIFace); ok { |
| 55 | _, b, ok := ci.CIEnd() |
| 56 | if ok && int(b) > e { |
| 57 | return int(b) |
| 58 | } |
| 59 | } |
| 60 | return e |
| 61 | } |
| 62 | |
| 63 | func min(a, b int) int { |
| 64 | if a < b { |
| 65 | return a |
| 66 | } |
| 67 | return b |
| 68 | } |
| 69 | |
| 70 | func max(a, b int) int { |
| 71 | if a > b { |
| 72 | return a |
| 73 | } |
| 74 | return b |
| 75 | } |
| 76 | |
| 77 | type sliceIt struct { |
| 78 | slice []interfaces.Relatable |
| 79 | i int |
| 80 | } |
| 81 | |
| 82 | func (s *sliceIt) Next() (interfaces.Relatable, error) { |
| 83 | if s.i < len(s.slice) { |
| 84 | v := s.slice[s.i] |
| 85 | s.i += 1 |
| 86 | return v, nil |
| 87 | } |
| 88 | s.slice = nil |
| 89 | return nil, io.EOF |
| 90 | |
| 91 | } |
| 92 | func (s *sliceIt) Close() error { |
| 93 | return nil |
| 94 | } |
| 95 | |
| 96 | func sliceToIterator(A []interfaces.Relatable) interfaces.RelatableIterator { |
| 97 | return &sliceIt{A, 0} |
| 98 | } |
| 99 | |
| 100 | // islice makes []interfaces.Relatable sortable. |
| 101 | type islice []interfaces.Relatable |
| 102 | |
| 103 | func (i islice) Len() int { |
| 104 | return len(i) |
| 105 | } |
| 106 | |
| 107 | func (i islice) Less(a, b int) bool { |
| 108 | if i[a].Start() < i[b].Start() { |
| 109 | return true |
| 110 | } |
| 111 | if i[a].Start() == i[b].Start() && i[a].End() <= i[b].End() { |
| 112 | return true |
| 113 | } |
| 114 | return false |
| 115 | } |
| 116 | |
| 117 | func (is islice) Swap(i, j int) { |
| 118 | is[i], is[j] = is[j], is[i] |
| 119 | } |
| 120 | |
| 121 | type pos struct { |
| 122 | chrom string |
| 123 | start int |
| 124 | end int |
| 125 | } |
| 126 | |
| 127 | func (p pos) Chrom() string { |
| 128 | return p.chrom |
| 129 | } |
| 130 | func (p pos) Start() uint32 { |
| 131 | return uint32(p.start) |
| 132 | } |
| 133 | func (p pos) End() uint32 { |
| 134 | return uint32(p.end) |
| 135 | } |
| 136 | |
| 137 | // make a set of streams ready to be sent to irelate. |
| 138 | func makeStreams(receiver chan []interfaces.RelatableIterator, mustSort bool, A []interfaces.Relatable, lastChrom string, minStart int, maxEnd int, dbs ...interfaces.Queryable) { |
| 139 | |
| 140 | if mustSort { |
| 141 | sort.Sort(islice(A)) |
| 142 | } |
| 143 | |
| 144 | streams := make([]interfaces.RelatableIterator, 0, len(dbs)+1) |
| 145 | streams = append(streams, sliceToIterator(A)) |
| 146 | p := pos{lastChrom, minStart, maxEnd} |
| 147 | |
| 148 | for _, db := range dbs { |
| 149 | stream, err := db.Query(p) |
| 150 | if err != nil { |
| 151 | log.Fatal(err) |
| 152 | } |
| 153 | streams = append(streams, stream) |
| 154 | } |
| 155 | receiver <- streams |
| 156 | close(receiver) |
| 157 | } |
| 158 | |
| 159 | func checkOverlap(a, b interfaces.Relatable) bool { |
| 160 | return b.Start() < a.End() |
| 161 | } |
| 162 | |
| 163 | func less(a, b interfaces.Relatable) bool { |
| 164 | return a.Start() < b.Start() || (a.Start() == b.Start() && a.End() < b.End()) |
| 165 | } |
| 166 | |
| 167 | type ciRel struct { |
| 168 | interfaces.Relatable |
| 169 | index int |
| 170 | } |
| 171 | |
| 172 | func (ci ciRel) Start() uint32 { |
| 173 | return uint32(getStart(ci.Relatable, int(ci.Relatable.Start()))) |
| 174 | } |
| 175 | |
| 176 | func (ci ciRel) End() uint32 { |
| 177 | return uint32(getEnd(ci.Relatable, int(ci.Relatable.End()))) |
| 178 | } |
| 179 | |
| 180 | // PIRelate implements a parallel IRelate |
| 181 | func PIRelate(chunk int, maxGap int, qstream interfaces.RelatableIterator, ciExtend bool, fn func(interfaces.Relatable), dbs ...interfaces.Queryable) interfaces.RelatableChannel { |
| 182 | nprocs := runtime.GOMAXPROCS(-1) |
| 183 | // final interval stream sent back to caller. |
| 184 | intersected := make(chan interfaces.Relatable, 2048) |
| 185 | |
| 186 | // receivers keeps the interval chunks in order. |
| 187 | receivers := make(chan chan []interfaces.RelatableIterator, 1) |
| 188 | |
| 189 | // to channels recieves channels that accept intervals from IRelate to be sent for merging. |
| 190 | // we send slices of intervals to reduce locking. |
| 191 | tochannels := make(chan chan chan []interfaces.Relatable, 2+nprocs/2) |
| 192 | |
| 193 | verbose := os.Getenv("IRELATE_VERBOSE") == "TRUE" |
| 194 | |
| 195 | // the user-defined callback runs int it's own goroutine. |
| 196 | // call on the relatable itself. but with all of the associated intervals. |
| 197 | work := func(rels []interfaces.Relatable, fn func(interfaces.Relatable)) chan []interfaces.Relatable { |
| 198 | ch := make(chan []interfaces.Relatable, 0) |
| 199 | go func() { |
| 200 | if fn != nil { |
| 201 | for _, r := range rels { |
| 202 | fn(r) |
| 203 | } |
| 204 | } |
| 205 | ch <- rels |
| 206 | close(ch) |
| 207 | }() |
| 208 | return ch |
| 209 | } |
| 210 | if ciExtend { |
| 211 | |
| 212 | work = func(rels []interfaces.Relatable, fn func(interfaces.Relatable)) chan []interfaces.Relatable { |
| 213 | ch := make(chan []interfaces.Relatable, 0) |
| 214 | go func() { |
| 215 | if fn != nil { |
| 216 | for _, r := range rels { |
| 217 | fn(r.(ciRel).Relatable) |
| 218 | } |
| 219 | } |
| 220 | ch <- rels |
| 221 | close(ch) |
| 222 | }() |
| 223 | return ch |
| 224 | |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // pull the intervals from IRelate, call fn() and (via work()) send chunks to be merged. |
| 229 | // calling fn() is a bottleneck. so we make sub-chunks and process them in a separate go-routine |
| 230 | // in work() |
| 231 | // inner channel keeps track of the order for each big chunk |
| 232 | go func() { |
| 233 | |
| 234 | for streamsChan := range receivers { |
| 235 | |
| 236 | inner := make(chan chan []interfaces.Relatable, nprocs) |
| 237 | tochannels <- inner |
| 238 | |
| 239 | // push a channel to to channels out here |
| 240 | // and then push to that channel inside this goroutine. |
| 241 | // this maintains order of the intervals. |
| 242 | go func(streams []interfaces.RelatableIterator) { |
| 243 | N := 400 |
| 244 | //saved := make([]interfaces.Relatable, N) |
| 245 | iterator := IRelate(checkOverlap, 0, less, streams...) |
| 246 | saved := make([]interfaces.Relatable, N) |
| 247 | k := 0 |
| 248 | |
| 249 | for { |
| 250 | interval, err := iterator.Next() |
| 251 | if err == io.EOF { |
| 252 | iterator.Close() |
| 253 | break |
| 254 | } |
| 255 | saved[k] = interval |
| 256 | k++ |
| 257 | |
| 258 | if k == N { |
| 259 | inner <- work(saved, fn) |
| 260 | k = 0 |
| 261 | saved = make([]interfaces.Relatable, N) |
| 262 | } |
| 263 | |
| 264 | } |
| 265 | if k > 0 { |
| 266 | inner <- work(saved[:k], fn) |
| 267 | } |
| 268 | close(inner) |
| 269 | }(<-streamsChan) // only one, just used a chan for ordering. |
| 270 | } |
| 271 | close(tochannels) |
| 272 | }() |
| 273 | |
| 274 | go mergeIntervals(tochannels, intersected, ciExtend) |
| 275 | |
| 276 | // split the query intervals into chunks and send for processing to irelate. |
| 277 | go func() { |
| 278 | |
| 279 | A := make([]interfaces.Relatable, 0, chunk/2) |
| 280 | |
| 281 | lastStart := -10 |
| 282 | lastChrom := "" |
| 283 | minStart := int(^uint32(0) >> 1) |
| 284 | maxEnd := 0 |
| 285 | var totalParsed, totalSkipped, c, idx int |
| 286 | for { |
| 287 | v, err := qstream.Next() |
| 288 | if err == io.EOF { |
| 289 | qstream.Close() |
| 290 | } |
| 291 | if v == nil { |
| 292 | break |
| 293 | } |
| 294 | |
| 295 | if ciExtend { |
| 296 | // turn it into an object that will return the ci bounds for Start(), End() |
| 297 | v = ciRel{v, idx} |
| 298 | idx++ |
| 299 | } |
| 300 | |
| 301 | // these will be based on CIPOS, CIEND if ciExtend is true |
| 302 | s, e := int(v.Start()), int(v.End()) |
| 303 | |
| 304 | // end chunk when: |
| 305 | // 1. switch chroms |
| 306 | // 2. see maxGap bases between adjacent intervals (currently looks at start only) |
| 307 | // 3. reaches chunkSize (and has at least a gap of 2 bases from last interval). |
| 308 | if v.Chrom() != lastChrom || (len(A) > 2048 && s-lastStart > maxGap) || ((s-lastStart > 25 && len(A) >= chunk) || len(A) >= chunk+200) || s-lastStart > 10*maxGap { |
| 309 | if len(A) > 0 { |
| 310 | // we push a channel onto a queue (another channel) and use that as the output order. |
| 311 | ch := make(chan []interfaces.RelatableIterator, 0) |
| 312 | receivers <- ch |
| 313 | // send work to IRelate |
| 314 | go makeStreams(ch, ciExtend, A, lastChrom, minStart, maxEnd, dbs...) |
| 315 | c++ |
| 316 | if verbose { |
| 317 | if lastChrom == v.Chrom() { |
| 318 | totalSkipped += s - lastStart |
| 319 | } |
| 320 | totalParsed += maxEnd - minStart |
| 321 | var mem runtime.MemStats |
| 322 | runtime.ReadMemStats(&mem) |
| 323 | log.Println("intervals in current chunk:", len(A), fmt.Sprintf("%s:%d-%d", lastChrom, minStart, maxEnd), "gap:", s-lastStart) |
| 324 | log.Println("\tc:", c, "receivers:", len(receivers), "tochannels:", len(tochannels), "intersected:", len(intersected)) |
| 325 | log.Printf("\tmemory use: %dMB , heap in use: %dMB\n", mem.Alloc/uint64(1000*1000), |
| 326 | mem.HeapInuse/uint64(1000*1000)) |
| 327 | log.Printf("\ttotal bases skipped / parsed: %d / %d (%.2f)\n", totalSkipped, totalParsed, float64(totalSkipped)/float64(totalParsed)) |
| 328 | } |
| 329 | |
| 330 | } |
| 331 | lastStart = s |
| 332 | lastChrom, minStart, maxEnd = v.Chrom(), s, e |
| 333 | A = make([]interfaces.Relatable, 0, chunk/2) |
| 334 | } else { |
| 335 | lastStart = s |
| 336 | maxEnd = max(e, maxEnd) |
| 337 | minStart = min(s, minStart) |
| 338 | } |
| 339 | |
| 340 | A = append(A, v) |
| 341 | } |
| 342 | |
| 343 | if len(A) > 0 { |
| 344 | ch := make(chan []interfaces.RelatableIterator, 0) |
| 345 | receivers <- ch |
| 346 | go makeStreams(ch, ciExtend, A, lastChrom, minStart, maxEnd, dbs...) |
| 347 | c++ |
| 348 | } |
| 349 | close(receivers) |
| 350 | }() |
| 351 | return intersected |
| 352 | } |
| 353 | |
| 354 | func mergeIntervals(tochannels chan chan chan []interfaces.Relatable, intersected chan interfaces.Relatable, ciExtend bool) { |
| 355 | // merge the intervals from different channels keeping order. |
| 356 | // 2 separate function code-blocks so there is no performance hit when they don't |
| 357 | // care about the cipos. |
| 358 | if ciExtend { |
| 359 | nextPrint := 0 |
| 360 | q := make(map[int]ciRel, 100) |
| 361 | for och := range tochannels { |
| 362 | for ch := range och { |
| 363 | for intervals := range ch { |
| 364 | for _, interval := range intervals { |
| 365 | ci := interval.(ciRel) |
| 366 | if ci.index == nextPrint { |
| 367 | intersected <- ci.Relatable |
| 368 | nextPrint++ |
| 369 | } else { |
| 370 | q[ci.index] = ci |
| 371 | for { |
| 372 | n, ok := q[nextPrint] |
| 373 | if !ok { |
| 374 | break |
| 375 | } |
| 376 | delete(q, nextPrint) |
| 377 | intersected <- n.Relatable |
| 378 | nextPrint++ |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | // empty out the q |
| 383 | for { |
| 384 | n, ok := q[nextPrint] |
| 385 | if !ok { |
| 386 | break |
| 387 | } |
| 388 | delete(q, nextPrint) |
| 389 | intersected <- n.Relatable |
| 390 | nextPrint++ |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | } else { |
| 396 | for och := range tochannels { |
| 397 | for ch := range och { |
| 398 | for intervals := range ch { |
| 399 | for _, interval := range intervals { |
| 400 | intersected <- interval |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | close(intersected) |
| 407 | } |