Add tilestats cmd.
[lightning.git] / slicenumpy.go
index c05f1509c05e37a40fb215b90a96950b36ad932e..a2e03f494462a94da2233899ea2488ef6c4c5087 100644 (file)
@@ -8,6 +8,7 @@ import (
        "bufio"
        "bytes"
        "encoding/gob"
+       "errors"
        "flag"
        "fmt"
        "io"
@@ -23,22 +24,27 @@ import (
        "strconv"
        "strings"
        "sync/atomic"
+       "unsafe"
 
        "git.arvados.org/arvados.git/sdk/go/arvados"
        "github.com/arvados/lightning/hgvs"
        "github.com/kshedden/gonpy"
+       "github.com/sirupsen/logrus"
        log "github.com/sirupsen/logrus"
        "golang.org/x/crypto/blake2b"
 )
 
 type sliceNumpy struct {
-       filter        filter
-       threads       int
-       chi2CasesFile string
-       chi2Cases     []bool
-       chi2PValue    float64
-       minCoverage   int
-       cgnames       []string
+       filter                filter
+       threads               int
+       chi2CaseControlColumn string
+       chi2CaseControlFile   string
+       chi2Cases             []bool
+       chi2PValue            float64
+       minCoverage           int
+       cgnames               []string
+       includeVariant1       bool
+       debugTag              tagID
 }
 
 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
@@ -62,10 +68,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
        hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
        hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
-       onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix")
+       onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
+       onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
+       debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
        flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads")
-       flags.StringVar(&cmd.chi2CasesFile, "chi2-cases-file", "", "text file indicating positive cases (for Χ² test)")
+       flags.StringVar(&cmd.chi2CaseControlFile, "chi2-case-control-file", "", "tsv file or directory indicating cases and controls for Χ² test (if directory, all .tsv files will be read)")
+       flags.StringVar(&cmd.chi2CaseControlColumn, "chi2-case-control-column", "", "name of case/control column in case-control files for Χ² test (value must be 0 for control, 1 for case)")
        flags.Float64Var(&cmd.chi2PValue, "chi2-p-value", 1, "do Χ² test and omit columns with p-value above this threshold")
+       flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
        cmd.filter.Flags(flags)
        err = flags.Parse(args)
        if err == flag.ErrHelp {
@@ -81,11 +91,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                }()
        }
 
-       if cmd.chi2CasesFile == "" && cmd.chi2PValue != 1 {
-               log.Errorf("cannot use provided -chi2-p-value=%f because -chi2-cases-file= value is empty", cmd.chi2PValue)
+       if cmd.chi2PValue != 1 && (cmd.chi2CaseControlFile == "" || cmd.chi2CaseControlColumn == "") {
+               log.Errorf("cannot use provided -chi2-p-value=%f because -chi2-case-control-file= or -chi2-case-control-column= value is empty", cmd.chi2PValue)
                return 2
        }
 
+       cmd.debugTag = tagID(*debugTag)
+
        if !*runlocal {
                runner := arvadosContainerRunner{
                        Name:        "lightning slice-numpy",
@@ -97,7 +109,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        KeepCache:   2,
                        APIAccess:   true,
                }
-               err = runner.TranslatePaths(inputDir, regionsFilename, &cmd.chi2CasesFile)
+               err = runner.TranslatePaths(inputDir, regionsFilename, &cmd.chi2CaseControlFile)
                if err != nil {
                        return 1
                }
@@ -111,9 +123,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
                        "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
                        "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
+                       "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
                        "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
-                       "-chi2-cases-file=" + cmd.chi2CasesFile,
+                       "-chi2-case-control-file=" + cmd.chi2CaseControlFile,
+                       "-chi2-case-control-column=" + cmd.chi2CaseControlColumn,
                        "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
+                       "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
+                       "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
                }
                runner.Args = append(runner.Args, cmd.filter.Args()...)
                var output string
@@ -125,7 +141,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                return 0
        }
 
-       infiles, err := allGobFiles(*inputDir)
+       infiles, err := allFiles(*inputDir, matchGobFile)
        if err != nil {
                return 1
        }
