def check_expected_removal(leader, particles, retained): particles.sort(key = FrameParticle.average) classifier = Salmon(top_k = 2) classifier._leader = leader classifier._particles = particles classifier.remove_identical_particles() assert classifier._leader is leader assert classifier._particles == retained, "expected: %s, got %s" % (map(str, retained), map(str, classifier._particles))
def test_frame_halving(): ''' Many halvings and particle challenges happen here. ''' rng = np.random.RandomState(0) salmon = Salmon(buffer_size=10, controller=PIDController(Kp=0.02, Td=0.4), n_samples=5, top_k=7, closeness_bonus=0, rng=rng) for _ in range(1000): salmon.camera_input(random_im(rng)) salmon.learn(random_nonwriteable_correction(rng))
def test_best_frame(): classifier = Salmon(top_k = 2) classifier.candidates_to_clear = [] frames = [create_frame(fid, d, r) for fid, d, r in [(5, 33.0, 0.3), (7, 28.0, 0.7), (6, 31.2, 0.5), (7, 34.9, 0.35), (8, 27.8, 0.6), (11, 29.0, 0.8)]] # The expected best frame is the one with image_dist 28.0 and response 0.7. # The frame with image_dist 27.8 is actually better, but because the response is not among the # top two responses, it should not be picked. expected_best_frame = frames[1] best_frame = classifier.get_best_frame(frames) assert best_frame is expected_best_frame assert classifier.candidates_to_clear == frames
def test_nonwriteable_correction(): ''' This used to fail because PID corrections were applied in-place to teacher signal ''' rng = np.random.RandomState(0) salmon = Salmon(buffer_size=500, controller=PIDController(Kp=0.02, Td=0.4), n_samples=40, top_k=7, closeness_bonus=0, rng=rng) for _ in range(5): salmon.camera_input(random_im(rng)) salmon.learn(random_nonwriteable_correction(rng))
def test_smoke(): # Note that this is not a joke about smoked salmon img1 = np.random.randn(40, 40, 3) img2 = np.roll(img1, shift = 3, axis = 1) # Add noise to the second image img2 += np.random.randn(40, 40, 3) * 0.1 motor_cmd = [np.random.randn(), np.random.randn()] salmon = Salmon() salmon.camera_input(img1) salmon.learn(motor_cmd) result = salmon.camera_input(img2) # No PID controller involved here, so we expect exactly the same motor command out # as we provided as a teaching signal assert np.array_equal(motor_cmd, result) # We rolled the test image by 3 pixels compared with the training image, # so we are expecting the phase shift in the horizontal direction # to be very close to 3.0 best_frame = salmon._leader.frame phase_x = best_frame.phase_x print "phase_x", phase_x assert 2.9 < phase_x < 3.1 # Now add a PID controller Kp = 0.1 salmon.controller = PIDController(Kp = Kp, Td = 0.0) result = salmon.camera_input(img2) # The first array in the list should be the first motor cmd entry given, # with an addition of the correction from the PID controller assert motor_cmd[0] + phase_x * Kp == result[0] # The second array in the list should be untouched assert np.array_equal(motor_cmd[1], result[1])