25 "git.arvados.org/arvados.git/sdk/go/arvados"
28 type importer struct {
37 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41 fmt.Fprintf(stderr, "%s\n", err)
44 flags := flag.NewFlagSet("", flag.ContinueOnError)
45 flags.SetOutput(stderr)
46 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
47 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
48 flags.StringVar(&cmd.outputFile, "o", "", "output `file`")
49 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for storing intermediate and output data")
50 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
51 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
52 err = flags.Parse(args)
53 if err == flag.ErrHelp {
56 } else if err != nil {
58 } else if cmd.tagLibraryFile == "" {
59 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
61 } else if flags.NArg() == 0 {
68 log.Println(http.ListenAndServe(*pprof, nil))
73 runner := arvadosContainerRunner{
74 Name: "lightning import",
75 Client: arvados.NewClientFromEnv(),
76 ProjectUUID: cmd.projectUUID,
78 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
82 inputs := flags.Args()
83 for i := range inputs {
84 err = runner.TranslatePaths(&inputs[i])
89 if cmd.outputFile == "" {
90 cmd.outputFile = "/mnt/output/library.gob"
92 // Not yet implemented, but this should write
93 // the collection to an existing collection,
94 // possibly even an in-place update.
95 err = errors.New("cannot specify output file in container mode: not implemented")
98 runner.Args = append([]string{"import", "-local=true", "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
106 infiles, err := listInputFiles(flags.Args())
111 tilelib, err := cmd.loadTileLibrary()
116 for range time.Tick(10 * time.Second) {
117 log.Printf("tilelib.Len() == %d", tilelib.Len())
123 if cmd.outputFile == "" {
124 w = bufio.NewWriter(stdout)
126 outfile, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
130 defer outfile.Close()
131 w = bufio.NewWriter(outfile)
133 cmd.encoder = gob.NewEncoder(w)
135 err = cmd.tileInputs(tilelib, infiles)
144 err = outfile.Close()
152 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
153 var input io.ReadCloser
154 input, err := os.Open(infile)
159 if strings.HasSuffix(infile, ".gz") {
160 input, err = gzip.NewReader(input)
166 return tilelib.TileFasta(infile, input)
169 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
170 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
171 f, err := os.Open(cmd.tagLibraryFile)
176 var rdr io.ReadCloser = f
177 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
178 rdr, err = gzip.NewReader(f)
180 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
184 var taglib tagLibrary
185 err = taglib.Load(rdr)
189 if taglib.Len() < 1 {
190 return nil, fmt.Errorf("cannot tile: tag library is empty")
192 log.Printf("tag library %s load done", cmd.tagLibraryFile)
193 return &tileLibrary{taglib: &taglib}, nil
196 func listInputFiles(paths []string) (files []string, err error) {
197 for _, path := range paths {
198 if fi, err := os.Stat(path); err != nil {
199 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
200 } else if !fi.IsDir() {
201 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
202 files = append(files, path)
206 d, err := os.Open(path)
208 return nil, fmt.Errorf("%s: open failed: %s", path, err)
211 names, err := d.Readdirnames(0)
213 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
216 for _, name := range names {
217 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
218 files = append(files, filepath.Join(path, name))
219 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
220 files = append(files, filepath.Join(path, name))
225 for _, file := range files {
226 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
228 } else if _, err := os.Stat(file + ".csi"); err == nil {
230 } else if _, err = os.Stat(file + ".tbi"); err == nil {
233 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
239 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
240 starttime := time.Now()
241 errs := make(chan error, 1)
242 todo := make(chan func() error, len(infiles)*2)
243 var encodeJobs sync.WaitGroup
244 for _, infile := range infiles {
246 var phases sync.WaitGroup
248 variants := make([][]tileVariantID, 2)
249 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
250 todo <- func() error {
252 log.Printf("%s starting", infile)
253 defer log.Printf("%s done", infile)
254 tseqs, err := cmd.tileFasta(tilelib, infile)
255 variants[0] = tseqs.Variants()
258 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
259 todo <- func() error {
261 log.Printf("%s starting", infile2)
262 defer log.Printf("%s done", infile2)
263 tseqs, err := cmd.tileFasta(tilelib, infile2)
264 variants[1] = tseqs.Variants()
268 for phase := 0; phase < 2; phase++ {
270 todo <- func() error {
272 log.Printf("%s phase %d starting", infile, phase+1)
273 defer log.Printf("%s phase %d done", infile, phase+1)
274 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
275 variants[phase] = tseqs.Variants()
282 defer encodeJobs.Done()
287 ntags := len(variants[0])
288 if ntags < len(variants[1]) {
289 ntags = len(variants[1])
291 flat := make([]tileVariantID, ntags*2)
292 for i := 0; i < ntags; i++ {
293 flat[i*2] = variants[0][i]
294 flat[i*2+1] = variants[1][i]
296 err := cmd.encoder.Encode(LibraryEntry{
297 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
308 var tileJobs sync.WaitGroup
309 running := int64(runtime.NumCPU())
310 for i := 0; i < runtime.NumCPU(); i++ {
313 defer tileJobs.Done()
314 defer atomic.AddInt64(&running, -1)
315 for fn := range todo {
326 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
327 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
328 eta := time.Now().Add(ttl)
329 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
339 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
340 if cmd.refFile == "" {
341 err = errors.New("cannot import vcf: reference data (-ref) not specified")
344 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
345 indexsuffix := ".tbi"
346 if _, err := os.Stat(infile + ".csi"); err == nil {
349 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
350 args = append([]string{
351 "docker", "run", "--rm",
353 "--volume=" + infile + ":" + infile + ":ro",
354 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
355 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
359 consensus := exec.Command(args[0], args[1:]...)
360 consensus.Stderr = os.Stderr
361 stdout, err := consensus.StdoutPipe()
366 err = consensus.Start()
370 defer consensus.Wait()
371 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
379 err = consensus.Wait()
381 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)