예제 #1
0
    def test_stop_batch_gradient(self):
        mean = TensorFluent(tf.zeros([self.batch_size]), [], True)
        variance = TensorFluent(tf.ones([self.batch_size]), [], True)
        _, sample = TensorFluent.Normal(mean, variance)

        stop_batch = tf.cast(
            tf.compat.v1.distributions.Bernoulli(probs=0.5).sample(
                self.batch_size), tf.bool)

        fluent = TensorFluent.stop_batch_gradient(sample, stop_batch)
        self._test_fluent(fluent, sample.dtype, sample.shape.as_list(),
                          sample.scope.as_list(), sample.batch)
        self._test_op_name(fluent, r'^Select')

        grad_before, = tf.gradients(
            ys=tf.reduce_sum(input_tensor=sample.tensor), xs=mean.tensor)
        grad_after, = tf.gradients(
            ys=tf.reduce_sum(input_tensor=fluent.tensor), xs=mean.tensor)

        self.assertIsInstance(grad_before, tf.Tensor)
        self.assertIsInstance(grad_after, tf.Tensor)

        with tf.compat.v1.Session() as sess:
            f1, f2 = sess.run([sample.tensor, fluent.tensor])
            self.assertListEqual(list(f1), list(f2))

            g1, g2, stop = sess.run([grad_before, grad_after, stop_batch])
            self.assertTrue(all(g1 == np.ones([self.batch_size])))
            self.assertTrue(all(g2 == (~stop).astype(np.float32)))
예제 #2
0
    def _compile_pvariable_expression(self, expr: Expression,
                                      scope: Dict[str, TensorFluent],
                                      **kwargs) -> TensorFluent:
        '''Compile a pvariable expression `expr` into a TensorFluent
        in the given `scope`. The resulting TensorFluent will have
        batch dimension given by `batch_size`.

        Args:
            expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression.
            scope (Dict[str, :obj:`rddl2tf.core.fluent.TensorFluent`]): A fluent scope.
            kwargs: Additional keyword arguments.

        Returns:
            :obj:`rddl2tf.core.fluent.TensorFluent`: The compiled expression as a TensorFluent.
        '''
        etype = expr.etype
        args = expr.args
        name = expr._pvar_to_name(args)
        if name not in scope:
            raise ValueError('Variable {} not in scope.'.format(name))
        fluent = scope[name]
        scope = args[1] if args[1] is not None else []
        if isinstance(fluent, TensorFluent):
            fluent = TensorFluent(fluent.tensor, scope, batch=fluent.batch)
        elif isinstance(fluent, tf.Tensor):
            fluent = TensorFluent(fluent, scope, batch=True)
        else:
            raise ValueError(
                'Variable in scope must be TensorFluent-like: {}'.format(
                    fluent))
        return fluent
