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 {
53 trainingSet []int // samples index => training set index, or -1 if not in training set
57 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
58 err := cmd.run(prog, args, stdin, stdout, stderr)
60 fmt.Fprintf(stderr, "%s\n", err)
66 func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
67 flags := flag.NewFlagSet("", flag.ContinueOnError)
68 flags.SetOutput(stderr)
69 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
70 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
71 arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
72 arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
73 projectUUID := flags.String("project", "", "project `UUID` for output data")
74 priority := flags.Int("priority", 500, "container request priority")
75 inputDir := flags.String("input-dir", "./in", "input `directory`")
76 outputDir := flags.String("output-dir", "./out", "output `directory`")
77 ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
78 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
79 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
80 mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
81 hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
82 hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
83 onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
84 onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
85 samplesFilename := flags.String("samples", "", "`samples.csv` file with training/validation and case/control groups (see 'lightning choose-samples')")
86 caseControlOnly := flags.Bool("case-control-only", false, "drop samples that are not in case/control groups")
87 onlyPCA := flags.Bool("pca", false, "run principal component analysis, write components to pca.npy and samples.csv")
88 flags.IntVar(&cmd.pcaComponents, "pca-components", 4, "number of PCA components to compute / use in logistic regression")
89 maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
90 debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
91 flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
92 flags.Float64Var(&cmd.chi2PValue, "chi2-p-value", 1, "do Χ² test (or logistic regression if -samples file has PCA components) and omit columns with p-value above this threshold")
93 flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
94 cmd.filter.Flags(flags)
95 err := flags.Parse(args)
96 if err == flag.ErrHelp {
98 } else if err != nil {
100 } else if flags.NArg() > 0 {
101 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
106 log.Println(http.ListenAndServe(*pprof, nil))
110 if cmd.chi2PValue != 1 && *samplesFilename == "" {
111 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -samples= value is empty", cmd.chi2PValue)
114 cmd.debugTag = tagID(*debugTag)
117 runner := arvadosContainerRunner{
118 Name: "lightning slice-numpy",
119 Client: arvados.NewClientFromEnv(),
120 ProjectUUID: *projectUUID,
121 RAM: int64(*arvadosRAM),
122 VCPUs: *arvadosVCPUs,
127 err = runner.TranslatePaths(inputDir, regionsFilename, samplesFilename)
131 runner.Args = []string{"slice-numpy", "-local=true",
133 "-input-dir=" + *inputDir,
134 "-output-dir=/mnt/output",
135 "-threads=" + fmt.Sprintf("%d", cmd.threads),
136 "-regions=" + *regionsFilename,
137 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
138 "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
139 "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
140 "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
141 "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
142 "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
143 "-samples=" + *samplesFilename,
144 "-case-control-only=" + fmt.Sprintf("%v", *caseControlOnly),
145 "-pca=" + fmt.Sprintf("%v", *onlyPCA),
146 "-pca-components=" + fmt.Sprintf("%d", cmd.pcaComponents),
147 "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
148 "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
149 "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
150 "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
152 runner.Args = append(runner.Args, cmd.filter.Args()...)
154 output, err = runner.Run()
158 fmt.Fprintln(stdout, output)
162 infiles, err := allFiles(*inputDir, matchGobFile)
166 if len(infiles) == 0 {
167 err = fmt.Errorf("no input files found in %s", *inputDir)
170 sort.Strings(infiles)
172 var refseq map[string][]tileLibRef
173 var reftiledata = make(map[tileLibRef][]byte, 11000000)
174 in0, err := open(infiles[0])
179 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
181 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
185 if *samplesFilename != "" {
186 cmd.samples, err = loadSampleInfo(*samplesFilename)
190 } else if *caseControlOnly {
191 return fmt.Errorf("-case-control-only does not make sense without -samples")
196 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
197 if len(ent.TagSet) > 0 {
200 for _, cseq := range ent.CompactSequences {
201 if cseq.Name == *ref || *ref == "" {
202 refseq = cseq.TileSequences
205 for _, cg := range ent.CompactGenomes {
206 if matchGenome.MatchString(cg.Name) {
207 cmd.cgnames = append(cmd.cgnames, cg.Name)
210 for _, tv := range ent.TileVariants {
212 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
222 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
225 if len(tagset) == 0 {
226 err = fmt.Errorf("tagset not found")
230 taglib := &tagLibrary{}
231 err = taglib.setTags(tagset)
235 taglen := taglib.TagLen()
236 sort.Strings(cmd.cgnames)
238 if len(cmd.cgnames) == 0 {
239 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
241 cmd.trainingSet = make([]int, len(cmd.cgnames))
242 if *samplesFilename == "" {
243 cmd.trainingSetSize = len(cmd.cgnames)
244 for i, name := range cmd.cgnames {
245 cmd.samples = append(cmd.samples, sampleInfo{
246 id: trimFilenameForLabel(name),
249 cmd.trainingSet[i] = i
251 } else if len(cmd.cgnames) != len(cmd.samples) {
252 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
254 for i, name := range cmd.cgnames {
255 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
256 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
259 if *caseControlOnly {
260 for i := 0; i < len(cmd.samples); i++ {
261 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
262 if i+1 < len(cmd.samples) {
263 copy(cmd.samples[i:], cmd.samples[i+1:])
264 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
266 cmd.samples = cmd.samples[:len(cmd.samples)-1]
267 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
273 cmd.trainingSetSize = 0
274 for i := range cmd.cgnames {
275 if cmd.samples[i].isTraining {
276 cmd.trainingSet[i] = cmd.trainingSetSize
277 cmd.trainingSetSize++
278 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
280 cmd.trainingSet[i] = -1
284 if cmd.filter.MinCoverage == 1 {
285 // In the generic formula below, floating point
286 // arithmetic can effectively push the coverage
287 // threshold above 1.0, which is impossible/useless.
288 // 1.0 needs to mean exactly 100% coverage.
289 cmd.minCoverage = len(cmd.cgnames)
291 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
295 samplesOutFilename := *outputDir + "/samples.csv"
296 log.Infof("writing sample metadata to %s", samplesOutFilename)
298 f, err = os.Create(samplesOutFilename)
303 for i, si := range cmd.samples {
307 } else if si.isControl {
315 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
317 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
323 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
329 log.Info("indexing reference tiles")
330 type reftileinfo struct {
331 variant tileVariantID
332 seqname string // chr1
333 pos int // distance from start of chromosome to starttag
334 tiledata []byte // acgtggcaa...
335 excluded bool // true if excluded by regions file
336 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
338 isdup := map[tagID]bool{}
339 reftile := map[tagID]*reftileinfo{}
340 for seqname, cseq := range refseq {
342 lastreftag := tagID(-1)
343 for _, libref := range cseq {
344 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
347 tiledata := reftiledata[libref]
348 if len(tiledata) == 0 {
349 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
352 foundthistag := false
353 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
354 if !foundthistag && tagid == libref.Tag {
358 if dupref, ok := reftile[tagid]; ok {
359 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)
360 delete(reftile, tagid)
362 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
366 if isdup[libref.Tag] {
367 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
368 } else if reftile[libref.Tag] != nil {
369 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)
370 delete(reftile, libref.Tag)
371 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
372 isdup[libref.Tag] = true
374 reftile[libref.Tag] = &reftileinfo{
376 variant: libref.Variant,
382 reftile[lastreftag].nexttag = libref.Tag
384 lastreftag = libref.Tag
386 pos += len(tiledata) - taglen
388 log.Printf("... %s done, len %d", seqname, pos+taglen)
392 if *regionsFilename != "" {
393 log.Printf("loading regions from %s", *regionsFilename)
394 mask, err = makeMask(*regionsFilename, *expandRegions)
398 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
399 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
400 for _, rt := range reftile {
401 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
405 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
408 type hgvsColSet map[hgvs.Variant][2][]int8
409 encodeHGVS := throttle{Max: len(refseq)}
410 encodeHGVSTodo := map[string]chan hgvsColSet{}
411 tmpHGVSCols := map[string]*os.File{}
413 for seqname := range refseq {
415 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
419 defer os.Remove(f.Name())
420 bufw := bufio.NewWriterSize(f, 1<<24)
421 enc := gob.NewEncoder(bufw)
422 tmpHGVSCols[seqname] = f
423 todo := make(chan hgvsColSet, 128)
424 encodeHGVSTodo[seqname] = todo
425 encodeHGVS.Go(func() error {
426 for colset := range todo {
427 err := enc.Encode(colset)
429 encodeHGVS.Report(err)
440 var toMerge [][]int16
441 if *mergeOutput || *hgvsSingle {
442 toMerge = make([][]int16, len(infiles))
444 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
445 var onehotChunkSize []uint32
446 var onehotXrefs [][]onehotXref
447 if *onehotSingle || *onlyPCA {
448 onehotIndirect = make([][2][]uint32, len(infiles))
449 onehotChunkSize = make([]uint32, len(infiles))
450 onehotXrefs = make([][]onehotXref, len(infiles))
452 chunkStartTag := make([]tagID, len(infiles))
454 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
455 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
456 log.Info("generating annotations and numpy matrix for each slice")
457 var errSkip = errors.New("skip infile")
459 for infileIdx, infile := range infiles {
460 infileIdx, infile := infileIdx, infile
461 throttleMem.Go(func() error {
462 seq := make(map[tagID][]TileVariant, 50000)
463 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
464 f, err := open(infile)
469 log.Infof("%04d: reading %s", infileIdx, infile)
470 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
471 for _, tv := range ent.TileVariants {
476 // corresponding ref tile, if
477 // mask is in play (we can't
478 // determine coordinates for
480 if mask != nil && reftile[tv.Tag] == nil {
484 // corresponding ref tile is
485 // outside target regions --
486 // unless it's a potential
488 if mask != nil && reftile[tv.Tag].excluded &&
489 (int(tv.Tag+1) >= len(tagset) ||
490 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
493 if tv.Tag == cmd.debugTag {
494 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
496 variants := seq[tv.Tag]
497 if len(variants) == 0 {
498 variants = make([]TileVariant, 100)
500 for len(variants) <= int(tv.Variant) {
501 variants = append(variants, TileVariant{})
503 variants[int(tv.Variant)] = tv
504 seq[tv.Tag] = variants
506 for _, cg := range ent.CompactGenomes {
507 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
510 if !matchGenome.MatchString(cg.Name) {
513 // pad to full slice size
514 // to avoid out-of-bounds
516 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
517 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
525 } else if err != nil {
526 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
528 tagstart := cgs[cmd.cgnames[0]].StartTag
529 tagend := cgs[cmd.cgnames[0]].EndTag
530 chunkStartTag[infileIdx] = tagstart
534 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
535 variantRemap := make([][]tileVariantID, tagend-tagstart)
536 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
537 for tag, variants := range seq {
538 tag, variants := tag, variants
539 throttleCPU.Go(func() error {
541 count := make(map[[blake2b.Size256]byte]int, len(variants))
545 count[blake2b.Sum256(rt.tiledata)] = 0
548 for cgname, cg := range cgs {
549 idx := int(tag-tagstart) * 2
550 for allele := 0; allele < 2; allele++ {
551 v := cg.Variants[idx+allele]
552 if v > 0 && len(variants[v].Sequence) > 0 {
553 count[variants[v].Blake2b]++
556 if v > 0 && tag == cmd.debugTag {
557 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])
561 if alleleCoverage < cmd.minCoverage*2 {
562 idx := int(tag-tagstart) * 2
563 for _, cg := range cgs {
565 cg.Variants[idx+1] = 0
567 if tag == cmd.debugTag {
568 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
573 // hash[i] will be the hash of
574 // the variant(s) that should
575 // be at rank i (0-based).
576 hash := make([][blake2b.Size256]byte, 0, len(count))
577 for b := range count {
578 hash = append(hash, b)
580 sort.Slice(hash, func(i, j int) bool {
581 bi, bj := &hash[i], &hash[j]
582 if ci, cj := count[*bi], count[*bj]; ci != cj {
585 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
588 // rank[b] will be the 1-based
589 // new variant number for
590 // variants whose hash is b.
591 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
592 for i, h := range hash {
593 rank[h] = tileVariantID(i + 1)
595 if tag == cmd.debugTag {
596 for h, r := range rank {
597 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
600 // remap[v] will be the new
601 // variant number for original
603 remap := make([]tileVariantID, len(variants))
604 for i, tv := range variants {
605 remap[i] = rank[tv.Blake2b]
607 if tag == cmd.debugTag {
608 for in, out := range remap {
610 log.Printf("tag %d remap %d => %d", tag, in, out)
614 variantRemap[tag-tagstart] = remap
616 refrank := rank[blake2b.Sum256(rt.tiledata)]
617 if tag == cmd.debugTag {
618 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
627 var onehotChunk [][]int8
628 var onehotXref []onehotXref
630 var annotationsFilename string
632 annotationsFilename = "/dev/null"
634 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
635 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
637 annof, err := os.Create(annotationsFilename)
641 annow := bufio.NewWriterSize(annof, 1<<20)
643 for tag := tagstart; tag < tagend; tag++ {
645 if rt == nil && mask != nil {
646 // With no ref tile, we don't
647 // have coordinates to say
648 // this is in the desired
649 // regions -- so it's not.
650 // TODO: handle ref spanning
654 if rt != nil && rt.excluded {
655 // TODO: don't skip yet --
656 // first check for spanning
657 // tile variants that
658 // intersect non-excluded ref
662 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
665 remap := variantRemap[tag-tagstart]
667 // was not assigned above,
668 // because minCoverage
672 maxv := tileVariantID(0)
673 for _, v := range remap {
678 if *onehotChunked || *onehotSingle || *onlyPCA {
679 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
680 if tag == cmd.debugTag {
681 log.WithFields(logrus.Fields{
684 }).Info("tv2homhet()")
686 onehotChunk = append(onehotChunk, onehot...)
687 onehotXref = append(onehotXref, xrefs...)
694 // Reference does not use any
695 // variant of this tile
697 // TODO: diff against the
698 // relevant portion of the
699 // ref's spanning tile
703 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
705 reftilestr := strings.ToUpper(string(rt.tiledata))
707 done := make([]bool, maxv+1)
708 variantDiffs := make([][]hgvs.Variant, maxv+1)
709 for v, tv := range variants {
711 if v == 0 || v == rt.variant || done[v] {
716 if len(tv.Sequence) < taglen {
719 // if reftilestr doesn't end
720 // in the same tag as tv,
721 // extend reftilestr with
722 // following ref tiles until
723 // it does (up to an arbitrary
724 // sanity-check limit)
725 reftilestr := reftilestr
726 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
727 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
728 rt = reftile[rt.nexttag]
732 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
734 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
737 if !strings.HasSuffix(reftilestr, endtagstr) {
738 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
741 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
742 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
745 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
746 for i := range diffs {
747 diffs[i].Position += rt.pos
749 for _, diff := range diffs {
750 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)
753 variantDiffs[v] = diffs
757 // We can now determine, for each HGVS
758 // variant (diff) in this reftile
759 // region, whether a given genome
760 // phase/allele (1) has the variant, (0) has
761 // =ref or a different variant in that
762 // position, or (-1) is lacking
763 // coverage / couldn't be diffed.
764 hgvsCol := hgvsColSet{}
765 for _, diffs := range variantDiffs {
766 for _, diff := range diffs {
767 if _, ok := hgvsCol[diff]; ok {
770 hgvsCol[diff] = [2][]int8{
771 make([]int8, len(cmd.cgnames)),
772 make([]int8, len(cmd.cgnames)),
776 for row, name := range cmd.cgnames {
777 variants := cgs[name].Variants[(tag-tagstart)*2:]
778 for ph := 0; ph < 2; ph++ {
780 if int(v) >= len(remap) {
786 // hgvsCol[*][ph][row] is already 0
787 } else if len(variantDiffs[v]) == 0 {
788 // lacking coverage / couldn't be diffed
789 for _, col := range hgvsCol {
793 for _, diff := range variantDiffs[v] {
794 hgvsCol[diff][ph][row] = 1
799 for diff, colpair := range hgvsCol {
800 allele2homhet(colpair)
801 if !cmd.filterHGVScolpair(colpair) {
802 delete(hgvsCol, diff)
805 if len(hgvsCol) > 0 {
806 encodeHGVSTodo[rt.seqname] <- hgvsCol
821 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
822 rows := len(cmd.cgnames)
823 cols := len(onehotChunk)
824 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
825 throttleNumpyMem.Acquire()
826 out := onehotcols2int8(onehotChunk)
827 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
828 err = writeNumpyInt8(fnm, out, rows, cols)
832 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
833 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
838 throttleNumpyMem.Release()
840 if *onehotSingle || *onlyPCA {
841 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
842 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
843 onehotXrefs[infileIdx] = onehotXref
844 n := len(onehotIndirect[infileIdx][0])
845 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
847 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
848 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
849 throttleNumpyMem.Acquire()
850 rows := len(cmd.cgnames)
852 out := make([]int16, rows*cols)
853 for row, name := range cmd.cgnames {
855 for col, v := range cgs[name].Variants {
856 tag := tagstart + tagID(col/2)
857 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
860 if rt := reftile[tag]; rt == nil || rt.excluded {
864 out[outidx] = 0 // tag not found / spanning tile
865 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
866 out[outidx] = int16(variantRemap[tag-tagstart][v])
868 out[outidx] = -1 // low quality tile variant
870 if tag == cmd.debugTag {
871 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
879 throttleNumpyMem.Release()
880 if *mergeOutput || *hgvsSingle {
881 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
882 toMerge[infileIdx] = out
884 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
885 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
886 err = writeNumpyInt16(fnm, out, rows, cols)
893 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
897 if err = throttleMem.Wait(); err != nil {
902 log.Info("flushing hgvsCols temp files")
903 for seqname := range refseq {
904 close(encodeHGVSTodo[seqname])
906 err = encodeHGVS.Wait()
910 for seqname := range refseq {
911 log.Infof("%s: reading hgvsCols from temp file", seqname)
912 f := tmpHGVSCols[seqname]
913 _, err = f.Seek(0, io.SeekStart)
917 var hgvsCols hgvsColSet
918 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
920 err = dec.Decode(&hgvsCols)
925 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
926 variants := make([]hgvs.Variant, 0, len(hgvsCols))
927 for v := range hgvsCols {
928 variants = append(variants, v)
930 sort.Slice(variants, func(i, j int) bool {
931 vi, vj := &variants[i], &variants[j]
932 if vi.Position != vj.Position {
933 return vi.Position < vj.Position
934 } else if vi.Ref != vj.Ref {
935 return vi.Ref < vj.Ref
937 return vi.New < vj.New
940 rows := len(cmd.cgnames)
941 cols := len(variants) * 2
942 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
943 out := make([]int8, rows*cols)
944 for varIdx, variant := range variants {
945 hgvsCols := hgvsCols[variant]
946 for row := range cmd.cgnames {
947 for ph := 0; ph < 2; ph++ {
948 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
952 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
958 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
959 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
960 var hgvsLabels bytes.Buffer
961 for varIdx, variant := range variants {
962 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
964 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
971 if *mergeOutput || *hgvsSingle {
972 var annow *bufio.Writer
975 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
976 annof, err = os.Create(annoFilename)
980 annow = bufio.NewWriterSize(annof, 1<<20)
983 rows := len(cmd.cgnames)
985 for _, chunk := range toMerge {
986 cols += len(chunk) / rows
988 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
991 out = make([]int16, rows*cols)
993 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
995 for outIdx, chunk := range toMerge {
996 chunkcols := len(chunk) / rows
998 for row := 0; row < rows; row++ {
999 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1002 toMerge[outIdx] = nil
1004 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1005 log.Infof("reading %s", annotationsFilename)
1006 buf, err := os.ReadFile(annotationsFilename)
1011 err = os.Remove(annotationsFilename)
1016 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1020 fields := bytes.SplitN(line, []byte{','}, 9)
1021 tag, _ := strconv.Atoi(string(fields[0]))
1022 incol, _ := strconv.Atoi(string(fields[1]))
1023 tileVariant, _ := strconv.Atoi(string(fields[2]))
1024 hgvsID := string(fields[3])
1025 seqname := string(fields[4])
1026 pos, _ := strconv.Atoi(string(fields[5]))
1029 // Null entry for un-diffable
1034 // Null entry for ref tile
1037 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1038 // The tile intersects one of
1039 // the selected regions, but
1040 // this particular HGVS
1041 // variant does not.
1044 hgvsColPair := hgvsCols[hgvsID]
1045 if hgvsColPair[0] == nil {
1046 // values in new columns start
1047 // out as -1 ("no data yet")
1048 // or 0 ("=ref") here, may
1049 // change to 1 ("hgvs variant
1050 // present") below, either on
1051 // this line or a future line.
1052 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1053 rt, ok := reftile[tagID(tag)]
1055 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1058 for ph := 0; ph < 2; ph++ {
1059 for row := 0; row < rows; row++ {
1060 v := chunk[row*chunkcols+incol*2+ph]
1061 if tileVariantID(v) == rt.variant {
1062 hgvsColPair[ph][row] = 0
1064 hgvsColPair[ph][row] = -1
1068 hgvsCols[hgvsID] = hgvsColPair
1070 hgvsref := hgvs.Variant{
1072 Ref: string(refseq),
1073 New: string(refseq),
1075 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])
1079 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])
1081 for ph := 0; ph < 2; ph++ {
1082 for row := 0; row < rows; row++ {
1083 v := chunk[row*chunkcols+incol*2+ph]
1084 if int(v) == tileVariant {
1085 hgvsColPair[ph][row] = 1
1091 startcol += chunkcols
1102 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1110 cols = len(hgvsCols) * 2
1111 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1112 out = make([]int16, rows*cols)
1113 hgvsIDs := make([]string, 0, cols/2)
1114 for hgvsID := range hgvsCols {
1115 hgvsIDs = append(hgvsIDs, hgvsID)
1117 sort.Strings(hgvsIDs)
1118 var hgvsLabels bytes.Buffer
1119 for idx, hgvsID := range hgvsIDs {
1120 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1121 for ph := 0; ph < 2; ph++ {
1122 hgvscol := hgvsCols[hgvsID][ph]
1123 for row, val := range hgvscol {
1124 out[row*cols+idx*2+ph] = val
1128 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1133 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1134 log.Printf("writing hgvs labels: %s", fnm)
1135 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1141 if *onehotSingle || *onlyPCA {
1143 for _, part := range onehotIndirect {
1144 nzCount += len(part[0])
1146 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1147 var xrefs []onehotXref
1148 chunkOffset := uint32(0)
1150 for i, part := range onehotIndirect {
1151 for i := range part[1] {
1152 part[1][i] += chunkOffset
1154 copy(onehot[outcol:], part[0])
1155 copy(onehot[outcol+nzCount:], part[1])
1156 xrefs = append(xrefs, onehotXrefs[i]...)
1158 outcol += len(part[0])
1159 chunkOffset += onehotChunkSize[i]
1163 onehotXrefs[i] = nil
1164 debug.FreeOSMemory()
1167 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1168 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1172 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1173 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1180 for _, c := range onehot[nzCount:] {
1186 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1188 log.Printf("have %d one-hot cols", cols)
1190 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1191 cols = (cols + 1) / 2
1195 // we work with pairs of columns
1198 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1199 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1200 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1201 for i, c := range onehot[nzCount:] {
1202 if int(c/2)%stride == 0 {
1203 outcol := int(c/2)/stride*2 + int(c)%2
1204 mtxFull.Set(int(onehot[i]), outcol, 1)
1205 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1206 mtxTrain.Set(trainRow, outcol, 1)
1210 log.Print("fitting")
1211 transformer := nlp.NewPCA(cmd.pcaComponents)
1212 transformer.Fit(mtxTrain.T())
1213 log.Printf("transforming")
1214 pca, err := transformer.Transform(mtxFull.T())
1219 outrows, outcols := pca.Dims()
1220 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1221 out := make([]float64, outrows*outcols)
1222 for i := 0; i < outrows; i++ {
1223 for j := 0; j < outcols; j++ {
1224 out[i*outcols+j] = pca.At(i, j)
1227 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1228 log.Printf("writing numpy: %s", fnm)
1229 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1233 npw, err := gonpy.NewWriter(nopCloser{output})
1235 return fmt.Errorf("gonpy.NewWriter: %w", err)
1237 npw.Shape = []int{outrows, outcols}
1238 err = npw.WriteFloat64(out)
1240 return fmt.Errorf("WriteFloat64: %w", err)
1242 err = output.Close()
1248 samplesOutFilename := *outputDir + "/samples.csv"
1249 log.Infof("writing sample metadata to %s", samplesOutFilename)
1251 f, err = os.Create(samplesOutFilename)
1256 for i, si := range cmd.samples {
1260 } else if si.isControl {
1269 for c := 0; c < outcols; c++ {
1270 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1272 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1274 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1280 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1286 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1287 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1288 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1290 f, err = os.Create(tagoffsetFilename)
1295 for idx, offset := range chunkStartTag {
1296 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1298 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1304 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1312 type sampleInfo struct {
1318 pcaComponents []float64
1321 // Read samples.csv file with case/control and training/validation
1323 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1325 f, err := open(samplesFilename)
1329 buf, err := io.ReadAll(f)
1335 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1340 split := strings.Split(string(csv), ",")
1342 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1344 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1347 idx, err := strconv.Atoi(split[0])
1350 return nil, fmt.Errorf("header does not look right: %q", csv)
1352 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1355 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1357 var pcaComponents []float64
1359 for _, s := range split[4:] {
1360 f, err := strconv.ParseFloat(s, 64)
1362 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1364 pcaComponents = append(pcaComponents, f)
1367 si = append(si, sampleInfo{
1369 isCase: split[2] == "1",
1370 isControl: split[2] == "0",
1371 isTraining: split[3] == "1",
1372 isValidation: split[3] == "0",
1373 pcaComponents: pcaComponents,
1379 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1380 if cmd.chi2PValue >= 1 {
1383 col0 := make([]bool, 0, len(cmd.chi2Cases))
1384 col1 := make([]bool, 0, len(cmd.chi2Cases))
1385 cases := make([]bool, 0, len(cmd.chi2Cases))
1386 for i, c := range cmd.chi2Cases {
1387 if colpair[0][i] < 0 {
1390 col0 = append(col0, colpair[0][i] != 0)
1391 col1 = append(col1, colpair[1][i] != 0)
1392 cases = append(cases, c)
1394 return len(cases) >= cmd.minCoverage &&
1395 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1398 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1399 output, err := os.Create(fnm)
1403 defer output.Close()
1404 bufw := bufio.NewWriterSize(output, 1<<26)
1405 npw, err := gonpy.NewWriter(nopCloser{bufw})
1409 log.WithFields(log.Fields{
1413 "bytes": rows * cols * 4,
1414 }).Infof("writing numpy: %s", fnm)
1415 npw.Shape = []int{rows, cols}
1416 npw.WriteUint32(out)
1421 return output.Close()
1424 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1425 output, err := os.Create(fnm)
1429 defer output.Close()
1430 bufw := bufio.NewWriterSize(output, 1<<26)
1431 npw, err := gonpy.NewWriter(nopCloser{bufw})
1435 log.WithFields(log.Fields{
1439 "bytes": rows * cols * 4,
1440 }).Infof("writing numpy: %s", fnm)
1441 npw.Shape = []int{rows, cols}
1447 return output.Close()
1450 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1451 output, err := os.Create(fnm)
1455 defer output.Close()
1456 bufw := bufio.NewWriterSize(output, 1<<26)
1457 npw, err := gonpy.NewWriter(nopCloser{bufw})
1461 log.WithFields(log.Fields{
1465 "bytes": rows * cols * 2,
1466 }).Infof("writing numpy: %s", fnm)
1467 npw.Shape = []int{rows, cols}
1473 return output.Close()
1476 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1477 output, err := os.Create(fnm)
1481 defer output.Close()
1482 bufw := bufio.NewWriterSize(output, 1<<26)
1483 npw, err := gonpy.NewWriter(nopCloser{bufw})
1487 log.WithFields(log.Fields{
1491 "bytes": rows * cols,
1492 }).Infof("writing numpy: %s", fnm)
1493 npw.Shape = []int{rows, cols}
1499 return output.Close()
1502 func allele2homhet(colpair [2][]int8) {
1503 a, b := colpair[0], colpair[1]
1504 for i, av := range a {
1506 if av < 0 || bv < 0 {
1509 } else if av > 0 && bv > 0 {
1512 } else if av > 0 || bv > 0 {
1516 // ref (or a different variant in same position)
1517 // (this is a no-op) a[i], b[i] = 0, 0
1522 type onehotXref struct {
1524 variant tileVariantID
1529 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1531 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1532 // variants of a single tile/tag#.
1534 // Return nil if no tile variant passes Χ² filter.
1535 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1536 if tag == cmd.debugTag {
1537 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1538 for i, name := range cmd.cgnames {
1539 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1541 log.WithFields(logrus.Fields{
1542 "cgs[i].Variants[tag*2+j]": tv,
1546 "chunkstarttag": chunkstarttag,
1547 }).Info("tv2homhet()")
1549 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1550 // everyone has the most common variant (of the variants we don't drop)
1553 tagoffset := tag - chunkstarttag
1555 for _, cg := range cgs {
1557 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1558 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1566 if coverage < cmd.minCoverage {
1569 // "observed" array for p-value calculation (training set
1571 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1572 // one-hot output (all samples)
1573 outcols := make([][]int8, (maxv+1)*2)
1574 for i := range obs {
1575 obs[i] = make([]bool, cmd.trainingSetSize)
1576 outcols[i] = make([]int8, len(cmd.cgnames))
1578 for cgid, name := range cmd.cgnames {
1579 tsid := cmd.trainingSet[cgid]
1580 cgvars := cgs[name].Variants[tagoffset*2:]
1581 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1582 for v := tileVariantID(1); v <= maxv; v++ {
1583 if tv0 == v && tv1 == v {
1585 obs[v*2][tsid] = true
1587 outcols[v*2][cgid] = 1
1588 } else if tv0 == v || tv1 == v {
1590 obs[v*2+1][tsid] = true
1592 outcols[v*2+1][cgid] = 1
1597 var xref []onehotXref
1598 for col := 2; col < len(obs); col++ {
1599 // col 0,1 correspond to tile variant 0, i.e.,
1600 // no-call; col 2,3 correspond to the most common
1601 // variant; so we (normally) start at col 4.
1602 if col < 4 && !cmd.includeVariant1 {
1606 if len(cmd.samples[0].pcaComponents) > 0 {
1607 p = pvalueGLM(cmd.samples, obs[col], cmd.pcaComponents)
1609 p = pvalue(obs[col], cmd.chi2Cases)
1611 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1614 onehot = append(onehot, outcols[col])
1615 xref = append(xref, onehotXref{
1617 variant: tileVariantID(col >> 1),
1625 // convert a []onehotXref with length N to a numpy-style []int32
1626 // matrix with N columns, one row per field of onehotXref struct.
1628 // Hom/het row contains hom=0, het=1.
1630 // P-value row contains 1000000x actual p-value.
1631 func onehotXref2int32(xrefs []onehotXref) []int32 {
1633 xdata := make([]int32, 5*xcols)
1634 for i, xref := range xrefs {
1635 xdata[i] = int32(xref.tag)
1636 xdata[xcols+i] = int32(xref.variant)
1638 xdata[xcols*2+i] = 1
1640 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1641 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1646 // transpose onehot data from in[col][row] to numpy-style
1647 // out[row*cols+col].
1648 func onehotcols2int8(in [][]int8) []int8 {
1654 out := make([]int8, rows*cols)
1655 for row := 0; row < rows; row++ {
1656 outrow := out[row*cols:]
1657 for col, incol := range in {
1658 outrow[col] = incol[row]
1664 // Return [2][]uint32{rowIndices, colIndices} indicating which
1665 // elements of matrixT[c][r] have non-zero values.
1666 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1668 for c, col := range matrixT {
1669 for r, val := range col {
1671 nz[0] = append(nz[0], uint32(r))
1672 nz[1] = append(nz[1], uint32(c))