use lazy getter for affected cache
@@ -3,6 +3,7 @@ package io.improbable.keanu.algorithms.variational.optimizer;
import io.improbable.keanu.network.LambdaSection;
import io.improbable.keanu.vertices.ProbabilityCalculator;
import io.improbable.keanu.vertices.Vertex;
+import lombok.Getter;
import java.util.HashSet;
import java.util.List;
@@ -13,34 +14,30 @@ import java.util.stream.Collectors;
public class LambdaSectionSnapshot {
private final List<Vertex> latentVertices;
- private Map<Variable, LambdaSection> affectedVariablesCache;
+ @Getter(lazy=true)
+ private final Map<Variable, LambdaSection> affectedVariablesCache = update();
public LambdaSectionSnapshot(List<Vertex> latentVertices) {
this.latentVertices = latentVertices;
}
- private void update() {
- if (affectedVariablesCache == null) {
- affectedVariablesCache = createVariablesAffectedByCache(
- latentVertices
- );
- }
+ private Map<Variable, LambdaSection> update() {
+ return createVariablesAffectedByCache(latentVertices);
}
public double logProb(Set<? extends Variable> variables) {
update();
double sumLogProb = 0.0;
for (Variable v : variables) {
- sumLogProb += ProbabilityCalculator.calculateLogProbFor(affectedVariablesCache.get(v).getLatentAndObservedVertices());
+ sumLogProb += ProbabilityCalculator.calculateLogProbFor(this.getAffectedVariablesCache().get(v).getLatentAndObservedVertices());
}
return sumLogProb;
}
public Set<? extends Variable> getAllVariablesAffectedBy(Set<? extends Variable> variables) {
- update();
Set<Variable> allAffectedVariables = new HashSet<>();
for (Variable variable : variables) {
- allAffectedVariables.addAll(affectedVariablesCache.get(variable).getAllVertices());
+ allAffectedVariables.addAll(this.getAffectedVariablesCache().get(variable).getAllVertices());
}
return allAffectedVariables;
}
