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