예제 #3
0
    def _compile_random_variable_expression(
        self, expr: Expression, scope: Dict[str, TensorFluent], **kwargs
    ) -> TensorFluent:
        """Compile a random variable expression `expr` into a TensorFluent
        in the given `scope` with optional batch size.

        If `reparam` tensor is given, then it conditionally stops gradient
        backpropagation at the batch level where `reparam` is False.

        Args:
            expr (:obj:`rddl2tf.expr.Expression`): A RDDL random variable expression.
            scope (Dict[str, :obj:`rddl2tf.core.fluent.TensorFluent`]): A fluent scope.
            kwargs: Additional keyword arguments.

        Keyword Args:
            noise (List[tf.Tensor]): Noise sample ops for reparameterization.

        Returns:
            :obj:`rddl2tf.core.fluent.TensorFluent`: The compiled expression as a TensorFluent.
        """
        etype = expr.etype
        args = expr.args

        noise = kwargs["noise"]

        if etype[1] == "KronDelta":
            sample = self._compile_expression(args[0], scope, **kwargs)
        elif etype[1] == "Bernoulli":
            mean = self._compile_expression(args[0], scope, **kwargs)
            dist, sample = TensorFluent.Bernoulli(mean, self.batch_size)
        elif etype[1] == "Uniform":
            xi = noise.pop()
            xi = TensorFluent(tf.sigmoid(xi), scope=[], batch=True)
            low = self._compile_expression(args[0], scope, **kwargs)
            high = self._compile_expression(args[0], scope, **kwargs)
            sample = low + (high - low) * xi
        elif etype[1] == "Normal":
            xi = noise.pop()
            xi = TensorFluent(2.0 * tf.tanh(xi / 2.0), scope=[], batch=True)
            mean = self._compile_expression(args[0], scope, **kwargs)
            variance = self._compile_expression(args[1], scope, **kwargs)
            sample = mean + TensorFluent.sqrt(variance) * xi
        elif etype[1] == "Laplace":
            mean = self._compile_expression(args[0], scope, **kwargs)
            variance = self._compile_expression(args[1], scope, **kwargs)
            dist, sample = TensorFluent.Laplace(mean, variance, self.batch_size)
        elif etype[1] == "Gamma":
            sample = TensorFluent(noise.pop(), scope=[], batch=True)
        elif etype[1] == "Exponential":
            xi = noise.pop()
            xi = TensorFluent(tf.sigmoid(xi), scope=[], batch=True)
            rate = self._compile_expression(args[0], scope, **kwargs)
            sample = -(TensorFluent.constant(1.0) / rate) * TensorFluent.log(xi)
        else:
            raise ValueError("Invalid random variable expression:\n{}.".format(expr))

        return sample
예제 #4
0
 def test_normal_fluent(self):
     mean = self.zero
     variance = self.one
     dist, fluent = TensorFluent.Normal(mean, variance, self.batch_size)
     self.assertIsInstance(dist, tf.compat.v1.distributions.Normal)
     self._test_op_name(fluent, r'^Normal[^/]*/sample')
     self._test_fluent(fluent, tf.float32, [self.batch_size], [], True)
예제 #5
0
    def _compile_control_flow_expression(self, expr: Expression,
                                         scope: Dict[str, TensorFluent],
                                         **kwargs) -> TensorFluent:
        '''Compile a control flow expression `expr` into a TensorFluent
        in the given `scope`. The resulting TensorFluent will have
        batch dimension given by `batch_size`.

        Args:
            expr (:obj:`rddl2tf.expr.Expression`): A RDDL control flow expression.
            scope (Dict[str, :obj:`rddl2tf.core.fluent.TensorFluent`]): A fluent scope.
            kwargs: Additional keyword arguments.

        Returns:
            :obj:`rddl2tf.core.fluent.TensorFluent`: The compiled expression as a TensorFluent.
        '''
        etype = expr.etype
        args = expr.args
        if etype[1] == 'if':
            condition = self._compile_expression(args[0], scope, **kwargs)
            true_case = self._compile_expression(args[1], scope, **kwargs)
            false_case = self._compile_expression(args[2], scope, **kwargs)
            fluent = TensorFluent.if_then_else(condition, true_case,
                                               false_case)
        else:
            raise ValueError(
                'Invalid control flow expression:\n{}'.format(expr))
        return fluent
예제 #6
0
    def _compile_pvariables(self,
            pvariables: List[Tuple[str, str, np.array]]) -> List[Tuple[str, TensorFluent]]:

        fluents = []
        with self.graph.as_default():
            for name, pvar_range, fluent in pvariables:
                dtype = utils.range_type_to_dtype(pvar_range)
                t = tf.constant(fluent, dtype=dtype, name=utils.identifier(name))
                scope = [None] * len(t.shape)
                fluent = TensorFluent(t, scope, batch=False)
                fluents.append((name, fluent))
        return fluents
