Skip to content

fix the bug of MHSampler. #302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions example/hurricane2.blog
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Hurricane
* Figure 4.2 in Milch's thesis
*/

type City;
type PrepLevel;
type DamageLevel;

random City First ~ UniformChoice({c for City c});

random City NotFirst ~ UniformChoice({c for City c: c != First});

random PrepLevel Prep(City c) ~
if (First == c) then Categorical({High -> 0.5, Low -> 0.5})
else case Damage(First) in
{Severe -> Categorical({High -> 0.9, Low -> 0.1}),
Mild -> Categorical({High -> 0.1, Low -> 0.9})}
;

random DamageLevel Damage(City c) ~
case Prep(c) in {High -> Categorical({Severe -> 0.2, Mild -> 0.8}),
Low -> Categorical({Severe -> 0.8, Mild -> 0.2})}
;

distinct City A, B;
distinct PrepLevel Low, High;
distinct DamageLevel Severe, Mild;

obs Damage(First) = Severe;

query First;
123 changes: 86 additions & 37 deletions src/main/java/blog/sample/GenericProposer.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Set;

import blog.bn.BasicVar;
import blog.bn.BayesNetVar;
import blog.bn.DerivedVar;
import blog.bn.VarWithDistrib;
import blog.common.Util;
import blog.distrib.CondProbDistrib;
Expand Down Expand Up @@ -147,46 +148,91 @@ public double proposeNextState(PartialWorldDiff world) {
System.out.println(world);
}

