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 } else if *caseControlOnly {
196 return fmt.Errorf("-case-control-only does not make sense without -samples")
201 err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
202 if len(ent.TagSet) > 0 {
205 for _, cseq := range ent.CompactSequences {
206 if cseq.Name == *ref || *ref == "" {
207 refseq = cseq.TileSequences
210 for _, cg := range ent.CompactGenomes {
211 if matchGenome.MatchString(cg.Name) {
212 cmd.cgnames = append(cmd.cgnames, cg.Name)
215 for _, tv := range ent.TileVariants {
217 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
227 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
230 if len(tagset) == 0 {
231 err = fmt.Errorf("tagset not found")
235 taglib := &tagLibrary{}
236 err = taglib.setTags(tagset)
240 taglen := taglib.TagLen()
241 sort.Strings(cmd.cgnames)
243 if len(cmd.cgnames) == 0 {
244 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
246 cmd.trainingSet = make([]int, len(cmd.cgnames))
247 if *samplesFilename == "" {
248 cmd.trainingSetSize = len(cmd.cgnames)
249 for i, name := range cmd.cgnames {
250 cmd.samples = append(cmd.samples, sampleInfo{
251 id: trimFilenameForLabel(name),
254 cmd.trainingSet[i] = i
256 } else if len(cmd.cgnames) != len(cmd.samples) {
257 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
259 for i, name := range cmd.cgnames {
260 if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
261 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
264 if *caseControlOnly {
265 for i := 0; i < len(cmd.samples); i++ {
266 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
267 if i+1 < len(cmd.samples) {
268 copy(cmd.samples[i:], cmd.samples[i+1:])
269 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
271 cmd.samples = cmd.samples[:len(cmd.samples)-1]
272 cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
278 cmd.trainingSetSize = 0
279 for i := range cmd.cgnames {
280 if cmd.samples[i].isTraining {
281 cmd.trainingSet[i] = cmd.trainingSetSize
282 cmd.trainingSetSize++
283 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
285 cmd.trainingSet[i] = -1
288 if cmd.pvalue == nil {
289 cmd.pvalue = func(onehot []bool) float64 {
290 return pvalue(onehot, cmd.chi2Cases)
294 if cmd.filter.MinCoverage == 1 {
295 // In the generic formula below, floating point
296 // arithmetic can effectively push the coverage
297 // threshold above 1.0, which is impossible/useless.
298 // 1.0 needs to mean exactly 100% coverage.
299 cmd.minCoverage = len(cmd.cgnames)
301 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
304 if len(cmd.samples[0].pcaComponents) > 0 {
305 cmd.pvalue = glmPvalueFunc(cmd.samples, cmd.pcaComponents)
306 // Unfortunately, statsmodel/glm lib logs stuff to
307 // os.Stdout when it panics on an unsolvable
308 // problem. We recover() from the panic in glm.go, but
309 // we also need to commandeer os.Stdout to avoid
310 // producing large quantities of logs.
311 stdoutWas := os.Stdout
312 defer func() { os.Stdout = stdoutWas }()
313 os.Stdout, err = os.Open(os.DevNull)
319 // cgnamemap[name]==true for samples that we are including in
321 cgnamemap := map[string]bool{}
322 for _, name := range cmd.cgnames {
323 cgnamemap[name] = true
326 err = writeSampleInfo(cmd.samples, *outputDir)
331 log.Info("indexing reference tiles")
332 type reftileinfo struct {
333 variant tileVariantID
334 seqname string // chr1
335 pos int // distance from start of chromosome to starttag
336 tiledata []byte // acgtggcaa...
337 excluded bool // true if excluded by regions file
338 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
340 isdup := map[tagID]bool{}
341 reftile := map[tagID]*reftileinfo{}
342 for seqname, cseq := range refseq {
344 lastreftag := tagID(-1)
345 for _, libref := range cseq {
346 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
349 tiledata := reftiledata[libref]
350 if len(tiledata) == 0 {
351 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
354 foundthistag := false
355 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
356 if !foundthistag && tagid == libref.Tag {
360 if dupref, ok := reftile[tagid]; ok {
361 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)
362 delete(reftile, tagid)
364 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
368 if isdup[libref.Tag] {
369 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
370 } else if reftile[libref.Tag] != nil {
371 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)
372 delete(reftile, libref.Tag)
373 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
374 isdup[libref.Tag] = true
376 reftile[libref.Tag] = &reftileinfo{
378 variant: libref.Variant,
384 reftile[lastreftag].nexttag = libref.Tag
386 lastreftag = libref.Tag
388 pos += len(tiledata) - taglen
390 log.Printf("... %s done, len %d", seqname, pos+taglen)
394 if *regionsFilename != "" {
395 log.Printf("loading regions from %s", *regionsFilename)
396 mask, err = makeMask(*regionsFilename, *expandRegions)
400 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
401 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
402 for _, rt := range reftile {
403 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
407 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
410 type hgvsColSet map[hgvs.Variant][2][]int8
411 encodeHGVS := throttle{Max: len(refseq)}
412 encodeHGVSTodo := map[string]chan hgvsColSet{}
413 tmpHGVSCols := map[string]*os.File{}
415 for seqname := range refseq {
417 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
421 defer os.Remove(f.Name())
422 bufw := bufio.NewWriterSize(f, 1<<24)
423 enc := gob.NewEncoder(bufw)
424 tmpHGVSCols[seqname] = f
425 todo := make(chan hgvsColSet, 128)
426 encodeHGVSTodo[seqname] = todo
427 encodeHGVS.Go(func() error {
428 for colset := range todo {
429 err := enc.Encode(colset)
431 encodeHGVS.Report(err)
442 var toMerge [][]int16
443 if *mergeOutput || *hgvsSingle {
444 toMerge = make([][]int16, len(infiles))
446 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
447 var onehotChunkSize []uint32
448 var onehotXrefs [][]onehotXref
449 if *onehotSingle || *onlyPCA {
450 onehotIndirect = make([][2][]uint32, len(infiles))
451 onehotChunkSize = make([]uint32, len(infiles))
452 onehotXrefs = make([][]onehotXref, len(infiles))
454 chunkStartTag := make([]tagID, len(infiles))
456 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
457 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
458 log.Info("generating annotations and numpy matrix for each slice")
459 var errSkip = errors.New("skip infile")
461 for infileIdx, infile := range infiles {
462 infileIdx, infile := infileIdx, infile
463 throttleMem.Go(func() error {
464 seq := make(map[tagID][]TileVariant, 50000)
465 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
466 f, err := open(infile)
471 log.Infof("%04d: reading %s", infileIdx, infile)
472 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
473 for _, tv := range ent.TileVariants {
478 // corresponding ref tile, if
479 // mask is in play (we can't
480 // determine coordinates for
482 if mask != nil && reftile[tv.Tag] == nil {
486 // corresponding ref tile is
487 // outside target regions --
488 // unless it's a potential
490 if mask != nil && reftile[tv.Tag].excluded &&
491 (int(tv.Tag+1) >= len(tagset) ||
492 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
495 if tv.Tag == cmd.debugTag {
496 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
498 variants := seq[tv.Tag]
499 if len(variants) == 0 {
500 variants = make([]TileVariant, 100)
502 for len(variants) <= int(tv.Variant) {
503 variants = append(variants, TileVariant{})
505 variants[int(tv.Variant)] = tv
506 seq[tv.Tag] = variants
508 for _, cg := range ent.CompactGenomes {
509 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
512 if !cgnamemap[cg.Name] {
515 // pad to full slice size
516 // to avoid out-of-bounds
518 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
519 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
527 } else if err != nil {
528 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
530 tagstart := cgs[cmd.cgnames[0]].StartTag
531 tagend := cgs[cmd.cgnames[0]].EndTag
532 chunkStartTag[infileIdx] = tagstart
536 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
537 variantRemap := make([][]tileVariantID, tagend-tagstart)
538 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
539 for tag, variants := range seq {
540 tag, variants := tag, variants
541 throttleCPU.Go(func() error {
543 count := make(map[[blake2b.Size256]byte]int, len(variants))
547 count[blake2b.Sum256(rt.tiledata)] = 0
550 for cgname, cg := range cgs {
551 idx := int(tag-tagstart) * 2
552 for allele := 0; allele < 2; allele++ {
553 v := cg.Variants[idx+allele]
554 if v > 0 && len(variants[v].Sequence) > 0 {
555 count[variants[v].Blake2b]++
558 if v > 0 && tag == cmd.debugTag {
559 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])
563 if alleleCoverage < cmd.minCoverage*2 {
564 idx := int(tag-tagstart) * 2
565 for _, cg := range cgs {
567 cg.Variants[idx+1] = 0
569 if tag == cmd.debugTag {
570 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
575 // hash[i] will be the hash of
576 // the variant(s) that should
577 // be at rank i (0-based).
578 hash := make([][blake2b.Size256]byte, 0, len(count))
579 for b := range count {
580 hash = append(hash, b)
582 sort.Slice(hash, func(i, j int) bool {
583 bi, bj := &hash[i], &hash[j]
584 if ci, cj := count[*bi], count[*bj]; ci != cj {
587 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
590 // rank[b] will be the 1-based
591 // new variant number for
592 // variants whose hash is b.
593 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
594 for i, h := range hash {
595 rank[h] = tileVariantID(i + 1)
597 if tag == cmd.debugTag {
598 for h, r := range rank {
599 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
602 // remap[v] will be the new
603 // variant number for original
605 remap := make([]tileVariantID, len(variants))
606 for i, tv := range variants {
607 remap[i] = rank[tv.Blake2b]
609 if tag == cmd.debugTag {
610 for in, out := range remap {
612 log.Printf("tag %d remap %d => %d", tag, in, out)
616 variantRemap[tag-tagstart] = remap
618 refrank := rank[blake2b.Sum256(rt.tiledata)]
619 if tag == cmd.debugTag {
620 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
629 var onehotChunk [][]int8
630 var onehotXref []onehotXref
632 var annotationsFilename string
634 annotationsFilename = "/dev/null"
636 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
637 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
639 annof, err := os.Create(annotationsFilename)
643 annow := bufio.NewWriterSize(annof, 1<<20)
645 for tag := tagstart; tag < tagend; tag++ {
647 if rt == nil && mask != nil {
648 // With no ref tile, we don't
649 // have coordinates to say
650 // this is in the desired
651 // regions -- so it's not.
652 // TODO: handle ref spanning
656 if rt != nil && rt.excluded {
657 // TODO: don't skip yet --
658 // first check for spanning
659 // tile variants that
660 // intersect non-excluded ref
664 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
667 remap := variantRemap[tag-tagstart]
669 // was not assigned above,
670 // because minCoverage
674 maxv := tileVariantID(0)
675 for _, v := range remap {
680 if *onehotChunked || *onehotSingle || *onlyPCA {
681 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
682 if tag == cmd.debugTag {
683 log.WithFields(logrus.Fields{
686 }).Info("tv2homhet()")
688 onehotChunk = append(onehotChunk, onehot...)
689 onehotXref = append(onehotXref, xrefs...)
696 // Reference does not use any
697 // variant of this tile
699 // TODO: diff against the
700 // relevant portion of the
701 // ref's spanning tile
705 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
707 reftilestr := strings.ToUpper(string(rt.tiledata))
709 done := make([]bool, maxv+1)
710 variantDiffs := make([][]hgvs.Variant, maxv+1)
711 for v, tv := range variants {
713 if v == 0 || v == rt.variant || done[v] {
718 if len(tv.Sequence) < taglen {
721 // if reftilestr doesn't end
722 // in the same tag as tv,
723 // extend reftilestr with
724 // following ref tiles until
725 // it does (up to an arbitrary
726 // sanity-check limit)
727 reftilestr := reftilestr
728 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
729 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
730 rt = reftile[rt.nexttag]
734 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
736 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
739 if !strings.HasSuffix(reftilestr, endtagstr) {
740 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
743 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
744 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
747 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
748 for i := range diffs {
749 diffs[i].Position += rt.pos
751 for _, diff := range diffs {
752 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)
755 variantDiffs[v] = diffs
759 // We can now determine, for each HGVS
760 // variant (diff) in this reftile
761 // region, whether a given genome
762 // phase/allele (1) has the variant, (0) has
763 // =ref or a different variant in that
764 // position, or (-1) is lacking
765 // coverage / couldn't be diffed.
766 hgvsCol := hgvsColSet{}
767 for _, diffs := range variantDiffs {
768 for _, diff := range diffs {
769 if _, ok := hgvsCol[diff]; ok {
772 hgvsCol[diff] = [2][]int8{
773 make([]int8, len(cmd.cgnames)),
774 make([]int8, len(cmd.cgnames)),
778 for row, name := range cmd.cgnames {
779 variants := cgs[name].Variants[(tag-tagstart)*2:]
780 for ph := 0; ph < 2; ph++ {
782 if int(v) >= len(remap) {
788 // hgvsCol[*][ph][row] is already 0
789 } else if len(variantDiffs[v]) == 0 {
790 // lacking coverage / couldn't be diffed
791 for _, col := range hgvsCol {
795 for _, diff := range variantDiffs[v] {
796 hgvsCol[diff][ph][row] = 1
801 for diff, colpair := range hgvsCol {
802 allele2homhet(colpair)
803 if !cmd.filterHGVScolpair(colpair) {
804 delete(hgvsCol, diff)
807 if len(hgvsCol) > 0 {
808 encodeHGVSTodo[rt.seqname] <- hgvsCol
823 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
824 rows := len(cmd.cgnames)
825 cols := len(onehotChunk)
826 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
827 throttleNumpyMem.Acquire()
828 out := onehotcols2int8(onehotChunk)
829 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
830 err = writeNumpyInt8(fnm, out, rows, cols)
834 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
835 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
840 throttleNumpyMem.Release()
842 if *onehotSingle || *onlyPCA {
843 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
844 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
845 onehotXrefs[infileIdx] = onehotXref
846 n := len(onehotIndirect[infileIdx][0])
847 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
849 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
850 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
851 throttleNumpyMem.Acquire()
852 rows := len(cmd.cgnames)
854 out := make([]int16, rows*cols)
855 for row, name := range cmd.cgnames {
857 for col, v := range cgs[name].Variants {
858 tag := tagstart + tagID(col/2)
859 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
862 if rt := reftile[tag]; rt == nil || rt.excluded {
866 out[outidx] = 0 // tag not found / spanning tile
867 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
868 out[outidx] = int16(variantRemap[tag-tagstart][v])
870 out[outidx] = -1 // low quality tile variant
872 if tag == cmd.debugTag {
873 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
881 throttleNumpyMem.Release()
882 if *mergeOutput || *hgvsSingle {
883 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
884 toMerge[infileIdx] = out
886 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
887 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
888 err = writeNumpyInt16(fnm, out, rows, cols)
895 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
899 if err = throttleMem.Wait(); err != nil {
904 log.Info("flushing hgvsCols temp files")
905 for seqname := range refseq {
906 close(encodeHGVSTodo[seqname])
908 err = encodeHGVS.Wait()
912 for seqname := range refseq {
913 log.Infof("%s: reading hgvsCols from temp file", seqname)
914 f := tmpHGVSCols[seqname]
915 _, err = f.Seek(0, io.SeekStart)
919 var hgvsCols hgvsColSet
920 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
922 err = dec.Decode(&hgvsCols)
927 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
928 variants := make([]hgvs.Variant, 0, len(hgvsCols))
929 for v := range hgvsCols {
930 variants = append(variants, v)
932 sort.Slice(variants, func(i, j int) bool {
933 vi, vj := &variants[i], &variants[j]
934 if vi.Position != vj.Position {
935 return vi.Position < vj.Position
936 } else if vi.Ref != vj.Ref {
937 return vi.Ref < vj.Ref
939 return vi.New < vj.New
942 rows := len(cmd.cgnames)
943 cols := len(variants) * 2
944 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
945 out := make([]int8, rows*cols)
946 for varIdx, variant := range variants {
947 hgvsCols := hgvsCols[variant]
948 for row := range cmd.cgnames {
949 for ph := 0; ph < 2; ph++ {
950 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
954 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
960 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
961 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
962 var hgvsLabels bytes.Buffer
963 for varIdx, variant := range variants {
964 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
966 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
973 if *mergeOutput || *hgvsSingle {
974 var annow *bufio.Writer
977 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
978 annof, err = os.Create(annoFilename)
982 annow = bufio.NewWriterSize(annof, 1<<20)
985 rows := len(cmd.cgnames)
987 for _, chunk := range toMerge {
988 cols += len(chunk) / rows
990 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
993 out = make([]int16, rows*cols)
995 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
997 for outIdx, chunk := range toMerge {
998 chunkcols := len(chunk) / rows
1000 for row := 0; row < rows; row++ {
1001 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1004 toMerge[outIdx] = nil
1006 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1007 log.Infof("reading %s", annotationsFilename)
1008 buf, err := os.ReadFile(annotationsFilename)
1013 err = os.Remove(annotationsFilename)
1018 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1022 fields := bytes.SplitN(line, []byte{','}, 9)
1023 tag, _ := strconv.Atoi(string(fields[0]))
1024 incol, _ := strconv.Atoi(string(fields[1]))
1025 tileVariant, _ := strconv.Atoi(string(fields[2]))
1026 hgvsID := string(fields[3])
1027 seqname := string(fields[4])
1028 pos, _ := strconv.Atoi(string(fields[5]))
1031 // Null entry for un-diffable
1036 // Null entry for ref tile
1039 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1040 // The tile intersects one of
1041 // the selected regions, but
1042 // this particular HGVS
1043 // variant does not.
1046 hgvsColPair := hgvsCols[hgvsID]
1047 if hgvsColPair[0] == nil {
1048 // values in new columns start
1049 // out as -1 ("no data yet")
1050 // or 0 ("=ref") here, may
1051 // change to 1 ("hgvs variant
1052 // present") below, either on
1053 // this line or a future line.
1054 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1055 rt, ok := reftile[tagID(tag)]
1057 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1060 for ph := 0; ph < 2; ph++ {
1061 for row := 0; row < rows; row++ {
1062 v := chunk[row*chunkcols+incol*2+ph]
1063 if tileVariantID(v) == rt.variant {
1064 hgvsColPair[ph][row] = 0
1066 hgvsColPair[ph][row] = -1
1070 hgvsCols[hgvsID] = hgvsColPair
1072 hgvsref := hgvs.Variant{
1074 Ref: string(refseq),
1075 New: string(refseq),
1077 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])
1081 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])
1083 for ph := 0; ph < 2; ph++ {
1084 for row := 0; row < rows; row++ {
1085 v := chunk[row*chunkcols+incol*2+ph]
1086 if int(v) == tileVariant {
1087 hgvsColPair[ph][row] = 1
1093 startcol += chunkcols
1104 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1112 cols = len(hgvsCols) * 2
1113 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1114 out = make([]int16, rows*cols)
1115 hgvsIDs := make([]string, 0, cols/2)
1116 for hgvsID := range hgvsCols {
1117 hgvsIDs = append(hgvsIDs, hgvsID)
1119 sort.Strings(hgvsIDs)
1120 var hgvsLabels bytes.Buffer
1121 for idx, hgvsID := range hgvsIDs {
1122 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1123 for ph := 0; ph < 2; ph++ {
1124 hgvscol := hgvsCols[hgvsID][ph]
1125 for row, val := range hgvscol {
1126 out[row*cols+idx*2+ph] = val
1130 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1135 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1136 log.Printf("writing hgvs labels: %s", fnm)
1137 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1143 if *onehotSingle || *onlyPCA {
1145 for _, part := range onehotIndirect {
1146 nzCount += len(part[0])
1148 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1149 var xrefs []onehotXref
1150 chunkOffset := uint32(0)
1152 for i, part := range onehotIndirect {
1153 for i := range part[1] {
1154 part[1][i] += chunkOffset
1156 copy(onehot[outcol:], part[0])
1157 copy(onehot[outcol+nzCount:], part[1])
1158 xrefs = append(xrefs, onehotXrefs[i]...)
1160 outcol += len(part[0])
1161 chunkOffset += onehotChunkSize[i]
1165 onehotXrefs[i] = nil
1166 debug.FreeOSMemory()
1169 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1170 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1174 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1175 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1179 fnm = fmt.Sprintf("%s/stats.json", *outputDir)
1180 j, err := json.Marshal(map[string]interface{}{
1181 "pvalueCallCount": cmd.pvalueCallCount,
1186 err = os.WriteFile(fnm, j, 0777)
1193 for _, c := range onehot[nzCount:] {
1199 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1201 log.Printf("have %d one-hot cols", cols)
1203 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1204 cols = (cols + 1) / 2
1208 // we work with pairs of columns
1211 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1212 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1213 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1214 for i, c := range onehot[nzCount:] {
1215 if int(c/2)%stride == 0 {
1216 outcol := int(c/2)/stride*2 + int(c)%2
1217 mtxFull.Set(int(onehot[i]), outcol, 1)
1218 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1219 mtxTrain.Set(trainRow, outcol, 1)
1223 log.Print("fitting")
1224 transformer := nlp.NewPCA(cmd.pcaComponents)
1225 transformer.Fit(mtxTrain.T())
1226 log.Printf("transforming")
1227 pca, err := transformer.Transform(mtxFull.T())
1232 outrows, outcols := pca.Dims()
1233 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1234 out := make([]float64, outrows*outcols)
1235 for i := 0; i < outrows; i++ {
1236 for j := 0; j < outcols; j++ {
1237 out[i*outcols+j] = pca.At(i, j)
1240 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1241 log.Printf("writing numpy: %s", fnm)
1242 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1246 npw, err := gonpy.NewWriter(nopCloser{output})
1248 return fmt.Errorf("gonpy.NewWriter: %w", err)
1250 npw.Shape = []int{outrows, outcols}
1251 err = npw.WriteFloat64(out)
1253 return fmt.Errorf("WriteFloat64: %w", err)
1255 err = output.Close()
1261 log.Print("copying pca components to sampleInfo")
1262 for i := range cmd.samples {
1263 cmd.samples[i].pcaComponents = make([]float64, outcols)
1264 for c := 0; c < outcols; c++ {
1265 cmd.samples[i].pcaComponents[i] = pca.At(i, c)
1270 err = writeSampleInfo(cmd.samples, *outputDir)
1276 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1277 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1278 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1280 f, err = os.Create(tagoffsetFilename)
1285 for idx, offset := range chunkStartTag {
1286 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1288 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1294 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1302 type sampleInfo struct {
1308 pcaComponents []float64
1311 // Read samples.csv file with case/control and training/validation
1313 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1315 f, err := open(samplesFilename)
1319 buf, err := io.ReadAll(f)
1325 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1330 split := strings.Split(string(csv), ",")
1332 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1334 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1337 idx, err := strconv.Atoi(split[0])
1340 return nil, fmt.Errorf("header does not look right: %q", csv)
1342 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1345 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1347 var pcaComponents []float64
1349 for _, s := range split[4:] {
1350 f, err := strconv.ParseFloat(s, 64)
1352 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1354 pcaComponents = append(pcaComponents, f)
1357 si = append(si, sampleInfo{
1359 isCase: split[2] == "1",
1360 isControl: split[2] == "0",
1361 isTraining: split[3] == "1",
1362 isValidation: split[3] == "0" && len(split[2]) > 0, // fix errant 0s in input
1363 pcaComponents: pcaComponents,
1369 func writeSampleInfo(samples []sampleInfo, outputDir string) error {
1370 fnm := outputDir + "/samples.csv"
1371 log.Infof("writing sample metadata to %s", fnm)
1372 f, err := os.Create(fnm)
1378 if len(samples) > 0 {
1379 for i := range samples[0].pcaComponents {
1380 pcaLabels += fmt.Sprintf(",PCA%d", i)
1383 _, err = fmt.Fprintf(f, "Index,SampleID,CaseControl,TrainingValidation%s\n", pcaLabels)
1387 for i, si := range samples {
1391 } else if si.isControl {
1396 } else if si.isValidation {
1400 for _, pcaval := range si.pcaComponents {
1401 pcavals += fmt.Sprintf(",%f", pcaval)
1403 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1405 return fmt.Errorf("write %s: %w", fnm, err)
1410 return fmt.Errorf("close %s: %w", fnm, err)
1416 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1417 if cmd.chi2PValue >= 1 {
1420 col0 := make([]bool, 0, len(cmd.chi2Cases))
1421 col1 := make([]bool, 0, len(cmd.chi2Cases))
1422 cases := make([]bool, 0, len(cmd.chi2Cases))
1423 for i, c := range cmd.chi2Cases {
1424 if colpair[0][i] < 0 {
1427 col0 = append(col0, colpair[0][i] != 0)
1428 col1 = append(col1, colpair[1][i] != 0)
1429 cases = append(cases, c)
1431 return len(cases) >= cmd.minCoverage &&
1432 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1435 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1436 output, err := os.Create(fnm)
1440 defer output.Close()
1441 bufw := bufio.NewWriterSize(output, 1<<26)
1442 npw, err := gonpy.NewWriter(nopCloser{bufw})
1446 log.WithFields(log.Fields{
1450 "bytes": rows * cols * 4,
1451 }).Infof("writing numpy: %s", fnm)
1452 npw.Shape = []int{rows, cols}
1453 npw.WriteUint32(out)
1458 return output.Close()
1461 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1462 output, err := os.Create(fnm)
1466 defer output.Close()
1467 bufw := bufio.NewWriterSize(output, 1<<26)
1468 npw, err := gonpy.NewWriter(nopCloser{bufw})
1472 log.WithFields(log.Fields{
1476 "bytes": rows * cols * 4,
1477 }).Infof("writing numpy: %s", fnm)
1478 npw.Shape = []int{rows, cols}
1484 return output.Close()
1487 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1488 output, err := os.Create(fnm)
1492 defer output.Close()
1493 bufw := bufio.NewWriterSize(output, 1<<26)
1494 npw, err := gonpy.NewWriter(nopCloser{bufw})
1498 log.WithFields(log.Fields{
1502 "bytes": rows * cols * 2,
1503 }).Infof("writing numpy: %s", fnm)
1504 npw.Shape = []int{rows, cols}
1510 return output.Close()
1513 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1514 output, err := os.Create(fnm)
1518 defer output.Close()
1519 bufw := bufio.NewWriterSize(output, 1<<26)
1520 npw, err := gonpy.NewWriter(nopCloser{bufw})
1524 log.WithFields(log.Fields{
1528 "bytes": rows * cols,
1529 }).Infof("writing numpy: %s", fnm)
1530 npw.Shape = []int{rows, cols}
1536 return output.Close()
1539 func allele2homhet(colpair [2][]int8) {
1540 a, b := colpair[0], colpair[1]
1541 for i, av := range a {
1543 if av < 0 || bv < 0 {
1546 } else if av > 0 && bv > 0 {
1549 } else if av > 0 || bv > 0 {
1553 // ref (or a different variant in same position)
1554 // (this is a no-op) a[i], b[i] = 0, 0
1559 type onehotXref struct {
1561 variant tileVariantID
1566 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1568 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1569 // variants of a single tile/tag#.
1571 // Return nil if no tile variant passes Χ² filter.
1572 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1573 if tag == cmd.debugTag {
1574 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1575 for i, name := range cmd.cgnames {
1576 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1578 log.WithFields(logrus.Fields{
1579 "cgs[i].Variants[tag*2+j]": tv,
1583 "chunkstarttag": chunkstarttag,
1584 }).Info("tv2homhet()")
1586 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1587 // everyone has the most common variant (of the variants we don't drop)
1590 tagoffset := tag - chunkstarttag
1592 for _, cg := range cgs {
1594 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1595 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1603 if coverage < cmd.minCoverage {
1606 // "observed" array for p-value calculation (training set
1608 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1609 // one-hot output (all samples)
1610 outcols := make([][]int8, (maxv+1)*2)
1611 for i := range obs {
1612 obs[i] = make([]bool, cmd.trainingSetSize)
1613 outcols[i] = make([]int8, len(cmd.cgnames))
1615 for cgid, name := range cmd.cgnames {
1616 tsid := cmd.trainingSet[cgid]
1617 cgvars := cgs[name].Variants[tagoffset*2:]
1618 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1619 for v := tileVariantID(1); v <= maxv; v++ {
1620 if tv0 == v && tv1 == v {
1622 obs[v*2][tsid] = true
1624 outcols[v*2][cgid] = 1
1625 } else if tv0 == v || tv1 == v {
1627 obs[v*2+1][tsid] = true
1629 outcols[v*2+1][cgid] = 1
1634 var xref []onehotXref
1635 for col := 2; col < len(obs); col++ {
1636 // col 0,1 correspond to tile variant 0, i.e.,
1637 // no-call; col 2,3 correspond to the most common
1638 // variant; so we (normally) start at col 4.
1639 if col < 4 && !cmd.includeVariant1 {
1642 atomic.AddInt64(&cmd.pvalueCallCount, 1)
1643 p := cmd.pvalue(obs[col])
1644 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1647 onehot = append(onehot, outcols[col])
1648 xref = append(xref, onehotXref{
1650 variant: tileVariantID(col >> 1),
1658 // convert a []onehotXref with length N to a numpy-style []int32
1659 // matrix with N columns, one row per field of onehotXref struct.
1661 // Hom/het row contains hom=0, het=1.
1663 // P-value row contains 1000000x actual p-value.
1664 func onehotXref2int32(xrefs []onehotXref) []int32 {
1666 xdata := make([]int32, 5*xcols)
1667 for i, xref := range xrefs {
1668 xdata[i] = int32(xref.tag)
1669 xdata[xcols+i] = int32(xref.variant)
1671 xdata[xcols*2+i] = 1
1673 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1674 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1679 // transpose onehot data from in[col][row] to numpy-style
1680 // out[row*cols+col].
1681 func onehotcols2int8(in [][]int8) []int8 {
1687 out := make([]int8, rows*cols)
1688 for row := 0; row < rows; row++ {
1689 outrow := out[row*cols:]
1690 for col, incol := range in {
1691 outrow[col] = incol[row]
1697 // Return [2][]uint32{rowIndices, colIndices} indicating which
1698 // elements of matrixT[c][r] have non-zero values.
1699 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1701 for c, col := range matrixT {
1702 for r, val := range col {
1704 nz[0] = append(nz[0], uint32(r))
1705 nz[1] = append(nz[1], uint32(c))