Beispiel #1
0
 def __init__(self, p0, T, O):
     req = TypedPSP(UncollapsedHMMRequestPSP(),
                    SPType([t.CountType()], t.RequestType()))
     output = TypedPSP(UncollapsedHMMOutputPSP(O),
                       SPType([t.CountType()], t.IntegerType()))
     super(UncollapsedHMMSP, self).__init__(req, output)
     self.p0 = p0
     self.T = T
     self.O = O
Beispiel #2
0
def __venture_start__(ripl):
    start = time.time()
    # NOTE: these are all currently inference SPs
    ripl.bind_foreign_inference_sp(
        "make_symbol",
        deterministic_typed(make_name,
                            [t.SymbolType(), t.NumberType()], t.SymbolType()))
    ripl.bind_foreign_inference_sp(
        "logsumexp",
        deterministic_typed(logsumexp, [t.ArrayUnboxedType(t.NumberType())],
                            t.NumberType()))
    ripl.bind_foreign_inference_sp(
        "concatenate",
        deterministic_typed(concatenate, [
            t.ArrayUnboxedType(t.NumberType()),
            t.ArrayUnboxedType(t.NumberType())
        ], t.ArrayUnboxedType(t.NumberType())))
    ripl.bind_foreign_inference_sp(
        "sum",
        deterministic_typed(sum_sp, [t.ArrayUnboxedType(t.NumberType())],
                            t.NumberType()))
    ripl.bind_foreign_inference_sp(
        "mean",
        deterministic_typed(mean_sp, [t.ArrayUnboxedType(t.NumberType())],
                            t.NumberType()))
    ripl.bind_foreign_inference_sp(
        "stderr",
        deterministic_typed(stderr, [t.ArrayUnboxedType(t.NumberType())],
                            t.NumberType()))
    ripl.bind_foreign_inference_sp(
        "random_string",
        deterministic_typed(random_string, [t.IntegerType()], t.StringType()))
    ripl.bind_foreign_inference_sp(
        "cat_string",
        deterministic_typed(cat_string,
                            [t.StringType(), t.StringType()], t.StringType()))
    ripl.bind_foreign_inference_sp(
        "start_timer", deterministic_typed(start_timer, [], t.NumberType()))
    ripl.bind_foreign_inference_sp(
        "time_elapsed",
        deterministic_typed(time_elapsed, [t.NumberType()], t.NumberType()))
    ripl.execute_program("define new_trace = proc() { run(new_model()) };")
    ripl.execute_program(
        "define run_in_trace = proc(trace, program) { first(run(in_model(trace, program))) };"
    )
    ripl.execute_program(
        "define parallel_mapv = proc(f, l) { run(parallel_mapv_action(f, l, 4)) };"
    )
Beispiel #3
0
    descr="lte returns true if its first argument compares less than or " \
          "equal to its second"))

# If you are wondering about the type signature, this function
# bootstraps the implicit coersion to numbers into an explicit one.
registerBuiltinSP(
    "real",
    deterministic_typed(
        lambda x: x, [t.NumberType()],
        t.NumberType(),
        descr="real explicitly coerces its argument to a number"))

registerBuiltinSP(
    "atom",
    deterministic_typed(
        lambda x: x, [t.IntegerType()],
        t.AtomType(),
        descr="atom returns the identity of its argument integer as an atom"))

registerBuiltinSP(
    "atom_index",
    deterministic_typed(
        lambda x: x, [t.AtomType()],
        t.IntegerType(),
        descr=
        "atom_index returns the identity of its argument atom as an integer"))

