19524: Update colors, plot unknown-phenotype behind known.
[lightning.git] / slicenumpy.go
index 4728b7f32c27858f5ad28aae595ab81b04d3c7bd..a9fee14c8d692430370b94f8ea0f3b35ca62fa43 100644 (file)
@@ -28,12 +28,16 @@ import (
 
        "git.arvados.org/arvados.git/sdk/go/arvados"
        "github.com/arvados/lightning/hgvs"
+       "github.com/james-bowman/nlp"
        "github.com/kshedden/gonpy"
        "github.com/sirupsen/logrus"
        log "github.com/sirupsen/logrus"
        "golang.org/x/crypto/blake2b"
+       "gonum.org/v1/gonum/mat"
 )
 
+const annotationMaxTileSpan = 100
+
 type sliceNumpy struct {
        filter                filter
        threads               int
@@ -48,16 +52,20 @@ type sliceNumpy struct {
 }
 
 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
-       var err error
-       defer func() {
-               if err != nil {
-                       fmt.Fprintf(stderr, "%s\n", err)
-               }
-       }()
+       err := cmd.run(prog, args, stdin, stdout, stderr)
+       if err != nil {
+               fmt.Fprintf(stderr, "%s\n", err)
+               return 1
+       }
+       return 0
+}
+func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
        flags := flag.NewFlagSet("", flag.ContinueOnError)
        flags.SetOutput(stderr)
        pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
        runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
+       arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
+       arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
        projectUUID := flags.String("project", "", "project `UUID` for output data")
        priority := flags.Int("priority", 500, "container request priority")
        inputDir := flags.String("input-dir", "./in", "input `directory`")
@@ -70,19 +78,21 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
        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")
+       onlyPCA := flags.Bool("pca", false, "generate pca matrix")
+       pcaComponents := flags.Int("pca-components", 4, "number of PCA components")
+       maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
        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.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
        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)
+       err := flags.Parse(args)
        if err == flag.ErrHelp {
-               err = nil
-               return 0
+               return nil
        } else if err != nil {
-               return 2
+               return err
        }
 
        if *pprof != "" {
@@ -92,8 +102,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        }
 
        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
+               return fmt.Errorf("cannot use provided -chi2-p-value=%f because -chi2-case-control-file= or -chi2-case-control-column= value is empty", cmd.chi2PValue)
        }
 
        cmd.debugTag = tagID(*debugTag)
@@ -103,15 +112,15 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        Name:        "lightning slice-numpy",
                        Client:      arvados.NewClientFromEnv(),
                        ProjectUUID: *projectUUID,
-                       RAM:         750000000000,
-                       VCPUs:       96,
+                       RAM:         int64(*arvadosRAM),
+                       VCPUs:       *arvadosVCPUs,
                        Priority:    *priority,
                        KeepCache:   2,
                        APIAccess:   true,
                }
                err = runner.TranslatePaths(inputDir, regionsFilename, &cmd.chi2CaseControlFile)
                if err != nil {
-                       return 1
+                       return err
                }
                runner.Args = []string{"slice-numpy", "-local=true",
                        "-pprof=:6060",
@@ -125,6 +134,9 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
                        "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
                        "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
+                       "-pca=" + fmt.Sprintf("%v", *onlyPCA),
+                       "-pca-components=" + fmt.Sprintf("%d", *pcaComponents),
+                       "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
                        "-chi2-case-control-file=" + cmd.chi2CaseControlFile,
                        "-chi2-case-control-column=" + cmd.chi2CaseControlColumn,
                        "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
@@ -135,19 +147,19 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                var output string
                output, err = runner.Run()
                if err != nil {
-                       return 1
+                       return err
                }
                fmt.Fprintln(stdout, output)
-               return 0
+               return nil
        }
 
        infiles, err := allFiles(*inputDir, matchGobFile)
        if err != nil {
-               return 1
+               return err
        }
        if len(infiles) == 0 {
                err = fmt.Errorf("no input files found in %s", *inputDir)
-               return 1
+               return err
        }
        sort.Strings(infiles)
 
