Split gvcf2numpy command into import and export-numpy.
[lightning.git] / import.go
1 package main
2
3 import (
4         "bufio"
5         "compress/gzip"
6         "encoding/gob"
7         "flag"
8         "fmt"
9         "io"
10         "log"
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
25 type importer struct {
26         tagLibraryFile string
27         refFile        string
28         encoder        *gob.Encoder
29 }
30
31 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
32         var err error
33         defer func() {
34                 if err != nil {
35                         fmt.Fprintf(stderr, "%s\n", err)
36                 }
37         }()
38         flags := flag.NewFlagSet("", flag.ContinueOnError)
39         flags.SetOutput(stderr)
40         flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
41         flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
42         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
43         err = flags.Parse(args)
44         if err == flag.ErrHelp {
45                 err = nil
46                 return 0
47         } else if err != nil {
48                 return 2
49         } else if cmd.refFile == "" || cmd.tagLibraryFile == "" {
50                 fmt.Fprintln(os.Stderr, "cannot run without -tag-library and -ref arguments")
51                 return 2
52         } else if flags.NArg() == 0 {
53                 flags.Usage()
54                 return 2
55         }
56
57         if *pprof != "" {
58                 go func() {
59                         log.Println(http.ListenAndServe(*pprof, nil))
60                 }()
61         }
62
63         infiles, err := listInputFiles(flags.Args())
64         if err != nil {
65                 return 1
66         }
67
68         tilelib, err := cmd.loadTileLibrary()
69         if err != nil {
70                 return 1
71         }
72         go func() {
73                 for range time.Tick(10 * time.Second) {
74                         log.Printf("tilelib.Len() == %d", tilelib.Len())
75                 }
76         }()
77         w := bufio.NewWriter(stdout)
78         cmd.encoder = gob.NewEncoder(w)
79         err = cmd.tileGVCFs(tilelib, infiles)
80         if err != nil {
81                 return 1
82         }
83         err = w.Flush()
84         if err != nil {
85                 return 1
86         }
87         return 0
88 }
89
90 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
91         var input io.ReadCloser
92         input, err := os.Open(infile)
93         if err != nil {
94                 return nil, err
95         }
96         defer input.Close()
97         if strings.HasSuffix(infile, ".gz") {
98                 input, err = gzip.NewReader(input)
99                 if err != nil {
100                         return nil, err
101                 }
102                 defer input.Close()
103         }
104         return tilelib.TileFasta(infile, input)
105 }
106
107 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
108         log.Printf("tag library %s load starting", cmd.tagLibraryFile)
109         f, err := os.Open(cmd.tagLibraryFile)
110         if err != nil {
111                 return nil, err
112         }
113         defer f.Close()
114         var rdr io.ReadCloser = f
115         if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
116                 rdr, err = gzip.NewReader(f)
117                 if err != nil {
118                         return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
119                 }
120                 defer rdr.Close()
121         }
122         var taglib tagLibrary
123         err = taglib.Load(rdr)
124         if err != nil {
125                 return nil, err
126         }
127         if taglib.Len() < 1 {
128                 return nil, fmt.Errorf("cannot tile: tag library is empty")
129         }
130         log.Printf("tag library %s load done", cmd.tagLibraryFile)
131         return &tileLibrary{taglib: &taglib}, nil
132 }
133
134 func listInputFiles(paths []string) (files []string, err error) {
135         for _, path := range paths {
136                 if fi, err := os.Stat(path); err != nil {
137                         return nil, fmt.Errorf("%s: stat failed: %s", path, err)
138                 } else if !fi.IsDir() {
139                         if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
140                                 files = append(files, path)
141                         }
142                         continue
143                 }
144                 d, err := os.Open(path)
145                 if err != nil {
146                         return nil, fmt.Errorf("%s: open failed: %s", path, err)
147                 }
148                 defer d.Close()
149                 names, err := d.Readdirnames(0)
150                 if err != nil {
151                         return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
152                 }
153                 sort.Strings(names)
154                 for _, name := range names {
155                         if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
156                                 files = append(files, filepath.Join(path, name))
157                         } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
158                                 files = append(files, filepath.Join(path, name))
159                         }
160                 }
161                 d.Close()
162         }
163         for _, file := range files {
164                 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
165                         continue
166                 } else if _, err := os.Stat(file + ".csi"); err == nil {
167                         continue
168                 } else if _, err = os.Stat(file + ".tbi"); err == nil {
169                         continue
170                 } else {
171                         return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
172                 }
173         }
174         return
175 }
176
177 func (cmd *importer) tileGVCFs(tilelib *tileLibrary, infiles []string) error {
178         starttime := time.Now()
179         errs := make(chan error, 1)
180         todo := make(chan func() error, len(infiles)*2)
181         var encodeJobs sync.WaitGroup
182         for _, infile := range infiles {
183                 infile := infile
184                 var phases sync.WaitGroup
185                 phases.Add(2)
186                 variants := make([][]tileVariantID, 2)
187                 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
188                         todo <- func() error {
189                                 defer phases.Done()
190                                 log.Printf("%s starting", infile)
191                                 defer log.Printf("%s done", infile)
192                                 tseqs, err := cmd.tileFasta(tilelib, infile)
193                                 variants[0] = tseqs.Variants()
194                                 return err
195                         }
196                         infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
197                         todo <- func() error {
198                                 defer phases.Done()
199                                 log.Printf("%s starting", infile2)
200                                 defer log.Printf("%s done", infile2)
201                                 tseqs, err := cmd.tileFasta(tilelib, infile2)
202                                 variants[1] = tseqs.Variants()
203                                 return err
204                         }
205                 } else {
206                         for phase := 0; phase < 2; phase++ {
207                                 phase := phase
208                                 todo <- func() error {
209                                         defer phases.Done()
210                                         log.Printf("%s phase %d starting", infile, phase+1)
211                                         defer log.Printf("%s phase %d done", infile, phase+1)
212                                         tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
213                                         variants[phase] = tseqs.Variants()
214                                         return err
215                                 }
216                         }
217                 }
218                 encodeJobs.Add(1)
219                 go func() {
220                         defer encodeJobs.Done()
221                         phases.Wait()
222                         if len(errs) > 0 {
223                                 return
224                         }
225                         ntags := len(variants[0])
226                         if ntags < len(variants[1]) {
227                                 ntags = len(variants[1])
228                         }
229                         flat := make([]tileVariantID, ntags*2)
230                         for i := 0; i < ntags; i++ {
231                                 flat[i*2] = variants[0][i]
232                                 flat[i*2+1] = variants[1][i]
233                         }
234                         err := cmd.encoder.Encode(LibraryEntry{
235                                 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
236                         })
237                         if err != nil {
238                                 select {
239                                 case errs <- err:
240                                 default:
241                                 }
242                         }
243                 }()
244         }
245         go close(todo)
246         var tileJobs sync.WaitGroup
247         running := int64(runtime.NumCPU())
248         for i := 0; i < runtime.NumCPU(); i++ {
249                 tileJobs.Add(1)
250                 go func() {
251                         defer tileJobs.Done()
252                         defer atomic.AddInt64(&running, -1)
253                         for fn := range todo {
254                                 if len(errs) > 0 {
255                                         return
256                                 }
257                                 err := fn()
258                                 if err != nil {
259                                         select {
260                                         case errs <- err:
261                                         default:
262                                         }
263                                 }
264                                 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
265                                 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
266                                 eta := time.Now().Add(ttl)
267                                 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
268                         }
269                 }()
270         }
271         tileJobs.Wait()
272         encodeJobs.Wait()
273         go close(errs)
274         return <-errs
275 }
276
277 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
278         args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
279         indexsuffix := ".tbi"
280         if _, err := os.Stat(infile + ".csi"); err == nil {
281                 indexsuffix = ".csi"
282         }
283         if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
284                 args = append([]string{
285                         "docker", "run", "--rm",
286                         "--log-driver=none",
287                         "--volume=" + infile + ":" + infile + ":ro",
288                         "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
289                         "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
290                         "lightning-runtime",
291                 }, args...)
292         }
293         consensus := exec.Command(args[0], args[1:]...)
294         consensus.Stderr = os.Stderr
295         stdout, err := consensus.StdoutPipe()
296         defer stdout.Close()
297         if err != nil {
298                 return
299         }
300         err = consensus.Start()
301         if err != nil {
302                 return
303         }
304         defer consensus.Wait()
305         tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
306         if err != nil {
307                 return
308         }
309         err = stdout.Close()
310         if err != nil {
311                 return
312         }
313         err = consensus.Wait()
314         if err != nil {
315                 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
316                 return
317         }
318         return
319 }