47af7e5caf55ea81d566a6dd7a15e4b979b2899b
[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                                 calls[seq] = append(calls[seq], &call{
145                                         tile:      int(tile),
146                                         variant:   int(variant),
147                                         position:  int(position),
148                                         deletion:  append([]byte(nil), fields[6]...),
149                                         insertion: append([]byte(nil), fields[7]...),
150                                 })
151                         }
152                         mtx.Lock()
153                         for seq, seqcalls := range calls {
154                                 allcalls[seq] = append(allcalls[seq], seqcalls...)
155                         }
156                         mtx.Unlock()
157                         return nil
158                 })
159         }
160         err = thr.Wait()
161         if err != nil {
162                 return 1
163         }
164         thr = throttle{Max: len(allcalls)}
165         for seq, seqcalls := range allcalls {
166                 seq, seqcalls := seq, seqcalls
167                 thr.Go(func() error {
168                         log.Printf("%s: sorting", seq)
169                         sort.Slice(seqcalls, func(i, j int) bool {
170                                 ii, jj := seqcalls[i], seqcalls[j]
171                                 if cmp := ii.position - jj.position; cmp != 0 {
172                                         return cmp < 0
173                                 }
174                                 if cmp := len(ii.deletion) - len(jj.deletion); cmp != 0 {
175                                         return cmp < 0
176                                 }
177                                 if cmp := bytes.Compare(ii.insertion, jj.insertion); cmp != 0 {
178                                         return cmp < 0
179                                 }
180                                 if cmp := ii.tile - jj.tile; cmp != 0 {
181                                         return cmp < 0
182                                 }
183                                 return ii.variant < jj.variant
184                         })
185
186                         vcfFilename := fmt.Sprintf("%s/annotations.%s.vcf", *outputDir, seq)
187                         log.Printf("%s: writing %s", seq, vcfFilename)
188
189                         f, err := os.Create(vcfFilename)
190                         if err != nil {
191                                 return err
192                         }
193                         defer f.Close()
194                         bufw := bufio.NewWriterSize(f, 1<<20)
195                         _, err = fmt.Fprintf(bufw, `##fileformat=VCFv4.0
196 ##INFO=<ID=TV,Number=.,Type=String,Description="tile-variant">
197 #CHROM  POS     ID      REF     ALT     QUAL    FILTER  INFO
198 `)
199                         if err != nil {
200                                 return err
201                         }
202                         placeholder := []byte{'.'}
203                         for i := 0; i < len(seqcalls); {
204                                 call := seqcalls[i]
205                                 i++
206                                 info := fmt.Sprintf("TV=,%d-%d,", call.tile, call.variant)
207                                 for i < len(seqcalls) &&
208                                         call.position == seqcalls[i].position &&
209                                         len(call.deletion) == len(seqcalls[i].deletion) &&
210                                         bytes.Equal(call.insertion, seqcalls[i].insertion) {
211                                         call = seqcalls[i]
212                                         i++
213                                         info += fmt.Sprintf("%d-%d,", call.tile, call.variant)
214                                 }
215                                 deletion := call.deletion
216                                 if len(deletion) == 0 {
217                                         deletion = placeholder
218                                 }
219                                 insertion := call.insertion
220                                 if len(insertion) == 0 {
221                                         insertion = placeholder
222                                 }
223                                 _, err = fmt.Fprintf(bufw, "%s\t%d\t.\t%s\t%s\t.\t.\t%s\n", seq, call.position, deletion, insertion, info)
224                                 if err != nil {
225                                         return err
226                                 }
227                         }
228                         err = bufw.Flush()
229                         if err != nil {
230                                 return err
231                         }
232                         err = f.Close()
233                         if err != nil {
234                                 return err
235                         }
236                         log.Printf("%s: done", seq)
237                         return nil
238                 })
239         }
240         err = thr.Wait()
241         if err != nil {
242                 return 1
243         }
244         return 0
245 }