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))))
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
327 samplesOutFilename := *outputDir + "/samples.csv"
328 log.Infof("writing sample metadata to %s", samplesOutFilename)
330 f, err = os.Create(samplesOutFilename)
335 for i, si := range cmd.samples {
339 } else if si.isControl {
347 _, err = fmt.Fprintf(f, "%d,%s,%s,%s\n", i, si.id, cc, tv)
349 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
355 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
361 log.Info("indexing reference tiles")
362 type reftileinfo struct {
363 variant tileVariantID
364 seqname string // chr1
365 pos int // distance from start of chromosome to starttag
366 tiledata []byte // acgtggcaa...
367 excluded bool // true if excluded by regions file
368 nexttag tagID // tagID of following tile (-1 for last tag of chromosome)
370 isdup := map[tagID]bool{}
371 reftile := map[tagID]*reftileinfo{}
372 for seqname, cseq := range refseq {
374 lastreftag := tagID(-1)
375 for _, libref := range cseq {
376 if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
379 tiledata := reftiledata[libref]
380 if len(tiledata) == 0 {
381 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
384 foundthistag := false
385 taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
386 if !foundthistag && tagid == libref.Tag {
390 if dupref, ok := reftile[tagid]; ok {
391 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)
392 delete(reftile, tagid)
394 log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
398 if isdup[libref.Tag] {
399 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
400 } else if reftile[libref.Tag] != nil {
401 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)
402 delete(reftile, libref.Tag)
403 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
404 isdup[libref.Tag] = true
406 reftile[libref.Tag] = &reftileinfo{
408 variant: libref.Variant,
414 reftile[lastreftag].nexttag = libref.Tag
416 lastreftag = libref.Tag
418 pos += len(tiledata) - taglen
420 log.Printf("... %s done, len %d", seqname, pos+taglen)
424 if *regionsFilename != "" {
425 log.Printf("loading regions from %s", *regionsFilename)
426 mask, err = makeMask(*regionsFilename, *expandRegions)
430 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
431 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
432 for _, rt := range reftile {
433 if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
437 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
440 type hgvsColSet map[hgvs.Variant][2][]int8
441 encodeHGVS := throttle{Max: len(refseq)}
442 encodeHGVSTodo := map[string]chan hgvsColSet{}
443 tmpHGVSCols := map[string]*os.File{}
445 for seqname := range refseq {
447 f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
451 defer os.Remove(f.Name())
452 bufw := bufio.NewWriterSize(f, 1<<24)
453 enc := gob.NewEncoder(bufw)
454 tmpHGVSCols[seqname] = f
455 todo := make(chan hgvsColSet, 128)
456 encodeHGVSTodo[seqname] = todo
457 encodeHGVS.Go(func() error {
458 for colset := range todo {
459 err := enc.Encode(colset)
461 encodeHGVS.Report(err)
472 var toMerge [][]int16
473 if *mergeOutput || *hgvsSingle {
474 toMerge = make([][]int16, len(infiles))
476 var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
477 var onehotChunkSize []uint32
478 var onehotXrefs [][]onehotXref
479 if *onehotSingle || *onlyPCA {
480 onehotIndirect = make([][2][]uint32, len(infiles))
481 onehotChunkSize = make([]uint32, len(infiles))
482 onehotXrefs = make([][]onehotXref, len(infiles))
484 chunkStartTag := make([]tagID, len(infiles))
486 throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
487 throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
488 log.Info("generating annotations and numpy matrix for each slice")
489 var errSkip = errors.New("skip infile")
491 for infileIdx, infile := range infiles {
492 infileIdx, infile := infileIdx, infile
493 throttleMem.Go(func() error {
494 seq := make(map[tagID][]TileVariant, 50000)
495 cgs := make(map[string]CompactGenome, len(cmd.cgnames))
496 f, err := open(infile)
501 log.Infof("%04d: reading %s", infileIdx, infile)
502 err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
503 for _, tv := range ent.TileVariants {
508 // corresponding ref tile, if
509 // mask is in play (we can't
510 // determine coordinates for
512 if mask != nil && reftile[tv.Tag] == nil {
516 // corresponding ref tile is
517 // outside target regions --
518 // unless it's a potential
520 if mask != nil && reftile[tv.Tag].excluded &&
521 (int(tv.Tag+1) >= len(tagset) ||
522 (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
525 if tv.Tag == cmd.debugTag {
526 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
528 variants := seq[tv.Tag]
529 if len(variants) == 0 {
530 variants = make([]TileVariant, 100)
532 for len(variants) <= int(tv.Variant) {
533 variants = append(variants, TileVariant{})
535 variants[int(tv.Variant)] = tv
536 seq[tv.Tag] = variants
538 for _, cg := range ent.CompactGenomes {
539 if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
542 if !cgnamemap[cg.Name] {
545 // pad to full slice size
546 // to avoid out-of-bounds
548 if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
549 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
557 } else if err != nil {
558 return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
560 tagstart := cgs[cmd.cgnames[0]].StartTag
561 tagend := cgs[cmd.cgnames[0]].EndTag
562 chunkStartTag[infileIdx] = tagstart
566 log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
567 variantRemap := make([][]tileVariantID, tagend-tagstart)
568 throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
569 for tag, variants := range seq {
570 tag, variants := tag, variants
571 throttleCPU.Go(func() error {
573 count := make(map[[blake2b.Size256]byte]int, len(variants))
577 count[blake2b.Sum256(rt.tiledata)] = 0
580 for cgname, cg := range cgs {
581 idx := int(tag-tagstart) * 2
582 for allele := 0; allele < 2; allele++ {
583 v := cg.Variants[idx+allele]
584 if v > 0 && len(variants[v].Sequence) > 0 {
585 count[variants[v].Blake2b]++
588 if v > 0 && tag == cmd.debugTag {
589 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])
593 if alleleCoverage < cmd.minCoverage*2 {
594 idx := int(tag-tagstart) * 2
595 for _, cg := range cgs {
597 cg.Variants[idx+1] = 0
599 if tag == cmd.debugTag {
600 log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
605 // hash[i] will be the hash of
606 // the variant(s) that should
607 // be at rank i (0-based).
608 hash := make([][blake2b.Size256]byte, 0, len(count))
609 for b := range count {
610 hash = append(hash, b)
612 sort.Slice(hash, func(i, j int) bool {
613 bi, bj := &hash[i], &hash[j]
614 if ci, cj := count[*bi], count[*bj]; ci != cj {
617 return bytes.Compare((*bi)[:], (*bj)[:]) < 0
620 // rank[b] will be the 1-based
621 // new variant number for
622 // variants whose hash is b.
623 rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
624 for i, h := range hash {
625 rank[h] = tileVariantID(i + 1)
627 if tag == cmd.debugTag {
628 for h, r := range rank {
629 log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
632 // remap[v] will be the new
633 // variant number for original
635 remap := make([]tileVariantID, len(variants))
636 for i, tv := range variants {
637 remap[i] = rank[tv.Blake2b]
639 if tag == cmd.debugTag {
640 for in, out := range remap {
642 log.Printf("tag %d remap %d => %d", tag, in, out)
646 variantRemap[tag-tagstart] = remap
648 refrank := rank[blake2b.Sum256(rt.tiledata)]
649 if tag == cmd.debugTag {
650 log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
659 var onehotChunk [][]int8
660 var onehotXref []onehotXref
662 var annotationsFilename string
664 annotationsFilename = "/dev/null"
666 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
667 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
669 annof, err := os.Create(annotationsFilename)
673 annow := bufio.NewWriterSize(annof, 1<<20)
675 for tag := tagstart; tag < tagend; tag++ {
677 if rt == nil && mask != nil {
678 // With no ref tile, we don't
679 // have coordinates to say
680 // this is in the desired
681 // regions -- so it's not.
682 // TODO: handle ref spanning
686 if rt != nil && rt.excluded {
687 // TODO: don't skip yet --
688 // first check for spanning
689 // tile variants that
690 // intersect non-excluded ref
694 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
697 remap := variantRemap[tag-tagstart]
699 // was not assigned above,
700 // because minCoverage
704 maxv := tileVariantID(0)
705 for _, v := range remap {
710 if *onehotChunked || *onehotSingle || *onlyPCA {
711 onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
712 if tag == cmd.debugTag {
713 log.WithFields(logrus.Fields{
716 }).Info("tv2homhet()")
718 onehotChunk = append(onehotChunk, onehot...)
719 onehotXref = append(onehotXref, xrefs...)
726 // Reference does not use any
727 // variant of this tile
729 // TODO: diff against the
730 // relevant portion of the
731 // ref's spanning tile
735 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
737 reftilestr := strings.ToUpper(string(rt.tiledata))
739 done := make([]bool, maxv+1)
740 variantDiffs := make([][]hgvs.Variant, maxv+1)
741 for v, tv := range variants {
743 if v == 0 || v == rt.variant || done[v] {
748 if len(tv.Sequence) < taglen {
751 // if reftilestr doesn't end
752 // in the same tag as tv,
753 // extend reftilestr with
754 // following ref tiles until
755 // it does (up to an arbitrary
756 // sanity-check limit)
757 reftilestr := reftilestr
758 endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
759 for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
760 rt = reftile[rt.nexttag]
764 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
766 if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
769 if !strings.HasSuffix(reftilestr, endtagstr) {
770 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
773 if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
774 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
777 diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
778 for i := range diffs {
779 diffs[i].Position += rt.pos
781 for _, diff := range diffs {
782 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)
785 variantDiffs[v] = diffs
789 // We can now determine, for each HGVS
790 // variant (diff) in this reftile
791 // region, whether a given genome
792 // phase/allele (1) has the variant, (0) has
793 // =ref or a different variant in that
794 // position, or (-1) is lacking
795 // coverage / couldn't be diffed.
796 hgvsCol := hgvsColSet{}
797 for _, diffs := range variantDiffs {
798 for _, diff := range diffs {
799 if _, ok := hgvsCol[diff]; ok {
802 hgvsCol[diff] = [2][]int8{
803 make([]int8, len(cmd.cgnames)),
804 make([]int8, len(cmd.cgnames)),
808 for row, name := range cmd.cgnames {
809 variants := cgs[name].Variants[(tag-tagstart)*2:]
810 for ph := 0; ph < 2; ph++ {
812 if int(v) >= len(remap) {
818 // hgvsCol[*][ph][row] is already 0
819 } else if len(variantDiffs[v]) == 0 {
820 // lacking coverage / couldn't be diffed
821 for _, col := range hgvsCol {
825 for _, diff := range variantDiffs[v] {
826 hgvsCol[diff][ph][row] = 1
831 for diff, colpair := range hgvsCol {
832 allele2homhet(colpair)
833 if !cmd.filterHGVScolpair(colpair) {
834 delete(hgvsCol, diff)
837 if len(hgvsCol) > 0 {
838 encodeHGVSTodo[rt.seqname] <- hgvsCol
853 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
854 rows := len(cmd.cgnames)
855 cols := len(onehotChunk)
856 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
857 throttleNumpyMem.Acquire()
858 out := onehotcols2int8(onehotChunk)
859 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
860 err = writeNumpyInt8(fnm, out, rows, cols)
864 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
865 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
870 throttleNumpyMem.Release()
872 if *onehotSingle || *onlyPCA {
873 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
874 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
875 onehotXrefs[infileIdx] = onehotXref
876 n := len(onehotIndirect[infileIdx][0])
877 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
879 if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
880 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
881 throttleNumpyMem.Acquire()
882 rows := len(cmd.cgnames)
884 out := make([]int16, rows*cols)
885 for row, name := range cmd.cgnames {
887 for col, v := range cgs[name].Variants {
888 tag := tagstart + tagID(col/2)
889 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
892 if rt := reftile[tag]; rt == nil || rt.excluded {
896 out[outidx] = 0 // tag not found / spanning tile
897 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
898 out[outidx] = int16(variantRemap[tag-tagstart][v])
900 out[outidx] = -1 // low quality tile variant
902 if tag == cmd.debugTag {
903 log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
911 throttleNumpyMem.Release()
912 if *mergeOutput || *hgvsSingle {
913 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
914 toMerge[infileIdx] = out
916 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
917 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
918 err = writeNumpyInt16(fnm, out, rows, cols)
925 log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
929 if err = throttleMem.Wait(); err != nil {
934 log.Info("flushing hgvsCols temp files")
935 for seqname := range refseq {
936 close(encodeHGVSTodo[seqname])
938 err = encodeHGVS.Wait()
942 for seqname := range refseq {
943 log.Infof("%s: reading hgvsCols from temp file", seqname)
944 f := tmpHGVSCols[seqname]
945 _, err = f.Seek(0, io.SeekStart)
949 var hgvsCols hgvsColSet
950 dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
952 err = dec.Decode(&hgvsCols)
957 log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
958 variants := make([]hgvs.Variant, 0, len(hgvsCols))
959 for v := range hgvsCols {
960 variants = append(variants, v)
962 sort.Slice(variants, func(i, j int) bool {
963 vi, vj := &variants[i], &variants[j]
964 if vi.Position != vj.Position {
965 return vi.Position < vj.Position
966 } else if vi.Ref != vj.Ref {
967 return vi.Ref < vj.Ref
969 return vi.New < vj.New
972 rows := len(cmd.cgnames)
973 cols := len(variants) * 2
974 log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
975 out := make([]int8, rows*cols)
976 for varIdx, variant := range variants {
977 hgvsCols := hgvsCols[variant]
978 for row := range cmd.cgnames {
979 for ph := 0; ph < 2; ph++ {
980 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
984 err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
990 fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
991 log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
992 var hgvsLabels bytes.Buffer
993 for varIdx, variant := range variants {
994 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
996 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
1003 if *mergeOutput || *hgvsSingle {
1004 var annow *bufio.Writer
1007 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
1008 annof, err = os.Create(annoFilename)
1012 annow = bufio.NewWriterSize(annof, 1<<20)
1015 rows := len(cmd.cgnames)
1017 for _, chunk := range toMerge {
1018 cols += len(chunk) / rows
1020 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
1023 out = make([]int16, rows*cols)
1025 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1027 for outIdx, chunk := range toMerge {
1028 chunkcols := len(chunk) / rows
1030 for row := 0; row < rows; row++ {
1031 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1034 toMerge[outIdx] = nil
1036 annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1037 log.Infof("reading %s", annotationsFilename)
1038 buf, err := os.ReadFile(annotationsFilename)
1043 err = os.Remove(annotationsFilename)
1048 for _, line := range bytes.Split(buf, []byte{'\n'}) {
1052 fields := bytes.SplitN(line, []byte{','}, 9)
1053 tag, _ := strconv.Atoi(string(fields[0]))
1054 incol, _ := strconv.Atoi(string(fields[1]))
1055 tileVariant, _ := strconv.Atoi(string(fields[2]))
1056 hgvsID := string(fields[3])
1057 seqname := string(fields[4])
1058 pos, _ := strconv.Atoi(string(fields[5]))
1061 // Null entry for un-diffable
1066 // Null entry for ref tile
1069 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1070 // The tile intersects one of
1071 // the selected regions, but
1072 // this particular HGVS
1073 // variant does not.
1076 hgvsColPair := hgvsCols[hgvsID]
1077 if hgvsColPair[0] == nil {
1078 // values in new columns start
1079 // out as -1 ("no data yet")
1080 // or 0 ("=ref") here, may
1081 // change to 1 ("hgvs variant
1082 // present") below, either on
1083 // this line or a future line.
1084 hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1085 rt, ok := reftile[tagID(tag)]
1087 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1090 for ph := 0; ph < 2; ph++ {
1091 for row := 0; row < rows; row++ {
1092 v := chunk[row*chunkcols+incol*2+ph]
1093 if tileVariantID(v) == rt.variant {
1094 hgvsColPair[ph][row] = 0
1096 hgvsColPair[ph][row] = -1
1100 hgvsCols[hgvsID] = hgvsColPair
1102 hgvsref := hgvs.Variant{
1104 Ref: string(refseq),
1105 New: string(refseq),
1107 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])
1111 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])
1113 for ph := 0; ph < 2; ph++ {
1114 for row := 0; row < rows; row++ {
1115 v := chunk[row*chunkcols+incol*2+ph]
1116 if int(v) == tileVariant {
1117 hgvsColPair[ph][row] = 1
1123 startcol += chunkcols
1134 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1142 cols = len(hgvsCols) * 2
1143 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1144 out = make([]int16, rows*cols)
1145 hgvsIDs := make([]string, 0, cols/2)
1146 for hgvsID := range hgvsCols {
1147 hgvsIDs = append(hgvsIDs, hgvsID)
1149 sort.Strings(hgvsIDs)
1150 var hgvsLabels bytes.Buffer
1151 for idx, hgvsID := range hgvsIDs {
1152 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1153 for ph := 0; ph < 2; ph++ {
1154 hgvscol := hgvsCols[hgvsID][ph]
1155 for row, val := range hgvscol {
1156 out[row*cols+idx*2+ph] = val
1160 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1165 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1166 log.Printf("writing hgvs labels: %s", fnm)
1167 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1173 if *onehotSingle || *onlyPCA {
1175 for _, part := range onehotIndirect {
1176 nzCount += len(part[0])
1178 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1179 var xrefs []onehotXref
1180 chunkOffset := uint32(0)
1182 for i, part := range onehotIndirect {
1183 for i := range part[1] {
1184 part[1][i] += chunkOffset
1186 copy(onehot[outcol:], part[0])
1187 copy(onehot[outcol+nzCount:], part[1])
1188 xrefs = append(xrefs, onehotXrefs[i]...)
1190 outcol += len(part[0])
1191 chunkOffset += onehotChunkSize[i]
1195 onehotXrefs[i] = nil
1196 debug.FreeOSMemory()
1199 fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1200 err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1204 fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1205 err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1209 fnm = fmt.Sprintf("%s/stats.json", *outputDir)
1210 j, err := json.Marshal(map[string]interface{}{
1211 "pvalueCallCount": cmd.pvalueCallCount,
1216 err = os.WriteFile(fnm, j, 0777)
1223 for _, c := range onehot[nzCount:] {
1229 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1231 log.Printf("have %d one-hot cols", cols)
1233 for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1234 cols = (cols + 1) / 2
1238 // we work with pairs of columns
1241 log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1242 mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1243 mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1244 for i, c := range onehot[nzCount:] {
1245 if int(c/2)%stride == 0 {
1246 outcol := int(c/2)/stride*2 + int(c)%2
1247 mtxFull.Set(int(onehot[i]), outcol, 1)
1248 if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1249 mtxTrain.Set(trainRow, outcol, 1)
1253 log.Print("fitting")
1254 transformer := nlp.NewPCA(cmd.pcaComponents)
1255 transformer.Fit(mtxTrain.T())
1256 log.Printf("transforming")
1257 pca, err := transformer.Transform(mtxFull.T())
1262 outrows, outcols := pca.Dims()
1263 log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1264 out := make([]float64, outrows*outcols)
1265 for i := 0; i < outrows; i++ {
1266 for j := 0; j < outcols; j++ {
1267 out[i*outcols+j] = pca.At(i, j)
1270 fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1271 log.Printf("writing numpy: %s", fnm)
1272 output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1276 npw, err := gonpy.NewWriter(nopCloser{output})
1278 return fmt.Errorf("gonpy.NewWriter: %w", err)
1280 npw.Shape = []int{outrows, outcols}
1281 err = npw.WriteFloat64(out)
1283 return fmt.Errorf("WriteFloat64: %w", err)
1285 err = output.Close()
1291 samplesOutFilename := *outputDir + "/samples.csv"
1292 log.Infof("writing sample metadata to %s", samplesOutFilename)
1294 f, err = os.Create(samplesOutFilename)
1300 for i := 0; i < outcols; i++ {
1301 pcaLabels += fmt.Sprintf(",PCA%d", i)
1303 _, err = fmt.Fprintf(f, "Index,SampleID,CaseControl,TrainingValidation%s\n", pcaLabels)
1307 for i, si := range cmd.samples {
1311 } else if si.isControl {
1316 } else if si.isValidation {
1320 for c := 0; c < outcols; c++ {
1321 pcavals += fmt.Sprintf(",%f", pca.At(i, c))
1323 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1325 err = fmt.Errorf("write %s: %w", samplesOutFilename, err)
1331 err = fmt.Errorf("close %s: %w", samplesOutFilename, err)
1337 if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1338 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1339 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1341 f, err = os.Create(tagoffsetFilename)
1346 for idx, offset := range chunkStartTag {
1347 _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1349 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1355 err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1363 type sampleInfo struct {
1369 pcaComponents []float64
1372 // Read samples.csv file with case/control and training/validation
1374 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1376 f, err := open(samplesFilename)
1380 buf, err := io.ReadAll(f)
1386 for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1391 split := strings.Split(string(csv), ",")
1393 return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1395 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1398 idx, err := strconv.Atoi(split[0])
1401 return nil, fmt.Errorf("header does not look right: %q", csv)
1403 return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1406 return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1408 var pcaComponents []float64
1410 for _, s := range split[4:] {
1411 f, err := strconv.ParseFloat(s, 64)
1413 return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1415 pcaComponents = append(pcaComponents, f)
1418 si = append(si, sampleInfo{
1420 isCase: split[2] == "1",
1421 isControl: split[2] == "0",
1422 isTraining: split[3] == "1",
1423 isValidation: split[3] == "0",
1424 pcaComponents: pcaComponents,
1430 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1431 if cmd.chi2PValue >= 1 {
1434 col0 := make([]bool, 0, len(cmd.chi2Cases))
1435 col1 := make([]bool, 0, len(cmd.chi2Cases))
1436 cases := make([]bool, 0, len(cmd.chi2Cases))
1437 for i, c := range cmd.chi2Cases {
1438 if colpair[0][i] < 0 {
1441 col0 = append(col0, colpair[0][i] != 0)
1442 col1 = append(col1, colpair[1][i] != 0)
1443 cases = append(cases, c)
1445 return len(cases) >= cmd.minCoverage &&
1446 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1449 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1450 output, err := os.Create(fnm)
1454 defer output.Close()
1455 bufw := bufio.NewWriterSize(output, 1<<26)
1456 npw, err := gonpy.NewWriter(nopCloser{bufw})
1460 log.WithFields(log.Fields{
1464 "bytes": rows * cols * 4,
1465 }).Infof("writing numpy: %s", fnm)
1466 npw.Shape = []int{rows, cols}
1467 npw.WriteUint32(out)
1472 return output.Close()
1475 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1476 output, err := os.Create(fnm)
1480 defer output.Close()
1481 bufw := bufio.NewWriterSize(output, 1<<26)
1482 npw, err := gonpy.NewWriter(nopCloser{bufw})
1486 log.WithFields(log.Fields{
1490 "bytes": rows * cols * 4,
1491 }).Infof("writing numpy: %s", fnm)
1492 npw.Shape = []int{rows, cols}
1498 return output.Close()
1501 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1502 output, err := os.Create(fnm)
1506 defer output.Close()
1507 bufw := bufio.NewWriterSize(output, 1<<26)
1508 npw, err := gonpy.NewWriter(nopCloser{bufw})
1512 log.WithFields(log.Fields{
1516 "bytes": rows * cols * 2,
1517 }).Infof("writing numpy: %s", fnm)
1518 npw.Shape = []int{rows, cols}
1524 return output.Close()
1527 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1528 output, err := os.Create(fnm)
1532 defer output.Close()
1533 bufw := bufio.NewWriterSize(output, 1<<26)
1534 npw, err := gonpy.NewWriter(nopCloser{bufw})
1538 log.WithFields(log.Fields{
1542 "bytes": rows * cols,
1543 }).Infof("writing numpy: %s", fnm)
1544 npw.Shape = []int{rows, cols}
1550 return output.Close()
1553 func allele2homhet(colpair [2][]int8) {
1554 a, b := colpair[0], colpair[1]
1555 for i, av := range a {
1557 if av < 0 || bv < 0 {
1560 } else if av > 0 && bv > 0 {
1563 } else if av > 0 || bv > 0 {
1567 // ref (or a different variant in same position)
1568 // (this is a no-op) a[i], b[i] = 0, 0
1573 type onehotXref struct {
1575 variant tileVariantID
1580 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1582 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1583 // variants of a single tile/tag#.
1585 // Return nil if no tile variant passes Χ² filter.
1586 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
1587 if tag == cmd.debugTag {
1588 tv := make([]tileVariantID, len(cmd.cgnames)*2)
1589 for i, name := range cmd.cgnames {
1590 copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
1592 log.WithFields(logrus.Fields{
1593 "cgs[i].Variants[tag*2+j]": tv,
1597 "chunkstarttag": chunkstarttag,
1598 }).Info("tv2homhet()")
1600 if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1601 // everyone has the most common variant (of the variants we don't drop)
1604 tagoffset := tag - chunkstarttag
1606 for _, cg := range cgs {
1608 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1609 if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1617 if coverage < cmd.minCoverage {
1620 // "observed" array for p-value calculation (training set
1622 obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1623 // one-hot output (all samples)
1624 outcols := make([][]int8, (maxv+1)*2)
1625 for i := range obs {
1626 obs[i] = make([]bool, cmd.trainingSetSize)
1627 outcols[i] = make([]int8, len(cmd.cgnames))
1629 for cgid, name := range cmd.cgnames {
1630 tsid := cmd.trainingSet[cgid]
1631 cgvars := cgs[name].Variants[tagoffset*2:]
1632 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1633 for v := tileVariantID(1); v <= maxv; v++ {
1634 if tv0 == v && tv1 == v {
1636 obs[v*2][tsid] = true
1638 outcols[v*2][cgid] = 1
1639 } else if tv0 == v || tv1 == v {
1641 obs[v*2+1][tsid] = true
1643 outcols[v*2+1][cgid] = 1
1648 var xref []onehotXref
1649 for col := 2; col < len(obs); col++ {
1650 // col 0,1 correspond to tile variant 0, i.e.,
1651 // no-call; col 2,3 correspond to the most common
1652 // variant; so we (normally) start at col 4.
1653 if col < 4 && !cmd.includeVariant1 {
1656 atomic.AddInt64(&cmd.pvalueCallCount, 1)
1657 p := cmd.pvalue(obs[col])
1658 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1661 onehot = append(onehot, outcols[col])
1662 xref = append(xref, onehotXref{
1664 variant: tileVariantID(col >> 1),
1672 // convert a []onehotXref with length N to a numpy-style []int32
1673 // matrix with N columns, one row per field of onehotXref struct.
1675 // Hom/het row contains hom=0, het=1.
1677 // P-value row contains 1000000x actual p-value.
1678 func onehotXref2int32(xrefs []onehotXref) []int32 {
1680 xdata := make([]int32, 5*xcols)
1681 for i, xref := range xrefs {
1682 xdata[i] = int32(xref.tag)
1683 xdata[xcols+i] = int32(xref.variant)
1685 xdata[xcols*2+i] = 1
1687 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1688 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1693 // transpose onehot data from in[col][row] to numpy-style
1694 // out[row*cols+col].
1695 func onehotcols2int8(in [][]int8) []int8 {
1701 out := make([]int8, rows*cols)
1702 for row := 0; row < rows; row++ {
1703 outrow := out[row*cols:]
1704 for col, incol := range in {
1705 outrow[col] = incol[row]
1711 // Return [2][]uint32{rowIndices, colIndices} indicating which
1712 // elements of matrixT[c][r] have non-zero values.
1713 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1715 for c, col := range matrixT {
1716 for r, val := range col {
1718 nz[0] = append(nz[0], uint32(r))
1719 nz[1] = append(nz[1], uint32(c))