@@ -155,13 +167,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        var reftiledata = make(map[tileLibRef][]byte, 11000000)
        in0, err := open(infiles[0])
        if err != nil {
-               return 1
+               return err
        }
 
        matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
        if err != nil {
                err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
-               return 1
+               return err
        }
 
        cmd.cgnames = nil
@@ -188,35 +200,47 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                return nil
        })
        if err != nil {
-               return 1
+               return err
        }
        in0.Close()
        if refseq == nil {
                err = fmt.Errorf("%s: reference sequence not found", infiles[0])
-               return 1
+               return err
        }
        if len(tagset) == 0 {
                err = fmt.Errorf("tagset not found")
-               return 1
+               return err
        }
 
        taglib := &tagLibrary{}
        err = taglib.setTags(tagset)
        if err != nil {
-               return 1
+               return err
        }
        taglen := taglib.TagLen()
 
        if len(cmd.cgnames) == 0 {
                err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
-               return 1
+               return err
        }
        sort.Strings(cmd.cgnames)
        err = cmd.useCaseControlFiles()
        if err != nil {
-               return 1
+               return err
+       }
+       if len(cmd.cgnames) == 0 {
+               err = fmt.Errorf("fatal: 0 cases, 0 controls, nothing to do")
+               return err
+       }
+       if cmd.filter.MinCoverage == 1 {
+               // In the generic formula below, floating point
+               // arithmetic can effectively push the coverage
+               // threshold above 1.0, which is impossible/useless.
+               // 1.0 needs to mean exactly 100% coverage.
+               cmd.minCoverage = len(cmd.cgnames)
+       } else {
+               cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
        }
-       cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(len(cmd.cgnames))))
 
        {
                labelsFilename := *outputDir + "/samples.csv"
@@ -224,7 +248,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                var f *os.File
                f, err = os.Create(labelsFilename)
                if err != nil {
-                       return 1
+                       return err
                }
                defer f.Close()
                for i, name := range cmd.cgnames {
@@ -235,13 +259,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        _, 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
+                               return err
                        }
                }
                err = f.Close()
                if err != nil {
                        err = fmt.Errorf("close %s: %w", labelsFilename, err)
-                       return 1
+                       return err
                }
        }
 
@@ -251,11 +275,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                seqname  string // chr1
                pos      int    // distance from start of chromosome to starttag
                tiledata []byte // acgtggcaa...
+               excluded bool   // true if excluded by regions file
+               nexttag  tagID  // tagID of following tile (-1 for last tag of chromosome)
        }
        isdup := map[tagID]bool{}
        reftile := map[tagID]*reftileinfo{}
        for seqname, cseq := range refseq {
                pos := 0
+               lastreftag := tagID(-1)
                for _, libref := range cseq {
                        if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
                                continue
@@ -263,7 +290,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        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
+                               return err
                        }
                        foundthistag := false
                        taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
@@ -292,7 +319,12 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        variant:  libref.Variant,
                                        tiledata: tiledata,
                                        pos:      pos,
+                                       nexttag:  -1,
+                               }
+                               if lastreftag >= 0 {
+                                       reftile[lastreftag].nexttag = libref.Tag
                                }
+                               lastreftag = libref.Tag
                        }
                        pos += len(tiledata) - taglen
                }
@@ -304,13 +336,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                log.Printf("loading regions from %s", *regionsFilename)
                mask, err = makeMask(*regionsFilename, *expandRegions)
                if err != nil {
-                       return 1
+                       return err
                }
                log.Printf("before applying mask, len(reftile) == %d", len(reftile))
                log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
-               for tag, rt := range reftile {
+               for _, rt := range reftile {
                        if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
-                               delete(reftile, tag)
+                               rt.excluded = true
                        }
                }
                log.Printf("after applying mask, len(reftile) == %d", len(reftile))
@@ -325,7 +357,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        var f *os.File
                        f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
                        if err != nil {
-                               return 1
+                               return err
                        }
                        defer os.Remove(f.Name())
                        bufw := bufio.NewWriterSize(f, 1<<24)
@@ -355,7 +387,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
        var onehotChunkSize []uint32
        var onehotXrefs [][]onehotXref
