Exemplo n.º 1
0
    def check_against_input(cls, module, args, inp_idx, grad, out_idx, y):
        print('\t\tChecking input #', inp_idx)

        x = args[inp_idx]
        relates = list()
        assert x.shape == grad.shape, \
        'Gradient shape mismatch: {} and {}'.format(x.shape, grad.shape)

        for each in range(cls.check_round):
            pick = tuple(randint(dim) for dim in x.shape)
            x1, x2 = x.copy(), x.copy()
            x1[pick] -= cls.epsilon
            x2[pick] += cls.epsilon

            args[inp_idx] = x1
            y1 = cls.tolist(module.forward(*args))[out_idx]
            L1 = (y1 - y) * (y1 - y)

            args[inp_idx] = x2
            y2 = cls.tolist(module.forward(*args))[out_idx]
            L2 = (y2 - y) * (y2 - y)

            grad_pick = (L2.sum() - L1.sum())
            grad_pick /= (2. * cls.epsilon)

            if grad_pick == grad[pick]:
                print('\t\t', grad_pick, grad[pick])
                continue
            relate = abs(grad_pick - grad[pick])
            relate /= max(abs(grad_pick), abs(grad[pick]))
            print('\t\t', grad_pick, grad[pick], relate)
            relates.append(relate)

        if len(relates) == 0: return
        relate = np.mean(relates)
def test_create_ants(set_up_tree_nests_fixed):
    """Tests whether right amount of ants with type ant are created at nest positions.
    set_up_tree_nests_fixed should not build two nests at one position."""
    tree, positions = set_up_tree_nests_fixed
    amount_ants = randint(1, 6)

    for pos in positions:
        nest = tree.get_at_position(pos)[0]
        tree.create_ants(nest, amount_ants)

    for pos in positions:
        objects_at_pos = tree.get_at_position(pos)
        assert len(objects_at_pos) == amount_ants + 1
        assert sum([isinstance(obj, Ant) for obj in objects_at_pos]) == amount_ants
Exemplo n.º 3
0
 def move_randomly(self):
     """
     changes the position of the ant using a random walk and combining it with the previous direction
     direction is updated
     :return: the updated position is returned
     """
     while True:  # to avoid standing still and divide by zero
         movement = randint(low=-1, high=2, size=2)  # random move
         self.direction += self.direction_memory * self.direction + movement
         if distance(self.direction) > 0.:
             break
     self.direction /= distance(self.direction)
     self.position = self.position + self.direction
     return self.position
Exemplo n.º 4
0
 def move_randomly(self):
     movement = randint(low=-1, high=2, size=2)  # random move
     self.momentum += 0.5 * self.momentum + movement
     self.momentum /= np.linalg.norm(self.momentum)
     self.position = self.position + self.momentum
     return self.position