1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
26 "golang.org/x/crypto/blake2b"
32 selectedTags map[tagID]bool
35 func (cmd *dump) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
36 err := cmd.run(prog, args, stdin, stdout, stderr)
43 func (cmd *dump) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
44 flags := flag.NewFlagSet("", flag.ContinueOnError)
45 flags.SetOutput(stderr)
46 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
47 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
48 projectUUID := flags.String("project", "", "project `UUID` for output data")
49 priority := flags.Int("priority", 500, "container request priority")
50 inputDir := flags.String("input-dir", "./in", "input `directory`")
51 outputDir := flags.String("output-dir", "./out", "output `directory`")
52 ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
53 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
54 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
55 selectedTags := flags.String("tags", "", "tag numbers to dump")
56 cmd.filter.Flags(flags)
57 err := flags.Parse(args)
58 if err == flag.ErrHelp {
60 } else if err != nil {
62 } else if flags.NArg() > 0 {
63 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
68 log.Println(http.ListenAndServe(*pprof, nil))
73 runner := arvadosContainerRunner{
74 Name: "lightning slice-numpy",
75 Client: arvados.NewClientFromEnv(),
76 ProjectUUID: *projectUUID,
83 err = runner.TranslatePaths(inputDir, regionsFilename)
87 runner.Args = []string{"dump", "-local=true",
89 "-input-dir=" + *inputDir,
90 "-output-dir=/mnt/output",
91 "-regions=" + *regionsFilename,
92 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
93 "-tags=" + *selectedTags,
95 runner.Args = append(runner.Args, cmd.filter.Args()...)
96 output, err := runner.Run()
100 fmt.Fprintln(stdout, output)
104 if *selectedTags != "" {
105 cmd.selectedTags = map[tagID]bool{}
106 for _, tagstr := range strings.Split(*selectedTags, ",") {
107 tag, err := strconv.ParseInt(tagstr, 10, 64)
111 cmd.selectedTags[tagID(tag)] = true
115 infiles, err := allFiles(*inputDir, matchGobFile)
119 if len(infiles) == 0 {
120 return fmt.Errorf("no input files found in %s", *inputDir)
122 sort.Strings(infiles)
124 var refseq map[string][]tileLibRef
125 var reftiledata = make(map[tileLibRef][]byte, 11000000)
126 in0, err := open(infiles[0])
131 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
133 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
139 DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
140 if len(ent.TagSet) > 0 {
141 taglen = len(ent.TagSet[0])
143 for _, cseq := range ent.CompactSequences {
144 if cseq.Name == *ref || *ref == "" {
145 refseq = cseq.TileSequences
148 for _, cg := range ent.CompactGenomes {
149 if matchGenome.MatchString(cg.Name) {
150 cmd.cgnames = append(cmd.cgnames, cg.Name)
153 for _, tv := range ent.TileVariants {
155 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
165 return fmt.Errorf("%s: reference sequence not found", infiles[0])
168 return fmt.Errorf("tagset not found")
170 if len(cmd.cgnames) == 0 {
171 return fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
173 sort.Strings(cmd.cgnames)
175 log.Info("indexing reference tiles")
176 type reftileinfo struct {
177 variant tileVariantID
178 seqname string // chr1
179 pos int // distance from start of chromosome to starttag
180 tiledata []byte // acgtggcaa...
182 isdup := map[tagID]bool{}
183 reftile := map[tagID]*reftileinfo{}
184 for seqname, cseq := range refseq {
186 for _, libref := range cseq {
187 tiledata := reftiledata[libref]
188 if len(tiledata) == 0 {
189 return fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
191 if isdup[libref.Tag] {
192 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
193 } else if reftile[libref.Tag] != nil {
194 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", tileLibRef{Tag: libref.Tag, Variant: reftile[libref.Tag].variant}, reftile[libref.Tag].seqname, reftile[libref.Tag].pos)
195 delete(reftile, libref.Tag)
196 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
197 isdup[libref.Tag] = true
199 reftile[libref.Tag] = &reftileinfo{
201 variant: libref.Variant,
206 pos += len(tiledata) - taglen
208 log.Printf("... %s done, len %d", seqname, pos+taglen)
212 if *regionsFilename != "" {
213 log.Printf("loading regions from %s", *regionsFilename)
214 mask, err = makeMask(*regionsFilename, *expandRegions)
218 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
219 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
220 for tag, rt := range reftile {
221 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
225 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
228 if cmd.selectedTags != nil {
229 log.Printf("deleting reftile entries other than %d selected tags", len(cmd.selectedTags))
230 for tag := range reftile {
231 if !cmd.selectedTags[tag] {
235 log.Printf("after applying selected tags, len(reftile) == %d", len(reftile))
238 dumpVariantsName := fmt.Sprintf("%s/variants.csv", *outputDir)
239 log.Infof("writing %s", dumpVariantsName)
240 dumpVariantsF, err := os.Create(dumpVariantsName)
244 dumpVariantsW := bufio.NewWriterSize(dumpVariantsF, 1<<20)
247 throttleMem := throttle{Max: runtime.GOMAXPROCS(0)}
248 log.Infof("reading %d slices with max concurrency %d", len(infiles), throttleMem.Max)
250 for infileIdx, infile := range infiles {
251 infileIdx, infile := infileIdx, infile
252 throttleMem.Go(func() error {
253 seq := make(map[tagID][]TileVariant, 50000)
254 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
255 f, err := open(infile)
260 log.Infof("%04d: reading %s", infileIdx, infile)
261 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
262 for _, tv := range ent.TileVariants {
266 if mask != nil && reftile[tv.Tag] == nil {
272 variants := seq[tv.Tag]
273 if len(variants) == 0 {
274 variants = make([]TileVariant, 100)
276 for len(variants) <= int(tv.Variant) {
277 variants = append(variants, TileVariant{})
279 variants[int(tv.Variant)] = tv
280 seq[tv.Tag] = variants
282 for _, cg := range ent.CompactGenomes {
283 if !matchGenome.MatchString(cg.Name) {
286 // pad to full slice size
287 // to avoid out-of-bounds
289 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
290 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
299 tagstart := cgs[cmd.cgnames[0]].StartTag
300 tagend := cgs[cmd.cgnames[0]].EndTag
304 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
305 variantRemap := make([][]tileVariantID, tagend-tagstart)
306 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
307 for tag, variants := range seq {
308 tag, variants := tag, variants
309 throttleCPU.Go(func() error {
310 count := make(map[[blake2b.Size256]byte]int, len(variants))
313 var rthash [blake2b.Size256]byte
315 rthash = blake2b.Sum256(rt.tiledata)
319 for _, cg := range cgs {
320 idx := int(tag-tagstart) * 2
321 for allele := 0; allele < 2; allele++ {
322 v := cg.Variants[idx+allele]
323 if v > 0 && len(variants[v].Sequence) > 0 {
324 count[variants[v].Blake2b]++
328 // hash[i] will be the hash of
329 // the variant(s) that should
330 // be at rank i (0-based).
331 hash := make([][blake2b.Size256]byte, 0, len(count))
332 for b := range count {
333 hash = append(hash, b)
335 sort.Slice(hash, func(i, j int) bool {
336 bi, bj := &hash[i], &hash[j]
337 if ci, cj := count[*bi], count[*bj]; ci != cj {
340 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
343 // rank[b] will be the 1-based
344 // new variant number for
345 // variants whose hash is b.
346 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
347 for i, h := range hash {
348 rank[h] = tileVariantID(i + 1)
350 // remap[v] will be the new
351 // variant number for original
353 remap := make([]tileVariantID, len(variants))
354 for i, tv := range variants {
355 remap[i] = rank[tv.Blake2b]
357 variantRemap[tag-tagstart] = remap
359 rt.variant = rank[rthash]
366 for tag := tagstart; tag < tagend; tag++ {
367 rt, ok := reftile[tag]
369 // Excluded by specified
370 // regions, or reference does
371 // not use any variant of this
372 // tile. (TODO: log this?
373 // mention it in annotations?)
376 remap := variantRemap[tag-tagstart]
377 maxv := tileVariantID(0)
378 for _, v := range remap {
386 fmt.Fprintf(dumpVariantsW, "%d,%d,1,%s,%d,%s\n", tag, rt.variant, rt.seqname, rt.pos+1, bytes.ToUpper(rt.tiledata))
389 done := make([]bool, maxv+1)
390 for v, tv := range variants {
392 if v == 0 || v == rt.variant || done[v] {
398 fmt.Fprintf(dumpVariantsW, "%d,%d,0,%s,%d,%s\n", tag, v, rt.seqname, rt.pos+1, bytes.ToUpper(tv.Sequence))
402 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
406 if err = throttleMem.Wait(); err != nil {
409 err = dumpVariantsW.Flush()
413 err = dumpVariantsF.Close()