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 cmd.pvalue = func(onehot []bool) float64 {
288 return pvalue(onehot, cmd.chi2Cases)
291 if cmd.filter.MinCoverage == 1 {
292 // In the generic formula below, floating point
293 // arithmetic can effectively push the coverage
294 // threshold above 1.0, which is impossible/useless.
295 // 1.0 needs to mean exactly 100% coverage.
296 cmd.minCoverage = len(cmd.cgnames)
298 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
302 samplesOutFilename := *outputDir + "/samples.csv"
303 log.Infof("writing sample metadata to %s", samplesOutFilename)
305 f, err = os.Create(samplesOutFilename)
310 for i, si := range cmd.samples {
314 } else if si.isControl {
322 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
324 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
330 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
336 log.Info("indexing reference tiles")
337 type reftileinfo struct {
338 variant tileVariantID
339 seqname string // chr1
340 pos int // distance from start of chromosome to starttag
341 tiledata []byte // acgtggcaa...
342 excluded bool // true if excluded by regions file
343 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
345 isdup := map[tagID]bool{}
346 reftile := map[tagID]*reftileinfo{}
347 for seqname, cseq := range refseq {
349 lastreftag := tagID(-1)
350 for _, libref := range cseq {
351 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
354 tiledata := reftiledata[libref]
355 if len(tiledata) == 0 {
356 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
359 foundthistag := false
360 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
361 if !foundthistag && tagid == libref.Tag {
365 if dupref, ok := reftile[tagid]; ok {
366 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)
367 delete(reftile, tagid)
369 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
373 if isdup[libref.Tag] {
374 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
375 } else if reftile[libref.Tag] != nil {
376 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)
377 delete(reftile, libref.Tag)
378 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
379 isdup[libref.Tag] = true
381 reftile[libref.Tag] = &reftileinfo{
383 variant: libref.Variant,
389 reftile[lastreftag].nexttag = libref.Tag
391 lastreftag = libref.Tag
393 pos += len(tiledata) - taglen
395 log.Printf("... %s done, len %d", seqname, pos+taglen)
399 if *regionsFilename != "" {
400 log.Printf("loading regions from %s", *regionsFilename)
401 mask, err = makeMask(*regionsFilename, *expandRegions)
405 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
406 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
407 for _, rt := range reftile {
408 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
412 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
415 type hgvsColSet map[hgvs.Variant][2][]int8
416 encodeHGVS := throttle{Max: len(refseq)}
417 encodeHGVSTodo := map[string]chan hgvsColSet{}
418 tmpHGVSCols := map[string]*os.File{}
420 for seqname := range refseq {
422 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
426 defer os.Remove(f.Name())
427 bufw := bufio.NewWriterSize(f, 1<<24)
428 enc := gob.NewEncoder(bufw)
429 tmpHGVSCols[seqname] = f
430 todo := make(chan hgvsColSet, 128)
431 encodeHGVSTodo[seqname] = todo
432 encodeHGVS.Go(func() error {
433 for colset := range todo {
434 err := enc.Encode(colset)
436 encodeHGVS.Report(err)
447 var toMerge [][]int16
448 if *mergeOutput || *hgvsSingle {
449 toMerge = make([][]int16, len(infiles))
451 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
452 var onehotChunkSize []uint32
453 var onehotXrefs [][]onehotXref
454 if *onehotSingle || *onlyPCA {
455 onehotIndirect = make([][2][]uint32, len(infiles))
456 onehotChunkSize = make([]uint32, len(infiles))
457 onehotXrefs = make([][]onehotXref, len(infiles))
459 chunkStartTag := make([]tagID, len(infiles))
461 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
462 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
463 log.Info("generating annotations and numpy matrix for each slice")
464 var errSkip = errors.New("skip infile")
466 for infileIdx, infile := range infiles {
467 infileIdx, infile := infileIdx, infile
468 throttleMem.Go(func() error {
469 seq := make(map[tagID][]TileVariant, 50000)
470 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
471 f, err := open(infile)
476 log.Infof("%04d: reading %s", infileIdx, infile)
477 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
478 for _, tv := range ent.TileVariants {
483 // corresponding ref tile, if
484 // mask is in play (we can't
485 // determine coordinates for
487 if mask != nil && reftile[tv.Tag] == nil {
491 // corresponding ref tile is
492 // outside target regions --
493 // unless it's a potential
495 if mask != nil && reftile[tv.Tag].excluded &&
496 (int(tv.Tag+1) >= len(tagset) ||
497 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
500 if tv.Tag == cmd.debugTag {
501 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
503 variants := seq[tv.Tag]
504 if len(variants) == 0 {
505 variants = make([]TileVariant, 100)
507 for len(variants) <= int(tv.Variant) {
508 variants = append(variants, TileVariant{})
510 variants[int(tv.Variant)] = tv
511 seq[tv.Tag] = variants
513 for _, cg := range ent.CompactGenomes {
514 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
517 if !matchGenome.MatchString(cg.Name) {
520 // pad to full slice size
521 // to avoid out-of-bounds
523 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
524 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
532 } else if err != nil {
533 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
535 tagstart := cgs[cmd.cgnames[0]].StartTag
536 tagend := cgs[cmd.cgnames[0]].EndTag
537 chunkStartTag[infileIdx] = tagstart
541 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
542 variantRemap := make([][]tileVariantID, tagend-tagstart)
543 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
544 for tag, variants := range seq {
545 tag, variants := tag, variants
546 throttleCPU.Go(func() error {
548 count := make(map[[blake2b.Size256]byte]int, len(variants))
552 count[blake2b.Sum256(rt.tiledata)] = 0
555 for cgname, cg := range cgs {
556 idx := int(tag-tagstart) * 2
557 for allele := 0; allele < 2; allele++ {
558 v := cg.Variants[idx+allele]
559 if v > 0 && len(variants[v].Sequence) > 0 {
560 count[variants[v].Blake2b]++
563 if v > 0 && tag == cmd.debugTag {
564 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])
568 if alleleCoverage < cmd.minCoverage*2 {
569 idx := int(tag-tagstart) * 2
570 for _, cg := range cgs {
572 cg.Variants[idx+1] = 0
574 if tag == cmd.debugTag {
575 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
580 // hash[i] will be the hash of
581 // the variant(s) that should
582 // be at rank i (0-based).
583 hash := make([][blake2b.Size256]byte, 0, len(count))
584 for b := range count {
585 hash = append(hash, b)
587 sort.Slice(hash, func(i, j int) bool {
588 bi, bj := &hash[i], &hash[j]
589 if ci, cj := count[*bi], count[*bj]; ci != cj {
592 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
595 // rank[b] will be the 1-based
596 // new variant number for
597 // variants whose hash is b.
598 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
599 for i, h := range hash {
600 rank[h] = tileVariantID(i + 1)
602 if tag == cmd.debugTag {
603 for h, r := range rank {
604 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
607 // remap[v] will be the new
608 // variant number for original
610 remap := make([]tileVariantID, len(variants))
611 for i, tv := range variants {
612 remap[i] = rank[tv.Blake2b]
614 if tag == cmd.debugTag {
615 for in, out := range remap {
617 log.Printf("tag %d remap %d => %d", tag, in, out)
621 variantRemap[tag-tagstart] = remap
623 refrank := rank[blake2b.Sum256(rt.tiledata)]
624 if tag == cmd.debugTag {
625 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
634 var onehotChunk [][]int8
635 var onehotXref []onehotXref
637 var annotationsFilename string
639 annotationsFilename = "/dev/null"
641 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
642 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
644 annof, err := os.Create(annotationsFilename)
648 annow := bufio.NewWriterSize(annof, 1<<20)
650 for tag := tagstart; tag < tagend; tag++ {
652 if rt == nil && mask != nil {
653 // With no ref tile, we don't
654 // have coordinates to say
655 // this is in the desired
656 // regions -- so it's not.
657 // TODO: handle ref spanning
661 if rt != nil && rt.excluded {
662 // TODO: don't skip yet --
663 // first check for spanning
664 // tile variants that
665 // intersect non-excluded ref
669 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
672 remap := variantRemap[tag-tagstart]
674 // was not assigned above,
675 // because minCoverage
679 maxv := tileVariantID(0)
680 for _, v := range remap {
685 if *onehotChunked || *onehotSingle || *onlyPCA {
686 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
687 if tag == cmd.debugTag {
688 log.WithFields(logrus.Fields{
691 }).Info("tv2homhet()")
693 onehotChunk = append(onehotChunk, onehot...)
694 onehotXref = append(onehotXref, xrefs...)
701 // Reference does not use any
702 // variant of this tile
704 // TODO: diff against the
705 // relevant portion of the
706 // ref's spanning tile
710 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
712 reftilestr := strings.ToUpper(string(rt.tiledata))
714 done := make([]bool, maxv+1)
715 variantDiffs := make([][]hgvs.Variant, maxv+1)
716 for v, tv := range variants {
718 if v == 0 || v == rt.variant || done[v] {
723 if len(tv.Sequence) < taglen {
726 // if reftilestr doesn't end
727 // in the same tag as tv,
728 // extend reftilestr with
729 // following ref tiles until
730 // it does (up to an arbitrary
731 // sanity-check limit)
732 reftilestr := reftilestr
733 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
734 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
735 rt = reftile[rt.nexttag]
739 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
741 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
744 if !strings.HasSuffix(reftilestr, endtagstr) {
745 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
748 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
749 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
752 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
753 for i := range diffs {
754 diffs[i].Position += rt.pos
756 for _, diff := range diffs {
757 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)
760 variantDiffs[v] = diffs
764 // We can now determine, for each HGVS
765 // variant (diff) in this reftile
766 // region, whether a given genome
767 // phase/allele (1) has the variant, (0) has
768 // =ref or a different variant in that
769 // position, or (-1) is lacking
770 // coverage / couldn't be diffed.
771 hgvsCol := hgvsColSet{}
772 for _, diffs := range variantDiffs {
773 for _, diff := range diffs {
774 if _, ok := hgvsCol[diff]; ok {
777 hgvsCol[diff] = [2][]int8{
778 make([]int8, len(cmd.cgnames)),
779 make([]int8, len(cmd.cgnames)),
783 for row, name := range cmd.cgnames {
784 variants := cgs[name].Variants[(tag-tagstart)*2:]
785 for ph := 0; ph < 2; ph++ {
787 if int(v) >= len(remap) {
793 // hgvsCol[*][ph][row] is already 0
794 } else if len(variantDiffs[v]) == 0 {
795 // lacking coverage / couldn't be diffed
796 for _, col := range hgvsCol {
800 for _, diff := range variantDiffs[v] {
801 hgvsCol[diff][ph][row] = 1
806 for diff, colpair := range hgvsCol {
807 allele2homhet(colpair)
808 if !cmd.filterHGVScolpair(colpair) {
809 delete(hgvsCol, diff)
812 if len(hgvsCol) > 0 {
813 encodeHGVSTodo[rt.seqname] <- hgvsCol
828 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
829 rows := len(cmd.cgnames)
830 cols := len(onehotChunk)
831 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
832 throttleNumpyMem.Acquire()
833 out := onehotcols2int8(onehotChunk)
834 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
835 err = writeNumpyInt8(fnm, out, rows, cols)
839 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
840 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
845 throttleNumpyMem.Release()
847 if *onehotSingle || *onlyPCA {
848 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
849 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
850 onehotXrefs[infileIdx] = onehotXref
851 n := len(onehotIndirect[infileIdx][0])
852 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
854 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
855 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
856 throttleNumpyMem.Acquire()
857 rows := len(cmd.cgnames)
859 out := make([]int16, rows*cols)
860 for row, name := range cmd.cgnames {
862 for col, v := range cgs[name].Variants {
863 tag := tagstart + tagID(col/2)
864 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
867 if rt := reftile[tag]; rt == nil || rt.excluded {
871 out[outidx] = 0 // tag not found / spanning tile
872 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
873 out[outidx] = int16(variantRemap[tag-tagstart][v])
875 out[outidx] = -1 // low quality tile variant
877 if tag == cmd.debugTag {
878 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
886 throttleNumpyMem.Release()
887 if *mergeOutput || *hgvsSingle {
888 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
889 toMerge[infileIdx] = out
891 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
892 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
893 err = writeNumpyInt16(fnm, out, rows, cols)
900 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
904 if err = throttleMem.Wait(); err != nil {
909 log.Info("flushing hgvsCols temp files")
910 for seqname := range refseq {
911 close(encodeHGVSTodo[seqname])
913 err = encodeHGVS.Wait()
917 for seqname := range refseq {
918 log.Infof("%s: reading hgvsCols from temp file", seqname)
919 f := tmpHGVSCols[seqname]
920 _, err = f.Seek(0, io.SeekStart)
924 var hgvsCols hgvsColSet
925 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
927 err = dec.Decode(&hgvsCols)
932 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
933 variants := make([]hgvs.Variant, 0, len(hgvsCols))
934 for v := range hgvsCols {
935 variants = append(variants, v)
937 sort.Slice(variants, func(i, j int) bool {
938 vi, vj := &variants[i], &variants[j]
939 if vi.Position != vj.Position {
940 return vi.Position < vj.Position
941 } else if vi.Ref != vj.Ref {
942 return vi.Ref < vj.Ref
944 return vi.New < vj.New
947 rows := len(cmd.cgnames)
948 cols := len(variants) * 2
949 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
950 out := make([]int8, rows*cols)
951 for varIdx, variant := range variants {
952 hgvsCols := hgvsCols[variant]
953 for row := range cmd.cgnames {
954 for ph := 0; ph < 2; ph++ {
955 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
959 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
965 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
966 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
967 var hgvsLabels bytes.Buffer
968 for varIdx, variant := range variants {
969 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
971 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
978 if *mergeOutput || *hgvsSingle {
979 var annow *bufio.Writer
982 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
983 annof, err = os.Create(annoFilename)
987 annow = bufio.NewWriterSize(annof, 1<<20)
990 rows := len(cmd.cgnames)
992 for _, chunk := range toMerge {
993 cols += len(chunk) / rows
995 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
998 out = make([]int16, rows*cols)
1000 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1002 for outIdx, chunk := range toMerge {
1003 chunkcols := len(chunk) / rows
1005 for row := 0; row < rows; row++ {
1006 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1009 toMerge[outIdx] = nil
1011 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1012 log.Infof("reading %s", annotationsFilename)
1013 buf, err := os.ReadFile(annotationsFilename)
1018 err = os.Remove(annotationsFilename)
1023 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1027 fields := bytes.SplitN(line, []byte{','}, 9)
1028 tag, _ := strconv.Atoi(string(fields[0]))
1029 incol, _ := strconv.Atoi(string(fields[1]))
1030 tileVariant, _ := strconv.Atoi(string(fields[2]))
1031 hgvsID := string(fields[3])
1032 seqname := string(fields[4])
1033 pos, _ := strconv.Atoi(string(fields[5]))
1036 // Null entry for un-diffable
1041 // Null entry for ref tile
1044 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1045 // The tile intersects one of
1046 // the selected regions, but
1047 // this particular HGVS
1048 // variant does not.
1051 hgvsColPair := hgvsCols[hgvsID]
1052 if hgvsColPair[0] == nil {
1053 // values in new columns start
1054 // out as -1 ("no data yet")
1055 // or 0 ("=ref") here, may
1056 // change to 1 ("hgvs variant
1057 // present") below, either on
1058 // this line or a future line.
1059 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1060 rt, ok := reftile[tagID(tag)]
1062 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1065 for ph := 0; ph < 2; ph++ {
1066 for row := 0; row < rows; row++ {
1067 v := chunk[row*chunkcols+incol*2+ph]
1068 if tileVariantID(v) == rt.variant {
1069 hgvsColPair[ph][row] = 0
1071 hgvsColPair[ph][row] = -1
1075 hgvsCols[hgvsID] = hgvsColPair
1077 hgvsref := hgvs.Variant{
1079 Ref: string(refseq),
1080 New: string(refseq),
1082 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])
1086 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])
1088 for ph := 0; ph < 2; ph++ {
1089 for row := 0; row < rows; row++ {
1090 v := chunk[row*chunkcols+incol*2+ph]
1091 if int(v) == tileVariant {
1092 hgvsColPair[ph][row] = 1
1098 startcol += chunkcols
1109 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1117 cols = len(hgvsCols) * 2
1118 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1119 out = make([]int16, rows*cols)
1120 hgvsIDs := make([]string, 0, cols/2)
1121 for hgvsID := range hgvsCols {
1122 hgvsIDs = append(hgvsIDs, hgvsID)
1124 sort.Strings(hgvsIDs)
1125 var hgvsLabels bytes.Buffer
1126 for idx, hgvsID := range hgvsIDs {
1127 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1128 for ph := 0; ph < 2; ph++ {
1129 hgvscol := hgvsCols[hgvsID][ph]
1130 for row, val := range hgvscol {
1131 out[row*cols+idx*2+ph] = val
1135 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1140 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1141 log.Printf("writing hgvs labels: %s", fnm)
1142 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1148 if *onehotSingle || *onlyPCA {
1150 for _, part := range onehotIndirect {
1151 nzCount += len(part[0])
1153 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1154 var xrefs []onehotXref
1155 chunkOffset := uint32(0)
1157 for i, part := range onehotIndirect {
1158 for i := range part[1] {
1159 part[1][i] += chunkOffset
1161 copy(onehot[outcol:], part[0])
1162 copy(onehot[outcol+nzCount:], part[1])
1163 xrefs = append(xrefs, onehotXrefs[i]...)
1165 outcol += len(part[0])
1166 chunkOffset += onehotChunkSize[i]
1170 onehotXrefs[i] = nil
1171 debug.FreeOSMemory()
1174 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1175 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1179 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1180 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1187 for _, c := range onehot[nzCount:] {
1193 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1195 log.Printf("have %d one-hot cols", cols)
1197 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1198 cols = (cols + 1) / 2
1202 // we work with pairs of columns
1205 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1206 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1207 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1208 for i, c := range onehot[nzCount:] {
1209 if int(c/2)%stride == 0 {
1210 outcol := int(c/2)/stride*2 + int(c)%2
1211 mtxFull.Set(int(onehot[i]), outcol, 1)
1212 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1213 mtxTrain.Set(trainRow, outcol, 1)
1217 log.Print("fitting")
1218 transformer := nlp.NewPCA(cmd.pcaComponents)
1219 transformer.Fit(mtxTrain.T())
1220 log.Printf("transforming")
1221 pca, err := transformer.Transform(mtxFull.T())
1226 outrows, outcols := pca.Dims()
1227 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1228 out := make([]float64, outrows*outcols)
1229 for i := 0; i < outrows; i++ {
1230 for j := 0; j < outcols; j++ {
1231 out[i*outcols+j] = pca.At(i, j)
1234 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1235 log.Printf("writing numpy: %s", fnm)
1236 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1240 npw, err := gonpy.NewWriter(nopCloser{output})
1242 return fmt.Errorf("gonpy.NewWriter: %w", err)
1244 npw.Shape = []int{outrows, outcols}
1245 err = npw.WriteFloat64(out)
1247 return fmt.Errorf("WriteFloat64: %w", err)
1249 err = output.Close()
1255 samplesOutFilename := *outputDir + "/samples.csv"
1256 log.Infof("writing sample metadata to %s", samplesOutFilename)
1258 f, err = os.Create(samplesOutFilename)
1263 for i, si := range cmd.samples {
1267 } else if si.isControl {
1276 for c := 0; c < outcols; c++ {
1277 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1279 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1281 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1287 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1293 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1294 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1295 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1297 f, err = os.Create(tagoffsetFilename)
1302 for idx, offset := range chunkStartTag {
1303 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1305 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1311 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1319 type sampleInfo struct {
1325 pcaComponents []float64
1328 // Read samples.csv file with case/control and training/validation
1330 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1332 f, err := open(samplesFilename)
1336 buf, err := io.ReadAll(f)
1342 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1347 split := strings.Split(string(csv), ",")
1349 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1351 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1354 idx, err := strconv.Atoi(split[0])
1357 return nil, fmt.Errorf("header does not look right: %q", csv)
1359 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1362 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1364 var pcaComponents []float64
1366 for _, s := range split[4:] {
1367 f, err := strconv.ParseFloat(s, 64)
1369 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1371 pcaComponents = append(pcaComponents, f)
1374 si = append(si, sampleInfo{
1376 isCase: split[2] == "1",
1377 isControl: split[2] == "0",
1378 isTraining: split[3] == "1",
1379 isValidation: split[3] == "0",
1380 pcaComponents: pcaComponents,
1386 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1387 if cmd.chi2PValue >= 1 {
1390 col0 := make([]bool, 0, len(cmd.chi2Cases))
1391 col1 := make([]bool, 0, len(cmd.chi2Cases))
1392 cases := make([]bool, 0, len(cmd.chi2Cases))
1393 for i, c := range cmd.chi2Cases {
1394 if colpair[0][i] < 0 {
1397 col0 = append(col0, colpair[0][i] != 0)
1398 col1 = append(col1, colpair[1][i] != 0)
1399 cases = append(cases, c)
1401 return len(cases) >= cmd.minCoverage &&
1402 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1405 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1406 output, err := os.Create(fnm)
1410 defer output.Close()
1411 bufw := bufio.NewWriterSize(output, 1<<26)
1412 npw, err := gonpy.NewWriter(nopCloser{bufw})
1416 log.WithFields(log.Fields{
1420 "bytes": rows * cols * 4,
1421 }).Infof("writing numpy: %s", fnm)
1422 npw.Shape = []int{rows, cols}
1423 npw.WriteUint32(out)
1428 return output.Close()
1431 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1432 output, err := os.Create(fnm)
1436 defer output.Close()
1437 bufw := bufio.NewWriterSize(output, 1<<26)
1438 npw, err := gonpy.NewWriter(nopCloser{bufw})
1442 log.WithFields(log.Fields{
1446 "bytes": rows * cols * 4,
1447 }).Infof("writing numpy: %s", fnm)
1448 npw.Shape = []int{rows, cols}
1454 return output.Close()
1457 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1458 output, err := os.Create(fnm)
1462 defer output.Close()
1463 bufw := bufio.NewWriterSize(output, 1<<26)
1464 npw, err := gonpy.NewWriter(nopCloser{bufw})
1468 log.WithFields(log.Fields{
1472 "bytes": rows * cols * 2,
1473 }).Infof("writing numpy: %s", fnm)
1474 npw.Shape = []int{rows, cols}
1480 return output.Close()
1483 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1484 output, err := os.Create(fnm)
1488 defer output.Close()
1489 bufw := bufio.NewWriterSize(output, 1<<26)
1490 npw, err := gonpy.NewWriter(nopCloser{bufw})
1494 log.WithFields(log.Fields{
1498 "bytes": rows * cols,
1499 }).Infof("writing numpy: %s", fnm)
1500 npw.Shape = []int{rows, cols}
1506 return output.Close()
1509 func allele2homhet(colpair [2][]int8) {
1510 a, b := colpair[0], colpair[1]
1511 for i, av := range a {
1513 if av < 0 || bv < 0 {
1516 } else if av > 0 && bv > 0 {
1519 } else if av > 0 || bv > 0 {
1523 // ref (or a different variant in same position)
1524 // (this is a no-op) a[i], b[i] = 0, 0
1529 type onehotXref struct {
1531 variant tileVariantID
1536 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1538 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1539 // variants of a single tile/tag#.
1541 // Return nil if no tile variant passes Χ² filter.
1542 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1543 if tag == cmd.debugTag {
1544 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1545 for i, name := range cmd.cgnames {
1546 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1548 log.WithFields(logrus.Fields{
1549 "cgs[i].Variants[tag*2+j]": tv,
1553 "chunkstarttag": chunkstarttag,
1554 }).Info("tv2homhet()")
1556 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1557 // everyone has the most common variant (of the variants we don't drop)
1560 tagoffset := tag - chunkstarttag
1562 for _, cg := range cgs {
1564 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1565 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1573 if coverage < cmd.minCoverage {
1576 // "observed" array for p-value calculation (training set
1578 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1579 // one-hot output (all samples)
1580 outcols := make([][]int8, (maxv+1)*2)
1581 for i := range obs {
1582 obs[i] = make([]bool, cmd.trainingSetSize)
1583 outcols[i] = make([]int8, len(cmd.cgnames))
1585 for cgid, name := range cmd.cgnames {
1586 tsid := cmd.trainingSet[cgid]
1587 cgvars := cgs[name].Variants[tagoffset*2:]
1588 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1589 for v := tileVariantID(1); v <= maxv; v++ {
1590 if tv0 == v && tv1 == v {
1592 obs[v*2][tsid] = true
1594 outcols[v*2][cgid] = 1
1595 } else if tv0 == v || tv1 == v {
1597 obs[v*2+1][tsid] = true
1599 outcols[v*2+1][cgid] = 1
1604 var xref []onehotXref
1605 for col := 2; col < len(obs); col++ {
1606 // col 0,1 correspond to tile variant 0, i.e.,
1607 // no-call; col 2,3 correspond to the most common
1608 // variant; so we (normally) start at col 4.
1609 if col < 4 && !cmd.includeVariant1 {
1612 p := cmd.pvalue(obs[col])
1613 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1616 onehot = append(onehot, outcols[col])
1617 xref = append(xref, onehotXref{
1619 variant: tileVariantID(col >> 1),
1627 // convert a []onehotXref with length N to a numpy-style []int32
1628 // matrix with N columns, one row per field of onehotXref struct.
1630 // Hom/het row contains hom=0, het=1.
1632 // P-value row contains 1000000x actual p-value.
1633 func onehotXref2int32(xrefs []onehotXref) []int32 {
1635 xdata := make([]int32, 5*xcols)
1636 for i, xref := range xrefs {
1637 xdata[i] = int32(xref.tag)
1638 xdata[xcols+i] = int32(xref.variant)
1640 xdata[xcols*2+i] = 1
1642 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1643 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1648 // transpose onehot data from in[col][row] to numpy-style
1649 // out[row*cols+col].
1650 func onehotcols2int8(in [][]int8) []int8 {
1656 out := make([]int8, rows*cols)
1657 for row := 0; row < rows; row++ {
1658 outrow := out[row*cols:]
1659 for col, incol := range in {
1660 outrow[col] = incol[row]
1666 // Return [2][]uint32{rowIndices, colIndices} indicating which
1667 // elements of matrixT[c][r] have non-zero values.
1668 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1670 for c, col := range matrixT {
1671 for r, val := range col {
1673 nz[0] = append(nz[0], uint32(r))
1674 nz[1] = append(nz[1], uint32(c))