// Remove barren variables
LinkedList newlyBarren = new LinkedList(world.getNewlyBarrenVars());
while (!newlyBarren.isEmpty()) {
BayesNetVar var = (BayesNetVar) newlyBarren.removeFirst();
if (!evidenceVars.contains(var) && !queryVars.contains(var)) {

// Remember its parents.
Set parentSet = world.getCBN().getParents(var);

if (var instanceof VarWithDistrib) {
// Multiply in the probability of sampling this
// variable again. Since the parent value may have
// changed, must use the old world.
logProbBackward += world.getSaved().getLogProbOfValue(var);

// Uninstantiate
world.setValue((VarWithDistrib) var, null);
// Remove unnecessary variables

Set evidenceAndQueries = new HashSet();
for (Iterator iter = evidenceVars.iterator(); iter.hasNext();) {
BayesNetVar var = (BayesNetVar) iter.next();
if (var instanceof BasicVar) {
evidenceAndQueries.add(var);
} else if (var instanceof DerivedVar) {
TraceParentRecEvalContext context = new TraceParentRecEvalContext(
new PartialWorldDiff(world));
var.ensureDetAndSupported(context);
if (context.getDependentVar() != null) {
evidenceAndQueries.addAll(context.getDependentVar());
}

// Check to see if its parents are now barren.
for (Iterator parentIter = parentSet.iterator(); parentIter.hasNext();) {

// If parent is barren, add to the end of this
// linked list. Note that if a parent has two
// barren children, it will only be added to the
// end of the list once, when the last child is
// considered.
BayesNetVar parent = (BayesNetVar) parentIter.next();
if (world.getCBN().getChildren(parent).isEmpty())
newlyBarren.addLast(parent);
}
}
for (Iterator iter = queryVars.iterator(); iter.hasNext();) {
BayesNetVar var = (BayesNetVar) iter.next();
if (var instanceof BasicVar) {
evidenceAndQueries.add(var);
} else if (var instanceof DerivedVar) {
TraceParentRecEvalContext context = new TraceParentRecEvalContext(
new PartialWorldDiff(world));
var.ensureDetAndSupported(context);
if (context.getDependentVar() != null) {
evidenceAndQueries.addAll(context.getDependentVar());
}
}
}

// Uniform sampling from new world.
boolean OK;
do {
OK = true;
for (Iterator iter = world.getInstantiatedVars().iterator(); iter
.hasNext();) {
BasicVar var = (BasicVar) iter.next();
Object value = world.getValue(var);
world.setValue(var, null);
if (!evidenceAndQueriesSupported(evidenceAndQueries, world)) {
world.setValue(var, value);
} else {
OK = false;
logProbBackward += world.getSaved().getLogProbOfValue(var);
}
}
} while (!OK);
logProbBackward += (-Math.log(world.getInstantiatedVars().size()
- numBasicEvidenceVars));
return (logProbBackward - logProbForward);
}

protected boolean evidenceAndQueriesSupported(Set evidenceAndQueries,
PartialWorld world) {
PartialWorldDiff tmpWorld = new PartialWorldDiff(world);
for (Iterator iter = evidenceAndQueries.iterator(); iter.hasNext();) {
BasicVar var = (BasicVar) iter.next();
if (!tmpWorld.isInstantiated(var)) {
return false;
}
TraceParentRecEvalContext context = new TraceParentRecEvalContext(
tmpWorld);
if (var instanceof VarWithDistrib) {
((VarWithDistrib) var).getDistrib(context);
if (context.getNumCalculateNewVars() > 0) {
return false;
}
}
}
for (Iterator iter = tmpWorld.getInstantiatedVars().iterator(); iter
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add type parameter to Iterator? Or you can use

for (Var var : ...getInstantiatedVars()) {
....
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lileicc
I don't think we need to add the type since you could see that we didn't add type parameter to Iterator everywhere else in the whole project.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chris will soon add type parameter to everywhere.
So you may start here.
If you use eclipse, you will see warnings. It is generally not a good idea
to keep the warnings.

On Fri, Aug 22, 2014 at 10:21 AM, Da Tang [email protected] wrote:

In src/main/java/blog/sample/GenericProposer.java:

  • PartialWorldDiff tmpWorld = new PartialWorldDiff(world);
  • for (Iterator iter = evidenceAndQueries.iterator(); iter.hasNext();) {
  •  BasicVar var = (BasicVar) iter.next();
    
  •  if (!tmpWorld.isInstantiated(var)) {
    
  •    return false;
    
  •  }
    
  •  TraceParentRecEvalContext context = new TraceParentRecEvalContext(
    
  •      tmpWorld);
    
  •  if (var instanceof VarWithDistrib) {
    
  •    ((VarWithDistrib) var).getDistrib(context);
    
  •    if (context.getNumCalculateNewVars() > 0) {
    
  •      return false;
    
  •    }
    
  •  }
    
  • }
  • for (Iterator iter = tmpWorld.getInstantiatedVars().iterator(); iter

@lileicc https://github.com/lileicc
I don't think we need to add the type since you could see that we didn't
add type parameter to Iterator everywhere else in the whole project.


Reply to this email directly or view it on GitHub
https://github.com/BayesianLogic/blog/pull/302/files#r16609606.

.hasNext();) {
BasicVar var = (BasicVar) iter.next();
if (!tmpWorld.isInstantiated(var)) {
return false;
}
TraceParentRecEvalContext context = new TraceParentRecEvalContext(
tmpWorld);
if (var instanceof VarWithDistrib) {
((VarWithDistrib) var).getDistrib(context);
if (context.getNumCalculateNewVars() > 0) {
return false;
}
}
}
return true;
}

// Samples a new value for the given variable (which must be
// supported in <code>world</code>) and sets this new value as the
// value of the variable in <code>world</code>. Then ensures that
Expand All @@ -195,7 +241,10 @@ public double proposeNextState(PartialWorldDiff world) {
// updates the logProbForward and logProbBackward variables.
protected void sampleValue(VarWithDistrib varToSample, PartialWorld world) {
// Save child set before graph becomes out of date
Set children = world.getCBN().getChildren(varToSample);
Set children = new HashSet();
children.addAll(world.getCBN().getChildren(varToSample));
children.addAll(evidenceVars);
children.addAll(queryVars);

DependencyModel.Distrib distrib = varToSample
.getDistrib(new DefaultEvalContext(world, true));
Expand All @@ -217,9 +266,10 @@ protected void sampleValue(VarWithDistrib varToSample, PartialWorld world) {

for (Iterator childrenIter = children.iterator(); childrenIter.hasNext();) {
BayesNetVar child = (BayesNetVar) childrenIter.next();
if (!world.isInstantiated(child)) // NOT SURE YET THIS IS THE RIGHT THING
// TO DO! CHECKING WITH BRIAN.
continue;
// if (!world.isInstantiated(child)) // NOT SURE YET THIS IS THE RIGHT
// THING
// TO DO! CHECKING WITH BRIAN.
// continue;
child.ensureDetAndSupported(instantiator);
}

Expand Down Expand Up @@ -251,6 +301,5 @@ public double latestLogProbBackward() {
public double latestLogProbForward() {
return logProbForward;
}

// End of debugger-only members.
}
136 changes: 69 additions & 67 deletions src/main/java/blog/sample/ParentRecEvalContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@

package blog.sample;

import java.util.*;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

import blog.ObjectIdentifier;
import blog.bn.BasicVar;
Expand All @@ -53,80 +55,80 @@
* {@link #getOrComputeValue(BasicVar)} instead.
*/
public class ParentRecEvalContext extends DefaultEvalContext {
/**
* Creates a new ParentRecEvalContext using the given world.
*/
public ParentRecEvalContext(PartialWorld world) {
super(world);
}
/**
* Creates a new ParentRecEvalContext using the given world.
*/
public ParentRecEvalContext(PartialWorld world) {
super(world);
}

/**
* Creates a new ParentRecEvalContext using the given world. If the
* <code>errorIfUndet</code> flag is true, the access methods on this instance
* will print error messages and exit the program if the world is not complete
* enough to determine the correct return value. Otherwise they will just
* return null in such cases.
*/
public ParentRecEvalContext(PartialWorld world, boolean errorIfUndet) {
super(world, errorIfUndet);
}
/**
* Creates a new ParentRecEvalContext using the given world. If the
* <code>errorIfUndet</code> flag is true, the access methods on this instance
* will print error messages and exit the program if the world is not complete
* enough to determine the correct return value. Otherwise they will just
* return null in such cases.
*/
public ParentRecEvalContext(PartialWorld world, boolean errorIfUndet) {
super(world, errorIfUndet);
}

final public Object getValue(BasicVar var) {
Object value = getOrComputeValue(var);
if (value == null) {
latestUninstParent = var;
var.ensureStable();
handleMissingVar(var);
} else {
if (parents.add(var)) {
var.ensureStable();
}
}
return value;
}
public Object getValue(BasicVar var) {
Object value = getOrComputeValue(var);
if (value == null) {
latestUninstParent = var;
var.ensureStable();
handleMissingVar(var);
} else {
if (parents.add(var)) {
var.ensureStable();
}
}
return value;
}

protected Object getOrComputeValue(BasicVar var) {
return world.getValue(var);
}
protected Object getOrComputeValue(BasicVar var) {
return world.getValue(var);
}

// Note that we don't have to override getSatisfiers, because the
// DefaultEvalContext implementation of getSatisfiers calls getValue
// on the number variable
// Note that we don't have to override getSatisfiers, because the
// DefaultEvalContext implementation of getSatisfiers calls getValue
// on the number variable

public NumberVar getPOPAppSatisfied(Object obj) {
if (obj instanceof NonGuaranteedObject) {
return ((NonGuaranteedObject) obj).getNumberVar();
}
public NumberVar getPOPAppSatisfied(Object obj) {
if (obj instanceof NonGuaranteedObject) {
return ((NonGuaranteedObject) obj).getNumberVar();
}

if (obj instanceof ObjectIdentifier) {
parents.add(new OriginVar((ObjectIdentifier) obj));
return world.getPOPAppSatisfied(obj);
}
if (obj instanceof ObjectIdentifier) {
parents.add(new OriginVar((ObjectIdentifier) obj));
return world.getPOPAppSatisfied(obj);
}

// Must be guaranteed object, so not generated by any number var
return null;
}
// Must be guaranteed object, so not generated by any number var
return null;
}

/**
* Returns the set of basic random variables that are instantiated and whose
* values have been used in calls to the access methods. This set is backed by
* the ParentRecEvalContext and will change as more random variables are used.
*
* @return unmodifiable Set of BasicVar
*/
public Set getParents() {
return Collections.unmodifiableSet(parents);
}
/**
* Returns the set of basic random variables that are instantiated and whose
* values have been used in calls to the access methods. This set is backed by
* the ParentRecEvalContext and will change as more random variables are used.
*
* @return unmodifiable Set of BasicVar
*/
public Set getParents() {
return Collections.unmodifiableSet(parents);
}

/**
* Returns the variable whose value was most recently needed by an access
* method, but which is not instantiated. This method returns null if no such
* variable exists.
*/
public BasicVar getLatestUninstParent() {
return latestUninstParent;
}
/**
* Returns the variable whose value was most recently needed by an access
* method, but which is not instantiated. This method returns null if no such
* variable exists.
*/
public BasicVar getLatestUninstParent() {
return latestUninstParent;
}

protected Set parents = new LinkedHashSet(); // of BasicVar
protected BasicVar latestUninstParent = null;
protected Set parents = new LinkedHashSet(); // of BasicVar
protected BasicVar latestUninstParent = null;
}
Loading