Mention undiffable variants in annotations, write -2 in hgvs matrix.
[lightning.git] / slicenumpy.go
index 8f3a861db56cd2e4f6909f1ad8353df2e496823a..a8fdeb064eefa682437b0558958785b003ed81fc 100644 (file)
@@ -10,12 +10,14 @@ import (
        "flag"
        "fmt"
        "io"
+       "io/ioutil"
        "net/http"
        _ "net/http/pprof"
        "os"
        "regexp"
        "runtime"
        "sort"
+       "strconv"
        "strings"
        "sync/atomic"
 
@@ -49,6 +51,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
        regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
        expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
+       mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
        flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads")
        cmd.filter.Flags(flags)
        err = flags.Parse(args)
@@ -87,6 +90,7 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        "-threads=" + fmt.Sprintf("%d", cmd.threads),
                        "-regions=" + *regionsFilename,
                        "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
+                       "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
                }
                runner.Args = append(runner.Args, cmd.filter.Args()...)
                var output string
@@ -189,52 +193,59 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        type reftileinfo struct {
                variant  tileVariantID
                seqname  string // chr1
-               pos      int    // distance from start of chr1 to start of tile
+               pos      int    // distance from start of chromosome to starttag
                tiledata []byte // acgtggcaa...
        }
+       isdup := map[tagID]bool{}
        reftile := map[tagID]*reftileinfo{}
        for seqname, cseq := range refseq {
+               pos := 0
                for _, libref := range cseq {
-                       reftile[libref.Tag] = &reftileinfo{
-                               seqname:  seqname,
-                               variant:  libref.Variant,
-                               tiledata: reftiledata[libref],
+                       tiledata := reftiledata[libref]
+                       if len(tiledata) == 0 {
+                               err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
+                               return 1
                        }
-               }
-       }
-
-       throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
-       log.Info("reconstructing reference sequences")
-       for seqname, cseq := range refseq {
-               seqname, cseq := seqname, cseq
-               throttleCPU.Go(func() error {
-                       defer log.Printf("... %s done", seqname)
-                       pos := 0
-                       for _, libref := range cseq {
-                               rt := reftile[libref.Tag]
-                               rt.pos = pos
-                               if len(rt.tiledata) == 0 {
-                                       return fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
+                       if isdup[libref.Tag] {
+                               log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
+                       } else if reftile[libref.Tag] != nil {
+                               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)
+                               delete(reftile, libref.Tag)
+                               log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
+                               isdup[libref.Tag] = true
+                       } else {
+                               reftile[libref.Tag] = &reftileinfo{
+                                       seqname:  seqname,
+                                       variant:  libref.Variant,
+                                       tiledata: tiledata,
+                                       pos:      pos,
                                }
-                               pos += len(rt.tiledata) - taglen
                        }
-                       return nil
-               })
+                       pos += len(tiledata) - taglen
+               }
+               log.Printf("... %s done, len %d", seqname, pos+taglen)
        }
-       throttleCPU.Wait()
 
        var mask *mask
        if *regionsFilename != "" {
+               log.Printf("loading regions from %s", *regionsFilename)
                mask, err = makeMask(*regionsFilename, *expandRegions)
                if err != nil {
                        return 1
                }
-               // Delete reftile entries for masked-out regions.
+               log.Printf("before applying mask, len(reftile) == %d", len(reftile))
+               log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
                for tag, rt := range reftile {
                        if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
                                delete(reftile, tag)
                        }
                }
+               log.Printf("after applying mask, len(reftile) == %d", len(reftile))
+       }
+
+       var toMerge [][]int16
+       if *mergeOutput {
+               toMerge = make([][]int16, len(infiles))
        }
 
        throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
@@ -365,8 +376,8 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                }
                                variants, ok := seq[tag]
                                if !ok {
-                                       outcol++
-                                       continue
+                                       // how could we even have a reftile if there is no sequence data??
+                                       return fmt.Errorf("bug: have no variants for tag %d but reftile is %+v", tag, rt)
                                }
                                reftilestr := strings.ToUpper(string(rt.tiledata))
                                remap := variantRemap[tag-tagstart]
@@ -379,9 +390,11 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                                                done[v] = true
                                        }
                                        if len(tv.Sequence) < taglen || !bytes.HasSuffix(rt.tiledata, tv.Sequence[len(tv.Sequence)-taglen:]) {
+                                               fmt.Fprintf(annow, "%d,%d,%d,.,%s,%d,.,,\n", tag, outcol, v, rt.seqname, rt.pos)
                                                continue
                                        }
                                        if lendiff := len(rt.tiledata) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
+                                               fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
                                                continue
                                        }
                                        diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
@@ -425,31 +438,15 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
                        seq = nil
                        throttleNumpyMem.Release()
 
