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))))
289 log.Info("indexing reference tiles")
290 type reftileinfo struct {
291 variant tileVariantID
292 seqname string // chr1
293 pos int // distance from start of chromosome to starttag
294 tiledata []byte // acgtggcaa...
295 excluded bool // true if excluded by regions file
296 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
298 isdup := map[tagID]bool{}
299 reftile := map[tagID]*reftileinfo{}
300 for seqname, cseq := range refseq {
302 lastreftag := tagID(-1)
303 for _, libref := range cseq {
304 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
307 tiledata := reftiledata[libref]
308 if len(tiledata) == 0 {
309 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
312 foundthistag := false
313 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
314 if !foundthistag && tagid == libref.Tag {
318 if dupref, ok := reftile[tagid]; ok {
319 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)
320 delete(reftile, tagid)
322 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
326 if isdup[libref.Tag] {
327 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
328 } else if reftile[libref.Tag] != nil {
329 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)
330 delete(reftile, libref.Tag)
331 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
332 isdup[libref.Tag] = true
334 reftile[libref.Tag] = &reftileinfo{
336 variant: libref.Variant,
342 reftile[lastreftag].nexttag = libref.Tag
344 lastreftag = libref.Tag
346 pos += len(tiledata) - taglen
348 log.Printf("... %s done, len %d", seqname, pos+taglen)
352 if *regionsFilename != "" {
353 log.Printf("loading regions from %s", *regionsFilename)
354 mask, err = makeMask(*regionsFilename, *expandRegions)
358 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
359 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
360 for _, rt := range reftile {
361 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
365 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
368 type hgvsColSet map[hgvs.Variant][2][]int8
369 encodeHGVS := throttle{Max: len(refseq)}
370 encodeHGVSTodo := map[string]chan hgvsColSet{}
371 tmpHGVSCols := map[string]*os.File{}
373 for seqname := range refseq {
375 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
379 defer os.Remove(f.Name())
380 bufw := bufio.NewWriterSize(f, 1<<24)
381 enc := gob.NewEncoder(bufw)
382 tmpHGVSCols[seqname] = f
383 todo := make(chan hgvsColSet, 128)
384 encodeHGVSTodo[seqname] = todo
385 encodeHGVS.Go(func() error {
386 for colset := range todo {
387 err := enc.Encode(colset)
389 encodeHGVS.Report(err)
400 var toMerge [][]int16
401 if *mergeOutput || *hgvsSingle {
402 toMerge = make([][]int16, len(infiles))
404 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
405 var onehotChunkSize []uint32
406 var onehotXrefs [][]onehotXref
407 if *onehotSingle || *onlyPCA {
408 onehotIndirect = make([][2][]uint32, len(infiles))
409 onehotChunkSize = make([]uint32, len(infiles))
410 onehotXrefs = make([][]onehotXref, len(infiles))
412 chunkStartTag := make([]tagID, len(infiles))
414 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
415 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
416 log.Info("generating annotations and numpy matrix for each slice")
417 var errSkip = errors.New("skip infile")
419 for infileIdx, infile := range infiles {
420 infileIdx, infile := infileIdx, infile
421 throttleMem.Go(func() error {
422 seq := make(map[tagID][]TileVariant, 50000)
423 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
424 f, err := open(infile)
429 log.Infof("%04d: reading %s", infileIdx, infile)
430 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
431 for _, tv := range ent.TileVariants {
436 // corresponding ref tile, if
437 // mask is in play (we can't
438 // determine coordinates for
440 if mask != nil && reftile[tv.Tag] == nil {
444 // corresponding ref tile is
445 // outside target regions --
446 // unless it's a potential
448 if mask != nil && reftile[tv.Tag].excluded &&
449 (int(tv.Tag+1) >= len(tagset) ||
450 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
453 if tv.Tag == cmd.debugTag {
454 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
456 variants := seq[tv.Tag]
457 if len(variants) == 0 {
458 variants = make([]TileVariant, 100)
460 for len(variants) <= int(tv.Variant) {
461 variants = append(variants, TileVariant{})
463 variants[int(tv.Variant)] = tv
464 seq[tv.Tag] = variants
466 for _, cg := range ent.CompactGenomes {
467 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
470 if !matchGenome.MatchString(cg.Name) {
473 // pad to full slice size
474 // to avoid out-of-bounds
476 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
477 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
485 } else if err != nil {
486 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
488 tagstart := cgs[cmd.cgnames[0]].StartTag
489 tagend := cgs[cmd.cgnames[0]].EndTag
490 chunkStartTag[infileIdx] = tagstart
494 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
495 variantRemap := make([][]tileVariantID, tagend-tagstart)
496 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
497 for tag, variants := range seq {
498 tag, variants := tag, variants
499 throttleCPU.Go(func() error {
501 count := make(map[[blake2b.Size256]byte]int, len(variants))
505 count[blake2b.Sum256(rt.tiledata)] = 0
508 for cgname, cg := range cgs {
509 idx := int(tag-tagstart) * 2
510 for allele := 0; allele < 2; allele++ {
511 v := cg.Variants[idx+allele]
512 if v > 0 && len(variants[v].Sequence) > 0 {
513 count[variants[v].Blake2b]++
516 if v > 0 && tag == cmd.debugTag {
517 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])
521 if alleleCoverage < cmd.minCoverage*2 {
522 idx := int(tag-tagstart) * 2
523 for _, cg := range cgs {
525 cg.Variants[idx+1] = 0
527 if tag == cmd.debugTag {
528 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
533 // hash[i] will be the hash of
534 // the variant(s) that should
535 // be at rank i (0-based).
536 hash := make([][blake2b.Size256]byte, 0, len(count))
537 for b := range count {
538 hash = append(hash, b)
540 sort.Slice(hash, func(i, j int) bool {
541 bi, bj := &hash[i], &hash[j]
542 if ci, cj := count[*bi], count[*bj]; ci != cj {
545 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
548 // rank[b] will be the 1-based
549 // new variant number for
550 // variants whose hash is b.
551 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
552 for i, h := range hash {
553 rank[h] = tileVariantID(i + 1)
555 if tag == cmd.debugTag {
556 for h, r := range rank {
557 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
560 // remap[v] will be the new
561 // variant number for original
563 remap := make([]tileVariantID, len(variants))
564 for i, tv := range variants {
565 remap[i] = rank[tv.Blake2b]
567 if tag == cmd.debugTag {
568 for in, out := range remap {
570 log.Printf("tag %d remap %d => %d", tag, in, out)
574 variantRemap[tag-tagstart] = remap
576 refrank := rank[blake2b.Sum256(rt.tiledata)]
577 if tag == cmd.debugTag {
578 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
587 var onehotChunk [][]int8
588 var onehotXref []onehotXref
590 var annotationsFilename string
592 annotationsFilename = "/dev/null"
594 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
595 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
597 annof, err := os.Create(annotationsFilename)
601 annow := bufio.NewWriterSize(annof, 1<<20)
603 for tag := tagstart; tag < tagend; tag++ {
605 if rt == nil && mask != nil {
606 // With no ref tile, we don't
607 // have coordinates to say
608 // this is in the desired
609 // regions -- so it's not.
610 // TODO: handle ref spanning
614 if rt != nil && rt.excluded {
615 // TODO: don't skip yet --
616 // first check for spanning
617 // tile variants that
618 // intersect non-excluded ref
622 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
625 remap := variantRemap[tag-tagstart]
627 // was not assigned above,
628 // because minCoverage
631 maxv := tileVariantID(0)
632 for _, v := range remap {
637 if *onehotChunked || *onehotSingle || *onlyPCA {
638 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
639 if tag == cmd.debugTag {
640 log.WithFields(logrus.Fields{
643 }).Info("tv2homhet()")
645 onehotChunk = append(onehotChunk, onehot...)
646 onehotXref = append(onehotXref, xrefs...)
653 // Reference does not use any
654 // variant of this tile
656 // TODO: diff against the
657 // relevant portion of the
658 // ref's spanning tile
662 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
664 reftilestr := strings.ToUpper(string(rt.tiledata))
666 done := make([]bool, maxv+1)
667 variantDiffs := make([][]hgvs.Variant, maxv+1)
668 for v, tv := range variants {
670 if v == 0 || v == rt.variant || done[v] {
675 if len(tv.Sequence) < taglen {
678 // if reftilestr doesn't end
679 // in the same tag as tv,
680 // extend reftilestr with
681 // following ref tiles until
682 // it does (up to an arbitrary
683 // sanity-check limit)
684 reftilestr := reftilestr
685 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
686 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
687 rt = reftile[rt.nexttag]
691 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
693 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
696 if !strings.HasSuffix(reftilestr, endtagstr) {
697 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
700 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
701 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
704 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
705 for i := range diffs {
706 diffs[i].Position += rt.pos
708 for _, diff := range diffs {
709 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)
712 variantDiffs[v] = diffs
716 // We can now determine, for each HGVS
717 // variant (diff) in this reftile
718 // region, whether a given genome
719 // phase/allele (1) has the variant, (0) has
720 // =ref or a different variant in that
721 // position, or (-1) is lacking
722 // coverage / couldn't be diffed.
723 hgvsCol := hgvsColSet{}
724 for _, diffs := range variantDiffs {
725 for _, diff := range diffs {
726 if _, ok := hgvsCol[diff]; ok {
729 hgvsCol[diff] = [2][]int8{
730 make([]int8, len(cmd.cgnames)),
731 make([]int8, len(cmd.cgnames)),
735 for row, name := range cmd.cgnames {
736 variants := cgs[name].Variants[(tag-tagstart)*2:]
737 for ph := 0; ph < 2; ph++ {
739 if int(v) >= len(remap) {
745 // hgvsCol[*][ph][row] is already 0
746 } else if len(variantDiffs[v]) == 0 {
747 // lacking coverage / couldn't be diffed
748 for _, col := range hgvsCol {
752 for _, diff := range variantDiffs[v] {
753 hgvsCol[diff][ph][row] = 1
758 for diff, colpair := range hgvsCol {
759 allele2homhet(colpair)
760 if !cmd.filterHGVScolpair(colpair) {
761 delete(hgvsCol, diff)
764 if len(hgvsCol) > 0 {
765 encodeHGVSTodo[rt.seqname] <- hgvsCol
780 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
781 rows := len(cmd.cgnames)
782 cols := len(onehotChunk)
783 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
784 throttleNumpyMem.Acquire()
785 out := onehotcols2int8(onehotChunk)
786 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
787 err = writeNumpyInt8(fnm, out, rows, cols)
791 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
792 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
797 throttleNumpyMem.Release()
799 if *onehotSingle || *onlyPCA {
800 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
801 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
802 onehotXrefs[infileIdx] = onehotXref
803 n := len(onehotIndirect[infileIdx][0])
804 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
806 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
807 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
808 throttleNumpyMem.Acquire()
809 rows := len(cmd.cgnames)
811 out := make([]int16, rows*cols)
812 for row, name := range cmd.cgnames {
814 for col, v := range cgs[name].Variants {
815 tag := tagstart + tagID(col/2)
816 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
819 if rt := reftile[tag]; rt == nil || rt.excluded {
823 out[outidx] = 0 // tag not found / spanning tile
824 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
825 out[outidx] = int16(variantRemap[tag-tagstart][v])
827 out[outidx] = -1 // low quality tile variant
829 if tag == cmd.debugTag {
830 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
838 throttleNumpyMem.Release()
839 if *mergeOutput || *hgvsSingle {
840 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
841 toMerge[infileIdx] = out
843 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
844 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
845 err = writeNumpyInt16(fnm, out, rows, cols)
852 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
856 if err = throttleMem.Wait(); err != nil {
861 log.Info("flushing hgvsCols temp files")
862 for seqname := range refseq {
863 close(encodeHGVSTodo[seqname])
865 err = encodeHGVS.Wait()
869 for seqname := range refseq {
870 log.Infof("%s: reading hgvsCols from temp file", seqname)
871 f := tmpHGVSCols[seqname]
872 _, err = f.Seek(0, io.SeekStart)
876 var hgvsCols hgvsColSet
877 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
879 err = dec.Decode(&hgvsCols)
884 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
885 variants := make([]hgvs.Variant, 0, len(hgvsCols))
886 for v := range hgvsCols {
887 variants = append(variants, v)
889 sort.Slice(variants, func(i, j int) bool {
890 vi, vj := &variants[i], &variants[j]
891 if vi.Position != vj.Position {
892 return vi.Position < vj.Position
893 } else if vi.Ref != vj.Ref {
894 return vi.Ref < vj.Ref
896 return vi.New < vj.New
899 rows := len(cmd.cgnames)
900 cols := len(variants) * 2
901 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
902 out := make([]int8, rows*cols)
903 for varIdx, variant := range variants {
904 hgvsCols := hgvsCols[variant]
905 for row := range cmd.cgnames {
906 for ph := 0; ph < 2; ph++ {
907 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
911 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
917 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
918 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
919 var hgvsLabels bytes.Buffer
920 for varIdx, variant := range variants {
921 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
923 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
930 if *mergeOutput || *hgvsSingle {
931 var annow *bufio.Writer
934 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
935 annof, err = os.Create(annoFilename)
939 annow = bufio.NewWriterSize(annof, 1<<20)
942 rows := len(cmd.cgnames)
944 for _, chunk := range toMerge {
945 cols += len(chunk) / rows
947 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
950 out = make([]int16, rows*cols)
952 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
954 for outIdx, chunk := range toMerge {
955 chunkcols := len(chunk) / rows
957 for row := 0; row < rows; row++ {
958 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
961 toMerge[outIdx] = nil
963 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
964 log.Infof("reading %s", annotationsFilename)
965 buf, err := os.ReadFile(annotationsFilename)
970 err = os.Remove(annotationsFilename)
975 for _, line := range bytes.Split(buf, []byte{'\n'}) {
979 fields := bytes.SplitN(line, []byte{','}, 9)
980 tag, _ := strconv.Atoi(string(fields[0]))
981 incol, _ := strconv.Atoi(string(fields[1]))
982 tileVariant, _ := strconv.Atoi(string(fields[2]))
983 hgvsID := string(fields[3])
984 seqname := string(fields[4])
985 pos, _ := strconv.Atoi(string(fields[5]))
988 // Null entry for un-diffable
993 // Null entry for ref tile
996 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
997 // The tile intersects one of
998 // the selected regions, but
999 // this particular HGVS
1000 // variant does not.
1003 hgvsColPair := hgvsCols[hgvsID]
1004 if hgvsColPair[0] == nil {
1005 // values in new columns start
1006 // out as -1 ("no data yet")
1007 // or 0 ("=ref") here, may
1008 // change to 1 ("hgvs variant
1009 // present") below, either on
1010 // this line or a future line.
1011 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1012 rt, ok := reftile[tagID(tag)]
1014 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1017 for ph := 0; ph < 2; ph++ {
1018 for row := 0; row < rows; row++ {
1019 v := chunk[row*chunkcols+incol*2+ph]
1020 if tileVariantID(v) == rt.variant {
1021 hgvsColPair[ph][row] = 0
1023 hgvsColPair[ph][row] = -1
1027 hgvsCols[hgvsID] = hgvsColPair
1029 hgvsref := hgvs.Variant{
1031 Ref: string(refseq),
1032 New: string(refseq),
1034 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])
1038 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])
1040 for ph := 0; ph < 2; ph++ {
1041 for row := 0; row < rows; row++ {
1042 v := chunk[row*chunkcols+incol*2+ph]
1043 if int(v) == tileVariant {
1044 hgvsColPair[ph][row] = 1
1050 startcol += chunkcols
1061 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1069 cols = len(hgvsCols) * 2
1070 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1071 out = make([]int16, rows*cols)
1072 hgvsIDs := make([]string, 0, cols/2)
1073 for hgvsID := range hgvsCols {
1074 hgvsIDs = append(hgvsIDs, hgvsID)
1076 sort.Strings(hgvsIDs)
1077 var hgvsLabels bytes.Buffer
1078 for idx, hgvsID := range hgvsIDs {
1079 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1080 for ph := 0; ph < 2; ph++ {
1081 hgvscol := hgvsCols[hgvsID][ph]
1082 for row, val := range hgvscol {
1083 out[row*cols+idx*2+ph] = val
1087 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1092 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1093 log.Printf("writing hgvs labels: %s", fnm)
1094 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1100 if *onehotSingle || *onlyPCA {
1102 for _, part := range onehotIndirect {
1103 nzCount += len(part[0])
1105 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1106 var xrefs []onehotXref
1107 chunkOffset := uint32(0)
1109 for i, part := range onehotIndirect {
1110 for i := range part[1] {
1111 part[1][i] += chunkOffset
1113 copy(onehot[outcol:], part[0])
1114 copy(onehot[outcol+nzCount:], part[1])
1115 xrefs = append(xrefs, onehotXrefs[i]...)
1117 outcol += len(part[0])
1118 chunkOffset += onehotChunkSize[i]
1122 onehotXrefs[i] = nil
1123 debug.FreeOSMemory()
1126 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1127 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1131 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1132 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1137 samplesOutFilename := *outputDir + "/samples.csv"
1138 log.Infof("writing sample metadata to %s", samplesOutFilename)
1140 f, err = os.Create(samplesOutFilename)
1145 for i, si := range cmd.samples {
1149 } else if si.isControl {
1157 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
1159 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1165 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1172 for _, c := range onehot[nzCount:] {
1178 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1180 log.Printf("have %d one-hot cols", cols)
1182 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1183 cols = (cols + 1) / 2
1186 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1187 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1188 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1189 for i, c := range onehot[nzCount:] {
1190 if int(c/2)%stride == 0 {
1191 outcol := int(c/2)/stride*2 + int(c)%2
1192 mtxFull.Set(int(onehot[i]), outcol, 1)
1193 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1194 mtxTrain.Set(trainRow, outcol, 1)
1198 log.Print("fitting")
1199 transformer := nlp.NewPCA(*pcaComponents)
1200 transformer.Fit(mtxTrain.T())
1201 log.Printf("transforming")
1202 pca, err := transformer.Transform(mtxFull.T())
1207 outrows, outcols := pca.Dims()
1208 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1209 out := make([]float64, outrows*outcols)
1210 for i := 0; i < outrows; i++ {
1211 for j := 0; j < outcols; j++ {
1212 out[i*outcols+j] = pca.At(i, j)
1215 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1216 log.Printf("writing numpy: %s", fnm)
1217 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1221 npw, err := gonpy.NewWriter(nopCloser{output})
1223 return fmt.Errorf("gonpy.NewWriter: %w", err)
1225 npw.Shape = []int{outrows, outcols}
1226 err = npw.WriteFloat64(out)
1228 return fmt.Errorf("WriteFloat64: %w", err)
1230 err = output.Close()
1236 samplesOutFilename := *outputDir + "/samples.csv"
1237 log.Infof("writing sample metadata to %s", samplesOutFilename)
1239 f, err = os.Create(samplesOutFilename)
1244 for i, si := range cmd.samples {
1248 } else if si.isControl {
1257 for c := 0; c < outcols; c++ {
1258 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1260 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1262 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1268 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1274 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1275 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1276 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1278 f, err = os.Create(tagoffsetFilename)
1283 for idx, offset := range chunkStartTag {
1284 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1286 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1292 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1300 type sampleInfo struct {
1306 pcaComponents []float64
1309 // Read samples.csv file with case/control and training/validation
1311 func (cmd *sliceNumpy) loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1313 f, err := open(samplesFilename)
1317 buf, err := io.ReadAll(f)
1323 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1328 split := strings.Split(string(csv), ",")
1329 if len(split) != 4 {
1330 return nil, fmt.Errorf("%d fields != 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1332 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1335 idx, err := strconv.Atoi(split[0])
1338 return nil, fmt.Errorf("header does not look right: %q", csv)
1340 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1343 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1345 si = append(si, sampleInfo{
1347 isCase: split[2] == "1",
1348 isControl: split[2] == "0",
1349 isTraining: split[3] == "1",
1350 isValidation: split[3] == "0",
1356 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1357 if cmd.chi2PValue >= 1 {
1360 col0 := make([]bool, 0, len(cmd.chi2Cases))
1361 col1 := make([]bool, 0, len(cmd.chi2Cases))
1362 cases := make([]bool, 0, len(cmd.chi2Cases))
1363 for i, c := range cmd.chi2Cases {
1364 if colpair[0][i] < 0 {
1367 col0 = append(col0, colpair[0][i] != 0)
1368 col1 = append(col1, colpair[1][i] != 0)
1369 cases = append(cases, c)
1371 return len(cases) >= cmd.minCoverage &&
1372 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1375 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1376 output, err := os.Create(fnm)
1380 defer output.Close()
1381 bufw := bufio.NewWriterSize(output, 1<<26)
1382 npw, err := gonpy.NewWriter(nopCloser{bufw})
1386 log.WithFields(log.Fields{
1390 "bytes": rows * cols * 4,
1391 }).Infof("writing numpy: %s", fnm)
1392 npw.Shape = []int{rows, cols}
1393 npw.WriteUint32(out)
1398 return output.Close()
1401 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1402 output, err := os.Create(fnm)
1406 defer output.Close()
1407 bufw := bufio.NewWriterSize(output, 1<<26)
1408 npw, err := gonpy.NewWriter(nopCloser{bufw})
1412 log.WithFields(log.Fields{
1416 "bytes": rows * cols * 4,
1417 }).Infof("writing numpy: %s", fnm)
1418 npw.Shape = []int{rows, cols}
1424 return output.Close()
1427 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1428 output, err := os.Create(fnm)
1432 defer output.Close()
1433 bufw := bufio.NewWriterSize(output, 1<<26)
1434 npw, err := gonpy.NewWriter(nopCloser{bufw})
1438 log.WithFields(log.Fields{
1442 "bytes": rows * cols * 2,
1443 }).Infof("writing numpy: %s", fnm)
1444 npw.Shape = []int{rows, cols}
1450 return output.Close()
1453 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1454 output, err := os.Create(fnm)
1458 defer output.Close()
1459 bufw := bufio.NewWriterSize(output, 1<<26)
1460 npw, err := gonpy.NewWriter(nopCloser{bufw})
1464 log.WithFields(log.Fields{
1468 "bytes": rows * cols,
1469 }).Infof("writing numpy: %s", fnm)
1470 npw.Shape = []int{rows, cols}
1476 return output.Close()
1479 func allele2homhet(colpair [2][]int8) {
1480 a, b := colpair[0], colpair[1]
1481 for i, av := range a {
1483 if av < 0 || bv < 0 {
1486 } else if av > 0 && bv > 0 {
1489 } else if av > 0 || bv > 0 {
1493 // ref (or a different variant in same position)
1494 // (this is a no-op) a[i], b[i] = 0, 0
1499 type onehotXref struct {
1501 variant tileVariantID
1506 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1508 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1509 // variants of a single tile/tag#.
1511 // Return nil if no tile variant passes Χ² filter.
1512 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1513 if tag == cmd.debugTag {
1514 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1515 for i, name := range cmd.cgnames {
1516 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1518 log.WithFields(logrus.Fields{
1519 "cgs[i].Variants[tag*2+j]": tv,
1523 "chunkstarttag": chunkstarttag,
1524 }).Info("tv2homhet()")
1526 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1527 // everyone has the most common variant (of the variants we don't drop)
1530 tagoffset := tag - chunkstarttag
1532 for _, cg := range cgs {
1534 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1535 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1543 if coverage < cmd.minCoverage {
1546 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1547 for i := range obs {
1548 obs[i] = make([]bool, cmd.trainingSetSize)
1550 for cgid, name := range cmd.cgnames {
1551 tsid := cmd.trainingSet[cgid]
1555 cgvars := cgs[name].Variants[tagoffset*2:]
1556 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1557 for v := tileVariantID(1); v <= maxv; v++ {
1558 if tv0 == v && tv1 == v {
1559 obs[v*2][tsid] = true
1560 } else if tv0 == v || tv1 == v {
1561 obs[v*2+1][tsid] = true
1566 var xref []onehotXref
1567 for col := 2; col < len(obs); col++ {
1568 // col 0,1 correspond to tile variant 0, i.e.,
1569 // no-call; col 2,3 correspond to the most common
1570 // variant; so we (normally) start at col 4.
1571 if col < 4 && !cmd.includeVariant1 {
1574 p := pvalue(obs[col], cmd.chi2Cases)
1575 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1578 onehot = append(onehot, bool2int8(obs[col]))
1579 xref = append(xref, onehotXref{
1581 variant: tileVariantID(col >> 1),
1589 func bool2int8(in []bool) []int8 {
1590 out := make([]int8, len(in))
1591 for i, v := range in {
1599 // convert a []onehotXref with length N to a numpy-style []int32
1600 // matrix with N columns, one row per field of onehotXref struct.
1602 // Hom/het row contains hom=0, het=1.
1604 // P-value row contains 1000000x actual p-value.
1605 func onehotXref2int32(xrefs []onehotXref) []int32 {
1607 xdata := make([]int32, 5*xcols)
1608 for i, xref := range xrefs {
1609 xdata[i] = int32(xref.tag)
1610 xdata[xcols+i] = int32(xref.variant)
1612 xdata[xcols*2+i] = 1
1614 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1615 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1620 // transpose onehot data from in[col][row] to numpy-style
1621 // out[row*cols+col].
1622 func onehotcols2int8(in [][]int8) []int8 {
1628 out := make([]int8, rows*cols)
1629 for row := 0; row < rows; row++ {
1630 outrow := out[row*cols:]
1631 for col, incol := range in {
1632 outrow[col] = incol[row]
1638 // Return [2][]uint32{rowIndices, colIndices} indicating which
1639 // elements of matrixT[c][r] have non-zero values.
1640 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1642 for c, col := range matrixT {
1643 for r, val := range col {
1645 nz[0] = append(nz[0], uint32(r))
1646 nz[1] = append(nz[1], uint32(c))