def test_should_encode_values(self):
        # given
        bits = 4  # 2^bits discrete states
        encoder = RealValueEncoder(bits)

        # then
        assert 0 == encoder.encode(0.0)
        assert 7 == encoder.encode(0.5)
        assert 15 == encoder.encode(1.0)
Exemple #2
0
def _mutate_attribute(ubr: UBR, encoder: RealValueEncoder, noise_max: float,
                      mu: float):

    if np.random.random() < mu:
        noise = np.random.uniform(-noise_max, noise_max)
        x1p = encoder.decode(ubr.x1)
        ubr.x1 = encoder.encode(x1p, noise)

    if np.random.random() < mu:
        noise = np.random.uniform(-noise_max, noise_max)
        x2p = encoder.decode(ubr.x2)
        ubr.x2 = encoder.encode(x2p, noise)
def _widen_attribute(ubr: UBR, encoder: RealValueEncoder, noise_max: float,
                     mu: float):

    # TODO: we should modify both condition and effect parts with the
    # same noise.
    if np.random.random() < mu:
        noise = np.random.uniform(-noise_max, noise_max)
        x1p = encoder.decode(ubr.x1)
        ubr.x1 = encoder.encode(x1p, noise)

    if np.random.random() < mu:
        noise = np.random.uniform(-noise_max, noise_max)
        x2p = encoder.decode(ubr.x2)
        ubr.x2 = encoder.encode(x2p, noise)
    def test_should_encode_with_noise_added(self):
        # given
        encoder = RealValueEncoder(16)
        noise_max = 0.1

        for _ in range(100):
            # when
            val = random.random()
            encoded = encoder.encode(val)
            encoded_with_noise = encoder.encode(val, noise_max)

            # then
            assert encoded_with_noise <= encoder.range[1]
            assert encoded_with_noise >= encoded
    def test_should_deny_encoding_illegal_values(self):
        # given
        encoder = RealValueEncoder(2)

        # when
        with pytest.raises(ValueError) as e1:
            encoder.encode(-0.2)

        with pytest.raises(ValueError) as e2:
            encoder.encode(1.1)

        # then
        assert e1 is not None
        assert e2 is not None
    def test_encode_should_return_integer(self, _p):
        # given
        encoder = RealValueEncoder(2)

        # when
        encoded = encoder.encode(_p)

        # then
        assert type(encoded) is int
    def test_should_encode_and_decode_approximately(self):
        # given
        encoder = RealValueEncoder(8)
        epsilon = 0.01
        observation = random.random()

        # when
        encoded = encoder.encode(observation)
        decoded = encoder.decode(encoded)

        # then
        assert abs(observation - decoded) < epsilon