Esempio n. 1
0
 def _format_filenames(filenames, spec):
     if isinstance(filenames, basestring) or \
        isinstance(filenames, VentureString):
         if isinstance(filenames, VentureString):
             filenames = filenames.getString()
         if isinstance(spec, basestring) or isinstance(spec, VentureString):
             return [filenames + '.png']
         else:
             raise VentureValueError(
                 'The number of specs must match the number of filenames.')
     else:
         if isinstance(spec, list) and len(spec) == len(filenames):
             return [
                 Infer._canonicalize(filename) + '.png'
                 for filename in filenames
             ]
         else:
             raise VentureValueError(
                 'The number of specs must match the number of filenames.')
Esempio n. 2
0
 def simulate(self, args):
     vals = args.operandValues()
     alpha = vals[0]
     os = vals[1] if len(vals) > 1 \
          else [VentureInteger(i) for i in range(len(alpha))]
     if len(os) != len(alpha):
         raise VentureValueError(
             "Set of objects to choose from is the wrong length")
     output = TypedPSP(CDirCatOutputPSP(alpha, os), SPType([], t.AnyType()))
     return VentureSPRecord(
         DirCatSP(NullRequestPSP(), output, alpha, len(alpha)))
Esempio n. 3
0
 def simulate(self, args):
     vals = args.operandValues()
     (alpha, n) = (float(vals[0]), int(vals[1]))
     os = vals[2] if len(vals) > 2 else [
         VentureInteger(i) for i in range(n)
     ]
     if len(os) != n:
         raise VentureValueError(
             "Set of objects to choose from is the wrong length")
     output = TypedPSP(CSymDirCatOutputPSP(alpha, n, os),
                       SPType([], t.AnyType()))
     return VentureSPRecord(DirCatSP(NullRequestPSP(), output, alpha, n))
Esempio n. 4
0
 def call_back(self, name, *exprs):
     name = SymbolType().asPython(name)
     if name not in self.engine.callbacks:
         raise VentureValueError("Unregistered callback {}".format(name))
     args = [self.engine.sample_all(e.asStackDict()) for e in exprs]
     try:
         ans = self.engine.callbacks[name](self, *args)
     except Exception as e:
         import sys
         info = sys.exc_info()
         raise VentureCallbackError(e), None, info[2]
     return self.convert_none(ans)
Esempio n. 5
0
    def simulate(self, args):
        vals = args.operandValues()
        value = vals[0]
        if isinstance(value, SPRef):
            # XXX trace.madeSPRecordAt(value.makerNode)
            value = value.makerNode.madeSPRecord

        operator = vals[1]
        if isinstance(operator, SPRef):
            # XXX trace.madeSPRecordAt(operator.makerNode)
            operator = operator.makerNode.madeSPRecord
        if not isinstance(operator.sp.requestPSP, NullRequestPSP):
            raise VentureValueError("Cannot assess a requesting SP.")
        if not operator.sp.outputPSP.isRandom():
            raise VentureValueError("Cannot assess a deterministic SP.")

        assessedArgs = ReplacingArgs(args,
                                     vals[2:],
                                     operandNodes=args.operandNodes[2:],
                                     spaux=operator.spAux)
        return operator.sp.outputPSP.logDensity(value, assessedArgs)
Esempio n. 6
0
 def simulate(self, args):
     vals = args.operandValues()
     if len(vals) == 1:  # Default values to choose from
         return sampleLogCategorical(
             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
         return sampleLogCategorical(ps, args.np_prng(), os)
Esempio n. 7
0
 def simulate(self, args):
     vals = args.operandValues()
     alpha = vals[0]
     n = len(alpha)
     os = vals[1] if len(vals) > 1 else [
         VentureInteger(i) for i in range(n)
     ]
     if len(os) != n:
         raise VentureValueError(
             "Set of objects to choose from is the wrong length")
     theta = args.np_prng().dirichlet(alpha)
     output = TypedPSP(UDirCatOutputPSP(theta, os), SPType([], t.AnyType()))
     return VentureSPRecord(DirCatSP(NullRequestPSP(), output, alpha, n))
Esempio n. 8
0
          "beginning of the given sequence, as another sequence of " \
          "the same type."))


def debug_print(label, value):
    print 'debug ' + label + ': ' + str(value)
    return value

registerBuiltinSP("debug", deterministic_typed(debug_print,
    [t.StringType(), t.AnyType("k")], t.AnyType("k"),
    descr = "Print the given value, labeled by a string. Return the value. " \
            "Intended for debugging or for monitoring execution."))

registerBuiltinSP(
    "value_error",
    deterministic_typed(lambda s: raise_(VentureValueError(str(s))),
                        [t.AnyType()], t.AnyType()))


def make_name(sym, index):
    return sym + "_" + str(int(index))

registerBuiltinSP("name", deterministic_typed(make_name,
    [t.SymbolType(), t.NumberType()], t.SymbolType(),
    descr = "Programmatically synthesize a variable name. " \
            "The name is determined by the given prefix and index."))


def dump_data(data, outfile):
    with open(outfile, 'w') as f:
        pkl.dump(data, f)
Esempio n. 9
0
 def try_f(*args, **kwargs):
   try:
     return f(*args, **kwargs)
   except np.linalg.LinAlgError as e: raise VentureValueError(e)
Esempio n. 10
0
def integer_mod(x, y):
    if int(y) == 0:
        raise VentureValueError("modulo by zero")
    else:
        return int(x) % int(y)
Esempio n. 11
0
def integer_divide(x, y):
    if int(y) == 0:
        raise VentureValueError("division by zero")
    else:
        return int(x) // int(y)
Esempio n. 12
0
 def simulate(self, args):
     vals = args.operandValues()
     if vals[1] <= vals[0]:
         raise VentureValueError("uniform_discrete called on invalid range "\
           "(%d,%d)" % (vals[0],vals[1]))
     return args.py_prng().randrange(*vals)