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