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)
193 // Unfortunately, statsmodel/glm lib logs
194 // stuff to os.Stdout when it panics on an
195 // unsolvable problem. We recover() from the
196 // panic in glm.go, but we also need to
197 // commandeer os.Stdout to avoid producing
198 // large quantities of logs.
199 stdoutWas := os.Stdout
200 defer func() { os.Stdout = stdoutWas }()
201 os.Stdout, err = os.Open(os.DevNull)
206 } else if *caseControlOnly {
207 return fmt.Errorf("-case-control-only does not make sense without -samples")
212 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
213 if len(ent.TagSet) > 0 {
216 for _, cseq := range ent.CompactSequences {
217 if cseq.Name == *ref || *ref == "" {
218 refseq = cseq.TileSequences
221 for _, cg := range ent.CompactGenomes {
222 if matchGenome.MatchString(cg.Name) {
223 cmd.cgnames = append(cmd.cgnames, cg.Name)
226 for _, tv := range ent.TileVariants {
228 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
238 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
241 if len(tagset) == 0 {
242 err = fmt.Errorf("tagset not found")
246 taglib := &tagLibrary{}
247 err = taglib.setTags(tagset)
251 taglen := taglib.TagLen()
252 sort.Strings(cmd.cgnames)
254 if len(cmd.cgnames) == 0 {
255 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
257 cmd.trainingSet = make([]int, len(cmd.cgnames))
258 if *samplesFilename == "" {
259 cmd.trainingSetSize = len(cmd.cgnames)
260 for i, name := range cmd.cgnames {
261 cmd.samples = append(cmd.samples, sampleInfo{
262 id: trimFilenameForLabel(name),
265 cmd.trainingSet[i] = i
267 } else if len(cmd.cgnames) != len(cmd.samples) {
268 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
270 for i, name := range cmd.cgnames {
271 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
272 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
275 if *caseControlOnly {
276 for i := 0; i < len(cmd.samples); i++ {
277 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
278 if i+1 < len(cmd.samples) {
279 copy(cmd.samples[i:], cmd.samples[i+1:])
280 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
282 cmd.samples = cmd.samples[:len(cmd.samples)-1]
283 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
289 cmd.trainingSetSize = 0
290 for i := range cmd.cgnames {
291 if cmd.samples[i].isTraining {
292 cmd.trainingSet[i] = cmd.trainingSetSize
293 cmd.trainingSetSize++
294 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
296 cmd.trainingSet[i] = -1
299 if cmd.pvalue == nil {
300 cmd.pvalue = func(onehot []bool) float64 {
301 return pvalue(onehot, cmd.chi2Cases)
305 if cmd.filter.MinCoverage == 1 {
306 // In the generic formula below, floating point
307 // arithmetic can effectively push the coverage
308 // threshold above 1.0, which is impossible/useless.
309 // 1.0 needs to mean exactly 100% coverage.
310 cmd.minCoverage = len(cmd.cgnames)
312 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
316 samplesOutFilename := *outputDir + "/samples.csv"
317 log.Infof("writing sample metadata to %s", samplesOutFilename)
319 f, err = os.Create(samplesOutFilename)
324 for i, si := range cmd.samples {
328 } else if si.isControl {
336 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
338 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
344 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
350 log.Info("indexing reference tiles")
351 type reftileinfo struct {
352 variant tileVariantID
353 seqname string // chr1
354 pos int // distance from start of chromosome to starttag
355 tiledata []byte // acgtggcaa...
356 excluded bool // true if excluded by regions file
357 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
359 isdup := map[tagID]bool{}
360 reftile := map[tagID]*reftileinfo{}
361 for seqname, cseq := range refseq {
363 lastreftag := tagID(-1)
364 for _, libref := range cseq {
365 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
368 tiledata := reftiledata[libref]
369 if len(tiledata) == 0 {
370 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
373 foundthistag := false
374 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
375 if !foundthistag && tagid == libref.Tag {
379 if dupref, ok := reftile[tagid]; ok {
380 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)
381 delete(reftile, tagid)
383 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
387 if isdup[libref.Tag] {
388 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
389 } else if reftile[libref.Tag] != nil {
390 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)
391 delete(reftile, libref.Tag)
392 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
393 isdup[libref.Tag] = true
395 reftile[libref.Tag] = &reftileinfo{
397 variant: libref.Variant,
403 reftile[lastreftag].nexttag = libref.Tag
405 lastreftag = libref.Tag
407 pos += len(tiledata) - taglen
409 log.Printf("... %s done, len %d", seqname, pos+taglen)
413 if *regionsFilename != "" {
414 log.Printf("loading regions from %s", *regionsFilename)
415 mask, err = makeMask(*regionsFilename, *expandRegions)
419 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
420 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
421 for _, rt := range reftile {
422 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
426 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
429 type hgvsColSet map[hgvs.Variant][2][]int8
430 encodeHGVS := throttle{Max: len(refseq)}
431 encodeHGVSTodo := map[string]chan hgvsColSet{}
432 tmpHGVSCols := map[string]*os.File{}
434 for seqname := range refseq {
436 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
440 defer os.Remove(f.Name())
441 bufw := bufio.NewWriterSize(f, 1<<24)
442 enc := gob.NewEncoder(bufw)
443 tmpHGVSCols[seqname] = f
444 todo := make(chan hgvsColSet, 128)
445 encodeHGVSTodo[seqname] = todo
446 encodeHGVS.Go(func() error {
447 for colset := range todo {
448 err := enc.Encode(colset)
450 encodeHGVS.Report(err)
461 var toMerge [][]int16
462 if *mergeOutput || *hgvsSingle {
463 toMerge = make([][]int16, len(infiles))
465 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
466 var onehotChunkSize []uint32
467 var onehotXrefs [][]onehotXref
468 if *onehotSingle || *onlyPCA {
469 onehotIndirect = make([][2][]uint32, len(infiles))
470 onehotChunkSize = make([]uint32, len(infiles))
471 onehotXrefs = make([][]onehotXref, len(infiles))
473 chunkStartTag := make([]tagID, len(infiles))
475 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
476 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
477 log.Info("generating annotations and numpy matrix for each slice")
478 var errSkip = errors.New("skip infile")
480 for infileIdx, infile := range infiles {
481 infileIdx, infile := infileIdx, infile
482 throttleMem.Go(func() error {
483 seq := make(map[tagID][]TileVariant, 50000)
484 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
485 f, err := open(infile)
490 log.Infof("%04d: reading %s", infileIdx, infile)
491 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
492 for _, tv := range ent.TileVariants {
497 // corresponding ref tile, if
498 // mask is in play (we can't
499 // determine coordinates for
501 if mask != nil && reftile[tv.Tag] == nil {
505 // corresponding ref tile is
506 // outside target regions --
507 // unless it's a potential
509 if mask != nil && reftile[tv.Tag].excluded &&
510 (int(tv.Tag+1) >= len(tagset) ||
511 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
514 if tv.Tag == cmd.debugTag {
515 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
517 variants := seq[tv.Tag]
518 if len(variants) == 0 {
519 variants = make([]TileVariant, 100)
521 for len(variants) <= int(tv.Variant) {
522 variants = append(variants, TileVariant{})
524 variants[int(tv.Variant)] = tv
525 seq[tv.Tag] = variants
527 for _, cg := range ent.CompactGenomes {
528 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
531 if !matchGenome.MatchString(cg.Name) {
534 // pad to full slice size
535 // to avoid out-of-bounds
537 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
538 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
546 } else if err != nil {
547 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
549 tagstart := cgs[cmd.cgnames[0]].StartTag
550 tagend := cgs[cmd.cgnames[0]].EndTag
551 chunkStartTag[infileIdx] = tagstart
555 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
556 variantRemap := make([][]tileVariantID, tagend-tagstart)
557 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
558 for tag, variants := range seq {
559 tag, variants := tag, variants
560 throttleCPU.Go(func() error {
562 count := make(map[[blake2b.Size256]byte]int, len(variants))
566 count[blake2b.Sum256(rt.tiledata)] = 0
569 for cgname, cg := range cgs {
570 idx := int(tag-tagstart) * 2
571 for allele := 0; allele < 2; allele++ {
572 v := cg.Variants[idx+allele]
573 if v > 0 && len(variants[v].Sequence) > 0 {
574 count[variants[v].Blake2b]++
577 if v > 0 && tag == cmd.debugTag {
578 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])
582 if alleleCoverage < cmd.minCoverage*2 {
583 idx := int(tag-tagstart) * 2
584 for _, cg := range cgs {
586 cg.Variants[idx+1] = 0
588 if tag == cmd.debugTag {
589 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
594 // hash[i] will be the hash of
595 // the variant(s) that should
596 // be at rank i (0-based).
597 hash := make([][blake2b.Size256]byte, 0, len(count))
598 for b := range count {
599 hash = append(hash, b)
601 sort.Slice(hash, func(i, j int) bool {
602 bi, bj := &hash[i], &hash[j]
603 if ci, cj := count[*bi], count[*bj]; ci != cj {
606 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
609 // rank[b] will be the 1-based
610 // new variant number for
611 // variants whose hash is b.
612 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
613 for i, h := range hash {
614 rank[h] = tileVariantID(i + 1)
616 if tag == cmd.debugTag {
617 for h, r := range rank {
618 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
621 // remap[v] will be the new
622 // variant number for original
624 remap := make([]tileVariantID, len(variants))
625 for i, tv := range variants {
626 remap[i] = rank[tv.Blake2b]
628 if tag == cmd.debugTag {
629 for in, out := range remap {
631 log.Printf("tag %d remap %d => %d", tag, in, out)
635 variantRemap[tag-tagstart] = remap
637 refrank := rank[blake2b.Sum256(rt.tiledata)]
638 if tag == cmd.debugTag {
639 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
648 var onehotChunk [][]int8
649 var onehotXref []onehotXref
651 var annotationsFilename string
653 annotationsFilename = "/dev/null"
655 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
656 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
658 annof, err := os.Create(annotationsFilename)
662 annow := bufio.NewWriterSize(annof, 1<<20)
664 for tag := tagstart; tag < tagend; tag++ {
666 if rt == nil && mask != nil {
667 // With no ref tile, we don't
668 // have coordinates to say
669 // this is in the desired
670 // regions -- so it's not.
671 // TODO: handle ref spanning
675 if rt != nil && rt.excluded {
676 // TODO: don't skip yet --
677 // first check for spanning
678 // tile variants that
679 // intersect non-excluded ref
683 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
686 remap := variantRemap[tag-tagstart]
688 // was not assigned above,
689 // because minCoverage
693 maxv := tileVariantID(0)
694 for _, v := range remap {
699 if *onehotChunked || *onehotSingle || *onlyPCA {
700 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
701 if tag == cmd.debugTag {
702 log.WithFields(logrus.Fields{
705 }).Info("tv2homhet()")
707 onehotChunk = append(onehotChunk, onehot...)
708 onehotXref = append(onehotXref, xrefs...)
715 // Reference does not use any
716 // variant of this tile
718 // TODO: diff against the
719 // relevant portion of the
720 // ref's spanning tile
724 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
726 reftilestr := strings.ToUpper(string(rt.tiledata))
728 done := make([]bool, maxv+1)
729 variantDiffs := make([][]hgvs.Variant, maxv+1)
730 for v, tv := range variants {
732 if v == 0 || v == rt.variant || done[v] {
737 if len(tv.Sequence) < taglen {
740 // if reftilestr doesn't end
741 // in the same tag as tv,
742 // extend reftilestr with
743 // following ref tiles until
744 // it does (up to an arbitrary
745 // sanity-check limit)
746 reftilestr := reftilestr
747 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
748 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
749 rt = reftile[rt.nexttag]
753 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
755 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
758 if !strings.HasSuffix(reftilestr, endtagstr) {
759 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
762 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
763 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
766 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
767 for i := range diffs {
768 diffs[i].Position += rt.pos
770 for _, diff := range diffs {
771 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)
774 variantDiffs[v] = diffs
778 // We can now determine, for each HGVS
779 // variant (diff) in this reftile
780 // region, whether a given genome
781 // phase/allele (1) has the variant, (0) has
782 // =ref or a different variant in that
783 // position, or (-1) is lacking
784 // coverage / couldn't be diffed.
785 hgvsCol := hgvsColSet{}
786 for _, diffs := range variantDiffs {
787 for _, diff := range diffs {
788 if _, ok := hgvsCol[diff]; ok {
791 hgvsCol[diff] = [2][]int8{
792 make([]int8, len(cmd.cgnames)),
793 make([]int8, len(cmd.cgnames)),
797 for row, name := range cmd.cgnames {
798 variants := cgs[name].Variants[(tag-tagstart)*2:]
799 for ph := 0; ph < 2; ph++ {
801 if int(v) >= len(remap) {
807 // hgvsCol[*][ph][row] is already 0
808 } else if len(variantDiffs[v]) == 0 {
809 // lacking coverage / couldn't be diffed
810 for _, col := range hgvsCol {
814 for _, diff := range variantDiffs[v] {
815 hgvsCol[diff][ph][row] = 1
820 for diff, colpair := range hgvsCol {
821 allele2homhet(colpair)
822 if !cmd.filterHGVScolpair(colpair) {
823 delete(hgvsCol, diff)
826 if len(hgvsCol) > 0 {
827 encodeHGVSTodo[rt.seqname] <- hgvsCol
842 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
843 rows := len(cmd.cgnames)
844 cols := len(onehotChunk)
845 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
846 throttleNumpyMem.Acquire()
847 out := onehotcols2int8(onehotChunk)
848 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
849 err = writeNumpyInt8(fnm, out, rows, cols)
853 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
854 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
859 throttleNumpyMem.Release()
861 if *onehotSingle || *onlyPCA {
862 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
863 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
864 onehotXrefs[infileIdx] = onehotXref
865 n := len(onehotIndirect[infileIdx][0])
866 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
868 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
869 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
870 throttleNumpyMem.Acquire()
871 rows := len(cmd.cgnames)
873 out := make([]int16, rows*cols)
874 for row, name := range cmd.cgnames {
876 for col, v := range cgs[name].Variants {
877 tag := tagstart + tagID(col/2)
878 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
881 if rt := reftile[tag]; rt == nil || rt.excluded {
885 out[outidx] = 0 // tag not found / spanning tile
886 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
887 out[outidx] = int16(variantRemap[tag-tagstart][v])
889 out[outidx] = -1 // low quality tile variant
891 if tag == cmd.debugTag {
892 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
900 throttleNumpyMem.Release()
901 if *mergeOutput || *hgvsSingle {
902 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
903 toMerge[infileIdx] = out
905 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
906 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
907 err = writeNumpyInt16(fnm, out, rows, cols)
914 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
918 if err = throttleMem.Wait(); err != nil {
923 log.Info("flushing hgvsCols temp files")
924 for seqname := range refseq {
925 close(encodeHGVSTodo[seqname])
927 err = encodeHGVS.Wait()
931 for seqname := range refseq {
932 log.Infof("%s: reading hgvsCols from temp file", seqname)
933 f := tmpHGVSCols[seqname]
934 _, err = f.Seek(0, io.SeekStart)
938 var hgvsCols hgvsColSet
939 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
941 err = dec.Decode(&hgvsCols)
946 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
947 variants := make([]hgvs.Variant, 0, len(hgvsCols))
948 for v := range hgvsCols {
949 variants = append(variants, v)
951 sort.Slice(variants, func(i, j int) bool {
952 vi, vj := &variants[i], &variants[j]
953 if vi.Position != vj.Position {
954 return vi.Position < vj.Position
955 } else if vi.Ref != vj.Ref {
956 return vi.Ref < vj.Ref
958 return vi.New < vj.New
961 rows := len(cmd.cgnames)
962 cols := len(variants) * 2
963 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
964 out := make([]int8, rows*cols)
965 for varIdx, variant := range variants {
966 hgvsCols := hgvsCols[variant]
967 for row := range cmd.cgnames {
968 for ph := 0; ph < 2; ph++ {
969 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
973 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
979 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
980 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
981 var hgvsLabels bytes.Buffer
982 for varIdx, variant := range variants {
983 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
985 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
992 if *mergeOutput || *hgvsSingle {
993 var annow *bufio.Writer
996 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
997 annof, err = os.Create(annoFilename)
1001 annow = bufio.NewWriterSize(annof, 1<<20)
1004 rows := len(cmd.cgnames)
1006 for _, chunk := range toMerge {
1007 cols += len(chunk) / rows
1009 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
1012 out = make([]int16, rows*cols)
1014 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1016 for outIdx, chunk := range toMerge {
1017 chunkcols := len(chunk) / rows
1019 for row := 0; row < rows; row++ {
1020 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1023 toMerge[outIdx] = nil
1025 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1026 log.Infof("reading %s", annotationsFilename)
1027 buf, err := os.ReadFile(annotationsFilename)
1032 err = os.Remove(annotationsFilename)
1037 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1041 fields := bytes.SplitN(line, []byte{','}, 9)
1042 tag, _ := strconv.Atoi(string(fields[0]))
1043 incol, _ := strconv.Atoi(string(fields[1]))
1044 tileVariant, _ := strconv.Atoi(string(fields[2]))
1045 hgvsID := string(fields[3])
1046 seqname := string(fields[4])
1047 pos, _ := strconv.Atoi(string(fields[5]))
1050 // Null entry for un-diffable
1055 // Null entry for ref tile
1058 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1059 // The tile intersects one of
1060 // the selected regions, but
1061 // this particular HGVS
1062 // variant does not.
1065 hgvsColPair := hgvsCols[hgvsID]
1066 if hgvsColPair[0] == nil {
1067 // values in new columns start
1068 // out as -1 ("no data yet")
1069 // or 0 ("=ref") here, may
1070 // change to 1 ("hgvs variant
1071 // present") below, either on
1072 // this line or a future line.
1073 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1074 rt, ok := reftile[tagID(tag)]
1076 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1079 for ph := 0; ph < 2; ph++ {
1080 for row := 0; row < rows; row++ {
1081 v := chunk[row*chunkcols+incol*2+ph]
1082 if tileVariantID(v) == rt.variant {
1083 hgvsColPair[ph][row] = 0
1085 hgvsColPair[ph][row] = -1
1089 hgvsCols[hgvsID] = hgvsColPair
1091 hgvsref := hgvs.Variant{
1093 Ref: string(refseq),
1094 New: string(refseq),
1096 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])
1100 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])
1102 for ph := 0; ph < 2; ph++ {
1103 for row := 0; row < rows; row++ {
1104 v := chunk[row*chunkcols+incol*2+ph]
1105 if int(v) == tileVariant {
1106 hgvsColPair[ph][row] = 1
1112 startcol += chunkcols
1123 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1131 cols = len(hgvsCols) * 2
1132 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1133 out = make([]int16, rows*cols)
1134 hgvsIDs := make([]string, 0, cols/2)
1135 for hgvsID := range hgvsCols {
1136 hgvsIDs = append(hgvsIDs, hgvsID)
1138 sort.Strings(hgvsIDs)
1139 var hgvsLabels bytes.Buffer
1140 for idx, hgvsID := range hgvsIDs {
1141 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1142 for ph := 0; ph < 2; ph++ {
1143 hgvscol := hgvsCols[hgvsID][ph]
1144 for row, val := range hgvscol {
1145 out[row*cols+idx*2+ph] = val
1149 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1154 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1155 log.Printf("writing hgvs labels: %s", fnm)
1156 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1162 if *onehotSingle || *onlyPCA {
1164 for _, part := range onehotIndirect {
1165 nzCount += len(part[0])
1167 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1168 var xrefs []onehotXref
1169 chunkOffset := uint32(0)
1171 for i, part := range onehotIndirect {
1172 for i := range part[1] {
1173 part[1][i] += chunkOffset
1175 copy(onehot[outcol:], part[0])
1176 copy(onehot[outcol+nzCount:], part[1])
1177 xrefs = append(xrefs, onehotXrefs[i]...)
1179 outcol += len(part[0])
1180 chunkOffset += onehotChunkSize[i]
1184 onehotXrefs[i] = nil
1185 debug.FreeOSMemory()
1188 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1189 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1193 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1194 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1201 for _, c := range onehot[nzCount:] {
1207 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1209 log.Printf("have %d one-hot cols", cols)
1211 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1212 cols = (cols + 1) / 2
1216 // we work with pairs of columns
1219 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1220 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1221 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1222 for i, c := range onehot[nzCount:] {
1223 if int(c/2)%stride == 0 {
1224 outcol := int(c/2)/stride*2 + int(c)%2
1225 mtxFull.Set(int(onehot[i]), outcol, 1)
1226 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1227 mtxTrain.Set(trainRow, outcol, 1)
1231 log.Print("fitting")
1232 transformer := nlp.NewPCA(cmd.pcaComponents)
1233 transformer.Fit(mtxTrain.T())
1234 log.Printf("transforming")
1235 pca, err := transformer.Transform(mtxFull.T())
1240 outrows, outcols := pca.Dims()
1241 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1242 out := make([]float64, outrows*outcols)
1243 for i := 0; i < outrows; i++ {
1244 for j := 0; j < outcols; j++ {
1245 out[i*outcols+j] = pca.At(i, j)
1248 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1249 log.Printf("writing numpy: %s", fnm)
1250 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1254 npw, err := gonpy.NewWriter(nopCloser{output})
1256 return fmt.Errorf("gonpy.NewWriter: %w", err)
1258 npw.Shape = []int{outrows, outcols}
1259 err = npw.WriteFloat64(out)
1261 return fmt.Errorf("WriteFloat64: %w", err)
1263 err = output.Close()
1269 samplesOutFilename := *outputDir + "/samples.csv"
1270 log.Infof("writing sample metadata to %s", samplesOutFilename)
1272 f, err = os.Create(samplesOutFilename)
1277 for i, si := range cmd.samples {
1281 } else if si.isControl {
1290 for c := 0; c < outcols; c++ {
1291 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1293 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1295 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1301 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1307 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1308 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1309 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1311 f, err = os.Create(tagoffsetFilename)
1316 for idx, offset := range chunkStartTag {
1317 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1319 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1325 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1333 type sampleInfo struct {
1339 pcaComponents []float64
1342 // Read samples.csv file with case/control and training/validation
1344 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1346 f, err := open(samplesFilename)
1350 buf, err := io.ReadAll(f)
1356 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1361 split := strings.Split(string(csv), ",")
1363 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1365 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1368 idx, err := strconv.Atoi(split[0])
1371 return nil, fmt.Errorf("header does not look right: %q", csv)
1373 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1376 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1378 var pcaComponents []float64
1380 for _, s := range split[4:] {
1381 f, err := strconv.ParseFloat(s, 64)
1383 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1385 pcaComponents = append(pcaComponents, f)
1388 si = append(si, sampleInfo{
1390 isCase: split[2] == "1",
1391 isControl: split[2] == "0",
1392 isTraining: split[3] == "1",
1393 isValidation: split[3] == "0",
1394 pcaComponents: pcaComponents,
1400 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1401 if cmd.chi2PValue >= 1 {
1404 col0 := make([]bool, 0, len(cmd.chi2Cases))
1405 col1 := make([]bool, 0, len(cmd.chi2Cases))
1406 cases := make([]bool, 0, len(cmd.chi2Cases))
1407 for i, c := range cmd.chi2Cases {
1408 if colpair[0][i] < 0 {
1411 col0 = append(col0, colpair[0][i] != 0)
1412 col1 = append(col1, colpair[1][i] != 0)
1413 cases = append(cases, c)
1415 return len(cases) >= cmd.minCoverage &&
1416 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1419 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1420 output, err := os.Create(fnm)
1424 defer output.Close()
1425 bufw := bufio.NewWriterSize(output, 1<<26)
1426 npw, err := gonpy.NewWriter(nopCloser{bufw})
1430 log.WithFields(log.Fields{
1434 "bytes": rows * cols * 4,
1435 }).Infof("writing numpy: %s", fnm)
1436 npw.Shape = []int{rows, cols}
1437 npw.WriteUint32(out)
1442 return output.Close()
1445 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1446 output, err := os.Create(fnm)
1450 defer output.Close()
1451 bufw := bufio.NewWriterSize(output, 1<<26)
1452 npw, err := gonpy.NewWriter(nopCloser{bufw})
1456 log.WithFields(log.Fields{
1460 "bytes": rows * cols * 4,
1461 }).Infof("writing numpy: %s", fnm)
1462 npw.Shape = []int{rows, cols}
1468 return output.Close()
1471 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1472 output, err := os.Create(fnm)
1476 defer output.Close()
1477 bufw := bufio.NewWriterSize(output, 1<<26)
1478 npw, err := gonpy.NewWriter(nopCloser{bufw})
1482 log.WithFields(log.Fields{
1486 "bytes": rows * cols * 2,
1487 }).Infof("writing numpy: %s", fnm)
1488 npw.Shape = []int{rows, cols}
1494 return output.Close()
1497 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1498 output, err := os.Create(fnm)
1502 defer output.Close()
1503 bufw := bufio.NewWriterSize(output, 1<<26)
1504 npw, err := gonpy.NewWriter(nopCloser{bufw})
1508 log.WithFields(log.Fields{
1512 "bytes": rows * cols,
1513 }).Infof("writing numpy: %s", fnm)
1514 npw.Shape = []int{rows, cols}
1520 return output.Close()
1523 func allele2homhet(colpair [2][]int8) {
1524 a, b := colpair[0], colpair[1]
1525 for i, av := range a {
1527 if av < 0 || bv < 0 {
1530 } else if av > 0 && bv > 0 {
1533 } else if av > 0 || bv > 0 {
1537 // ref (or a different variant in same position)
1538 // (this is a no-op) a[i], b[i] = 0, 0
1543 type onehotXref struct {
1545 variant tileVariantID
1550 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1552 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1553 // variants of a single tile/tag#.
1555 // Return nil if no tile variant passes Χ² filter.
1556 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1557 if tag == cmd.debugTag {
1558 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1559 for i, name := range cmd.cgnames {
1560 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1562 log.WithFields(logrus.Fields{
1563 "cgs[i].Variants[tag*2+j]": tv,
1567 "chunkstarttag": chunkstarttag,
1568 }).Info("tv2homhet()")
1570 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1571 // everyone has the most common variant (of the variants we don't drop)
1574 tagoffset := tag - chunkstarttag
1576 for _, cg := range cgs {
1578 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1579 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1587 if coverage < cmd.minCoverage {
1590 // "observed" array for p-value calculation (training set
1592 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1593 // one-hot output (all samples)
1594 outcols := make([][]int8, (maxv+1)*2)
1595 for i := range obs {
1596 obs[i] = make([]bool, cmd.trainingSetSize)
1597 outcols[i] = make([]int8, len(cmd.cgnames))
1599 for cgid, name := range cmd.cgnames {
1600 tsid := cmd.trainingSet[cgid]
1601 cgvars := cgs[name].Variants[tagoffset*2:]
1602 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1603 for v := tileVariantID(1); v <= maxv; v++ {
1604 if tv0 == v && tv1 == v {
1606 obs[v*2][tsid] = true
1608 outcols[v*2][cgid] = 1
1609 } else if tv0 == v || tv1 == v {
1611 obs[v*2+1][tsid] = true
1613 outcols[v*2+1][cgid] = 1
1618 var xref []onehotXref
1619 for col := 2; col < len(obs); col++ {
1620 // col 0,1 correspond to tile variant 0, i.e.,
1621 // no-call; col 2,3 correspond to the most common
1622 // variant; so we (normally) start at col 4.
1623 if col < 4 && !cmd.includeVariant1 {
1626 p := cmd.pvalue(obs[col])
1627 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1630 onehot = append(onehot, outcols[col])
1631 xref = append(xref, onehotXref{
1633 variant: tileVariantID(col >> 1),
1641 // convert a []onehotXref with length N to a numpy-style []int32
1642 // matrix with N columns, one row per field of onehotXref struct.
1644 // Hom/het row contains hom=0, het=1.
1646 // P-value row contains 1000000x actual p-value.
1647 func onehotXref2int32(xrefs []onehotXref) []int32 {
1649 xdata := make([]int32, 5*xcols)
1650 for i, xref := range xrefs {
1651 xdata[i] = int32(xref.tag)
1652 xdata[xcols+i] = int32(xref.variant)
1654 xdata[xcols*2+i] = 1
1656 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1657 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1662 // transpose onehot data from in[col][row] to numpy-style
1663 // out[row*cols+col].
1664 func onehotcols2int8(in [][]int8) []int8 {
1670 out := make([]int8, rows*cols)
1671 for row := 0; row < rows; row++ {
1672 outrow := out[row*cols:]
1673 for col, incol := range in {
1674 outrow[col] = incol[row]
1680 // Return [2][]uint32{rowIndices, colIndices} indicating which
1681 // elements of matrixT[c][r] have non-zero values.
1682 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1684 for c, col := range matrixT {
1685 for r, val := range col {
1687 nz[0] = append(nz[0], uint32(r))
1688 nz[1] = append(nz[1], uint32(c))