@@ -149,10 +165,10 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        }
 
        cmd.cgnames = nil
-       taglen := -1
-       DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
+       var tagset [][]byte
+       err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
                if len(ent.TagSet) > 0 {
-                       taglen = len(ent.TagSet[0])
+                       tagset = ent.TagSet
                }
                for _, cseq := range ent.CompactSequences {
                        if cseq.Name == *ref || *ref == "" {
@@ -179,60 +195,31 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                err = fmt.Errorf("%s: reference sequence not found", infiles[0])
                return 1
        }
-       if taglen < 0 {
+       if len(tagset) == 0 {
                err = fmt.Errorf("tagset not found")
                return 1
        }
+
+       taglib := &tagLibrary{}
+       err = taglib.setTags(tagset)
+       if err != nil {
+               return 1
+       }
+       taglen := taglib.TagLen()
+
        if len(cmd.cgnames) == 0 {
                err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
                return 1
        }
        sort.Strings(cmd.cgnames)
-
-       cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
-
-       if cmd.chi2CasesFile != "" {
-               f, err2 := open(cmd.chi2CasesFile)
-               if err2 != nil {
-                       err = err2
-                       return 1
-               }
-               buf, err2 := io.ReadAll(f)
-               f.Close()
-               if err2 != nil {
-                       err = err2
-                       return 1
-               }
-               cmd.chi2Cases = make([]bool, len(cmd.cgnames))
-               ncases := 0
-               for _, pattern := range bytes.Split(buf, []byte{'\n'}) {
-                       if len(pattern) == 0 {
-                               continue
-                       }
-                       pattern := string(pattern)
-                       idx := -1
-                       for i, name := range cmd.cgnames {
-                               if !strings.Contains(name, pattern) {
-                                       continue
-                               }
-                               cmd.chi2Cases[i] = true
-                               ncases++
-                               if idx >= 0 {
-                                       log.Warnf("pattern %q in cases file matches multiple genome IDs: %q, %q", pattern, cmd.cgnames[idx], name)
-                               } else {
-                                       idx = i
-                               }
-                       }
-                       if idx < 0 {
-                               log.Warnf("pattern %q in cases file does not match any genome IDs", pattern)
-                               continue
-                       }
-               }
-               log.Printf("%d cases, %d controls", ncases, len(cmd.cgnames)-ncases)
+       err = cmd.useCaseControlFiles()
+       if err != nil {
+               return 1
        }
+       cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
 
        {
-               labelsFilename := *outputDir + "/labels.csv"
+               labelsFilename := *outputDir + "/samples.csv"
                log.Infof("writing labels to %s", labelsFilename)
                var f *os.File
                f, err = os.Create(labelsFilename)
@@ -241,7 +228,11 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                }
                defer f.Close()
                for i, name := range cmd.cgnames {
-                       _, err = fmt.Fprintf(f, "%d,%q\n", i, trimFilenameForLabel(name))
+                       cc := 0
+                       if cmd.chi2Cases != nil && cmd.chi2Cases[i] {
+                               cc = 1
+                       }
+                       _, err = fmt.Fprintf(f, "%d,%q,%d\n", i, trimFilenameForLabel(name), cc)
                        if err != nil {
                                err = fmt.Errorf("write %s: %w", labelsFilename, err)
                                return 1
@@ -266,11 +257,28 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        for seqname, cseq := range refseq {
                pos := 0
                for _, libref := range cseq {
+                       if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
+                               continue
+                       }
                        tiledata := reftiledata[libref]
                        if len(tiledata) == 0 {
                                err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
                                return 1
                        }
+                       foundthistag := false
+                       taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
+                               if !foundthistag && tagid == libref.Tag {
+                                       foundthistag = true
+                                       return
+                               }
+                               if dupref, ok := reftile[tagid]; ok {
+                                       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)
+                                       delete(reftile, tagid)
+                               } else {
+                                       log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
+                               }
+                               isdup[tagid] = true
+                       })
                        if isdup[libref.Tag] {
                                log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
                        } else if reftile[libref.Tag] != nil {
@@ -344,10 +352,20 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        if *mergeOutput || *hgvsSingle {
                toMerge = make([][]int16, len(infiles))
        }
+       var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
+       var onehotChunkSize []uint32
+       var onehotXrefs [][]onehotXref
+       if *onehotSingle {
+               onehotIndirect = make([][2][]uint32, len(infiles))
+               onehotChunkSize = make([]uint32, len(infiles))
+               onehotXrefs = make([][]onehotXref, len(infiles))
+       }
+       chunkStartTag := make([]tagID, len(infiles))
 
        throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
        throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
        log.Info("generating annotations and numpy matrix for each slice")
+       var errSkip = errors.New("skip infile")
        var done int64
        for infileIdx, infile := range infiles {
                infileIdx, infile := infileIdx, infile
@@ -371,6 +389,9 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                // masked-out tiles.
                                                continue
                                        }
+                                       if tv.Tag == cmd.debugTag {
+                                               log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
+                                       }
                                        variants := seq[tv.Tag]
                                        if len(variants) == 0 {
                                                variants = make([]TileVariant, 100)
@@ -382,6 +403,9 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        seq[tv.Tag] = variants
                                }
                                for _, cg := range ent.CompactGenomes {
+                                       if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
+                                               return errSkip
+                                       }
                                        if !matchGenome.MatchString(cg.Name) {
                                                continue
                                        }
@@ -395,11 +419,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                }
                                return nil
                        })
-                       if err != nil {
+                       if err == errSkip {
+                               return nil
+                       } else if err != nil {
                                return err
                        }
                        tagstart := cgs[cmd.cgnames[0]].StartTag
                        tagend := cgs[cmd.cgnames[0]].EndTag
+                       chunkStartTag[infileIdx] = tagstart
 
                        // TODO: filters
 
@@ -408,9 +435,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
                        for tag, variants := range seq {
                                tag, variants := tag, variants
-                               throttleCPU.Acquire()
-                               go func() {
-                                       defer throttleCPU.Release()
+                               throttleCPU.Go(func() error {
                                        count := make(map[[blake2b.Size256]byte]int, len(variants))
 
                                        rt := reftile[tag]
@@ -418,13 +443,16 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                count[blake2b.Sum256(rt.tiledata)] = 0
                                        }
 
-                                       for _, cg := range cgs {
+                                       for cgname, cg := range cgs {
                                                idx := int(tag-tagstart) * 2
                                                for allele := 0; allele < 2; allele++ {
                                                        v := cg.Variants[idx+allele]
                                                        if v > 0 && len(variants[v].Sequence) > 0 {
                                                                count[variants[v].Blake2b]++
                                                        }
+                                                       if v > 0 && tag == cmd.debugTag {
+                                                               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])
+                                                       }
                                                }
                                        }
                                        // hash[i] will be the hash of
@@ -449,6 +477,11 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        for i, h := range hash {
                                                rank[h] = tileVariantID(i + 1)
                                        }
+                                       if tag == cmd.debugTag {
+                                               for h, r := range rank {
+                                                       log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
+                                               }
+                                       }
                                        // remap[v] will be the new
                                        // variant number for original
                                        // variant number v.
@@ -456,16 +489,28 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        for i, tv := range variants {
                                                remap[i] = rank[tv.Blake2b]
                                        }
+                                       if tag == cmd.debugTag {
+                                               for in, out := range remap {
+                                                       if out > 0 {
+                                                               log.Printf("tag %d remap %d => %d", tag, in, out)
+                                                       }
+                                               }
+                                       }
                                        variantRemap[tag-tagstart] = remap
                                        if rt != nil {
-                                               rt.variant = rank[blake2b.Sum256(rt.tiledata)]
+                                               refrank := rank[blake2b.Sum256(rt.tiledata)]
+                                               if tag == cmd.debugTag {
+                                                       log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
+                                               }
+                                               rt.variant = refrank
                                        }
-                               }()
+                                       return nil
+                               })
                        }
                        throttleCPU.Wait()
 
                        var onehotChunk [][]int8
