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