Debian Codegraph @

eutils/table.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: table.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "html"
36 "io"
37 "os"
38 "runtime"
39 "strconv"
40 "strings"
41 )
42
43 // TableConverter parses tab-delimited or comma-separated values files into XML object stream
44 func TableConverter(inp io.Reader, delim, set, rec string, skip int, header, lower, upper, indent, insdx bool, fields []string) <-chan string {
45
46 if inp == nil {
47 return nil
48 }
49
50 head := ""
51 tail := ""
52
53 hd := ""
54 tl := ""
55
56 if set != "" && set != "-" {
57 head = "<" + set + ">"
58 tail = "</" + set + ">"
59 }
60
61 if rec != "" && rec != "-" {
62 hd = "<" + rec + ">"
63 tl = "</" + rec + ">"
64 }
65
66 numFlds := len(fields)
67
68 if numFlds < 1 && !header {
69 DisplayError("Insufficient arguments for table converter")
70 os.Exit(1)
71 }
72
73 out := make(chan string, chanDepth)
74 if out == nil {
75 DisplayError("Unable to create table converter channel")
76 os.Exit(1)
77 }
78
79 convertTable := func(inp io.Reader, out chan<- string) {
80
81 // close channel when all records have been sent
82 defer close(out)
83
84 okay := false
85 row := 0
86
87 var buffer strings.Builder
88
89 scanr := bufio.NewScanner(inp)
90
91 // override scanner limit to allow reading of titin protein and cDNA sequences:
92 const bufferSize = 1024 * 1024
93 buf := make([]byte, bufferSize)
94 scanr.Buffer(buf, bufferSize)
95
96 if head != "" {
97 buffer.WriteString(head)
98 buffer.WriteString("\n")
99 }
100
101 if header {
102
103 // uses fields from first row for column names
104 for scanr.Scan() {
105
106 line := scanr.Text()
107
108 row++
109
110 if skip > 0 {
111 skip--
112 continue
113 }
114
115 cols := strings.Split(line, delim)
116
117 for _, str := range cols {
118 fields = append(fields, str)
119 numFlds++
120 }
121 break
122 }
123
124 if numFlds < 1 {
125 DisplayError("Line with column names not found")
126 os.Exit(1)
127 }
128 }
129
130 for scanr.Scan() {
131
132 line := scanr.Text()
133
134 row++
135
136 if skip > 0 {
137 skip--
138 continue
139 }
140
141 cols := strings.Split(line, delim)
142
143 if len(cols) != numFlds {
144 DisplayError("Mismatched columns in row %d - '%s'", row, line)
145 continue
146 }
147
148 if hd != "" {
149 if indent {
150 buffer.WriteString(" ")
151 }
152 buffer.WriteString(hd)
153 buffer.WriteString("\n")
154 }
155
156 for i, fld := range fields {
157
158 val := cols[i]
159 if lower {
160 val = strings.ToLower(val)
161 }
162 if upper {
163 val = strings.ToUpper(val)
164 }
165 if fld[0] == '*' {
166 fld = fld[1:]
167 } else {
168 val = html.EscapeString(val)
169 }
170 val = strings.TrimSpace(val)
171
172 if insdx && val == "-" {
173 continue
174 }
175
176 if indent {
177 buffer.WriteString(" ")
178 }
179 buffer.WriteString("<")
180 buffer.WriteString(fld)
181 buffer.WriteString(">")
182 buffer.WriteString(val)
183 buffer.WriteString("</")
184 buffer.WriteString(fld)
185 buffer.WriteString(">")
186 buffer.WriteString("\n")
187 }
188
189 if tl != "" {
190 if indent {
191 buffer.WriteString(" ")
192 }
193 buffer.WriteString(tl)
194 buffer.WriteString("\n")
195 }
196
197 okay = true
198 }
199
200 if tail != "" {
201 buffer.WriteString(tail)
202 buffer.WriteString("\n")
203 }
204
205 if okay {
206 txt := buffer.String()
207 if txt != "" {
208 // send remaining result through output channel
209 out <- txt
210 }
211 }
212
213 buffer.Reset()
214
215 runtime.Gosched()
216 }
217
218 go convertTable(inp, out)
219
220 return out
221 }
222
223 // TableToMap reads a two-column tab-delimited file and populates the data into an existing map
224 func TableToMap(tf string, mp map[string]string) {
225
226 if mp == nil {
227 // allow program to continue
228 return
229 }
230
231 inFile, err := os.Open(tf)
232 if err != nil {
233 DisplayError("Unable to open table file %s - %s", tf, err.Error())
234 // warn, but allow program to continue
235 return
236 }
237
238 scanr := bufio.NewScanner(inFile)
239
240 // populate transformation map
241 for scanr.Scan() {
242
243 line := scanr.Text()
244 cols := strings.Split(line, "\t")
245 if len(cols) != 2 {
246 continue
247 }
248 frst := cols[0]
249 scnd := cols[1]
250
251 // set new value
252 mp[frst] = scnd
253 }
254
255 inFile.Close()
256 }
257
258 // TabletoXML converts tab-delimited or comma-separated values files to an XML string
259 func TabletoXML(tbl, delim, set, rec string, skip int, header, lower, upper, indent, insdx bool, fields []string) string {
260
261 return StringToXML(tbl, func(inp io.Reader) <-chan string {
262 return TableConverter(inp, delim, set, rec, skip, header, lower, upper, indent, insdx, fields)
263 })
264 }
265
266 // ParentsToLineage reads a table of identifiers and parents, and returns a table of identifiers and full lineages
267 func ParentsToLineage(inp io.Reader) <-chan string {
268
269 if inp == nil {
270 return nil
271 }
272
273 out := make(chan string, chanDepth)
274 if out == nil {
275 DisplayError("Unable to create parent to lineage converter channel")
276 os.Exit(1)
277 }
278
279 convertParentsToLineage := func(inp io.Reader, out chan<- string) {
280
281 // close channel when all records have been sent
282 defer close(out)
283
284 okay := false
285 row := 0
286 hasFourColumns := false
287
288 // maximum depth to prevent stack overflow if circular references are present
289 const maxDepth = 1000
290
291 identToParent := make(map[string]string)
292 identToLineage := make(map[string]string)
293 identToLabel := make(map[string]string)
294 identToSort := make(map[string]int)
295
296 // getLineage recursive definition
297 var getLineage func(id string, depth int) (string, bool)
298
299 // returns lineage string, plus boolean ok flag
300 getLineage = func(id string, depth int) (string, bool) {
301
302 if id == "" {
303 return "", true
304 }
305 // fail if depth exceeds maximum, indicating likely circular reference
306 if depth > maxDepth {
307 return "", false
308 }
309
310 ln := identToLineage[id]
311 if ln != "" {
312 // return previously calculated lineage
313 return ln, true
314 }
315
316 pt := identToParent[id]
317
318 // check for root note
319 if pt == "" || pt == "-" {
320 // assign lineage to root node
321 identToLineage[id] = id
322 return id, true
323 }
324
325 // recursively get parent lineage
326 lin, ok := getLineage(pt, depth+1)
327 // immediately unwind stack upon failure
328 if !ok {
329 return "", false
330 }
331
332 // parent lineage should now be available, concatenate with current identifier
333 lin += ";" + id
334
335 // store newly-calculated lineage, to be used subsequently by its children
336 identToLineage[id] = lin
337
338 if hasFourColumns && identToSort[id] < identToSort[pt] {
339 DisplayError("[%s] %s should not be a child of [%s] %s", identToLabel[id], id, identToLabel[pt], pt)
340 }
341
342 return lin, true
343 }
344
345 scanr := bufio.NewScanner(inp)
346
347 // read identifier, its immediate parent, and optionally the feature type (e.g., gene) and the sort key (e.g., 1)
348 for scanr.Scan() {
349
350 line := scanr.Text()
351
352 row++
353
354 cols := strings.Split(line, "\t")
355 ncols := len(cols)
356
357 if ncols != 2 && ncols != 4 {
358 DisplayError("Row %d should not have %d columns", row, len(cols))
359 continue
360 }
361
362 id := cols[0]
363 prnt := cols[1]
364 lbl := ""
365 srt := ""
366 if ncols == 4 {
367 hasFourColumns = true
368 lbl = cols[2]
369 srt = cols[3]
370 }
371
372 vl, ok := identToParent[id]
373 if ok {
374 if vl != prnt {
375 DisplayWarning("Conflicting assignment in row %d - parent of '%s' went from '%s' to '%s'", row, id, vl, prnt)
376 }
377 continue
378 }
379
380 if prnt != "" {
381 identToParent[id] = prnt
382 }
383
384 if lbl != "" {
385 vl, ok = identToLabel[id]
386 if ok {
387 if vl != lbl {
388 DisplayWarning("Conflicting label in row %d - '%s' went from '%s' to '%s'", row, id, vl, lbl)
389 }
390 } else {
391 identToLabel[id] = lbl
392 }
393 }
394
395 if srt != "" {
396 val, err := strconv.Atoi(srt)
397 if err == nil {
398 nm, oky := identToSort[id]
399 if oky {
400 if nm != val {
401 DisplayWarning("Conflicting sort key in row %d - '%s' went from '%d' to '%d'", row, id, nm, val)
402 }
403 } else {
404 identToSort[id] = val
405 }
406 }
407 }
408 }
409
410 // compute full lineage for each identifier
411 for id := range identToParent {
412
413 ln := identToLineage[id]
414 if ln != "" {
415 continue
416 }
417
418 lin, ok := getLineage(id, 0)
419 if !ok {
420 DisplayError("Data that should be a tree structure appears to have an internal cycle")
421 // and prevent output through channel
422 okay = false
423 break
424 }
425 if lin == "" {
426 continue
427 }
428
429 okay = true
430 }
431
432 if okay {
433 for id := range identToParent {
434 ln := identToLineage[id]
435 txt := id + "\t" + ln
436 out <- txt
437 }
438 }
439
440 runtime.Gosched()
441 }
442
443 go convertParentsToLineage(inp, out)
444
445 return out
446 }