20753: Fix column offset in full matrix when ref tile did not place.
[lightning.git] / slicenumpy.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "bufio"
9         "bytes"
10         "encoding/gob"
11         "encoding/json"
12         "errors"
13         "flag"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "math"
18         "net/http"
19         _ "net/http/pprof"
20         "os"
21         "regexp"
22         "runtime"
23         "runtime/debug"
24         "sort"
25         "strconv"
26         "strings"
27         "sync/atomic"
28         "unsafe"
29
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"
38 )
39
40 const annotationMaxTileSpan = 100
41
42 type sliceNumpy struct {
43         filter             filter
44         threads            int
45         chi2Cases          []bool
46         chi2PValue         float64
47         pvalueMinFrequency float64
48         maxFrequency       float64
49         pcaComponents      int
50         minCoverage        int
51         minCoverageAll     bool
52         includeVariant1    bool
53         debugTag           tagID
54
55         cgnames         []string
56         samples         []sampleInfo
57         trainingSet     []int // samples index => training set index, or -1 if not in training set
58         trainingSetSize int
59         pvalue          func(onehot []bool) float64
60         pvalueCallCount int64
61 }
62
63 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
64         err := cmd.run(prog, args, stdin, stdout, stderr)
65         if err != nil {
66                 fmt.Fprintf(stderr, "%s\n", err)
67                 return 1
68         }
69         return 0
70 }
71
72 func (cmd *sliceNumpy) run(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
73         flags := flag.NewFlagSet("", flag.ContinueOnError)
74         flags.SetOutput(stderr)
75         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
76         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
77         arvadosRAM := flags.Int("arvados-ram", 750000000000, "amount of memory to request for arvados container (`bytes`)")
78         arvadosVCPUs := flags.Int("arvados-vcpus", 96, "number of VCPUs to request for arvados container")
79         projectUUID := flags.String("project", "", "project `UUID` for output data")
80         priority := flags.Int("priority", 500, "container request priority")
81         preemptible := flags.Bool("preemptible", true, "request preemptible instance")
82         inputDir := flags.String("input-dir", "./in", "input `directory`")
83         outputDir := flags.String("output-dir", "./out", "output `directory`")
84         ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
85         regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
86         expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
87         mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
88         hgvsSingle := flags.Bool("single-hgvs-matrix", false, "also generate hgvs-based matrix")
89         hgvsChunked := flags.Bool("chunked-hgvs-matrix", false, "also generate hgvs-based matrix per chromosome")
90         onehotSingle := flags.Bool("single-onehot", false, "generate one-hot tile-based matrix")
91         onehotChunked := flags.Bool("chunked-onehot", false, "generate one-hot tile-based matrix per input chunk")
92         samplesFilename := flags.String("samples", "", "`samples.csv` file with training/validation and case/control groups (see 'lightning choose-samples')")
93         caseControlOnly := flags.Bool("case-control-only", false, "drop samples that are not in case/control groups")
94         onlyPCA := flags.Bool("pca", false, "run principal component analysis, write components to pca.npy and samples.csv")
95         flags.IntVar(&cmd.pcaComponents, "pca-components", 4, "number of PCA components to compute / use in logistic regression")
96         maxPCATiles := flags.Int("max-pca-tiles", 0, "maximum tiles to use as PCA input (filter, then drop every 2nd colum pair until below max)")
97         debugTag := flags.Int("debug-tag", -1, "log debugging details about specified tag")
98         flags.BoolVar(&cmd.minCoverageAll, "min-coverage-all", false, "apply -min-coverage filter based on all samples, not just training set")
99         flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads, and number of VCPUs to request for arvados container")
100         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")
101         flags.Float64Var(&cmd.pvalueMinFrequency, "pvalue-min-frequency", 0.01, "skip p-value calculation on tile variants below this frequency in the training set")
102         flags.Float64Var(&cmd.maxFrequency, "max-frequency", 1, "do not output variants above this frequency in the training set")
103         flags.BoolVar(&cmd.includeVariant1, "include-variant-1", false, "include most common variant when building one-hot matrix")
104         cmd.filter.Flags(flags)
105         err := flags.Parse(args)
106         if err == flag.ErrHelp {
107                 return nil
108         } else if err != nil {
109                 return err
110         } else if flags.NArg() > 0 {
111                 return fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
112         }
113
114         if *pprof != "" {
115                 go func() {
116                         log.Println(http.ListenAndServe(*pprof, nil))
117                 }()
118         }
119
120         if cmd.chi2PValue != 1 && *samplesFilename == "" {
121                 return fmt.Errorf("cannot use provided -chi2-p-value=%f because -samples= value is empty", cmd.chi2PValue)
122         }
123
124         cmd.debugTag = tagID(*debugTag)
125
126         if !*runlocal {
127                 runner := arvadosContainerRunner{
128                         Name:        "lightning slice-numpy",
129                         Client:      arvados.NewClientFromEnv(),
130                         ProjectUUID: *projectUUID,
131                         RAM:         int64(*arvadosRAM),
132                         VCPUs:       *arvadosVCPUs,
133                         Priority:    *priority,
134                         KeepCache:   2,
135                         APIAccess:   true,
136                         Preemptible: *preemptible,
137                 }
138                 err = runner.TranslatePaths(inputDir, regionsFilename, samplesFilename)
139                 if err != nil {
140                         return err
141                 }
142                 runner.Args = []string{"slice-numpy", "-local=true",
143                         "-pprof=:6060",
144                         "-input-dir=" + *inputDir,
145                         "-output-dir=/mnt/output",
146                         "-threads=" + fmt.Sprintf("%d", cmd.threads),
147                         "-regions=" + *regionsFilename,
148                         "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
149                         "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
150                         "-single-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsSingle),
151                         "-chunked-hgvs-matrix=" + fmt.Sprintf("%v", *hgvsChunked),
152                         "-single-onehot=" + fmt.Sprintf("%v", *onehotSingle),
153                         "-chunked-onehot=" + fmt.Sprintf("%v", *onehotChunked),
154                         "-samples=" + *samplesFilename,
155                         "-case-control-only=" + fmt.Sprintf("%v", *caseControlOnly),
156                         "-min-coverage-all=" + fmt.Sprintf("%v", cmd.minCoverageAll),
157                         "-pca=" + fmt.Sprintf("%v", *onlyPCA),
158                         "-pca-components=" + fmt.Sprintf("%d", cmd.pcaComponents),
159                         "-max-pca-tiles=" + fmt.Sprintf("%d", *maxPCATiles),
160                         "-chi2-p-value=" + fmt.Sprintf("%f", cmd.chi2PValue),
161                         "-pvalue-min-frequency=" + fmt.Sprintf("%f", cmd.pvalueMinFrequency),
162                         "-max-frequency=" + fmt.Sprintf("%f", cmd.maxFrequency),
163                         "-include-variant-1=" + fmt.Sprintf("%v", cmd.includeVariant1),
164                         "-debug-tag=" + fmt.Sprintf("%d", cmd.debugTag),
165                 }
166                 runner.Args = append(runner.Args, cmd.filter.Args()...)
167                 var output string
168                 output, err = runner.Run()
169                 if err != nil {
170                         return err
171                 }
172                 fmt.Fprintln(stdout, output)
173                 return nil
174         }
175
176         infiles, err := allFiles(*inputDir, matchGobFile)
177         if err != nil {
178                 return err
179         }
180         if len(infiles) == 0 {
181                 err = fmt.Errorf("no input files found in %s", *inputDir)
182                 return err
183         }
184         sort.Strings(infiles)
185
186         var refseq map[string][]tileLibRef
187         var reftiledata = make(map[tileLibRef][]byte, 11000000)
188         in0, err := open(infiles[0])
189         if err != nil {
190                 return err
191         }
192
193         matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
194         if err != nil {
195                 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
196                 return err
197         }
198
199         if *samplesFilename != "" {
200                 cmd.samples, err = loadSampleInfo(*samplesFilename)
201                 if err != nil {
202                         return err
203                 }
204         } else if *caseControlOnly {
205                 return fmt.Errorf("-case-control-only does not make sense without -samples")
206         }
207
208         cmd.cgnames = nil
209         var tagset [][]byte
210         err = DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
211                 if len(ent.TagSet) > 0 {
212                         tagset = ent.TagSet
213                 }
214                 for _, cseq := range ent.CompactSequences {
215                         if cseq.Name == *ref || *ref == "" {
216                                 refseq = cseq.TileSequences
217                         }
218                 }
219                 for _, cg := range ent.CompactGenomes {
220                         if matchGenome.MatchString(cg.Name) {
221                                 cmd.cgnames = append(cmd.cgnames, cg.Name)
222                         }
223                 }
224                 for _, tv := range ent.TileVariants {
225                         if tv.Ref {
226                                 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
227                         }
228                 }
229                 return nil
230         })
231         if err != nil {
232                 return err
233         }
234         in0.Close()
235         if refseq == nil {
236                 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
237                 return err
238         }
239         if len(tagset) == 0 {
240                 err = fmt.Errorf("tagset not found")
241                 return err
242         }
243
244         taglib := &tagLibrary{}
245         err = taglib.setTags(tagset)
246         if err != nil {
247                 return err
248         }
249         taglen := taglib.TagLen()
250         sort.Strings(cmd.cgnames)
251
252         if len(cmd.cgnames) == 0 {
253                 return fmt.Errorf("fatal: 0 matching samples in library, nothing to do")
254         }
255         cmd.trainingSet = make([]int, len(cmd.cgnames))
256         if *samplesFilename == "" {
257                 cmd.trainingSetSize = len(cmd.cgnames)
258                 for i, name := range cmd.cgnames {
259                         cmd.samples = append(cmd.samples, sampleInfo{
260                                 id:         trimFilenameForLabel(name),
261                                 isTraining: true,
262                         })
263                         cmd.trainingSet[i] = i
264                 }
265         } else if len(cmd.cgnames) != len(cmd.samples) {
266                 return fmt.Errorf("mismatched sample list: %d samples in library, %d in %s", len(cmd.cgnames), len(cmd.samples), *samplesFilename)
267         } else {
268                 for i, name := range cmd.cgnames {
269                         if s := trimFilenameForLabel(name); s != cmd.samples[i].id {
270                                 return fmt.Errorf("mismatched sample list: sample %d is %q in library, %q in %s", i, s, cmd.samples[i].id, *samplesFilename)
271                         }
272                 }
273                 if *caseControlOnly {
274                         for i := 0; i < len(cmd.samples); i++ {
275                                 if !cmd.samples[i].isTraining && !cmd.samples[i].isValidation {
276                                         if i+1 < len(cmd.samples) {
277                                                 copy(cmd.samples[i:], cmd.samples[i+1:])
278                                                 copy(cmd.cgnames[i:], cmd.cgnames[i+1:])
279                                         }
280                                         cmd.samples = cmd.samples[:len(cmd.samples)-1]
281                                         cmd.cgnames = cmd.cgnames[:len(cmd.cgnames)-1]
282                                         i--
283                                 }
284                         }
285                 }
286                 cmd.chi2Cases = nil
287                 cmd.trainingSetSize = 0
288                 for i := range cmd.cgnames {
289                         if cmd.samples[i].isTraining {
290                                 cmd.trainingSet[i] = cmd.trainingSetSize
291                                 cmd.trainingSetSize++
292                                 cmd.chi2Cases = append(cmd.chi2Cases, cmd.samples[i].isCase)
293                         } else {
294                                 cmd.trainingSet[i] = -1
295                         }
296                 }
297                 if cmd.pvalue == nil {
298                         cmd.pvalue = func(onehot []bool) float64 {
299                                 return pvalue(onehot, cmd.chi2Cases)
300                         }
301                 }
302         }
303
304         if cmd.minCoverageAll {
305                 cmd.minCoverage = len(cmd.cgnames)
306         } else {
307                 cmd.minCoverage = cmd.trainingSetSize
308         }
309         if cmd.filter.MinCoverage < 1 {
310                 cmd.minCoverage = int(math.Ceil(cmd.filter.MinCoverage * float64(cmd.minCoverage)))
311         }
312
313         if len(cmd.samples[0].pcaComponents) > 0 {
314                 cmd.pvalue = glmPvalueFunc(cmd.samples, cmd.pcaComponents)
315                 // Unfortunately, statsmodel/glm lib logs stuff to
316                 // os.Stdout when it panics on an unsolvable
317                 // problem. We recover() from the panic in glm.go, but
318                 // we also need to commandeer os.Stdout to avoid
319                 // producing large quantities of logs.
320                 stdoutWas := os.Stdout
321                 defer func() { os.Stdout = stdoutWas }()
322                 os.Stdout, err = os.Open(os.DevNull)
323                 if err != nil {
324                         return err
325                 }
326         }
327
328         // cgnamemap[name]==true for samples that we are including in
329         // output
330         cgnamemap := map[string]bool{}
331         for _, name := range cmd.cgnames {
332                 cgnamemap[name] = true
333         }
334
335         err = writeSampleInfo(cmd.samples, *outputDir)
336         if err != nil {
337                 return err
338         }
339
340         log.Info("indexing reference tiles")
341         type reftileinfo struct {
342                 variant  tileVariantID
343                 seqname  string // chr1
344                 pos      int    // distance from start of chromosome to starttag
345                 tiledata []byte // acgtggcaa...
346                 excluded bool   // true if excluded by regions file
347                 nexttag  tagID  // tagID of following tile (-1 for last tag of chromosome)
348         }
349         isdup := map[tagID]bool{}
350         reftile := map[tagID]*reftileinfo{}
351         for seqname, cseq := range refseq {
352                 pos := 0
353                 lastreftag := tagID(-1)
354                 for _, libref := range cseq {
355                         if cmd.filter.MaxTag >= 0 && libref.Tag > tagID(cmd.filter.MaxTag) {
356                                 continue
357                         }
358                         tiledata := reftiledata[libref]
359                         if len(tiledata) == 0 {
360                                 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
361                                 return err
362                         }
363                         foundthistag := false
364                         taglib.FindAll(tiledata[:len(tiledata)-1], func(tagid tagID, offset, _ int) {
365                                 if !foundthistag && tagid == libref.Tag {
366                                         foundthistag = true
367                                         return
368                                 }
369                                 if dupref, ok := reftile[tagid]; ok {
370                                         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)
371                                         delete(reftile, tagid)
372                                 } else {
373                                         log.Printf("found tag %d at offset %d inside tile variant %+v on %s @ %d", tagid, offset, libref, seqname, pos+offset+1)
374                                 }
375                                 isdup[tagid] = true
376                         })
377                         if isdup[libref.Tag] {
378                                 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
379                         } else if reftile[libref.Tag] != nil {
380                                 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)
381                                 delete(reftile, libref.Tag)
382                                 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
383                                 isdup[libref.Tag] = true
384                         } else {
385                                 reftile[libref.Tag] = &reftileinfo{
386                                         seqname:  seqname,
387                                         variant:  libref.Variant,
388                                         tiledata: tiledata,
389                                         pos:      pos,
390                                         nexttag:  -1,
391                                 }
392                                 if lastreftag >= 0 {
393                                         reftile[lastreftag].nexttag = libref.Tag
394                                 }
395                                 lastreftag = libref.Tag
396                         }
397                         pos += len(tiledata) - taglen
398                 }
399                 log.Printf("... %s done, len %d", seqname, pos+taglen)
400         }
401
402         var mask *mask
403         if *regionsFilename != "" {
404                 log.Printf("loading regions from %s", *regionsFilename)
405                 mask, err = makeMask(*regionsFilename, *expandRegions)
406                 if err != nil {
407                         return err
408                 }
409                 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
410                 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
411                 for _, rt := range reftile {
412                         if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
413                                 rt.excluded = true
414                         }
415                 }
416                 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
417         }
418
419         type hgvsColSet map[hgvs.Variant][2][]int8
420         encodeHGVS := throttle{Max: len(refseq)}
421         encodeHGVSTodo := map[string]chan hgvsColSet{}
422         tmpHGVSCols := map[string]*os.File{}
423         if *hgvsChunked {
424                 for seqname := range refseq {
425                         var f *os.File
426                         f, err = os.Create(*outputDir + "/tmp." + seqname + ".gob")
427                         if err != nil {
428                                 return err
429                         }
430                         defer os.Remove(f.Name())
431                         bufw := bufio.NewWriterSize(f, 1<<24)
432                         enc := gob.NewEncoder(bufw)
433                         tmpHGVSCols[seqname] = f
434                         todo := make(chan hgvsColSet, 128)
435                         encodeHGVSTodo[seqname] = todo
436                         encodeHGVS.Go(func() error {
437                                 for colset := range todo {
438                                         err := enc.Encode(colset)
439                                         if err != nil {
440                                                 encodeHGVS.Report(err)
441                                                 for range todo {
442                                                 }
443                                                 return err
444                                         }
445                                 }
446                                 return bufw.Flush()
447                         })
448                 }
449         }
450
451         var toMerge [][]int16
452         if *mergeOutput || *hgvsSingle {
453                 toMerge = make([][]int16, len(infiles))
454         }
455         var onehotIndirect [][2][]uint32 // [chunkIndex][axis][index]
456         var onehotChunkSize []uint32
457         var onehotXrefs [][]onehotXref
458         if *onehotSingle || *onlyPCA {
459                 onehotIndirect = make([][2][]uint32, len(infiles))
460                 onehotChunkSize = make([]uint32, len(infiles))
461                 onehotXrefs = make([][]onehotXref, len(infiles))
462         }
463         chunkStartTag := make([]tagID, len(infiles))
464
465         throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
466         throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
467         log.Info("generating annotations and numpy matrix for each slice")
468         var errSkip = errors.New("skip infile")
469         var done int64
470         for infileIdx, infile := range infiles {
471                 infileIdx, infile := infileIdx, infile
472                 throttleMem.Go(func() error {
473                         seq := make(map[tagID][]TileVariant, 50000)
474                         cgs := make(map[string]CompactGenome, len(cmd.cgnames))
475                         f, err := open(infile)
476                         if err != nil {
477                                 return err
478                         }
479                         defer f.Close()
480                         log.Infof("%04d: reading %s", infileIdx, infile)
481                         err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
482                                 for _, tv := range ent.TileVariants {
483                                         if tv.Ref {
484                                                 continue
485                                         }
486                                         // Skip tile with no
487                                         // corresponding ref tile, if
488                                         // mask is in play (we can't
489                                         // determine coordinates for
490                                         // these)
491                                         if mask != nil && reftile[tv.Tag] == nil {
492                                                 continue
493                                         }
494                                         // Skip tile whose
495                                         // corresponding ref tile is
496                                         // outside target regions --
497                                         // unless it's a potential
498                                         // spanning tile.
499                                         if mask != nil && reftile[tv.Tag].excluded &&
500                                                 (int(tv.Tag+1) >= len(tagset) ||
501                                                         (bytes.HasSuffix(tv.Sequence, tagset[tv.Tag+1]) && reftile[tv.Tag+1] != nil && !reftile[tv.Tag+1].excluded)) {
502                                                 continue
503                                         }
504                                         if tv.Tag == cmd.debugTag {
505                                                 log.Printf("infile %d %s tag %d variant %d hash %x", infileIdx, infile, tv.Tag, tv.Variant, tv.Blake2b[:3])
506                                         }
507                                         variants := seq[tv.Tag]
508                                         if len(variants) == 0 {
509                                                 variants = make([]TileVariant, 100)
510                                         }
511                                         for len(variants) <= int(tv.Variant) {
512                                                 variants = append(variants, TileVariant{})
513                                         }
514                                         variants[int(tv.Variant)] = tv
515                                         seq[tv.Tag] = variants
516                                 }
517                                 for _, cg := range ent.CompactGenomes {
518                                         if cmd.filter.MaxTag >= 0 && cg.StartTag > tagID(cmd.filter.MaxTag) {
519                                                 return errSkip
520                                         }
521                                         if !cgnamemap[cg.Name] {
522                                                 continue
523                                         }
524                                         // pad to full slice size
525                                         // to avoid out-of-bounds
526                                         // checks later
527                                         if sliceSize := 2 * int(cg.EndTag-cg.StartTag); len(cg.Variants) < sliceSize {
528                                                 cg.Variants = append(cg.Variants, make([]tileVariantID, sliceSize-len(cg.Variants))...)
529                                         }
530                                         cgs[cg.Name] = cg
531                                 }
532                                 return nil
533                         })
534                         if err == errSkip {
535                                 return nil
536                         } else if err != nil {
537                                 return fmt.Errorf("%04d: DecodeLibrary(%s): %w", infileIdx, infile, err)
538                         }
539                         tagstart := cgs[cmd.cgnames[0]].StartTag
540                         tagend := cgs[cmd.cgnames[0]].EndTag
541                         chunkStartTag[infileIdx] = tagstart
542
543                         // TODO: filters
544
545                         log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
546                         variantRemap := make([][]tileVariantID, tagend-tagstart)
547                         throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
548                         for tag, variants := range seq {
549                                 tag, variants := tag, variants
550                                 throttleCPU.Go(func() error {
551                                         alleleCoverage := 0
552                                         count := make(map[[blake2b.Size256]byte]int, len(variants))
553
554                                         rt := reftile[tag]
555                                         if rt != nil {
556                                                 count[blake2b.Sum256(rt.tiledata)] = 0
557                                         }
558
559                                         for cgidx, cgname := range cmd.cgnames {
560                                                 if !cmd.minCoverageAll && !cmd.samples[cgidx].isTraining {
561                                                         continue
562                                                 }
563                                                 cg := cgs[cgname]
564                                                 idx := int(tag-tagstart) * 2
565                                                 for allele := 0; allele < 2; allele++ {
566                                                         v := cg.Variants[idx+allele]
567                                                         if v > 0 && len(variants[v].Sequence) > 0 {
568                                                                 count[variants[v].Blake2b]++
569                                                                 alleleCoverage++
570                                                         }
571                                                         if v > 0 && tag == cmd.debugTag {
572                                                                 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])
573                                                         }
574                                                 }
575                                         }
576                                         if alleleCoverage < cmd.minCoverage*2 {
577                                                 idx := int(tag-tagstart) * 2
578                                                 for _, cg := range cgs {
579                                                         cg.Variants[idx] = 0
580                                                         cg.Variants[idx+1] = 0
581                                                 }
582                                                 if tag == cmd.debugTag {
583                                                         log.Printf("tag %d alleleCoverage %d < min %d, sample data wiped", tag, alleleCoverage, cmd.minCoverage*2)
584                                                 }
585                                                 return nil
586                                         }
587
588                                         // hash[i] will be the hash of
589                                         // the variant(s) that should
590                                         // be at rank i (0-based).
591                                         hash := make([][blake2b.Size256]byte, 0, len(count))
592                                         for b := range count {
593                                                 hash = append(hash, b)
594                                         }
595                                         sort.Slice(hash, func(i, j int) bool {
596                                                 bi, bj := &hash[i], &hash[j]
597                                                 if ci, cj := count[*bi], count[*bj]; ci != cj {
598                                                         return ci > cj
599                                                 } else {
600                                                         return bytes.Compare((*bi)[:], (*bj)[:]) < 0
601                                                 }
602                                         })
603                                         // rank[b] will be the 1-based
604                                         // new variant number for
605                                         // variants whose hash is b.
606                                         rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
607                                         for i, h := range hash {
608                                                 rank[h] = tileVariantID(i + 1)
609                                         }
610                                         if tag == cmd.debugTag {
611                                                 for h, r := range rank {
612                                                         log.Printf("tag %d rank(%x) = %v", tag, h[:3], r)
613                                                 }
614                                         }
615                                         // remap[v] will be the new
616                                         // variant number for original
617                                         // variant number v.
618                                         remap := make([]tileVariantID, len(variants))
619                                         for i, tv := range variants {
620                                                 remap[i] = rank[tv.Blake2b]
621                                         }
622                                         if tag == cmd.debugTag {
623                                                 for in, out := range remap {
624                                                         if out > 0 {
625                                                                 log.Printf("tag %d remap %d => %d", tag, in, out)
626                                                         }
627                                                 }
628                                         }
629                                         variantRemap[tag-tagstart] = remap
630                                         if rt != nil {
631                                                 refrank := rank[blake2b.Sum256(rt.tiledata)]
632                                                 if tag == cmd.debugTag {
633                                                         log.Printf("tag %d reftile variant %d => %d", tag, rt.variant, refrank)
634                                                 }
635                                                 rt.variant = refrank
636                                         }
637                                         return nil
638                                 })
639                         }
640                         throttleCPU.Wait()
641
642                         var onehotChunk [][]int8
643                         var onehotXref []onehotXref
644
645                         var annotationsFilename string
646                         if *onlyPCA {
647                                 annotationsFilename = "/dev/null"
648                         } else {
649                                 annotationsFilename = fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
650                                 log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
651                         }
652                         annof, err := os.Create(annotationsFilename)
653                         if err != nil {
654                                 return err
655                         }
656                         annow := bufio.NewWriterSize(annof, 1<<20)
657                         outcol := 0
658                         for tag := tagstart; tag < tagend; tag++ {
659                                 rt := reftile[tag]
660                                 if rt == nil && mask != nil {
661                                         // With no ref tile, we don't
662                                         // have coordinates to say
663                                         // this is in the desired
664                                         // regions -- so it's not.
665                                         // TODO: handle ref spanning
666                                         // tile case.
667                                         continue
668                                 }
669                                 if rt != nil && rt.excluded {
670                                         // TODO: don't skip yet --
671                                         // first check for spanning
672                                         // tile variants that
673                                         // intersect non-excluded ref
674                                         // tiles.
675                                         continue
676                                 }
677                                 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
678                                         break
679                                 }
680                                 remap := variantRemap[tag-tagstart]
681                                 if remap == nil {
682                                         // was not assigned above,
683                                         // because minCoverage
684                                         outcol++
685                                         continue
686                                 }
687                                 maxv := tileVariantID(0)
688                                 for _, v := range remap {
689                                         if maxv < v {
690                                                 maxv = v
691                                         }
692                                 }
693                                 if *onehotChunked || *onehotSingle || *onlyPCA {
694                                         onehot, xrefs := cmd.tv2homhet(cgs, maxv, remap, tag, tagstart, seq)
695                                         if tag == cmd.debugTag {
696                                                 log.WithFields(logrus.Fields{
697                                                         "onehot": onehot,
698                                                         "xrefs":  xrefs,
699                                                 }).Info("tv2homhet()")
700                                         }
701                                         onehotChunk = append(onehotChunk, onehot...)
702                                         onehotXref = append(onehotXref, xrefs...)
703                                 }
704                                 if *onlyPCA {
705                                         outcol++
706                                         continue
707                                 }
708                                 if rt == nil {
709                                         // Reference does not use any
710                                         // variant of this tile
711                                         //
712                                         // TODO: diff against the
713                                         // relevant portion of the
714                                         // ref's spanning tile
715                                         outcol++
716                                         continue
717                                 }
718                                 fmt.Fprintf(annow, "%d,%d,%d,=,%s,%d,,,\n", tag, outcol, rt.variant, rt.seqname, rt.pos)
719                                 variants := seq[tag]
720                                 reftilestr := strings.ToUpper(string(rt.tiledata))
721
722                                 done := make([]bool, maxv+1)
723                                 variantDiffs := make([][]hgvs.Variant, maxv+1)
724                                 for v, tv := range variants {
725                                         v := remap[v]
726                                         if v == 0 || v == rt.variant || done[v] {
727                                                 continue
728                                         } else {
729                                                 done[v] = true
730                                         }
731                                         if len(tv.Sequence) < taglen {
732                                                 continue
733                                         }
734                                         // if reftilestr doesn't end
735                                         // in the same tag as tv,
736                                         // extend reftilestr with
737                                         // following ref tiles until
738                                         // it does (up to an arbitrary
739                                         // sanity-check limit)
740                                         reftilestr := reftilestr
741                                         endtagstr := strings.ToUpper(string(tv.Sequence[len(tv.Sequence)-taglen:]))
742                                         for i, rt := 0, rt; i < annotationMaxTileSpan && !strings.HasSuffix(reftilestr, endtagstr) && rt.nexttag >= 0; i++ {
743                                                 rt = reftile[rt.nexttag]
744                                                 if rt == nil {
745                                                         break
746                                                 }
747                                                 reftilestr += strings.ToUpper(string(rt.tiledata[taglen:]))
748                                         }
749                                         if mask != nil && !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(reftilestr)) {
750                                                 continue
751                                         }
752                                         if !strings.HasSuffix(reftilestr, endtagstr) {
753                                                 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
754                                                 continue
755                                         }
756                                         if lendiff := len(reftilestr) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
757                                                 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
758                                                 continue
759                                         }
760                                         diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
761                                         for i := range diffs {
762                                                 diffs[i].Position += rt.pos
763                                         }
764                                         for _, diff := range diffs {
765                                                 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)
766                                         }
767                                         if *hgvsChunked {
768                                                 variantDiffs[v] = diffs
769                                         }
770                                 }
771                                 if *hgvsChunked {
772                                         // We can now determine, for each HGVS
773                                         // variant (diff) in this reftile
774                                         // region, whether a given genome
775                                         // phase/allele (1) has the variant, (0) has
776                                         // =ref or a different variant in that
777                                         // position, or (-1) is lacking
778                                         // coverage / couldn't be diffed.
779                                         hgvsCol := hgvsColSet{}
780                                         for _, diffs := range variantDiffs {
781                                                 for _, diff := range diffs {
782                                                         if _, ok := hgvsCol[diff]; ok {
783                                                                 continue
784                                                         }
785                                                         hgvsCol[diff] = [2][]int8{
786                                                                 make([]int8, len(cmd.cgnames)),
787                                                                 make([]int8, len(cmd.cgnames)),
788                                                         }
789                                                 }
790                                         }
791                                         for row, name := range cmd.cgnames {
792                                                 variants := cgs[name].Variants[(tag-tagstart)*2:]
793                                                 for ph := 0; ph < 2; ph++ {
794                                                         v := variants[ph]
795                                                         if int(v) >= len(remap) {
796                                                                 v = 0
797                                                         } else {
798                                                                 v = remap[v]
799                                                         }
800                                                         if v == rt.variant {
801                                                                 // hgvsCol[*][ph][row] is already 0
802                                                         } else if len(variantDiffs[v]) == 0 {
803                                                                 // lacking coverage / couldn't be diffed
804                                                                 for _, col := range hgvsCol {
805                                                                         col[ph][row] = -1
806                                                                 }
807                                                         } else {
808                                                                 for _, diff := range variantDiffs[v] {
809                                                                         hgvsCol[diff][ph][row] = 1
810                                                                 }
811                                                         }
812                                                 }
813                                         }
814                                         for diff, colpair := range hgvsCol {
815                                                 allele2homhet(colpair)
816                                                 if !cmd.filterHGVScolpair(colpair) {
817                                                         delete(hgvsCol, diff)
818                                                 }
819                                         }
820                                         if len(hgvsCol) > 0 {
821                                                 encodeHGVSTodo[rt.seqname] <- hgvsCol
822                                         }
823                                 }
824                                 outcol++
825                         }
826                         err = annow.Flush()
827                         if err != nil {
828                                 return err
829                         }
830                         err = annof.Close()
831                         if err != nil {
832                                 return err
833                         }
834
835                         if *onehotChunked {
836                                 // transpose onehotChunk[col][row] to numpy[row*ncols+col]
837                                 rows := len(cmd.cgnames)
838                                 cols := len(onehotChunk)
839                                 log.Infof("%04d: preparing onehot numpy (rows=%d, cols=%d, mem=%d)", infileIdx, rows, cols, rows*cols)
840                                 throttleNumpyMem.Acquire()
841                                 out := onehotcols2int8(onehotChunk)
842                                 fnm := fmt.Sprintf("%s/onehot.%04d.npy", *outputDir, infileIdx)
843                                 err = writeNumpyInt8(fnm, out, rows, cols)
844                                 if err != nil {
845                                         return err
846                                 }
847                                 fnm = fmt.Sprintf("%s/onehot-columns.%04d.npy", *outputDir, infileIdx)
848                                 err = writeNumpyInt32(fnm, onehotXref2int32(onehotXref), 4, len(onehotXref))
849                                 if err != nil {
850                                         return err
851                                 }
852                                 debug.FreeOSMemory()
853                                 throttleNumpyMem.Release()
854                         }
855                         if *onehotSingle || *onlyPCA {
856                                 onehotIndirect[infileIdx] = onehotChunk2Indirect(onehotChunk)
857                                 onehotChunkSize[infileIdx] = uint32(len(onehotChunk))
858                                 onehotXrefs[infileIdx] = onehotXref
859                                 n := len(onehotIndirect[infileIdx][0])
860                                 log.Infof("%04d: keeping onehot coordinates in memory (n=%d, mem=%d)", infileIdx, n, n*8*2)
861                         }
862                         if !(*onehotSingle || *onehotChunked || *onlyPCA) || *mergeOutput || *hgvsSingle {
863                                 log.Infof("%04d: preparing numpy (rows=%d, cols=%d)", infileIdx, len(cmd.cgnames), 2*outcol)
864                                 throttleNumpyMem.Acquire()
865                                 rows := len(cmd.cgnames)
866                                 cols := 2 * outcol
867                                 out := make([]int16, rows*cols)
868                                 for row, name := range cmd.cgnames {
869                                         outidx := row * cols
870                                         for col, v := range cgs[name].Variants {
871                                                 tag := tagstart + tagID(col/2)
872                                                 if cmd.filter.MaxTag >= 0 && tag > tagID(cmd.filter.MaxTag) {
873                                                         break
874                                                 }
875                                                 if rt := reftile[tag]; mask != nil && (rt == nil || rt.excluded) {
876                                                         continue
877                                                 }
878                                                 if v == 0 {
879                                                         out[outidx] = 0 // tag not found / spanning tile
880                                                 } else if variants, ok := seq[tag]; ok && int(v) < len(variants) && len(variants[v].Sequence) > 0 {
881                                                         out[outidx] = int16(variantRemap[tag-tagstart][v])
882                                                 } else {
883                                                         out[outidx] = -1 // low quality tile variant
884                                                 }
885                                                 if tag == cmd.debugTag {
886                                                         log.Printf("tag %d row %d col %d outidx %d v %d out %d", tag, row, col, outidx, v, out[outidx])
887                                                 }
888                                                 outidx++
889                                         }
890                                 }
891                                 seq = nil
892                                 cgs = nil
893                                 debug.FreeOSMemory()
894                                 throttleNumpyMem.Release()
895                                 if *mergeOutput || *hgvsSingle {
896                                         log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
897                                         toMerge[infileIdx] = out
898                                 }
899                                 if !*mergeOutput && !*onehotChunked && !*onehotSingle {
900                                         fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
901                                         err = writeNumpyInt16(fnm, out, rows, cols)
902                                         if err != nil {
903                                                 return err
904                                         }
905                                 }
906                         }
907                         debug.FreeOSMemory()
908                         log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
909                         return nil
910                 })
911         }
912         if err = throttleMem.Wait(); err != nil {
913                 return err
914         }
915
916         if *hgvsChunked {
917                 log.Info("flushing hgvsCols temp files")
918                 for seqname := range refseq {
919                         close(encodeHGVSTodo[seqname])
920                 }
921                 err = encodeHGVS.Wait()
922                 if err != nil {
923                         return err
924                 }
925                 for seqname := range refseq {
926                         log.Infof("%s: reading hgvsCols from temp file", seqname)
927                         f := tmpHGVSCols[seqname]
928                         _, err = f.Seek(0, io.SeekStart)
929                         if err != nil {
930                                 return err
931                         }
932                         var hgvsCols hgvsColSet
933                         dec := gob.NewDecoder(bufio.NewReaderSize(f, 1<<24))
934                         for err == nil {
935                                 err = dec.Decode(&hgvsCols)
936                         }
937                         if err != io.EOF {
938                                 return err
939                         }
940                         log.Infof("%s: sorting %d hgvs variants", seqname, len(hgvsCols))
941                         variants := make([]hgvs.Variant, 0, len(hgvsCols))
942                         for v := range hgvsCols {
943                                 variants = append(variants, v)
944                         }
945                         sort.Slice(variants, func(i, j int) bool {
946                                 vi, vj := &variants[i], &variants[j]
947                                 if vi.Position != vj.Position {
948                                         return vi.Position < vj.Position
949                                 } else if vi.Ref != vj.Ref {
950                                         return vi.Ref < vj.Ref
951                                 } else {
952                                         return vi.New < vj.New
953                                 }
954                         })
955                         rows := len(cmd.cgnames)
956                         cols := len(variants) * 2
957                         log.Infof("%s: building hgvs matrix (rows=%d, cols=%d, mem=%d)", seqname, rows, cols, rows*cols)
958                         out := make([]int8, rows*cols)
959                         for varIdx, variant := range variants {
960                                 hgvsCols := hgvsCols[variant]
961                                 for row := range cmd.cgnames {
962                                         for ph := 0; ph < 2; ph++ {
963                                                 out[row*cols+varIdx+ph] = hgvsCols[ph][row]
964                                         }
965                                 }
966                         }
967                         err = writeNumpyInt8(fmt.Sprintf("%s/hgvs.%s.npy", *outputDir, seqname), out, rows, cols)
968                         if err != nil {
969                                 return err
970                         }
971                         out = nil
972
973                         fnm := fmt.Sprintf("%s/hgvs.%s.annotations.csv", *outputDir, seqname)
974                         log.Infof("%s: writing hgvs column labels to %s", seqname, fnm)
975                         var hgvsLabels bytes.Buffer
976                         for varIdx, variant := range variants {
977                                 fmt.Fprintf(&hgvsLabels, "%d,%s:g.%s\n", varIdx, seqname, variant.String())
978                         }
979                         err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0666)
980                         if err != nil {
981                                 return err
982                         }
983                 }
984         }
985
986         if *mergeOutput || *hgvsSingle {
987                 var annow *bufio.Writer
988                 var annof *os.File
989                 if *mergeOutput {
990                         annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
991                         annof, err = os.Create(annoFilename)
992                         if err != nil {
993                                 return err
994                         }
995                         annow = bufio.NewWriterSize(annof, 1<<20)
996                 }
997
998                 rows := len(cmd.cgnames)
999                 cols := 0
1000                 for _, chunk := range toMerge {
1001                         cols += len(chunk) / rows
1002                 }
1003                 log.Infof("merging output matrix (rows=%d, cols=%d, mem=%d) and annotations", rows, cols, rows*cols*2)
1004                 var out []int16
1005                 if *mergeOutput {
1006                         out = make([]int16, rows*cols)
1007                 }
1008                 hgvsCols := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
1009                 startcol := 0
1010                 for outIdx, chunk := range toMerge {
1011                         chunkcols := len(chunk) / rows
1012                         if *mergeOutput {
1013                                 for row := 0; row < rows; row++ {
1014                                         copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
1015                                 }
1016                         }
1017                         toMerge[outIdx] = nil
1018
1019                         annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
1020                         log.Infof("reading %s", annotationsFilename)
1021                         buf, err := os.ReadFile(annotationsFilename)
1022                         if err != nil {
1023                                 return err
1024                         }
1025                         if *mergeOutput {
1026                                 err = os.Remove(annotationsFilename)
1027                                 if err != nil {
1028                                         return err
1029                                 }
1030                         }
1031                         for _, line := range bytes.Split(buf, []byte{'\n'}) {
1032                                 if len(line) == 0 {
1033                                         continue
1034                                 }
1035                                 fields := bytes.SplitN(line, []byte{','}, 9)
1036                                 tag, _ := strconv.Atoi(string(fields[0]))
1037                                 incol, _ := strconv.Atoi(string(fields[1]))
1038                                 tileVariant, _ := strconv.Atoi(string(fields[2]))
1039                                 hgvsID := string(fields[3])
1040                                 seqname := string(fields[4])
1041                                 pos, _ := strconv.Atoi(string(fields[5]))
1042                                 refseq := fields[6]
1043                                 if hgvsID == "" {
1044                                         // Null entry for un-diffable
1045                                         // tile variant
1046                                         continue
1047                                 }
1048                                 if hgvsID == "=" {
1049                                         // Null entry for ref tile
1050                                         continue
1051                                 }
1052                                 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
1053                                         // The tile intersects one of
1054                                         // the selected regions, but
1055                                         // this particular HGVS
1056                                         // variant does not.
1057                                         continue
1058                                 }
1059                                 hgvsColPair := hgvsCols[hgvsID]
1060                                 if hgvsColPair[0] == nil {
1061                                         // values in new columns start
1062                                         // out as -1 ("no data yet")
1063                                         // or 0 ("=ref") here, may
1064                                         // change to 1 ("hgvs variant
1065                                         // present") below, either on
1066                                         // this line or a future line.
1067                                         hgvsColPair = [2][]int16{make([]int16, len(cmd.cgnames)), make([]int16, len(cmd.cgnames))}
1068                                         rt, ok := reftile[tagID(tag)]
1069                                         if !ok {
1070                                                 err = fmt.Errorf("bug: seeing annotations for tag %d, but it has no reftile entry", tag)
1071                                                 return err
1072                                         }
1073                                         for ph := 0; ph < 2; ph++ {
1074                                                 for row := 0; row < rows; row++ {
1075                                                         v := chunk[row*chunkcols+incol*2+ph]
1076                                                         if tileVariantID(v) == rt.variant {
1077                                                                 hgvsColPair[ph][row] = 0
1078                                                         } else {
1079                                                                 hgvsColPair[ph][row] = -1
1080                                                         }
1081                                                 }
1082                                         }
1083                                         hgvsCols[hgvsID] = hgvsColPair
1084                                         if annow != nil {
1085                                                 hgvsref := hgvs.Variant{
1086                                                         Position: pos,
1087                                                         Ref:      string(refseq),
1088                                                         New:      string(refseq),
1089                                                 }
1090                                                 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])
1091                                         }
1092                                 }
1093                                 if annow != nil {
1094                                         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])
1095                                 }
1096                                 for ph := 0; ph < 2; ph++ {
1097                                         for row := 0; row < rows; row++ {
1098                                                 v := chunk[row*chunkcols+incol*2+ph]
1099                                                 if int(v) == tileVariant {
1100                                                         hgvsColPair[ph][row] = 1
1101                                                 }
1102                                         }
1103                                 }
1104                         }
1105
1106                         startcol += chunkcols
1107                 }
1108                 if *mergeOutput {
1109                         err = annow.Flush()
1110                         if err != nil {
1111                                 return err
1112                         }
1113                         err = annof.Close()
1114                         if err != nil {
1115                                 return err
1116                         }
1117                         err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
1118                         if err != nil {
1119                                 return err
1120                         }
1121                 }
1122                 out = nil
1123
1124                 if *hgvsSingle {
1125                         cols = len(hgvsCols) * 2
1126                         log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
1127                         out = make([]int16, rows*cols)
1128                         hgvsIDs := make([]string, 0, cols/2)
1129                         for hgvsID := range hgvsCols {
1130                                 hgvsIDs = append(hgvsIDs, hgvsID)
1131                         }
1132                         sort.Strings(hgvsIDs)
1133                         var hgvsLabels bytes.Buffer
1134                         for idx, hgvsID := range hgvsIDs {
1135                                 fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
1136                                 for ph := 0; ph < 2; ph++ {
1137                                         hgvscol := hgvsCols[hgvsID][ph]
1138                                         for row, val := range hgvscol {
1139                                                 out[row*cols+idx*2+ph] = val
1140                                         }
1141                                 }
1142                         }
1143                         err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
1144                         if err != nil {
1145                                 return err
1146                         }
1147
1148                         fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
1149                         log.Printf("writing hgvs labels: %s", fnm)
1150                         err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
1151                         if err != nil {
1152                                 return err
1153                         }
1154                 }
1155         }
1156         if *onehotSingle || *onlyPCA {
1157                 nzCount := 0
1158                 for _, part := range onehotIndirect {
1159                         nzCount += len(part[0])
1160                 }
1161                 onehot := make([]uint32, nzCount*2) // [r,r,r,...,c,c,c,...]
1162                 var xrefs []onehotXref
1163                 chunkOffset := uint32(0)
1164                 outcol := 0
1165                 for i, part := range onehotIndirect {
1166                         for i := range part[1] {
1167                                 part[1][i] += chunkOffset
1168                         }
1169                         copy(onehot[outcol:], part[0])
1170                         copy(onehot[outcol+nzCount:], part[1])
1171                         xrefs = append(xrefs, onehotXrefs[i]...)
1172
1173                         outcol += len(part[0])
1174                         chunkOffset += onehotChunkSize[i]
1175
1176                         part[0] = nil
1177                         part[1] = nil
1178                         onehotXrefs[i] = nil
1179                         debug.FreeOSMemory()
1180                 }
1181                 if *onehotSingle {
1182                         fnm := fmt.Sprintf("%s/onehot.npy", *outputDir)
1183                         err = writeNumpyUint32(fnm, onehot, 2, nzCount)
1184                         if err != nil {
1185                                 return err
1186                         }
1187                         fnm = fmt.Sprintf("%s/onehot-columns.npy", *outputDir)
1188                         err = writeNumpyInt32(fnm, onehotXref2int32(xrefs), 5, len(xrefs))
1189                         if err != nil {
1190                                 return err
1191                         }
1192                         fnm = fmt.Sprintf("%s/stats.json", *outputDir)
1193                         j, err := json.Marshal(map[string]interface{}{
1194                                 "pvalueCallCount": cmd.pvalueCallCount,
1195                         })
1196                         if err != nil {
1197                                 return err
1198                         }
1199                         err = os.WriteFile(fnm, j, 0777)
1200                         if err != nil {
1201                                 return err
1202                         }
1203                 }
1204                 if *onlyPCA {
1205                         cols := 0
1206                         for _, c := range onehot[nzCount:] {
1207                                 if int(c) >= cols {
1208                                         cols = int(c) + 1
1209                                 }
1210                         }
1211                         if cols == 0 {
1212                                 return fmt.Errorf("cannot do PCA: one-hot matrix is empty")
1213                         }
1214                         log.Printf("have %d one-hot cols", cols)
1215                         stride := 1
1216                         for *maxPCATiles > 0 && cols > *maxPCATiles*2 {
1217                                 cols = (cols + 1) / 2
1218                                 stride = stride * 2
1219                         }
1220                         if cols%2 == 1 {
1221                                 // we work with pairs of columns
1222                                 cols++
1223                         }
1224                         log.Printf("creating full matrix (%d rows) and training matrix (%d rows) with %d cols, stride %d", len(cmd.cgnames), cmd.trainingSetSize, cols, stride)
1225                         mtxFull := mat.NewDense(len(cmd.cgnames), cols, nil)
1226                         mtxTrain := mat.NewDense(cmd.trainingSetSize, cols, nil)
1227                         for i, c := range onehot[nzCount:] {
1228                                 if int(c/2)%stride == 0 {
1229                                         outcol := int(c/2)/stride*2 + int(c)%2
1230                                         mtxFull.Set(int(onehot[i]), outcol, 1)
1231                                         if trainRow := cmd.trainingSet[int(onehot[i])]; trainRow >= 0 {
1232                                                 mtxTrain.Set(trainRow, outcol, 1)
1233                                         }
1234                                 }
1235                         }
1236                         log.Print("fitting")
1237                         transformer := nlp.NewPCA(cmd.pcaComponents)
1238                         transformer.Fit(mtxTrain.T())
1239                         log.Printf("transforming")
1240                         pca, err := transformer.Transform(mtxFull.T())
1241                         if err != nil {
1242                                 return err
1243                         }
1244                         pca = pca.T()
1245                         outrows, outcols := pca.Dims()
1246                         log.Printf("copying result to numpy output array: %d rows, %d cols", outrows, outcols)
1247                         out := make([]float64, outrows*outcols)
1248                         for i := 0; i < outrows; i++ {
1249                                 for j := 0; j < outcols; j++ {
1250                                         out[i*outcols+j] = pca.At(i, j)
1251                                 }
1252                         }
1253                         fnm := fmt.Sprintf("%s/pca.npy", *outputDir)
1254                         log.Printf("writing numpy: %s", fnm)
1255                         output, err := os.OpenFile(fnm, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
1256                         if err != nil {
1257                                 return err
1258                         }
1259                         npw, err := gonpy.NewWriter(nopCloser{output})
1260                         if err != nil {
1261                                 return fmt.Errorf("gonpy.NewWriter: %w", err)
1262                         }
1263                         npw.Shape = []int{outrows, outcols}
1264                         err = npw.WriteFloat64(out)
1265                         if err != nil {
1266                                 return fmt.Errorf("WriteFloat64: %w", err)
1267                         }
1268                         err = output.Close()
1269                         if err != nil {
1270                                 return err
1271                         }
1272                         log.Print("done")
1273
1274                         log.Print("copying pca components to sampleInfo")
1275                         for i := range cmd.samples {
1276                                 cmd.samples[i].pcaComponents = make([]float64, outcols)
1277                                 for c := 0; c < outcols; c++ {
1278                                         cmd.samples[i].pcaComponents[c] = pca.At(i, c)
1279                                 }
1280                         }
1281                         log.Print("done")
1282
1283                         err = writeSampleInfo(cmd.samples, *outputDir)
1284                         if err != nil {
1285                                 return err
1286                         }
1287                 }
1288         }
1289         if !*mergeOutput && !*onehotChunked && !*onehotSingle && !*onlyPCA {
1290                 tagoffsetFilename := *outputDir + "/chunk-tag-offset.csv"
1291                 log.Infof("writing tag offsets to %s", tagoffsetFilename)
1292                 var f *os.File
1293                 f, err = os.Create(tagoffsetFilename)
1294                 if err != nil {
1295                         return err
1296                 }
1297                 defer f.Close()
1298                 for idx, offset := range chunkStartTag {
1299                         _, err = fmt.Fprintf(f, "%q,%d\n", fmt.Sprintf("matrix.%04d.npy", idx), offset)
1300                         if err != nil {
1301                                 err = fmt.Errorf("write %s: %w", tagoffsetFilename, err)
1302                                 return err
1303                         }
1304                 }
1305                 err = f.Close()
1306                 if err != nil {
1307                         err = fmt.Errorf("close %s: %w", tagoffsetFilename, err)
1308                         return err
1309                 }
1310         }
1311
1312         return nil
1313 }
1314
1315 type sampleInfo struct {
1316         id            string
1317         isCase        bool
1318         isControl     bool
1319         isTraining    bool
1320         isValidation  bool
1321         pcaComponents []float64
1322 }
1323
1324 // Read samples.csv file with case/control and training/validation
1325 // flags.
1326 func loadSampleInfo(samplesFilename string) ([]sampleInfo, error) {
1327         var si []sampleInfo
1328         f, err := open(samplesFilename)
1329         if err != nil {
1330                 return nil, err
1331         }
1332         buf, err := io.ReadAll(f)
1333         f.Close()
1334         if err != nil {
1335                 return nil, err
1336         }
1337         lineNum := 0
1338         for _, csv := range bytes.Split(buf, []byte{'\n'}) {
1339                 lineNum++
1340                 if len(csv) == 0 {
1341                         continue
1342                 }
1343                 split := strings.Split(string(csv), ",")
1344                 if len(split) < 4 {
1345                         return nil, fmt.Errorf("%d fields < 4 in %s line %d: %q", len(split), samplesFilename, lineNum, csv)
1346                 }
1347                 if split[0] == "Index" && split[1] == "SampleID" && split[2] == "CaseControl" && split[3] == "TrainingValidation" {
1348                         continue
1349                 }
1350                 idx, err := strconv.Atoi(split[0])
1351                 if err != nil {
1352                         if lineNum == 1 {
1353                                 return nil, fmt.Errorf("header does not look right: %q", csv)
1354                         }
1355                         return nil, fmt.Errorf("%s line %d: index: %s", samplesFilename, lineNum, err)
1356                 }
1357                 if idx != len(si) {
1358                         return nil, fmt.Errorf("%s line %d: index %d out of order", samplesFilename, lineNum, idx)
1359                 }
1360                 var pcaComponents []float64
1361                 if len(split) > 4 {
1362                         for _, s := range split[4:] {
1363                                 f, err := strconv.ParseFloat(s, 64)
1364                                 if err != nil {
1365                                         return nil, fmt.Errorf("%s line %d: cannot parse float %q: %s", samplesFilename, lineNum, s, err)
1366                                 }
1367                                 pcaComponents = append(pcaComponents, f)
1368                         }
1369                 }
1370                 si = append(si, sampleInfo{
1371                         id:            split[1],
1372                         isCase:        split[2] == "1",
1373                         isControl:     split[2] == "0",
1374                         isTraining:    split[3] == "1",
1375                         isValidation:  split[3] == "0" && len(split[2]) > 0, // fix errant 0s in input
1376                         pcaComponents: pcaComponents,
1377                 })
1378         }
1379         return si, nil
1380 }
1381
1382 func writeSampleInfo(samples []sampleInfo, outputDir string) error {
1383         fnm := outputDir + "/samples.csv"
1384         log.Infof("writing sample metadata to %s", fnm)
1385         f, err := os.Create(fnm)
1386         if err != nil {
1387                 return err
1388         }
1389         defer f.Close()
1390         pcaLabels := ""
1391         if len(samples) > 0 {
1392                 for i := range samples[0].pcaComponents {
1393                         pcaLabels += fmt.Sprintf(",PCA%d", i)
1394                 }
1395         }
1396         _, err = fmt.Fprintf(f, "Index,SampleID,CaseControl,TrainingValidation%s\n", pcaLabels)
1397         if err != nil {
1398                 return err
1399         }
1400         for i, si := range samples {
1401                 var cc, tv string
1402                 if si.isCase {
1403                         cc = "1"
1404                 } else if si.isControl {
1405                         cc = "0"
1406                 }
1407                 if si.isTraining {
1408                         tv = "1"
1409                 } else if si.isValidation {
1410                         tv = "0"
1411                 }
1412                 var pcavals string
1413                 for _, pcaval := range si.pcaComponents {
1414                         pcavals += fmt.Sprintf(",%f", pcaval)
1415                 }
1416                 _, err = fmt.Fprintf(f, "%d,%s,%s,%s%s\n", i, si.id, cc, tv, pcavals)
1417                 if err != nil {
1418                         return fmt.Errorf("write %s: %w", fnm, err)
1419                 }
1420         }
1421         err = f.Close()
1422         if err != nil {
1423                 return fmt.Errorf("close %s: %w", fnm, err)
1424         }
1425         log.Print("done")
1426         return nil
1427 }
1428
1429 func (cmd *sliceNumpy) filterHGVScolpair(colpair [2][]int8) bool {
1430         if cmd.chi2PValue >= 1 {
1431                 return true
1432         }
1433         col0 := make([]bool, 0, len(cmd.chi2Cases))
1434         col1 := make([]bool, 0, len(cmd.chi2Cases))
1435         cases := make([]bool, 0, len(cmd.chi2Cases))
1436         for i, c := range cmd.chi2Cases {
1437                 if colpair[0][i] < 0 {
1438                         continue
1439                 }
1440                 col0 = append(col0, colpair[0][i] != 0)
1441                 col1 = append(col1, colpair[1][i] != 0)
1442                 cases = append(cases, c)
1443         }
1444         return len(cases) >= cmd.minCoverage &&
1445                 (pvalue(col0, cases) <= cmd.chi2PValue || pvalue(col1, cases) <= cmd.chi2PValue)
1446 }
1447
1448 func writeNumpyUint32(fnm string, out []uint32, rows, cols int) error {
1449         output, err := os.Create(fnm)
1450         if err != nil {
1451                 return err
1452         }
1453         defer output.Close()
1454         bufw := bufio.NewWriterSize(output, 1<<26)
1455         npw, err := gonpy.NewWriter(nopCloser{bufw})
1456         if err != nil {
1457                 return err
1458         }
1459         log.WithFields(log.Fields{
1460                 "filename": fnm,
1461                 "rows":     rows,
1462                 "cols":     cols,
1463                 "bytes":    rows * cols * 4,
1464         }).Infof("writing numpy: %s", fnm)
1465         npw.Shape = []int{rows, cols}
1466         npw.WriteUint32(out)
1467         err = bufw.Flush()
1468         if err != nil {
1469                 return err
1470         }
1471         return output.Close()
1472 }
1473
1474 func writeNumpyInt32(fnm string, out []int32, rows, cols int) error {
1475         output, err := os.Create(fnm)
1476         if err != nil {
1477                 return err
1478         }
1479         defer output.Close()
1480         bufw := bufio.NewWriterSize(output, 1<<26)
1481         npw, err := gonpy.NewWriter(nopCloser{bufw})
1482         if err != nil {
1483                 return err
1484         }
1485         log.WithFields(log.Fields{
1486                 "filename": fnm,
1487                 "rows":     rows,
1488                 "cols":     cols,
1489                 "bytes":    rows * cols * 4,
1490         }).Infof("writing numpy: %s", fnm)
1491         npw.Shape = []int{rows, cols}
1492         npw.WriteInt32(out)
1493         err = bufw.Flush()
1494         if err != nil {
1495                 return err
1496         }
1497         return output.Close()
1498 }
1499
1500 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
1501         output, err := os.Create(fnm)
1502         if err != nil {
1503                 return err
1504         }
1505         defer output.Close()
1506         bufw := bufio.NewWriterSize(output, 1<<26)
1507         npw, err := gonpy.NewWriter(nopCloser{bufw})
1508         if err != nil {
1509                 return err
1510         }
1511         log.WithFields(log.Fields{
1512                 "filename": fnm,
1513                 "rows":     rows,
1514                 "cols":     cols,
1515                 "bytes":    rows * cols * 2,
1516         }).Infof("writing numpy: %s", fnm)
1517         npw.Shape = []int{rows, cols}
1518         npw.WriteInt16(out)
1519         err = bufw.Flush()
1520         if err != nil {
1521                 return err
1522         }
1523         return output.Close()
1524 }
1525
1526 func writeNumpyInt8(fnm string, out []int8, rows, cols int) error {
1527         output, err := os.Create(fnm)
1528         if err != nil {
1529                 return err
1530         }
1531         defer output.Close()
1532         bufw := bufio.NewWriterSize(output, 1<<26)
1533         npw, err := gonpy.NewWriter(nopCloser{bufw})
1534         if err != nil {
1535                 return err
1536         }
1537         log.WithFields(log.Fields{
1538                 "filename": fnm,
1539                 "rows":     rows,
1540                 "cols":     cols,
1541                 "bytes":    rows * cols,
1542         }).Infof("writing numpy: %s", fnm)
1543         npw.Shape = []int{rows, cols}
1544         npw.WriteInt8(out)
1545         err = bufw.Flush()
1546         if err != nil {
1547                 return err
1548         }
1549         return output.Close()
1550 }
1551
1552 func allele2homhet(colpair [2][]int8) {
1553         a, b := colpair[0], colpair[1]
1554         for i, av := range a {
1555                 bv := b[i]
1556                 if av < 0 || bv < 0 {
1557                         // no-call
1558                         a[i], b[i] = -1, -1
1559                 } else if av > 0 && bv > 0 {
1560                         // hom
1561                         a[i], b[i] = 1, 0
1562                 } else if av > 0 || bv > 0 {
1563                         // het
1564                         a[i], b[i] = 0, 1
1565                 } else {
1566                         // ref (or a different variant in same position)
1567                         // (this is a no-op) a[i], b[i] = 0, 0
1568                 }
1569         }
1570 }
1571
1572 type onehotXref struct {
1573         tag     tagID
1574         variant tileVariantID
1575         hom     bool
1576         pvalue  float64
1577         maf     float64
1578 }
1579
1580 const onehotXrefSize = unsafe.Sizeof(onehotXref{})
1581
1582 // Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
1583 // variants of a single tile/tag#.
1584 //
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:])
1591                 }
1592                 log.WithFields(logrus.Fields{
1593                         "cgs[i].Variants[tag*2+j]": tv,
1594                         "maxv":                     maxv,
1595                         "remap":                    remap,
1596                         "tag":                      tag,
1597                         "chunkstarttag":            chunkstarttag,
1598                 }).Info("tv2homhet()")
1599         }
1600         if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
1601                 // everyone has the most common variant (of the variants we don't drop)
1602                 return nil, nil
1603         }
1604         tagoffset := tag - chunkstarttag
1605         coverage := 0
1606         for cgidx, cgname := range cmd.cgnames {
1607                 if !cmd.minCoverageAll && !cmd.samples[cgidx].isTraining {
1608                         continue
1609                 }
1610                 cg := cgs[cgname]
1611                 alleles := 0
1612                 for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
1613                         if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
1614                                 alleles++
1615                         }
1616                 }
1617                 if alleles == 2 {
1618                         coverage++
1619                 }
1620         }
1621         if coverage < cmd.minCoverage {
1622                 return nil, nil
1623         }
1624         // "observed" array for p-value calculation (training set
1625         // only)
1626         obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
1627         // one-hot output (all samples)
1628         outcols := make([][]int8, (maxv+1)*2)
1629         for i := range obs {
1630                 obs[i] = make([]bool, cmd.trainingSetSize)
1631                 outcols[i] = make([]int8, len(cmd.cgnames))
1632         }
1633         for cgid, name := range cmd.cgnames {
1634                 tsid := cmd.trainingSet[cgid]
1635                 cgvars := cgs[name].Variants[tagoffset*2:]
1636                 tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
1637                 for v := tileVariantID(1); v <= maxv; v++ {
1638                         if tv0 == v && tv1 == v {
1639                                 if tsid >= 0 {
1640                                         obs[v*2][tsid] = true
1641                                 }
1642                                 outcols[v*2][cgid] = 1
1643                         } else if tv0 == v || tv1 == v {
1644                                 if tsid >= 0 {
1645                                         obs[v*2+1][tsid] = true
1646                                 }
1647                                 outcols[v*2+1][cgid] = 1
1648                         }
1649                 }
1650         }
1651         var onehot [][]int8
1652         var xref []onehotXref
1653         var maf float64
1654         for col := 2; col < len(obs); col++ {
1655                 // col 0,1 correspond to tile variant 0, i.e.,
1656                 // no-call; col 2,3 correspond to the most common
1657                 // variant; so we (normally) start at col 4.
1658                 if col < 4 && !cmd.includeVariant1 {
1659                         continue
1660                 }
1661                 if col&1 == 0 {
1662                         maf = homhet2maf(obs[col : col+2])
1663                         if maf < cmd.pvalueMinFrequency {
1664                                 // Skip both columns (hom and het) if
1665                                 // allele frequency is below threshold
1666                                 col++
1667                                 continue
1668                         }
1669                         if maf > cmd.maxFrequency {
1670                                 // Skip both columns if allele
1671                                 // frequency is above threshold
1672                                 col++
1673                                 continue
1674                         }
1675                 }
1676                 atomic.AddInt64(&cmd.pvalueCallCount, 1)
1677                 p := cmd.pvalue(obs[col])
1678                 if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
1679                         continue
1680                 }
1681                 onehot = append(onehot, outcols[col])
1682                 xref = append(xref, onehotXref{
1683                         tag:     tag,
1684                         variant: tileVariantID(col >> 1),
1685                         hom:     col&1 == 0,
1686                         pvalue:  p,
1687                         maf:     maf,
1688                 })
1689         }
1690         return onehot, xref
1691 }
1692
1693 func homhet2maf(onehot [][]bool) float64 {
1694         if len(onehot[0]) == 0 {
1695                 return 0
1696         }
1697         n := 0
1698         for i := range onehot[0] {
1699                 if onehot[0][i] {
1700                         // hom
1701                         n += 2
1702                 } else if onehot[1][i] {
1703                         // het
1704                         n += 1
1705                 }
1706         }
1707         return float64(n) / float64(len(onehot[0])*2)
1708 }
1709
1710 // convert a []onehotXref with length N to a numpy-style []int32
1711 // matrix with N columns, one row per field of onehotXref struct.
1712 //
1713 // Hom/het row contains hom=0, het=1.
1714 //
1715 // P-value row contains 1000000x actual p-value.
1716 func onehotXref2int32(xrefs []onehotXref) []int32 {
1717         xcols := len(xrefs)
1718         xdata := make([]int32, 6*xcols)
1719         for i, xref := range xrefs {
1720                 xdata[i] = int32(xref.tag)
1721                 xdata[xcols+i] = int32(xref.variant)
1722                 if xref.hom {
1723                         xdata[xcols*2+i] = 1
1724                 }
1725                 xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
1726                 xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
1727                 xdata[xcols*5+i] = int32(xref.maf * 1000000)
1728         }
1729         return xdata
1730 }
1731
1732 // transpose onehot data from in[col][row] to numpy-style
1733 // out[row*cols+col].
1734 func onehotcols2int8(in [][]int8) []int8 {
1735         if len(in) == 0 {
1736                 return nil
1737         }
1738         cols := len(in)
1739         rows := len(in[0])
1740         out := make([]int8, rows*cols)
1741         for row := 0; row < rows; row++ {
1742                 outrow := out[row*cols:]
1743                 for col, incol := range in {
1744                         outrow[col] = incol[row]
1745                 }
1746         }
1747         return out
1748 }
1749
1750 // Return [2][]uint32{rowIndices, colIndices} indicating which
1751 // elements of matrixT[c][r] have non-zero values.
1752 func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
1753         var nz [2][]uint32
1754         for c, col := range matrixT {
1755                 for r, val := range col {
1756                         if val != 0 {
1757                                 nz[0] = append(nz[0], uint32(r))
1758                                 nz[1] = append(nz[1], uint32(c))
1759                         }
1760                 }
1761         }
1762         return nz
1763 }