1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.arvados.org/arvados.git/sdk/go/arvados"
31 "github.com/arvados/lightning/hgvs"
32 "github.com/james-bowman/nlp"
33 "github.com/kshedden/gonpy"
34 "github.com/sirupsen/logrus"
35 log "github.com/sirupsen/logrus"
36 "golang.org/x/crypto/blake2b"
37 "gonum.org/v1/gonum/mat"
40 const annotationMaxTileSpan = 100
42 type sliceNumpy struct {
54 trainingSet []int // samples index => training set index, or -1 if not in training set
56 pvalue func(onehot []bool) float64
60 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
61 err := cmd.run(prog, args, stdin, stdout, stderr)
63 fmt.Fprintf(stderr, "%s\n", err)
69 func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
70 flags := flag.NewFlagSet("", flag.ContinueOnError)
71 flags.SetOutput(stderr)
72 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
73 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
74 arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
75 arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
76 projectUUID := flags.String("project", "", "project `UUID` for output data")
77 priority := flags.Int("priority", 500, "container request priority")
78 preemptible := flags.Bool("preemptible", true, "request preemptible instance")
79 inputDir := flags.String("input-dir", "./in", "input `directory`")
80 outputDir := flags.String("output-dir", "./out", "output `directory`")
81 ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
82 regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
83 expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
84 mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
85 hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
86 hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
87 onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
88 onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
89 samplesFilename := flags.String("samples", "", "`samples.csv` file with training/validation and case/control groups (see 'lightning choose-samples')")
90 caseControlOnly := flags.Bool("case-control-only", false, "drop samples that are not in case/control groups")
91 onlyPCA := flags.Bool("pca", false, "run principal component analysis, write components to pca.npy and samples.csv")
92 flags.IntVar(&cmd.pcaComponents, "pca-components", 4, "number of PCA components to compute / use in logistic regression")
93 maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
94 debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
95 flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
96 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")
97 flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
98 cmd.filter.Flags(flags)
99 err := flags.Parse(args)
100 if err == flag.ErrHelp {
102 } else if err != nil {
104 } else if flags.NArg() > 0 {
105 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
110 log.Println(http.ListenAndServe(*pprof, nil))
114 if cmd.chi2PValue != 1 && *samplesFilename == "" {
115 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -samples= value is empty", cmd.chi2PValue)
118 cmd.debugTag = tagID(*debugTag)
121 runner := arvadosContainerRunner{
122 Name: "lightning slice-numpy",
123 Client: arvados.NewClientFromEnv(),
124 ProjectUUID: *projectUUID,
125 RAM: int64(*arvadosRAM),
126 VCPUs: *arvadosVCPUs,
130 Preemptible: *preemptible,
132 err = runner.TranslatePaths(inputDir, regionsFilename, samplesFilename)
136 runner.Args = []string{"slice-numpy", "-local=true",
138 "-input-dir=" + *inputDir,
139 "-output-dir=/mnt/output",
140 "-threads=" + fmt.Sprintf("%d", cmd.threads),
141 "-regions=" + *regionsFilename,
142 "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
143 "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
144 "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
145 "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
146 "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
147 "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
148 "-samples=" + *samplesFilename,
149 "-case-control-only=" + fmt.Sprintf("%v", *caseControlOnly),
150 "-pca=" + fmt.Sprintf("%v", *onlyPCA),
151 "-pca-components=" + fmt.Sprintf("%d", cmd.pcaComponents),
152 "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
153 "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
154 "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
155 "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
157 runner.Args = append(runner.Args, cmd.filter.Args()...)
159 output, err = runner.Run()
163 fmt.Fprintln(stdout, output)
167 infiles, err := allFiles(*inputDir, matchGobFile)
171 if len(infiles) == 0 {
172 err = fmt.Errorf("no input files found in %s", *inputDir)
175 sort.Strings(infiles)
177 var refseq map[string][]tileLibRef
178 var reftiledata = make(map[tileLibRef][]byte, 11000000)
179 in0, err := open(infiles[0])
184 matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
186 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
190 if *samplesFilename != "" {
191 cmd.samples, err = loadSampleInfo(*samplesFilename)
195 if len(cmd.samples[0].pcaComponents) > 0 {
196 cmd.pvalue = glmPvalueFunc(cmd.samples, cmd.pcaComponents)
197 // Unfortunately, statsmodel/glm lib logs
198 // stuff to os.Stdout when it panics on an
199 // unsolvable problem. We recover() from the
200 // panic in glm.go, but we also need to
201 // commandeer os.Stdout to avoid producing
202 // large quantities of logs.
203 stdoutWas := os.Stdout
204 defer func() { os.Stdout = stdoutWas }()
205 os.Stdout, err = os.Open(os.DevNull)
210 } else if *caseControlOnly {
211 return fmt.Errorf("-case-control-only does not make sense without -samples")
216 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
217 if len(ent.TagSet) > 0 {
220 for _, cseq := range ent.CompactSequences {
221 if cseq.Name == *ref || *ref == "" {
222 refseq = cseq.TileSequences
225 for _, cg := range ent.CompactGenomes {
226 if matchGenome.MatchString(cg.Name) {
227 cmd.cgnames = append(cmd.cgnames, cg.Name)
230 for _, tv := range ent.TileVariants {
232 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
242 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
245 if len(tagset) == 0 {
246 err = fmt.Errorf("tagset not found")
250 taglib := &tagLibrary{}
251 err = taglib.setTags(tagset)
255 taglen := taglib.TagLen()
256 sort.Strings(cmd.cgnames)
258 if len(cmd.cgnames) == 0 {
259 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
261 cmd.trainingSet = make([]int, len(cmd.cgnames))
262 if *samplesFilename == "" {
263 cmd.trainingSetSize = len(cmd.cgnames)
264 for i, name := range cmd.cgnames {
265 cmd.samples = append(cmd.samples, sampleInfo{
266 id: trimFilenameForLabel(name),
269 cmd.trainingSet[i] = i
271 } else if len(cmd.cgnames) != len(cmd.samples) {
272 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
274 for i, name := range cmd.cgnames {
275 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
276 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
279 if *caseControlOnly {
280 for i := 0; i < len(cmd.samples); i++ {
281 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
282 if i+1 < len(cmd.samples) {
283 copy(cmd.samples[i:], cmd.samples[i+1:])
284 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
286 cmd.samples = cmd.samples[:len(cmd.samples)-1]
287 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
293 cmd.trainingSetSize = 0
294 for i := range cmd.cgnames {
295 if cmd.samples[i].isTraining {
296 cmd.trainingSet[i] = cmd.trainingSetSize
297 cmd.trainingSetSize++
298 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
300 cmd.trainingSet[i] = -1
303 if cmd.pvalue == nil {
304 cmd.pvalue = func(onehot []bool) float64 {
305 return pvalue(onehot, cmd.chi2Cases)
309 if cmd.filter.MinCoverage == 1 {
310 // In the generic formula below, floating point
311 // arithmetic can effectively push the coverage
312 // threshold above 1.0, which is impossible/useless.
313 // 1.0 needs to mean exactly 100% coverage.
314 cmd.minCoverage = len(cmd.cgnames)
316 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
320 samplesOutFilename := *outputDir + "/samples.csv"
321 log.Infof("writing sample metadata to %s", samplesOutFilename)
323 f, err = os.Create(samplesOutFilename)
328 for i, si := range cmd.samples {
332 } else if si.isControl {
340 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
342 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
348 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
354 log.Info("indexing reference tiles")
355 type reftileinfo struct {
356 variant tileVariantID
357 seqname string // chr1
358 pos int // distance from start of chromosome to starttag
359 tiledata []byte // acgtggcaa...
360 excluded bool // true if excluded by regions file
361 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
363 isdup := map[tagID]bool{}
364 reftile := map[tagID]*reftileinfo{}
365 for seqname, cseq := range refseq {
367 lastreftag := tagID(-1)
368 for _, libref := range cseq {
369 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
372 tiledata := reftiledata[libref]
373 if len(tiledata) == 0 {
374 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
377 foundthistag := false
378 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
379 if !foundthistag && tagid == libref.Tag {
383 if dupref, ok := reftile[tagid]; ok {
384 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)
385 delete(reftile, tagid)
387 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
391 if isdup[libref.Tag] {
392 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
393 } else if reftile[libref.Tag] != nil {
394 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)
395 delete(reftile, libref.Tag)
396 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
397 isdup[libref.Tag] = true
399 reftile[libref.Tag] = &reftileinfo{
401 variant: libref.Variant,
407 reftile[lastreftag].nexttag = libref.Tag
409 lastreftag = libref.Tag
411 pos += len(tiledata) - taglen
413 log.Printf("... %s done, len %d", seqname, pos+taglen)
417 if *regionsFilename != "" {
418 log.Printf("loading regions from %s", *regionsFilename)
419 mask, err = makeMask(*regionsFilename, *expandRegions)
423 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
424 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
425 for _, rt := range reftile {
426 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
430 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
433 type hgvsColSet map[hgvs.Variant][2][]int8
434 encodeHGVS := throttle{Max: len(refseq)}
435 encodeHGVSTodo := map[string]chan hgvsColSet{}
436 tmpHGVSCols := map[string]*os.File{}
438 for seqname := range refseq {
440 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
444 defer os.Remove(f.Name())
445 bufw := bufio.NewWriterSize(f, 1<<24)
446 enc := gob.NewEncoder(bufw)
447 tmpHGVSCols[seqname] = f
448 todo := make(chan hgvsColSet, 128)
449 encodeHGVSTodo[seqname] = todo
450 encodeHGVS.Go(func() error {
451 for colset := range todo {
452 err := enc.Encode(colset)
454 encodeHGVS.Report(err)
465 var toMerge [][]int16
466 if *mergeOutput || *hgvsSingle {
467 toMerge = make([][]int16, len(infiles))
469 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
470 var onehotChunkSize []uint32
471 var onehotXrefs [][]onehotXref
472 if *onehotSingle || *onlyPCA {
473 onehotIndirect = make([][2][]uint32, len(infiles))
474 onehotChunkSize = make([]uint32, len(infiles))
475 onehotXrefs = make([][]onehotXref, len(infiles))
477 chunkStartTag := make([]tagID, len(infiles))
479 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
480 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
481 log.Info("generating annotations and numpy matrix for each slice")
482 var errSkip = errors.New("skip infile")
484 for infileIdx, infile := range infiles {
485 infileIdx, infile := infileIdx, infile
486 throttleMem.Go(func() error {
487 seq := make(map[tagID][]TileVariant, 50000)
488 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
489 f, err := open(infile)
494 log.Infof("%04d: reading %s", infileIdx, infile)
495 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
496 for _, tv := range ent.TileVariants {
501 // corresponding ref tile, if
502 // mask is in play (we can't
503 // determine coordinates for
505 if mask != nil && reftile[tv.Tag] == nil {
509 // corresponding ref tile is
510 // outside target regions --
511 // unless it's a potential
513 if mask != nil && reftile[tv.Tag].excluded &&
514 (int(tv.Tag+1) >= len(tagset) ||
515 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
518 if tv.Tag == cmd.debugTag {
519 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
521 variants := seq[tv.Tag]
522 if len(variants) == 0 {
523 variants = make([]TileVariant, 100)
525 for len(variants) <= int(tv.Variant) {
526 variants = append(variants, TileVariant{})
528 variants[int(tv.Variant)] = tv
529 seq[tv.Tag] = variants
531 for _, cg := range ent.CompactGenomes {
532 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
535 if !matchGenome.MatchString(cg.Name) {
538 // pad to full slice size
539 // to avoid out-of-bounds
541 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
542 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
550 } else if err != nil {
551 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
553 tagstart := cgs[cmd.cgnames[0]].StartTag
554 tagend := cgs[cmd.cgnames[0]].EndTag
555 chunkStartTag[infileIdx] = tagstart
559 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
560 variantRemap := make([][]tileVariantID, tagend-tagstart)
561 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
562 for tag, variants := range seq {
563 tag, variants := tag, variants
564 throttleCPU.Go(func() error {
566 count := make(map[[blake2b.Size256]byte]int, len(variants))
570 count[blake2b.Sum256(rt.tiledata)] = 0
573 for cgname, cg := range cgs {
574 idx := int(tag-tagstart) * 2
575 for allele := 0; allele < 2; allele++ {
576 v := cg.Variants[idx+allele]
577 if v > 0 && len(variants[v].Sequence) > 0 {
578 count[variants[v].Blake2b]++
581 if v > 0 && tag == cmd.debugTag {
582 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])
586 if alleleCoverage < cmd.minCoverage*2 {
587 idx := int(tag-tagstart) * 2
588 for _, cg := range cgs {
590 cg.Variants[idx+1] = 0
592 if tag == cmd.debugTag {
593 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
598 // hash[i] will be the hash of
599 // the variant(s) that should
600 // be at rank i (0-based).
601 hash := make([][blake2b.Size256]byte, 0, len(count))
602 for b := range count {
603 hash = append(hash, b)
605 sort.Slice(hash, func(i, j int) bool {
606 bi, bj := &hash[i], &hash[j]
607 if ci, cj := count[*bi], count[*bj]; ci != cj {
610 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
613 // rank[b] will be the 1-based
614 // new variant number for
615 // variants whose hash is b.
616 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
617 for i, h := range hash {
618 rank[h] = tileVariantID(i + 1)
620 if tag == cmd.debugTag {
621 for h, r := range rank {
622 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
625 // remap[v] will be the new
626 // variant number for original
628 remap := make([]tileVariantID, len(variants))
629 for i, tv := range variants {
630 remap[i] = rank[tv.Blake2b]
632 if tag == cmd.debugTag {
633 for in, out := range remap {
635 log.Printf("tag %d remap %d => %d", tag, in, out)
639 variantRemap[tag-tagstart] = remap
641 refrank := rank[blake2b.Sum256(rt.tiledata)]
642 if tag == cmd.debugTag {
643 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
652 var onehotChunk [][]int8
653 var onehotXref []onehotXref
655 var annotationsFilename string
657 annotationsFilename = "/dev/null"
659 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
660 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
662 annof, err := os.Create(annotationsFilename)
666 annow := bufio.NewWriterSize(annof, 1<<20)
668 for tag := tagstart; tag < tagend; tag++ {
670 if rt == nil && mask != nil {
671 // With no ref tile, we don't
672 // have coordinates to say
673 // this is in the desired
674 // regions -- so it's not.
675 // TODO: handle ref spanning
679 if rt != nil && rt.excluded {
680 // TODO: don't skip yet --
681 // first check for spanning
682 // tile variants that
683 // intersect non-excluded ref
687 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
690 remap := variantRemap[tag-tagstart]
692 // was not assigned above,
693 // because minCoverage
697 maxv := tileVariantID(0)
698 for _, v := range remap {
703 if *onehotChunked || *onehotSingle || *onlyPCA {
704 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
705 if tag == cmd.debugTag {
706 log.WithFields(logrus.Fields{
709 }).Info("tv2homhet()")
711 onehotChunk = append(onehotChunk, onehot...)
712 onehotXref = append(onehotXref, xrefs...)
719 // Reference does not use any
720 // variant of this tile
722 // TODO: diff against the
723 // relevant portion of the
724 // ref's spanning tile
728 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
730 reftilestr := strings.ToUpper(string(rt.tiledata))
732 done := make([]bool, maxv+1)
733 variantDiffs := make([][]hgvs.Variant, maxv+1)
734 for v, tv := range variants {
736 if v == 0 || v == rt.variant || done[v] {
741 if len(tv.Sequence) < taglen {
744 // if reftilestr doesn't end
745 // in the same tag as tv,
746 // extend reftilestr with
747 // following ref tiles until
748 // it does (up to an arbitrary
749 // sanity-check limit)
750 reftilestr := reftilestr
751 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
752 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
753 rt = reftile[rt.nexttag]
757 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
759 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
762 if !strings.HasSuffix(reftilestr, endtagstr) {
763 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
766 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
767 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
770 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
771 for i := range diffs {
772 diffs[i].Position += rt.pos
774 for _, diff := range diffs {
775 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)
778 variantDiffs[v] = diffs
782 // We can now determine, for each HGVS
783 // variant (diff) in this reftile
784 // region, whether a given genome
785 // phase/allele (1) has the variant, (0) has
786 // =ref or a different variant in that
787 // position, or (-1) is lacking
788 // coverage / couldn't be diffed.
789 hgvsCol := hgvsColSet{}
790 for _, diffs := range variantDiffs {
791 for _, diff := range diffs {
792 if _, ok := hgvsCol[diff]; ok {
795 hgvsCol[diff] = [2][]int8{
796 make([]int8, len(cmd.cgnames)),
797 make([]int8, len(cmd.cgnames)),
801 for row, name := range cmd.cgnames {
802 variants := cgs[name].Variants[(tag-tagstart)*2:]
803 for ph := 0; ph < 2; ph++ {
805 if int(v) >= len(remap) {
811 // hgvsCol[*][ph][row] is already 0
812 } else if len(variantDiffs[v]) == 0 {
813 // lacking coverage / couldn't be diffed
814 for _, col := range hgvsCol {
818 for _, diff := range variantDiffs[v] {
819 hgvsCol[diff][ph][row] = 1
824 for diff, colpair := range hgvsCol {
825 allele2homhet(colpair)
826 if !cmd.filterHGVScolpair(colpair) {
827 delete(hgvsCol, diff)
830 if len(hgvsCol) > 0 {
831 encodeHGVSTodo[rt.seqname] <- hgvsCol
846 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
847 rows := len(cmd.cgnames)
848 cols := len(onehotChunk)
849 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
850 throttleNumpyMem.Acquire()
851 out := onehotcols2int8(onehotChunk)
852 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
853 err = writeNumpyInt8(fnm, out, rows, cols)
857 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
858 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
863 throttleNumpyMem.Release()
865 if *onehotSingle || *onlyPCA {
866 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
867 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
868 onehotXrefs[infileIdx] = onehotXref
869 n := len(onehotIndirect[infileIdx][0])
870 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
872 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
873 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
874 throttleNumpyMem.Acquire()
875 rows := len(cmd.cgnames)
877 out := make([]int16, rows*cols)
878 for row, name := range cmd.cgnames {
880 for col, v := range cgs[name].Variants {
881 tag := tagstart + tagID(col/2)
882 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
885 if rt := reftile[tag]; rt == nil || rt.excluded {
889 out[outidx] = 0 // tag not found / spanning tile
890 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
891 out[outidx] = int16(variantRemap[tag-tagstart][v])
893 out[outidx] = -1 // low quality tile variant
895 if tag == cmd.debugTag {
896 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
904 throttleNumpyMem.Release()
905 if *mergeOutput || *hgvsSingle {
906 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
907 toMerge[infileIdx] = out
909 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
910 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
911 err = writeNumpyInt16(fnm, out, rows, cols)
918 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
922 if err = throttleMem.Wait(); err != nil {
927 log.Info("flushing hgvsCols temp files")
928 for seqname := range refseq {
929 close(encodeHGVSTodo[seqname])
931 err = encodeHGVS.Wait()
935 for seqname := range refseq {
936 log.Infof("%s: reading hgvsCols from temp file", seqname)
937 f := tmpHGVSCols[seqname]
938 _, err = f.Seek(0, io.SeekStart)
942 var hgvsCols hgvsColSet
943 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
945 err = dec.Decode(&hgvsCols)
950 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
951 variants := make([]hgvs.Variant, 0, len(hgvsCols))
952 for v := range hgvsCols {
953 variants = append(variants, v)
955 sort.Slice(variants, func(i, j int) bool {
956 vi, vj := &variants[i], &variants[j]
957 if vi.Position != vj.Position {
958 return vi.Position < vj.Position
959 } else if vi.Ref != vj.Ref {
960 return vi.Ref < vj.Ref
962 return vi.New < vj.New
965 rows := len(cmd.cgnames)
966 cols := len(variants) * 2
967 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
968 out := make([]int8, rows*cols)
969 for varIdx, variant := range variants {
970 hgvsCols := hgvsCols[variant]
971 for row := range cmd.cgnames {
972 for ph := 0; ph < 2; ph++ {
973 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
977 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
983 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
984 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
985 var hgvsLabels bytes.Buffer
986 for varIdx, variant := range variants {
987 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
989 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
996 if *mergeOutput || *hgvsSingle {
997 var annow *bufio.Writer
1000 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
1001 annof, err = os.Create(annoFilename)
1005 annow = bufio.NewWriterSize(annof, 1<<20)
1008 rows := len(cmd.cgnames)
1010 for _, chunk := range toMerge {
1011 cols += len(chunk) / rows
1013 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
1016 out = make([]int16, rows*cols)
1018 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1020 for outIdx, chunk := range toMerge {
1021 chunkcols := len(chunk) / rows
1023 for row := 0; row < rows; row++ {
1024 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1027 toMerge[outIdx] = nil
1029 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1030 log.Infof("reading %s", annotationsFilename)
1031 buf, err := os.ReadFile(annotationsFilename)
1036 err = os.Remove(annotationsFilename)
1041 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1045 fields := bytes.SplitN(line, []byte{','}, 9)
1046 tag, _ := strconv.Atoi(string(fields[0]))
1047 incol, _ := strconv.Atoi(string(fields[1]))
1048 tileVariant, _ := strconv.Atoi(string(fields[2]))
1049 hgvsID := string(fields[3])
1050 seqname := string(fields[4])
1051 pos, _ := strconv.Atoi(string(fields[5]))
1054 // Null entry for un-diffable
1059 // Null entry for ref tile
1062 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1063 // The tile intersects one of
1064 // the selected regions, but
1065 // this particular HGVS
1066 // variant does not.
1069 hgvsColPair := hgvsCols[hgvsID]
1070 if hgvsColPair[0] == nil {
1071 // values in new columns start
1072 // out as -1 ("no data yet")
1073 // or 0 ("=ref") here, may
1074 // change to 1 ("hgvs variant
1075 // present") below, either on
1076 // this line or a future line.
1077 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1078 rt, ok := reftile[tagID(tag)]
1080 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1083 for ph := 0; ph < 2; ph++ {
1084 for row := 0; row < rows; row++ {
1085 v := chunk[row*chunkcols+incol*2+ph]
1086 if tileVariantID(v) == rt.variant {
1087 hgvsColPair[ph][row] = 0
1089 hgvsColPair[ph][row] = -1
1093 hgvsCols[hgvsID] = hgvsColPair
1095 hgvsref := hgvs.Variant{
1097 Ref: string(refseq),
1098 New: string(refseq),
1100 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])
1104 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])
1106 for ph := 0; ph < 2; ph++ {
1107 for row := 0; row < rows; row++ {
1108 v := chunk[row*chunkcols+incol*2+ph]
1109 if int(v) == tileVariant {
1110 hgvsColPair[ph][row] = 1
1116 startcol += chunkcols
1127 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1135 cols = len(hgvsCols) * 2
1136 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1137 out = make([]int16, rows*cols)
1138 hgvsIDs := make([]string, 0, cols/2)
1139 for hgvsID := range hgvsCols {
1140 hgvsIDs = append(hgvsIDs, hgvsID)
1142 sort.Strings(hgvsIDs)
1143 var hgvsLabels bytes.Buffer
1144 for idx, hgvsID := range hgvsIDs {
1145 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1146 for ph := 0; ph < 2; ph++ {
1147 hgvscol := hgvsCols[hgvsID][ph]
1148 for row, val := range hgvscol {
1149 out[row*cols+idx*2+ph] = val
1153 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1158 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1159 log.Printf("writing hgvs labels: %s", fnm)
1160 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1166 if *onehotSingle || *onlyPCA {
1168 for _, part := range onehotIndirect {
1169 nzCount += len(part[0])
1171 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1172 var xrefs []onehotXref
1173 chunkOffset := uint32(0)
1175 for i, part := range onehotIndirect {
1176 for i := range part[1] {
1177 part[1][i] += chunkOffset
1179 copy(onehot[outcol:], part[0])
1180 copy(onehot[outcol+nzCount:], part[1])
1181 xrefs = append(xrefs, onehotXrefs[i]...)
1183 outcol += len(part[0])
1184 chunkOffset += onehotChunkSize[i]
1188 onehotXrefs[i] = nil
1189 debug.FreeOSMemory()
1192 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1193 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1197 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1198 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1202 fnm = fmt.Sprintf("%s/stats.json", *outputDir)
1203 j, err := json.Marshal(map[string]interface{}{
1204 "pvalueCallCount": cmd.pvalueCallCount,
1209 err = os.WriteFile(fnm, j, 0777)
1216 for _, c := range onehot[nzCount:] {
1222 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1224 log.Printf("have %d one-hot cols", cols)
1226 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1227 cols = (cols + 1) / 2
1231 // we work with pairs of columns
1234 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1235 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1236 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1237 for i, c := range onehot[nzCount:] {
1238 if int(c/2)%stride == 0 {
1239 outcol := int(c/2)/stride*2 + int(c)%2
1240 mtxFull.Set(int(onehot[i]), outcol, 1)
1241 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1242 mtxTrain.Set(trainRow, outcol, 1)
1246 log.Print("fitting")
1247 transformer := nlp.NewPCA(cmd.pcaComponents)
1248 transformer.Fit(mtxTrain.T())
1249 log.Printf("transforming")
1250 pca, err := transformer.Transform(mtxFull.T())
1255 outrows, outcols := pca.Dims()
1256 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1257 out := make([]float64, outrows*outcols)
1258 for i := 0; i < outrows; i++ {
1259 for j := 0; j < outcols; j++ {
1260 out[i*outcols+j] = pca.At(i, j)
1263 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1264 log.Printf("writing numpy: %s", fnm)
1265 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1269 npw, err := gonpy.NewWriter(nopCloser{output})
1271 return fmt.Errorf("gonpy.NewWriter: %w", err)
1273 npw.Shape = []int{outrows, outcols}
1274 err = npw.WriteFloat64(out)
1276 return fmt.Errorf("WriteFloat64: %w", err)
1278 err = output.Close()
1284 samplesOutFilename := *outputDir + "/samples.csv"
1285 log.Infof("writing sample metadata to %s", samplesOutFilename)
1287 f, err = os.Create(samplesOutFilename)
1292 for i, si := range cmd.samples {
1296 } else if si.isControl {
1301 } else if si.isValidation {
1305 for c := 0; c < outcols; c++ {
1306 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1308 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1310 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1316 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1322 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1323 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1324 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1326 f, err = os.Create(tagoffsetFilename)
1331 for idx, offset := range chunkStartTag {
1332 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1334 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1340 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1348 type sampleInfo struct {
1354 pcaComponents []float64
1357 // Read samples.csv file with case/control and training/validation
1359 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1361 f, err := open(samplesFilename)
1365 buf, err := io.ReadAll(f)
1371 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1376 split := strings.Split(string(csv), ",")
1378 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1380 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1383 idx, err := strconv.Atoi(split[0])
1386 return nil, fmt.Errorf("header does not look right: %q", csv)
1388 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1391 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1393 var pcaComponents []float64
1395 for _, s := range split[4:] {
1396 f, err := strconv.ParseFloat(s, 64)
1398 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1400 pcaComponents = append(pcaComponents, f)
1403 si = append(si, sampleInfo{
1405 isCase: split[2] == "1",
1406 isControl: split[2] == "0",
1407 isTraining: split[3] == "1",
1408 isValidation: split[3] == "0",
1409 pcaComponents: pcaComponents,
1415 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1416 if cmd.chi2PValue >= 1 {
1419 col0 := make([]bool, 0, len(cmd.chi2Cases))
1420 col1 := make([]bool, 0, len(cmd.chi2Cases))
1421 cases := make([]bool, 0, len(cmd.chi2Cases))
1422 for i, c := range cmd.chi2Cases {
1423 if colpair[0][i] < 0 {
1426 col0 = append(col0, colpair[0][i] != 0)
1427 col1 = append(col1, colpair[1][i] != 0)
1428 cases = append(cases, c)
1430 return len(cases) >= cmd.minCoverage &&
1431 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1434 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1435 output, err := os.Create(fnm)
1439 defer output.Close()
1440 bufw := bufio.NewWriterSize(output, 1<<26)
1441 npw, err := gonpy.NewWriter(nopCloser{bufw})
1445 log.WithFields(log.Fields{
1449 "bytes": rows * cols * 4,
1450 }).Infof("writing numpy: %s", fnm)
1451 npw.Shape = []int{rows, cols}
1452 npw.WriteUint32(out)
1457 return output.Close()
1460 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1461 output, err := os.Create(fnm)
1465 defer output.Close()
1466 bufw := bufio.NewWriterSize(output, 1<<26)
1467 npw, err := gonpy.NewWriter(nopCloser{bufw})
1471 log.WithFields(log.Fields{
1475 "bytes": rows * cols * 4,
1476 }).Infof("writing numpy: %s", fnm)
1477 npw.Shape = []int{rows, cols}
1483 return output.Close()
1486 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1487 output, err := os.Create(fnm)
1491 defer output.Close()
1492 bufw := bufio.NewWriterSize(output, 1<<26)
1493 npw, err := gonpy.NewWriter(nopCloser{bufw})
1497 log.WithFields(log.Fields{
1501 "bytes": rows * cols * 2,
1502 }).Infof("writing numpy: %s", fnm)
1503 npw.Shape = []int{rows, cols}
1509 return output.Close()
1512 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1513 output, err := os.Create(fnm)
1517 defer output.Close()
1518 bufw := bufio.NewWriterSize(output, 1<<26)
1519 npw, err := gonpy.NewWriter(nopCloser{bufw})
1523 log.WithFields(log.Fields{
1527 "bytes": rows * cols,
1528 }).Infof("writing numpy: %s", fnm)
1529 npw.Shape = []int{rows, cols}
1535 return output.Close()
1538 func allele2homhet(colpair [2][]int8) {
1539 a, b := colpair[0], colpair[1]
1540 for i, av := range a {
1542 if av < 0 || bv < 0 {
1545 } else if av > 0 && bv > 0 {
1548 } else if av > 0 || bv > 0 {
1552 // ref (or a different variant in same position)
1553 // (this is a no-op) a[i], b[i] = 0, 0
1558 type onehotXref struct {
1560 variant tileVariantID
1565 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1567 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1568 // variants of a single tile/tag#.
1570 // Return nil if no tile variant passes Χ² filter.
1571 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1572 if tag == cmd.debugTag {
1573 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1574 for i, name := range cmd.cgnames {
1575 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1577 log.WithFields(logrus.Fields{
1578 "cgs[i].Variants[tag*2+j]": tv,
1582 "chunkstarttag": chunkstarttag,
1583 }).Info("tv2homhet()")
1585 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1586 // everyone has the most common variant (of the variants we don't drop)
1589 tagoffset := tag - chunkstarttag
1591 for _, cg := range cgs {
1593 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1594 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1602 if coverage < cmd.minCoverage {
1605 // "observed" array for p-value calculation (training set
1607 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1608 // one-hot output (all samples)
1609 outcols := make([][]int8, (maxv+1)*2)
1610 for i := range obs {
1611 obs[i] = make([]bool, cmd.trainingSetSize)
1612 outcols[i] = make([]int8, len(cmd.cgnames))
1614 for cgid, name := range cmd.cgnames {
1615 tsid := cmd.trainingSet[cgid]
1616 cgvars := cgs[name].Variants[tagoffset*2:]
1617 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1618 for v := tileVariantID(1); v <= maxv; v++ {
1619 if tv0 == v && tv1 == v {
1621 obs[v*2][tsid] = true
1623 outcols[v*2][cgid] = 1
1624 } else if tv0 == v || tv1 == v {
1626 obs[v*2+1][tsid] = true
1628 outcols[v*2+1][cgid] = 1
1633 var xref []onehotXref
1634 for col := 2; col < len(obs); col++ {
1635 // col 0,1 correspond to tile variant 0, i.e.,
1636 // no-call; col 2,3 correspond to the most common
1637 // variant; so we (normally) start at col 4.
1638 if col < 4 && !cmd.includeVariant1 {
1641 atomic.AddInt64(&cmd.pvalueCallCount, 1)
1642 p := cmd.pvalue(obs[col])
1643 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1646 onehot = append(onehot, outcols[col])
1647 xref = append(xref, onehotXref{
1649 variant: tileVariantID(col >> 1),
1657 // convert a []onehotXref with length N to a numpy-style []int32
1658 // matrix with N columns, one row per field of onehotXref struct.
1660 // Hom/het row contains hom=0, het=1.
1662 // P-value row contains 1000000x actual p-value.
1663 func onehotXref2int32(xrefs []onehotXref) []int32 {
1665 xdata := make([]int32, 5*xcols)
1666 for i, xref := range xrefs {
1667 xdata[i] = int32(xref.tag)
1668 xdata[xcols+i] = int32(xref.variant)
1670 xdata[xcols*2+i] = 1
1672 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1673 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1678 // transpose onehot data from in[col][row] to numpy-style
1679 // out[row*cols+col].
1680 func onehotcols2int8(in [][]int8) []int8 {
1686 out := make([]int8, rows*cols)
1687 for row := 0; row < rows; row++ {
1688 outrow := out[row*cols:]
1689 for col, incol := range in {
1690 outrow[col] = incol[row]
1696 // Return [2][]uint32{rowIndices, colIndices} indicating which
1697 // elements of matrixT[c][r] have non-zero values.
1698 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1700 for c, col := range matrixT {
1701 for r, val := range col {
1703 nz[0] = append(nz[0], uint32(r))
1704 nz[1] = append(nz[1], uint32(c))