Compare commits

..

6 commits
0.1.2 ... main

Author SHA1 Message Date
b7feb7a341 (patch) general code improvements and more documentation (#8)
All checks were successful
/ Build and Release Library (push) Successful in 2m30s
Reviewed-on: #8
2026-03-28 03:23:43 +00:00
c297f2f2ca (patch) fix incoming algorithm -- inverted boolean (#7)
All checks were successful
/ Build and Release Library (push) Successful in 2m31s
Reviewed-on: #7
2026-01-26 03:03:36 +00:00
ebd7d98ebb (patch) upgrade pre-commit (#6)
All checks were successful
/ Build and Release Library (push) Successful in 2m22s
Reviewed-on: #6
2026-01-25 03:55:13 +00:00
cf1690aebb (patch) update scala to 3.8.1 (#5)
All checks were successful
/ Build and Release Library (push) Successful in 2m22s
Reviewed-on: #5
2026-01-24 17:13:19 +00:00
05258f86f5 (patch) add incoming edges (#4)
All checks were successful
/ Build and Release Library (push) Successful in 2m21s
Reviewed-on: #4
2026-01-08 04:26:52 +00:00
5827a13f21 (patch) Add data variants to traversals in fs2 (#3)
All checks were successful
/ Build and Release Library (push) Successful in 2m24s
Reviewed-on: #3
2026-01-06 03:59:07 +00:00
12 changed files with 239 additions and 21 deletions

View file

@ -1,7 +1,7 @@
---
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v6.0.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
@ -12,6 +12,6 @@ repos:
- id: trailing-whitespace
- id: check-yaml
- repo: https://git.garrity.co/garrity-software/gs-pre-commit-scala
rev: v1.0.1
rev: v1.0.2
hooks:
- id: scalafmt

View file

@ -1,5 +1,5 @@
// See: https://github.com/scalameta/scalafmt/tags for the latest tags.
version = 3.10.2
version = 3.10.4
runner.dialect = scala3
maxColumn = 80

View file

@ -1,4 +1,4 @@
val scala3: String = "3.7.4"
val scala3: String = "3.8.2"
ThisBuild / scalaVersion := scala3
ThisBuild / versionScheme := Some("semver-spec")
@ -31,14 +31,14 @@ val Deps = new {
}
val Fs2 = new {
val Core: ModuleID = "co.fs2" %% "fs2-core" % "3.12.2"
val Core: ModuleID = "co.fs2" %% "fs2-core" % "3.13.0"
}
val Gs = new {
val Datagen: ModuleID = "gs" %% "gs-datagen-core-v0" % "0.3.3"
val Datagen: ModuleID = "gs" %% "gs-datagen-core-v0" % "0.4.1"
}
val MUnit: ModuleID = "org.scalameta" %% "munit" % "1.1.1"
val MUnit: ModuleID = "org.scalameta" %% "munit" % "1.2.4"
}
lazy val testSettings = Seq(
@ -51,6 +51,7 @@ lazy val testSettings = Seq(
lazy val `gs-graph` = project
.in(file("."))
.aggregate(core, cats, fs2)
.settings(noPublishSettings)
.settings(sharedSettings)
.settings(testSettings)
.settings(name := s"${gsProjectName.value}-v${semVerMajor.value}")

View file

@ -20,6 +20,26 @@ final class Adjacency(val neighbors: Vector[Vector[Vertex]]):
*/
def at(vertex: Vertex): Vector[Vertex] = neighbors(vertex.ordinal)
/** Get the vector of _incoming_ [[Vertex]] that point _to_ some input
* [[Vertex]].
*
* @param vertex
* The [[Vertex]] for which to retrieve the incoming vertices.
* @return
* The list of [[Vertex]] that have an edge _to_ the input [[Vertex]].
*/
def incoming(vertex: Vertex): Vector[Vertex] =
if vertex.ordinal >= neighbors.length then Vector.empty
else
neighbors.zipWithIndex
.filter {
// ignore the neighbors of the input vertex
case (_, index) => index != vertex.ordinal
}
.filter(_._1.contains(vertex))
.map(_._2)
.map(Vertex(_))
/** Express this [[Adjacency]] as a vector of [[Edge]].
*
* @return
@ -31,10 +51,9 @@ final class Adjacency(val neighbors: Vector[Vector[Vertex]]):
tos.map(to => Edge(from, to)).distinct
}
/** @return
* The number of vertices represented by this adjacency list.
/** The number of vertices represented by this adjacency list.
*/
def numberOfVertices: Size = Size.fromVector(neighbors)
lazy val numberOfVertices: Size = Size.fromVector(neighbors)
/** Perform a linear traversal for each [[gs.graph.v0.Vertex]] to calculate
* the total number of edges in this adjacency list.
@ -42,9 +61,11 @@ final class Adjacency(val neighbors: Vector[Vector[Vertex]]):
* @return
* The number of edges in this adjacency list.
*/
def numberOfEdges: Size = Size(neighbors.map(_.length).reduce(_ + _))
lazy val numberOfEdges: Size = Size(neighbors.map(_.length).reduce(_ + _))
def findRoots(): Vector[Vertex] =
/** All vertices that do not have inbound connections.
*/
lazy val roots: Vector[Vertex] =
val counts = Array.fill(neighbors.length)(0)
neighbors.foreach { ns =>
// Each vertex listed here is receiving an inbound connection, if we
@ -74,6 +95,17 @@ object Adjacency:
*/
def apply(adj: Vector[Vector[Vertex]]): Adjacency = new Adjacency(adj)
/** Create an empty adjacency list for some number of vertices. No vertex has
* any connections to another vertex.
*
* @param numberOfVertices
* The number of vertices in this disconnected graph.
* @return
* Some new empty adjacency.
*/
def empty(numberOfVertices: Size): Adjacency =
new Adjacency(Vector.fill(numberOfVertices.value)(Vector.empty))
given CanEqual[Adjacency, Adjacency] = CanEqual.derived
/** @return
@ -86,7 +118,8 @@ object Adjacency:
*/
final val Single: Adjacency = new Adjacency(Vector(Vector.empty))
/** Calculate an [[Adjacency]] from some collection of [[Edge]].
/** Calculate an [[Adjacency]] from some collection of [[Edge]], where those
* edges are assumed to be directed.
*
* @param numberOfVertices
* The number of [[Vertex]] (`N`) in this graph.

View file

@ -1,5 +1,7 @@
package gs.graph.v0
import java.util.Objects
/** Represents a relationship between two [[Vertex]].
*
* When used is a directed context, the edge goes _from_ `v1` _to_ `v2`.
@ -41,6 +43,11 @@ final class Edge(
case other: Edge => v1 == other.v1 && v2 == other.v2
case _ => false
/** @inheritDocs
*/
override def hashCode(): Int =
Objects.hash(v1, v2)
end Edge
object Edge:

View file

@ -1,5 +1,10 @@
package gs.graph.v0
/** Describes the fundamental disposition of some graph.
*
* @param name
* The string value of this disposition.
*/
sealed abstract class GraphDisposition(val name: String):
override def equals(that: Any): Boolean =
@ -15,7 +20,12 @@ object GraphDisposition:
given CanEqual[GraphDisposition, GraphDisposition] = CanEqual.derived
/** The graph has directed relationships between vertices.
*/
case object Directed extends GraphDisposition("directed")
/** The graph has relationships between vertices with no logical direction.
*/
case object Undirected extends GraphDisposition("undirected")
end GraphDisposition

View file

@ -29,6 +29,8 @@ class Digraph(
*/
override def selectRoots(): Vector[Vertex] = roots
/** @inheritDocs
*/
override def equals(that: Any): Boolean =
that match
case other: Digraph =>
@ -78,7 +80,7 @@ object Digraph:
new Digraph(
numberOfVertices = adjacency.numberOfVertices,
adjacency = adjacency,
roots = adjacency.findRoots()
roots = adjacency.roots
)
/** Find all roots for the given collection of [[Edge]].

View file

@ -6,14 +6,30 @@ import gs.graph.v0.GraphException
import gs.graph.v0.Size
import gs.graph.v0.Vertex
/** Specialization of [[Digraph]] that always has a single root vertex.
*
* @param n
* The number of [[Vertex]] present in this graph.
* @param a
* The [[Adjacency]] that describes this graph.
* @param r
* The singular root [[Vertex]].
*/
class SingleRootDigraph(
n: Size,
a: Adjacency,
r: Vertex
) extends Digraph(n, a, Vector(r))
root: Vertex
) extends Digraph(n, a, Vector(root))
object SingleRootDigraph:
/** Attempt to show that the given [[Digraph]] has a single root.
*
* @param dg
* The input [[Digraph]].
* @return
* [[SingleRootDigraph]] or `None` if the number of roots is not 1.
*/
def fromDirectedGraph(dg: Digraph): Option[SingleRootDigraph] =
if dg.roots.size == 1 then
Some(
@ -25,6 +41,18 @@ object SingleRootDigraph:
)
else None
/** Given some edges, build a [[SingleRootDigraph]]. Throw an exception if
* this operation fails.
*
* @param numberOfVertices
* The number of [[Vertex]] in the graph.
* @param edges
* The collection of [[Edge]] that describe the graph.
* @param root
* The root [[Vertex]].
* @return
* The new [[SingleRootDigraph]].
*/
def fromEdgesUnsafe(
numberOfVertices: Size,
edges: Iterable[Edge],
@ -38,6 +66,17 @@ object SingleRootDigraph:
)
else throw GraphException.RootOutOfBounds(root, numberOfVertices)
/** Given some edges, build a [[SingleRootDigraph]] if that collection
* represents a graph with a single root.
*
* @param numberOfVertices
* The number of [[Vertex]] in the graph.
* @param edges
* The collection of [[Edge]] that describe the graph.
* @return
* The new [[SingleRootDigraph]], or `None` if the edges do not describe a
* digraph with a single root.
*/
def fromEdges(
numberOfVertices: Size,
edges: Iterable[Edge]
@ -53,6 +92,19 @@ object SingleRootDigraph:
)
else None
/** Given some [[Adjacency]] and a given root [[Vertex]], instantiate a new
* [[SingleRootDigraph]].
*
* Throws an exception if the given root is not contained within the
* [[Adjacency]].
*
* @param adjacency
* The [[Adjacency]] which describes the graph.
* @param root
* The root [[Vertex]].
* @return
* New [[SingleRootDigraph]]
*/
def fromAdjacencyUnsafe(
adjacency: Adjacency,
root: Vertex
@ -65,10 +117,20 @@ object SingleRootDigraph:
)
else throw GraphException.RootOutOfBounds(root, adjacency.numberOfVertices)
/** Given some [[Adjacency]] and a given root [[Vertex]], instantiate a new
* [[SingleRootDigraph]] if the [[Vertex]] is within the graph..
*
* @param adjacency
* The [[Adjacency]] which describes the graph.
* @param root
* The root [[Vertex]].
* @return
* New [[SingleRootDigraph]], or `None` if the given root is not valid.
*/
def fromAdjacency(
adjacency: Adjacency
): Option[SingleRootDigraph] =
val roots = adjacency.findRoots()
val roots = adjacency.roots
if roots.size == 1 then
Some(
new SingleRootDigraph(

View file

@ -0,0 +1,27 @@
package gs.graph.v0
class AdjacencyTests extends munit.FunSuite:
test("should provide incoming connections") {
val N = Size(7)
val vs = (0 until N.value).map(Vertex(_)).toArray
val E = List(
Edge(vs(0), vs(1)),
Edge(vs(0), vs(2)),
Edge(vs(0), vs(3)),
Edge(vs(1), vs(4)),
Edge(vs(2), vs(4)),
Edge(vs(3), vs(4)),
Edge(vs(3), vs(5)),
Edge(vs(4), vs(6))
)
val A = Adjacency.fromDirectedEdges(N, E)
assertEquals(A.incoming(vs(0)), Vector.empty)
assertEquals(A.incoming(vs(1)), Vector(vs(0)))
assertEquals(A.incoming(vs(2)), Vector(vs(0)))
assertEquals(A.incoming(vs(3)), Vector(vs(0)))
assertEquals(A.incoming(vs(4)), Vector(vs(1), vs(2), vs(3)))
assertEquals(A.incoming(vs(5)), Vector(vs(3)))
assertEquals(A.incoming(vs(6)), Vector(vs(4)))
}

View file

@ -9,6 +9,7 @@ import fs2.Stream
import gs.graph.v0.Graph
import gs.graph.v0.Size
import gs.graph.v0.Vertex
import gs.graph.v0.data.AnyGraphWithData
object GraphTraversalFs2:
@ -24,6 +25,18 @@ object GraphTraversalFs2:
.map(root => pullDfs(graph, state, visit, root).stream.unNoneTerminate)
.reduce(_ ++ _)
def dfs[F[_]: Sync, A, Out](
graph: AnyGraphWithData[A],
visit: A => F[Out]
): Stream[F, Out] =
if graph.isEmpty then Stream.empty
else
val state = new DfsState(graph.numberOfVertices)
graph
.selectRoots()
.map(root => pullDfs(graph, state, visit, root).stream.unNoneTerminate)
.reduce(_ ++ _)
def bfs[F[_]: Async, Out](
graph: Graph,
visit: Vertex => F[Out]
@ -41,6 +54,23 @@ object GraphTraversalFs2:
.map(_.reduce(_ ++ _))
.map(_.unNone)
def bfs[F[_]: Async, A, Out](
graph: AnyGraphWithData[A],
visit: A => F[Out]
): F[Stream[F, Out]] =
if graph.isEmpty then Async[F].pure(Stream.empty)
else
graph
.selectRoots()
.map { root =>
BfsState.initialize[F](graph.numberOfVertices).flatMap { state =>
doBfs(graph, visit, state, root)
}
}
.sequence
.map(_.reduce(_ ++ _))
.map(_.unNone)
private def doBfs[F[_]: Async, Out](
graph: Graph,
visit: Vertex => F[Out],
@ -64,6 +94,29 @@ object GraphTraversalFs2:
}
}
private def doBfs[F[_]: Async, A, Out](
graph: AnyGraphWithData[A],
visit: A => F[Out],
state: BfsState[F],
root: Vertex
): F[Stream[F, Option[Out]]] =
state.enqueue(root).map { _ =>
Stream
.repeatEval(state.dequeue())
.unNoneTerminate
.evalMap { vertex =>
state.isVisited(vertex).flatMap {
case true => Async[F].delay(None)
case false =>
for
_ <- state.visit(vertex)
out <- visit(graph.data(vertex.ordinal))
_ <- enqueueAllNeighbors(vertex, graph, state)
yield Some(out)
}
}
}
private def enqueueAllNeighbors[F[_]: Async](
vertex: Vertex,
graph: Graph,
@ -101,6 +154,29 @@ object GraphTraversalFs2:
}
}
private def pullDfs[F[_]: Sync, A, Out](
graph: AnyGraphWithData[A],
state: DfsState[F],
visit: A => F[Out],
current: Vertex
): Pull[F, Option[Out], Unit] =
Pull.eval(state.isVisited(current)).flatMap { visited =>
if visited then Pull.output1(None) >> Pull.done
else
Pull.eval(state.visit(current))
>> Pull
.eval(visit(graph.data(current.ordinal)))
.flatMap(out => Pull.output1(Some(out)))
>> graph
.neighbors(current)
.foldLeft(Pull.done: Pull[F, Option[Out], Unit]) {
(
acc,
neighbor
) => acc >> pullDfs(graph, state, visit, neighbor)
}
}
abstract private class TraverseState[F[_]: Sync](n: Size):
val visited: Array[Boolean] = Array.fill(n.value)(false)

View file

@ -1 +1 @@
sbt.version=1.11.7
sbt.version=1.12.8

View file

@ -28,6 +28,6 @@ externalResolvers := Seq(
"Garrity Software Releases" at "https://maven.garrity.co/gs"
)
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.3.1")
addSbtPlugin("gs" % "sbt-garrity-software" % "0.6.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.4.4")
addSbtPlugin("gs" % "sbt-garrity-software" % "0.7.0")
addSbtPlugin("gs" % "sbt-gs-semver" % "0.3.0")