-                       fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
-                       output, err := os.Create(fnm)
-                       if err != nil {
-                               return err
-                       }
-                       defer output.Close()
-                       bufw := bufio.NewWriterSize(output, 1<<26)
-                       npw, err := gonpy.NewWriter(nopCloser{bufw})
-                       if err != nil {
-                               return err
-                       }
-                       log.WithFields(log.Fields{
-                               "filename": fnm,
-                               "rows":     rows,
-                               "cols":     cols,
-                       }).Infof("%04d: writing numpy", infileIdx)
-                       npw.Shape = []int{rows, cols}
-                       npw.WriteInt16(out)
-                       err = bufw.Flush()
-                       if err != nil {
-                               return err
-                       }
-                       err = output.Close()
-                       if err != nil {
-                               return err
+                       if *mergeOutput {
+                               log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
+                               toMerge[infileIdx] = out
+                       } else {
+                               fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
+                               err = writeNumpyInt16(fnm, out, rows, cols)
+                               if err != nil {
+                                       return err
+                               }
                        }
                        log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
                        return nil
@@ -458,5 +455,152 @@ func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, s
        if err = throttleMem.Wait(); err != nil {
                return 1
        }
+       if *mergeOutput {
+               log.Info("merging output matrix and annotations")
+
+               annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
+               annof, err := os.Create(annoFilename)
+               if err != nil {
+                       return 1
+               }
+               annow := bufio.NewWriterSize(annof, 1<<20)
+
+               rows := len(cgnames)
+               cols := 0
+               for _, chunk := range toMerge {
+                       cols += len(chunk) / rows
+               }
+               out := make([]int16, rows*cols)
+               hgvs := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
+               startcol := 0
+               for outIdx, chunk := range toMerge {
+                       chunkcols := len(chunk) / rows
+                       for row := 0; row < rows; row++ {
+                               copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
+                       }
+                       toMerge[outIdx] = nil
+
+                       annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
+                       log.Infof("reading %s", annotationsFilename)
+                       buf, err := os.ReadFile(annotationsFilename)
+                       if err != nil {
+                               return 1
+                       }
+                       err = os.Remove(annotationsFilename)
+                       if err != nil {
+                               return 1
+                       }
+                       for _, line := range bytes.Split(buf, []byte{'\n'}) {
+                               if len(line) == 0 {
+                                       continue
+                               }
+                               fields := bytes.SplitN(line, []byte{','}, 8)
+                               incol, _ := strconv.Atoi(string(fields[1]))
+                               tileVariant, _ := strconv.Atoi(string(fields[2]))
+                               hgvsID := string(fields[3])
+                               seqname := string(fields[4])
+                               pos, _ := strconv.Atoi(string(fields[5]))
+                               refseq := fields[6]
+                               if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
+                                       // The tile intersects one of
+                                       // the selected regions, but
+                                       // this particular HGVS
+                                       // variant does not.
+                                       continue
+                               }
+                               fmt.Fprintf(annow, "%s,%d,%d,%s,%s,%d,%s,%s\n", fields[0], incol+startcol/2, tileVariant, hgvsID, seqname, pos, refseq, fields[7])
+                               hgvscols := hgvs[hgvsID]
+                               if hgvscols[0] == nil {
+                                       hgvscols = [2][]int16{make([]int16, len(cgnames)), make([]int16, len(cgnames))}
+                                       hgvs[hgvsID] = hgvscols
+                               }
+                               for ph := 0; ph < 2; ph++ {
+                                       for row := 0; row < rows; row++ {
+                                               v := chunk[row*chunkcols+incol*2+ph]
+                                               if int(v) == tileVariant {
+                                                       if len(hgvsID) == 0 {
+                                                               // we have the tile variant sequence, but the diff against ref didn't work out (see lendiff above)
+                                                               hgvscols[ph][row] = -2
+                                                       } else {
+                                                               hgvscols[ph][row] = 1
+                                                       }
+                                               } else if v < 0 {
+                                                       hgvscols[ph][row] = -1
+                                               }
+                                       }
+                               }
+                       }
+
+                       startcol += chunkcols
+               }
+               err = annow.Flush()
+               if err != nil {
+                       return 1
+               }
+               err = annof.Close()
+               if err != nil {
+                       return 1
+               }
+               err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
+               if err != nil {
+                       return 1
+               }
+               out = nil
+
+               cols = len(hgvs) * 2
+               log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
+               out = make([]int16, rows*cols)
+               hgvsIDs := make([]string, 0, len(hgvs))
+               for hgvsID := range hgvs {
+                       hgvsIDs = append(hgvsIDs, hgvsID)
+               }
+               sort.Strings(hgvsIDs)
+               var hgvsLabels bytes.Buffer
+               for idx, hgvsID := range hgvsIDs {
+                       fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
+                       for ph := 0; ph < 2; ph++ {
+                               hgvscol := hgvs[hgvsID][ph]
+                               for row, val := range hgvscol {
+                                       out[row*cols+idx*2+ph] = val
+                               }
+                       }
+               }
+               err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
+               if err != nil {
+                       return 1
+               }
+
+               fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
+               log.Printf("writing hgvs labels: %s", fnm)
+               err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
+               if err != nil {
+                       return 1
+               }
+       }
        return 0
 }
+
+func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
+       output, err := os.Create(fnm)
+       if err != nil {
+               return err
+       }
+       defer output.Close()
+       bufw := bufio.NewWriterSize(output, 1<<26)
+       npw, err := gonpy.NewWriter(nopCloser{bufw})
+       if err != nil {
+               return err
+       }
+       log.WithFields(log.Fields{
+               "filename": fnm,
+               "rows":     rows,
+               "cols":     cols,
+       }).Infof("writing numpy: %s", fnm)
+       npw.Shape = []int{rows, cols}
+       npw.WriteInt16(out)
+       err = bufw.Flush()
+       if err != nil {
+               return err
+       }
+       return output.Close()
+}