Fix divide by zero.
[lightning.git] / import.go
index 3ce00ce19c2e96f5643a143358692978c3dbf33b..254029e4770ba68834b6a1bed19c5cf0ca4f57cc 100644 (file)
--- a/import.go
+++ b/import.go
@@ -33,6 +33,7 @@ type importer struct {
        runLocal       bool
        skipOOO        bool
        outputTiles    bool
+       includeNoCalls bool
        encoder        *gob.Encoder
 }
 
@@ -52,6 +53,7 @@ func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, std
        flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
        flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
        flags.BoolVar(&cmd.outputTiles, "output-tiles", false, "include tile variant sequences in output file")
+       flags.BoolVar(&cmd.includeNoCalls, "include-no-calls", false, "treat tiles with no-calls as regular tiles")
        priority := flags.Int("priority", 500, "container request priority")
        pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
        loglevel := flags.String("loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
@@ -110,7 +112,16 @@ func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, std
                        err = errors.New("cannot specify output file in container mode: not implemented")
                        return 1
                }
-               runner.Args = append([]string{"import", "-local=true", "-loglevel=" + *loglevel, fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO), "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, fmt.Sprintf("-output-tiles=%v", cmd.outputTiles), "-o", cmd.outputFile}, inputs...)
+               runner.Args = append([]string{"import",
+                       "-local=true",
+                       "-loglevel=" + *loglevel,
+                       fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO),
+                       fmt.Sprintf("-output-tiles=%v", cmd.outputTiles),
+                       fmt.Sprintf("-include-no-calls=%v", cmd.includeNoCalls),
+                       "-tag-library", cmd.tagLibraryFile,
+                       "-ref", cmd.refFile,
+                       "-o", cmd.outputFile,
+               }, inputs...)
                var output string
                output, err = runner.Run()
                if err != nil {
@@ -143,8 +154,9 @@ func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, std
        bufw := bufio.NewWriter(output)
        cmd.encoder = gob.NewEncoder(bufw)
 
-       tilelib := &tileLibrary{taglib: taglib, skipOOO: cmd.skipOOO}
+       tilelib := &tileLibrary{taglib: taglib, includeNoCalls: cmd.includeNoCalls, skipOOO: cmd.skipOOO}
        if cmd.outputTiles {
+               cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
                tilelib.encoder = cmd.encoder
        }
        go func() {
@@ -212,12 +224,19 @@ func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
        return &taglib, nil
 }
 
+var (
+       vcfFilenameRe    = regexp.MustCompile(`\.vcf(\.gz)?$`)
+       fasta1FilenameRe = regexp.MustCompile(`\.1\.fa(sta)?(\.gz)?$`)
+       fasta2FilenameRe = regexp.MustCompile(`\.2\.fa(sta)?(\.gz)?$`)
+       fastaFilenameRe  = regexp.MustCompile(`\.fa(sta)?(\.gz)?$`)
+)
+
 func listInputFiles(paths []string) (files []string, err error) {
        for _, path := range paths {
                if fi, err := os.Stat(path); err != nil {
                        return nil, fmt.Errorf("%s: stat failed: %s", path, err)
                } else if !fi.IsDir() {
-                       if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
+                       if !fasta2FilenameRe.MatchString(path) {
                                files = append(files, path)
                        }
                        continue
@@ -233,23 +252,27 @@ func listInputFiles(paths []string) (files []string, err error) {
                }
                sort.Strings(names)
                for _, name := range names {
-                       if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
+                       if vcfFilenameRe.MatchString(name) {
                                files = append(files, filepath.Join(path, name))
-                       } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
+                       } else if fastaFilenameRe.MatchString(name) && !fasta2FilenameRe.MatchString(name) {
                                files = append(files, filepath.Join(path, name))
                        }
                }
                d.Close()
        }
        for _, file := range files {
-               if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
-                       continue
-               } else if _, err := os.Stat(file + ".csi"); err == nil {
-                       continue
-               } else if _, err = os.Stat(file + ".tbi"); err == nil {
+               if fastaFilenameRe.MatchString(file) {
                        continue
+               } else if vcfFilenameRe.MatchString(file) {
+                       if _, err := os.Stat(file + ".csi"); err == nil {
+                               continue
+                       } else if _, err = os.Stat(file + ".tbi"); err == nil {
+                               continue
+                       } else {
+                               return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
+                       }
                } else {
-                       return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
+                       return nil, fmt.Errorf("don't know how to handle filename %s", file)
                }
        }
        return
@@ -265,7 +288,7 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                var phases sync.WaitGroup
                phases.Add(2)
                variants := make([][]tileVariantID, 2)
-               if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
+               if fasta1FilenameRe.MatchString(infile) {
                        todo <- func() error {
                                defer phases.Done()
                                log.Printf("%s starting", infile)
@@ -276,7 +299,7 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                                log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
                                return err
                        }
-                       infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
+                       infile2 := fasta1FilenameRe.ReplaceAllString(infile, `.2.fa$1$2`)
                        todo <- func() error {
                                defer phases.Done()
                                log.Printf("%s starting", infile2)
@@ -284,10 +307,31 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                                tseqs, err := cmd.tileFasta(tilelib, infile2)
                                var kept, dropped int
                                variants[1], kept, dropped = tseqs.Variants()
-                               log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
+                               log.Printf("%s found %d unique tags plus %d repeats", infile2, kept, dropped)
                                return err
                        }
-               } else {
+               } else if fastaFilenameRe.MatchString(infile) {
+                       todo <- func() error {
+                               defer phases.Done()
+                               defer phases.Done()
+                               log.Printf("%s starting", infile)
+                               defer log.Printf("%s done", infile)
+                               tseqs, err := cmd.tileFasta(tilelib, infile)
+                               if err != nil {
+                                       return err
+                               }
+                               totlen := 0
+                               for _, tseq := range tseqs {
+                                       totlen += len(tseq)
+                               }
+                               log.Printf("%s tiled %d seqs, total len %d", infile, len(tseqs), totlen)
+                               return cmd.encoder.Encode(LibraryEntry{
+                                       CompactSequences: []CompactSequence{{Name: infile, TileSequences: tseqs}},
+                               })
+                       }
+                       // Don't write out a CompactGenomes entry
+                       continue
+               } else if vcfFilenameRe.MatchString(infile) {
                        for phase := 0; phase < 2; phase++ {
                                phase := phase
                                todo <- func() error {
@@ -301,6 +345,8 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                                        return err
                                }
                        }
+               } else {
+                       panic(fmt.Sprintf("bug: unhandled filename %q", infile))
                }
                encodeJobs.Add(1)
                go func() {
@@ -309,20 +355,8 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                        if len(errs) > 0 {
                                return
                        }
-                       ntags := len(variants[0])
-                       if ntags < len(variants[1]) {
-                               ntags = len(variants[1])
-                       }
-                       flat := make([]tileVariantID, ntags*2)
-                       for i := 0; i < ntags; i++ {
-                               for hap := 0; hap < 2; hap++ {
-                                       if i < len(variants[hap]) {
-                                               flat[i*2+hap] = variants[hap][i]
-                                       }
-                               }
-                       }
                        err := cmd.encoder.Encode(LibraryEntry{
-                               CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
+                               CompactGenomes: []CompactGenome{{Name: infile, Variants: flatten(variants)}},
                        })
                        if err != nil {
                                select {
@@ -353,9 +387,11 @@ func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
                                        }
                                }
                                remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
-                               ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
-                               eta := time.Now().Add(ttl)
-                               log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
+                               if remain < cap(todo) {
+                                       ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
+                                       eta := time.Now().Add(ttl)
+                                       log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
+                               }
                        }
                }()
        }
@@ -412,3 +448,21 @@ func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (t
        }
        return
 }
+
+func flatten(variants [][]tileVariantID) []tileVariantID {
+       ntags := 0
+       for _, v := range variants {
+               if ntags < len(v) {
+                       ntags = len(v)
+               }
+       }
+       flat := make([]tileVariantID, ntags*2)
+       for i := 0; i < ntags; i++ {
+               for hap := 0; hap < 2; hap++ {
+                       if i < len(variants[hap]) {
+                               flat[i*2+hap] = variants[hap][i]
+                       }
+               }
+       }
+       return flat
+}