Skip to content

Commit

Permalink
Merge pull request #239 from p2t2/DEV2.2.2
Browse files Browse the repository at this point in the history
Dev2.2.2
  • Loading branch information
Michael Reposa committed Jul 7, 2014
2 parents cc6d42c + 5a36559 commit ab45d86
Show file tree
Hide file tree
Showing 36 changed files with 396 additions and 259 deletions.
1 change: 1 addition & 0 deletions Figaro/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/bin/
9 changes: 6 additions & 3 deletions Figaro/META-INF/MANIFEST.MF
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Figaro
Bundle-SymbolicName: com.cra.figaro
Bundle-Version: 2.2.0
Bundle-Version: 2.2.2
Export-Package: com.cra.figaro.algorithm,
com.cra.figaro.algorithm.decision,
com.cra.figaro.algorithm.decision.index,
com.cra.figaro.algorithm.factored,
com.cra.figaro.algorithm.filtering,
com.cra.figaro.algorithm.lazyfactored,
com.cra.figaro.algorithm.sampling,
com.cra.figaro.language,
com.cra.figaro.library.atomic.continuous,
Expand All @@ -18,8 +19,10 @@ Export-Package: com.cra.figaro.algorithm,
Bundle-Vendor: Charles River Analytics
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: org.scala-lang.scala-library,
org.scala-lang.scala-actors,
org.scala-lang.scala-reflect
org.scala-lang.scala-reflect,
com.typesafe.akka.actor;bundle-version="2.3.3",
com.typesafe.config;bundle-version="1.2.1",
org.scalatest;bundle-version="2.1.6"
Import-Package: org.apache.commons.math3.distribution;version="3.3.0"


Expand Down
2 changes: 1 addition & 1 deletion Figaro/figaro_build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version=2.2.1.0
version=2.2.2.0
115 changes: 79 additions & 36 deletions Figaro/src/main/scala/com/cra/figaro/algorithm/Anytime.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
package com.cra.figaro.algorithm

import com.cra.figaro.language._
import actors._
import akka.actor._
import com.typesafe.config.ConfigFactory

/**
* Class of services implemented by the anytime algorithm.
Expand All @@ -25,24 +26,15 @@ abstract class Service
* Class of responses to services.
*/
abstract class Response
/**
* General Response (String)
*/
case class ExceptionResponse(msg: String) extends Response

/**
* Messages to or from the actor.
*/
sealed abstract class Message
/**
* Message to stop the anytime algorithm
*/
case object Stop extends Message
/**
* Message to resume the anytime algorithm
*/
case object Resume extends Message
/**
* Message to kill the anytime algorithm
*/
case object Kill extends Message

