Debian Codegraph @

eutils/align.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: align.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "golang.org/x/text/language"
36 "golang.org/x/text/message"
37 "io"
38 "os"
39 "strconv"
40 "strings"
41 "unicode/utf8"
42 )
43
44 // Inspired by Steve Kinzler's align script - see http://kinzler.com/me/align/
45
46 // AlignColumns aligns a tab-delimited table to the computed widths of individual columns.
47 func AlignColumns(inp io.Reader, margin, padding, minimum int, align string) <-chan string {
48
49 /*
50 column alignment letters, with last repeated as needed:
51
52 l left
53 c center
54 r right
55 n numeric aligned on decimal point
56 N numeric with decimal parts zero-padded
57 z zero-pad leading integers
58 m commas to group by 3 digits
59 M commas plus zero-pad decimals
60 w just print column widths
61 */
62
63 if inp == nil {
64 return nil
65 }
66
67 out := make(chan string, chanDepth)
68 if out == nil {
69 DisplayError("Unable to create alignment channel")
70 os.Exit(1)
71 }
72
73 // used for adding commas every 3 digits
74 p := message.NewPrinter(language.English)
75
76 spaces := " "
77
78 // spaces at left margin
79 mrg := ""
80 // spaces between columns
81 pad := " "
82
83 lettrs := make(map[int]rune)
84 // last alignment code persists for additional data columns
85 lst := 'l'
86
87 if margin > 0 && margin < 30 {
88 mrg = spaces[0:margin]
89 }
90
91 showAll := true
92
93 if padding > 0 && padding < 30 {
94 pad = spaces[0:padding]
95 } else if padding == -1 {
96 // continue using tab character between columns
97 pad = "\t"
98 }
99
100 align = strings.TrimSpace(align)
101
102 if strings.HasPrefix(align, "w") {
103 // print column widths
104 showAll = false
105 align = ""
106 }
107
108 for i, ch := range align {
109 lettrs[i] = ch
110 lst = ch
111 }
112
113 alignTable := func(inp io.Reader, out chan<- string) {
114
115 // close channel when all chunks have been sent
116 defer close(out)
117
118 var arry []string
119
120 width := make(map[int]int)
121 whole := make(map[int]int)
122 fract := make(map[int]int)
123
124 scanr := bufio.NewScanner(inp)
125
126 row := 0
127 numCols := 0
128
129 // allows leading plus or minus, digits interspersed with optional commas, decimal point, and digits
130 isNumeric := func(str string) bool {
131
132 hasNum := false
133 hasPeriod := false
134
135 for i, ch := range str {
136 switch ch {
137 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
138 hasNum = true
139 case '+', '-':
140 if i > 0 {
141 return false
142 }
143 case '.':
144 hasPeriod = true
145 case ',':
146 if hasPeriod {
147 return false
148 }
149 default:
150 return false
151 }
152 }
153
154 return hasNum
155 }
156
157 processLine := func(line string) string {
158
159 var flds []string
160
161 cols := strings.Split(line, "\t")
162 if numCols == 0 {
163 numCols = len(cols)
164 } else if numCols != len(cols) {
165 DisplayError("Mismatched number of columns in row %d: actual %d, expected %d", row, len(cols), numCols)
166 // os.Exit(1)
167 }
168
169 for i, str := range cols {
170
171 str = CompressRunsOfSpaces(str)
172 str = strings.TrimSpace(str)
173
174 code, ok := lettrs[i]
175 if !ok {
176 code = lst
177 }
178
179 if code == 'm' || code == 'M' {
180 // save modified column data string if inserting commas
181 terminalDot := false
182 if strings.HasSuffix(str, ".") {
183 terminalDot = true
184 }
185
186 wh, fr := SplitInTwoLeft(str, ".")
187
188 val, err := strconv.Atoi(wh)
189 if err == nil {
190 wh = p.Sprintf("%d", val)
191 if fr != "" {
192 str = wh + "." + fr
193 } else if terminalDot {
194 str = wh + "."
195 } else {
196 str = wh
197 }
198 }
199 }
200
201 flds = append(flds, str)
202
203 // determine maximum length of current column
204 ln := utf8.RuneCountInString(str)
205 if ln > width[i] {
206 width[i] = ln
207 }
208
209 switch code {
210 case 'n', 'N', 'z', 'Z', 'm', 'M':
211 if isNumeric(str) {
212 // determine maximum length of integer and decimal parts
213 wh, fr := SplitInTwoLeft(str, ".")
214 if fr != "" {
215 fr = "." + fr
216 }
217
218 lf := utf8.RuneCountInString(wh)
219 if lf > whole[i] {
220 whole[i] = lf
221 }
222 rt := utf8.RuneCountInString(fr)
223 if rt > fract[i] {
224 fract[i] = rt
225 }
226 ln = whole[i] + fract[i]
227 if ln > width[i] {
228 width[i] = ln
229 }
230 }
231 }
232 }
233
234 return strings.Join(flds, "\t")
235 }
236
237 // clean up spaces, calculate column widths
238 for scanr.Scan() {
239
240 row++
241 line := scanr.Text()
242 if line == "" {
243 continue
244 }
245
246 line = processLine(line)
247 if showAll {
248 arry = append(arry, line)
249 }
250 }
251
252 for i := range numCols {
253
254 code, ok := lettrs[i]
255 if !ok {
256 code = lst
257 }
258
259 switch code {
260 case 'n', 'N', 'z', 'Z', 'm', 'M':
261 // adjust maximum widths with aligned decimal points
262 ln := whole[i] + fract[i]
263 if ln > width[i] {
264 width[i] = ln
265 }
266 }
267
268 // apply minimum column width
269 if width[i] < minimum {
270 width[i] = minimum
271 }
272 }
273
274 if !showAll {
275
276 var cols []string
277
278 for i := range numCols {
279 wid := width[i]
280 val := strconv.Itoa(wid)
281 cols = append(cols, val)
282 }
283
284 txt := strings.Join(cols, "\t")
285 if txt != "" {
286 txt += "\n"
287 }
288
289 out <- txt
290
291 return
292 }
293
294 var buffer strings.Builder
295
296 // process saved lines
297 for _, line := range arry {
298
299 buffer.Reset()
300
301 cols := strings.Split(line, "\t")
302
303 btwn := mrg
304
305 for i, str := range cols {
306
307 buffer.WriteString(btwn)
308
309 code, ok := lettrs[i]
310 if !ok {
311 code = lst
312 }
313
314 // accommodate multi-byte characters like Greek letter beta
315 ln := utf8.RuneCountInString(str)
316
317 mx := width[i]
318 diff := mx - ln
319
320 lft := 0
321 rgt := 0
322 lftPad := " "
323 rgtPad := " "
324
325 // calculate left and right padding by column alignment
326 if diff > 0 {
327 switch code {
328 case 'l':
329 rgt = diff
330 case 'c':
331 lft = diff / 2
332 rgt = diff - lft
333 case 'r':
334 lft = diff
335 case 'n', 'N', 'z', 'Z', 'm', 'M':
336 lft = diff
337 if isNumeric(str) {
338 switch code {
339 case 'N':
340 rgtPad = "0"
341 case 'z':
342 lftPad = "0"
343 case 'Z':
344 lftPad = "0"
345 rgtPad = "0"
346 case 'M':
347 rgtPad = "0"
348 }
349 sn := whole[i]
350 rc := fract[i]
351 wh, fr := SplitInTwoLeft(str, ".")
352 if fract[i] > 0 {
353 if fr == "" {
354 fr = "."
355 } else {
356 fr = "." + fr
357 }
358 lf := utf8.RuneCountInString(wh)
359 lft = sn - lf
360 rt := utf8.RuneCountInString(fr)
361 rgt = rc - rt
362 str = wh + fr
363 }
364 }
365 default:
366 rgt = diff
367 }
368 }
369
370 for lft > 0 {
371 lft--
372 buffer.WriteString(lftPad)
373 }
374
375 buffer.WriteString(str)
376 btwn = pad
377
378 for rgt > 0 {
379 rgt--
380 buffer.WriteString(rgtPad)
381 }
382 }
383
384 txt := buffer.String()
385 txt = strings.TrimRight(txt, " ") + "\n"
386
387 if txt != "" {
388 // send adjusted line down output channel
389 out <- txt
390 }
391 }
392 }
393
394 // launch single alignment goroutine
395 go alignTable(inp, out)
396
397 return out
398 }