Esempio n. 1
0
def testMoreElaborate(seed):
    # Confirm that HMC still works in the presence of brush.  Do not,
    # however, mess with the possibility that the principal nodes that
    # HMC operates over may themselves be in the brush.
    ripl = get_ripl(seed=seed)
    ripl.assume("x", "(tag (quote param) 0 (uniform_continuous -10 10))")
    ripl.assume("y",
                "(tag (quote param) 1 (uniform_continuous -10 10))",
                label="pid")
    ripl.assume("xout", """
(if (< x 0)
    (normal x 1)
    (normal x 2))""")
    ripl.assume(
        "out",
        "(multivariate_normal (array xout y) (matrix (list (list 1 0.5) (list 0.5 1))))"
    )
    # Note: Can't observe coordinatewise because observe is not flexible
    # enough.  For this to work we would need observations of splits.
    # ripl.observe("(lookup out 0)", 0)
    # ripl.observe("(lookup out 1)", 0)
    # Can't observe through the ripl literally because the string
    # substitution (!) is not flexible enough.
    # ripl.observe("out", [0, 0])
    ripl.observe("out", val.list([val.real(0), val.real(0)]))

    preds_mh = collectSamples(ripl,
                              "pid",
                              infer="(resimulation_mh default one 10)")
    ripl.sivm.core_sivm.engine.reinit_inference_problem()
    preds_hmc = collectSamples(ripl, "pid", infer="(hmc 'param all 0.1 20 10)")
    return reportSameContinuous(preds_mh, preds_hmc)
Esempio n. 2
0
def checkConstrainAVar6b(program):
    # This program is illegal, because when proposing to f, we may end
    # up constraining x, and x has a child that makes requests.
    ripl = get_ripl()
    ripl.assume("x", "(normal 0.0 1.0)")
    ripl.assume("y", "(normal 0.0 1.0)")
    ripl.assume("f", "(mem (lambda () (tag 0 0 (flip))))")
    ripl.observe("(if (f) x y)", 3.0)
    ripl.predict("(if (< (normal x 1.0) 3) x y)")
    collectSamples(ripl, "pid", infer=program)
Esempio n. 3
0
def checkConstrainAVar5b(program):
    # This program is illegal, because when proposing to f, we may end
    # up constraining x, and x has a child in A (it is in the (new)brush
    # itself).
    ripl = get_ripl()
    ripl.assume("x", "(normal 0.0 1.0)")
    ripl.assume("y", "(normal 0.0 1.0)")
    ripl.assume("f", "(mem (lambda () (tag 0 0 (flip))))")
    ripl.predict("(if (f) (normal x 0.0001) (normal y 0.0001))")
    ripl.observe("(if (f) x y)", 3.0)
    collectSamples(ripl, "pid", infer=program)
Esempio n. 4
0
def testForceBrush5(seed):
    ripl = get_ripl(seed=seed)
    ripl.assume("x", "(normal 0 1)", label="pid")
    ripl.assume("y", "(if (< x 0) (normal x 1) (normal (+ x 10) 1))")
    ripl.observe("y", 8)
    preds_mh = collectSamples(ripl, "pid", infer="(mh default one 10)")
    ripl.sivm.core_sivm.engine.reinit_inference_problem()
    preds_hmc = collectSamples(ripl,
                               "pid",
                               infer="(hmc default one 0.1 20 10)")
    return reportSameContinuous(preds_mh, preds_hmc)
def testRollingResample():
    ripl = get_ripl()
    ripl.assume("a", "(normal 10.0 1.0)", label="pid")
    ripl.observe("(normal a 1.0)", 14.0)

    flat_resample = "(do (resample 5) (likelihood_weight) (resample 1))"
    predictions1 = collectSamples(ripl, "pid", infer=flat_resample)

    rolling_resample = "(repeat 5 (do add_particle (resample 1)))"
    predictions2 = collectSamples(ripl, "pid", infer=rolling_resample)

    return reportSameContinuous(predictions1, predictions2)