-                       var onehotXrefs []onehotXref
+                       var onehotXref []onehotXref
 
                        annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
                        log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
@@ -476,18 +521,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        annow := bufio.NewWriterSize(annof, 1<<20)
                        outcol := 0
                        for tag := tagstart; tag < tagend; tag++ {
-                               rt, ok := reftile[tag]
-                               if !ok {
-                                       if mask == nil {
-                                               outcol++
-                                       }
-                                       // Excluded by specified
-                                       // regions, or reference does
-                                       // not use any variant of this
-                                       // tile. (TODO: log this?
-                                       // mention it in annotations?)
+                               rt := reftile[tag]
+                               if rt == nil && mask != nil {
+                                       // Excluded by specified regions
                                        continue
                                }
+                               if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
+                                       break
+                               }
                                remap := variantRemap[tag-tagstart]
                                maxv := tileVariantID(0)
                                for _, v := range remap {
@@ -495,10 +536,22 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                maxv = v
                                        }
                                }
-                               if *onehotChunked {
+                               if *onehotChunked || *onehotSingle {
                                        onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart)
+                                       if tag == cmd.debugTag {
+                                               log.WithFields(logrus.Fields{
+                                                       "onehot": onehot,
+                                                       "xrefs":  xrefs,
+                                               }).Info("tv2homhet()")
+                                       }
                                        onehotChunk = append(onehotChunk, onehot...)
-                                       onehotXrefs = append(onehotXrefs, xrefs...)
+                                       onehotXref = append(onehotXref, xrefs...)
+                               }
+                               if rt == nil {
+                                       // Reference does not use any
+                                       // variant of this tile
+                                       outcol++
+                                       continue
                                }
                                fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
                                variants := seq[tag]
