Fix race.
[lightning.git] / annotate.go
1 package lightning
2
3 import (
4         "bufio"
5         "context"
6         "errors"
7         "flag"
8         "fmt"
9         "io"
10         "io/ioutil"
11         "net/http"
12         _ "net/http/pprof"
13         "os"
14         "runtime"
15         "sort"
16         "strconv"
17         "strings"
18         "sync"
19
20         "git.arvados.org/arvados.git/sdk/go/arvados"
21         "github.com/arvados/lightning/hgvs"
22         log "github.com/sirupsen/logrus"
23 )
24
25 type annotatecmd struct {
26         dropTiles        []bool
27         variantHash      bool
28         maxTileSize      int
29         tag2tagid        map[string]tagID
30         reportAnnotation func(tag tagID, outcol int, variant tileVariantID, refname string, seqname string, pdi hgvs.Variant)
31 }
32
33 func (cmd *annotatecmd) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
34         var err error
35         defer func() {
36                 if err != nil {
37                         fmt.Fprintf(stderr, "%s\n", err)
38                 }
39         }()
40         flags := flag.NewFlagSet("", flag.ContinueOnError)
41         flags.SetOutput(stderr)
42         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
43         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
44         projectUUID := flags.String("project", "", "project `UUID` for output data")
45         priority := flags.Int("priority", 500, "container request priority")
46         inputFilename := flags.String("i", "-", "input `file` (library)")
47         outputFilename := flags.String("o", "-", "output `file`")
48         flags.BoolVar(&cmd.variantHash, "variant-hash", false, "output variant hash instead of index")
49         flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
50         err = flags.Parse(args)
51         if err == flag.ErrHelp {
52                 err = nil
53                 return 0
54         } else if err != nil {
55                 return 2
56         }
57
58         if *pprof != "" {
59                 go func() {
60                         log.Println(http.ListenAndServe(*pprof, nil))
61                 }()
62         }
63         if !*runlocal {
64                 if *outputFilename != "-" {
65                         err = errors.New("cannot specify output file in container mode: not implemented")
66                         return 1
67                 }
68                 runner := arvadosContainerRunner{
69                         Name:        "lightning annotate",
70                         Client:      arvados.NewClientFromEnv(),
71                         ProjectUUID: *projectUUID,
72                         RAM:         80000000000,
73                         VCPUs:       16,
74                         Priority:    *priority,
75                 }
76                 err = runner.TranslatePaths(inputFilename)
77                 if err != nil {
78                         return 1
79                 }
80                 runner.Args = []string{"annotate", "-local=true", fmt.Sprintf("-variant-hash=%v", cmd.variantHash), "-max-tile-size", strconv.Itoa(cmd.maxTileSize), "-i", *inputFilename, "-o", "/mnt/output/tilevariants.csv"}
81                 var output string
82                 output, err = runner.Run()
83                 if err != nil {
84                         return 1
85                 }
86                 fmt.Fprintln(stdout, output+"/tilevariants.csv")
87                 return 0
88         }
89
90         var input io.ReadCloser
91         if *inputFilename == "-" {
92                 input = ioutil.NopCloser(stdin)
93         } else {
94                 input, err = os.Open(*inputFilename)
95                 if err != nil {
96                         return 1
97                 }
98                 defer input.Close()
99         }
100
101         var output io.WriteCloser
102         if *outputFilename == "-" {
103                 output = nopCloser{stdout}
104         } else {
105                 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
106                 if err != nil {
107                         return 1
108                 }
109                 defer output.Close()
110         }
111         bufw := bufio.NewWriterSize(output, 4*1024*1024)
112
113         tilelib := &tileLibrary{
114                 retainNoCalls:       true,
115                 retainTileSequences: true,
116         }
117         err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
118         if err != nil {
119                 return 1
120         }
121         err = cmd.exportTileDiffs(bufw, tilelib)
122         if err != nil {
123                 return 1
124         }
125         err = bufw.Flush()
126         if err != nil {
127                 return 1
128         }
129         err = output.Close()
130         if err != nil {
131                 return 1
132         }
133         err = input.Close()
134         if err != nil {
135                 return 1
136         }
137         return 0
138 }
139
140 func (cmd *annotatecmd) exportTileDiffs(outw io.Writer, tilelib *tileLibrary) error {
141         tagset := tilelib.taglib.Tags()
142         if len(tagset) == 0 {
143                 return errors.New("cannot annotate library without tags")
144         }
145         taglen := len(tagset[0])
146         var refs []string
147         for name := range tilelib.refseqs {
148                 refs = append(refs, name)
149         }
150         cmd.tag2tagid = make(map[string]tagID, len(tagset))
151         for tagid, tagseq := range tagset {
152                 cmd.tag2tagid[string(tagseq)] = tagID(tagid)
153         }
154         sort.Strings(refs)
155         log.Infof("len(refs) %d", len(refs))
156
157         outch := make(chan string, runtime.NumCPU()*2)
158         var outwg sync.WaitGroup
159         defer outwg.Wait()
160         outwg.Add(1)
161         go func() {
162                 defer outwg.Done()
163                 for s := range outch {
164                         io.WriteString(outw, s)
165                 }
166         }()
167         defer close(outch)
168
169         nseqs := 0
170         for _, refcs := range tilelib.refseqs {
171                 nseqs += len(refcs)
172         }
173
174         throttle := &throttle{Max: runtime.NumCPU()*2 + nseqs*2 + 1}
175         defer throttle.Wait()
176
177         for _, refname := range refs {
178                 refname := refname
179                 refcs := tilelib.refseqs[refname]
180                 var seqnames []string
181                 for seqname := range refcs {
182                         seqnames = append(seqnames, seqname)
183                 }
184                 sort.Strings(seqnames)
185                 for _, seqname := range seqnames {
186                         seqname := seqname
187                         throttle.Acquire()
188                         if throttle.Err() != nil {
189                                 break
190                         }
191                         go func() {
192                                 defer throttle.Release()
193                                 throttle.Report(cmd.annotateSequence(throttle, outch, tilelib, taglen, refname, seqname, refcs[seqname], len(refs) > 1))
194                         }()
195                 }
196         }
197         throttle.Wait()
198         return throttle.Err()
199 }
200
201 func (cmd *annotatecmd) annotateSequence(throttle *throttle, outch chan<- string, tilelib *tileLibrary, taglen int, refname, seqname string, reftiles []tileLibRef, refnamecol bool) error {
202         refnamefield := ""
203         if refnamecol {
204                 refnamefield = "," + trimFilenameForLabel(refname)
205         }
206         var refseq []byte
207         // tilestart[123] is the index into refseq
208         // where the tile for tag 123 was placed.
209         tilestart := map[tagID]int{}
210         tileend := map[tagID]int{}
211         for _, libref := range reftiles {
212                 if libref.Variant < 1 {
213                         return fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, seqname, libref.Tag)
214                 }
215                 seq := tilelib.TileVariantSequence(libref)
216                 if len(seq) < taglen {
217                         return fmt.Errorf("reference %q seq %q uses tile %d variant %d with sequence len %d < taglen %d", refname, seqname, libref.Tag, libref.Variant, len(seq), taglen)
218                 }
219                 overlap := taglen
220                 if len(refseq) == 0 {
221                         overlap = 0
222                 }
223                 tilestart[libref.Tag] = len(refseq) - overlap
224                 refseq = append(refseq, seq[overlap:]...)
225                 tileend[libref.Tag] = len(refseq)
226         }
227         log.Infof("seq %s len(refseq) %d len(tilestart) %d", seqname, len(refseq), len(tilestart))
228         // outtag is tag's index in the subset of tags that aren't
229         // dropped. If there are 10M tags and half are dropped by
230         // dropTiles, tag ranges from 0 to 10M-1 and outtag ranges
231         // from 0 to 5M-1.
232         //
233         // IOW, in the matrix built by cgs2array(), {tag} is
234         // represented by columns {outtag}*2 and {outtag}*2+1.
235         outcol := -1
236         for tag, tvs := range tilelib.variant {
237                 if len(cmd.dropTiles) > tag && cmd.dropTiles[tag] {
238                         continue
239                 }
240                 tag := tagID(tag)
241                 outcol++
242                 // Must shadow outcol var to use safely in goroutine below.
243                 outcol := outcol
244                 refstart, ok := tilestart[tag]
245                 if !ok {
246                         // Tag didn't place on this reference
247                         // sequence. (It might place on the same
248                         // chromosome in a genome anyway, but we don't
249                         // output the annotations that would result.)
250                         // outch <- fmt.Sprintf("%d,%d,-1%s\n", tag, outcol, refnamefield)
251                         continue
252                 }
253                 for variant := 1; variant <= len(tvs); variant++ {
254                         variant, hash := tileVariantID(variant), tvs[variant-1]
255                         tileseq := tilelib.TileVariantSequence(tileLibRef{Tag: tag, Variant: variant})
256                         if len(tileseq) == 0 {
257                                 continue
258                         } else if len(tileseq) < taglen {
259                                 return fmt.Errorf("tilevar %d,%d has sequence len %d < taglen %d", tag, variant, len(tileseq), taglen)
260                         }
261                         var refpart []byte
262                         endtag := string(tileseq[len(tileseq)-taglen:])
263                         if endtagid, ok := cmd.tag2tagid[endtag]; !ok {
264                                 // Tile variant doesn't end on a tag, so it can only place at the end of a chromosome.
265                                 refpart = refseq[refstart:]
266                                 log.Warnf("%x tilevar %d,%d endtag not in ref: %s", hash[:13], tag, variant, endtag)
267                         } else if refendtagstart, ok := tilestart[endtagid]; !ok {
268                                 // Ref ends a chromsome with a (possibly very large) variant of this tile, but genomes with this tile don't.
269                                 // Give up. (TODO: something smarter)
270                                 log.Debugf("%x not annotating tilevar %d,%d because end tag %d is not in ref", hash[:13], tag, variant, endtagid)
271                                 continue
272                         } else {
273                                 // Non-terminal tile vs. non-terminal reference.
274                                 refpart = refseq[refstart : refendtagstart+taglen]
275                                 log.Tracef("\n%x tilevar %d,%d endtag %s endtagid %d refendtagstart %d", hash[:13], tag, variant, endtag, endtagid, refendtagstart)
276                         }
277                         if len(refpart) > cmd.maxTileSize {
278                                 log.Warnf("%x tilevar %d,%d skipping long diff, ref %s seq %s pos %d ref len %d", hash[:13], tag, variant, refname, seqname, refstart, len(refpart))
279                                 continue
280                         }
281                         if len(tileseq) > cmd.maxTileSize {
282                                 log.Warnf("%x tilevar %d,%d skipping long diff, ref %s seq %s variant len %d", hash[:13], tag, variant, refname, seqname, len(tileseq))
283                                 continue
284                         }
285                         // log.Printf("\n%x @ refstart %d \n< %s\n> %s\n", tv.Blake2b, refstart, refpart, tileseq)
286
287                         throttle.Acquire()
288                         go func() {
289                                 defer throttle.Release()
290                                 diffs, _ := hgvs.Diff(strings.ToUpper(string(refpart)), strings.ToUpper(string(tileseq)), 0)
291                                 for _, diff := range diffs {
292                                         diff.Position += refstart
293                                         var varid string
294                                         if cmd.variantHash {
295                                                 varid = fmt.Sprintf("%x", hash)[:13]
296                                         } else {
297                                                 varid = fmt.Sprintf("%d", variant)
298                                         }
299                                         outch <- fmt.Sprintf("%d,%d,%s%s,%s:g.%s\n", tag, outcol, varid, refnamefield, seqname, diff.String())
300                                         if cmd.reportAnnotation != nil {
301                                                 cmd.reportAnnotation(tag, outcol, variant, refname, seqname, diff)
302                                         }
303                                 }
304                         }()
305                 }
306         }
307         return nil
308 }