Esempio n. 6
0
def checkConstrainWithAPredict1(program):
    # We may constrain the (flip) in f, and this has a child that makes
    # requests. Therefore this should (currently) throw an exception.
    ripl = get_ripl()
    ripl.assume("f", "(mem (lambda () (flip)))")
    ripl.assume("op1", "(if (flip) flip (lambda () (f)))")
    ripl.assume("op2", "(if (op1) op1 (lambda () (op1)))")
    ripl.assume("op3", "(if (op2) op2 (lambda () (op2)))")
    ripl.assume("op4", "(if (op3) op2 op1)")
    ripl.predict("(op4)")
    ripl.observe("(op4)", True)
    collectSamples(ripl, "pid", infer=program)
Esempio n. 7
0
def checkConstrainAVar5a(program):
    # This program is illegal, because when proposing to f, we may end
    # up constraining x, which needs to be propagated but the
    # propagation reaches a random choice. This could in principle be
    # allowed because there is no exchangeable couping, but for now we
    # have decided to forbid all non-identity downstream edges.
    ripl = get_ripl()
    ripl.assume("x", "(normal 0.0 1.0)")
    ripl.assume("y", "(normal 0.0 1.0)")
    ripl.assume("f", "(mem (lambda () (tag 0 0 (flip))))")
    ripl.predict("(normal x 0.0001)")
    ripl.observe("(if (f) x y)", 3.0)
    collectSamples(ripl, "pid", infer=program)
Esempio n. 8
0
def testMoveMatrix():
    ripl = get_ripl()
    ripl.assume("mu", "(array 0 0)")
    ripl.assume("scale", "(matrix (list (list 2 1) (list 1 2)))")
    ripl.assume("sigma", "(wishart scale 4)", label="pid")
    ripl.assume("out", "(multivariate_normal mu sigma)")
    ripl.observe("out", val.list([val.real(1), val.real(1)]))

    preds_mh = collectSamples(ripl,
                              "pid",
                              infer="(resimulation_mh default one 30)")
    ripl.sivm.core_sivm.engine.reinit_inference_problem()
    preds_hmc = collectSamples(ripl, "pid", infer="(hmc default all 0.01 5 5)")
def testNormal4(seed):
    ripl = get_ripl(seed=seed)
    ripl.assume("f", "(lambda (mu) (normal mu 1))")
    ripl.assume("g", "(lambda (x y z) ((lambda () f)))")
    ripl.predict("((g (f (normal 0 1)) (f 5) (f (f 1))) 5)", label="pid")
    predictions = collectSamples(ripl, "pid")
    return reportKnownGaussian(5, 1, predictions)