/**
* A message to the handler to handle the given service.
*/
Expand Down Expand Up @@ -72,46 +64,97 @@ trait Anytime extends Algorithm {
* A class representing the actor running the algorithm.
*/
class Runner extends Actor {
private var running = false

def act() {
running = true
while (true) {
if (running) runStep()
receiveWithin(0) {
case TIMEOUT => ()
case Stop => { running = false; stopUpdate() }
case Resume => running = true
case Kill =>
exit()
case Handle(service) => sender ! handle(service)
}
}
import context._

def active: Receive = {
case Handle(service) =>
sender ! handle(service)
case "stop" =>
stopUpdate()
become (inactive)
case "next" =>
runStep()
self ! "next"
case _ =>
sender ! ExceptionResponse("Algorithm is still running")
}

def inactive: Receive = {
case Handle(service) =>
sender ! handle(service)
case "start" =>
runStep()
become(active)
self ! "next"
case "resume" =>
resume()
become(active)
self ! "next"
case "kill" =>
become(shuttingDown)
case _ =>
sender ! ExceptionResponse("Algorithm is stopped")
}

def shuttingDown: Receive = {
case _ =>
sender ! ExceptionResponse("Anytime algorithm has terminated")
}

def receive = inactive


}

/**
* The actor running the algorithm.
*/
protected var runner: Runner = _
val customConf = ConfigFactory.parseString("""
akka {
log-dead-letters = 0
log-dead-letters-during-shutdown = off
}
""")

var system: ActorSystem = null
var runner: ActorRef = null
var running = false;

/**
* A handler of services provided by the algorithm.
*/
def handle(service: Service): Response


protected def doStart() = {
initialize()
runner = new Runner
runner.start()
if (!running) {
system = ActorSystem("Anytime", ConfigFactory.load(customConf))
runner = system.actorOf(Props(new Runner))
initialize()
// println("Using ANYTIME")
running = true
}

runner ! "start"
}

protected def doStop() = runner ! Stop
protected def doStop() = runner ! "stop"

protected def doResume() = runner ! Resume
protected def doResume() = runner ! "resume"

protected def doKill() = {
runner ! Kill
shutdown
}

def shutdown {
cleanUp()
if (running)
{
runner ! "kill"
system.stop(runner)
system.shutdown
}
// println("Shutdown ANYTIME")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
package com.cra.figaro.algorithm

import com.cra.figaro.language._
import actors._
import Actor._

/**
* Anytime algorithms that compute most likely values of elements.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

package com.cra.figaro.algorithm

import actors._
import Actor._
import akka.pattern.{ask}
import akka.util.Timeout
import scala.concurrent.duration
import scala.concurrent.Await
import java.util.concurrent.TimeUnit

/**
* Anytime algorithms that compute probability of evidence.
Expand All @@ -35,11 +38,16 @@ trait AnytimeProbEvidence extends ProbEvidenceAlgorithm with Anytime {
* Returns the probability of evidence of the universe on which the algorithm operates.
* Throws AlgorithmInactiveException if the algorithm is not active.
*/
implicit val timeout = Timeout(5000, TimeUnit.MILLISECONDS)
def probabilityOfEvidence(): Double = {
if (!active) throw new AlgorithmInactiveException
runner ! Handle(ComputeProbEvidence)
receive {
val response = runner ? Handle(ComputeProbEvidence)
Await.result(response, timeout.duration ).asInstanceOf[Response] match {
case ProbEvidence(result) => result
case ExceptionResponse(msg) =>
println(msg)
0.0
case _ => 0.0
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@
package com.cra.figaro.algorithm

import com.cra.figaro.language._
import actors._
import Actor._
import java.util.concurrent.TimeUnit
import akka.util.Timeout
import akka.pattern.{ask}
import scala.concurrent.duration
import scala.concurrent.Await

/**
* Anytime algorithms that compute conditional probability of query elements.
Expand Down Expand Up @@ -58,25 +61,37 @@ trait AnytimeProbQuery extends ProbQueryAlgorithm with Anytime {
Probability(computeProbability(target, predicate))
}

implicit val timeout = Timeout(5000, TimeUnit.MILLISECONDS)
protected def doDistribution[T](target: Element[T]): Stream[(Double, T)] = {
runner ! Handle(ComputeDistribution(target))
receive {
val response = runner ? Handle(ComputeDistribution(target))
Await.result(response, timeout.duration ).asInstanceOf[Response] match {
case Distribution(result) => result.asInstanceOf[Stream[(Double, T)]]
case ExceptionResponse(msg) =>
println(msg)
Stream()
case _ => Stream()
}
}

protected def doExpectation[T](target: Element[T], function: T => Double): Double = {
runner ! Handle(ComputeExpectation(target, function))
receive {
case Expectation(result) =>
result
val response = runner ? Handle(ComputeExpectation(target, function))
Await.result(response, timeout.duration ).asInstanceOf[Response] match {
case Expectation(result) => result
case ExceptionResponse(msg) =>
println(msg)
0.0
case _ => 0.0
}
}

protected override def doProbability[T](target: Element[T], predicate: T => Boolean): Double = {
runner ! Handle(ComputeProbability(target, predicate))
receive {
val response = runner ? Handle(ComputeProbability(target, predicate))
Await.result(response, timeout.duration ).asInstanceOf[Response] match {
case Probability(result) => result
case ExceptionResponse(msg) =>
println(msg)
0.0
case _ => 0.0
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ abstract class DecisionMetropolisHastings[T, U] private (universe: Universe, pro
import MetropolisHastings._

// Used for debugging
private var elementsToTrack: Map[Element[_], Unit] = Map()
private var elementsToTrack: Map[Element[_], Null] = Map()
private var proposalCounts: Map[Element[_], Int] = Map()
// Make sure these maps don't cause memory leaks
universe.register(elementsToTrack)
Expand Down Expand Up @@ -339,7 +339,7 @@ abstract class DecisionMetropolisHastings[T, U] private (universe: Universe, pro
*/
def test(numSamples: Int, predicates: Seq[Predicate[_]], elementsToTrack: Seq[Element[_]]): (Map[Predicate[_], Double], Map[Element[_], Double]) = {
val successes: Map[Predicate[_], Int] = Map((predicates map (_ -> 0)): _*)
this.elementsToTrack = Map((elementsToTrack map (_ -> ()): _*))
this.elementsToTrack = Map((elementsToTrack map (_ -> null): _*))
proposalCounts = Map((elementsToTrack map (_ -> 0)): _*)
def collectResults() =
for { predicate <- predicates } {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ abstract class MetropolisHastings(universe: Universe, proposalScheme: ProposalSc
import MetropolisHastings._

// Used for debugging
private var elementsToTrack: Map[Element[_], Unit] = Map()
private var elementsToTrack: Map[Element[_], Null] = Map()
private var proposalCounts: Map[Element[_], Int] = Map()
// Make sure these maps don't cause memory leaks
universe.register(elementsToTrack)
Expand Down Expand Up @@ -347,7 +347,7 @@ abstract class MetropolisHastings(universe: Universe, proposalScheme: ProposalSc
rejects = 0
proposalCounts = Map((elementsToTrack map (_ -> 0)): _*)
val successes: Map[Predicate[_], Int] = Map((predicates map (_ -> 0)): _*)
this.elementsToTrack = Map((elementsToTrack map (_ -> ()): _*))
this.elementsToTrack = Map((elementsToTrack map (_ -> null): _*))
def collectResults() =
for { predicate <- predicates } {
if (predicate.test) successes += predicate -> (successes(predicate) + 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ abstract class MetropolisHastingsAnnealer(universe: Universe, proposalScheme: Pr
import MetropolisHastings._

// Used for debugging
private var elementsToTrack: Map[Element[_], Unit] = Map()
private var elementsToTrack: Map[Element[_], Null] = Map()
private var proposalCounts: Map[Element[_], Int] = Map()
// Make sure these maps don't cause memory leaks
universe.register(elementsToTrack)
Expand Down Expand Up @@ -336,7 +336,7 @@ abstract class MetropolisHastingsAnnealer(universe: Universe, proposalScheme: Pr
*/
def test(numSamples: Int, predicates: Seq[Predicate[_]], elementsToTrack: Seq[Element[_]]): (Map[Predicate[_], Double], Map[Element[_], Double]) = {
val successes: Map[Predicate[_], Int] = Map((predicates map (_ -> 0)): _*)
this.elementsToTrack = Map((elementsToTrack map (_ -> ()): _*))
this.elementsToTrack = Map((elementsToTrack map (_ -> null): _*))
proposalCounts = Map((elementsToTrack map (_ -> 0)): _*)
def collectResults() =
for { predicate <- predicates } {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ object ProbEvidenceSampler {
baseline.start()
Thread.sleep(baselineWaitingTime)
baseline.stop()
baseline.probAdditionalEvidence(evidence)
val alg = baseline.probAdditionalEvidence(evidence)
baseline.kill
alg
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ class AbstractionTest extends WordSpec with Matchers {
* Therefore flip should be around 0.4 for true.
*/
ve.probability(flip, (b: Boolean) => b) should be(0.4 +- 0.02)
ve.kill
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ class AlgorithmTest extends WordSpec with Matchers {
val a = new SimpleAnytime(c)
a.start()
a.expectation(c, (b: Boolean) => -1.0) should be > (0.0)
a.kill()
a.shutdown
}

"have a stable answer after stopping" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,7 @@ class ProbEvidenceTest extends WordSpec with Matchers {
val alg = BeliefPropagation(100, universe.activeElements.toList:_*)
alg.start
alg.computeEvidence should be(prob +- 0.01)

alg.kill
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ class AnnealingTest extends WordSpec with Matchers with PrivateMethodTester {
val temp2 = annealer2.getTemperature

temp2 should be > temp1

annealer1.kill
annealer2.kill
}

"increase the temperature with more iterations" in {
Expand Down
Loading

0 comments on commit ab45d86

Please sign in to comment.