registerBuiltinSP(
    "integer",
    deterministic_typed(
        int, [t.NumberType()],
Beispiel #4
0
  deterministic_typed(lambda *nums: np.array(nums),
    [t.ProbabilityType()], t.SimplexType(), variadic=True,
    descr="simplex returns the simplex point given by its argument coordinates."))

registerBuiltinSP("is_simplex", type_test(t.SimplexType()))

registerBuiltinSP("normalize",
  deterministic_typed(u.normalizeList,
    [t.HomogeneousListType(t.NumberType())],
    t.SimplexType(),
    descr="%s converts its argument sequence to a simplex by scaling" \
          "its elements so that they sum to 1."))

registerBuiltinSP("arange",
  deterministic_typed(np.arange,
    [t.IntegerType(), t.IntegerType()],
    t.ArrayUnboxedType(t.IntegerType()),
    min_req_args=1,
    descr="%s([start], stop) returns an array of n consecutive integers " \
          "from start (inclusive) up to stop (exclusive)."))

registerBuiltinSP("fill",
  deterministic_typed(np.full,
    [t.IntegerType(), t.NumberType()],
    t.ArrayUnboxedType(t.NumberType()),
    descr="%s(n, x) returns an array with the number x repeated n times"))

registerBuiltinSP("linspace",
  deterministic_typed(np.linspace,
    [t.NumberType(), t.NumberType(), t.CountType()],
    t.ArrayUnboxedType(t.NumberType()),
Beispiel #5
0
    deterministic_typed(Star, [],
                        t.ForeignBlobType(),
                        descr="""
Walk to all the random choices in the dynamic extent of the source.
"""))

inf.registerBuiltinInferenceSP("minimal_subproblem", \
    deterministic_typed(MinimalSubproblem, [t.ForeignBlobType()], t.ForeignBlobType(), descr="""
Construct the minimal subproblem from the given selection.
"""))

# XXX Do I want different names for "random singleton variable" vs
# "random singleton block"?  ATM, they can be disambiguated by
# dispatch.
inf.registerBuiltinInferenceSP("random_singleton", \
    deterministic_typed(Random1, [t.ForeignBlobType()], t.ForeignBlobType(), descr="""
Randomly select one component of the current selection.

Correctly account for the acceptance correction due to possible
changes in the probability of selecting a particular subproblem to
work on.

A "component" may be a single random choice, if the current selection
is a set, or a set, if the current selection is a dictionary of tag
values to sets of variables.
"""))

inf.registerBuiltinInferenceSP("esr", \
    deterministic_typed(EsrEdge, [t.IntegerType()], t.ForeignBlobType(),
                        descr="""Walk to the given requested result."""))
Beispiel #6
0
    def logDensity(self, value, args):
        n = args.operandValues()[0]
        xs = args.spaux().xs
        assert len(xs) > n
        theta = np.dot(xs[n], self.O)
        return math.log(theta[value])

    def incorporate(self, value, args):
        n = args.operandValues()[0]
        os = args.spaux().os
        if n not in os: os[n] = []
        os[n].append(value)

    def unincorporate(self, value, args):
        n = args.operandValues()[0]
        os = args.spaux().os
        del os[n][os[n].index(value)]
        if not os[n]: del os[n]


class UncollapsedHMMRequestPSP(DeterministicPSP):
    def simulate(self, args):
        return Request([], [args.operandValues()[0]])


registerBuiltinSP(
    "make_lazy_hmm",
    typed_nr(MakeUncollapsedHMMOutputPSP(),
             [t.SimplexType(), t.MatrixType(),
              t.MatrixType()], SPType([t.CountType()], t.IntegerType())))
Beispiel #7
0
def binaryNumInt(f, sim_grad=None, descr=None):
    return deterministic_typed(f,
                               [t.NumberType(), t.NumberType()],
                               t.IntegerType(),
                               sim_grad=sim_grad,
                               descr=descr)
Beispiel #8
0
          ' write (log_{name} x) instead. '\
          'If you are tempted to write ({name} (logistic x)),'\
          ' write (log_odds_{name} x) instead.'\
          .format(name=name)


registerBuiltinSP(
    "flip",
    typed_nr(BernoulliOutputPSP(), [t.ProbabilityType()],
             t.BoolType(),
             min_req_args=0))

registerBuiltinSP(
    "bernoulli",
    typed_nr(BernoulliOutputPSP(), [t.ProbabilityType()],
             t.IntegerType(),
             min_req_args=0))


class LogBernoulliOutputPSP(DiscretePSP):
    def simulate(self, args):
        logp = args.operandValues()[0]
        return math.log(args.py_prng().random()) < logp

    def logDensity(self, val, args):
        logp = args.operandValues()[0]
        if val: return logp
        else: return log1p(-math.exp(logp))

    def gradientOfLogDensity(self, val, args):
        logp = args.operandValues()[0]