24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
28 type importer struct {
38 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
42 fmt.Fprintf(stderr, "%s\n", err)
45 flags := flag.NewFlagSet("", flag.ContinueOnError)
46 flags.SetOutput(stderr)
47 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
48 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
49 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
50 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
51 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
52 flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
53 priority := flags.Int("priority", 500, "container request priority")
54 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
55 loglevel := flags.String("loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
56 err = flags.Parse(args)
57 if err == flag.ErrHelp {
60 } else if err != nil {
62 } else if cmd.tagLibraryFile == "" {
63 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
65 } else if flags.NArg() == 0 {
72 log.Println(http.ListenAndServe(*pprof, nil))
76 lvl, err := log.ParseLevel(*loglevel)
83 runner := arvadosContainerRunner{
84 Name: "lightning import",
85 Client: arvados.NewClientFromEnv(),
86 ProjectUUID: cmd.projectUUID,
91 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
95 inputs := flags.Args()
96 for i := range inputs {
97 err = runner.TranslatePaths(&inputs[i])
102 if cmd.outputFile == "-" {
103 cmd.outputFile = "/mnt/output/library.gob"
105 // Not yet implemented, but this should write
106 // the collection to an existing collection,
107 // possibly even an in-place update.
108 err = errors.New("cannot specify output file in container mode: not implemented")
111 runner.Args = append([]string{"import", "-local=true", "-loglevel=" + *loglevel, fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO), "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
113 output, err = runner.Run()
117 fmt.Fprintln(stdout, output+"/library.gob")
121 infiles, err := listInputFiles(flags.Args())
126 tilelib, err := cmd.loadTileLibrary()
131 for range time.Tick(10 * time.Minute) {
132 log.Printf("tilelib.Len() == %d", tilelib.Len())
136 var output io.WriteCloser
137 if cmd.outputFile == "-" {
138 output = nopCloser{stdout}
140 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
146 bufw := bufio.NewWriter(output)
147 cmd.encoder = gob.NewEncoder(bufw)
149 err = cmd.tileInputs(tilelib, infiles)
164 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
165 var input io.ReadCloser
166 input, err := os.Open(infile)
171 if strings.HasSuffix(infile, ".gz") {
172 input, err = gzip.NewReader(input)
178 return tilelib.TileFasta(infile, input)
181 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
182 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
183 f, err := os.Open(cmd.tagLibraryFile)
188 var rdr io.ReadCloser = f
189 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
190 rdr, err = gzip.NewReader(f)
192 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
196 var taglib tagLibrary
197 err = taglib.Load(rdr)
201 if taglib.Len() < 1 {
202 return nil, fmt.Errorf("cannot tile: tag library is empty")
204 log.Printf("tag library %s load done", cmd.tagLibraryFile)
205 return &tileLibrary{taglib: &taglib, skipOOO: cmd.skipOOO}, nil
208 func listInputFiles(paths []string) (files []string, err error) {
209 for _, path := range paths {
210 if fi, err := os.Stat(path); err != nil {
211 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
212 } else if !fi.IsDir() {
213 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
214 files = append(files, path)
218 d, err := os.Open(path)
220 return nil, fmt.Errorf("%s: open failed: %s", path, err)
223 names, err := d.Readdirnames(0)
225 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
228 for _, name := range names {
229 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
230 files = append(files, filepath.Join(path, name))
231 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
232 files = append(files, filepath.Join(path, name))
237 for _, file := range files {
238 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
240 } else if _, err := os.Stat(file + ".csi"); err == nil {
242 } else if _, err = os.Stat(file + ".tbi"); err == nil {
245 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
251 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
252 starttime := time.Now()
253 errs := make(chan error, 1)
254 todo := make(chan func() error, len(infiles)*2)
255 var encodeJobs sync.WaitGroup
256 for _, infile := range infiles {
258 var phases sync.WaitGroup
260 variants := make([][]tileVariantID, 2)
261 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
262 todo <- func() error {
264 log.Printf("%s starting", infile)
265 defer log.Printf("%s done", infile)
266 tseqs, err := cmd.tileFasta(tilelib, infile)
267 var kept, dropped int
268 variants[0], kept, dropped = tseqs.Variants()
269 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
272 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
273 todo <- func() error {
275 log.Printf("%s starting", infile2)
276 defer log.Printf("%s done", infile2)
277 tseqs, err := cmd.tileFasta(tilelib, infile2)
278 var kept, dropped int
279 variants[1], kept, dropped = tseqs.Variants()
280 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
284 for phase := 0; phase < 2; phase++ {
286 todo <- func() error {
288 log.Printf("%s phase %d starting", infile, phase+1)
289 defer log.Printf("%s phase %d done", infile, phase+1)
290 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
291 var kept, dropped int
292 variants[phase], kept, dropped = tseqs.Variants()
293 log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
300 defer encodeJobs.Done()
305 ntags := len(variants[0])
306 if ntags < len(variants[1]) {
307 ntags = len(variants[1])
309 flat := make([]tileVariantID, ntags*2)
310 for i := 0; i < ntags; i++ {
311 for hap := 0; hap < 2; hap++ {
312 if i < len(variants[hap]) {
313 flat[i*2+hap] = variants[hap][i]
317 err := cmd.encoder.Encode(LibraryEntry{
318 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
329 var tileJobs sync.WaitGroup
331 for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
333 atomic.AddInt64(&running, 1)
335 defer tileJobs.Done()
336 defer atomic.AddInt64(&running, -1)
337 for fn := range todo {
348 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
349 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
350 eta := time.Now().Add(ttl)
351 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
361 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
362 if cmd.refFile == "" {
363 err = errors.New("cannot import vcf: reference data (-ref) not specified")
366 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
367 indexsuffix := ".tbi"
368 if _, err := os.Stat(infile + ".csi"); err == nil {
371 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
372 args = append([]string{
373 "docker", "run", "--rm",
375 "--volume=" + infile + ":" + infile + ":ro",
376 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
377 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
381 consensus := exec.Command(args[0], args[1:]...)
382 consensus.Stderr = os.Stderr
383 stdout, err := consensus.StdoutPipe()
388 err = consensus.Start()
392 defer consensus.Wait()
393 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
401 err = consensus.Wait()
403 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)