When writing library, write tags too.
[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                 cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
160                 tilelib.encoder = cmd.encoder
161         }
162         go func() {
163                 for range time.Tick(10 * time.Minute) {
164                         log.Printf("tilelib.Len() == %d", tilelib.Len())
165                 }
166         }()
167
168         err = cmd.tileInputs(tilelib, infiles)
169         if err != nil {
170                 return 1
171         }
172         err = bufw.Flush()
173         if err != nil {
174                 return 1
175         }
176         err = output.Close()
177         if err != nil {
178                 return 1
179         }
180         return 0
181 }
182
183 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
184         var input io.ReadCloser
185         input, err := os.Open(infile)
186         if err != nil {
187                 return nil, err
188         }
189         defer input.Close()
190         if strings.HasSuffix(infile, ".gz") {
191                 input, err = gzip.NewReader(input)
192                 if err != nil {
193                         return nil, err
194                 }
195                 defer input.Close()
196         }
197         return tilelib.TileFasta(infile, input)
198 }
199
200 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
201         log.Printf("tag library %s load starting", cmd.tagLibraryFile)
202         f, err := os.Open(cmd.tagLibraryFile)
203         if err != nil {
204                 return nil, err
205         }
206         defer f.Close()
207         var rdr io.ReadCloser = f
208         if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
209                 rdr, err = gzip.NewReader(f)
210                 if err != nil {
211                         return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
212                 }
213                 defer rdr.Close()
214         }
215         var taglib tagLibrary
216         err = taglib.Load(rdr)
217         if err != nil {
218                 return nil, err
219         }
220         if taglib.Len() < 1 {
221                 return nil, fmt.Errorf("cannot tile: tag library is empty")
222         }
223         log.Printf("tag library %s load done", cmd.tagLibraryFile)
224         return &taglib, nil
225 }
226
227 func listInputFiles(paths []string) (files []string, err error) {
228         for _, path := range paths {
229                 if fi, err := os.Stat(path); err != nil {
230                         return nil, fmt.Errorf("%s: stat failed: %s", path, err)
231                 } else if !fi.IsDir() {
232                         if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
233                                 files = append(files, path)
234                         }
235                         continue
236                 }
237                 d, err := os.Open(path)
238                 if err != nil {
239                         return nil, fmt.Errorf("%s: open failed: %s", path, err)
240                 }
241                 defer d.Close()
242                 names, err := d.Readdirnames(0)
243                 if err != nil {
244                         return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
245                 }
246                 sort.Strings(names)
247                 for _, name := range names {
248                         if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
249                                 files = append(files, filepath.Join(path, name))
250                         } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
251                                 files = append(files, filepath.Join(path, name))
252                         }
253                 }
254                 d.Close()
255         }
256         for _, file := range files {
257                 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
258                         continue
259                 } else if _, err := os.Stat(file + ".csi"); err == nil {
260                         continue
261                 } else if _, err = os.Stat(file + ".tbi"); err == nil {
262                         continue
263                 } else {
264                         return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
265                 }
266         }
267         return
268 }
269
270 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
271         starttime := time.Now()
272         errs := make(chan error, 1)
273         todo := make(chan func() error, len(infiles)*2)
274         var encodeJobs sync.WaitGroup
275         for _, infile := range infiles {
276                 infile := infile
277                 var phases sync.WaitGroup
278                 phases.Add(2)
279                 variants := make([][]tileVariantID, 2)
280                 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
281                         todo <- func() error {
282                                 defer phases.Done()
283                                 log.Printf("%s starting", infile)
284                                 defer log.Printf("%s done", infile)
285                                 tseqs, err := cmd.tileFasta(tilelib, infile)
286                                 var kept, dropped int
287                                 variants[0], kept, dropped = tseqs.Variants()
288                                 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
289                                 return err
290                         }
291                         infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
292                         todo <- func() error {
293                                 defer phases.Done()
294                                 log.Printf("%s starting", infile2)
295                                 defer log.Printf("%s done", infile2)
296                                 tseqs, err := cmd.tileFasta(tilelib, infile2)
297                                 var kept, dropped int
298                                 variants[1], kept, dropped = tseqs.Variants()
299                                 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
300                                 return err
301                         }
302                 } else {
303                         for phase := 0; phase < 2; phase++ {
304                                 phase := phase
305                                 todo <- func() error {
306                                         defer phases.Done()
307                                         log.Printf("%s phase %d starting", infile, phase+1)
308                                         defer log.Printf("%s phase %d done", infile, phase+1)
309                                         tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
310                                         var kept, dropped int
311                                         variants[phase], kept, dropped = tseqs.Variants()
312                                         log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
313                                         return err
314                                 }
315                         }
316                 }
317                 encodeJobs.Add(1)
318                 go func() {
319                         defer encodeJobs.Done()
320                         phases.Wait()
321                         if len(errs) > 0 {
322                                 return
323                         }
324                         ntags := len(variants[0])
325                         if ntags < len(variants[1]) {
326                                 ntags = len(variants[1])
327                         }
328                         flat := make([]tileVariantID, ntags*2)
329                         for i := 0; i < ntags; i++ {
330                                 for hap := 0; hap < 2; hap++ {
331                                         if i < len(variants[hap]) {
332                                                 flat[i*2+hap] = variants[hap][i]
333                                         }
334                                 }
335                         }
336                         err := cmd.encoder.Encode(LibraryEntry{
337                                 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
338                         })
339                         if err != nil {
340                                 select {
341                                 case errs <- err:
342                                 default:
343                                 }
344                         }
345                 }()
346         }
347         go close(todo)
348         var tileJobs sync.WaitGroup
349         var running int64
350         for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
351                 tileJobs.Add(1)
352                 atomic.AddInt64(&running, 1)
353                 go func() {
354                         defer tileJobs.Done()
355                         defer atomic.AddInt64(&running, -1)
356                         for fn := range todo {
357                                 if len(errs) > 0 {
358                                         return
359                                 }
360                                 err := fn()
361                                 if err != nil {
362                                         select {
363                                         case errs <- err:
364                                         default:
365                                         }
366                                 }
367                                 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
368                                 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
369                                 eta := time.Now().Add(ttl)
370                                 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
371                         }
372                 }()
373         }
374         tileJobs.Wait()
375         encodeJobs.Wait()
376         go close(errs)
377         return <-errs
378 }
379
380 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
381         if cmd.refFile == "" {
382                 err = errors.New("cannot import vcf: reference data (-ref) not specified")
383                 return
384         }
385         args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
386         indexsuffix := ".tbi"
387         if _, err := os.Stat(infile + ".csi"); err == nil {
388                 indexsuffix = ".csi"
389         }
390         if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
391                 args = append([]string{
392                         "docker", "run", "--rm",
393                         "--log-driver=none",
394                         "--volume=" + infile + ":" + infile + ":ro",
395                         "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
396                         "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
397                         "lightning-runtime",
398                 }, args...)
399         }
400         consensus := exec.Command(args[0], args[1:]...)
401         consensus.Stderr = os.Stderr
402         stdout, err := consensus.StdoutPipe()
403         defer stdout.Close()
404         if err != nil {
405                 return
406         }
407         err = consensus.Start()
408         if err != nil {
409                 return
410         }
411         defer consensus.Wait()
412         tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
413         if err != nil {
414                 return
415         }
416         err = stdout.Close()
417         if err != nil {
418                 return
419         }
420         err = consensus.Wait()
421         if err != nil {
422                 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
423                 return
424         }
425         return
426 }