src/main/scala/chipsldpc/graph/TannerGraph.scala

Source from the repository checkout used to build these docs. Line numbers link to individual source lines.

 1package chipsldpc.graph
 2
 3final case class TannerEdge(check: Int, variable: Int)
 4
 5/** Immutable, canonically numbered Tanner graph used only during elaboration. */
 6final class TannerGraph private (
 7    val checkCount: Int,
 8    val variableCount: Int,
 9    val edges: Vector[TannerEdge],
10    val rowOnes: Vector[Vector[Int]],
11    val colOnes: Vector[Vector[Int]],
12    val checkEdges: Vector[Vector[Int]],
13    val variableEdges: Vector[Vector[Int]],
14) {
15  val edgeCount: Int = edges.size
16}
17
18object TannerGraph {
19  /** Build from H's nonzero columns per row; edge IDs are row-major. */
20  def fromRows(variableCount: Int, rowOnes: Seq[Seq[Int]]): TannerGraph = {
21    require(variableCount > 0, "variableCount must be positive")
22    require(rowOnes.nonEmpty, "the graph must contain a check")
23
24    val rows = rowOnes.zipWithIndex.map { case (row, check) =>
25      val sorted = row.toVector.sorted
26      require(sorted.nonEmpty, s"check $check is unused")
27      require(sorted.forall(v => v >= 0 && v < variableCount),
28        s"check $check contains a variable outside [0, $variableCount)")
29      require(sorted.distinct.size == sorted.size, s"check $check contains duplicate variables")
30      sorted
31    }.toVector
32
33    val edges = rows.zipWithIndex.flatMap { case (variables, check) =>
34      variables.map(TannerEdge(check, _))
35    }
36    val offsets = rows.scanLeft(0)(_ + _.size)
37    val checkEdges = rows.indices.map(i => (offsets(i) until offsets(i + 1)).toVector).toVector
38    val columnChecks = Array.fill(variableCount)(Vector.newBuilder[Int])
39    val columnEdges = Array.fill(variableCount)(Vector.newBuilder[Int])
40    edges.zipWithIndex.foreach { case (edge, id) =>
41      columnChecks(edge.variable) += edge.check
42      columnEdges(edge.variable) += id
43    }
44    val cols = columnChecks.map(_.result()).toVector
45    require(cols.forall(_.nonEmpty), "every variable must be incident to a check")
46
47    new TannerGraph(
48      rows.size,
49      variableCount,
50      edges,
51      rows,
52      cols,
53      checkEdges,
54      columnEdges.map(_.result()).toVector,
55    )
56  }
57}