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 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...)
108 infiles, err := listInputFiles(flags.Args())
113 tilelib, err := cmd.loadTileLibrary()
118 for range time.Tick(10 * time.Second) {
119 log.Printf("tilelib.Len() == %d", tilelib.Len())
123 var output io.WriteCloser
124 if cmd.outputFile == "" {
125 output = nopCloser{stdout}
127 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
133 bufw := bufio.NewWriter(output)
134 cmd.encoder = gob.NewEncoder(bufw)
136 err = cmd.tileInputs(tilelib, infiles)
151 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
152 var input io.ReadCloser
153 input, err := os.Open(infile)
158 if strings.HasSuffix(infile, ".gz") {
159 input, err = gzip.NewReader(input)
165 return tilelib.TileFasta(infile, input)
168 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
169 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
170 f, err := os.Open(cmd.tagLibraryFile)
175 var rdr io.ReadCloser = f
176 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
177 rdr, err = gzip.NewReader(f)
179 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
183 var taglib tagLibrary
184 err = taglib.Load(rdr)
188 if taglib.Len() < 1 {
189 return nil, fmt.Errorf("cannot tile: tag library is empty")
191 log.Printf("tag library %s load done", cmd.tagLibraryFile)
192 return &tileLibrary{taglib: &taglib}, nil
195 func listInputFiles(paths []string) (files []string, err error) {
196 for _, path := range paths {
197 if fi, err := os.Stat(path); err != nil {
198 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
199 } else if !fi.IsDir() {
200 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
201 files = append(files, path)
205 d, err := os.Open(path)
207 return nil, fmt.Errorf("%s: open failed: %s", path, err)
210 names, err := d.Readdirnames(0)
212 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
215 for _, name := range names {
216 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
217 files = append(files, filepath.Join(path, name))
218 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
219 files = append(files, filepath.Join(path, name))
224 for _, file := range files {
225 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
227 } else if _, err := os.Stat(file + ".csi"); err == nil {
229 } else if _, err = os.Stat(file + ".tbi"); err == nil {
232 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
238 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
239 starttime := time.Now()
240 errs := make(chan error, 1)
241 todo := make(chan func() error, len(infiles)*2)
242 var encodeJobs sync.WaitGroup
243 for _, infile := range infiles {
245 var phases sync.WaitGroup
247 variants := make([][]tileVariantID, 2)
248 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
249 todo <- func() error {
251 log.Printf("%s starting", infile)
252 defer log.Printf("%s done", infile)
253 tseqs, err := cmd.tileFasta(tilelib, infile)
254 variants[0] = tseqs.Variants()
257 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
258 todo <- func() error {
260 log.Printf("%s starting", infile2)
261 defer log.Printf("%s done", infile2)
262 tseqs, err := cmd.tileFasta(tilelib, infile2)
263 variants[1] = tseqs.Variants()
267 for phase := 0; phase < 2; phase++ {
269 todo <- func() error {
271 log.Printf("%s phase %d starting", infile, phase+1)
272 defer log.Printf("%s phase %d done", infile, phase+1)
273 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
274 variants[phase] = tseqs.Variants()
281 defer encodeJobs.Done()
286 ntags := len(variants[0])
287 if ntags < len(variants[1]) {
288 ntags = len(variants[1])
290 flat := make([]tileVariantID, ntags*2)
291 for i := 0; i < ntags; i++ {
292 flat[i*2] = variants[0][i]
293 flat[i*2+1] = variants[1][i]
295 err := cmd.encoder.Encode(LibraryEntry{
296 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
307 var tileJobs sync.WaitGroup
308 running := int64(runtime.NumCPU())
309 for i := 0; i < runtime.NumCPU(); i++ {
312 defer tileJobs.Done()
313 defer atomic.AddInt64(&running, -1)
314 for fn := range todo {
325 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
326 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
327 eta := time.Now().Add(ttl)
328 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
338 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
339 if cmd.refFile == "" {
340 err = errors.New("cannot import vcf: reference data (-ref) not specified")
343 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
344 indexsuffix := ".tbi"
345 if _, err := os.Stat(infile + ".csi"); err == nil {
348 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
349 args = append([]string{
350 "docker", "run", "--rm",
352 "--volume=" + infile + ":" + infile + ":ro",
353 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
354 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
358 consensus := exec.Command(args[0], args[1:]...)
359 consensus.Stderr = os.Stderr
360 stdout, err := consensus.StdoutPipe()
365 err = consensus.Start()
369 defer consensus.Wait()
370 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
378 err = consensus.Wait()
380 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)