Option to treat tiles with no-calls as regular tiles.
[lightning.git] / import.go
1 package main
2
3 import (
4         "bufio"
5         "compress/gzip"
6         "encoding/gob"
7         "errors"
8         "flag"
9         "fmt"
10         "io"
11         "net/http"
12         _ "net/http/pprof"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "regexp"
17         "runtime"
18         "sort"
19         "strings"
20         "sync"
21         "sync/atomic"
22         "time"
23
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         log "github.com/sirupsen/logrus"
26 )
27
28 type importer struct {
29         tagLibraryFile string
30         refFile        string
31         outputFile     string
32         projectUUID    string
33         runLocal       bool
34         skipOOO        bool
35         outputTiles    bool
36         includeNoCalls bool
37         encoder        *gob.Encoder
38 }
39
40 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41         var err error
42         defer func() {
43                 if err != nil {
44                         fmt.Fprintf(stderr, "%s\n", err)
45                 }
46         }()
47         flags := flag.NewFlagSet("", flag.ContinueOnError)
48         flags.SetOutput(stderr)
49         flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
50         flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
51         flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
52         flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
53         flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
54         flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
55         flags.BoolVar(&cmd.outputTiles, "output-tiles", false, "include tile variant sequences in output file")
56         flags.BoolVar(&cmd.includeNoCalls, "include-no-calls", false, "treat tiles with no-calls as regular tiles")
57         priority := flags.Int("priority", 500, "container request priority")
58         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
59         loglevel := flags.String("loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
60         err = flags.Parse(args)
61         if err == flag.ErrHelp {
62                 err = nil
63                 return 0
64         } else if err != nil {
65                 return 2
66         } else if cmd.tagLibraryFile == "" {
67                 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
68                 return 2
69         } else if flags.NArg() == 0 {
70                 flags.Usage()
71                 return 2
72         }
73
74         if *pprof != "" {
75                 go func() {
76                         log.Println(http.ListenAndServe(*pprof, nil))
77                 }()
78         }
79
80         lvl, err := log.ParseLevel(*loglevel)
81         if err != nil {
82                 return 2
83         }
84         log.SetLevel(lvl)
85
86         if !cmd.runLocal {
87                 runner := arvadosContainerRunner{
88                         Name:        "lightning import",
89                         Client:      arvados.NewClientFromEnv(),
90                         ProjectUUID: cmd.projectUUID,
91                         RAM:         60000000000,
92                         VCPUs:       16,
93                         Priority:    *priority,
94                 }
95                 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
96                 if err != nil {
97                         return 1
98                 }
99                 inputs := flags.Args()
100                 for i := range inputs {
101                         err = runner.TranslatePaths(&inputs[i])
102                         if err != nil {
103                                 return 1
104                         }
105                 }
106                 if cmd.outputFile == "-" {
107                         cmd.outputFile = "/mnt/output/library.gob"
108                 } else {
109                         // Not yet implemented, but this should write
110                         // the collection to an existing collection,
111                         // possibly even an in-place update.
112                         err = errors.New("cannot specify output file in container mode: not implemented")
113                         return 1
114                 }
115                 runner.Args = append([]string{"import",
116                         "-local=true",
117                         "-loglevel=" + *loglevel,
118                         fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO),
119                         fmt.Sprintf("-output-tiles=%v", cmd.outputTiles),
120                         fmt.Sprintf("-include-no-calls=%v", cmd.includeNoCalls),
121                         "-tag-library", cmd.tagLibraryFile,
122                         "-ref", cmd.refFile,
123                         "-o", cmd.outputFile,
124                 }, inputs...)
125                 var output string
126                 output, err = runner.Run()
127                 if err != nil {
128                         return 1
129                 }
130                 fmt.Fprintln(stdout, output+"/library.gob")
131                 return 0
132         }
133
134         infiles, err := listInputFiles(flags.Args())
135         if err != nil {
136                 return 1
137         }
138
139         taglib, err := cmd.loadTagLibrary()
140         if err != nil {
141                 return 1
142         }
143
144         var output io.WriteCloser
145         if cmd.outputFile == "-" {
146                 output = nopCloser{stdout}
147         } else {
148                 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
149                 if err != nil {
150                         return 1
151                 }
152                 defer output.Close()
153         }
154         bufw := bufio.NewWriter(output)
155         cmd.encoder = gob.NewEncoder(bufw)
156
157         tilelib := &tileLibrary{taglib: taglib, includeNoCalls: cmd.includeNoCalls, skipOOO: cmd.skipOOO}
158         if cmd.outputTiles {
159                 tilelib.encoder = cmd.encoder
160         }
161         go func() {
162                 for range time.Tick(10 * time.Minute) {
163                         log.Printf("tilelib.Len() == %d", tilelib.Len())
164                 }
165         }()
166
167         err = cmd.tileInputs(tilelib, infiles)
168         if err != nil {
169                 return 1
170         }
171         err = bufw.Flush()
172         if err != nil {
173                 return 1
174         }
175         err = output.Close()
176         if err != nil {
177                 return 1
178         }
179         return 0
180 }
181
182 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
183         var input io.ReadCloser
184         input, err := os.Open(infile)
185         if err != nil {
186                 return nil, err
187         }
188         defer input.Close()
189         if strings.HasSuffix(infile, ".gz") {
190                 input, err = gzip.NewReader(input)
191                 if err != nil {
192                         return nil, err
193                 }
194                 defer input.Close()
195         }
196         return tilelib.TileFasta(infile, input)
197 }
198
199 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
200         log.Printf("tag library %s load starting", cmd.tagLibraryFile)
201         f, err := os.Open(cmd.tagLibraryFile)
202         if err != nil {
203                 return nil, err
204         }
205         defer f.Close()
206         var rdr io.ReadCloser = f
207         if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
208                 rdr, err = gzip.NewReader(f)
209                 if err != nil {
210                         return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
211                 }
212                 defer rdr.Close()
213         }
214         var taglib tagLibrary
215         err = taglib.Load(rdr)
216         if err != nil {
217                 return nil, err
218         }
219         if taglib.Len() < 1 {
220                 return nil, fmt.Errorf("cannot tile: tag library is empty")
221         }
222         log.Printf("tag library %s load done", cmd.tagLibraryFile)
223         return &taglib, nil
224 }
225
226 func listInputFiles(paths []string) (files []string, err error) {
227         for _, path := range paths {
228                 if fi, err := os.Stat(path); err != nil {
229                         return nil, fmt.Errorf("%s: stat failed: %s", path, err)
230                 } else if !fi.IsDir() {
231                         if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
232                                 files = append(files, path)
233                         }
234                         continue
235                 }
236                 d, err := os.Open(path)
237                 if err != nil {
238                         return nil, fmt.Errorf("%s: open failed: %s", path, err)
239                 }
240                 defer d.Close()
241                 names, err := d.Readdirnames(0)
242                 if err != nil {
243                         return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
244                 }
245                 sort.Strings(names)
246                 for _, name := range names {
247                         if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
248                                 files = append(files, filepath.Join(path, name))
249                         } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
250                                 files = append(files, filepath.Join(path, name))
251                         }
252                 }
253                 d.Close()
254         }
255         for _, file := range files {
256                 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
257                         continue
258                 } else if _, err := os.Stat(file + ".csi"); err == nil {
259                         continue
260                 } else if _, err = os.Stat(file + ".tbi"); err == nil {
261                         continue
262                 } else {
263                         return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
264                 }
265         }
266         return
267 }
268
269 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
270         starttime := time.Now()
271         errs := make(chan error, 1)
272         todo := make(chan func() error, len(infiles)*2)
273         var encodeJobs sync.WaitGroup
274         for _, infile := range infiles {
275                 infile := infile
276                 var phases sync.WaitGroup
277                 phases.Add(2)
278                 variants := make([][]tileVariantID, 2)
279                 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
280                         todo <- func() error {
281                                 defer phases.Done()
282                                 log.Printf("%s starting", infile)
283                                 defer log.Printf("%s done", infile)
284                                 tseqs, err := cmd.tileFasta(tilelib, infile)
285                                 var kept, dropped int
286                                 variants[0], kept, dropped = tseqs.Variants()
287                                 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
288                                 return err
289                         }
290                         infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
291                         todo <- func() error {
292                                 defer phases.Done()
293                                 log.Printf("%s starting", infile2)
294                                 defer log.Printf("%s done", infile2)
295                                 tseqs, err := cmd.tileFasta(tilelib, infile2)
296                                 var kept, dropped int
297                                 variants[1], kept, dropped = tseqs.Variants()
298                                 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
299                                 return err
300                         }
301                 } else {
302                         for phase := 0; phase < 2; phase++ {
303                                 phase := phase
304                                 todo <- func() error {
305                                         defer phases.Done()
306                                         log.Printf("%s phase %d starting", infile, phase+1)
307                                         defer log.Printf("%s phase %d done", infile, phase+1)
308                                         tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
309                                         var kept, dropped int
310                                         variants[phase], kept, dropped = tseqs.Variants()
311                                         log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
312                                         return err
313                                 }
314                         }
315                 }
316                 encodeJobs.Add(1)
317                 go func() {
318                         defer encodeJobs.Done()
319                         phases.Wait()
320                         if len(errs) > 0 {
321                                 return
322                         }
323                         ntags := len(variants[0])
324                         if ntags < len(variants[1]) {
325                                 ntags = len(variants[1])
326                         }
327                         flat := make([]tileVariantID, ntags*2)
328                         for i := 0; i < ntags; i++ {
329                                 for hap := 0; hap < 2; hap++ {
330                                         if i < len(variants[hap]) {
331                                                 flat[i*2+hap] = variants[hap][i]
332                                         }
333                                 }
334                         }
335                         err := cmd.encoder.Encode(LibraryEntry{
336                                 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
337                         })
338                         if err != nil {
339                                 select {
340                                 case errs <- err:
341                                 default:
342                                 }
343                         }
344                 }()
345         }
346         go close(todo)
347         var tileJobs sync.WaitGroup
348         var running int64
349         for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
350                 tileJobs.Add(1)
351                 atomic.AddInt64(&running, 1)
352                 go func() {
353                         defer tileJobs.Done()
354                         defer atomic.AddInt64(&running, -1)
355                         for fn := range todo {
356                                 if len(errs) > 0 {
357                                         return
358                                 }
359                                 err := fn()
360                                 if err != nil {
361                                         select {
362                                         case errs <- err:
363                                         default:
364                                         }
365                                 }
366                                 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
367                                 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
368                                 eta := time.Now().Add(ttl)
369                                 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
370                         }
371                 }()
372         }
373         tileJobs.Wait()
374         encodeJobs.Wait()
375         go close(errs)
376         return <-errs
377 }
378
379 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
380         if cmd.refFile == "" {
381                 err = errors.New("cannot import vcf: reference data (-ref) not specified")
382                 return
383         }
384         args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
385         indexsuffix := ".tbi"
386         if _, err := os.Stat(infile + ".csi"); err == nil {
387                 indexsuffix = ".csi"
388         }
389         if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
390                 args = append([]string{
391                         "docker", "run", "--rm",
392                         "--log-driver=none",
393                         "--volume=" + infile + ":" + infile + ":ro",
394                         "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
395                         "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
396                         "lightning-runtime",
397                 }, args...)
398         }
399         consensus := exec.Command(args[0], args[1:]...)
400         consensus.Stderr = os.Stderr
401         stdout, err := consensus.StdoutPipe()
402         defer stdout.Close()
403         if err != nil {
404                 return
405         }
406         err = consensus.Start()
407         if err != nil {
408                 return
409         }
410         defer consensus.Wait()
411         tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
412         if err != nil {
413                 return
414         }
415         err = stdout.Close()
416         if err != nil {
417                 return
418         }
419         err = consensus.Wait()
420         if err != nil {
421                 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
422                 return
423         }
424         return
425 }