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 "-chunks", fmt.Sprintf("%d", *chunks),
100 runner.Args = append(runner.Args, cmd.filter.Args()...)
102 output, err = runner.Run()
106 fmt.Fprintln(stdout, output+"/matrix.npy")
110 tilelib := &tileLibrary{
112 retainTileSequences: true,
113 compactGenomes: map[string][]tileVariantID{},
115 err = tilelib.LoadDir(context.Background(), *inputDir, nil)
120 log.Info("filtering")
121 cmd.filter.Apply(tilelib)
125 log.Info("building lowqual map")
126 lowqual := lowqual(tilelib)
127 names := cgnames(tilelib)
129 if *labelsFilename != "" {
130 log.Infof("writing labels to %s", *labelsFilename)
132 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
137 outBasename := "matrix.npy"
138 for i, name := range names {
139 _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
141 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
147 err = fmt.Errorf("close %s: %w", *labelsFilename, err)
152 log.Info("determining which tiles intersect given regions")
153 dropTiles, err := chooseTiles(tilelib, *regionsFilename, *expandRegions)
158 annotation2tvs := map[string]map[hgvs.Variant][]tileLibRef{}
159 if *annotationsFilename != "" {
160 log.Info("writing annotations")
161 var annow io.WriteCloser
162 annow, err = os.OpenFile(*annotationsFilename, os.O_CREATE|os.O_WRONLY, 0666)
170 dropTiles: dropTiles,
171 reportAnnotation: func(tag tagID, _ int, variant tileVariantID, refname string, seqname string, pdi hgvs.Variant) {
174 if annotation2tvs[seqname] == nil {
175 annotation2tvs[seqname] = map[hgvs.Variant][]tileLibRef{}
177 annotation2tvs[seqname][pdi] = append(annotation2tvs[seqname][pdi], tileLibRef{Tag: tag, Variant: variant})
179 }).exportTileDiffs(annow, tilelib)
189 var lastErr atomic.Value
190 var wg sync.WaitGroup
191 for seqname, pdivars := range annotation2tvs {
192 seqname, pdivars := seqname, pdivars
196 log.Infof("choosing hgvs columns for seq %s", seqname)
197 var pdis []hgvs.Variant
198 for pdi, librefs := range pdivars {
199 // Include this HGVS column if it was
200 // seen in a variant of any
202 for _, libref := range librefs {
203 if int(libref.Tag) >= len(dropTiles) || !dropTiles[libref.Tag] {
204 pdis = append(pdis, pdi)
209 sort.Slice(pdis, func(i, j int) bool {
210 if cmp := pdis[i].Position - pdis[j].Position; cmp != 0 {
212 } else if pdis[i].Ref != pdis[j].Ref {
213 return pdis[i].Ref < pdis[j].Ref
215 return pdis[i].New < pdis[j].New
218 log.Infof("writing column labels for seq %s", seqname)
220 for _, pdi := range pdis {
221 fmt.Fprintf(&buf, "%s:g.%s\n", seqname, pdi.String())
223 err := ioutil.WriteFile(*outputDir+"/"+seqname+".columns.csv", buf.Bytes(), 0777)
229 log.Infof("building hgvs matrix for seq %s", seqname)
230 data := make([]int8, len(names)*len(pdis)*2)
231 for row, name := range names {
232 cg := tilelib.compactGenomes[name]
233 rowstart := row * len(pdis) * 2
234 for col, pdi := range pdis {
235 for _, libref := range pdivars[pdi] {
236 if len(cg) <= int(libref.Tag)*2+1 {
239 for phase := 0; phase < 2; phase++ {
240 if cg[int(libref.Tag)*2+phase] == libref.Variant {
241 data[rowstart+col*2+phase] = 1
247 log.Infof("writing hgvs numpy for seq %s", seqname)
248 f, err := os.OpenFile(*outputDir+"/"+seqname+".npy", os.O_CREATE|os.O_WRONLY, 0777)
254 npw, err := gonpy.NewWriter(f)
259 npw.Shape = []int{len(names), len(pdis) * 2}
261 // gonpy closes f and ignores errors, doh.
264 // lastErr.Store(err)
270 if e, ok := lastErr.Load().(error); ok {
275 chunksize := (len(tilelib.variant) + *chunks - 1) / *chunks
276 for chunk := 0; chunk < *chunks; chunk++ {
277 log.Infof("preparing chunk %d of %d", chunk+1, *chunks)
278 tagstart := chunk * chunksize
279 tagend := tagstart + chunksize
280 if tagend > len(tilelib.variant) {
281 tagend = len(tilelib.variant)
283 out, rows, cols := cgs2array(tilelib, names, lowqual, dropTiles, tagstart, tagend)
285 var npw *gonpy.NpyWriter
286 var output io.WriteCloser
287 fnm := *outputDir + "/matrix.npy"
289 fnm = fmt.Sprintf("%s/matrix.%d.npy", *outputDir, chunk)
291 output, err = os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0777)
296 bufw := bufio.NewWriter(output)
297 npw, err = gonpy.NewWriter(nopCloser{bufw})
302 log.Info("recoding to onehot")
303 recoded, librefs, recodedcols := recodeOnehot(out, cols)
304 out, cols = recoded, recodedcols
305 if *librefsFilename != "" {
306 log.Infof("writing onehot column mapping")
307 err = cmd.writeLibRefs(*librefsFilename, tilelib, librefs)
313 log.WithFields(logrus.Fields{
317 }).Info("writing numpy")
318 npw.Shape = []int{rows, cols}
332 func (*exportNumpy) writeLibRefs(fnm string, tilelib *tileLibrary, librefs []tileLibRef) error {
333 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0666)
338 for i, libref := range librefs {
339 _, err = fmt.Fprintf(f, "%d,%d,%d\n", i, libref.Tag, libref.Variant)
347 func cgnames(tilelib *tileLibrary) (cgnames []string) {
348 for name := range tilelib.compactGenomes {
349 cgnames = append(cgnames, name)
351 sort.Slice(cgnames, func(i, j int) bool {
352 return trimFilenameForLabel(cgnames[i]) < trimFilenameForLabel(cgnames[j])
357 func lowqual(tilelib *tileLibrary) (lowqual []map[tileVariantID]bool) {
358 lowqual = make([]map[tileVariantID]bool, len(tilelib.variant))
359 for tag, variants := range tilelib.variant {
361 for varidx, hash := range variants {
362 if len(tilelib.hashSequence(hash)) == 0 {
364 lq = map[tileVariantID]bool{}
367 lq[tileVariantID(varidx+1)] = true
374 func cgs2array(tilelib *tileLibrary, names []string, lowqual []map[tileVariantID]bool, dropTiles []bool, tagstart, tagend int) (data []int16, rows, cols int) {
375 rows = len(tilelib.compactGenomes)
376 for tag := tagstart; tag < tagend; tag++ {
377 if len(dropTiles) <= tag || !dropTiles[tag] {
381 data = make([]int16, rows*cols)
382 for row, name := range names {
383 cg := tilelib.compactGenomes[name]
385 for tag := tagstart; tag < tagend && tag*2+1 < len(cg); tag++ {
386 if len(dropTiles) > tag && dropTiles[tag] {
389 for phase := 0; phase < 2; phase++ {
391 if v > 0 && lowqual[tag][v] {
392 data[row*cols+outidx] = -1
394 data[row*cols+outidx] = int16(v)
403 func chooseTiles(tilelib *tileLibrary, regionsFilename string, expandRegions int) (drop []bool, err error) {
404 if regionsFilename == "" {
407 rfile, err := zopen(regionsFilename)
412 regions, err := ioutil.ReadAll(rfile)
417 log.Print("chooseTiles: building mask")
419 for _, line := range bytes.Split(regions, []byte{'\n'}) {
420 if bytes.HasPrefix(line, []byte{'#'}) {
423 fields := bytes.Split(line, []byte{'\t'})
427 refseqname := string(fields[0])
428 if strings.HasPrefix(refseqname, "chr") {
429 refseqname = refseqname[3:]
431 start, err1 := strconv.Atoi(string(fields[1]))
432 end, err2 := strconv.Atoi(string(fields[2]))
433 if err1 == nil && err2 == nil {
436 start, err1 = strconv.Atoi(string(fields[3]))
437 end, err2 = strconv.Atoi(string(fields[4]))
438 if err1 == nil && err2 == nil {
442 err = fmt.Errorf("cannot parse input line as BED or GFF/GTF: %q", line)
446 mask.Add(refseqname, start-expandRegions, end+expandRegions)
448 log.Print("chooseTiles: mask.Freeze")
451 tagset := tilelib.taglib.Tags()
452 if len(tagset) == 0 {
453 err = errors.New("cannot choose tiles by region in a library without tags")
456 taglen := len(tagset[0])
458 log.Print("chooseTiles: check ref tiles")
459 // Find position+size of each reference tile, and if it
460 // intersects any of the desired regions, set drop[tag]=false.
462 // (Note it doesn't quite work to do the more obvious thing --
463 // start with drop=false and change to true when ref tiles
464 // intersect target regions -- because that would give us
465 // drop=false for tiles that don't appear at all in the
468 // TODO: (optionally?) don't drop tags for which some tile
469 // variants are spanning tiles, i.e., where the reference tile
470 // does not intersect the desired regions, but a spanning tile
471 // from a genome does.
472 drop = make([]bool, len(tilelib.variant))
473 for i := range drop {
476 for refname, refseqs := range tilelib.refseqs {
477 for refseqname, reftiles := range refseqs {
478 if strings.HasPrefix(refseqname, "chr") {
479 refseqname = refseqname[3:]
482 for _, libref := range reftiles {
483 if libref.Variant < 1 {
484 err = fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, refseqname, libref.Tag)
487 seq := tilelib.TileVariantSequence(libref)
488 if len(seq) < taglen {
489 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)
493 tileend = tilestart + len(seq) - taglen
494 if mask.Check(refseqname, tilestart, tileend) {
495 drop[libref.Tag] = false
501 log.Print("chooseTiles: done")
505 func recodeOnehot(in []int16, incols int) (out []int16, librefs []tileLibRef, outcols int) {
506 rows := len(in) / incols
507 maxvalue := make([]int16, incols)
508 for row := 0; row < rows; row++ {
509 for col := 0; col < incols; col++ {
510 if v := in[row*incols+col]; maxvalue[col] < v {
515 outcol := make([]int, incols)
517 for incol, maxv := range maxvalue {
518 outcol[incol] = outcols
522 for v := 1; v <= int(maxv); v++ {
523 librefs = append(librefs, tileLibRef{Tag: tagID(incol), Variant: tileVariantID(v)})
527 log.Printf("recodeOnehot: dropped %d input cols with zero maxvalue", dropped)
529 out = make([]int16, rows*outcols)
530 for inidx, row := 0, 0; row < rows; row++ {
531 outrow := out[row*outcols:]
532 for col := 0; col < incols; col++ {
533 if v := in[inidx]; v > 0 {
534 outrow[outcol[col]+int(v)-1] = 1
542 type nopCloser struct {
546 func (nopCloser) Close() error { return nil }
548 func trimFilenameForLabel(s string) string {
549 if i := strings.LastIndex(s, "/"); i >= 0 {
552 s = strings.TrimSuffix(s, ".gz")
553 s = strings.TrimSuffix(s, ".fa")
554 s = strings.TrimSuffix(s, ".fasta")
555 s = strings.TrimSuffix(s, ".1")
556 s = strings.TrimSuffix(s, ".2")
557 s = strings.TrimSuffix(s, ".gz")
558 s = strings.TrimSuffix(s, ".vcf")