Merge branch 'main' into 19868-pca-in-ml
[lightning.git] / dump.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "bufio"
9         "bytes"
10         "flag"
11         "fmt"
12         "io"
13         "net/http"
14         _ "net/http/pprof"
15         "os"
16         "regexp"
17         "runtime"
18         "sort"
19         "strconv"
20         "strings"
21         "sync"
22         "sync/atomic"
23
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         log "github.com/sirupsen/logrus"
26         "golang.org/x/crypto/blake2b"
27 )
28
29 type dump struct {
30         filter       filter
31         cgnames      []string
32         selectedTags map[tagID]bool
33 }
34
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)
37         if err != nil {
38                 return 1
39         }
40         return 0
41 }
42
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 {
59                 return nil
60         } else if err != nil {
61                 return err
62         } else if flags.NArg() > 0 {
63                 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
64         }
65
66         if *pprof != "" {
67                 go func() {
68                         log.Println(http.ListenAndServe(*pprof, nil))
69                 }()
70         }
71
72         if !*runlocal {
73                 runner := arvadosContainerRunner{
74                         Name:        "lightning slice-numpy",
75                         Client:      arvados.NewClientFromEnv(),
76                         ProjectUUID: *projectUUID,
77                         RAM:         750000000000,
78                         VCPUs:       96,
79                         Priority:    *priority,
80                         KeepCache:   2,
81                         APIAccess:   true,
82                 }
83                 err = runner.TranslatePaths(inputDir, regionsFilename)
84                 if err != nil {
85                         return err
86                 }
87                 runner.Args = []string{"dump", "-local=true",
88                         "-pprof=:6060",
89                         "-input-dir=" + *inputDir,
90                         "-output-dir=/mnt/output",
91                         "-regions=" + *regionsFilename,
92                         "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
93                         "-tags=" + *selectedTags,
94                 }
95                 runner.Args = append(runner.Args, cmd.filter.Args()...)
96                 output, err := runner.Run()
97                 if err != nil {
98                         return err
99                 }
100                 fmt.Fprintln(stdout, output)
101                 return nil
102         }
103
104         if *selectedTags != "" {
105                 cmd.selectedTags = map[tagID]bool{}
106                 for _, tagstr := range strings.Split(*selectedTags, ",") {
107                         tag, err := strconv.ParseInt(tagstr, 10, 64)
108                         if err != nil {
109                                 return err
110                         }
111                         cmd.selectedTags[tagID(tag)] = true
112                 }
113         }
114
115         infiles, err := allFiles(*inputDir, matchGobFile)
116         if err != nil {
117                 return err
118         }
119         if len(infiles) == 0 {
120                 return fmt.Errorf("no input files found in %s", *inputDir)
121         }
122         sort.Strings(infiles)
123
124         var refseq map[string][]tileLibRef
125         var reftiledata = make(map[tileLibRef][]byte, 11000000)
126         in0, err := open(infiles[0])
127         if err != nil {
128                 return err
129         }
130
131         matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
132         if err != nil {
133                 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
134                 return err
135         }
136
137         cmd.cgnames = nil
138         taglen := -1
139         DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
140                 if len(ent.TagSet) > 0 {
141                         taglen = len(ent.TagSet[0])
142                 }
143                 for _, cseq := range ent.CompactSequences {
144                         if cseq.Name == *ref || *ref == "" {
145                                 refseq = cseq.TileSequences
146                         }
147                 }
148                 for _, cg := range ent.CompactGenomes {
149                         if matchGenome.MatchString(cg.Name) {
150                                 cmd.cgnames = append(cmd.cgnames, cg.Name)
151                         }
152                 }
153                 for _, tv := range ent.TileVariants {
154                         if tv.Ref {
155                                 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
156                         }
157                 }
158                 return nil
159         })
160         if err != nil {
161                 return err
162         }
163         in0.Close()
164         if refseq == nil {
165                 return fmt.Errorf("%s: reference sequence not found", infiles[0])
166         }
167         if taglen < 0 {
168                 return fmt.Errorf("tagset not found")
169         }
170         if len(cmd.cgnames) == 0 {
171                 return fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
172         }
173         sort.Strings(cmd.cgnames)
174
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...
181         }
182         isdup := map[tagID]bool{}
183         reftile := map[tagID]*reftileinfo{}
184         for seqname, cseq := range refseq {
185                 pos := 0
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)
190                         }
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
198                         } else {
199                                 reftile[libref.Tag] = &reftileinfo{
200                                         seqname:  seqname,
201                                         variant:  libref.Variant,
202                                         tiledata: tiledata,
203                                         pos:      pos,
204                                 }
205                         }
206                         pos += len(tiledata) - taglen
207                 }
208                 log.Printf("... %s done, len %d", seqname, pos+taglen)
209         }
210
211         var mask *mask
212         if *regionsFilename != "" {
213                 log.Printf("loading regions from %s", *regionsFilename)
214                 mask, err = makeMask(*regionsFilename, *expandRegions)
215                 if err != nil {
216                         return err
217                 }
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)) {
222                                 delete(reftile, tag)
223                         }
224                 }
225                 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
226         }
227
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] {
232                                 delete(reftile, tag)
233                         }
234                 }
235                 log.Printf("after applying selected tags, len(reftile) == %d", len(reftile))
236         }
237
238         dumpVariantsName := fmt.Sprintf("%s/variants.csv", *outputDir)
239         log.Infof("writing %s", dumpVariantsName)
240         dumpVariantsF, err := os.Create(dumpVariantsName)
241         if err != nil {
242                 return err
243         }
244         dumpVariantsW := bufio.NewWriterSize(dumpVariantsF, 1<<20)
245         mtx := sync.Mutex{}
246
247         throttleMem := throttle{Max: runtime.GOMAXPROCS(0)}
248         log.Infof("reading %d slices with max concurrency %d", len(infiles), throttleMem.Max)
249         var done int64
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)
256                         if err != nil {
257                                 return err
258                         }
259                         defer f.Close()
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 {
263                                         if tv.Ref {
264                                                 continue
265                                         }
266                                         if mask != nil && reftile[tv.Tag] == nil {
267                                                 // Don't waste
268                                                 // time/memory on
269                                                 // masked-out tiles.
270                                                 continue
271                                         }
272                                         variants := seq[tv.Tag]
273                                         if len(variants) == 0 {
274                                                 variants = make([]TileVariant, 100)
275                                         }
276                                         for len(variants) <= int(tv.Variant) {
277                                                 variants = append(variants, TileVariant{})
278                                         }
279                                         variants[int(tv.Variant)] = tv
280                                         seq[tv.Tag] = variants
281                                 }
282                                 for _, cg := range ent.CompactGenomes {
283                                         if !matchGenome.MatchString(cg.Name) {
284                                                 continue
285                                         }
286                                         // pad to full slice size
287                                         // to avoid out-of-bounds
288                                         // checks later
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))...)
291                                         }
292                                         cgs[cg.Name] = cg
293                                 }
294                                 return nil
295                         })
296                         if err != nil {
297                                 return err
298                         }
299                         tagstart := cgs[cmd.cgnames[0]].StartTag
300                         tagend := cgs[cmd.cgnames[0]].EndTag
301
302                         // TODO: filters
303
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))
311
312                                         rt := reftile[tag]
313                                         var rthash [blake2b.Size256]byte
314                                         if rt != nil {
315                                                 rthash = blake2b.Sum256(rt.tiledata)
316                                                 count[rthash] = 0
317                                         }
318
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]++
325                                                         }
326                                                 }
327                                         }
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)
334                                         }
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 {
338                                                         return ci > cj
339                                                 } else {
340                                                         return bytes.Compare((*bi)[:], (*bj)[:]) < 0
341                                                 }
342                                         })
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)
349                                         }
350                                         // remap[v] will be the new
351                                         // variant number for original
352                                         // variant number v.
353                                         remap := make([]tileVariantID, len(variants))
354                                         for i, tv := range variants {
355                                                 remap[i] = rank[tv.Blake2b]
356                                         }
357                                         variantRemap[tag-tagstart] = remap
358                                         if rt != nil {
359                                                 rt.variant = rank[rthash]
360                                         }
361                                         return nil
362                                 })
363                         }
364                         throttleCPU.Wait()
365
366                         for tag := tagstart; tag < tagend; tag++ {
367                                 rt, ok := reftile[tag]
368                                 if !ok {
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?)
374                                         continue
375                                 }
376                                 remap := variantRemap[tag-tagstart]
377                                 maxv := tileVariantID(0)
378                                 for _, v := range remap {
379                                         if maxv < v {
380                                                 maxv = v
381                                         }
382                                 }
383                                 variants := seq[tag]
384
385                                 mtx.Lock()
386                                 fmt.Fprintf(dumpVariantsW, "%d,%d,1,%s,%d,%s\n", tag, rt.variant, rt.seqname, rt.pos+1, bytes.ToUpper(rt.tiledata))
387                                 mtx.Unlock()
388
389                                 done := make([]bool, maxv+1)
390                                 for v, tv := range variants {
391                                         v := remap[v]
392                                         if v == 0 || v == rt.variant || done[v] {
393                                                 continue
394                                         } else {
395                                                 done[v] = true
396                                         }
397                                         mtx.Lock()
398                                         fmt.Fprintf(dumpVariantsW, "%d,%d,0,%s,%d,%s\n", tag, v, rt.seqname, rt.pos+1, bytes.ToUpper(tv.Sequence))
399                                         mtx.Unlock()
400                                 }
401                         }
402                         log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
403                         return nil
404                 })
405         }
406         if err = throttleMem.Wait(); err != nil {
407                 return err
408         }
409         err = dumpVariantsW.Flush()
410         if err != nil {
411                 return err
412         }
413         err = dumpVariantsF.Close()
414         if err != nil {
415                 return err
416         }
417         return nil
418 }