예제 #7
0
    def test_stop_gradient(self):
        mean = self.zero
        variance = self.one
        _, sample = TensorFluent.Normal(mean, variance, self.batch_size)
        fluent = TensorFluent.stop_gradient(sample)
        self._test_fluent(fluent, sample.dtype, sample.shape.as_list(),
                          sample.scope.as_list(), sample.batch)
        self._test_op_name(fluent, r'^StopGradient')

        grad_before, = tf.gradients(
            ys=tf.reduce_sum(input_tensor=sample.tensor), xs=mean.tensor)
        grad_after, = tf.gradients(
            ys=tf.reduce_sum(input_tensor=fluent.tensor), xs=mean.tensor)

        self.assertIsInstance(grad_before, tf.Tensor)
        self.assertIsNone(grad_after)

        with tf.compat.v1.Session() as sess:
            f1, f2 = sess.run([sample.tensor, fluent.tensor])
            self.assertListEqual(list(f1), list(f2))

            g1 = sess.run(grad_before)
            self.assertEqual(g1, self.batch_size)
예제 #8
0
def test_batch_normal(compiler):
    with compiler.graph.as_default():
        shape_scope = {
            "mu/1": TensorFluentShape((64, 16), batch=True),
            "sigma/1": TensorFluentShape((64, 16), batch=True),
        }

        scope = {
            "mu/1": TensorFluent(tf.zeros([64, 16]), scope=["?x"], batch=True),
            "sigma/1": TensorFluent(tf.ones([64, 16]),
                                    scope=["?x"],
                                    batch=True),
        }

    noise1 = compiler._get_expression_reparameterization(X1, scope=shape_scope)
    _test_reparameterization_dist(noise1, [(NORMAL, [64, 16])])
    _test_reparameterized_expression(compiler,
                                     X1,
                                     scope=scope,
                                     noise=noise1,
                                     name="noise1")

    noise2 = compiler._get_expression_reparameterization(X2, scope=shape_scope)
    _test_reparameterization_dist(noise2, [(NORMAL, [64, 16])])
    _test_reparameterized_expression(compiler,
                                     X2,
                                     scope=scope,
                                     noise=noise2,
                                     name="noise2")

    noise3 = compiler._get_expression_reparameterization(X3, scope=shape_scope)
    _test_reparameterization_dist(noise3, [(NORMAL, [64, 16])])
    _test_reparameterized_expression(compiler,
                                     X3,
                                     scope=scope,
                                     noise=noise3,
                                     name="noise3")
예제 #9
0
def test_exponential(compiler):
    # rainfall(?r) = Exponential(RAIN_RATE(?r));
    with compiler.graph.as_default():
        shape_scope = {"rate/1": TensorFluentShape((32, 8), batch=True)}

        scope = {
            "rate/1": TensorFluent(tf.ones((32, 8)), scope=["?r"], batch=True)
        }

    noise1 = compiler._get_expression_reparameterization(EXP1,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise1, [(UNIFORM, [32, 8])])
    _test_reparameterized_expression(compiler,
                                     EXP1,
                                     scope=scope,
                                     noise=noise1,
                                     name="noise1")
예제 #10
0
    def _compile_random_variable_expression(self, expr: Expression,
                                            scope: Dict[str, TensorFluent],
                                            **kwargs) -> TensorFluent:
        '''Compile a random variable expression `expr` into a TensorFluent
        in the given `scope` with optional batch size.

        If `reparam` tensor is given, then it conditionally stops gradient
        backpropagation at the batch level where `reparam` is False.

        Args:
            expr (:obj:`rddl2tf.expr.Expression`): A RDDL random variable expression.
            scope (Dict[str, :obj:`rddl2tf.core.fluent.TensorFluent`]): A fluent scope.
            kwargs: Additional keyword arguments.

        Returns:
            :obj:`rddl2tf.core.fluent.TensorFluent`: The compiled expression as a TensorFluent.
        '''
        etype = expr.etype
        args = expr.args

        if etype[1] == 'KronDelta':
            sample = self._compile_expression(args[0], scope, **kwargs)
        elif etype[1] == 'Bernoulli':
            mean = self._compile_expression(args[0], scope, **kwargs)
            dist, sample = TensorFluent.Bernoulli(mean, self.batch_size)
        elif etype[1] == 'Uniform':
            low = self._compile_expression(args[0], scope, **kwargs)
            high = self._compile_expression(args[1], scope, **kwargs)
            dist, sample = TensorFluent.Uniform(low, high, self.batch_size)
        elif etype[1] == 'Normal':
            mean = self._compile_expression(args[0], scope, **kwargs)
            variance = self._compile_expression(args[1], scope, **kwargs)
            dist, sample = TensorFluent.Normal(mean, variance, self.batch_size)
        elif etype[1] == 'Laplace':
            mean = self._compile_expression(args[0], scope, **kwargs)
            variance = self._compile_expression(args[1], scope, **kwargs)
            dist, sample = TensorFluent.Laplace(mean, variance,
                                                self.batch_size)
        elif etype[1] == 'Gamma':
            shape = self._compile_expression(args[0], scope, **kwargs)
            scale = self._compile_expression(args[1], scope, **kwargs)
            dist, sample = TensorFluent.Gamma(shape, scale, self.batch_size)
        elif etype[1] == 'Exponential':
            rate = self._compile_expression(args[0], scope, **kwargs)
            dist, sample = TensorFluent.Exponential(rate, self.batch_size)
        else:
            raise ValueError(
                'Invalid random variable expression:\n{}.'.format(expr))

        return sample
