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