Debian Codegraph @

eutils/hgvs.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: hgvs.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "html"
35 "regexp"
36 "sort"
37 "strconv"
38 "strings"
39 )
40
41 var (
42 accnRegEx *regexp.Regexp
43 genRegEx *regexp.Regexp
44 protRegEx *regexp.Regexp
45 )
46
47 // integer table for HGVS class used to define sort order
48 const (
49 _ = iota
50 GENOMIC
51 CODING
52 NONCODING
53 MITOCONDRIAL
54 RNA
55 PROTEIN
56 )
57
58 var hgvsClass = map[int]string{
59 GENOMIC: "Genomic",
60 CODING: "Coding",
61 NONCODING: "Noncoding",
62 MITOCONDRIAL: "Mitochondrial",
63 RNA: "RNA",
64 PROTEIN: "Protein",
65 }
66
67 // integer table for HGVS type used to define sort order
68 const (
69 _ = iota
70 SUBS
71 MIS
72 TRM
73 EXT
74 SYN
75 DEL
76 INV
77 DUP
78 INS
79 CONV
80 INDEL
81 FS
82 TRANS
83 REP
84 MULT
85 )
86
87 var hgvsType = map[int]string{
88 SUBS: "Substitution",
89 MIS: "Missense",
90 TRM: "Termination",
91 EXT: "Extension",
92 SYN: "Synonymous",
93 DEL: "Deletion",
94 INV: "Inversion",
95 DUP: "Duplication",
96 INS: "Insertion",
97 CONV: "Conversion",
98 INDEL: "Indel",
99 FS: "Frameshift",
100 TRANS: "Translocation",
101 REP: "Repetitive",
102 MULT: "Multiple",
103 }
104
105 // SPDI accession subfields used for controlling sort order
106 type SPDI struct {
107 Class int
108 Type int
109 Accession string
110 Prefix string
111 Digits string
112 Number int
113 Version int
114 Position int
115 Deleted string
116 Inserted string
117 Hgvs string
118 }
119
120 var naConvert = map[string]string{
121 "-": "-",
122 "a": "A",
123 "c": "C",
124 "g": "G",
125 "r": "R",
126 "t": "T",
127 "u": "T",
128 "y": "Y",
129 }
130
131 var aaConvert = map[string]string{
132 "-": "-",
133 "*": "*",
134 "a": "A",
135 "b": "B",
136 "c": "C",
137 "d": "D",
138 "e": "E",
139 "f": "F",
140 "g": "G",
141 "h": "H",
142 "i": "I",
143 "j": "J",
144 "k": "K",
145 "l": "L",
146 "m": "M",
147 "n": "N",
148 "o": "O",
149 "p": "P",
150 "q": "Q",
151 "r": "R",
152 "s": "S",
153 "t": "T",
154 "u": "U",
155 "v": "V",
156 "w": "W",
157 "x": "X",
158 "y": "Y",
159 "z": "Z",
160 "ala": "A",
161 "arg": "R",
162 "asn": "N",
163 "asp": "D",
164 "asx": "B",
165 "cys": "C",
166 "gap": "-",
167 "gln": "Q",
168 "glu": "E",
169 "glx": "Z",
170 "gly": "G",
171 "his": "H",
172 "ile": "I",
173 "leu": "L",
174 "lys": "K",
175 "met": "M",
176 "phe": "F",
177 "pro": "P",
178 "pyl": "O",
179 "sec": "U",
180 "ser": "S",
181 "stp": "*",
182 "ter": "*",
183 "thr": "T",
184 "trp": "W",
185 "tyr": "Y",
186 "val": "V",
187 "xle": "J",
188 "xxx": "X",
189 }
190
191 // ParseHGVS parses sequence variant format into XML
192 func ParseHGVS(str string) string {
193
194 // initialize variation description regular expressions
195 if accnRegEx == nil {
196 accnRegEx = regexp.MustCompile("\\*|\\d+|\\.|\\D+")
197 }
198 if genRegEx == nil {
199 genRegEx = regexp.MustCompile("\\d+|\\D|>|\\D")
200 }
201 if protRegEx == nil {
202 protRegEx = regexp.MustCompile("\\*|\\d+|\\D+")
203 }
204
205 // track highest version per accession
206 highest := make(map[string]int)
207
208 hasNM := false
209 hasNP := false
210
211 // parse substitution
212 parseSubs := func(cls, acc, vrn string) *SPDI {
213
214 pos := ""
215 ins := ""
216 del := ""
217 class := 0
218 htype := 0
219 ok := false
220
221 // parse variation string
222 switch cls {
223 case "g":
224 class = GENOMIC
225
226 arry := genRegEx.FindAllString(vrn, -1)
227 if len(arry) != 4 {
228 // DisplayError("Unrecognized variant '%s', array '%v'", vrn, arry)
229 return nil
230 }
231
232 pos = arry[0]
233
234 lf := strings.ToLower(arry[1])
235 rt := strings.ToLower(arry[3])
236
237 del, ok = naConvert[lf]
238 if !ok {
239 DisplayError("Unrecognized nucleotide '%s'", lf)
240 return nil
241 }
242 ins, ok = naConvert[rt]
243 if !ok {
244 DisplayError("Unrecognized nucleotide '%s'", rt)
245 return nil
246 }
247
248 htype = SUBS
249 case "c":
250 class = CODING
251
252 arry := genRegEx.FindAllString(vrn, -1)
253 if len(arry) != 4 {
254 // DisplayError("Unrecognized variant '%s', array '%v'", vrn, arry)
255 return nil
256 }
257
258 // pos starts at the first nucleotide of the translation initiation codon
259 pos = arry[0]
260
261 lf := strings.ToLower(arry[1])
262 rt := strings.ToLower(arry[3])
263
264 del, ok = naConvert[lf]
265 if !ok {
266 DisplayError("Unrecognized nucleotide '%s'", lf)
267 return nil
268 }
269 ins, ok = naConvert[rt]
270 if !ok {
271 DisplayError("Unrecognized nucleotide '%s'", rt)
272 return nil
273 }
274
275 htype = SUBS
276 case "p":
277 class = PROTEIN
278
279 arry := protRegEx.FindAllString(vrn, -1)
280 if len(arry) != 3 {
281 // DisplayError("Unrecognized variant '%s', array '%v'", vrn, arry)
282 return nil
283 }
284
285 pos = arry[1]
286
287 lf := strings.ToLower(arry[0])
288 rt := strings.ToLower(arry[2])
289
290 del, ok = aaConvert[lf]
291 if !ok {
292 DisplayError("Unrecognized amino acid '%s'", lf)
293 return nil
294 }
295 ins, ok = aaConvert[rt]
296 if !ok {
297 DisplayError("Unrecognized amino acid '%s'", rt)
298 return nil
299 }
300
301 htype = MIS
302 if ins == "*" {
303 htype = TRM
304 } else if del == "*" {
305 htype = EXT
306 } else if del == ins {
307 htype = SYN
308 }
309 default:
310 // DisplayWarning("Parsing of HGVS class '%s' not yet implemented", cls)
311 return nil
312 }
313
314 // position should be unsigned integer
315 if !IsAllDigits(pos) {
316 DisplayError("Non-integer position '%s'", pos)
317 return nil
318 }
319
320 num, err := strconv.Atoi(pos)
321 if err != nil {
322 DisplayError("Integer conversion error '%s'", err)
323 return nil
324 }
325 // adjust position to 0-based
326 num--
327
328 spdi := &SPDI{Class: class, Type: htype, Accession: acc, Position: num, Deleted: del, Inserted: ins}
329
330 return spdi
331 }
332
333 // reality checks on variant type, will eventually call the different type-specific parsers
334 parseOneType := func(cls, acc, vrn string) *SPDI {
335
336 if strings.Index(vrn, "delins") >= 0 || strings.Index(vrn, "indel") >= 0 {
337 // DisplayWarning("deletion-insertion not yet implemented")
338 return nil
339 }
340 if strings.Index(vrn, "del") >= 0 {
341 // DisplayWarning("deletion not yet implemented")
342 return nil
343 }
344 if strings.Index(vrn, "inv") >= 0 {
345 // DisplayWarning("inversion not yet implemented")
346 return nil
347 }
348 if strings.Index(vrn, "dup") >= 0 {
349 // DisplayWarning("duplication not yet implemented")
350 return nil
351 }
352 if strings.Index(vrn, "con") >= 0 {
353 // DisplayWarning("conversion not yet implemented")
354 return nil
355 }
356 if strings.Index(vrn, "ins") >= 0 {
357 // DisplayWarning("insertion not yet implemented")
358 return nil
359 }
360 if strings.Index(vrn, "fs") >= 0 {
361 // DisplayWarning("frameshift not yet implemented")
362 return nil
363 }
364 if strings.Index(vrn, "*") >= 0 {
365 // DisplayWarning("UTR variant not yet implemented")
366 return nil
367 }
368 if strings.Index(vrn, "?") >= 0 {
369 // DisplayWarning("predictions not yet implemented")
370 return nil
371 }
372 if strings.Index(vrn, ";") >= 0 {
373 // DisplayWarning("variation pairs not yet implemented")
374 return nil
375 }
376 if strings.Index(vrn, "/") >= 0 {
377 // DisplayWarning("variation pairs not yet implemented")
378 return nil
379 }
380 if strings.Index(vrn, "(") >= 0 || strings.Index(vrn, ")") >= 0 {
381 // DisplayWarning("intron variation not yet implemented")
382 return nil
383 }
384 if strings.Index(vrn, "[") >= 0 || strings.Index(vrn, "]") >= 0 || strings.Index(vrn, ";") >= 0 {
385 // DisplayWarning("repetitive stretch not yet implemented")
386 return nil
387 }
388
389 // otherwise use substitution
390 return parseSubs(cls, acc, vrn)
391 }
392
393 var buffer strings.Builder
394
395 var spdis []*SPDI
396
397 ok := false
398
399 // trim prefix and suffix
400 str = strings.TrimPrefix(str, "HGVS=")
401 idx := strings.Index(str, "|")
402 if idx >= 0 {
403 str = str[:idx]
404 }
405
406 // separate at commas
407 hgvs := strings.Split(str, ",")
408
409 for _, hgv := range hgvs {
410
411 // skip empty item
412 if hgv == "" {
413 continue
414 }
415
416 // extract accession
417 acc, rgt := SplitInTwoLeft(hgv, ":")
418 if acc == "" || rgt == "" {
419 // DisplayError("Unable to parse HGVS '%s'", hgv)
420 continue
421 }
422 // split into type and variation
423 cls, vrn := SplitInTwoLeft(rgt, ".")
424 if cls == "" || vrn == "" {
425 // DisplayError("Unable to parse HGVS '%s'", rgt)
426 continue
427 }
428
429 // normalize variant string
430 vrn = strings.TrimSpace(vrn)
431 vrn = strings.ToLower(vrn)
432
433 // predicted protein change enclosed in parentheses
434 vrn = strings.TrimPrefix(vrn, "(")
435 vrn = strings.TrimSuffix(vrn, ")")
436
437 spdi := parseOneType(cls, acc, vrn)
438 if spdi == nil {
439 continue
440 }
441
442 // get accession fields for sorting
443 pfx := ""
444 num := ""
445 ver := "0"
446
447 // use regular expression to handle XX_ and XX_ABCD accessions
448 arry := accnRegEx.FindAllString(acc, -1)
449 if len(arry) == 2 {
450 pfx = strings.ToUpper(arry[0])
451 num = strings.ToLower(arry[1])
452 } else if len(arry) == 4 {
453 pfx = strings.ToUpper(arry[0])
454 num = strings.ToLower(arry[1])
455 ver = strings.ToLower(arry[3])
456 if arry[2] != "." {
457 DisplayError("Unable to parse version '%s', arry '%v'", acc, arry)
458 continue
459 }
460 } else {
461 DisplayError("Unable to parse accession '%s', arry '%v'", acc, arry)
462 continue
463 }
464
465 if pfx == "" || num == "" {
466 DisplayError("Unable to parse accession '%s'", acc)
467 continue
468 }
469
470 // RefSeq accession body should be unsigned integer
471 if !IsAllDigits(num) {
472 DisplayError("Non-integer accession body '%s'", num)
473 continue
474 }
475
476 val, err := strconv.Atoi(num)
477 if err != nil {
478 DisplayError("Integer conversion error '%s'", err)
479 continue
480 }
481
482 vsn, err := strconv.Atoi(ver)
483 if err != nil {
484 DisplayError("Version error '%s'", err)
485 continue
486 }
487
488 spdi.Prefix = pfx
489 spdi.Digits = num
490 spdi.Number = val
491 spdi.Version = vsn
492 spdi.Hgvs = html.EscapeString(hgv)
493
494 // record highest version for each accession
495 unver := pfx + num
496 vr, found := highest[unver]
497 if !found {
498 highest[unver] = vsn
499 } else if vr > vsn {
500 highest[unver] = vr
501 }
502
503 if strings.HasPrefix(pfx, "NM_") {
504 hasNM = true
505 }
506 if strings.HasPrefix(pfx, "NP_") {
507 hasNP = true
508 }
509
510 spdis = append(spdis, spdi)
511 ok = true
512 }
513
514 if !ok {
515 return ""
516 }
517
518 // SPDI is not a type in the cmp.Ordered interface, so slices.SortFunc cannot be used here
519 sort.Slice(spdis, func(i, j int) bool {
520 a := spdis[i]
521 b := spdis[j]
522 if a.Class != b.Class {
523 return a.Class < b.Class
524 }
525 if a.Type != b.Type {
526 return a.Type < b.Type
527 }
528 if a.Prefix != b.Prefix {
529 return a.Prefix < b.Prefix
530 }
531 // numeric comparison of accession digits ignores leading zeros
532 if a.Number != b.Number {
533 return a.Number < b.Number
534 }
535 // most recent version goes first
536 if a.Version != b.Version {
537 return a.Version > b.Version
538 }
539 if a.Position != b.Position {
540 return a.Position < b.Position
541 }
542 if a.Deleted != b.Deleted {
543 return a.Deleted < b.Deleted
544 }
545 if a.Inserted != b.Inserted {
546 return a.Inserted < b.Inserted
547 }
548 return false
549 })
550
551 for _, itm := range spdis {
552
553 // skip earlier accession versions
554 unver := itm.Prefix + itm.Digits
555 vr, found := highest[unver]
556 if found && vr > itm.Version {
557 continue
558 }
559
560 // skip XM_ and XP_ if NM_ or NP_, respectively, are already present
561 if hasNM && strings.HasPrefix(itm.Accession, "XM_") {
562 continue
563 }
564 if hasNP && strings.HasPrefix(itm.Accession, "XP_") {
565 continue
566 }
567
568 clss := hgvsClass[itm.Class]
569 htyp := hgvsType[itm.Type]
570
571 pos := strconv.Itoa(itm.Position)
572 lbl := "Position"
573 if itm.Class == CODING {
574 lbl = "Offset"
575 }
576 buffer.WriteString("<Variant>" +
577 "<Class>" + clss + "</Class>" +
578 "<Type>" + htyp + "</Type>" +
579 "<Accession>" + itm.Accession + "</Accession>" +
580 "<" + lbl + ">" + pos + "</" + lbl + ">" +
581 "<Deleted>" + itm.Deleted + "</Deleted>" +
582 "<Inserted>" + itm.Inserted + "</Inserted>" +
583 "<Hgvs>" + itm.Hgvs + "</Hgvs>" +
584 "</Variant>\n")
585 }
586
587 return buffer.String()
588 }