예제 #11
0
    def _compile_constant_expression(self, expr: Expression,
                                     scope: Dict[str, TensorFluent],
                                     **kwargs) -> TensorFluent:
        '''Compile a constant expression `expr` into a TensorFluent
        in the given `scope`. The resulting TensorFluent will have
        batch dimension given by `batch_size`.

        Args:
            expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression.
            scope (Dict[str, :obj:`rddl2tf.core.fluent.TensorFluent`]): A fluent scope.
            kwargs: Additional keyword arguments.

        Returns:
            :obj:`rddl2tf.core.fluent.TensorFluent`: The compiled expression as a TensorFluent.
        '''
        etype = expr.etype
        args = expr.args
        dtype = utils.python_type_to_dtype(etype[1])
        fluent = TensorFluent.constant(args, dtype=dtype)
        return fluent
예제 #12
0
def test_function(compiler):
    with compiler.graph.as_default():
        shape_scope = {
            "mu/1": TensorFluentShape([24], batch=False),
            "sigma/1": TensorFluentShape([24], batch=False),
        }

        scope = {
            "mu/1": TensorFluent(tf.zeros([24]), scope=["?x"], batch=False),
            "sigma/1": TensorFluent(tf.ones([24]), scope=["?x"], batch=False),
        }

    noise1 = compiler._get_expression_reparameterization(EXP_2,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise1, [])
    _test_reparameterized_expression(compiler,
                                     EXP_2,
                                     scope=scope,
                                     noise=noise1,
                                     name="noise1")

    noise2 = compiler._get_expression_reparameterization(EXP_Z,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise2, [(NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     EXP_Z,
                                     scope=scope,
                                     noise=noise2,
                                     name="noise2")

    noise3 = compiler._get_expression_reparameterization(EXP_X1,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise3, [(NORMAL, [24])])
    _test_reparameterized_expression(compiler,
                                     EXP_X1,
                                     scope=scope,
                                     noise=noise3,
                                     name="noise3")

    noise4 = compiler._get_expression_reparameterization(Y1, scope=shape_scope)
    _test_reparameterization_dist(noise4, [(NORMAL, [1]), (NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     Y1,
                                     scope=scope,
                                     noise=noise4,
                                     name="noise4")

    noise5 = compiler._get_expression_reparameterization(Y2, scope=shape_scope)
    _test_reparameterization_dist(noise5, [(NORMAL, [1]), (NORMAL, [24])])
    _test_reparameterized_expression(compiler,
                                     Y2,
                                     scope=scope,
                                     noise=noise5,
                                     name="noise5")

    noise6 = compiler._get_expression_reparameterization(Y3, scope=shape_scope)
    _test_reparameterization_dist(noise6, [(NORMAL, [24]), (NORMAL, [24])])
    _test_reparameterized_expression(compiler,
                                     Y3,
                                     scope=scope,
                                     noise=noise6,
                                     name="noise6")
예제 #13
0
def test_arithmetic(compiler):
    with compiler.graph.as_default():
        shape_scope = {
            "mu/1": TensorFluentShape([32], batch=False),
            "sigma/1": TensorFluentShape([32], batch=False),
        }

        scope = {
            "mu/1": TensorFluent(tf.zeros([32]), scope=["?x"], batch=False),
            "sigma/1": TensorFluent(tf.ones([32]), scope=["?x"], batch=False),
        }

    noise1 = compiler._get_expression_reparameterization(TWO, scope={})
    _test_reparameterization_dist(noise1, [])
    _test_reparameterized_expression(compiler,
                                     TWO,
                                     scope={},
                                     noise=noise1,
                                     name="noise1")

    noise2 = compiler._get_expression_reparameterization(Z_TIMES_Z, scope={})
    _test_reparameterization_dist(noise2, [(NORMAL, [1]), (NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     Z_TIMES_Z,
                                     scope={},
                                     noise=noise2,
                                     name="noise2")

    noise3 = compiler._get_expression_reparameterization(X2_TIMES_X2,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise3, [(NORMAL, [32]), (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X2_TIMES_X2,
                                     scope=scope,
                                     noise=noise3,
                                     name="noise3")

    noise4 = compiler._get_expression_reparameterization(MU_PLUS_Z,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise4, [(NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     MU_PLUS_Z,
                                     scope=scope,
                                     noise=noise4,
                                     name="noise4")

    noise5 = compiler._get_expression_reparameterization(Z_PLUS_MU,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise5, [(NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     Z_PLUS_MU,
                                     scope=scope,
                                     noise=noise5,
                                     name="noise5")

    noise6 = compiler._get_expression_reparameterization(MU_PLUS_X2,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise6, [(NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     MU_PLUS_X2,
                                     scope=scope,
                                     noise=noise6,
                                     name="noise6")

    noise7 = compiler._get_expression_reparameterization(X2_PLUS_MU,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise7, [(NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X2_PLUS_MU,
                                     scope=scope,
                                     noise=noise7,
                                     name="noise7")

    noise8 = compiler._get_expression_reparameterization(X1_PLUS_Z,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise8, [(NORMAL, [32]), (NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     X1_PLUS_Z,
                                     scope=scope,
                                     noise=noise8,
                                     name="noise8")

    noise9 = compiler._get_expression_reparameterization(Z_PLUS_X1,
                                                         scope=shape_scope)
    _test_reparameterization_dist(noise9, [(NORMAL, [1]), (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     Z_PLUS_X1,
                                     scope=scope,
                                     noise=noise9,
                                     name="noise9")
예제 #14
0
def test_multivariate_normal(compiler):
    with compiler.graph.as_default():
        shape_scope = {
            "mu/1": TensorFluentShape([32], batch=False),
            "sigma/1": TensorFluentShape([32], batch=False),
        }

        scope = {
            "mu/1": TensorFluent(tf.zeros([32]), scope=["?x"], batch=False),
            "sigma/1": TensorFluent(tf.ones([32]), scope=["?x"], batch=False),
        }

    noise1 = compiler._get_expression_reparameterization(X1, scope=shape_scope)
    _test_reparameterization_dist(noise1, [(NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X1,
                                     scope=scope,
                                     noise=noise1,
                                     name="noise1")

    noise2 = compiler._get_expression_reparameterization(X2, scope=shape_scope)
    _test_reparameterization_dist(noise2, [(NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X2,
                                     scope=scope,
                                     noise=noise2,
                                     name="noise2")

    noise3 = compiler._get_expression_reparameterization(X3, scope=shape_scope)
    _test_reparameterization_dist(noise3, [(NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X3,
                                     scope=scope,
                                     noise=noise3,
                                     name="noise3")

    noise4 = compiler._get_expression_reparameterization(X4, scope=shape_scope)
    _test_reparameterization_dist(noise4, [(NORMAL, [1]), (NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     X4,
                                     scope=scope,
                                     noise=noise4,
                                     name="noise4")

    noise5 = compiler._get_expression_reparameterization(X5, scope=shape_scope)
    _test_reparameterization_dist(noise5, [(NORMAL, [32]), (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X5,
                                     scope=scope,
                                     noise=noise5,
                                     name="noise5")

    noise6 = compiler._get_expression_reparameterization(X6, scope=shape_scope)
    _test_reparameterization_dist(noise6, [(NORMAL, [32]), (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X6,
                                     scope=scope,
                                     noise=noise6,
                                     name="noise6")

    noise7 = compiler._get_expression_reparameterization(X7, scope=shape_scope)
    _test_reparameterization_dist(noise7, [(NORMAL, [1]), (NORMAL, [1]),
                                           (NORMAL, [1])])
    _test_reparameterized_expression(compiler,
                                     X7,
                                     scope=scope,
                                     noise=noise7,
                                     name="noise7")

    noise8 = compiler._get_expression_reparameterization(X8, scope=shape_scope)
    _test_reparameterization_dist(noise8, [(NORMAL, [1]), (NORMAL, [1]),
                                           (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X8,
                                     scope=scope,
                                     noise=noise8,
                                     name="noise8")

    noise9 = compiler._get_expression_reparameterization(X9, scope=shape_scope)
    _test_reparameterization_dist(noise9, [(NORMAL, [32]), (NORMAL, [1]),
                                           (NORMAL, [1]), (NORMAL, [32])])
    _test_reparameterized_expression(compiler,
                                     X9,
                                     scope=scope,
                                     noise=noise9,
                                     name="noise9")
예제 #15
0
    def test_if_then_else(self):
        # if (abs[x - gx] > 0.0) then
        #     (u * u) * 0.01
        # else
        #     0.0
        x = tf.random.normal([self.batch_size, 1])
        x = TensorFluent(x, scope=[], batch=True)
        gx = tf.random.normal([])
        gx = TensorFluent(gx, scope=[], batch=False)
        u = tf.random.normal([
            self.batch_size,
        ])
        u = TensorFluent(u, scope=[], batch=True)
        c0 = TensorFluent.constant(0.01)
        cond = TensorFluent.abs(x - gx) > self.zero
        true_case = (u * u) * c0
        false_case = self.zero
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, 1], [], True)

        # if ((u * u) * 0.01 > 1.0) then
        #     abs[x - gx]
        # else
        #     0.0
        cond = ((u * u) * c0) > self.one
        true_case = TensorFluent.abs(x - gx)
        false_case = self.zero
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, 1], [], True)

        # if (gx < 1.0) then
        #     1.0 + u
        # else
        #     0.05 * (u * u)
        c1 = TensorFluent.constant(0.05)
        cond = (gx < self.one)
        true_case = self.one + u
        false_case = c1 * (u * u)
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size], [], True)

        # if (gx < 0.0) then
        #     1.0
        # else
        #     abs[x - gx]
        cond = (gx < self.zero)
        true_case = self.one
        false_case = TensorFluent.abs(x - gx)
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, 1], [], True)

        # if (visited(?wpt)) then
        #     (1.0)
        # else
        #     (0.0)
        visited = tf.stack([[True, False, True]] * self.batch_size, axis=0)
        visited = TensorFluent(visited, scope=['?wpt'], batch=True)
        cond = visited
        true_case = self.one
        false_case = self.zero
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, 3], ['?wpt'],
                          True)

        # if (rlevel'(?r)<=LOWER_BOUND(?r)) then
        #     LOW_PENALTY(?r)*(LOWER_BOUND(?r)-rlevel'(?r))
        # else
        #     HIGH_PENALTY(?r)*(rlevel'(?r)-UPPER_BOUND(?r))];
        r_size = 8
        low_penalty = TensorFluent.constant(-5.0)
        high_penalty = TensorFluent.constant(-10.0)
        lower_bound = tf.random.normal([r_size], mean=50.0, stddev=10.0)
        lower_bound = TensorFluent(lower_bound, scope=['?r'], batch=False)
        upper_bound = tf.random.normal([r_size], mean=200.0, stddev=10.0)
        upper_bound = TensorFluent(upper_bound, scope=['?r'], batch=False)
        rlevel = tf.random.normal([self.batch_size, r_size],
                                  mean=100.0,
                                  stddev=10.0)
        rlevel = TensorFluent(rlevel, scope=['?r'], batch=True)
        cond = (rlevel <= lower_bound)
        true_case = low_penalty * (lower_bound - rlevel)
        false_case = high_penalty * (rlevel - upper_bound)
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, r_size], ['?r'],
                          True)

        # if (snapPicture) then
        #    (time + 0.25)
        # else
        #    (time + abs[xMove] + abs[yMove]);
        time = tf.fill([self.batch_size, 1], 12.0)
        time = TensorFluent(time, scope=[], batch=True)
        snapPicture = tf.fill([self.batch_size], True)
        snapPicture = TensorFluent(snapPicture, scope=[], batch=True)
        xMove = tf.fill([self.batch_size], 10.0)
        xMove = TensorFluent(xMove, scope=[], batch=True)
        yMove = tf.fill([self.batch_size], -3.0)
        yMove = TensorFluent(yMove, scope=[], batch=True)
        cond = snapPicture
        true_case = (time + TensorFluent.constant(0.25))
        false_case = (time + TensorFluent.abs(xMove) + TensorFluent.abs(yMove))
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.float32, [self.batch_size, 1], [], True)

        # if (alive(?x,?y)) then
        #     Bernoulli(1.0 - NOISE-PROB(?x,?y))
        # else
        #     Bernoulli(NOISE-PROB(?x,?y));
        x_size, y_size = 3, 3
        alive = tf.compat.v1.distributions.Bernoulli(probs=0.7, dtype=tf.bool).\
            sample([self.batch_size, x_size, y_size])
        alive = TensorFluent(alive, scope=['?x', '?y'], batch=True)
        noise_prob = tf.random.uniform([x_size, y_size], dtype=tf.float32)
        noise_prob = TensorFluent(noise_prob, scope=['?x', '?y'], batch=False)
        cond = alive
        true_case = TensorFluent.Bernoulli(self.one - noise_prob,
                                           batch_size=self.batch_size)[1]
        false_case = TensorFluent.Bernoulli(noise_prob,
                                            batch_size=self.batch_size)[1]
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.bool, [self.batch_size, 3, 3], ['?x', '?y'],
                          True)

        # if (reboot(?x)) then
        #     KronDelta(true)
        # else
        #     ~running(?x);
        x_size = 128
        mean = tf.random.uniform([x_size], dtype=tf.float32)
        mean = TensorFluent(mean, scope=['?x'])
        running = TensorFluent.Bernoulli(mean, batch_size=self.batch_size)[1]
        reboot = TensorFluent.Bernoulli(self.one - mean,
                                        batch_size=self.batch_size)[1]
        cond = reboot
        true_case = TensorFluent.constant(True, dtype=tf.bool)
        false_case = ~running
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.bool, [self.batch_size, x_size], ['?x'],
                          True)

        # if (running(?x)) then
        #     Bernoulli(.45 + .5 * running(?x))
        # else
        #     Bernoulli(REBOOT-PROB);
        c0 = TensorFluent.constant(0.45)
        c1 = TensorFluent.constant(0.5)
        reboot_prob = TensorFluent.constant(0.15)
        cond = running
        true_case = TensorFluent.Bernoulli(c0 + c1 * running)[1]
        false_case = TensorFluent.Bernoulli(reboot_prob)[1]
        ite = TensorFluent.if_then_else(cond, true_case, false_case)
        self._test_fluent(ite, tf.bool, [self.batch_size, x_size], ['?x'],
                          True)
예제 #16
0
 def setUp(self):
     self.batch_size = 32
     tf.compat.v1.reset_default_graph()
     self.zero = TensorFluent.constant(0.0)
     self.one = TensorFluent.constant(1)