@@ -602,60 +655,54 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                cols := len(onehotChunk)
                                log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
                                throttleNumpyMem.Acquire()
-                               out := make([]int8, rows*cols)
-                               for row := range cmd.cgnames {
-                                       out := out[row*cols:]
-                                       for colnum, values := range onehotChunk {
-                                               out[colnum] = values[row]
-                                       }
-                               }
-                               seq = nil
-                               cgs = nil
-                               debug.FreeOSMemory()
-                               throttleNumpyMem.Release()
-
+                               out := onehotcols2int8(onehotChunk)
                                fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
                                err = writeNumpyInt8(fnm, out, rows, cols)
                                if err != nil {
                                        return err
                                }
-
                                fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
-                               xcols := len(onehotXrefs)
-                               xdata := make([]int32, 4*xcols)
-                               for i, xref := range onehotXrefs {
-                                       xdata[i] = int32(xref.tag)
-                                       xdata[xcols+i] = int32(xref.variant)
-                                       if xref.het {
-                                               xdata[xcols*2+i] = 1
-                                       }
-                                       xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
-                               }
-                               err = writeNumpyInt32(fnm, xdata, 4, xcols)
+                               err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
                                if err != nil {
                                        return err
                                }
+                               debug.FreeOSMemory()
+                               throttleNumpyMem.Release()
+                       }
+                       if *onehotSingle {
+                               onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
+                               onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
+                               onehotXrefs[infileIdx] = onehotXref
+                               n := len(onehotIndirect[infileIdx][0])
+                               log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
                        }