Esempio n. 10
0
def testCategorical1(seed):
    ripl = get_ripl(seed=seed)
    ripl.predict("(categorical (simplex 0.3 0.7))", label="pid")

    predictions = collectSamples(ripl, "pid")
    ans = [(0, 0.3), (1, 0.7)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 11
0
def testBernoulli1(seed):
    ripl = get_ripl(seed=seed)
    ripl.predict("(bernoulli 0.3)", label="pid")

    predictions = collectSamples(ripl, "pid")
    ans = [(True, 0.3), (False, 0.7)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 12
0
def checkAAAParticleWeights(sp, seed):
    if inParallel() and "make_suff_stat_bernoulli" in sp and backend_name(
    ) == "puma":
        raise SkipTest(
            "The Lite SPs in Puma interface is not thread-safe, and make_suff_stat_bernoulli comes from Lite."
        )
    if "dir_cat" in sp and backend_name() == 'puma':
        raise SkipTest(
            "Dirichlet categorical in Puma does not accept objects parameter.  Issue #340"
        )
    ripl = get_ripl(seed=seed)

    ripl.assume("a", "1.0")
    # bogus labelled directives, so the infer step can forget them
    ripl.predict("nil", label="f")
    ripl.predict("nil", label="pid")

    predictions = collectSamples(ripl,
                                 "pid",
                                 infer="""\
(do (resample 10)
    (forget 'pid)
    (forget 'f)
    (assume f %s f)
    (predict (f) pid)
    (observe (f) true obs1)
    (observe (f) true obs2)
    (resample 1)
    (forget 'obs2)
    (forget 'obs1))""" % sp)
    ans = [(False, .25), (True, .75)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 13
0
def testAssumedGibbsWithLatent():
#    raise(SkipTest('for quick results.'))
    "Checks an exact proposal with latent randomness"
    ripl = get_ripl()
    ripl.assume("x", "(scope_include (quote X) 0 (normal 0 1.0))", label="pid")
    ripl.observe("(scope_include (quote Y) 0 (normal (sqrt (* x x)) 1.0))", 10.0)
    
    MyBimodalExactPosterior = partial(BimodalExactPosterior, mu1=0, sigma1=1.0, sigma2=1.0)
    ripl.register_proposal_program_class("MyBimodalExactPosterior", MyBimodalExactPosterior)
    
    # Posterior for a is bi-modal with two modes at -5, 5, both with precision 2
    #  ripl.predict("(normal a 1.0)")
    proposal_src = """
        [declare {
        "name":"bimodalexact",
        "class":"MyBimodalExactPosterior",
        "conditioned":[["Y",0]],
        "target":[["X",0]],
        "ready":"yes",
        "num_samples":0}]
        """
    ripl.execute_program(proposal_src)
    predictions = collectSamples(ripl,"pid",infer="(custommh bimodalexact assumed_gibbs 1 1)")
    cdf = (lambda x:(stats.norm(loc=-5, scale=math.sqrt(0.5)).cdf(x)+stats.norm(loc=5, scale=math.sqrt(0.5)).cdf(x))*0.5)
    return reportKnownContinuous(cdf, predictions, "0.5*N(-5,sqrt(0.5))+0.5*N(5,sqrt(0.5))")
Esempio n. 14
0
def test_foreign_latents_infer(seed):
    # Same as test.inference_quality.micro.test_latents.testHMMSP1

    builtins = builtin.builtInSPs()
    ripl = get_ripl(seed=seed)
    ripl.bind_foreign_sp("test_lazy_hmm", builtins["make_lazy_hmm"])

    ripl.assume(
        "f", """
(test_lazy_hmm
 (simplex 0.5 0.5)
 (matrix (array (array 0.7 0.3)
                (array 0.3 0.7)))
 (matrix (array (array 0.9 0.2)
                (array 0.1 0.8))))
""")
    ripl.observe("(f 1)", "integer<0>")
    ripl.observe("(f 2)", "integer<0>")
    ripl.observe("(f 3)", "integer<1>")
    ripl.observe("(f 4)", "integer<0>")
    ripl.observe("(f 5)", "integer<0>")
    ripl.predict("(f 6)", label="pid")
    ripl.predict("(f 7)")
    ripl.predict("(f 8)")

    predictions = collectSamples(ripl, "pid")
    ans = [(0, 0.6528), (1, 0.3472)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 15
0
def testCustomTrainer():
#    raise(SkipTest('for quick results.'))
    "Train a proposal to inverse a QMR model with rare diseases, using custom trainer"
    ripl = get_ripl()
    ripl.assume("d0", "(scope_include (quote D) 0 (bernoulli 0.01))", label="D0")
    ripl.assume("d1", "(scope_include (quote D) 1 (bernoulli 0.01))", label="D1")
    ripl.assume("d2", "(scope_include (quote D) 2 (bernoulli 0.005))", label="D2")
    ripl.assume("joint", "(+ (* d0 4) (* d1 2) d2)", label="pid")
    ripl.observe("(scope_include (quote S) 0 (bernoulli (- 1.0001 (pow 0.5 (+ d0 d1)))))", 1.0)
    ripl.observe("(scope_include (quote S) 1 (bernoulli (- 1.0001 (pow 0.5 (+ d0 d2)))))", 1.0)
    ripl.observe("(scope_include (quote S) 2 (bernoulli (- 1.0001 (pow 0.5 (+ d1 d2)))))", 1.0)
    
    ripl.register_proposal_program_class("LogisticRegressionProposalProgram", LogisticRegressionProposalProgram)
    ripl.register_trainer_src("QMR_highprior", QMR_highprior)
    
    # Posterior for d2 is Bernoulli with p(d2=1) = 0.5
    proposal_src = """
        [declare {
        "name":"logreg",
        "class":"LogisticRegressionProposalProgram",
        "conditioned":[["S",0], ["S",1], ["S",2]],
        "target":[["D",0], ["D",1], ["D",2]],
        "trainer":"QMR_highprior",
        "num_samples":1000}]
        """
    ripl.execute_program(proposal_src)
    predictions = collectSamples(ripl,"pid",infer="(custommh logreg aux 1 5)")
    ans = [(0, 0.000001), (1, 0.003), (2, 0.006), (3, 0.25), (4, 0.006), (5, 0.25), (6, 0.5), (7, 0.004)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 16
0
def testVentureBinaryHMM1(seed):
    ripl = get_ripl(seed=seed)

    ripl.assume(
        "f", """
(mem (lambda (i)
  (if (eq i 0)
    (bernoulli 0.5)
    (if (f (- i 1))
      (bernoulli 0.7)
      (bernoulli 0.3)))))
""")

    ripl.assume(
        "g", """
(mem (lambda (i)
  (if (f i)
    (bernoulli 0.8)
    (bernoulli 0.1))))
""")

    ripl.observe("(g 1)", False)
    ripl.observe("(g 2)", False)
    ripl.observe("(g 3)", True)
    ripl.observe("(g 4)", False)
    ripl.observe("(g 5)", False)
    ripl.predict("(g 6)", label="pid")

    predictions = collectSamples(ripl, "pid")
    ans = [(0, 0.6528), (1, 0.3472)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 17
0
def testPGibbsDynamicScopeInterval(seed):
  ripl = get_ripl(seed=seed)

  ripl.assume("transition_fn", "(lambda (x) (normal x 1.0))")
  ripl.assume("observation_fn", "(lambda (y) (normal y 1.0))")

  ripl.assume("initial_state_fn", "(lambda () (normal 0.0 1.0))")
  ripl.assume("f","""
(mem (lambda (t)
  (tag 0 t (if (= t 0) (initial_state_fn) (transition_fn (f (- t 1)))))))
""")

  ripl.assume("g","(mem (lambda (t) (observation_fn (f t))))")

  ripl.observe("(g 0)",1.0)
  ripl.observe("(g 1)",2.0)
  ripl.observe("(g 2)",3.0)
  ripl.observe("(g 3)",4.0)
  ripl.observe("(g 4)",5.0)

  ripl.predict("(f 4)","pid")

  P = 3 if ignore_inference_quality() else 8
  T = 2 if ignore_inference_quality() else 10

  infer = "(do (pgibbs 0 (ordered_range 0 3) %d %d) (pgibbs 0 (ordered_range 1 4) %d %d))" % (P,P,T,T)

  predictions = collectSamples(ripl,"pid",infer=infer)
  return reportKnownGaussian(390/89.0, math.sqrt(55/89.0), predictions)
Esempio n. 18
0
def checkPGibbsDynamicScope1(operator, seed):
  ripl = get_ripl(seed=seed)

  ripl.assume("transition_fn", "(lambda (x) (normal x 1.0))")
  ripl.assume("observation_fn", "(lambda (y) (normal y 1.0))")

  ripl.assume("initial_state_fn", "(lambda () (normal 0.0 1.0))")
  ripl.assume("f","""
(mem (lambda (t)
  (tag 0 t (if (= t 0) (initial_state_fn) (transition_fn (f (- t 1)))))))
""")

  ripl.assume("g","(mem (lambda (t) (observation_fn (f t))))")

  ripl.observe("(g 0)",1.0)
  ripl.observe("(g 1)",2.0)
  ripl.observe("(g 2)",3.0)
  ripl.observe("(g 3)",4.0)
  ripl.observe("(g 4)",5.0)

  ripl.predict("(f 4)","pid")

  if ignore_inference_quality():
    infer = "(%s 0 ordered 3 2)" % operator
  else:
    infer = "(%s 0 ordered 20 10)" % operator

  predictions = collectSamples(ripl,"pid",infer=infer)
  return reportKnownGaussian(390/89.0, math.sqrt(55/89.0), predictions)
Esempio n. 19
0
def testHMMSP2(seed):
    ripl = get_ripl(seed=seed)
    ripl.assume(
        "f", """
(if (flip)
(make_lazy_hmm
 (simplex 0.5 0.5)
 (matrix (array (array 0.7 0.3)
               (array 0.3 0.7)))
 (matrix (array (array 0.9 0.2)
               (array 0.1 0.8))))
(make_lazy_hmm
 (simplex 0.5 0.5)
 (matrix (array (array 0.7 0.3)
               (array 0.3 0.7)))
 (matrix (array (array 0.9 0.2)
               (array 0.1 0.8)))))
""")
    ripl.observe("(f 1)", "integer<0>")
    ripl.observe("(f 2)", "integer<0>")
    ripl.observe("(f 3)", "integer<1>")
    ripl.observe("(f 4)", "integer<0>")
    ripl.observe("(f 5)", "integer<0>")
    ripl.predict("(f 6)", label="pid")
    ripl.predict("(f 7)")
    ripl.predict("(f 8)")

    predictions = collectSamples(ripl, "pid")
    ans = [(0, 0.6528), (1, 0.3472)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 20
0
def testHMMSP4(seed):
    ripl = get_ripl(seed=seed)
    ripl.assume("z", "(flip)")
    ripl.assume(
        "f", """
(make_lazy_hmm
 (simplex 0.5 0.5)
 (matrix (array (array 0.7 0.3)
               (array 0.3 0.7)))
 (if z
  (matrix (array (array 0.9 0.2)
                 (array 0.1 0.8)))
  (matrix (array (array 0.8 0.8)
                 (array 0.2 0.2)))))
""")
    ripl.observe("(f 1)", "integer<0>")
    ripl.observe("(f 2)", "integer<0>")
    ripl.observe("(f 3)", "integer<1>")
    ripl.observe("(f 4)", "integer<0>")
    ripl.observe("(f 5)", "integer<0>")
    ripl.predict("z", label="pid")

    predictions = collectSamples(ripl, "pid")
    ans = [(True, 0.2952), (False, 0.7048)]
    return reportKnownDiscrete(ans, predictions)
def checkDirichletCategoricalWeakPrior(ripl, label):
    for _ in range(default_num_data(8)):
        ripl.observe("(f)", "integer<1>")

    predictions = collectSamples(ripl, label, infer="mixes_slowly")
    ans = [(1, .9), (0, .1)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 22
0
def checkPGibbsBlockingMHHMM1(operator, seed):
  # The point of this is that it should give reasonable results in
  # very few transitions but with a large number of particles.
  ripl = get_ripl(seed=seed)

  ripl.assume("x0","(tag 0 0 (normal 0.0 1.0))")
  ripl.assume("x1","(tag 0 1 (normal x0 1.0))")
  ripl.assume("x2","(tag 0 2 (normal x1 1.0))")
  ripl.assume("x3","(tag 0 3 (normal x2 1.0))")
  ripl.assume("x4","(tag 0 4 (normal x3 1.0))")

  ripl.assume("y0","(normal x0 1.0)")
  ripl.assume("y1","(normal x1 1.0)")
  ripl.assume("y2","(normal x2 1.0)")
  ripl.assume("y3","(normal x3 1.0)")
  ripl.assume("y4","(normal x4 1.0)")

  ripl.observe("y0",1.0)
  ripl.observe("y1",2.0)
  ripl.observe("y2",3.0)
  ripl.observe("y3",4.0)
  ripl.observe("y4",5.0)
  ripl.predict("x4",label="pid")

  if ignore_inference_quality():
    infer = "(%s 0 ordered 3 2)" % operator
  else:
    infer = "(%s 0 ordered 20 10)" % operator

  predictions = collectSamples(ripl,"pid",infer=infer)
  return reportKnownGaussian(390.0/89.0, math.sqrt(55/89.0), predictions)
Esempio n. 23
0
def testExpon1(seed):
    # Check that exponential distribution is parameterized correctly
    ripl = get_ripl(seed=seed)
    ripl.assume("a", "(expon 4.0)", label="pid")
    observed = collectSamples(ripl, "pid")
    expon_cdf = lambda x: expon.cdf(x, scale=1. / 4)
    return reportKnownContinuous(expon_cdf, observed)
Esempio n. 24
0
def testAuxWithoutLatent():
#    raise(SkipTest('for quick results.'))
    "Checks the posterior distribution on a Gaussian given an unlikely observation"
    ripl = get_ripl()
    ripl.assume("a", "(scope_include (quote A) 0 (normal 10.0 1.0))", label="pid")
    ripl.observe("(scope_include (quote B) 0 (normal a 1.0))", 20.0)
    
    # fake mu1=9, so that assumed_gibbs is doomed to fail the statistical test
    MyNormalBiasedPosterior = partial(NormalExactPosterior, mu1=9, sigma1=1.0, sigma2=1.0)
    ripl.register_proposal_program_class("MyNormalBiasedPosterior", MyNormalBiasedPosterior)
    
    # Posterior for a is normal with mean 15, precision 2
    #  ripl.predict("(normal a 1.0)")
    proposal_src = """
        [declare {
        "name":"normalbiased",
        "class":"MyNormalBiasedPosterior",
        "conditioned":[["B",0]],
        "target":[["A",0]],
        "ready":"yes",
        "num_samples":0}]
        """
    ripl.execute_program(proposal_src)
    predictions = collectSamples(ripl,"pid",infer="(custommh normalbiased aux 1 20)")
    cdf = stats.norm(loc=15, scale=math.sqrt(0.5)).cdf
    return reportKnownContinuous(cdf, predictions, "N(15,sqrt(0.5))")
Esempio n. 25
0
def testStudentT2(seed):
    # Simple program involving simulating from a student_t, with basic
    # testing of loc and shape params.
    ripl = get_ripl(seed=seed)
    ripl.assume("x", "(student_t 1.0 3 2)")
    ripl.assume("a", "(/ (- x 3) 2)")
    ripl.observe("(normal a 1.0)", 3.0)
    ripl.predict("(normal a 1.0)", label="pid")
    predictions = collectSamples(ripl, "pid", infer="mixes_slowly")

    # Posterior of a is proprtional to
    def postprop(a):
        return stats.t(1).pdf(a) * stats.norm(loc=3).pdf(a)

    import scipy.integrate as integrate
    (normalize, _) = integrate.quad(postprop, -10, 10)

    def posterior(a):
        return postprop(a) / normalize

    (meana, _) = integrate.quad(lambda x: x * posterior(x), -10, 10)
    (meanasq, _) = integrate.quad(lambda x: x * x * posterior(x), -10, 10)
    vara = meanasq - meana * meana
    # TODO Test agreement with the whole shape of the distribution, not
    # just the mean
    return reportKnownMean(meana, predictions, variance=vara + 1.0)
Esempio n. 26
0
def testLogFlip(seed):
    ripl = get_ripl(seed=seed)

    ripl.predict('(log_flip (log 0.5))', label='pid')

    predictions = collectSamples(ripl, 'pid')
    ans = [(False, 0.5), (True, 0.5)]
    return reportKnownDiscrete(ans, predictions)
def checkMakeSymDirCat1(maker, seed):
    # Extremely simple program, with an AAA procedure when uncollapsed
    ripl = get_ripl(seed=seed)
    ripl.assume("f", "(%s 1.0 2)" % maker)
    ripl.predict("(f)", label="pid")
    predictions = collectSamples(ripl, "pid")
    ans = [(0, .5), (1, .5)]
    return reportKnownDiscrete(ans, predictions)
def checkDirichletCategoricalAAA(ripl, label, infer=None):
    for i in range(1, 4):
        for _ in range(default_num_data(20)):
            ripl.observe("(f)", "integer<%d>" % i)

    predictions = collectSamples(ripl, label, infer=infer)
    ans = [(0, .1), (1, .3), (2, .3), (3, .3)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 29
0
def checkPGibbsBasic2(in_parallel, seed):
  # Basic sanity test
  ripl = get_ripl(seed=seed)
  ripl.assume("x","(flip 0.1)",label="pid")
  infer = "(pgibbs default one 2 %s %s)" % (default_num_transitions_per_sample(), in_parallel)
  predictions = collectSamples(ripl,"pid",infer=infer)
  ans = [(False,.9),(True,.1)]
  return reportKnownDiscrete(ans, predictions)
Esempio n. 30
0
def testCategorical2(seed):
    ripl = get_ripl(seed=seed)
    ripl.predict("(categorical (simplex 0.3 0.7) (array true false))",
                 label="pid")

    predictions = collectSamples(ripl, "pid")
    ans = [(True, 0.3), (False, 0.7)]
    return reportKnownDiscrete(ans, predictions)
def testBasicRejection1(seed):
    ripl = get_ripl(seed=seed)
    ripl.assume("x", "(flip 0.5)", label="pid")
    predictions = collectSamples(ripl,
                                 "pid",
                                 infer="(rejection default all 1)")
    ans = [(True, 0.5), (False, 0.5)]
    return reportKnownDiscrete(ans, predictions)
Esempio n. 32
0
def testOuterMix1(seed):
  # Makes sure that the mix-mh weights are correct
  ripl = get_ripl(seed=seed)
  ripl.predict("(if (bernoulli 0.5) (if (bernoulli 0.5) 2 3) 1)", label="pid")

  predictions = collectSamples(ripl,"pid")
  ans = [(1,.5), (2,.25), (3,.25)]
  return reportKnownDiscrete(ans, predictions)
Esempio n. 33
0
def checkForceBrush2(infer, seed):
    ripl = get_ripl(seed=seed)
    ripl.assume("x", "(normal 0 1)")
    ripl.predict("(if (< x 0) (normal 0 1) (normal 100 1))", label="pid")
    predictions = collectSamples(ripl, "pid", infer=infer)
    cdf = lambda x: 0.5 * stats.norm(loc=0, scale=1).cdf(x) + 0.5 * stats.norm(
        loc=100, scale=1).cdf(x)
    return reportKnownContinuous(cdf, predictions, "N(0,1)/2 + N(100,1)/2")
Esempio n. 34
0
def testDefaultTrainer():
#    raise(SkipTest('for quick results.'))
    "Train a proposal to inverse a joint Gaussian model, using default (target) trainer"
    ripl = get_ripl()
    ripl.assume("a", "(scope_include (quote A) 0 (normal 0.0 1.0))", label="pid")
    ripl.observe("(scope_include (quote B) 0 (normal (+ (* a 2) 2) 1.0))", 4.5)
    
    ripl.register_proposal_program_class("LinearRegressionProposalProgram", LinearRegressionProposalProgram)
    
    # Posterior for a is normal with mean 1.0, precision 5
    proposal_src = """
        [declare {
        "name":"linreg",
        "class":"LinearRegressionProposalProgram",
        "conditioned":[["B",0]],
        "target":[["A",0]],
        "num_samples":1000}]
        """
    ripl.execute_program(proposal_src)
    predictions = collectSamples(ripl,"pid",infer="(custommh linreg aux 1 5)")
    cdf = stats.norm(loc=1.0, scale=math.sqrt(0.2)).cdf
    return reportKnownContinuous(cdf, predictions, "N(1.0,sqrt(0.2))")
Esempio n. 35
0
def testCustommhSaveLoad():
#    raise(SkipTest('for quick results.'))
    "Checks the posterior distribution on a Gaussian given an unlikely observation"
    ripl = get_ripl()
    ripl.assume("a", "(scope_include (quote A) 0 (normal 10.0 1.0))", label="pid")
    ripl.observe("(scope_include (quote B) 0 (normal a 1.0))", 20.0)
    
    MyNormalExactPosterior = partial(NormalExactPosterior, mu1=10.0, sigma1=1.0, sigma2=1.0)
    ripl.register_proposal_program_class("MyNormalExactPosterior", MyNormalExactPosterior)
    
    # Posterior for a is normal with mean 15, precision 2
    #  ripl.predict("(normal a 1.0)")
    proposal_src_1 = """
        [declare {
        "name":"normalexact1",
        "class":"MyNormalExactPosterior",
        "conditioned":[["B",0]],
        "target":[["A",0]],
        "ready":"yes",
        "save_to":"test_custommh_save_load.npy",
        "num_samples":0}]
        """
    ripl.execute_program(proposal_src_1)
    proposal_src_2 = """
        [declare {
        "name":"normalexact2",
        "class":"MyNormalExactPosterior",
        "conditioned":[["B",0]],
        "target":[["A",0]],
        "load_from":"test_custommh_save_load.npy",
        "num_samples":0}]
        """
    ripl.execute_program(proposal_src_2)
    predictions = collectSamples(ripl,"pid",infer="(custommh normalexact2 assumed_gibbs 1 1)")
    cdf = stats.norm(loc=15, scale=math.sqrt(0.5)).cdf
    return reportKnownContinuous(cdf, predictions, "N(15,sqrt(0.5))")