Debian Codegraph @

eutils/utils.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: utils.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "compress/gzip"
36 "fmt"
37 "github.com/klauspost/cpuid"
38 "github.com/pbnjay/memory"
39 "io"
40 "os"
41 "path/filepath"
42 "runtime"
43 "runtime/debug"
44 "strconv"
45 "strings"
46 "time"
47 )
48
49 // EDirectVersion is the current EDirect release number
50 const EDirectVersion = "24.0"
51
52 // ANSI escape codes for terminal color, highlight, and reverse
53 const (
54 RED = "\033[31m"
55 BLUE = "\033[34m"
56 BOLD = "\033[1m"
57 RVRS = "\033[7m"
58 INIT = "\033[0m"
59 LOUD = INIT + RED + BOLD
60 INVT = LOUD + RVRS
61 )
62
63 // PERFORMANCE PARAMETERS AND PROCESSING OPTIONS
64
65 // eutils library-specific general control variables are set on an
66 // individual program basis, and are safe because Go programs are
67 // statically linked, eschewing dynamically-loaded shared libraries.
68
69 // Library-specific variables are initialized in an "init" function
70 // at the end of this file. All init functions in a program are
71 // executed before control transfers to the "main" function.
72
73 // performance tuning variables
74 var (
75 chanDepth int
76 farmSize int
77 heapSize int
78 numServe int
79 goGc int
80 nCPU int
81 numProcs int
82 serverRatio int
83 )
84
85 // reading and cleaning options
86 var (
87 doStrict bool
88 doMixed bool
89 doSelf bool
90 deAccent bool
91 deSymbol bool
92 doASCII bool
93 doCompress bool
94 doCleanup bool
95 doStem bool
96 deStop bool
97 )
98
99 // additional options
100 var (
101 doUnicode bool
102 doScript bool
103 doMathML bool
104 )
105
106 // derived policy variables
107 var (
108 allowEmbed bool
109 contentMods bool
110 countLines bool
111 )
112
113 var (
114 unicodeFix = NOMARKUP
115 scriptFix = NOMARKUP
116 mathMLFix = NOMARKUP
117 )
118
119 // parser character type lookup tables
120 var (
121 inBlank [256]bool
122 inFirst [256]bool
123 inElement [256]bool
124 inLower [256]bool
125 inContent [256]bool
126 inAsnTag [256]bool
127 inAsnString [256]bool
128 inAsnBits [256]bool
129 )
130
131 // program execution timer
132 var (
133 startTime time.Time
134 )
135
136 // SetTunings sets performance parameters
137 func SetTunings(nmProcs, nmServe, svRatio, chnDepth, frmSize, hepSize, gogc int, turbo bool) {
138
139 // set default values
140 if frmSize < 1 {
141 frmSize = 64
142 }
143
144 if hepSize < 8 || hepSize > 64 {
145 hepSize = 16
146 }
147
148 if gogc < 50 || gogc > 1000 {
149 gogc = 600
150 }
151
152 farmSize = frmSize
153 heapSize = hepSize
154 goGc = gogc
155
156 // calculate number of simultaneous threads for multiplexed goroutines
157 nCPU = runtime.NumCPU()
158 if nCPU < 1 {
159 nCPU = 1
160 }
161
162 // Reality checks on number of processors to use. Performance degrades if capacity is above
163 // maximum number of partitions per second (context switching?). Best performance varies
164 // slightly among PubmedArticle, gene DocumentSummary, and INSDSeq sequence records.
165 if nmProcs < 1 {
166 if turbo {
167 // best performance measurement with size-indexed data is obtained when 12 hyperthreads are assigned
168 nmProcs = 12
169 threads := nCPU
170 if threads > 4 && threads < 12 {
171 nmProcs = threads
172 }
173 } else {
174 // best performance measurement with Boyer-Moore-Horspool when 6 to 8 processors are assigned
175 nmProcs = 8
176 if cpuid.CPU.ThreadsPerCore > 1 {
177 cores := nCPU / cpuid.CPU.ThreadsPerCore
178 if cores > 4 && cores < 8 {
179 nmProcs = cores
180 }
181 }
182 }
183 }
184
185 if nmProcs > nCPU {
186 nmProcs = nCPU
187 }
188
189 numProcs = nmProcs
190
191 // allow simultaneous threads for multiplexed goroutines
192 runtime.GOMAXPROCS(numProcs)
193
194 // adjust garbage collection target percentage
195 debug.SetGCPercent(goGc)
196
197 if svRatio < 1 || svRatio > 32 {
198 svRatio = 4
199 }
200
201 serverRatio = svRatio
202
203 if nmServe > 0 {
204 serverRatio = nmServe / numProcs
205 } else {
206 nmServe = numProcs * serverRatio
207 }
208
209 if nmServe > 128 {
210 nmServe = 128
211 } else if nmServe < 1 {
212 nmServe = numProcs
213 }
214
215 numServe = nmServe
216
217 // number of channels usually equals number of servers
218 if chnDepth < nCPU || chnDepth > 128 {
219 chnDepth = numServe
220 }
221
222 chanDepth = chnDepth
223 }
224
225 // SetOptions sets processing options
226 func SetOptions(strict, mixed, self, accent, symbol, ascii, compress, cleanup, stem, stop bool) {
227
228 doStrict = strict
229 doMixed = mixed
230
231 doSelf = self
232
233 deAccent = accent
234 deSymbol = symbol
235 doASCII = ascii
236
237 doCompress = compress
238 doCleanup = cleanup
239
240 doStem = stem
241 deStop = stop
242
243 countLines = false
244
245 // set dependent flags
246 countLines = doMixed
247 allowEmbed = doStrict || doMixed
248 contentMods = allowEmbed || doCompress || doUnicode || doScript || doMathML || deAccent || deSymbol || doASCII
249 }
250
251 // ChanDepth returns the communication channel depth
252 func ChanDepth() int {
253
254 return chanDepth
255 }
256
257 // NumServe returns the number of concurrent servers
258 func NumServe() int {
259
260 return numServe
261 }
262
263 // GetTunings returns performance parameter values
264 func GetTunings() (nmProcs, nmServe, svRatio, chnDepth, frmSize, hepSize, gogc int) {
265
266 return numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc
267 }
268
269 // GetOptions returns processing option values
270 func GetOptions() (strict, mixed, self, accent, symbol, ascii, compress, cleanup, stem, stop bool) {
271
272 return doStrict, doMixed, doSelf, deAccent, deSymbol, doASCII, doCompress, doCleanup, doStem, deStop
273 }
274
275 // GetNumericArg returns an integer argument, reporting an error if no remaining arguments
276 func GetNumericArg(args []string, name string, zer, min, max int) int {
277
278 if len(args) < 2 {
279 DisplayError("%s is missing", name)
280 os.Exit(1)
281 }
282 value, err := strconv.Atoi(args[1])
283 if err != nil {
284 DisplayError("%s (%s) is not an integer", name, args[1])
285 os.Exit(1)
286 }
287
288 // special case for argument value of 0
289 if value < 1 {
290 return zer
291 }
292 // limit value to between specified minimum and maximum
293 if value < min && min > 0 {
294 return min
295 }
296 if value > max && max > 0 {
297 return max
298 }
299 return value
300 }
301
302 // GetStringArg returns a string argument, reporting an error if no remaining arguments
303 func GetStringArg(args []string, name string) string {
304
305 if len(args) < 2 {
306 DisplayError("%s is missing", name)
307 os.Exit(1)
308 }
309 return args[1]
310 }
311
312 // PrintDuration prints processing rate and program duration
313 func PrintDuration(name string, recordCount, byteCount int) {
314
315 stopTime := time.Now()
316 duration := stopTime.Sub(startTime)
317 seconds := float64(duration.Nanoseconds()) / 1e9
318
319 prec := 3
320 if seconds >= 100 {
321 prec = 1
322 } else if seconds >= 10 {
323 prec = 2
324 }
325
326 if recordCount >= 1000000 {
327 throughput := float64(recordCount/100000) / 10.0
328 fmt.Fprintf(os.Stderr, "\nProcessed %.1f million %s in %.*f seconds", throughput, name, prec, seconds)
329 } else if recordCount > 0 {
330 fmt.Fprintf(os.Stderr, "\nProcessed %d %s in %.*f seconds", recordCount, name, prec, seconds)
331 } else {
332 fmt.Fprintf(os.Stderr, "\nProcessing completed in %.*f seconds", prec, seconds)
333 }
334
335 if seconds >= 0.001 && recordCount > 0 {
336 rate := int(float64(recordCount) / seconds)
337 if rate >= 1000000 {
338 fmt.Fprintf(os.Stderr, " (%d million %s/second", rate/1000000, name)
339 } else {
340 fmt.Fprintf(os.Stderr, " (%d %s/second", rate, name)
341 }
342 if byteCount > 0 {
343 rate := int(float64(byteCount) / seconds)
344 if rate >= 1000000 {
345 fmt.Fprintf(os.Stderr, ", %d megabytes/second", rate/1000000)
346 } else if rate >= 1000 {
347 fmt.Fprintf(os.Stderr, ", %d kilobytes/second", rate/1000)
348 } else {
349 fmt.Fprintf(os.Stderr, ", %d bytes/second", rate)
350 }
351 }
352 fmt.Fprintf(os.Stderr, ")")
353 }
354
355 fmt.Fprintf(os.Stderr, "\n\n")
356 }
357
358 // PrintMemory is adapted from PrintMemUsage in: https://golangcode.com/print-the-current-memory-usage/
359 func PrintMemory() {
360
361 var m runtime.MemStats
362 runtime.ReadMemStats(&m)
363
364 bToMb := func(b uint64) uint64 {
365 return b / 1024 / 1024
366 }
367
368 // For info on each, see: https://golang.org/pkg/runtime/#MemStats
369 fmt.Fprintf(os.Stderr, "Alloc = %v MiB", bToMb(m.Alloc))
370 fmt.Fprintf(os.Stderr, "\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
371 fmt.Fprintf(os.Stderr, "\tSys = %v MiB", bToMb(m.Sys))
372 fmt.Fprintf(os.Stderr, "\tNumGC = %v\n", m.NumGC)
373 }
374
375 // PrintStats prints performance tuning parameters
376 func PrintStats() {
377
378 fmt.Fprintf(os.Stderr, "Thrd %d\n", nCPU)
379 if cpuid.CPU.ThreadsPerCore > 0 {
380 fmt.Fprintf(os.Stderr, "Core %d\n", nCPU/cpuid.CPU.ThreadsPerCore)
381 }
382 if cpuid.CPU.LogicalCores > 0 {
383 fmt.Fprintf(os.Stderr, "Sock %d\n", nCPU/cpuid.CPU.LogicalCores)
384 }
385 fmt.Fprintf(os.Stderr, "Mmry %d\n", memory.TotalMemory()/(1024*1024*1024))
386
387 fmt.Fprintf(os.Stderr, "Proc %d\n", numProcs)
388 fmt.Fprintf(os.Stderr, "Serv %d\n", numServe)
389 fmt.Fprintf(os.Stderr, "Chan %d\n", chanDepth)
390 fmt.Fprintf(os.Stderr, "Heap %d\n", heapSize)
391 fmt.Fprintf(os.Stderr, "Farm %d\n", farmSize)
392 fmt.Fprintf(os.Stderr, "Gogc %d\n", goGc)
393
394 fi, err := os.Stdin.Stat()
395 if err == nil {
396 mode := fi.Mode().String()
397 fmt.Fprintf(os.Stderr, "Mode %s\n", mode)
398 }
399
400 fmt.Fprintf(os.Stderr, "\n")
401 }
402
403 // PrintHelp finds and prints indicated help file
404 func PrintHelp(programName, helpFile string) {
405
406 ex, eerr := os.Executable()
407 if eerr == nil {
408 fmt.Printf("%s %s\n\n", programName, EDirectVersion)
409 exPath := filepath.Dir(ex)
410 fpath := filepath.Join(exPath, "help", helpFile)
411 file, ferr := os.Open(fpath)
412 if file != nil && ferr == nil {
413 scanner := bufio.NewScanner(file)
414 for scanner.Scan() {
415 fmt.Println(scanner.Text())
416 }
417 }
418 file.Close()
419 fmt.Printf("\n")
420 }
421 }
422
423 // DisplayError prints a decorated ERROR message on stderr
424 func DisplayError(format string, params ...any) {
425
426 str := fmt.Sprintf(format, params...)
427 fmt.Fprintf(os.Stderr, "\n%s ERROR: %s %s%s\n", INVT, LOUD, str, INIT)
428 }
429
430 // DisplayWarning prints a decorated WARNING message on stderr
431 func DisplayWarning(format string, params ...any) {
432
433 str := fmt.Sprintf(format, params...)
434 fmt.Fprintf(os.Stderr, "\n%s WARNING: %s %s%s\n", INVT, LOUD, str, INIT)
435 }
436
437 // ReadTextFileToString reads an ASCII or Unicode text file into a string, decompressing automatically if it has a ".gz" suffix
438 func ReadTextFileToString(fileName string) string {
439
440 // this function returns an empty string on failure instead of calling os.Exit
441
442 f, err := os.Open(fileName)
443 if err != nil {
444 DisplayError("Unable to open input file '%s'", fileName)
445 return ""
446 }
447
448 defer f.Close()
449
450 var in io.Reader
451
452 in = f
453
454 if strings.HasSuffix(fileName, ".gz") {
455
456 brd := bufio.NewReader(f)
457 if brd == nil {
458 DisplayError("Unable to create buffered reader on '%s'", fileName)
459 return ""
460 }
461 zpr, err := gzip.NewReader(brd)
462 if err != nil {
463 DisplayError("Unable to create decompressor on '%s'", fileName)
464 return ""
465 }
466
467 defer zpr.Close()
468
469 in = zpr
470 }
471
472 byt, err := io.ReadAll(in)
473 if err != nil {
474 return ""
475 }
476
477 str := string(byt)
478 if str == "" {
479 return ""
480 }
481
482 if !strings.HasSuffix(str, "\n") {
483 str += "\n"
484 }
485
486 return str
487 }
488
489 // initialize lookup tables that simplify the tokenizer
490 func init() {
491
492 startTime = time.Now()
493
494 for i := range inBlank {
495 inBlank[i] = false
496 }
497 inBlank[' '] = true
498 inBlank['\t'] = true
499 inBlank['\n'] = true
500 inBlank['\r'] = true
501 inBlank['\f'] = true
502
503 // first character of element cannot be a digit, dash, or period
504 for i := range inFirst {
505 inFirst[i] = false
506 }
507 for ch := 'A'; ch <= 'Z'; ch++ {
508 inFirst[ch] = true
509 }
510 for ch := 'a'; ch <= 'z'; ch++ {
511 inFirst[ch] = true
512 }
513 inFirst['_'] = true
514 // extend legal initial letter with at sign and digits to handle biological data converted from JSON
515 inFirst['@'] = true
516 for ch := '0'; ch <= '9'; ch++ {
517 inFirst[ch] = true
518 }
519
520 // remaining characters also includes colon for namespace
521 for i := range inElement {
522 inElement[i] = false
523 }
524 for ch := 'A'; ch <= 'Z'; ch++ {
525 inElement[ch] = true
526 }
527 for ch := 'a'; ch <= 'z'; ch++ {
528 inElement[ch] = true
529 }
530 for ch := '0'; ch <= '9'; ch++ {
531 inElement[ch] = true
532 }
533 inElement['_'] = true
534 inElement['-'] = true
535 inElement['.'] = true
536 inElement[':'] = true
537
538 // embedded markup and math tags are lower case
539 for i := range inLower {
540 inLower[i] = false
541 }
542 for ch := 'a'; ch <= 'z'; ch++ {
543 inLower[ch] = true
544 }
545 for ch := '0'; ch <= '9'; ch++ {
546 inLower[ch] = true
547 }
548 inLower['_'] = true
549 inLower['-'] = true
550 inLower['.'] = true
551 inLower[':'] = true
552
553 // shortcut to find <, >, or &, or non-ASCII
554 for i := range inContent {
555 inContent[i] = false
556 }
557 for i := 0; i <= 127; i++ {
558 inContent[i] = true
559 }
560 inContent['<'] = false
561 inContent['>'] = false
562 inContent['&'] = false
563
564 // ASN.1 tag can have letters, digits, and dashes
565 for i := range inAsnTag {
566 inAsnTag[i] = false
567 }
568 for ch := 'A'; ch <= 'Z'; ch++ {
569 inAsnTag[ch] = true
570 }
571 for ch := 'a'; ch <= 'z'; ch++ {
572 inAsnTag[ch] = true
573 }
574 for ch := '0'; ch <= '9'; ch++ {
575 inAsnTag[ch] = true
576 }
577 inAsnTag['-'] = true
578
579 // ASN.1 string starts and ends with double quote
580 for i := range inAsnString {
581 inAsnString[i] = false
582 }
583 for ch := ' '; ch <= '~'; ch++ {
584 inAsnString[ch] = true
585 }
586 inAsnString['"'] = false
587 // "
588
589 // ASN.1 bit string flanked by apostrophe, followed by H or B
590 for i := range inAsnBits {
591 inAsnBits[i] = false
592 }
593 for ch := ' '; ch <= '~'; ch++ {
594 inAsnBits[ch] = true
595 }
596 inAsnBits['\''] = false
597
598 // initialize reading and cleaning options with default values
599 SetOptions(false, false, false, false, false, false, false, false, false, true)
600
601 // initialize performance tuning variables with default values
602 SetTunings(0, 0, 0, 0, 0, 0, 0, false)
603 }