-                       if !*onehotChunked || *mergeOutput || *hgvsSingle {
-                               log.Infof("%04d: preparing numpy", infileIdx)
+                       if !(*onehotSingle || *onehotChunked) || *mergeOutput || *hgvsSingle {
+                               log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
                                throttleNumpyMem.Acquire()
                                rows := len(cmd.cgnames)
                                cols := 2 * outcol
                                out := make([]int16, rows*cols)
                                for row, name := range cmd.cgnames {
-                                       out := out[row*cols:]
-                                       outcol := 0
+                                       outidx := row * cols
                                        for col, v := range cgs[name].Variants {
                                                tag := tagstart + tagID(col/2)
+                                               if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
+                                                       break
+                                               }
                                                if mask != nil && reftile[tag] == nil {
                                                        continue
                                                }
-                                               if variants, ok := seq[tag]; ok && len(variants) > int(v) && len(variants[v].Sequence) > 0 {
-                                                       out[outcol] = int16(variantRemap[tag-tagstart][v])
+                                               if v == 0 {
+                                                       out[outidx] = 0 // tag not found / spanning tile
+                                               } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
+                                                       out[outidx] = int16(variantRemap[tag-tagstart][v])
                                                } else {
-                                                       out[outcol] = -1
+                                                       out[outidx] = -1 // low quality tile variant
+                                               }
+                                               if tag == cmd.debugTag {
+                                                       log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
                                                }
-                                               outcol++
+                                               outidx++
                                        }
                                }
                                seq = nil
@@ -666,7 +713,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
                                        toMerge[infileIdx] = out
                                }
-                               if !*mergeOutput && !*onehotChunked {
+                               if !*mergeOutput && !*onehotChunked && !*onehotSingle {
                                        fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
                                        err = writeNumpyInt16(fnm, out, rows, cols)
                                        if err != nil {
@@ -923,9 +970,150 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        }
                }
        }
+       if *onehotSingle {
+               nzCount := 0
+               for _, part := range onehotIndirect {
+                       nzCount += len(part[0])
+               }
+               onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
+               var xrefs []onehotXref
+               chunkOffset := uint32(0)
+               outcol := 0
+               for i, part := range onehotIndirect {
+                       for i := range part[1] {
+                               part[1][i] += chunkOffset
+                       }
+                       copy(onehot[outcol:], part[0])
+                       copy(onehot[outcol+nzCount:], part[1])
+                       xrefs = append(xrefs, onehotXrefs[i]...)
+
+                       outcol += len(part[0])
+                       chunkOffset += onehotChunkSize[i]
+
+                       part[0] = nil
+                       part[1] = nil
+                       onehotXrefs[i] = nil
+                       debug.FreeOSMemory()
+               }
+               fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
+               err = writeNumpyUint32(fnm, onehot, 2, nzCount)
+               if err != nil {
+                       return 1
+               }
+               fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
+               err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 4, len(xrefs))
+               if err != nil {
+                       return 1
+               }
+       }
+       if !*mergeOutput && !*onehotChunked && !*onehotSingle {
+               tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
+               log.Infof("writing tag offsets to %s", tagoffsetFilename)
+               var f *os.File
+               f, err = os.Create(tagoffsetFilename)
+               if err != nil {
+                       return 1
+               }
+               defer f.Close()
+               for idx, offset := range chunkStartTag {
+                       _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
+                       if err != nil {
+                               err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
+                               return 1
+                       }
+               }
+               err = f.Close()
+               if err != nil {
+                       err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
+                       return 1
+               }
+       }
        return 0
 }
 
