24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
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 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,
80 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
84 inputs := flags.Args()
85 for i := range inputs {
86 err = runner.TranslatePaths(&inputs[i])
91 if cmd.outputFile == "-" {
92 cmd.outputFile = "/mnt/output/library.gob"
94 // Not yet implemented, but this should write
95 // the collection to an existing collection,
96 // possibly even an in-place update.
97 err = errors.New("cannot specify output file in container mode: not implemented")
100 runner.Args = append([]string{"import", "-local=true", "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
102 output, err = runner.Run()
106 fmt.Fprintln(stdout, output+"/library.gob")
110 infiles, err := listInputFiles(flags.Args())
115 tilelib, err := cmd.loadTileLibrary()
120 for range time.Tick(10 * time.Minute) {
121 log.Printf("tilelib.Len() == %d", tilelib.Len())
125 var output io.WriteCloser
126 if cmd.outputFile == "-" {
127 output = nopCloser{stdout}
129 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
135 bufw := bufio.NewWriter(output)
136 cmd.encoder = gob.NewEncoder(bufw)
138 err = cmd.tileInputs(tilelib, infiles)
153 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
154 var input io.ReadCloser
155 input, err := os.Open(infile)
160 if strings.HasSuffix(infile, ".gz") {
161 input, err = gzip.NewReader(input)
167 return tilelib.TileFasta(infile, input)
170 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
171 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
172 f, err := os.Open(cmd.tagLibraryFile)
177 var rdr io.ReadCloser = f
178 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
179 rdr, err = gzip.NewReader(f)
181 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
185 var taglib tagLibrary
186 err = taglib.Load(rdr)
190 if taglib.Len() < 1 {
191 return nil, fmt.Errorf("cannot tile: tag library is empty")
193 log.Printf("tag library %s load done", cmd.tagLibraryFile)
194 return &tileLibrary{taglib: &taglib}, nil
197 func listInputFiles(paths []string) (files []string, err error) {
198 for _, path := range paths {
199 if fi, err := os.Stat(path); err != nil {
200 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
201 } else if !fi.IsDir() {
202 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
203 files = append(files, path)
207 d, err := os.Open(path)
209 return nil, fmt.Errorf("%s: open failed: %s", path, err)
212 names, err := d.Readdirnames(0)
214 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
217 for _, name := range names {
218 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
219 files = append(files, filepath.Join(path, name))
220 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
221 files = append(files, filepath.Join(path, name))
226 for _, file := range files {
227 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
229 } else if _, err := os.Stat(file + ".csi"); err == nil {
231 } else if _, err = os.Stat(file + ".tbi"); err == nil {
234 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
240 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
241 starttime := time.Now()
242 errs := make(chan error, 1)
243 todo := make(chan func() error, len(infiles)*2)
244 var encodeJobs sync.WaitGroup
245 for _, infile := range infiles {
247 var phases sync.WaitGroup
249 variants := make([][]tileVariantID, 2)
250 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
251 todo <- func() error {
253 log.Printf("%s starting", infile)
254 defer log.Printf("%s done", infile)
255 tseqs, err := cmd.tileFasta(tilelib, infile)
256 variants[0] = tseqs.Variants()
259 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
260 todo <- func() error {
262 log.Printf("%s starting", infile2)
263 defer log.Printf("%s done", infile2)
264 tseqs, err := cmd.tileFasta(tilelib, infile2)
265 variants[1] = tseqs.Variants()
269 for phase := 0; phase < 2; phase++ {
271 todo <- func() error {
273 log.Printf("%s phase %d starting", infile, phase+1)
274 defer log.Printf("%s phase %d done", infile, phase+1)
275 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
276 variants[phase] = tseqs.Variants()
283 defer encodeJobs.Done()
288 ntags := len(variants[0])
289 if ntags < len(variants[1]) {
290 ntags = len(variants[1])
292 flat := make([]tileVariantID, ntags*2)
293 for i := 0; i < ntags; i++ {
294 flat[i*2] = variants[0][i]
295 flat[i*2+1] = variants[1][i]
297 err := cmd.encoder.Encode(LibraryEntry{
298 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
309 var tileJobs sync.WaitGroup
311 for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
313 atomic.AddInt64(&running, 1)
315 defer tileJobs.Done()
316 defer atomic.AddInt64(&running, -1)
317 for fn := range todo {
328 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
329 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
330 eta := time.Now().Add(ttl)
331 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
341 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
342 if cmd.refFile == "" {
343 err = errors.New("cannot import vcf: reference data (-ref) not specified")
346 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
347 indexsuffix := ".tbi"
348 if _, err := os.Stat(infile + ".csi"); err == nil {
351 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
352 args = append([]string{
353 "docker", "run", "--rm",
355 "--volume=" + infile + ":" + infile + ":ro",
356 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
357 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
361 consensus := exec.Command(args[0], args[1:]...)
362 consensus.Stderr = os.Stderr
363 stdout, err := consensus.StdoutPipe()
368 err = consensus.Start()
372 defer consensus.Wait()
373 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
381 err = consensus.Wait()
383 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)