19073: Fix dup tag detection.
[lightning.git] / anno2vcf.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "bufio"
9         "bytes"
10         "flag"
11         "fmt"
12         "io"
13         "net/http"
14         _ "net/http/pprof"
15         "os"
16         "runtime"
17         "sort"
18         "strconv"
19         "strings"
20         "sync"
21
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         log "github.com/sirupsen/logrus"
24 )
25
26 type anno2vcf struct {
27 }
28
29 func (cmd *anno2vcf) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
30         var err error
31         defer func() {
32                 if err != nil {
33                         fmt.Fprintf(stderr, "%s\n", err)
34                 }
35         }()
36         flags := flag.NewFlagSet("", flag.ContinueOnError)
37         flags.SetOutput(stderr)
38         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
39         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
40         projectUUID := flags.String("project", "", "project `UUID` for output data")
41         priority := flags.Int("priority", 500, "container request priority")
42         inputDir := flags.String("input-dir", "./in", "input `directory`")
43         outputDir := flags.String("output-dir", "./out", "output `directory`")
44         err = flags.Parse(args)
45         if err == flag.ErrHelp {
46                 err = nil
47                 return 0
48         } else if err != nil {
49                 return 2
50         }
51
52         if *pprof != "" {
53                 go func() {
54                         log.Println(http.ListenAndServe(*pprof, nil))
55                 }()
56         }
57
58         if !*runlocal {
59                 runner := arvadosContainerRunner{
60                         Name:        "lightning anno2vcf",
61                         Client:      arvados.NewClientFromEnv(),
62                         ProjectUUID: *projectUUID,
63                         RAM:         500000000000,
64                         VCPUs:       64,
65                         Priority:    *priority,
66                         KeepCache:   2,
67                         APIAccess:   true,
68                 }
69                 err = runner.TranslatePaths(inputDir)
70                 if err != nil {
71                         return 1
72                 }
73                 runner.Args = []string{"anno2vcf", "-local=true",
74                         "-pprof", ":6060",
75                         "-input-dir", *inputDir,
76                         "-output-dir", "/mnt/output",
77                 }
78                 var output string
79                 output, err = runner.Run()
80                 if err != nil {
81                         return 1
82                 }
83                 fmt.Fprintln(stdout, output)
84                 return 0
85         }
86
87         d, err := open(*inputDir)
88         if err != nil {
89                 log.Print(err)
90                 return 1
91         }
92         defer d.Close()
93         fis, err := d.Readdir(-1)
94         if err != nil {
95                 log.Print(err)
96                 return 1
97         }
98         d.Close()
99         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
100
101         type call struct {
102                 tile      int
103                 variant   int
104                 position  int
105                 deletion  []byte
106                 insertion []byte
107                 hgvsID    []byte
108         }
109         allcalls := map[string][]*call{}
110         var mtx sync.Mutex
111         thr := throttle{Max: runtime.GOMAXPROCS(0)}
112         log.Print("reading input files")
113         for _, fi := range fis {
114                 if !strings.HasSuffix(fi.Name(), "annotations.csv") {
115                         continue
116                 }
117                 filename := *inputDir + "/" + fi.Name()
118                 thr.Go(func() error {
119                         log.Printf("reading %s", filename)
120                         f, err := open(filename)
121                         if err != nil {
122                                 return err
123                         }
124                         defer f.Close()
125                         buf, err := io.ReadAll(f)
126                         if err != nil {
127                                 return fmt.Errorf("%s: %s", filename, err)
128                         }
129                         f.Close()
130                         lines := bytes.Split(buf, []byte{'\n'})
131                         calls := map[string][]*call{}
132                         for lineIdx, line := range lines {
133                                 if len(line) == 0 {
134                                         continue
135                                 }
136                                 if lineIdx&0xff == 0 && thr.Err() != nil {
137                                         return nil
138                                 }
139                                 fields := bytes.Split(line, []byte{','})
140                                 if len(fields) < 8 {
141                                         return fmt.Errorf("%s line %d: wrong number of fields (%d < %d): %q", fi.Name(), lineIdx+1, len(fields), 8, line)
142                                 }
143                                 hgvsID := fields[3]
144                                 if len(hgvsID) < 2 {
145                                         // "=" reference or ""
146                                         // non-diffable tile variant
147                                         continue
148                                 }
149                                 tile, _ := strconv.ParseInt(string(fields[0]), 10, 64)
150                                 variant, _ := strconv.ParseInt(string(fields[2]), 10, 64)
151                                 position, _ := strconv.ParseInt(string(fields[5]), 10, 64)
152                                 seq := string(fields[4])
153                                 if calls[seq] == nil {
154                                         calls[seq] = make([]*call, 0, len(lines)/50)
155                                 }
156                                 del := fields[6]
157                                 ins := fields[7]
158                                 if (len(del) == 0 || len(ins) == 0) && len(fields) >= 9 {
159                                         // "123,,AA,T" means 123insAA
160                                         // preceded by T. We record it
161                                         // here as "122 T TAA" to
162                                         // avoid writing an empty
163                                         // "ref" field in our
164                                         // VCF. Similarly, we record
165                                         // deletions as "122 TAA T"
166                                         // rather than "123 AA .".
167                                         del = append(append(make([]byte, 0, len(fields[8])+len(del)), fields[8]...), del...)
168                                         ins = append(append(make([]byte, 0, len(fields[8])+len(ins)), fields[8]...), ins...)
169                                         position -= int64(len(fields[8]))
170                                 } else {
171                                         del = append([]byte(nil), del...)
172                                         ins = append([]byte(nil), ins...)
173                                 }
174                                 calls[seq] = append(calls[seq], &call{
175                                         tile:      int(tile),
176                                         variant:   int(variant),
177                                         position:  int(position),
178                                         deletion:  del,
179                                         insertion: ins,
180                                         hgvsID:    hgvsID,
181                                 })
182                         }
183                         mtx.Lock()
184                         for seq, seqcalls := range calls {
185                                 allcalls[seq] = append(allcalls[seq], seqcalls...)
186                         }
187                         mtx.Unlock()
188                         return nil
189                 })
190         }
191         err = thr.Wait()
192         if err != nil {
193                 return 1
194         }
195         thr = throttle{Max: len(allcalls)}
196         for seq, seqcalls := range allcalls {
197                 seq, seqcalls := seq, seqcalls
198                 thr.Go(func() error {
199                         log.Printf("%s: sorting", seq)
200                         sort.Slice(seqcalls, func(i, j int) bool {
201                                 ii, jj := seqcalls[i], seqcalls[j]
202                                 if cmp := ii.position - jj.position; cmp != 0 {
203                                         return cmp < 0
204                                 }
205                                 if cmp := len(ii.deletion) - len(jj.deletion); cmp != 0 {
206                                         return cmp < 0
207                                 }
208                                 if cmp := bytes.Compare(ii.insertion, jj.insertion); cmp != 0 {
209                                         return cmp < 0
210                                 }
211                                 if cmp := ii.tile - jj.tile; cmp != 0 {
212                                         return cmp < 0
213                                 }
214                                 return ii.variant < jj.variant
215                         })
216
217                         vcfFilename := fmt.Sprintf("%s/annotations.%s.vcf", *outputDir, seq)
218                         log.Printf("%s: writing %s", seq, vcfFilename)
219
220                         f, err := os.Create(vcfFilename)
221                         if err != nil {
222                                 return err
223                         }
224                         defer f.Close()
225                         bufw := bufio.NewWriterSize(f, 1<<20)
226                         _, err = fmt.Fprintf(bufw, `##fileformat=VCFv4.0
227 ##INFO=<ID=TV,Number=.,Type=String,Description="tile-variant">
228 #CHROM  POS     ID      REF     ALT     QUAL    FILTER  INFO
229 `)
230                         if err != nil {
231                                 return err
232                         }
233                         placeholder := []byte{'.'}
234                         for i := 0; i < len(seqcalls); {
235                                 call := seqcalls[i]
236                                 i++
237                                 info := fmt.Sprintf("TV=,%d-%d,", call.tile, call.variant)
238                                 for i < len(seqcalls) &&
239                                         call.position == seqcalls[i].position &&
240                                         len(call.deletion) == len(seqcalls[i].deletion) &&
241                                         bytes.Equal(call.insertion, seqcalls[i].insertion) {
242                                         call = seqcalls[i]
243                                         i++
244                                         info += fmt.Sprintf("%d-%d,", call.tile, call.variant)
245                                 }
246                                 deletion := call.deletion
247                                 if len(deletion) == 0 {
248                                         deletion = placeholder
249                                 }
250                                 insertion := call.insertion
251                                 if len(insertion) == 0 {
252                                         insertion = placeholder
253                                 }
254                                 _, err = fmt.Fprintf(bufw, "%s\t%d\t%s\t%s\t%s\t.\t.\t%s\n", seq, call.position, call.hgvsID, deletion, insertion, info)
255                                 if err != nil {
256                                         return err
257                                 }
258                         }
259                         err = bufw.Flush()
260                         if err != nil {
261                                 return err
262                         }
263                         err = f.Close()
264                         if err != nil {
265                                 return err
266                         }
267                         log.Printf("%s: done", seq)
268                         return nil
269                 })
270         }
271         err = thr.Wait()
272         if err != nil {
273                 return 1
274         }
275         return 0
276 }