1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "github.com/arvados/lightning/hgvs"
27 "github.com/kshedden/gonpy"
28 "github.com/sirupsen/logrus"
29 log "github.com/sirupsen/logrus"
32 type exportNumpy struct {
36 func (cmd *exportNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
40 fmt.Fprintf(stderr, "%s\n", err)
43 flags := flag.NewFlagSet("", flag.ContinueOnError)
44 flags.SetOutput(stderr)
45 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
46 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
47 projectUUID := flags.String("project", "", "project `UUID` for output data")
48 priority := flags.Int("priority", 500, "container request priority")
49 inputDir := flags.String("input-dir", "./in", "input `directory`")
50 outputDir := flags.String("output-dir", "./out", "output `directory`")
51 annotationsFilename := flags.String("output-annotations", "", "output `file` for tile variant annotations csv")
52 librefsFilename := flags.String("output-onehot2tilevar", "", "when using -one-hot, create csv `file` mapping column# to tag# and variant#")
53 labelsFilename := flags.String("output-labels", "", "output `file` for genome labels csv")
54 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
55 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
56 onehot := flags.Bool("one-hot", false, "recode tile variants as one-hot")
57 chunks := flags.Int("chunks", 1, "split output into `N` numpy files")
58 cmd.filter.Flags(flags)
59 err = flags.Parse(args)
60 if err == flag.ErrHelp {
63 } else if err != nil {
69 log.Println(http.ListenAndServe(*pprof, nil))
74 runner := arvadosContainerRunner{
75 Name: "lightning export-numpy",
76 Client: arvados.NewClientFromEnv(),
77 ProjectUUID: *projectUUID,
84 err = runner.TranslatePaths(inputDir, regionsFilename)
88 runner.Args = []string{"export-numpy", "-local=true",
90 fmt.Sprintf("-one-hot=%v", *onehot),
91 "-input-dir", *inputDir,
92 "-output-dir", "/mnt/output",
93 "-output-annotations", "/mnt/output/annotations.csv",
94 "-output-onehot2tilevar", "/mnt/output/onehot2tilevar.csv",
95 "-output-labels", "/mnt/output/labels.csv",
96 "-regions", *regionsFilename,
97 "-expand-regions", fmt.Sprintf("%d", *expandRegions),
98 "-max-variants", fmt.Sprintf("%d", cmd.filter.MaxVariants),
99 "-min-coverage", fmt.Sprintf("%f", cmd.filter.MinCoverage),
100 "-max-tag", fmt.Sprintf("%d", cmd.filter.MaxTag),
101 "-chunks", fmt.Sprintf("%d", *chunks),
104 output, err = runner.Run()
108 fmt.Fprintln(stdout, output+"/matrix.npy")
112 tilelib := &tileLibrary{
114 retainTileSequences: true,
115 compactGenomes: map[string][]tileVariantID{},
117 err = tilelib.LoadDir(context.Background(), *inputDir, nil)
122 log.Info("filtering")
123 cmd.filter.Apply(tilelib)
127 log.Info("building lowqual map")
128 lowqual := lowqual(tilelib)
129 names := cgnames(tilelib)
131 if *labelsFilename != "" {
132 log.Infof("writing labels to %s", *labelsFilename)
134 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
139 outBasename := "matrix.npy"
140 for i, name := range names {
141 _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
143 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
149 err = fmt.Errorf("close %s: %w", *labelsFilename, err)
154 log.Info("determining which tiles intersect given regions")
155 dropTiles, err := chooseTiles(tilelib, *regionsFilename, *expandRegions)
160 annotation2tvs := map[string]map[hgvs.Variant][]tileLibRef{}
161 if *annotationsFilename != "" {
162 log.Info("writing annotations")
163 var annow io.WriteCloser
164 annow, err = os.OpenFile(*annotationsFilename, os.O_CREATE|os.O_WRONLY, 0666)
172 dropTiles: dropTiles,
173 reportAnnotation: func(tag tagID, _ int, variant tileVariantID, refname string, seqname string, pdi hgvs.Variant) {
176 if annotation2tvs[seqname] == nil {
177 annotation2tvs[seqname] = map[hgvs.Variant][]tileLibRef{}
179 annotation2tvs[seqname][pdi] = append(annotation2tvs[seqname][pdi], tileLibRef{Tag: tag, Variant: variant})
181 }).exportTileDiffs(annow, tilelib)
191 var lastErr atomic.Value
192 var wg sync.WaitGroup
193 for seqname, pdivars := range annotation2tvs {
194 seqname, pdivars := seqname, pdivars
198 log.Infof("choosing hgvs columns for seq %s", seqname)
199 var pdis []hgvs.Variant
200 for pdi, librefs := range pdivars {
201 // Include this HGVS column if it was
202 // seen in a variant of any
204 for _, libref := range librefs {
205 if int(libref.Tag) >= len(dropTiles) || !dropTiles[libref.Tag] {
206 pdis = append(pdis, pdi)
211 sort.Slice(pdis, func(i, j int) bool {
212 if cmp := pdis[i].Position - pdis[j].Position; cmp != 0 {
214 } else if pdis[i].Ref != pdis[j].Ref {
215 return pdis[i].Ref < pdis[j].Ref
217 return pdis[i].New < pdis[j].New
220 log.Infof("writing column labels for seq %s", seqname)
222 for _, pdi := range pdis {
223 fmt.Fprintf(&buf, "%s:g.%s\n", seqname, pdi.String())
225 err := ioutil.WriteFile(*outputDir+"/"+seqname+".columns.csv", buf.Bytes(), 0777)
231 log.Infof("building hgvs matrix for seq %s", seqname)
232 data := make([]int8, len(names)*len(pdis)*2)
233 for row, name := range names {
234 cg := tilelib.compactGenomes[name]
235 rowstart := row * len(pdis) * 2
236 for col, pdi := range pdis {
237 for _, libref := range pdivars[pdi] {
238 if len(cg) <= int(libref.Tag)*2+1 {
241 for phase := 0; phase < 2; phase++ {
242 if cg[int(libref.Tag)*2+phase] == libref.Variant {
243 data[rowstart+col*2+phase] = 1
249 log.Infof("writing hgvs numpy for seq %s", seqname)
250 f, err := os.OpenFile(*outputDir+"/"+seqname+".npy", os.O_CREATE|os.O_WRONLY, 0777)
256 npw, err := gonpy.NewWriter(f)
261 npw.Shape = []int{len(names), len(pdis) * 2}
263 // gonpy closes f and ignores errors, doh.
266 // lastErr.Store(err)
272 if e, ok := lastErr.Load().(error); ok {
277 chunksize := (len(tilelib.variant) + *chunks - 1) / *chunks
278 for chunk := 0; chunk < *chunks; chunk++ {
279 log.Infof("preparing chunk %d of %d", chunk+1, *chunks)
280 tagstart := chunk * chunksize
281 tagend := tagstart + chunksize
282 if tagend > len(tilelib.variant) {
283 tagend = len(tilelib.variant)
285 out, rows, cols := cgs2array(tilelib, names, lowqual, dropTiles, tagstart, tagend)
287 var npw *gonpy.NpyWriter
288 var output io.WriteCloser
289 fnm := *outputDir + "/matrix.npy"
291 fnm = fmt.Sprintf("%s/matrix.%d.npy", *outputDir, chunk)
293 output, err = os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0777)
298 bufw := bufio.NewWriter(output)
299 npw, err = gonpy.NewWriter(nopCloser{bufw})
304 log.Info("recoding to onehot")
305 recoded, librefs, recodedcols := recodeOnehot(out, cols)
306 out, cols = recoded, recodedcols
307 if *librefsFilename != "" {
308 log.Infof("writing onehot column mapping")
309 err = cmd.writeLibRefs(*librefsFilename, tilelib, librefs)
315 log.WithFields(logrus.Fields{
319 }).Info("writing numpy")
320 npw.Shape = []int{rows, cols}
334 func (*exportNumpy) writeLibRefs(fnm string, tilelib *tileLibrary, librefs []tileLibRef) error {
335 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0666)
340 for i, libref := range librefs {
341 _, err = fmt.Fprintf(f, "%d,%d,%d\n", i, libref.Tag, libref.Variant)
349 func cgnames(tilelib *tileLibrary) (cgnames []string) {
350 for name := range tilelib.compactGenomes {
351 cgnames = append(cgnames, name)
353 sort.Slice(cgnames, func(i, j int) bool {
354 return trimFilenameForLabel(cgnames[i]) < trimFilenameForLabel(cgnames[j])
359 func lowqual(tilelib *tileLibrary) (lowqual []map[tileVariantID]bool) {
360 lowqual = make([]map[tileVariantID]bool, len(tilelib.variant))
361 for tag, variants := range tilelib.variant {
363 for varidx, hash := range variants {
364 if len(tilelib.hashSequence(hash)) == 0 {
366 lq = map[tileVariantID]bool{}
369 lq[tileVariantID(varidx+1)] = true
376 func cgs2array(tilelib *tileLibrary, names []string, lowqual []map[tileVariantID]bool, dropTiles []bool, tagstart, tagend int) (data []int16, rows, cols int) {
377 rows = len(tilelib.compactGenomes)
378 for tag := tagstart; tag < tagend; tag++ {
379 if len(dropTiles) <= tag || !dropTiles[tag] {
383 data = make([]int16, rows*cols)
384 for row, name := range names {
385 cg := tilelib.compactGenomes[name]
387 for tag := tagstart; tag < tagend && tag*2+1 < len(cg); tag++ {
388 if len(dropTiles) > tag && dropTiles[tag] {
391 for phase := 0; phase < 2; phase++ {
393 if v > 0 && lowqual[tag][v] {
394 data[row*cols+outidx] = -1
396 data[row*cols+outidx] = int16(v)
405 func chooseTiles(tilelib *tileLibrary, regionsFilename string, expandRegions int) (drop []bool, err error) {
406 if regionsFilename == "" {
409 rfile, err := zopen(regionsFilename)
414 regions, err := ioutil.ReadAll(rfile)
419 log.Print("chooseTiles: building mask")
421 for _, line := range bytes.Split(regions, []byte{'\n'}) {
422 if bytes.HasPrefix(line, []byte{'#'}) {
425 fields := bytes.Split(line, []byte{'\t'})
429 refseqname := string(fields[0])
430 if strings.HasPrefix(refseqname, "chr") {
431 refseqname = refseqname[3:]
433 start, err1 := strconv.Atoi(string(fields[1]))
434 end, err2 := strconv.Atoi(string(fields[2]))
435 if err1 == nil && err2 == nil {
438 start, err1 = strconv.Atoi(string(fields[3]))
439 end, err2 = strconv.Atoi(string(fields[4]))
440 if err1 == nil && err2 == nil {
444 err = fmt.Errorf("cannot parse input line as BED or GFF/GTF: %q", line)
448 mask.Add(refseqname, start-expandRegions, end+expandRegions)
450 log.Print("chooseTiles: mask.Freeze")
453 tagset := tilelib.taglib.Tags()
454 if len(tagset) == 0 {
455 err = errors.New("cannot choose tiles by region in a library without tags")
458 taglen := len(tagset[0])
460 log.Print("chooseTiles: check ref tiles")
461 // Find position+size of each reference tile, and if it
462 // intersects any of the desired regions, set drop[tag]=false.
464 // (Note it doesn't quite work to do the more obvious thing --
465 // start with drop=false and change to true when ref tiles
466 // intersect target regions -- because that would give us
467 // drop=false for tiles that don't appear at all in the
470 // TODO: (optionally?) don't drop tags for which some tile
471 // variants are spanning tiles, i.e., where the reference tile
472 // does not intersect the desired regions, but a spanning tile
473 // from a genome does.
474 drop = make([]bool, len(tilelib.variant))
475 for i := range drop {
478 for refname, refseqs := range tilelib.refseqs {
479 for refseqname, reftiles := range refseqs {
480 if strings.HasPrefix(refseqname, "chr") {
481 refseqname = refseqname[3:]
484 for _, libref := range reftiles {
485 if libref.Variant < 1 {
486 err = fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, refseqname, libref.Tag)
489 seq := tilelib.TileVariantSequence(libref)
490 if len(seq) < taglen {
491 err = fmt.Errorf("reference %q seq %q uses tile %d variant %d with sequence len %d < taglen %d", refname, refseqname, libref.Tag, libref.Variant, len(seq), taglen)
495 tileend = tilestart + len(seq) - taglen
496 if mask.Check(refseqname, tilestart, tileend) {
497 drop[libref.Tag] = false
503 log.Print("chooseTiles: done")
507 func recodeOnehot(in []int16, incols int) (out []int16, librefs []tileLibRef, outcols int) {
508 rows := len(in) / incols
509 maxvalue := make([]int16, incols)
510 for row := 0; row < rows; row++ {
511 for col := 0; col < incols; col++ {
512 if v := in[row*incols+col]; maxvalue[col] < v {
517 outcol := make([]int, incols)
519 for incol, maxv := range maxvalue {
520 outcol[incol] = outcols
524 for v := 1; v <= int(maxv); v++ {
525 librefs = append(librefs, tileLibRef{Tag: tagID(incol), Variant: tileVariantID(v)})
529 log.Printf("recodeOnehot: dropped %d input cols with zero maxvalue", dropped)
531 out = make([]int16, rows*outcols)
532 for inidx, row := 0, 0; row < rows; row++ {
533 outrow := out[row*outcols:]
534 for col := 0; col < incols; col++ {
535 if v := in[inidx]; v > 0 {
536 outrow[outcol[col]+int(v)-1] = 1
544 type nopCloser struct {
548 func (nopCloser) Close() error { return nil }
550 func trimFilenameForLabel(s string) string {
551 if i := strings.LastIndex(s, "/"); i >= 0 {
554 s = strings.TrimSuffix(s, ".gz")
555 s = strings.TrimSuffix(s, ".fa")
556 s = strings.TrimSuffix(s, ".fasta")
557 s = strings.TrimSuffix(s, ".1")
558 s = strings.TrimSuffix(s, ".2")
559 s = strings.TrimSuffix(s, ".gz")
560 s = strings.TrimSuffix(s, ".vcf")