Debian Codegraph @

eutils/merge.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: merge.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "container/heap"
36 "fmt"
37 "github.com/klauspost/pgzip"
38 "io"
39 "maps"
40 "os"
41 "path/filepath"
42 "runtime"
43 "runtime/debug"
44 "slices"
45 "strings"
46 "sync"
47 )
48
49 // Plex allows distribution of indexing
50 type Plex struct {
51 Sibs []string
52 Ident string
53 Text string
54 Which int
55 Index int
56 }
57
58 // PlexHeap methods satisfy heap.Interface
59 type PlexHeap []Plex
60
61 func (h PlexHeap) Len() int {
62 return len(h)
63 }
64 func (h PlexHeap) Less(i, j int) bool {
65 return h[i].Ident < h[j].Ident
66 }
67 func (h PlexHeap) Swap(i, j int) {
68 h[i], h[j] = h[j], h[i]
69 }
70
71 // Push works on pointer to PlexHeap
72 func (h *PlexHeap) Push(x interface{}) {
73 *h = append(*h, x.(Plex))
74 }
75
76 // Pop works on pointer to PlexHeap
77 func (h *PlexHeap) Pop() interface{} {
78 old := *h
79 n := len(old)
80 x := old[n-1]
81 *h = old[0 : n-1]
82 return x
83 }
84
85 // CreatePresenters creates one channel per input file
86 func CreatePresenters(files []string) []<-chan Plex {
87
88 if files == nil {
89 return nil
90 }
91
92 numFiles := len(files)
93 if numFiles < 1 {
94 DisplayError("Not enough inverted files to merge")
95 os.Exit(1)
96 }
97
98 chns := make([]<-chan Plex, numFiles)
99 if chns == nil {
100 DisplayError("Unable to create presenter channel array")
101 os.Exit(1)
102 }
103
104 // xmlPresenter sends partitioned XML strings through channel
105 xmlPresenter := func(fileNum int, fileName string, out chan<- Plex) {
106
107 // close channel when all records have been processed
108 defer close(out)
109
110 f, err := os.Open(fileName)
111 if err != nil {
112 DisplayError("Unable to open input file '%s'", fileName)
113 os.Exit(1)
114 }
115
116 // close input file when all records have been processed
117 defer f.Close()
118
119 var in io.Reader
120
121 in = f
122
123 // if suffix is ".gz", use decompressor
124 iszip := false
125 if strings.HasSuffix(fileName, ".gz") {
126 iszip = true
127 }
128
129 if iszip {
130 brd := bufio.NewReader(f)
131 if brd == nil {
132 DisplayError("Unable to create buffered reader on '%s'", fileName)
133 os.Exit(1)
134 }
135 // using parallel pgzip for better performance on large files
136 zpr, err := pgzip.NewReader(brd)
137 if err != nil {
138 DisplayError("Unable to create decompressor on '%s'", fileName)
139 os.Exit(1)
140 }
141
142 // close decompressor when all records have been processed
143 defer zpr.Close()
144
145 // use decompressor for reading file
146 in = zpr
147 }
148
149 rdr := CreateXMLStreamer(in, nil)
150
151 if rdr == nil {
152 DisplayError("Unable to create XML Block Reader")
153 os.Exit(1)
154 }
155
156 find := ParseIndex("InvKey")
157
158 // partition all input by pattern and send XML substring through channel
159 PartitionXML("InvDocument", "", false, rdr,
160 func(str string) {
161 id := FindIdentifier(str[:], "InvDocument", find)
162
163 out <- Plex{Which: fileNum, Ident: id, Text: str, Index: 0, Sibs: nil}
164 })
165 }
166
167 // launch multiple presenter goroutines
168 for i, str := range files {
169
170 chn := make(chan Plex, chanDepth)
171 if chn == nil {
172 DisplayError("Unable to create presenter channel")
173 os.Exit(1)
174 }
175
176 go xmlPresenter(i, str, chn)
177
178 chns[i] = chn
179 }
180
181 // no need for separate anonymous goroutine to wait until all presenters are done
182
183 return chns
184 }
185
186 // CreateManifold reads from each file, sends merged postings in sorted order
187 func CreateManifold(inp []<-chan Plex) <-chan Plex {
188
189 if inp == nil {
190 return nil
191 }
192
193 out := make(chan Plex, chanDepth)
194 if out == nil {
195 DisplayError("Unable to create manifold channel")
196 os.Exit(1)
197 }
198
199 // xmlManifold restores alphabetical order of merged postings
200 xmlManifold := func(inp []<-chan Plex, out chan<- Plex) {
201
202 // close channel when all records have been processed
203 defer close(out)
204
205 // initialize empty heap
206 hp := &PlexHeap{}
207 heap.Init(hp)
208
209 // read first object from all input channels in turn
210 for _, chn := range inp {
211 plx, ok := <-chn
212 if ok {
213 heap.Push(hp, plx)
214 }
215 }
216
217 // array to collect strings with same identifier
218 var arry []string
219
220 prevIdent := ""
221 rec := 0
222
223 // reading from heap returns objects in alphabetical order
224 for hp.Len() > 0 {
225
226 // remove lowest item from heap, use interface type assertion
227 curr := heap.Pop(hp).(Plex)
228
229 // compare adjacent record identifiers
230 if prevIdent == curr.Ident {
231
232 // save next inverted object string in slice
233 arry = append(arry, curr.Text)
234
235 } else {
236
237 if len(arry) > 0 {
238
239 rec++
240 // send set from previous identifier to output channel
241 out <- Plex{Which: 0, Ident: prevIdent, Text: "", Index: rec, Sibs: arry}
242
243 // empty the slice
244 arry = nil
245
246 runtime.Gosched()
247 }
248
249 // remember new identifier
250 prevIdent = curr.Ident
251
252 // save first inverted object with this identifier
253 arry = append(arry, curr.Text)
254 }
255
256 // read next object from channel that just supplied lowest item
257 chn := inp[curr.Which]
258 plx, ok := <-chn
259 if ok {
260 heap.Push(hp, plx)
261 }
262 }
263
264 if len(arry) > 0 {
265
266 rec++
267 // send last record
268 out <- Plex{Which: 0, Ident: prevIdent, Text: "", Index: rec, Sibs: arry}
269
270 arry = nil
271 }
272 }
273
274 // launch single manifold goroutine
275 go xmlManifold(inp, out)
276
277 return out
278 }
279
280 // CreateFusers collects all inverted indices for a given term
281 func CreateFusers(inp <-chan XMLRecord) <-chan Plex {
282
283 if inp == nil {
284 return nil
285 }
286
287 out := make(chan Plex, chanDepth)
288 if out == nil {
289 DisplayError("Unable to create fuser channel")
290 os.Exit(1)
291 }
292
293 var flock sync.Mutex
294
295 // map for combining inverted indices
296 inverted := make(map[string][]string)
297
298 addInverts := func(id, str string) {
299
300 // protect map with mutex
301 flock.Lock()
302
303 data, ok := inverted[id]
304 if !ok {
305 data = make([]string, 0, 1)
306 }
307
308 data = append(data, str)
309 // always need to update inverted, since data may be reallocated
310 inverted[id] = data
311
312 // unlock at end to avoid defer overhead
313 flock.Unlock()
314 }
315
316 xmlFuser := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- Plex) {
317
318 defer wg.Done()
319
320 find := ParseIndex("InvKey")
321
322 // read partitioned XML from producer channel
323 for ext := range inp {
324
325 str := ext.Text[:]
326 id := FindIdentifier(str, "InvDocument", find)
327 addInverts(id, str)
328 }
329 }
330
331 var wg sync.WaitGroup
332
333 // launch multiple fuser goroutines
334 for range numProcs {
335 wg.Add(1)
336 go xmlFuser(&wg, inp, out)
337 }
338
339 // launch separate anonymous goroutine to wait until all fusers are done
340 go func() {
341 wg.Wait()
342
343 // sort id keys in alphabetical order
344 keys := slices.Sorted(maps.Keys(inverted))
345
346 rec := 0
347
348 for _, id := range keys {
349
350 arry := inverted[id]
351
352 rec++
353 // send array of records with same identifier to output channel
354 out <- Plex{Which: 0, Ident: id, Text: "", Index: rec, Sibs: arry}
355
356 // empty the slice
357 arry = nil
358 }
359
360 close(out)
361 }()
362
363 return out
364 }
365
366 // CreateJoiners repackages adjacent indices for the same term without fusing
367 func CreateJoiners(inp <-chan Plex) <-chan XMLRecord {
368
369 if inp == nil {
370 return nil
371 }
372
373 out := make(chan XMLRecord, chanDepth)
374 if out == nil {
375 DisplayError("Unable to create merger channel")
376 os.Exit(1)
377 }
378
379 // xmlJoiner unpacks adjacent InvDocument records with the same identifier
380 xmlJoiner := func(inp <-chan Plex, out chan<- XMLRecord) {
381
382 defer close(out)
383
384 for plx := range inp {
385
386 rec := plx.Index
387 key := plx.Ident
388 data := plx.Sibs
389
390 if len(data) < 1 {
391 continue
392 }
393
394 for _, str := range data {
395 out <- XMLRecord{Index: rec, Ident: key, Text: str[:]}
396 }
397
398 runtime.Gosched()
399 }
400 }
401
402 // launch single joiner goroutine
403 go xmlJoiner(inp, out)
404
405 return out
406 }
407
408 // CreateMergers combines collected indices for the same term
409 func CreateMergers(inp <-chan Plex) <-chan XMLRecord {
410
411 if inp == nil {
412 return nil
413 }
414
415 out := make(chan XMLRecord, chanDepth)
416 if out == nil {
417 DisplayError("Unable to create merger channel")
418 os.Exit(1)
419 }
420
421 // xmlMerger fuses adjacent InvDocument records with the same identifier
422 xmlMerger := func(wg *sync.WaitGroup, inp <-chan Plex, out chan<- XMLRecord) {
423
424 defer wg.Done()
425
426 fusePostings := func(key string, data []string) string {
427
428 fields := make(map[string]map[string]string)
429
430 addIdents := func(fld, pos, uid string) {
431
432 // no need for mutex here
433 positions, ok := fields[fld]
434 if !ok {
435 positions = make(map[string]string)
436 fields[fld] = positions
437 }
438
439 positions[uid] = pos
440 }
441
442 addUID := func(tag, attr, content string) {
443
444 if tag != "InvKey" {
445
446 addIdents(tag, attr, content)
447 }
448 }
449
450 for _, str := range data {
451 StreamValues(str[:], "InvDocument", addUID)
452 }
453
454 // sort fields in alphabetical order
455 keys := slices.Sorted(maps.Keys(fields))
456
457 var res []string
458
459 for _, fld := range keys {
460
461 positions := fields[fld]
462
463 arry := slices.SortedFunc(maps.Keys(positions), CompareAlphaOrNumericKeys)
464
465 // print list of UIDs, skipping duplicates
466 last := ""
467 for _, uid := range arry {
468 // detect duplicate UIDs, now in same list after conversion of one term entry from foreign alphabet
469 if uid == last {
470 continue
471 }
472
473 atr := positions[uid]
474 if atr != "" {
475 str := "<" + fld + " " + atr + ">" + uid + "</" + fld + ">"
476 res = append(res, str)
477 } else {
478 str := "<" + fld + ">" + uid + "</" + fld + ">"
479 res = append(res, str)
480 }
481
482 last = uid
483 }
484 }
485
486 itms := strings.Join(res, "\n")
487
488 return "<InvDocument>\n<InvKey>" + key + "</InvKey>\n<InvIDs>\n" + itms + "\n</InvIDs>\n</InvDocument>\n"
489 }
490
491 for plx := range inp {
492
493 rec := plx.Index
494 key := plx.Ident
495 data := plx.Sibs
496
497 if len(data) < 1 {
498 continue
499 }
500
501 str := fusePostings(key, data)
502
503 out <- XMLRecord{Index: rec, Ident: key, Text: str}
504
505 runtime.Gosched()
506 }
507 }
508
509 var wg sync.WaitGroup
510
511 // launch multiple merger goroutines
512 for range numProcs {
513 wg.Add(1)
514 go xmlMerger(&wg, inp, out)
515 }
516
517 // launch separate anonymous goroutine to wait until all mergers are done
518 go func() {
519 wg.Wait()
520 close(out)
521 }()
522
523 return out
524 }
525
526 // CreateSplitter distributes adjacent records with the same identifier prefix
527 func CreateSplitter(mergePath, db string, zipp, isLink bool, inp <-chan XMLRecord) <-chan string {
528
529 if inp == nil {
530 return nil
531 }
532
533 // obtain paths from environment variable(s)
534 mergeBase := GetLocalArchiveFolder(db, "Merged", true)
535
536 if mergeBase == "" {
537 DisplayError("Unable to get local merge path")
538 os.Exit(1)
539 }
540
541 // check to make sure local merge directory is mounted
542 _, err := os.Stat(mergeBase)
543 if err != nil && os.IsNotExist(err) {
544 DisplayError("Local merge directory '%s' is not mounted", mergeBase)
545 os.Exit(1)
546 }
547
548 out := make(chan string, chanDepth)
549 if out == nil {
550 DisplayError("Unable to create splitter channel")
551 os.Exit(1)
552 }
553
554 openSaver := func(mergeBase, key string, zipp bool) (*os.File, *bufio.Writer, *pgzip.Writer) {
555
556 var (
557 fl *os.File
558 wrtr *bufio.Writer
559 zpr *pgzip.Writer
560 err error
561 )
562
563 sfx := ".mrg"
564 if zipp {
565 sfx += ".gz"
566 }
567
568 fpath := filepath.Join(mergeBase, key+sfx)
569 if fpath == "" {
570 return nil, nil, nil
571 }
572
573 // overwrites and truncates existing file
574 fl, err = os.Create(fpath)
575 if err != nil {
576 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
577 return nil, nil, nil
578 }
579
580 var out io.Writer
581
582 out = fl
583
584 if zipp {
585
586 // using parallel pgzip for better performance on large files
587 zpr, err = pgzip.NewWriterLevel(fl, pgzip.BestSpeed)
588 if err != nil {
589 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
590 return nil, nil, nil
591 }
592
593 out = zpr
594 }
595
596 // create buffered writer layer
597 wrtr = bufio.NewWriter(out)
598 if wrtr == nil {
599 DisplayError("Unable to create bufio.NewWriter")
600 return nil, nil, nil
601 }
602
603 return fl, wrtr, zpr
604 }
605
606 closeSaver := func(fl *os.File, wrtr *bufio.Writer, zpr *pgzip.Writer) {
607
608 wrtr.Flush()
609 if zpr != nil {
610 zpr.Close()
611 }
612 // fl.Sync()
613
614 err := fl.Close()
615 if err != nil {
616 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
617 }
618 }
619
620 // xmlSplitter distributes adjacent records with the same identifier prefix
621 xmlSplitter := func(inp <-chan XMLRecord, out chan<- string) {
622
623 // close channel when all records have been processed
624 defer close(out)
625
626 var (
627 fl *os.File
628 wrtr *bufio.Writer
629 zpr *pgzip.Writer
630 )
631
632 currTag := ""
633 prevTag := ""
634
635 // remember previous record
636 prev := XMLRecord{}
637
638 getCurrTag := func(ident string) string {
639
640 // links always use first 4 characters of zero-padded identifier
641 if isLink {
642 if len(ident) > LinkLen {
643 ident = ident[:LinkLen]
644 }
645 return ident
646 }
647
648 // use first few characters of identifier
649 tag := IdentifierKey(ident)
650 if tag == "" {
651 return ""
652 }
653
654 // then truncate to 2, 3, or 4 character prefix
655 if len(tag) > 2 {
656 key := tag[:2]
657 num, ok := TrieLen[key]
658 if ok {
659 if num > 3 && len(tag) > 3 {
660 key = tag[:3]
661 num, ok = MergLen[key]
662 if ok && num > 3 {
663 tag = tag[:4]
664 } else {
665 tag = tag[:3]
666 }
667 } else if num > 2 {
668 tag = tag[:3]
669 } else {
670 tag = tag[:2]
671 }
672 } else {
673 tag = tag[:2]
674 }
675 }
676
677 return tag
678 }
679
680 for curr := range inp {
681
682 // use first few characters of identifier
683 currTag = getCurrTag(curr.Ident)
684 if currTag == "" {
685 continue
686 }
687
688 if fl == nil {
689 // open initial file
690 fl, wrtr, zpr = openSaver(mergeBase, currTag, zipp)
691 if wrtr == nil {
692 continue
693 }
694
695 // send first opening tag and indent
696 wrtr.WriteString("<InvDocumentSet>\n ")
697 }
698
699 // compare keys from adjacent term lists
700 if prev.Text != "" && prevTag != currTag {
701
702 // after IdentifierKey converts space to underscore,
703 // okay that x_ and x0 will be out of alphabetical order
704
705 // send closing tag
706 wrtr.WriteString("</InvDocumentSet>\n")
707
708 closeSaver(fl, wrtr, zpr)
709
710 out <- currTag
711
712 // force garbage collection
713 runtime.GC()
714 debug.FreeOSMemory()
715
716 runtime.Gosched()
717
718 // open next file
719 fl, wrtr, zpr = openSaver(mergeBase, currTag, zipp)
720 if wrtr == nil {
721 continue
722 }
723
724 // send opening tag and indent
725 wrtr.WriteString("<InvDocumentSet>\n ")
726 }
727
728 // send one InvDocument
729 str := strings.TrimSpace(curr.Text)
730
731 wrtr.WriteString(str)
732 if !strings.HasSuffix(str, "\n") {
733 wrtr.WriteString("\n")
734 }
735
736 // now remember this record
737 prev = curr
738
739 prevTag = currTag
740 }
741
742 if prev.Text != "" {
743
744 // send last closing tag
745 wrtr.WriteString("</InvDocumentSet>\n")
746
747 closeSaver(fl, wrtr, zpr)
748
749 out <- currTag
750
751 // force garbage collection
752 runtime.GC()
753 debug.FreeOSMemory()
754
755 runtime.Gosched()
756 }
757 }
758
759 // launch single splitter goroutine
760 go xmlSplitter(inp, out)
761
762 return out
763 }