+// Read case/control files, remove non-case/control entries from
+// cmd.cgnames, and build cmd.chi2Cases.
+func (cmd *sliceNumpy) useCaseControlFiles() error {
+       if cmd.chi2CaseControlFile == "" {
+               return nil
+       }
+       infiles, err := allFiles(cmd.chi2CaseControlFile, nil)
+       if err != nil {
+               return err
+       }
+       // index in cmd.cgnames => case(true) / control(false)
+       cc := map[int]bool{}
+       for _, infile := range infiles {
+               f, err := open(infile)
+               if err != nil {
+                       return err
+               }
+               buf, err := io.ReadAll(f)
+               f.Close()
+               if err != nil {
+                       return err
+               }
+               ccCol := -1
+               for _, tsv := range bytes.Split(buf, []byte{'\n'}) {
+                       if len(tsv) == 0 {
+                               continue
+                       }
+                       split := strings.Split(string(tsv), "\t")
+                       if ccCol < 0 {
+                               // header row
+                               for col, name := range split {
+                                       if name == cmd.chi2CaseControlColumn {
+                                               ccCol = col
+                                               break
+                                       }
+                               }
+                               if ccCol < 0 {
+                                       return fmt.Errorf("%s: no column named %q in header row %q", infile, cmd.chi2CaseControlColumn, tsv)
+                               }
+                               continue
+                       }
+                       if len(split) <= ccCol {
+                               continue
+                       }
+                       pattern := split[0]
+                       found := -1
+                       for i, name := range cmd.cgnames {
+                               if strings.Contains(name, pattern) {
+                                       if found >= 0 {
+                                               log.Warnf("pattern %q in %s matches multiple genome IDs (%qs, %q)", pattern, infile, cmd.cgnames[found], name)
+                                       }
+                                       found = i
+                               }
+                       }
+                       if found < 0 {
+                               log.Warnf("pattern %q in %s does not match any genome IDs", pattern, infile)
+                               continue
+                       }
+                       if split[ccCol] == "0" {
+                               cc[found] = false
+                       }
+                       if split[ccCol] == "1" {
+                               cc[found] = true
+                       }
+               }
+       }
+       allnames := cmd.cgnames
+       cmd.cgnames = nil
+       cmd.chi2Cases = nil
+       ncases := 0
+       for i, name := range allnames {
+               if cc, ok := cc[i]; ok {
+                       cmd.cgnames = append(cmd.cgnames, name)
+                       cmd.chi2Cases = append(cmd.chi2Cases, cc)
+                       if cc {
+                               ncases++
+                       }
+               }
+       }
+       log.Printf("%d cases, %d controls, %d neither (dropped)", ncases, len(cmd.cgnames)-ncases, len(allnames)-len(cmd.cgnames))
+       return nil
+}
+
 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
        if cmd.chi2PValue >= 1 {
                return true
@@ -942,7 +1130,33 @@ func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
                cases = append(cases, c)
        }
        return len(cases) >= cmd.minCoverage &&
-               (pvalue(cases, col0) <= cmd.chi2PValue || pvalue(cases, col1) <= cmd.chi2PValue)
+               (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
+}
+
+func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
+       output, err := os.Create(fnm)
+       if err != nil {
+               return err
+       }
+       defer output.Close()
+       bufw := bufio.NewWriterSize(output, 1<<26)
+       npw, err := gonpy.NewWriter(nopCloser{bufw})
+       if err != nil {
+               return err
+       }
+       log.WithFields(log.Fields{
+               "filename": fnm,
+               "rows":     rows,
+               "cols":     cols,
+               "bytes":    rows * cols * 4,
+       }).Infof("writing numpy: %s", fnm)
+       npw.Shape = []int{rows, cols}
+       npw.WriteUint32(out)
+       err = bufw.Flush()
+       if err != nil {
+               return err
+       }
+       return output.Close()
 }
 
 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
