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]
626 maxv := tileVariantID(0)
627 for _, v := range remap {
632 if *onehotChunked || *onehotSingle || *onlyPCA {
633 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
634 if tag == cmd.debugTag {
635 log.WithFields(logrus.Fields{
638 }).Info("tv2homhet()")
640 onehotChunk = append(onehotChunk, onehot...)
641 onehotXref = append(onehotXref, xrefs...)
648 // Reference does not use any
649 // variant of this tile
651 // TODO: diff against the
652 // relevant portion of the
653 // ref's spanning tile
657 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
659 reftilestr := strings.ToUpper(string(rt.tiledata))
661 done := make([]bool, maxv+1)
662 variantDiffs := make([][]hgvs.Variant, maxv+1)
663 for v, tv := range variants {
665 if v == 0 || v == rt.variant || done[v] {
670 if len(tv.Sequence) < taglen {
673 // if reftilestr doesn't end
674 // in the same tag as tv,
675 // extend reftilestr with
676 // following ref tiles until
677 // it does (up to an arbitrary
678 // sanity-check limit)
679 reftilestr := reftilestr
680 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
681 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
682 rt = reftile[rt.nexttag]
686 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
688 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
691 if !strings.HasSuffix(reftilestr, endtagstr) {
692 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
695 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
696 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
699 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
700 for i := range diffs {
701 diffs[i].Position += rt.pos
703 for _, diff := range diffs {
704 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)
707 variantDiffs[v] = diffs
711 // We can now determine, for each HGVS
712 // variant (diff) in this reftile
713 // region, whether a given genome
714 // phase/allele (1) has the variant, (0) has
715 // =ref or a different variant in that
716 // position, or (-1) is lacking
717 // coverage / couldn't be diffed.
718 hgvsCol := hgvsColSet{}
719 for _, diffs := range variantDiffs {
720 for _, diff := range diffs {
721 if _, ok := hgvsCol[diff]; ok {
724 hgvsCol[diff] = [2][]int8{
725 make([]int8, len(cmd.cgnames)),
726 make([]int8, len(cmd.cgnames)),
730 for row, name := range cmd.cgnames {
731 variants := cgs[name].Variants[(tag-tagstart)*2:]
732 for ph := 0; ph < 2; ph++ {
734 if int(v) >= len(remap) {
740 // hgvsCol[*][ph][row] is already 0
741 } else if len(variantDiffs[v]) == 0 {
742 // lacking coverage / couldn't be diffed
743 for _, col := range hgvsCol {
747 for _, diff := range variantDiffs[v] {
748 hgvsCol[diff][ph][row] = 1
753 for diff, colpair := range hgvsCol {
754 allele2homhet(colpair)
755 if !cmd.filterHGVScolpair(colpair) {
756 delete(hgvsCol, diff)
759 if len(hgvsCol) > 0 {
760 encodeHGVSTodo[rt.seqname] <- hgvsCol
775 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
776 rows := len(cmd.cgnames)
777 cols := len(onehotChunk)
778 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
779 throttleNumpyMem.Acquire()
780 out := onehotcols2int8(onehotChunk)
781 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
782 err = writeNumpyInt8(fnm, out, rows, cols)
786 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
787 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
792 throttleNumpyMem.Release()
794 if *onehotSingle || *onlyPCA {
795 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
796 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
797 onehotXrefs[infileIdx] = onehotXref
798 n := len(onehotIndirect[infileIdx][0])
799 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
801 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
802 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
803 throttleNumpyMem.Acquire()
804 rows := len(cmd.cgnames)
806 out := make([]int16, rows*cols)
807 for row, name := range cmd.cgnames {
809 for col, v := range cgs[name].Variants {
810 tag := tagstart + tagID(col/2)
811 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
814 if rt := reftile[tag]; rt == nil || rt.excluded {
818 out[outidx] = 0 // tag not found / spanning tile
819 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
820 out[outidx] = int16(variantRemap[tag-tagstart][v])
822 out[outidx] = -1 // low quality tile variant
824 if tag == cmd.debugTag {
825 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
833 throttleNumpyMem.Release()
834 if *mergeOutput || *hgvsSingle {
835 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
836 toMerge[infileIdx] = out
838 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
839 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
840 err = writeNumpyInt16(fnm, out, rows, cols)
847 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
851 if err = throttleMem.Wait(); err != nil {
856 log.Info("flushing hgvsCols temp files")
857 for seqname := range refseq {
858 close(encodeHGVSTodo[seqname])
860 err = encodeHGVS.Wait()
864 for seqname := range refseq {
865 log.Infof("%s: reading hgvsCols from temp file", seqname)
866 f := tmpHGVSCols[seqname]
867 _, err = f.Seek(0, io.SeekStart)
871 var hgvsCols hgvsColSet
872 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
874 err = dec.Decode(&hgvsCols)
879 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
880 variants := make([]hgvs.Variant, 0, len(hgvsCols))
881 for v := range hgvsCols {
882 variants = append(variants, v)
884 sort.Slice(variants, func(i, j int) bool {
885 vi, vj := &variants[i], &variants[j]
886 if vi.Position != vj.Position {
887 return vi.Position < vj.Position
888 } else if vi.Ref != vj.Ref {
889 return vi.Ref < vj.Ref
891 return vi.New < vj.New
894 rows := len(cmd.cgnames)
895 cols := len(variants) * 2
896 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
897 out := make([]int8, rows*cols)
898 for varIdx, variant := range variants {
899 hgvsCols := hgvsCols[variant]
900 for row := range cmd.cgnames {
901 for ph := 0; ph < 2; ph++ {
902 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
906 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
912 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
913 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
914 var hgvsLabels bytes.Buffer
915 for varIdx, variant := range variants {
916 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
918 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
925 if *mergeOutput || *hgvsSingle {
926 var annow *bufio.Writer
929 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
930 annof, err = os.Create(annoFilename)
934 annow = bufio.NewWriterSize(annof, 1<<20)
937 rows := len(cmd.cgnames)
939 for _, chunk := range toMerge {
940 cols += len(chunk) / rows
942 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
945 out = make([]int16, rows*cols)
947 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
949 for outIdx, chunk := range toMerge {
950 chunkcols := len(chunk) / rows
952 for row := 0; row < rows; row++ {
953 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
956 toMerge[outIdx] = nil
958 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
959 log.Infof("reading %s", annotationsFilename)
960 buf, err := os.ReadFile(annotationsFilename)
965 err = os.Remove(annotationsFilename)
970 for _, line := range bytes.Split(buf, []byte{'\n'}) {
974 fields := bytes.SplitN(line, []byte{','}, 9)
975 tag, _ := strconv.Atoi(string(fields[0]))
976 incol, _ := strconv.Atoi(string(fields[1]))
977 tileVariant, _ := strconv.Atoi(string(fields[2]))
978 hgvsID := string(fields[3])
979 seqname := string(fields[4])
980 pos, _ := strconv.Atoi(string(fields[5]))
983 // Null entry for un-diffable
988 // Null entry for ref tile
991 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
992 // The tile intersects one of
993 // the selected regions, but
994 // this particular HGVS
998 hgvsColPair := hgvsCols[hgvsID]
999 if hgvsColPair[0] == nil {
1000 // values in new columns start
1001 // out as -1 ("no data yet")
1002 // or 0 ("=ref") here, may
1003 // change to 1 ("hgvs variant
1004 // present") below, either on
1005 // this line or a future line.
1006 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1007 rt, ok := reftile[tagID(tag)]
1009 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1012 for ph := 0; ph < 2; ph++ {
1013 for row := 0; row < rows; row++ {
1014 v := chunk[row*chunkcols+incol*2+ph]
1015 if tileVariantID(v) == rt.variant {
1016 hgvsColPair[ph][row] = 0
1018 hgvsColPair[ph][row] = -1
1022 hgvsCols[hgvsID] = hgvsColPair
1024 hgvsref := hgvs.Variant{
1026 Ref: string(refseq),
1027 New: string(refseq),
1029 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])
1033 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])
1035 for ph := 0; ph < 2; ph++ {
1036 for row := 0; row < rows; row++ {
1037 v := chunk[row*chunkcols+incol*2+ph]
1038 if int(v) == tileVariant {
1039 hgvsColPair[ph][row] = 1
1045 startcol += chunkcols
1056 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1064 cols = len(hgvsCols) * 2
1065 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1066 out = make([]int16, rows*cols)
1067 hgvsIDs := make([]string, 0, cols/2)
1068 for hgvsID := range hgvsCols {
1069 hgvsIDs = append(hgvsIDs, hgvsID)
1071 sort.Strings(hgvsIDs)
1072 var hgvsLabels bytes.Buffer
1073 for idx, hgvsID := range hgvsIDs {
1074 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1075 for ph := 0; ph < 2; ph++ {
1076 hgvscol := hgvsCols[hgvsID][ph]
1077 for row, val := range hgvscol {
1078 out[row*cols+idx*2+ph] = val
1082 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1087 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1088 log.Printf("writing hgvs labels: %s", fnm)
1089 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1095 if *onehotSingle || *onlyPCA {
1097 for _, part := range onehotIndirect {
1098 nzCount += len(part[0])
1100 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1101 var xrefs []onehotXref
1102 chunkOffset := uint32(0)
1104 for i, part := range onehotIndirect {
1105 for i := range part[1] {
1106 part[1][i] += chunkOffset
1108 copy(onehot[outcol:], part[0])
1109 copy(onehot[outcol+nzCount:], part[1])
1110 xrefs = append(xrefs, onehotXrefs[i]...)
1112 outcol += len(part[0])
1113 chunkOffset += onehotChunkSize[i]
1117 onehotXrefs[i] = nil
1118 debug.FreeOSMemory()
1121 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1122 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1126 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1127 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1132 samplesOutFilename := *outputDir + "/samples.csv"
1133 log.Infof("writing sample metadata to %s", samplesOutFilename)
1135 f, err = os.Create(samplesOutFilename)
1140 for i, si := range cmd.samples {
1144 } else if si.isControl {
1152 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
1154 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1160 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1167 for _, c := range onehot[nzCount:] {
1173 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1175 log.Printf("have %d one-hot cols", cols)
1177 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1178 cols = (cols + 1) / 2
1181 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1182 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1183 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1184 for i, c := range onehot[nzCount:] {
1185 if int(c/2)%stride == 0 {
1186 outcol := int(c/2)/stride*2 + int(c)%2
1187 mtxFull.Set(int(onehot[i]), outcol, 1)
1188 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1189 mtxTrain.Set(trainRow, outcol, 1)
1193 log.Print("fitting")
1194 transformer := nlp.NewPCA(*pcaComponents)
1195 transformer.Fit(mtxTrain.T())
1196 log.Printf("transforming")
1197 pca, err := transformer.Transform(mtxFull.T())
1202 outrows, outcols := pca.Dims()
1203 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1204 out := make([]float64, outrows*outcols)
1205 for i := 0; i < outrows; i++ {
1206 for j := 0; j < outcols; j++ {
1207 out[i*outcols+j] = pca.At(i, j)
1210 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1211 log.Printf("writing numpy: %s", fnm)
1212 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1216 npw, err := gonpy.NewWriter(nopCloser{output})
1218 return fmt.Errorf("gonpy.NewWriter: %w", err)
1220 npw.Shape = []int{outrows, outcols}
1221 err = npw.WriteFloat64(out)
1223 return fmt.Errorf("WriteFloat64: %w", err)
1225 err = output.Close()
1231 samplesOutFilename := *outputDir + "/samples.csv"
1232 log.Infof("writing sample metadata to %s", samplesOutFilename)
1234 f, err = os.Create(samplesOutFilename)
1239 for i, si := range cmd.samples {
1243 } else if si.isControl {
1252 for c := 0; c < outcols; c++ {
1253 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1255 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1257 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1263 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1269 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1270 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1271 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1273 f, err = os.Create(tagoffsetFilename)
1278 for idx, offset := range chunkStartTag {
1279 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1281 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1287 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1295 type sampleInfo struct {
1301 pcaComponents []float64
1304 // Read samples.csv file with case/control and training/validation
1306 func (cmd *sliceNumpy) loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1308 f, err := open(samplesFilename)
1312 buf, err := io.ReadAll(f)
1318 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1323 split := strings.Split(string(csv), ",")
1324 if len(split) != 4 {
1325 return nil, fmt.Errorf("%d fields != 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1327 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1330 idx, err := strconv.Atoi(split[0])
1333 return nil, fmt.Errorf("header does not look right: %q", csv)
1335 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1338 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1340 si = append(si, sampleInfo{
1342 isCase: split[2] == "1",
1343 isControl: split[2] == "0",
1344 isTraining: split[3] == "1",
1345 isValidation: split[3] == "0",
1351 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1352 if cmd.chi2PValue >= 1 {
1355 col0 := make([]bool, 0, len(cmd.chi2Cases))
1356 col1 := make([]bool, 0, len(cmd.chi2Cases))
1357 cases := make([]bool, 0, len(cmd.chi2Cases))
1358 for i, c := range cmd.chi2Cases {
1359 if colpair[0][i] < 0 {
1362 col0 = append(col0, colpair[0][i] != 0)
1363 col1 = append(col1, colpair[1][i] != 0)
1364 cases = append(cases, c)
1366 return len(cases) >= cmd.minCoverage &&
1367 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1370 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1371 output, err := os.Create(fnm)
1375 defer output.Close()
1376 bufw := bufio.NewWriterSize(output, 1<<26)
1377 npw, err := gonpy.NewWriter(nopCloser{bufw})
1381 log.WithFields(log.Fields{
1385 "bytes": rows * cols * 4,
1386 }).Infof("writing numpy: %s", fnm)
1387 npw.Shape = []int{rows, cols}
1388 npw.WriteUint32(out)
1393 return output.Close()
1396 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1397 output, err := os.Create(fnm)
1401 defer output.Close()
1402 bufw := bufio.NewWriterSize(output, 1<<26)
1403 npw, err := gonpy.NewWriter(nopCloser{bufw})
1407 log.WithFields(log.Fields{
1411 "bytes": rows * cols * 4,
1412 }).Infof("writing numpy: %s", fnm)
1413 npw.Shape = []int{rows, cols}
1419 return output.Close()
1422 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1423 output, err := os.Create(fnm)
1427 defer output.Close()
1428 bufw := bufio.NewWriterSize(output, 1<<26)
1429 npw, err := gonpy.NewWriter(nopCloser{bufw})
1433 log.WithFields(log.Fields{
1437 "bytes": rows * cols * 2,
1438 }).Infof("writing numpy: %s", fnm)
1439 npw.Shape = []int{rows, cols}
1445 return output.Close()
1448 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1449 output, err := os.Create(fnm)
1453 defer output.Close()
1454 bufw := bufio.NewWriterSize(output, 1<<26)
1455 npw, err := gonpy.NewWriter(nopCloser{bufw})
1459 log.WithFields(log.Fields{
1463 "bytes": rows * cols,
1464 }).Infof("writing numpy: %s", fnm)
1465 npw.Shape = []int{rows, cols}
1471 return output.Close()
1474 func allele2homhet(colpair [2][]int8) {
1475 a, b := colpair[0], colpair[1]
1476 for i, av := range a {
1478 if av < 0 || bv < 0 {
1481 } else if av > 0 && bv > 0 {
1484 } else if av > 0 || bv > 0 {
1488 // ref (or a different variant in same position)
1489 // (this is a no-op) a[i], b[i] = 0, 0
1494 type onehotXref struct {
1496 variant tileVariantID
1501 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1503 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1504 // variants of a single tile/tag#.
1506 // Return nil if no tile variant passes Χ² filter.
1507 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1508 if tag == cmd.debugTag {
1509 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1510 for i, name := range cmd.cgnames {
1511 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1513 log.WithFields(logrus.Fields{
1514 "cgs[i].Variants[tag*2+j]": tv,
1518 "chunkstarttag": chunkstarttag,
1519 }).Info("tv2homhet()")
1521 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1522 // everyone has the most common variant (of the variants we don't drop)
1525 tagoffset := tag - chunkstarttag
1527 for _, cg := range cgs {
1529 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1530 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1538 if coverage < cmd.minCoverage {
1541 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1542 for i := range obs {
1543 obs[i] = make([]bool, cmd.trainingSetSize)
1545 for cgid, name := range cmd.cgnames {
1546 tsid := cmd.trainingSet[cgid]
1550 cgvars := cgs[name].Variants[tagoffset*2:]
1551 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1552 for v := tileVariantID(1); v <= maxv; v++ {
1553 if tv0 == v && tv1 == v {
1554 obs[v*2][tsid] = true
1555 } else if tv0 == v || tv1 == v {
1556 obs[v*2+1][tsid] = true
1561 var xref []onehotXref
1562 for col := 2; col < len(obs); col++ {
1563 // col 0,1 correspond to tile variant 0, i.e.,
1564 // no-call; col 2,3 correspond to the most common
1565 // variant; so we (normally) start at col 4.
1566 if col < 4 && !cmd.includeVariant1 {
1569 p := pvalue(obs[col], cmd.chi2Cases)
1570 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1573 onehot = append(onehot, bool2int8(obs[col]))
1574 xref = append(xref, onehotXref{
1576 variant: tileVariantID(col >> 1),
1584 func bool2int8(in []bool) []int8 {
1585 out := make([]int8, len(in))
1586 for i, v := range in {
1594 // convert a []onehotXref with length N to a numpy-style []int32
1595 // matrix with N columns, one row per field of onehotXref struct.
1597 // Hom/het row contains hom=0, het=1.
1599 // P-value row contains 1000000x actual p-value.
1600 func onehotXref2int32(xrefs []onehotXref) []int32 {
1602 xdata := make([]int32, 5*xcols)
1603 for i, xref := range xrefs {
1604 xdata[i] = int32(xref.tag)
1605 xdata[xcols+i] = int32(xref.variant)
1607 xdata[xcols*2+i] = 1
1609 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1610 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1615 // transpose onehot data from in[col][row] to numpy-style
1616 // out[row*cols+col].
1617 func onehotcols2int8(in [][]int8) []int8 {
1623 out := make([]int8, rows*cols)
1624 for row := 0; row < rows; row++ {
1625 outrow := out[row*cols:]
1626 for col, incol := range in {
1627 outrow[col] = incol[row]
1633 // Return [2][]uint32{rowIndices, colIndices} indicating which
1634 // elements of matrixT[c][r] have non-zero values.
1635 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1637 for c, col := range matrixT {
1638 for r, val := range col {
1640 nz[0] = append(nz[0], uint32(r))
1641 nz[1] = append(nz[1], uint32(c))