26 type importer struct {
32 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
36 fmt.Fprintf(stderr, "%s\n", err)
39 flags := flag.NewFlagSet("", flag.ContinueOnError)
40 flags.SetOutput(stderr)
41 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
42 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
43 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
44 err = flags.Parse(args)
45 if err == flag.ErrHelp {
48 } else if err != nil {
50 } else if cmd.tagLibraryFile == "" {
51 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
53 } else if flags.NArg() == 0 {
60 log.Println(http.ListenAndServe(*pprof, nil))
64 infiles, err := listInputFiles(flags.Args())
69 tilelib, err := cmd.loadTileLibrary()
74 for range time.Tick(10 * time.Second) {
75 log.Printf("tilelib.Len() == %d", tilelib.Len())
78 w := bufio.NewWriter(stdout)
79 cmd.encoder = gob.NewEncoder(w)
80 err = cmd.tileInputs(tilelib, infiles)
91 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
92 var input io.ReadCloser
93 input, err := os.Open(infile)
98 if strings.HasSuffix(infile, ".gz") {
99 input, err = gzip.NewReader(input)
105 return tilelib.TileFasta(infile, input)
108 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
109 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
110 f, err := os.Open(cmd.tagLibraryFile)
115 var rdr io.ReadCloser = f
116 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
117 rdr, err = gzip.NewReader(f)
119 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
123 var taglib tagLibrary
124 err = taglib.Load(rdr)
128 if taglib.Len() < 1 {
129 return nil, fmt.Errorf("cannot tile: tag library is empty")
131 log.Printf("tag library %s load done", cmd.tagLibraryFile)
132 return &tileLibrary{taglib: &taglib}, nil
135 func listInputFiles(paths []string) (files []string, err error) {
136 for _, path := range paths {
137 if fi, err := os.Stat(path); err != nil {
138 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
139 } else if !fi.IsDir() {
140 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
141 files = append(files, path)
145 d, err := os.Open(path)
147 return nil, fmt.Errorf("%s: open failed: %s", path, err)
150 names, err := d.Readdirnames(0)
152 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
155 for _, name := range names {
156 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
157 files = append(files, filepath.Join(path, name))
158 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
159 files = append(files, filepath.Join(path, name))
164 for _, file := range files {
165 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
167 } else if _, err := os.Stat(file + ".csi"); err == nil {
169 } else if _, err = os.Stat(file + ".tbi"); err == nil {
172 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
178 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
179 starttime := time.Now()
180 errs := make(chan error, 1)
181 todo := make(chan func() error, len(infiles)*2)
182 var encodeJobs sync.WaitGroup
183 for _, infile := range infiles {
185 var phases sync.WaitGroup
187 variants := make([][]tileVariantID, 2)
188 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
189 todo <- func() error {
191 log.Printf("%s starting", infile)
192 defer log.Printf("%s done", infile)
193 tseqs, err := cmd.tileFasta(tilelib, infile)
194 variants[0] = tseqs.Variants()
197 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
198 todo <- func() error {
200 log.Printf("%s starting", infile2)
201 defer log.Printf("%s done", infile2)
202 tseqs, err := cmd.tileFasta(tilelib, infile2)
203 variants[1] = tseqs.Variants()
207 for phase := 0; phase < 2; phase++ {
209 todo <- func() error {
211 log.Printf("%s phase %d starting", infile, phase+1)
212 defer log.Printf("%s phase %d done", infile, phase+1)
213 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
214 variants[phase] = tseqs.Variants()
221 defer encodeJobs.Done()
226 ntags := len(variants[0])
227 if ntags < len(variants[1]) {
228 ntags = len(variants[1])
230 flat := make([]tileVariantID, ntags*2)
231 for i := 0; i < ntags; i++ {
232 flat[i*2] = variants[0][i]
233 flat[i*2+1] = variants[1][i]
235 err := cmd.encoder.Encode(LibraryEntry{
236 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
247 var tileJobs sync.WaitGroup
248 running := int64(runtime.NumCPU())
249 for i := 0; i < runtime.NumCPU(); i++ {
252 defer tileJobs.Done()
253 defer atomic.AddInt64(&running, -1)
254 for fn := range todo {
265 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
266 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
267 eta := time.Now().Add(ttl)
268 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
278 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
279 if cmd.refFile == "" {
280 err = errors.New("cannot import vcf: reference data (-ref) not specified")
283 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
284 indexsuffix := ".tbi"
285 if _, err := os.Stat(infile + ".csi"); err == nil {
288 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
289 args = append([]string{
290 "docker", "run", "--rm",
292 "--volume=" + infile + ":" + infile + ":ro",
293 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
294 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
298 consensus := exec.Command(args[0], args[1:]...)
299 consensus.Stderr = os.Stderr
300 stdout, err := consensus.StdoutPipe()
305 err = consensus.Start()
309 defer consensus.Wait()
310 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
318 err = consensus.Wait()
320 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)