@@ -1046,17 +1260,32 @@ func allele2homhet(colpair [2][]int8) {
 type onehotXref struct {
        tag     tagID
        variant tileVariantID
-       het     bool
+       hom     bool
        pvalue  float64
 }
 
-// Build onehot matrix (m[variant*2+isHet][genome] == 0 or 1) for all
+const onehotXrefSize = unsafe.Sizeof(onehotXref{})
+
+// Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
 // variants of a single tile/tag#.
 //
 // Return nil if no tile variant passes Χ² filter.
 func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID) ([][]int8, []onehotXref) {
-       if maxv < 2 {
-               // everyone has the most common variant
+       if tag == cmd.debugTag {
+               tv := make([]tileVariantID, len(cmd.cgnames)*2)
+               for i, name := range cmd.cgnames {
+                       copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
+               }
+               log.WithFields(logrus.Fields{
+                       "cgs[i].Variants[tag*2+j]": tv,
+                       "maxv":                     maxv,
+                       "remap":                    remap,
+                       "tag":                      tag,
+                       "chunkstarttag":            chunkstarttag,
+               }).Info("tv2homhet()")
+       }
+       if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
+               // everyone has the most common variant (of the variants we don't drop)
                return nil, nil
        }
        tagoffset := tag - chunkstarttag
@@ -1074,34 +1303,36 @@ func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantI
                obs[i] = make([]bool, len(cmd.cgnames))
        }
        for cgid, name := range cmd.cgnames {
-               cgvars := cgs[name].Variants
-               for v := tileVariantID(2); v <= maxv; v++ {
-                       if remap[cgvars[tagoffset*2]] == v && remap[cgvars[tagoffset*2+1]] == v {
+               cgvars := cgs[name].Variants[tagoffset*2:]
+               tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
+               for v := tileVariantID(1); v <= maxv; v++ {
+                       if tv0 == v && tv1 == v {
                                obs[v*2][cgid] = true
-                       } else if remap[cgvars[tagoffset*2]] == v || remap[cgvars[tagoffset*2+1]] == v {
+                       } else if tv0 == v || tv1 == v {
                                obs[v*2+1][cgid] = true
                        }
                }
        }
        var onehot [][]int8
        var xref []onehotXref
-       for homcol := 4; homcol < len(obs); homcol += 2 {
-               p := [2]float64{
-                       pvalue(cmd.chi2Cases, obs[homcol]),
-                       pvalue(cmd.chi2Cases, obs[homcol+1]),
-               }
-               if cmd.chi2PValue < 1 && !(p[0] < cmd.chi2PValue || p[1] < cmd.chi2PValue) {
+       for col := 2; col < len(obs); col++ {
+               // col 0,1 correspond to tile variant 0, i.e.,
+               // no-call; col 2,3 correspond to the most common
+               // variant; so we (normally) start at col 4.
+               if col < 4 && !cmd.includeVariant1 {
                        continue
                }
-               for het := 0; het < 2; het++ {
-                       onehot = append(onehot, bool2int8(obs[homcol+het]))
-                       xref = append(xref, onehotXref{
-                               tag:     tag,
-                               variant: tileVariantID(homcol / 2),
-                               het:     het == 1,
-                               pvalue:  p[het],
-                       })
+               p := pvalue(obs[col], cmd.chi2Cases)
+               if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
+                       continue
                }
+               onehot = append(onehot, bool2int8(obs[col]))
+               xref = append(xref, onehotXref{
+                       tag:     tag,
+                       variant: tileVariantID(col >> 1),
+                       hom:     col&1 == 0,
+                       pvalue:  p,
+               })
        }
        return onehot, xref
 }
@@ -1115,3 +1346,56 @@ func bool2int8(in []bool) []int8 {
        }
        return out
 }
+
+// convert a []onehotXref with length N to a numpy-style []int32
+// matrix with N columns, one row per field of onehotXref struct.
+//
+// Hom/het row contains hom=0, het=1.
+//
+// P-value row contains 1000000x actual p-value.
+func onehotXref2int32(xrefs []onehotXref) []int32 {
+       xcols := len(xrefs)
+       xdata := make([]int32, 4*xcols)
+       for i, xref := range xrefs {
+               xdata[i] = int32(xref.tag)
+               xdata[xcols+i] = int32(xref.variant)
+               if xref.hom {
+                       xdata[xcols*2+i] = 1
+               }
+               xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
+       }
+       return xdata
+}
+
+// transpose onehot data from in[col][row] to numpy-style
+// out[row*cols+col].
+func onehotcols2int8(in [][]int8) []int8 {
+       if len(in) == 0 {
+               return nil
+       }
+       cols := len(in)
+       rows := len(in[0])
+       out := make([]int8, rows*cols)
+       for row := 0; row < rows; row++ {
+               outrow := out[row*cols:]
+               for col, incol := range in {
+                       outrow[col] = incol[row]
+               }
+       }
+       return out
+}
+
+// Return [2][]uint32{rowIndices, colIndices} indicating which
+// elements of matrixT[c][r] have non-zero values.
+func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
+       var nz [2][]uint32
+       for c, col := range matrixT {
+               for r, val := range col {
+                       if val != 0 {
+                               nz[0] = append(nz[0], uint32(r))
+                               nz[1] = append(nz[1], uint32(c))
+                       }
+               }
+       }
+       return nz
+}