Exemple #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
Exemple #2
0
 def simulate(self, _trace, args):
     madeaux = args.madeSPAux()
     [xsum, ctN] = madeaux.cts()
     (alpha, beta) = args.operandValues()
     new_alpha = alpha + xsum
     new_beta = beta + ctN
     new_mu = args.np_prng().gamma(shape=(alpha + xsum),
                                   scale=1. / new_beta)
     output = TypedPSP(UGammaPoissonOutputPSP(new_mu, new_alpha, new_beta),
                       SPType([], t.CountType()))
     return VentureSPRecord(SuffPoissonSP(NullRequestPSP(), output),
                            madeaux)
Exemple #3
0
        (alpha, n) = args.operandValues()
        return simulateDirichlet([float(alpha) for _ in range(int(n))],
                                 args.np_prng())

    def logDensity(self, val, args):
        (alpha, n) = args.operandValues()
        return logDensityDirichlet(val, [float(alpha) for _ in range(int(n))])

    def description(self, name):
        return "  %s(alpha, n) samples a simplex point according to the " \
          "symmetric Dirichlet distribution on n dimensions with " \
          "concentration parameter alpha." % name

registerBuiltinSP("symmetric_dirichlet", \
  typed_nr(SymmetricDirichletOutputPSP(),
           [t.PositiveType(), t.CountType()], t.SimplexType()))

#### Common classes for AAA dirichlet distributions


class DirCatSPAux(SPAux):
    def __init__(self, n=None, counts=None):
        if counts is not None:
            self.counts = counts
        elif n is not None:
            self.counts = Node([0] * n)
        else:
            raise Exception("Must pass 'n' or 'counts' to DirCatSPAux")

    def copy(self):
        return DirCatSPAux(counts=copy.deepcopy(self.counts))
Exemple #4
0
  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()),
    descr="%s(start, stop, n) returns an array of n evenly spaced numbers " \
          "over the interval [start, stop]."))

registerBuiltinSP("zero_matrix",
  deterministic_typed(lambda n, m: np.zeros((n, m)),
    [t.CountType(), t.CountType()], t.MatrixType(),
    descr="%s(n, m) returns a zero matrix of shape n by m."))

registerBuiltinSP("id_matrix",
  deterministic_typed(np.identity, [t.CountType()], t.MatrixType(),
    descr="%s(n) returns an identity matrix of dimension n."))

registerBuiltinSP("diag_matrix",
  deterministic_typed(np.diag,
Exemple #5
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())))
Exemple #6
0
 def simulate(self, args):
     mu = args.operandValues()[0]
     output = TypedPSP(SuffPoissonOutputPSP(mu), SPType([], t.CountType()))
     return VentureSPRecord(SuffPoissonSP(NullRequestPSP(), output))
Exemple #7
0
 def simulate(self, args):
     (alpha, beta) = args.operandValues()
     mu = args.np_prng().gamma(shape=alpha, scale=1. / beta)
     output = TypedPSP(UGammaPoissonOutputPSP(mu, alpha, beta),
                       SPType([], t.CountType()))
     return VentureSPRecord(SuffPoissonSP(NullRequestPSP(), output))
Exemple #8
0
 def simulate(self, args):
     (alpha, beta) = args.operandValues()
     output = TypedPSP(CGammaPoissonOutputPSP(alpha, beta),
                       SPType([], t.CountType()))
     return VentureSPRecord(SuffPoissonSP(NullRequestPSP(), output))
Exemple #9
0
        if p == 1:
            return [n]
        elif p == 0:
            return [0]
        else:
            return [i for i in range(int(n) + 1)]

    def description(self, name):
        return '  %s(n, p) simulates flipping n Bernoulli trials independently '\
          'with probability p and returns the total number of successes.' % name


registerBuiltinSP(
    "binomial",
    typed_nr(BinomialOutputPSP(),
             [t.CountType(), t.ProbabilityType()], t.CountType()))


class CategoricalOutputPSP(DiscretePSP):
    # (categorical ps outputs)
    def simulate(self, args):
        vals = args.operandValues()
        if len(vals) == 1:  # Default values to choose from
            return simulateCategorical(
                vals[0], args.np_prng(),
                [VentureInteger(i) for i in range(len(vals[0]))])
        else:
            if len(vals[0]) != len(vals[1]):
                raise VentureValueError(
                    "Categorical passed different length arguments.")
            ps, os = vals