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