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 {
52 trainingSet []int // samples index => training set index, or -1 if not in training set
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 samplesFilename := flags.String("samples", "", "`samples.csv` file with training/validation and case/control groups (see 'lightning choose-samples')")
85 caseControlOnly := flags.Bool("case-control-only", false, "drop samples that are not in case/control groups")
86 onlyPCA := flags.Bool("pca", false, "generate pca matrix")
87 pcaComponents := flags.Int("pca-components", 4, "number of PCA components")
88 maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
89 debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
90 flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
91 flags.Float64Var(&cmd.chi2PValue, "chi2-p-value", 1, "do Χ² test and omit columns with p-value above this threshold")
92 flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
93 cmd.filter.Flags(flags)
94 err := flags.Parse(args)
95 if err == flag.ErrHelp {
97 } else if err != nil {
103 log.Println(http.ListenAndServe(*pprof, nil))
107 if cmd.chi2PValue != 1 && *samplesFilename == "" {
108 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -samples= value is empty", cmd.chi2PValue)
111 cmd.debugTag = tagID(*debugTag)
114 runner := arvadosContainerRunner{
115 Name: "lightning slice-numpy",
116 Client: arvados.NewClientFromEnv(),
117 ProjectUUID: *projectUUID,
118 RAM: int64(*arvadosRAM),
119 VCPUs: *arvadosVCPUs,
124 err = runner.TranslatePaths(inputDir, regionsFilename, samplesFilename)
128 runner.Args = []string{"slice-numpy", "-local=true",
130 "-input-dir=" + *inputDir,
131 "-output-dir=/mnt/output",
132 "-threads=" + fmt.Sprintf("%d", cmd.threads),
133 "-regions=" + *regionsFilename,
134 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
135 "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
136 "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
137 "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
138 "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
139 "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
140 "-samples=" + *samplesFilename,
141 "-case-control-only=" + fmt.Sprintf("%v", *caseControlOnly),
142 "-pca=" + fmt.Sprintf("%v", *onlyPCA),
143 "-pca-components=" + fmt.Sprintf("%d", *pcaComponents),
144 "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
145 "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
146 "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
147 "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
149 runner.Args = append(runner.Args, cmd.filter.Args()...)
151 output, err = runner.Run()
155 fmt.Fprintln(stdout, output)
159 infiles, err := allFiles(*inputDir, matchGobFile)
163 if len(infiles) == 0 {
164 err = fmt.Errorf("no input files found in %s", *inputDir)
167 sort.Strings(infiles)
169 var refseq map[string][]tileLibRef
170 var reftiledata = make(map[tileLibRef][]byte, 11000000)
171 in0, err := open(infiles[0])
176 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
178 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
182 if *samplesFilename != "" {
183 cmd.samples, err = cmd.loadSampleInfo(*samplesFilename)
187 } else if *caseControlOnly {
188 return fmt.Errorf("-case-control-only does not make sense without -samples")
193 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
194 if len(ent.TagSet) > 0 {
197 for _, cseq := range ent.CompactSequences {
198 if cseq.Name == *ref || *ref == "" {
199 refseq = cseq.TileSequences
202 for _, cg := range ent.CompactGenomes {
203 if matchGenome.MatchString(cg.Name) {
204 cmd.cgnames = append(cmd.cgnames, cg.Name)
207 for _, tv := range ent.TileVariants {
209 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
219 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
222 if len(tagset) == 0 {
223 err = fmt.Errorf("tagset not found")
227 taglib := &tagLibrary{}
228 err = taglib.setTags(tagset)
232 taglen := taglib.TagLen()
233 sort.Strings(cmd.cgnames)
235 if len(cmd.cgnames) == 0 {
236 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
238 cmd.trainingSet = make([]int, len(cmd.cgnames))
239 if *samplesFilename == "" {
240 cmd.trainingSetSize = len(cmd.cgnames)
241 for i, name := range cmd.cgnames {
242 cmd.samples = append(cmd.samples, sampleInfo{
243 id: trimFilenameForLabel(name),
246 cmd.trainingSet[i] = i
248 } else if len(cmd.cgnames) != len(cmd.samples) {
249 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
251 for i, name := range cmd.cgnames {
252 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
253 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
256 if *caseControlOnly {
257 for i := 0; i < len(cmd.samples); i++ {
258 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
259 if i+1 < len(cmd.samples) {
260 copy(cmd.samples[i:], cmd.samples[i+1:])
261 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
263 cmd.samples = cmd.samples[:len(cmd.samples)-1]
264 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
269 cmd.trainingSetSize = 0
270 for i := range cmd.cgnames {
271 if cmd.samples[i].isTraining {
272 cmd.trainingSet[i] = cmd.trainingSetSize
273 cmd.trainingSetSize++
275 cmd.trainingSet[i] = -1
279 if cmd.filter.MinCoverage == 1 {
280 // In the generic formula below, floating point
281 // arithmetic can effectively push the coverage
282 // threshold above 1.0, which is impossible/useless.
283 // 1.0 needs to mean exactly 100% coverage.
284 cmd.minCoverage = len(cmd.cgnames)
286 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
290 samplesOutFilename := *outputDir + "/samples.csv"
291 log.Infof("writing sample metadata to %s", samplesOutFilename)
293 f, err = os.Create(samplesOutFilename)
298 for i, si := range cmd.samples {
302 } else if si.isControl {
310 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
312 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
318 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
324 log.Info("indexing reference tiles")
325 type reftileinfo struct {
326 variant tileVariantID
327 seqname string // chr1
328 pos int // distance from start of chromosome to starttag
329 tiledata []byte // acgtggcaa...
330 excluded bool // true if excluded by regions file
331 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
333 isdup := map[tagID]bool{}
334 reftile := map[tagID]*reftileinfo{}
335 for seqname, cseq := range refseq {
337 lastreftag := tagID(-1)
338 for _, libref := range cseq {
339 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
342 tiledata := reftiledata[libref]
343 if len(tiledata) == 0 {
344 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
347 foundthistag := false
348 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
349 if !foundthistag && tagid == libref.Tag {
353 if dupref, ok := reftile[tagid]; ok {
354 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)
355 delete(reftile, tagid)
357 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
361 if isdup[libref.Tag] {
362 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
363 } else if reftile[libref.Tag] != nil {
364 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)
365 delete(reftile, libref.Tag)
366 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
367 isdup[libref.Tag] = true
369 reftile[libref.Tag] = &reftileinfo{
371 variant: libref.Variant,
377 reftile[lastreftag].nexttag = libref.Tag
379 lastreftag = libref.Tag
381 pos += len(tiledata) - taglen
383 log.Printf("... %s done, len %d", seqname, pos+taglen)
387 if *regionsFilename != "" {
388 log.Printf("loading regions from %s", *regionsFilename)
389 mask, err = makeMask(*regionsFilename, *expandRegions)
393 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
394 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
395 for _, rt := range reftile {
396 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
400 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
403 type hgvsColSet map[hgvs.Variant][2][]int8
404 encodeHGVS := throttle{Max: len(refseq)}
405 encodeHGVSTodo := map[string]chan hgvsColSet{}
406 tmpHGVSCols := map[string]*os.File{}
408 for seqname := range refseq {
410 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
414 defer os.Remove(f.Name())
415 bufw := bufio.NewWriterSize(f, 1<<24)
416 enc := gob.NewEncoder(bufw)
417 tmpHGVSCols[seqname] = f
418 todo := make(chan hgvsColSet, 128)
419 encodeHGVSTodo[seqname] = todo
420 encodeHGVS.Go(func() error {
421 for colset := range todo {
422 err := enc.Encode(colset)
424 encodeHGVS.Report(err)
435 var toMerge [][]int16
436 if *mergeOutput || *hgvsSingle {
437 toMerge = make([][]int16, len(infiles))
439 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
440 var onehotChunkSize []uint32
441 var onehotXrefs [][]onehotXref
442 if *onehotSingle || *onlyPCA {
443 onehotIndirect = make([][2][]uint32, len(infiles))
444 onehotChunkSize = make([]uint32, len(infiles))
445 onehotXrefs = make([][]onehotXref, len(infiles))
447 chunkStartTag := make([]tagID, len(infiles))
449 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
450 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
451 log.Info("generating annotations and numpy matrix for each slice")
452 var errSkip = errors.New("skip infile")
454 for infileIdx, infile := range infiles {
455 infileIdx, infile := infileIdx, infile
456 throttleMem.Go(func() error {
457 seq := make(map[tagID][]TileVariant, 50000)
458 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
459 f, err := open(infile)
464 log.Infof("%04d: reading %s", infileIdx, infile)
465 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
466 for _, tv := range ent.TileVariants {
471 // corresponding ref tile, if
472 // mask is in play (we can't
473 // determine coordinates for
475 if mask != nil && reftile[tv.Tag] == nil {
479 // corresponding ref tile is
480 // outside target regions --
481 // unless it's a potential
483 if mask != nil && reftile[tv.Tag].excluded &&
484 (int(tv.Tag+1) >= len(tagset) ||
485 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
488 if tv.Tag == cmd.debugTag {
489 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
491 variants := seq[tv.Tag]
492 if len(variants) == 0 {
493 variants = make([]TileVariant, 100)
495 for len(variants) <= int(tv.Variant) {
496 variants = append(variants, TileVariant{})
498 variants[int(tv.Variant)] = tv
499 seq[tv.Tag] = variants
501 for _, cg := range ent.CompactGenomes {
502 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
505 if !matchGenome.MatchString(cg.Name) {
508 // pad to full slice size
509 // to avoid out-of-bounds
511 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
512 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
520 } else if err != nil {
521 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
523 tagstart := cgs[cmd.cgnames[0]].StartTag
524 tagend := cgs[cmd.cgnames[0]].EndTag
525 chunkStartTag[infileIdx] = tagstart
529 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
530 variantRemap := make([][]tileVariantID, tagend-tagstart)
531 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
532 for tag, variants := range seq {
533 tag, variants := tag, variants
534 throttleCPU.Go(func() error {
536 count := make(map[[blake2b.Size256]byte]int, len(variants))
540 count[blake2b.Sum256(rt.tiledata)] = 0
543 for cgname, cg := range cgs {
544 idx := int(tag-tagstart) * 2
545 for allele := 0; allele < 2; allele++ {
546 v := cg.Variants[idx+allele]
547 if v > 0 && len(variants[v].Sequence) > 0 {
548 count[variants[v].Blake2b]++
551 if v > 0 && tag == cmd.debugTag {
552 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])
556 if alleleCoverage < cmd.minCoverage*2 {
557 idx := int(tag-tagstart) * 2
558 for _, cg := range cgs {
560 cg.Variants[idx+1] = 0
562 if tag == cmd.debugTag {
563 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
568 // hash[i] will be the hash of
569 // the variant(s) that should
570 // be at rank i (0-based).
571 hash := make([][blake2b.Size256]byte, 0, len(count))
572 for b := range count {
573 hash = append(hash, b)
575 sort.Slice(hash, func(i, j int) bool {
576 bi, bj := &hash[i], &hash[j]
577 if ci, cj := count[*bi], count[*bj]; ci != cj {
580 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
583 // rank[b] will be the 1-based
584 // new variant number for
585 // variants whose hash is b.
586 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
587 for i, h := range hash {
588 rank[h] = tileVariantID(i + 1)
590 if tag == cmd.debugTag {
591 for h, r := range rank {
592 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
595 // remap[v] will be the new
596 // variant number for original
598 remap := make([]tileVariantID, len(variants))
599 for i, tv := range variants {
600 remap[i] = rank[tv.Blake2b]
602 if tag == cmd.debugTag {
603 for in, out := range remap {
605 log.Printf("tag %d remap %d => %d", tag, in, out)
609 variantRemap[tag-tagstart] = remap
611 refrank := rank[blake2b.Sum256(rt.tiledata)]
612 if tag == cmd.debugTag {
613 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
622 var onehotChunk [][]int8
623 var onehotXref []onehotXref
625 var annotationsFilename string
627 annotationsFilename = "/dev/null"
629 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
630 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
632 annof, err := os.Create(annotationsFilename)
636 annow := bufio.NewWriterSize(annof, 1<<20)
638 for tag := tagstart; tag < tagend; tag++ {
640 if rt == nil && mask != nil {
641 // With no ref tile, we don't
642 // have coordinates to say
643 // this is in the desired
644 // regions -- so it's not.
645 // TODO: handle ref spanning
649 if rt != nil && rt.excluded {
650 // TODO: don't skip yet --
651 // first check for spanning
652 // tile variants that
653 // intersect non-excluded ref
657 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
660 remap := variantRemap[tag-tagstart]
662 // was not assigned above,
663 // because minCoverage
666 maxv := tileVariantID(0)
667 for _, v := range remap {
672 if *onehotChunked || *onehotSingle || *onlyPCA {
673 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
674 if tag == cmd.debugTag {
675 log.WithFields(logrus.Fields{
678 }).Info("tv2homhet()")
680 onehotChunk = append(onehotChunk, onehot...)
681 onehotXref = append(onehotXref, xrefs...)
688 // Reference does not use any
689 // variant of this tile
691 // TODO: diff against the
692 // relevant portion of the
693 // ref's spanning tile
697 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
699 reftilestr := strings.ToUpper(string(rt.tiledata))
701 done := make([]bool, maxv+1)
702 variantDiffs := make([][]hgvs.Variant, maxv+1)
703 for v, tv := range variants {
705 if v == 0 || v == rt.variant || done[v] {
710 if len(tv.Sequence) < taglen {
713 // if reftilestr doesn't end
714 // in the same tag as tv,
715 // extend reftilestr with
716 // following ref tiles until
717 // it does (up to an arbitrary
718 // sanity-check limit)
719 reftilestr := reftilestr
720 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
721 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
722 rt = reftile[rt.nexttag]
726 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
728 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
731 if !strings.HasSuffix(reftilestr, endtagstr) {
732 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
735 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
736 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
739 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
740 for i := range diffs {
741 diffs[i].Position += rt.pos
743 for _, diff := range diffs {
744 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)
747 variantDiffs[v] = diffs
751 // We can now determine, for each HGVS
752 // variant (diff) in this reftile
753 // region, whether a given genome
754 // phase/allele (1) has the variant, (0) has
755 // =ref or a different variant in that
756 // position, or (-1) is lacking
757 // coverage / couldn't be diffed.
758 hgvsCol := hgvsColSet{}
759 for _, diffs := range variantDiffs {
760 for _, diff := range diffs {
761 if _, ok := hgvsCol[diff]; ok {
764 hgvsCol[diff] = [2][]int8{
765 make([]int8, len(cmd.cgnames)),
766 make([]int8, len(cmd.cgnames)),
770 for row, name := range cmd.cgnames {
771 variants := cgs[name].Variants[(tag-tagstart)*2:]
772 for ph := 0; ph < 2; ph++ {
774 if int(v) >= len(remap) {
780 // hgvsCol[*][ph][row] is already 0
781 } else if len(variantDiffs[v]) == 0 {
782 // lacking coverage / couldn't be diffed
783 for _, col := range hgvsCol {
787 for _, diff := range variantDiffs[v] {
788 hgvsCol[diff][ph][row] = 1
793 for diff, colpair := range hgvsCol {
794 allele2homhet(colpair)
795 if !cmd.filterHGVScolpair(colpair) {
796 delete(hgvsCol, diff)
799 if len(hgvsCol) > 0 {
800 encodeHGVSTodo[rt.seqname] <- hgvsCol
815 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
816 rows := len(cmd.cgnames)
817 cols := len(onehotChunk)
818 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
819 throttleNumpyMem.Acquire()
820 out := onehotcols2int8(onehotChunk)
821 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
822 err = writeNumpyInt8(fnm, out, rows, cols)
826 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
827 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
832 throttleNumpyMem.Release()
834 if *onehotSingle || *onlyPCA {
835 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
836 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
837 onehotXrefs[infileIdx] = onehotXref
838 n := len(onehotIndirect[infileIdx][0])
839 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
841 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
842 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
843 throttleNumpyMem.Acquire()
844 rows := len(cmd.cgnames)
846 out := make([]int16, rows*cols)
847 for row, name := range cmd.cgnames {
849 for col, v := range cgs[name].Variants {
850 tag := tagstart + tagID(col/2)
851 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
854 if rt := reftile[tag]; rt == nil || rt.excluded {
858 out[outidx] = 0 // tag not found / spanning tile
859 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
860 out[outidx] = int16(variantRemap[tag-tagstart][v])
862 out[outidx] = -1 // low quality tile variant
864 if tag == cmd.debugTag {
865 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
873 throttleNumpyMem.Release()
874 if *mergeOutput || *hgvsSingle {
875 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
876 toMerge[infileIdx] = out
878 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
879 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
880 err = writeNumpyInt16(fnm, out, rows, cols)
887 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
891 if err = throttleMem.Wait(); err != nil {
896 log.Info("flushing hgvsCols temp files")
897 for seqname := range refseq {
898 close(encodeHGVSTodo[seqname])
900 err = encodeHGVS.Wait()
904 for seqname := range refseq {
905 log.Infof("%s: reading hgvsCols from temp file", seqname)
906 f := tmpHGVSCols[seqname]
907 _, err = f.Seek(0, io.SeekStart)
911 var hgvsCols hgvsColSet
912 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
914 err = dec.Decode(&hgvsCols)
919 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
920 variants := make([]hgvs.Variant, 0, len(hgvsCols))
921 for v := range hgvsCols {
922 variants = append(variants, v)
924 sort.Slice(variants, func(i, j int) bool {
925 vi, vj := &variants[i], &variants[j]
926 if vi.Position != vj.Position {
927 return vi.Position < vj.Position
928 } else if vi.Ref != vj.Ref {
929 return vi.Ref < vj.Ref
931 return vi.New < vj.New
934 rows := len(cmd.cgnames)
935 cols := len(variants) * 2
936 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
937 out := make([]int8, rows*cols)
938 for varIdx, variant := range variants {
939 hgvsCols := hgvsCols[variant]
940 for row := range cmd.cgnames {
941 for ph := 0; ph < 2; ph++ {
942 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
946 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
952 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
953 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
954 var hgvsLabels bytes.Buffer
955 for varIdx, variant := range variants {
956 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
958 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
965 if *mergeOutput || *hgvsSingle {
966 var annow *bufio.Writer
969 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
970 annof, err = os.Create(annoFilename)
974 annow = bufio.NewWriterSize(annof, 1<<20)
977 rows := len(cmd.cgnames)
979 for _, chunk := range toMerge {
980 cols += len(chunk) / rows
982 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
985 out = make([]int16, rows*cols)
987 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
989 for outIdx, chunk := range toMerge {
990 chunkcols := len(chunk) / rows
992 for row := 0; row < rows; row++ {
993 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
996 toMerge[outIdx] = nil
998 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
999 log.Infof("reading %s", annotationsFilename)
1000 buf, err := os.ReadFile(annotationsFilename)
1005 err = os.Remove(annotationsFilename)
1010 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1014 fields := bytes.SplitN(line, []byte{','}, 9)
1015 tag, _ := strconv.Atoi(string(fields[0]))
1016 incol, _ := strconv.Atoi(string(fields[1]))
1017 tileVariant, _ := strconv.Atoi(string(fields[2]))
1018 hgvsID := string(fields[3])
1019 seqname := string(fields[4])
1020 pos, _ := strconv.Atoi(string(fields[5]))
1023 // Null entry for un-diffable
1028 // Null entry for ref tile
1031 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1032 // The tile intersects one of
1033 // the selected regions, but
1034 // this particular HGVS
1035 // variant does not.
1038 hgvsColPair := hgvsCols[hgvsID]
1039 if hgvsColPair[0] == nil {
1040 // values in new columns start
1041 // out as -1 ("no data yet")
1042 // or 0 ("=ref") here, may
1043 // change to 1 ("hgvs variant
1044 // present") below, either on
1045 // this line or a future line.
1046 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1047 rt, ok := reftile[tagID(tag)]
1049 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1052 for ph := 0; ph < 2; ph++ {
1053 for row := 0; row < rows; row++ {
1054 v := chunk[row*chunkcols+incol*2+ph]
1055 if tileVariantID(v) == rt.variant {
1056 hgvsColPair[ph][row] = 0
1058 hgvsColPair[ph][row] = -1
1062 hgvsCols[hgvsID] = hgvsColPair
1064 hgvsref := hgvs.Variant{
1066 Ref: string(refseq),
1067 New: string(refseq),
1069 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])
1073 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])
1075 for ph := 0; ph < 2; ph++ {
1076 for row := 0; row < rows; row++ {
1077 v := chunk[row*chunkcols+incol*2+ph]
1078 if int(v) == tileVariant {
1079 hgvsColPair[ph][row] = 1
1085 startcol += chunkcols
1096 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1104 cols = len(hgvsCols) * 2
1105 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1106 out = make([]int16, rows*cols)
1107 hgvsIDs := make([]string, 0, cols/2)
1108 for hgvsID := range hgvsCols {
1109 hgvsIDs = append(hgvsIDs, hgvsID)
1111 sort.Strings(hgvsIDs)
1112 var hgvsLabels bytes.Buffer
1113 for idx, hgvsID := range hgvsIDs {
1114 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1115 for ph := 0; ph < 2; ph++ {
1116 hgvscol := hgvsCols[hgvsID][ph]
1117 for row, val := range hgvscol {
1118 out[row*cols+idx*2+ph] = val
1122 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1127 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1128 log.Printf("writing hgvs labels: %s", fnm)
1129 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1135 if *onehotSingle || *onlyPCA {
1137 for _, part := range onehotIndirect {
1138 nzCount += len(part[0])
1140 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1141 var xrefs []onehotXref
1142 chunkOffset := uint32(0)
1144 for i, part := range onehotIndirect {
1145 for i := range part[1] {
1146 part[1][i] += chunkOffset
1148 copy(onehot[outcol:], part[0])
1149 copy(onehot[outcol+nzCount:], part[1])
1150 xrefs = append(xrefs, onehotXrefs[i]...)
1152 outcol += len(part[0])
1153 chunkOffset += onehotChunkSize[i]
1157 onehotXrefs[i] = nil
1158 debug.FreeOSMemory()
1161 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1162 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1166 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1167 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1174 for _, c := range onehot[nzCount:] {
1180 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1182 log.Printf("have %d one-hot cols", cols)
1184 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1185 cols = (cols + 1) / 2
1188 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1189 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1190 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1191 for i, c := range onehot[nzCount:] {
1192 if int(c/2)%stride == 0 {
1193 outcol := int(c/2)/stride*2 + int(c)%2
1194 mtxFull.Set(int(onehot[i]), outcol, 1)
1195 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1196 mtxTrain.Set(trainRow, outcol, 1)
1200 log.Print("fitting")
1201 transformer := nlp.NewPCA(*pcaComponents)
1202 transformer.Fit(mtxTrain.T())
1203 log.Printf("transforming")
1204 pca, err := transformer.Transform(mtxFull.T())
1209 outrows, outcols := pca.Dims()
1210 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1211 out := make([]float64, outrows*outcols)
1212 for i := 0; i < outrows; i++ {
1213 for j := 0; j < outcols; j++ {
1214 out[i*outcols+j] = pca.At(i, j)
1217 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1218 log.Printf("writing numpy: %s", fnm)
1219 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1223 npw, err := gonpy.NewWriter(nopCloser{output})
1225 return fmt.Errorf("gonpy.NewWriter: %w", err)
1227 npw.Shape = []int{outrows, outcols}
1228 err = npw.WriteFloat64(out)
1230 return fmt.Errorf("WriteFloat64: %w", err)
1232 err = output.Close()
1238 samplesOutFilename := *outputDir + "/samples.csv"
1239 log.Infof("writing sample metadata to %s", samplesOutFilename)
1241 f, err = os.Create(samplesOutFilename)
1246 for i, si := range cmd.samples {
1250 } else if si.isControl {
1259 for c := 0; c < outcols; c++ {
1260 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1262 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1264 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1270 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1276 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1277 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1278 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1280 f, err = os.Create(tagoffsetFilename)
1285 for idx, offset := range chunkStartTag {
1286 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1288 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1294 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1302 type sampleInfo struct {
1308 pcaComponents []float64
1311 // Read samples.csv file with case/control and training/validation
1313 func (cmd *sliceNumpy) loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1315 f, err := open(samplesFilename)
1319 buf, err := io.ReadAll(f)
1325 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1330 split := strings.Split(string(csv), ",")
1331 if len(split) != 4 {
1332 return nil, fmt.Errorf("%d fields != 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1334 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1337 idx, err := strconv.Atoi(split[0])
1340 return nil, fmt.Errorf("header does not look right: %q", csv)
1342 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1345 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1347 si = append(si, sampleInfo{
1349 isCase: split[2] == "1",
1350 isControl: split[2] == "0",
1351 isTraining: split[3] == "1",
1352 isValidation: split[3] == "0",
1358 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1359 if cmd.chi2PValue >= 1 {
1362 col0 := make([]bool, 0, len(cmd.chi2Cases))
1363 col1 := make([]bool, 0, len(cmd.chi2Cases))
1364 cases := make([]bool, 0, len(cmd.chi2Cases))
1365 for i, c := range cmd.chi2Cases {
1366 if colpair[0][i] < 0 {
1369 col0 = append(col0, colpair[0][i] != 0)
1370 col1 = append(col1, colpair[1][i] != 0)
1371 cases = append(cases, c)
1373 return len(cases) >= cmd.minCoverage &&
1374 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1377 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1378 output, err := os.Create(fnm)
1382 defer output.Close()
1383 bufw := bufio.NewWriterSize(output, 1<<26)
1384 npw, err := gonpy.NewWriter(nopCloser{bufw})
1388 log.WithFields(log.Fields{
1392 "bytes": rows * cols * 4,
1393 }).Infof("writing numpy: %s", fnm)
1394 npw.Shape = []int{rows, cols}
1395 npw.WriteUint32(out)
1400 return output.Close()
1403 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1404 output, err := os.Create(fnm)
1408 defer output.Close()
1409 bufw := bufio.NewWriterSize(output, 1<<26)
1410 npw, err := gonpy.NewWriter(nopCloser{bufw})
1414 log.WithFields(log.Fields{
1418 "bytes": rows * cols * 4,
1419 }).Infof("writing numpy: %s", fnm)
1420 npw.Shape = []int{rows, cols}
1426 return output.Close()
1429 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1430 output, err := os.Create(fnm)
1434 defer output.Close()
1435 bufw := bufio.NewWriterSize(output, 1<<26)
1436 npw, err := gonpy.NewWriter(nopCloser{bufw})
1440 log.WithFields(log.Fields{
1444 "bytes": rows * cols * 2,
1445 }).Infof("writing numpy: %s", fnm)
1446 npw.Shape = []int{rows, cols}
1452 return output.Close()
1455 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1456 output, err := os.Create(fnm)
1460 defer output.Close()
1461 bufw := bufio.NewWriterSize(output, 1<<26)
1462 npw, err := gonpy.NewWriter(nopCloser{bufw})
1466 log.WithFields(log.Fields{
1470 "bytes": rows * cols,
1471 }).Infof("writing numpy: %s", fnm)
1472 npw.Shape = []int{rows, cols}
1478 return output.Close()
1481 func allele2homhet(colpair [2][]int8) {
1482 a, b := colpair[0], colpair[1]
1483 for i, av := range a {
1485 if av < 0 || bv < 0 {
1488 } else if av > 0 && bv > 0 {
1491 } else if av > 0 || bv > 0 {
1495 // ref (or a different variant in same position)
1496 // (this is a no-op) a[i], b[i] = 0, 0
1501 type onehotXref struct {
1503 variant tileVariantID
1508 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1510 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1511 // variants of a single tile/tag#.
1513 // Return nil if no tile variant passes Χ² filter.
1514 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1515 if tag == cmd.debugTag {
1516 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1517 for i, name := range cmd.cgnames {
1518 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1520 log.WithFields(logrus.Fields{
1521 "cgs[i].Variants[tag*2+j]": tv,
1525 "chunkstarttag": chunkstarttag,
1526 }).Info("tv2homhet()")
1528 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1529 // everyone has the most common variant (of the variants we don't drop)
1532 tagoffset := tag - chunkstarttag
1534 for _, cg := range cgs {
1536 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1537 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1545 if coverage < cmd.minCoverage {
1548 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1549 for i := range obs {
1550 obs[i] = make([]bool, cmd.trainingSetSize)
1552 for cgid, name := range cmd.cgnames {
1553 tsid := cmd.trainingSet[cgid]
1557 cgvars := cgs[name].Variants[tagoffset*2:]
1558 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1559 for v := tileVariantID(1); v <= maxv; v++ {
1560 if tv0 == v && tv1 == v {
1561 obs[v*2][tsid] = true
1562 } else if tv0 == v || tv1 == v {
1563 obs[v*2+1][tsid] = true
1568 var xref []onehotXref
1569 for col := 2; col < len(obs); col++ {
1570 // col 0,1 correspond to tile variant 0, i.e.,
1571 // no-call; col 2,3 correspond to the most common
1572 // variant; so we (normally) start at col 4.
1573 if col < 4 && !cmd.includeVariant1 {
1576 p := pvalue(obs[col], cmd.chi2Cases)
1577 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1580 onehot = append(onehot, bool2int8(obs[col]))
1581 xref = append(xref, onehotXref{
1583 variant: tileVariantID(col >> 1),
1591 func bool2int8(in []bool) []int8 {
1592 out := make([]int8, len(in))
1593 for i, v := range in {
1601 // convert a []onehotXref with length N to a numpy-style []int32
1602 // matrix with N columns, one row per field of onehotXref struct.
1604 // Hom/het row contains hom=0, het=1.
1606 // P-value row contains 1000000x actual p-value.
1607 func onehotXref2int32(xrefs []onehotXref) []int32 {
1609 xdata := make([]int32, 5*xcols)
1610 for i, xref := range xrefs {
1611 xdata[i] = int32(xref.tag)
1612 xdata[xcols+i] = int32(xref.variant)
1614 xdata[xcols*2+i] = 1
1616 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1617 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1622 // transpose onehot data from in[col][row] to numpy-style
1623 // out[row*cols+col].
1624 func onehotcols2int8(in [][]int8) []int8 {
1630 out := make([]int8, rows*cols)
1631 for row := 0; row < rows; row++ {
1632 outrow := out[row*cols:]
1633 for col, incol := range in {
1634 outrow[col] = incol[row]
1640 // Return [2][]uint32{rowIndices, colIndices} indicating which
1641 // elements of matrixT[c][r] have non-zero values.
1642 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1644 for c, col := range matrixT {
1645 for r, val := range col {
1647 nz[0] = append(nz[0], uint32(r))
1648 nz[1] = append(nz[1], uint32(c))