24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
28 type importer struct {
40 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
44 fmt.Fprintf(stderr, "%s\n", err)
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 {
64 } else if err != nil {
66 } else if cmd.tagLibraryFile == "" {
67 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
69 } else if flags.NArg() == 0 {
76 log.Println(http.ListenAndServe(*pprof, nil))
80 lvl, err := log.ParseLevel(*loglevel)
87 runner := arvadosContainerRunner{
88 Name: "lightning import",
89 Client: arvados.NewClientFromEnv(),
90 ProjectUUID: cmd.projectUUID,
95 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
99 inputs := flags.Args()
100 for i := range inputs {
101 err = runner.TranslatePaths(&inputs[i])
106 if cmd.outputFile == "-" {
107 cmd.outputFile = "/mnt/output/library.gob"
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")
115 runner.Args = append([]string{"import",
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,
123 "-o", cmd.outputFile,
126 output, err = runner.Run()
130 fmt.Fprintln(stdout, output+"/library.gob")
134 infiles, err := listInputFiles(flags.Args())
139 taglib, err := cmd.loadTagLibrary()
144 var output io.WriteCloser
145 if cmd.outputFile == "-" {
146 output = nopCloser{stdout}
148 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
154 bufw := bufio.NewWriter(output)
155 cmd.encoder = gob.NewEncoder(bufw)
157 tilelib := &tileLibrary{taglib: taglib, includeNoCalls: cmd.includeNoCalls, skipOOO: cmd.skipOOO}
159 cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
160 tilelib.encoder = cmd.encoder
163 for range time.Tick(10 * time.Minute) {
164 log.Printf("tilelib.Len() == %d", tilelib.Len())
168 err = cmd.tileInputs(tilelib, infiles)
183 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
184 var input io.ReadCloser
185 input, err := os.Open(infile)
190 if strings.HasSuffix(infile, ".gz") {
191 input, err = gzip.NewReader(input)
197 return tilelib.TileFasta(infile, input)
200 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
201 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
202 f, err := os.Open(cmd.tagLibraryFile)
207 var rdr io.ReadCloser = f
208 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
209 rdr, err = gzip.NewReader(f)
211 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
215 var taglib tagLibrary
216 err = taglib.Load(rdr)
220 if taglib.Len() < 1 {
221 return nil, fmt.Errorf("cannot tile: tag library is empty")
223 log.Printf("tag library %s load done", cmd.tagLibraryFile)
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)
237 d, err := os.Open(path)
239 return nil, fmt.Errorf("%s: open failed: %s", path, err)
242 names, err := d.Readdirnames(0)
244 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
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))
256 for _, file := range files {
257 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
259 } else if _, err := os.Stat(file + ".csi"); err == nil {
261 } else if _, err = os.Stat(file + ".tbi"); err == nil {
264 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
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 {
277 var phases sync.WaitGroup
279 variants := make([][]tileVariantID, 2)
280 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
281 todo <- func() error {
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)
291 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
292 todo <- func() error {
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)
303 for phase := 0; phase < 2; phase++ {
305 todo <- func() error {
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)
319 defer encodeJobs.Done()
324 ntags := len(variants[0])
325 if ntags < len(variants[1]) {
326 ntags = len(variants[1])
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]
336 err := cmd.encoder.Encode(LibraryEntry{
337 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
348 var tileJobs sync.WaitGroup
350 for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
352 atomic.AddInt64(&running, 1)
354 defer tileJobs.Done()
355 defer atomic.AddInt64(&running, -1)
356 for fn := range todo {
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)
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")
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 {
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",
394 "--volume=" + infile + ":" + infile + ":ro",
395 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
396 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
400 consensus := exec.Command(args[0], args[1:]...)
401 consensus.Stderr = os.Stderr
402 stdout, err := consensus.StdoutPipe()
407 err = consensus.Start()
411 defer consensus.Wait()
412 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
420 err = consensus.Wait()
422 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)