+
+func writeNumpyInt8(fnm string, out []int8, 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,
+ "bytes": rows * cols,
+ }).Infof("writing numpy: %s", fnm)
+ npw.Shape = []int{rows, cols}
+ npw.WriteInt8(out)
+ err = bufw.Flush()
+ if err != nil {
+ return err
+ }
+ return output.Close()
+}
+
+func allele2homhet(colpair [2][]int8) {
+ a, b := colpair[0], colpair[1]
+ for i, av := range a {
+ bv := b[i]
+ if av < 0 || bv < 0 {
+ // no-call
+ a[i], b[i] = -1, -1
+ } else if av > 0 && bv > 0 {
+ // hom
+ a[i], b[i] = 1, 0
+ } else if av > 0 || bv > 0 {
+ // het
+ a[i], b[i] = 0, 1
+ } else {
+ // ref (or a different variant in same position)
+ // (this is a no-op) a[i], b[i] = 0, 0
+ }
+ }
+}
+
+type onehotXref struct {
+ tag tagID
+ variant tileVariantID
+ hom bool
+ pvalue float64
+ maf float64
+}
+
+const onehotXrefSize = unsafe.Sizeof(onehotXref{})
+
+// Build onehot matrix (m[tileVariantIndex][genome] == 0 or 1) for all
+// variants of a single tile/tag#.
+//
+// Return nil if no tile variant passes Χ² filter.
+func (cmd *sliceNumpy) tv2homhet(cgs map[string]CompactGenome, maxv tileVariantID, remap []tileVariantID, tag, chunkstarttag tagID, seq map[tagID][]TileVariant) ([][]int8, []onehotXref) {
+ if tag == cmd.debugTag {
+ tv := make([]tileVariantID, len(cmd.cgnames)*2)
+ for i, name := range cmd.cgnames {
+ copy(tv[i*2:(i+1)*2], cgs[name].Variants[(tag-chunkstarttag)*2:])
+ }
+ log.WithFields(logrus.Fields{
+ "cgs[i].Variants[tag*2+j]": tv,
+ "maxv": maxv,
+ "remap": remap,
+ "tag": tag,
+ "chunkstarttag": chunkstarttag,
+ }).Info("tv2homhet()")
+ }
+ if maxv < 1 || (maxv < 2 && !cmd.includeVariant1) {
+ // everyone has the most common variant (of the variants we don't drop)
+ return nil, nil
+ }
+ tagoffset := tag - chunkstarttag
+ coverage := 0
+ for _, cg := range cgs {
+ alleles := 0
+ for _, v := range cg.Variants[tagoffset*2 : tagoffset*2+2] {
+ if v > 0 && int(v) < len(seq[tag]) && len(seq[tag][v].Sequence) > 0 {
+ alleles++
+ }
+ }
+ if alleles == 2 {
+ coverage++
+ }
+ }
+ if coverage < cmd.minCoverage {
+ return nil, nil
+ }
+ // "observed" array for p-value calculation (training set
+ // only)
+ obs := make([][]bool, (maxv+1)*2) // 2 slices (hom + het) for each variant#
+ // one-hot output (all samples)
+ outcols := make([][]int8, (maxv+1)*2)
+ for i := range obs {
+ obs[i] = make([]bool, cmd.trainingSetSize)
+ outcols[i] = make([]int8, len(cmd.cgnames))
+ }
+ for cgid, name := range cmd.cgnames {
+ tsid := cmd.trainingSet[cgid]
+ cgvars := cgs[name].Variants[tagoffset*2:]
+ tv0, tv1 := remap[cgvars[0]], remap[cgvars[1]]
+ for v := tileVariantID(1); v <= maxv; v++ {
+ if tv0 == v && tv1 == v {
+ if tsid >= 0 {
+ obs[v*2][tsid] = true
+ }
+ outcols[v*2][cgid] = 1
+ } else if tv0 == v || tv1 == v {
+ if tsid >= 0 {
+ obs[v*2+1][tsid] = true
+ }
+ outcols[v*2+1][cgid] = 1
+ }
+ }
+ }
+ var onehot [][]int8
+ var xref []onehotXref
+ var maf float64
+ for col := 2; col < len(obs); col++ {
+ // col 0,1 correspond to tile variant 0, i.e.,
+ // no-call; col 2,3 correspond to the most common
+ // variant; so we (normally) start at col 4.
+ if col < 4 && !cmd.includeVariant1 {
+ continue
+ }
+ if col&1 == 0 {
+ maf = homhet2maf(obs[col : col+2])
+ if maf < cmd.pvalueMinFrequency {
+ // Skip both columns (hom and het) if
+ // allele frequency is below threshold
+ col++
+ continue
+ }
+ if maf > cmd.maxFrequency {
+ // Skip both columns if allele
+ // frequency is above threshold
+ col++
+ continue
+ }
+ }
+ atomic.AddInt64(&cmd.pvalueCallCount, 1)
+ p := cmd.pvalue(obs[col])
+ if cmd.chi2PValue < 1 && !(p < cmd.chi2PValue) {
+ continue
+ }
+ onehot = append(onehot, outcols[col])
+ xref = append(xref, onehotXref{
+ tag: tag,
+ variant: tileVariantID(col >> 1),
+ hom: col&1 == 0,
+ pvalue: p,
+ maf: maf,
+ })
+ }
+ return onehot, xref
+}
+
+func homhet2maf(onehot [][]bool) float64 {
+ if len(onehot[0]) == 0 {
+ return 0
+ }
+ n := 0
+ for i := range onehot[0] {
+ if onehot[0][i] {
+ // hom
+ n += 2
+ } else if onehot[1][i] {
+ // het
+ n += 1
+ }
+ }
+ return float64(n) / float64(len(onehot[0])*2)
+}
+
+// convert a []onehotXref with length N to a numpy-style []int32
+// matrix with N columns, one row per field of onehotXref struct.
+//
+// Hom/het row contains hom=0, het=1.
+//
+// P-value row contains 1000000x actual p-value.
+func onehotXref2int32(xrefs []onehotXref) []int32 {
+ xcols := len(xrefs)
+ xdata := make([]int32, 6*xcols)
+ for i, xref := range xrefs {
+ xdata[i] = int32(xref.tag)
+ xdata[xcols+i] = int32(xref.variant)
+ if xref.hom {
+ xdata[xcols*2+i] = 1
+ }
+ xdata[xcols*3+i] = int32(xref.pvalue * 1000000)
+ xdata[xcols*4+i] = int32(-math.Log10(xref.pvalue) * 1000000)
+ xdata[xcols*5+i] = int32(xref.maf * 1000000)
+ }
+ return xdata
+}
+
+// transpose onehot data from in[col][row] to numpy-style
+// out[row*cols+col].
+func onehotcols2int8(in [][]int8) []int8 {
+ if len(in) == 0 {
+ return nil
+ }
+ cols := len(in)
+ rows := len(in[0])
+ out := make([]int8, rows*cols)
+ for row := 0; row < rows; row++ {
+ outrow := out[row*cols:]
+ for col, incol := range in {
+ outrow[col] = incol[row]
+ }
+ }
+ return out
+}
+
+// Return [2][]uint32{rowIndices, colIndices} indicating which
+// elements of matrixT[c][r] have non-zero values.
+func onehotChunk2Indirect(matrixT [][]int8) [2][]uint32 {
+ var nz [2][]uint32
+ for c, col := range matrixT {
+ for r, val := range col {
+ if val != 0 {
+ nz[0] = append(nz[0], uint32(r))
+ nz[1] = append(nz[1], uint32(c))
+ }
+ }
+ }
+ return nz
+}