Refactor to more manageable methods
package io.improbable.keanu.algorithms.graphtraversal;
+import io.improbable.keanu.vertices.ConstantVertex;
import io.improbable.keanu.vertices.Vertex;
import lombok.experimental.UtilityClass;
@@ -27,25 +28,27 @@ public class DifferentiableChecker {
while (!queue.isEmpty()) {
Vertex visiting = queue.poll();
- if (!visiting.isDifferentiable()) {
- if (isVertexConstant(visiting, constantValueVerticesCache)) {
- continue;
- } else {
+ if (isNonDiffableAndNotConstant(visiting, constantValueVerticesCache)) {
return false;
}
- }
+ if (visiting.isDifferentiable()) {
Collection<Vertex> nextVertices = visiting.getParents();
for (Vertex next : nextVertices) {
- if (!queued.contains(next) && !constantValueVerticesCache.contains(next)) {
+ if (!queued.contains(next) && !isValueKnownToBeConstant(next, constantValueVerticesCache)) {
queue.offer(next);
queued.add(next);
}
}
}
+ }
return true;
}
+ private boolean isNonDiffableAndNotConstant(Vertex vertex, Set<Vertex> constantValueVerticesCache) {
+ return !vertex.isDifferentiable() && !isVertexConstant(vertex, constantValueVerticesCache);
+ }
+
private boolean isVertexConstant(Vertex vertex, Set<Vertex> constantValueVerticesCache) {
if (vertex.isProbabilistic() && !vertex.isObserved()) {
return false;
@@ -64,18 +67,11 @@ public class DifferentiableChecker {
while (!queue.isEmpty()) {
Vertex visiting = queue.poll();
- if (constantValueVerticesCache.contains(visiting)) {
- continue;
- }
-
- if (visiting.isProbabilistic()) {
- if (visiting.isObserved()) {
- continue;
- } else {
+ if (isUnobservedProbabilistic(visiting)) {
return false;
}
- }
+ if (!isValueKnownToBeConstant(vertex, constantValueVerticesCache)) {
Collection<Vertex> nextVertices = visiting.getParents();
for (Vertex next : nextVertices) {
if (!queued.contains(next)) {
@@ -84,7 +80,18 @@ public class DifferentiableChecker {
}
}
}
+ }
constantValueVerticesCache.addAll(queued);
return true;
}
+
+ // We know whether these are constant. For cases such as a MultiplicationVertex we would need to
+ // explore its parents to ensure its constant.
+ private boolean isValueKnownToBeConstant(Vertex vertex, Set<Vertex> constantValueVerticesCache) {
+ return vertex instanceof ConstantVertex || constantValueVerticesCache.contains(vertex) || vertex.isObserved();
+ }
+
+ private boolean isUnobservedProbabilistic(Vertex vertex) {
+ return vertex.isProbabilistic() && !vertex.isObserved();
+ }
}
