1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "github.com/arvados/lightning/hgvs"
31 "github.com/james-bowman/nlp"
32 "github.com/kshedden/gonpy"
33 "github.com/sirupsen/logrus"
34 log "github.com/sirupsen/logrus"
35 "golang.org/x/crypto/blake2b"
36 "gonum.org/v1/gonum/mat"
39 const annotationMaxTileSpan = 100
41 type sliceNumpy struct {
44 chi2CaseControlColumn string
45 chi2CaseControlFile string
48 trainingSet []int // see loadTrainingSet
56 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 err := cmd.run(prog, args, stdin, stdout, stderr)
59 fmt.Fprintf(stderr, "%s\n", err)
65 func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
66 flags := flag.NewFlagSet("", flag.ContinueOnError)
67 flags.SetOutput(stderr)
68 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
69 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
70 arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
71 arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
72 projectUUID := flags.String("project", "", "project `UUID` for output data")
73 priority := flags.Int("priority", 500, "container request priority")
74 inputDir := flags.String("input-dir", "./in", "input `directory`")
75 outputDir := flags.String("output-dir", "./out", "output `directory`")
76 ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
77 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
78 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
79 mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
80 hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
81 hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
82 onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
83 onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
84 trainingSetFilename := flags.String("training-set", "", "`tsv` file with sample IDs to be used for PCA fitting and Χ² test (if not provided, use all samples)")
85 onlyPCA := flags.Bool("pca", false, "generate pca matrix")
86 pcaComponents := flags.Int("pca-components", 4, "number of PCA components")
87 maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
88 debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
89 flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
90 flags.StringVar(&cmd.chi2CaseControlFile, "chi2-case-control-file", "", "tsv file or directory indicating cases and controls for Χ² test (if directory, all .tsv files will be read)")
91 flags.StringVar(&cmd.chi2CaseControlColumn, "chi2-case-control-column", "", "name of case/control column in case-control files for Χ² test (value must be 0 for control, 1 for case)")
92 flags.Float64Var(&cmd.chi2PValue, "chi2-p-value", 1, "do Χ² test and omit columns with p-value above this threshold")
93 flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
94 cmd.filter.Flags(flags)
95 err := flags.Parse(args)
96 if err == flag.ErrHelp {
98 } else if err != nil {
104 log.Println(http.ListenAndServe(*pprof, nil))
108 if cmd.chi2PValue != 1 && (cmd.chi2CaseControlFile == "" || cmd.chi2CaseControlColumn == "") {
109 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -chi2-case-control-file= or -chi2-case-control-column= value is empty", cmd.chi2PValue)
112 cmd.debugTag = tagID(*debugTag)
115 runner := arvadosContainerRunner{
116 Name: "lightning slice-numpy",
117 Client: arvados.NewClientFromEnv(),
118 ProjectUUID: *projectUUID,
119 RAM: int64(*arvadosRAM),
120 VCPUs: *arvadosVCPUs,
125 err = runner.TranslatePaths(inputDir, regionsFilename, trainingSetFilename, &cmd.chi2CaseControlFile)
129 runner.Args = []string{"slice-numpy", "-local=true",
131 "-input-dir=" + *inputDir,
132 "-output-dir=/mnt/output",
133 "-threads=" + fmt.Sprintf("%d", cmd.threads),
134 "-regions=" + *regionsFilename,
135 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
136 "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
137 "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
138 "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
139 "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
140 "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
141 "-training-set=" + *trainingSetFilename,
142 "-pca=" + fmt.Sprintf("%v", *onlyPCA),
143 "-pca-components=" + fmt.Sprintf("%d", *pcaComponents),
144 "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
145 "-chi2-case-control-file=" + cmd.chi2CaseControlFile,
146 "-chi2-case-control-column=" + cmd.chi2CaseControlColumn,
147 "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
148 "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
149 "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
151 runner.Args = append(runner.Args, cmd.filter.Args()...)
153 output, err = runner.Run()
157 fmt.Fprintln(stdout, output)
161 infiles, err := allFiles(*inputDir, matchGobFile)
165 if len(infiles) == 0 {
166 err = fmt.Errorf("no input files found in %s", *inputDir)
169 sort.Strings(infiles)
171 var refseq map[string][]tileLibRef
172 var reftiledata = make(map[tileLibRef][]byte, 11000000)
173 in0, err := open(infiles[0])
178 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
180 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
186 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
187 if len(ent.TagSet) > 0 {
190 for _, cseq := range ent.CompactSequences {
191 if cseq.Name == *ref || *ref == "" {
192 refseq = cseq.TileSequences
195 for _, cg := range ent.CompactGenomes {
196 if matchGenome.MatchString(cg.Name) {
197 cmd.cgnames = append(cmd.cgnames, cg.Name)
200 for _, tv := range ent.TileVariants {
202 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
212 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
215 if len(tagset) == 0 {
216 err = fmt.Errorf("tagset not found")
220 taglib := &tagLibrary{}
221 err = taglib.setTags(tagset)
225 taglen := taglib.TagLen()
227 if len(cmd.cgnames) == 0 {
228 err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
231 sort.Strings(cmd.cgnames)
232 err = cmd.useCaseControlFiles()
236 if len(cmd.cgnames) == 0 {
237 err = fmt.Errorf("fatal: 0 cases, 0 controls, nothing to do")
240 err = cmd.loadTrainingSet(*trainingSetFilename)
244 if cmd.filter.MinCoverage == 1 {
245 // In the generic formula below, floating point
246 // arithmetic can effectively push the coverage
247 // threshold above 1.0, which is impossible/useless.
248 // 1.0 needs to mean exactly 100% coverage.
249 cmd.minCoverage = len(cmd.cgnames)
251 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
255 labelsFilename := *outputDir + "/samples.csv"
256 log.Infof("writing labels to %s", labelsFilename)
258 f, err = os.Create(labelsFilename)
263 for i, name := range cmd.cgnames {
265 if cmd.chi2Cases != nil && cmd.chi2Cases[i] {
268 _, err = fmt.Fprintf(f, "%d,%q,%d\n", i, trimFilenameForLabel(name), cc)
270 err = fmt.Errorf("write %s: %w", labelsFilename, err)
276 err = fmt.Errorf("close %s: %w", labelsFilename, err)
281 log.Info("indexing reference tiles")
282 type reftileinfo struct {
283 variant tileVariantID
284 seqname string // chr1
285 pos int // distance from start of chromosome to starttag
286 tiledata []byte // acgtggcaa...
287 excluded bool // true if excluded by regions file
288 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
290 isdup := map[tagID]bool{}
291 reftile := map[tagID]*reftileinfo{}
292 for seqname, cseq := range refseq {
294 lastreftag := tagID(-1)
295 for _, libref := range cseq {
296 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
299 tiledata := reftiledata[libref]
300 if len(tiledata) == 0 {
301 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
304 foundthistag := false
305 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
306 if !foundthistag && tagid == libref.Tag {
310 if dupref, ok := reftile[tagid]; ok {
311 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique, also found inside %+v from %s @ %d", tileLibRef{Tag: tagid, Variant: dupref.variant}, dupref.seqname, dupref.pos, libref, seqname, pos+offset+1)
312 delete(reftile, tagid)
314 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
318 if isdup[libref.Tag] {
319 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
320 } else if reftile[libref.Tag] != nil {
321 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)
322 delete(reftile, libref.Tag)
323 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
324 isdup[libref.Tag] = true
326 reftile[libref.Tag] = &reftileinfo{
328 variant: libref.Variant,
334 reftile[lastreftag].nexttag = libref.Tag
336 lastreftag = libref.Tag
338 pos += len(tiledata) - taglen
340 log.Printf("... %s done, len %d", seqname, pos+taglen)
344 if *regionsFilename != "" {
345 log.Printf("loading regions from %s", *regionsFilename)
346 mask, err = makeMask(*regionsFilename, *expandRegions)
350 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
351 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
352 for _, rt := range reftile {
353 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
357 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
360 type hgvsColSet map[hgvs.Variant][2][]int8
361 encodeHGVS := throttle{Max: len(refseq)}
362 encodeHGVSTodo := map[string]chan hgvsColSet{}
363 tmpHGVSCols := map[string]*os.File{}
365 for seqname := range refseq {
367 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
371 defer os.Remove(f.Name())
372 bufw := bufio.NewWriterSize(f, 1<<24)
373 enc := gob.NewEncoder(bufw)
374 tmpHGVSCols[seqname] = f
375 todo := make(chan hgvsColSet, 128)
376 encodeHGVSTodo[seqname] = todo
377 encodeHGVS.Go(func() error {
378 for colset := range todo {
379 err := enc.Encode(colset)
381 encodeHGVS.Report(err)
392 var toMerge [][]int16
393 if *mergeOutput || *hgvsSingle {
394 toMerge = make([][]int16, len(infiles))
396 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
397 var onehotChunkSize []uint32
398 var onehotXrefs [][]onehotXref
399 if *onehotSingle || *onlyPCA {
400 onehotIndirect = make([][2][]uint32, len(infiles))
401 onehotChunkSize = make([]uint32, len(infiles))
402 onehotXrefs = make([][]onehotXref, len(infiles))
404 chunkStartTag := make([]tagID, len(infiles))
406 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
407 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
408 log.Info("generating annotations and numpy matrix for each slice")
409 var errSkip = errors.New("skip infile")
411 for infileIdx, infile := range infiles {
412 infileIdx, infile := infileIdx, infile
413 throttleMem.Go(func() error {
414 seq := make(map[tagID][]TileVariant, 50000)
415 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
416 f, err := open(infile)
421 log.Infof("%04d: reading %s", infileIdx, infile)
422 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
423 for _, tv := range ent.TileVariants {
428 // corresponding ref tile, if
429 // mask is in play (we can't
430 // determine coordinates for
432 if mask != nil && reftile[tv.Tag] == nil {
436 // corresponding ref tile is
437 // outside target regions --
438 // unless it's a potential
440 if mask != nil && reftile[tv.Tag].excluded &&
441 (int(tv.Tag+1) >= len(tagset) ||
442 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
445 if tv.Tag == cmd.debugTag {
446 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
448 variants := seq[tv.Tag]
449 if len(variants) == 0 {
450 variants = make([]TileVariant, 100)
452 for len(variants) <= int(tv.Variant) {
453 variants = append(variants, TileVariant{})
455 variants[int(tv.Variant)] = tv
456 seq[tv.Tag] = variants
458 for _, cg := range ent.CompactGenomes {
459 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
462 if !matchGenome.MatchString(cg.Name) {
465 // pad to full slice size
466 // to avoid out-of-bounds
468 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
469 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
477 } else if err != nil {
478 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
480 tagstart := cgs[cmd.cgnames[0]].StartTag
481 tagend := cgs[cmd.cgnames[0]].EndTag
482 chunkStartTag[infileIdx] = tagstart
486 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
487 variantRemap := make([][]tileVariantID, tagend-tagstart)
488 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
489 for tag, variants := range seq {
490 tag, variants := tag, variants
491 throttleCPU.Go(func() error {
493 count := make(map[[blake2b.Size256]byte]int, len(variants))
497 count[blake2b.Sum256(rt.tiledata)] = 0
500 for cgname, cg := range cgs {
501 idx := int(tag-tagstart) * 2
502 for allele := 0; allele < 2; allele++ {
503 v := cg.Variants[idx+allele]
504 if v > 0 && len(variants[v].Sequence) > 0 {
505 count[variants[v].Blake2b]++
508 if v > 0 && tag == cmd.debugTag {
509 log.Printf("tag %d cg %s allele %d tv %d hash %x count is now %d", tag, cgname, allele, v, variants[v].Blake2b[:3], count[variants[v].Blake2b])
513 if alleleCoverage < cmd.minCoverage*2 {
514 idx := int(tag-tagstart) * 2
515 for _, cg := range cgs {
517 cg.Variants[idx+1] = 0
519 if tag == cmd.debugTag {
520 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
525 // hash[i] will be the hash of
526 // the variant(s) that should
527 // be at rank i (0-based).
528 hash := make([][blake2b.Size256]byte, 0, len(count))
529 for b := range count {
530 hash = append(hash, b)
532 sort.Slice(hash, func(i, j int) bool {
533 bi, bj := &hash[i], &hash[j]
534 if ci, cj := count[*bi], count[*bj]; ci != cj {
537 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
540 // rank[b] will be the 1-based
541 // new variant number for
542 // variants whose hash is b.
543 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
544 for i, h := range hash {
545 rank[h] = tileVariantID(i + 1)
547 if tag == cmd.debugTag {
548 for h, r := range rank {
549 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
552 // remap[v] will be the new
553 // variant number for original
555 remap := make([]tileVariantID, len(variants))
556 for i, tv := range variants {
557 remap[i] = rank[tv.Blake2b]
559 if tag == cmd.debugTag {
560 for in, out := range remap {
562 log.Printf("tag %d remap %d => %d", tag, in, out)
566 variantRemap[tag-tagstart] = remap
568 refrank := rank[blake2b.Sum256(rt.tiledata)]
569 if tag == cmd.debugTag {
570 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
579 var onehotChunk [][]int8
580 var onehotXref []onehotXref
582 var annotationsFilename string
584 annotationsFilename = "/dev/null"
586 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
587 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
589 annof, err := os.Create(annotationsFilename)
593 annow := bufio.NewWriterSize(annof, 1<<20)
595 for tag := tagstart; tag < tagend; tag++ {
597 if rt == nil && mask != nil {
598 // With no ref tile, we don't
599 // have coordinates to say
600 // this is in the desired
601 // regions -- so it's not.
602 // TODO: handle ref spanning
606 if rt != nil && rt.excluded {
607 // TODO: don't skip yet --
608 // first check for spanning
609 // tile variants that
610 // intersect non-excluded ref
614 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
617 remap := variantRemap[tag-tagstart]
618 maxv := tileVariantID(0)
619 for _, v := range remap {
624 if *onehotChunked || *onehotSingle || *onlyPCA {
625 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
626 if tag == cmd.debugTag {
627 log.WithFields(logrus.Fields{
630 }).Info("tv2homhet()")
632 onehotChunk = append(onehotChunk, onehot...)
633 onehotXref = append(onehotXref, xrefs...)
640 // Reference does not use any
641 // variant of this tile
643 // TODO: diff against the
644 // relevant portion of the
645 // ref's spanning tile
649 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
651 reftilestr := strings.ToUpper(string(rt.tiledata))
653 done := make([]bool, maxv+1)
654 variantDiffs := make([][]hgvs.Variant, maxv+1)
655 for v, tv := range variants {
657 if v == 0 || v == rt.variant || done[v] {
662 if len(tv.Sequence) < taglen {
665 // if reftilestr doesn't end
666 // in the same tag as tv,
667 // extend reftilestr with
668 // following ref tiles until
669 // it does (up to an arbitrary
670 // sanity-check limit)
671 reftilestr := reftilestr
672 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
673 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
674 rt = reftile[rt.nexttag]
678 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
680 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
683 if !strings.HasSuffix(reftilestr, endtagstr) {
684 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
687 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
688 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
691 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
692 for i := range diffs {
693 diffs[i].Position += rt.pos
695 for _, diff := range diffs {
696 fmt.Fprintf(annow, "%d,%d,%d,%s:g.%s,%s,%d,%s,%s,%s\n", tag, outcol, v, rt.seqname, diff.String(), rt.seqname, diff.Position, diff.Ref, diff.New, diff.Left)
699 variantDiffs[v] = diffs
703 // We can now determine, for each HGVS
704 // variant (diff) in this reftile
705 // region, whether a given genome
706 // phase/allele (1) has the variant, (0) has
707 // =ref or a different variant in that
708 // position, or (-1) is lacking
709 // coverage / couldn't be diffed.
710 hgvsCol := hgvsColSet{}
711 for _, diffs := range variantDiffs {
712 for _, diff := range diffs {
713 if _, ok := hgvsCol[diff]; ok {
716 hgvsCol[diff] = [2][]int8{
717 make([]int8, len(cmd.cgnames)),
718 make([]int8, len(cmd.cgnames)),
722 for row, name := range cmd.cgnames {
723 variants := cgs[name].Variants[(tag-tagstart)*2:]
724 for ph := 0; ph < 2; ph++ {
726 if int(v) >= len(remap) {
732 // hgvsCol[*][ph][row] is already 0
733 } else if len(variantDiffs[v]) == 0 {
734 // lacking coverage / couldn't be diffed
735 for _, col := range hgvsCol {
739 for _, diff := range variantDiffs[v] {
740 hgvsCol[diff][ph][row] = 1
745 for diff, colpair := range hgvsCol {
746 allele2homhet(colpair)
747 if !cmd.filterHGVScolpair(colpair) {
748 delete(hgvsCol, diff)
751 if len(hgvsCol) > 0 {
752 encodeHGVSTodo[rt.seqname] <- hgvsCol
767 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
768 rows := len(cmd.cgnames)
769 cols := len(onehotChunk)
770 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
771 throttleNumpyMem.Acquire()
772 out := onehotcols2int8(onehotChunk)
773 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
774 err = writeNumpyInt8(fnm, out, rows, cols)
778 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
779 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
784 throttleNumpyMem.Release()
786 if *onehotSingle || *onlyPCA {
787 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
788 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
789 onehotXrefs[infileIdx] = onehotXref
790 n := len(onehotIndirect[infileIdx][0])
791 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
793 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
794 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
795 throttleNumpyMem.Acquire()
796 rows := len(cmd.cgnames)
798 out := make([]int16, rows*cols)
799 for row, name := range cmd.cgnames {
801 for col, v := range cgs[name].Variants {
802 tag := tagstart + tagID(col/2)
803 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
806 if rt := reftile[tag]; rt == nil || rt.excluded {
810 out[outidx] = 0 // tag not found / spanning tile
811 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
812 out[outidx] = int16(variantRemap[tag-tagstart][v])
814 out[outidx] = -1 // low quality tile variant
816 if tag == cmd.debugTag {
817 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
825 throttleNumpyMem.Release()
826 if *mergeOutput || *hgvsSingle {
827 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
828 toMerge[infileIdx] = out
830 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
831 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
832 err = writeNumpyInt16(fnm, out, rows, cols)
839 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
843 if err = throttleMem.Wait(); err != nil {
848 log.Info("flushing hgvsCols temp files")
849 for seqname := range refseq {
850 close(encodeHGVSTodo[seqname])
852 err = encodeHGVS.Wait()
856 for seqname := range refseq {
857 log.Infof("%s: reading hgvsCols from temp file", seqname)
858 f := tmpHGVSCols[seqname]
859 _, err = f.Seek(0, io.SeekStart)
863 var hgvsCols hgvsColSet
864 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
866 err = dec.Decode(&hgvsCols)
871 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
872 variants := make([]hgvs.Variant, 0, len(hgvsCols))
873 for v := range hgvsCols {
874 variants = append(variants, v)
876 sort.Slice(variants, func(i, j int) bool {
877 vi, vj := &variants[i], &variants[j]
878 if vi.Position != vj.Position {
879 return vi.Position < vj.Position
880 } else if vi.Ref != vj.Ref {
881 return vi.Ref < vj.Ref
883 return vi.New < vj.New
886 rows := len(cmd.cgnames)
887 cols := len(variants) * 2
888 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
889 out := make([]int8, rows*cols)
890 for varIdx, variant := range variants {
891 hgvsCols := hgvsCols[variant]
892 for row := range cmd.cgnames {
893 for ph := 0; ph < 2; ph++ {
894 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
898 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
904 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
905 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
906 var hgvsLabels bytes.Buffer
907 for varIdx, variant := range variants {
908 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
910 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
917 if *mergeOutput || *hgvsSingle {
918 var annow *bufio.Writer
921 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
922 annof, err = os.Create(annoFilename)
926 annow = bufio.NewWriterSize(annof, 1<<20)
929 rows := len(cmd.cgnames)
931 for _, chunk := range toMerge {
932 cols += len(chunk) / rows
934 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
937 out = make([]int16, rows*cols)
939 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
941 for outIdx, chunk := range toMerge {
942 chunkcols := len(chunk) / rows
944 for row := 0; row < rows; row++ {
945 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
948 toMerge[outIdx] = nil
950 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
951 log.Infof("reading %s", annotationsFilename)
952 buf, err := os.ReadFile(annotationsFilename)
957 err = os.Remove(annotationsFilename)
962 for _, line := range bytes.Split(buf, []byte{'\n'}) {
966 fields := bytes.SplitN(line, []byte{','}, 9)
967 tag, _ := strconv.Atoi(string(fields[0]))
968 incol, _ := strconv.Atoi(string(fields[1]))
969 tileVariant, _ := strconv.Atoi(string(fields[2]))
970 hgvsID := string(fields[3])
971 seqname := string(fields[4])
972 pos, _ := strconv.Atoi(string(fields[5]))
975 // Null entry for un-diffable
980 // Null entry for ref tile
983 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
984 // The tile intersects one of
985 // the selected regions, but
986 // this particular HGVS
990 hgvsColPair := hgvsCols[hgvsID]
991 if hgvsColPair[0] == nil {
992 // values in new columns start
993 // out as -1 ("no data yet")
994 // or 0 ("=ref") here, may
995 // change to 1 ("hgvs variant
996 // present") below, either on
997 // this line or a future line.
998 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
999 rt, ok := reftile[tagID(tag)]
1001 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1004 for ph := 0; ph < 2; ph++ {
1005 for row := 0; row < rows; row++ {
1006 v := chunk[row*chunkcols+incol*2+ph]
1007 if tileVariantID(v) == rt.variant {
1008 hgvsColPair[ph][row] = 0
1010 hgvsColPair[ph][row] = -1
1014 hgvsCols[hgvsID] = hgvsColPair
1016 hgvsref := hgvs.Variant{
1018 Ref: string(refseq),
1019 New: string(refseq),
1021 fmt.Fprintf(annow, "%d,%d,%d,%s:g.%s,%s,%d,%s,%s,%s\n", tag, incol+startcol/2, rt.variant, seqname, hgvsref.String(), seqname, pos, refseq, refseq, fields[8])
1025 fmt.Fprintf(annow, "%d,%d,%d,%s,%s,%d,%s,%s,%s\n", tag, incol+startcol/2, tileVariant, hgvsID, seqname, pos, refseq, fields[7], fields[8])
1027 for ph := 0; ph < 2; ph++ {
1028 for row := 0; row < rows; row++ {
1029 v := chunk[row*chunkcols+incol*2+ph]
1030 if int(v) == tileVariant {
1031 hgvsColPair[ph][row] = 1
1037 startcol += chunkcols
1048 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1056 cols = len(hgvsCols) * 2
1057 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1058 out = make([]int16, rows*cols)
1059 hgvsIDs := make([]string, 0, cols/2)
1060 for hgvsID := range hgvsCols {
1061 hgvsIDs = append(hgvsIDs, hgvsID)
1063 sort.Strings(hgvsIDs)
1064 var hgvsLabels bytes.Buffer
1065 for idx, hgvsID := range hgvsIDs {
1066 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1067 for ph := 0; ph < 2; ph++ {
1068 hgvscol := hgvsCols[hgvsID][ph]
1069 for row, val := range hgvscol {
1070 out[row*cols+idx*2+ph] = val
1074 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1079 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1080 log.Printf("writing hgvs labels: %s", fnm)
1081 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1087 if *onehotSingle || *onlyPCA {
1089 for _, part := range onehotIndirect {
1090 nzCount += len(part[0])
1092 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1093 var xrefs []onehotXref
1094 chunkOffset := uint32(0)
1096 for i, part := range onehotIndirect {
1097 for i := range part[1] {
1098 part[1][i] += chunkOffset
1100 copy(onehot[outcol:], part[0])
1101 copy(onehot[outcol+nzCount:], part[1])
1102 xrefs = append(xrefs, onehotXrefs[i]...)
1104 outcol += len(part[0])
1105 chunkOffset += onehotChunkSize[i]
1109 onehotXrefs[i] = nil
1110 debug.FreeOSMemory()
1113 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1114 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1118 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1119 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1126 for _, c := range onehot[nzCount:] {
1132 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1134 log.Printf("have %d one-hot cols", cols)
1136 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1137 cols = (cols + 1) / 2
1140 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1141 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1142 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1143 for i, c := range onehot[nzCount:] {
1144 if int(c/2)%stride == 0 {
1145 outcol := int(c/2)/stride*2 + int(c)%2
1146 mtxFull.Set(int(onehot[i]), outcol, 1)
1147 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1148 mtxTrain.Set(trainRow, outcol, 1)
1152 log.Print("fitting")
1153 transformer := nlp.NewPCA(*pcaComponents)
1154 transformer.Fit(mtxTrain.T())
1155 log.Printf("transforming")
1156 pca, err := transformer.Transform(mtxFull.T())
1161 outrows, outcols := pca.Dims()
1162 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1163 out := make([]float64, outrows*outcols)
1164 for i := 0; i < outrows; i++ {
1165 for j := 0; j < outcols; j++ {
1166 out[i*outcols+j] = pca.At(i, j)
1169 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1170 log.Printf("writing numpy: %s", fnm)
1171 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1175 npw, err := gonpy.NewWriter(nopCloser{output})
1177 return fmt.Errorf("gonpy.NewWriter: %w", err)
1179 npw.Shape = []int{outrows, outcols}
1180 err = npw.WriteFloat64(out)
1182 return fmt.Errorf("WriteFloat64: %w", err)
1184 err = output.Close()
1191 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1192 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1193 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1195 f, err = os.Create(tagoffsetFilename)
1200 for idx, offset := range chunkStartTag {
1201 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1203 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1209 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1216 // Read training set file(s) from path (may be dir or file) and set up
1219 // cmd.trainingSet[i] == n >= 0 if cmd.cgnames[i] is the nth training
1222 // cmd.trainingSet[i] == -1 if cmd.cgnames[i] is not in the training
1224 func (cmd *sliceNumpy) loadTrainingSet(path string) error {
1225 cmd.trainingSet = make([]int, len(cmd.cgnames))
1227 cmd.trainingSetSize = len(cmd.cgnames)
1228 for i := range cmd.trainingSet {
1229 cmd.trainingSet[i] = i
1233 for i := range cmd.trainingSet {
1234 cmd.trainingSet[i] = -1
1236 infiles, err := allFiles(path, nil)
1240 for _, infile := range infiles {
1241 f, err := open(infile)
1245 buf, err := io.ReadAll(f)
1250 for _, tsv := range bytes.Split(buf, []byte{'\n'}) {
1254 split := strings.Split(string(tsv), "\t")
1257 for i, name := range cmd.cgnames {
1258 if strings.Contains(name, pattern) {
1260 log.Warnf("pattern %q in %s already matched sample ID %q -- not using %q", pattern, infile, cmd.cgnames[found], name)
1263 cmd.trainingSet[found] = 1
1268 log.Warnf("pattern %q in %s does not match any genome IDs", pattern, infile)
1274 for i, x := range cmd.trainingSet {
1276 cmd.trainingSet[i] = tsi
1280 cmd.trainingSetSize = tsi + 1
1284 // Read case/control files, remove non-case/control entries from
1285 // cmd.cgnames, and build cmd.chi2Cases.
1286 func (cmd *sliceNumpy) useCaseControlFiles() error {
1287 if cmd.chi2CaseControlFile == "" {
1290 infiles, err := allFiles(cmd.chi2CaseControlFile, nil)
1294 // index in cmd.cgnames => case(true) / control(false)
1295 cc := map[int]bool{}
1296 for _, infile := range infiles {
1297 f, err := open(infile)
1301 buf, err := io.ReadAll(f)
1307 for _, tsv := range bytes.Split(buf, []byte{'\n'}) {
1311 split := strings.Split(string(tsv), "\t")
1314 for col, name := range split {
1315 if name == cmd.chi2CaseControlColumn {
1321 return fmt.Errorf("%s: no column named %q in header row %q", infile, cmd.chi2CaseControlColumn, tsv)
1325 if len(split) <= ccCol {
1330 for i, name := range cmd.cgnames {
1331 if strings.Contains(name, pattern) {
1333 log.Warnf("pattern %q in %s matches multiple genome IDs (%q, %q)", pattern, infile, cmd.cgnames[found], name)
1336 if split[ccCol] == "0" {
1339 if split[ccCol] == "1" {
1345 log.Warnf("pattern %q in %s does not match any genome IDs", pattern, infile)
1350 allnames := cmd.cgnames
1354 for i, name := range allnames {
1355 if cc, ok := cc[i]; ok {
1356 cmd.cgnames = append(cmd.cgnames, name)
1357 cmd.chi2Cases = append(cmd.chi2Cases, cc)
1363 log.Printf("%d cases, %d controls, %d neither (dropped)", ncases, len(cmd.cgnames)-ncases, len(allnames)-len(cmd.cgnames))
1367 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1368 if cmd.chi2PValue >= 1 {
1371 col0 := make([]bool, 0, len(cmd.chi2Cases))
1372 col1 := make([]bool, 0, len(cmd.chi2Cases))
1373 cases := make([]bool, 0, len(cmd.chi2Cases))
1374 for i, c := range cmd.chi2Cases {
1375 if colpair[0][i] < 0 {
1378 col0 = append(col0, colpair[0][i] != 0)
1379 col1 = append(col1, colpair[1][i] != 0)
1380 cases = append(cases, c)
1382 return len(cases) >= cmd.minCoverage &&
1383 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1386 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1387 output, err := os.Create(fnm)
1391 defer output.Close()
1392 bufw := bufio.NewWriterSize(output, 1<<26)
1393 npw, err := gonpy.NewWriter(nopCloser{bufw})
1397 log.WithFields(log.Fields{
1401 "bytes": rows * cols * 4,
1402 }).Infof("writing numpy: %s", fnm)
1403 npw.Shape = []int{rows, cols}
1404 npw.WriteUint32(out)
1409 return output.Close()
1412 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1413 output, err := os.Create(fnm)
1417 defer output.Close()
1418 bufw := bufio.NewWriterSize(output, 1<<26)
1419 npw, err := gonpy.NewWriter(nopCloser{bufw})
1423 log.WithFields(log.Fields{
1427 "bytes": rows * cols * 4,
1428 }).Infof("writing numpy: %s", fnm)
1429 npw.Shape = []int{rows, cols}
1435 return output.Close()
1438 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1439 output, err := os.Create(fnm)
1443 defer output.Close()
1444 bufw := bufio.NewWriterSize(output, 1<<26)
1445 npw, err := gonpy.NewWriter(nopCloser{bufw})
1449 log.WithFields(log.Fields{
1453 "bytes": rows * cols * 2,
1454 }).Infof("writing numpy: %s", fnm)
1455 npw.Shape = []int{rows, cols}
1461 return output.Close()
1464 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1465 output, err := os.Create(fnm)
1469 defer output.Close()
1470 bufw := bufio.NewWriterSize(output, 1<<26)
1471 npw, err := gonpy.NewWriter(nopCloser{bufw})
1475 log.WithFields(log.Fields{
1479 "bytes": rows * cols,
1480 }).Infof("writing numpy: %s", fnm)
1481 npw.Shape = []int{rows, cols}
1487 return output.Close()
1490 func allele2homhet(colpair [2][]int8) {
1491 a, b := colpair[0], colpair[1]
1492 for i, av := range a {
1494 if av < 0 || bv < 0 {
1497 } else if av > 0 && bv > 0 {
1500 } else if av > 0 || bv > 0 {
1504 // ref (or a different variant in same position)
1505 // (this is a no-op) a[i], b[i] = 0, 0
1510 type onehotXref struct {
1512 variant tileVariantID
1517 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1519 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1520 // variants of a single tile/tag#.
1522 // Return nil if no tile variant passes Χ² filter.
1523 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1524 if tag == cmd.debugTag {
1525 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1526 for i, name := range cmd.cgnames {
1527 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1529 log.WithFields(logrus.Fields{
1530 "cgs[i].Variants[tag*2+j]": tv,
1534 "chunkstarttag": chunkstarttag,
1535 }).Info("tv2homhet()")
1537 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1538 // everyone has the most common variant (of the variants we don't drop)
1541 tagoffset := tag - chunkstarttag
1543 for _, cg := range cgs {
1545 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1546 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1554 if coverage < cmd.minCoverage {
1557 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1558 for i := range obs {
1559 obs[i] = make([]bool, len(cmd.cgnames))
1561 for cgid, name := range cmd.cgnames {
1562 cgvars := cgs[name].Variants[tagoffset*2:]
1563 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1564 for v := tileVariantID(1); v <= maxv; v++ {
1565 if tv0 == v && tv1 == v {
1566 obs[v*2][cgid] = true
1567 } else if tv0 == v || tv1 == v {
1568 obs[v*2+1][cgid] = true
1573 var xref []onehotXref
1574 for col := 2; col < len(obs); col++ {
1575 // col 0,1 correspond to tile variant 0, i.e.,
1576 // no-call; col 2,3 correspond to the most common
1577 // variant; so we (normally) start at col 4.
1578 if col < 4 && !cmd.includeVariant1 {
1581 p := pvalue(obs[col], cmd.chi2Cases)
1582 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1585 onehot = append(onehot, bool2int8(obs[col]))
1586 xref = append(xref, onehotXref{
1588 variant: tileVariantID(col >> 1),
1596 func bool2int8(in []bool) []int8 {
1597 out := make([]int8, len(in))
1598 for i, v := range in {
1606 // convert a []onehotXref with length N to a numpy-style []int32
1607 // matrix with N columns, one row per field of onehotXref struct.
1609 // Hom/het row contains hom=0, het=1.
1611 // P-value row contains 1000000x actual p-value.
1612 func onehotXref2int32(xrefs []onehotXref) []int32 {
1614 xdata := make([]int32, 5*xcols)
1615 for i, xref := range xrefs {
1616 xdata[i] = int32(xref.tag)
1617 xdata[xcols+i] = int32(xref.variant)
1619 xdata[xcols*2+i] = 1
1621 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1622 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1627 // transpose onehot data from in[col][row] to numpy-style
1628 // out[row*cols+col].
1629 func onehotcols2int8(in [][]int8) []int8 {
1635 out := make([]int8, rows*cols)
1636 for row := 0; row < rows; row++ {
1637 outrow := out[row*cols:]
1638 for col, incol := range in {
1639 outrow[col] = incol[row]
1645 // Return [2][]uint32{rowIndices, colIndices} indicating which
1646 // elements of matrixT[c][r] have non-zero values.
1647 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1649 for c, col := range matrixT {
1650 for r, val := range col {
1652 nz[0] = append(nz[0], uint32(r))
1653 nz[1] = append(nz[1], uint32(c))