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
55 pvalue func(onehot []bool) float64
58 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
59 err := cmd.run(prog, args, stdin, stdout, stderr)
61 fmt.Fprintf(stderr, "%s\n", err)
67 func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
68 flags := flag.NewFlagSet("", flag.ContinueOnError)
69 flags.SetOutput(stderr)
70 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
71 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
72 arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
73 arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
74 projectUUID := flags.String("project", "", "project `UUID` for output data")
75 priority := flags.Int("priority", 500, "container request priority")
76 inputDir := flags.String("input-dir", "./in", "input `directory`")
77 outputDir := flags.String("output-dir", "./out", "output `directory`")
78 ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
79 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
80 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
81 mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
82 hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
83 hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
84 onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
85 onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
86 samplesFilename := flags.String("samples", "", "`samples.csv` file with training/validation and case/control groups (see 'lightning choose-samples')")
87 caseControlOnly := flags.Bool("case-control-only", false, "drop samples that are not in case/control groups")
88 onlyPCA := flags.Bool("pca", false, "run principal component analysis, write components to pca.npy and samples.csv")
89 flags.IntVar(&cmd.pcaComponents, "pca-components", 4, "number of PCA components to compute / use in logistic regression")
90 maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
91 debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
92 flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
93 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")
94 flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
95 cmd.filter.Flags(flags)
96 err := flags.Parse(args)
97 if err == flag.ErrHelp {
99 } else if err != nil {
101 } else if flags.NArg() > 0 {
102 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
107 log.Println(http.ListenAndServe(*pprof, nil))
111 if cmd.chi2PValue != 1 && *samplesFilename == "" {
112 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -samples= value is empty", cmd.chi2PValue)
115 cmd.debugTag = tagID(*debugTag)
118 runner := arvadosContainerRunner{
119 Name: "lightning slice-numpy",
120 Client: arvados.NewClientFromEnv(),
121 ProjectUUID: *projectUUID,
122 RAM: int64(*arvadosRAM),
123 VCPUs: *arvadosVCPUs,
128 err = runner.TranslatePaths(inputDir, regionsFilename, samplesFilename)
132 runner.Args = []string{"slice-numpy", "-local=true",
134 "-input-dir=" + *inputDir,
135 "-output-dir=/mnt/output",
136 "-threads=" + fmt.Sprintf("%d", cmd.threads),
137 "-regions=" + *regionsFilename,
138 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
139 "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
140 "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
141 "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
142 "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
143 "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
144 "-samples=" + *samplesFilename,
145 "-case-control-only=" + fmt.Sprintf("%v", *caseControlOnly),
146 "-pca=" + fmt.Sprintf("%v", *onlyPCA),
147 "-pca-components=" + fmt.Sprintf("%d", cmd.pcaComponents),
148 "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
149 "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
150 "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
151 "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
153 runner.Args = append(runner.Args, cmd.filter.Args()...)
155 output, err = runner.Run()
159 fmt.Fprintln(stdout, output)
163 infiles, err := allFiles(*inputDir, matchGobFile)
167 if len(infiles) == 0 {
168 err = fmt.Errorf("no input files found in %s", *inputDir)
171 sort.Strings(infiles)
173 var refseq map[string][]tileLibRef
174 var reftiledata = make(map[tileLibRef][]byte, 11000000)
175 in0, err := open(infiles[0])
180 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
182 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
186 if *samplesFilename != "" {
187 cmd.samples, err = loadSampleInfo(*samplesFilename)
191 if len(cmd.samples[0].pcaComponents) > 0 {
192 cmd.pvalue = glmPvalueFunc(cmd.samples, cmd.pcaComponents)
194 } else if *caseControlOnly {
195 return fmt.Errorf("-case-control-only does not make sense without -samples")
200 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
201 if len(ent.TagSet) > 0 {
204 for _, cseq := range ent.CompactSequences {
205 if cseq.Name == *ref || *ref == "" {
206 refseq = cseq.TileSequences
209 for _, cg := range ent.CompactGenomes {
210 if matchGenome.MatchString(cg.Name) {
211 cmd.cgnames = append(cmd.cgnames, cg.Name)
214 for _, tv := range ent.TileVariants {
216 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
226 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
229 if len(tagset) == 0 {
230 err = fmt.Errorf("tagset not found")
234 taglib := &tagLibrary{}
235 err = taglib.setTags(tagset)
239 taglen := taglib.TagLen()
240 sort.Strings(cmd.cgnames)
242 if len(cmd.cgnames) == 0 {
243 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
245 cmd.trainingSet = make([]int, len(cmd.cgnames))
246 if *samplesFilename == "" {
247 cmd.trainingSetSize = len(cmd.cgnames)
248 for i, name := range cmd.cgnames {
249 cmd.samples = append(cmd.samples, sampleInfo{
250 id: trimFilenameForLabel(name),
253 cmd.trainingSet[i] = i
255 } else if len(cmd.cgnames) != len(cmd.samples) {
256 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
258 for i, name := range cmd.cgnames {
259 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
260 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
263 if *caseControlOnly {
264 for i := 0; i < len(cmd.samples); i++ {
265 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
266 if i+1 < len(cmd.samples) {
267 copy(cmd.samples[i:], cmd.samples[i+1:])
268 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
270 cmd.samples = cmd.samples[:len(cmd.samples)-1]
271 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
277 cmd.trainingSetSize = 0
278 for i := range cmd.cgnames {
279 if cmd.samples[i].isTraining {
280 cmd.trainingSet[i] = cmd.trainingSetSize
281 cmd.trainingSetSize++
282 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
284 cmd.trainingSet[i] = -1
287 if cmd.pvalue == nil {
288 cmd.pvalue = func(onehot []bool) float64 {
289 return pvalue(onehot, cmd.chi2Cases)
293 if cmd.filter.MinCoverage == 1 {
294 // In the generic formula below, floating point
295 // arithmetic can effectively push the coverage
296 // threshold above 1.0, which is impossible/useless.
297 // 1.0 needs to mean exactly 100% coverage.
298 cmd.minCoverage = len(cmd.cgnames)
300 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
304 samplesOutFilename := *outputDir + "/samples.csv"
305 log.Infof("writing sample metadata to %s", samplesOutFilename)
307 f, err = os.Create(samplesOutFilename)
312 for i, si := range cmd.samples {
316 } else if si.isControl {
324 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
326 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
332 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
338 log.Info("indexing reference tiles")
339 type reftileinfo struct {
340 variant tileVariantID
341 seqname string // chr1
342 pos int // distance from start of chromosome to starttag
343 tiledata []byte // acgtggcaa...
344 excluded bool // true if excluded by regions file
345 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
347 isdup := map[tagID]bool{}
348 reftile := map[tagID]*reftileinfo{}
349 for seqname, cseq := range refseq {
351 lastreftag := tagID(-1)
352 for _, libref := range cseq {
353 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
356 tiledata := reftiledata[libref]
357 if len(tiledata) == 0 {
358 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
361 foundthistag := false
362 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
363 if !foundthistag && tagid == libref.Tag {
367 if dupref, ok := reftile[tagid]; ok {
368 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)
369 delete(reftile, tagid)
371 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
375 if isdup[libref.Tag] {
376 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
377 } else if reftile[libref.Tag] != nil {
378 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)
379 delete(reftile, libref.Tag)
380 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
381 isdup[libref.Tag] = true
383 reftile[libref.Tag] = &reftileinfo{
385 variant: libref.Variant,
391 reftile[lastreftag].nexttag = libref.Tag
393 lastreftag = libref.Tag
395 pos += len(tiledata) - taglen
397 log.Printf("... %s done, len %d", seqname, pos+taglen)
401 if *regionsFilename != "" {
402 log.Printf("loading regions from %s", *regionsFilename)
403 mask, err = makeMask(*regionsFilename, *expandRegions)
407 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
408 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
409 for _, rt := range reftile {
410 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
414 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
417 type hgvsColSet map[hgvs.Variant][2][]int8
418 encodeHGVS := throttle{Max: len(refseq)}
419 encodeHGVSTodo := map[string]chan hgvsColSet{}
420 tmpHGVSCols := map[string]*os.File{}
422 for seqname := range refseq {
424 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
428 defer os.Remove(f.Name())
429 bufw := bufio.NewWriterSize(f, 1<<24)
430 enc := gob.NewEncoder(bufw)
431 tmpHGVSCols[seqname] = f
432 todo := make(chan hgvsColSet, 128)
433 encodeHGVSTodo[seqname] = todo
434 encodeHGVS.Go(func() error {
435 for colset := range todo {
436 err := enc.Encode(colset)
438 encodeHGVS.Report(err)
449 var toMerge [][]int16
450 if *mergeOutput || *hgvsSingle {
451 toMerge = make([][]int16, len(infiles))
453 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
454 var onehotChunkSize []uint32
455 var onehotXrefs [][]onehotXref
456 if *onehotSingle || *onlyPCA {
457 onehotIndirect = make([][2][]uint32, len(infiles))
458 onehotChunkSize = make([]uint32, len(infiles))
459 onehotXrefs = make([][]onehotXref, len(infiles))
461 chunkStartTag := make([]tagID, len(infiles))
463 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
464 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
465 log.Info("generating annotations and numpy matrix for each slice")
466 var errSkip = errors.New("skip infile")
468 for infileIdx, infile := range infiles {
469 infileIdx, infile := infileIdx, infile
470 throttleMem.Go(func() error {
471 seq := make(map[tagID][]TileVariant, 50000)
472 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
473 f, err := open(infile)
478 log.Infof("%04d: reading %s", infileIdx, infile)
479 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
480 for _, tv := range ent.TileVariants {
485 // corresponding ref tile, if
486 // mask is in play (we can't
487 // determine coordinates for
489 if mask != nil && reftile[tv.Tag] == nil {
493 // corresponding ref tile is
494 // outside target regions --
495 // unless it's a potential
497 if mask != nil && reftile[tv.Tag].excluded &&
498 (int(tv.Tag+1) >= len(tagset) ||
499 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
502 if tv.Tag == cmd.debugTag {
503 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
505 variants := seq[tv.Tag]
506 if len(variants) == 0 {
507 variants = make([]TileVariant, 100)
509 for len(variants) <= int(tv.Variant) {
510 variants = append(variants, TileVariant{})
512 variants[int(tv.Variant)] = tv
513 seq[tv.Tag] = variants
515 for _, cg := range ent.CompactGenomes {
516 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
519 if !matchGenome.MatchString(cg.Name) {
522 // pad to full slice size
523 // to avoid out-of-bounds
525 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
526 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
534 } else if err != nil {
535 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
537 tagstart := cgs[cmd.cgnames[0]].StartTag
538 tagend := cgs[cmd.cgnames[0]].EndTag
539 chunkStartTag[infileIdx] = tagstart
543 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
544 variantRemap := make([][]tileVariantID, tagend-tagstart)
545 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
546 for tag, variants := range seq {
547 tag, variants := tag, variants
548 throttleCPU.Go(func() error {
550 count := make(map[[blake2b.Size256]byte]int, len(variants))
554 count[blake2b.Sum256(rt.tiledata)] = 0
557 for cgname, cg := range cgs {
558 idx := int(tag-tagstart) * 2
559 for allele := 0; allele < 2; allele++ {
560 v := cg.Variants[idx+allele]
561 if v > 0 && len(variants[v].Sequence) > 0 {
562 count[variants[v].Blake2b]++
565 if v > 0 && tag == cmd.debugTag {
566 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])
570 if alleleCoverage < cmd.minCoverage*2 {
571 idx := int(tag-tagstart) * 2
572 for _, cg := range cgs {
574 cg.Variants[idx+1] = 0
576 if tag == cmd.debugTag {
577 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
582 // hash[i] will be the hash of
583 // the variant(s) that should
584 // be at rank i (0-based).
585 hash := make([][blake2b.Size256]byte, 0, len(count))
586 for b := range count {
587 hash = append(hash, b)
589 sort.Slice(hash, func(i, j int) bool {
590 bi, bj := &hash[i], &hash[j]
591 if ci, cj := count[*bi], count[*bj]; ci != cj {
594 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
597 // rank[b] will be the 1-based
598 // new variant number for
599 // variants whose hash is b.
600 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
601 for i, h := range hash {
602 rank[h] = tileVariantID(i + 1)
604 if tag == cmd.debugTag {
605 for h, r := range rank {
606 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
609 // remap[v] will be the new
610 // variant number for original
612 remap := make([]tileVariantID, len(variants))
613 for i, tv := range variants {
614 remap[i] = rank[tv.Blake2b]
616 if tag == cmd.debugTag {
617 for in, out := range remap {
619 log.Printf("tag %d remap %d => %d", tag, in, out)
623 variantRemap[tag-tagstart] = remap
625 refrank := rank[blake2b.Sum256(rt.tiledata)]
626 if tag == cmd.debugTag {
627 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
636 var onehotChunk [][]int8
637 var onehotXref []onehotXref
639 var annotationsFilename string
641 annotationsFilename = "/dev/null"
643 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
644 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
646 annof, err := os.Create(annotationsFilename)
650 annow := bufio.NewWriterSize(annof, 1<<20)
652 for tag := tagstart; tag < tagend; tag++ {
654 if rt == nil && mask != nil {
655 // With no ref tile, we don't
656 // have coordinates to say
657 // this is in the desired
658 // regions -- so it's not.
659 // TODO: handle ref spanning
663 if rt != nil && rt.excluded {
664 // TODO: don't skip yet --
665 // first check for spanning
666 // tile variants that
667 // intersect non-excluded ref
671 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
674 remap := variantRemap[tag-tagstart]
676 // was not assigned above,
677 // because minCoverage
681 maxv := tileVariantID(0)
682 for _, v := range remap {
687 if *onehotChunked || *onehotSingle || *onlyPCA {
688 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
689 if tag == cmd.debugTag {
690 log.WithFields(logrus.Fields{
693 }).Info("tv2homhet()")
695 onehotChunk = append(onehotChunk, onehot...)
696 onehotXref = append(onehotXref, xrefs...)
703 // Reference does not use any
704 // variant of this tile
706 // TODO: diff against the
707 // relevant portion of the
708 // ref's spanning tile
712 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
714 reftilestr := strings.ToUpper(string(rt.tiledata))
716 done := make([]bool, maxv+1)
717 variantDiffs := make([][]hgvs.Variant, maxv+1)
718 for v, tv := range variants {
720 if v == 0 || v == rt.variant || done[v] {
725 if len(tv.Sequence) < taglen {
728 // if reftilestr doesn't end
729 // in the same tag as tv,
730 // extend reftilestr with
731 // following ref tiles until
732 // it does (up to an arbitrary
733 // sanity-check limit)
734 reftilestr := reftilestr
735 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
736 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
737 rt = reftile[rt.nexttag]
741 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
743 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
746 if !strings.HasSuffix(reftilestr, endtagstr) {
747 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
750 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
751 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
754 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
755 for i := range diffs {
756 diffs[i].Position += rt.pos
758 for _, diff := range diffs {
759 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)
762 variantDiffs[v] = diffs
766 // We can now determine, for each HGVS
767 // variant (diff) in this reftile
768 // region, whether a given genome
769 // phase/allele (1) has the variant, (0) has
770 // =ref or a different variant in that
771 // position, or (-1) is lacking
772 // coverage / couldn't be diffed.
773 hgvsCol := hgvsColSet{}
774 for _, diffs := range variantDiffs {
775 for _, diff := range diffs {
776 if _, ok := hgvsCol[diff]; ok {
779 hgvsCol[diff] = [2][]int8{
780 make([]int8, len(cmd.cgnames)),
781 make([]int8, len(cmd.cgnames)),
785 for row, name := range cmd.cgnames {
786 variants := cgs[name].Variants[(tag-tagstart)*2:]
787 for ph := 0; ph < 2; ph++ {
789 if int(v) >= len(remap) {
795 // hgvsCol[*][ph][row] is already 0
796 } else if len(variantDiffs[v]) == 0 {
797 // lacking coverage / couldn't be diffed
798 for _, col := range hgvsCol {
802 for _, diff := range variantDiffs[v] {
803 hgvsCol[diff][ph][row] = 1
808 for diff, colpair := range hgvsCol {
809 allele2homhet(colpair)
810 if !cmd.filterHGVScolpair(colpair) {
811 delete(hgvsCol, diff)
814 if len(hgvsCol) > 0 {
815 encodeHGVSTodo[rt.seqname] <- hgvsCol
830 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
831 rows := len(cmd.cgnames)
832 cols := len(onehotChunk)
833 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
834 throttleNumpyMem.Acquire()
835 out := onehotcols2int8(onehotChunk)
836 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
837 err = writeNumpyInt8(fnm, out, rows, cols)
841 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
842 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
847 throttleNumpyMem.Release()
849 if *onehotSingle || *onlyPCA {
850 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
851 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
852 onehotXrefs[infileIdx] = onehotXref
853 n := len(onehotIndirect[infileIdx][0])
854 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
856 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
857 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
858 throttleNumpyMem.Acquire()
859 rows := len(cmd.cgnames)
861 out := make([]int16, rows*cols)
862 for row, name := range cmd.cgnames {
864 for col, v := range cgs[name].Variants {
865 tag := tagstart + tagID(col/2)
866 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
869 if rt := reftile[tag]; rt == nil || rt.excluded {
873 out[outidx] = 0 // tag not found / spanning tile
874 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
875 out[outidx] = int16(variantRemap[tag-tagstart][v])
877 out[outidx] = -1 // low quality tile variant
879 if tag == cmd.debugTag {
880 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
888 throttleNumpyMem.Release()
889 if *mergeOutput || *hgvsSingle {
890 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
891 toMerge[infileIdx] = out
893 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
894 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
895 err = writeNumpyInt16(fnm, out, rows, cols)
902 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
906 if err = throttleMem.Wait(); err != nil {
911 log.Info("flushing hgvsCols temp files")
912 for seqname := range refseq {
913 close(encodeHGVSTodo[seqname])
915 err = encodeHGVS.Wait()
919 for seqname := range refseq {
920 log.Infof("%s: reading hgvsCols from temp file", seqname)
921 f := tmpHGVSCols[seqname]
922 _, err = f.Seek(0, io.SeekStart)
926 var hgvsCols hgvsColSet
927 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
929 err = dec.Decode(&hgvsCols)
934 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
935 variants := make([]hgvs.Variant, 0, len(hgvsCols))
936 for v := range hgvsCols {
937 variants = append(variants, v)
939 sort.Slice(variants, func(i, j int) bool {
940 vi, vj := &variants[i], &variants[j]
941 if vi.Position != vj.Position {
942 return vi.Position < vj.Position
943 } else if vi.Ref != vj.Ref {
944 return vi.Ref < vj.Ref
946 return vi.New < vj.New
949 rows := len(cmd.cgnames)
950 cols := len(variants) * 2
951 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
952 out := make([]int8, rows*cols)
953 for varIdx, variant := range variants {
954 hgvsCols := hgvsCols[variant]
955 for row := range cmd.cgnames {
956 for ph := 0; ph < 2; ph++ {
957 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
961 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
967 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
968 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
969 var hgvsLabels bytes.Buffer
970 for varIdx, variant := range variants {
971 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
973 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
980 if *mergeOutput || *hgvsSingle {
981 var annow *bufio.Writer
984 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
985 annof, err = os.Create(annoFilename)
989 annow = bufio.NewWriterSize(annof, 1<<20)
992 rows := len(cmd.cgnames)
994 for _, chunk := range toMerge {
995 cols += len(chunk) / rows
997 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
1000 out = make([]int16, rows*cols)
1002 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1004 for outIdx, chunk := range toMerge {
1005 chunkcols := len(chunk) / rows
1007 for row := 0; row < rows; row++ {
1008 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1011 toMerge[outIdx] = nil
1013 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1014 log.Infof("reading %s", annotationsFilename)
1015 buf, err := os.ReadFile(annotationsFilename)
1020 err = os.Remove(annotationsFilename)
1025 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1029 fields := bytes.SplitN(line, []byte{','}, 9)
1030 tag, _ := strconv.Atoi(string(fields[0]))
1031 incol, _ := strconv.Atoi(string(fields[1]))
1032 tileVariant, _ := strconv.Atoi(string(fields[2]))
1033 hgvsID := string(fields[3])
1034 seqname := string(fields[4])
1035 pos, _ := strconv.Atoi(string(fields[5]))
1038 // Null entry for un-diffable
1043 // Null entry for ref tile
1046 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1047 // The tile intersects one of
1048 // the selected regions, but
1049 // this particular HGVS
1050 // variant does not.
1053 hgvsColPair := hgvsCols[hgvsID]
1054 if hgvsColPair[0] == nil {
1055 // values in new columns start
1056 // out as -1 ("no data yet")
1057 // or 0 ("=ref") here, may
1058 // change to 1 ("hgvs variant
1059 // present") below, either on
1060 // this line or a future line.
1061 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1062 rt, ok := reftile[tagID(tag)]
1064 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1067 for ph := 0; ph < 2; ph++ {
1068 for row := 0; row < rows; row++ {
1069 v := chunk[row*chunkcols+incol*2+ph]
1070 if tileVariantID(v) == rt.variant {
1071 hgvsColPair[ph][row] = 0
1073 hgvsColPair[ph][row] = -1
1077 hgvsCols[hgvsID] = hgvsColPair
1079 hgvsref := hgvs.Variant{
1081 Ref: string(refseq),
1082 New: string(refseq),
1084 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])
1088 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])
1090 for ph := 0; ph < 2; ph++ {
1091 for row := 0; row < rows; row++ {
1092 v := chunk[row*chunkcols+incol*2+ph]
1093 if int(v) == tileVariant {
1094 hgvsColPair[ph][row] = 1
1100 startcol += chunkcols
1111 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1119 cols = len(hgvsCols) * 2
1120 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1121 out = make([]int16, rows*cols)
1122 hgvsIDs := make([]string, 0, cols/2)
1123 for hgvsID := range hgvsCols {
1124 hgvsIDs = append(hgvsIDs, hgvsID)
1126 sort.Strings(hgvsIDs)
1127 var hgvsLabels bytes.Buffer
1128 for idx, hgvsID := range hgvsIDs {
1129 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1130 for ph := 0; ph < 2; ph++ {
1131 hgvscol := hgvsCols[hgvsID][ph]
1132 for row, val := range hgvscol {
1133 out[row*cols+idx*2+ph] = val
1137 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1142 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1143 log.Printf("writing hgvs labels: %s", fnm)
1144 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1150 if *onehotSingle || *onlyPCA {
1152 for _, part := range onehotIndirect {
1153 nzCount += len(part[0])
1155 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1156 var xrefs []onehotXref
1157 chunkOffset := uint32(0)
1159 for i, part := range onehotIndirect {
1160 for i := range part[1] {
1161 part[1][i] += chunkOffset
1163 copy(onehot[outcol:], part[0])
1164 copy(onehot[outcol+nzCount:], part[1])
1165 xrefs = append(xrefs, onehotXrefs[i]...)
1167 outcol += len(part[0])
1168 chunkOffset += onehotChunkSize[i]
1172 onehotXrefs[i] = nil
1173 debug.FreeOSMemory()
1176 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1177 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1181 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1182 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1189 for _, c := range onehot[nzCount:] {
1195 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1197 log.Printf("have %d one-hot cols", cols)
1199 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1200 cols = (cols + 1) / 2
1204 // we work with pairs of columns
1207 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1208 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1209 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1210 for i, c := range onehot[nzCount:] {
1211 if int(c/2)%stride == 0 {
1212 outcol := int(c/2)/stride*2 + int(c)%2
1213 mtxFull.Set(int(onehot[i]), outcol, 1)
1214 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1215 mtxTrain.Set(trainRow, outcol, 1)
1219 log.Print("fitting")
1220 transformer := nlp.NewPCA(cmd.pcaComponents)
1221 transformer.Fit(mtxTrain.T())
1222 log.Printf("transforming")
1223 pca, err := transformer.Transform(mtxFull.T())
1228 outrows, outcols := pca.Dims()
1229 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1230 out := make([]float64, outrows*outcols)
1231 for i := 0; i < outrows; i++ {
1232 for j := 0; j < outcols; j++ {
1233 out[i*outcols+j] = pca.At(i, j)
1236 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1237 log.Printf("writing numpy: %s", fnm)
1238 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1242 npw, err := gonpy.NewWriter(nopCloser{output})
1244 return fmt.Errorf("gonpy.NewWriter: %w", err)
1246 npw.Shape = []int{outrows, outcols}
1247 err = npw.WriteFloat64(out)
1249 return fmt.Errorf("WriteFloat64: %w", err)
1251 err = output.Close()
1257 samplesOutFilename := *outputDir + "/samples.csv"
1258 log.Infof("writing sample metadata to %s", samplesOutFilename)
1260 f, err = os.Create(samplesOutFilename)
1265 for i, si := range cmd.samples {
1269 } else if si.isControl {
1278 for c := 0; c < outcols; c++ {
1279 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1281 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1283 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1289 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1295 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1296 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1297 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1299 f, err = os.Create(tagoffsetFilename)
1304 for idx, offset := range chunkStartTag {
1305 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1307 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1313 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1321 type sampleInfo struct {
1327 pcaComponents []float64
1330 // Read samples.csv file with case/control and training/validation
1332 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1334 f, err := open(samplesFilename)
1338 buf, err := io.ReadAll(f)
1344 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1349 split := strings.Split(string(csv), ",")
1351 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1353 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1356 idx, err := strconv.Atoi(split[0])
1359 return nil, fmt.Errorf("header does not look right: %q", csv)
1361 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1364 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1366 var pcaComponents []float64
1368 for _, s := range split[4:] {
1369 f, err := strconv.ParseFloat(s, 64)
1371 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1373 pcaComponents = append(pcaComponents, f)
1376 si = append(si, sampleInfo{
1378 isCase: split[2] == "1",
1379 isControl: split[2] == "0",
1380 isTraining: split[3] == "1",
1381 isValidation: split[3] == "0",
1382 pcaComponents: pcaComponents,
1388 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1389 if cmd.chi2PValue >= 1 {
1392 col0 := make([]bool, 0, len(cmd.chi2Cases))
1393 col1 := make([]bool, 0, len(cmd.chi2Cases))
1394 cases := make([]bool, 0, len(cmd.chi2Cases))
1395 for i, c := range cmd.chi2Cases {
1396 if colpair[0][i] < 0 {
1399 col0 = append(col0, colpair[0][i] != 0)
1400 col1 = append(col1, colpair[1][i] != 0)
1401 cases = append(cases, c)
1403 return len(cases) >= cmd.minCoverage &&
1404 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1407 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1408 output, err := os.Create(fnm)
1412 defer output.Close()
1413 bufw := bufio.NewWriterSize(output, 1<<26)
1414 npw, err := gonpy.NewWriter(nopCloser{bufw})
1418 log.WithFields(log.Fields{
1422 "bytes": rows * cols * 4,
1423 }).Infof("writing numpy: %s", fnm)
1424 npw.Shape = []int{rows, cols}
1425 npw.WriteUint32(out)
1430 return output.Close()
1433 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1434 output, err := os.Create(fnm)
1438 defer output.Close()
1439 bufw := bufio.NewWriterSize(output, 1<<26)
1440 npw, err := gonpy.NewWriter(nopCloser{bufw})
1444 log.WithFields(log.Fields{
1448 "bytes": rows * cols * 4,
1449 }).Infof("writing numpy: %s", fnm)
1450 npw.Shape = []int{rows, cols}
1456 return output.Close()
1459 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1460 output, err := os.Create(fnm)
1464 defer output.Close()
1465 bufw := bufio.NewWriterSize(output, 1<<26)
1466 npw, err := gonpy.NewWriter(nopCloser{bufw})
1470 log.WithFields(log.Fields{
1474 "bytes": rows * cols * 2,
1475 }).Infof("writing numpy: %s", fnm)
1476 npw.Shape = []int{rows, cols}
1482 return output.Close()
1485 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1486 output, err := os.Create(fnm)
1490 defer output.Close()
1491 bufw := bufio.NewWriterSize(output, 1<<26)
1492 npw, err := gonpy.NewWriter(nopCloser{bufw})
1496 log.WithFields(log.Fields{
1500 "bytes": rows * cols,
1501 }).Infof("writing numpy: %s", fnm)
1502 npw.Shape = []int{rows, cols}
1508 return output.Close()
1511 func allele2homhet(colpair [2][]int8) {
1512 a, b := colpair[0], colpair[1]
1513 for i, av := range a {
1515 if av < 0 || bv < 0 {
1518 } else if av > 0 && bv > 0 {
1521 } else if av > 0 || bv > 0 {
1525 // ref (or a different variant in same position)
1526 // (this is a no-op) a[i], b[i] = 0, 0
1531 type onehotXref struct {
1533 variant tileVariantID
1538 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1540 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1541 // variants of a single tile/tag#.
1543 // Return nil if no tile variant passes Χ² filter.
1544 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1545 if tag == cmd.debugTag {
1546 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1547 for i, name := range cmd.cgnames {
1548 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1550 log.WithFields(logrus.Fields{
1551 "cgs[i].Variants[tag*2+j]": tv,
1555 "chunkstarttag": chunkstarttag,
1556 }).Info("tv2homhet()")
1558 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1559 // everyone has the most common variant (of the variants we don't drop)
1562 tagoffset := tag - chunkstarttag
1564 for _, cg := range cgs {
1566 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1567 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1575 if coverage < cmd.minCoverage {
1578 // "observed" array for p-value calculation (training set
1580 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1581 // one-hot output (all samples)
1582 outcols := make([][]int8, (maxv+1)*2)
1583 for i := range obs {
1584 obs[i] = make([]bool, cmd.trainingSetSize)
1585 outcols[i] = make([]int8, len(cmd.cgnames))
1587 for cgid, name := range cmd.cgnames {
1588 tsid := cmd.trainingSet[cgid]
1589 cgvars := cgs[name].Variants[tagoffset*2:]
1590 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1591 for v := tileVariantID(1); v <= maxv; v++ {
1592 if tv0 == v && tv1 == v {
1594 obs[v*2][tsid] = true
1596 outcols[v*2][cgid] = 1
1597 } else if tv0 == v || tv1 == v {
1599 obs[v*2+1][tsid] = true
1601 outcols[v*2+1][cgid] = 1
1606 var xref []onehotXref
1607 for col := 2; col < len(obs); col++ {
1608 // col 0,1 correspond to tile variant 0, i.e.,
1609 // no-call; col 2,3 correspond to the most common
1610 // variant; so we (normally) start at col 4.
1611 if col < 4 && !cmd.includeVariant1 {
1614 p := cmd.pvalue(obs[col])
1615 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1618 onehot = append(onehot, outcols[col])
1619 xref = append(xref, onehotXref{
1621 variant: tileVariantID(col >> 1),
1629 // convert a []onehotXref with length N to a numpy-style []int32
1630 // matrix with N columns, one row per field of onehotXref struct.
1632 // Hom/het row contains hom=0, het=1.
1634 // P-value row contains 1000000x actual p-value.
1635 func onehotXref2int32(xrefs []onehotXref) []int32 {
1637 xdata := make([]int32, 5*xcols)
1638 for i, xref := range xrefs {
1639 xdata[i] = int32(xref.tag)
1640 xdata[xcols+i] = int32(xref.variant)
1642 xdata[xcols*2+i] = 1
1644 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1645 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1650 // transpose onehot data from in[col][row] to numpy-style
1651 // out[row*cols+col].
1652 func onehotcols2int8(in [][]int8) []int8 {
1658 out := make([]int8, rows*cols)
1659 for row := 0; row < rows; row++ {
1660 outrow := out[row*cols:]
1661 for col, incol := range in {
1662 outrow[col] = incol[row]
1668 // Return [2][]uint32{rowIndices, colIndices} indicating which
1669 // elements of matrixT[c][r] have non-zero values.
1670 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1672 for c, col := range matrixT {
1673 for r, val := range col {
1675 nz[0] = append(nz[0], uint32(r))
1676 nz[1] = append(nz[1], uint32(c))