-       if *onehotSingle {
+       if *onehotSingle || *onlyPCA {
                onehotIndirect = make([][2][]uint32, len(infiles))
                onehotChunkSize = make([]uint32, len(infiles))
                onehotXrefs = make([][]onehotXref, len(infiles))
@@ -383,10 +415,22 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        if tv.Ref {
                                                continue
                                        }
+                                       // Skip tile with no
+                                       // corresponding ref tile, if
+                                       // mask is in play (we can't
+                                       // determine coordinates for
+                                       // these)
                                        if mask != nil && reftile[tv.Tag] == nil {
-                                               // Don't waste
-                                               // time/memory on
-                                               // masked-out tiles.
+                                               continue
+                                       }
+                                       // Skip tile whose
+                                       // corresponding ref tile is
+                                       // outside target regions --
+                                       // unless it's a potential
+                                       // spanning tile.
+                                       if mask != nil && reftile[tv.Tag].excluded &&
+                                               (int(tv.Tag+1) >= len(tagset) ||
+                                                       (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
                                                continue
                                        }
                                        if tv.Tag == cmd.debugTag {
@@ -422,7 +466,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        if err == errSkip {
                                return nil
                        } else if err != nil {
-                               return err
+                               return fmt.Errorf("%04d: DecodeLibrary(%s): err", infileIdx, infile)
                        }
                        tagstart := cgs[cmd.cgnames[0]].StartTag
                        tagend := cgs[cmd.cgnames[0]].EndTag
@@ -436,6 +480,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        for tag, variants := range seq {
                                tag, variants := tag, variants
                                throttleCPU.Go(func() error {
+                                       alleleCoverage := 0
                                        count := make(map[[blake2b.Size256]byte]int, len(variants))
 
                                        rt := reftile[tag]
@@ -449,12 +494,25 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                        v := cg.Variants[idx+allele]
                                                        if v > 0 && len(variants[v].Sequence) > 0 {
                                                                count[variants[v].Blake2b]++
+                                                               alleleCoverage++
                                                        }
                                                        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])
                                                        }
                                                }
                                        }
+                                       if alleleCoverage < cmd.minCoverage*2 {
+                                               idx := int(tag-tagstart) * 2
+                                               for _, cg := range cgs {
+                                                       cg.Variants[idx] = 0
+                                                       cg.Variants[idx+1] = 0
+                                               }
+                                               if tag == cmd.debugTag {
+                                                       log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
+                                               }
+                                               return nil
+                                       }
+
                                        // hash[i] will be the hash of
                                        // the variant(s) that should
                                        // be at rank i (0-based).
@@ -512,8 +570,13 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        var onehotChunk [][]int8
                        var onehotXref []onehotXref
 
-                       annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
-                       log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
+                       var annotationsFilename string
+                       if *onlyPCA {
+                               annotationsFilename = "/dev/null"
+                       } else {
+                               annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
+                               log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
+                       }
                        annof, err := os.Create(annotationsFilename)
                        if err != nil {
                                return err
@@ -523,7 +586,20 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        for tag := tagstart; tag < tagend; tag++ {
                                rt := reftile[tag]
                                if rt == nil && mask != nil {
-                                       // Excluded by specified regions
+                                       // With no ref tile, we don't
+                                       // have coordinates to say
+                                       // this is in the desired
+                                       // regions -- so it's not.
+                                       // TODO: handle ref spanning
+                                       // tile case.
+                                       continue
+                               }
+                               if rt != nil && rt.excluded {
+                                       // TODO: don't skip yet --
+                                       // first check for spanning
+                                       // tile variants that
+                                       // intersect non-excluded ref
+                                       // tiles.
                                        continue
                                }
                                if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
@@ -536,7 +612,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                maxv = v
                                        }
                                }
-                               if *onehotChunked || *onehotSingle {
+                               if *onehotChunked || *onehotSingle || *onlyPCA {
                                        onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
                                        if tag == cmd.debugTag {
                                                log.WithFields(logrus.Fields{
@@ -547,9 +623,17 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        onehotChunk = append(onehotChunk, onehot...)
                                        onehotXref = append(onehotXref, xrefs...)
                                }
+                               if *onlyPCA {
+                                       outcol++
+                                       continue
+                               }
                                if rt == nil {
                                        // Reference does not use any
                                        // variant of this tile
+                                       //
+                                       // TODO: diff against the
+                                       // relevant portion of the
+                                       // ref's spanning tile
                                        outcol++
                                        continue
                                }
@@ -561,16 +645,37 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                variantDiffs := make([][]hgvs.Variant, maxv+1)
                                for v, tv := range variants {
                                        v := remap[v]
-                                       if v == rt.variant || done[v] {
+                                       if v == 0 || v == rt.variant || done[v] {
                                                continue
                                        } else {
                                                done[v] = true
                                        }
-                                       if len(tv.Sequence) < taglen || !bytes.HasSuffix(rt.tiledata, tv.Sequence[len(tv.Sequence)-taglen:]) {
+                                       if len(tv.Sequence) < taglen {
+                                               continue
+                                       }
+                                       // if reftilestr doesn't end
+                                       // in the same tag as tv,
+                                       // extend reftilestr with
+                                       // following ref tiles until
+                                       // it does (up to an arbitrary
+                                       // sanity-check limit)
+                                       reftilestr := reftilestr
+                                       endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
+                                       for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
+                                               rt = reftile[rt.nexttag]
+                                               if rt == nil {
+                                                       break
+                                               }
+                                               reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
+                                       }
+                                       if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
+                                               continue
+                                       }
+                                       if !strings.HasSuffix(reftilestr, endtagstr) {
                                                fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
                                                continue
                                        }
-                                       if lendiff := len(rt.tiledata) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
+                                       if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
                                                fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
                                                continue
                                        }
@@ -669,14 +774,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                debug.FreeOSMemory()
                                throttleNumpyMem.Release()
                        }
-                       if *onehotSingle {
+                       if *onehotSingle || *onlyPCA {
                                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 !(*onehotSingle || *onehotChunked) || *mergeOutput || *hgvsSingle {
+                       if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
                                log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
                                throttleNumpyMem.Acquire()
                                rows := len(cmd.cgnames)
@@ -689,7 +794,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
                                                        break
                                                }
-                                               if mask != nil && reftile[tag] == nil {
+                                               if rt := reftile[tag]; rt == nil || rt.excluded {
                                                        continue
                                                }
                                                if v == 0 {
@@ -727,7 +832,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                })
        }
        if err = throttleMem.Wait(); err != nil {
-               return 1
+               return err
        }
 
        if *hgvsChunked {
@@ -737,14 +842,14 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                }
                err = encodeHGVS.Wait()
                if err != nil {
-                       return 1
+                       return err
                }
                for seqname := range refseq {
                        log.Infof("%s: reading hgvsCols from temp file", seqname)
                        f := tmpHGVSCols[seqname]
                        _, err = f.Seek(0, io.SeekStart)
                        if err != nil {
-                               return 1
+                               return err
                        }
                        var hgvsCols hgvsColSet
                        dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
@@ -752,7 +857,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                err = dec.Decode(&hgvsCols)
                        }
                        if err != io.EOF {
-                               return 1
+                               return err
                        }
                        log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
                        variants := make([]hgvs.Variant, 0, len(hgvsCols))
@@ -783,7 +888,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        }
                        err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
                        if err != nil {
-                               return 1
+                               return err
                        }
                        out = nil
 
@@ -795,7 +900,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        }
                        err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
                        if err != nil {
-                               return 1
+                               return err
                        }
                }
        }
@@ -807,7 +912,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
                        annof, err = os.Create(annoFilename)
                        if err != nil {
-                               return 1
+                               return err
                        }
                        annow = bufio.NewWriterSize(annof, 1<<20)
                }
@@ -837,12 +942,12 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        log.Infof("reading %s", annotationsFilename)
                        buf, err := os.ReadFile(annotationsFilename)
                        if err != nil {
-                               return 1
+                               return err
                        }
                        if *mergeOutput {
                                err = os.Remove(annotationsFilename)
                                if err != nil {
-                                       return 1
+                                       return err
                                }
                        }
                        for _, line := range bytes.Split(buf, []byte{'\n'}) {
@@ -885,7 +990,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                        rt, ok := reftile[tagID(tag)]
                                        if !ok {
                                                err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
-                                               return 1
+                                               return err
                                        }
                                        for ph := 0; ph < 2; ph++ {
                                                for row := 0; row < rows; row++ {
@@ -925,15 +1030,15 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                if *mergeOutput {
                        err = annow.Flush()
                        if err != nil {
-                               return 1
+                               return err
                        }
                        err = annof.Close()
                        if err != nil {
-                               return 1
+                               return err
                        }
                        err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
                        if err != nil {
-                               return 1
+                               return err
                        }
                }
                out = nil
@@ -959,18 +1064,18 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        }
                        err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
                        if err != nil {
-                               return 1
+                               return err
                        }
 
                        fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
                        log.Printf("writing hgvs labels: %s", fnm)
                        err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
                        if err != nil {
-                               return 1
+                               return err
                        }
                }
        }
-       if *onehotSingle {
+       if *onehotSingle || *onlyPCA {
                nzCount := 0
                for _, part := range onehotIndirect {
                        nzCount += len(part[0])
@@ -995,40 +1100,103 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        onehotXrefs[i] = nil
                        debug.FreeOSMemory()
                }
-               fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
-               err = writeNumpyUint32(fnm, onehot, 2, nzCount)
-               if err != nil {
-                       return 1
+               if *onehotSingle {
+                       fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
+                       err = writeNumpyUint32(fnm, onehot, 2, nzCount)
+                       if err != nil {
+                               return err
+                       }
+                       fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
+                       err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
+                       if err != nil {
+                               return err
+                       }
                }
-               fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
-               err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
-               if err != nil {
-                       return 1
+               if *onlyPCA {
+                       cols := 0
+                       for _, c := range onehot[nzCount:] {
+                               if int(c) >= cols {
+                                       cols = int(c) + 1
+                               }
+                       }
+                       if cols == 0 {
+                               return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
+                       }
+                       log.Printf("have %d one-hot cols", cols)
+                       stride := 1
+                       for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
+                               cols = cols / 2
+                               stride = stride * 2
+                       }
+                       log.Printf("creating matrix: %d rows, %d cols, stride %d", len(cmd.cgnames), cols, stride)
+                       mtx := mat.NewDense(len(cmd.cgnames), cols, nil)
+                       for i, c := range onehot[nzCount:] {
+                               if int(c/2)%stride == 0 {
+                                       mtx.Set(int(onehot[i]), int(c/2)/stride*2+int(c)%2, 1)
+                               }
+                       }
+                       log.Print("fitting")
+                       transformer := nlp.NewPCA(*pcaComponents)
+                       transformer.Fit(mtx.T())
+                       log.Printf("transforming")
+                       pca, err := transformer.Transform(mtx.T())
+                       if err != nil {
+                               return err
+                       }
+                       pca = pca.T()
+                       outrows, outcols := pca.Dims()
+                       log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
+                       out := make([]float64, outrows*outcols)
+                       for i := 0; i < outrows; i++ {
+                               for j := 0; j < outcols; j++ {
+                                       out[i*outcols+j] = pca.At(i, j)
+                               }
+                       }
+                       fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
+                       log.Printf("writing numpy: %s", fnm)
+                       output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
+                       if err != nil {
+                               return err
+                       }
+                       npw, err := gonpy.NewWriter(nopCloser{output})
+                       if err != nil {
+                               return fmt.Errorf("gonpy.NewWriter: %w", err)
+                       }
+                       npw.Shape = []int{outrows, outcols}
+                       err = npw.WriteFloat64(out)
+                       if err != nil {
+                               return fmt.Errorf("WriteFloat64: %w", err)
+                       }
+                       err = output.Close()
+                       if err != nil {
+                               return err
+                       }
+                       log.Print("done")
                }
        }
-       if !*mergeOutput && !*onehotChunked && !*onehotSingle {
+       if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
                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
+                       return err
                }
                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
+                               return err
                        }
                }
                err = f.Close()
                if err != nil {
                        err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
-                       return 1
+                       return err
                }
        }
-       return 0
+       return nil
 }
 
 // Read case/control files, remove non-case/control entries from
@@ -1293,7 +1461,7 @@ func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantI
        for _, cg := range cgs {
                alleles := 0
                for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
-                       if v > 0 && int(v) < len(seq[tagoffset]) && len(seq[tagoffset][v].Sequence) > 0 {
+                       if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
                                alleles++
                        }
                }