예제 #1
0
파일: vsinline.py 프로젝트: wilsondy/cgpm
 def __init__(self, outputs, inputs, rng=None, expression=None, **kwargs):
     # Set the rng.
     self.rng = rng if rng is not None else gu.gen_rng(1)
     seed = self.rng.randint(1, 2**31 - 1)
     # Basic input and output checking.
     if len(outputs) != 1:
         raise ValueError('InlineVsCgpm produces 1 output only.')
     if len(set(inputs)) != len(inputs):
         raise ValueError('Non unique inputs: %s' % inputs)
     if not all(o not in inputs for o in outputs):
         raise ValueError('Duplicates: %s, %s' % (inputs, outputs))
     if not all(i not in outputs for i in inputs):
         raise ValueError('Duplicates: %s, %s' % (inputs, outputs))
     # Retrieve the expression.
     if expression is None:
         raise ValueError('Missing expression: %s' % expression)
     # Save the outputs.
     self.outputs = outputs
     # Check correct inputs against the expression.
     self._validate_expression_concrete(expression, inputs)
     # Store the inputs and expression.
     self.inputs = inputs
     self.expression = expression
     # Execute the program in the ripl to make sure it parses.
     self.ripl = vs.make_lite_ripl(seed=seed)
     self.ripl.execute_program(self.expression)
     self.ripl.execute_program('assume uniform = uniform_continuous')
예제 #2
0
파일: magics.py 프로젝트: probcomp/iventure
 def _ripl(self):
     if self.__ripl is None:
         try:
             import venture.shortcuts as vs
         except ImportError:
             raise NotImplementedError(
                 'This notebook does not support VentureScript.')
         self.__ripl = vs.make_lite_ripl(seed=self._riplseed)
     assert self.__ripl is not None
     return self.__ripl
예제 #3
0
 def __init__(self, outputs, inputs, rng=None, sp=None, **kwargs):
     # Set the rng.
     self.rng = rng if rng is not None else gu.gen_rng(1)
     seed = self.rng.randint(1, 2**31 - 1)
     # Basic input and output checking.
     if len(set(outputs)) != len(outputs):
         raise ValueError('Non unique outputs: %s' % outputs)
     if len(set(inputs)) != len(inputs):
         raise ValueError('Non unique inputs: %s' % inputs)
     if not all(o not in inputs for o in outputs):
         raise ValueError('Duplicates: %s, %s' % (inputs, outputs))
     if not all(i not in outputs for i in inputs):
         raise ValueError('Duplicates: %s, %s' % (inputs, outputs))
     # Retrieve the ripl.
     self.ripl = kwargs.get('ripl', vs.make_lite_ripl(seed=seed))
     self.mode = kwargs.get('mode', 'church_prime')
     # Execute the program.
     self.source = kwargs.get('source', None)
     if self.source is not None:
         self.ripl.set_mode(self.mode)
         self.ripl.execute_program(self.source)
     # Load any plugins.
     self.plugins = kwargs.get('plugins', None)
     if self.plugins:
         for plugin in self.plugins.split(','):
             self.ripl.load_plugin(plugin.strip())
     # Force the mode to church_prime.
     self.ripl.set_mode('church_prime')
     # Create the CGpm.
     if not kwargs.get('supress', None):
         self.ripl.evaluate('(%s)' % ('make_cgpm' if sp is None else sp,))
     # Check correct outputs.
     if len(outputs) != len(self.ripl.sample('simulators')):
         raise ValueError('source.simulators list disagrees with outputs.')
     self.outputs = outputs
     # Check correct inputs.
     if len(inputs) != self.ripl.evaluate('(size inputs)'):
         raise ValueError('source.inputs list disagrees with inputs.')
     self.inputs = inputs
     # Check overriden observers.
     if len(self.outputs) != self.ripl.evaluate('(size observers)'):
         raise ValueError('source.observers list disagrees with outputs.')
     # XXX Eliminate this nested defaultdict
     # Inputs and labels for incorporate/unincorporate.
     self.obs = defaultdict(lambda: defaultdict(dict))
예제 #4
0
 def from_metadata(cls, metadata, rng=None):
     ripl = vs.make_lite_ripl()
     ripl.loads(base64.b64decode(metadata['binary']))
     cgpm = VsCGpm(
         outputs=metadata['outputs'],
         inputs=metadata['inputs'],
         ripl=ripl,
         source=metadata['source'],
         mode=metadata['mode'],
         supress=True,
         plugins=metadata['plugins'],
         rng=rng,
     )
     # Restore the observations. We need to convert string keys to integers.
     # XXX Eliminate this terrible defaultdict hack. See Github #187.
     obs_converted = VsCGpm._obs_from_json(metadata['obs'])
     cgpm.obs = defaultdict(lambda: defaultdict(dict))
     for key, value in obs_converted.iteritems():
         cgpm.obs[key] = defaultdict(dict, value)
     return cgpm
예제 #5
0
        return [
            convert_from_venture_value(val)
            for val in venture_value.getArray()
        ]
    elif isinstance(venture_value, vv.VentureMatrix):
        return venture_value.matrix
    elif isinstance(venture_value, vv.VenturePair):
        return [
            convert_from_venture_value(val)
            for val in venture_value.getArray()
        ]
    else:
        raise ValueError(
            'Venture value cannot be converted', str(venture_value))

ripl = vs.make_lite_ripl(seed=1)

ripl.load_plugin("extensions.py")

def execute_venture_program(prog):
    results = ripl.execute_program(prog, type=True)
    return convert_from_stack_dict(results[-1]["value"])

execute_venture_program("""
define times = list(0.0, 0.0526316, 0.105263, 0.157895, 0.210526, 0.263158, 0.315789,
                    0.368421, 0.421053, 0.473684, 0.526316, 0.578947, 0.631579, 0.684211,
                    0.736842, 0.789474, 0.842105, 0.894737, 0.947368, 1.0);

define start_x = 0.1;
define start_y = 0.1;
define stop_x = 0.5;
예제 #6
0
def make_new_ripl(seed):
    """Make a new RIPL with given seed."""
    ripl = vs.make_lite_ripl(seed=seed)
    ripl = load_plugins(ripl)
    return ripl
예제 #7
0
        return change_point(location, scale, K, H)
    else:
        assert False, 'Failed to interpret AST'

def interpret_embedded_dsl(expr):
    parser = VentureScriptParser()
    ast = parser.parse_instruction(expr)['expression']
    assert len(ast) == 3
    assert ast[0]['value'] == 'make_gp'
    gp_mean = interpret_mean_kernel(ast[1])
    gp_cov = interpret_covariance_kernel(ast[2])
    return sp.VentureSPRecord(gp.GPSP(gp_mean, gp_cov))


if __name__ == '__main__':
    ripl = vs.make_lite_ripl()
    ripl.bind_foreign_sp(
        'interpret_embedded_dsl',
        deterministic_typed(
            interpret_embedded_dsl,
            [vt.StringType()],
            gp.gpType,
            min_req_args=1
        )
    )
    ripl.evaluate("""
        make_gp(gp_mean_const(0.), gp_cov_scale(0.1, gp_cov_bump(.1,.1)))
    """)
    ripl.execute_program("""
        assume gp = interpret_embedded_dsl(
            "make_gp(